answer
stringlengths
17
10.2M
package org.eclipse.ice.viz.service.csv; import java.io.File; import java.lang.Thread.UncaughtExceptionHandler; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.eclipse.ice.client.common.ActionTree; import org.eclipse.ice.client.widgets.viz.service.IPlot; import org.eclipse.ice.viz.plotviewer.CSVDataLoader; import org.eclipse.ice.viz.plotviewer.CSVDataProvider; import org.eclipse.ice.viz.plotviewer.CSVPlotEditor; import org.eclipse.ice.viz.plotviewer.PlotProvider; import org.eclipse.ice.viz.plotviewer.SeriesProvider; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.MenuEvent; import org.eclipse.swt.events.MenuListener; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Menu; /** * This class implements the IPlot interface to provide access to a basic CSV * plot using the existing CSV infrastructure in ICE. * * In addition to the IPlot operations it provides the load() operation that * should be called after construction. * * @author Jay Jay Billings, Anna Wojtowicz * */ public class CSVPlot implements IPlot { /** * The source of the data for this plot */ private URI source; /** * The plot properties */ private final Map<String, String> properties; /** * The types that this plot can assume */ private final Map<String, String[]> types; /** * The CSVDataProvider used to store the loaded CSV data. */ private CSVDataProvider baseProvider; /** * A map of drawn plots, keyed on the parent {@code Composite}s. Only one * rendering should be created for a single parent. Subsequent calls to * {@link #draw(String, String, Composite)} with a parent already in the * map's key set should update the plot category and type for the associated * drawn plot. */ private final Map<Composite, DrawnPlot> drawnPlots; /** * The Constructor * * @param source * The URI of the CSV file. */ public CSVPlot(URI source) { this.source = source; // Create the property map, empty by default properties = new HashMap<String, String>(); // Create the plot type map and add empty arrays by default types = new HashMap<String, String[]>(); // Create the map of drawn plots. drawnPlots = new HashMap<Composite, DrawnPlot>(); return; } /** * This operation loads the data that will be plotted. It uses a separate * thread to avoid hanging the UI in the event that the file is large. It * does not attempt to load the file if the source is null. * */ public void load() { if (source != null) { // Only load the file if it is a CSV file. final File file = new File(source); if (file.getName().endsWith(".csv")) { // Create the loading thread. Thread loadingThread = new Thread(new Runnable() { @Override public void run() { load(file); } }); // Force the loading thread to report unhandled exceptions to // this thread's exception handler. loadingThread.setUncaughtExceptionHandler(Thread .currentThread().getUncaughtExceptionHandler()); // Start the thread loadingThread.start(); } } return; } /** * Attempts to load the specified file. This should populate the * {@link #baseProvider} as well as the map of {@link #types} or plot * series. * * @param file * The file to load. This is assumed to be a valid file. */ private void load(File file) { // Load the file using the CSV utilities. CSVDataLoader dataLoader = new CSVDataLoader(); try { baseProvider = dataLoader.load(file); } catch (Exception e) { throw new RuntimeException(e); } // Set the source so the title (and other properties) are set correctly. baseProvider.setSource(source.toString()); // Get the variables from the base IDataProvider. List<String> variables = baseProvider.getFeatureList(); int nVariables = variables.size(); // FIXME Remove this and set the independent variables elsewhere. baseProvider.setFeatureAsIndependentVariable(variables.get(0)); // Create a list to hold all available series. Each combination of // feature names (except for feature vs. itself) should be an allowed // series. Populate the list with the series names, which should be // "y-variable vs. x-variable". List<String> plotTypes = new ArrayList<String>(nVariables * nVariables); for (int y = 0; y < nVariables; y++) { String variableY = variables.get(y); for (int x = 0; x < nVariables; x++) { if (y != x) { String type = variableY + " vs. " + variables.get(x); plotTypes.add(type); } } } // Put the types in the map of types. Line, scatter, and bar plots can // be created for any of the plot types, so we can re-use the same // string array. String[] plotTypesArray = plotTypes.toArray(new String[] {}); types.put("Line", plotTypesArray); types.put("Scatter", plotTypesArray); types.put("Bar", plotTypesArray); return; } /** * @see org.eclipse.ice.client.widgets.viz.service.IPlot#getPlotTypes() */ @Override public Map<String, String[]> getPlotTypes() throws Exception { return new HashMap<String, String[]>(types); } /** * @see org.eclipse.ice.client.widgets.viz.service.IPlot#getNumberOfAxes() */ @Override public int getNumberOfAxes() { // The CSV plots are always 2D return 2; } /** * @see org.eclipse.ice.client.widgets.viz.service.IPlot#getProperties() */ @Override public Map<String, String> getProperties() { return properties; } /** * @see org.eclipse.ice.client.widgets.viz.service.IPlot#setProperties(java.util.Map) */ @Override public void setProperties(Map<String, String> props) throws Exception { // Do nothing } /** * @see org.eclipse.ice.client.widgets.viz.service.IPlot#getDataSource() */ @Override public URI getDataSource() { return source; } /** * @see org.eclipse.ice.client.widgets.viz.service.IPlot#getSourceHost() */ @Override public String getSourceHost() { return source.getHost(); } /** * @see org.eclipse.ice.client.widgets.viz.service.IPlot#isSourceRemote() */ @Override public boolean isSourceRemote() { boolean retVal = false; // If the source is null, then it is a local file. Otherwise check it // explicitly. if (source.getHost() != null) { retVal = !"localhost".equals(source.getHost()); } return retVal; } /** * @see org.eclipse.ice.client.widgets.viz.service.IPlot#draw(java.lang.String, * java.lang.String, org.eclipse.swt.widgets.Composite) */ @Override public Composite draw(String category, String plotType, Composite parent) throws Exception { Composite child = null; // Determine whether the specified plotType is valid. Note that this // also requires the category to be valid! String[] types = this.types.get(category); boolean typeValid = false; if (types != null) { for (String type : types) { if (type != null && type.equals(plotType)) { typeValid = true; break; } } } if (baseProvider != null && typeValid && parent != null && !parent.isDisposed()) { // Get the drawn plot associated with the parent Composite, creating // a new editor if necessary. DrawnPlot drawnPlot = drawnPlots.get(parent); if (drawnPlot == null) { drawnPlot = new DrawnPlot(parent); drawnPlots.put(parent, drawnPlot); // When the parent is disposed, remove the drawn plot and // dispose of any of its resources. parent.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { drawnPlots.remove((Composite) e.widget).dispose(); } }); } // Reset the plot time to the initial time. Double plotTime = baseProvider.getTimes().get(0); // FIXME Won't this affect all of the drawn plots? baseProvider.setTime(plotTime); // Remove all previous plots. drawnPlot.clear(); // Add the specified series to the drawn plot. drawnPlot.addSeries(category, plotType); // Refresh the drawn plot. drawnPlot.refresh(); // We need to return the Composite used to render the CSV plot. child = drawnPlot.editor.getPlotCanvas(); } else { // Complain that the plot is invalid throw new Exception("Invalid plot: category = " + category + ", type = " + plotType + ", provider = " + baseProvider.toString()); } return child; } /** * An instance of this nested class is composed of the drawn * {@link CSVPlotEditor} and all providers necessary to populate it with CSV * data. * * @author Jordan Deyton * */ private class DrawnPlot { // TODO Change CSVPlot to extend MultiPlot and create a PlotRender based // off this nested class. /** * The editor in which the CSV plot is rendered. */ public final CSVPlotEditor editor; /** * The data provider containing the loaded CSV data. */ public final CSVDataProvider dataProvider; /** * The provider responsible for maintaining the plot configuration. */ public final PlotProvider plotProvider; /** * A tree of JFace {@code Action}s for adding new series to the drawn * plot. */ private final ActionTree addSeriesTree; /** * A tree of JFace {@code Action}s for removing plotted series from the * drawn plot. */ private final ActionTree removeSeriesTree; /** * A map keyed on the series and containing the ActionTrees for removing * them from the plot. */ private final Map<SeriesProvider, ActionTree> seriesMap = new HashMap<SeriesProvider, ActionTree>(); /** * Creates a {@link CSVPlotEditor} and all providers necessary to * populate it. The editor is created inside the specified parent * {@code Composite}. * * @param parent * The {@code Composite} in which to draw the CSV plot * editor. */ public DrawnPlot(Composite parent) throws Exception { // Create the editor and all required providers. editor = new CSVPlotEditor(); dataProvider = baseProvider; plotProvider = new PlotProvider(); // Set the plot title based on the file name. int lastSeparator = dataProvider.getSourceInfo().lastIndexOf("/"); String plotTitle = (lastSeparator > -1 ? dataProvider .getSourceInfo().substring(lastSeparator + 1) : dataProvider.getSourceInfo()); // Set the title for the new plot provider plotProvider.setPlotTitle(plotTitle); // Create the plot inside the parent Composite. editor.createPartControl(parent); // Get the child Composite used to render the Composite canvas = editor.getPlotCanvas(); // Get the context Menu for the parent Composite, or create a new // one if the parent lacks a context Menu. Menu menu = parent.getMenu(); if (menu == null) { MenuManager menuManager = new MenuManager(); menu = menuManager.createContextMenu(canvas); } // Create the ActionTrees for adding and removing series on the fly. addSeriesTree = new ActionTree("Add Series"); removeSeriesTree = new ActionTree("Remove Series"); final Separator separator = new Separator(); final ActionTree clearAction = new ActionTree(new Action( "Clear Plot") { @Override public void run() { clear(); refresh(); } }); // Fill out the add series tree. This tree will never need to be // updated. for (Entry<String, String[]> e : getPlotTypes().entrySet()) { final String category = e.getKey(); String[] types = e.getValue(); if (category != null && types != null) { // Create the tree for the category and all its types. ActionTree catTree = new ActionTree(category); addSeriesTree.add(catTree); // Create Actions for all the types. Each Action should call // addSeries(...) with the category and type. for (final String type : types) { if (type != null) { catTree.add(new ActionTree(new Action(type) { @Override public void run() { addSeries(category, type); refresh(); } })); } } } } // When the Menu is about to be shown, add the add/remove series // actions to it. menu.addMenuListener(new MenuListener() { @Override public void menuHidden(MenuEvent e) { // Nothing to do. } @Override public void menuShown(MenuEvent e) { // Rebuild the menu. Menu menu = (Menu) e.widget; addSeriesTree.getContributionItem().fill(menu, -1); removeSeriesTree.getContributionItem().fill(menu, -1); separator.fill(menu, -1); clearAction.getContributionItem().fill(menu, -1); } }); // Set the context Menu for the main plot canvas. The slider can // have its own menu set later. editor.getPlotCanvas().setMenu(menu); return; } /** * Adds a new series to the drawn plot. * * @param category * The category of the series to add. * @param type * The type of the series to add. * @param drawnPlot * The drawn plot that will get a new series. */ public void addSeries(String category, String type) { // Reset the plot time to the initial time. Double plotTime = baseProvider.getTimes().get(0); // FIXME Won't this affect all of the drawn plots? baseProvider.setTime(plotTime); // Get the axes to plot String[] axes = type.split(" "); String yAxis = axes[0]; String xAxis = axes[2]; // Create a new series title for the new series String seriesTitle = yAxis + " vs. " + xAxis + " at " + plotTime; // Create a new series provider final SeriesProvider seriesProvider = new SeriesProvider(); seriesProvider.setDataProvider(dataProvider); seriesProvider.setTimeForDataProvider(plotTime); seriesProvider.setSeriesTitle(seriesTitle); seriesProvider.setXDataFeature(xAxis); seriesProvider.setYDataFeature(yAxis); seriesProvider.setSeriesType(category); // Add this new series to the plot provider plotProvider.addSeries(plotTime, seriesProvider); // Add an ActionTree to remove the series. ActionTree tree = new ActionTree(new Action(seriesTitle) { @Override public void run() { removeSeries(seriesProvider); refresh(); } }); removeSeriesTree.add(tree); // Store the series and ActionTree for later reference. seriesMap.put(seriesProvider, tree); return; } /** * Removes the specified series from the drawn plot. * * @param series * The series to remove. */ public void removeSeries(SeriesProvider series) { ActionTree tree = seriesMap.remove(series); if (tree != null) { double plotTime = baseProvider.getTimes().get(0); removeSeriesTree.remove(tree); plotProvider.removeSeries(plotTime, series); } return; } /** * Clears all series from the drawn plot. */ public void clear() { double plotTime = baseProvider.getTimes().get(0); for (Entry<SeriesProvider, ActionTree> e : seriesMap.entrySet()) { plotProvider.removeSeries(plotTime, e.getKey()); } seriesMap.clear(); removeSeriesTree.removeAll(); return; } /** * Refreshes the drawn plot after a change has occurred. */ public void refresh() { // Add the new plot to the editor. editor.showPlotProvider(plotProvider); } /** * Disposes of the drawn plot and all related resources. */ public void dispose() { // Nothing to do yet. } } }
package com.tterrag.k9.mappings; import java.io.File; import java.io.IOException; import java.io.Writer; import java.net.URI; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.time.Duration; import java.time.Instant; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import java.util.function.Function; import java.util.stream.Collectors; import org.apache.commons.lang3.ObjectUtils; import com.google.common.base.Joiner; import com.google.common.base.Strings; import com.google.common.collect.ListMultimap; import com.tterrag.k9.mappings.mcp.IntermediateMapping; import com.tterrag.k9.mappings.mcp.McpDownloader; import com.tterrag.k9.mappings.mcp.McpMapping; import com.tterrag.k9.mappings.mcp.McpMapping.Side; import com.tterrag.k9.mappings.mcp.SrgDatabase; import com.tterrag.k9.mappings.mcp.SrgMapping; import com.tterrag.k9.mappings.yarn.YarnDownloader; import com.tterrag.k9.util.Fluxes; import lombok.extern.slf4j.Slf4j; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import reactor.util.function.Tuple2; @Slf4j public class Yarn2McpService { private static final MappingType[] SUPPORTED_TYPES = { MappingType.FIELD, MappingType.METHOD }; private static final String YARN = "yarn", MIXED = "mixed"; private static final String MIXED_VERSION = "1.14.3"; public final Path output; public Yarn2McpService(String output) { this.output = Paths.get(output, "de", "oceanlabs", "mcp"); } public Mono<Void> start() { // First, generate mappings for the latest mcp version if they are not done already. // These either shouldn't change (if yarn is on a newer version) or will get updated // by the daily export (if yarn is on the same version). return McpDownloader.INSTANCE.getLatestMinecraftVersion(false) .flatMap(version -> publishIfNotExists(version, YARN, this::publishMappings)) // Then run initial output of the latest yarn version if no file exists for today .then(YarnDownloader.INSTANCE.getLatestMinecraftVersion(true)) .publishOn(Schedulers.elastic()) .flatMap(version -> publishIfNotExists(version, YARN, this::publishMappings).thenReturn(version)) // Also publish mixed mappings .flatMap(version -> publishIfNotExists(version, MIXED, v -> publishMixedMappings(MIXED_VERSION, v))) // Then begin a periodic publish every day at midnight .thenMany(Flux.interval(Duration.between(Instant.now(), Instant.now().plus(1, ChronoUnit.DAYS).truncatedTo(ChronoUnit.DAYS)), Duration.ofDays(1))) .flatMap(tick -> YarnDownloader.INSTANCE.getLatestMinecraftVersion(true) .flatMap(version -> publishMappings(version).thenReturn(version)) .flatMap(version -> publishMixedMappings(MIXED_VERSION, version)) .thenReturn(tick) .doOnError(t -> log.error("Error performing periodic mapping push", t)) .onErrorReturn(tick)) .then(); } private Mono<Void> publishIfNotExists(String version, String name, Function<String, Mono<Void>> func) { return Mono.fromSupplier(() -> getOutputFile(version, name)) .filter(p -> !p.toFile().exists()) .flatMap($ -> func.apply(version)); } private Mono<SrgDatabase> getSrgs(String version) { return McpDownloader.INSTANCE.updateSrgs(version) .then(Mono.fromCallable(() -> (SrgDatabase) new SrgDatabase(version).reload())); } private Mono<Void> publishMixedMappings(String mcpVersion, String yarnVersion) { return McpDownloader.INSTANCE.getLatestMinecraftVersion(false) .filter(v -> v.equals(mcpVersion)) .flatMap($ -> Mono.zip( getSrgs(yarnVersion), YarnDownloader.INSTANCE.getDatabase(yarnVersion), McpDownloader.INSTANCE.getDatabase(mcpVersion))) .flux() .transform(Fluxes.groupWith(Flux.just(SUPPORTED_TYPES), (type, dbs) -> Mono.zip( findMatching(type, dbs.getT1(), dbs.getT2()), this.<SrgMapping, Mapping>findMatchingByIntermediate(type, dbs.getT1(), dbs.getT3())))) .flatMap(gf -> gf .doOnNext(maps -> maps.getT1().forEach(maps.getT2()::putIfAbsent)) .map(Tuple2::getT2) .flatMapIterable(Map::entrySet) .filter(e -> e.getKey().getName() != null || e.getValue().getName() != null) .map(e -> toCsv(e.getKey(), e.getValue())) .collectList() .flatMap(csv -> writeToFile(yarnVersion, gf.key(), csv, MIXED))) .then(); } private Mono<Void> publishMappings(String version) { return Mono.zip(getSrgs(version), YarnDownloader.INSTANCE.getDatabase(version)) .doOnNext($ -> log.info("Publishing yarn-over-mcp for MC " + version)) .flux() .transform(Fluxes.groupWith(Flux.just(SUPPORTED_TYPES), (type, t) -> findMatching(type, t.getT1(), t.getT2()))) .flatMap(gf -> gf.flatMapIterable(m -> m.entrySet()) .filter(e -> e.getKey().getName() != null || e.getValue().getName() != null) .filter(e -> !e.getKey().getIntermediate().equals("func_213454_em") && !e.getKey().getIntermediate().equals("field_77356_a")) // Some broken mappings .map(e -> toCsv(e.getKey(), e.getValue())) .collectList() .flatMap(csv -> writeToFile(version, gf.key(), csv, YARN))) .then(); } private <M extends IntermediateMapping> Comparator<M> bySrg() { return Comparator.<M>comparingInt(m -> FastIntLookupDatabase.getSrgId(m.getIntermediate()) .orElse(Integer.MAX_VALUE)) .thenComparing(Mapping::getIntermediate); } private <M1 extends IntermediateMapping, M2 extends Mapping> Mono<SortedMap<M1, M2>> findMatchingByIntermediate( MappingType type, AbstractMappingDatabase<? extends M1> a, AbstractMappingDatabase<? extends M2> b) { return Mono.fromSupplier(() -> { ListMultimap<String, ? extends M1> aBySrg = a.getTable(NameType.INTERMEDIATE, type); ListMultimap<String, ? extends M2> bBySrg = b.getTable(NameType.INTERMEDIATE, type); SortedMap<M1, M2> ret = new TreeMap<>(bySrg()); for (String key : aBySrg.keySet()) { List<? extends M1> aMappings = aBySrg.get(key); List<? extends M2> bMappings = bBySrg.get(key); if (!aMappings.isEmpty() && !bMappings.isEmpty()) { ret.put(aMappings.get(0), bMappings.get(0)); } } return ret; }); } private <M1 extends IntermediateMapping, M2 extends Mapping> Mono<SortedMap<M1, M2>> findMatching( MappingType type, AbstractMappingDatabase<M1> mcp, AbstractMappingDatabase<M2> yarn) { return Mono.defer(() -> { Map<String, M1> mcpBySignature = bySignature(mcp.getTable(NameType.ORIGINAL, type)); Map<String, M2> yarnBySignature = bySignature(yarn.getTable(NameType.ORIGINAL, type)); return Flux.fromIterable(mcpBySignature.entrySet()) .filter(e -> yarnBySignature.containsKey(e.getKey())) .collectMap(Map.Entry::getValue, e -> yarnBySignature.get(e.getKey()), () -> new TreeMap<M1, M2>(bySrg())) .map(m -> (SortedMap<M1, M2>) m); // wtf reactor? }); } private <M1 extends Mapping, M2 extends Mapping> String toCsv(M1 m1, M2 m2) { return Joiner.on(',').join( m1.getIntermediate(), ObjectUtils.firstNonNull(m2.getName(), m1.getName()), m1 instanceof McpMapping ? ((McpMapping)m1).getSide().ordinal() : Side.BOTH.ordinal(), Strings.nullToEmpty(m1.getDesc())); } private Path getOutputFile(String version, String name) { String channel = "mcp_snapshot"; LocalDate today = LocalDate.now(); String snapshot = String.format("%04d%02d%02d-%s-%s", today.getYear(), today.getMonthValue(), today.getDayOfMonth(), name, version); return output .resolve(channel) .resolve(snapshot) .resolve(channel + "-" + snapshot + ".zip"); } private Mono<Void> writeToFile(String version, MappingType type, List<String> csv, String name) { return Mono.fromRunnable(() -> { try { Path zip = getOutputFile(version, name); File parent = zip.getParent().toFile(); if (!parent.mkdirs() && !parent.exists()) { throw new IllegalStateException("Could not create maven directory: " + zip.getParent()); } Map<String, String> env = new HashMap<>(); env.put("create", "true"); URI uri = URI.create("jar:" + zip.toUri()); log.info("Writing yarn-to-mcp data to " + zip.toAbsolutePath()); try (FileSystem fs = FileSystems.newFileSystem(uri, env)) { Path nf = fs.getPath(type.getCsvName() + ".csv"); try (Writer writer = Files.newBufferedWriter(nf, StandardCharsets.UTF_8, StandardOpenOption.CREATE)) { for (String line : csv) { writer.write(line + "\n"); } } } } catch (IOException e) { throw new RuntimeException(e); } }); } private String getSignature(Mapping mapping) { StringBuilder ret = new StringBuilder(mapping.getOwner(NameType.ORIGINAL)).append(".").append(mapping.getOriginal()); if (mapping.getType() == MappingType.METHOD) { ret.append(mapping.getDesc(NameType.ORIGINAL)); } return ret.toString(); } private <T extends Mapping> Map<String, T> bySignature(ListMultimap<String, T> table) { return table.values().stream() .collect(Collectors.toMap(this::getSignature, Function.identity())); } }
package org.jetbrains.postfixCompletion.templates; import com.intellij.codeInsight.unwrap.ScopeHighlighter; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.util.Pass; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiExpression; import com.intellij.psi.util.PsiExpressionTrimRenderer; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.refactoring.IntroduceTargetChooser; import com.intellij.refactoring.introduceVariable.IntroduceVariableBase; import org.jetbrains.annotations.NotNull; import org.jetbrains.postfixCompletion.util.CommonUtils; import org.jetbrains.postfixCompletion.util.JavaSurroundersProxy; import java.util.List; public final class CastExpressionPostfixTemplate extends PostfixTemplate { public CastExpressionPostfixTemplate() { super("cast"); } @Override public boolean isApplicable(@NotNull PsiElement context) { return PsiTreeUtil.getParentOfType(context, PsiExpression.class) != null; } @Override public void expand(@NotNull PsiElement context, @NotNull final Editor editor) { List<PsiExpression> expressions = IntroduceVariableBase.collectExpressions(context.getContainingFile(), editor, editor.getCaretModel().getOffset()); if (expressions.isEmpty()) { CommonUtils.showErrorHint(context.getProject(), editor); } else if (expressions.size() == 1) { doIt(editor, expressions.get(0)); } else { IntroduceTargetChooser.showChooser(editor, expressions, new Pass<PsiExpression>() { public void pass(@NotNull PsiExpression e) { doIt(editor, e); } }, new PsiExpressionTrimRenderer.RenderFunction(), "Expressions", 0, ScopeHighlighter.NATURAL_RANGER); } } private static void doIt(@NotNull final Editor editor, @NotNull final PsiExpression expression) { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { JavaSurroundersProxy.cast(expression.getProject(), editor, expression); } }); } }
package org.vitrivr.cineast.api.websocket.handlers; import org.eclipse.jetty.websocket.api.Session; import org.vitrivr.cineast.api.websocket.handlers.abstracts.StatelessWebsocketMessageHandler; import org.vitrivr.cineast.core.data.entities.MultimediaMetadataDescriptor; import org.vitrivr.cineast.core.data.messages.lookup.MetadataLookup; import org.vitrivr.cineast.core.data.messages.result.MetadataQueryResult; import org.vitrivr.cineast.core.db.dao.reader.MultimediaMetadataReader; import java.util.List; /** * @author rgasser * @version 1.0 * @created 10.02.17 */ public class MetadataLookupMessageHandler extends StatelessWebsocketMessageHandler<MetadataLookup> { /** * Invoked when a Message of type MetadataLookup arrives and requires handling. Looks up the * MultimediaMetadataDescriptors of the requested objects, wraps them in a MetadataQueryResult object * and writes them to the stream. * * @param session WebSocketSession for which the message arrived. * @param message Message of type a that needs to be handled. */ @Override public void handle(Session session, MetadataLookup message) { MultimediaMetadataReader reader = new MultimediaMetadataReader(); List<MultimediaMetadataDescriptor> descriptors = reader.lookupMultimediaMetadata(message.getIds()); this.write(session, new MetadataQueryResult("", descriptors)); reader.close(); } }
package de.springbootbuch.webmvc; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import java.io.IOException; import org.springframework.boot.jackson.JsonComponent; /** * Part of springbootbuch.de. * * @author Michael J. Simons * @author @rotnroll666 */ @JsonComponent public class FilmSerializer extends JsonSerializer<Film> { @Override public void serialize( Film film, JsonGenerator gen, SerializerProvider serializers ) throws IOException, JsonProcessingException { gen.writeStartObject(); gen.writeObjectField("id", film.getId()); gen.writeObjectField("title", film.getTitle()); gen.writeObjectField( "releaseYear", film.getReleaseYear().getValue()); gen.writeEndObject(); } }
package eu.fbk.dkm.premon.premonitor; import java.io.File; import java.io.FileInputStream; import java.lang.reflect.Constructor; import java.net.URL; import java.nio.file.Files; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.annotation.Nullable; import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; import com.google.common.collect.HashBasedTable; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import com.google.common.collect.Ordering; import com.google.common.collect.Sets; import com.google.common.collect.Table; import com.google.common.collect.Table.Cell; import com.google.common.io.Resources; import org.openrdf.model.BNode; import org.openrdf.model.Namespace; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.model.impl.ContextStatementImpl; import org.openrdf.model.impl.URIImpl; import org.openrdf.model.vocabulary.*; import org.openrdf.rio.RDFHandler; import org.openrdf.rio.RDFHandlerException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import eu.fbk.dkm.premon.util.ProcessorUndoRDFS; import eu.fbk.dkm.premon.vocab.DECOMP; import eu.fbk.dkm.premon.vocab.FB; import eu.fbk.dkm.premon.vocab.LEXINFO; import eu.fbk.dkm.premon.vocab.NIF; import eu.fbk.dkm.premon.vocab.ONTOLEX; import eu.fbk.dkm.premon.vocab.PM; import eu.fbk.dkm.premon.vocab.PMO; import eu.fbk.dkm.premon.vocab.PMONB; import eu.fbk.dkm.premon.vocab.PMOPB; import eu.fbk.dkm.utils.CommandLine; import eu.fbk.rdfpro.AbstractRDFHandler; import eu.fbk.rdfpro.RDFHandlers; import eu.fbk.rdfpro.RDFProcessor; import eu.fbk.rdfpro.RDFProcessors; import eu.fbk.rdfpro.RDFSource; import eu.fbk.rdfpro.RDFSources; import eu.fbk.rdfpro.RuleEngine; import eu.fbk.rdfpro.Ruleset; import eu.fbk.rdfpro.SetOperator; import eu.fbk.rdfpro.util.Hash; import eu.fbk.rdfpro.util.IO; import eu.fbk.rdfpro.util.QuadModel; import eu.fbk.rdfpro.util.Statements; import eu.fbk.rdfpro.util.Tracker; /** * Premonitor command line tool for converting predicate resources to the PreMOn model */ public class Premonitor { private static final String DEFAULT_PATH = "."; private static final String DEFAULT_PROPERTIES_FILE = "premonitor.properties"; private static final String DEFAULT_OUTPUT_BASE = "output/premon"; private static final String DEFAULT_OUTPUT_FORMATS = "trig.gz,tql.gz,ttl.gz"; private static final String DEFAULT_WORDNET_FILE = "wordnet-3.1/wn31.nt.gz"; private static final Pattern PROPERTIES_RESOURCES_PATTERN = Pattern .compile("^resource([0-9]+)\\.(.*)$"); private static final String WN_PREFIX = "http://wordnet-rdf.princeton.edu/wn31/"; private static final URI LEMON_LEXICAL_ENTRY = Statements.VALUE_FACTORY .createURI("http://lemon-model.net/lemon#LexicalEntry"); private static final URI LEMON_REFERENCE = Statements.VALUE_FACTORY .createURI("http://lemon-model.net/lemon#reference"); private static final URI WN_OLD_SENSE = Statements.VALUE_FACTORY .createURI("http://wordnet-rdf.princeton.edu/ontology#old_sense_key"); private static final Logger LOGGER = LoggerFactory.getLogger(Premonitor.class); public static void main(final String[] args) { try { final CommandLine cmd = CommandLine .parser() .withName("./premonitor") .withHeader("Transform linguistic resources into RDF") .withOption("i", "input", String.format("input folder (default %s)", DEFAULT_PATH), "FOLDER", CommandLine.Type.DIRECTORY_EXISTING, true, false, false) .withOption("b", "output-base", "Output base path/name (default 'premon')", "PATH", CommandLine.Type.FILE, true, false, false) .withOption("f", "output-formats", "Comma-separated list of output formats (default 'tql.gz')", "FMTS", CommandLine.Type.STRING, true, false, false) .withOption("p", "properties", String.format("Property file (default %s)", DEFAULT_PROPERTIES_FILE), "FILE", CommandLine.Type.FILE, true, false, false) .withOption("s", "single", "Extract single lemma (apply to all resources)", "LEMMA", CommandLine.Type.STRING, true, false, false) .withOption( null, "wordnet", String.format("WordNet RDF triple file (default: %s)", DEFAULT_WORDNET_FILE), "FILE", CommandLine.Type.FILE_EXISTING, true, false, false) .withOption(null, "wordnet-sensekeys", "WordNet senseKey mapping", "FILE", CommandLine.Type.FILE_EXISTING, true, false, false) .withOption("r", "omit-owl2rl", "Omit OWL2RL reasoning (faster)") .withOption("x", "omit-stats", "Omit generation of statistics (faster)") .withOption("m", "omit-filter-mappings", "Omit filtering illegal mappings " + "referring to non-existing conceptualizations (faster)") .withLogger(LoggerFactory.getLogger("eu.fbk")).parse(args); // Input/output File inputFolder = new File(DEFAULT_PATH); if (cmd.hasOption("input")) { inputFolder = cmd.getOptionValue("input", File.class); } File propertiesFile = new File(DEFAULT_PROPERTIES_FILE); if (cmd.hasOption("properties")) { propertiesFile = cmd.getOptionValue("properties", File.class); } System.setProperty("javax.xml.accessExternalDTD", "file"); // WordNet final HashMap<String, URI> wnInfo = new HashMap<>(); final URL resource = ClassLoader.getSystemClassLoader().getResource( "eu/fbk/dkm/premon/premonitor/wn30-senseKeys.tsv"); List<String> allLines = null; if (resource != null) { allLines = Resources.readLines(resource, Charsets.UTF_8); } if (cmd.hasOption("wordnet-sensekeys")) { allLines = Files.readAllLines(cmd.getOptionValue("wordnet-sensekeys", File.class) .toPath()); } if (allLines != null) { for (String line : allLines) { line = line.trim(); final String[] parts = line.split("\\s+"); if (parts.length >= 2) { String senseKey = parts[0]; final String synsetID = parts[1]; senseKey = senseKey.replaceAll(":[^:]*:[^:]*$", ""); wnInfo.put(senseKey, Converter.createURI(WN_PREFIX, synsetID)); } } } if (cmd.hasOption("wordnet")) { final File wnRDF = cmd.getOptionValue("wordnet", File.class); if (wnRDF != null && wnRDF.exists()) { LOGGER.info("Loading WordNet"); final RDFSource source = RDFSources.read(true, true, null, null, wnRDF.getAbsolutePath()); source.emit(new AbstractRDFHandler() { @Override public void handleStatement(final Statement statement) throws RDFHandlerException { // Really really bad! if (statement.getPredicate().equals(RDF.TYPE) && statement.getObject().equals(LEMON_LEXICAL_ENTRY)) { if (statement.getSubject() instanceof URI) { synchronized (wnInfo) { // required to establish owl:sameAs links wnInfo.put(statement.getSubject().stringValue(), (URI) statement.getSubject()); } } } // Really really bad! if (statement.getPredicate().equals(LEMON_REFERENCE)) { final Resource s = statement.getSubject(); final Value o = statement.getObject(); if (s instanceof URI && o instanceof URI) { synchronized (wnInfo) { // required to establish VN32 links final String name = s.stringValue(); final int start = name.lastIndexOf('/') + 1; final int end = name.lastIndexOf('-', name.indexOf('#', start)); final String lemma = name.substring(start, end).replace( '+', '_'); final String key = o.stringValue() + "|" + lemma; final URI oldURI = wnInfo.put(key, (URI) s); Preconditions.checkState(oldURI == null || oldURI.equals(s)); } } } } }, 1); LOGGER.info("Loaded {} URIs", wnInfo.size()); } } // Load properties final HashMap<Integer, Properties> multiProperties = new HashMap<>(); LOGGER.info("Loading properties file: {}", propertiesFile.getAbsolutePath()); if (propertiesFile.exists()) { final Properties tmpProp = new Properties(); tmpProp.load(new FileInputStream(propertiesFile)); for (final Object key : tmpProp.keySet()) { final Matcher m = PROPERTIES_RESOURCES_PATTERN.matcher((String) key); if (m.find()) { final Integer id = Integer.parseInt(m.group(1)); final String subProperty = m.group(2); if (multiProperties.get(id) == null) { multiProperties.put(id, new Properties()); } multiProperties.get(id).setProperty(subProperty, tmpProp.getProperty((String) key)); } } } final Map<String, Map<URI, QuadModel>> models = new HashMap<>(); for (final Integer id : multiProperties.keySet()) { final Properties properties = multiProperties.get(id); final boolean active = properties.getProperty("active", "0").equals("1"); if (!active) { LOGGER.info("Resource {} is not active", id); continue; } final String source = properties.getProperty("source"); if (source == null || source.length() == 0) { LOGGER.error("Resource {} has no source", id); continue; } LOGGER.info("Processing {}", properties.getProperty("label")); // Check class final String className = properties.getProperty("class"); if (className == null) { LOGGER.error("Resource {} has no class", id); continue; } // Check folder String folderName = properties.getProperty("folder"); if (folderName == null) { LOGGER.error("Resource {} has no folder", id); continue; } if (!folderName.startsWith(File.separator)) { folderName = inputFolder + File.separator + folderName; } final File folder = new File(folderName); if (!folder.exists()) { LOGGER.error("Folder {} does not exist", folderName); continue; } if (!folder.isDirectory()) { LOGGER.error("Folder {} is not a folder", folderName); continue; } try { // Build an RDFHandler that populates a NS map and a QuadModel for each graph final AtomicInteger numQuads = new AtomicInteger(); final Map<String, String> namespaces = Maps.newHashMap(); final Map<URI, QuadModel> graphModels = new HashMap<>(); models.put(source, graphModels); final RDFHandler handler = new AbstractRDFHandler() { @Override public void handleNamespace(final String prefix, final String uri) { namespaces.put(prefix, uri); } @Override public synchronized void handleStatement(final Statement stmt) { numQuads.incrementAndGet(); URI graph; try { graph = (URI) stmt.getContext(); } catch (final ClassCastException ex) { LOGGER.warn("Unexpected non-URI graph: " + stmt.getContext()); return; } QuadModel graphModel = graphModels.get(graph); if (graphModel == null) { graphModel = QuadModel.create(); graphModels.put(graph, graphModel); } graphModel.add(stmt.getSubject(), stmt.getPredicate(), stmt.getObject()); } }; // Create and invoke Converter using reflection final Class<?> cls = Class.forName(className); final Constructor<?> constructor = cls.getConstructor(File.class, RDFHandler.class, Properties.class, Map.class); final Object converter = constructor.newInstance(folder, handler, properties, wnInfo); if (converter instanceof Converter) { ((Converter) converter).convert(); } // Apply default + Converter namespaces to all the graphs collected int numUniqueQuads = 0; for (final QuadModel model : graphModels.values()) { numUniqueQuads += model.size(); for (final Map.Entry<String, String> entry : namespaces.entrySet()) { model.setNamespace(entry.getKey(), entry.getValue()); } model.setNamespace(PM.PREFIX, PM.NAMESPACE); model.setNamespace(PMO.PREFIX, PMO.NAMESPACE); model.setNamespace(PMOPB.PREFIX, PMOPB.NAMESPACE); model.setNamespace(PMONB.PREFIX, PMONB.NAMESPACE); model.setNamespace(ONTOLEX.PREFIX, ONTOLEX.NAMESPACE); model.setNamespace(DECOMP.PREFIX, DECOMP.NAMESPACE); model.setNamespace(LEXINFO.PREFIX, LEXINFO.NAMESPACE); model.setNamespace(FB.PREFIX, FB.NAMESPACE); } // Log the number of triples extracted LOGGER.info("Extracted {} quads ({} before deduplication)", numUniqueQuads, numQuads.get()); } catch (final ClassNotFoundException e) { // Log and ignore LOGGER.error("Class {} not found", className); } } try { // Extract output base name and formats, removing leading '.' character from them final String base = cmd.getOptionValue("b", String.class, DEFAULT_OUTPUT_BASE); final String[] formats = cmd.getOptionValue("f", String.class, DEFAULT_OUTPUT_FORMATS).split(","); for (int i = 0; i < formats.length; ++i) { if (formats[i].charAt(0) == '.') { formats[i] = formats[i].substring(1); } } // Extract flags controlling output generation final boolean owl2rl = !cmd.hasOption("r"); final boolean statistics = !cmd.hasOption("x"); final boolean filterMappings = !cmd.hasOption("m"); // Emit the output based on previous settings emit(base, formats, models, owl2rl, statistics, filterMappings); } catch (final Exception ex) { // Wrap and propagate throw new RDFHandlerException( "IO error, some files might not have been properly saved (" + ex.getMessage() + ")", ex); } } catch (final Throwable ex) { CommandLine.fail(ex); } } private static void emit(final String base, final String[] formats, final Map<String, Map<URI, QuadModel>> models, final boolean owl2rl, final boolean statistics, final boolean filterMappings) throws RDFHandlerException { // Load TBox and get rid of unwanted classes final QuadModel tbox = QuadModel.create(); RDFSources.read(false, true, null, null, "classpath:/eu/fbk/dkm/premon/premonitor/tbox.ttl") .emit(RDFHandlers.wrap(tbox), 1); final String semNS = "http://www.ontologydesignpatterns.org/cp/owl/semiotics.owl final Set<URI> unwantedConcepts = ImmutableSet.of(NIF.URISCHEME, NIF.RFC5147_STRING, NIF.CSTRING, new URIImpl(semNS + "InformationEntity"), new URIImpl(semNS + "Expression"), new URIImpl(semNS + "Meaning")); for (final Statement stmt : ImmutableList.copyOf(tbox)) { final Resource s = stmt.getSubject(); final URI p = stmt.getPredicate(); final Value o = stmt.getObject(); if (unwantedConcepts.contains(s) || unwantedConcepts.contains(o) || (s.equals(PMO.SEMANTIC_CLASS_MAPPING) || s.equals(PMO.SEMANTIC_ROLE_MAPPING) || s .equals(PMO.CONCEPTUALIZATION_MAPPING)) && p.equals(RDFS.SUBCLASSOF) && o instanceof BNode) { tbox.remove(stmt); } } LOGGER.info("TBox loaded - {} quads", tbox.size()); // Close TBox final Ruleset tboxRuleset = Ruleset .fromRDF("classpath:/eu/fbk/dkm/premon/premonitor/ruleset.ttl"); RuleEngine.create(tboxRuleset).eval(tbox); LOGGER.info("TBox closed - {} quads", tbox.size()); if (owl2rl) { // Initialize ABox rule engine final Ruleset aboxRuleset = tboxRuleset.getABoxRuleset(tbox); final RuleEngine aboxEngine = RuleEngine.create(aboxRuleset); LOGGER.info("ABox rule engine initialized - {}", aboxEngine); // Perform ABox inference for (final Map.Entry<String, Map<URI, QuadModel>> entry1 : models.entrySet()) { for (final Map.Entry<URI, QuadModel> entry2 : entry1.getValue().entrySet()) { final int sizeBefore = entry2.getValue().size(); aboxEngine.eval(entry2.getValue()); for (final Statement stmt : tbox) { entry2.getValue().remove(stmt.getSubject(), stmt.getPredicate(), stmt.getObject()); } final int sizeAfter = entry2.getValue().size(); LOGGER.info("ABox closed for {}, graph {}: from {} to {} quads", entry1.getKey(), entry2.getKey(), sizeBefore, sizeAfter); } } // Remove redundant quads (i.e., type quads of pm:entries from other graphs, and type // quads of pm:entries and resource graphs from pm:examples) for (final Map.Entry<String, Map<URI, QuadModel>> entry1 : models.entrySet()) { final String source = entry1.getKey(); final Map<URI, QuadModel> sourceModels = entry1.getValue(); final QuadModel entriesModel = sourceModels.get(PM.ENTRIES); for (final Map.Entry<URI, QuadModel> entry2 : sourceModels.entrySet()) { final URI graph = entry2.getKey(); final boolean isEntries = graph.equals(PM.ENTRIES); final boolean isExamples = isExampleGraph(graph); final QuadModel filteredModel = QuadModel.create(); outer: for (final Statement stmt : entry2.getValue()) { if (stmt.getPredicate().getNamespace().equals("sys:")) { continue; } else if (stmt.getPredicate().equals(RDF.TYPE)) { if (stmt.getObject() instanceof BNode) { continue; } else if (stmt.getObject() instanceof URI && ((URI) stmt.getObject()).getNamespace().equals("sys:")) { continue; } else if (isExamples) { for (final QuadModel model : sourceModels.values()) { if (model != entry2.getValue() && model.contains(stmt)) { continue outer; } } } else if (!isEntries) { if (entriesModel!=null && entriesModel.contains(stmt)) { continue; } } } filteredModel.add(stmt); } final int sizeBefore = entry2.getValue().size(); entry2.setValue(filteredModel); final int sizeAfter = entry2.getValue().size(); LOGGER.info("ABox filtered for {}, graph {}: from {} to {} quads", source, entry2.getKey(), sizeBefore, sizeAfter); } } } // Filter TBox for (final Statement stmt : ImmutableList.copyOf(tbox)) { if (stmt.getPredicate().getNamespace().equals("sys:") || stmt.getObject() instanceof URI && ((URI) stmt.getObject()).getNamespace().equals("sys:")) { tbox.remove(stmt); } } // Compute mapping statistics before filtering mappings final List<String> sourceKeys = ImmutableList.copyOf(Iterables.concat(models.keySet(), ImmutableList.of("on5", "wn30", "wn31", "ili", "all"))); final List<QuadModel> quadModels = models.values().stream() .flatMap(m -> m.values().stream()).collect(Collectors.toList()); Map<String, MappingStatistics> msBefore = null; Map<String, MappingStatistics> msAfter = null; if (statistics) { msBefore = Maps.newHashMap(); for (final Map.Entry<String, Map<URI, QuadModel>> entry : models.entrySet()) { msBefore.put(entry.getKey(), new MappingStatistics(entry.getValue().values(), sourceKeys)); } msBefore.put("all", new MappingStatistics(quadModels, ImmutableList.of())); msAfter = msBefore; } if (filterMappings) { filterMappings(models); } // Compute and emit statistics if (statistics) { if (filterMappings) { msAfter = Maps.newHashMap(); for (final Map.Entry<String, Map<URI, QuadModel>> entry : models.entrySet()) { msAfter.put(entry.getKey(), new MappingStatistics(entry.getValue().values(), sourceKeys)); } msAfter.put("all", new MappingStatistics(quadModels, ImmutableList.of())); } LOGGER.info("Resource statistics"); LOGGER.info(String.format(" %-10s %-9s %-9s %-9s %-9s %-9s %-9s %-9s %-9s %-9s", "source", "#classes", "#roles", "#conc", "#entries", "#examples", "#annsets", "#classrel", "#rolerel", "#corestmt")); for (final Map.Entry<String, Map<URI, QuadModel>> entry : models.entrySet()) { final String source = entry.getKey(); final InstanceStatistics s = new InstanceStatistics(entry.getValue().values(), tbox); LOGGER.info(String.format(" %-10s %-9d %-9d %-9d %-9d %-9d %-9d %-9d %-9d %-9d", source, s.numSemanticClasses, s.numSemanticRoles, s.numConceptualizations, s.numLexicalEntries, s.numExamples, s.numAnnotationSets, s.numClassRels, s.numRoleRels, s.numCoreTriples)); } final InstanceStatistics s = new InstanceStatistics(quadModels, tbox); LOGGER.info(String.format(" %-10s %-9d %-9d %-9d %-9d %-9d %-9d %-9d %-9d %-9d", "all", s.numSemanticClasses, s.numSemanticRoles, s.numConceptualizations, s.numLexicalEntries, s.numExamples, s.numAnnotationSets, s.numClassRels, s.numRoleRels, s.numCoreTriples)); LOGGER.info("Mapping statistics"); LOGGER.info(String.format(" %-32s %-39s %-39s", "sources", "# good mappings", "# invalid mappings")); LOGGER.info(String.format( " %-10s %-10s %-10s %-9s %-9s %-9s %-9s %-9s %-9s %-9s %-9s", "from", "to", "resource", "con", "class", "role", "other", "con", "class", "role", "other")); for (final String from : sourceKeys) { final Integer z = new Integer(0); for (final String to : sourceKeys) { for (final String resource : Iterables.concat(models.keySet(), ImmutableList.of("all"))) { final MappingStatistics ms = msAfter.get(resource); final MappingStatistics msb = msBefore.get(resource); final int nx, nc, nr, no, nxb, ncb, nrb, nob; nx = MoreObjects.firstNonNull(ms.conMappings.get(from, to), z); nc = MoreObjects.firstNonNull(ms.classMappings.get(from, to), z); nr = MoreObjects.firstNonNull(ms.roleMappings.get(from, to), z); no = MoreObjects.firstNonNull(ms.otherMappings.get(from, to), z); nxb = MoreObjects.firstNonNull(msb.conMappings.get(from, to), z); ncb = MoreObjects.firstNonNull(msb.classMappings.get(from, to), z); nrb = MoreObjects.firstNonNull(msb.roleMappings.get(from, to), z); nob = MoreObjects.firstNonNull(msb.otherMappings.get(from, to), z); if (nxb + ncb + nrb + nob > 0) { LOGGER.info(String.format( " %-10s %-10s %-10s %-9d %-9d %-9d %-9d %-9d %-9d %-9d %-9d", from, to, resource, nx, nc, nr, no, nxb - nx, ncb - nc, nrb - nr, nob - no)); } } } } } // Start emitting data LOGGER.info("Emitting datasets ..."); // Emit TBox emit(base, "tbox", formats, ImmutableMap.of(PM.TBOX, tbox), null, owl2rl, false); // Emit data of each resource, separating examples from other graphs final Multimap<URI, QuadModel> modelsByURI = HashMultimap.create(); for (final Map.Entry<String, Map<URI, QuadModel>> entry : models.entrySet()) { final String source = entry.getKey(); final Map<URI, QuadModel> graphModels = entry.getValue(); emit(base, source, formats, Maps.filterKeys(graphModels, g -> !isExampleGraph(g)), tbox, owl2rl, statistics); emit(base, source + "-examples", formats, Maps.filterKeys(graphModels, g -> isExampleGraph(g)), tbox, owl2rl, statistics); modelsByURI.putAll(Multimaps.forMap(graphModels)); } // Emit aggregated data final Map<URI, QuadModel> mergedGraphModels = Maps.newHashMap(); mergedGraphModels.put(PM.TBOX, tbox); for (final Map.Entry<URI, Collection<QuadModel>> entry : modelsByURI.asMap().entrySet()) { if (entry.getValue().size() == 1) { mergedGraphModels.put(entry.getKey(), entry.getValue().iterator().next()); } else if (entry.getValue().size() > 1) { final QuadModel mergedModel = QuadModel.create(); for (final QuadModel model : entry.getValue()) { for (final Namespace ns : model.getNamespaces()) { mergedModel.setNamespace(ns); } mergedModel.addAll(model); } mergedGraphModels.put(entry.getKey(), mergedModel); } } emit(base, "models", formats, Maps.filterKeys(mergedGraphModels, g -> !isExampleGraph(g)), tbox, owl2rl, statistics); emit(base, "all", formats, mergedGraphModels, tbox, owl2rl, statistics); } private static void emit(final String base, final String classifier, final String[] formats, final Map<URI, QuadModel> models, @Nullable final QuadModel tbox, final boolean owl2rl, final boolean statistics) throws RDFHandlerException { // Assemble RDFpro pipeline - start emitting closed data in all configured formats final List<RDFProcessor> processors = Lists.newArrayList(); for (final String format : formats) { final String location = base + "-" + classifier + (owl2rl ? "-inf." : ".") + format; processors.add(RDFProcessors.write(null, 1000, location)); } processors.add(RDFProcessors.track(new Tracker(LOGGER, null, classifier + (owl2rl ? "-inf" : "") + " - %d quads", null))); // Compute and emit statistics if enabled if (statistics) { final List<RDFProcessor> statsProcessors = Lists.newArrayList(); statsProcessors.add(RDFProcessors.stats(null, null, null, null, false)); for (final String format : formats) { final String location = base + "-" + classifier + "-stats." + format; statsProcessors.add(RDFProcessors.write(null, 1000, location)); } statsProcessors.add(RDFProcessors.track(new Tracker(LOGGER, null, classifier + "-stats - %d quads", null))); statsProcessors.add(RDFProcessors.NIL); processors.add(RDFProcessors.parallel(SetOperator.UNION_MULTISET, RDFProcessors.IDENTITY, RDFProcessors.sequence(statsProcessors.toArray(new RDFProcessor[0])))); } // Remove inferrable triples, write, compute statistics, write if (owl2rl && tbox != null) { processors.add(new ProcessorUndoRDFS(RDFSources.wrap(tbox))); for (final String format : formats) { final String location = base + "-" + classifier + "-noinf." + format; processors.add(RDFProcessors.write(null, 1000, location)); } processors.add(RDFProcessors.track(new Tracker(LOGGER, null, classifier + "-noinf - %d quads", null))); } // Build the resulting sequence processor final RDFProcessor processor = RDFProcessors.sequence(processors .toArray(new RDFProcessor[processors.size()])); // Apply the processor final RDFHandler handler = processor.wrap(RDFHandlers.NIL); try { // Start handler.startRDF(); // Emit namespaces first final Set<Namespace> namespaces = Sets.newHashSet(); for (final QuadModel model : models.values()) { namespaces.addAll(model.getNamespaces()); } for (final Namespace namespace : Ordering.natural().sortedCopy(namespaces)) { handler.handleNamespace(namespace.getPrefix(), namespace.getName()); } // Emit data, one graph at a time and starting with pm:meta and pm:entries final List<URI> sortedGraphs = Lists.newArrayList(); if (models.containsKey(PM.META)) { sortedGraphs.add(PM.META); } if (models.containsKey(PM.ENTRIES)) { sortedGraphs.add(PM.ENTRIES); } for (final URI graph : Ordering.from(Statements.valueComparator()).sortedCopy( models.keySet())) { if (!graph.equals(PM.META) && !graph.equals(PM.ENTRIES)) { sortedGraphs.add(graph); } } for (final URI graph : sortedGraphs) { for (final Statement stmt : models.get(graph)) { handler.handleStatement(new ContextStatementImpl(stmt.getSubject(), stmt .getPredicate(), stmt.getObject(), graph)); } } } catch (final Throwable ex) { LOGGER.error("File generation failed", ex); } finally { // End and release allocated resources handler.endRDF(); IO.closeQuietly(handler); } } private static void filterMappings(final Map<String, Map<URI, QuadModel>> models) { LOGGER.info("Removing illegal mappings..."); final Set<URI> validItems = Sets.newHashSet(); for (final Map<URI, QuadModel> map : models.values()) { for (final QuadModel model : map.values()) { for (final Statement stmt : model.filter(null, PMO.EVOKED_CONCEPT, null)) { validItems.add((URI) stmt.getSubject()); // conceptualizations } for (final Statement stmt : model.filter(null, PMO.SEM_ROLE, null)) { validItems.add((URI) stmt.getSubject()); // semantic class validItems.add((URI) stmt.getObject()); // semantic roles } } } for (final Map<URI, QuadModel> map : models.values()) { for (final Map.Entry<URI, QuadModel> entry : map.entrySet()) { final QuadModel model = entry.getValue(); for (final URI type : new URI[] { PMO.CONCEPTUALIZATION_MAPPING, PMO.SEMANTIC_CLASS_MAPPING, PMO.SEMANTIC_ROLE_MAPPING }) { int numMappingsToDelete = 0; int numMappings = 0; int mappingsDeletedCompletely = 0; int referencesRemoved = 0; final Map<String, Integer> numMappingsPerSource = Maps.newHashMap(); final List<Statement> stmtsToDelete = Lists.newArrayList(); for (final Resource m : model.filter(null, RDF.TYPE, type).subjects()) { ++numMappings; final List<Statement> stmts = ImmutableList.copyOf(model.filter(m, null, null)); boolean valid = true; final List<Statement> stmtsInvalid = Lists.newArrayList(); for (final Statement stmt : stmts) { if (stmt.getPredicate().equals(PMO.ITEM) && !validItems.contains(stmt.getObject())) { ++numMappingsToDelete; final String str = stmt.getObject().stringValue(); for (final String source : models.keySet()) { if (str.contains("-" + source + "-") || str.contains("/" + source + "-")) { numMappingsPerSource.put(source, 1 + numMappingsPerSource.getOrDefault(source, 0)); } } if (numMappingsToDelete <= 10) { LOGGER.warn("Removing illegal mapping {} - missing {}", m, stmt.getObject()); } else if (LOGGER.isDebugEnabled()) { LOGGER.debug("Removing illegal mapping {} - missing {}", m, stmt.getObject()); } else if (numMappingsToDelete == 11) { LOGGER.warn("Omitting further illegal mappings ...."); } stmtsInvalid.add(stmt); valid = false; break; } } if (!valid) { int items = 0, itemsInv = 0; for (final Statement stmt : stmts) { if (stmt.getPredicate().equals(PMO.ITEM)) { items++; } } for (final Statement stmt : stmtsInvalid) { if (stmt.getPredicate().equals(PMO.ITEM)) { itemsInv++;//useless (all Statement in stmtsInvalid are items) } } if (items - itemsInv < 2) { stmtsToDelete.addAll(stmts); mappingsDeletedCompletely++; if (numMappingsToDelete <= 10 || LOGGER.isDebugEnabled()) { LOGGER.info("Removing the complete mapping"); } } else { stmtsToDelete.addAll(stmtsInvalid); referencesRemoved++; if (numMappingsToDelete <= 10 || LOGGER.isDebugEnabled()) { LOGGER.info("Removing only missing reference"); } } } } if (numMappingsToDelete > 0) { for (final Statement stmt : stmtsToDelete) { model.remove(stmt); } LOGGER.warn( "{}/{} illegal {} mappings and {} references {} removed from {}\n mappingsDeletedCompletely, numMappings, type.equals(PMO.SEMANTIC_CLASS_MAPPING) ? "semantic class" : type.equals(PMO.CONCEPTUALIZATION_MAPPING) ? "conceptualization" : "semantic role", referencesRemoved, numMappingsPerSource, entry.getKey()); } } } } //Cleaning Ontological Mappings for (final Map<URI, QuadModel> map : models.values()) { for (final Map.Entry<URI, QuadModel> entry : map.entrySet()) { final QuadModel model = entry.getValue(); final List<Statement> stmts = ImmutableList.copyOf(model.filter(null,PMO.ONTO_MATCH, null)); int numMappingsToDelete = 0; int numTriplesToDelete = 0; for (Statement stmt:stmts ) { if (!validItems.contains(stmt.getSubject())) { ++numMappingsToDelete; //delete ontology matching triple ++numTriplesToDelete; model.remove(stmt); if (numMappingsToDelete <= 10) { LOGGER.warn("Removing illegal ontoMatch {} - missing {}", stmt.getSubject(), stmt.getObject()); } else if (LOGGER.isDebugEnabled()) { LOGGER.debug("Removing illegal ontoMatch {} - missing {}", stmt.getSubject(), stmt.getObject()); } else if (numMappingsToDelete == 11) { LOGGER.warn("Omitting further illegal ontoMatch assertions ...."); } //check if there are other things mapping to the same ontological concept, otherwise remove all its triple if (ImmutableList.copyOf(model.filter(null, PMO.ONTO_MATCH, stmt.getObject())).isEmpty()) { final List<Statement> onto_stmts_all = ImmutableList.copyOf(model.filter((URI) stmt.getObject(),null, null)); for (final Statement s: onto_stmts_all ) { ++numTriplesToDelete; model.remove(s); LOGGER.debug("Removing onto triple {} - {} - {}", s.getSubject(),s.getPredicate(), s.getObject()); } } //Check if only remaining triple on subject is "rdf:type skos:Concept". if so remove final List<Statement> rel_stmts = ImmutableList.copyOf(model.filter(stmt.getSubject(),null, null)); if ((ImmutableList.copyOf(model.filter(stmt.getSubject(),null, null)).size()==1)&&rel_stmts.get(0).getPredicate().equals(RDF.TYPE)&&rel_stmts.get(0).getObject().equals(SKOS.CONCEPT)) { ++numTriplesToDelete; LOGGER.debug("Removing type triple {} - {} - {}", rel_stmts.get(0).getSubject(),rel_stmts.get(0).getPredicate(), rel_stmts.get(0).getObject()); model.remove(stmt); } } } LOGGER.warn( "{} illegal ontoMatch assertions and {} related triples removed from {}\n numMappingsToDelete, numTriplesToDelete, entry.getKey()); } } } private static boolean isExampleGraph(final URI uri) { return uri.getLocalName().endsWith("-ex"); } private static final class InstanceStatistics { final int numSemanticClasses; final int numSemanticRoles; final int numConceptualizations; final int numLexicalEntries; final int numExamples; final int numAnnotationSets; final int numClassRels; final int numRoleRels; final int numCoreTriples; public InstanceStatistics(final Iterable<? extends QuadModel> models, final QuadModel tbox) { final Set<URI> roleRelProperties = Sets.newHashSet(); for (final Resource rel : tbox.filter(null, RDFS.SUBPROPERTYOF, PMO.ROLE_REL) .subjects()) { if (rel instanceof URI && !rel.equals(PMO.ROLE_REL)) { roleRelProperties.add((URI) rel); } } final Set<Value> classes = Sets.newHashSet(); final Set<Value> roles = Sets.newHashSet(); final Set<Value> examples = Sets.newHashSet(); final Set<Value> annotationSets = Sets.newHashSet(); final Set<Statement> classRels = Sets.newHashSet(); final Set<Statement> roleRels = Sets.newHashSet(); for (final QuadModel model : models) { for (final Resource c : model.filter(null, RDF.TYPE, PMO.SEMANTIC_CLASS) .subjects()) { if (model.contains(null, PMO.EVOKED_CONCEPT, c) || model.contains(c, PMO.CLASS_REL, null) || model.contains(null, PMO.CLASS_REL, c)) { classes.add(c); } } roles.addAll(model.filter(null, PMO.SEM_ROLE, null).objects()); examples.addAll(model.filter(null, RDF.TYPE, PMO.EXAMPLE).subjects()); annotationSets.addAll(model.filter(null, RDF.TYPE, PMO.ANNOTATION_SET).subjects()); classRels.addAll(model.filter(null, PMO.CLASS_REL, null)); for (final URI roleRelProperty : roleRelProperties) { roleRels.addAll(model.filter(null, roleRelProperty, null)); } } this.numSemanticClasses = classes.size(); this.numSemanticRoles = roles.size(); this.numExamples = examples.size(); this.numAnnotationSets = annotationSets.size(); this.numClassRels = classRels.size(); this.numRoleRels = roleRels.size(); final Set<Statement> conceptualizations = Sets.newHashSet(); final Set<Value> lexicalEntries = Sets.newHashSet(); for (final QuadModel model : models) { for (final Statement stmt : model.filter(null, ONTOLEX.EVOKES, null)) { if (classes.contains(stmt.getObject()) || roles.contains(stmt.getObject())) { conceptualizations.add(stmt); lexicalEntries.add(stmt.getSubject()); } } } this.numConceptualizations = conceptualizations.size(); this.numLexicalEntries = lexicalEntries.size(); final Set<Value> coreInstances = Sets.newHashSet(); for (final QuadModel model : models) { for (final Statement stmt : model.filter(null, RDF.TYPE, null)) { final Value type = stmt.getObject(); if (type.equals(PMO.SEMANTIC_CLASS) || type.equals(PMO.SEMANTIC_ROLE) || type.equals(PMO.CONCEPTUALIZATION) || type.equals(PMO.MAPPING) || type.equals(ONTOLEX.LEXICAL_ENTRY) || type.equals(ONTOLEX.FORM)) { coreInstances.add(stmt.getSubject()); } } } final Set<Statement> coreStmts = Sets.newHashSet(); for (final QuadModel model : models) { for (final Statement stmt : model) { if (coreInstances.contains(stmt.getSubject()) || coreInstances.contains(stmt.getObject())) { if (stmt.getPredicate().equals(ONTOLEX.CANONICAL_FORM) || stmt.getPredicate().equals(ONTOLEX.WRITTEN_REP) || stmt.getPredicate().equals(PMO.FIRST)) { continue; // avoid counting inferences } final String ns = stmt.getPredicate().getNamespace(); if (ns.equals(PMO.NAMESPACE) || ns.equals(ONTOLEX.NAMESPACE) || ns.equals(DECOMP.NAMESPACE) || ns.equals(LEXINFO.NAMESPACE) || ns.equals(RDFS.NAMESPACE) || ns.equals(OWL.NAMESPACE) || ns.equals(DCTERMS.NAMESPACE)) { coreStmts.add(stmt); } } } } this.numCoreTriples = coreStmts.size(); } } private static final class MappingStatistics { final Table<String, String, Integer> conMappings; final Table<String, String, Integer> classMappings; final Table<String, String, Integer> roleMappings; final Table<String, String, Integer> otherMappings; public MappingStatistics(final Iterable<? extends QuadModel> models, final Iterable<String> sources) { final Table<String, String, Set<Hash>> conHashes = HashBasedTable.create(); final Table<String, String, Set<Hash>> classHashes = HashBasedTable.create(); final Table<String, String, Set<Hash>> roleHashes = HashBasedTable.create(); final Table<String, String, Set<Hash>> otherHashes = HashBasedTable.create(); final List<String> sourceKeys = ImmutableList.copyOf(sources); final List<Pattern> sourcePatterns = ImmutableList.copyOf(sourceKeys.stream() .map(s -> Pattern.compile("[-/]" + Pattern.quote(s) + "-")).iterator()); for (final QuadModel model : models) { for (final Resource mapping : model.filter(null, RDF.TYPE, PMO.MAPPING).subjects()) { final Table<String, String, Set<Hash>> hashes; if (model.contains(mapping, RDF.TYPE, PMO.CONCEPTUALIZATION_MAPPING)) { hashes = conHashes; } else if (model.contains(mapping, RDF.TYPE, PMO.SEMANTIC_CLASS_MAPPING)) { hashes = classHashes; } else if (model.contains(mapping, RDF.TYPE, PMO.SEMANTIC_ROLE_MAPPING)) { hashes = roleHashes; } else { hashes = otherHashes; } final Map<String, String> items = Maps.newHashMap(); for (final Value item : model.filter(mapping, PMO.ITEM, null).objects()) { final String str = item.stringValue(); for (int i = 0; i < sourceKeys.size(); ++i) { if (sourcePatterns.get(i).matcher(str).find()) { items.put(sourceKeys.get(i), item.stringValue()); } } } for (final String fromSource : items.keySet()) { for (final String toSource : items.keySet()) { if (fromSource.compareTo(toSource) < 0) { addHash(hashes, fromSource, toSource, items.get(fromSource), "|", items.get(toSource)); } } } addHash(hashes, "all", "all", Joiner.on('|').join(Ordering.natural().sortedCopy(items.values()))); } } this.conMappings = countHashes(conHashes); this.classMappings = countHashes(classHashes); this.roleMappings = countHashes(roleHashes); this.otherMappings = countHashes(otherHashes); } private static void addHash(final Table<String, String, Set<Hash>> hashes, final String row, final String col, final String... hashedStrings) { Set<Hash> set = hashes.get(row, col); if (set == null) { set = Sets.newHashSet(); hashes.put(row, col, set); } set.add(Hash.murmur3(hashedStrings)); } private static Table<String, String, Integer> countHashes( final Table<String, String, Set<Hash>> hashes) { final Table<String, String, Integer> counts = HashBasedTable.create(); for (final Cell<String, String, Set<Hash>> cell : hashes.cellSet()) { counts.put(cell.getRowKey(), cell.getColumnKey(), cell.getValue().size()); } return counts; } } }
package org.clarksnut.query; import java.util.ArrayList; import java.util.List; public class BoolQuery implements ComposedQuery { private final List<Query> must = new ArrayList<>(); private final List<Query> mustNot = new ArrayList<>(); private final List<Query> should = new ArrayList<>(); private final List<Query> filter = new ArrayList<>(); private String minimumShouldMatch; @Override public String getQueryName() { return "BoolQuery"; } public BoolQuery must(Query query) { this.must.add(query); return this; } public BoolQuery mustNot(Query query) { this.mustNot.add(query); return this; } public BoolQuery should(Query query) { this.should.add(query); return this; } public BoolQuery minimumShouldMatch(String minimumShouldMatch) { this.minimumShouldMatch = minimumShouldMatch; return this; } public BoolQuery minimumShouldMatch(Integer minimumShouldMatch) { this.minimumShouldMatch = Integer.toString(minimumShouldMatch); return this; } public BoolQuery filter(Query query) { this.filter.add(query); return this; } public List<Query> getMust() { return must; } public List<Query> getMustNot() { return mustNot; } public List<Query> getShould() { return should; } public String getMinimumShouldMatch() { return minimumShouldMatch; } public List<Query> getFilter() { return filter; } }
package org.cojen.tupl.rows; import java.math.BigDecimal; import java.math.BigInteger; import org.cojen.maker.Label; import org.cojen.maker.MethodMaker; import org.cojen.maker.Variable; import static org.cojen.tupl.rows.ColumnInfo.*; /** * @author Brian S O'Neill */ public class Converter { /** * Generates code which decodes a column and stores it in dstVar, applying a lossy * conversion if necessary. * * @param srcVar source byte array * @param offsetVar int type; is incremented as a side-effect * @param endVar end offset, which when null implies the end of the array */ static void decode(final MethodMaker mm, final Variable srcVar, final Variable offsetVar, final Variable endVar, final ColumnCodec srcCodec, final ColumnInfo dstInfo, final Variable dstVar) { if (dstInfo.type.isAssignableFrom(srcCodec.mInfo.type) && (!srcCodec.mInfo.isNullable() || dstInfo.isNullable())) { srcCodec.decode(dstVar, srcVar, offsetVar, null); } else { // Decode into a temp variable and then perform a best-effort conversion. var tempVar = mm.var(srcCodec.mInfo.type); srcCodec.decode(tempVar, srcVar, offsetVar, endVar); convertLossy(mm, srcCodec.mInfo, tempVar, dstInfo, dstVar); } } /** * Generates code which converts a source variable into something that the destination * variable can accept. No conversion is applied if unnecessary. * * The conversion never results in an exception, but data loss is possible. Numerical * conversions are clamped to fit within a target range, for example. If a conversion is * completely impossible, then a suitable default value is chosen. See setDefault. */ static void convertLossy(final MethodMaker mm, final ColumnInfo srcInfo, final Variable srcVar, final ColumnInfo dstInfo, final Variable dstVar) { if (srcInfo.typeCode == dstInfo.typeCode) { dstVar.set(srcVar); return; } Label end = mm.label(); if (srcInfo.isNullable()) { Label notNull = mm.label(); srcVar.ifNe(null, notNull); if (dstInfo.isNullable()) { dstVar.set(null); } else { setDefault(mm, dstInfo, dstVar); } mm.goto_(end); notNull.here(); } // Note: At this point, srcVar isn't null. if (dstInfo.isArray()) { ColumnInfo dstElementInfo = dstInfo.nonArray(); if (srcInfo.isArray()) { // Array to array conversion. ColumnInfo srcElementInfo = srcInfo.nonArray(); dstVar.set(ConvertUtils.convertArray (mm, dstVar.classType(), srcVar.alength(), ixVar -> { Variable dstElementVar = mm.var(dstElementInfo.type); convertLossy(mm, srcElementInfo, srcVar.aget(ixVar), dstElementInfo, dstElementVar); return dstElementVar; })); } else { // Non-array to array conversion. if (srcInfo.plainTypeCode() == TYPE_UTF8 && dstElementInfo.plainTypeCode() == TYPE_CHAR) { // Special case for String to char[]. Extract all the characters. var lengthVar = srcVar.invoke("length"); dstVar.set(mm.new_(dstVar, lengthVar)); srcVar.invoke("getChars", 0, lengthVar, dstVar, 0); } else { var dstElementVar = mm.var(dstElementInfo.type); convertLossy(mm, srcInfo, srcVar, dstElementInfo, dstElementVar); dstVar.set(mm.new_(dstVar, 1)); dstVar.aset(0, dstElementVar); } } end.here(); return; } if (srcInfo.isArray()) { // Array to non-array conversion. ColumnInfo srcElementInfo = srcInfo.nonArray(); if (srcElementInfo.plainTypeCode() == TYPE_CHAR && dstInfo.plainTypeCode() == TYPE_UTF8) { // Special case for char[] to String. Copy all the characters. dstVar.set(mm.var(String.class).invoke("valueOf", srcVar)); } else { Label notEmpty = mm.label(); srcVar.alength().ifNe(0, notEmpty); setDefault(mm, dstInfo, dstVar); mm.goto_(end); notEmpty.here(); convertLossy(mm, srcElementInfo, srcVar.aget(0), dstInfo, dstVar); } end.here(); return; } int srcPlainTypeCode = srcInfo.plainTypeCode(); if (dstInfo.isAssignableFrom(srcPlainTypeCode)) { dstVar.set(srcVar); end.here(); return; } int dstPlainTypeCode = dstInfo.plainTypeCode(); boolean handled = true; switch (dstPlainTypeCode) { case TYPE_BOOLEAN: // Note: For numbers, boolean is treated as an int clamped to the range [0, 1]. switch (srcPlainTypeCode) { case TYPE_BYTE, TYPE_SHORT, TYPE_INT, TYPE_LONG -> dstVar.set(srcVar.gt(0)); case TYPE_UBYTE, TYPE_USHORT, TYPE_UINT, TYPE_ULONG -> dstVar.set(srcVar.ne(0)); case TYPE_FLOAT -> dstVar.set(srcVar.ge(1.0f)); case TYPE_DOUBLE -> dstVar.set(srcVar.ge(1.0d)); case TYPE_BIG_INTEGER -> dstVar.set(srcVar.invoke("compareTo", mm.var(BigInteger.class).field("ZERO")).gt(0)); case TYPE_BIG_DECIMAL -> dstVar.set(srcVar.invoke("compareTo", mm.var(BigDecimal.class).field("ONE")).ge(0)); case TYPE_CHAR -> { var utils = mm.var(Converter.class); if (dstInfo.type.isPrimitive()) { dstVar.set(utils.invoke("charToBoolean", srcVar)); } else { Boolean default_ = dstInfo.isNullable() ? null : false; dstVar.set(utils.invoke("charToBoolean", srcVar, default_)); } } case TYPE_UTF8 -> { var utils = mm.var(Converter.class); if (dstInfo.type.isPrimitive()) { dstVar.set(utils.invoke("stringToBoolean", srcVar)); } else { Boolean default_ = dstInfo.isNullable() ? null : false; dstVar.set(utils.invoke("stringToBoolean", srcVar, default_)); } } default -> handled = false; } break; case TYPE_BYTE: switch (srcPlainTypeCode) { case TYPE_BOOLEAN -> boolToNum(mm, srcVar, dstVar); case TYPE_SHORT, TYPE_INT, TYPE_LONG -> clampSS(mm, srcVar, -128, 127, dstVar); case TYPE_UBYTE -> clampUS(mm, srcVar, Byte.MAX_VALUE, dstVar); case TYPE_USHORT, TYPE_UINT, TYPE_ULONG -> clampUS_narrow(mm, srcVar, Byte.MAX_VALUE, dstVar); case TYPE_CHAR -> clampUS_narrow(mm, srcVar.cast(int.class), Byte.MAX_VALUE, dstVar); case TYPE_FLOAT, TYPE_DOUBLE -> clampSS(mm, srcVar.cast(int.class), -128, 127, dstVar); case TYPE_BIG_INTEGER -> clampBigInteger_narrow(mm, srcVar, Byte.MIN_VALUE, Byte.MAX_VALUE, dstInfo, dstVar, "byteValue"); case TYPE_BIG_DECIMAL -> clampBigDecimal_narrow(mm, srcVar, Byte.MIN_VALUE, Byte.MAX_VALUE, dstInfo, dstVar, "byteValue"); case TYPE_UTF8 -> { var bd = parseBigDecimal(mm, srcVar, dstInfo, dstVar, end); clampBigDecimal_narrow(mm, bd, Byte.MIN_VALUE, Byte.MAX_VALUE, dstInfo, dstVar, "byteValue"); } default -> handled = false; } break; case TYPE_SHORT: switch (srcPlainTypeCode) { case TYPE_BOOLEAN -> boolToNum(mm, srcVar, dstVar); case TYPE_INT, TYPE_LONG -> clampSS(mm, srcVar, -32768, 32767, dstVar); case TYPE_UBYTE -> dstVar.set(srcVar.cast(int.class).and(0xff).cast(short.class)); case TYPE_USHORT -> clampUS(mm, srcVar, Short.MAX_VALUE, dstVar); case TYPE_UINT, TYPE_ULONG -> clampUS_narrow(mm, srcVar, Short.MAX_VALUE, dstVar); case TYPE_CHAR -> clampUS_narrow(mm, srcVar.cast(int.class), Short.MAX_VALUE, dstVar); case TYPE_FLOAT, TYPE_DOUBLE -> clampSS(mm, srcVar.cast(int.class), -32768, 32767, dstVar); case TYPE_BIG_INTEGER -> clampBigInteger_narrow(mm, srcVar, Short.MIN_VALUE, Short.MAX_VALUE, dstInfo, dstVar, "shortValue"); case TYPE_BIG_DECIMAL -> clampBigDecimal_narrow(mm, srcVar, Short.MIN_VALUE, Short.MAX_VALUE, dstInfo, dstVar, "shortValue"); case TYPE_UTF8 -> { var bd = parseBigDecimal(mm, srcVar, dstInfo, dstVar, end); clampBigDecimal_narrow(mm, bd, Short.MIN_VALUE, Short.MAX_VALUE, dstInfo, dstVar, "shortValue"); } default -> handled = false; } break; case TYPE_INT: switch (srcPlainTypeCode) { case TYPE_BOOLEAN -> boolToNum(mm, srcVar, dstVar); case TYPE_LONG -> clampSS(mm, srcVar, Integer.MIN_VALUE, Integer.MAX_VALUE, dstVar); case TYPE_UBYTE -> dstVar.set(srcVar.cast(int.class).and(0xff)); case TYPE_USHORT, TYPE_CHAR -> dstVar.set(srcVar.cast(int.class).and(0xffff)); case TYPE_UINT -> clampUS(mm, srcVar, Integer.MAX_VALUE, dstVar); case TYPE_ULONG -> clampUS_narrow(mm, srcVar, Integer.MAX_VALUE, dstVar); case TYPE_FLOAT, TYPE_DOUBLE -> dstVar.set(srcVar.cast(int.class)); case TYPE_BIG_INTEGER -> clampBigInteger_narrow(mm, srcVar, Integer.MIN_VALUE, Integer.MAX_VALUE, dstInfo, dstVar, "intValue"); case TYPE_BIG_DECIMAL -> clampBigDecimal_narrow(mm, srcVar, Integer.MIN_VALUE, Integer.MAX_VALUE, dstInfo, dstVar, "intValue"); case TYPE_UTF8 -> { var bd = parseBigDecimal(mm, srcVar, dstInfo, dstVar, end); clampBigDecimal_narrow(mm, bd, Integer.MIN_VALUE, Integer.MAX_VALUE, dstInfo, dstVar, "intValue"); } default -> handled = false; } break; case TYPE_LONG: switch (srcPlainTypeCode) { case TYPE_BOOLEAN -> boolToNum(mm, srcVar, dstVar); case TYPE_UBYTE -> dstVar.set(srcVar.cast(long.class).and(0xffL)); case TYPE_USHORT, TYPE_CHAR -> dstVar.set(srcVar.cast(long.class).and(0xffffL)); case TYPE_UINT -> dstVar.set(srcVar.cast(long.class).and(0xffff_ffffL)); case TYPE_ULONG -> clampUS(mm, srcVar, Long.MAX_VALUE, dstVar); case TYPE_FLOAT, TYPE_DOUBLE -> dstVar.set(srcVar.cast(long.class)); case TYPE_BIG_INTEGER -> clampBigInteger_narrow(mm, srcVar, Long.MIN_VALUE, Long.MAX_VALUE, dstInfo, dstVar, "longValue"); case TYPE_BIG_DECIMAL -> clampBigDecimal_narrow(mm, srcVar, Long.MIN_VALUE, Long.MAX_VALUE, dstInfo, dstVar, "longValue"); case TYPE_UTF8 -> { var bd = parseBigDecimal(mm, srcVar, dstInfo, dstVar, end); clampBigDecimal_narrow(mm, bd, Long.MIN_VALUE, Long.MAX_VALUE, dstInfo, dstVar, "longValue"); } default -> handled = false; } break; case TYPE_UBYTE: switch (srcPlainTypeCode) { case TYPE_BOOLEAN -> boolToNum(mm, srcVar, dstVar); case TYPE_BYTE -> clampSU(mm, srcVar, dstVar); case TYPE_SHORT, TYPE_INT, TYPE_LONG -> clampSU_narrow(mm, srcVar, 0xff, dstVar); case TYPE_USHORT, TYPE_UINT -> clampUU_narrow(mm, srcVar, 0xff, dstVar); case TYPE_CHAR -> clampUU_narrow(mm, srcVar.cast(int.class), 0xff, dstVar); case TYPE_ULONG -> clampUU_narrow(mm, srcVar, 0xffL, dstVar); case TYPE_FLOAT -> clampSU_narrow(mm, srcVar.cast(int.class), 0xff, dstVar); case TYPE_DOUBLE -> clampSU_narrow(mm, srcVar.cast(long.class), 0xffL, dstVar); case TYPE_BIG_INTEGER -> clampBigInteger_narrow(mm, srcVar, 0, 0xff, dstInfo, dstVar, "byteValue"); case TYPE_BIG_DECIMAL -> clampBigDecimal_narrow(mm, srcVar, 0, 0xff, dstInfo, dstVar, "byteValue"); case TYPE_UTF8 -> { var bd = parseBigDecimal(mm, srcVar, dstInfo, dstVar, end); clampBigDecimal_narrow(mm, bd, 0, 0xff, dstInfo, dstVar, "byteValue"); } default -> handled = false; } break; case TYPE_USHORT: switch (srcPlainTypeCode) { case TYPE_BOOLEAN -> boolToNum(mm, srcVar, dstVar); case TYPE_BYTE, TYPE_SHORT -> clampSU(mm, srcVar, dstVar); case TYPE_INT, TYPE_LONG -> clampSU_narrow(mm, srcVar, 0xffff, dstVar); case TYPE_UBYTE -> dstVar.set(srcVar.cast(int.class).and(0xff).cast(short.class)); case TYPE_UINT -> clampUU_narrow(mm, srcVar, 0xffff, dstVar); case TYPE_ULONG -> clampUU_narrow(mm, srcVar, 0xffffL, dstVar); case TYPE_FLOAT -> clampSU_narrow(mm, srcVar.cast(int.class), 0xffff, dstVar); case TYPE_DOUBLE -> clampSU_narrow(mm, srcVar.cast(long.class), 0xffffL, dstVar); case TYPE_CHAR -> dstVar.set(srcVar.cast(short.class)); case TYPE_BIG_INTEGER -> clampBigInteger_narrow(mm, srcVar, 0, 0xffff, dstInfo, dstVar, "shortValue"); case TYPE_BIG_DECIMAL -> clampBigDecimal_narrow(mm, srcVar, 0, 0xffff, dstInfo, dstVar, "shortValue"); case TYPE_UTF8 -> { var bd = parseBigDecimal(mm, srcVar, dstInfo, dstVar, end); clampBigDecimal_narrow(mm, bd, 0, 0xffff, dstInfo, dstVar, "shortValue"); } default -> handled = false; } break; case TYPE_UINT: switch (srcPlainTypeCode) { case TYPE_BOOLEAN -> boolToNum(mm, srcVar, dstVar); case TYPE_BYTE, TYPE_SHORT, TYPE_INT -> clampSU(mm, srcVar, dstVar); case TYPE_LONG -> clampSU_narrow(mm, srcVar, 0xffff_ffffL, dstVar); case TYPE_UBYTE -> dstVar.set(srcVar.cast(int.class).and(0xff)); case TYPE_USHORT, TYPE_CHAR -> dstVar.set(srcVar.cast(int.class).and(0xffff)); case TYPE_ULONG -> clampUU_narrow(mm, srcVar, 0xffff_ffffL, dstVar); case TYPE_FLOAT, TYPE_DOUBLE -> clampSU_narrow(mm, srcVar.cast(long.class), 0xffff_ffffL, dstVar); case TYPE_BIG_INTEGER -> clampBigInteger_narrow(mm, srcVar, 0, 0xffff_ffffL, dstInfo, dstVar, "intValue"); case TYPE_BIG_DECIMAL -> clampBigDecimal_narrow(mm, srcVar, 0, 0xffff_ffffL, dstInfo, dstVar, "intValue"); case TYPE_UTF8 -> { var bd = parseBigDecimal(mm, srcVar, dstInfo, dstVar, end); clampBigDecimal_narrow(mm, bd, 0, 0xffff_ffffL, dstInfo, dstVar, "intValue"); } default -> handled = false; } break; case TYPE_ULONG: switch (srcPlainTypeCode) { case TYPE_BOOLEAN -> boolToNum(mm, srcVar, dstVar); case TYPE_BYTE, TYPE_SHORT, TYPE_INT, TYPE_LONG -> clampSU(mm, srcVar, dstVar); case TYPE_UBYTE -> dstVar.set(srcVar.cast(long.class).and(0xff)); case TYPE_USHORT, TYPE_CHAR -> dstVar.set(srcVar.cast(long.class).and(0xffff)); case TYPE_UINT -> dstVar.set(srcVar.cast(long.class).and(0xffff_ffffL)); case TYPE_FLOAT, TYPE_DOUBLE -> dstVar.set(mm.var(Converter.class).invoke("doubleToUnsignedLong", srcVar)); case TYPE_BIG_INTEGER -> clampBigIntegerU_narrow(mm, srcVar, dstInfo, dstVar); case TYPE_BIG_DECIMAL -> clampBigDecimalU_narrow(mm, srcVar, dstInfo, dstVar); case TYPE_UTF8 -> { var bd = parseBigDecimal(mm, srcVar, dstInfo, dstVar, end); clampBigDecimalU_narrow(mm, bd, dstInfo, dstVar); } default -> handled = false; } break; case TYPE_FLOAT: switch (srcPlainTypeCode) { case TYPE_BOOLEAN -> boolToNum(mm, srcVar, dstVar); case TYPE_INT, TYPE_LONG, TYPE_DOUBLE -> dstVar.set(unbox(srcVar).cast(dstVar)); case TYPE_UBYTE -> dstVar.set(srcVar.cast(int.class).and(0xff).cast(dstVar)); case TYPE_USHORT, TYPE_CHAR -> dstVar.set(srcVar.cast(int.class).and(0xffff).cast(dstVar)); case TYPE_UINT -> dstVar.set(srcVar.cast(long.class).and(0xffff_ffffL).cast(dstVar)); case TYPE_ULONG -> { var bd = mm.var(BigDecimal.class); toBigDecimalU(mm, srcVar, bd); dstVar.set(bd.invoke("floatValue")); } case TYPE_BIG_INTEGER, TYPE_BIG_DECIMAL -> dstVar.set(srcVar.invoke("floatValue")); case TYPE_UTF8 -> parseNumber(mm, "parseFloat", srcVar, dstInfo, dstVar); default -> handled = false; } break; case TYPE_DOUBLE: switch (srcPlainTypeCode) { case TYPE_BOOLEAN -> boolToNum(mm, srcVar, dstVar); case TYPE_LONG -> dstVar.set(unbox(srcVar).cast(dstVar)); case TYPE_UBYTE -> dstVar.set(srcVar.cast(int.class).and(0xff).cast(dstVar)); case TYPE_USHORT, TYPE_CHAR -> dstVar.set(srcVar.cast(int.class).and(0xffff).cast(dstVar)); case TYPE_UINT -> dstVar.set(srcVar.cast(long.class).and(0xffff_ffffL).cast(dstVar)); case TYPE_ULONG -> { var bd = mm.var(BigDecimal.class); toBigDecimalU(mm, srcVar, bd); dstVar.set(bd.invoke("doubleValue")); } case TYPE_BIG_INTEGER, TYPE_BIG_DECIMAL -> dstVar.set(srcVar.invoke("doubleValue")); case TYPE_UTF8 -> parseNumber(mm, "parseDouble", srcVar, dstInfo, dstVar); default -> handled = false; } break; case TYPE_CHAR: switch (srcPlainTypeCode) { case TYPE_BOOLEAN -> { Label L1 = mm.label(); srcVar.ifTrue(L1); Label cont = mm.label(); dstVar.set('f'); mm.goto_(cont); L1.here(); dstVar.set('t'); cont.here(); } case TYPE_BYTE, TYPE_SHORT -> clampSU(mm, srcVar, dstVar); case TYPE_INT, TYPE_LONG -> clampSU_narrow(mm, srcVar, 0xffff, '\uffff', dstVar); case TYPE_UBYTE -> dstVar.set(srcVar.cast(int.class).and(0xff).cast(char.class)); case TYPE_USHORT -> dstVar.set(srcVar.cast(char.class)); case TYPE_UINT -> clampUU_narrow(mm, srcVar, 0xffff, '\uffff', dstVar); case TYPE_ULONG -> clampUU_narrow(mm, srcVar, 0xffffL, '\uffff', dstVar); case TYPE_FLOAT -> clampSU_narrow(mm, srcVar.cast(int.class), 0xffff, '\uffff', dstVar); case TYPE_DOUBLE -> clampSU_narrow(mm, srcVar.cast(long.class), 0xffffL, '\uffff', dstVar); case TYPE_BIG_INTEGER -> clampBigInteger_narrow(mm, srcVar, 0, 0xffff, dstInfo, dstVar, "intValue"); case TYPE_BIG_DECIMAL -> clampBigDecimal_narrow(mm, srcVar, 0, 0xffff, dstInfo, dstVar, "intValue"); case TYPE_UTF8 -> { Label L1 = mm.label(); srcVar.invoke("isEmpty").ifFalse(L1); setDefault(mm, dstInfo, dstVar); Label cont = mm.label(); mm.goto_(cont); L1.here(); dstVar.set(srcVar.invoke("charAt", 0)); cont.here(); } default -> handled = false; } break; case TYPE_UTF8: switch (srcPlainTypeCode) { case TYPE_UBYTE -> dstVar.set(mm.var(Integer.class).invoke ("toUnsignedString", srcVar.cast(int.class).and(0xff))); case TYPE_USHORT -> dstVar.set(mm.var(Integer.class).invoke ("toUnsignedString", srcVar.cast(int.class).and(0xffff))); case TYPE_UINT, TYPE_ULONG -> dstVar.set(srcVar.invoke("toUnsignedString", srcVar)); default -> dstVar.set(mm.var(String.class).invoke("valueOf", srcVar)); } break; case TYPE_BIG_INTEGER: var bi = mm.var(BigInteger.class); switch (srcPlainTypeCode) { case TYPE_BOOLEAN -> { Label isFalse = mm.label(); srcVar.ifFalse(isFalse); dstVar.set(bi.field("ONE")); mm.goto_(end); isFalse.here(); dstVar.set(bi.field("ZERO")); } case TYPE_BYTE, TYPE_SHORT, TYPE_INT, TYPE_LONG -> dstVar.set(bi.invoke("valueOf", srcVar)); case TYPE_UBYTE -> dstVar.set(bi.invoke("valueOf", srcVar.cast(long.class).and(0xffL))); case TYPE_USHORT, TYPE_CHAR -> dstVar.set(bi.invoke("valueOf", srcVar.cast(long.class).and(0xffffL))); case TYPE_UINT -> dstVar.set(bi.invoke("valueOf", srcVar.cast(long.class).and(0xffff_ffffL))); case TYPE_ULONG -> toBigIntegerU(mm, srcVar, dstVar); case TYPE_BIG_DECIMAL -> dstVar.set(srcVar.invoke("toBigInteger")); case TYPE_FLOAT, TYPE_DOUBLE -> { Label tryStart = mm.label().here(); dstVar.set(mm.var(BigDecimal.class).invoke("valueOf", srcVar) .invoke("toBigInteger")); mm.catch_(tryStart, NumberFormatException.class, exVar -> { setDefault(mm, dstInfo, dstVar); mm.goto_(end); }); } case TYPE_UTF8 -> { var bd = parseBigDecimal(mm, srcVar, dstInfo, dstVar, end); dstVar.set(bd.invoke("toBigInteger")); } default -> handled = false; } break; case TYPE_BIG_DECIMAL: var bd = mm.var(BigDecimal.class); switch (srcPlainTypeCode) { case TYPE_BOOLEAN -> { Label isFalse = mm.label(); srcVar.ifFalse(isFalse); dstVar.set(bd.field("ONE")); mm.goto_(end); isFalse.here(); dstVar.set(bd.field("ZERO")); } case TYPE_BYTE, TYPE_SHORT, TYPE_INT, TYPE_LONG -> dstVar.set(bd.invoke("valueOf", srcVar)); case TYPE_FLOAT, TYPE_DOUBLE -> { Label tryStart = mm.label().here(); dstVar.set(mm.var(BigDecimalUtils.class).invoke("toBigDecimal", srcVar)); mm.catch_(tryStart, NumberFormatException.class, exVar -> { setDefault(mm, dstInfo, dstVar); mm.goto_(end); }); } case TYPE_UBYTE -> dstVar.set(bd.invoke("valueOf", srcVar.cast(long.class).and(0xffL))); case TYPE_USHORT, TYPE_CHAR -> dstVar.set(bd.invoke("valueOf", srcVar.cast(long.class).and(0xffffL))); case TYPE_UINT -> dstVar.set(bd.invoke("valueOf", srcVar.cast(long.class).and(0xffff_ffffL))); case TYPE_ULONG -> toBigDecimalU(mm, srcVar, dstVar); case TYPE_BIG_INTEGER -> dstVar.set(mm.new_(bd, srcVar)); case TYPE_UTF8 -> parseBigDecimal(mm, srcVar, dstInfo, dstVar, end); default -> handled = false; } break; default: handled = false; } if (!handled) { setDefault(mm, dstInfo, dstVar); } end.here(); } /** * Assigns a default value to the variable: null, 0, false, etc. */ static void setDefault(MethodMaker mm, ColumnInfo dstInfo, Variable dstVar) { if (dstInfo.isNullable()) { dstVar.set(null); } else if (dstInfo.isArray()) { dstVar.set(mm.new_(dstVar.classType(), 0)); } else { switch (dstInfo.plainTypeCode()) { case TYPE_BOOLEAN -> dstVar.set(false); case TYPE_UTF8 -> dstVar.set(""); case TYPE_BIG_INTEGER, TYPE_BIG_DECIMAL -> dstVar.set(dstVar.field("ZERO")); default -> dstVar.set(0); } } } /** * Stores 0 or 1 into a primitive numerical variable. */ private static void boolToNum(MethodMaker mm, Variable srcVar, Variable dstVar) { Label isFalse = mm.label(); srcVar.ifFalse(isFalse); dstVar.set(1); Label cont = mm.label(); mm.goto_(cont); isFalse.here(); dstVar.set(0); cont.here(); } private static void parseNumber(MethodMaker mm, String method, Variable srcVar, ColumnInfo dstInfo, Variable dstVar) { Label tryStart = mm.label().here(); dstVar.set(dstVar.invoke(method, srcVar)); mm.catch_(tryStart, NumberFormatException.class, ex -> setDefault(mm, dstInfo, dstVar)); } /** * @param srcVar short, int, or long (signed) * @param dstVar byte, short, or int (signed) */ private static void clampSS(MethodMaker mm, Variable srcVar, int min, int max, Variable dstVar) { srcVar = unbox(srcVar); Label cont = mm.label(); Label L1 = mm.label(); srcVar.ifGt(min, L1); dstVar.set(min); mm.goto_(cont); L1.here(); Label L2 = mm.label(); srcVar.ifLe(max, L2); dstVar.set(max); mm.goto_(cont); L2.here(); dstVar.set(srcVar.cast(dstVar)); cont.here(); } /** * The src and dst types must be the same size. * * @param srcVar byte, short, int, or long (unsigned) * @param dstVar byte, short, int, or long (signed) */ private static void clampUS(MethodMaker mm, Variable srcVar, long max, Variable dstVar) { srcVar = unbox(srcVar); Label cont = mm.label(); Label L1 = mm.label(); srcVar.ifGe(0, L1); dstVar.set(max); mm.goto_(cont); L1.here(); dstVar.set(srcVar.cast(dstVar)); cont.here(); } /** * The dst type is expected to be smaller than the src type. * * @param srcVar short, int, or long (unsigned) * @param dstVar byte, short, or int (signed) */ private static void clampUS_narrow(MethodMaker mm, Variable srcVar, int max, Variable dstVar) { srcVar = unbox(srcVar); Label cont = mm.label(); Label L1 = mm.label(); srcVar.and(~max).ifEq(0, L1); dstVar.set(max); mm.goto_(cont); L1.here(); dstVar.set(srcVar.cast(dstVar)); cont.here(); } /** * The dst type is expected to be smaller than the src type. * * @param srcVar short or int (unsigned) * @param dstVar byte or short (unsigned) */ private static void clampUU_narrow(MethodMaker mm, Variable srcVar, int max, Variable dstVar) { clampUU_narrow(mm, srcVar, max, -1, dstVar); } private static void clampUU_narrow(MethodMaker mm, Variable srcVar, int max, Object clampMax, Variable dstVar) { srcVar = unbox(srcVar); Label cont = mm.label(); Label L1 = mm.label(); srcVar.and(~max).ifEq(0, L1); dstVar.set(clampMax); mm.goto_(cont); L1.here(); dstVar.set(srcVar.and(max).cast(dstVar)); cont.here(); } /** * The dst type is expected to be smaller than the src type. * * @param srcVar long (unsigned) * @param dstVar byte, short, or int (unsigned) */ private static void clampUU_narrow(MethodMaker mm, Variable srcVar, long max, Variable dstVar) { clampUU_narrow(mm, srcVar, max, -1L, dstVar); } /** * The dst type is expected to be smaller than the src type. * * @param srcVar long (unsigned) * @param dstVar byte, short, or int (unsigned) */ private static void clampUU_narrow(MethodMaker mm, Variable srcVar, long max, Object clampMax, Variable dstVar) { srcVar = unbox(srcVar); Label cont = mm.label(); Label L1 = mm.label(); srcVar.and(~max).ifEq(0, L1); dstVar.set(clampMax); mm.goto_(cont); L1.here(); dstVar.set(srcVar.and(max).cast(dstVar)); cont.here(); } /** * The dst type must not be smaller than the src type. * * @param srcVar byte, short, int, or long (signed) * @param dstVar byte, short, int, or long (unsigned) */ private static void clampSU(MethodMaker mm, Variable srcVar, Variable dstVar) { srcVar = unbox(srcVar); Label cont = mm.label(); Label L1 = mm.label(); srcVar.ifGe(0, L1); dstVar.set(0); mm.goto_(cont); L1.here(); dstVar.set(srcVar.cast(dstVar)); cont.here(); } /** * The dst type is expected to be smaller than the src type. * * @param srcVar short or int (signed) * @param dstVar byte, short, or int (unsigned) */ private static void clampSU_narrow(MethodMaker mm, Variable srcVar, int max, Variable dstVar) { clampSU_narrow(mm, srcVar, max, -1, dstVar); } private static void clampSU_narrow(MethodMaker mm, Variable srcVar, int max, Object clampMax, Variable dstVar) { srcVar = unbox(srcVar); Label cont = mm.label(); Label L1 = mm.label(); srcVar.ifGt(0, L1); dstVar.set(0); mm.goto_(cont); L1.here(); Label L2 = mm.label(); srcVar.ifLe(max, L2); dstVar.set(clampMax); mm.goto_(cont); L2.here(); dstVar.set(srcVar.cast(dstVar)); cont.here(); } /** * The dst type is expected to be smaller than the src type. * * @param srcVar long (signed) * @param dstVar byte, short, or int (unsigned) */ private static void clampSU_narrow(MethodMaker mm, Variable srcVar, long max, Variable dstVar) { clampSU_narrow(mm, srcVar, max, -1L, dstVar); } private static void clampSU_narrow(MethodMaker mm, Variable srcVar, long max, Object clampMax, Variable dstVar) { srcVar = unbox(srcVar); Label cont = mm.label(); Label L1 = mm.label(); srcVar.ifGt(0, L1); dstVar.set(0); mm.goto_(cont); L1.here(); Label L2 = mm.label(); srcVar.ifLe(max, L2); dstVar.set(clampMax); mm.goto_(cont); L2.here(); dstVar.set(srcVar.cast(dstVar)); cont.here(); } /** * @param srcVar BigInteger * @param dstVar byte, short, int, char, or long (signed) */ private static void clampBigInteger_narrow(MethodMaker mm, Variable srcVar, long min, long max, ColumnInfo dstInfo, Variable dstVar, String method) { clampBig_narrow(mm, srcVar, min, BigInteger.valueOf(min), max, BigInteger.valueOf(max), dstInfo, dstVar, method); } /** * @param srcVar BigDecimal * @param dstVar byte, short, int, or long (signed) */ private static void clampBigDecimal_narrow(MethodMaker mm, Variable srcVar, long min, long max, ColumnInfo dstInfo, Variable dstVar, String method) { clampBig_narrow(mm, srcVar, min, BigDecimal.valueOf(min), max, BigDecimal.valueOf(max), dstInfo, dstVar, method); } /** * @param srcVar BigInteger * @param dstVar long (unsigned) */ private static void clampBigIntegerU_narrow(MethodMaker mm, Variable srcVar, ColumnInfo dstInfo, Variable dstVar) { clampBig_narrow(mm, srcVar, 0, BigInteger.ZERO, -1, new BigInteger(Long.toUnsignedString(-1)), dstInfo, dstVar, "longValue"); } /** * @param srcVar BigDecimal * @param dstVar long (unsigned) */ private static void clampBigDecimalU_narrow(MethodMaker mm, Variable srcVar, ColumnInfo dstInfo, Variable dstVar) { clampBig_narrow(mm, srcVar, 0, BigDecimal.ZERO, -1, new BigDecimal(Long.toUnsignedString(-1)), dstInfo, dstVar, "longValue"); } /** * @param srcVar BigInteger or BigDecimal * @param dstVar byte, short, int, char, or long (signed) */ private static void clampBig_narrow(MethodMaker mm, Variable srcVar, long min, Number minObj, long max, Number maxObj, ColumnInfo dstInfo, Variable dstVar, String method) { Label cont = mm.label(); Label L1 = mm.label(); srcVar.invoke("compareTo", mm.var(srcVar).setExact(minObj)).ifGt(0, L1); dstVar.set(min); mm.goto_(cont); L1.here(); Label L2 = mm.label(); srcVar.invoke("compareTo", mm.var(srcVar).setExact(maxObj)).ifLe(0, L2); switch (dstInfo.plainTypeCode()) { case TYPE_UBYTE, TYPE_BYTE -> dstVar.set((byte) max); case TYPE_USHORT, TYPE_SHORT -> dstVar.set((short) max); case TYPE_UINT, TYPE_INT -> dstVar.set((int) max); default -> dstVar.set(max); } mm.goto_(cont); L2.here(); var v = srcVar.invoke(method); if (dstInfo.plainTypeCode() == TYPE_CHAR) { v = v.cast(char.class); } dstVar.set(v); cont.here(); } /** * @param srcVar long (unsigned) * @param dstVar BigInteger */ private static void toBigIntegerU(MethodMaker mm, Variable srcVar, Variable dstVar) { srcVar = unbox(srcVar); var bi = mm.var(BigInteger.class); Label L1 = mm.label(); srcVar.ifLt(0L, L1); Label cont = mm.label(); dstVar.set(bi.invoke("valueOf", srcVar)); mm.goto_(cont); L1.here(); var magnitude = mm.new_(byte[].class, 8); mm.var(RowUtils.class).invoke("encodeLongBE", magnitude, 0, srcVar); dstVar.set(mm.new_(bi, 1, magnitude)); cont.here(); } /** * @param srcVar long (unsigned) * @param dstVar BigDecimal */ private static void toBigDecimalU(MethodMaker mm, Variable srcVar, Variable dstVar) { srcVar = unbox(srcVar); Label L1 = mm.label(); srcVar.ifLt(0L, L1); Label cont = mm.label(); dstVar.set(mm.var(BigDecimal.class).invoke("valueOf", srcVar)); mm.goto_(cont); L1.here(); var magnitude = mm.new_(byte[].class, 8); mm.var(RowUtils.class).invoke("encodeLongBE", magnitude, 0, srcVar); dstVar.set(mm.new_(BigDecimal.class, mm.new_(BigInteger.class, 1, magnitude))); cont.here(); } /** * If parse fails, sets a default and jumps to the end. * * @param srcVar String * @return BigDecimal variable, or null if dstInfo is BigDecimal and was set here */ private static Variable parseBigDecimal(MethodMaker mm, Variable srcVar, ColumnInfo dstInfo, Variable dstVar, Label end) { Label tryStart = mm.label().here(); var bd = mm.new_(BigDecimal.class, srcVar); if (dstInfo.type == BigDecimal.class) { dstVar.set(bd); bd = null; } mm.catch_(tryStart, NumberFormatException.class, exVar -> { setDefault(mm, dstInfo, dstVar); mm.goto_(end); }); return bd; } private static Variable unbox(Variable v) { return v.classType().isPrimitive() ? v : v.unbox(); } // Called by generated code. public static boolean charToBoolean(char c) { // Note: For numbers, boolean is treated as an int clamped to the range [0, 1]. return switch (c) { case 0, '0', 'f', 'F' -> false; case 1, '1', 't', 'T' -> true; default -> c <= 9 || ('1' < c && c <= '9'); }; } // Called by generated code. public static Boolean charToBoolean(char c, Boolean default_) { // Note: For numbers, boolean is treated as an int clamped to the range [0, 1]. switch (c) { case 0: case '0': case 'f': case 'F': return false; case 1: case '1': case 't': case 'T': return true; } if (c <= 9 || ('1' < c && c <= '9')) { return true; } return default_; } // Called by generated code. public static boolean stringToBoolean(String str) { // Note: For numbers, boolean is treated as an int clamped to the range [0, 1]. if (str.equalsIgnoreCase("false")) { return false; } if (str.equalsIgnoreCase("true")) { return true; } try { return new BigDecimal(str).compareTo(BigDecimal.ONE) >= 0; } catch (NumberFormatException e) { } return false; } // Called by generated code. public static Boolean stringToBoolean(String str, Boolean default_) { // Note: For numbers, boolean is treated as an int clamped to the range [0, 1]. if (str.equalsIgnoreCase("false")) { return false; } if (str.equalsIgnoreCase("true")) { return true; } try { return new BigDecimal(str).compareTo(BigDecimal.ONE) >= 0; } catch (NumberFormatException e) { } return default_; } // Called by generated code. public static long doubleToUnsignedLong(double d) { if (d <= 0) { return 0; // min unsigned long } long result = (long) d; if (result < Long.MAX_VALUE) { return result; } if (d >= 18446744073709551615.0) { return -1; // max unsigned long } return BigDecimal.valueOf(d).longValue(); } }
package foodtruck.server; import com.google.common.collect.ImmutableMap; import com.google.inject.Provides; import com.google.inject.assistedinject.FactoryModuleBuilder; import com.google.inject.name.Named; import com.google.inject.servlet.ServletModule; import com.sun.jersey.api.core.PackagesResourceConfig; import com.sun.jersey.guice.spi.container.servlet.GuiceContainer; import foodtruck.server.dashboard.AddressRuleServlet; import foodtruck.server.dashboard.AdminDashboardServlet; import foodtruck.server.dashboard.ApplicationDetailServlet; import foodtruck.server.dashboard.ApplicationServlet; import foodtruck.server.dashboard.BeaconServlet; import foodtruck.server.dashboard.BeaconsServlet; import foodtruck.server.dashboard.CompoundEventServlet; import foodtruck.server.dashboard.LocationEditServlet; import foodtruck.server.dashboard.LocationListServlet; import foodtruck.server.dashboard.MessageEditServlet; import foodtruck.server.dashboard.MessageListServlet; import foodtruck.server.dashboard.NotificationServlet; import foodtruck.server.dashboard.ObserverServlet; import foodtruck.server.dashboard.StatsServlet; import foodtruck.server.dashboard.SyncServlet; import foodtruck.server.dashboard.TestNotificationServlet; import foodtruck.server.dashboard.TruckListServlet; import foodtruck.server.dashboard.TruckServlet; import foodtruck.server.dashboard.TruckStopServlet; import foodtruck.server.job.ErrorCountServlet; import foodtruck.server.job.InvalidateScheduleCache; import foodtruck.server.job.ProfileSyncServlet; import foodtruck.server.job.PurgeStatsServlet; import foodtruck.server.job.PushNotificationServlet; import foodtruck.server.job.RecacheServlet; import foodtruck.server.job.SendLunchNotificationsServlet; import foodtruck.server.job.TruckMonitorServlet; import foodtruck.server.job.TweetCacheUpdateServlet; import foodtruck.server.job.TwitterCachePurgeServlet; import foodtruck.server.job.UpdateLocationStats; import foodtruck.server.job.UpdateTruckStats; import foodtruck.server.resources.DailySpecialResourceFactory; import foodtruck.server.vendor.LocationEditVendorServlet; import foodtruck.server.vendor.LocationStopDeleteServlet; import foodtruck.server.vendor.LocationVendorServlet; import foodtruck.server.vendor.MenuServlet; import foodtruck.server.vendor.VendorCallbackServlet; import foodtruck.server.vendor.VendorLogoutServlet; import foodtruck.server.vendor.VendorOffTheRoadServlet; import foodtruck.server.vendor.VendorRecacheServlet; import foodtruck.server.vendor.VendorServlet; import foodtruck.server.vendor.VendorSettingsServlet; import foodtruck.server.vendor.VendorTwitterRedirectServlet; /** * Wires all the endpoints for the application. * @author aviolette * @since Jul 12, 2011 */ class FoodtruckServletModule extends ServletModule { @Override protected void configureServlets() { // Offline endpoints called via cron-jobs serve("/cron/push_notifications").with(PushNotificationServlet.class); serve("/cron/recache").with(RecacheServlet.class); serve("/cron/tweets").with(TweetCacheUpdateServlet.class); serve("/cron/tweetPurge").with(TwitterCachePurgeServlet.class); serve("/cron/statPurge").with(PurgeStatsServlet.class); serve("/cron/notifications").with(SendLunchNotificationsServlet.class); serve("/cron/updateTruckStats").with(UpdateTruckStats.class); serve("/cron/updateLocationStats").with(UpdateLocationStats.class); serve("/cron/error_stats").with(ErrorCountServlet.class); serve("/cron/activate_beacon").with(TruckMonitorServlet.class); // Dashboard endpoints serve("/admin").with(AdminDashboardServlet.class); serve("/admin/addresses").with(AddressRuleServlet.class); serveRegex("/admin/beacons/[\\w]+").with(BeaconServlet.class); serve("/admin/beacons").with(BeaconsServlet.class); serveRegex("/admin/trucks/[\\S]*/stops/[\\w]*").with(TruckStopServlet.class); serveRegex("/admin/trucks/[\\S]*/menu").with(foodtruck.server.dashboard.MenuServlet.class); serve("/admin/event_at/*").with(CompoundEventServlet.class); serve("/admin/profileSync").with(ProfileSyncServlet.class); serve("/admin/invalidateCache").with(InvalidateScheduleCache.class); // Vendor dashboard endpoints serve("/vendor").with(VendorServlet.class); serveRegex("/vendor/locations/[\\d]*/stops/[\\w]*/delete").with(LocationStopDeleteServlet.class); serveRegex("/vendor/locations/[\\d]*/stops/[\\w]*").with(LocationEditVendorServlet.class);
package org.epics.util.text; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.AbstractList; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.epics.util.array.ArrayDouble; import org.epics.util.array.ListDouble; import static org.epics.util.text.StringUtil.DOUBLE_REGEX_WITH_NAN; public class CsvParser { // Configuration private final String separators; private final Header header; /** * The configuration options for the header. */ public enum Header { /** * Auto detects whether the first line is a header. * <p> * The first line is interpreted as data only if it can be safely * distinguished. If all columns contain strings, then the first * line is always interpreted as a header. If the types in the * first line do not match the column (e.g. first line string, rest are * numbers) then it is interpreted as header. If the types match, * and one of them is not a string (e.g. number) then the first * line is interpreted as data. */ AUTO, /** * The first line is the header. */ FIRST_LINE, /** * The data contains no header, and the first line is data. * <p> * A header is automatically generated with the convention given by * spreadsheets columns: A, B, ..., Y, Z, AA, AB, ..., AZ, BA, and so on. */ NONE}; private class State { // Parser state private int nColumns; private boolean columnMismatch = false; private List<String> columnNames; private List<Boolean> columnNumberParsable; private List<Boolean> columnTimestampParsable; private List<List<String>> columnTokens; // Regex object used for parsing private Matcher mLineTokens; private final Matcher mQuote = pQuote.matcher(""); private final Matcher mDouble = pDouble.matcher(""); } private static final Pattern pQuote = Pattern.compile("\"\""); private static final Pattern pDouble = Pattern.compile(DOUBLE_REGEX_WITH_NAN); /** * Automatic parser: auto-detects whether the first line is a header or not * and tries the most common separators (i.e. ',' ';' 'TAB' 'SPACE'). */ public static final CsvParser AUTOMATIC = new CsvParser(",;\t ", Header.AUTO); private CsvParser(String separators, Header header) { this.separators = separators; this.header = header; } /** * Returns the list of separators that are going to be tried while parsing. * * @return a string with all the possible separators */ public String getSeparators() { return separators; } /** * Creates a new parser that uses the given separators. * <p> * Each character of the string is tried until the parsing is * successful. * * @param separators the new list of separators * @return a new parser */ public CsvParser withSeparators(String separators) { return new CsvParser(separators, header); } /** * Returns the way that the parser handles the header (the first line of * the csv file). * * @return the header configuration of the parser */ public Header getHeader() { return header; } /** * Creates a new parser with the given header handling. * * @param header the header configuration for the parser * @return a new parser */ public CsvParser withHeader(Header header) { return new CsvParser(separators, header); } /** * Parser the text provided by the reader with the format defined in this * parser. This method is thread-safe. * <p> * If the parsing fails, this method does not throw an exception but * will have information in the result. The idea is that, in the future, * the parser can provide multiple reasons as why the parsing failed or * event incomplete results. * * @param reader a reader * @return the parsed information */ public CsvParserResult parse(Reader reader) { // State used for parsing. Since each call has its own state, // the parsing is thread safe. State state = new State(); // Divide into lines. // Note that means we are going to keep in memory the whole file. // This is not very memory efficient. But since we have to do multiple // passes to find the right separator, we don't have much choice. // Also: the actual parsed result will need to stay in memory anyway. List<String> lines = csvLines(reader); // Try each seaparater separatorLoop: for(int nSeparator = 0; nSeparator < getSeparators().length(); nSeparator++) { String currentSeparator = getSeparators().substring(nSeparator, nSeparator+1); // Taken from Mastering Regular Exceptions // Disabled comments so that space could work as possible separator String regex = // puts a doublequoted field in group(1) and an unquoted field into group(2) // Start with beginning of line or separator "\\G(?:^|" + currentSeparator + ")" + // Match a quoted string "(?:" + "\"" + "((?:[^\"]++|\"\")*+)" + "\"" + // Or match a string without the separator "|" + "([^\"" + currentSeparator + "]*)" + ")"; // Compile the matcher once for all the parsing state.mLineTokens = Pattern.compile(regex).matcher(""); // Try to parse the first line (the titles) // If only one columns is found, proceed to next separator state.columnNames = parseTitles(state, lines.get(0)); state.nColumns = state.columnNames.size(); if (state.nColumns == 1) { continue; } // Prepare the data structures to hold column data while parsing state.columnMismatch = false; state.columnNumberParsable = new ArrayList<>(state.nColumns); state.columnTimestampParsable = new ArrayList<>(state.nColumns); state.columnTokens = new ArrayList<>(); for (int i = 0; i < state.nColumns; i++) { state.columnNumberParsable.add(true); state.columnTimestampParsable.add(false); state.columnTokens.add(new ArrayList<String>()); } // Parse each line // If one line does not match the number of columns found in the first // line, pass to the next separator for (int i = 1; i < lines.size(); i++) { parseLine(state, lines.get(i)); if (state.columnMismatch) { continue separatorLoop; } } // The parsing succeeded! No need to try other separator break; } // We are out of the loop: did we end because we parsed correctly, // or because even the last separator was a mismatch? if (state.columnMismatch) { return new CsvParserResult(null, null, null, 0, false, "Number of columns is not the same for all lines"); } // Parsing was successful. // Should the first line be used as data? if (header == Header.NONE || (header == Header.AUTO && isFirstLineData(state, state.columnNames))) { for (int i = 0; i < state.nColumns; i++) { state.columnTokens.set(i, joinList(state.columnNames.get(i), state.columnTokens.get(i))); state.columnNames.set(i, alphabeticName(i)); } } // Now it's time to convert the tokens to the actual type. List<Object> columnValues = new ArrayList<>(state.nColumns); List<Class<?>> columnTypes = new ArrayList<>(state.nColumns); for (int i = 0; i < state.nColumns; i++) { if (state.columnNumberParsable.get(i)) { columnValues.add(convertToListDouble(state.columnTokens.get(i))); columnTypes.add(double.class); } else { columnValues.add(state.columnTokens.get(i)); columnTypes.add(String.class); } } // Prepare result, and remember to clear the state, so // we don't keep references to junk CsvParserResult result = new CsvParserResult(state.columnNames, columnValues, columnTypes, state.columnTokens.get(0).size(), true, null); return result; } /** * Given a list of tokens, convert them to a list of numbers. * * @param tokens the tokens to be converted * @return the number list */ private ListDouble convertToListDouble(List<String> tokens) { double[] values = new double[tokens.size()]; for (int i = 0; i < values.length; i++) { values[i] = Double.parseDouble(tokens.get(i)); } return new ArrayDouble(values); } /** * Divides the whole text into lines. * * @param reader the source of text * @return the lines */ static List<String> csvLines(Reader reader) { // This needs to handle quoted text that spans multiple lines, // so we divide the full text into chunks that correspond to // a single csv line try { BufferedReader br = new BufferedReader(reader); List<String> lines = new ArrayList<>(); // The current line read from the Reader String line; // The full csv line that may span multiple lines String longLine = null; while ((line = br.readLine()) != null) { // If we have a line from the previous iteration, // we concatenate it if (longLine == null) { longLine = line; } else { longLine = longLine.concat("\n").concat(line); } // Count the number of quotes: if it's even, the csv line // must end here. If not, it will continue to the next if (isEvenQuotes(longLine)) { lines.add(longLine); longLine = null; } } // If there is text leftover, the line was not closed propertly. // XXX: we need to figure out how to handle errors like this if (longLine != null) { lines.add(longLine); } return lines; } catch(IOException ex) { throw new RuntimeException("Couldn't process data", ex); } } /** * Determines whether the string contains an even number of double quote * characters. * * @param string the given string * @return true if contains even number of '"' */ static boolean isEvenQuotes(String string) { // In principle, we could use the regex given by: // Pattern pEvenQuotes = Pattern.compile("([^\"]*\\\"[^\"]*\\\")*[^\"]*"); // We assume just counting the instances of double quotes is more efficient // but we haven't really tested that assumption. boolean even = true; for (int i = 0; i < string.length(); i++) { if (string.charAt(i) == '\"') { even = !even; } } return even; } /** * Parses the first line to get the column names. * * @param line the text line * @return the column names */ private List<String> parseTitles(State state, String line) { // Match using the parser List<String> titles = new ArrayList<>(); state.mLineTokens.reset(line); while (state.mLineTokens.find()) { String value; if (state.mLineTokens.start(2) >= 0) { value = state.mLineTokens.group(2); } else { // If quoted, always use string value = state.mQuote.reset(state.mLineTokens.group(1)).replaceAll("\""); } titles.add(value); } return titles; } /** * Parses a line, saving the tokens, and determines the type match. * * @param line a new line */ private void parseLine(State state, String line) { // Match using the parser state.mLineTokens.reset(line); int nColumn = 0; while (state.mLineTokens.find()) { // Does this line have more columns than expected? if (nColumn == state.nColumns) { state.columnMismatch = true; return; } String token; if (state.mLineTokens.start(2) >= 0) { // The token was unquoted. Check if it could be a number. token = state.mLineTokens.group(2); if (!isTokenNumberParsable(state, token)) { state.columnNumberParsable.set(nColumn, false); } } else { // If quoted, always use string token = state.mQuote.reset(state.mLineTokens.group(1)).replaceAll("\""); state.columnNumberParsable.set(nColumn, false); } state.columnTokens.get(nColumn).add(token); nColumn++; } // Does this line have fewer columns than expected? if (nColumn != state.nColumns) { state.columnMismatch = true; } } /** * Check whether the token can be parsed to a number. * * @param state the state of the parser * @param token the token * @return true if token matches a double */ private boolean isTokenNumberParsable(State state, String token) { return state.mDouble.reset(token).matches(); } /** * Checks whether the header can be safely interpreted as data. * This is used for the auto header detection. * * @param state the state of the parser * @param headerTokens the header * @return true if header should be handled as data */ private boolean isFirstLineData(State state, List<String> headerTokens) { // Check whether the type of the header match the type of the following data boolean headerCompatible = true; // Check whether if all types where strings boolean allStrings = true; for (int i = 0; i < state.nColumns; i++) { if (state.columnNumberParsable.get(i)) { allStrings = false; if (!isTokenNumberParsable(state, headerTokens.get(i))) { headerCompatible = false; } } } // If all columns are strings, it's impossible to tell whether we have // a header or not: assume we have a header. // If the column types matches (e.g. the header for a number column is also // a number) then we'll assume the header is actually data. return !allStrings && headerCompatible; } /** * Takes an elements and a list and returns a new list with both. * * @param head the first element * @param tail the rest of the elements * @return a list with all elements */ private List<String> joinList(final String head, final List<String> tail) { return new AbstractList<String>() { @Override public String get(int index) { if (index == 0) { return head; } else { return tail.get(index - 1); } } @Override public int size() { return tail.size()+1; } }; } static String alphabeticName(int i) { String name = ""; while (true) { int offset = i % 26; i = i / 26; char character = (char) ('A' + offset); name = name + character; if (i == 0) { return name; } } } /** * Parses a line of text representing comma separated values and returns * the values themselves. * * @param line the line to parse * @param separatorChar the regular expression for the separator * @return the list of values */ public static List<Object> parseCSVLine(String line, String separatorChar) { String regex = // puts a doublequoted field in group(1) and an unquoted field into group(2) "\\G(?:^|" + separatorChar + ")" + "(?:" + "\"" + "((?:[^\"]++|\"\")*+)" + "\"" + "|" + "([^\"" + separatorChar + "]*)" + ")"; Matcher mMain = Pattern.compile(regex).matcher(""); Matcher mQuote = Pattern.compile("\"\"").matcher(""); Matcher mDouble = Pattern.compile(DOUBLE_REGEX_WITH_NAN).matcher(""); List<Object> values = new ArrayList<>(); mMain.reset(line); while (mMain.find()) { Object value; if (mMain.start(2) >= 0) { String field = mMain.group(2); if (mDouble.reset(field).matches()) { value = Double.parseDouble(field); } else { value = field; } } else { // If quoted, always use string value = mQuote.reset(mMain.group(1)).replaceAll("\""); } values.add(value); } return values; } }
package fr.kisuke.rest.resources; import java.io.*; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import com.sun.jersey.multipart.FormDataParam; import fr.kisuke.dao.picture.PictureDao; import fr.kisuke.dao.user.UserDao; import fr.kisuke.entity.Pictures; import org.apache.commons.io.IOUtils; import org.codehaus.jackson.map.ObjectMapper; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; import org.apache.commons.io.FilenameUtils; //@Produces({"application/xml"}) @Component //@Scope("request") @Path("/upload") //@Controller //@RequestMapping("") public class UploadResource { private final String UPLOADED_FILE_PATH = "/srv/appli/images/"; // private final String UPLOADED_FILE_PATH = "c:/temp/"; private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private PictureDao pictureDao; @Autowired private UserDao userDao; @Autowired private ObjectMapper mapper; @POST @Path("/file") @Consumes("multipart/form-data") @Produces("text/plain") public Response uploadFile( @FormDataParam("content") final InputStream uploadedInputStream, @FormDataParam("fileName") String fileName) throws IOException { //String uploadContent=IOUtils.toString(uploadedInputStream); this.logger.info("create an upload picture(): " + fileName); //convert the uploaded file to inputstream byte [] bytes = IOUtils.toByteArray(uploadedInputStream); //constructs upload file path fileName = UPLOADED_FILE_PATH + fileName; // return Response.ok(uploadContent).build(); writeFile(bytes,fileName); return Response.ok().build(); } /** * header sample * { * Content-Type=[image/png], * Content-Disposition=[form-data; name="file"; filename="filename.extension"] * } **/ //get uploaded filename, is there a easy way in RESTEasy? private String getFileName(MultivaluedMap<String, String> header) { String[] contentDisposition = header.getFirst("Content-Disposition").split(";"); for (String filename : contentDisposition) { if ((filename.trim().startsWith("filename"))) { String[] name = filename.split("="); String finalFileName = name[1].trim().replaceAll("\"", ""); return finalFileName; } } return "unknown"; } //save to somewhere private void writeFile(byte[] content, String filename) throws IOException { UserDetails userdetails = isAdmin(); DateTime now = new DateTime(); String path = FilenameUtils.getFullPath(filename); String basename = FilenameUtils.getBaseName(filename)+now.getMillis(); String extension = FilenameUtils.getExtension(filename); String nameNorm = basename+"."+extension; String nameMed = basename+"-Med."+extension; String nameLow = basename+"-Low."+extension; String filenameNorm = path + nameNorm; String filenameMed = path + nameMed; String filenameLow = path + nameLow; Pictures picture = new Pictures(); //picture.setCreationDate(now); File file = new File(filenameNorm); if (!file.exists()) { file.createNewFile(); } File fileMed = new File(filenameMed); if (!fileMed.exists()) { fileMed.createNewFile(); } File fileLow = new File(filenameLow); if (!fileLow.exists()) { fileLow.createNewFile(); } recordFileOnDisk(content, file); recordFileOnDisk(content, fileMed); recordFileOnDisk(content, fileLow); picture.setName(FilenameUtils.getName(filename)); picture.setNameHight(nameNorm); picture.setNameMed(nameMed); picture.setNameLow(nameLow); picture.setPath(path); picture.setUser(userDao.findByName(userdetails.getUsername())); this.pictureDao.save(picture); } private void recordFileOnDisk(byte[] content, File file) throws IOException { FileOutputStream fop = new FileOutputStream(file); fop.write(content); fop.flush(); fop.close(); } private UserDetails isAdmin() { //UserDetails userDetails = null; Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Object principal = authentication.getPrincipal(); if (principal instanceof String && ((String) principal).equals("anonymousUser")) { return null; }else { return (UserDetails) principal; } } }
package org.experiment.TREC; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.Properties; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.benchmark.byTask.feeds.*; import org.apache.lucene.benchmark.byTask.utils.Config; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; public class IndexTREC { private IndexTREC() {} public static void main(String[] args) { String message = "nohup mvn compile && nohup mvn -DargLine=\"-Xmx1524m\" -e exec:java " + "-Dexec.mainClass=\"org.experiment.TREC.IndexTREC\" " + "-Dexec.args=\"index /home/datasets/TREC/WT2G/dataset\" &> trecIndex.log"; String indexPath, docsPath; if (args.length == 2 ) { indexPath = args[0]; docsPath = args[1]; } else { indexPath = "index"; docsPath = "/media/sonic/Windows/TREC/WT2G/dataset";// /home/datasets/TREC/WT2G/dataset } boolean create = true; for(int i=0;i<args.length;i++) { if ("-index".equals(args[i])) { indexPath = args[i+1]; i++; } else if ("-docs".equals(args[i])) { docsPath = args[i+1]; i++; } else if ("-update".equals(args[i])) { create = false; } } final File docDir = new File(docsPath); if (!docDir.exists() || !docDir.canRead()) { System.out.println("Document directory '" +docDir.getAbsolutePath()+ "' does not exist or is not readable, please check the path"); System.exit(1); } Date start = new Date(); try { System.out.println("Indexing to directory '" + indexPath + "'..."); Directory dir = FSDirectory.open(Paths.get(indexPath)); Analyzer analyzer = new StandardAnalyzer(); // add analyzers... IndexWriterConfig iwc = new IndexWriterConfig(analyzer); if (create) { // Create a new index in the directory, removing any // previously indexed documents: iwc.setOpenMode(OpenMode.CREATE); } else { // Add new documents to an existing index: iwc.setOpenMode(OpenMode.CREATE_OR_APPEND); } // Optional: for better indexing performance, if you // are indexing many documents, increase the RAM // buffer. But if you do this, increase the max heap // size to the JVM (eg add -Xmx512m or -Xmx1g): iwc.setRAMBufferSizeMB(1024.0); IndexWriter writer = new IndexWriter(dir, iwc); indexDocs(writer, docDir); // NOTE: if you want to maximize search performance, // you can optionally call forceMerge here. This can be // a terribly costly operation, so generally it's only // worth it when your index is relatively static (ie // you're done adding documents to it): // writer.forceMerge(1); System.out.println("numDocs: " + writer.numDocs() + " maxDoc: " + writer.maxDoc()); writer.close(); Date end = new Date(); System.out.println(end.getTime() - start.getTime() + " total milliseconds"); } catch (IOException e) { System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage()); } } /** * Indexes the given file using the given writer, or if a directory is given, * recurses over files and directories found under the given directory. * * NOTE: This method indexes one document per input file. This is slow. For good * throughput, put multiple documents into your input file(s). An example of this is * in the benchmark module, which can create "line doc" files, one document per line, * using the * <a href="../../../../../contrib-benchmark/org/apache/lucene/benchmark/byTask/tasks/WriteLineDocTask.html" * >WriteLineDocTask</a>. * * @param writer Writer to the index where the given file/dir info will be stored * @param file The file to index, or the directory to recurse into to find files to index * @throws IOException If there is a low-level I/O error */ static void indexDocs(IndexWriter writer, File file) throws IOException { int counter = 0; // do not try to index files that cannot be read if (file.canRead()) { if (file.isDirectory()) { String[] files = file.list(); // an IO error could occur if (files != null) { for (int i = 0; i < files.length; i++) { indexDocs(writer, new File(file, files[i])); } } } else { TrecDocIterator docs = new TrecDocIterator(file); Document doc; while (docs.hasNext()) { doc = docs.next(); if (doc != null && doc.getField("contents") != null) { writer.addDocument(doc); counter++; } } } } System.out.println("Number of document: " + counter); } }
package hudson.plugins.sap; import hudson.EnvVars; import hudson.Launcher; import hudson.Extension; import hudson.model.BuildListener; import hudson.model.AbstractBuild; import hudson.plugins.sap.utils.NeoCommandLine; import hudson.tasks.Builder; import hudson.tasks.BuildStepDescriptor; import hudson.util.FormValidation; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.DataBoundConstructor; import net.sf.json.JSONObject; import java.io.File; import java.io.IOException; public class HcpDeploymentBuilder extends Builder { private final String host; private final String account; private final String user; private final String password; private final String appname; private final String packageLocation; @DataBoundConstructor public HcpDeploymentBuilder(String host, String account, String user, String password, String appname, String packageLocation) { this.host = host; this.account = account; this.user = user; this.password = password; this.appname = appname; this.packageLocation = packageLocation; } public String getHost() { return host; } public String getAccount() { return account; } public String getUser() { return user; } public String getPassword() { return password; } public String getAppname() { return appname; } public String getPackageLocation(){ return packageLocation; } private String getCurrentJobName(AbstractBuild build, BuildListener listener) { try { EnvVars envVars; envVars = (EnvVars) build.getEnvironment(listener); return envVars.get("JOB_NAME"); } catch (IOException e) { listener.getLogger().println(e.getMessage()); } catch (InterruptedException e) { listener.getLogger().println(e.getMessage()); } return null; } private String defaultWarExtractor(AbstractBuild build, BuildListener listener) { return System.getProperty("user.dir") + File.separator + "jobs" + File.separator + getCurrentJobName(build, listener) + File.separator + "workspace"; } @Override public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) { listener.getLogger().println("deploying application to SAP Hana Cloud Platform"); listener.getLogger().println("displaying parameters:"); listener.getLogger().println("hostname : " + host); listener.getLogger().println("accountname : " + account); listener.getLogger().println("username : " + user); listener.getLogger().println("application name : " + appname); listener.getLogger().println("war/jar location : " + packageLocation); listener.getLogger().println("NEO SDK root directory : " + getDescriptor().neoSdkHome()); NeoCommandLine commandLine = new NeoCommandLine(); commandLine.setHost(host); commandLine.setAccount(account); commandLine.setUser(user); commandLine.setPassword(password); commandLine.setAppName(appname); if (packageLocation != null && !packageLocation.equals("")) commandLine.setSourceLocation(packageLocation); else { listener.getLogger().println("war/jar location is null or empty. So using default location."); commandLine.setSourceLocation(defaultWarExtractor(build, listener)); } if (getDescriptor().neoSdkHome() != null && !getDescriptor().neoSdkHome().equals("")) commandLine.setNeosdk(getDescriptor().neoSdkHome()); else { listener.getLogger().println("Set NEO_SDK_HOME location correctly"); return false; } commandLine.deployApplication(listener.getLogger()); return true; } @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl)super.getDescriptor(); } @Extension public static final class DescriptorImpl extends BuildStepDescriptor<Builder> { private String neo_sdk_home; public DescriptorImpl() { load(); } public FormValidation doValidateInput(@QueryParameter("host") final String host, @QueryParameter("account") final String account, @QueryParameter("user") final String user, @QueryParameter("password") final String password, @QueryParameter("appname") final String appname, @QueryParameter("packageLocation") final String packageLocation) { if (host == null || host.equals("")) return FormValidation.error("hostname is null or empty"); if (account == null || account.equals("")) return FormValidation.error("accountname is null or empty"); if (user == null || user.equals("")) return FormValidation.error("username is null or empty"); if (password == null || password.equals("")) return FormValidation.error("password is null or empty"); if (appname == null || appname.equals("")) return FormValidation.error("application name is null or empty"); return FormValidation.ok(); } @Override public String getDisplayName() { return "SAP Hana Cloud Platform credentials & application details"; } @Override public boolean isApplicable(Class type) { return true; } @Override public boolean configure(StaplerRequest staplerRequest, JSONObject json) throws FormException { neo_sdk_home = json.getString("NEO_SDK_HOME"); save(); return true; } public String neoSdkHome() { return neo_sdk_home; } } }
package com.github.davidcarboni.thetrain.helpers; import com.github.davidcarboni.cryptolite.Random; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; /** * Tests for {@link UnionInputStream}. */ public class UnionInputStreamTest { @Test public void shouldReadBytesBuffered() throws IOException { // Given // Two streams for some data byte[] data = Random.bytes(1024); ByteArrayInputStream a = new ByteArrayInputStream(data, 0, 512); ByteArrayInputStream b = new ByteArrayInputStream(data, 512, 1024); UnionInputStream input = new UnionInputStream(a, b); // When // We union the streams (buffered read) ByteArrayOutputStream output = new ByteArrayOutputStream(); int r; byte[] buffer = new byte[10]; while ((r = input.read(buffer, 0, 10)) > 0) { output.write(buffer, 0, r); } // Then // We should get the expected data Assert.assertArrayEquals(data, output.toByteArray()); } @Test public void shouldReadBytesUnbuffered() throws IOException { // Given // Two streams for some data byte[] data = Random.bytes(1024); ByteArrayInputStream a = new ByteArrayInputStream(data, 0, 512); ByteArrayInputStream b = new ByteArrayInputStream(data, 512, 1024); UnionInputStream input = new UnionInputStream(a, b); // When // We union the streams (unbuffered read) ByteArrayOutputStream output = new ByteArrayOutputStream(); int r; while ((r = input.read()) != -1) { output.write(r); } // Then // We should get the expected data Assert.assertArrayEquals(data, output.toByteArray()); } @Test public void shouldClose() throws Exception { // Given // Two mock input streams InputStream a = Mockito.mock(InputStream.class); InputStream b = Mockito.mock(InputStream.class); UnionInputStream input = new UnionInputStream(a, b); // When // We close the stream input.close(); // Then // The underlying streams should be closed Mockito.verify(a).close(); Mockito.verify(b).close(); } }
package in.ac.amu.zhcet.service; import com.google.cloud.storage.Acl; import com.google.cloud.storage.BlobInfo; import com.google.cloud.storage.Bucket; import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; import com.google.firebase.auth.FirebaseCredentials; import com.google.firebase.cloud.StorageClient; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.io.*; import java.net.URL; import java.net.URLEncoder; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.UUID; @Slf4j @Service public class FirebaseService { public FirebaseService() throws IOException { log.info("Initializing Firebase"); InputStream serviceAccount = getServiceAccountJson(); FirebaseOptions options = new FirebaseOptions.Builder() .setCredential(FirebaseCredentials.fromCertificate(serviceAccount)) .setDatabaseUrl("https://zhcet-web-amu.firebaseio.com/") .setStorageBucket("zhcet-web-amu.appspot.com") .build(); try { FirebaseApp.initializeApp(options); log.info("Firebase Initialized"); } catch (RuntimeException i) { log.info("Firebase already Initialized"); } } private InputStream getServiceAccountJson() { String fileName = "service-account.json"; try { InputStream is = getClass().getResourceAsStream("/" + fileName); if (is == null) { log.info("service-account.json not found in class resources. Maybe debug build? Trying to load another way"); URL url = getClass().getClassLoader().getResource(fileName); if (url == null) { log.info(fileName + " not found in class loader resource as well... Using last resort..."); throw new FileNotFoundException(); } is = new FileInputStream(url.getFile()); } return is; } catch (FileNotFoundException e) { log.info("service-account.json not found in file system... Attempting to load from environment..."); return new ByteArrayInputStream(System.getenv("FIREBASE_JSON").getBytes()); } } private Bucket getBucket() { return StorageClient.getInstance().bucket(); } public String uploadFile(String path, String contentType, InputStream fileStream) throws UnsupportedEncodingException { log.info(String.format("Uploading file '%s' of type %s...", path, contentType)); Bucket bucket = getBucket(); log.info("Bucket used : " + bucket.getName()); String uuid = UUID.randomUUID().toString(); log.info("Firebase Download Token : " + uuid); Map<String, String> map = new HashMap<>(); map.put("firebaseStorageDownloadTokens", uuid); BlobInfo uploadContent = BlobInfo.newBuilder(getBucket().getName(), path) .setContentType(contentType) .setMetadata(map) .setAcl(Collections.singletonList(Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER))) .build(); BlobInfo uploaded = bucket.getStorage().create(uploadContent, fileStream); log.info("File Uploaded"); log.info("Media Link : " + uploaded.getMediaLink()); log.info("Metadata : " + uploaded.getMetadata().toString()); String link = String.format("https://firebasestorage.googleapis.com/v0/b/%s/o/%s?alt=media&token=%s", uploaded.getBucket(), URLEncoder.encode(uploaded.getName(), "UTF-8"), uuid); log.info("Firebase Link : " + link); return link; } }
package com.google.cloud.genomics.dataflow.pipelines; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.util.GcsUtil; import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; import com.google.cloud.genomics.dataflow.utils.GenomicsOptions; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.io.BufferedReader; import java.io.IOException; import java.io.Writer; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; /** * This test expects you to have: * -a Google Cloud API key in the GOOGLE_API_KEY environment variable, * -a GCS folder path in TEST_OUTPUT_GCS_FOLDER to store temporary test outputs, * -a GCS folder path in TEST_STAGING_GCS_FOLDER to store temporary files, * GCS folder paths should be of the form "gs://bucket/folder/" * * This test will read and write to GCS. */ @RunWith(JUnit4.class) public class CountReadsITCase { final String API_KEY = System.getenv("GOOGLE_API_KEY"); final String TEST_OUTPUT_GCS_FOLDER = System.getenv("TEST_OUTPUT_GCS_FOLDER"); final String TEST_STAGING_GCS_FOLDER = System.getenv("TEST_STAGING_GCS_FOLDER"); // this file shouldn't move. final String TEST_BAM_FNAME = "gs://genomics-public-data/ftp-trace.ncbi.nih.gov/1000genomes/ftp/pilot_data/data/NA06985/alignment/NA06985.454.MOSAIK.SRP000033.2009_11.bam"; @Before public void voidEnsureEnvVar() { Assert.assertNotNull("You must set the GOOGLE_API_KEY environment variable for this test.", API_KEY); Assert.assertNotNull("You must set the TEST_OUTPUT_GCS_FOLDER environment variable for this test.", TEST_OUTPUT_GCS_FOLDER); Assert.assertTrue("TEST_OUTPUT_GCS_FOLDER must end with '/'", TEST_OUTPUT_GCS_FOLDER.endsWith("/")); Assert.assertTrue("TEST_OUTPUT_GCS_FOLDER must start with 'gs://'", TEST_OUTPUT_GCS_FOLDER.startsWith("gs://")); Assert.assertNotNull("You must set the TEST_STAGING_GCS_FOLDER environment variable for this test.", TEST_STAGING_GCS_FOLDER); Assert.assertTrue("TEST_STAGING_GCS_FOLDER must start with 'gs://'", TEST_STAGING_GCS_FOLDER.startsWith("gs://")); // we don't care how TEST_STAGING_GCS_FOLDER ends, so no check for it. } /** * CountReads running on the client's machine. */ @Test public void testLocal() throws Exception { final String OUTPUT = TEST_OUTPUT_GCS_FOLDER + "CountReadsITCase-testLocal-output.txt"; String[] ARGS = { "--apiKey=" + API_KEY, "--project=genomics-pipelines", "--output=" + OUTPUT, "--references=1:550000:560000", "--BAMFilePath=" + TEST_BAM_FNAME }; final long EXPECTED = 685; GenomicsOptions popts = PipelineOptionsFactory.create().as(GenomicsOptions.class); popts.setApiKey(API_KEY); GcsUtil gcsUtil = new GcsUtil.GcsUtilFactory().create(popts); touchOutput(gcsUtil, OUTPUT); CountReads.main(ARGS); BufferedReader reader = new BufferedReader(Channels.newReader(gcsUtil.open(GcsPath.fromUri(OUTPUT)), "UTF-8")); long got = Long.parseLong(reader.readLine()); Assert.assertEquals(EXPECTED, got); } /** * CountReads running on Dataflow. */ @Test public void testCloud() throws Exception { final String OUTPUT = TEST_OUTPUT_GCS_FOLDER + "CountReadsITCase-testCloud-output.txt"; String[] ARGS = { "--apiKey="+API_KEY, "--project=genomics-pipelines", "--output=" + OUTPUT, "--numWorkers=2", "--runner=BlockingDataflowPipelineRunner", "--stagingLocation=" + TEST_STAGING_GCS_FOLDER, "--references=1:550000:560000", "--BAMFilePath=" + TEST_BAM_FNAME }; final long EXPECTED = 685; GenomicsOptions popts = PipelineOptionsFactory.create().as(GenomicsOptions.class); popts.setApiKey(API_KEY); GcsUtil gcsUtil = new GcsUtil.GcsUtilFactory().create(popts); touchOutput(gcsUtil, OUTPUT); CountReads.main(ARGS); BufferedReader reader = new BufferedReader(Channels.newReader(gcsUtil.open(GcsPath.fromUri(OUTPUT)), "UTF-8")); long got = Long.parseLong(reader.readLine()); Assert.assertEquals(EXPECTED, got); } /** * make sure we can get to the output, and at the same time avoid a false negative if * the program does nothing and we find the output from an earlier run. */ private void touchOutput(GcsUtil gcsUtil, String outputGcsPath) throws IOException { try (Writer writer = Channels.newWriter(gcsUtil.create(GcsPath.fromUri(outputGcsPath), "text/plain"), "UTF-8")) { writer.write("output will go here"); } } }
package org.graylog2.log; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.Level; import org.apache.log4j.MDC; import org.apache.log4j.spi.ErrorCode; import org.apache.log4j.spi.LocationInfo; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.ThrowableInformation; import org.graylog2.GelfMessage; import org.graylog2.GelfSender; import org.json.simple.JSONValue; import java.io.PrintWriter; import java.io.StringWriter; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Map; /** * anton @ 11.30.1 17:28 */ public class GelfAppender extends AppenderSkeleton { private String graylogHost; private String originHost; private int graylogPort = 12201; private String facility; private GelfSender gelfSender; private boolean extractStacktrace; private boolean useDiagnosticContext; private Map<String, String> fields; private static final int MAX_SHORT_MESSAGE_LENGTH = 250; private static final String ORIGIN_HOST_KEY = "originHost"; private static final String LOGGER_NAME = "logger"; private static final String LOGGER_NDC = "loggerNdc"; private static final String JAVA_TIMESTAMP = "timestampMs"; public GelfAppender() { super(); this.originHost = getLocalHostName(); } private String getLocalHostName() { String hostName = null; try { hostName = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { errorHandler.error("Unknown local hostname", e, ErrorCode.GENERIC_FAILURE); } return hostName; } public void setAdditionalFields(String additionalFields) { fields = (Map<String, String>) JSONValue.parse(additionalFields.replaceAll("'", "\"")); } public int getGraylogPort() { return graylogPort; } public void setGraylogPort(int graylogPort) { this.graylogPort = graylogPort; } public String getGraylogHost() { return graylogHost; } public void setGraylogHost(String graylogHost) { this.graylogHost = graylogHost; } public String getFacility() { return facility; } public void setFacility(String facility) { this.facility = facility; } public boolean isExtractStacktrace() { return extractStacktrace; } public void setExtractStacktrace(boolean extractStacktrace) { this.extractStacktrace = extractStacktrace; } public String getOriginHost() { return originHost; } public void setOriginHost(String originHost) { this.originHost = originHost; } public boolean isUseDiagnosticContext() { return useDiagnosticContext; } public void setUseDiagnosticContext(boolean useDiagnosticContext) { this.useDiagnosticContext = useDiagnosticContext; } @Override public void activateOptions() { try { gelfSender = new GelfSender(graylogHost, graylogPort); } catch (UnknownHostException e) { errorHandler.error("Unknown Graylog2 hostname:" + getGraylogHost(), e, ErrorCode.WRITE_FAILURE); } catch (SocketException e) { errorHandler.error("Socket exception", e, ErrorCode.WRITE_FAILURE); } } @Override protected void append(LoggingEvent event) { long timeStamp = getTimestamp(event); Level level = event.getLevel(); LocationInfo locationInformation = event.getLocationInformation(); String file = locationInformation.getFileName(); String lineNumber = locationInformation.getLineNumber(); String renderedMessage = event.getRenderedMessage(); String shortMessage; if(renderedMessage == null) { renderedMessage = ""; } if (renderedMessage.length() > MAX_SHORT_MESSAGE_LENGTH) { shortMessage = renderedMessage.substring(0, MAX_SHORT_MESSAGE_LENGTH - 1); } else { shortMessage = renderedMessage; } if (isExtractStacktrace()) { ThrowableInformation throwableInformation = event.getThrowableInformation(); if (throwableInformation != null) { renderedMessage += "\n\r" + extractStacktrace(throwableInformation); } } GelfMessage gelfMessage = new GelfMessage(shortMessage, renderedMessage, timeStamp, String.valueOf(level.getSyslogEquivalent()), lineNumber, file); if (getOriginHost() != null) { gelfMessage.setHost(getOriginHost()); } if (getFacility() != null) { gelfMessage.setFacility(getFacility()); } if (fields != null && !fields.isEmpty()) { if (fields.containsKey(ORIGIN_HOST_KEY) && gelfMessage.getHost() == null) { gelfMessage.setHost(fields.get(ORIGIN_HOST_KEY)); fields.remove(ORIGIN_HOST_KEY); } for(String key : fields.keySet()) { gelfMessage.addField(key, fields.get(key)); } } if (isUseDiagnosticContext()) { // Get MDC and add a GELF field for each key/value pair Map<String, Object> mdc = MDC.getContext(); if(mdc != null) { for(Map.Entry<String, Object> entry : mdc.entrySet()) { gelfMessage.addField(entry.getKey(), entry.getValue().toString()); } } // Get NDC and add a GELF field String ndc = event.getNDC(); if(ndc != null) { gelfMessage.addField(LOGGER_NDC, ndc); } gelfMessage.addField(JAVA_TIMESTAMP, Long.toString(timeStamp)); } if(!getGelfSender().sendMessage(gelfMessage)) { errorHandler.error("Could not send GELF message"); } } public GelfSender getGelfSender() { return gelfSender; } private long getTimestamp(LoggingEvent event) { return Log4jVersionChecker.getTimeStamp(event); } private String extractStacktrace(ThrowableInformation throwableInformation) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); throwableInformation.getThrowable().printStackTrace(pw); return sw.toString(); } public void close() { getGelfSender().close(); } public boolean requiresLayout() { return false; } }
package info.faceland.loot.api.groups; import org.bukkit.Material; import java.util.Set; public interface ItemGroup { Set<Material> getLegalMaterials(); void addLegalMaterial(Material material); void removeLegalMaterial(Material material); boolean isLegalMaterial(Material material); }
package org.hid4java; import org.hid4java.event.HidServicesListenerList; import org.hid4java.jna.HidApi; import org.hid4java.jna.HidDeviceInfoStructure; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * <p>Manager to provide the following to HID services:</p> * <ul> * <li>Access to the underlying JNA and hidapi library</li> * <li>Device attach/detach detection</li> * </ul> * * @since 0.0.1 * */ class HidDeviceManager { /** * The scan interval in milliseconds */ private int scanInterval = 500; /** * The currently attached devices keyed on ID */ private final Map<String, HidDevice> attachedDevices = Collections.synchronizedMap(new HashMap<String, HidDevice>()); /** * HID services listener list */ private final HidServicesListenerList listenerList; private Thread scanThread = null; /** * Indicates whether or not the {@link #scanThread} is running */ private boolean scanning = false; /** * Constructs a new device manager * * @param listenerList The HID services providing access to the event model * @param scanInterval The scan interval in milliseconds (default is 500ms) * * @throws HidException If USB HID initialization fails */ HidDeviceManager(HidServicesListenerList listenerList, final int scanInterval) throws HidException { this.listenerList = listenerList; this.scanInterval = scanInterval; // Attempt to initialise and fail fast try { HidApi.init(); } catch (Throwable t) { // Typically this is a linking issue with the native library throw new HidException("Hidapi did not initialise: " + t.getMessage(), t); } } /** * Starts the manager * * If already started (scanning) it will immediately return without doing anything * * Otherwise this will perform a one-off scan of all devices then if the scan interval * is zero will stop there or will start the scanning daemon thread at the required interval. * * @throws HidException If something goes wrong (such as Hidapi not initialising correctly) */ public void start() { // Check for previous start if (this.isScanning()) { return; } // Perform a one-off scan to populate attached devices scan(); // Do not start the scan thread when interval is set to 0 final int scanInterval = this.scanInterval; if (scanInterval == 0) { return; } // Create a daemon thread to ensure lifecycle scanThread = new Thread( new Runnable() { @Override public void run() { scanning = true; while (true) { try { Thread.sleep(scanInterval); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); break; } scan(); } // Allow restart scanning = false; } }); scanThread.setDaemon(true); scanThread.setName("hid4java Device Scanner"); scanThread.start(); } /** * Stop the scanning thread if it is running */ public synchronized void stop() { if (scanThread != null) { scanThread.interrupt(); } } /** * Updates the device list by adding newly connected devices to it and by * removing no longer connected devices */ public synchronized void scan() { List<String> removeList = new ArrayList<String>(); List<HidDevice> attachedHidDeviceList = getAttachedHidDevices(); for (HidDevice attachedDevice : attachedHidDeviceList) { if (!this.attachedDevices.containsKey(attachedDevice.getId())) { // Device has become attached so add it but do not open attachedDevices.put(attachedDevice.getId(), attachedDevice); // Fire the event on a separate thread listenerList.fireHidDeviceAttached(attachedDevice); } } for (Map.Entry<String, HidDevice> entry : attachedDevices.entrySet()) { String deviceId = entry.getKey(); HidDevice hidDevice = entry.getValue(); if (!attachedHidDeviceList.contains(hidDevice)) { // Keep track of removals removeList.add(deviceId); // Fire the event on a separate thread listenerList.fireHidDeviceDetached(this.attachedDevices.get(deviceId)); } } if (!removeList.isEmpty()) { // Update the attached devices map this.attachedDevices.keySet().removeAll(removeList); } } /** * @param scanInterval The scan thread's interval in millis (requires restart of thread) */ public void setScanInterval(int scanInterval) { this.scanInterval = scanInterval; } /** * @return True if the scan thread is running, false otherwise. */ public boolean isScanning() { return scanning; } /** * @return A list of all attached HID devices */ public List<HidDevice> getAttachedHidDevices() { List<HidDevice> hidDeviceList = new ArrayList<HidDevice>(); final HidDeviceInfoStructure root; try { // Use 0,0 to list all attached devices // This comes back as a linked list from hidapi root = HidApi.enumerateDevices(0, 0); } catch (Throwable e) { // Could not initialise hidapi (possibly an unknown platform) // Prevent further scanning as a fail safe stop(); // Inform the caller that something serious has gone wrong throw new HidException("Unable to start HidApi: " + e.getMessage()); } if (root != null) { HidDeviceInfoStructure hidDeviceInfoStructure = root; do { // Wrap in HidDevice hidDeviceList.add(new HidDevice(hidDeviceInfoStructure)); // Move to the next in the linked list hidDeviceInfoStructure = hidDeviceInfoStructure.next(); } while (hidDeviceInfoStructure != null); // Dispose of the device list to free memory HidApi.freeEnumeration(root); } return hidDeviceList; } }
package io.actor4j.core.failsafe; import java.util.UUID; public final class FailsafeMethod { public static void run(final FailsafeManager failsafeManager, final String message, final Method method, UUID uuid) { boolean error = false; Exception exception = null; try { method.run(uuid); } catch(Exception e) { if (message!=null) System.out.printf("Method failed: %s (UUID: %s)%n", message, uuid.toString()); method.error(e); error = true; exception = e; } finally { method.after(); } if (error) failsafeManager.notifyErrorHandler(exception, message, uuid); } public static void runAndCatchThrowable(final FailsafeManager failsafeManager, final String message, final Method method, UUID uuid) { boolean error = false; Throwable throwable = null; try { method.run(uuid); } catch(Throwable t) { if (message!=null) System.out.printf("Method failed: %s (UUID: %s)%n", message, uuid.toString()); method.error(t); error = true; throwable = t; } finally { method.after(); } if (error) failsafeManager.notifyErrorHandler(throwable, message, uuid); } public static void run(final FailsafeManager failsafeManager, final Method method, UUID uuid) { run(failsafeManager, null, method, uuid); } public static void runAndCatchThrowable(final FailsafeManager failsafeManager, final Method method, UUID uuid) { runAndCatchThrowable(failsafeManager, null, method, uuid); } }
package org.icij.extract.cli; import org.icij.extract.core.*; import java.util.logging.Logger; import java.nio.file.Path; import java.nio.file.Paths; import org.redisson.Redisson; import org.redisson.core.RQueue; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.CommandLine; /** * Extract * * @author Matthew Caruana Galizia <mcaruana@icij.org> * @version 1.0.0-beta * @since 1.0.0-beta */ public class QueueCli extends Cli { public static void setScannerOptions(CommandLine cmd, Scanner scanner) { if (cmd.hasOption("include-pattern")) { scanner.setIncludeGlob((String) cmd.getOptionValue("include-pattern")); } if (cmd.hasOption("exclude-pattern")) { scanner.setExcludeGlob((String) cmd.getOptionValue("exclude-pattern")); } if (cmd.hasOption("follow-symlinks")) { scanner.followSymLinks(); } } public QueueCli(Logger logger) { super(logger, new String[] { "v", "q", "d", "redis-namespace", "redis-address", "include-pattern", "exclude-pattern", "follow-symlinks" }); } public CommandLine parse(String[] args) throws ParseException, IllegalArgumentException { final CommandLine cmd = super.parse(args); final Redisson redisson = getRedisson(cmd); final RQueue<String> queue = redisson.getQueue(cmd.getOptionValue("redis-namespace", "extract") + ":queue"); final Scanner scanner = new QueueingScanner(logger, queue); setScannerOptions(cmd, scanner); final String directory = (String) cmd.getOptionValue('d', "."); scanner.scan(Paths.get(directory)); redisson.shutdown(); return cmd; } public void printHelp() { super.printHelp(Command.QUEUE, "Queue files for processing later."); } }
package io.ebean.datasource.pool; import io.ebean.datasource.DataSourceAlert; import io.ebean.datasource.DataSourceConfig; import io.ebean.datasource.DataSourceConfigurationException; import io.ebean.datasource.DataSourceInitialiseException; import io.ebean.datasource.DataSourcePool; import io.ebean.datasource.DataSourcePoolListener; import io.ebean.datasource.InitDatabase; import io.ebean.datasource.PoolStatistics; import io.ebean.datasource.PoolStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.Statement; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicBoolean; /** * A robust DataSource implementation. * <p> * <ul> * <li>Manages the number of connections closing connections that have been idle for some time.</li> * <li>Notifies when the datasource goes down and comes back up.</li> * <li>Provides PreparedStatement caching</li> * <li>Knows the busy connections</li> * <li>Traces connections that have been leaked</li> * </ul> * </p> */ public class ConnectionPool implements DataSourcePool { private static final Logger logger = LoggerFactory.getLogger(ConnectionPool.class); /** * The name given to this dataSource. */ private final String name; private final DataSourceConfig config; /** * Used to notify of changes to the DataSource status. */ private final DataSourceAlert notify; /** * Optional listener that can be notified when connections are got from and * put back into the pool. */ private final DataSourcePoolListener poolListener; /** * Properties used to create a Connection. */ private final Properties connectionProps; /** * Queries, that are run for each connection on first open. */ private final List<String> initSql; /** * The jdbc connection url. */ private final String databaseUrl; /** * The jdbc driver. */ private final String databaseDriver; /** * The sql used to test a connection. */ private final String heartbeatsql; private final int heartbeatFreqSecs; private final int heartbeatTimeoutSeconds; private final long trimPoolFreqMillis; /** * The transaction isolation level as per java.sql.Connection. */ private final int transactionIsolation; /** * The default autoCommit setting for Connections in this pool. */ private final boolean autoCommit; private final boolean readOnly; private final boolean failOnStart; /** * Max idle time in millis. */ private final int maxInactiveMillis; /** * Max age a connection is allowed in millis. * A value of 0 means no limit (no trimming based on max age). */ private final long maxAgeMillis; /** * Flag set to true to capture stackTraces (can be expensive). */ private boolean captureStackTrace; /** * The max size of the stack trace to report. */ private final int maxStackTraceSize; /** * flag to indicate we have sent an alert message. */ private boolean dataSourceDownAlertSent; /** * The time the pool was last trimmed. */ private long lastTrimTime; /** * Assume that the DataSource is up. heartBeat checking will discover when * it goes down, and comes back up again. */ private boolean dataSourceUp = true; /** * Stores the dataSourceDown-reason (if there is any) */ private SQLException dataSourceDownReason; /** * The current alert. */ private AtomicBoolean inWarningMode = new AtomicBoolean(); /** * The minimum number of connections this pool will maintain. */ private int minConnections; /** * The maximum number of connections this pool will grow to. */ private int maxConnections; /** * The number of connections to exceed before a warning Alert is fired. */ private int warningSize; /** * The time a thread will wait for a connection to become available. */ private final int waitTimeoutMillis; /** * The size of the preparedStatement cache; */ private int pstmtCacheSize; private final PooledConnectionQueue queue; private final Timer heartBeatTimer; /** * Used to find and close() leaked connections. Leaked connections are * thought to be busy but have not been used for some time. Each time a * connection is used it sets it's lastUsedTime. */ private long leakTimeMinutes; public ConnectionPool(String name, DataSourceConfig params) { this.config = params; this.name = name; this.notify = params.getAlert(); this.poolListener = params.getListener(); this.autoCommit = params.isAutoCommit(); this.readOnly = params.isReadOnly(); this.failOnStart = params.isFailOnStart(); this.initSql = params.getInitSql(); this.transactionIsolation = params.getIsolationLevel(); this.maxInactiveMillis = 1000 * params.getMaxInactiveTimeSecs(); this.maxAgeMillis = 60000 * params.getMaxAgeMinutes(); this.leakTimeMinutes = params.getLeakTimeMinutes(); this.captureStackTrace = params.isCaptureStackTrace(); this.maxStackTraceSize = params.getMaxStackTraceSize(); this.databaseDriver = params.getDriver(); this.databaseUrl = params.getUrl(); this.pstmtCacheSize = params.getPstmtCacheSize(); this.minConnections = params.getMinConnections(); this.maxConnections = params.getMaxConnections(); this.waitTimeoutMillis = params.getWaitTimeoutMillis(); this.heartbeatsql = params.getHeartbeatSql(); this.heartbeatFreqSecs = params.getHeartbeatFreqSecs(); this.heartbeatTimeoutSeconds = params.getHeartbeatTimeoutSeconds(); this.trimPoolFreqMillis = 1000 * params.getTrimPoolFreqSecs(); queue = new PooledConnectionQueue(this); String un = params.getUsername(); String pw = params.getPassword(); if (un == null) { throw new DataSourceConfigurationException("DataSource user is null?"); } if (pw == null) { throw new DataSourceConfigurationException("DataSource password is null?"); } this.connectionProps = new Properties(); this.connectionProps.setProperty("user", un); this.connectionProps.setProperty("password", pw); Map<String, String> customProperties = params.getCustomProperties(); if (customProperties != null) { Set<Entry<String, String>> entrySet = customProperties.entrySet(); for (Entry<String, String> entry : entrySet) { this.connectionProps.setProperty(entry.getKey(), entry.getValue()); } } try { initialise(); int freqMillis = heartbeatFreqSecs * 1000; heartBeatTimer = new Timer(name + ".heartBeat", true); if (freqMillis > 0) { heartBeatTimer.scheduleAtFixedRate(new HeartBeatRunnable(), freqMillis, freqMillis); } } catch (SQLException e) { throw new DataSourceInitialiseException("Error initialising DataSource: " + e.getMessage(), e); } } class HeartBeatRunnable extends TimerTask { @Override public void run() { checkDataSource(); } } @Override public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new SQLFeatureNotSupportedException("We do not support java.util.logging"); } private void initialise() throws SQLException { // Ensure database driver is loaded try { ClassLoader contextLoader = Thread.currentThread().getContextClassLoader(); if (contextLoader != null) { Class.forName(databaseDriver, true, contextLoader); } else { Class.forName(databaseDriver, true, this.getClass().getClassLoader()); } } catch (Throwable e) { throw new IllegalStateException("Problem loading Database Driver [" + this.databaseDriver + "]: " + e.getMessage(), e); } String transIsolation = TransactionIsolation.getDescription(transactionIsolation); //noinspection StringBufferReplaceableByString StringBuilder sb = new StringBuilder(70); sb.append("DataSourcePool [").append(name); sb.append("] autoCommit[").append(autoCommit); sb.append("] transIsolation[").append(transIsolation); sb.append("] min[").append(minConnections); sb.append("] max[").append(maxConnections).append("]"); logger.info(sb.toString()); if (config.useInitDatabase()) { initialiseDatabase(); } try { queue.ensureMinimumConnections(); } catch (SQLException e) { if (failOnStart) { throw e; } logger.error("Error trying to ensure minimum connections, maybe db server is down - message:" + e.getMessage(), e); } } /** * Initialise the database using the owner credentials if we can't connect using the normal credentials. * <p> * That is, if we think the username doesn't exist in the DB, initialise the DB using the owner credentials. * </p> */ private void initialiseDatabase() throws SQLException { try (Connection connection = createUnpooledConnection(connectionProps, false)) { // successfully obtained a connection so skip initDatabase connection.clearWarnings(); } catch (SQLException e) { logger.info("Obtaining connection using ownerUsername:{} to initialise database", config.getOwnerUsername()); // expected when user does not exists, obtain a connection using owner credentials try (Connection ownerConnection = createUnpooledConnection(config.getOwnerUsername(), config.getOwnerPassword())) { // initialise the DB (typically create the user/role using the owner credentials etc) InitDatabase initDatabase = config.getInitDatabase(); initDatabase.run(ownerConnection, config); ownerConnection.commit(); } catch (SQLException e2) { throw new SQLException("Failed to run InitDatabase with ownerUsername:" + config.getOwnerUsername() + " message:" + e2.getMessage(), e2); } } } /** * Returns false. */ @Override public boolean isWrapperFor(Class<?> arg0) throws SQLException { return false; } /** * Not Implemented. */ @Override public <T> T unwrap(Class<T> arg0) throws SQLException { throw new SQLException("Not Implemented"); } /** * Return the dataSource name. */ @Override public String getName() { return name; } /** * Return the max size of stack traces used when trying to find connection pool leaks. * <p> * This is only used when {@link #isCaptureStackTrace()} is true. * </p> */ int getMaxStackTraceSize() { return maxStackTraceSize; } /** * Returns false when the dataSource is down. */ @Override public boolean isDataSourceUp() { return dataSourceUp; } @Override public SQLException getDataSourceDownReason() { return dataSourceDownReason; } /** * Called when the pool hits the warning level. */ protected void notifyWarning(String msg) { if (inWarningMode.compareAndSet(false, true)) { // send an Error to the event log... logger.warn(msg); if (notify != null) { notify.dataSourceWarning(this, msg); } } } private synchronized void notifyDataSourceIsDown(SQLException ex) { if (dataSourceUp) { reset(); } dataSourceUp = false; if (ex != null) { dataSourceDownReason = ex; } if (!dataSourceDownAlertSent) { dataSourceDownAlertSent = true; logger.error("FATAL: DataSourcePool [" + name + "] is down or has network error!!! message:" + ex.getMessage(), ex); if (notify != null) { notify.dataSourceDown(this, ex); } } } private synchronized void notifyDataSourceIsUp() { if (dataSourceDownAlertSent) { // set to false here, so that a getConnection() call in DataSourceAlert.dataSourceUp // in same thread does not fire the event again (and end in recursion) // all other threads will be blocked, becasue method is synchronized. dataSourceDownAlertSent = false; logger.error("RESOLVED FATAL: DataSourcePool [" + name + "] is back up!"); if (notify != null) { notify.dataSourceUp(this); } } else if (!dataSourceUp) { logger.info("DataSourcePool [" + name + "] is back up!"); } if (!dataSourceUp) { dataSourceUp = true; dataSourceDownReason = null; reset(); } } /** * Trim connections (in the free list) based on idle time and maximum age. */ private void trimIdleConnections() { if (System.currentTimeMillis() > (lastTrimTime + trimPoolFreqMillis)) { try { queue.trim(maxInactiveMillis, maxAgeMillis); lastTrimTime = System.currentTimeMillis(); } catch (Exception e) { logger.error("Error trying to trim idle connections - message:" + e.getMessage(), e); } } } /** * Check the dataSource is up. Trim connections. * <p> * This is called by the HeartbeatRunnable which should be scheduled to * run periodically (every heartbeatFreqSecs seconds actually). * </p> */ private void checkDataSource() { // first trim idle connections trimIdleConnections(); Connection conn = null; try { // Get a connection from the pool and test it conn = getConnection(); if (testConnection(conn)) { notifyDataSourceIsUp(); } else { notifyDataSourceIsDown(null); } } catch (SQLException ex) { notifyDataSourceIsDown(ex); } finally { try { if (conn != null) { conn.close(); } } catch (SQLException ex) { logger.warn("Can't close connection in checkDataSource!"); } } } /** * Initializes the connection we got from the driver. */ private void initConnection(Connection conn) throws SQLException { conn.setAutoCommit(autoCommit); // isolation level is set globally for all connections (at least for H2) // and you will need admin rights - so we do not change it, if it already // matches. if (conn.getTransactionIsolation() != transactionIsolation) { conn.setTransactionIsolation(transactionIsolation); } if (readOnly) { conn.setReadOnly(readOnly); } if (initSql != null) { for (String query : initSql) { try (Statement stmt = conn.createStatement()) { stmt.execute(query); } } } } /** * Create an un-pooled connection with the given username and password. */ public Connection createUnpooledConnection(String username, String password) throws SQLException { Properties properties = new Properties(connectionProps); properties.setProperty("user", username); properties.setProperty("password", password); return createUnpooledConnection(properties, true); } /** * Create an un-pooled connection. */ public Connection createUnpooledConnection() throws SQLException { return createUnpooledConnection(connectionProps, true); } private Connection createUnpooledConnection(Properties properties, boolean notifyIsDown) throws SQLException { try { Connection conn = DriverManager.getConnection(databaseUrl, properties); initConnection(conn); return conn; } catch (SQLException ex) { if (notifyIsDown) { notifyDataSourceIsDown(null); } throw ex; } } /** * Set a new maximum size. The pool should respect this new maximum * immediately and not require a restart. You may want to increase the * maxConnections if the pool gets large and hits the warning level. */ @Override public void setMaxSize(int max) { queue.setMaxSize(max); this.maxConnections = max; } /** * Return the max size this pool can grow to. */ public int getMaxSize() { return maxConnections; } /** * Set the min size this pool should maintain. */ public void setMinSize(int min) { queue.setMinSize(min); this.minConnections = min; } /** * Return the min size this pool should maintain. */ public int getMinSize() { return minConnections; } /** * Set a new maximum size. The pool should respect this new maximum * immediately and not require a restart. You may want to increase the * maxConnections if the pool gets large and hits the warning and or alert * levels. */ @Override public void setWarningSize(int warningSize) { queue.setWarningSize(warningSize); this.warningSize = warningSize; } /** * Return the warning size. When the pool hits this size it can send a * notify message to an administrator. */ @Override public int getWarningSize() { return warningSize; } /** * Return the time in millis that threads will wait when the pool has hit * the max size. These threads wait for connections to be returned by the * busy connections. */ public int getWaitTimeoutMillis() { return waitTimeoutMillis; } /** * Return the time after which inactive connections are trimmed. */ public int getMaxInactiveMillis() { return maxInactiveMillis; } /** * Return the maximum age a connection is allowed to be before it is trimmed * out of the pool. This value can be 0 which means there is no maximum age. */ public long getMaxAgeMillis() { return maxAgeMillis; } private boolean testConnection(Connection conn) throws SQLException { if (heartbeatsql == null) { return conn.isValid(heartbeatTimeoutSeconds); } Statement stmt = null; ResultSet rset = null; try { // It should only error IF the DataSource is down or a network issue stmt = conn.createStatement(); if (heartbeatTimeoutSeconds > 0) { stmt.setQueryTimeout(heartbeatTimeoutSeconds); } rset = stmt.executeQuery(heartbeatsql); conn.commit(); return true; } finally { try { if (rset != null) { rset.close(); } } catch (SQLException e) { logger.error("Error closing resultSet", e); } try { if (stmt != null) { stmt.close(); } } catch (SQLException e) { logger.error("Error closing statement", e); } } } /** * Make sure the connection is still ok to use. If not then remove it from * the pool. */ boolean validateConnection(PooledConnection conn) { try { return testConnection(conn); } catch (Exception e) { logger.warn("heartbeatsql test failed on connection:" + conn.getName() + " message:" + e.getMessage()); return false; } } /** * Called by the PooledConnection themselves, returning themselves to the * pool when they have been finished with. * <p> * Note that connections may not be added back to the pool if returnToPool * is false or if they where created before the recycleTime. In both of * these cases the connection is fully closed and not pooled. * </p> * * @param pooledConnection the returning connection */ void returnConnection(PooledConnection pooledConnection) { // return a normal 'good' connection returnTheConnection(pooledConnection, false); } /** * This is a bad connection and must be removed from the pool's busy list and fully closed. */ void returnConnectionForceClose(PooledConnection pooledConnection) { returnTheConnection(pooledConnection, true); } /** * Return connection. If forceClose is true then this is a bad connection that * must be removed and closed fully. */ private void returnTheConnection(PooledConnection pooledConnection, boolean forceClose) { if (poolListener != null && !forceClose) { poolListener.onBeforeReturnConnection(pooledConnection); } queue.returnPooledConnection(pooledConnection, forceClose); if (forceClose) { // Got a bad connection so check the pool checkDataSource(); } } /** * Collect statistics of a connection that is fully closing */ void reportClosingConnection(PooledConnection pooledConnection) { queue.reportClosingConnection(pooledConnection); } /** * Returns information describing connections that are currently being used. */ public String getBusyConnectionInformation() { return queue.getBusyConnectionInformation(); } /** * Dumps the busy connection information to the logs. * <p> * This includes the stackTrace elements if they are being captured. This is * useful when needing to look a potential connection pool leaks. * </p> */ public void dumpBusyConnectionInformation() { queue.dumpBusyConnectionInformation(); } /** * Close any busy connections that have not been used for some time. * <p> * These connections are considered to have leaked from the connection pool. * </p> * <p> * Connection leaks occur when code doesn't ensure that connections are * closed() after they have been finished with. There should be an * appropriate try catch finally block to ensure connections are always * closed and put back into the pool. * </p> */ public void closeBusyConnections(long leakTimeMinutes) { queue.closeBusyConnections(leakTimeMinutes); } /** * Grow the pool by creating a new connection. The connection can either be * added to the available list, or returned. * <p> * This method is protected by synchronization in calling methods. * </p> */ PooledConnection createConnectionForQueue(int connId) throws SQLException { try { Connection c = createUnpooledConnection(); PooledConnection pc = new PooledConnection(this, connId, c); pc.resetForUse(); if (!dataSourceUp) { notifyDataSourceIsUp(); } return pc; } catch (SQLException ex) { notifyDataSourceIsDown(ex); throw ex; } } /** * Close all the connections in the pool. * <p> * <ul> * <li>Checks that the database is up. * <li>Resets the Alert level. * <li>Closes busy connections that have not been used for some time (aka * leaks). * <li>This closes all the currently available connections. * <li>Busy connections are closed when they are returned to the pool. * </ul> * </p> */ public void reset() { queue.reset(leakTimeMinutes); inWarningMode.set(false); } /** * Return a pooled connection. */ @Override public Connection getConnection() throws SQLException { return getPooledConnection(); } /** * Get a connection from the pool. * <p> * This will grow the pool if all the current connections are busy. This * will go into a wait if the pool has hit its maximum size. * </p> */ private PooledConnection getPooledConnection() throws SQLException { PooledConnection c = queue.getPooledConnection(); if (captureStackTrace) { c.setStackTrace(Thread.currentThread().getStackTrace()); } if (poolListener != null) { poolListener.onAfterBorrowConnection(c); } return c; } /** * Send a message to the DataSourceAlertListener to test it. This is so that * you can make sure the alerter is configured correctly etc. */ public void testAlert() { String msg = "Just testing if alert message is sent successfully."; if (notify != null) { notify.dataSourceWarning(this, msg); } } /** * This will close all the free connections, and then go into a wait loop, * waiting for the busy connections to be freed. * <p> * <p> * The DataSources's should be shutdown AFTER thread pools. Leaked * Connections are not waited on, as that would hang the server. * </p> */ @Override public void shutdown(boolean deregisterDriver) { heartBeatTimer.cancel(); queue.shutdown(); if (deregisterDriver) { deregisterDriver(); } } /** * Return the default autoCommit setting Connections in this pool will use. * * @return true if the pool defaults autoCommit to true */ @Override public boolean isAutoCommit() { return autoCommit; } /** * Return the default transaction isolation level connections in this pool * should have. * * @return the default transaction isolation level */ int getTransactionIsolation() { return transactionIsolation; } /** * Return true if the connection pool is currently capturing the StackTrace * when connections are 'got' from the pool. * <p> * This is set to true to help diagnose connection pool leaks. * </p> */ public boolean isCaptureStackTrace() { return captureStackTrace; } /** * Set this to true means that the StackElements are captured every time a * connection is retrieved from the pool. This can be used to identify * connection pool leaks. */ public void setCaptureStackTrace(boolean captureStackTrace) { this.captureStackTrace = captureStackTrace; } /** * Create an un-pooled connection with the given username and password. * <p> * This uses the default isolation level and autocommit mode. */ @Override public Connection getConnection(String username, String password) throws SQLException { Properties props = new Properties(); props.putAll(connectionProps); props.setProperty("user", username); props.setProperty("password", password); Connection conn = DriverManager.getConnection(databaseUrl, props); initConnection(conn); return conn; } /** * Not implemented and shouldn't be used. */ @Override public int getLoginTimeout() throws SQLException { throw new SQLException("Method not supported"); } /** * Not implemented and shouldn't be used. */ @Override public void setLoginTimeout(int seconds) throws SQLException { throw new SQLException("Method not supported"); } /** * Returns null. */ @Override public PrintWriter getLogWriter() { return null; } /** * Not implemented. */ @Override public void setLogWriter(PrintWriter writer) throws SQLException { throw new SQLException("Method not supported"); } /** * For detecting and closing leaked connections. Connections that have been * busy for more than leakTimeMinutes are considered leaks and will be * closed on a reset(). * <p> * If you want to use a connection for that longer then you should consider * creating an unpooled connection or setting longRunning to true on that * connection. * </p> */ public void setLeakTimeMinutes(long leakTimeMinutes) { this.leakTimeMinutes = leakTimeMinutes; } /** * Return the number of minutes after which a busy connection could be * considered leaked from the connection pool. */ public long getLeakTimeMinutes() { return leakTimeMinutes; } /** * Return the preparedStatement cache size. */ public int getPstmtCacheSize() { return pstmtCacheSize; } /** * Set the preparedStatement cache size. */ public void setPstmtCacheSize(int pstmtCacheSize) { this.pstmtCacheSize = pstmtCacheSize; } /** * Return the current status of the connection pool. * <p> * If you pass reset = true then the counters such as * hitCount, waitCount and highWaterMark are reset. * </p> */ @Override public PoolStatus getStatus(boolean reset) { return queue.getStatus(reset); } /** * Return the aggregated load statistics collected on all the connections in the pool. */ @Override public PoolStatistics getStatistics(boolean reset) { return queue.getStatistics(reset); } /** * Deregister the JDBC driver. */ private void deregisterDriver() { try { logger.debug("Deregister the JDBC driver " + this.databaseDriver); DriverManager.deregisterDriver(DriverManager.getDriver(this.databaseUrl)); } catch (SQLException e) { logger.warn("Error trying to deregister the JDBC driver " + this.databaseDriver, e); } } public static class Status implements PoolStatus { private final int minSize; private final int maxSize; private final int free; private final int busy; private final int waiting; private final int highWaterMark; private final int waitCount; private final int hitCount; protected Status(int minSize, int maxSize, int free, int busy, int waiting, int highWaterMark, int waitCount, int hitCount) { this.minSize = minSize; this.maxSize = maxSize; this.free = free; this.busy = busy; this.waiting = waiting; this.highWaterMark = highWaterMark; this.waitCount = waitCount; this.hitCount = hitCount; } public String toString() { return "min[" + minSize + "] max[" + maxSize + "] free[" + free + "] busy[" + busy + "] waiting[" + waiting + "] highWaterMark[" + highWaterMark + "] waitCount[" + waitCount + "] hitCount[" + hitCount + "]"; } /** * Return the min pool size. */ @Override public int getMinSize() { return minSize; } /** * Return the max pool size. */ @Override public int getMaxSize() { return maxSize; } /** * Return the current number of free connections in the pool. */ @Override public int getFree() { return free; } /** * Return the current number of busy connections in the pool. */ @Override public int getBusy() { return busy; } /** * Return the current number of threads waiting for a connection. */ @Override public int getWaiting() { return waiting; } /** * Return the high water mark of busy connections. */ @Override public int getHighWaterMark() { return highWaterMark; } /** * Return the total number of times a thread had to wait. */ @Override public int getWaitCount() { return waitCount; } /** * Return the total number of times there was an attempt to get a * connection. * <p> * If the attempt to get a connection failed with a timeout or other * exception those attempts are still included in this hit count. * </p> */ @Override public int getHitCount() { return hitCount; } } }
package me.nallar.javatransformer.api; import lombok.Getter; import lombok.ToString; @Getter @ToString public class Parameter extends Type { public final String name; public Parameter(Type t, String name) { super(t.descriptor, t.signature); this.name = name; } public Parameter(String real, String generic, String name) { super(real, generic); this.name = name; } }
package uk.co.eluinhost.ultrahardcore.features.playerfreeze; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerJoinEvent; import uk.co.eluinhost.ultrahardcore.features.UHCFeature; import java.util.HashSet; import java.util.Set; public class PlayerFreezeFeature extends UHCFeature { private Set<String> m_players = new HashSet<String>(); /** * handles frozen players */ public PlayerFreezeFeature() { super("PlayerFreeze", "Allows for freezing players in place"); } /** * @param playerName the player name to freeze */ public void addPlayer(String playerName){ m_players.add(playerName); //TODO stop movement } /** * @param playerName the player name */ public void removePlayer(String playerName){ m_players.remove(playerName); //TODO allow movement } /** * Remove all from the frozen list */ public void unfreezeAll(){ //TODO allow movement for all m_players.clear(); } /** * Whenever a player joins * @param pje the player join event */ @EventHandler public void onPlayerJoinEvent(PlayerJoinEvent pje){ //TODO check whether to reapply freeze } /** * Called when the feature is being enabled */ @Override protected void enableCallback(){ //TODO reapply freezes? } /** * Called when the feature is being disabled */ @Override protected void disableCallback(){ //TODO remove freezes } }
package org.ngseq.metagenomics; import org.apache.commons.cli.*; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DFSClient; import org.apache.hadoop.hdfs.DFSInputStream; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.broadcast.Broadcast; import scala.Tuple2; import java.io.*; import java.net.URI; import java.util.ArrayList; /** spark-submit --master local[${NUM_EXECUTORS}] --executor-memory 10g --class org.ngseq.metagenomics.BlastN metagenomics-0.9-jar-with-dependencies.jar -in ${OUTPUT_PATH}/${PROJECT_NAME}_blast_nonhuman -out ${OUTPUT_PATH}/${PROJECT_NAME}_blast_final -db ${BLAST_DATABASE} -outfmt 6 -num_threads ${BLAST_THREADS} spark-submit --master yarn --deploy-mode ${DEPLOY_MODE} --conf spark.dynamicAllocation.enabled=true --conf spark.dynamicAllocation.cachedExecutorIdleTimeout=100 --conf spark.shuffle.service.enabled=true --conf spark.scheduler.mode=${SCHEDULER_MODE} --conf spark.task.maxFailures=100 --conf spark.yarn.max.executor.failures=100 --executor-memory 10g --conf spark.yarn.executor.memoryOverhead=10000 --class org.ngseq.metagenomics.BlastN metagenomics-0.9-jar-with-dependencies.jar -in ${OUTPUT_PATH}/${PROJECT_NAME}_blast_nonhuman -out ${OUTPUT_PATH}/${PROJECT_NAME}_blast_final -db ${BLAST_DATABASE} -outfmt 6 -num_threads ${BLAST_THREADS} */ public class BlastN { public static void main(String[] args) throws IOException { Options options = new Options(); options.addOption(new Option( "temp", "Temporary output")); options.addOption(new Option( "out", true, "" )); options.addOption(new Option( "in", true, "" )); options.addOption(new Option( "word_size", "")); options.addOption(new Option( "gapopen", true, "" )); options.addOption(new Option( "gapextend", true, "" )); options.addOption(new Option( "penalty", true, "" )); options.addOption(new Option( "reward", true, "" )); options.addOption(new Option( "max_target_seqs", true, "" )); options.addOption(new Option( "evalue", true, "" )); options.addOption(new Option( "show_gis", "" )); options.addOption(new Option( "outfmt", true, "" )); options.addOption(new Option( "db", true, "Path to local BlastNT database (database must be available on every node under the same path)" )); options.addOption(new Option( "task", true, "" )); options.addOption(new Option( "num_threads", true, "" )); options.addOption(new Option( "taxname", true, "Use Blast taxonomy names for filtering e.g. viruses, bacteria, archaea" )); options.addOption( new Option( "bin", true,"Path to blastn binary, defaults calls 'blastn'" ) ); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "spark-submit <spark specific args>", options, true ); CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse( options, args ); } catch( ParseException exp ) { System.err.println( "Parsing failed. Reason: " + exp.getMessage() ); System.exit(1); } String input = cmd.getOptionValue("in"); String output = cmd.getOptionValue("out"); int word_size = (cmd.hasOption("word_size")==true)? Integer.valueOf(cmd.getOptionValue("word_size")):11; int gapopen = (cmd.hasOption("gapopen")==true)? Integer.valueOf(cmd.getOptionValue("gapopen")):0; int gapextend = (cmd.hasOption("gapextend")==true)? Integer.valueOf(cmd.getOptionValue("gapextend")):2; int penalty = (cmd.hasOption("penalty")==true)? Integer.valueOf(cmd.getOptionValue("penalty")):-1; int reward = (cmd.hasOption("reward")==true)? Integer.valueOf(cmd.getOptionValue("reward")):1; int max_target_seqs = (cmd.hasOption("max_target_seqs")==true)? Integer.valueOf(cmd.getOptionValue("max_target_seqs")):10; double evalue = (cmd.hasOption("evalue")==true)? Double.valueOf(cmd.getOptionValue("evalue")):0.001; boolean show_gis = cmd.hasOption("show_gis"); String outfmt = (cmd.hasOption("outfmt")==true)? cmd.getOptionValue("outfmt"): "6 qseqid sseqid pident length mismatch gapopen qstart qend sstart send evalue bitscore sscinames sskingdoms"; String db = cmd.getOptionValue("db"); String task = (cmd.hasOption("task")==true)? cmd.getOptionValue("task"):"blastn"; int num_threads = (cmd.hasOption("num_threads")==true)? Integer.valueOf(cmd.getOptionValue("num_threads")):1; String taxname = (cmd.hasOption("taxname")==true)? cmd.getOptionValue("taxname"):""; String bin = (cmd.hasOption("bin")==true)? cmd.getOptionValue("bin"):"blastn"; SparkConf conf = new SparkConf().setAppName("BlastN"); JavaSparkContext sc = new JavaSparkContext(conf); sc.hadoopConfiguration().set("textinputformat.record.delimiter", ">"); FileSystem fs = FileSystem.get(new Configuration()); FileStatus[] st = fs.listStatus(new Path(input)); ArrayList<String> splitFileList = new ArrayList<>(); for (int i=0;i<st.length;i++){ if(!st[i].isDirectory()){ if(st[i].getLen()>1){ splitFileList.add(st[i].getPath().toUri().getRawPath().toString()); System.out.println(st[i].getPath().toUri().getRawPath().toString()); } } } JavaRDD<String> fastaFilesRDD = sc.parallelize(splitFileList, splitFileList.size()); Broadcast<String> bs = sc.broadcast(fs.getUri().toString()); JavaRDD<String> outRDD = fastaFilesRDD.mapPartitions(f -> { Process process; String fname = f.next(); DFSClient client = new DFSClient(URI.create(bs.getValue()), new Configuration()); DFSInputStream hdfsstream = client.open(fname); String blastn_cmd; if(task.equalsIgnoreCase("megablast")) blastn_cmd = bin+" -db "+db+" -num_threads "+num_threads+" -task megablast -word_size "+word_size+" -max_target_seqs "+max_target_seqs+" -evalue "+evalue+" " + ((show_gis == true) ? "-show_gis " : "") + " -outfmt "+outfmt; else blastn_cmd = bin+" -db "+db+" -num_threads "+num_threads+" -word_size "+word_size+" -gapopen "+gapopen+" -gapextend "+gapextend+" -penalty "+penalty+" -reward "+reward+" -max_target_seqs "+max_target_seqs+" -evalue "+evalue+" " + ((show_gis == true) ? "-show_gis " : "") + " -outfmt "+outfmt; System.out.println(blastn_cmd); ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", blastn_cmd); process = pb.start(); BufferedReader hdfsinput = new BufferedReader(new InputStreamReader(hdfsstream)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream())); String line; while ((line = hdfsinput.readLine()) != null) { writer.write(line); writer.newLine(); } writer.close(); BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); String bline; ArrayList<String> out = new ArrayList<String>(); while ((bline = in.readLine()) != null) { out.add(bline); } /* BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream())); String e; while ((e = err.readLine()) != null) { out.add(e); } */ in.close(); return out.iterator(); }); if(taxname!="") outRDD.filter(res ->{ String[] fields = res.split("\t"); String taxonomy = fields[res.length()]; return taxonomy.equalsIgnoreCase(taxname); }).saveAsTextFile(output); else outRDD.saveAsTextFile(output); sc.stop(); } }
package de.lancom.systems.stomp.spring; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import de.lancom.systems.stomp.core.client.StompClient; import de.lancom.systems.stomp.core.client.StompUrl; import de.lancom.systems.stomp.core.connection.StompFrameContextInterceptors; import de.lancom.systems.stomp.core.wire.StompAckMode; import de.lancom.systems.stomp.core.wire.StompFrame; import de.lancom.systems.stomp.core.wire.frame.SendFrame; import de.lancom.systems.stomp.spring.annotation.Subscription; import de.lancom.systems.stomp.test.AsyncHolder; import lombok.extern.slf4j.Slf4j; @Slf4j @ContextConfiguration(classes = TestConfiguration.class) @RunWith(SpringJUnit4ClassRunner.class) public class TopicConsumerTest { private static final int WAIT_SECONDS = 5; private static final String URL_TOPIC = "${broker.url}/topic/645f7e02-17f8-4b6e-baf4-b43b55a74784"; private static final String URL_TOPIC_BIG = "${broker.url}/topic/645f7e02-17f8-4b6e-baf4-b43b55a74799"; private static final AsyncHolder<String> TOPIC_HOLDER_GENERAL = AsyncHolder.create(); private static final AsyncHolder<String> TOPIC_HOLDER_A = AsyncHolder.create(); private static final AsyncHolder<String> TOPIC_HOLDER_B = AsyncHolder.create(); private static final AsyncHolder<String> TOPIC_HOLDER_BIG = AsyncHolder.create(); @Autowired private Environment environment; @Autowired private StompClient client; private static boolean interceptorAdded; @Subscription(value = URL_TOPIC, ackMode = StompAckMode.AUTO) public void processTopicFrameGeneral(final StompUrl url, final StompFrame frame) { TOPIC_HOLDER_GENERAL.set(frame.getBodyAsString()); } @Subscription(value = URL_TOPIC, selector = "flag = 'a'", ackMode = StompAckMode.AUTO) public void processTopicFrameA(final String body) { System.out.println("A"); TOPIC_HOLDER_A.set(body); } @Subscription(value = URL_TOPIC, selector = "flag = 'b'", ackMode = StompAckMode.AUTO) public void processTopicFrameB(final StompFrame frame) { System.out.println("B"); TOPIC_HOLDER_B.set(frame.getBodyAsString()); } @Subscription(value = URL_TOPIC_BIG, ackMode = StompAckMode.AUTO) public void processTopicFrameBig(final StompFrame frame) { System.out.println("big"); TOPIC_HOLDER_B.set(frame.getBodyAsString()); } @Before public void setup() { if (!interceptorAdded) { client.addInterceptor(StompFrameContextInterceptors.logger()); interceptorAdded = true; } } @Test public void consumeTopicFiltered() throws Exception { final StompUrl url = StompUrl.parse(environment.resolvePlaceholders(URL_TOPIC)); final SendFrame sendFrame1 = new SendFrame(url.getDestination(), "Flag A"); sendFrame1.setHeader("flag", "a"); assertTrue( "Send failed", client.transmitFrame(url, sendFrame1).await(WAIT_SECONDS, TimeUnit.SECONDS) ); final SendFrame sendFrame2 = new SendFrame(url.getDestination(), "Flag B"); sendFrame2.setHeader("flag", "b"); assertTrue( "Send failed", client.transmitFrame(url, sendFrame2).await(WAIT_SECONDS, TimeUnit.SECONDS) ); assertTrue(TOPIC_HOLDER_A.expect(1, WAIT_SECONDS, TimeUnit.SECONDS)); assertThat(TOPIC_HOLDER_A.getCount(), is(1)); assertThat(TOPIC_HOLDER_A.contains("Flag A"), is(true)); assertTrue(TOPIC_HOLDER_B.expect(1, WAIT_SECONDS, TimeUnit.SECONDS)); assertThat(TOPIC_HOLDER_B.getCount(), is(1)); assertThat(TOPIC_HOLDER_B.contains("Flag B"), is(true)); assertTrue(TOPIC_HOLDER_GENERAL.expect(2, WAIT_SECONDS, TimeUnit.SECONDS)); assertThat(TOPIC_HOLDER_GENERAL.getCount(), is(2)); assertThat(TOPIC_HOLDER_GENERAL.contains("Flag A"), is(true)); assertThat(TOPIC_HOLDER_GENERAL.contains("Flag B"), is(true)); } @Test @Ignore public void consumeTopicFrameBig() throws Exception { final StompUrl url = StompUrl.parse(environment.resolvePlaceholders(URL_TOPIC_BIG)); final String body = "[{\"_id\":\"5857feb79d286b06b7aa56b6\",\"index\":0,\"guid\":\"cc78ec9a-7783-4334-876e-1ebacdc97daa\",\"isActive\":false,\"balance\":\"$1,741.97\",\"picture\":\"http: final SendFrame sendFrame = new SendFrame(url.getDestination(), body); assertTrue( "Send failed", client.transmitFrame(url, sendFrame).await(WAIT_SECONDS, TimeUnit.SECONDS) ); assertTrue(TOPIC_HOLDER_BIG.expect(1, WAIT_SECONDS, TimeUnit.SECONDS)); assertThat(TOPIC_HOLDER_BIG.getCount(), is(1)); Assert.assertEquals(body, TOPIC_HOLDER_BIG.get()); } }
package net.darkhax.bookshelf.lib; public class MutableString implements java.io.Serializable, Comparable<String>, CharSequence { private static final long serialVersionUID = 8345543667917868717L; /** * The String value held by the MutableString. */ private String value; /** * Constructs a MutableString object. This variant on String allows for the instance to be * altered, as opposed to Java's immutable String. * * @param string The value to set. */ public MutableString (String string) { this.value = string; } /** * Sets the value of the MutableStrong. * * @param string The value to set. */ public void setValue (String string) { this.value = string; } /** * Retrieves the value of the MutableString. * * @return String The value held by the MutableString. */ public String getValue () { return this.value; } @Override public int length () { return this.value.length(); } @Override public char charAt (int index) { return this.value.charAt(index); } @Override public CharSequence subSequence (int start, int end) { return this.value.subSequence(start, end); } @Override public String toString () { return this.value; } @Override public int compareTo (String o) { return this.value.compareTo(o); } @Override public boolean equals (Object obj) { return this.value.equals(obj); } @Override public int hashCode () { return this.value.hashCode(); } }
package org.semanticweb.yars.nx; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import org.semanticweb.yars.nx.parser.ParseException; /** * A bnode, anonymous resource. * * @author Andreas Harth * @author Tobias Kaefer */ public class BNode implements Serializable, Node { public static String PREFIX = "_:"; public static boolean PRETTY_PRINT = false; // the value of the bnode including prefix protected String _data; // version number for serialization private static final long serialVersionUID = 6233987125715026425L; /** * Constructor if we have a bnode with a nodeID. * Need to add context of the file to the nodeID later, * otherwise there will be clashes. */ public BNode(String nodeid) { this(nodeid, false); } public BNode(String nodeid, boolean hasPrefix) { if (hasPrefix) _data = nodeid; else if (!nodeid.startsWith(PREFIX)) _data = PREFIX + nodeid; else _data = nodeid; } /** * Get URI. */ public String toString() { if(PRETTY_PRINT){ try{ String[] conb = parseContextualBNode(); return conb[1]+"@["+conb[0]+"]"; } catch(ParseException pe){ return unescapeForBNode(_data.substring(PREFIX.length())); } } else return _data.substring(PREFIX.length()); } public int hashCode() { return _data.hashCode(); } public String toN3() { return _data; } /** * Equality check */ public boolean equals(Object o) { if (o == this) return true; else if (o instanceof BNode) return _data.equals(((BNode) o)._data); else return false; } /** * Compare. */ public int compareTo(Object o) { if(o==this) return 0; else if (o instanceof BNode) { BNode b = (BNode)o; return _data.compareTo(b._data); } else if (o instanceof Resource) { return Integer.MAX_VALUE/2; } else if (o instanceof Literal) { return Integer.MAX_VALUE; } else if(o instanceof Unbound){ return Integer.MIN_VALUE/2; } else if (o instanceof Variable) { return Integer.MIN_VALUE; } throw new ClassCastException("parameter is not of type BNode but " + o.getClass().getName()); } /** * Override readObject for backwards compatability and storing hashcode */ private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); if(!_data.startsWith(PREFIX)) _data = PREFIX+_data; } public String[] parseContextualBNode() throws ParseException{ String d = _data.substring(PREFIX.length()); String[] uri = d.toString().split("xx"); if(uri.length!=2){ throw new ParseException("This is not a valid context encoded BNode"); } uri[0] = unescapeForBNode(uri[0]); uri[1] = unescapeForBNode(uri[1]); return uri; } public static String[] parseContextualBNode(BNode b) throws ParseException{ String[] uri = b.toString().split("xx"); if(uri.length!=2){ throw new ParseException("Not a valid context encoded BNode "+b); } uri[0] = unescapeForBNode(uri[0]); uri[1] = unescapeForBNode(uri[1]); return uri; } public static BNode createBNode(String docURI, String localID){ String escapedDU = escapeForBNode(docURI); String escapedLI = escapeForBNode(localID); return new BNode(escapedDU+"xx"+escapedLI); } public static BNode createBNode(String unescaped){ String escaped = escapeForBNode(unescaped); return new BNode(escaped); } public static String escapeForBNode(String unescaped){ try { return URLEncoder.encode(unescaped, "utf-8").replace("x", "x78").replace("-", "x2D").replace(".", "x2E").replace("_", "x5F").replace('%', 'x'); } catch (UnsupportedEncodingException e) { //never je suppose return null; } } public static String unescapeForBNode(String escaped){ try { return URLDecoder.decode(escaped.replace('x', '%'), "utf-8"); } catch (UnsupportedEncodingException e) { //never je suppose return null; } } public static void main(String[] args) throws ParseException{ String unescaped = "http://asdj.com/-xx42xxx/%20thing/"; System.err.println(escapeForBNode(unescaped)); System.err.println(unescapeForBNode(escapeForBNode(unescaped))); System.err.println(createBNode(unescaped,"xx78x")); for(String s:parseContextualBNode(createBNode(unescaped,"xx78x"))){ System.err.println(s); } } }
package net.sourceforge.stripes.controller; import net.sourceforge.stripes.action.ActionBean; import net.sourceforge.stripes.action.ActionBeanContext; import net.sourceforge.stripes.action.FileBean; import net.sourceforge.stripes.action.Wizard; import net.sourceforge.stripes.config.Configuration; import net.sourceforge.stripes.exception.StripesRuntimeException; import net.sourceforge.stripes.util.CryptoUtil; import net.sourceforge.stripes.util.HtmlUtil; import net.sourceforge.stripes.util.Log; import net.sourceforge.stripes.util.OgnlUtil; import net.sourceforge.stripes.util.ReflectUtil; import net.sourceforge.stripes.validation.ScopedLocalizableError; import net.sourceforge.stripes.validation.TypeConverter; import net.sourceforge.stripes.validation.Validate; import net.sourceforge.stripes.validation.ValidateNestedProperties; import net.sourceforge.stripes.validation.ValidationError; import net.sourceforge.stripes.validation.ValidationErrors; import ognl.NoSuchPropertyException; import ognl.OgnlException; import javax.servlet.http.HttpServletRequest; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; /** * Implementation of the ActionBeanPropertyBinder interface that uses the OGNL toolkit to perform * the JavaBean property binding. Uses a pair of helper classes (OgnlUtil and OgnlCustomNullHandler) * in order to efficiently manage the fetching and setting of simple, nested, indexed, mapped and * other properties (see Ognl documentation for full syntax and capabilities). When setting * nested properties, if intermediary objects are null, they will be instantiated and linked in to * the object graph to allow the setting of the target property. * * @see net.sourceforge.stripes.util.OgnlCustomNullHandler * @see OgnlUtil * @author Tim Fennell */ public class OgnlActionBeanPropertyBinder implements ActionBeanPropertyBinder { private static Log log = Log.getInstance(OgnlActionBeanPropertyBinder.class); private static Set<String> SPECIAL_KEYS = new HashSet<String>(); static { SPECIAL_KEYS.add(StripesConstants.URL_KEY_SOURCE_PAGE); SPECIAL_KEYS.add(StripesConstants.URL_KEY_FIELDS_PRESENT); SPECIAL_KEYS.add(StripesConstants.URL_KEY_FLASH_SCOPE_ID); } /** Map of validation annotations that is built at startup. */ private Map<Class<? extends ActionBean>, Map<String,Validate>> validations; /** * Map of validation annotations to the set of events they should be run on. Note that * the events may be prepended with "!", so watch out! */ private Map<Validate,Set<String>> validationEventMap; /** Configuration instance passed in at initialization time. */ private Configuration configuration; /** * Looks up and caches in a useful form the metadata necessary to perform validations as * properties are bound to the bean. */ public void init(Configuration configuration) throws Exception { this.configuration = configuration; Set<Class<? extends ActionBean>> beanClasses = ActionClassCache.getInstance().getActionBeanClasses(); this.validations = new HashMap<Class<? extends ActionBean>, Map<String,Validate>>(); this.validationEventMap = new HashMap<Validate,Set<String>>(); for (Class<? extends ActionBean> beanClass : beanClasses) { Map<String, Validate> fieldValidations = new HashMap<String, Validate>(); processClassAnnotations(beanClass, fieldValidations); this.validations.put(beanClass, fieldValidations); // Go through and put the list of events for this validation into // a quicker to access structure for (Validate info : fieldValidations.values()) { Set<String> events = null; if (info.on().length == 0) { events = Collections.emptySet(); } else { events = new HashSet<String>(); for (String event : info.on()) { events.add(event); } } this.validationEventMap.put(info, events); } // Print out a pretty debug message showing what validations got configured StringBuilder builder = new StringBuilder(128); for (Map.Entry<String,Validate> entry : fieldValidations.entrySet()) { if (builder.length() > 0) builder.append(", "); builder.append(entry.getKey()); builder.append("->"); builder.append(ReflectUtil.toString(entry.getValue())); } log.debug("Loaded validations for ActionBean ", beanClass.getSimpleName(), ": ", builder.length() > 0 ? builder : "<none>"); } } /** * Helper method that processes a class looking for validation annotations. Will recurse * and process the superclasses first in order to ensure that annotations lower down the * inheritance hierarchy take precedence over those higher up. * * @param clazz the ActionBean subclasses (or parent thereof) in question * @param fieldValidations a map of fieldname->Validate in which to store validations */ protected void processClassAnnotations(Class clazz, Map<String,Validate> fieldValidations) { Class superclass = clazz.getSuperclass(); if (superclass != null) { processClassAnnotations(superclass, fieldValidations); } // Process the methods on the class Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { if (!Modifier.isPublic(method.getModifiers())) { continue; // only public methods! } Validate validation = method.getAnnotation(Validate.class); if (validation != null) { String fieldName = getPropertyName(method.getName()); fieldValidations.put(fieldName, validation); } ValidateNestedProperties nested = method.getAnnotation(ValidateNestedProperties.class); if (nested != null) { String fieldName = getPropertyName(method.getName()); Validate[] validations = nested.value(); for (Validate nestedValidate : validations) { if ( "".equals(nestedValidate.field()) ) { log.warn("Nested validation used without field name: ", validation); } else { fieldValidations.put(fieldName + "." + nestedValidate.field(), nestedValidate); } } } } // Process the fields for validation annotations Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { Validate validation = field.getAnnotation(Validate.class); if (validation != null) { fieldValidations.put(field.getName(), validation); } ValidateNestedProperties nested = field.getAnnotation(ValidateNestedProperties.class); if (nested != null) { Validate[] validations = nested.value(); for (Validate nestedValidate : validations) { if ( "".equals(nestedValidate.field()) ) { log.warn("Nested validation used without field name: ", validation); } else { fieldValidations.put(field.getName() + "." + nestedValidate.field(), nestedValidate); } } } } } /** * <p>Loops through the parameters contained in the request and attempts to bind each one to the * supplied ActionBean. Invokes validation for each of the properties on the bean before * binding is attempted. Only fields which do not produce validation errors will be bound * to the ActionBean.</p> * * <p>Individual property binding is delegated to the other interface method, * bind(ActionBean, String, Object), in order to allow for easy extension of this class.</p> * * @param bean the ActionBean whose properties are to be validated and bound * @param context the ActionBeanContext of the current request * @param validate true indicates that validation should be run, false indicates that only * type conversion should occur */ public ValidationErrors bind(ActionBean bean, ActionBeanContext context, boolean validate) { ValidationErrors fieldErrors = new ValidationErrors(); // Take the ParameterMap and turn the keys into ParameterNames Map<ParameterName,String[]> parameters = getParameters(context); // Run the required validation first to catch fields that weren't even submitted if (validate) { validateRequiredFields(parameters, bean, fieldErrors); } // First we bind all the regular parameters for (Map.Entry<ParameterName,String[]> entry : parameters.entrySet() ) { List<Object> convertedValues = null; ParameterName name = entry.getKey(); try { if (!SPECIAL_KEYS.contains(name.getName()) && !name.getName().equals(context.getEventName()) && !fieldErrors.containsKey(name.getName()) ) { log.trace("Running binding for property with name: ", name); Class type = OgnlUtil.getPropertyClass(name.getName(), bean); String[] values = entry.getValue(); // Do Validation and type conversion List<ValidationError> errors = new ArrayList<ValidationError>(); Validate validationInfo = this.validations.get(bean.getClass()).get(name.getStrippedName()); // If the property should be ignored, skip to the next property if (validationInfo != null && validationInfo.ignore()) { continue; } if (validate && validationInfo != null) { doPreConversionValidations(name, values, validationInfo, errors); } convertedValues = convert(bean, name, values, type, validationInfo, errors); if (validate && validationInfo != null) { doPostConversionValidations(name, convertedValues, validationInfo, errors); } // If we have errors, save them, otherwise bind the parameter to the form if (errors.size() > 0) { fieldErrors.addAll(name.getName(), errors); } else if (convertedValues.size() > 0) { bindNonNullValue(bean, name.getName(), convertedValues, type); } else { bindNullValue(bean, name.getName(), type); } } } catch (Exception e) { handlePropertyBindingError(bean, name, convertedValues, e, fieldErrors); } } bindMissingValuesAsNull(bean, context); // Then we figure out if any files were uploaded and bind those too StripesRequestWrapper request = StripesRequestWrapper.findStripesWrapper(context.getRequest()); if ( request.isMultipart() ) { Enumeration<String> fileParameterNames = request.getFileParameterNames(); while (fileParameterNames.hasMoreElements()) { String fileParameterName = fileParameterNames.nextElement(); FileBean fileBean = request.getFileParameterValue(fileParameterName); log.trace("Attempting to bind file parameter with name [", fileParameterName, "] and value: ", fileBean); if (fileBean != null) { try { bind(bean, fileParameterName, fileBean); } catch (Exception e) { log.debug(e, "Could not bind file property with name [", fileParameterName, "] and value: ", fileBean); } } } } return fieldErrors; } /** * Invoked whenever an exception is thrown when attempting to bind a property to an * ActionBean. By default logs some information about the occurrence, but could be overridden * to do more intelligent things based on the application. */ protected void handlePropertyBindingError(ActionBean bean, ParameterName name, List<Object> values, Exception e, ValidationErrors errors) { if (e instanceof NoSuchPropertyException) { NoSuchPropertyException nspe = (NoSuchPropertyException) e; log.debug("Could not bind property with name [", name, "] to bean of type: ", bean.getClass().getSimpleName(), " : ", nspe.getReason() == null ? nspe.getMessage() : nspe.getReason().getMessage()); } else { log.debug(e, "Could not bind property with name [", name, "] to bean of type: ", bean.getClass().getSimpleName()); } } /** * Uses a hidden field to deterine what (if any) fields were present in the form but did * not get submitted to the server. For each such field the value is "softly" set to null * on the ActionBean. This is not uncommon for checkboxes, and also for multi-selects. * * @param bean the ActionBean being bound to * @param context the current ActionBeanContext */ protected void bindMissingValuesAsNull(ActionBean bean, ActionBeanContext context) { HttpServletRequest request = context.getRequest(); Set<String> paramatersSubmitted = request.getParameterMap().keySet(); for (String name: getFieldsPresentInfo(bean)) { if (!paramatersSubmitted.contains(name)) { try { bindNullValue(bean, name, OgnlUtil.getPropertyClass(name, bean)); } catch (Exception e) { log.warn(e, "Could not set property '", name, "' to null on ActionBean of", "type '", bean.getClass(), "'."); } } } } /** * In a lot of cases (and specifically during wizards) the Stripes form field writes out * a hidden field containing a set of field names. This is encrypted to stop the user from * monkeying with it. This method retrieves the list of field names, decrypts it and splits * it out into a Collection of field names. * @param bean the current ActionBean * @return a non-null (though possibly empty) list of field names */ protected Collection<String> getFieldsPresentInfo(ActionBean bean) { HttpServletRequest request = bean.getContext().getRequest(); String fieldsPresent = request.getParameter(StripesConstants.URL_KEY_FIELDS_PRESENT); if (fieldsPresent == null || "".equals(fieldsPresent)) { if (bean.getClass().getAnnotation(Wizard.class) != null) { //FIXME: might want to let the ActionBean handle the initial request somehow? throw new StripesRuntimeException( "Submission of a wizard form in Stripes absolutely requires that " + "the hidden field Stripes writes containing the names of the fields " + "present on the form is present and encrypted (as Stripes write it). " + "This is necessary to prevent a user from spoofing the system and " + "getting around any security/data checks." ); } else { return Collections.emptySet(); } } else { fieldsPresent = CryptoUtil.decrypt(fieldsPresent, request); return HtmlUtil.splitValues(fieldsPresent); } } /** * Internal helper method to bind one or more values to a single property on an * ActionBean. If the target type is an array of Collection, then all values are bound. * If the target type is a scalar type then the first value in the List of values is bound. * * @param bean the ActionBean instance to which the property is being bound * @param property the name of the property being bound * @param valueOrValues a List containing one or more values * @param targetType the declared type of the property on the ActionBean * @throws Exception if the property cannot be bound for any reason */ protected void bindNonNullValue(ActionBean bean, String property, List<Object> valueOrValues, Class targetType) throws Exception { Class valueType = valueOrValues.iterator().next().getClass(); // If the target type is an array, set it as one, otherwise set as scalar if (targetType.isArray() && !valueType.isArray()) { OgnlUtil.setValue(property, bean, valueOrValues.toArray()); } else if (Collection.class.isAssignableFrom(targetType) && !Collection.class.isAssignableFrom(valueType)) { Collection collection = null; if (targetType.isInterface()) { collection = (Collection) ReflectUtil.getInterfaceInstance(targetType); } else { collection = (Collection) targetType.newInstance(); } collection.addAll(valueOrValues); OgnlUtil.setValue(property, bean, collection); } else { OgnlUtil.setValue(property, bean, valueOrValues.get(0)); } } /** * Internal helper method that determines what to do when no value was supplied for a * given form field (but the field was present on the page). In all cases if the property * is already null, or intervening objects in a nested property are null, nothing is done. * If the property is non-null, it will be set to null. Unless the property is a collection, * in which case it will be clear()'d. * * @param bean the ActionBean to which properties are being bound * @param property the name of the property being bound * @param type the declared type of the property on the ActionBean * @throws OgnlException if the value cannot be manipulated for any reason */ protected void bindNullValue(ActionBean bean, String property, Class type) throws OgnlException { // If the class is a collection, try fetching it and setting it and clearing it if (Collection.class.isAssignableFrom(type)) { Collection collection = (Collection) OgnlUtil.getValue(property, bean); if (collection != null) { collection.clear(); } } else { OgnlUtil.setNullValue(property, bean); } } /** * Converts the map of parameters in the request into a Map of ParameterName to String[]. */ protected Map<ParameterName, String[]> getParameters(ActionBeanContext context) { Map<String, String[]> requestParameters = context.getRequest().getParameterMap(); Map<ParameterName, String[]> parameters = new HashMap<ParameterName,String[]>(); for (Map.Entry<String,String[]> entry : requestParameters.entrySet()) { parameters.put(new ParameterName(entry.getKey()), entry.getValue()); } return parameters; } /** * Uses Ognl to attempt the setting of the named property on the target bean. If the binding * fails for any reason (property does not exist, type conversion not possible etc.) an * exception will be thrown. * * @param bean the ActionBean on to which the property is to be bound * @param propertyName the name of the property to be bound (simple or complex) * @param propertyValue the value of the target property * @throws Exception thrown if the property cannot be bound for any reason */ public void bind(ActionBean bean, String propertyName, Object propertyValue) throws Exception { OgnlUtil.setValue(propertyName, bean, propertyValue); } /** * Helper method that returns the name of the property when supplied with the corresponding * get or set method. Does not do anything particularly intelligent, just drops the first * three characters and makes the next character lower case. */ protected String getPropertyName(String methodName) { return methodName.substring(3,4).toLowerCase() + methodName.substring(4); } /** * Figures out what is the real type that TypeConversions should target for this property. For * a simple property this will be just the type of the property as declared in the ActionBean. * For Arrays the returned type will be the component type of the array. For collections, if * a TypeConverter has been specified, the target type of the TypeConverter will be returned, * otherwise we will assume that it is a collection of Strings and hope for the best. * * @param bean the ActionBean on which the property exists * @param propertyType the declared type of the property * @param propertyName the name of the property * */ protected Class getRealType(ActionBean bean, Class propertyType, ParameterName propertyName) throws Exception { if (propertyType.isArray()) { propertyType = propertyType.getComponentType(); } else if (Collection.class.isAssignableFrom(propertyType)) { // Try to get the information from the property's return type... propertyType = OgnlUtil.getCollectionPropertyComponentClass(bean, propertyName.getName()); if (propertyType == null) { // We couldn't figure it out from generics, so see if it was specified Map<String, Validate> map = this.validations.get(bean.getClass()); Validate validationInfo = map.get(propertyName.getStrippedName()); if (validationInfo != null && validationInfo.converter() != TypeConverter.class) { Method method = validationInfo.converter().getMethod ("convert", String.class, Class.class, Collection.class); propertyType = method.getReturnType(); } else { log.warn("Unable to determine type of objects held in collection, on ", "ActionBean class [", bean.getClass(), "] property [", propertyName.getName(), "]. To fix this either modify the getter ", "method for this property to use generics, e.g. List<Foo> get(), ", "or specify the appropriate converter in the @Validate annotation ", "for this property on the ActionBean. Assuming type is String, ", "which may or may not work!"); propertyType = String.class; } } } return propertyType; } /** * Validates that all required fields have been submitted. This is done by looping through * the set of validation annotations and checking that each field marked as required * was submitted in the request and submitted with a non-empty value. */ protected void validateRequiredFields(Map<ParameterName,String[]> parameters, ActionBean bean, ValidationErrors errors) { log.debug("Running required field validation on bean class ", bean.getClass().getName()); // Assemble a set of names that we know have indexed parameters, so we won't check // for required-ness the regular way Set<String> indexedParams = new HashSet<String>(); for (ParameterName name : parameters.keySet()) { if (name.isIndexed()) { indexedParams.add(name.getStrippedName()); } } Map<String,Validate> validationInfos = this.validations.get(bean.getClass()); if (validationInfos != null) { boolean wizard = bean.getClass().getAnnotation(Wizard.class) != null; Collection<String> fieldsOnPage = getFieldsPresentInfo(bean); for (Map.Entry<String,Validate> entry : validationInfos.entrySet()) { String propertyName = entry.getKey(); Validate validationInfo = entry.getValue(); // If the field is required, and we don't have index params that collapse // to that property name, check that it was supplied if (validationInfo.required() && !indexedParams.contains(propertyName) && applies(validationInfo, bean.getContext())) { // Make the added check that if the form is a wizard, the required field is // in the set of fields that were on the page if (!wizard || fieldsOnPage.contains(propertyName)) { String[] values = bean.getContext().getRequest().getParameterValues(propertyName); log.debug("Checking required field: ", propertyName, ", with values: ", values); checkSingleRequiredField(propertyName, propertyName, values, errors); } } } } // Now the easy work is done, figure out which rows of indexed props had values submitted // and what to flag up as failing required field validation if (indexedParams.size() > 0) { Map<String,Row> rows = new HashMap<String,Row>(); for (Map.Entry<ParameterName,String[]> entry : parameters.entrySet()) { ParameterName name = entry.getKey(); String[] values = entry.getValue(); if (name.isIndexed()) { String rowKey = name.getName().substring(0, name.getName().indexOf(']')+1); if (!rows.containsKey(rowKey)) { rows.put(rowKey, new Row()); } rows.get(rowKey).put(name, values); } } for (Row row : rows.values()) { if (row.hasNonEmptyValues()) { for (Map.Entry<ParameterName,String[]> entry : row.entrySet()) { ParameterName name = entry.getKey(); String[] values = entry.getValue(); Validate validationInfo = validationInfos.get(name.getStrippedName()); if (validationInfo != null && validationInfo.required() && applies(validationInfo, bean.getContext())) { checkSingleRequiredField (name.getName(), name.getStrippedName(), values, errors); } } } else { // If the row is full of empty data, get rid of it all to // prevent problems in downstream validation for (ParameterName name : row.keySet()) { parameters.remove(name); } } } } } /** * <p>Checks to see if a single field's set of values are 'present', where that is defined * as having one or more values, and where each value is a non-empty String after it has * had white space trimmed from each end.<p> * * <p>For any fields that fail validation, creates a ScopedLocaliableError that uses the * stripped name of the field to find localized info (e.g. foo.bar instead of foo[1].bar). * The error is bound to the actual field on the form though, e.g. foo[1].bar.</p> * * @param name the name of the parameter verbatim from the request * @param strippedName the name of the parameter with any indexing removed from it * @param values the String[] of values that was submitted in the request * @param errors a ValidationErrors object into which errors can be placed */ protected void checkSingleRequiredField(String name, String strippedName, String[] values, ValidationErrors errors) { if (values == null || values.length == 0) { ValidationError error = new ScopedLocalizableError("validation.required", "valueNotPresent"); error.setFieldValue(null); errors.add( name, error ); } else { for (String value : values) { if (value.length() == 0) { ValidationError error = new ScopedLocalizableError("validation.required", "valueNotPresent"); error.setFieldValue(value); errors.add( name, error ); } } } } /** * Performs several basic validations on the String value supplied in the HttpServletRequest, * based on information provided in annotations on the ActionBean. * * @param propertyName the name of the property being validated (used for constructing errors) * @param values the String[] of values from the request being validated * @param validationInfo the Valiate annotation that was decorating the property being validated * @param errors a collection of errors to be populated with any validation errors discovered */ protected void doPreConversionValidations(ParameterName propertyName, String[] values, Validate validationInfo, List<ValidationError> errors) { for (String value : values) { // Only run validations when there are non-empty values if (value != null && value.length() > 0) { if (validationInfo.minlength() != -1 && value.length() < validationInfo.minlength()) { ValidationError error = new ScopedLocalizableError ("validation.minlength", "valueTooShort", validationInfo.minlength()); error.setFieldValue(value); errors.add( error ); } if (validationInfo.maxlength() != -1 && value.length() > validationInfo.maxlength()) { ValidationError error = new ScopedLocalizableError("validation.maxlength", "valueTooLong", validationInfo.maxlength()); error.setFieldValue(value); errors.add( error ); } if ( validationInfo.mask().length() > 0 && !Pattern.compile(validationInfo.mask()).matcher(value).matches() ) { ValidationError error = new ScopedLocalizableError("validation.mask", "valueDoesNotMatch"); error.setFieldValue(value); errors.add( error ); } } } } /** * Performs basic post-conversion validations on the properties of the ActionBean after they * have been converted to their rich type by the type conversion system. Validates single * properties in isolation from other properties. * * @param propertyName the name of the property being validated (used for constructing errors) * @param values the List of converted values - possibly empty but never null * @param validationInfo the Valiate annotation that was decorating the property being validated * @param errors a collection of errors to be populated with any validation errors discovered */ protected void doPostConversionValidations(ParameterName propertyName, List<Object> values, Validate validationInfo, List<ValidationError> errors) { for (Object value : values) { // If the value is a number then we should check to see if there are range boundaries // established, and check them. if (value instanceof Number) { Number number = (Number) value; if (validationInfo.minvalue() != Double.MIN_VALUE && number.doubleValue() < validationInfo.minvalue() ) { ValidationError error = new ScopedLocalizableError("validation.minvalue", "valueBelowMinimum", validationInfo.minvalue()); error.setFieldValue( String.valueOf(value) ); errors.add(error); } if (validationInfo.maxvalue() != Double.MAX_VALUE && number.doubleValue() > validationInfo.maxvalue() ) { ValidationError error = new ScopedLocalizableError("validation.maxvalue", "valueAboveMaximum", validationInfo.maxvalue()); error.setFieldValue( String.valueOf(value) ); errors.add(error); } } } } /** * Determines whether or not a specific validation applies to the current event or not. * * @param info the ValidationInfo being looked at * @param context the current ActionBeanContext * @return true if the Validation should be executed, false otherwise */ protected boolean applies(Validate info, ActionBeanContext context) { Set<String> events = this.validationEventMap.get(info); String current = context.getEventName(); if (info.on().length == 0 || current == null) { return true; } if (info.on()[0].startsWith("!")) { return !events.contains("!" + current); } else { return events.contains(current); } } /** * <p>Converts the String[] of values for a given parameter in the HttpServletRequest into the * desired type of Object. If a converter is declared using an annotation for the property * (or getter/setter) then that converter will be used - if it does not convert to the right * type an exception will be logged and values will not be converted. If no Converter was * specified then a default converter will be looked up based on the target type of the * property. If there is no default converter, then a Constructor will be looked for on the * target type which takes a single String parameter. If such a Constructor exists it will be * invoked.</p> * * <p>Only parameter values that are non-null and do not equal the empty String will be converted * and returned. So an input array with one entry equalling the empty string, [""], will result * in an <b>empty</b> List being returned. Similarly, if a length three array is passed in * with one item equalling the empty String, a List of length two will be returned.</p> * * @param bean the ActionBean on which the property to convert exists * @param values a String array of values to attempt conversion of * @param errors a List into which ValidationError objects will be populated for any errors * discovered during conversion. * @param validationInfo the @Validate annotation for the property if one exists * @return List<Object> a List of objects containing only objects of the desired type. It is * not guaranteed to be the same length as the values array passed in. */ private List<Object> convert(ActionBean bean, ParameterName propertyName, String[] values, Class propertyType, Validate validationInfo, List<ValidationError> errors) throws Exception { List<Object> returns = new ArrayList<Object>(); propertyType = getRealType(bean, propertyType, propertyName); // Dig up the type converter TypeConverter converter = null; if (validationInfo != null && validationInfo.converter() != TypeConverter.class) { converter = this.configuration.getTypeConverterFactory() .getInstance(validationInfo.converter(), bean.getContext().getRequest().getLocale()); } else { converter = this.configuration.getTypeConverterFactory() .getTypeConverter(propertyType, bean.getContext().getRequest().getLocale()); } log.debug("Converting ", values.length, " value(s) using converter ", converter); for (int i=0; i<values.length; ++i) { if (!"".equals(values[i])) { try { Object retval = null; if (converter != null) { retval = converter.convert(values[i], propertyType, errors); } else if (propertyType.isAssignableFrom(String.class)) { retval = values[i]; } else { Constructor constructor = propertyType.getConstructor(String.class); if (constructor != null) { retval = constructor.newInstance(values[i]); } else { log.debug("Could not find a way to convert the parameter ", propertyName.getName(), " to a ", propertyType.getSimpleName(), ". No TypeConverter could be found and the class does not ", "have a constructor that takes a single String parameter."); } } // If we managed to get a non-null converted value, add it to the return set if (retval != null) { returns.add(retval); } // Set the field name and value on the error for (ValidationError error : errors) { error.setFieldName(propertyName.getStrippedName()); error.setFieldValue(values[i]); } } catch(Exception e) { //TODO: figure out what to do, if anything, with these exceptions log.warn(e, "Looks like type converter ", converter, " threw an exception."); } } } return returns; } } class Row extends HashMap<ParameterName,String[]> { private boolean hasNonEmptyValues = false; /** * Adds the value to the map, along the way checking to see if there are any * non-null values for the row so far. */ public String[] put(ParameterName key, String[] values) { if (!hasNonEmptyValues) { hasNonEmptyValues = (values != null) && (values.length > 0) && (values[0] != null) && (values[0].trim().length() > 0); } return super.put(key, values); } /** Returns true if the row had any non-empty values in it, otherwise false. */ public boolean hasNonEmptyValues() { return this.hasNonEmptyValues; } }
package com.splicemachine.derby.impl.load; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.splicemachine.derby.utils.SpliceUtils; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; import org.apache.hadoop.util.StringUtils; import org.apache.log4j.Logger; import javax.annotation.Nullable; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; class ImportFile { private static String IS_DIRECTORY = "isDirectory"; private static String IS_DIR = "isDir"; private static Directory directory; private interface Directory { boolean isDirectory(FileStatus fileStatus) throws IOException; } static { try { FileStatus.class.getMethod(IS_DIRECTORY, null); directory = new Directory() { @Override public boolean isDirectory(FileStatus fileStatus) throws IOException { try { Method method = fileStatus.getClass().getMethod(IS_DIRECTORY, null); return (Boolean) method.invoke(fileStatus, null); } catch (Exception e) { throw new IOException("Error with Hadoop Version, directory lookup off",e); } } }; } catch (NoSuchMethodException e) { directory = new Directory() { @Override public boolean isDirectory(FileStatus fileStatus) throws IOException { try { Method method = fileStatus.getClass().getMethod(IS_DIR, null); return (Boolean) method.invoke(fileStatus, null); } catch (Exception e) { throw new IOException("Error with Hadoop Version, directory lookup off",e); } } }; } } private static final Logger LOG = Logger.getLogger(ImportFile.class); private final String inputPath; private List<FileStatus> fileStatus; ImportFile(String inputPath) { this.inputPath = inputPath; } public List<Path> getPaths() throws IOException { if(fileStatus==null) fileStatus = listStatus(inputPath); return Lists.transform(fileStatus,new Function<FileStatus, Path>() { @Override public Path apply(@Nullable FileStatus fileStatus) { //noinspection ConstantConditions return fileStatus.getPath(); } }); } /** * * @return the total length of this "file", in bytes * @throws IOException if something goes wrong */ public long getTotalLength() throws IOException { if(fileStatus==null) fileStatus = listStatus(inputPath); long length=0l; for(FileStatus status:fileStatus){ length+=status.getLen(); } return length; } private static final PathFilter hiddenFileFilter = new PathFilter(){ public boolean accept(Path p){ String name = p.getName(); return !name.startsWith("_") && !name.startsWith("."); } }; /** * Allows for multiple input paths separated by commas * @param input the input path pattern */ private static Path[] getInputPaths(String input) { String [] list = StringUtils.split(input); Path[] result = new Path[list.length]; for (int i = 0; i < list.length; i++) { result[i] = new Path(StringUtils.unEscapeString(list[i])); } return result; } private static List<FileStatus> listStatus(String input) throws IOException { Path[] dirs = getInputPaths(input); if (dirs.length == 0) throw new IOException("No Path Supplied in job"); List<Path> errors = Lists.newArrayListWithExpectedSize(0); // creates a MultiPathFilter with the hiddenFileFilter and the // user provided one (if any). List<PathFilter> filters = new ArrayList<PathFilter>(); filters.add(hiddenFileFilter); PathFilter inputFilter = new MultiPathFilter(filters); List<FileStatus> result = Lists.newArrayListWithExpectedSize(dirs.length); for (Path p : dirs) { FileSystem fs = FileSystem.get(SpliceUtils.config); FileStatus[] matches = fs.globStatus(p, inputFilter); if (matches == null) { errors.add(p); } else if (matches.length == 0) { errors.add(p); } else { for (FileStatus globStat : matches) { if (directory.isDirectory(globStat)) { Collections.addAll(result, fs.listStatus(globStat.getPath(), inputFilter)); } else { result.add(globStat); } } } } if (!errors.isEmpty()) { throw new FileNotFoundException(errors.toString()); } LOG.info("Total input paths to process : " + result.size()); return result; } private static class MultiPathFilter implements PathFilter { private List<PathFilter> filters; public MultiPathFilter(List<PathFilter> filters) { this.filters = filters; } public boolean accept(Path path) { for (PathFilter filter : filters) { if (!filter.accept(path)) { return false; } } return true; } } }
/** Khalid */ package org.sikuli.slides.utils; import java.awt.Desktop; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URI; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Utils { private static final Logger logger = (Logger) LoggerFactory.getLogger(Utils.class); /* * Get the extension of a file. */ public static String getExtension(File f) { String ext = null; String s = f.getName(); int i = s.lastIndexOf('.'); if (i > 0 && i < s.length() - 1) { ext = s.substring(i+1).toLowerCase(); } return ext; } public static boolean createWorkingDirectory(){ File tmpDirectory, workingDirectory; try{ tmpDirectory=FileUtils.getTempDirectory(); } catch(IllegalStateException e){ return false; } if (tmpDirectory.exists()) { workingDirectory=new File(tmpDirectory.getAbsoluteFile()+File.separator+Constants.SIKULI_SLIDES_ROOT_DIRECTORY); Constants.workingDirectoryPath=workingDirectory.getAbsolutePath(); if(workingDirectory.exists()){ return true; } else if(workingDirectory.mkdir()){ return true; } else{ return false; } } else{ return false; } } public static void doZipFile(File file){ byte[] buffer = new byte[1024]; try{ FileOutputStream fos = new FileOutputStream(Constants.workingDirectoryPath+File.separator+file.getName()+".zip"); ZipOutputStream zos = new ZipOutputStream(fos); ZipEntry ze= new ZipEntry(file.getName()); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(file.getAbsolutePath()); int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); zos.closeEntry(); zos.close(); }catch(IOException ex){ ex.printStackTrace(); } } public static void doUnZipFile(File file){ byte[] buffer = new byte[1024]; try{ //create output directory File folder = new File(Constants.workingDirectoryPath+File.separator+file.getName().substring(0, file.getName().indexOf('.'))); // if the directory doesn't exist, create it if(!folder.exists()){ folder.mkdir(); } // if the directory already exists, delete it and recreate it. else{ FileUtils.deleteDirectory(folder); folder.mkdir(); } // Next, unzip it. //get the zip file content ZipInputStream zis = new ZipInputStream(new FileInputStream(file.getAbsoluteFile())); //get the zipped file list entry ZipEntry ze = zis.getNextEntry(); while(ze!=null){ String fileName = ze.getName(); File newFile = new File(folder + File.separator + fileName); //create all non exists folders //else you will hit FileNotFoundException for compressed folder new File(newFile.getParent()).mkdirs(); FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); //delete the zip file since we no longer need it. File zipFile = new File(Constants.workingDirectoryPath+File.separator+file.getName()+".zip"); if(zipFile.delete()) return; else logger.error("Couldn't delete zip: "+Constants.workingDirectoryPath+File.separator+file.getName()+".zip"); } catch(IOException ex){ ex.printStackTrace(); } } public static void createSikuliImagesDirectory(){ //create sikuli directory File folder = new File(Constants.projectDirectory+File.separator+Constants.SIKULI_DIRECTORY); //create sikuli images directory File imagesFolder = new File(Constants.projectDirectory+File.separator+Constants.SIKULI_DIRECTORY+File.separator+Constants.IMAGES_DIRECTORY); // if the directory doesn't exist, create it if(!folder.exists()){ folder.mkdir(); imagesFolder.mkdir(); } } /** * Open a new URL in the default web browser * @param uri */ public static void openURLInBrowser(String URLString) { try { URI uri = new URI(URLString); Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null; if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) { desktop.browse(uri); } } catch (Exception e) { logger.error("Failed to open the following URL: "+ URLString); } } }
package org.tap4j.plugin; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.annotation.Nonnull; import org.apache.commons.lang.BooleanUtils; import org.kohsuke.stapler.DataBoundConstructor; import org.tap4j.model.Plan; import org.tap4j.model.TestSet; import org.tap4j.plugin.model.TestSetMap; import org.tap4j.plugin.util.Constants; import hudson.EnvVars; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.Util; import hudson.matrix.MatrixAggregatable; import hudson.matrix.MatrixAggregator; import hudson.matrix.MatrixBuild; import hudson.model.AbstractProject; import hudson.model.Action; import hudson.model.BuildListener; import hudson.model.Result; import hudson.model.Run; import hudson.model.TaskListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Publisher; import hudson.tasks.Recorder; import hudson.tasks.test.TestResultAggregator; import jenkins.tasks.SimpleBuildStep; public class TapPublisher extends Recorder implements MatrixAggregatable, SimpleBuildStep { private final String testResults; private final Boolean failIfNoResults; private final Boolean failedTestsMarkBuildAsFailure; private final Boolean outputTapToConsole; private final Boolean enableSubtests; private final Boolean discardOldReports; private final Boolean todoIsFailure; private final Boolean includeCommentDiagnostics; private final Boolean validateNumberOfTests; private final Boolean planRequired; private final Boolean verbose; private final Boolean showOnlyFailures; private final Boolean stripSingleParents; private final Boolean flattenTapResult; private final Boolean skipIfBuildNotOk; @Deprecated public TapPublisher(String testResults, Boolean failIfNoResults, Boolean failedTestsMarkBuildAsFailure, Boolean outputTapToConsole, Boolean enableSubtests, Boolean discardOldReports, Boolean todoIsFailure, Boolean includeCommentDiagnostics, Boolean validateNumberOfTests, Boolean planRequired, Boolean verbose) { this(testResults, failIfNoResults, failedTestsMarkBuildAsFailure, outputTapToConsole, enableSubtests, discardOldReports, todoIsFailure, includeCommentDiagnostics, validateNumberOfTests, planRequired, verbose, Boolean.FALSE); } @Deprecated public TapPublisher(String testResults, Boolean failIfNoResults, Boolean failedTestsMarkBuildAsFailure, Boolean outputTapToConsole, Boolean enableSubtests, Boolean discardOldReports, Boolean todoIsFailure, Boolean includeCommentDiagnostics, Boolean validateNumberOfTests, Boolean planRequired, Boolean verbose, Boolean showOnlyFailures) { this(testResults, failIfNoResults, failedTestsMarkBuildAsFailure, outputTapToConsole, enableSubtests, discardOldReports, todoIsFailure, includeCommentDiagnostics, validateNumberOfTests, planRequired, verbose, Boolean.FALSE, Boolean.FALSE); } @Deprecated public TapPublisher(String testResults, Boolean failIfNoResults, Boolean failedTestsMarkBuildAsFailure, Boolean outputTapToConsole, Boolean enableSubtests, Boolean discardOldReports, Boolean todoIsFailure, Boolean includeCommentDiagnostics, Boolean validateNumberOfTests, Boolean planRequired, Boolean verbose, Boolean showOnlyFailures, Boolean stripSingleParents) { this(testResults, failIfNoResults, failedTestsMarkBuildAsFailure, outputTapToConsole, enableSubtests, discardOldReports, todoIsFailure, includeCommentDiagnostics, validateNumberOfTests, planRequired, verbose, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE); } @Deprecated public TapPublisher(String testResults, Boolean failIfNoResults, Boolean failedTestsMarkBuildAsFailure, Boolean outputTapToConsole, Boolean enableSubtests, Boolean discardOldReports, Boolean todoIsFailure, Boolean includeCommentDiagnostics, Boolean validateNumberOfTests, Boolean planRequired, Boolean verbose, Boolean showOnlyFailures, Boolean stripSingleParents, Boolean flattenTapResult) { this(testResults, failIfNoResults, failedTestsMarkBuildAsFailure, outputTapToConsole, enableSubtests, discardOldReports, todoIsFailure, includeCommentDiagnostics, validateNumberOfTests, planRequired, verbose, showOnlyFailures, stripSingleParents, flattenTapResult, Boolean.FALSE); } @DataBoundConstructor public TapPublisher(String testResults, Boolean failIfNoResults, Boolean failedTestsMarkBuildAsFailure, Boolean outputTapToConsole, Boolean enableSubtests, Boolean discardOldReports, Boolean todoIsFailure, Boolean includeCommentDiagnostics, Boolean validateNumberOfTests, Boolean planRequired, Boolean verbose, Boolean showOnlyFailures, Boolean stripSingleParents, Boolean flattenTapResult, Boolean skipIfBuildNotOk) { this.testResults = testResults; this.failIfNoResults = BooleanUtils.toBooleanDefaultIfNull(failIfNoResults, false); this.failedTestsMarkBuildAsFailure = BooleanUtils.toBooleanDefaultIfNull(failedTestsMarkBuildAsFailure, false); this.outputTapToConsole = BooleanUtils.toBooleanDefaultIfNull(outputTapToConsole, true); this.enableSubtests = BooleanUtils.toBooleanDefaultIfNull(enableSubtests, true); this.discardOldReports = BooleanUtils.toBooleanDefaultIfNull(discardOldReports, false); this.todoIsFailure = BooleanUtils.toBooleanDefaultIfNull(todoIsFailure, true); this.includeCommentDiagnostics = BooleanUtils.toBooleanDefaultIfNull(includeCommentDiagnostics, true); this.validateNumberOfTests = BooleanUtils.toBooleanDefaultIfNull(validateNumberOfTests, false); this.planRequired = BooleanUtils.toBooleanDefaultIfNull(planRequired, true); // true is the old behaviour this.verbose = BooleanUtils.toBooleanDefaultIfNull(verbose, true); this.showOnlyFailures = BooleanUtils.toBooleanDefaultIfNull(showOnlyFailures, false); this.stripSingleParents = BooleanUtils.toBooleanDefaultIfNull(stripSingleParents, false); this.flattenTapResult = BooleanUtils.toBooleanDefaultIfNull(flattenTapResult, false); this.skipIfBuildNotOk = BooleanUtils.toBooleanDefaultIfNull(skipIfBuildNotOk, false); } public Object readResolve() { final String _testResults = this.getTestResults(); final Boolean _failIfNoResults = BooleanUtils.toBooleanDefaultIfNull(this.getFailIfNoResults(), false); final Boolean _failedTestsMarkBuildAsFailure = BooleanUtils.toBooleanDefaultIfNull(this.getFailedTestsMarkBuildAsFailure(), false); final Boolean _outputTapToConsole = BooleanUtils.toBooleanDefaultIfNull(this.getOutputTapToConsole(), false); final Boolean _enableSubtests = BooleanUtils.toBooleanDefaultIfNull(this.getEnableSubtests(), true); final Boolean _discardOldReports = BooleanUtils.toBooleanDefaultIfNull(this.getDiscardOldReports(), false); final Boolean _todoIsFailure = BooleanUtils.toBooleanDefaultIfNull(this.getTodoIsFailure(), true); final Boolean _includeCommentDiagnostics = BooleanUtils.toBooleanDefaultIfNull(this.getIncludeCommentDiagnostics(), true); final Boolean _validateNumberOfTests = BooleanUtils.toBooleanDefaultIfNull(this.getValidateNumberOfTests(), false); final Boolean _planRequired = BooleanUtils.toBooleanDefaultIfNull(this.getPlanRequired(), true); final Boolean _verbose = BooleanUtils.toBooleanDefaultIfNull(this.getVerbose(), true); final Boolean _showOnlyFailures = BooleanUtils.toBooleanDefaultIfNull(this.getShowOnlyFailures(), false); final Boolean _stripSingleParents = BooleanUtils.toBooleanDefaultIfNull(this.getStripSingleParents(), false); final Boolean _flattenTapResult = BooleanUtils.toBooleanDefaultIfNull(this.getFlattenTapResult(), false); return new TapPublisher( _testResults, _failIfNoResults, _failedTestsMarkBuildAsFailure, _outputTapToConsole, _enableSubtests, _discardOldReports, _todoIsFailure, _includeCommentDiagnostics, _validateNumberOfTests, _planRequired, _verbose, _showOnlyFailures, _stripSingleParents, _flattenTapResult); } public Boolean getShowOnlyFailures() { return this.showOnlyFailures; } public Boolean getStripSingleParents() { return this.stripSingleParents; } /** * @return the failIfNoResults */ public Boolean getFailIfNoResults() { return failIfNoResults; } /** * @return the testResults */ public String getTestResults() { return testResults; } public Boolean getFailedTestsMarkBuildAsFailure() { return failedTestsMarkBuildAsFailure; } /** * @return the outputTapToConsole */ public Boolean getOutputTapToConsole() { return outputTapToConsole; } /** * @return the enableSubtests */ public Boolean getEnableSubtests() { return enableSubtests; } /** * @return the discardOldReports */ public Boolean getDiscardOldReports() { return discardOldReports; } /** * @return the todoIsFailure */ public Boolean getTodoIsFailure() { return todoIsFailure; } /** * @return the includeCommentDiagnostics */ public Boolean getIncludeCommentDiagnostics() { return includeCommentDiagnostics; } public Boolean getValidateNumberOfTests() { return validateNumberOfTests; } public Boolean getPlanRequired() { return planRequired; } public Boolean getVerbose() { return verbose; } public Boolean getFlattenTapResult() { return flattenTapResult; } public Boolean getSkipIfBuildNotOk() { return skipIfBuildNotOk; } /** * Gets the directory where the plug-in saves its TAP streams before processing them and * displaying in the UI. * <p> * Adapted from JUnit Attachments Plug-in. * * @param build Jenkins build * @return virtual directory (FilePath) */ public static FilePath getReportsDirectory(Run build) { return new FilePath(new File(build.getRootDir().getAbsolutePath())).child(Constants.TAP_DIR_NAME); } /* * (non-Javadoc) * * @see * hudson.tasks.BuildStepCompatibilityLayer#getProjectAction(hudson.model * .AbstractProject) */ @Override public Action getProjectAction(AbstractProject<?, ?> project) { return new TapProjectAction(project); } /* * (non-Javadoc) * * @see * hudson.tasks.BuildStepCompatibilityLayer#perform(hudson.model.AbstractBuild * , hudson.Launcher, hudson.model.BuildListener) */ @Override public void perform( @Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException { performImpl(run, workspace, listener); } private boolean performImpl(Run<?, ?> build, FilePath workspace, TaskListener listener) throws IOException, InterruptedException { final PrintStream logger = listener.getLogger(); if (isPerformPublisher(build)) { logger.println("TAP Reports Processing: START"); EnvVars envVars = build.getEnvironment(listener); String antPattern = Util.replaceMacro(this.testResults, envVars); logger.println("Looking for TAP results report in workspace using pattern: " + antPattern); FilePath[] reports = locateReports(workspace, antPattern); /* * filter out the reports based on timestamps. See JENKINS-12187 */ if (this.getDiscardOldReports()) { reports = checkReports(build, reports, logger); } if (reports.length == 0) { if(this.getFailIfNoResults()) { logger.println("Did not find any matching files. Setting build result to FAILURE."); build.setResult(Result.FAILURE); return Boolean.FALSE; } else { logger.println("Did not find any matching files."); // build can still continue return Boolean.TRUE; } } boolean filesSaved = saveReports(workspace, TapPublisher.getReportsDirectory(build), reports, logger); if (!filesSaved) { logger.println("Failed to save TAP reports"); return Boolean.TRUE; } TapResult testResult = null; try { testResult = loadResults(antPattern, build, logger); testResult.setShowOnlyFailures(this.getShowOnlyFailures()); testResult.tally(); } catch (Throwable t) { /* * don't fail build if TAP parser barfs. only print out the * exception to console. */ t.printStackTrace(logger); } TapTestResultAction trAction = build.getAction(TapTestResultAction.class); boolean appending; if (trAction == null) { appending = false; trAction = new TapTestResultAction(build, testResult); } else { appending = true; trAction.mergeResult(testResult); } if (!appending) { build.addAction(trAction); } if (testResult.getTestSets().size() > 0 || testResult.getParseErrorTestSets().size() > 0) { // create an individual report for all of the results and add it to // the build TapBuildAction action = build.getAction(TapBuildAction.class); if (action == null) { action = new TapBuildAction(build, testResult); build.addAction(action); } else { appending = true; action.mergeResult(testResult); } if (testResult.hasParseErrors()) { listener.getLogger().println("TAP parse errors found in the build. Marking build as UNSTABLE"); build.setResult(Result.UNSTABLE); } if (this.getValidateNumberOfTests()) { if (!this.validateNumberOfTests(testResult.getTestSets())) { listener.getLogger().println("Not all test cases were executed according to the test set plan. Marking build as UNSTABLE"); build.setResult(Result.UNSTABLE); } } if (testResult.getFailed() > 0) { if(this.getFailedTestsMarkBuildAsFailure()) { listener.getLogger().println("There are failed test cases and the job is configured to mark the build as failure. Marking build as FAILURE"); build.setResult(Result.FAILURE); } else { listener.getLogger().println("There are failed test cases. Marking build as UNSTABLE"); build.setResult(Result.UNSTABLE); } } if (appending) { build.save(); } } else { logger.println("Found matching files but did not find any TAP results."); return Boolean.TRUE; } logger.println("TAP Reports Processing: FINISH"); } else { logger.println("Build result is not better or equal unstable. Skipping TAP publisher."); } return Boolean.TRUE; } /** * Return {@code true} if the build is ongoing, if the user did not ask to fail when * failed, or otherwise if the build result is not better or equal to unstable. * @param build Run * @return whether to perform the publisher or not, based on user provided configuration */ private boolean isPerformPublisher(Run<?, ?> build) { Result result = build.getResult(); // may be null if build is ongoing if (result == null) { return true; } if (!getSkipIfBuildNotOk()) { return true; } return result.isBetterOrEqualTo(Result.UNSTABLE); } /** * Iterates through the list of test sets and validates its plans and * test results. * * @param testSets * @return <true> if there are any test case that doesn't follow the plan */ private boolean validateNumberOfTests(List<TestSetMap> testSets) { for (TestSetMap testSetMap : testSets) { TestSet testSet = testSetMap.getTestSet(); Plan plan = testSet.getPlan(); if (plan != null) { int planned = plan.getLastTestNumber(); int numberOfTests = testSet.getTestResults().size(); if (planned != numberOfTests) return false; } } return true; } /** * @param owner * @param logger * @return */ private TapResult loadResults(String antPattern, Run owner, PrintStream logger) { final FilePath tapDir = TapPublisher.getReportsDirectory(owner); FilePath[] results; TapResult tr; try { results = tapDir.list(antPattern); final TapParser parser = new TapParser(getOutputTapToConsole(), getEnableSubtests(), getTodoIsFailure(), getIncludeCommentDiagnostics(), getValidateNumberOfTests(), getPlanRequired(), getVerbose(), getStripSingleParents(), getFlattenTapResult(), logger); final TapResult result = parser.parse(results, owner); result.setOwner(owner); return result; } catch (Exception e) { e.printStackTrace(logger); tr = new TapResult("", owner, Collections.<TestSetMap>emptyList(), getTodoIsFailure(), getIncludeCommentDiagnostics(), getValidateNumberOfTests()); tr.setOwner(owner); return tr; } } /** * @param workspace * @param tapDir * @param reports * @param logger * @return */ private boolean saveReports(FilePath workspace, FilePath tapDir, FilePath[] reports, PrintStream logger) { logger.println("Saving reports..."); try { tapDir.mkdirs(); for (FilePath report : reports) { //FilePath dst = tapDir.child(report.getName()); FilePath dst = getDistDir(workspace, tapDir, report); report.copyTo(dst); } } catch (Exception e) { e.printStackTrace(logger); return false; } return true; } /** * Used to maintain the directory structure when persisting to the tap-reports dir. * * @param workspace Jenkins WS * @param tapDir tap reports dir * @param orig original directory * @return persisted directory virtual structure */ private FilePath getDistDir(FilePath workspace, FilePath tapDir, FilePath orig) { if(orig == null) return null; StringBuilder difference = new StringBuilder(); FilePath parent = orig.getParent(); do { if(parent.equals(workspace)) break; difference.insert(0, parent.getName() + File.separatorChar); } while((parent = parent.getParent()) !=null); difference.append(orig.getName()); return tapDir.child(difference.toString()); } /** * Checks that there are new report files. * * @param build * @param reports * @param logger * @return */ private FilePath[] checkReports(Run build, FilePath[] reports, PrintStream logger) { List<FilePath> filePathList = new ArrayList<FilePath>(reports.length); for (FilePath report : reports) { /* * Check that the file was created as part of this build and is not * something left over from before. * * Checks that the last modified time of file is greater than the * start time of the build */ try { /* * dividing by 1000 and comparing because we want to compare * secs and not milliseconds */ if (build.getTimestamp().getTimeInMillis() / 1000 <= report.lastModified() / 1000) { filePathList.add(report); } else { logger.println(report.getName() + " was last modified before " + "this build started. Ignoring it."); } } catch (IOException e) { // just log the exception e.printStackTrace(logger); } catch (InterruptedException e) { // just log the exception e.printStackTrace(logger); } } return filePathList.toArray(new FilePath[] {}); } /** * @param workspace * @param testResults * @return * @throws InterruptedException * @throws IOException */ private FilePath[] locateReports(FilePath workspace, String testResults) throws IOException, InterruptedException { return workspace.list(testResults); } /* * (non-Javadoc) * * @see hudson.tasks.BuildStep#getRequiredMonitorService() */ public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; } // matrix jobs and test result aggregation support /* (non-Javadoc) * @see hudson.matrix.MatrixAggregatable#createAggregator(hudson.matrix.MatrixBuild, hudson.Launcher, hudson.model.BuildListener) */ public MatrixAggregator createAggregator(MatrixBuild build, Launcher launcher, BuildListener listener) { return new TestResultAggregator(build, launcher, listener); } @Extension public static class DescriptorImpl extends BuildStepDescriptor<Publisher> { public DescriptorImpl() { super(TapPublisher.class); load(); } @Override public String getDisplayName() { return "Publish TAP Results"; } /* * (non-Javadoc) * * @see hudson.tasks.BuildStepDescriptor#isApplicable(java.lang.Class) */ @Override public boolean isApplicable(@SuppressWarnings("rawtypes") Class<? extends AbstractProject> jobType) { return Boolean.TRUE; } } }
package net.sf.mzmine.chartbasics; import java.awt.Dimension; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.logging.Logger; import org.jfree.chart.ChartRenderingInfo; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.Axis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.entity.AxisEntity; import org.jfree.chart.entity.ChartEntity; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.fx.ChartCanvas; import org.jfree.chart.fx.ChartViewer; import org.jfree.chart.plot.CombinedDomainXYPlot; import org.jfree.chart.plot.CombinedRangeXYPlot; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.plot.Zoomable; import org.jfree.chart.ui.RectangleEdge; import org.jfree.data.Range; /** * Collection of methods for JFreeCharts <br> * Calculate mouseXY to plotXY <br> * Calc width and height for plots where domain and range axis share the same dimensions <br> * Zoom and shift axes by absolute or relative values * * @author Robin Schmid (robinschmid@uni-muenster.de) */ public class ChartLogicsFX { private static Logger logger = Logger.getLogger(ChartLogicsFX.class.getName()); /** * Translates mouse coordinates to chart coordinates (xy-axis) * * @param myChart * @param mouseX * @param mouseY * @return Range as chart coordinates */ public static Point2D mouseXYToPlotXY(ChartViewer myChart, double mouseX, double mouseY) { return mouseXYToPlotXY(myChart, (int) mouseX, (int) mouseY); } /** * Translates mouse coordinates to chart coordinates (xy-axis) * * @param myChart * @param mouseX * @param mouseY * @return Range as chart coordinates (never null) */ public static Point2D mouseXYToPlotXY(ChartViewer myChart, int mouseX, int mouseY) { XYPlot plot = null; // find plot as parent of axis ChartEntity entity = findChartEntity(myChart.getCanvas(), mouseX, mouseY); if(entity instanceof AxisEntity) { Axis a = ((AxisEntity)entity).getAxis(); if(a.getPlot() instanceof XYPlot) plot = (XYPlot) a.getPlot(); } ChartRenderingInfo info = myChart.getRenderingInfo(); int subplot = info.getPlotInfo().getSubplotIndex(new Point2D.Double(mouseX, mouseY)); Rectangle2D dataArea = info.getPlotInfo().getDataArea(); if(subplot!=-1) dataArea = info.getPlotInfo().getSubplotInfo(subplot).getDataArea(); // find subplot or plot if(plot==null) plot = findXYSubplot(myChart.getChart(), info, mouseX, mouseY); // find axis ValueAxis domainAxis = plot.getDomainAxis(); ValueAxis rangeAxis = plot.getRangeAxis(); RectangleEdge domainAxisEdge = plot.getDomainAxisEdge(); RectangleEdge rangeAxisEdge = plot.getRangeAxisEdge(); // parent? if(domainAxis==null && plot.getParent()!=null && plot.getParent() instanceof XYPlot) { XYPlot pp = ((XYPlot) plot.getParent()); domainAxis = pp.getDomainAxis(); domainAxisEdge = pp.getDomainAxisEdge(); } if(rangeAxis==null && plot.getParent()!=null && plot.getParent() instanceof XYPlot) { XYPlot pp = ((XYPlot) plot.getParent()); rangeAxis = pp.getRangeAxis(); rangeAxisEdge = pp.getRangeAxisEdge(); } double cx = 0; double cy = 0; if (domainAxis != null) cx = domainAxis.java2DToValue(mouseX, dataArea, domainAxisEdge); if (rangeAxis != null) cy = rangeAxis.java2DToValue(mouseY, dataArea, rangeAxisEdge); return new Point2D.Double(cx,cy); } /** * Find chartentities like JFreeChartEntity, AxisEntity, PlotEntity, TitleEntity, XY... * * @param chart * @return */ public static ChartEntity findChartEntity(ChartCanvas chart, double mx, double my) { // TODO check if insets were needed // coordinates to find chart entities int x = (int) (mx/ chart.getScaleX()); int y = (int) (my / chart.getScaleY()); ChartRenderingInfo info = chart.getRenderingInfo(); ChartEntity entity = null; if (info != null) { EntityCollection entities = info.getEntityCollection(); if (entities != null) { entity = entities.getEntity(x, y); } } return entity; } /** * Subplot or main plot at point * @param chart * @param info * @param mouseX * @param mouseY * @return */ private static XYPlot findXYSubplot(JFreeChart chart, ChartRenderingInfo info, int mouseX, int mouseY) { int subplot = info.getPlotInfo().getSubplotIndex(new Point2D.Double(mouseX, mouseY)); XYPlot plot = null; if(subplot!=-1) { if(chart.getPlot() instanceof CombinedDomainXYPlot) plot = (XYPlot) ((CombinedDomainXYPlot)chart.getPlot()).getSubplots().get(subplot); else if(chart.getPlot() instanceof CombinedRangeXYPlot) plot = (XYPlot) ((CombinedRangeXYPlot)chart.getPlot()).getSubplots().get(subplot); } else if(chart.getPlot() instanceof XYPlot) plot = (XYPlot) chart.getPlot(); return plot; } /** * Translates screen (pixel) values to plot values * * @param myChart * @return width in data space for x and y */ public static Point2D screenValueToPlotValue(ChartViewer myChart, int val) { Point2D p = mouseXYToPlotXY(myChart, 0, 0); Point2D p2 = mouseXYToPlotXY(myChart, val, val); // inverted y return new Point2D.Double(p2.getX() - p.getX(), p.getY() - p2.getY()); } /** * Data width to pixel width on screen * * @param myChart * @param dataWidth width of data * @param axis for width calculation * @return */ public static double calcWidthOnScreen(ChartViewer myChart, double dataWidth, ValueAxis axis, RectangleEdge axisEdge) { XYPlot plot = (XYPlot) myChart.getChart().getPlot(); ChartRenderingInfo info = myChart.getRenderingInfo(); Rectangle2D dataArea = info.getPlotInfo().getDataArea(); // width 2D return axis.lengthToJava2D(dataWidth, dataArea, axisEdge); } /** * Calculates the size of a chart for a given fixed plot width Domain and Range axes need to share * the same unit (e.g. mm) * * @param chart * @param width * @return */ public static Dimension calcSizeForPlotWidth(ChartViewer myChart, double plotWidth) { return calcSizeForPlotWidth(myChart, plotWidth, 4); } /** * Calculates the size of a chart for a given fixed plot width Domain and Range axes need to share * the same unit (e.g. mm) * * @param chart * @param plotWidth * @return */ public static Dimension calcSizeForPlotWidth(ChartViewer myChart, double plotWidth, int iterations) { // ranges XYPlot plot = (XYPlot) myChart.getChart().getPlot(); ValueAxis domainAxis = plot.getDomainAxis(); Range x = domainAxis.getRange(); ValueAxis rangeAxis = plot.getRangeAxis(); Range y = rangeAxis.getRange(); // plot height is fixed double plotHeight = plotWidth / x.getLength() * y.getLength(); return calcSizeForPlotSize(myChart, plotWidth, plotHeight, iterations); } /** * Calculates the size of a chart for a given fixed plot width and height * * @param chart * @param plotWidth * @return */ public static Dimension calcSizeForPlotSize(ChartViewer myChart, double plotWidth, double plotHeight) { return calcSizeForPlotSize(myChart, plotWidth, plotHeight, 4); } /** * Calculates the size of a chart for a given fixed plot width and height * * @param chart * @param plotWidth * @return */ public static Dimension calcSizeForPlotSize(ChartViewer myChart, double plotWidth, double plotHeight, int iterations) { makeChartResizable(myChart); // estimate plotwidth / height double estimatedChartWidth = plotWidth + 200; double estimatedChartHeight = plotHeight + 200; double lastW = estimatedChartWidth; double lastH = estimatedChartHeight; // paint and get closer try { for (int i = 0; i < iterations; i++) { // paint on ghost panel with estimated height (if copy panel==true) myChart.getCanvas().setWidth((int) estimatedChartWidth); myChart.getCanvas().setHeight((int) estimatedChartHeight); myChart.getCanvas().draw(); // rendering info ChartRenderingInfo info = myChart.getRenderingInfo(); Rectangle2D dataArea = info.getPlotInfo().getDataArea(); Rectangle2D chartArea = info.getChartArea(); // // calc title space: will be added later to the right plot size // double titleWidth = chartArea.getWidth()-dataArea.getWidth(); // double titleHeight = chartArea.getHeight()-dataArea.getHeight(); // calc width and height estimatedChartWidth = estimatedChartWidth - dataArea.getWidth() + plotWidth; estimatedChartHeight = estimatedChartHeight - dataArea.getHeight() + plotHeight; if ((int) lastW == (int) estimatedChartWidth && (int) lastH == (int) estimatedChartHeight) break; else { lastW = estimatedChartWidth; lastH = estimatedChartHeight; } } } catch (Exception ex) { ex.printStackTrace(); } return new Dimension((int) estimatedChartWidth, (int) estimatedChartHeight); } /** * calls this method twice (2 iterations) with an estimated chartHeight of 3*chartWidth Domain and * Range axes need to share the same unit (e.g. mm) * * @param myChart * @param dataWidth width of data * @param axis for width calculation * @return */ public static double calcHeightToWidth(ChartViewer myChart, double chartWidth) { return calcHeightToWidth(myChart, chartWidth, chartWidth * 3, 4); } /** * calculates the correct height with multiple iterations Domain and Range axes need to share the * same unit (e.g. mm) * * @param myChart * @param dataWidth width of data * @param axis for width calculation * @return */ public static double calcHeightToWidth(ChartViewer myChart, double chartWidth, double estimatedHeight, int iterations) { // if(myChart.getChartRenderingInfo()==null || // myChart.getChartRenderingInfo().getChartArea()==null || // myChart.getChartRenderingInfo().getChartArea().getWidth()==0) // result double height = estimatedHeight; double lastH = height; makeChartResizable(myChart); try { for (int i = 0; i < iterations; i++) { // paint on ghost panel with estimated height (if copy panel==true) myChart.getCanvas().setWidth((int) chartWidth); myChart.getCanvas().setHeight((int) estimatedHeight); myChart.getCanvas().draw(); XYPlot plot = (XYPlot) myChart.getChart().getPlot(); ChartRenderingInfo info = myChart.getRenderingInfo(); Rectangle2D dataArea = info.getPlotInfo().getDataArea(); Rectangle2D chartArea = info.getChartArea(); // calc title space: will be added later to the right plot size double titleWidth = chartArea.getWidth() - dataArea.getWidth(); double titleHeight = chartArea.getHeight() - dataArea.getHeight(); // calc right plot size with axis dim. // real plot width is given by factor; double realPW = chartWidth - titleWidth; // ranges ValueAxis domainAxis = plot.getDomainAxis(); org.jfree.data.Range x = domainAxis.getRange(); ValueAxis rangeAxis = plot.getRangeAxis(); org.jfree.data.Range y = rangeAxis.getRange(); // real plot height can be calculated by double realPH = realPW / x.getLength() * y.getLength(); // the real height height = realPH + titleHeight; // for next iteration estimatedHeight = height; if ((int) lastH == (int) height) break; else lastH = height; } } catch (Exception ex) { ex.printStackTrace(); } return height; } /** * Removes draw size restrictions * * @param myChart */ public static void makeChartResizable(ChartViewer myChart) { // TODO set max and min sizes } /** * * Domain and Range axes need to share the same unit (e.g. mm) * * @param myChart * @return */ public static double calcWidthToHeight(ChartViewer myChart, double chartHeight) { makeChartResizable(myChart); myChart.getCanvas().draw(); XYPlot plot = (XYPlot) myChart.getChart().getPlot(); ChartRenderingInfo info = myChart.getRenderingInfo(); Rectangle2D dataArea = info.getPlotInfo().getDataArea(); Rectangle2D chartArea = info.getChartArea(); // calc title space: will be added later to the right plot size double titleWidth = chartArea.getWidth() - dataArea.getWidth(); double titleHeight = chartArea.getHeight() - dataArea.getHeight(); // calc right plot size with axis dim. // real plot width is given by factor; double realPH = chartHeight - titleHeight; // ranges ValueAxis domainAxis = plot.getDomainAxis(); org.jfree.data.Range x = domainAxis.getRange(); ValueAxis rangeAxis = plot.getRangeAxis(); org.jfree.data.Range y = rangeAxis.getRange(); // real plot height can be calculated by double realPW = realPH / y.getLength() * x.getLength(); double width = realPW + titleWidth; return width; } /** * Returns dimensions for limiting factor width or height * * @param myChart * @return */ public static Dimension calcMaxSize(ChartViewer myChart, double chartWidth, double chartHeight) { makeChartResizable(myChart); // paint on a ghost panel myChart.getCanvas().draw(); XYPlot plot = (XYPlot) myChart.getChart().getPlot(); ChartRenderingInfo info = myChart.getRenderingInfo(); Rectangle2D dataArea = info.getPlotInfo().getDataArea(); Rectangle2D chartArea = info.getChartArea(); // calc title space: will be added later to the right plot size double titleWidth = chartArea.getWidth() - dataArea.getWidth(); double titleHeight = chartArea.getHeight() - dataArea.getHeight(); // calculatig width for max height // calc right plot size with axis dim. // real plot width is given by factor; double realPH = chartHeight - titleHeight; // ranges ValueAxis domainAxis = plot.getDomainAxis(); org.jfree.data.Range x = domainAxis.getRange(); ValueAxis rangeAxis = plot.getRangeAxis(); org.jfree.data.Range y = rangeAxis.getRange(); // real plot height can be calculated by double realPW = realPH / y.getLength() * x.getLength(); double width = realPW + titleWidth; // if width is higher than given chartWidth then calc height for chartWidth if (width > chartWidth) { // calc right plot size with axis dim. // real plot width is given by factor; realPW = chartWidth - titleWidth; // real plot height can be calculated by realPH = realPW / x.getLength() * y.getLength(); double height = realPH + titleHeight; // Return size return new Dimension((int) chartWidth, (int) height); } else { // Return size return new Dimension((int) width, (int) chartHeight); } } /** * * @param myChart * @return Range the domainAxis zoom (X-axis) */ public static Range getZoomDomainAxis(ChartViewer myChart) { XYPlot plot = (XYPlot) myChart.getChart().getPlot(); ValueAxis domainAxis = plot.getDomainAxis(); return new Range(domainAxis.getLowerBound(), domainAxis.getUpperBound()); } /** * Zoom into a chart panel * * @param myChart * @param zoom * @param autoRangeY if true the range (Y) axis auto bounds will be restored */ public static void setZoomDomainAxis(ChartViewer myChart, Range zoom, boolean autoRangeY) { XYPlot plot = (XYPlot) myChart.getChart().getPlot(); ValueAxis domainAxis = plot.getDomainAxis(); setZoomAxis(domainAxis, keepRangeWithinAutoBounds(domainAxis, zoom)); if (autoRangeY) { autoRangeAxis(myChart); } } /** * Zoom into a chart panel * * @param myChart * @param zoom * @param autoRangeY if true the range (Y) axis auto bounds will be restored */ public static void setZoomAxis(ValueAxis axis, Range zoom) { axis.setRange(zoom); } /** * Auto range the range axis * * @param myChart * @param zoom * @param autoRangeY if true the range (Y) axis auto bounds will be restored */ public static void autoAxes(ChartViewer myChart) { XYPlot plot = (XYPlot) myChart.getChart().getPlot(); if (plot instanceof Zoomable) { Zoomable z = (Zoomable) plot; Point2D endPoint = new Point2D.Double(0, 0); PlotRenderingInfo pri = myChart.getRenderingInfo().getPlotInfo(); boolean saved = plot.isNotify(); plot.setNotify(false); z.zoomDomainAxes(0, pri, endPoint); z.zoomRangeAxes(0, pri, endPoint); plot.setNotify(saved); } } /** * Auto range the range axis * * @param myChart * @param zoom * @param autoRangeY if true the range (Y) axis auto bounds will be restored */ public static void autoRangeAxis(ChartViewer myChart) { XYPlot plot = (XYPlot) myChart.getChart().getPlot(); if (plot instanceof Zoomable) { Zoomable z = (Zoomable) plot; Point2D endPoint = new Point2D.Double(0, 0); PlotRenderingInfo pri = myChart.getRenderingInfo().getPlotInfo(); z.zoomRangeAxes(0, pri, endPoint); } } /** * Auto range the range axis * * @param myChart * @param zoom * @param autoRangeY if true the range (Y) axis auto bounds will be restored */ public static void autoDomainAxis(ChartViewer myChart) { XYPlot plot = (XYPlot) myChart.getChart().getPlot(); if (plot instanceof Zoomable) { Zoomable z = (Zoomable) plot; Point2D endPoint = new Point2D.Double(0, 0); PlotRenderingInfo pri = myChart.getRenderingInfo().getPlotInfo(); z.zoomDomainAxes(0, pri, endPoint); } } /** * Move a chart by a percentage x-offset if xoffset is <0 the shift will be negativ (xoffset>0 * results in a positive shift) * * @param myChart * @param xoffset in percent * @param autoRangeY if true the range (Y) axis auto bounds will be restored */ public static void offsetDomainAxis(ChartViewer myChart, double xoffset, boolean autoRangeY) { XYPlot plot = (XYPlot) myChart.getChart().getPlot(); ValueAxis domainAxis = plot.getDomainAxis(); // apply offset on x double distance = (domainAxis.getUpperBound() - domainAxis.getLowerBound()) * xoffset; Range range = new Range(domainAxis.getLowerBound() + distance, domainAxis.getUpperBound() + distance); setZoomDomainAxis(myChart, keepRangeWithinAutoBounds(domainAxis, range), autoRangeY); } /** * Apply an absolute offset to domain (x) axis and move it * * @param myChart * @param xoffset * @param autoRangeY */ public static void offsetDomainAxisAbsolute(ChartViewer myChart, double xoffset, boolean autoRangeY) { XYPlot plot = (XYPlot) myChart.getChart().getPlot(); ValueAxis domainAxis = plot.getDomainAxis(); // apply offset on x Range range = new Range(domainAxis.getLowerBound() + xoffset, domainAxis.getUpperBound() + xoffset); setZoomDomainAxis(myChart, keepRangeWithinAutoBounds(domainAxis, range), autoRangeY); } /** * Apply an absolute offset to an axis and move it * * @param myChart * @param offset */ public static void offsetAxisAbsolute(ValueAxis axis, double offset) { Range range = new Range(axis.getLowerBound() + offset, axis.getUpperBound() + offset); setZoomAxis(axis, keepRangeWithinAutoBounds(axis, range)); } /** * Apply an relative offset to an axis and move it. LowerBound and UpperBound are defined by * {@link ValueAxis#getDefaultAutoRange()} * * @param myChart * @param offset percentage */ public static void offsetAxis(ValueAxis axis, double offset) { double distance = (axis.getUpperBound() - axis.getLowerBound()) * offset; Range range = new Range(axis.getLowerBound() + distance, axis.getUpperBound() + distance); setZoomAxis(axis, keepRangeWithinAutoBounds(axis, range)); } public static Range keepRangeWithinAutoBounds(ValueAxis axis, Range range) { // keep within auto range bounds // Range auto = axis.getDefaultAutoRange(); // if(range.getLowerBound()<auto.getLowerBound()){ // double negative = range.getLowerBound()-auto.getLowerBound(); // range = new Range(auto.getLowerBound(), range.getUpperBound()-negative); // if(range.getUpperBound()>auto.getUpperBound()) { // double positive = range.getUpperBound()-auto.getUpperBound(); // range = new Range(range.getLowerBound()-positive, auto.getUpperBound()); return range; } /** * Zoom in (negative yzoom) or zoom out of range axis. * * @param myChart * @param yzoom percentage zoom factor * @param holdLowerBound if true only the upper bound will be zoomed */ public static void zoomRangeAxis(ChartViewer myChart, double yzoom, boolean holdLowerBound) { XYPlot plot = (XYPlot) myChart.getChart().getPlot(); ValueAxis rangeAxis = plot.getRangeAxis(); double lower = rangeAxis.getLowerBound(); double upper = rangeAxis.getUpperBound(); double dist = upper - lower; if (holdLowerBound) { upper += dist * yzoom; } else { lower -= dist * yzoom / 2; upper += dist * yzoom / 2; } if (lower < upper) { Range range = new Range(lower, upper); setZoomAxis(rangeAxis, keepRangeWithinAutoBounds(rangeAxis, range)); } } /** * Zoom in (negative zoom) or zoom out of axis. * * @param myChart * @param zoom percentage zoom factor * @param holdLowerBound if true only the upper bound will be zoomed */ public static void zoomAxis(ValueAxis axis, double zoom, boolean holdLowerBound) { double lower = axis.getLowerBound(); double upper = axis.getUpperBound(); double dist = upper - lower; if (holdLowerBound) { if (zoom == 0) return; upper += dist * zoom; } else { lower -= dist * zoom / 2; upper += dist * zoom / 2; } if (lower < upper) { logger.info("Set zoom:" + lower + ", " + upper + " (keep lower:" + holdLowerBound + ")"); Range range = new Range(lower, upper); setZoomAxis(axis, keepRangeWithinAutoBounds(axis, range)); } } /** * Zoom in (negative zoom) or zoom out of axis. * * @param myChart * @param zoom percentage zoom factor * @param start point on this range (first click/pressed event), used as center */ public static void zoomAxis(ValueAxis axis, double zoom, double start) { double lower = axis.getLowerBound(); double upper = axis.getUpperBound(); double dist = upper - lower; double f = (start - lower) / dist; lower -= dist * zoom * f; upper += dist * zoom * (1 - f); if (lower < upper) { Range range = new Range(lower, upper); setZoomAxis(axis, keepRangeWithinAutoBounds(axis, range)); } } /** * * @param ChartViewer * @return */ // TODO public static boolean isMouseZoomable(ChartViewer chart) { // return chartPanel instanceof EChartPanel ? ((EChartPanel) chartPanel).isMouseZoomable() // : chartPanel.isRangeZoomable() && chartPanel.isDomainZoomable(); return chart.getCanvas().isRangeZoomable() && chart.getCanvas().isDomainZoomable(); } }
package org.towerofawesome; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ChatComponentTranslation; import org.towerofawesome.init.ModItems; import org.towerofawesome.util.References; import org.towerofawesome.util.Utilities; import javax.annotation.Nullable; import java.util.*; public class Controller { UUID controllerId; public BuildingType type; public long lastInput; public HashMap<Product, Integer> inputs = new HashMap<Product, Integer>(); public HashMap<Product, Integer> outputs = new HashMap<Product, Integer>(); public int maxCapacityPerInput; public int maxCapacityPerOutput; public Controller(UUID id, BuildingType type) throws Exception { if (type == null) throw new Exception("type cannot be null!"); this.lastInput = new Date().getTime(); this.controllerId = id; this.type = type; //TODO re-add input output stuff } public void doProduction() { this.doProduction(null); } public void doProduction(@Nullable EntityPlayer player) { int produced; long now = new Date().getTime(); long maxRunTime = (now - this.lastInput) / 1000; this.lastInput = now; Product lowestValueIndex = Utilities.getIndexOfLowestValue(this.inputs); int minInputStoredAmount = -1; int maxProductionTime = -1; double minInputProductionTime; if (lowestValueIndex != null) { minInputProductionTime = this.type.inputs.get(this.type.inputs.indexOf(lowestValueIndex)).productionTime; minInputStoredAmount = this.inputs.get(lowestValueIndex); maxProductionTime = (int) (minInputStoredAmount / minInputProductionTime); } if (player != null) { player.addChatMessage(new ChatComponentTranslation("Production would run for at most " + maxProductionTime + " seconds.")); player.addChatMessage(new ChatComponentTranslation("Smallest stack contains " + minInputStoredAmount + " items")); } } public boolean setAddress(UUID address) { this.controllerId = address; return true; } public UUID getAddress() { return this.controllerId; } public BuildingType getType() { return this.type; } public List<Product> getInputs() { return this.type.inputs; } public List<Product> getOutputs() { return this.type.outputs; } public int getSizeInventory() { if (this.inputs != null) return this.inputs.keySet().toArray().length; else return 0; } public ItemStack getStackInSlot(int slot) { return null; } public ItemStack decrStackSize(int slot, int amount) { //BlockTycoon.log.info("Something requested " + amount + " from slot " + slot); //for (int i = 0; i < outputs.length; i++) // if (outputs[i] > 0) // outputs[i]--; // ItemStack stack = new ItemStack(ModItems.itemCrate); // stack.stackSize = 1; // NBTTagCompound tag = stack.getTagCompound(); // if (tag == null) // tag = new NBTTagCompound(); // tag.setString("goods_type", this.type.outputs.get(i).name); // stack.setTagCompound(tag); // return stack; return null; } public ItemStack getStackInSlotOnClosing(int slot) { return this.getStackInSlot(slot); } public void setInventorySlotContents(int slot, ItemStack stack) { BlockTycoon.log.info("Something tried to insert " + stack.getUnlocalizedName() + " into slot " + slot); } public String getInventoryName() { return "IO Port"; } public boolean hasCustomInventoryName() { return true; } public int getInventoryStackLimit() { return 0; } public boolean isUseableByPlayer(EntityPlayer player) { return false; } public void openInventory() { } public void closeInventory() { } public boolean isItemValidForSlot(int slot, ItemStack stack) { BlockTycoon.log.info("Query received for " + stack.getUnlocalizedName() + " for slot " + slot); if (stack.getUnlocalizedName().equals("item." + References.MOD_ID + ":crate")) { NBTTagCompound tag = stack.getTagCompound(); if (tag != null && tag.hasKey("goods_type")) { if (this.type.inputs.get(slot).name.equals(tag.getString("goods_type"))) { BlockTycoon.log.info("Goods of type \"" + tag.getString("goods_type") + "\" is valid for slot " + slot); return true; } } } BlockTycoon.log.info("Item \"" + stack.getUnlocalizedName() + "\" is not valid for slot " + slot); return false; } }
package net.virtualinfinity.infiniterm; import net.virtualinfinity.emulation.*; import net.virtualinfinity.emulation.telnet.TelnetDecoder; import net.virtualinfinity.emulation.ui.OutputDeviceImpl; import net.virtualinfinity.emulation.ui.PresentationComponent; import net.virtualinfinity.nio.EventLoop; import net.virtualinfinity.swing.StickyBottomScrollPane; import net.virtualinfinity.telnet.Option; import net.virtualinfinity.telnet.TelnetSession; import javax.swing.*; import java.awt.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.WindowEvent; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import java.util.Vector; import java.util.function.Consumer; /** * @author <a href='mailto:Daniel@coloraura.com'>Daniel Pitts</a> */ public class Terminal { public static final String IBM_437 = "IBM437"; private final PresentationComponent view; private final JFrame frame; private final JComboBox<String> hostInput; private final JComboBox<Charset> encodingInput; private final EventLoop eventLoop; private final KeyListenerInputDevice inputDevice = new KeyListenerInputDevice(); private State state = State.DISCONNECTED; private final int id; private static int nextId = 0; private Decoder decoder; private Encoder encoder; { synchronized (Terminal.class) { id = nextId++; } } public Terminal() throws IOException { this.eventLoop = new EventLoop(this::handleException); this.frame = new JFrame(); view = new PresentationComponent(); view.setFont(new Font("PT Mono", Font.PLAIN, 16)); frame.add(new StickyBottomScrollPane(view)); // TODO: Font picker and preferences. frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); frame.addWindowStateListener(e -> { if (e.getNewState() == WindowEvent.WINDOW_CLOSING) { disconnect(); } }); final JToolBar toolBar = new JToolBar(); toolBar.add(new JLabel("Host:")); hostInput = new JComboBox<>(); hostInput.setEditable(true); hostInput.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("enter"), "connect"); hostInput.getActionMap().put("connect", new ConnectAction()); toolBar.add(hostInput); toolBar.add(new JButton(new ConnectAction())); toolBar.addSeparator(); toolBar.add(new JLabel("Encoding:")); //noinspection UseOfObsoleteCollectionType final Vector<Charset> charsets = new Vector<>(); charsets.add(Charset.defaultCharset()); if (Charset.isSupported(IBM_437)) { charsets.add(Charset.forName(IBM_437)); } charsets.addAll(Charset.availableCharsets().values()); encodingInput = new JComboBox<>(charsets); encodingInput.setEditable(false); encodingInput.setSelectedItem(Charset.defaultCharset()); encodingInput.setAction(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { onIOThread(() -> setCharSet(selectedCharset())); } }); toolBar.add(encodingInput); frame.add(toolBar, BorderLayout.PAGE_START); view.getInputMap().put(KeyStroke.getKeyStroke("meta V"), "paste"); view.getActionMap().put("paste", new PasteAction(inputDevice)); view.addKeyListener(inputDevice); } private void handleException(SelectionKey selectionKey, IOException e) { e.printStackTrace(); } public void show() { frame.pack(); frame.setVisible(true); new Thread(() -> { try { eventLoop.run(); } catch (IOException e) { e.printStackTrace(); } }, "EventLoop-" + id).start(); } private void connect() { if (state != State.DISCONNECTED) { return; } final Object selectedItem = hostInput.getModel().getSelectedItem(); if (selectedItem == null) { JOptionPane.showMessageDialog(frame, "Please select a host to connect to.", "No host selected", JOptionPane.ERROR_MESSAGE); return; } state = State.CONNECTING; onIOThread(() -> { SocketChannel channel = null; try { channel = SocketChannel.open(parseAddress(selectedItem.toString())); channel.configureBlocking(false); finishConnect(selectedCharset(), channel); } catch (Exception e) { disconnect(); displayConnectError(e); if (channel != null) { try { channel.close(); } catch (IOException e1) { } } } }); } private Charset selectedCharset() { return encodingInput.getItemAt(encodingInput.getSelectedIndex()); } private void onIOThread(Runnable action) { eventLoop.invokeLater(action); } private void finishConnect(Charset charset, SocketChannel channel) throws ClosedChannelException { try { channel.finishConnect(); } catch (IOException e) { disconnect(); displayConnectError(e); return; } state = State.CONNECTED; final OutputDeviceImpl device = new OutputDeviceImpl(view.getModel()); device.inputDevice(inputDevice); decoder = new Decoder(device); final TelnetSession telnetSession = createTelnetSession(channel, decoder); encoder = new Encoder(new TelnetSessionDispatcher(telnetSession, eventLoop)); setCharSet(charset); onGuiThread(() -> inputDevice.setEncoder(encoder)); } private void setCharSet(Charset charset) { if (encoder != null) { encoder.charset(charset); } if (decoder != null) { decoder.charset(charset); } } private void onGuiThread(Runnable action) { EventQueue.invokeLater(action); } private void displayConnectError(Exception e) { onGuiThread(() -> JOptionPane.showMessageDialog(frame, "Unable to connect to host:" + e.toString(), "Connection error.", JOptionPane.ERROR_MESSAGE)); } private TelnetSession createTelnetSession(SocketChannel channel, Decoder decoder) throws ClosedChannelException { final TelnetSession session = new TelnetSession(channel, new TelnetDecoder(decoder)); eventLoop.registerHandler(channel, session); session.option(Option.ECHO).allowRemote(); session.option(Option.BINARY_TRANSMISSION).allowRemote().allowLocal(); session.option(Option.SUPPRESS_GO_AHEAD).requestRemoteEnable().allowLocal(); session.installOptionReceiver(new LocalTerminalTypeHandler()).allowLocal(); return session; } private SocketAddress parseAddress(String host) { final int colon = host.indexOf(':'); if (colon < 0) { return new InetSocketAddress(host, 23); } return new InetSocketAddress(host.substring(0, colon), Integer.parseInt(host.substring(colon+1))); } public void disconnect() { } private class ConnectAction extends AbstractAction { public ConnectAction() { super("Connect"); } @Override public void actionPerformed(ActionEvent e) { connect(); view.requestFocusInWindow(); } } private enum State { DISCONNECTED, CONNECTING, CONNECTED, } private static class TelnetSessionDispatcher implements Consumer<ByteBuffer> { private final TelnetSession telnetSession; private final EventLoop eventLoop; public TelnetSessionDispatcher(TelnetSession telnetSession, EventLoop eventLoop) { this.telnetSession = telnetSession; this.eventLoop = eventLoop; } @Override public void accept(ByteBuffer buffer) { final ByteBuffer copy = ByteBuffer.allocate(buffer.remaining()); copy.put(buffer); copy.flip(); eventLoop.invokeLater(() -> { telnetSession.writeData(copy); }); } } private static class PasteAction extends AbstractAction { private final InputDevice inputDevice; public PasteAction(InputDevice inputDevice) { this.inputDevice = inputDevice; } @Override public void actionPerformed(ActionEvent e) { final Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard(); final Transferable contents = cb.getContents(null); if (contents == null) { return; } try { if (contents.isDataFlavorSupported(DataFlavor.stringFlavor)) { DataFlavor.getTextPlainUnicodeFlavor().getReaderForText(contents); inputDevice.pasted(CharBuffer.wrap((CharSequence)contents.getTransferData(DataFlavor.stringFlavor))); } } catch (Exception e1) { e1.printStackTrace(); } } } }
package org.zendesk.client.v2; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.ning.http.client.AsyncCompletionHandler; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.ListenableFuture; import com.ning.http.client.Realm; import com.ning.http.client.Request; import com.ning.http.client.RequestBuilder; import com.ning.http.client.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zendesk.client.v2.model.Attachment; import org.zendesk.client.v2.model.Audit; import org.zendesk.client.v2.model.Comment; import org.zendesk.client.v2.model.Field; import org.zendesk.client.v2.model.Group; import org.zendesk.client.v2.model.Identity; import org.zendesk.client.v2.model.Organization; import org.zendesk.client.v2.model.Ticket; import org.zendesk.client.v2.model.User; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.concurrent.ExecutionException; /** * @author stephenc * @since 04/04/2013 13:08 */ public class ZenDesk implements Closeable { private static final String JSON = "application/json"; private final boolean closeClient; private final AsyncHttpClient client; private final Realm realm; private final String url; private final ObjectMapper mapper; private final Logger logger; private boolean closed = false; private ZenDesk(AsyncHttpClient client, String url, String username, String password) { this.logger = LoggerFactory.getLogger(ZenDesk.class); this.closeClient = client == null; this.client = client == null ? new AsyncHttpClient() : client; this.url = url.endsWith("/") ? url + "api/v2" : url + "/api/v2"; if (username != null) { this.realm = new Realm.RealmBuilder() .setScheme(Realm.AuthScheme.BASIC) .setPrincipal(username) .setPassword(password) .setUsePreemptiveAuth(true) .build(); } else { if (password != null) { throw new IllegalStateException("Cannot specify token or password without specifying username"); } this.realm = null; } createMapper(); this.mapper = createMapper(); } // Closeable interface methods public boolean isClosed() { return closed || client.isClosed(); } public void close() { if (closeClient && !client.isClosed()) { client.close(); } closed = true; } // Action methods public Ticket getTicket(int id) { return complete(submit(req("GET", tmpl("/tickets/{id}.json").set("id", id)), handle(Ticket.class, "ticket"))); } public void deleteTicket(Ticket ticket) { checkHasId(ticket); deleteTicket(ticket.getId()); } public void deleteTicket(int id) { complete(submit(req("DELETE", tmpl("/tickets/{id}.json").set("id", id)), handleStatus())); } public Ticket createTicket(Ticket ticket) { return complete(submit(req("POST", cnst("/tickets.json"), JSON, json(Collections.singletonMap("ticket", ticket))), handle(Ticket.class, "ticket"))); } public Ticket updateTicket(Ticket ticket) { checkHasId(ticket); return complete(submit(req("PUT", tmpl("/tickets/{id}.json").set("id", ticket.getId()), JSON, json(Collections.singletonMap("ticket", ticket))), handle(Ticket.class, "ticket"))); } public void markTicketAsSpam(Ticket ticket) { checkHasId(ticket); markTicketAsSpam(ticket.getId()); } public void markTicketAsSpam(int id) { complete(submit(req("PUT", tmpl("/tickets/{id}/mark_as_spam.json").set("id", id)), handleStatus())); } public void deleteTickets(int id, int... ids) { complete(submit(req("DELETE", tmpl("/tickets/destroy_many.json{?ids}").set("ids", idArray(id, ids))), handleStatus())); } public Iterable<Ticket> getTickets() { return new PagedIterable<Ticket>(cnst("/tickets.json"), handleList(Ticket.class, "tickets")); } public List<Ticket> getTickets(int id, int... ids) { return complete(submit(req("GET", tmpl("/tickets/show_many.json{?ids}").set("ids", idArray(id, ids))), handleList(Ticket.class, "tickets"))); } public Iterable<Ticket> getRecentTickets() { return new PagedIterable<Ticket>(cnst("/tickets/recent.json"), handleList(Ticket.class, "tickets")); } public Iterable<Ticket> getOrganizationTickets(int organizationId) { return new PagedIterable<Ticket>( tmpl("/organizations/{organizationId}/tickets.json").set("organizationId", organizationId), handleList(Ticket.class, "tickets")); } public Iterable<Ticket> getUserRequestedTickets(int userId) { return new PagedIterable<Ticket>(tmpl("/users/{userId}/tickets/requested.json").set("userId", userId), handleList(Ticket.class, "tickets")); } public Iterable<Ticket> getUserCCDTickets(int userId) { return new PagedIterable<Ticket>(tmpl("/users/{userId}/tickets/ccd.json").set("userId", userId), handleList(Ticket.class, "tickets")); } public Iterable<Audit> getTicketAudits(Ticket ticket) { checkHasId(ticket); return getTicketAudits(ticket.getId()); } public Iterable<Audit> getTicketAudits(Integer id) { return new PagedIterable<Audit>(tmpl("/tickets/{ticketId}/audits.json").set("ticketId", id), handleList(Audit.class, "audits")); } public Audit getTicketAudit(Ticket ticket, Audit audit) { checkHasId(audit); return getTicketAudit(ticket, audit.getId()); } public Audit getTicketAudit(Ticket ticket, int id) { checkHasId(ticket); return getTicketAudit(ticket.getId(), id); } public Audit getTicketAudit(int ticketId, int auditId) { return complete(submit(req("GET", tmpl("/tickets/{ticketId}/audits/{auditId}.json").set("ticketId", ticketId).set("auditId", auditId)), handle(Audit.class, "audit"))); } public void trustTicketAudit(Ticket ticket, Audit audit) { checkHasId(audit); trustTicketAudit(ticket, audit.getId()); } public void trustTicketAudit(Ticket ticket, int id) { checkHasId(ticket); trustTicketAudit(ticket.getId(), id); } public void trustTicketAudit(int ticketId, int auditId) { complete(submit(req("PUT", tmpl("/tickets/{ticketId}/audits/{auditId}/trust.json").set("ticketId", ticketId) .set("auditId", auditId)), handleStatus())); } public void makePrivateTicketAudit(Ticket ticket, Audit audit) { checkHasId(audit); makePrivateTicketAudit(ticket, audit.getId()); } public void makePrivateTicketAudit(Ticket ticket, int id) { checkHasId(ticket); makePrivateTicketAudit(ticket.getId(), id); } public void makePrivateTicketAudit(int ticketId, int auditId) { complete(submit(req("PUT", tmpl("/tickets/{ticketId}/audits/{auditId}/make_private.json").set("ticketId", ticketId) .set("auditId", auditId)), handleStatus())); } public List<Field> getTicketFields() { return complete(submit(req("GET", cnst("/ticket_fields.json")), handleList(Field.class, "ticket_fields"))); } public Field getTicketField(int id) { return complete(submit(req("GET", tmpl("/ticket_fields/{id}.json").set("id", id)), handle(Field.class, "ticket_field"))); } public Field createTicketField(Field field) { return complete(submit(req("POST", cnst("/ticket_fields.json"), JSON, json( Collections.singletonMap("ticket_field", field))), handle(Field.class, "ticket_field"))); } public Field updateTicketField(Field field) { checkHasId(field); return complete(submit(req("PUT", tmpl("/ticket_fields/{id}.json").set("id", field.getId()), JSON, json(Collections.singletonMap("ticket_field", field))), handle(Field.class, "ticket_field"))); } public void deleteTicketField(Field field) { checkHasId(field); deleteTicket(field.getId()); } public void deleteTicketField(int id) { complete(submit(req("DELETE", tmpl("/ticket_fields/{id}.json").set("id", id)), handleStatus())); } public Attachment.Upload createUpload(String fileName, byte[] content) { return createUpload(null, fileName, "application/binary", content); } public Attachment.Upload createUpload(String fileName, String contentType, byte[] content) { return createUpload(null, fileName, contentType, content); } public Attachment.Upload createUpload(String token, String fileName, String contentType, byte[] content) { TemplateUri uri = tmpl("/uploads.json{?filename}{?token}").set("filename", fileName); if (token != null) { uri.set("token", token); } return complete( submit(req("POST", uri, contentType, content), handle(Attachment.Upload.class, "upload"))); } public void deleteUpload(Attachment.Upload upload) { checkHasToken(upload); deleteUpload(upload.getToken()); } public void deleteUpload(String token) { complete(submit(req("DELETE", tmpl("/uploads/{token}.json").set("token", token)), handleStatus())); } public Attachment getAttachment(Attachment attachment) { checkHasId(attachment); return getAttachment(attachment.getId()); } public Attachment getAttachment(int id) { return complete(submit(req("GET", tmpl("/attachments/{id}.json").set("id", id)), handle(Attachment.class, "attachment"))); } public void deleteAttachment(Attachment attachment) { checkHasId(attachment); deleteAttachment(attachment.getId()); } public void deleteAttachment(int id) { complete(submit(req("DELETE", tmpl("/attachments/{id}.json").set("id", id)), handleStatus())); } public Iterable<User> getUsers() { return new PagedIterable<User>(cnst("/users.json"), handleList(User.class, "users")); } public Iterable<User> getGroupUsers(int id) { return new PagedIterable<User>(tmpl("/groups/{id}/users.json").set("id", id), handleList(User.class, "users")); } public Iterable<User> getOrganizationUsers(int id) { return new PagedIterable<User>(tmpl("/organization/{id}/users.json").set("id", id), handleList(User.class, "users")); } public User getUser(int id) { return complete(submit(req("GET", tmpl("/users/{id}.json").set("id", id)), handle(User.class, "user"))); } public User createUser(User user) { return complete(submit(req("POST", cnst("/users.json"), JSON, json( Collections.singletonMap("user", user))), handle(User.class, "user"))); } public List<User> createUsers(User... users) { return createUsers(Arrays.asList(users)); } public List<User> createUsers(List<User> users) { return complete(submit(req("POST", cnst("/users/create_many.json"), JSON, json( Collections.singletonMap("users", users))), handleList(User.class, "results"))); } public User updateUser(User user) { checkHasId(user); return complete(submit(req("PUT", tmpl("/users/{id}.json").set("id", user.getId()), JSON, json( Collections.singletonMap("user", user))), handle(User.class, "user"))); } public void deleteUser(User user) { checkHasId(user); deleteUser(user.getId()); } public void deleteUser(int id) { complete(submit(req("DELETE", tmpl("/users/{id}.json").set("id", id)), handleStatus())); } public Iterable<User> lookupUserByEmail(String email) { return new PagedIterable<User>(tmpl("/users/search.json{?query}").set("query", email), handleList(User.class, "users")); } public Iterable<User> lookupUserByExternalId(String externalId) { return new PagedIterable<User>(tmpl("/users/search.json{?external_id}").set("external_id", externalId), handleList(User.class, "users")); } public User getCurrentUser() { return complete(submit(req("GET", cnst("/users/me.json")), handle(User.class, "user"))); } public void resetUserPassword(User user, String password) { checkHasId(user); resetUserPassword(user.getId(), password); } public void resetUserPassword(int id, String password) { complete(submit(req("POST", tmpl("/users/{id}/password.json").set("id", id), JSON, json(Collections.singletonMap("password", password))), handleStatus())); } public void changeUserPassword(User user, String oldPassword, String newPassword) { checkHasId(user); Map<String, String> req = new HashMap<String, String>(); req.put("previous_password", oldPassword); req.put("password", newPassword); complete(submit(req("PUT", tmpl("/users/{id}/password.json").set("id", user.getId()), JSON, json(req)), handleStatus())); } public List<Identity> getUserIdentities(User user) { checkHasId(user); return getUserIdentities(user.getId()); } public List<Identity> getUserIdentities(int userId) { return complete(submit(req("GET", tmpl("/users/{id}/identities.json").set("id", userId)), handleList(Identity.class, "identities"))); } public Identity getUserIdentity(User user, Identity identity) { checkHasId(identity); return getUserIdentity(user, identity.getId()); } public Identity getUserIdentity(User user, int identityId) { checkHasId(user); return getUserIdentity(user.getId(), identityId); } public Identity getUserIdentity(int userId, int identityId) { return complete(submit(req("GET", tmpl("/users/{userId}/identities/{identityId}.json").set("userId", userId) .set("identityId", identityId)), handle( Identity.class, "identity"))); } public List<Identity> setUserPrimaryIdentity(User user, Identity identity) { checkHasId(identity); return setUserPrimaryIdentity(user, identity.getId()); } public List<Identity> setUserPrimaryIdentity(User user, int identityId) { checkHasId(user); return setUserPrimaryIdentity(user.getId(), identityId); } public List<Identity> setUserPrimaryIdentity(int userId, int identityId) { return complete(submit(req("PUT", tmpl("/users/{userId}/identities/{identityId}/make_primary.json").set("userId", userId) .set("identityId", identityId), JSON, ""), handleList(Identity.class, "identities"))); } public Identity verifyUserIdentity(User user, Identity identity) { checkHasId(identity); return verifyUserIdentity(user, identity.getId()); } public Identity verifyUserIdentity(User user, int identityId) { checkHasId(user); return verifyUserIdentity(user.getId(), identityId); } public Identity verifyUserIdentity(int userId, int identityId) { return complete(submit(req("PUT", tmpl("/users/{userId}/identities/{identityId}/verify.json") .set("userId", userId) .set("identityId", identityId), JSON, ""), handle(Identity.class, "identity"))); } public Identity requestVerifyUserIdentity(User user, Identity identity) { checkHasId(identity); return requestVerifyUserIdentity(user, identity.getId()); } public Identity requestVerifyUserIdentity(User user, int identityId) { checkHasId(user); return requestVerifyUserIdentity(user.getId(), identityId); } public Identity requestVerifyUserIdentity(int userId, int identityId) { return complete(submit(req("PUT", tmpl("/users/{userId}/identities/{identityId}/request_verification") .set("userId", userId) .set("identityId", identityId)), handle(Identity.class, "identity"))); } public void deleteUserIdentity(User user, Identity identity) { checkHasId(identity); deleteUserIdentity(user, identity.getId()); } public void deleteUserIdentity(User user, int identityId) { checkHasId(user); deleteUserIdentity(user.getId(), identityId); } public void deleteUserIdentity(int userId, int identityId) { complete(submit(req("DELETE", tmpl("/users/{userId}/identities/{identityId}.json") .set("userId", userId) .set("identityId", identityId) ), handleStatus())); } public Iterable<org.zendesk.client.v2.model.Request> getRequests() { return new PagedIterable<org.zendesk.client.v2.model.Request>(cnst("/requests.json"), handleList(org.zendesk.client.v2.model.Request.class, "requests")); } public Iterable<org.zendesk.client.v2.model.Request> getOpenRequests() { return new PagedIterable<org.zendesk.client.v2.model.Request>(cnst("/requests/open.json"), handleList(org.zendesk.client.v2.model.Request.class, "requests")); } public Iterable<org.zendesk.client.v2.model.Request> getSolvedRequests() { return new PagedIterable<org.zendesk.client.v2.model.Request>(cnst("/requests/solved.json"), handleList(org.zendesk.client.v2.model.Request.class, "requests")); } public Iterable<org.zendesk.client.v2.model.Request> getCCRequests() { return new PagedIterable<org.zendesk.client.v2.model.Request>(cnst("/requests/ccd.json"), handleList(org.zendesk.client.v2.model.Request.class, "requests")); } public Iterable<org.zendesk.client.v2.model.Request> getUserRequests(User user) { checkHasId(user); return getUserRequests(user.getId()); } public Iterable<org.zendesk.client.v2.model.Request> getUserRequests(int id) { return new PagedIterable<org.zendesk.client.v2.model.Request>(tmpl("/users/{id}/requests.json").set("id", id), handleList(org.zendesk.client.v2.model.Request.class, "requests")); } public org.zendesk.client.v2.model.Request getRequest(int id) { return complete(submit(req("GET", tmpl("/requests/{id}.json").set("id", id)), handle(org.zendesk.client.v2.model.Request.class, "request"))); } public org.zendesk.client.v2.model.Request createRequest(org.zendesk.client.v2.model.Request request) { return complete(submit(req("POST", cnst("/requests.json"), JSON, json(Collections.singletonMap("request", request))), handle(org.zendesk.client.v2.model.Request.class, "request"))); } public org.zendesk.client.v2.model.Request updateRequest(org.zendesk.client.v2.model.Request request) { checkHasId(request); return complete(submit(req("PUT", tmpl("/requests/{id}.json").set("id", request.getId()), JSON, json(Collections.singletonMap("request", request))), handle(org.zendesk.client.v2.model.Request.class, "request"))); } public Iterable<Comment> getRequestComments(org.zendesk.client.v2.model.Request request) { checkHasId(request); return getRequestComments(request.getId()); } public Iterable<Comment> getRequestComments(int id) { return new PagedIterable<Comment>(tmpl("/requests/{id}/comments.json").set("id", id), handleList(Comment.class, "comments")); } public Comment getRequestComment(org.zendesk.client.v2.model.Request request, Comment comment) { checkHasId(comment); return getRequestComment(request, comment.getId()); } public Comment getRequestComment(org.zendesk.client.v2.model.Request request, int commentId) { checkHasId(request); return getRequestComment(request.getId(), commentId); } public Comment getRequestComment(int requestId, int commentId) { return complete(submit(req("GET", tmpl("/requests/{requestId}/comments/{commentId}.json") .set("requestId", requestId) .set("commentId", commentId)), handle(Comment.class, "comment"))); } public Iterable<Organization> getOrganizations() { return new PagedIterable<Organization>(cnst("/organizations.json"), handleList(Organization.class, "organizations")); } public Iterable<Organization> getAutoCompleteOrganizations(String name) { if (name == null || name.length() < 2) { throw new IllegalArgumentException("Name must be at least 2 characters long"); } return new PagedIterable<Organization>(tmpl("/organizations/autocomplete.json{?name}").set("name", name), handleList(Organization.class, "organizations")); } // TODO getOrganizationRelatedInformation public Organization getOrganization(int id) { return complete(submit(req("GET", tmpl("/organizations/{id}.json").set("id", id)), handle(Organization.class, "organization"))); } public Organization createOrganization(Organization organization) { return complete(submit(req("POST", cnst("/organizations.json"), JSON, json( Collections.singletonMap("organization", organization))), handle(Organization.class, "organization"))); } public List<Organization> createOrganizations(Organization... organizations) { return createOrganizations(Arrays.asList(organizations)); } public List<Organization> createOrganizations(List<Organization> organizations) { return complete(submit(req("POST", cnst("/organizations/create_many.json"), JSON, json( Collections.singletonMap("organizations", organizations))), handleList(Organization.class, "results"))); } public Organization updateOrganization(Organization organization) { checkHasId(organization); return complete(submit(req("PUT", tmpl("/organizations/{id}.json").set("id", organization.getId()), JSON, json( Collections.singletonMap("organization", organization))), handle(Organization.class, "organization"))); } public void deleteOrganization(Organization organization) { checkHasId(organization); deleteOrganization(organization.getId()); } public void deleteOrganization(int id) { complete(submit(req("DELETE", tmpl("/organizations/{id}.json").set("id", id)), handleStatus())); } public Iterable<Organization> lookupOrganizationsByExternalId(String externalId) { if (externalId == null || externalId.length() < 2) { throw new IllegalArgumentException("Name must be at least 2 characters long"); } return new PagedIterable<Organization>(tmpl("/organizations/search.json{?external_id}").set("external_id", externalId), handleList(Organization.class, "organizations")); } public Iterable<Group> getGroups() { return new PagedIterable<Group>(cnst("/groups.json"), handleList(Group.class, "groups")); } public Iterable<Group> getAssignableGroups() { return new PagedIterable<Group>(cnst("/groups/assignable.json"), handleList(Group.class, "groups")); } public Group getGroup(int id) { return complete(submit(req("GET", tmpl("/groups/{id}.json").set("id", id)), handle(Group.class, "group"))); } public Group createGroup(Group group) { return complete(submit(req("POST", cnst("/groups.json"), JSON, json( Collections.singletonMap("group", group))), handle(Group.class, "group"))); } public List<Group> createGroups(Group... groups) { return createGroups(Arrays.asList(groups)); } public List<Group> createGroups(List<Group> groups) { return complete(submit(req("POST", cnst("/groups/create_many.json"), JSON, json( Collections.singletonMap("groups", groups))), handleList(Group.class, "results"))); } public Group updateGroup(Group group) { checkHasId(group); return complete(submit(req("PUT", tmpl("/groups/{id}.json").set("id", group.getId()), JSON, json( Collections.singletonMap("group", group))), handle(Group.class, "group"))); } public void deleteGroup(Group group) { checkHasId(group); deleteGroup(group.getId()); } public void deleteGroup(int id) { complete(submit(req("DELETE", tmpl("/groups/{id}.json").set("id", id)), handleStatus())); } // Helper methods private String json(Object object) { try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { throw new ZenDeskException(e.getMessage(), e); } } private <T> ListenableFuture<T> submit(Request request, AsyncCompletionHandler<T> handler) { try { return client.executeRequest(request, handler); } catch (IOException e) { throw new ZenDeskException(e.getMessage(), e); } } private Request req(String method, Uri template) { RequestBuilder builder = new RequestBuilder(method); if (realm != null) { builder.setRealm(realm); } builder.setUrl(template.toString()); return builder.build(); } private Request req(String method, Uri template, String contentType, String body) { RequestBuilder builder = new RequestBuilder(method); if (realm != null) { builder.setRealm(realm); } builder.setUrl(template.toString()); builder.addHeader("Content-type", contentType); builder.setBody(body); return builder.build(); } private Request req(String method, Uri template, String contentType, byte[] body) { RequestBuilder builder = new RequestBuilder(method); if (realm != null) { builder.setRealm(realm); } builder.setUrl(template.toString()); builder.addHeader("Content-type", contentType); builder.setBody(body); return builder.build(); } private Request req(String method, Uri template, int page) { RequestBuilder builder = new RequestBuilder(method); if (realm != null) { builder.setRealm(realm); } builder.addQueryParameter("page", Integer.toString(page)); builder.setUrl(template.toString()); return builder.build(); } protected AsyncCompletionHandler<Void> handleStatus() { return new AsyncCompletionHandler<Void>() { @Override public Void onCompleted(Response response) throws Exception { logger.debug("Response HTTP/{} {}\n{}", response.getStatusCode(), response.getStatusText(), response.getResponseBody()); if (response.getStatusCode() / 100 == 2) { return null; } throw new ZenDeskException(response.getStatusText()); } }; } protected <T> AsyncCompletionHandler<T> handle(final Class<T> clazz) { return new AsyncCompletionHandler<T>() { @Override public T onCompleted(Response response) throws Exception { logger.debug("Response HTTP/{} {}\n{}", response.getStatusCode(), response.getStatusText(), response.getResponseBody()); if (response.getStatusCode() / 100 == 2) { return (T) mapper.reader(clazz).readValue(response.getResponseBodyAsBytes()); } if (response.getStatusCode() == 404) { return null; } throw new ZenDeskException(response.getStatusText()); } }; } protected <T> AsyncCompletionHandler<T> handle(final Class<T> clazz, final String name) { return new AsyncCompletionHandler<T>() { @Override public T onCompleted(Response response) throws Exception { logger.debug("Response HTTP/{} {}\n{}", response.getStatusCode(), response.getStatusText(), response.getResponseBody()); if (response.getStatusCode() / 100 == 2) { return mapper.convertValue(mapper.readTree(response.getResponseBodyAsBytes()).get(name), clazz); } if (response.getStatusCode() == 404) { return null; } throw new ZenDeskException(response.getStatusText()); } }; } protected <T> AsyncCompletionHandler<List<T>> handleList(final Class<T> clazz) { return new AsyncCompletionHandler<List<T>>() { @Override public List<T> onCompleted(Response response) throws Exception { logger.info("Response HTTP/{} {}\n{}", response.getStatusCode(), response.getStatusText(), response.getResponseBody()); if (response.getStatusCode() / 100 == 2) { List<T> values = new ArrayList<T>(); for (JsonNode node : mapper.readTree(response.getResponseBodyAsBytes())) { values.add(mapper.convertValue(node, clazz)); } return values; } throw new ZenDeskException(response.getStatusText()); } }; } protected <T> AsyncCompletionHandler<List<T>> handleList(final Class<T> clazz, final String name) { return new AsyncCompletionHandler<List<T>>() { @Override public List<T> onCompleted(Response response) throws Exception { logger.debug("Response HTTP/{} {}\n{}", response.getStatusCode(), response.getStatusText(), response.getResponseBody()); if (response.getStatusCode() / 100 == 2) { List<T> values = new ArrayList<T>(); for (JsonNode node : mapper.readTree(response.getResponseBodyAsBytes()).get(name)) { values.add(mapper.convertValue(node, clazz)); } return values; } throw new ZenDeskException(response.getStatusText()); } }; } private TemplateUri tmpl(String template) { return new TemplateUri(url + template); } private Uri cnst(String template) { return new FixedUri(url + template); } // Static helper methods private static <T> T complete(ListenableFuture<T> future) { try { return future.get(); } catch (InterruptedException e) { throw new ZenDeskException(e.getMessage(), e); } catch (ExecutionException e) { throw new ZenDeskException(e.getMessage(), e); } } private static void checkHasId(Ticket ticket) { if (ticket.getId() == null) { throw new IllegalArgumentException("Ticket requires id"); } } private static void checkHasId(org.zendesk.client.v2.model.Request request) { if (request.getId() == null) { throw new IllegalArgumentException("Request requires id"); } } private static void checkHasId(Audit audit) { if (audit.getId() == null) { throw new IllegalArgumentException("Audit requires id"); } } private static void checkHasId(Comment comment) { if (comment.getId() == null) { throw new IllegalArgumentException("Comment requires id"); } } private static void checkHasId(Field field) { if (field.getId() == null) { throw new IllegalArgumentException("Field requires id"); } } private static void checkHasId(Attachment attachment) { if (attachment.getId() == null) { throw new IllegalArgumentException("Attachment requires id"); } } private static void checkHasId(User user) { if (user.getId() == null) { throw new IllegalArgumentException("User requires id"); } } private static void checkHasId(Identity identity) { if (identity.getId() == null) { throw new IllegalArgumentException("Identity requires id"); } } private static void checkHasId(Organization organization) { if (organization.getId() == null) { throw new IllegalArgumentException("Organization requires id"); } } private static void checkHasId(Group group) { if (group.getId() == null) { throw new IllegalArgumentException("Group requires id"); } } private static void checkHasToken(Attachment.Upload upload) { if (upload.getToken() == null) { throw new IllegalArgumentException("Upload requires token"); } } private static List<Integer> idArray(int id, int... ids) { List<Integer> result = new ArrayList<Integer>(ids.length + 1); result.add(id); for (int i : ids) { result.add(i); } return result; } public static ObjectMapper createMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return mapper; } // Helper classes private class PagedIterable<T> implements Iterable<T> { private final Uri url; private final AsyncCompletionHandler<List<T>> handler; private final int initialPage; private PagedIterable(Uri url, AsyncCompletionHandler<List<T>> handler) { this(url, handler, 1); } private PagedIterable(Uri url, AsyncCompletionHandler<List<T>> handler, int initialPage) { this.handler = handler; this.url = url; this.initialPage = initialPage; } public Iterator<T> iterator() { return new PagedIterator(initialPage); } private class PagedIterator implements Iterator<T> { private Iterator<T> current; private int page; private PagedIterator(int page) { this.page = page; } public boolean hasNext() { if (current == null || !current.hasNext()) { if (page > 0) { List<T> values = complete(submit(req("GET", url, page++), handler)); if (values.isEmpty()) { page = -1; } current = values.iterator(); } else { return false; } } return current.hasNext(); } public T next() { if (!hasNext()) { throw new NoSuchElementException(); } return current.next(); } public void remove() { throw new UnsupportedOperationException(); } } } public static class Builder { private AsyncHttpClient client = null; private final String url; private String username = null; private String password = null; private String token = null; public Builder(String url) { this.url = url; } public Builder setClient(AsyncHttpClient client) { this.client = client; return this; } public Builder setUsername(String username) { this.username = username; return this; } public Builder setPassword(String password) { this.password = password; if (password != null) { this.token = null; } return this; } public Builder setToken(String token) { this.token = token; if (token != null) { this.password = null; } return this; } public Builder setRetry(boolean retry) { return this; } public ZenDesk build() { if (token == null) { return new ZenDesk(client, url, username, password); } return new ZenDesk(client, url, username + "/token", token); } } }
package nl.vpro.poel.controller; import nl.vpro.poel.domain.User; import nl.vpro.poel.domain.UserGroup; import nl.vpro.poel.dto.UsersForm; import nl.vpro.poel.service.UserGroupService; import nl.vpro.poel.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.util.List; @Controller @RequestMapping("/admin/users") public class UsersController { private UserService userService; private UserGroupService userGroupService; @Autowired public UsersController(UserService userService, UserGroupService userGroupService) { this.userService = userService; this.userGroupService = userGroupService; } @RequestMapping(method = RequestMethod.GET) String showUsers(Model model) { List<User> allUsers = userService.getAllUsers(); model.addAttribute("users", allUsers); List<UserGroup> userGroups = userGroupService.findAll(); model.addAttribute("userGroups", userGroups); return "admin/users"; } @RequestMapping(method = RequestMethod.POST) String saveUsers(@ModelAttribute("users") UsersForm usersForm, BindingResult bindingResult) { userService.updateUserGroupForUsers(usersForm); return "redirect:/admin/users"; } }
package ptrman.levels.retina; import org.apache.commons.math3.linear.ArrayRealVector; import ptrman.Datastructures.IMap2d; import ptrman.Datastructures.SpatialAcceleratedMap2d; import ptrman.Datastructures.Tuple2; import ptrman.Datastructures.Vector2d; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static ptrman.math.ArrayRealVectorHelper.arrayRealVectorToInteger; /** * * calculates the altitude */ public class ProcessB { private int counterCellPositiveCandidates; private int counterCellCandidates; /** * * we use the whole image, in phaeaco he worked with the incomplete image witht the guiding of processA, this is not implemented that way */ public void process(List<ProcessA.Sample> samples, IMap2d<Boolean> map) { Vector2d<Integer> foundPosition; final int MAXRADIUS = (int)Math.sqrt(100.0*100.0); final int GRIDSIZE_FOR_SPATIALACCELERATEDMAP2D = 8; counterCellPositiveCandidates = 0; counterCellCandidates = 0; this.map = map; spatialAcceleratedMap2d = new SpatialAcceleratedMap2d(map, GRIDSIZE_FOR_SPATIALACCELERATEDMAP2D); spatialAcceleratedMap2d.recalculateGridCellStateMap(); for( ProcessA.Sample iterationSample : samples ) { Tuple2<Vector2d<Integer>, Double> nearestResult; nearestResult = findNearestPositionWhereMapIs(false, arrayRealVectorToInteger(iterationSample.position), map, MAXRADIUS); if( nearestResult == null ) { iterationSample.altitude = ((MAXRADIUS+1)*2)*((MAXRADIUS+1)*2); continue; } // else here iterationSample.altitude = nearestResult.e1; } System.out.println("cell acceleration (positive cases): " + Float.toString(((float)counterCellPositiveCandidates / (float)counterCellCandidates) * 100.0f) + "%" ); } // TODO< move into external function > // TODO< provide a version which doesn't need a maxradius (we need only that version) > /** * * \return null if no point could be found in the radius */ private Tuple2<Vector2d<Integer>, Double> findNearestPositionWhereMapIs(boolean value, Vector2d<Integer> position, IMap2d<Boolean> image, int radius) { final ArrayRealVector positionReal = ptrman.math.ArrayRealVectorHelper.integerToArrayRealVector(position); final Vector2d<Integer> gridCenterPosition = spatialAcceleratedMap2d.getGridPositionOfPosition(position); final int gridMaxSearchRadius = 2 + radius / spatialAcceleratedMap2d.getGridsize(); // set this to int.max when the radius is not limited int radiusToScan = gridMaxSearchRadius; Vector2d<Integer> nearestPixelCandidate = null; double nearestPixelCandidateDistanceSquared = Double.MAX_VALUE; for( int currentGridRadius = 0; currentGridRadius < radiusToScan; currentGridRadius++ ) { final List<Vector2d<Integer>> gridCellsToScan; // if we are at the center we need to scan only the center if( currentGridRadius == 0 ) { gridCellsToScan = new ArrayList<Vector2d<Integer>>(Arrays.asList(new Vector2d[]{gridCenterPosition})); } else { gridCellsToScan = spatialAcceleratedMap2d.getGridLocationsOfGridRadius(gridCenterPosition, currentGridRadius); } counterCellCandidates += gridCellsToScan.size(); // use acceleration map and filter out the gridcells we don't need to scan gridCellsToScan.removeIf(cellPosition -> !spatialAcceleratedMap2d.canValueBeFoundInCell(cellPosition, value)); counterCellPositiveCandidates += gridCellsToScan.size(); final List<Vector2d<Integer>> pixelPositionsToCheck = getPositionsOfCandidatePixelsOfCells(gridCellsToScan, value); // pixel scan logic if( !gridCellsToScan.isEmpty() ) { // do this because we need to scan the next radius too radiusToScan = java.lang.Math.min(radiusToScan, currentGridRadius+1+1); } for( final Vector2d<Integer> iterationPixelPosition : pixelPositionsToCheck ) { final ArrayRealVector iterationPixelPositionReal = ptrman.math.ArrayRealVectorHelper.integerToArrayRealVector(iterationPixelPosition); final double currentDistanceSquared = positionReal.dotProduct(iterationPixelPositionReal); if( currentDistanceSquared < nearestPixelCandidateDistanceSquared ) { nearestPixelCandidateDistanceSquared = currentDistanceSquared; nearestPixelCandidate = iterationPixelPosition; } } } return new Tuple2<>(nearestPixelCandidate, java.lang.Math.sqrt(nearestPixelCandidateDistanceSquared)); } private List<Vector2d<Integer>> getPositionsOfCandidatePixelsOfCells(final List<Vector2d<Integer>> cellPositions, final boolean value) { List<Vector2d<Integer>> result = new ArrayList<>(); for( final Vector2d<Integer> iterationCellPosition : cellPositions ) { result.addAll(getPositionsOfCandidatePixelsOfCell(iterationCellPosition, value)); } return result; } private List<Vector2d<Integer>> getPositionsOfCandidatePixelsOfCell(final Vector2d<Integer> cellPosition, final boolean value) { List<Vector2d<Integer>> result = new ArrayList<>(); final int gridsize = spatialAcceleratedMap2d.getGridsize(); for( int y = cellPosition.y * gridsize; y < (cellPosition.y+1) * gridsize; y++ ) { for( int x = cellPosition.x * gridsize; x < (cellPosition.x+1) * gridsize; x++ ) { if( map.readAt(x, y) == value ) { result.add(new Vector2d<>(x, y)); } } } return result; } private SpatialAcceleratedMap2d spatialAcceleratedMap2d; private IMap2d<Boolean> map; }
package com.yahoo.vespa.http.client.config; import net.jcip.annotations.Immutable; import java.io.Serializable; /** * Represents an endpoint, in most cases a JDisc container * in a Vespa cluster configured with <code>document-api</code>. * * @author <a href="mailto:einarmr@yahoo-inc.com">Einar M R Rosenvinge</a> * @since 5.1.20 */ @Immutable public final class Endpoint implements Serializable { /** * Creates an Endpoint with the default port and without using SSL. * * @param hostname the hostname * @return an Endpoint instance */ public static Endpoint create(String hostname) { return new Endpoint(hostname, DEFAULT_PORT, false); } /** * Creates an Endpoint with the given hostname, port and SSL setting. * * @param hostname the hostname * @param port the port * @param useSsl true if SSL is to be used * @return an Endpoint instance * @see com.yahoo.vespa.http.client.config.ConnectionParams#getSslContext() needs to be set as well for SSL */ public static Endpoint create(String hostname, int port, boolean useSsl) { return new Endpoint(hostname, port, useSsl); } private static final long serialVersionUID = 4545345L; private final String hostname; private final int port; private final boolean useSsl; private static final int DEFAULT_PORT = 4080; private Endpoint(String hostname, int port, boolean useSsl) { if (hostname.startsWith("https: throw new RuntimeException("Hostname should be name of machine, not prefixed with protocol (https: } if (hostname.startsWith("http: this.hostname = hostname.replaceFirst("http: } else { this.hostname = hostname; } this.port = port; this.useSsl = useSsl; } public String getHostname() { return hostname; } public int getPort() { return port; } public boolean isUseSsl() { return useSsl; } @Override public String toString() { return hostname + ":" + port + " ssl=" + useSsl; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Endpoint)) return false; Endpoint endpoint = (Endpoint) o; return port == endpoint.port && useSsl == endpoint.useSsl && hostname.equals(endpoint.hostname); } @Override public int hashCode() { int result = hostname.hashCode(); result = 31 * result + port; result = 31 * result + (useSsl ? 1 : 0); return result; } }
package nom.bdezonia.zorbage.algorithm; import nom.bdezonia.zorbage.type.algebra.Addition; import nom.bdezonia.zorbage.type.algebra.Algebra; import nom.bdezonia.zorbage.type.algebra.Invertible; import nom.bdezonia.zorbage.type.algebra.Multiplication; import nom.bdezonia.zorbage.type.algebra.Ordered; import nom.bdezonia.zorbage.type.algebra.Unity; import nom.bdezonia.zorbage.type.storage.datasource.IndexedDataSource; /** * * @author Barry DeZonia * */ public class Variance { private Variance() {} /** * * @param alg * @param storage * @param result */ public static <T extends Algebra<T,U> & Addition<U> & Multiplication<U> & Unity<U> & Invertible<U> & Ordered<U>, U> void compute(T alg, IndexedDataSource<U> storage, U result) { long storageSize = storage.size(); if (storageSize == 0 || storageSize == 1) { alg.zero().call(result); return; } U avg = alg.construct(); U sum = alg.construct(); U count = alg.construct(); U one = alg.construct(); alg.unity().call(one); Mean.compute(alg, storage, avg); SumSquareCount.compute(alg, storage, avg, sum, count); alg.subtract().call(count, one, count); alg.divide().call(sum, count, result); } }
package ru.r2cloud.satellite; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.r2cloud.model.ObservationRequest; import ru.r2cloud.model.Satellite; import ru.r2cloud.model.SdrType; import ru.r2cloud.util.Configuration; public class Schedule { private static final Logger LOG = LoggerFactory.getLogger(Schedule.class); private static final Long PARTIAL_TOLERANCE_MILLIS = 60 * 4 * 1000L; private final ObservationFactory factory; private final Timetable timetable; private final Map<String, ScheduledObservation> tasksById = new HashMap<>(); private final Map<String, ObservationRequest> observationsById = new HashMap<>(); private final Map<String, TimeSlot> timeSlotById = new HashMap<>(); private final Map<String, List<ObservationRequest>> observationsBySatelliteId = new HashMap<>(); public Schedule(Configuration config, ObservationFactory factory) { this.factory = factory; boolean rotatorIsEnabled = config.getBoolean("rotator.enabled"); // this complicated if just to put some logging if (config.getSdrType().equals(SdrType.SDRSERVER)) { if (rotatorIsEnabled) { LOG.info("concurrent observations are disabled because of rotator"); timetable = new SequentialTimetable(PARTIAL_TOLERANCE_MILLIS); } else { timetable = new OverlappedTimetable(PARTIAL_TOLERANCE_MILLIS); } } else { timetable = new SequentialTimetable(PARTIAL_TOLERANCE_MILLIS); } } public synchronized void assignTasksToSlot(String observationId, ScheduledObservation entry) { if (!observationsById.containsKey(observationId)) { throw new IllegalArgumentException("unknown observation"); } ScheduledObservation previous = tasksById.put(observationId, entry); if (previous != null && previous != entry) { LOG.info("cancelling previous scheduled tasks for observation: {}", observationId); previous.cancel(); } } // scheduled observation might not exist public synchronized ScheduledObservation cancel(String observationId) { if (observationId == null) { return null; } ObservationRequest previousReq = observationsById.remove(observationId); if (previousReq == null) { return null; } removeFromIndex(previousReq); timetable.remove(timeSlotById.remove(observationId)); ScheduledObservation previous = tasksById.remove(observationId); if (previous == null) { return null; } LOG.info("cancelling {}: {}", observationId, previousReq.getStartTimeMillis()); previous.cancel(); return previous; } public synchronized void cancelAll() { for (ObservationRequest cur : observationsById.values()) { removeFromIndex(cur); timetable.remove(timeSlotById.remove(cur.getId())); ScheduledObservation previous = tasksById.remove(cur.getId()); if (previous == null) { continue; } previous.cancel(); } observationsById.clear(); } public synchronized List<ObservationRequest> createInitialSchedule(List<Satellite> allSatellites, long current) { Map<String, List<ObservationRequest>> passesBySatellite = new HashMap<>(); for (Satellite cur : allSatellites) { List<ObservationRequest> passes = factory.createSchedule(new Date(current), cur); if (passes.isEmpty()) { continue; } passesBySatellite.put(cur.getId(), passes); } List<ObservationRequest> result = new ArrayList<>(); // fill-in full observations while (!Thread.currentThread().isInterrupted()) { boolean moreObservationsToCheck = false; for (Satellite cur : allSatellites) { List<ObservationRequest> allPasses = passesBySatellite.get(cur.getId()); if (allPasses == null) { continue; } ObservationRequest reserved = reserveFullSlot(allPasses); if (reserved == null) { continue; } moreObservationsToCheck = true; result.add(reserved); allPasses.remove(reserved); } if (!moreObservationsToCheck) { break; } } // fill-in partial observations while (!Thread.currentThread().isInterrupted()) { boolean moreObservationsToCheck = false; for (Satellite cur : allSatellites) { List<ObservationRequest> allPasses = passesBySatellite.get(cur.getId()); if (allPasses == null) { continue; } ObservationRequest reserved = reservePartialSlot(allPasses); if (reserved == null) { continue; } moreObservationsToCheck = true; result.add(reserved); allPasses.remove(reserved); } if (!moreObservationsToCheck) { break; } } index(result); Collections.sort(result, ObservationRequestComparator.INSTANCE); return result; } public synchronized List<ObservationRequest> getBySatelliteId(String satelliteId) { List<ObservationRequest> previous = observationsBySatelliteId.get(satelliteId); if (previous == null) { return Collections.emptyList(); } return previous; } // even if this satellite will be scheduled well forward the rest of satellites // whole schedule will be cleared on next re-schedule public synchronized List<ObservationRequest> addSatelliteToSchedule(Satellite satellite, long current) { List<ObservationRequest> previous = observationsBySatelliteId.get(satellite.getId()); if (previous != null && !previous.isEmpty()) { return previous; } List<ObservationRequest> allPasses = factory.createSchedule(new Date(current), satellite); List<ObservationRequest> batch = new ArrayList<>(); for (ObservationRequest cur : allPasses) { TimeSlot slot = new TimeSlot(); slot.setStart(cur.getStartTimeMillis()); slot.setEnd(cur.getEndTimeMillis()); slot.setFrequency(satellite.getFrequencyBand().getCenter()); if (timetable.addFully(slot)) { batch.add(cur); timeSlotById.put(cur.getId(), slot); continue; } TimeSlot partial = timetable.addPartially(slot); if (partial != null) { cur.setStartTimeMillis(partial.getStart()); cur.setEndTimeMillis(partial.getEnd()); batch.add(cur); timeSlotById.put(cur.getId(), partial); continue; } } index(batch); return batch; } public synchronized ObservationRequest findFirstBySatelliteId(String id, long current) { List<ObservationRequest> curList = observationsBySatelliteId.get(id); if (curList == null || curList.isEmpty()) { return null; } for (ObservationRequest cur : curList) { // the list is sorted so it is safe to do that if (cur.getStartTimeMillis() > current) { return cur; } } return null; } public synchronized ObservationRequest moveObservation(ObservationRequest req, long startTime) { cancel(req.getId()); long previousPeriod = req.getEndTimeMillis() - req.getStartTimeMillis(); req.setStartTimeMillis(startTime); req.setEndTimeMillis(startTime + previousPeriod); TimeSlot slot = new TimeSlot(); slot.setStart(req.getStartTimeMillis()); slot.setEnd(req.getEndTimeMillis()); slot.setFrequency(req.getCenterBandFrequency()); if (!timetable.addFully(slot)) { return null; } index(Collections.singletonList(req)); return req; } public synchronized List<ObservationRequest> findObservations(long startTimeMillis, long endTimeMillis) { List<ObservationRequest> sorted = new ArrayList<>(observationsById.values()); Collections.sort(sorted, ObservationRequestComparator.INSTANCE); List<ObservationRequest> result = new ArrayList<>(); for (ObservationRequest cur : sorted) { if (cur.getStartTimeMillis() > startTimeMillis && cur.getStartTimeMillis() < endTimeMillis) { result.add(cur); } else if (cur.getEndTimeMillis() > startTimeMillis && cur.getEndTimeMillis() < endTimeMillis) { result.add(cur); } else if (cur.getStartTimeMillis() < startTimeMillis && endTimeMillis < cur.getEndTimeMillis()) { result.add(cur); } } return result; } private ObservationRequest reserveFullSlot(List<ObservationRequest> allPasses) { for (ObservationRequest curObservation : allPasses) { TimeSlot slot = new TimeSlot(); slot.setStart(curObservation.getStartTimeMillis()); slot.setEnd(curObservation.getEndTimeMillis()); slot.setFrequency(curObservation.getCenterBandFrequency()); if (timetable.addFully(slot)) { timeSlotById.put(curObservation.getId(), slot); return curObservation; } } return null; } private ObservationRequest reservePartialSlot(List<ObservationRequest> allPasses) { for (ObservationRequest curObservation : allPasses) { TimeSlot slot = new TimeSlot(); slot.setStart(curObservation.getStartTimeMillis()); slot.setEnd(curObservation.getEndTimeMillis()); slot.setFrequency(curObservation.getCenterBandFrequency()); TimeSlot partial = timetable.addPartially(slot); if (partial != null) { curObservation.setStartTimeMillis(partial.getStart()); curObservation.setEndTimeMillis(partial.getEnd()); timeSlotById.put(curObservation.getId(), partial); return curObservation; } } return null; } private void removeFromIndex(ObservationRequest req) { List<ObservationRequest> curList = observationsBySatelliteId.get(req.getSatelliteId()); if (curList == null) { return; } Iterator<ObservationRequest> it = curList.iterator(); while (it.hasNext()) { ObservationRequest cur = it.next(); if (cur.getId().equals(req.getId())) { it.remove(); break; } } } private void index(List<ObservationRequest> req) { for (ObservationRequest cur : req) { List<ObservationRequest> curList = observationsBySatelliteId.get(cur.getSatelliteId()); if (curList == null) { curList = new ArrayList<>(); observationsBySatelliteId.put(cur.getSatelliteId(), curList); } curList.add(cur); observationsById.put(cur.getId(), cur); } for (List<ObservationRequest> values : observationsBySatelliteId.values()) { Collections.sort(values, ObservationRequestComparator.INSTANCE); } } }
package omtteam.omlib.handler; import net.minecraft.command.ICommandSender; import net.minecraft.util.text.TextComponentString; import net.minecraftforge.common.DimensionManager; import omtteam.omlib.network.messages.MessageSetSharePlayerList; import omtteam.omlib.util.Player; import javax.annotation.Nullable; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.function.Predicate; public class OwnerShareHandler implements Serializable { private static OwnerShareHandler instance; private HashMap<Player, ArrayList<Player>> ownerShareMap; private OwnerShareHandler() { ownerShareMap = new HashMap<>(); } public static OwnerShareHandler getInstance() { if (instance == null) { instance = new OwnerShareHandler(); } return instance; } public HashMap<Player, ArrayList<Player>> getOwnerShareMap() { return ownerShareMap; } public void setOwnerShareMap(@Nullable HashMap<Player, ArrayList<Player>> ownerShareMap) { if (ownerShareMap != null) { this.ownerShareMap = ownerShareMap; } } @Nullable public Map.Entry<Player, ArrayList<Player>> getEntryFromName(String name) { for (Map.Entry<Player, ArrayList<Player>> entry : ownerShareMap.entrySet()) { if (entry.getKey().getName().equals(name)) { return entry; } } return null; } @Nullable private Map.Entry<Player, ArrayList<Player>> getEntry(Player player) { for (Map.Entry<Player, ArrayList<Player>> entry : ownerShareMap.entrySet()) { if (entry.getKey().equals(player)) { return entry; } } return null; } public void addSharePlayer(Player owner, Player sharePlayer, @Nullable ICommandSender sender) { Map.Entry<Player, ArrayList<Player>> entryFound = null; if (owner.equals(sharePlayer)) { return; } for (Map.Entry<Player, ArrayList<Player>> entry : ownerShareMap.entrySet()) { if (entry.getKey().equals(owner)) { entryFound = entry; } } if (entryFound == null) { ArrayList<Player> list = new ArrayList<>(); list.add(sharePlayer); if (sender != null) { sender.sendMessage(new TextComponentString("Added player " + sharePlayer.getName() + " to your Share List!")); } ownerShareMap.put(owner, list); } else { if (!entryFound.getValue().contains(sharePlayer)) { entryFound.getValue().add(sharePlayer); if (sender != null) { sender.sendMessage(new TextComponentString("Added player " + sharePlayer.getName() + " to your Share List!")); } } } OMLibNetworkingHandler.sendMessgeToAllPlayers(new MessageSetSharePlayerList(this)); } public void removeSharePlayer(Player owner, Player sharePlayer, @Nullable ICommandSender sender) { Map.Entry<Player, ArrayList<Player>> entryFound = null; if (owner.equals(sharePlayer)) { if (sender != null) { sender.sendMessage(new TextComponentString("You cannot add/remove yourself to/from your Share List!")); } return; } for (Map.Entry<Player, ArrayList<Player>> entry : ownerShareMap.entrySet()) { if (entry.getKey().equals(owner)) { entryFound = entry; } } if (entryFound != null) { int sizeBefore = entryFound.getValue().size(); Predicate<Player> predicate = p -> p.equals(sharePlayer); entryFound.getValue().removeIf(predicate); if (sender != null) { if (entryFound.getValue().size() < sizeBefore) { sender.sendMessage(new TextComponentString("Removed player " + sharePlayer.getName() + " from your Share List!")); } else { sender.sendMessage(new TextComponentString("Could not remove player " + sharePlayer.getName() + " from your Share List!")); } } } else if (sender != null) { sender.sendMessage(new TextComponentString("Could not remove player " + sharePlayer.getName() + " from your Share List!")); } OMLibNetworkingHandler.sendMessgeToAllPlayers(new MessageSetSharePlayerList(this)); } public void printSharePlayers(Player owner, ICommandSender sender) { StringBuilder playerList = new StringBuilder(); Map.Entry<Player, ArrayList<Player>> entryFound = null; for (Map.Entry<Player, ArrayList<Player>> entry : ownerShareMap.entrySet()) { if (entry.getKey().equals(owner)) { entryFound = entry; } } if (entryFound != null) { ArrayList<Player> list = entryFound.getValue(); for (int i = 0; i < list.size(); i++) { Player player = list.get(i); if (i <= list.size() - 1) { playerList.append(player.getName()); playerList.append(", "); } else { playerList.append(player.getName()); } } } sender.sendMessage(new TextComponentString("Players on your share list: " + playerList.toString())); } public boolean isPlayerSharedOwner(Player owner, Player shareCheck) { Map.Entry<Player, ArrayList<Player>> entry = getEntry(owner); if (entry != null) { for (Player player : entry.getValue()) { if (player.equals(shareCheck)) { return true; } } } return false; } static void saveToDisk() { Path path = Paths.get(DimensionManager.getCurrentSaveRootDirectory().toString() + "/omlib/"); Path fullpath = Paths.get(DimensionManager.getCurrentSaveRootDirectory().toString() + "/omlib/OwnerShare.sav"); try { if (Files.notExists(path)) { if (path.toFile().mkdir()) { throw new Exception("Failed to create dir"); } } if (getInstance() != null && getInstance().getOwnerShareMap() != null) { FileOutputStream saveFile = new FileOutputStream(fullpath.toFile()); ObjectOutputStream save = new ObjectOutputStream(saveFile); save.writeObject(getInstance().getOwnerShareMap()); save.close(); saveFile.close(); } } catch (Exception e) { e.printStackTrace(); try { Files.deleteIfExists(fullpath); } catch (Exception exception) { exception.printStackTrace(); } } } static void loadFromDisk() { HashMap<Player, ArrayList<Player>> input = new HashMap<>(); try { Path fullpath = Paths.get(DimensionManager.getCurrentSaveRootDirectory().toString() + "/omlib/OwnerShare.sav"); FileInputStream saveFile = new FileInputStream(fullpath.toFile()); ObjectInputStream save = new ObjectInputStream(saveFile); Object object = save.readObject(); if (object instanceof HashMap) { input = (HashMap<Player, ArrayList<Player>>) object; } getInstance().setOwnerShareMap(input); save.close(); saveFile.close(); } catch (Exception e) { e.printStackTrace(); } } }
package seedu.ezdo.model; import java.text.ParseException; import java.util.ArrayList; import java.util.EmptyStackException; import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.logging.Logger; import javafx.collections.transformation.FilteredList; import seedu.ezdo.commons.core.ComponentManager; import seedu.ezdo.commons.core.LogsCenter; import seedu.ezdo.commons.core.UnmodifiableObservableList; import seedu.ezdo.commons.events.model.EzDoChangedEvent; import seedu.ezdo.commons.events.model.IsSortedAscendingChangedEvent; import seedu.ezdo.commons.events.model.SortCriteriaChangedEvent; import seedu.ezdo.commons.exceptions.DateException; import seedu.ezdo.commons.util.CollectionUtil; import seedu.ezdo.commons.util.DateUtil; import seedu.ezdo.commons.util.StringUtil; import seedu.ezdo.model.tag.Tag; import seedu.ezdo.model.todo.DueDate; import seedu.ezdo.model.todo.Priority; import seedu.ezdo.model.todo.ReadOnlyTask; import seedu.ezdo.model.todo.StartDate; import seedu.ezdo.model.todo.Task; import seedu.ezdo.model.todo.TaskDate; import seedu.ezdo.model.todo.UniqueTaskList; import seedu.ezdo.model.todo.UniqueTaskList.SortCriteria; import seedu.ezdo.model.todo.UniqueTaskList.TaskNotFoundException; /** * Represents the in-memory model of the ezDo data. All changes to any model * should be synchronized. */ public class ModelManager extends ComponentManager implements Model { private static final Logger logger = LogsCenter.getLogger(ModelManager.class); public static final int STACK_CAPACITY = 5; private final EzDo ezDo; private final FilteredList<ReadOnlyTask> filteredTasks; private final UserPrefs userPrefs; //@@author A0139248X private SortCriteria currentSortCriteria; private Boolean currentIsSortedAscending; private final FixedStack<ReadOnlyEzDo> undoStack; private final FixedStack<ReadOnlyEzDo> redoStack; /** * Initializes a ModelManager with the given ezDo and userPrefs. */ public ModelManager(ReadOnlyEzDo ezDo, UserPrefs userPrefs) { super(); assert !CollectionUtil.isAnyNull(ezDo, userPrefs); logger.fine("Initializing with ezDo: " + ezDo + " and user prefs " + userPrefs); this.ezDo = new EzDo(ezDo); this.userPrefs = userPrefs; filteredTasks = new FilteredList<>(this.ezDo.getTaskList()); currentSortCriteria = userPrefs.getSortCriteria(); currentIsSortedAscending = userPrefs.getIsSortedAscending(); undoStack = new FixedStack<ReadOnlyEzDo>(STACK_CAPACITY); redoStack = new FixedStack<ReadOnlyEzDo>(STACK_CAPACITY); updateFilteredListToShowAll(); } public ModelManager() { this(new EzDo(), new UserPrefs()); } @Override public void resetData(ReadOnlyEzDo newData) { updateStacks(); ezDo.resetData(newData); indicateEzDoChanged(); } //@@author A0139248X @Override public ReadOnlyEzDo getEzDo() { return ezDo; } @Override public UserPrefs getUserPrefs() { return userPrefs; } /** Raises an event to indicate the model has changed */ private void indicateEzDoChanged() { raise(new EzDoChangedEvent(ezDo)); } //@@author A0139248X @Override public synchronized void killTasks(ArrayList<ReadOnlyTask> tasksToKill) throws TaskNotFoundException { updateStacks(); ezDo.removeTasks(tasksToKill); updateFilteredListToShowAll(); indicateEzDoChanged(); } @Override public synchronized void addTask(Task task) throws UniqueTaskList.DuplicateTaskException, DateException { checkTaskDate(task); updateStacks(); ezDo.addTask(task); ezDo.sortTasks(currentSortCriteria, currentIsSortedAscending); updateFilteredListToShowAll(); indicateEzDoChanged(); } //@@author A0139248X @Override public synchronized void doneTasks(ArrayList<Task> doneTasks) { updateStacks(); ezDo.doneTasks(doneTasks); updateFilteredListToShowAll(); indicateEzDoChanged(); } @Override public void updateTask(int filteredTaskListIndex, ReadOnlyTask editedTask) throws UniqueTaskList.DuplicateTaskException, DateException { assert editedTask != null; checkTaskDate(editedTask); updateStacks(); int ezDoIndex = filteredTasks.getSourceIndex(filteredTaskListIndex); ezDo.updateTask(ezDoIndex, editedTask); ezDo.sortTasks(currentSortCriteria, currentIsSortedAscending); indicateEzDoChanged(); } //@@author A0139248X @Override public void undo() throws EmptyStackException { ReadOnlyEzDo currentState = new EzDo(this.getEzDo()); ReadOnlyEzDo prevState = undoStack.pop(); ezDo.resetData(prevState); redoStack.push(currentState); updateFilteredListToShowAll(); indicateEzDoChanged(); } @Override public void redo() throws EmptyStackException { ReadOnlyEzDo prevState = new EzDo(this.getEzDo()); ezDo.resetData(redoStack.pop()); undoStack.push(prevState); updateFilteredListToShowAll(); indicateEzDoChanged(); } @Override public void updateStacks() throws EmptyStackException { ReadOnlyEzDo prevState = new EzDo(this.getEzDo()); undoStack.push(prevState); redoStack.clear(); } @Override public void checkTaskDate(ReadOnlyTask task) throws DateException { assert task != null; try { if (!DateUtil.isTaskDateValid(task)) { throw new DateException("Start date after due date!"); } } catch (ParseException pe) { logger.info("Parse exception while checking if task date valid"); throw new DateException("Error parsing dates!"); } } //@@author A0139248X private void updateFilteredTaskList(Expression expression) { filteredTasks.setPredicate(expression::satisfies); } @Override public void updateFilteredTaskList(ArrayList<Object> listToCompare, boolean startBefore, boolean dueBefore, boolean startAfter, boolean dueAfter) { updateFilteredTaskList(new PredicateExpression(new NameQualifier(listToCompare, startBefore, dueBefore, startAfter, dueAfter))); } @Override public UnmodifiableObservableList<ReadOnlyTask> getFilteredTaskList() { return new UnmodifiableObservableList<>(filteredTasks); } @Override public void updateFilteredListToShowAll() { updateFilteredTaskList(new PredicateExpression(new NotDoneQualifier())); } @Override public void updateFilteredDoneList() { updateFilteredTaskList(new PredicateExpression(new DoneQualifier())); } interface Expression { boolean satisfies(ReadOnlyTask task); @Override String toString(); } private class PredicateExpression implements Expression { private final Qualifier qualifier; PredicateExpression(Qualifier qualifier) { this.qualifier = qualifier; } @Override public boolean satisfies(ReadOnlyTask task) { return qualifier.run(task); } @Override public String toString() { return qualifier.toString(); } } interface Qualifier { boolean run(ReadOnlyTask task); @Override String toString(); } private class DoneQualifier implements Qualifier { DoneQualifier() { } @Override public boolean run(ReadOnlyTask task) { return task.getDone(); } @Override public String toString() { return ""; } } private class NotDoneQualifier implements Qualifier { NotDoneQualifier() { } @Override public boolean run(ReadOnlyTask task) { return !task.getDone(); } @Override public String toString() { return ""; } } private class NameQualifier implements Qualifier { private Set<String> nameKeyWords; private Optional<Priority> priority; private Optional<StartDate> startDate; private Optional<DueDate> dueDate; private Set<String> tags; private boolean startBefore; private boolean dueBefore; private boolean startAfter; private boolean dueAfter; NameQualifier(ArrayList<Object> listToCompare, boolean startBefore, boolean dueBefore, boolean startAfter, boolean dueAfter) { this.nameKeyWords = (Set<String>) listToCompare.get(0); this.priority = (Optional<Priority>) listToCompare.get(1); this.startDate = (Optional<StartDate>) listToCompare.get(2); this.dueDate = (Optional<DueDate>) listToCompare.get(3); this.tags = (Set<String>) listToCompare.get(4); this.startBefore = startBefore; this.dueBefore = dueBefore; this.startAfter = startAfter; this.dueAfter = dueAfter; } @Override public boolean run(ReadOnlyTask task) { Set<String> taskTagStringSet = convertToTagStringSet(task.getTags().toSet()); return (nameKeyWords.contains("") || nameKeyWords.stream() .allMatch(keyword -> StringUtil.containsWordIgnoreCase(task.getName().fullName, keyword))) && !task.getDone() && comparePriority(task.getPriority()) && (((!startBefore && !startAfter) && compareStartDate(task.getStartDate())) || (startBefore && compareBeforeStart(task.getStartDate())) || (startAfter && compareAfterStart(task.getStartDate()))) && (((!dueBefore && !dueAfter) && compareDueDate(task.getDueDate())) || (dueBefore && compareBeforeDue(task.getDueDate())) || (dueAfter && compareAfterDue(task.getDueDate()))) && (taskTagStringSet.containsAll(tags)); } @Override public String toString() { return "name=" + String.join(", ", nameKeyWords); } private Set<String> convertToTagStringSet(Set<Tag> tags) { Object[] tagArray = tags.toArray(); Set<String> tagSet = new HashSet<String>(); for (int i = 0; i < tags.size(); i++) { tagSet.add(((Tag) tagArray[i]).tagName); } return tagSet; } private boolean comparePriority(Priority taskPriority) { String taskPriorityString = taskPriority.toString(); boolean priorityExist = (taskPriorityString.length() != 0); return (!priority.isPresent() || (priority.get().toString().equals("") && priorityExist) || (priorityExist && taskPriorityString.equals(priority.get().toString()))); } private boolean compareStartDate(TaskDate taskStartDate) { String taskStartDateString = taskStartDate.toString(); boolean taskStartDateExist = (taskStartDateString.length() != 0); return (!startDate.isPresent() || (startDate.get().toString().equals("") && taskStartDateExist) || (taskStartDateExist && taskStartDateString.substring(0, 10).equals (startDate.get().toString().substring(0, 10)))); } private boolean compareDueDate(TaskDate taskDueDate) { String taskDueDateString = taskDueDate.toString(); boolean taskDueDateExist = (taskDueDateString.length() != 0); return (!dueDate.isPresent() || (dueDate.get().toString().equals("") && taskDueDateExist) || (taskDueDateExist && taskDueDateString.substring(0, 10).equals (dueDate.get().toString().substring(0, 10)))); } private boolean compareBeforeStart(TaskDate taskStartDate) { String taskStartDateString = taskStartDate.toString(); boolean taskStartDateExist = (taskStartDateString.length() != 0); return (!startDate.isPresent() || (startDate.get().toString().equals("") && taskStartDateExist) || (taskStartDateExist && comesBefore(startDate.get().toString(), taskStartDateString))); } private boolean compareBeforeDue(TaskDate taskDueDate) { String taskDueDateString = taskDueDate.toString(); boolean taskDueDateExist = (taskDueDateString.length() != 0); return (!dueDate.isPresent() || (dueDate.get().toString().equals("") && taskDueDateExist) || (taskDueDateExist && comesBefore(dueDate.get().toString(), taskDueDateString))); } private boolean compareAfterStart(TaskDate taskStartDate) { String taskStartDateString = taskStartDate.toString(); boolean taskStartDateExist = (taskStartDateString.length() != 0); return (!startDate.isPresent() || (startDate.get().toString().equals("") && taskStartDateExist) || (taskStartDateExist && comesBefore(taskStartDateString, startDate.get().toString()))); } private boolean compareAfterDue(TaskDate taskDueDate) { String taskDueDateString = taskDueDate.toString(); boolean taskDueDateExist = (taskDueDateString.length() != 0); return (!dueDate.isPresent() || (dueDate.get().toString().equals("") && taskDueDateExist) || (taskDueDateExist && comesBefore(taskDueDateString, dueDate.get().toString()))); } private boolean comesBefore(String givenDate, String taskDate) { int givenDD = Integer.parseInt(givenDate.substring(0, 2)); int givenMM = Integer.parseInt(givenDate.substring(3, 5)); int givenYYYY = Integer.parseInt(givenDate.substring(6, 10)); int taskDD = Integer.parseInt(taskDate.substring(0, 2)); int taskMM = Integer.parseInt(taskDate.substring(3, 5)); int taskYYYY = Integer.parseInt(taskDate.substring(6, 10)); return (taskYYYY < givenYYYY) || ((taskYYYY == givenYYYY) && (taskMM < givenMM)) || ((taskYYYY == givenYYYY) && (taskMM == givenMM) && (taskDD <= givenDD)); } } //@@author A0138907W /** * Sorts the task in ezDo by the given sort criteria. * * @param sortCriteria The field to sort by. * @param isSortedAscending If true, sorts in ascending order. Otherwise, sorts in descending order. */ @Override public void sortTasks(SortCriteria sortCriteria, Boolean isSortedAscending) { if (!this.currentSortCriteria.equals(sortCriteria)) { this.currentSortCriteria = sortCriteria; indicateSortCriteriaChanged(); } if (!this.currentIsSortedAscending.equals(isSortedAscending)) { this.currentIsSortedAscending = isSortedAscending; indicateIsSortedAscendingChanged(); } ezDo.sortTasks(sortCriteria, isSortedAscending); indicateEzDoChanged(); } //@@author A0139248X /** * Raises a {@code SortCriteriaChangedEvent}. */ public void indicateSortCriteriaChanged() { raise(new SortCriteriaChangedEvent(currentSortCriteria)); } //@@author A0138907W /** * Raises a {@code IsSortedAscendingChangedEvent}. */ public void indicateIsSortedAscendingChanged() { raise(new IsSortedAscendingChangedEvent(currentIsSortedAscending)); } }
package shipit.later; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import com.couchbase.client.java.document.StringDocument; import com.couchbase.client.java.view.DesignDocument; import com.couchbase.client.java.view.View; import com.couchbase.client.java.view.ViewQuery; import com.couchbase.client.java.view.ViewResult; import com.couchbase.client.java.view.ViewRow; public class BucketDownloader extends CouchbaseWorker { public static final String DESIGN_DOC = "CouchDownloader"; public static final String VIEW = "all_docs"; public BucketDownloader(String host, String bucket, String password) { super(host, bucket, password); } private void downloadViews(String outputPath) throws IOException { String viewDir = outputPath + "/views"; File vd = new File(viewDir); if (!vd.exists()) { vd.mkdirs(); System.out.println("Created: " + viewDir); } List<DesignDocument> listDesignDoc = client.getBucket().bucketManager() .getDesignDocuments(); for (DesignDocument dd : listDesignDoc) { String designDocDir = viewDir + "/" + dd.name(); File ddd = new File(designDocDir); ddd.mkdirs(); System.out.println("Created: " + designDocDir); List<View> listView = dd.views(); for (View v : listView) { String viewFileName = designDocDir + "/" + v.name() + ".map.json"; FileOutputStream fos = new FileOutputStream(viewFileName); System.out.println("Writing view: " + viewFileName); fos.write(v.map().getBytes()); if (v.reduce() != null) { String viewReduceFileName = designDocDir + "/" + v.name() + ".reduce.json"; System.out.println("Writing view reduce: " + viewReduceFileName); FileOutputStream rfos = new FileOutputStream( viewReduceFileName); rfos.write(v.reduce().getBytes()); rfos.close(); } fos.close(); } } } public void download(String outputPath) throws IOException { downloadViews(outputPath); // 1: Load the View infos ViewQuery viewQuery = ViewQuery.from(DESIGN_DOC, VIEW); ViewResult result = client.getBucket().query(viewQuery); String documentFileName = outputPath + "/" + Main.OUT_JSON_DOCS_FILENAME; FileOutputStream fos = new FileOutputStream(documentFileName); System.out.println("Writing documents: " + documentFileName); BufferedOutputStream bos = new BufferedOutputStream(fos); FileOutputStream kvFile = new FileOutputStream(outputPath + "/" + Main.OUT_NONJSON_DOCS_FILENAME); BufferedOutputStream kvBos = new BufferedOutputStream(kvFile); try { // 4: Iterate over the Data and print out the full document for (ViewRow row : result) { try { String csvLine = row.id() + "," + row.document().content().toString(); bos.write(csvLine.getBytes()); bos.write("\n".getBytes()); } catch (Exception e) { // System.out.println("Error: " + e); if (e instanceof com.couchbase.client.java.error.TranscodingException) { kvBos.write((row.key().toString() + "," + row.document( StringDocument.class).content()).getBytes()); kvBos.write("\n".getBytes()); } } } } finally { bos.close(); kvBos.close(); } } }
package uk.ac.ebi.atlas.model.baseline; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.SortedSetMultimap; import com.google.common.collect.TreeMultimap; import org.apache.commons.lang3.StringUtils; import org.springframework.context.annotation.Scope; import javax.inject.Named; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import static com.google.common.base.Preconditions.checkState; @Named @Scope("prototype") public class ExperimentalFactorsBuilder { private String defaultQueryType; private Set<Factor> defaultFilterFactors; private Map<String, String> factorNamesByType = new HashMap<>(); private List<FactorGroup> orderedFactorGroups; private Map<String, FactorGroup> orderedFactorGroupsByAssayGroupId; private Set<String> menuFilterFactorTypes; public ExperimentalFactorsBuilder withDefaultQueryType(String defaultQueryType) { this.defaultQueryType = defaultQueryType; return this; } public ExperimentalFactorsBuilder withDefaultFilterFactors(Set<Factor> defaultFilterFactors) { this.defaultFilterFactors = defaultFilterFactors; return this; } public ExperimentalFactorsBuilder withFactorNamesByType(Map<String, String> factorNamesByType) { this.factorNamesByType = factorNamesByType; return this; } public ExperimentalFactorsBuilder withOrderedFactorGroups(List<FactorGroup> orderedFactorGroups) { this.orderedFactorGroups = orderedFactorGroups; return this; } public ExperimentalFactorsBuilder withOrderedFactorGroupsByAssayGroupId(Map<String, FactorGroup> orderedFactorGroupsByAssayGroup) { this.orderedFactorGroupsByAssayGroupId = orderedFactorGroupsByAssayGroup; return this; } public ExperimentalFactorsBuilder withMenuFilterFactorTypes(Set<String> menuFilterFactorTypes) { this.menuFilterFactorTypes = menuFilterFactorTypes; return this; } public ExperimentalFactors create() { checkState(menuFilterFactorTypes != null, "Please provide a set of menu filter factor types"); checkState(StringUtils.isNotBlank(defaultQueryType), "Please provide a non blank defaultQueryType"); checkState(defaultFilterFactors != null, "Please provide a set of filter factors"); SortedSetMultimap<String, Factor> factorsByType = buildFactorsByType(); SortedSetMultimap<Factor, Factor> coOccurringFactors = buildCoOccurringFactors(); return new ExperimentalFactors(factorsByType, factorNamesByType, orderedFactorGroups, coOccurringFactors, menuFilterFactorTypes, orderedFactorGroupsByAssayGroupId, defaultQueryType, defaultFilterFactors); } public ExperimentalFactors createFromXML() { checkState(menuFilterFactorTypes != null, "Please provide a set of menu filter factor types"); checkState(StringUtils.isNotBlank(defaultQueryType), "Please provide a non blank defaultQueryType"); checkState(defaultFilterFactors != null, "Please provide a set of filter factors"); LinkedHashMultimap<String, Factor> xmlFactorsByType = buildXmlFactorsByType(); LinkedHashMultimap<Factor, Factor> coOccurringFactors = buildXmlCoOccurringFactors(); return new ExperimentalFactors(xmlFactorsByType, factorNamesByType, orderedFactorGroups, coOccurringFactors, menuFilterFactorTypes, orderedFactorGroupsByAssayGroupId, defaultQueryType, defaultFilterFactors); } SortedSetMultimap<String, Factor> buildFactorsByType() { SortedSetMultimap<String, Factor> factorsByType = TreeMultimap.create(); for (FactorGroup factorGroup : orderedFactorGroups) { for (Factor factor : factorGroup) { factorsByType.put(factor.getType(), factor); } } return factorsByType; } private LinkedHashMultimap<String, Factor> buildXmlFactorsByType() { LinkedHashMultimap<String, Factor> xmlFactorsByType = LinkedHashMultimap.create(); for(FactorGroup factorGroup : orderedFactorGroups) { for (Factor factor : factorGroup) { xmlFactorsByType.put(factor.getType(), factor); } } return xmlFactorsByType; } SortedSetMultimap<Factor, Factor> buildCoOccurringFactors() { SortedSetMultimap<Factor, Factor> coOccurringFactors = TreeMultimap.create(); for (FactorGroup factorGroup : orderedFactorGroups) { for (Factor factor : factorGroup) { for (Factor value : factorGroup) { if (!value.equals(factor)) { coOccurringFactors.put(factor, value); } } } } return coOccurringFactors; } private LinkedHashMultimap<Factor, Factor> buildXmlCoOccurringFactors() { LinkedHashMultimap<Factor, Factor> xmlCoOccurringFactors = LinkedHashMultimap.create(); for (FactorGroup factorGroup : orderedFactorGroups) { for (Factor factor : factorGroup) { for (Factor value : factorGroup) { if (!value.equals(factor)) { xmlCoOccurringFactors.put(factor, value); } } } } return xmlCoOccurringFactors; } }
package org.cbioportal.genome_nexus.web; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.json.JsonParser; import org.springframework.boot.json.JsonParserFactory; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.RestTemplate; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, properties = { "vep.url=http://grch37.rest.ensembl.org/vep/human/hgvs/VARIANT?content-type=application/json&xref_refseq=1&ccds=1&canonical=1&domains=1&hgvs=1&numbers=1&protein=1", "spring.data.mongodb.uri=mongodb://localhost/integration", "server.port=38893" } ) public class AnnotationIntegrationTest { private final static String BASE_URL = "http://localhost:38893/annotation/"; private RestTemplate restTemplate = new RestTemplate(); private Map<String, Object> fetchVariantAnnotationGET(String variant) { String response = this.restTemplate.getForObject(BASE_URL + variant, String.class); JsonParser springParser = JsonParserFactory.getJsonParser(); return springParser.parseMap(response); } private List<Map<String, Object>> fetchVariantAnnotationPOST(String[] variants) { String responses = this.restTemplate.postForObject(BASE_URL, variants, String.class); JsonParser springParser = JsonParserFactory.getJsonParser(); return (List<Map<String, Object>>)(List<?>) springParser.parseList(responses); } @Test public void testAnnotation() { String[] variants = { "12:g.43130875C>G", "12:g.43130996C>G", "INVALID" }; // GET requests // // test intergenic_consequences String variantAllele = ((HashMap)((ArrayList) this.fetchVariantAnnotationGET(variants[0]).get("intergenic_consequences")).get(0)).get("variantAllele").toString(); // variantAllele should be G assertEquals("G", variantAllele); // POST request // // for each variant we should have one matching instance, except the invalid one assertEquals(variants.length - 1, this.fetchVariantAnnotationPOST(variants).size()); String variantAllele0 = ((HashMap)((ArrayList) this.fetchVariantAnnotationPOST(variants).get(0).get("intergenic_consequences")).get(0)).get("variantAllele").toString(); // the Get and Post should have same result assertEquals(variantAllele, variantAllele0); } @Test public void testAnnotationMT() { String[] variants = { "MT:g.10360G>A", }; // GET requests // String mostSevereConsequence = this.fetchVariantAnnotationGET(variants[0]).get("most_severe_consequence").toString(); // most severe consequence for this MT variant hould be missense_variant assertEquals("missense_variant", mostSevereConsequence); // POST request // // for each variant we should have one matching instance assertEquals(variants.length, this.fetchVariantAnnotationPOST(variants).size()); String mostSevereConsequence0 = this.fetchVariantAnnotationPOST(variants).get(0).get("most_severe_consequence").toString(); assertEquals("missense_variant", mostSevereConsequence0); } @Test public void testLongDeletion() { String[] variants = { // ref allele has 8614 characters "11:g.4967810delTTTTTCTTGCAATATCTCAAGTTTCTTAAAGTGAAAGGGAAGGGAAGAACCAGGAGCATGCTCTTAAAGGAGAATACTATCCCTATTTGGGCAACTCTGACAGTTGTCAGGATTGAGGTGTATCTCAGAGGGTTGTGGATGGCTAGGAATCTATCAAATGACATGATCAGGAGGACTGAGGACTCCAGTACTGAGAATCCATGAATGAAGAATTCCTGGGCAAAGCAGGCATTGGATGAAATTTCAGGAGCATTGAACAGGAAGATGCTTAACACAGTGGGCAGAGATGATAAAGACAAACCCAAGTCTGACATAGCCAACATGGAAAGAAAATAGTACATGGGCTCATGCAAGGAGGGCTCTGTCTTGATGATAAAAAGAATGGTGCCATTTCCTAGAATAGCAATAAGATACATGCTGCAGATGGGGATAGAGATCCAGATGTGTGCATATTCTAGCCCTGGCATCCCAACCAAGAAGAAGGTGGTGATTTCAACATATGATGTGTTGATAATGGACATGATTCATTCATAGGGCTCTGCTATGAAAAATACAGATGCTTGTGTTGGTAAAATAGGAATATCTGTAAATTTAGTAGAAAAAAAGCAGTGTTAAAATTTGTGGCTTCTTTCAGCTTTCTTTTGAGAGAACAAAGCATTTATGTGGCTATCATCATGAAGAGAGATGGTTGGTTGCTGCTTTGGACTATAATCTGTCGTATAATACATTGGAAAAATTATTTCTGGACATGTTATTTCTATAGAGAATCCAGATTTAAATTTTGTATTTAGTTACGCATCTGATTTCATTTTTTCCTGTAAAATATTAGTAAACGCTGGTCAATTAACTGGAATCTTCTATTTCTTGCTCTCAGATCTATGTTCTGACCTTCAGTTCTATGTGATTAATTGCCAGTAATAATAGTCAAATGAAAGCTAAATAAATGAGAATACCTGGGTACTTACCAGTAAGTGGATATGTTTGTAAGCACTTTTGATAAAAGCTAAATAATTCTGATATACAAACCCAAGGTATTGTTGAACTTGTCCACCACAAAAGACTCCTCTTATATATAAGGGCTTGTCTTATTCTTTCTACCTAACCACTGGCTCTGGGATTACTGAGTTCTCTGGGGATTGCAGCAAGGCTAGATTTTGTCTGACAATAAGAATAAACATTTGCAGATGCAGTAAATCTACAGAGATGGTTGATACCAAGGAAACAAACATCTAGGTCTGTAATAAGGAACAATTTTGTTGGAGAGGTCTTTAATTGCCTGGTATTAGATAGACATGGTAAATTATCTGCAAAACTAGGATACTTCTGATGGATAGTTGGCTTGTGTATTACTCGTCTGCACAAGGCCAAGTCTAAGCAGAGATGCTGTGAGTTGATTCTGTATTCAAGGAAGTGTTGCAGGACAAACATCCTAGGACATAATGTGTTATCCTAGATTTTATTCCTGAATCCTGGATCCATCTCCCCAGACCCATTAGACATCACTAATTAAATATCCTTAAAACCAACTTGTCCAACTTATACAAGTTTTTCTCCCTTACCAAATCTTCCCTGTTTAAGGGACCTACTTCGGTAATAAGACTTTATGTTTAAGAATCTACAAGCCAAAAATCTGAGCTTCTTTGTCTTACACACAATAATGACCAATATTTCTTAGAAAATTAAATTGTTTTACTTACTGAGTTCCATTACCAGATGATGATTTGGAATCTTGAAATTTTTTAAATAATATTATCAAGTTATATCATTATCTTCATTTTACTGATGAAGAAAATTTTTCTCAAGATGAAGTCTTCTGTTTAAGATCACAGAAGTGTTGTAGGGTAGAGGTAAGATAGCAACTCAGGTCTGTTATATTACTGATAATTAAGTATATAGCACGCTATCAGGTTTGCCAAGCAATATTTAAGGAGTTATGAACTGAATGTACAGCTGGAATTGTGTATTATTTTTAGCATTCTAAACTGACTACTAGTTGATTCTAGTGGATAAGATGAAACATTTGGTCCTACAGTTGCAAATCTTTGCAACAGTGAAAATCATGCTAGTATAGAGATCCTAAGGAAAAGGCTCTTGAGGAGAAAAAAACTATATACTCACCTCTATTAGTAAATAGTCATTGGAAGGATTTCAATATTTACTTGACTAAAGAGTGGAAATATAAGAATGTATTACCATAACCTTCCCATAAATTCTTTTAAACTATGTGATGATTACTTCTTAGTTGCCAATTGCCTACTGTTTGCATCCCCAATGAAAATAAGCCCCACTTGGTTATGTTGTCAAGAATTCTCTCCTTCCACTGTTGCTTTTTCTCTTAGCTTTCTCCAGGTACTTCTTATTAAAGAGATAGCAGAAAGTTTGTGTATGTTTGTGTGTGTGAAAATTGCTTTGACAAGGACATGTGCTCATTGGCTCAATGTTCATGTGTTCATTGGCTCAATGTTCAACTTTGTGGACCAAATCAATTTGTTTCATGACAATTTAAAGTAAGCTACAGTAAGACAGGCAGTGCATTACTATCATGGTGGATGGCATATAGTAGCTTATTAAATACTTGTTGAATGAATAAATGATTGTATTTTTTAAACTGGCATCTTTTTTATCTTTATTATTATTTTTCCCATTGTGCTACGTTTGCTATGAAATAAAAATATGGGTTTTAGCAATTGTAAAAACTATTCTCAAGGATTTTTACATTGTAATCTAGTATTAATTTTCAACTTAATTTACATAATATGTTTTAAAAGTGTTATTTATGTACAAAGAATATTAATATACAGCTATAATTATAATAATAAAATGAGGCATGTATATTAATTATTAATATCTCATTCTAGAGACGTGAAGTATTGTTCTTGTAAAAAACAAAATGTTGCAAATCAGTTGAGGTTTCTCTTGGCCCCATATACTGAAATAATAGTGAAGGGGGGCAAATCATACAGATGAGATACAGCTAAAGCAGTTCCTATACAGAAAATTATAGGTTAAATTTATTTATTAGGAAATAAGAGTTGAAAAATCAAAAAATGTAACTTCTATTTCAAGAAGATAGTGAAGGAATAACAACAAAATCTCCAAAAAAATGAAGAAAATAAACTGGTAAAATCAGAAATGAATAAAATAGAAATATGATATAAAATAATGTCATCAAAGCAGAAATTTCATTCCTTAACAAGTTTTAAAAAATCCATAATTTAACAAAACTGAAAGAATAAAGAGATAAAACACTAAACTTATTTTAATGTATACCATTTGAACTAATGTATGTATACCCATTTCAGGGTATACATACCCATTTCAGGTACCCAGAATATGCCATTTGAACTAATGGCACTTATTCCGGAGTCATGAAAATTTTACATTTCAATCTTTATGGTAAGGCATTAGAATCACCCAGGGAGCTCTCAAAAGTTGTGATATTCAGGTTCACTTGATTTATGACAGTGACACAATTCTATAAGGAATAGATGGTATTTACAATAGATAGAGCAATTTAAATGCAAGTAGAAAGAAAGAAATCTTGAGTTTTATCAAAACATTAATTTGAGTTGGACAATAGGCCTAAGTATTCAAGGTAAAACAAAAAATCTTGTAGAAAAACTATGGTAATATTTTCATGATTTGGGATAACCATGGATACAACCAGGAAAAACAAATTTCATAGACAGAATTAATTAATAGAAAGCATTTCCATGGAAAGACCTCTGGGAATAAATAATATCATCATATGGAATAGTACTCAGCCTTAAAAAAAGGATGAAATTCTGTCATTTGCTACAACATGGATGGAACTGGAGAACATTATGTTAAATAAAATAAGCCAGGCACAGAAAGACAAACACTGCATGTTCTCACTTAGATGTGGAATCTAAAACAATTGAACTCATAGAAACAAAGTAGCATGATGAATACTAGATGATGGGGATGGGGGGAGTCTGGAGATGATAGTCAAAAGGTAAAAAGTTAGAAAGAATAAATTCGATTATTTTATAACAATAGCACAGCATGCTGAATATAGCTAATATTTGAGTCCTCTGTATTTCAATATTTCTAAGAGTAAATTTCTAATGTTCTCATCAAAAAAAAATATTATTATTATATATATCTGACAAATGATATGTAAAGAACTGCAAATGAATAAGTAAAATTCAGTAAAAAATAGGCAATGCACTTGACTTGCACTGTTCAATTTGCATTTGGAAAAATGCAAATTAATATCACAATGAGGTATTATATCATACCCATTAGAATGGCTAACATCAAAAAGAATAACAATCCCAAATTGTGGTGAATATGTGGAGAACTAGAATGCTTACACTTTGCTATTAGATGTGTAAATCAGTGCAAGTTCTTTGGTGACAAAGTTTAGCATTATCTTCTATAGGTACATAAATACCTACCCTATGACTTAAAATATCATTTCTAAAAAAGTTAGTTCCTGTTTCAAGCAAACACATTCTAAGAATGTCTATAGGAACTTTATCATATTAGCCAACATTTGAAAAAGACTCTAATATTCATCAACATGTGAATGGGTAAAATTGAATTAGGTATTCTGATTTAATTGACTATGATGTTAACCTGAATATCACAACTTTTGAGAGCTCCCTGGGTGATTTTAATGCCTTACCATAAAGATTGAAATGTAAAATTTTCATGACTCCAGAATAAGTGCCATTAGTTCAAATGGCATATTTCTGGGTACCTGTCTGTCTTTGATGGCTTGATTTCTCCATGAGTCACAATTACTGCTAGGTACAAAGGTACTTAATCACTGATGCAGAATAATGTATGCTTTTTAAAGTGCTACCAGTGAACTCTCTCCAGGCTGTTACATAAACTGATTTCTTAGATTATCATTTAGTGATCATTTTTTGTAAATAATATTTTTGTTATTATTGTTTCTCACTGAAGTGATTCTGCCATTATTGGCTGTTCTAGTAGATAAATACTGGGTTGTTAGGTTTCTTAAAAAATAATTTTTATGTTGTTTGTTCCTGTCTGATACCATTTCTCCAAACTTTCTGGAAAGAGAATGGCCATTTTAATATATCACAGTCACAGTGATAGGGGTTGTGGCACAGAGATTGGCATATGAACCAATTGCACCAGTCACATTAAGTTTTTATCCTTGGTATACTGATTACTTCTGCTTAGAATATTAAGGAAGCTATTAAACATTTTTCTTTTAAGTGGATCTGAGAGTGACAGTTCTCTCTCCTCTCTTCATTGAGAGAGAAAAAGTGCTCTACTGCCTATTTGTCTGCCCACGATTTAGCAAACTACGTGGGTTAGTTTTGTTCAAAACACGTATAGAAACAAAACAGAGAGCTGAAGCATGTAAGTTAGCGGTGATAACAACTTCTTTGCAGCACTTAAGTGTCCTGTAGCTCACAAGGTTCCTACAACTTTTAATTCAAGTCTGTCTGCTGTTATGATATTTTACCTCAGAATGTTTACGTTTCTTTAAGATAATATTGGGTTTGCTGTTGTTTGCCATGTTCTTCATTTCAGGAACATGTGCAAATCATTATGTTCACCATAAATCATCACCTCCCCCATAGGCATTCATGTATCTGTATTTTATTTTTCATTTTATTTTATTAAGACTGCCCAAAACCCCAAAAATACAGATTATCTTTGAGACTCTTGAATGAGACATCTATGTACAATATCCTGAAAGAATAAGATGCTTATTAAAGCCAACTAATTGCTCCTCATCTTGTTAGTGGAAATGAAGTCTTTATATTGAGCTGCCTATCCTCACCCTGAGAGAATAGGAGCTTCTGTTTCTTTCAATTAATAAAGCATGTCAACTACTGCTTTGTTGTACTACAACCCCAAACCCATATCTGTATTTGTAAGACTTTGGAAAAGGCAGATGGATATAGTTACGCACCTTGAACACAGAAGCAGTTCTTGCCCTGATCTGATAATAGGATTTCCTATACTAGGACAGGTTTGTGAAAACATATGTAGTTCTGAATTTAAAAACTAAAATGTACTCAAGATAATACTATCCTGGAGTATCAGAGATTAGGTTTGAATCCCAGCTTTTGATTTCCTCTCTGTGTGAGTTTCATAAAATCAAACTCTCAGAGCCTCAATCTCTTCAACTAAAATAAATAAGAAAAAACCCTTTATAAAAAGCTGGGTCATTGTGAAAAATAGCTTTTTTAAAATGCCTAAAAATACCTGGAAGCACATCGTGCATGTATTAGAGGTTTGAAAGCAATACTTGTATCTATTAAAATTTTCCATTAATTGGGAGGTACTGTCAGCTGTGGGCTGATTATTTTTTTTAAGCATTTGACATTCCTGGAAGGTGTTTCTTGATTTACCTGAGGATGAAGTGTAGGAGACTTGAACTGGCATGGTTGATGGAAATGACTTGATTCAACGAGTGGGTAAAATGAAAAGGCTAAAGTGGTTTTCACAATATGCAAGATTTTGAGGTCATAGTGGGAAGGAAAGTTGGACTATTTTTCAGCCACAAATCTAAAGCAATAAATTTCTCTTTGTACCATATCTTTTTTCCTGTTTTAAAAATCTTTAGCATCAATGATACGCCTGTATTTGAAATAGACAATTTAAGAAAATTGTATCCTACCATGAATAAATATTACTAAACTCTTCAGAGAGCAAGTTTTTCTACAAACATGGTCTTATTTTTAAAATCATTCATTAGCATTTATTTATTGAACTCTACTCTTCATCAGAAATGTTCTAGACATTAGGTAGGAAAAATTAAAGAAAATAGATAGGTTTCTTCAATCGCTCATAATACACTTTATTCAAGAAGTAGAAAGAAATGAAATAAGCACAAAAGTTATCTATAATTGCAAATATTAAGTATAATAAAGAATAAAGAATAAACAAGTAATAAAAGAGATAAAAGAGAGGGTCATAATACAAGCTTGGGCTAGGTAATTTATGATGAAATTAAGCCAACATTTAAAGAAAAAAGAAAAGGAATGCCTTACACAAAATTGGTGTCAAGCATTTTAACAAAAGAGTTCTGATGTGAAAACTCACAGGAAGAAAAGAGCTCTGTAAATTCAAAAACGATTCAGTAGGTCAATGTGGCTGGAGATTAATGAATATCTGATGATGTTGAACAAGTAGAAAGGGTCCAGCTCATGTAGGGTCTCGGAATATGTTCTTCCTTCGGCTTGGCGTGTTGGCTCACGCCTGTAATACCAGCACTTTGGGAGGCCAAGGCAGGCGGATCACTTGAGGTCAGGAGTTTGAGACCAACCTGGCCAACATGGTGAAACCCTGTCTCTACAAAAAATACAAAAATCAGCCAGGCGTGGTGACATGCGCCTGTAATCCTAGATACTCGGGAGGCTGAGAGGCAAGAGAATCGCTTGAACCTGGGAGGCGGAGGTTGCAGTGAGCAGAGATTGTGCTACTGCACCCCAGCTTGGGCTACAGAGCAAGATTTCGTCTCAAAAAAAATTTCTTTATTGATTTAATTGTATTTCTAAAGAAGTGAGAGTTCAAATTTAAAAGAGGCACTCATATATTCAGTTTGCCTTTTTAATTACTCTTGCCTTGCATAGCGAATCTTTTATAAGGCAGGGAACTTAGCAATATTTTACTGAAGAAATGCTTGGTGACTTCTAGGGTGGGGAAATGATGGGGCGGGGATTGGACTGAAAAACTATCTGTTGGGTACTATGCTCACTACCTGGGTCCAATACCCATGTAAAAATCCAACCCATATCAAATATAAAAGCTGGAATTTAAAAAAGATGGTGACATACTAACATGATTAAAATGGATAGAGAGACAGATATAATATAAAATTTGGGTCTAGCAGTAAAAGAACCTGGTATAGAGAGACTGAATGTAGATAACGAGGAATCCAACTTCTGTCAGAACTGTAAAAATTATCGTTTTTCTGTCTTGGTTGTAATTTGTTGTTTGTATCAGAGGTGCTATCATAAGACATTTATTTTTATTCTGCTTAACTGAAATGGGGACATAAGGCAACGTACTTCCTGGTTACAGTTTTATTCCCATTCTCAGTATCTAGAGTGAATAAAATAAGTCTGTGATAACGATAAAAATATGTGTTGATAATTCTTGGTGTCAAATATTAGGTTTCTCAAATTTACCTTAAATATCTTACCAGACATTTCCAGGTTTTCTGTCACATATGACTGTTAAATCTTCCATTGACACAATTTTGCTACAACTCTCACTCTAATCTGTTTAGTTTTTACACAATAAACAATTGGTTTCATCAGCGGAGGTACAAGTAGGAGAACATTTGCCATGAGAACATTAATGAGGGGAGAGACATGCCCGGCAAAGCGGTGGACAACGGCCAGGTTGATGATGGGCAGGTAGAAGATGATCACTGCACAGATGTGTGAAACACAAGTATTGAGAGCCTTAAGCTCCTCCTTTTTGGATGCAATTCCCGGTACAGTCTTGAGGATCAGGGTGTAAGACACAGCAATGAGAATAAAGTCTACCATAAGGCAGAGTGCTCCAAAAAAGCCATAGATAACATCAATTCTGTTGTCAGAACAGGCCAACTTCATGACATCCTGGTGGAGACAGTAGGAATGGGATAATTGGT", }; // GET requests // String assemblyName = this.fetchVariantAnnotationGET(variants[0]).get("assembly_name").toString(); // most severe consequence for this MT variant hould be missense_variant assertEquals("GRCh37", assemblyName); // POST request // // for each variant we should have one matching instance assertEquals(variants.length, this.fetchVariantAnnotationPOST(variants).size()); String assemblyName0 = this.fetchVariantAnnotationPOST(variants).get(0).get("assembly_name").toString(); assertEquals("GRCh37", assemblyName0); } }
package tigase.db.jdbc; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import tigase.db.AuthorizationException; import tigase.db.DBInitException; import tigase.db.RepositoryFactory; import tigase.db.TigaseDBException; import tigase.db.UserAuthRepository; import tigase.db.UserAuthRepositoryImpl; import tigase.db.UserExistsException; import tigase.db.UserNotFoundException; import tigase.db.UserRepository; import tigase.util.SimpleCache; /** * Not synchronized implementation! * Musn't be used by more than one thread at the same time. * <p> * Thanks to Daniele for better unique IDs handling. * Created: Thu Oct 26 11:48:53 2006 * </p> * @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a> * @author <a href="mailto:piras@tiscali.com">Daniele</a> * @version $Rev$ */ public class JDBCRepository implements UserAuthRepository, UserRepository { private static final Logger log = Logger.getLogger("tigase.db.jdbc.JDBCRepository"); public static final String DEF_USERS_TBL = "tig_users"; public static final String DEF_NODES_TBL = "tig_nodes"; public static final String DEF_PAIRS_TBL = "tig_pairs"; public static final String DEF_MAXIDS_TBL = "tig_max_ids"; public static final String DEF_ROOT_NODE = "root"; private static final String USER_STR = "User: "; private String users_tbl = DEF_USERS_TBL; private String nodes_tbl = DEF_NODES_TBL; private String pairs_tbl = DEF_PAIRS_TBL; private String maxids_tbl = DEF_MAXIDS_TBL; private String root_node = DEF_ROOT_NODE; private UserAuthRepository auth = null; private String db_conn = null; private Connection conn = null; private PreparedStatement uid_st = null; private PreparedStatement node_add_st = null; private PreparedStatement data_for_node_st = null; private PreparedStatement keys_for_node_st = null; private PreparedStatement nodes_for_node_st = null; private PreparedStatement insert_key_val_st = null; private PreparedStatement remove_key_data_st = null; private PreparedStatement conn_valid_st = null; private Map<String, Object> cache = null; private long lastConnectionValidated = 0; private long connectionValidateInterval = 1000*60; private boolean autoCreateUser = false; private static long var_max_uid = 0; private static long var_max_nid = 0; /** * Describe <code>getMaxUid</code> method handles unique IDs much better for * distributed environment than the old code. * Thank's to Daniele for the help and the code. * * @return a <code>long</code> value */ private long getMaxUid() { return (System.currentTimeMillis() * 100) + ((var_max_uid++) % 100); } /** * <code>getMaxNid</code> method handles unique IDs much better for * distributed environment than the old code. * Thank's to Daniele for the help and the code. * * @return a <code>long</code> value */ private long getMaxNid() { return (System.currentTimeMillis() * 100) + ((var_max_nid++) % 100); } private void release(Statement stmt, ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException sqlEx) { } } if (stmt != null) { try { stmt.close(); } catch (SQLException sqlEx) { } } } private boolean checkConnection() throws SQLException { try { long tmp = System.currentTimeMillis(); if ((tmp - lastConnectionValidated) >= connectionValidateInterval) { conn_valid_st.executeQuery(); lastConnectionValidated = tmp; } // end of if () } catch (Exception e) { initRepo(); } // end of try-catch return true; } private long getUserUID(String user_id) throws SQLException, UserNotFoundException { Long cache_res = (Long)cache.get(user_id); if (cache_res != null) { return cache_res.longValue(); } // end of if (result != null) ResultSet rs = null; long result = -1; try { uid_st.setString(1, user_id); rs = uid_st.executeQuery(); if (rs.next()) { result = rs.getLong(1); } else { if (autoCreateUser) { result = addUserRepo(user_id); } else { throw new UserNotFoundException("User does not exist: " + user_id); } // end of if (autoCreateUser) else } // end of if (isnext) else } finally { release(null, rs); } cache.put(user_id, new Long(result)); return result; } // private void incrementMaxUID() throws SQLException { // Statement stmt = null; // try { // stmt = conn.createStatement(); // // Update max_uid to current value // stmt.executeUpdate("update " + maxids_tbl + " set max_uid=(max_uid+1);"); // } finally { // release(stmt, null); // stmt = null; // private void incrementMaxNID() throws SQLException { // Statement stmt = null; // try { // stmt = conn.createStatement(); // // Update max_uid to current value // stmt.executeUpdate("update " + maxids_tbl + " set max_nid=(max_nid+1);"); // } finally { // release(stmt, null); // stmt = null; private String buildNodeQuery(long uid, String node_path) { String query = "select nid as nid1 from " + nodes_tbl + " where (uid = " + uid + ")" + " AND (parent_nid is null)" + " AND (node = '" + root_node + "')"; if (node_path == null) { return query; } else { StringTokenizer strtok = new StringTokenizer(node_path, "/", false); int cnt = 1; String subquery = query; while (strtok.hasMoreTokens()) { String token = strtok.nextToken(); ++cnt; subquery = "select nid as nid" + cnt + ", node as node" + cnt + " from " + nodes_tbl + ", (" + subquery + ") nodes" + (cnt-1) + " where (parent_nid = nid" + (cnt-1) + ")" + " AND (node = '" + token + "')"; } // end of while (strtok.hasMoreTokens()) return subquery; } // end of else } private long getNodeNID(long uid, String node_path) throws SQLException, UserNotFoundException { String query = buildNodeQuery(uid, node_path); Statement stmt = null; ResultSet rs = null; try { stmt = conn.createStatement(); rs = stmt.executeQuery(query); if (rs.next()) { return rs.getLong(1); } else { return -1; } // end of if (isnext) else } finally { release(stmt, rs); stmt = null; rs = null; } } private long getNodeNID(String user_id, String node_path) throws SQLException, UserNotFoundException { Long cache_res = (Long)cache.get(user_id+"/"+node_path); if (cache_res != null) { return cache_res.longValue(); } // end of if (result != null) long uid = getUserUID(user_id); long result = getNodeNID(uid, node_path); if (result > 0) { cache.put(user_id+"/"+node_path, new Long(result)); } // end of if (result > 0) return result; } private long addNode(long uid, long parent_nid, String node_name) throws SQLException { long new_nid = getMaxNid(); node_add_st.setLong(1, new_nid); if (parent_nid < 0) { node_add_st.setNull(2, Types.BIGINT); } else { node_add_st.setLong(2, parent_nid); } // end of else node_add_st.setLong(3, uid); node_add_st.setString(4, node_name); node_add_st.executeUpdate(); //incrementMaxNID(); return new_nid; } private long createNodePath(String user_id, String node_path) throws SQLException, UserNotFoundException { if (node_path == null) { // Or should I throw NullPointerException? return getNodeNID(user_id, null); } // end of if (node_path == null) long uid = getUserUID(user_id); long nid = getNodeNID(uid, null); StringTokenizer strtok = new StringTokenizer(node_path, "/", false); String built_path = ""; while (strtok.hasMoreTokens()) { String token = strtok.nextToken(); built_path = built_path + "/" + token; long cur_nid = getNodeNID(uid, built_path); if (cur_nid > 0) { nid = cur_nid; } else { nid = addNode(uid, nid, token); } // end of if (cur_nid > 0) else } // end of while (strtok.hasMoreTokens()) return nid; } private void initPreparedStatements() throws SQLException { String query = "select uid from " + users_tbl + " where user_id = ?;"; uid_st = conn.prepareStatement(query); query = "insert into " + nodes_tbl + " (nid, parent_nid, uid, node)" + " values (?, ?, ?, ?);"; node_add_st = conn.prepareStatement(query); query = "select pval from " + pairs_tbl + " where (nid = ?) AND (pkey = ?);"; data_for_node_st = conn.prepareStatement(query); query = "select pkey from " + pairs_tbl + " where (nid = ?);"; keys_for_node_st = conn.prepareStatement(query); query = "select nid, node from " + nodes_tbl + " where parent_nid = ?;"; nodes_for_node_st = conn.prepareStatement(query); query = "insert into " + pairs_tbl + " (nid, uid, pkey, pval) " + " values (?, ?, ?, ?)"; insert_key_val_st = conn.prepareStatement(query); query = "delete from " + pairs_tbl + " where (nid = ?) AND (pkey = ?)"; remove_key_data_st = conn.prepareStatement(query); query = "select localtime;"; conn_valid_st = conn.prepareStatement(query); } // Implementation of tigase.db.UserRepository private void initRepo() throws SQLException { Statement stmt = null; ResultSet rs = null; try { conn = DriverManager.getConnection(db_conn); conn.setAutoCommit(true); initPreparedStatements(); auth = new UserAuthRepositoryImpl(this); stmt = conn.createStatement(); // // load maximum ids // String query = "SELECT max_uid, max_nid FROM " + maxids_tbl; // rs = stmt.executeQuery(query); // rs.next(); // max_uid = rs.getLong("max_uid"); // max_nid = rs.getLong("max_nid"); cache = new SimpleCache<String, Object>(10000); } finally { release(stmt, rs); stmt = null; rs = null; } } public String getResourceUri() { return db_conn; } /** * Describe <code>initRepository</code> method here. * * @param connection_str a <code>String</code> value */ public void initRepository(final String connection_str) throws DBInitException { db_conn = connection_str; if (db_conn.contains("autoCreateUser=true")) { autoCreateUser=true; } // end of if (db_conn.contains()) try { initRepo(); log.info("Initialized database connection: " + connection_str); } catch (SQLException e) { conn = null; throw new DBInitException("Problem initializing jdbc connection: " + db_conn, e); } } /** * Describe <code>getUsers</code> method here. * * @return a <code>List</code> value */ public List<String> getUsers() throws TigaseDBException { Statement stmt = null; ResultSet rs = null; try { stmt = conn.createStatement(); // Load all user ids from database rs = stmt.executeQuery("SELECT user_id FROM " + users_tbl); List<String> users = new ArrayList<String>(); while (rs.next()) { users.add(rs.getString(1)); } // end of while (rs.next()) return users; } catch (SQLException e) { throw new TigaseDBException("Problem loading user list from repository", e); } finally { release(stmt, rs); stmt = null; rs = null; } } private long addUserRepo(final String user_id) throws SQLException { checkConnection(); Statement stmt = null; String query = null; long uid = getMaxUid(); try { stmt = conn.createStatement(); // Add user into database. query = "insert into " + users_tbl + " (uid, user_id) values (" + uid + ", '" + user_id + "');"; stmt.executeUpdate(query); // incrementMaxUID(); addNode(uid, -1, root_node); } finally { release(stmt, null); stmt = null; } cache.put(user_id, new Long(uid)); return uid; } /** * Describe <code>addUser</code> method here. * * @param user_id a <code>String</code> value * @exception UserExistsException if an error occurs */ public void addUser(final String user_id) throws UserExistsException, TigaseDBException { try { addUserRepo(user_id); } catch (SQLException e) { throw new UserExistsException("Error adding user to repository: ", e); } } /** * Describe <code>removeUser</code> method here. * * @param user_id a <code>String</code> value * @exception UserNotFoundException if an error occurs */ public void removeUser(final String user_id) throws UserNotFoundException, TigaseDBException { Statement stmt = null; ResultSet rs = null; String query = null; try { checkConnection(); stmt = conn.createStatement(); // Get user account uid long uid = getUserUID(user_id); // Remove all user enrties from pairs table query = "delete from " + pairs_tbl + " where uid = " + uid; stmt.executeUpdate(query); // Remove all user entries from nodes table query = "delete from " + nodes_tbl + " where uid = " + uid; stmt.executeUpdate(query); // Remove user account from users table query = "delete from " + users_tbl + " where uid = " + uid; stmt.executeUpdate(query); } catch (SQLException e) { throw new TigaseDBException("Error removing user from repository: " + query, e); } finally { release(stmt, rs); stmt = null; cache.remove(user_id); //cache.clear(); } } /** * Describe <code>getDataList</code> method here. * * @param user_id a <code>String</code> value * @param subnode a <code>String</code> value * @param key a <code>String</code> value * @return a <code>String[]</code> value * @exception UserNotFoundException if an error occurs */ public String[] getDataList(final String user_id, final String subnode, final String key) throws UserNotFoundException, TigaseDBException { // String[] cache_res = (String[])cache.get(user_id+"/"+subnode+"/"+key); // if (cache_res != null) { // return cache_res; // } // end of if (result != null) ResultSet rs = null; try { checkConnection(); long nid = getNodeNID(user_id, subnode); if (nid > 0) { List<String> results = new ArrayList<String>(); data_for_node_st.setLong(1, nid); data_for_node_st.setString(2, key); rs = data_for_node_st.executeQuery(); while (rs.next()) { results.add(rs.getString(1)); } String[] result = results.size() == 0 ? null : results.toArray(new String[results.size()]); //cache.put(user_id+"/"+subnode+"/"+key, result); return result; } else { return null; } // end of if (nid > 0) else } catch (SQLException e) { throw new TigaseDBException("Error getting data list.", e); } finally { release(null, rs); } } /** * Describe <code>getSubnodes</code> method here. * * @param user_id a <code>String</code> value * @param subnode a <code>String</code> value * @return a <code>String[]</code> value * @exception UserNotFoundException if an error occurs */ public String[] getSubnodes(final String user_id, final String subnode) throws UserNotFoundException, TigaseDBException { ResultSet rs = null; try { checkConnection(); long nid = getNodeNID(user_id, subnode); if (nid > 0) { List<String> results = new ArrayList<String>(); nodes_for_node_st.setLong(1, nid); rs = nodes_for_node_st.executeQuery(); while (rs.next()) { results.add(rs.getString(2)); } return results.size() == 0 ? null : results.toArray(new String[results.size()]); } else { return null; } // end of if (nid > 0) else } catch (SQLException e) { throw new TigaseDBException("Error getting subnodes list.", e); } finally { release(null, rs); } } /** * Describe <code>getSubnodes</code> method here. * * @param user_id a <code>String</code> value * @return a <code>String[]</code> value * @exception UserNotFoundException if an error occurs */ public String[] getSubnodes(final String user_id) throws UserNotFoundException, TigaseDBException { return getSubnodes(user_id, null); } private void deleteSubnode(long nid) throws SQLException { Statement stmt = null; ResultSet rs = null; String query = null; try { stmt = conn.createStatement(); query = "delete from " + pairs_tbl + " where nid = " + nid; stmt.executeUpdate(query); query = "delete from " + nodes_tbl + " where nid = " + nid; stmt.executeUpdate(query); query = "select nid from " + nodes_tbl + " where parent_nid = " + nid; rs = stmt.executeQuery(query); // I am not really sure if this is correct, besides it is not save for // many JDBC drivers to call a query while reading results from another // query. // while (rs.next()) { // long subnode_nid = rs.getLong(1); // deleteSubnode(subnode_nid); // } // end of while (rs.next()) } finally { release(stmt, rs); } } /** * Describe <code>removeSubnode</code> method here. * * @param user_id a <code>String</code> value * @param subnode a <code>String</code> value * @exception UserNotFoundException if an error occurs */ public void removeSubnode(final String user_id, final String subnode) throws UserNotFoundException, TigaseDBException { if (subnode == null) { return; } // end of if (subnode == null) try { checkConnection(); long nid = getNodeNID(user_id, subnode); if (nid > 0) { deleteSubnode(nid); cache.remove(user_id+"/"+subnode); } } catch (SQLException e) { throw new TigaseDBException("Error getting subnodes list.", e); } } /** * Describe <code>setDataList</code> method here. * * @param user_id a <code>String</code> value * @param subnode a <code>String</code> value * @param key a <code>String</code> value * @param list a <code>String[]</code> value * @exception UserNotFoundException if an error occurs */ public void setDataList(final String user_id, final String subnode, final String key, final String[] list) throws UserNotFoundException, TigaseDBException { removeData(user_id, subnode, key); addDataList(user_id, subnode, key, list); } /** * Describe <code>addDataList</code> method here. * * @param user_id a <code>String</code> value * @param subnode a <code>String</code> value * @param key a <code>String</code> value * @param list a <code>String[]</code> value * @exception UserNotFoundException if an error occurs */ public void addDataList(final String user_id, final String subnode, final String key, final String[] list) throws UserNotFoundException, TigaseDBException { try { checkConnection(); long uid = getUserUID(user_id); long nid = getNodeNID(uid, subnode); if (nid < 0) { nid = createNodePath(user_id, subnode); } insert_key_val_st.setLong(1, nid); insert_key_val_st.setLong(2, uid); insert_key_val_st.setString(3, key); for (String val: list) { insert_key_val_st.setString(4, val); insert_key_val_st.executeUpdate(); } // end of for (String val: list) } catch (SQLException e) { throw new TigaseDBException("Error getting subnodes list.", e); } // cache.put(user_id+"/"+subnode+"/"+key, list); } /** * Describe <code>getKeys</code> method here. * * @param user_id a <code>String</code> value * @param subnode a <code>String</code> value * @return a <code>String[]</code> value * @exception UserNotFoundException if an error occurs */ public String[] getKeys(final String user_id, final String subnode) throws UserNotFoundException, TigaseDBException { ResultSet rs = null; try { checkConnection(); long nid = getNodeNID(user_id, subnode); if (nid > 0) { List<String> results = new ArrayList<String>(); keys_for_node_st.setLong(1, nid); rs = keys_for_node_st.executeQuery(); while (rs.next()) { results.add(rs.getString(1)); } return results.size() == 0 ? null : results.toArray(new String[results.size()]); } else { return null; } // end of if (nid > 0) else } catch (SQLException e) { throw new TigaseDBException("Error getting subnodes list.", e); } finally { release(null, rs); } } /** * Describe <code>getKeys</code> method here. * * @param user_id a <code>String</code> value * @return a <code>String[]</code> value * @exception UserNotFoundException if an error occurs */ public String[] getKeys(final String user_id) throws UserNotFoundException, TigaseDBException { return getKeys(user_id, null); } /** * Describe <code>getData</code> method here. * * @param user_id a <code>String</code> value * @param subnode a <code>String</code> value * @param key a <code>String</code> value * @param def a <code>String</code> value * @return a <code>String</code> value * @exception UserNotFoundException if an error occurs */ public String getData(final String user_id, final String subnode, final String key, final String def) throws UserNotFoundException, TigaseDBException { // String[] cache_res = (String[])cache.get(user_id+"/"+subnode+"/"+key); // if (cache_res != null) { // return cache_res[0]; // } // end of if (result != null) ResultSet rs = null; try { checkConnection(); long nid = getNodeNID(user_id, subnode); if (nid > 0) { String result = def; data_for_node_st.setLong(1, nid); data_for_node_st.setString(2, key); rs = data_for_node_st.executeQuery(); if (rs.next()) { result = rs.getString(1); } //cache.put(user_id+"/"+subnode+"/"+key, new String[] {result}); return result; } else { return def; } // end of if (nid > 0) else } catch (SQLException e) { throw new TigaseDBException("Error getting data list.", e); } finally { release(null, rs); } } /** * Describe <code>getData</code> method here. * * @param user_id a <code>String</code> value * @param subnode a <code>String</code> value * @param key a <code>String</code> value * @return a <code>String</code> value * @exception UserNotFoundException if an error occurs */ public String getData(final String user_id, final String subnode, final String key) throws UserNotFoundException, TigaseDBException { return getData(user_id, subnode, key, null); } /** * Describe <code>getData</code> method here. * * @param user_id a <code>String</code> value * @param key a <code>String</code> value * @return a <code>String</code> value * @exception UserNotFoundException if an error occurs */ public String getData(final String user_id, final String key) throws UserNotFoundException, TigaseDBException { return getData(user_id, null, key, null); } /** * Describe <code>setData</code> method here. * * @param user_id a <code>String</code> value * @param subnode a <code>String</code> value * @param key a <code>String</code> value * @param value a <code>String</code> value * @exception UserNotFoundException if an error occurs */ public void setData(final String user_id, final String subnode, final String key, final String value) throws UserNotFoundException, TigaseDBException { setDataList(user_id, subnode, key, new String[] {value}); } /** * Describe <code>setData</code> method here. * * @param user_id a <code>String</code> value * @param key a <code>String</code> value * @param value a <code>String</code> value * @exception UserNotFoundException if an error occurs */ public void setData(final String user_id, final String key, final String value) throws UserNotFoundException, TigaseDBException { setData(user_id, null, key, value); } /** * Describe <code>removeData</code> method here. * * @param user_id a <code>String</code> value * @param subnode a <code>String</code> value * @param key a <code>String</code> value * @exception UserNotFoundException if an error occurs */ public void removeData(final String user_id, final String subnode, final String key) throws UserNotFoundException, TigaseDBException { // cache.remove(user_id+"/"+subnode+"/"+key); try { checkConnection(); long nid = getNodeNID(user_id, subnode); if (nid > 0) { remove_key_data_st.setLong(1, nid); remove_key_data_st.setString(2, key); remove_key_data_st.executeUpdate(); } } catch (SQLException e) { throw new TigaseDBException("Error getting subnodes list.", e); } } /** * Describe <code>removeData</code> method here. * * @param user_id a <code>String</code> value * @param key a <code>String</code> value * @exception UserNotFoundException if an error occurs */ public void removeData(final String user_id, final String key) throws UserNotFoundException, TigaseDBException { removeData(user_id, null, key); } // Implementation of tigase.db.UserAuthRepository /** * Describe <code>plainAuth</code> method here. * * @param user a <code>String</code> value * @param password a <code>String</code> value * @return a <code>boolean</code> value * @exception UserNotFoundException if an error occurs * @exception TigaseDBException if an error occurs */ public boolean plainAuth(final String user, final String password) throws UserNotFoundException, TigaseDBException, AuthorizationException { return auth.plainAuth(user, password); } /** * Describe <code>digestAuth</code> method here. * * @param user a <code>String</code> value * @param digest a <code>String</code> value * @param id a <code>String</code> value * @param alg a <code>String</code> value * @return a <code>boolean</code> value * @exception UserNotFoundException if an error occurs * @exception TigaseDBException if an error occurs */ public boolean digestAuth(final String user, final String digest, final String id, final String alg) throws UserNotFoundException, TigaseDBException, AuthorizationException { return auth.digestAuth(user, digest, id, alg); } /** * Describe <code>otherAuth</code> method here. * * @param props a <code>Map</code> value * @return a <code>boolean</code> value * @exception UserNotFoundException if an error occurs * @exception TigaseDBException if an error occurs * @exception AuthorizationException if an error occurs */ public boolean otherAuth(final Map<String, Object> props) throws UserNotFoundException, TigaseDBException, AuthorizationException { return auth.otherAuth(props); } public void updatePassword(final String user, final String password) throws TigaseDBException { auth.updatePassword(user, password); } public void logout(final String user) throws UserNotFoundException, TigaseDBException { auth.logout(user); } /** * Describe <code>addUser</code> method here. * * @param user a <code>String</code> value * @param password a <code>String</code> value * @exception UserExistsException if an error occurs * @exception TigaseDBException if an error occurs */ public void addUser(final String user, final String password) throws UserExistsException, TigaseDBException { auth.addUser(user, password); } public void queryAuth(Map<String, Object> authProps) { auth.queryAuth(authProps); } } // JDBCRepository
package org.apache.ibatis.executor; import org.apache.ibatis.cache.CacheKey; import org.apache.ibatis.cache.impl.PerpetualCache; import static org.apache.ibatis.executor.ExecutionPlaceholder.EXECUTION_PLACEHOLDER; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.ParameterMapping; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.transaction.Transaction; import org.apache.ibatis.type.TypeHandlerRegistry; import java.sql.SQLException; import java.sql.Statement; import java.util.*; import java.util.concurrent.ConcurrentLinkedQueue; public abstract class BaseExecutor implements Executor { protected Transaction transaction; protected ConcurrentLinkedQueue<DeferredLoad> deferredLoads; protected PerpetualCache localCache; protected Configuration configuration; protected int queryStack = 0; protected List<BatchResult> batchResults = new ArrayList<BatchResult>(); private boolean closed; protected BaseExecutor(Configuration configuration, Transaction transaction) { this.transaction = transaction; this.deferredLoads = new ConcurrentLinkedQueue<DeferredLoad>(); this.localCache = new PerpetualCache("LocalCache"); this.closed = false; this.configuration = configuration; } public Transaction getTransaction() { if (closed) throw new ExecutorException("Executor was closed."); return transaction; } public void close(boolean forceRollback) { try { try { rollback(forceRollback); } finally { if (transaction != null) transaction.close(); } } catch (SQLException e) { // Ignore. There's nothing that can be done at this point. } finally { transaction = null; deferredLoads = null; localCache = null; batchResults = null; closed = true; } } public boolean isClosed() { return closed; } public int update(MappedStatement ms, Object parameter) throws SQLException { ErrorContext.instance().resource(ms.getResource()).activity("executing an update").object(ms.getId()); if (closed) throw new ExecutorException("Executor was closed."); clearLocalCache(); return doUpdate(ms, parameter); } public List flushStatements() throws SQLException { if (closed) throw new ExecutorException("Executor was closed."); batchResults.addAll(doFlushStatements()); return batchResults; } public List query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException { ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId()); if (closed) throw new ExecutorException("Executor was closed."); List list; try { queryStack++; CacheKey key = createCacheKey(ms, parameter, rowBounds); final List cachedList = (List) localCache.getObject(key); if (cachedList != null) { list = cachedList; } else { localCache.putObject(key, EXECUTION_PLACEHOLDER); try { list = doQuery(ms, parameter, rowBounds, resultHandler); } finally { localCache.removeObject(key); } localCache.putObject(key, list); } } finally { queryStack } if (queryStack == 0) { for (DeferredLoad deferredLoad : deferredLoads) { deferredLoad.load(); } } return list; } public void deferLoad(MappedStatement ms, MetaObject resultObject, String property, CacheKey key) { if (closed) throw new ExecutorException("Executor was closed."); deferredLoads.add(new DeferredLoad(ms, resultObject, property, key)); } public CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds) { if (closed) throw new ExecutorException("Executor was closed."); BoundSql boundSql = ms.getBoundSql(parameterObject); CacheKey cacheKey = new CacheKey(); cacheKey.update(ms.getId()); cacheKey.update(rowBounds.getOffset()); cacheKey.update(rowBounds.getLimit()); cacheKey.update(boundSql.getSql()); List<ParameterMapping> parameterMappings = boundSql.getParameterMappings(); if (parameterMappings.size() > 0 && parameterObject != null) { TypeHandlerRegistry typeHandlerRegistry = ms.getConfiguration().getTypeHandlerRegistry(); if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) { cacheKey.update(parameterObject); } else { MetaObject metaObject = configuration.newMetaObject(parameterObject); for (ParameterMapping parameterMapping : parameterMappings) { String propertyName = parameterMapping.getProperty(); if (metaObject.hasGetter(propertyName)) { cacheKey.update(metaObject.getValue(propertyName)); } else if (boundSql.hasAdditionalParameter(propertyName)) { cacheKey.update(boundSql.getAdditionalParameter(propertyName)); } } } } return cacheKey; } public boolean isCached(MappedStatement ms, CacheKey key) { return localCache.getObject(key) != null; } public void commit(boolean required) throws SQLException { if (closed) { throw new ExecutorException("Cannot commit, transaction is already closed"); } clearLocalCache(); flushStatements(); if (required) { transaction.commit(); } } public void rollback(boolean required) throws SQLException { if (!closed) { clearLocalCache(); flushStatements(); if (required) { transaction.rollback(); } } } public void clearLocalCache() { if (!closed) { localCache.clear(); } } protected abstract int doUpdate(MappedStatement ms, Object parameter) throws SQLException; protected abstract List<BatchResult> doFlushStatements() throws SQLException; protected abstract List doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException; protected void closeStatement(Statement statement) { if (statement != null) { try { statement.close(); } catch (SQLException e) { // ignore } } } private class DeferredLoad { MappedStatement mappedStatement; private MetaObject resultObject; private String property; private CacheKey key; public DeferredLoad(MappedStatement mappedStatement, MetaObject resultObject, String property, CacheKey key) { this.mappedStatement = mappedStatement; this.resultObject = resultObject; this.property = property; this.key = key; } public void load() { Object value = null; List list = (List) localCache.getObject(key); Class targetType = resultObject.getSetterType(property); if (Set.class.isAssignableFrom(targetType)) { value = new HashSet(list); } else if (Collection.class.isAssignableFrom(targetType)) { value = list; } else if (targetType.isArray()) { Object array = java.lang.reflect.Array.newInstance(targetType.getComponentType(), list.size()); value = list.toArray((Object[]) array); } else { if (list != null && list.size() > 1) { throw new ExecutorException("Statement returned more than one row, where no more than one was expected."); } else if (list != null && list.size() == 1) { value = list.get(0); } } resultObject.setValue(property, value); } } }
package tigase.util; import java.util.LinkedHashMap; import java.util.Map.Entry; import java.util.Map; import java.util.logging.Logger; import java.util.regex.Pattern; /** * Describe class RoutingsContainer here. * * * Created: Sat Feb 11 16:30:42 2006 * * @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a> * @version $Rev$ */ public class RoutingsContainer { /** * Variable <code>log</code> is a class logger. */ private static final Logger log = Logger.getLogger("tigase.util.RoutingsContainer"); private RoutingComputer comp = null; /** * Creates a new <code>RoutingsContainer</code> instance. * */ public RoutingsContainer(boolean multiMode) { if (multiMode) { comp = new MultiMode(); } // end of if (mode) else { comp = new SingleMode(); } // end of if (mode) else } public void addRouting(final String pattern, final String address) { comp.addRouting(pattern, address); } public String computeRouting(final String pattern) { return comp.computeRouting(pattern); } protected interface RoutingComputer { void addRouting(final String pattern, final String address); String computeRouting(final String pattern); } protected class SingleMode implements RoutingComputer { private String routing = null; public void addRouting(final String pattern, final String address) { routing = address; } public String computeRouting(final String address) { return routing; } } protected class MultiMode implements RoutingComputer { private Map<Pattern, String> routings = new LinkedHashMap<Pattern, String>(); private String def = null; public void addRouting(final String pattern, final String address) { log.fine("Adding routing: " + pattern + " --> " + address); routings.put(Pattern.compile(pattern), address); if (def == null) { def = address; } // end of if (def == null) } public String computeRouting(final String address) { if (address == null) { log.finer("For null address returning default routing: " + def); return def; } // end of if (address == null) for (Map.Entry<Pattern, String> entry: routings.entrySet()) { if (entry.getKey().matcher(address).find()) { log.finest("For address: " + address + " pattern: " + entry.getKey().pattern() + " matched."); return entry.getValue(); } // end of if (pattern.matcher(address).find()) } // end of for () return def; } } } // RoutingsContainer
package wicket.quickstart; import java.awt.List; import java.util.Iterator; import java.util.Vector; import wicket.ajax.AbstractDefaultAjaxBehavior; import wicket.ajax.AjaxEventBehavior; import wicket.ajax.AjaxRequestTarget; import wicket.ajax.AjaxSelfUpdatingTimerBehavior; import wicket.ajax.markup.html.form.AjaxSubmitLink; import wicket.behavior.HeaderContributor; import wicket.behavior.SimpleAttributeModifier; import wicket.markup.ComponentTag; import wicket.markup.html.IHeaderContributor; import wicket.markup.html.WebMarkupContainer; import wicket.markup.html.basic.Label; import wicket.markup.html.form.Button; import wicket.markup.html.form.Form; import wicket.markup.html.form.HiddenField; import wicket.markup.html.form.TextField; import wicket.markup.html.list.ListItem; import wicket.markup.html.list.ListView; import wicket.model.PropertyModel; import wicket.util.time.Duration; import wicket.Component; import wicket.PageParameters; import wicket.RequestCycle; import wicket.Response; /** * Basic bookmarkable index page. * * NOTE: You can get session properties from QuickStartSession via getQuickStartSession() * gFigures -> new Figure(x, y) * gSelectedFigureIndex * */ public class MapOverview extends QuickStartPage { List javaScriptInstructions; Player player; Vector<Player> players; ListView playerListview; public MapOverview(final PageParameters parameters) { javaScriptInstructions = new List(); player = ((QuickStartSession) getSession()).player; players = ((QuickStartSession) getSession()).players; //add(HeaderContributor.forJavaScript("MapOverview.js")); WebMarkupContainer body = new WebMarkupContainer("body"); AjaxEventBehavior loader = new AjaxEventBehavior("onload") { private static final long serialVersionUID = 1L; @Override protected void onEvent(AjaxRequestTarget target) { target.appendJavascript("changeOrAddFigure(\""+ player.name + "\", 1, 1, 1)"); target.appendJavascript("setMyFigure(\""+ player.name + "\")"); target.appendJavascript("drawBoard()"); //Vector<Player> players = ((QuickStartSession) getSession()).players; //target.appendJavascript("alert(\""+ players.size() + " players\")"); //changeOrAddFigure("Marieke", 2, 5); //changeOrAddFigure("Emile", 3, 6); } }; body.add(loader); add(body); //Label nameLabel = new Label("nameLabel", new PropertyModel(player, "name")); //Label avatarLabel = new Label("avatarLabel", new PropertyModel(player, "avatar")); playerListview = new ListView("playerList", players) { protected void populateItem(ListItem item) { //item.add(new Label("player", item.getModel())); Player p = (Player)item.getModelObject(); item.add(new Label("avatar", new PropertyModel(p, "avatar"))); item.add(new Label("player", new PropertyModel(p, "name"))); if(p.equals(player)){item.add(new SimpleAttributeModifier("style", "font-weight:bold;"));} } }; //body.add(nameLabel); //body.add(avatarLabel); WebMarkupContainer playerlistContainer = new WebMarkupContainer("playerlistContainer"); playerlistContainer.add(playerListview); playerlistContainer.setOutputMarkupId(true); body.add(playerlistContainer); //Call-back functie final AbstractDefaultAjaxBehavior behavior = new AbstractDefaultAjaxBehavior(){ @Override protected void respond(AjaxRequestTarget arg0) { player.locationx = Integer.parseInt(RequestCycle.get().getRequest().getParameter("x")); player.locationy = Integer.parseInt(RequestCycle.get().getRequest().getParameter("y")); } }; final AjaxSelfUpdatingTimerBehavior updatingBehavior = new AjaxSelfUpdatingTimerBehavior(Duration.seconds(10)){ @Override protected void onPostProcessTarget(AjaxRequestTarget timerTarget) { //@TODO: Update only moved players Iterator<Player> i = players.iterator(); while(i.hasNext()){ Player p = i.next(); if(!p.equals(player)){ timerTarget.appendJavascript("changeOrAddFigure(\"" + p.name + "\", " + p.avatar + "\", " + p.locationx + ", " + p.locationy + ")"); } } timerTarget.appendJavascript("drawBoard()"); } }; playerlistContainer.add(behavior); playerlistContainer.add(updatingBehavior); Button commitMoveButton = new Button("commitMoveButton"){ @Override public void onComponentTag(ComponentTag tag){ tag.put("onClick", "wicketAjaxGet('"+behavior.getCallbackUrl()+"&x='+getMyX()+'&y='+getMyY()+'');"); } }; body.add(commitMoveButton); } }
package org.biouno.unochoice.model; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; import org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript; import org.jenkinsci.plugins.scriptsecurity.scripts.ApprovalContext; import org.kohsuke.stapler.DataBoundConstructor; import groovy.lang.Binding; import hudson.Extension; import hudson.PluginManager; import hudson.Util; import jenkins.model.Jenkins; /** * A Groovy script. * * @author Bruno P. Kinoshita * @since 0.23 */ public class GroovyScript extends AbstractScript { /* * Serial UID. */ private static final long serialVersionUID = -3741105849416473898L; private static final Logger LOGGER = Logger.getLogger(GroovyScript.class.getName()); /** * Script content. */ @Deprecated private String script; /** * Secure script content. */ private SecureGroovyScript secureScript; @Nullable @Deprecated private String fallbackScript; /** * Secure fallback script content. */ @Nullable private SecureGroovyScript secureFallbackScript; @Deprecated public GroovyScript(String script, String fallbackScript) { this(new SecureGroovyScript(script, false, null), new SecureGroovyScript(fallbackScript, false, null)); } @DataBoundConstructor public GroovyScript(SecureGroovyScript script, SecureGroovyScript fallbackScript) { if (script != null) { this.secureScript = script.configuringWithNonKeyItem(); } if (fallbackScript != null) { this.secureFallbackScript = fallbackScript.configuringWithNonKeyItem(); } } private Object readResolve() { if (script != null) { secureScript = new SecureGroovyScript(script, false, null).configuring(ApprovalContext.create()); } if (fallbackScript != null) { secureFallbackScript = new SecureGroovyScript(fallbackScript, false, null) .configuring(ApprovalContext.create()); } return this; } /** * @return the script */ public SecureGroovyScript getScript() { return secureScript; } /** * @return the fallbackScript */ public SecureGroovyScript getFallbackScript() { return secureFallbackScript; } /* * (non-Javadoc) * * @see org.biouno.unochoice.model.Script#eval() */ @Override public Object eval() { return eval(Collections.<String, String> emptyMap()); } /* * (non-Javadoc) * * @see org.biouno.unochoice.model.Script#eval(java.util.Map) */ @Override public Object eval(Map<String, String> parameters) throws RuntimeException { if (secureScript == null) { return null; } final Jenkins instance = Jenkins.getInstance(); ClassLoader cl = null; if (instance != null) { try { PluginManager pluginManager = instance.getPluginManager(); cl = pluginManager.uberClassLoader; } catch (Exception e) { LOGGER.log(Level.FINEST, e.getMessage(), e); } } if (cl == null) { cl = Thread.currentThread().getContextClassLoader(); } final Binding context = new Binding(); // @SuppressWarnings("unchecked") final Map<String, String> envVars = System.getenv(); for (Entry<String, String> parameter : parameters.entrySet()) { Object value = parameter.getValue(); if (value != null) { if (value instanceof String) { value = Util.replaceMacro((String) value, envVars); } context.setVariable(parameter.getKey().toString(), value); } } try { return secureScript.evaluate(cl, context); } catch (Exception re) { if (this.secureFallbackScript != null) { try { LOGGER.log(Level.FINEST, "Fallback to default script...", re); return secureFallbackScript.evaluate(cl, context); } catch (Exception e2) { LOGGER.log(Level.WARNING, "Error executing fallback script", e2); throw new RuntimeException("Failed to evaluate fallback script: " + e2.getMessage(), e2); } } else { LOGGER.log(Level.WARNING, "No fallback script configured for '%s'"); throw new RuntimeException("Failed to evaluate script: " + re.getMessage(), re); } } } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { final String secureScriptText = (secureScript != null) ? secureScript.getScript() : ""; final String fallbackScriptText = (secureFallbackScript != null) ? secureFallbackScript.getScript() : ""; return "GroovyScript [script=" + secureScriptText + ", fallbackScript=" + fallbackScriptText + "]"; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((secureFallbackScript == null) ? 0 : secureFallbackScript.hashCode()); result = prime * result + ((secureScript == null) ? 0 : secureScript.hashCode()); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; GroovyScript other = (GroovyScript) obj; if (secureFallbackScript == null) { if (other.secureFallbackScript != null) return false; } else if (!secureFallbackScript.equals(other.secureFallbackScript)) return false; if (secureScript == null) { if (other.secureScript != null) return false; } else if (!secureScript.equals(other.secureScript)) return false; return true; } @Extension public static class DescriptorImpl extends ScriptDescriptor { /* * (non-Javadoc) * * @see hudson.model.Descriptor#getDisplayName() */ @Override public String getDisplayName() { return "Groovy Script"; } } }
package org.ccci.gto.android.thekey; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.webkit.WebSettings; import android.webkit.WebView; public final class DisplayUtil { @SuppressLint("SetJavaScriptEnabled") @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public final static WebView createLoginWebView(final Context context, final TheKey thekey, final LoginWebViewClient webViewClient) { final WebView webView = new WebView(context); webView.setVisibility(View.GONE); webView.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); webView.setScrollbarFadingEnabled(true); final WebSettings settings = webView.getSettings(); settings.setSavePassword(false); settings.setJavaScriptEnabled(true); settings.setLoadsImagesAutomatically(true); settings.setAllowFileAccess(false); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { settings.setAllowContentAccess(false); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { settings.setAllowFileAccessFromFileURLs(false); settings.setAllowUniversalAccessFromFileURLs(false); } } webView.setWebViewClient(webViewClient); webView.loadUrl(thekey.getAuthorizeUri().toString()); return webView; } }
package org.cytoscape.rest.internal; import java.util.Map; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.cytoscape.application.CyApplicationManager; import org.cytoscape.application.swing.CySwingApplication; import org.cytoscape.command.AvailableCommands; import org.cytoscape.command.CommandExecutorTaskFactory; import org.cytoscape.group.CyGroupFactory; import org.cytoscape.group.CyGroupManager; import org.cytoscape.io.BasicCyFileFilter; import org.cytoscape.io.DataCategory; import org.cytoscape.io.read.InputStreamTaskFactory; import org.cytoscape.io.util.StreamUtil; import org.cytoscape.io.write.CyNetworkViewWriterFactory; import org.cytoscape.io.write.PresentationWriterFactory; import org.cytoscape.io.write.VizmapWriterFactory; import org.cytoscape.model.CyNetworkFactory; import org.cytoscape.model.CyNetworkManager; import org.cytoscape.model.CyTableFactory; import org.cytoscape.model.CyTableManager; import org.cytoscape.model.subnetwork.CyRootNetworkManager; import org.cytoscape.property.CyProperty; import org.cytoscape.rest.internal.reader.EdgeListReaderFactory; import org.cytoscape.rest.internal.task.CyBinder; import org.cytoscape.rest.internal.task.GrizzlyServerManager; import org.cytoscape.rest.internal.task.HeadlessTaskMonitor; import org.cytoscape.service.util.AbstractCyActivator; import org.cytoscape.session.CySessionManager; import org.cytoscape.task.NetworkCollectionTaskFactory; import org.cytoscape.task.NetworkTaskFactory; import org.cytoscape.task.create.NewNetworkSelectedNodesAndEdgesTaskFactory; import org.cytoscape.task.create.NewSessionTaskFactory; import org.cytoscape.task.read.LoadNetworkURLTaskFactory; import org.cytoscape.task.read.OpenSessionTaskFactory; import org.cytoscape.task.select.SelectFirstNeighborsTaskFactory; import org.cytoscape.task.write.ExportNetworkViewTaskFactory; import org.cytoscape.task.write.SaveSessionAsTaskFactory; import org.cytoscape.view.layout.CyLayoutAlgorithmManager; import org.cytoscape.view.model.CyNetworkViewFactory; import org.cytoscape.view.model.CyNetworkViewManager; import org.cytoscape.view.presentation.RenderingEngineManager; import org.cytoscape.view.vizmap.VisualMappingFunctionFactory; import org.cytoscape.view.vizmap.VisualMappingManager; import org.cytoscape.view.vizmap.VisualStyleFactory; import org.cytoscape.work.SynchronousTaskManager; import org.cytoscape.work.TaskFactory; import org.cytoscape.work.TaskMonitor; import org.osgi.framework.BundleContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CyActivator extends AbstractCyActivator { private static final Logger logger = LoggerFactory.getLogger(CyActivator.class); public class WriterListener { private VizmapWriterFactory jsFactory; @SuppressWarnings("rawtypes") public void registerFactory(final VizmapWriterFactory factory, final Map props) { if (factory != null && factory.getClass().getSimpleName().equals("CytoscapeJsVisualStyleWriterFactory")) { this.jsFactory = factory; } } @SuppressWarnings("rawtypes") public void unregisterFactory(final VizmapWriterFactory factory, final Map props) { } public VizmapWriterFactory getFactory() { return this.jsFactory; } } private GrizzlyServerManager grizzlyServerManager = null; public CyActivator() { super(); } public void start(BundleContext bc) { logger.info("Initializing cyREST API server..."); long start = System.currentTimeMillis(); final MappingFactoryManager mappingFactoryManager = new MappingFactoryManager(); registerServiceListener(bc, mappingFactoryManager, "addFactory", "removeFactory", VisualMappingFunctionFactory.class); final GraphicsWriterManager graphicsWriterManager = new GraphicsWriterManager(); registerServiceListener(bc, graphicsWriterManager, "addFactory", "removeFactory", PresentationWriterFactory.class); @SuppressWarnings("unchecked") final CyProperty<Properties> cyPropertyServiceRef = getService(bc, CyProperty.class, "(cyPropertyName=cytoscape3.props)"); final TaskMonitor headlessTaskMonitor = new HeadlessTaskMonitor(); final CyNetworkFactory netFact = getService(bc, CyNetworkFactory.class); final CyNetworkViewFactory netViewFact = getService(bc, CyNetworkViewFactory.class); final CyNetworkManager netMan = getService(bc, CyNetworkManager.class); final CyRootNetworkManager cyRootNetworkManager = getService(bc, CyRootNetworkManager.class); final CyNetworkViewManager netViewMan = getService(bc, CyNetworkViewManager.class); final VisualMappingManager visMan = getService(bc, VisualMappingManager.class); final CyApplicationManager applicationManager = getService(bc, CyApplicationManager.class); final CyLayoutAlgorithmManager layoutManager = getService(bc, CyLayoutAlgorithmManager.class); final VisualStyleFactory vsFactory = getService(bc, VisualStyleFactory.class); final CyGroupFactory groupFactory = getService(bc, CyGroupFactory.class); final CyGroupManager groupManager = getService(bc, CyGroupManager.class); final CyTableManager tableManager = getService(bc, CyTableManager.class); final CyTableFactory tableFactory = getService(bc, CyTableFactory.class); final StreamUtil streamUtil = getService(bc, StreamUtil.class); final CySessionManager sessionManager = getService(bc, CySessionManager.class); final SaveSessionAsTaskFactory saveSessionAsTaskFactory = getService(bc, SaveSessionAsTaskFactory.class); final OpenSessionTaskFactory openSessionTaskFactory = getService(bc, OpenSessionTaskFactory.class); final NewSessionTaskFactory newSessionTaskFactory = getService(bc, NewSessionTaskFactory.class); final CySwingApplication desktop = getService(bc, CySwingApplication.class); final ExportNetworkViewTaskFactory exportNetworkViewTaskFactory = getService(bc, ExportNetworkViewTaskFactory.class); // For commands final AvailableCommands available = getService(bc, AvailableCommands.class); final CommandExecutorTaskFactory ceTaskFactory = getService(bc, CommandExecutorTaskFactory.class); final SynchronousTaskManager<?> synchronousTaskManager = getService(bc, SynchronousTaskManager.class); // Get any command line arguments. The "-R" is ours @SuppressWarnings("unchecked") final CyProperty<Properties> commandLineProps = getService(bc, CyProperty.class, "(cyPropertyName=commandline.props)"); final Properties clProps = commandLineProps.getProperties(); String restPortNumber = cyPropertyServiceRef.getProperties().getProperty(GrizzlyServerManager.PORT_NUMBER_PROP); if (clProps.getProperty(GrizzlyServerManager.PORT_NUMBER_PROP) != null) restPortNumber = clProps.getProperty(GrizzlyServerManager.PORT_NUMBER_PROP); if(restPortNumber == null) { restPortNumber = GrizzlyServerManager.DEF_PORT_NUMBER.toString(); } // Set Port number cyPropertyServiceRef.getProperties().setProperty(GrizzlyServerManager.PORT_NUMBER_PROP, restPortNumber); // Task factories final NewNetworkSelectedNodesAndEdgesTaskFactory networkSelectedNodesAndEdgesTaskFactory = getService(bc, NewNetworkSelectedNodesAndEdgesTaskFactory.class); final CyNetworkViewWriterFactory cytoscapeJsWriterFactory = getService(bc, CyNetworkViewWriterFactory.class, "(id=cytoscapejsNetworkWriterFactory)"); final InputStreamTaskFactory cytoscapeJsReaderFactory = getService(bc, InputStreamTaskFactory.class, "(id=cytoscapejsNetworkReaderFactory)"); final LoadNetworkURLTaskFactory loadNetworkURLTaskFactory = getService(bc, LoadNetworkURLTaskFactory.class); final SelectFirstNeighborsTaskFactory selectFirstNeighborsTaskFactory = getService(bc, SelectFirstNeighborsTaskFactory.class); // TODO: need ID for these services. final NetworkTaskFactory fitContent = getService(bc, NetworkTaskFactory.class, "(title=Fit Content)"); final NetworkTaskFactory edgeBundler = getService(bc, NetworkTaskFactory.class, "(title=All Nodes and Edges)"); final NetworkTaskFactory showDetailsTaskFactory = getService(bc, NetworkTaskFactory.class, "(title=Show/Hide Graphics Details)"); final RenderingEngineManager renderingEngineManager = getService(bc,RenderingEngineManager.class); final WriterListener writerListsner = new WriterListener(); registerServiceListener(bc, writerListsner, "registerFactory", "unregisterFactory", VizmapWriterFactory.class); final TaskFactoryManager taskFactoryManagerManager = new TaskFactoryManagerImpl(); // Get all compatible tasks registerServiceListener(bc, taskFactoryManagerManager, "addTaskFactory", "removeTaskFactory", TaskFactory.class); registerServiceListener(bc, taskFactoryManagerManager, "addNetworkTaskFactory", "removeNetworkTaskFactory", NetworkTaskFactory.class); registerServiceListener(bc, taskFactoryManagerManager, "addNetworkCollectionTaskFactory", "removeNetworkCollectionTaskFactory", NetworkCollectionTaskFactory.class); // Extra readers and writers final BasicCyFileFilter elFilter = new BasicCyFileFilter(new String[] { "el" }, new String[] { "text/edgelist" }, "Edgelist files", DataCategory.NETWORK, streamUtil); final EdgeListReaderFactory edgeListReaderFactory = new EdgeListReaderFactory(elFilter, netViewFact, netFact, netMan, cyRootNetworkManager); final Properties edgeListReaderFactoryProps = new Properties(); edgeListReaderFactoryProps.setProperty("ID", "edgeListReaderFactory"); registerService(bc, edgeListReaderFactory, InputStreamTaskFactory.class, edgeListReaderFactoryProps); // Start REST Server final CyBinder binder = new CyBinder(netMan, netViewMan, netFact, taskFactoryManagerManager, applicationManager, visMan, cytoscapeJsWriterFactory, cytoscapeJsReaderFactory, layoutManager, writerListsner, headlessTaskMonitor, tableManager, vsFactory, mappingFactoryManager, groupFactory, groupManager, cyRootNetworkManager, loadNetworkURLTaskFactory, cyPropertyServiceRef, networkSelectedNodesAndEdgesTaskFactory, edgeListReaderFactory, netViewFact, tableFactory, fitContent, new EdgeBundlerImpl(edgeBundler), renderingEngineManager, sessionManager, saveSessionAsTaskFactory, openSessionTaskFactory, newSessionTaskFactory, desktop, new LevelOfDetails(showDetailsTaskFactory), selectFirstNeighborsTaskFactory, graphicsWriterManager, exportNetworkViewTaskFactory, available, ceTaskFactory, synchronousTaskManager); this.grizzlyServerManager = new GrizzlyServerManager(binder, cyPropertyServiceRef); logger.info("cyREST dependency import took: " + (System.currentTimeMillis() - start) + " msec."); // Start Grizzly server in separate thread final ExecutorService service = Executors.newSingleThreadExecutor(); service.submit(()-> { try { this.grizzlyServerManager.startServer(); } catch (Exception e) { e.printStackTrace(); logger.warn("Failed to initialize cyREST server.", e); } }); logger.info("cyREST initialized in " + (System.currentTimeMillis() - start) + " msec."); } @Override public void shutDown() { logger.info("Shutting down REST server..."); if (grizzlyServerManager != null) { grizzlyServerManager.stopServer(); } } class EdgeBundlerImpl implements EdgeBundler { private final NetworkTaskFactory bundler; public EdgeBundlerImpl(final NetworkTaskFactory tf) { this.bundler = tf; } @Override public NetworkTaskFactory getBundlerTF() { return bundler; } } public class LevelOfDetails { private final NetworkTaskFactory lod; public LevelOfDetails(final NetworkTaskFactory tf) { this.lod = tf; } public NetworkTaskFactory getLodTF() { return lod; } } }
package org.dynmap.hdmap.renderer; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import java.util.Map; import org.dynmap.Log; import org.dynmap.renderer.CustomRenderer; import org.dynmap.renderer.MapDataContext; import org.dynmap.renderer.RenderPatch; import org.dynmap.renderer.RenderPatchFactory; import org.dynmap.renderer.RenderPatchFactory.SideVisible; import org.dynmap.utils.BlockStep; import org.dynmap.utils.MapIterator; public class SkullRenderer extends CustomRenderer { private int blkid; private static final int NUM_FACES = 5; private static final int NUM_DIRECTIONS = 16; private static final String[] tileFields = { "SkullType", "Rot" }; private RenderPatch basemesh[]; private RenderPatch meshes[][] = new RenderPatch[NUM_FACES * NUM_DIRECTIONS][]; @Override public boolean initializeRenderer(RenderPatchFactory rpf, int blkid, int blockdatamask, Map<String,String> custparm) { if(!super.initializeRenderer(rpf, blkid, blockdatamask, custparm)) return false; this.blkid = blkid; /* Remember our block ID */ ArrayList<RenderPatch> list = new ArrayList<RenderPatch>(); list.add(rpf.getPatch(0.75, 0.0, 0.25, 0.25, 0.0, 0.25, 0.75, 0.0, 0.75, 0, 1, 0, 1, SideVisible.TOP, 0)); list.add(rpf.getPatch(0.75, 0.5, 0.25, 0.25, 0.5, 0.25, 0.75, 0.5, 0.75, 0, 1, 0, 1, SideVisible.TOP, 0)); RenderPatch side = rpf.getPatch(0.75, 0.0, 0.25, 0.25, 0.0, 0.25, 0.75, 0.5, 0.25, 0, 1, 0, 1, SideVisible.TOP, 0); RenderPatch side2 = rpf.getRotatedPatch(side, 0, 90, 0, 0); RenderPatch side3 = rpf.getRotatedPatch(side, 0, 180, 0, 0); RenderPatch side4 = rpf.getRotatedPatch(side, 0, 270, 0, 0); list.add(side4); list.add(side); list.add(side2); list.add(side3); basemesh = list.toArray(new RenderPatch[list.size()]); return true; } @Override public int getMaximumTextureCount() { return 6 * NUM_FACES; } private static final int faces[] = { 0, 1, 2, 3, 4, 5 }; @Override public RenderPatch[] getRenderPatchList(MapDataContext ctx) { ArrayList<RenderPatch> list = new ArrayList<RenderPatch>(); int rot = 0; int face = 0; Object val = ctx.getBlockTileEntityField("Rot"); if(val instanceof Byte) rot = ((Byte)val).intValue(); while(rot < 0) rot += NUM_DIRECTIONS; // Normalize (bad values from some mods) val = ctx.getBlockTileEntityField("SkullType"); if(val instanceof Byte) face = ((Byte)val).intValue(); while(face < 0) face += faces.length; // Normalize (bad values from some mods) int idx = (NUM_DIRECTIONS * face) + rot; if(idx < meshes.length) { if(meshes[idx] == null) { RenderPatchFactory rpf = ctx.getPatchFactory(); RenderPatch[] rp = new RenderPatch[basemesh.length]; for(int i = 0; i < rp.length; i++) { rp[i] = rpf.getRotatedPatch(basemesh[i], 0, 45*rot/2, 0, faces[i] + (6*face)); } meshes[idx] = rp; } return meshes[idx]; } else return meshes[0]; } @Override public String[] getTileEntityFieldsNeeded() { return tileFields; } }
package com.jeasonfire.engineer.game.levels; import java.awt.Point; import java.util.ArrayList; import com.jeasonfire.engineer.game.entities.Entity; import com.jeasonfire.engineer.game.entities.Player; import com.jeasonfire.engineer.game.entities.Stairs; import com.jeasonfire.engineer.game.entities.Turret; import com.jeasonfire.engineer.graphics.HexColor; import com.jeasonfire.engineer.graphics.screens.Screen; import com.jeasonfire.engineer.graphics.sprites.Sprite; public class Level { public static int tileSize = 16, cellSize = 3; public int[] tiles; public int width, height; public ArrayList<Entity> entities; public int currentLevel = 4, maxLevels = 4; private boolean generateNewLevel = true; protected int xScroll, yScroll; private float xScrollCenter, yScrollCenter; private float transparencyRange = 4; private long startTime = 0; private long tipLength = 5000; public boolean victory = false, gameover = false; private class SwitchGate { private ArrayList<Point> switchPoint; private ArrayList<Point> gatePoint; private boolean open = false; public SwitchGate() { switchPoint = new ArrayList<Point>(); gatePoint = new ArrayList<Point>(); } public void addSwitch(int x, int y) { switchPoint.add(new Point(x, y)); } public void addGate(int x, int y) { gatePoint.add(new Point(x, y)); } public boolean getNearSwitch(int x, int y) { for (Point p : switchPoint) { if (p.x == x && p.y == y) { return true; } } return false; } public void setOpen(boolean open) { this.open = open; } public boolean getOpen() { return open; } public int getSwitchX(int index) { return switchPoint.get(index).x; } public int getSwitchY(int index) { return switchPoint.get(index).y; } public int getSwitchSize() { return switchPoint.size(); } public int getGateX(int index) { return gatePoint.get(index).x; } public int getGateY(int index) { return gatePoint.get(index).y; } public int getGateSize() { return gatePoint.size(); } }; private SwitchGate[] switchGates; private static Sprite[] tileset; static { Sprite load = new Sprite("tileset.png"); tileset = new Sprite[(load.getWidth() / tileSize) * (load.getWidth() / tileSize)]; for (int y = 0; y < load.getHeight() / tileSize; y++) { for (int x = 0; x < load.getWidth() / tileSize; x++) { tileset[x + y * (load.getWidth() / tileSize)] = load.cut(x * tileSize, y * tileSize, tileSize, tileSize); } } }; public Level() { generate(currentLevel); } public void generate(int level) { generateNewLevel = false; Sprite load = new Sprite("level" + level + ".png"); this.width = load.getWidth() * cellSize; this.height = load.getHeight() * cellSize; this.tiles = new int[width * height]; switchGates = new SwitchGate[256]; entities = new ArrayList<Entity>(); for (int y = 0; y < height / cellSize; y++) { for (int x = 0; x < width / cellSize; x++) { int id = load.getPixel(x, y) & 0xFFFFFF; if (id == 0xFFFFFF) { setNextLevel(x, y); } else if (HexColor.getRed(id) == 0xFF) { if (HexColor.getGreen(id) > 0) setSwitch(HexColor.getGreen(id), x, y); if (HexColor.getBlue(id) > 0) setGate(HexColor.getBlue(id), x, y); } else if (id == 0xFF00) { setPlayer(x, y); } else if (id == 0xAA0000) { setTurret(x, y); } else { setCell(id, x, y); } } } startTime = 0; } public void nextLevel() { currentLevel++; generateNewLevel = true; if (currentLevel > maxLevels) victory = true; } public void resetLevel() { generateNewLevel = true; } public void toggleSwitch(int x, int y) { for (SwitchGate sg : switchGates) { if (sg != null && sg.getNearSwitch(x, y)) { sg.setOpen(!sg.getOpen()); } } } public void setSwitch(int id, int x, int y) { if (switchGates[id] == null) switchGates[id] = new SwitchGate(); switchGates[id].addSwitch(x, y); setCell(0, x, y); } public void setGate(int id, int x, int y) { if (switchGates[id] == null) switchGates[id] = new SwitchGate(); switchGates[id].addGate(x, y); } public void setNextLevel(int x, int y) { setCell(0, x, y); entities.add(new Stairs(x * cellSize * tileSize + cellSize * tileSize / 2 - tileSize / 2, y * cellSize * tileSize + cellSize * tileSize / 2 - tileSize / 2)); } public void setPlayer(int x, int y) { setCell(0, x, y); entities.add(new Player(x * cellSize * tileSize + cellSize * tileSize / 2 - tileSize / 2, y * cellSize * tileSize + cellSize * tileSize / 2 - tileSize / 2)); } public void setTurret(int x, int y) { setCell(0, x, y); entities.add(new Turret(x * cellSize * tileSize + cellSize * tileSize / 2 - tileSize / 2, y * cellSize * tileSize + cellSize * tileSize / 2 - tileSize / 2)); } public void setCell(int id, int x, int y) { for (int i = 0; i < cellSize * cellSize; i++) { setTile(id, x * cellSize + i % cellSize, y * cellSize + i / cellSize); } } public int getCell(int x, int y) { return tiles[(x * cellSize) + (y * cellSize + cellSize / 2) * width]; } public void setTile(int id, int x, int y) { if (x + y * width < 0 || x + y * width >= tiles.length) return; switch (id) { case 0: case 0xFFFFFF: tiles[x + y * width] = 0; break; case 0xFF: tiles[x + y * width] = 1; break; case 0xAA: tiles[x + y * width] = 2; break; } } public void draw(Screen screen) { for (int y = 0; y < height; y++) { int yy = y + yScroll / tileSize; if (yy < 0 || yy >= height) continue; int yp = y * tileSize - (yScroll % tileSize); if (yp < -tileSize || yp >= screen.getHeight()) continue; for (int x = 0; x < width; x++) { int xx = x + xScroll / tileSize; if (xx < 0 || xx >= width) continue; int xp = x * tileSize - (xScroll % tileSize); if (xp < -tileSize || xp >= screen.getWidth()) continue; screen.drawSprite(getTileSprite(tiles[xx + yy * width]), xp, yp, 1, getTransparency(xx, yy)); } } for (SwitchGate sg : switchGates) { if (sg != null) { for (int i = 0; i < sg.getSwitchSize(); i++) { if (sg.getOpen()) { screen.drawShadedRectangle(0xCC00, 0xAA00, 0x8800, sg.getSwitchX(i) * cellSize * tileSize + cellSize * tileSize / 2 - tileSize / 2 - xScroll, sg.getSwitchY(i) * cellSize * tileSize + cellSize * tileSize / 2 - tileSize / 2 - yScroll, tileSize, tileSize); } else { screen.drawShadedRectangle(0xCC0000, 0xAA0000, 0x880000, sg.getSwitchX(i) * cellSize * tileSize + cellSize * tileSize / 2 - tileSize / 2 - xScroll, sg.getSwitchY(i) * cellSize * tileSize + cellSize * tileSize / 2 - tileSize / 2 - yScroll, tileSize, tileSize); } } } } for (int i = 0; i < entities.size(); i++) { if (entities.get(i) instanceof Player) { xScroll = (int) (entities.get(i).getX() - screen.getWidth() / 2 + entities .get(i).getWidth() / 2); xScrollCenter = entities.get(i).getX(); yScroll = (int) (entities.get(i).getY() - screen.getHeight() / 2 + entities.get(i).getHeight() / 2); yScrollCenter = entities.get(i).getY(); } entities.get(i).draw(screen, (int) xScroll, (int) yScroll); } if (currentLevel == 1 && System.currentTimeMillis() - startTime < tipLength) { screen.drawString("Switches turn lasers off.".substring(0, (int) Math.min(30 * (System.currentTimeMillis() - startTime) / (tipLength / 2), 30)), 8, 8); } else if (currentLevel == 1) { screen.drawString("Switches turn lasers off.", 8, 8, 1, (float) (1.0 / ((System.currentTimeMillis() - tipLength - startTime) / 500.0) - 0.2)); } if (currentLevel == 2 && System.currentTimeMillis() - startTime < tipLength) { screen.drawString("Shift to run!".substring(0, (int) Math.min(13 * (System.currentTimeMillis() - startTime) / (tipLength / 2), 13)), 8, 8); } else if (currentLevel == 2) { screen.drawString("Shift to run!", 8, 8, 1, (float) (1.0 / ((System.currentTimeMillis() - tipLength - startTime) / 500.0) - 0.2)); } if (currentLevel == 3 && System.currentTimeMillis() - startTime < tipLength) { screen.drawString("Bullets also kill turrets.".substring(0, (int) Math.min(27 * (System.currentTimeMillis() - startTime) / (tipLength / 2), 27)), 8, 8); } else if (currentLevel == 3) { screen.drawString("Bullets also kill turrets.", 8, 8, 1, (float) (1.0 / ((System.currentTimeMillis() - tipLength - startTime) / 500.0) - 0.2)); } if (currentLevel == 4 && System.currentTimeMillis() - startTime < tipLength) { screen.drawString("Switches can also switch off. (Also, bullets aren't laser-resistant)".substring(0, (int) Math.min(73 * (System.currentTimeMillis() - startTime) / (tipLength / 2), 73)), 8, 8); } else if (currentLevel == 4) { screen.drawString("Switches can also switch off. (Also, bullets aren't laser-resistant)", 8, 8, 1, (float) (1.0 / ((System.currentTimeMillis() - tipLength - startTime) / 500.0) - 0.2)); } } public float getTransparency(float x, float y) { float xt = x - xScrollCenter / tileSize; float yt = y - yScrollCenter / tileSize; float intensity = (float) (transparencyRange - Math.sqrt(xt * xt + yt * yt)); if (intensity < 0) return 0; intensity = 1 - 1 / intensity; return intensity; } public void update(float delta) { if (generateNewLevel) generate(currentLevel); if (startTime <= 0) { startTime = System.currentTimeMillis(); } for (int i = 0; i < entities.size(); i++) { entities.get(i).update(delta, this); } for (SwitchGate sg : switchGates) { if (sg != null) { for (int i = 0; i < sg.getGateSize(); i++) { if (sg.getOpen()) { setCell(0, sg.getGateX(i), sg.getGateY(i)); } if (!sg.getOpen()) { setCell(0xAA, sg.getGateX(i), sg.getGateY(i)); } } } } } public Sprite getTileSprite(int index) { if (index < 0 || index >= tileset.length) return new Sprite(tileSize, tileSize); return tileset[index]; } public boolean getTileSolid(int id) { switch (id) { default: case 0: return false; case 1: case 2: return true; } } public boolean isSolid(float x, float y) { if (x < 0 || x / tileSize >= width || y < 0 || y / tileSize >= height) return false; return getTileSolid(tiles[(int) (x / tileSize) + (int) (y / tileSize) * width]); } }
package org.interfaceit; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.interfaceit.format.CodeFormatter; import org.interfaceit.meta.arguments.ArgumentNameSource; import org.interfaceit.ui.meta.error.UnableToCreateOutputDirectory; import org.interfaceit.util.ClassNameUtils; import org.interfaceit.util.FileSystem; import org.interfaceit.util.FileUtils; /** * Generates an interface with default methods that delegate to static methods * * @author aro_tech * */ public class DelegateMethodGenerator implements ClassCodeGenerator { private final FileSystem fileSystem; private final DeprecationPolicy deprecationPolicy; private final CodeFormatter formatter; /** * Constructor using default FileSystem */ public DelegateMethodGenerator() { super(); this.fileSystem = FileUtils.getDefaultFileSystem(); this.deprecationPolicy = DeprecationPolicy.PROPAGATE_DEPRECATION; this.formatter = CodeFormatter.getDefault(); } /** * Constructor * * @param fileSystem * @param deprecationPolicy * @param formatter */ public DelegateMethodGenerator(FileSystem fileSystem, DeprecationPolicy deprecationPolicy, CodeFormatter formatter) { super(); this.fileSystem = fileSystem; this.deprecationPolicy = deprecationPolicy; this.formatter = formatter; } /** * Get all static methods for a class * * @param clazz * @return List of all static methods */ protected List<Method> listStaticMethodsForClass(Class<?> clazz) { return Arrays.stream(clazz.getMethods()).filter(m -> Modifier.isStatic(m.getModifiers())) .sorted(makeMethodSorter()).collect(Collectors.toList()); } private Comparator<? super Method> makeMethodSorter() { return (m1, m2) -> { int val = m1.getName().compareTo(m2.getName()); int parameterCountM1 = m1.getParameterCount(); if (val == 0) { val = Integer.compare(parameterCountM1, m2.getParameterCount()); } if (val == 0) { val = compareSimpleTypeNamesOfParameters(m1, m2, val, parameterCountM1); } if (val == 0) { val = m1.toGenericString().compareTo(m2.toGenericString()); } return val; }; } private int compareSimpleTypeNamesOfParameters(Method m1, Method m2, int val, int parameterCountM1) { for (int i = 0; val == 0 && i < parameterCountM1; i++) { val = ClassNameUtils.extractSimpleName(m1.getParameters()[i].getParameterizedType().getTypeName()) .toLowerCase().compareTo( ClassNameUtils.extractSimpleName(m2.getParameters()[i].getParameterizedType().getTypeName()) .toLowerCase()); } return val; } /** * Generate code for 1 static method delegation * * @param targetInterfaceName * The name of the wrapper interface, to avoid class name * conflicts * @param method * @param importsOut * The method potentially adds values to this set if imports are * required * @param argumentNameSource * Provider of argument name information lost during compilation * @return the code for the method delegation */ public String makeDelegateMethod(String targetInterfaceName, Method method, Set<String> importsOut, ArgumentNameSource argumentNameSource) { StringBuilder buf = new StringBuilder(); String genericStringForMethod = method.toGenericString(); String declaringClassTypeName = method.getDeclaringClass().getTypeName(); String methodName = method.getName(); formatter .appendMethodComment(buf, methodName, genericStringForMethod, declaringClassTypeName, generateParamsForJavadocLink(method)) .append(lineBreak(0)).append(this.makeMethodSignature(method, importsOut, argumentNameSource)) .append(" {").append(lineBreak(2)) .append(this.makeDelegateCall(method, targetInterfaceName, importsOut, argumentNameSource)) .append(lineBreak(1)).append("}").append(lineBreak(0)); return buf.toString(); } private String lineBreak(int indentations) { return formatter.newlineWithIndentations(indentations); } private String generateParamsForJavadocLink(Method method) { StringBuilder paramsForJavadocLink = new StringBuilder(); for (Type cur : method.getParameterTypes()) { if (paramsForJavadocLink.length() > 0) { paramsForJavadocLink.append(','); } paramsForJavadocLink.append(cur.getTypeName()); } return paramsForJavadocLink.toString(); } /** * Generate the non-static signature of the method * * @param method * @param importNamesOut * collects any java imports required for the arguments and/or * return type * @param argumentNameSource * For naming arguments * @param indentationUnit * spaces to be inserted n times at the beginning of lines based * on block depth * @return The signature */ protected String makeMethodSignature(Method method, Set<String> importNamesOut, ArgumentNameSource argumentNameSource) { String indentationUnit = formatter.getIndentationUnit(); StringBuilder buf = new StringBuilder(); if (shouldDeprecate(method)) { buf.append(indentationUnit).append("@Deprecated").append(lineBreak(0)); } buf.append(indentationUnit).append("default ") .append(makeGenericMarkerAndUpdateImports(method, importNamesOut)); buf.append(extractShortNameAndUpdateImports(importNamesOut, method.getGenericReturnType().getTypeName())); buf.append(' ').append(method.getName()).append('('); appendMethodArgumentsInSignature(method, importNamesOut, buf, argumentNameSource); buf.append(')'); addThrowsClauseToSignatureUpdatingImports(method, importNamesOut, buf); return buf.toString(); } private boolean shouldDeprecate(Method method) { return isDeprecated(method) && this.deprecationPolicy == DeprecationPolicy.PROPAGATE_DEPRECATION; } /** * Check whether method is deprecated * * @param method * @return true if deprecated, false if not */ protected boolean isDeprecated(Method method) { return method.getDeclaredAnnotationsByType(Deprecated.class).length > 0; } private void addThrowsClauseToSignatureUpdatingImports(Method method, Set<String> importNamesOut, StringBuilder buf) { Class<?>[] exceptionTypes = method.getExceptionTypes(); if (exceptionTypes.length > 0) { buf.append(" throws ") .append(makeCommaDelimitedExceptionTypesListUpdatingImports(importNamesOut, exceptionTypes)); } } private String makeCommaDelimitedExceptionTypesListUpdatingImports(Set<String> importNamesOut, Class<?>[] exceptionTypes) { return String.join(", ", Arrays.stream(exceptionTypes) .map(type -> extractShortNameAndUpdateImports(importNamesOut, type.getTypeName())) .collect(Collectors.toList())); } private String makeGenericMarkerAndUpdateImports(Method method, Set<String> importNamesOut) { StringBuilder buf = new StringBuilder(); TypeVariable<Method>[] typeParameters = method.getTypeParameters(); for (TypeVariable<Method> cur : typeParameters) { appendOpeningOrDelimiter(buf); buf.append(cur.getName()); Type[] bounds = cur.getBounds(); if (hasSuperclassBound(bounds)) { appendAndImportExtendedType(importNamesOut, buf, bounds); } } appendClosingIfOpened(buf); return buf.toString(); } private void appendClosingIfOpened(StringBuilder buf) { if (buf.length() > 0) { buf.append('>').append(' '); } } private void appendOpeningOrDelimiter(StringBuilder buf) { if (buf.length() > 0) { buf.append(","); } else { buf.append('<'); } } private boolean hasSuperclassBound(Type[] bounds) { return bounds.length > 0 && Arrays.stream(bounds).noneMatch(t -> t.getTypeName().endsWith("java.lang.Object")); } private void appendAndImportExtendedType(Set<String> importNamesOut, StringBuilder buf, Type[] bounds) { buf.append(" extends "); for (int i = 0; i < bounds.length; i++) { if (i > 0) { buf.append(","); } String typeName = bounds[i].getTypeName(); buf.append(ClassNameUtils.extractSimpleName(typeName)); importNamesOut.addAll(ClassNameUtils.makeImports(typeName)); } } private void appendMethodArgumentsInSignature(Method method, Set<String> importNamesOut, StringBuilder buf, ArgumentNameSource argumentNameSource) { Type[] types = method.getGenericParameterTypes(); for (int i = 0; i < types.length; i++) { if (i > 0) { buf.append(", "); } appendOneArgument(method, importNamesOut, buf, argumentNameSource, types, i); } } private void appendOneArgument(Method method, Set<String> importNamesOut, StringBuilder buf, ArgumentNameSource argumentNameSource, Type[] types, int i) { String fullTypeName = types[i].getTypeName(); buf.append(extractAndProcessShortTypeName(method, importNamesOut, types, i, fullTypeName)).append(' ') .append(argumentNameSource.getArgumentNameFor(method, i)); } private String extractAndProcessShortTypeName(Method method, Set<String> importNamesOut, Type[] types, int i, String fullTypeName) { String shortTypeName = extractShortNameAndUpdateImports(importNamesOut, fullTypeName); if (isVarargsParameter(method, types, i)) { shortTypeName = ClassNameUtils.convertToVarArgs(shortTypeName); } return shortTypeName; } private boolean isVarargsParameter(Method method, Type[] types, int i) { return i == types.length - 1 && method.isVarArgs(); } private static String extractShortNameAndUpdateImports(Set<String> importNamesOut, String fullTypeName) { String shortTypeName = ClassNameUtils.extractSimpleName(fullTypeName); if (shortTypeName.length() < fullTypeName.length()) { importNamesOut.addAll(ClassNameUtils.makeImports(fullTypeName)); } return shortTypeName; } /** * Generate the line of code calling the static method * * @param method * @param targetInterfaceName * The name of the wrapper interface, to avoid class name * conflicts * @param importsOut * For receiving imports needed * @param argumentNameSource * @return The line of code which calls the delegate class's static method */ public String makeDelegateCall(Method method, String targetInterfaceName, Set<String> importsOut, ArgumentNameSource argumentNameSource) { StringBuilder buf = new StringBuilder(); appendReturnIfNotVoid(method, buf); Class<?> declaringClass = method.getDeclaringClass(); String delegateClassName = ClassNameUtils.getDelegateClassNameWithoutPackageIfNoConflict(declaringClass, targetInterfaceName); addImportIfNeeded(importsOut, declaringClass, delegateClassName); appendStaticCall(method, argumentNameSource, buf, delegateClassName); return buf.toString(); } private void addImportIfNeeded(Set<String> importsOut, Class<?> declaringClass, String delegateClassName) { if (needToImport(delegateClassName)) { importsOut.add(declaringClass.getCanonicalName()); } } private void appendStaticCall(Method method, ArgumentNameSource argumentNameSource, StringBuilder buf, String delegateClassName) { buf.append(delegateClassName).append(".").append(method.getName()).append("("); appendArgumentsInDelegateCall(method, argumentNameSource, buf); buf.append(");"); } private void appendReturnIfNotVoid(Method method, StringBuilder buf) { if (!"void".equals(method.getReturnType().getTypeName())) { buf.append("return "); } } private void appendArgumentsInDelegateCall(Method method, ArgumentNameSource argumentNameSource, StringBuilder buf) { int parameterCount = method.getParameterCount(); for (int i = 0; i < parameterCount; i++) { if (i > 0) { buf.append(", "); } buf.append(argumentNameSource.getArgumentNameFor(method, i)); } } /** * @param delegateClassName * @return */ private boolean needToImport(String delegateClassName) { return delegateClassName.indexOf('.') < 0; } /** * Retrieve the constants for a class * * @param clazz * @return List of all constants declared in clazz */ protected List<Field> listConstantsForClass(Class<?> clazz) { return Arrays.stream(clazz.getFields()).filter(f -> { int modifiers = f.getModifiers(); return Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers); }).sorted(Comparator.comparing(Field::getName)).collect(Collectors.toList()); } /** * Generate code for one constant * * @param field * @param fieldClass * @param imports * @param buf * @param targetInterfaceName * @param indentationUnit */ protected void generateConstant(Field field, Class<?> fieldClass, Set<String> imports, StringBuilder buf, String targetInterfaceName, String indentationUnit) { String type = extractShortNameAndUpdateImports(imports, getTypeNameFromFieldForConstant(field)); buf.append(lineBreak(0)); appendCommentForConstant(field, fieldClass, buf, indentationUnit); appendConstantDeclaration(field, fieldClass, buf, targetInterfaceName, indentationUnit, type); } private void appendConstantDeclaration(Field field, Class<?> fieldClass, StringBuilder buf, String targetInterfaceName, String indentationUnit, String type) { buf.append(indentationUnit).append("public static final ").append(type).append(' ').append(field.getName()) .append(" = ") .append(ClassNameUtils.getDelegateClassNameWithoutPackageIfNoConflict(fieldClass, targetInterfaceName)) .append('.').append(field.getName()).append(";").append(lineBreak(0)); } /** * Append a javadoc comment for a generated constant * * @param field * @param fieldClass * @param buf * @param indentationUnit */ protected void appendCommentForConstant(Field field, Class<?> fieldClass, StringBuilder buf, String indentationUnit) { buf.append(indentationUnit).append("/** ").append("{@link ").append(fieldClass.getTypeName()).append('#') .append(field.getName()).append("} */").append(lineBreak(0)); } private String getTypeNameFromFieldForConstant(Field field) { String typeName = field.getType().getTypeName(); TypeVariable<?>[] typeParameters = field.getType().getTypeParameters(); if (null != typeParameters && typeParameters.length > 0) { typeName += Arrays.asList(typeParameters).stream().map(t -> "Object") .collect(Collectors.joining(",", "<", ">")); } return typeName; } /** * Generate Java code declaring and assigning constants which refer to each * constant in the delegate class * * @param delegateClass * @param importsUpdated * As a side effect, the imports needed for these constants are * added to the set * @param indentationSpaces * @param targetInterfaceName * @return The Java code declaring and initializing all constants for the * wrapper interface */ protected String generateConstantsForClassUpdatingImports(Class<?> delegateClass, Set<String> importsUpdated, String targetInterfaceName) { String indentationUnit = formatter.getIndentationUnit(); StringBuilder buf = new StringBuilder(); this.listConstantsForClass(delegateClass).stream().forEach(field -> { generateConstant(field, delegateClass, importsUpdated, buf, targetInterfaceName, indentationUnit); }); importsUpdated.addAll(ClassNameUtils.makeImports(delegateClass.getTypeName())); return buf.toString(); } /** * Generate the code of a java interface file delegating to the target * class's static fields and methods * * @param targetPackageName * @param targetInterfaceName * @param delegateClass * @param argumentNameSource * @param indentationSpaces * @return Generated code */ public String generateDelegateClassCode(String targetPackageName, String targetInterfaceName, Class<?> delegateClass, ArgumentNameSource argumentNameSource) { Set<String> imports = new HashSet<String>(); StringBuilder result = new StringBuilder(); String constants = this.generateConstantsForClassUpdatingImports(delegateClass, imports, targetInterfaceName); String methods = this.generateMethodsForClassUpdatingImports(delegateClass, imports, targetInterfaceName, argumentNameSource); appendPackage(targetPackageName, result); appendSortedImports(result, imports, targetInterfaceName); appendInterfaceBody(targetInterfaceName, delegateClass, result, constants, methods); return result.toString(); } private void appendInterfaceBody(String targetInterfaceName, Class<?> delegateClass, StringBuilder buf, String constants, String methods) { formatter.appendClassComment(delegateClass, buf); buf.append("public interface ").append(targetInterfaceName); buf.append(" {"); for (int i = 0; i < 3; i++) { buf.append(lineBreak(0)); } formatter.appendCommentBeforeConstants(buf).append(constants).append(lineBreak(0)).append(lineBreak(0)); formatter.appendCommentBeforeMethods(buf).append(methods).append(lineBreak(0)).append("}"); } private void appendPackage(String targetPackageName, StringBuilder buf) { if (null != targetPackageName && !targetPackageName.isEmpty()) { buf.append("package ").append(targetPackageName).append(";").append(lineBreak(0)).append(lineBreak(0)); } } private void appendSortedImports(StringBuilder buf, Set<String> importsUpdated, String targetInterfaceName) { String[] sortedImports = importsUpdated.toArray(new String[importsUpdated.size()]); Arrays.sort(sortedImports); for (String cur : sortedImports) { if (hasNoConflict(targetInterfaceName, cur)) { buf.append("import ").append(cur).append("; ").append(lineBreak(0)); } } } private boolean hasNoConflict(String targetInterfaceName, String cur) { return !cur.endsWith("." + targetInterfaceName); } /** * Generate java code for all delegate methods * * @param delegateClass * @param importsUpdated * @param indentationSpaces * @param targetInterfaceName * @param argumentNameSource * @return code */ protected String generateMethodsForClassUpdatingImports(Class<?> delegateClass, Set<String> importsUpdated, String targetInterfaceName, ArgumentNameSource argumentNameSource) { StringBuilder buf = new StringBuilder(); for (Method cur : this.listStaticMethodsForClass(delegateClass)) { if (deprecationPolicyDoesNotForbid(cur)) { buf.append(lineBreak(0)) .append(this.makeDelegateMethod(targetInterfaceName, cur, importsUpdated, argumentNameSource)) .append(lineBreak(0)).append(lineBreak(0)); } } return buf.toString(); } /** * Apply the deprecation policy to the method * * @param method * @return true if the handling of the method is not blocked by the * deprecation policy, false if blocked */ protected boolean deprecationPolicyDoesNotForbid(Method method) { return !isDeprecated(method) || this.deprecationPolicy != DeprecationPolicy.IGNORE_DEPRECATED_METHODS; } /* * (non-Javadoc) * * @see org.interfaceit.ClassCodeGenerator#generateClassToFile(java.io.File, * java.lang.String, java.lang.Class, java.lang.String) */ @Override public File generateClassToFile(File saveDirectory, String targetInterfaceName, Class<?> delegateClass, String targetPackageName, ArgumentNameSource argumentNameSource) throws IOException { return writeClassFile(saveDirectory, this.generateDelegateClassCode(targetPackageName, targetInterfaceName, delegateClass, argumentNameSource), interfaceNameToFileName(targetInterfaceName)); } private String interfaceNameToFileName(String targetInterfaceName) { return targetInterfaceName + ".java"; } private File writeClassFile(File dir, String content, String fileName) throws IOException, UnableToCreateOutputDirectory { fileSystem.makeOutputDirectoryIfAbsent(dir); return fileSystem.writeFile(dir, fileName, content); } }
package com.karateca.ddescriber.model; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.treeStructure.Tree; import java.util.Enumeration; /** * @author andresdom@google.com (Andres Dominguez) */ public class JasmineTree extends Tree { private final TreeNode rootNode; public JasmineTree() { super(new TreeNode("Root node")); rootNode = (TreeNode) this.getModel().getRoot(); expandRow(0); setRootVisible(false); } public void addFile(JasmineFile jasmineFile) { rootNode.add(jasmineFile.getTreeNode()); } public TreeNode getRootNode() { return rootNode; } public void updateFile(JasmineFile jasmineFile) { TreeNode found = findNodeForJasmineFile(jasmineFile.getVirtualFile()); if (found != null) { // The jasmine file is in the tree already. Update it or remove it. updateOrRemove(jasmineFile, found); } else if (jasmineFile.hasTestsMarkedToRun()) { rootNode.add(jasmineFile.getTreeNode()); } } private void updateOrRemove(JasmineFile jasmineFile, TreeNode found) { if (jasmineFile.hasTestsMarkedToRun()) { jasmineFile.updateTreeNode(found); } else { rootNode.remove(found); found.removeFromParent(); } } private TreeNode findNodeForJasmineFile(VirtualFile virtualFile) { Enumeration children = rootNode.children(); while (children.hasMoreElements()) { TreeNode treeNode = (TreeNode) children.nextElement(); if (treeNode.getVirtualFile() == virtualFile) { return treeNode; } } return null; } }
package com.nilhcem.hostseditor.core; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.inject.Singleton; import android.util.Log; import com.google.common.base.Charsets; import com.google.common.io.Files; import com.nilhcem.hostseditor.model.Host; @Singleton public class HostsManager { private static final String TAG = "HostsManager"; public static final String HOSTS_FILE = "/system/etc/hosts"; private List<Host> mHosts = null; // Do not access this field directly even in the same class, use getAllHosts() instead. // Must be in an async call public synchronized List<Host> getHosts(boolean forceRefresh) { if (mHosts == null || forceRefresh) { mHosts = Collections.synchronizedList(new ArrayList<Host>()); try { List<String> lines = Files.readLines(new File(HOSTS_FILE), Charsets.UTF_8); for (String line : lines) { Host host = Host.fromString(line); if (host != null) { mHosts.add(host); } } } catch (IOException e) { Log.e(TAG, "I/O error while opening hosts file", e); } } return mHosts; } }
package lombok.eclipse.handlers; import static lombok.eclipse.Eclipse.*; import static lombok.eclipse.handlers.PKG.*; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import lombok.AccessLevel; import lombok.Data; import lombok.core.AnnotationValues; import lombok.core.AST.Kind; import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseAST.Node; import lombok.eclipse.handlers.PKG.MethodExistsResult; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AllocationExpression; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.Assignment; import org.eclipse.jdt.internal.compiler.ast.BinaryExpression; import org.eclipse.jdt.internal.compiler.ast.CastExpression; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.ConditionalExpression; import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration; import org.eclipse.jdt.internal.compiler.ast.EqualExpression; import org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FalseLiteral; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.FieldReference; import org.eclipse.jdt.internal.compiler.ast.IfStatement; import org.eclipse.jdt.internal.compiler.ast.IntLiteral; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.MarkerAnnotation; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.NameReference; import org.eclipse.jdt.internal.compiler.ast.NullLiteral; import org.eclipse.jdt.internal.compiler.ast.OperatorIds; import org.eclipse.jdt.internal.compiler.ast.ParameterizedSingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.Reference; import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.StringLiteral; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.TrueLiteral; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeParameter; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.ast.UnaryExpression; import org.eclipse.jdt.internal.compiler.ast.Wildcard; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.lookup.TypeConstants; import org.eclipse.jdt.internal.compiler.lookup.TypeIds; import org.mangosdk.spi.ProviderFor; @ProviderFor(EclipseAnnotationHandler.class) public class HandleData implements EclipseAnnotationHandler<Data> { @Override public boolean handle(AnnotationValues<Data> annotation, Annotation ast, Node annotationNode) { Data ann = annotation.getInstance(); Node typeNode = annotationNode.up(); TypeDeclaration typeDecl = null; if ( typeNode.get() instanceof TypeDeclaration ) typeDecl = (TypeDeclaration) typeNode.get(); int modifiers = typeDecl == null ? 0 : typeDecl.modifiers; boolean notAClass = (modifiers & (ClassFileConstants.AccInterface | ClassFileConstants.AccAnnotation | ClassFileConstants.AccEnum)) != 0; if ( typeDecl == null || notAClass ) { annotationNode.addError("@Data is only supported on a class."); return false; } List<Node> nodesForEquality = new ArrayList<Node>(); List<Node> nodesForConstructorAndToString = new ArrayList<Node>(); for ( Node child : typeNode.down() ) { if ( child.getKind() != Kind.FIELD ) continue; FieldDeclaration fieldDecl = (FieldDeclaration) child.get(); //Skip static fields. if ( (fieldDecl.modifiers & ClassFileConstants.AccStatic) != 0 ) continue; if ( (fieldDecl.modifiers & ClassFileConstants.AccTransient) == 0 ) nodesForEquality.add(child); nodesForConstructorAndToString.add(child); new HandleGetter().generateGetterForField(child, annotationNode.get()); if ( (fieldDecl.modifiers & ClassFileConstants.AccFinal) == 0 ) new HandleSetter().generateSetterForField(child, annotationNode.get()); } if ( methodExists("toString", typeNode) == MethodExistsResult.NOT_EXISTS ) { MethodDeclaration toString = createToString(typeNode, nodesForConstructorAndToString, ast); injectMethod(typeNode, toString); } if ( constructorExists(typeNode) == MethodExistsResult.NOT_EXISTS ) { ConstructorDeclaration constructor = createConstructor( ann.staticConstructor().isEmpty(), typeNode, nodesForConstructorAndToString, ast); injectMethod(typeNode, constructor); } if ( !ann.staticConstructor().isEmpty() ) { if ( methodExists("of", typeNode) == MethodExistsResult.NOT_EXISTS ) { MethodDeclaration staticConstructor = createStaticConstructor( ann.staticConstructor(), typeNode, nodesForConstructorAndToString, ast); injectMethod(typeNode, staticConstructor); } } if ( methodExists("equals", typeNode) == MethodExistsResult.NOT_EXISTS ) { MethodDeclaration equals = createEquals(typeNode, nodesForEquality, ast); injectMethod(typeNode, equals); } if ( methodExists("hashCode", typeNode) == MethodExistsResult.NOT_EXISTS ) { MethodDeclaration hashCode = createHashCode(typeNode, nodesForEquality, ast); injectMethod(typeNode, hashCode); } return false; } private MethodDeclaration createToString(Node type, Collection<Node> fields, ASTNode pos) { char[] rawTypeName = ((TypeDeclaration)type.get()).name; String typeName = rawTypeName == null ? "" : new String(rawTypeName); char[] prefix = (typeName + "(").toCharArray(); char[] suffix = ")".toCharArray(); char[] infix = ", ".toCharArray(); long p = (long)pos.sourceStart << 32 | pos.sourceEnd; final int PLUS = OperatorIds.PLUS; boolean first = true; Expression current = new StringLiteral(prefix, 0, 0, 0); for ( Node field : fields ) { FieldDeclaration f = (FieldDeclaration)field.get(); if ( f.name == null || f.type == null ) continue; if ( !first ) { current = new BinaryExpression(current, new StringLiteral(infix, 0, 0, 0), PLUS); } else first = false; Expression ex; if ( f.type.dimensions() > 0 ) { MessageSend arrayToString = new MessageSend(); arrayToString.receiver = generateQualifiedNameRef(TypeConstants.JAVA, TypeConstants.UTIL, "Arrays".toCharArray()); arrayToString.arguments = new Expression[] { new SingleNameReference(f.name, p) }; if ( f.type.dimensions() > 1 || !BUILT_IN_TYPES.contains(new String(f.type.getLastToken())) ) { arrayToString.selector = "deepToString".toCharArray(); } else { arrayToString.selector = "toString".toCharArray(); } ex = arrayToString; } else ex = new SingleNameReference(f.name, p); current = new BinaryExpression(current, ex, PLUS); } current = new BinaryExpression(current, new StringLiteral(suffix, 0, 0, 0), PLUS); ReturnStatement returnStatement = new ReturnStatement(current, (int)(p >> 32), (int)p); MethodDeclaration method = new MethodDeclaration(((CompilationUnitDeclaration) type.top().get()).compilationResult); method.modifiers = PKG.toModifier(AccessLevel.PUBLIC); method.returnType = new QualifiedTypeReference(TypeConstants.JAVA_LANG_STRING, new long[] {0, 0, 0}); method.annotations = new Annotation[] { new MarkerAnnotation(new QualifiedTypeReference(TypeConstants.JAVA_LANG_OVERRIDE, new long[] { 0, 0, 0}), 0) }; method.arguments = null; method.selector = "toString".toCharArray(); method.thrownExceptions = null; method.typeParameters = null; method.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG; method.bodyStart = method.declarationSourceStart = method.sourceStart = pos.sourceStart; method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = pos.sourceEnd; method.statements = new Statement[] { returnStatement }; return method; } private ConstructorDeclaration createConstructor(boolean isPublic, Node type, Collection<Node> fields, ASTNode pos) { long p = (long)pos.sourceStart << 32 | pos.sourceEnd; ConstructorDeclaration constructor = new ConstructorDeclaration( ((CompilationUnitDeclaration) type.top().get()).compilationResult); constructor.modifiers = PKG.toModifier(isPublic ? AccessLevel.PUBLIC : AccessLevel.PRIVATE); constructor.annotations = null; constructor.selector = ((TypeDeclaration)type.get()).name; constructor.constructorCall = new ExplicitConstructorCall(ExplicitConstructorCall.ImplicitSuper); constructor.thrownExceptions = null; constructor.typeParameters = null; constructor.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG; constructor.bodyStart = constructor.declarationSourceStart = constructor.sourceStart = pos.sourceStart; constructor.bodyEnd = constructor.declarationSourceEnd = constructor.sourceEnd = pos.sourceEnd; constructor.arguments = null; List<Argument> args = new ArrayList<Argument>(); List<Statement> assigns = new ArrayList<Statement>(); for ( Node fieldNode : fields ) { FieldDeclaration field = (FieldDeclaration) fieldNode.get(); FieldReference thisX = new FieldReference(("this." + new String(field.name)).toCharArray(), p); thisX.receiver = new ThisReference((int)(p >> 32), (int)p); thisX.token = field.name; assigns.add(new Assignment(thisX, new SingleNameReference(field.name, p), (int)p)); long fieldPos = (((long)field.sourceStart) << 32) | field.sourceEnd; args.add(new Argument(field.name, fieldPos, copyType(field.type), 0)); } constructor.statements = assigns.isEmpty() ? null : assigns.toArray(new Statement[assigns.size()]); constructor.arguments = args.isEmpty() ? null : args.toArray(new Argument[args.size()]); return constructor; } private MethodDeclaration createStaticConstructor(String name, Node type, Collection<Node> fields, ASTNode pos) { long p = (long)pos.sourceStart << 32 | pos.sourceEnd; MethodDeclaration constructor = new MethodDeclaration( ((CompilationUnitDeclaration) type.top().get()).compilationResult); constructor.modifiers = PKG.toModifier(AccessLevel.PUBLIC) | Modifier.STATIC; TypeDeclaration typeDecl = (TypeDeclaration) type.get(); if ( typeDecl.typeParameters != null && typeDecl.typeParameters.length > 0 ) { TypeReference[] refs = new TypeReference[typeDecl.typeParameters.length]; int idx = 0; for ( TypeParameter param : typeDecl.typeParameters ) { refs[idx++] = new SingleTypeReference(param.name, 0); } constructor.returnType = new ParameterizedSingleTypeReference(typeDecl.name, refs, 0, p); } else constructor.returnType = new SingleTypeReference(((TypeDeclaration)type.get()).name, p); constructor.annotations = null; constructor.selector = name.toCharArray(); constructor.thrownExceptions = null; constructor.typeParameters = copyTypeParams(((TypeDeclaration)type.get()).typeParameters); constructor.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG; constructor.bodyStart = constructor.declarationSourceStart = constructor.sourceStart = pos.sourceStart; constructor.bodyEnd = constructor.declarationSourceEnd = constructor.sourceEnd = pos.sourceEnd; List<Argument> args = new ArrayList<Argument>(); List<Expression> assigns = new ArrayList<Expression>(); AllocationExpression statement = new AllocationExpression(); statement.type = copyType(constructor.returnType); for ( Node fieldNode : fields ) { FieldDeclaration field = (FieldDeclaration) fieldNode.get(); long fieldPos = (((long)field.sourceStart) << 32) | field.sourceEnd; assigns.add(new SingleNameReference(field.name, fieldPos)); args.add(new Argument(field.name, fieldPos, copyType(field.type), 0)); } statement.arguments = assigns.isEmpty() ? null : assigns.toArray(new Expression[assigns.size()]); constructor.arguments = args.isEmpty() ? null : args.toArray(new Argument[args.size()]); constructor.statements = new Statement[] { new ReturnStatement(statement, (int)(p >> 32), (int)p) }; return constructor; } private static final Set<String> BUILT_IN_TYPES = Collections.unmodifiableSet(new HashSet<String>(Arrays.asList( "byte", "short", "int", "long", "char", "boolean", "double", "float"))); private MethodDeclaration createEquals(Node type, Collection<Node> fields, ASTNode pos) { MethodDeclaration method = new MethodDeclaration( ((CompilationUnitDeclaration) type.top().get()).compilationResult); method.modifiers = PKG.toModifier(AccessLevel.PUBLIC); method.returnType = TypeReference.baseTypeReference(TypeIds.T_boolean, 0); method.annotations = new Annotation[] { new MarkerAnnotation(new QualifiedTypeReference(TypeConstants.JAVA_LANG_OVERRIDE, new long[] { 0, 0, 0}), 0) }; method.selector = "equals".toCharArray(); method.thrownExceptions = null; method.typeParameters = null; method.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG; method.bodyStart = method.declarationSourceStart = method.sourceStart = pos.sourceStart; method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = pos.sourceEnd; method.arguments = new Argument[] { new Argument(new char[] { 'o' }, 0, new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, new long[] { 0, 0, 0 }), 0) }; List<Statement> statements = new ArrayList<Statement>(); /* if ( o == this ) return true; */ { EqualExpression otherEqualsThis = new EqualExpression( new SingleNameReference(new char[] { 'o' }, 0), new ThisReference(0, 0), OperatorIds.EQUAL_EQUAL); ReturnStatement returnTrue = new ReturnStatement(new TrueLiteral(0, 0), 0, 0); IfStatement ifOtherEqualsThis = new IfStatement(otherEqualsThis, returnTrue, 0, 0); statements.add(ifOtherEqualsThis); } /* if ( o == null ) return false; */ { EqualExpression otherEqualsNull = new EqualExpression( new SingleNameReference(new char[] { 'o' }, 0), new NullLiteral(0, 0), OperatorIds.EQUAL_EQUAL); ReturnStatement returnFalse = new ReturnStatement(new FalseLiteral(0, 0), 0, 0); IfStatement ifOtherEqualsNull = new IfStatement(otherEqualsNull, returnFalse, 0, 0); statements.add(ifOtherEqualsNull); } /* if ( o.getClass() != getClass() ) return false; */ { MessageSend otherGetClass = new MessageSend(); otherGetClass.receiver = new SingleNameReference(new char[] { 'o' }, 0); otherGetClass.selector = "getClass".toCharArray(); MessageSend thisGetClass = new MessageSend(); thisGetClass.receiver = new ThisReference(0, 0); thisGetClass.selector = "getClass".toCharArray(); EqualExpression classesNotEqual = new EqualExpression(otherGetClass, thisGetClass, OperatorIds.NOT_EQUAL); ReturnStatement returnFalse = new ReturnStatement(new FalseLiteral(0, 0), 0, 0); IfStatement ifClassesNotEqual = new IfStatement(classesNotEqual, returnFalse, 0, 0); statements.add(ifClassesNotEqual); } char[] otherN = "other".toCharArray(); TypeDeclaration typeDecl = (TypeDeclaration)type.get(); /* MyType<?> other = (MyType<?>) o; */ { if ( !fields.isEmpty() ) { LocalDeclaration other = new LocalDeclaration(otherN, 0, 0); char[] typeName = typeDecl.name; Expression targetType; if ( typeDecl.typeParameters == null || typeDecl.typeParameters.length == 0 ) { targetType = new SingleNameReference(((TypeDeclaration)type.get()).name, 0); other.type = new SingleTypeReference(typeName, 0); } else { TypeReference[] typeArgs = new TypeReference[typeDecl.typeParameters.length]; for ( int i = 0 ; i < typeArgs.length ; i++ ) typeArgs[i] = new Wildcard(Wildcard.UNBOUND); targetType = new ParameterizedSingleTypeReference(typeName, typeArgs, 0, 0); other.type = new ParameterizedSingleTypeReference(typeName, copyTypes(typeArgs), 0, 0); } other.initialization = new CastExpression( new SingleNameReference(new char[] { 'o' }, 0), targetType); statements.add(other); } } for ( Node field : fields ) { FieldDeclaration f = (FieldDeclaration) field.get(); char[] token = f.type.getLastToken(); if ( f.type.dimensions() == 0 && token != null ) { if ( Arrays.equals(TypeConstants.FLOAT, token) ) { statements.add(generateCompareFloatOrDouble(otherN, "Float".toCharArray(), f.name)); } else if ( Arrays.equals(TypeConstants.DOUBLE, token) ) { statements.add(generateCompareFloatOrDouble(otherN, "Double".toCharArray(), f.name)); } else if ( BUILT_IN_TYPES.contains(new String(token)) ) { EqualExpression fieldsNotEqual = new EqualExpression( new SingleNameReference(f.name, 0), generateQualifiedNameRef(otherN, f.name), OperatorIds.NOT_EQUAL); ReturnStatement returnStatement = new ReturnStatement(new FalseLiteral(0, 0), 0, 0); statements.add(new IfStatement(fieldsNotEqual, returnStatement, 0, 0)); } else /* objects */ { EqualExpression fieldIsNull = new EqualExpression( new SingleNameReference(f.name, 0), new NullLiteral(0, 0), OperatorIds.EQUAL_EQUAL); EqualExpression otherFieldIsntNull = new EqualExpression( generateQualifiedNameRef(otherN, f.name), new NullLiteral(0, 0), OperatorIds.NOT_EQUAL); MessageSend equalsCall = new MessageSend(); equalsCall.receiver = new SingleNameReference(f.name, 0); equalsCall.selector = "equals".toCharArray(); equalsCall.arguments = new Expression[] { generateQualifiedNameRef(otherN, f.name) }; UnaryExpression fieldsNotEqual = new UnaryExpression(equalsCall, OperatorIds.NOT); ConditionalExpression fullEquals = new ConditionalExpression(fieldIsNull, otherFieldIsntNull, fieldsNotEqual); ReturnStatement returnStatement = new ReturnStatement(new FalseLiteral(0, 0), 0, 0); statements.add(new IfStatement(fullEquals, returnStatement, 0, 0)); } } else if ( f.type.dimensions() > 0 && token != null ) { MessageSend arraysEqualCall = new MessageSend(); arraysEqualCall.receiver = generateQualifiedNameRef(TypeConstants.JAVA, TypeConstants.UTIL, "Arrays".toCharArray()); if ( f.type.dimensions() > 1 || !BUILT_IN_TYPES.contains(new String(token)) ) { arraysEqualCall.selector = "deepEquals".toCharArray(); } else { arraysEqualCall.selector = "equals".toCharArray(); } arraysEqualCall.arguments = new Expression[] { new SingleNameReference(f.name, 0), generateQualifiedNameRef(otherN, f.name) }; UnaryExpression arraysNotEqual = new UnaryExpression(arraysEqualCall, OperatorIds.NOT); ReturnStatement returnStatement = new ReturnStatement(new FalseLiteral(0, 0), 0, 0); statements.add(new IfStatement(arraysNotEqual, returnStatement, 0, 0)); } } /* return true; */ { statements.add(new ReturnStatement(new TrueLiteral(0, 0), 0, 0)); } method.statements = statements.toArray(new Statement[statements.size()]); return method; } private IfStatement generateCompareFloatOrDouble(char[] otherN, char[] floatOrDouble, char[] fieldName) { /* if ( Float.compare(fieldName, other.fieldName) != 0 ) return false */ MessageSend floatCompare = new MessageSend(); floatCompare.receiver = generateQualifiedNameRef(TypeConstants.JAVA, TypeConstants.LANG, floatOrDouble); floatCompare.selector = "compare".toCharArray(); floatCompare.arguments = new Expression[] { new SingleNameReference(fieldName, 0), generateQualifiedNameRef(otherN, fieldName) }; EqualExpression ifFloatCompareIsNot0 = new EqualExpression(floatCompare, new IntLiteral(new char[] {'0'}, 0, 0), OperatorIds.NOT_EQUAL); ReturnStatement returnFalse = new ReturnStatement(new FalseLiteral(0, 0), 0, 0); return new IfStatement(ifFloatCompareIsNot0, returnFalse, 0, 0); } private Reference generateFieldReference(char[] fieldName) { FieldReference thisX = new FieldReference(("this." + new String(fieldName)).toCharArray(), 0); thisX.receiver = new ThisReference(0, 0); thisX.token = fieldName; return thisX; } private NameReference generateQualifiedNameRef(char[]... varNames) { if ( varNames.length > 1 ) return new QualifiedNameReference(varNames, new long[varNames.length], 0, 0); else return new SingleNameReference(varNames[0], 0); } private MethodDeclaration createHashCode(Node type, Collection<Node> fields, ASTNode pos) { MethodDeclaration method = new MethodDeclaration( ((CompilationUnitDeclaration) type.top().get()).compilationResult); method.modifiers = PKG.toModifier(AccessLevel.PUBLIC); method.returnType = TypeReference.baseTypeReference(TypeIds.T_int, 0); method.annotations = new Annotation[] { new MarkerAnnotation(new QualifiedTypeReference(TypeConstants.JAVA_LANG_OVERRIDE, new long[] { 0, 0, 0}), 0) }; method.selector = "hashCode".toCharArray(); method.thrownExceptions = null; method.typeParameters = null; method.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG; method.bodyStart = method.declarationSourceStart = method.sourceStart = pos.sourceStart; method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = pos.sourceEnd; method.arguments = null; List<Statement> statements = new ArrayList<Statement>(); List<Expression> intoResult = new ArrayList<Expression>(); final char[] PRIME = "PRIME".toCharArray(); final char[] RESULT = "result".toCharArray(); final boolean isEmpty = fields.isEmpty(); /* final int PRIME = 31; */ { if ( !isEmpty ) { /* Without fields, PRIME isn't used, and that would trigger a 'local variable not used' warning. */ LocalDeclaration primeDecl = new LocalDeclaration(PRIME, 0 ,0); primeDecl.modifiers = Modifier.FINAL; primeDecl.type = TypeReference.baseTypeReference(TypeIds.T_int, 0); primeDecl.initialization = new IntLiteral("31".toCharArray(), 0, 0); statements.add(primeDecl); } } /* int result = 1; */ { LocalDeclaration resultDecl = new LocalDeclaration(RESULT, 0, 0); resultDecl.initialization = new IntLiteral("1".toCharArray(), 0, 0); resultDecl.type = TypeReference.baseTypeReference(TypeIds.T_int, 0); statements.add(resultDecl); } int tempCounter = 0; for ( Node field : fields ) { FieldDeclaration f = (FieldDeclaration) field.get(); char[] token = f.type.getLastToken(); if ( f.type.dimensions() == 0 && token != null ) { if ( Arrays.equals(TypeConstants.FLOAT, token) ) { /* Float.floatToIntBits(fieldName) */ MessageSend floatToIntBits = new MessageSend(); floatToIntBits.receiver = generateQualifiedNameRef(TypeConstants.JAVA_LANG_FLOAT); floatToIntBits.selector = "floatToIntBits".toCharArray(); floatToIntBits.arguments = new Expression[] { generateFieldReference(f.name) }; intoResult.add(floatToIntBits); } else if ( Arrays.equals(TypeConstants.DOUBLE, token) ) { /* longToIntForHashCode(Double.doubleToLongBits(fieldName)) */ MessageSend doubleToLongBits = new MessageSend(); doubleToLongBits.receiver = generateQualifiedNameRef(TypeConstants.JAVA_LANG_DOUBLE); doubleToLongBits.selector = "doubleToLongBits".toCharArray(); doubleToLongBits.arguments = new Expression[] { generateFieldReference(f.name) }; final char[] tempName = ("temp" + ++tempCounter).toCharArray(); LocalDeclaration tempVar = new LocalDeclaration(tempName, 0, 0); tempVar.initialization = doubleToLongBits; tempVar.type = TypeReference.baseTypeReference(TypeIds.T_long, 0); tempVar.modifiers = Modifier.FINAL; statements.add(tempVar); intoResult.add(longToIntForHashCode( new SingleNameReference(tempName, 0), new SingleNameReference(tempName, 0))); } else if ( Arrays.equals(TypeConstants.BOOLEAN, token) ) { /* booleanField ? 1231 : 1237 */ intoResult.add(new ConditionalExpression( generateFieldReference(f.name), new IntLiteral("1231".toCharArray(), 0, 0), new IntLiteral("1237".toCharArray(), 0 ,0))); } else if ( Arrays.equals(TypeConstants.LONG, token) ) { intoResult.add(longToIntForHashCode(generateFieldReference(f.name), generateFieldReference(f.name))); } else if ( BUILT_IN_TYPES.contains(new String(token)) ) { intoResult.add(generateFieldReference(f.name)); } else /* objects */ { /* this.fieldName == null ? 0 : this.fieldName.hashCode() */ MessageSend hashCodeCall = new MessageSend(); hashCodeCall.receiver = generateFieldReference(f.name); hashCodeCall.selector = "hashCode".toCharArray(); EqualExpression objIsNull = new EqualExpression( generateFieldReference(f.name), new NullLiteral(0, 0), OperatorIds.EQUAL_EQUAL); ConditionalExpression nullOrHashCode = new ConditionalExpression( objIsNull, new IntLiteral("0".toCharArray(), 0, 0), hashCodeCall); intoResult.add(nullOrHashCode); } } else if ( f.type.dimensions() > 0 && token != null ) { /* Arrays.deepHashCode(array) //just hashCode for simple arrays */ MessageSend arraysHashCodeCall = new MessageSend(); arraysHashCodeCall.receiver = generateQualifiedNameRef(TypeConstants.JAVA, TypeConstants.UTIL, "Arrays".toCharArray()); if ( f.type.dimensions() > 1 || !BUILT_IN_TYPES.contains(new String(token)) ) { arraysHashCodeCall.selector = "deepHashCode".toCharArray(); } else { arraysHashCodeCall.selector = "hashCode".toCharArray(); } arraysHashCodeCall.arguments = new Expression[] { generateFieldReference(f.name) }; intoResult.add(arraysHashCodeCall); } } /* fold each intoResult entry into: result = result * PRIME + (item); */ { for ( Expression ex : intoResult ) { BinaryExpression multiplyByPrime = new BinaryExpression(new SingleNameReference(RESULT, 0), new SingleNameReference(PRIME, 0), OperatorIds.MULTIPLY); BinaryExpression addItem = new BinaryExpression(multiplyByPrime, ex, OperatorIds.PLUS); statements.add(new Assignment(new SingleNameReference(RESULT, 0), addItem, 0)); } } /* return result; */ { statements.add(new ReturnStatement(new SingleNameReference(RESULT, 0), 0, 0)); } method.statements = statements.toArray(new Statement[statements.size()]); return method; } /** Give 2 clones! */ private Expression longToIntForHashCode(Reference ref1, Reference ref2) { /* (int)(ref >>> 32 ^ ref) */ BinaryExpression higherBits = new BinaryExpression( ref1, new IntLiteral("32".toCharArray(), 0, 0), OperatorIds.UNSIGNED_RIGHT_SHIFT); BinaryExpression xorParts = new BinaryExpression(ref2, higherBits, OperatorIds.XOR); return new CastExpression(xorParts, TypeReference.baseTypeReference(TypeIds.T_int, 0)); } }
package com.buhtum.algo; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.List; import static java.lang.Math.max; public class Knapsack { private final static Logger log = LoggerFactory.getLogger(Knapsack.class); /** * Recursive implementation of 0-1 knapsack problem. Terrible O(2^n) */ public static int naiveRecursive01(List<Item> items, int capacity) { return naiveRecursive01(items, capacity, items.size()); } private static int naiveRecursive01(List<Item> items, int capacity, int size) { if (capacity == 0 || size == 0) return 0; final int index = size - 1; final Item item = items.get(index); if (item.getWeight() > capacity) { return naiveRecursive01(items, capacity, index); } else { return max( item.getValue() + naiveRecursive01(items, capacity - item.getWeight(), index), naiveRecursive01(items, capacity, index)); } } public static int dynamic01(List<Item> tuples, int capacity) { final int size = tuples.size(); final int values[][] = new int[size + 1][capacity + 1]; Arrays.fill(values[0], 0); for (int itemIndex = 1; itemIndex <= size; itemIndex++) { final Item item = tuples.get(itemIndex - 1); for (int weight = 0; weight <= capacity; weight++) { if (item.getWeight() <= weight) { values[itemIndex][weight] = max( item.getValue() + values[itemIndex - 1][weight - item.getWeight()], values[itemIndex - 1][weight]); } else { values[itemIndex][weight] = values[itemIndex - 1][weight]; } } } printArray(values); int remainingCapacity = capacity; for (int itemIndex = size; itemIndex > 0; itemIndex if (values[itemIndex][remainingCapacity] != values[itemIndex - 1][remainingCapacity]) { final Item item = tuples.get(itemIndex - 1); log.debug("Picked item {}: {}", itemIndex, item); remainingCapacity -= item.getWeight(); } } return values[size][capacity]; } public static int dynamicUnbounded(List<Item> tuples, int capacity) { int weights[] = new int[capacity + 1]; Arrays.fill(weights, 0); for (int w = 1; w <= capacity; w++) { weights[w] = 0; Item pickedItem = null; for (final Item item : tuples) { if (item.getWeight() <= w) { final int newValue = item.getValue() + weights[w - item.getWeight()]; if (weights[w] < newValue) { weights[w] = newValue; pickedItem = item; } } } if (pickedItem != null) { log.debug("Picked item: " + pickedItem); } } return weights[capacity]; } private static void printArray(int[][] arr) { for (int i = 0; i < arr.length; i++) { StringBuilder sb = new StringBuilder(); for (int j = 0; j < arr[i].length; j++) { sb.append(String.format("%3d", arr[i][j])).append(" "); } log.debug("{}: {}", i, sb.toString()); } } public static class Item { private final int value; private final int weight; private Item(int value, int weight) { this.value = value; this.weight = weight; } public static Item of(int value, int weight) { return new Item(value, weight); } public int getValue() { return value; } public int getWeight() { return weight; } public String toString() { return "[weight: " + weight + "; value: " + value + "]"; } @Override public boolean equals(Object o) { return EqualsBuilder.reflectionEquals(this, o); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } } }
package org.kohsuke.file_leak_detector; import java.io.File; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.io.Writer; import java.lang.reflect.Field; import java.net.SocketAddress; import java.net.SocketImpl; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Date; import java.net.Socket; import java.net.ServerSocket; import java.nio.channels.SocketChannel; import java.util.WeakHashMap; import java.util.zip.ZipFile; /** * Intercepted JDK calls land here. * * @author Kohsuke Kawaguchi */ public class Listener { /** * Remembers who/where/when opened a file. */ public static class Record { public final Exception stackTrace = new Exception(); public final String threadName; public final long time; protected Record() { // keeping a Thread would potentially leak a thread, so let's just do a name this.threadName = Thread.currentThread().getName(); this.time = System.currentTimeMillis(); } public void dump(String prefix, PrintWriter pw) { StackTraceElement[] trace = stackTrace.getStackTrace(); int i=0; // skip until we find the Method.invoke() that called us for (; i<trace.length; i++) if(trace[i].getClassName().equals("java.lang.reflect.Method")) { i++; break; } // print the rest for (; i < trace.length; i++) pw.println("\tat " + trace[i]); } } /** * Record of opened file. */ public static final class FileRecord extends Record { public final File file; private FileRecord(File file) { this.file = file; } public void dump(String prefix, PrintWriter pw) { pw.println(prefix + file + " by thread:" + threadName + " on " + new Date(time)); super.dump(prefix,pw); } } /** * Record of opened socket. */ public static final class SocketRecord extends Record { public final Socket socket; public final String peer; private SocketRecord(Socket socket) { this.socket = socket; peer = getRemoteAddress(socket); } private String getRemoteAddress(Socket socket) { SocketAddress ra = socket.getRemoteSocketAddress(); return ra!=null ? ra.toString() : null; } public void dump(String prefix, PrintWriter ps) { // best effort at showing where it is/was listening String peer = this.peer; if (peer==null) peer=getRemoteAddress(socket); ps.println(prefix+"socket to "+peer+" by thread:"+threadName+" on "+new Date(time)); super.dump(prefix,ps); } } /** * Record of opened server socket. */ public static final class ServerSocketRecord extends Record { public final ServerSocket socket; public final String address; private ServerSocketRecord(ServerSocket socket) { this.socket = socket; address = getLocalAddress(socket); } private String getLocalAddress(ServerSocket socket) { SocketAddress la = socket.getLocalSocketAddress(); return la!=null ? la.toString() : null; } public void dump(String prefix, PrintWriter ps) { // best effort at showing where it is/was listening String address = this.address; if (address==null) address=getLocalAddress(socket); ps.println(prefix+"server socket at "+address+" by thread:"+threadName+" on "+new Date(time)); super.dump(prefix,ps); } } /** * Record of opened SocketChannel. */ public static final class SocketChannelRecord extends Record { public final SocketChannel socket; private SocketChannelRecord(SocketChannel socket) { this.socket = socket; } public void dump(String prefix, PrintWriter ps) { ps.println(prefix+"socket channel by thread:"+threadName+" on "+new Date(time)); super.dump(prefix,ps); } } /** * Files that are currently open, keyed by the owner object (like {@link FileInputStream}. */ private static Map<Object,Record> TABLE = new WeakHashMap<Object,Record>(); /** * Trace the open/close op */ public static PrintWriter TRACE = null; /** * Trace the "too many open files" error here */ public static PrintWriter ERROR = new PrintWriter(System.err); /** * Tracing may cause additional files to be opened. * In such a case, avoid infinite recursion. */ private static boolean tracing = false; /** * If the table size grows beyond this, report the table */ public static int THRESHOLD = 999999; /** * Is the agent actually transforming the class files? */ /*package*/ static boolean AGENT_INSTALLED = false; /** * Returns true if the leak detector agent is running. */ public static boolean isAgentInstalled() { return AGENT_INSTALLED; } public static synchronized void makeStrong() { TABLE = new LinkedHashMap<Object, Record>(TABLE); } /** * Called when a new file is opened. * * @param _this * {@link FileInputStream}, {@link FileOutputStream}, {@link RandomAccessFile}, or {@link ZipFile}. * @param f * File being opened. */ public static synchronized void open(Object _this, File f) { put(_this, new FileRecord(f)); } /** * Called when a socket is opened. */ public static synchronized void openSocket(Object _this) { // intercept when if (_this instanceof SocketImpl) { try { // one of the following must be true SocketImpl si = (SocketImpl) _this; Socket s = (Socket)SOCKETIMPL_SOCKET.get(si); if (s!=null) put(_this, new SocketRecord(s)); ServerSocket ss = (ServerSocket)SOCKETIMPL_SERVER_SOCKET.get(si); if (ss!=null) put(_this, new ServerSocketRecord(ss)); } catch (IllegalAccessException e) { throw new AssertionError(e); } } if (_this instanceof SocketChannel) { put(_this, new SocketChannelRecord((SocketChannel) _this)); } } public static synchronized List<Record> getCurrentOpenFiles() { return new ArrayList<Record>(TABLE.values()); } private static synchronized void put(Object _this, Record r) { TABLE.put(_this, r); if(TABLE.size()>THRESHOLD) { THRESHOLD=999999; dump(ERROR); } if(TRACE!=null && !tracing) { tracing = true; r.dump("Opened ",TRACE); tracing = false; } } /** * Called when a file is closed. * * This method tolerates a double-close where a close method is called on an already closed object. * * @param _this * {@link FileInputStream}, {@link FileOutputStream}, {@link RandomAccessFile}, {@link Socket}, {@link ServerSocket}, or {@link ZipFile}. */ public static synchronized void close(Object _this) { Record r = TABLE.remove(_this); if(r!=null && TRACE!=null && !tracing) { tracing = true; r.dump("Closed ",TRACE); tracing = false; } } /** * Dumps all files that are currently open. */ public static synchronized void dump(OutputStream out) { dump(new OutputStreamWriter(out)); } public static synchronized void dump(Writer w) { PrintWriter pw = new PrintWriter(w); Record[] records = TABLE.values().toArray(new Record[0]); pw.println(records.length+" descriptors are open"); int i=0; for (Record r : records) { r.dump("#"+(++i)+" ",pw); } pw.println(" pw.flush(); } /** * Called when the system has too many open files. */ public static synchronized void outOfDescriptors() { if(ERROR!=null && !tracing) { tracing = true; ERROR.println("Too many open files"); dump(ERROR); tracing = false; } } private static Field SOCKETIMPL_SOCKET,SOCKETIMPL_SERVER_SOCKET; static { try { SOCKETIMPL_SOCKET = SocketImpl.class.getDeclaredField("socket"); SOCKETIMPL_SERVER_SOCKET = SocketImpl.class.getDeclaredField("serverSocket"); SOCKETIMPL_SOCKET.setAccessible(true); SOCKETIMPL_SERVER_SOCKET.setAccessible(true); } catch (NoSuchFieldException e) { throw new Error(e); } } }
package com.google.sps.data; import com.google.api.client.extensions.appengine.http.UrlFetchTransport; import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload; import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import java.io.IOException; import java.lang.SecurityException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.security.GeneralSecurityException; public class User { // API variables: // Client ID is generated from Ali's google APIs credentials page. private static final String CLIENT_ID = "1034390229233-u07o0iaas2oql8l4jhe7fevpfsbrtv7n.apps.googleusercontent.com"; // Payload class contains decrypted user information. private static final String PRIVATE_KIND = "Private"; private static final String PUBLIC_KIND = "Public"; private static final String COOKBOOK = "cookbook"; private static final String PLANNER = "planner"; private static final String DRAFTS = "drafts"; private Payload payload; /** User Entity Structure: Key = User(userID) { "name" : String, "cookbook" : ArrayList<Key)>, *May contain public or private recipe kind. "planner" : ArrayList<Key)>, *May contain public or private recipe kind. "drafts" : ArrayList<Key> *May contain private recipe kind. } * Recipe lists maintain the order they were added in. */ private Entity entity; private DatastoreService datastore; /** * Verifies user and creates a User instance for accessing and adding user data. * Throws SecurityException on failure, import from java.lang.SecurityException. * @Param idTokenString is the Google-user ID Token provided buy user-auth.js/getIdToken. * Token should be passed as URL Fetch argument from front end. */ public User(String idTokenString) throws SecurityException { GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier .Builder(UrlFetchTransport.getDefaultInstance(), new JacksonFactory()) .setAudience(Collections.singletonList(CLIENT_ID)) .build(); GoogleIdToken idToken; try { idToken = verifier.verify(idTokenString); } catch(IOException | GeneralSecurityException e) { throw new SecurityException("Failed to verify Google token", e); } payload = idToken.getPayload(); datastore = DatastoreServiceFactory.getDatastoreService(); Key userKey = KeyFactory.createKey("User", getId()); try { // Check if User already has a profile entity = datastore.get(userKey); } catch(EntityNotFoundException e) { // Create initial User instance, default name from idToken payload. entity = new Entity(userKey); entity.setProperty("name", (String) payload.get("name")); } } /** * Returns the String user unique ID. */ public String getId() { //return payload.getSubject(); return "user-test-ID-string"; } public String getName() { return (String) entity.getProperty("name"); } public void setName(String name) { entity.setProperty("name", name); uploadEntity(); } public List<Key> getCookbookList() { return getRecipeList(COOKBOOK); } public List<Key> getPlannerList() { return getRecipeList(PLANNER); } public List<Key> getDraftList() { return getRecipeList(DRAFTS); } public void addCookbookKey(Key key) { addKey(key, COOKBOOK); } public void addPlannerKey(Key key) { addKey(key, PLANNER); } public void addDraftKey(Key key) { addKey(key, DRAFTS); } public void removeCookbookKey(Key key) { removeKey(key, COOKBOOK); } public void removePlannerKey(Key key) { removeKey(key, PLANNER); } public void removeDraftKey(Key key) { removeKey(key, DRAFTS); } // PUBLIC METHODS END HERE /** * Adds the current version of User entity to datastore. */ private void uploadEntity() { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); datastore.put(entity); } /** * Helper method for retrieving ArrayList<Key> of given recipe list. */ @SuppressWarnings("unchecked") // Compiler cannot verify generic property type. private ArrayList<Key> getRecipeList(String listName) { ArrayList<Key> arrayListValue = (ArrayList<Key>) entity.getProperty(listName); if (arrayListValue == null) { return new ArrayList<Key>(); } return arrayListValue; } /** * Helper method for adding a key to a given recipe list. */ private void addKey(Key key, String listName) { ArrayList<Key> keys = getRecipeList(listName); if (!keys.contains(key)) { keys.add(key); entity.setProperty(listName, keys); uploadEntity(); } } /** * Helper methods for deleting a key from a given recipe list. */ private void removeKey(Key key, String listName) { ArrayList<Key> keys = getRecipeList(listName); if (keys.remove(key)) { uploadEntity(); } } }
package org.markdownwriterfx.editor; import java.util.ArrayList; import java.util.Collections; import javafx.scene.input.KeyEvent; import com.vladsch.flexmark.ast.Block; import com.vladsch.flexmark.ast.DelimitedNode; import com.vladsch.flexmark.ast.HardLineBreak; import com.vladsch.flexmark.ast.ListItem; import com.vladsch.flexmark.ast.Node; import com.vladsch.flexmark.ast.NodeVisitor; import com.vladsch.flexmark.ast.Paragraph; import com.vladsch.flexmark.ast.SoftLineBreak; import com.vladsch.flexmark.ast.Text; import com.vladsch.flexmark.util.Pair; /** * Smart Markdown text formatting methods. * * @author Karl Tauber */ class SmartFormat { private static final int WRAP_LENGTH = 80; private final MarkdownEditorPane editor; private final MarkdownTextArea textArea; SmartFormat(MarkdownEditorPane editor, MarkdownTextArea textArea) { this.editor = editor; this.textArea = textArea; } void format(KeyEvent e) { Node markdownAST = editor.getMarkdownAST(); if (markdownAST == null) return; int wrapLength = WRAP_LENGTH; // find and format paragraphs ArrayList<Pair<Paragraph, String>> formattedParagraphs = new ArrayList<>(); NodeVisitor visitor = new NodeVisitor(Collections.emptyList()) { @Override public void visit(Node node) { if (node instanceof Paragraph) { Paragraph paragraph = (Paragraph) node; int indent = computeIndent(paragraph); String newText = formatParagraph(paragraph, wrapLength, indent); if (!paragraph.getChars().equals(newText, false)) formattedParagraphs.add(new Pair<>(paragraph, newText)); } else visitChildren(node); } }; visitor.visit(markdownAST); // replace text of formatted paragraphs CompoundChange.run(textArea, changer -> { for (int i = formattedParagraphs.size() - 1; i >= 0; i Pair<Paragraph, String> pair = formattedParagraphs.get(i); Paragraph paragraph = pair.getFirst(); String newText = pair.getSecond(); int startOffset = paragraph.getStartOffset(); int endOffset = paragraph.getEndOffset(); if (paragraph.getChars().endsWith("\n")) endOffset changer.replaceText(startOffset, endOffset, newText); } } ); SmartEdit.selectRange(textArea, 0, 0); } private int computeIndent(Paragraph paragraph) { Block parent = paragraph.getParent(); if (parent instanceof ListItem) { int paraStartOffset = paragraph.getStartOffset(); int paraLineStartOffset = paragraph.getDocument().getChars().startOfLine(paraStartOffset); return paraStartOffset - paraLineStartOffset; } else return 0; } private String formatParagraph(Paragraph paragraph, int wrapLength, int indent) { // collect the paragraph text StringBuilder buf = new StringBuilder(paragraph.getTextLength()); collectFormattableText(buf, paragraph); // format the paragraph text return formatText(buf.toString(), wrapLength, indent); } /** * Collects the text of a single paragraph. * * Replaces: * - tabs with spaces * - newlines with spaces (may occur in Code nodes) * - soft line breaks with spaces * - hard line breaks with special marker characters * - spaces and tabs in special nodes, that should not formatted, with marker characters */ private void collectFormattableText(StringBuilder buf, Node node) { for (Node n = node.getFirstChild(); n != null; n = n.getNext()) { if (n instanceof Text) buf.append(n.getChars().toString().replace('\t', ' ').replace('\n', ' ')); else if (n instanceof DelimitedNode) { // italic, bold and code buf.append(((DelimitedNode) n).getOpeningMarker()); collectFormattableText(buf, n); buf.append(((DelimitedNode) n).getClosingMarker()); } else if (n instanceof SoftLineBreak) buf.append(' '); else if (n instanceof HardLineBreak) buf.append(n.getChars().startsWith("\\") ? " \4 " : " \3 "); else { // other text that should be not wrapped or formatted buf.append(protectWhitespace(n.getChars().toString())); } } } /** * Formats the given text by merging multiple spaces into one space * and wrapping lines. */ private String formatText(String text, int wrapLength, int indent) { String[] words = text.split(" +"); StringBuilder buf = new StringBuilder(text.length()); int lineLength = indent; for (String word : words) { if (word.equals("\3") || word.equals("\4")) { // hard line break ("two spaces" or "backslash") buf.append(word.equals("\3") ? " \n" : "\\\n"); lineLength = 0; continue; } if (lineLength > indent && lineLength + 1 + word.length() > wrapLength) { // wrap buf.append('\n'); lineLength = 0; } else if (lineLength > indent) { // add space before word buf.append(' '); lineLength++; } // indent if (indent > 0 && lineLength == 0) { for (int i = 0; i < indent; i++) buf.append(' '); lineLength += indent; } // add word buf.append(word); lineLength += word.length(); } return unprotectWhitespace(buf.toString()); } private String protectWhitespace(String s) { return s.replace(' ', '\1').replace('\t', '\2'); } private String unprotectWhitespace(String s) { return s.replace('\1', ' ').replace('\2', '\t'); } }
package com.hkamran.mocking; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.hkamran.mocking.Filter.State; import com.hkamran.mocking.servers.HTTPServer; import com.hkamran.mocking.servers.WebSocket; /** * Hello world! * */ public class Main { private static final int DEFAULT_PROXY_PORT = 9090; private static final int DEFAULT_WEB_PORT = 8090; private final static Logger log = LogManager.getLogger(Main.class); public static void main(String[] args) { try { Options options = createCMDOptions(); HelpFormatter f = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine cmd; f.setWidth(250); cmd = parser.parse(options, args, true); Integer webPort = getWebPort(cmd); Integer initialProxy = getProxyPort(cmd); /** * Setup Filter .. * */ log.info("Starting up Recorder...."); Proxies proxies = new Proxies(); Integer id = proxies.add("Default Service", initialProxy); Proxy proxy = proxies.get(id); Filter filter = proxy.getFilter(); filter.setState(State.PROXY); filter.setRedirectInfo("www.thomas-bayer.com", 80); filter.setRedirectState(true); /** * Start Program */ WebSocket.setProxyManager(proxies); HTTPServer.setProxyManager(proxies); HTTPServer frontEnd = new HTTPServer(); log.info("Startup finished! "); frontEnd.start(webPort); } catch (Exception e) { System.err.println("Unable to start application..."); e.printStackTrace(); } } private static Integer getProxyPort(CommandLine cmd) { Integer webPort = DEFAULT_PROXY_PORT; if (cmd.hasOption("proxyPort")) { webPort = Integer.parseInt(cmd.getOptionValue("proxyPort")); } return webPort; } private static Integer getWebPort(CommandLine cmd) { Integer webPort = DEFAULT_WEB_PORT; if (cmd.hasOption("webPort")) { webPort = Integer.parseInt(cmd.getOptionValue("webPort")); } return webPort; } private static Options createCMDOptions() { Option webPort = new Option("webPort", true, "Port for the web gui"); webPort.setArgName("webPort"); webPort.setRequired(false); Option proxyPort = new Option("proxyPort", true, "Port for the initial proxy"); proxyPort.setArgName("proxyPort"); proxyPort.setRequired(false); Options options = new Options(); options.addOption(webPort); options.addOption(proxyPort); return options; } }
package org.mcupdater.autopackager; import cofh.api.energy.TileEnergyHandler; import cofh.util.InventoryHelper; import com.dynious.refinedrelocation.api.APIUtils; import com.dynious.refinedrelocation.api.tileentity.ISortingMember; import com.dynious.refinedrelocation.api.tileentity.handlers.ISortingMemberHandler; import cpw.mods.fml.common.Optional; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.ForgeDirection; import org.mcupdater.shared.Position; @Optional.Interface(iface = "ISortingMember", modid = "RefinedRelocation") public class TilePackager extends TileEnergyHandler implements ISortingMember { private Object sortingHandler; private ForgeDirection orientation; /** * tickCounter increments every frame, every tickDelay frames it attempts to work. * We default to TICK_NORMAL but will wait for TICK_SLEEP instead if we ever fail * to pack something. * * @TODO Move TICK_NORMAL/TICK_SLEEP and ENERGY_COST into config file. */ private int tickCounter = 0; private static final int TICK_NORMAL = 10; // 500ms private static final int TICK_SLEEP = 200; // 10s private int tickDelay = TICK_NORMAL; private static final int ENERGY_COST = 1000; @Override public void updateEntity() { super.updateEntity(); if (++tickCounter % tickDelay == 0) { if (storage.getEnergyStored() > ENERGY_COST) { if (tryCraft()) { storage.extractEnergy(ENERGY_COST, false); tickDelay = TICK_NORMAL; } else { tickDelay = TICK_SLEEP; } } } } private boolean tryCraft() { if (orientation == null) { return false; } Position inputPos = new Position(xCoord, yCoord, zCoord, orientation); Position outputPos = new Position(xCoord, yCoord, zCoord, orientation); inputPos.moveLeft(1.0); outputPos.moveRight(1.0); TileEntity tileInput = worldObj.getBlockTileEntity((int)inputPos.x, (int)inputPos.y, (int)inputPos.z); TileEntity tileOutput = worldObj.getBlockTileEntity((int)outputPos.x, (int)outputPos.y, (int)outputPos.z); if (tileInput instanceof IInventory && tileOutput instanceof IInventory) { IInventory invInput = (IInventory) tileInput; IInventory invOutput = (IInventory) tileOutput; for (int slot = 0; slot < invInput.getSizeInventory(); slot++) { if (invInput.getStackInSlot(slot) != null && invInput.getStackInSlot(slot).stackSize >= 4) { ItemStack testStack = invInput.getStackInSlot(slot).copy(); testStack.stackSize = 1; InventoryCrafting smallCraft = new InventoryCrafting(new Container(){ @Override public boolean canInteractWith(EntityPlayer entityPlayer) { return false; } }, 2, 2); for (int craftSlot = 0; craftSlot < 4; craftSlot++) { smallCraft.setInventorySlotContents(craftSlot, testStack); } ItemStack result = CraftingManager.getInstance().findMatchingRecipe(smallCraft, worldObj); if (result != null) { testStack = InventoryHelper.simulateInsertItemStackIntoInventory(invOutput, result, 1); if (testStack == null) { invInput.getStackInSlot(slot).splitStack(4); if (invInput.getStackInSlot(slot).stackSize == 0) { invInput.setInventorySlotContents(slot, null); } InventoryHelper.insertItemStackIntoInventory(invOutput, result, 1); return true; } } } if (invInput.getStackInSlot(slot) != null && invInput.getStackInSlot(slot).stackSize >= 9) { ItemStack testStack = invInput.getStackInSlot(slot).copy(); testStack.stackSize = 1; InventoryCrafting largeCraft = new InventoryCrafting(new Container(){ @Override public boolean canInteractWith(EntityPlayer entityPlayer) { return false; } }, 3, 3); for (int craftSlot = 0; craftSlot < 9; craftSlot++) { largeCraft.setInventorySlotContents(craftSlot, testStack); } ItemStack result = CraftingManager.getInstance().findMatchingRecipe(largeCraft, worldObj); if (result != null) { testStack = InventoryHelper.simulateInsertItemStackIntoInventory(invOutput, result, 1); if (testStack == null) { invInput.getStackInSlot(slot).splitStack(9); if (invInput.getStackInSlot(slot).stackSize == 0) { invInput.setInventorySlotContents(slot, null); } InventoryHelper.insertItemStackIntoInventory(invOutput, result, 1); return true; } } } } } return false; } @Override public void writeToNBT(NBTTagCompound tagCompound) { super.writeToNBT(tagCompound); tagCompound.setInteger("orientation",orientation.ordinal()); } @Override public void readFromNBT(NBTTagCompound tagCompound) { super.readFromNBT(tagCompound); this.orientation = ForgeDirection.getOrientation(tagCompound.getInteger("orientation")); } public void setOrientation(ForgeDirection orientation) { this.orientation = orientation; } @Optional.Method(modid = "RefinedRelocation") @Override public ISortingMemberHandler getSortingHandler() { if (sortingHandler == null) { sortingHandler = APIUtils.createSortingMemberHandler(this); } return (ISortingMemberHandler) sortingHandler; } }
package org.monkeyscript.lite; import java.util.Arrays; import org.mozilla.javascript.*; // org.mozilla.javascript.NativeString was used as a reference for implementation of this final class NativeBuffer extends IdScriptableObject { static final long serialVersionUID = L; private static final Object BUFFER_TAG = "Buffer"; static void init(Scriptable scope, boolean sealed) { NativeBuffer obj = NativeBuffer.newEmpty(); obj.exportAsJSClass(MAX_PROTOTYPE_ID, scope, sealed); } static private NativeBuffer newEmpty() { return new NativeBuffer(0); } private NativeBuffer(int len) { length = len; type = UNTYPED; } private NativeBuffer(byte b) { bytes = new byte[1]; bytes[0] = b; length = bytes.length; type = BINARY; } private NativeBuffer(byte[] b) { bytes = b; length = b.length; type = BINARY; } private NativeBuffer(char c) { chars = new char[1]; chars[0] = b; length = chars.length; type = TEXT; } private NativeBuffer(char[] c) { chars = c; length = c.length; type = TEXT; } static private Object quickNewNativeBuffer(Context cx, Scriptable scope, Object target) { return ScriptRuntime.newObject(cx, scope, "Buffer", new Object[] { target }); } @Override public String getClassName() { return "Buffer"; } private static final int Id_length = 1, Id_text = 2, MAX_INSTANCE_ID = 2; @Override protected int getMaxInstanceId() { return MAX_INSTANCE_ID; } @Override protected int findInstanceIdInfo(String s) { if (s.equals("length")) { return instanceIdInfo(DONTENUM, Id_length); return instanceIdInfo(DONTENUM, Id_text); } return super.findInstanceIdInfo(s); } @Override protected String getInstanceIdName(int id) { if (id == Id_length) { return "length"; } if (id == Id_text) { return "text"; } return super.getInstanceIdName(id); } @Override protected Object getInstanceIdValue(int id) { if (id == Id_length) { return ScriptRuntime.wrapInt(bytes.length); } if (id == Id_text) { if ( type == UNTYPED ) return Undefined.instance; return ScriptRuntime.wrapBoolean( type == TEXT ); } return super.getInstanceIdValue(id); } @Override protected void setInstanceIdValue(int id, Object value) { if (id == Id_length) { setLength(value); return; } if (id == Id_text) { TypeMode newType; if ( value == Undefined.instance ) newType = UNTYPED; else if ( value == Boolean.FALSE ) newType = BINARY; else if ( value == Boolean.TRUE ) newType = TEXT; else throw ScriptRuntime.typeError("Trying to set the .text attribute of a buffer to an invalid value"); if ( newType == type ) return; if ( length > 0 && type != UNTYPED ) // A Buffer with size that is already typed cannot have it's type changed throw ScriptRuntime.constructError("Error", "Cannot change type of buffer when already initialized with a type and content"); if ( type == BINARY ) bytes = null; if ( type == TEXT ) chars = null; if ( newType == BINARY ) bytes = new byte[length]; if ( newType == TEXT ) chars = new char[length]; type = newType; return; } super.setInstanceIdValue(id, value); } @Override protected void fillConstructorProperties(IdFunctionObject ctor) { addIdFunctionProperty(ctor, BUFFER_TAG, ConstructorId_slice, "slice", 3); super.fillConstructorProperties(ctor); } @Override protected void initPrototypeId(int id) { String s; int arity; switch (id) { case Id_constructor: arity=1; s="constructor"; break; case Id_toString: arity=0; s="toString"; break; case Id_toSource: arity=0; s="toSource"; break; case Id_slice: arity=2; s="slice"; break; case Id_equals: arity=1; s="equals"; break; default: throw new IllegalArgumentException(String.valueOf(id)); } initPrototypeMethod(BUFFER_TAG, id, s, arity); } public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!f.hasTag(BUFFER_TAG)) { return super.execIdCall(f, cx, scope, thisObj, args); } int id = f.methodId(); again: for(;;) { switch (id) { case Id_constructor: { boolean inNewExpr = (thisObj == null); if (!inNewExpr) { // IdFunctionObject.construct will set up parent, proto return f.construct(cx, scope, args); } return jsConstructor(cx, scope, args); } case Id_toString: return thisObj.toString(); case Id_valueOf: return realThis(thisObj, f); case Id_toSource: { byte[] b = realThis(thisObj, f).bytes; StringBuffer sb = new StringBuffer("(new Buffer())"); for (int i = 0; i < b.length; i++) { if (i > 0) sb.insert(sb.length()-3, ", "); sb.insert(sb.length()-3, Integer.toString(byteToInt(b[i]))); } return sb.toString(); } case Id_slice: return quickNewNativeBlob(cx, scope, js_slice(realThis(thisObj, f).bytes, args)); case Id_equals: { // ToDo boolean eq = false; byte[] b1 = realThis(thisObj, f).bytes; byte[] b2; if(args[0] instanceof NativeBlob) { b2 = ((NativeBlob)args[0]).bytes; if (b1.length != b2.length) break; // short circut if different byte lengths for (int i = 0; i < b2.length; i++) if ( b1[i] != b2[i] ) break; eq = true; } return ScriptRuntime.wrapBoolean(eq); } } throw new IllegalArgumentException(String.valueOf(id)); } } private static NativeBuffer realThis(Object thisObj, IdFunctionObject f) { if (!(thisObj instanceof NativeBuffer)) throw incompatibleCallError(f); return (NativeBuffer)thisObj; } private void setLength(Object val) { double d = ScriptRuntime.toNumber(val); long longVal = ScriptRuntime.toUint32(d); if (longVal != d) throw Context.reportRuntimeError0("msg.arraylength.bad"); if ( longVal == length ) return; if ( type != UNTYPED ) { long staticLength = getStaticLength(); if ( longVal > length ) { // We're growing the array if ( longVal > staticLength ) if ( length < staticLength ) clearStatic( if ( longVal > staticLength ) // We're extending past the length of the static array // Expand it by copying and extending the length expandStatic(length, longVal); else // We're only extending the length within the currently allocated array // We need to empty out the area we are extending into clearStatic(longVal, staticLength); } else { // We're shrinking the array if () { } } } length = longVal; // Finally set the new length } private long getStaticLength() { if ( type == UNTYPED ) return null; if ( type == BINARY ) return bytes.length; if ( type == TEXT ) return chars.length; } private void clearStatic(long from, long to) { if ( type == BINARY ) Arrays.fill(bytes, (int)from, (int)to, Byte.MIN_VALUE); else if ( type == TEXT ) Arrays.fill(chars, (int)from, (int)to, '\0'); } private void expandStatic(long oldLength, long newLen) { if ( type == BINARY ) { byte[] newArray = new byte[newLen]; System.arraycopy(bytes, 0, newArray, 0, oldLength); } else if ( type == TEXT ) char[] newArray = new char[newLen]; System.arraycopy(chars, 0, newArray, 0, oldLength); } } private enum TypeMode { UNTYPED, BINARY, TEXT } private long length; private TypeMode type = UNTYPED; private byte[] bytes; private char[] chars; }
package com.wheany; import com.vaadin.server.StreamResource; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.*; import java.io.*; import static java.lang.Math.*; public class ImageResource implements StreamResource.StreamSource { int reloads = 0; BufferedImage original; BufferedImage adjusted; private int RAdjust = 0; private int GAdjust = 0; private int BAdjust = 0; public ImageResource(File input) throws IOException { BufferedImage in = ImageIO.read(input); original = new BufferedImage(in.getWidth(), in.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = original.createGraphics(); g.drawImage(in, 0, 0, null); g.dispose(); adjusted = new BufferedImage(original.getWidth(), original.getHeight(), BufferedImage.TYPE_INT_RGB); updateAdjusted(); } private int clamp_0_255(int value) { return max(0, min(255, value)); } private void updateAdjusted() { int[] originalRGB = original.getRGB(0, 0, original.getWidth(), original.getHeight(), null, 0, original.getWidth()); int[] adjustedRGB = new int[originalRGB.length]; for (int i = 0; i < originalRGB.length; i++) { int r = (originalRGB[i] & 0x00FF0000) >>> 16; int g = (originalRGB[i] & 0x0000FF00) >>> 8; int b = (originalRGB[i] & 0x000000FF); int adjustedR = clamp_0_255(r + RAdjust); int adjustedG = clamp_0_255(g + GAdjust); int adjustedB = clamp_0_255(b + BAdjust); adjustedRGB[i] = (adjustedR << 16) | (adjustedG << 8) | adjustedB; } adjusted.setRGB(0,0,original.getWidth(),original.getHeight(),adjustedRGB,0,original.getWidth()); } public double getValue() { return value; } public void setValue(double value) { this.value = value; } private double value = 0; /* We need to implement this method that returns * the resource as a stream. */ public InputStream getStream () { /* Create an image and draw something on it. */ BufferedImage image = new BufferedImage (adjusted.getWidth(), adjusted.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics drawable = image.getGraphics(); drawable.drawImage(adjusted, 0, 0, null); drawable.setColor(Color.lightGray); drawable.fillRect(0,0,200,200); drawable.setColor(Color.yellow); drawable.fillOval(25,25,150,150); drawable.setColor(Color.blue); drawable.drawRect(0,0,199,199); drawable.setColor(Color.black); drawable.drawString("Reloads="+reloads, 75, 100); drawable.drawString("Value="+value, 75, 125); reloads++; try { /* Write the image to a buffer. */ ByteArrayOutputStream imagebuffer = new ByteArrayOutputStream(); ImageIO.write(image, "png", imagebuffer); /* Return a stream from the buffer. */ return new ByteArrayInputStream( imagebuffer.toByteArray()); } catch (IOException e) { return null; } } }
package org.royaldev.royalcommands; import org.bukkit.Bukkit; import org.bukkit.Difficulty; import org.bukkit.GameMode; import org.bukkit.World; import org.bukkit.WorldCreator; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerChangedWorldEvent; import org.bukkit.event.weather.ThunderChangeEvent; import org.bukkit.event.weather.WeatherChangeEvent; import org.bukkit.event.world.WorldLoadEvent; import org.bukkit.event.world.WorldUnloadEvent; import org.royaldev.royalcommands.configuration.ConfManager; import org.royaldev.royalcommands.listeners.InventoryListener; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; // TODO: Use WE for regions for portals? public class WorldManager { private class WorldWatcher implements Listener { @EventHandler public void worldUnload(WorldUnloadEvent e) { if (e.isCancelled()) return; synchronized (loadedWorlds) { if (loadedWorlds.contains(e.getWorld().getName())) loadedWorlds.remove(e.getWorld().getName()); } } @EventHandler public void worldLoad(WorldLoadEvent e) { synchronized (loadedWorlds) { if (!loadedWorlds.contains(e.getWorld().getName())) loadedWorlds.add(e.getWorld().getName()); addNewToConfig(); } } @EventHandler public void onWorldTele(PlayerChangedWorldEvent e) { World to = e.getPlayer().getWorld(); if (!configuredWorlds.contains(to.getName())) return; if (!loadedWorlds.contains(to.getName())) return; GameMode gm; String mode = config.getString("worlds." + to.getName() + ".gamemode", "SURVIVAL").trim(); if (mode == null) mode = "SURVIVAL"; // how? try { gm = GameMode.valueOf(mode); } catch (IllegalArgumentException ex) { gm = GameMode.SURVIVAL; } e.getPlayer().setGameMode(gm); } @EventHandler public void onWeather(WeatherChangeEvent e) { if (e.isCancelled()) return; World w = e.getWorld(); if (!configuredWorlds.contains(w.getName())) return; if (!loadedWorlds.contains(w.getName())) return; boolean allowWeather = config.getBoolean("worlds." + w.getName() + ".weather", true); if (!allowWeather) e.setCancelled(true); } @EventHandler public void onThunder(ThunderChangeEvent e) { if (e.isCancelled()) return; World w = e.getWorld(); if (!configuredWorlds.contains(w.getName())) return; if (!loadedWorlds.contains(w.getName())) return; boolean allowWeather = config.getBoolean("worlds." + w.getName() + ".weather", true); if (!allowWeather) e.setCancelled(true); } } private final List<String> loadedWorlds = new ArrayList<String>(); private final List<String> configuredWorlds = new ArrayList<String>(); public static InventoryListener il; private final ConfManager config = ConfManager.getConfManager("worlds.yml"); private final Logger log = RoyalCommands.instance.getLogger(); public WorldManager() { il = new InventoryListener(RoyalCommands.instance); if (!Config.useWorldManager) return; if (!config.exists()) config.createFile(); if (config.getConfigurationSection("worlds") != null) { synchronized (configuredWorlds) { for (String key : config.getConfigurationSection("worlds").getKeys(false)) { configuredWorlds.add(key); } } } for (World w : Bukkit.getWorlds()) { if (loadedWorlds.contains(w.getName())) continue; loadedWorlds.add(w.getName()); } addNewToConfig(); setupWorlds(); for (String s : loadedWorlds) { if (!configuredWorlds.contains(s)) continue; World w = Bukkit.getWorld(s); if (w == null) continue; boolean isStorming = config.getBoolean("worlds." + w.getName() + ".is_storming_if_weather_false", false); w.setStorm(isStorming); } Bukkit.getPluginManager().registerEvents(il, RoyalCommands.instance); Bukkit.getPluginManager().registerEvents(new WorldWatcher(), RoyalCommands.instance); } public ConfManager getConfig() { return config; } public void reloadConfig() { config.reload(); setupWorlds(); } public void setupWorlds() { for (String ws : configuredWorlds) { String path = "worlds." + ws + "."; World w = null; if (config.getBoolean(path + "loadatstartup") && Bukkit.getWorld(ws) == null) { try { w = loadWorld(ws); } catch (IllegalArgumentException e) { log.warning("Could not load world " + ws + " as specified in worlds.yml: " + e.getMessage()); continue; } catch (NullPointerException e) { log.warning("Could not load world " + ws + " as specified in worlds.yml: " + e.getMessage()); continue; } } if (!loadedWorlds.contains(ws)) continue; if (w == null) w = Bukkit.getWorld(ws); if (w == null) { log.warning("Could not manage world " + ws + ": No such world"); continue; } w.setSpawnFlags(config.getBoolean(path + "spawnmonsters", true), config.getBoolean(path + "spawnanimals", true)); w.setKeepSpawnInMemory(config.getBoolean("keepspawnloaded", true)); w.setPVP(config.getBoolean(path + "pvp", true)); w.setMonsterSpawnLimit(config.getInt(path + "monsterspawnlimit", 70)); w.setAnimalSpawnLimit(config.getInt(path + "animalspawnlimit", 15)); w.setWaterAnimalSpawnLimit(config.getInt(path + "wateranimalspawnlimit", 5)); w.setTicksPerAnimalSpawns(config.getInt(path + "animalspawnticks", 400)); w.setTicksPerMonsterSpawns(config.getInt(path + "monsterspawnticks", 1)); Difficulty d; try { d = Difficulty.valueOf(config.getString(path + "difficulty", "normal").toUpperCase()); } catch (Exception e) { d = Difficulty.NORMAL; } w.setDifficulty(d); } } public void addToLoadedWorlds(String name) { synchronized (loadedWorlds) { if (!loadedWorlds.contains(name)) loadedWorlds.add(name); } } public void addToLoadedWorlds(World w) { synchronized (loadedWorlds) { if (!loadedWorlds.contains(w.getName())) loadedWorlds.add(w.getName()); } } public void removeFromLoadedWorlds(String name) { synchronized (loadedWorlds) { if (loadedWorlds.contains(name)) loadedWorlds.remove(name); } } public void removeFromLoadedWorlds(World w) { synchronized (loadedWorlds) { if (loadedWorlds.contains(w.getName())) loadedWorlds.remove(w.getName()); } } public World loadWorld(String name) throws IllegalArgumentException, NullPointerException { if (Bukkit.getServer().getWorldContainer() == null) throw new NullPointerException("Could not read world files!"); File world = new File(Bukkit.getServer().getWorldContainer(), name); if (!world.exists()) throw new IllegalArgumentException("No such world!"); if (!world.isDirectory()) throw new IllegalArgumentException("World is not a directory!"); WorldCreator wc = new WorldCreator(name); String generator = config.getString("worlds." + name + ".generator", "DefaultGen"); if (generator.equals("DefaultGen")) generator = null; World w; try { wc.generator(generator); w = wc.createWorld(); } catch (Exception e) { // catch silly generators using old code (may not actually catch) throw new IllegalArgumentException("Generator (" + generator + ") is using old code: " + e.getMessage()); } synchronized (loadedWorlds) { loadedWorlds.add(w.getName()); } return w; } /** * Attempts to unload a world * * @param w World to unload * @return If world was unloaded */ public boolean unloadWorld(World w) { boolean worked = Bukkit.unloadWorld(w, true); synchronized (loadedWorlds) { if (loadedWorlds.contains(w.getName()) && worked) loadedWorlds.remove(w.getName()); } return worked; } /** * Attempts to unload a world * * @param name Name of world to unload * @return If world was unloaded */ public boolean unloadWorld(String name) { boolean worked = Bukkit.unloadWorld(name, true); synchronized (loadedWorlds) { if (loadedWorlds.contains(name) && worked) loadedWorlds.remove(name); } return worked; } public void addNewToConfig() { for (String ws : loadedWorlds) { if (configuredWorlds.contains(ws)) continue; World w = Bukkit.getWorld(ws); if (w == null) continue; String path = "worlds." + ws + "."; config.set(path + "displayname", ws); config.set(path + "spawnmonsters", w.getAllowMonsters()); config.set(path + "spawnanimals", w.getAllowAnimals()); config.set(path + "keepspawnloaded", w.getKeepSpawnInMemory()); config.set(path + "generatestructures", w.canGenerateStructures()); config.set(path + "pvp", w.getPVP()); config.set(path + "weather", true); config.set(path + "maxheight", w.getMaxHeight()); config.set(path + "monsterspawnlimit", w.getMonsterSpawnLimit()); config.set(path + "animalspawnlimit", w.getAnimalSpawnLimit()); config.set(path + "wateranimalspawnlimit", w.getWaterAnimalSpawnLimit()); config.set(path + "animalspawnticks", w.getTicksPerAnimalSpawns()); config.set(path + "monsterspawnticks", w.getTicksPerMonsterSpawns()); config.set(path + "difficulty", w.getDifficulty().name()); config.set(path + "worldtype", w.getWorldType().name()); config.set(path + "environment", w.getEnvironment().name()); config.set(path + "gamemode", Bukkit.getServer().getDefaultGameMode().name()); if (w.getGenerator() == null) config.set(path + "generator", "DefaultGen"); config.set(path + "seed", w.getSeed()); config.set(path + "freezetime", false); config.set(path + "loadatstartup", true); } } /** * Gets a world based on its alias (case-insensitive). * * @param name Alias of world * @return World or null if no matching alias */ public World getWorld(String name) { World w; for (String s : loadedWorlds) { String path = "worlds." + s + "."; if (config.getString(path + "displayname", "").equalsIgnoreCase(name)) { w = Bukkit.getWorld(s); return w; } } return null; } /** * Gets a world based on its alias (case-sensitive). * * @param name Alias of world * @return World or null if no matching alias */ public World getCaseSensitiveWorld(String name) { World w; for (String s : loadedWorlds) { String path = "worlds." + s + "."; if (config.getString(path + "displayname", "").equals(name)) { w = Bukkit.getWorld(s); return w; } } return null; } }
package org.flymine.util; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.Collections; import java.util.Map; import java.util.Random; import java.util.WeakHashMap; /** * This is a Map implementation designed specifically for people intending to create a cache. * The behaviour is exactly as that of a WeakHashMap. The difference is the circumstances under * which entries are garbage collected from the map. In a WeakHashMap, entries are garbage collected * almost as soon as the garbage collector notices that the only reference to the key is through the * WeakHashMap. Since on Linux the garbage collector performs a minor collection several times a * second, entries do not live long enough to serve any use as part of a cache. * * <p>This CacheMap implementation makes use of SoftReferences to hold references to the most * recently created or used entries in the Map, preventing them from being garbage collected until * the garbage collector really needs some memory to be freed. * * <p>The holding system is system-wide, so CacheMap objects that have not been used for a while * will empty out even if the system is not running out of memory. * * <p>Like most collection classes, this class is not synchronized. A * synchronized <tt>WeakHashMap</tt> may be constructed using the * <tt>Collections.synchronizedMap</tt> method. * * <p>The holding system attempts to follow the following characteristics: * <ul><li>When the garbage collector needs to free memory, it will free the oldest items before * the newest items. * <li>There is some randomness in the cache replacement policies, which can improve * performance in a lot of situations. * <li>The number of objects retained for a particular CacheMap is proportional to the rate of * insertions, when several CacheMaps compete. * <li>Accessing entries in the cache causes them to be retained for longer. * <li>The previous mechanism can cope equally with single objects being accessed very * frequently, and many objects being accessed. * </ul> * * <p>The holding mechanism is split into two portions - holding for created entries and holding for * accessed entries. The holding system for created entries is efficient as long as entries are not * created many times. If a given key is put into the map many times, the holder will become * useless. * <p>The holding system for accessed entries can cope with a certain number of concurrent * repetatively accessed entries (currently about 15), after which it degenerates. An individual * repeating access will be noticed with a probability exponentially based on the distance between * repetitions, with about equal odds at a spacing of ten. * * @see java.util.WeakHashMap * @see java.lang.ref.SoftReference * @author Matthew Wakeling */ public class CacheMap extends WeakHashMap { /* Desired characteristics: * 1. When the garbage collector needs to free memory, it should free the oldest or least used * entries before the newest or most used. * 2. There should be some randomness in the holder replacement policy, so that there isn't a * sudden performance drop when the working set becomes larger than the cache. * 3. One large cache with lots of activity shouldn't be able to crowd out a small cache with * not much activity - ie. the number of entries that a particular cache can retain should * be proportional to the rate at which entries are created or accessed. * 4. Accessing entries should hold them in memory nearly as effectively as creating them. * * I think, officially 1 and 2 are incompatible. Oh well. * 2 and 3 can both be served by having one large array as holder, and randomly replacing * entries. * With 4, the problem is the difference between creating entries, which should only happen * once, and accessing the entries, which may happen multiple times. If the holder is an * array, then inserting a single entry multiple times has the effect of reducing the useful * size of the array. * * I therefore suggest the following holder implementation: * The main holder is effectively a circular array of "x * y" entries, but split up into "x" * separate arrays, each of size "y". Each array is referenced by a SoftReference that * the garbage collector is welcome to clear. If one of the separate arrays is accessed and * found to be cleared by the garbage collector, then the system merely recreates an empty * array of size "y" before accessing it. Entries are put into a position in the overall * circular array according to a base offset added to a random number between 0 and "z - 1", * where "z" is near "y". After each operation, the base offset is incremented. A good * source of random numbers is java.util.Random - its algorithms appear to be geared towards * fast production of numbers. This provides a reasonable tradeoff between 1 and 2. * * A separate holding system is provided for the system to hold entries that are accessed * frequently. It consists of a small array (size ~20) in which new entries are placed, and * checked to find duplicates. Entries which fall out of the bottom of this array are added * to another array of size size "w", which is a single array referenced by a * SoftReference. Entries are placed in it completely randomly (though probably also with * an incrementing offset to avoid holes in the PRNG). Duplicate entries may appear in this * last array. * The small array works like this: First, an entry is searched for linearly through the * array from position 0 to the end. If it exists in the first half, then it is swapped with * the entry one towards position 0. If it exists in the second half, then it is moved to * a random position in the first half, and all the entries in between are shifted towards * the end of the array. New entries are inserted randomly between mid-way through the * array and the end. All entries from that position to the end are shifted one towards the * end. The one that falls off the end is put into the big array. * In this way, the most common entries will end up in the first half of the array, and will * not be placed in the large array. Also, new entries have an exponentially distributed * number of chances to be recognised as a multiple access and moved to the first half of * the small array. * * NOTE: We shouldn't call .equals() or .hashCode() on any of the key objects put in the * cache, because that may take a long time. */ protected static final int HOLDER_ARRAY_COUNT = 256; protected static final int HOLDER_ARRAY_SIZE = 1024; protected static final int HOLDER_RANDOMNESS = 2000; protected static final int ACCESS_HOLDER_SMALL = 20; protected static final int ACCESS_HOLDER_SMALL_MIDDLE = 10; protected static final int ACCESS_HOLDER_LARGE = 2048; protected static SoftReference holder[] = new SoftReference[HOLDER_ARRAY_COUNT]; protected static SoftReference small[] = new SoftReference[ACCESS_HOLDER_SMALL]; protected static SoftReference large; protected static int holderOffset = 0; protected static int accessOffset = 0; protected static final int HOLDER_SIZE = HOLDER_ARRAY_COUNT * HOLDER_ARRAY_SIZE; protected static Random createdRand = new Random(); protected static Random accessedRand = new Random(); protected Map canonicalisation = Collections.synchronizedMap(new WeakHashMap()); public CacheMap(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } public CacheMap(int initialCapacity) { super(initialCapacity); } /** * Constructs a new, empty <tt>CacheMap</tt> with the default initial * capacity (16) and the default load factor (0.75). */ public CacheMap() { super(); } /** * Constructs a new <tt>CacheMap</tt> with the same mappings as the * specified <tt>Map</tt>. The <tt>CacheMap</tt> is created with * default load factor, which is <tt>0.75</tt> and an initial capacity * sufficient to hold the mappings in the specified <tt>Map</tt>. * * @param t the map whose mappings are to be placed in this map. * @throws NullPointerException if the specified map is null. */ public CacheMap(Map t) { super(t); } /** * @see java.util.WeakHashMap#get */ public Object get(Object key) { Object canonical = null; canonical = canonicalisation.get(key); if (canonical != null) { canonical = ((WeakReference) canonical).get(); } if (canonical == null) { canonical = key; } accessed(canonical); return super.get(key); } /** * @see java.util.WeakHashMap#containsKey */ public boolean containsKey(Object key) { Object canonical = null; canonical = canonicalisation.get(key); if (canonical != null) { canonical = ((WeakReference) canonical).get(); } if (canonical == null) { canonical = key; } accessed(canonical); return super.containsKey(key); } /** * @see java.util.WeakHashMap#put */ public Object put(Object key, Object value) { canonicalisation.put(key, new WeakReference(key)); created(key); return super.put(key, value); } /** * This method places the given Object into a holder system, that attempts to keep the most * recently created objects in memory, at the discretion of the garbage collector. * * @param obj the Object to hold */ protected static void created(Object obj) { synchronized (createdRand) { int positionToUse = (createdRand.nextInt(HOLDER_RANDOMNESS) + holderOffset) % HOLDER_SIZE; holderOffset++; if (holderOffset >= HOLDER_SIZE) { holderOffset = 0; } int arrayNo = positionToUse / HOLDER_ARRAY_SIZE; int arrayPosition = positionToUse % HOLDER_ARRAY_SIZE; Object array[] = null; if (holder[arrayNo] != null) { array = (Object []) holder[arrayNo].get(); } if (array == null) { array = new Object[HOLDER_ARRAY_SIZE]; holder[arrayNo] = new SoftReference(array); } array[arrayPosition] = obj; } } /** * This method paces the given Object into a holder system, that attempts to keep the most * recently accessed objects in memory, at the discretion of the garbage collector. * The difference between this method and created() is that this holder is usually smaller, and * it has some limited protection against objects being added multiple times. * * @param obj the Object to hold */ protected static void accessed(Object obj) { synchronized (accessedRand) { // First, see if our object is present in the small array, or if there's a cleared // position to fill. int lastClearPosition = -1; int objectEqualPosition = -1; for (int i = 0; (i < ACCESS_HOLDER_SMALL) && (objectEqualPosition == -1); i++) { if ((small[i] == null) || (small[i].get() == null)) { lastClearPosition = i; } else if ((small[i] != null) && (small[i].get() == obj)) { objectEqualPosition = i; } } if (objectEqualPosition != -1) { // Here, we need to move the entry around intelligently. if ((objectEqualPosition < ACCESS_HOLDER_SMALL_MIDDLE) && (objectEqualPosition > 0)) { // It is already in the first half, so it needs to be moved one point towards // position 0, by swapping it with the one next to it. SoftReference temp = small[objectEqualPosition]; small[objectEqualPosition] = small[objectEqualPosition - 1]; small[objectEqualPosition - 1] = temp; } else if (objectEqualPosition >= ACCESS_HOLDER_SMALL_MIDDLE) { // It is in the second half, so it needs to be moved to a random position in // the first half, and ones in-between shifted. int newPosition = accessedRand.nextInt(ACCESS_HOLDER_SMALL_MIDDLE); SoftReference temp = small[objectEqualPosition]; for (int i = objectEqualPosition; i > newPosition; i small[i] = small[i - 1]; } small[newPosition] = temp; } } else if (lastClearPosition != -1) { // There's an empty slot, so fill it, from the bottom up. small[lastClearPosition] = new SoftReference(obj); } else { // It's not already there - in this case we need to insert the new entry somewhere // in the second half, shift all the ones below it down, and transfer the one // that falls off the end into the large array. // Firstly, add the one on the bottom to the large array. We are guaranteed that it // is not null. Object largeArray[] = null; if (large != null) { largeArray = (Object []) large.get(); } if (largeArray == null) { largeArray = new Object[ACCESS_HOLDER_LARGE]; large = new SoftReference(largeArray); } largeArray[(accessedRand.nextInt(ACCESS_HOLDER_LARGE) + accessOffset) % ACCESS_HOLDER_LARGE] = small[ACCESS_HOLDER_SMALL - 1].get(); // Second, shift all the entries up to the insertion point towards the end. int newPosition = ACCESS_HOLDER_SMALL_MIDDLE + accessedRand.nextInt(ACCESS_HOLDER_SMALL - ACCESS_HOLDER_SMALL_MIDDLE); for (int i = ACCESS_HOLDER_SMALL - 1; i > newPosition; i small[i] = small[i - 1]; } small[newPosition] = new SoftReference(obj); } } } }
package com.zenplanner.sql; import com.google.common.base.Joiner; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.*; public class Table extends TreeMap<String, Column> { private final String name; private List<Column> pk; private static final int maxKeys = 2000; // jtds driver limit public Table(String name) { this.name = name; } public String getName() { return name; } public int hashCode() { return name.hashCode(); } public boolean equals(Object obj) { if (!(obj instanceof Table)) { return false; } return name.equalsIgnoreCase(((Table) obj).getName()); } /** * @return A list of the columns that constitute the primary key */ public List<Column> getPk() { if(pk != null) { return pk; } synchronized (this) { List<Column> pk = new ArrayList<>(); for(Column col : values()) { if(col.isPrimaryKey()) { pk.add(col); } } this.pk = pk; return pk; } } public boolean hasColumn(String name) { return containsKey(name); } /** * @return the insert SQL for this table */ public String writeInsertQuery() { List<String> colNames = new ArrayList<>(); List<String> valueNames = new ArrayList<>(); for(Column col : values()) { String colName = col.getColumnName(); colNames.add("\n\t[" + colName + "]"); valueNames.add("?"); } String nameClause = Joiner.on(", ").join(colNames); String valueClause = Joiner.on(", ").join(valueNames); String sql = String.format("insert into [%s] (%s\n) values (%s)", getName(), nameClause, valueClause); return sql; } public String writeUpdateQuery() { List<String> updateCols = new ArrayList<>(); List<Column> pk = getPk(); for(Column col : values()) { if(pk.contains(col)) { continue; // TODO: Cache non-update columns for speed } String colName = col.getColumnName(); updateCols.add(String.format("\t[%s]=?", colName)); } List<String> whereCols = new ArrayList<>(); for(Column col : pk) { String colName = col.getColumnName(); whereCols.add(String.format("[%s]=?", colName)); } String updateClause = Joiner.on(",\n").join(updateCols); String whereClause = Joiner.on("\n\tand ").join(whereCols); String sql = String.format("update [%s] set\n%s\nwhere %s", getName(), updateClause, whereClause); return sql; } /** * @return A magical query that returns the primary key and a hash of the row */ public String writeHashedQuery(Map<String,List<Object>> filters) { List<String> colNames = new ArrayList<>(); List<String> pk = new ArrayList<>(); for(Column col : values()) { colNames.add(col.getSelect()); } for (Column col : getPk()) { pk.add(String.format("[%s]", col.getColumnName())); } String hashNames = Joiner.on("+\n\t\t").join(colNames); String orderClause = Joiner.on(",").join(pk); String selectClause = orderClause + ",\n\tHASHBYTES('md5',\n\t\t" + hashNames + "\n\t) as [Hash]"; String sql = String.format("select\n\t%s\nfrom [%s]\n", selectClause, getName()); // Filter sql = buildWhereClause(filters, sql); sql += String.format("\norder by %s", orderClause); return sql; } private String buildWhereClause(Map<String, List<Object>> filters, String sql) { if(hasAllColumns(filters.keySet())) { StringBuilder sb = new StringBuilder(); for(String key : filters.keySet()) { if(sb.length() > 0) { sb.append("\n\t and "); } List<Object> vals = filters.get(key); List<String> terms = new ArrayList<>(); for(Object val : vals) { terms.add("?"); } sb.append("[" + key + "] in (" + Joiner.on(",").join(terms) + ")"); } sql += "where " + sb.toString(); } return sql; } public String writeCountQuery(Map<String,List<Object>> filters) { String sql = String.format("select\n\tcount(*)\nfrom [%s]\n", getName()); sql = buildWhereClause(filters, sql); return sql; } public boolean hasAllColumns(Set<String> colNames) { Set<String> filterCols = new HashSet<>(); filterCols.addAll(keySet()); filterCols.retainAll(colNames); return filterCols.size() == colNames.size(); } /** * Pulls an array of objects that represents the PK from a row * * @param rs A ResultSet to check * @return A List representing the PK * @throws Exception */ public Key getPk(ResultSet rs) throws Exception { Key key = new Key(); if (rs.isClosed() || rs.isBeforeFirst() || rs.isAfterLast() || rs.getRow() == 0) { return null; } for (Column col : values()) { if (col.isPrimaryKey()) { Comparable<?> val = col.getValue(rs); key.add(val); } } return key; } public void setIdentityInsert(Connection con, boolean enabled) { try (Statement stmt = con.createStatement()) { String state = enabled ? "ON" : "OFF"; stmt.executeUpdate(String.format("SET IDENTITY_INSERT [%s] %s;", getName(), state)); } catch (Exception ex) { // TODO: Nicer solution for tables that don't have an identity } } public PreparedStatement createSelectQuery(Connection con, Set<Key> keys, int count) { StringBuilder sb = new StringBuilder(); for(Column col : values()) { if(sb.length() > 0) { sb.append(", "); } sb.append("[" + col.getColumnName() + "]"); } String sql = "select " + sb.toString(); return createQuery(sql, con, keys, count); } public PreparedStatement createDeleteQuery(Connection con, Set<Key> keys, int count) { return createQuery("delete", con, keys, count); } // TODO: Break this monster out into separate methods for SQL and values private PreparedStatement createQuery(String prefix, Connection con, Set<Key> keys, int count) { List<Object> parms = new ArrayList<>(); List<Column> pk = getPk(); StringBuilder sb = new StringBuilder(); int rowIndex = 0; for (Key key : new HashSet<>(keys)) { keys.remove(key); // Remove as we go if (sb.length() > 0) { sb.append("\tor "); } sb.append("("); for (int pkIdx = 0; pkIdx < pk.size(); pkIdx++) { if (pkIdx > 0) { sb.append(" and "); } Column col = pk.get(pkIdx); sb.append("["); sb.append(col.getColumnName()); sb.append("]=?"); // Grab the value of the parameter Object val = key.get(pkIdx); parms.add(val); } sb.append(")\n"); if (++rowIndex >= count) { break; } } String sql = String.format("%s\nfrom [%s]\nwhere %s", prefix, getName(), sb.toString()); try { PreparedStatement stmt = con.prepareStatement(sql); for (int i = 0; i < parms.size(); i++) { Object javaVal = parms.get(i); Object sqlVal = javaToSql(javaVal); stmt.setObject(i + 1, sqlVal); } return stmt; } catch (Exception ex) { throw new RuntimeException("Error creating select query!", ex); } } public static Object javaToSql(Object val) { if(val == null) { return null; } if(val instanceof UUID) { return UuidUtil.uuidToByteArray(((UUID)val)); } if(val instanceof String) { return val; } if(val instanceof Long) { return val; } throw new RuntimeException("Unknown type: " + val.getClass().getName()); } public void deleteRows(Connection dcon, Set<Key> keys) throws Exception { List<Column> pk = getPk(); int rowLimit = (int) Math.floor(maxKeys / pk.size()); for (int rowIndex = 0; rowIndex < keys.size(); ) { int count = Math.min(keys.size() - rowIndex, rowLimit); System.out.println("Deleting " + count + " rows from " + getName()); try (PreparedStatement selectStmt = createDeleteQuery(dcon, keys, count)) { selectStmt.execute(); } rowIndex += count; } } /** * Queries the source database for row information on each row who's PK is in the keys array, and inserts those * rows into the destination connection. * * @param scon The source connection * @param dcon The destination connection * @param keys The keys of the rows for which to query * @throws Exception */ public void insertRows(Connection scon, Connection dcon, Set<Key> keys) throws Exception { if (keys.size() <= 0) { return; } int colCount = size(); String sql = writeInsertQuery(); setIdentityInsert(dcon, true); List<Column> pk = getPk(); int rowLimit = (int) Math.floor(maxKeys / pk.size()); System.out.println("Batch insert " + keys.size() + " rows into " + getName()); while (keys.size() > 0) { int count = Math.min(keys.size(), rowLimit); System.out.println("Inserting " + count + " rows into " + getName()); try (PreparedStatement selectStmt = createSelectQuery(scon, keys, count)) { try (ResultSet rs = selectStmt.executeQuery()) { try (PreparedStatement insertStmt = dcon.prepareStatement(sql)) { while (rs.next()) { insertStmt.clearParameters(); for(int i = 1; i <= colCount; i++) { insertStmt.setObject(i, rs.getObject(i)); } insertStmt.addBatch(); } try { insertStmt.executeBatch(); } catch (Exception ex) { throw new RuntimeException("Error inserting rows: " + sql, ex); } //System.out.println("Inserted " + rowCount + " rows"); } } } catch (Exception ex) { throw new RuntimeException("Error inserting rows: " + sql, ex); } } } public void updateRows(Connection scon, Connection dcon, Set<Key> keys) throws Exception { if (keys.size() <= 0) { return; } List<Column> pk = getPk(); int rowLimit = (int) Math.floor(maxKeys / pk.size()); for (int rowIndex = 0; rowIndex < keys.size(); ) { int count = Math.min(keys.size() - rowIndex, rowLimit); System.out.println("Updating " + count + " rows in " + getName()); try (PreparedStatement selectStmt = createSelectQuery(scon, keys, count)) { try (ResultSet rs = selectStmt.executeQuery()) { String sql = writeUpdateQuery(); try (PreparedStatement updateStmt = dcon.prepareStatement(sql)) { while (rs.next()) { updateRow(updateStmt, rs); } try { updateStmt.executeBatch(); } catch (Exception ex) { throw new RuntimeException("Error updating rows!", ex); } } } } rowIndex += count; } } private void updateRow(PreparedStatement stmt, ResultSet rs) throws Exception { stmt.clearParameters(); int i = 0; List<Column> pk = getPk(); for (Column col : values()) { if(pk.contains(col)) { continue; // TODO: Cache non-update columns for speed } String colName = col.getColumnName(); Object val = rs.getObject(colName); stmt.setObject(++i, val); } for(Column col : pk) { String colName = col.getColumnName(); Object val = rs.getObject(colName); stmt.setObject(++i, val); } stmt.addBatch(); } /** * Gets the primary key from whichever row exists * * @param srs The source RecordSet * @param drs The destination RecordSet * @return The primary key of the row * @throws Exception */ public Key getPk(ResultSet srs, ResultSet drs) throws Exception { DbComparator.ChangeType change = detectChange(srs, drs); if (change == DbComparator.ChangeType.DELETE) { return getPk(drs); } return getPk(srs); } /** * Basically this is the join logic. It compares the two rows presently under the cursors, and returns an action * that needs to be taken based on whether the row is in left but not right, right but not left, or in both but * changes are present. As usual for join code, this method assumes that the ResultSets are ordered, and the * Key.compare() method exhibits the same ordering as the database engine. * * @param srs The source RecordSet * @param drs The destination RecordSet * @return A ChangeType indicating what action should be taken to sync the two databases * @throws Exception */ public DbComparator.ChangeType detectChange(ResultSet srs, ResultSet drs) throws Exception { // Verify we're on the same row Key srcPk = getPk(srs); Key dstPk = getPk(drs); int eq = Key.compare(srcPk, dstPk); /* Left Right ACD BDE A B Left < right, insert A into right C B Left > right, delete B from right D D Left = right, update D in right null E Left > right, delete E from right */ if (eq < 0) { // Left < right, insert return DbComparator.ChangeType.INSERT; } if (eq > 0) { // Left > right, delete return DbComparator.ChangeType.DELETE; } // Keys match, check hashes byte[] shash = getHash(srs); byte[] dhash = getHash(drs); if (shash == null && dhash == null) { throw new RuntimeException("Both rows are null!"); } if (shash == null) { return DbComparator.ChangeType.DELETE; } if (dhash == null) { return DbComparator.ChangeType.INSERT; } if (Arrays.equals(shash, dhash)) { return DbComparator.ChangeType.NONE; } return DbComparator.ChangeType.UPDATE; } /** * Get the Hash from a ResultSet, or returns null if the ResultSet is exhausted * * @param rs The ResultSet * @return The Hash, or null */ private static byte[] getHash(ResultSet rs) throws Exception { if (rs == null || rs.isBeforeFirst() || rs.isAfterLast() || rs.getRow() == 0) { return null; } return rs.getBytes("Hash"); } }
package org.smoothbuild.db.object.obj; import static com.google.common.base.Preconditions.checkElementIndex; import static org.smoothbuild.db.object.obj.Helpers.wrapHashedDbExceptionAsObjectDbException; import static org.smoothbuild.db.object.obj.exc.DecodeObjRootException.cannotReadRootException; import static org.smoothbuild.db.object.obj.exc.DecodeObjRootException.wrongSizeOfRootSequenceException; import static org.smoothbuild.util.collect.Lists.allMatchOtherwise; import java.math.BigInteger; import java.util.List; import java.util.Objects; import java.util.Optional; import org.smoothbuild.db.hashed.Hash; import org.smoothbuild.db.hashed.HashedDb; import org.smoothbuild.db.hashed.exc.HashedDbException; import org.smoothbuild.db.hashed.exc.NoSuchDataException; import org.smoothbuild.db.object.db.ObjectHDbException; import org.smoothbuild.db.object.obj.base.MerkleRoot; import org.smoothbuild.db.object.obj.base.ObjectH; import org.smoothbuild.db.object.obj.base.ValueH; import org.smoothbuild.db.object.obj.exc.DecodeObjTypeException; import org.smoothbuild.db.object.obj.exc.NoSuchObjException; import org.smoothbuild.db.object.obj.expr.CallH; import org.smoothbuild.db.object.obj.expr.ConstructH; import org.smoothbuild.db.object.obj.expr.OrderH; import org.smoothbuild.db.object.obj.expr.RefH; import org.smoothbuild.db.object.obj.expr.SelectH; import org.smoothbuild.db.object.obj.val.ArrayH; import org.smoothbuild.db.object.obj.val.ArrayHBuilder; import org.smoothbuild.db.object.obj.val.BlobH; import org.smoothbuild.db.object.obj.val.BlobHBuilder; import org.smoothbuild.db.object.obj.val.BoolH; import org.smoothbuild.db.object.obj.val.DefinedFunctionH; import org.smoothbuild.db.object.obj.val.FunctionH; import org.smoothbuild.db.object.obj.val.IfFunctionH; import org.smoothbuild.db.object.obj.val.IntH; import org.smoothbuild.db.object.obj.val.MapFunctionH; import org.smoothbuild.db.object.obj.val.NativeFunctionH; import org.smoothbuild.db.object.obj.val.StringH; import org.smoothbuild.db.object.obj.val.TupleH; import org.smoothbuild.db.object.type.TypeHDb; import org.smoothbuild.db.object.type.TypingH; import org.smoothbuild.db.object.type.base.SpecH; import org.smoothbuild.db.object.type.base.TypeH; import org.smoothbuild.db.object.type.expr.SelectTypeH; import org.smoothbuild.db.object.type.val.ArrayTypeH; import org.smoothbuild.db.object.type.val.DefinedFunctionTypeH; import org.smoothbuild.db.object.type.val.FunctionTypeH; import org.smoothbuild.db.object.type.val.NativeFunctionTypeH; import org.smoothbuild.db.object.type.val.TupleTypeH; import org.smoothbuild.lang.base.type.Typing; import org.smoothbuild.util.collect.Lists; import com.google.common.collect.ImmutableList; /** * This class is thread-safe. */ public class ObjectHDb { private final HashedDb hashedDb; private final TypeHDb typeHDb; private final TypingH typing; private final IfFunctionH ifFunction; private final MapFunctionH mapFunction; public ObjectHDb(HashedDb hashedDb, TypeHDb typeHDb, TypingH typing) { this.hashedDb = hashedDb; this.typeHDb = typeHDb; this.typing = typing; try { this.ifFunction = newIfFunction(); this.mapFunction = newMapFunction(); } catch (HashedDbException e) { throw new ObjectHDbException(e); } } // methods for creating ValueH subclasses public ArrayHBuilder arrayBuilder(TypeH elemType) { return new ArrayHBuilder(typeHDb.array(elemType), this); } public BlobHBuilder blobBuilder() { return wrapHashedDbExceptionAsObjectDbException(() -> new BlobHBuilder(this, hashedDb.sink())); } public BoolH bool(boolean value) { return wrapHashedDbExceptionAsObjectDbException(() -> newBool(value)); } public DefinedFunctionH definedFunction(DefinedFunctionTypeH type, ObjectH body) { if (!typing.isAssignable(type.result(), body.type())) { throw new IllegalArgumentException("`type` specifies result as " + type.result().name() + " but body.evaluationType() is " + body.type().name() + "."); } return wrapHashedDbExceptionAsObjectDbException(() -> newFunction(type, body)); } public IntH int_(BigInteger value) { return wrapHashedDbExceptionAsObjectDbException(() -> newInt(value)); } public NativeFunctionH nativeFunction( NativeFunctionTypeH type, BlobH jarFile, StringH classBinaryName, BoolH isPure) { return wrapHashedDbExceptionAsObjectDbException( () -> newNativeFunction(type, jarFile, classBinaryName, isPure)); } public StringH string(String value) { return wrapHashedDbExceptionAsObjectDbException(() -> newString(value)); } public TupleH tuple(TupleTypeH tupleType, ImmutableList<ValueH> items) { var types = tupleType.items(); allMatchOtherwise(types, items, (s, i) -> Objects.equals(s, i.spec()), (i, j) -> { throw new IllegalArgumentException( "tupleType specifies " + i + " items but provided " + j + "."); }, (i) -> { throw new IllegalArgumentException("tupleType specifies item at index " + i + " with type " + types.get(i).name() + " but provided item has type " + items.get(i).spec().name() + " at that index."); } ); return wrapHashedDbExceptionAsObjectDbException(() -> newTuple(tupleType, items)); } // methods for creating ExprH subclasses public CallH call(ObjectH function, ConstructH arguments) { return wrapHashedDbExceptionAsObjectDbException(() -> newCall(function, arguments)); } public ConstructH construct(ImmutableList<ObjectH> items) { return wrapHashedDbExceptionAsObjectDbException(() -> newConstruct(items)); } public IfFunctionH ifFunction() { return ifFunction; } public MapFunctionH mapFunction() { return mapFunction; } public OrderH order(ImmutableList<ObjectH> elems) { return wrapHashedDbExceptionAsObjectDbException(() -> newOrder(elems)); } public RefH ref(BigInteger value, TypeH evaluationType) { return wrapHashedDbExceptionAsObjectDbException(() -> newRef(evaluationType, value)); } public SelectH select(ObjectH tuple, IntH index) { return wrapHashedDbExceptionAsObjectDbException(() -> newSelect(tuple, index)); } // generic getter public ObjectH get(Hash rootHash) { List<Hash> hashes = decodeRootSequence(rootHash); if (hashes.size() != 2) { throw wrongSizeOfRootSequenceException(rootHash, hashes.size()); } SpecH type = getTypeOrChainException(rootHash, hashes.get(0)); Hash dataHash = hashes.get(1); return type.newObj(new MerkleRoot(rootHash, type, dataHash), this); } private SpecH getTypeOrChainException(Hash rootHash, Hash typeHash) { try { return typeHDb.get(typeHash); } catch (ObjectHDbException e) { throw new DecodeObjTypeException(rootHash, e); } } private List<Hash> decodeRootSequence(Hash rootHash) { try { return hashedDb.readSequence(rootHash); } catch (NoSuchDataException e) { throw new NoSuchObjException(rootHash, e); } catch (HashedDbException e) { throw cannotReadRootException(rootHash, e); } } // methods for creating Val Obj-s public ArrayH newArray(ArrayTypeH type, List<ValueH> elems) throws HashedDbException { var data = writeArrayData(elems); var root = newRoot(type, data); return type.newObj(root, this); } public BlobH newBlob(Hash dataHash) throws HashedDbException { var root = newRoot(typeHDb.blob(), dataHash); return typeHDb.blob().newObj(root, this); } private BoolH newBool(boolean value) throws HashedDbException { var data = writeBoolData(value); var root = newRoot(typeHDb.bool(), data); return typeHDb.bool().newObj(root, this); } private DefinedFunctionH newFunction(DefinedFunctionTypeH type, ObjectH body) throws HashedDbException { var data = writeFunctionData(body); var root = newRoot(type, data); return type.newObj(root, this); } private IntH newInt(BigInteger value) throws HashedDbException { var data = writeIntData(value); var root = newRoot(typeHDb.int_(), data); return typeHDb.int_().newObj(root, this); } private NativeFunctionH newNativeFunction(NativeFunctionTypeH type, BlobH jarFile, StringH classBinaryName, BoolH isPure) throws HashedDbException { var data = writeNativeFunctionData(jarFile, classBinaryName, isPure); var root = newRoot(type, data); return type.newObj(root, this); } private StringH newString(String string) throws HashedDbException { var data = writeStringData(string); var root = newRoot(typeHDb.string(), data); return typeHDb.string().newObj(root, this); } private TupleH newTuple(TupleTypeH type, ImmutableList<ValueH> objects) throws HashedDbException { var data = writeTupleData(objects); var root = newRoot(type, data); return type.newObj(root, this); } // methods for creating Expr-s private CallH newCall(ObjectH function, ConstructH arguments) throws HashedDbException { var resultType = inferCallResultType(function, arguments); var type = typeHDb.call(resultType); var data = writeCallData(function, arguments); var root = newRoot(type, data); return type.newObj(root, this); } private TypeH inferCallResultType(ObjectH function, ConstructH arguments) { var funcType = functionEvaluationType(function); var argTypes = arguments.type().items(); var paramTypes = funcType.params(); allMatchOtherwise( paramTypes, argTypes, typing::isParamAssignable, (expectedSize, actualSize) -> illegalArguments(funcType, arguments), i -> illegalArguments(funcType, arguments) ); var varBounds = typing.inferVariableBoundsInCall(paramTypes, argTypes); return typing.mapVariables(funcType.result(), varBounds, typeHDb.lower()); } private void illegalArguments(FunctionTypeH functionType, ConstructH arguments) { throw new IllegalArgumentException( "Arguments evaluation type %s should be equal to function evaluation type parameters %s." .formatted(arguments.type().name(), functionType.paramsTuple().name())); } private FunctionTypeH functionEvaluationType(ObjectH function) { if (function.type() instanceof FunctionTypeH functionType) { return functionType; } else { throw new IllegalArgumentException("`function` component doesn't evaluate to Function."); } } private IfFunctionH newIfFunction() throws HashedDbException { var type = typeHDb.ifFunction(); return (IfFunctionH) newInternalFunction(type); } private FunctionH newInternalFunction(FunctionTypeH type) throws HashedDbException { // Internal functions don't have any data. We use empty sequence as its data so // code reading such function from hashedDb can be simpler and code that stores // h-objects as artifacts doesn't need handle this special case. Hash dataHash = hashedDb.writeSequence(); var root = newRoot(type, dataHash); return type.newObj(root, this); } private OrderH newOrder(ImmutableList<ObjectH> elems) throws HashedDbException { TypeH elemType = elemType(elems); var type = typeHDb.order(elemType); var data = writeOrderData(elems); var root = newRoot(type, data); return type.newObj(root, this); } private TypeH elemType(ImmutableList<ObjectH> elems) { Optional<TypeH> elemType = elems.stream() .map(ObjectH::type) .reduce((type1, type2) -> { if (type1.equals(type2)) { return type1; } else { throw new IllegalArgumentException("Element evaluation types are not equal " + type1.name() + " != " + type2.name() + "."); } }); SpecH type = elemType.orElse(typeHDb.nothing()); if (type instanceof TypeH typeH) { return typeH; } else { throw new IllegalArgumentException( "Element type should be ValOType but was " + type.getClass().getCanonicalName()); } } private ConstructH newConstruct(ImmutableList<ObjectH> items) throws HashedDbException { var itemTypes = Lists.map(items, ObjectH::type); var evaluationType = typeHDb.tuple(itemTypes); var type = typeHDb.construct(evaluationType); var data = writeConstructData(items); var root = newRoot(type, data); return type.newObj(root, this); } private MapFunctionH newMapFunction() throws HashedDbException { var type = typeHDb.mapFunction(); return (MapFunctionH) newInternalFunction(type); } private SelectH newSelect(ObjectH tuple, IntH index) throws HashedDbException { var type = selectType(tuple, index); var data = writeSelectData(tuple, index); var root = newRoot(type, data); return type.newObj(root, this); } private SelectTypeH selectType(ObjectH expr, IntH index) { if (expr.type() instanceof TupleTypeH tuple) { int intIndex = index.jValue().intValue(); ImmutableList<TypeH> items = tuple.items(); checkElementIndex(intIndex, items.size()); var itemType = items.get(intIndex); return typeHDb.select(itemType); } else { throw new IllegalArgumentException(); } } private RefH newRef(TypeH evaluationType, BigInteger index) throws HashedDbException { var data = writeRefData(index); var type = typeHDb.ref(evaluationType); var root = newRoot(type, data); return type.newObj(root, this); } private MerkleRoot newRoot(SpecH type, Hash dataHash) throws HashedDbException { Hash rootHash = hashedDb.writeSequence(type.hash(), dataHash); return new MerkleRoot(rootHash, type, dataHash); } // methods for writing data of Expr-s private Hash writeCallData(ObjectH function, ConstructH arguments) throws HashedDbException { return hashedDb.writeSequence(function.hash(), arguments.hash()); } private Hash writeConstructData(ImmutableList<ObjectH> items) throws HashedDbException { return writeSequence(items); } private Hash writeNativeFunctionData(BlobH jarFile, StringH classBinaryName, BoolH isPure) throws HashedDbException { return hashedDb.writeSequence(jarFile.hash(), classBinaryName.hash(), isPure.hash()); } private Hash writeOrderData(ImmutableList<ObjectH> elems) throws HashedDbException { return writeSequence(elems); } private Hash writeRefData(BigInteger value) throws HashedDbException { return hashedDb.writeBigInteger(value); } private Hash writeSelectData(ObjectH tuple, IntH index) throws HashedDbException { return hashedDb.writeSequence(tuple.hash(), index.hash()); } // methods for writing data of Val-s private Hash writeArrayData(List<ValueH> elems) throws HashedDbException { return writeSequence(elems); } private Hash writeBoolData(boolean value) throws HashedDbException { return hashedDb.writeBoolean(value); } private Hash writeIntData(BigInteger value) throws HashedDbException { return hashedDb.writeBigInteger(value); } private Hash writeFunctionData(ObjectH body) { return body.hash(); } private Hash writeStringData(String string) throws HashedDbException { return hashedDb.writeString(string); } private Hash writeTupleData(ImmutableList<ValueH> items) throws HashedDbException { return writeSequence(items); } // helpers private Hash writeSequence(List<? extends ObjectH> objs) throws HashedDbException { var hashes = Lists.map(objs, ObjectH::hash); return hashedDb.writeSequence(hashes); } public ImmutableList<Hash> readSequence(Hash hash) throws HashedDbException { return hashedDb().readSequence(hash); } // TODO visible for classes from db.object package tree until creating Obj is cached and // moved completely to ObjectDb class public HashedDb hashedDb() { return hashedDb; } public Typing<TypeH> typing() { return typing; } }
package org.smoothbuild.task.exec; import static org.smoothbuild.db.values.ValuesDb.memoryValuesDb; import java.util.ArrayList; import java.util.List; import org.smoothbuild.db.values.ValuesDb; import org.smoothbuild.io.fs.base.FileSystem; import org.smoothbuild.io.fs.mem.MemoryFileSystem; import org.smoothbuild.io.util.TempDir; import org.smoothbuild.io.util.TempManager; import org.smoothbuild.lang.message.Message; import org.smoothbuild.lang.plugin.Container; import org.smoothbuild.lang.value.ValueFactory; public class ContainerImpl implements Container { private final FileSystem projectFileSystem; private final ValuesDb valuesDb; private final TempManager tempManager; private final List<Message> messages; private final List<TempDir> tempDirs; public ContainerImpl(FileSystem projectFileSystem, ValuesDb valuesDb, TempManager tempManager) { this.projectFileSystem = projectFileSystem; this.valuesDb = valuesDb; this.tempManager = tempManager; this.messages = new ArrayList<>(); this.tempDirs = new ArrayList<>(); } public static ContainerImpl containerImpl() { return new ContainerImpl(new MemoryFileSystem(), memoryValuesDb(), new TempManager()); } @Override public ValueFactory create() { return valuesDb; } public FileSystem projectFileSystem() { return projectFileSystem; } @Override public void log(Message message) { messages.add(message); } public List<Message> messages() { return messages; } @Override public TempDir createTempDir() { TempDir tempDir = tempManager.tempDir(valuesDb); tempDirs.add(tempDir); return tempDir; } public void destroy() { tempDirs.stream().forEach(TempDir::destroy); } }
package cronapi.email; import java.util.LinkedList; import org.apache.commons.mail.DefaultAuthenticator; import org.apache.commons.mail.EmailAttachment; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; import cronapi.CronapiMetaData; import cronapi.Var; import cronapi.CronapiMetaData.CategoryType; import cronapi.CronapiMetaData.ObjectType; @CronapiMetaData(category = CategoryType.EMAIL, categoryTags = { "Email" }) public class Operations { @CronapiMetaData(type = "function", name = "{{sendEmailName}}", nameTags = { "sendEmail" }, description = "{{sendEmailDescription}}", params = { "{{sendEmailParam0}}", "{{sendEmailParam1}}", "{{sendEmailParam2}}", "{{sendEmailParam3}}", "{{sendEmailParam4}}", "{{sendEmailParam5}}", "{{sendEmailParam6}}", "{{sendEmailParam7}}", "{{sendEmailParam8}}", "{{sendEmailParam9}}", "{{sendEmailParam10}}", "{{sendEmailParam11}}", }, paramsType = { ObjectType.STRING, ObjectType.STRING, ObjectType.LIST, ObjectType.LIST, ObjectType.STRING, ObjectType.STRING, ObjectType.STRING, ObjectType.LIST, ObjectType.STRING, ObjectType.STRING, ObjectType.STRING, ObjectType.STRING }) public static final void sendEmail(Var from, Var to, Var Cc, Var Bcc, Var subject, Var msg, Var html, Var attachments, Var smtpHost, Var smtpPort, Var login, Var password) throws Exception { try { HtmlEmail email = new HtmlEmail(); email.setCharset(cronapi.CronapiConfigurator.ENCODING); email.setSSLOnConnect(true); email.setHostName(smtpHost.getObjectAsString()); email.setSslSmtpPort(smtpPort.getObjectAsString()); email.setAuthenticator(new DefaultAuthenticator(login.getObjectAsString(), password.getObjectAsString())); email.setFrom(from.getObjectAsString()); email.setDebug(false); email.setSubject(subject.getObjectAsString()); email.setMsg(msg.getObjectAsString()); if (Cc.getType() == Var.Type.LIST) { for (Var v : Cc.getObjectAsList()) { email.addCc(v.getObjectAsString()); } } else if (!Cc.equals(Var.VAR_NULL)) { email.addCc(Cc.getObjectAsString()); } if (Bcc.getType() == Var.Type.LIST) { for (Var v : Bcc.getObjectAsList()) { email.addBcc(v.getObjectAsString()); } } else if (!Bcc.equals(Var.VAR_NULL)) { email.addBcc(Bcc.getObjectAsString()); } if (!html.equals(Var.VAR_NULL)) { email.setHtmlMsg(html.getObjectAsString()); } if (!attachments.equals(Var.VAR_NULL)) { if (attachments.getType() == Var.Type.LIST) { for (Var v : attachments.getObjectAsList()) { EmailAttachment anexo = new EmailAttachment(); anexo.setPath(v.getObjectAsString()); anexo.setDisposition(EmailAttachment.ATTACHMENT); anexo.setName(v.getObjectAsString()); email.attach(anexo); } } else if (attachments.getType() == Var.Type.STRING) { EmailAttachment anexo = new EmailAttachment(); anexo.setPath(attachments.getObjectAsString()); anexo.setDisposition(EmailAttachment.ATTACHMENT); anexo.setName(attachments.getObjectAsString()); email.attach(anexo); } } if (to.getType() == Var.Type.LIST) { for (Var v : to.getObjectAsList()) { email.addTo(v.getObjectAsString()); } } else if (to.getType() == Var.Type.STRING) { email.addTo(to.getObjectAsString()); } email.send(); } catch (EmailException e) { throw new RuntimeException(e); } } }
package org.sourcepit.common.utils.xml; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public final class XmlUtils { private XmlUtils() { super(); } public static String getEncoding(InputStream inputStream) { return SAXEncodingDetector.parse(inputStream); } public static Document newDocument() { final DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); final DocumentBuilder docBuilder; try { docBuilder = dbfac.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } final Document document = docBuilder.newDocument(); document.setXmlStandalone(true); return document; } public static Document readXml(InputStream inputStream) { try { Document document = newDocumentBuilder().parse(inputStream); document.setXmlStandalone(true); return document; } catch (IOException e) { throw new IllegalArgumentException(e); } catch (SAXException e) { throw new IllegalArgumentException(e); } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } } public static Document readXml(File xmlFile) throws IllegalArgumentException { try { Document document = newDocumentBuilder().parse(xmlFile); document.setXmlStandalone(true); return document; } catch (IOException e) { throw new IllegalArgumentException(e); } catch (SAXException e) { throw new IllegalArgumentException(e); } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } } private static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setIgnoringComments(false); factory.setIgnoringElementContentWhitespace(true); return factory.newDocumentBuilder(); } public static void writeXml(Document doc, OutputStream outputStream) { try { // Prepare the DOM document for writing Source source = new DOMSource(doc); // Prepare the output file Result result = new StreamResult(outputStream); // Write the DOM document to the file Transformer xformer = TransformerFactory.newInstance().newTransformer(); try { xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3"); } catch (IllegalArgumentException e) { // ignore } try { xformer.setOutputProperty(OutputKeys.INDENT, "yes"); } catch (IllegalArgumentException e) { // ignore } xformer.transform(source, result); } catch (TransformerConfigurationException e) { throw new IllegalStateException(e); } catch (TransformerException e) { throw new IllegalStateException(e); } } // This method writes a DOM document to a file public static void writeXml(Document doc, File file) { try { // Prepare the DOM document for writing Source source = new DOMSource(doc); // Prepare the output file Result result = new StreamResult(file); // Write the DOM document to the file Transformer xformer = TransformerFactory.newInstance().newTransformer(); try { xformer.setOutputProperty(OutputKeys.INDENT, "yes"); } catch (IllegalArgumentException e) { // ignore } xformer.transform(source, result); } catch (TransformerConfigurationException e) { throw new IllegalStateException(e); } catch (TransformerException e) { throw new IllegalStateException(e); } } public static Iterable<Node> queryNodes(Document document, String xPath) { return toIterable(queryNodeList(document, xPath)); } public static Node queryNode(Document document, String xPath) { try { XPathExpression expr = XPathFactory.newInstance().newXPath().compile(xPath); return (Node) expr.evaluate(document, XPathConstants.NODE); } catch (XPathExpressionException e) { throw new IllegalArgumentException(e); } } public static NodeList queryNodeList(Document document, String xPath) { try { XPathExpression expr = XPathFactory.newInstance().newXPath().compile(xPath); return (NodeList) expr.evaluate(document, XPathConstants.NODESET); } catch (XPathExpressionException e) { throw new IllegalArgumentException(e); } } public static Iterable<Node> toIterable(NodeList nodeList) { return nodeList == null ? DomIterable.EMPTY_ITERABLE : new DomIterable(nodeList); } public static String queryText(Document document, String xPath) { try { XPathExpression expr = XPathFactory.newInstance().newXPath().compile(xPath); return (String) expr.evaluate(document, XPathConstants.STRING); } catch (XPathExpressionException e) { throw new IllegalArgumentException(e); } } public static class DomIterable implements Iterable<Node> { private static final DomIterable EMPTY_ITERABLE = new DomIterable(new NodeList() { public Node item(int index) { return null; } public int getLength() { return 0; } }); private final NodeList nodeList; public DomIterable(NodeList nodeList) { this.nodeList = nodeList; } public static Iterable<Node> newIterable(Element element, String tagName) { return new DomIterable(element.getElementsByTagName(tagName)); } public static Iterable<Node> newIterable(Document document, String tagName) { return new DomIterable(document.getElementsByTagName(tagName)); } public static Iterable<Node> newIterable(Node node, String tagName) { if (node instanceof Element) { return newIterable((Element) node, tagName); } else if (node instanceof Document) { return newIterable((Document) node, tagName); } return EMPTY_ITERABLE; } public Iterator<Node> iterator() { return new NodeIterator(nodeList); } } private static class NodeIterator implements Iterator<Node>, Iterable<Node> { private final NodeList nodeList; private int i = 0; public NodeIterator(NodeList nodeList) { this.nodeList = nodeList; } public boolean hasNext() { return nodeList.getLength() > i; } public Node next() { return nodeList.item(i++); } public void remove() { throw new UnsupportedOperationException(); } public Iterator<Node> iterator() { return this; } } }
package cz.muni.fi.mias; import java.io.FileInputStream; import java.util.Properties; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * Settings class responsible for loading settings from mias.properties Property file. * mias.properties file is located in the path specified by the cz.muni.fi.mias.mias.to file or in the working directory. * * @author Martin Liska * @since 14.12.2012 */ public class Settings { private static final Logger LOG = LogManager.getLogger(Settings.class); public static final String EMPTY_STRING = ""; private static Properties config; public static char dirSep = System.getProperty("file.separator").charAt(0); public static String eol = System.getProperty("line.separator"); public static final String MATHDOCHEADER = "<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE html PUBLIC \"- public static final String OPTION_CONF = "conf"; public static final String OPTION_ADD = "add"; public static final String OPTION_OVERWRITE = "overwrite"; public static final String OPTION_DELETE = "delete"; public static final String OPTION_OPTIMIZE = "optimize"; public static final String OPTION_DELETEINDEX = "deleteindex"; public static final String OPTION_STATS = "stats"; public static final String OPTION_INDOCPROCESS = "indocprocess"; public static Options getMIaSOptions() { Options options = new Options(); options.addOption(Option.builder(OPTION_CONF) .hasArg() .required() .desc("Path to indexing configuration file.") .build()); options.addOption(Option.builder(OPTION_ADD) .hasArgs() .numberOfArgs(2) .argName("input_path> <root_dir") .desc("where root_dir is an absolute path to a directory in the input_path to determine the relative path that the files will be indexed with") .build()); options.addOption(Option.builder(OPTION_OVERWRITE) .hasArgs() .numberOfArgs(2) .argName("input_path> <root_dir") .desc("Overwrites existing index") .build()); options.addOption(Option.builder(OPTION_DELETE) .hasArg() .argName("dir_or_file") .desc("Deletes file(s) from index.") .build()); options.addOption(Option.builder(OPTION_OPTIMIZE) .desc("Optimizes the index for maximum searching performance.") .build()); options.addOption(Option.builder(OPTION_DELETEINDEX) .desc("Deletes the index.") .build()); options.addOption(Option.builder(OPTION_STATS) .desc("Prints statistics about index.") .build()); options.addOption(Option.builder(OPTION_INDOCPROCESS) .hasArgs() .numberOfArgs(2) .argName("input_path> <root_dir") .desc("where root_dir is an absolute path to a directory in the input_path. Processes math formulae and inserts M-terms into documents created under root_dir.") .build()); return options; } public static void init(String propertiesFilePath) { config = new Properties(); try { config.load(new FileInputStream(propertiesFilePath)); } catch (Exception e) { LOG.fatal(e); System.exit(2); } } public static void init() { config = new Properties(); } /** * * @return Direcotry where the index is located or will be stored. */ public static String getIndexDir() { String indexDir = config.getProperty("INDEXDIR"); String result = "/index"; if (result != null) { result = indexDir; } return result; } /** * * @return Preference for updating of the already indexed files. If true, the already indexed files will be updated. If false * only new files will be added. */ public static boolean getUpdateFiles() { String duplicates = config.getProperty("UPDATE"); boolean result = false; if (duplicates != null) { result = Boolean.parseBoolean(duplicates); } return result; } /** * * @return Number of threads for processing. */ public static int getNumThreads() { String threads = config.getProperty("THREADS"); int result = -1; try { result = Integer.parseInt(threads); } catch (Exception e) { } if (result < 1) { result = Runtime.getRuntime().availableProcessors(); } return result; } /** * * @return Maximum number of results that the system retrieves. */ public static int getMaxResults() { String n = config.getProperty("MAXRESULTS"); int result = 1000; try { result = Integer.parseInt(n); } catch (Exception e) { } return result; } public static void setMaxResults(String maxResults) { config.setProperty("MAXRESULTS", maxResults); } /** * * @return A limit for the number of indexed files for one run. -1 means no limit. */ public static long getDocLimit() { String n = config.getProperty("DOCLIMIT"); long result = -1; try { result = Integer.parseInt(n); } catch (Exception e) { } return result; } public static boolean getIndexFormulaeDocuments() { String prop = config.getProperty("FORMULA_DOCUMENTS"); boolean result = false; if (prop != null) { result = Boolean.parseBoolean(prop); } return result; } }
package org.threadly.load; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import org.threadly.concurrent.future.ListenableFuture; import org.threadly.concurrent.future.SettableListenableFuture; import org.threadly.load.ExecutableScript.ExecutionItem; import org.threadly.load.ExecutableScript.ExecutionItem.ChildItems; import org.threadly.util.Clock; /** * <p>Provides the shared implementation among all execution step builders. This also defines the * minimum API set that all builders must implement.</p> * * @author jent - Mike Jensen */ public abstract class AbstractScriptBuilder { protected final ArrayList<ExecutionItem> stepRunners; private final AtomicBoolean finalized; private int neededThreadCount; private Exception replacementException = null; protected AbstractScriptBuilder(AbstractScriptBuilder sourceBuilder) { if (sourceBuilder == null) { stepRunners = new ArrayList<ExecutionItem>(); neededThreadCount = 1; } else { sourceBuilder.replaced(); this.stepRunners = sourceBuilder.stepRunners; this.neededThreadCount = sourceBuilder.neededThreadCount; } this.finalized = new AtomicBoolean(false); } /** * Adds a step in the current test position which will log out the percent of completion for the * entire test script. The provided future will complete once the test has reached this point * in the script. The resulting double provided by the future is the percent of completion at * this moment. You can easily log this by adding a * {@link org.threadly.concurrent.future.FutureCallback} to the returned future. * * If there are steps running in parallel at the time of execution for this progress future it * should be noted the number is a best guess, as no locking occurs during determining the * current progress. * * If the script is stopped (likely due to an error or step failure), this returned future will * complete in an error state (ie {@link ListenableFuture#get()} will throw a * {@code ExecutionException}. * * @return A future which provide a double representing the percent of how much of the script has completed */ public ListenableFuture<Double> addProgressFuture() { SettableListenableFuture<Double> slf = new SettableListenableFuture<Double>(false); addStep(new ProgressScriptStep(slf)); return slf; } /** * Sets a new limit for the script steps to be executed at. This will only take place for steps * which execute AFTER this point in the script. This is effectively adding a task at this * point in the script that will set an limit on how fast the steps can run. If you want your * entire script to adher to this limit it must be done before any steps are added. * * This allows you to control request rates, allowing you at run time to adjust the rate at * which executions are occurring. * * Provide a value of zero to disable this and allow steps to execute as fast as possible. * * @param stepsPerSecondLimit Steps per second allowed to execute */ public void setMaxScriptStepRate(double stepsPerSecondLimit) { addStep(new RateAdjustmentStep(stepsPerSecondLimit)); } public abstract ParallelScriptBuilder inParallel(); public abstract SequentialScriptBuilder inSequence(); /** * Add a step to this builder. For more specific step addition descriptions please see: * {@link SequentialScriptBuilder#addStep(ScriptStepInterface)} and * {@link ParallelScriptBuilder#addStep(ScriptStepInterface)}. * * @param step Test step to add to builder */ public abstract void addStep(ScriptStepInterface step); /** * Add a {@link ExecutionItem} to this builder. This is a private API so that we can add test * steps which need access to the executing {@link AbstractScriptBuilder}. * * @param chainItem Item to add to current execution chain */ protected abstract void addStep(ExecutionItem chainItem); /** * Add a sequential series of steps to this builder. Since the behavior of this depends on the * current step, please see a more specific step addition behavior descriptions here: * {@link SequentialScriptBuilder#addSteps(SequentialScriptBuilder)} and * {@link ParallelScriptBuilder#addSteps(SequentialScriptBuilder)}. * * @param sequentialSteps Test steps to be added to this builder */ public abstract void addSteps(SequentialScriptBuilder sequentialSteps); /** * Add a parallel series of steps to this builder. Since the behavior of this depends on the * current step, please see a more specific step addition behavior descriptions here: * {@link SequentialScriptBuilder#addSteps(SequentialScriptBuilder)} and * {@link ParallelScriptBuilder#addSteps(SequentialScriptBuilder)}. * * @param parallelSteps Test steps to be added to this builder */ public abstract void addSteps(ParallelScriptBuilder parallelSteps); /** * Call to check how many threads this script will need to execute at the current build point. * This can give you an idea of how intensely parallel this script is. * * @return Number of threads to run script at it's most parallel point */ public int getNeededThreadCount() { return neededThreadCount; } /** * Make a copy of the script chain. This is necessary if you want to add the chain multiple * times to another chain. The returned chain will execute the same script step instances (so * if added to a parallel builder make sure the script steps are thread safe). * * @return A copy builder */ public abstract AbstractScriptBuilder makeCopy(); protected void maybeUpdatedMaximumThreads(int currentValue) { if (neededThreadCount < currentValue) { neededThreadCount = currentValue; } } /** * Finalizes the script construction if it has not already finalized. This is not the same as {@link #replaced} */ private void maybeFinalize() { verifyNotReplaced(); if (! finalized.getAndSet(true)) { finalizeStep(); stepRunners.trimToSize(); } } /** * Called when the step is about to be either executed or replaced. This finalizes the step * to add it to the execution chain if it makes sense to do so. */ protected abstract void finalizeStep(); /** * Marks this builder as replaced. Once replaced no operations can continue to happen on this * builder. All further building must be done on the builder which is replacing this one. */ protected void replaced() { maybeFinalize(); replacementException = new Exception(); } /** * Verifies this builder is still valid to build on. Meaning it has not been finalized or * replaced by another builder. */ protected void verifyValid() { verifyNotReplaced(); if (finalized.get()) { throw new IllegalStateException("Script finalized"); } } /** * Verifies that this builder has not been replaced by another builder. This is a subset check * of {@link #verifyValid()}. */ protected void verifyNotReplaced() { if (replacementException != null) { throw new RuntimeException("This builder has been replaced, " + "caused by exception will indicate the stack of where it was replaced", replacementException); } } /** * Finalizes the script and compiles into an executable form. * * @return A script which can be started */ public ExecutableScript build() { maybeFinalize(); if (stepRunners.isEmpty()) { throw new IllegalStateException("No steps added to script to build"); } return new ExecutableScript(neededThreadCount, stepRunners); } /** * <p>A simple implementation of {@link ChildItems} which takes in a list of items that it is * holding.</p> * * @author jent - Mike Jensen */ protected static class ChildItemContainer implements ChildItems { protected final ExecutionItem[] items; protected final boolean runSequentially; protected ChildItemContainer() { this(null, true); } protected ChildItemContainer(ExecutionItem[] items, boolean runSequentially) { this.items = items; this.runSequentially = runSequentially; } @Override public boolean itemsRunSequential() { return runSequentially; } @Override public boolean hasChildren() { return items != null; } @Override public Iterator<ExecutionItem> iterator() { if (items == null) { return Collections.<ExecutionItem>emptyList().iterator(); } else { return Collections.unmodifiableList(Arrays.asList(items)).iterator(); } } } /** * <p>{@link ExecutionItem} which changes the limit at which steps can be executed.</p> * * @author jent - Mike Jensen */ private static class RateAdjustmentStep extends GhostExecutionItem { private final double newRateLimit; public RateAdjustmentStep(double newRateLimit) { this.newRateLimit = newRateLimit; } @Override public void runChainItem(ExecutionAssistant assistant) { assistant.setStepPerSecondLimit(newRateLimit); } @Override public String toString() { return "RateAdjustment:" + newRateLimit; } @Override public boolean manipulatesExecutionAssistant() { return true; } } /** * <p>Test step which will report the current running test progress.</p> * * @author jent - Mike Jensen */ private static class ProgressScriptStep extends GhostExecutionItem { private final SettableListenableFuture<Double> slf; public ProgressScriptStep(SettableListenableFuture<Double> slf) { this.slf = slf; } @Override public void runChainItem(ExecutionAssistant assistant) { try { List<? extends ListenableFuture<?>> scriptFutures = assistant.getGlobalRunningFutureSet(); double doneCount = 0; Iterator<? extends ListenableFuture<?>> it = scriptFutures.iterator(); while (it.hasNext()) { if (it.next().isDone()) { doneCount++; } } slf.setResult((doneCount / scriptFutures.size()) * 100); } catch (Exception e) { slf.setFailure(e); } } @Override public String toString() { return ProgressScriptStep.class.getSimpleName(); } @Override public boolean manipulatesExecutionAssistant() { return false; } } /** * <p>Abstract implementation for any {@link ExecutionItem} which should not be ever seen to the * user. Either by a future returned as a step, or copied into a new chain.</p> * * @author jent - Mike Jensen */ protected abstract static class GhostExecutionItem implements ExecutionItem { @Override public void prepareForRun() { // nothing to do here } @Override public List<? extends SettableListenableFuture<StepResult>> getFutures() { return Collections.emptyList(); } @Override public ExecutionItem makeCopy() { return null; } @Override public ChildItems getChildItems() { return new ChildItemContainer(); } @Override public boolean isChainExecutor() { return false; } } /** * <p>Basic abstract implementation for every test step collection to execute it's tests. This * also provides the minimum API that any collection of steps must implement.</p> * * @author jent - Mike Jensen */ protected abstract static class StepCollectionRunner implements ExecutionItem { private final ArrayList<SettableListenableFuture<StepResult>> futures; private ExecutionItem[] steps; public StepCollectionRunner() { steps = new ExecutionItem[0]; futures = new ArrayList<SettableListenableFuture<StepResult>>(); } /** * Call to check how many steps are in this collection. * * @return Number of steps this collection runs */ public int getStepCount() { return steps.length; } /** * Returns the backing array of steps which will be ran by this collection. * * @return Array of items which will be ran */ public ExecutionItem[] getSteps() { return steps; } @Override public void prepareForRun() { futures.trimToSize(); } private ExecutionItem[] makeStepsCopy(int extraEndSpace) { ExecutionItem[] newSteps = new ExecutionItem[steps.length + extraEndSpace]; System.arraycopy(steps, 0, newSteps, 0, steps.length); return newSteps; } /** * Adds an {@link ExecutionItem} to this collection of steps to run. * * @param item Item to be added, can not be {@code null} */ public void addItem(ExecutionItem item) { futures.addAll(item.getFutures()); ExecutionItem[] newSteps = makeStepsCopy(1); newSteps[steps.length] = item; steps = newSteps; } /** * Adds an array of {@link ExecutionItem}'s to this collection of steps to run. * * @param items Items to be added, can not be {@code null} */ public void addItems(ExecutionItem[] items) { if (items.length == 0) { return; } for (ExecutionItem ei : items) { futures.addAll(ei.getFutures()); } ExecutionItem[] newSteps = makeStepsCopy(items.length); System.arraycopy(items, 0, newSteps, steps.length, items.length); steps = newSteps; } @Override public List<? extends SettableListenableFuture<StepResult>> getFutures() { return futures; } @Override public String toString() { return Arrays.toString(steps); } @Override public boolean manipulatesExecutionAssistant() { return false; } @Override public boolean isChainExecutor() { return true; } } /** * <p>Implementation for executing a {@link ScriptStepInterface} instance. This class also * represents the future for the test step execution. If executed it is guaranteed to provide a * {@link StepResult} (with or without error).</p> * * @author jent - Mike Jensen */ protected static class ScriptStepRunner extends SettableListenableFuture<StepResult> implements ExecutionItem { protected final ScriptStepInterface scriptStep; public ScriptStepRunner(ScriptStepInterface scriptStep) { super(false); this.scriptStep = scriptStep; } @Override public void prepareForRun() { // nothing to do here } @Override public void runChainItem(ExecutionAssistant assistant) { setRunningThread(Thread.currentThread()); long startNanos = Clock.systemNanoTime(); StepResult result; try { scriptStep.runStep(); long endNanos = Clock.systemNanoTime(); result = new StepResult(scriptStep.getIdentifier(), endNanos - startNanos); } catch (Throwable t) { long endNanos = Clock.systemNanoTime(); result = new StepResult(scriptStep.getIdentifier(), endNanos - startNanos, t); } setResult(result); } @Override public ScriptStepRunner makeCopy() { return new ScriptStepRunner(scriptStep); } @Override public List<SettableListenableFuture<StepResult>> getFutures() { SettableListenableFuture<StepResult> slf = this; return Collections.singletonList(slf); } @Override public ChildItems getChildItems() { return new ChildItemContainer(); } @Override public String toString() { return scriptStep.getIdentifier(); } @Override public boolean manipulatesExecutionAssistant() { return false; } @Override public boolean isChainExecutor() { return false; } } }
package de.craften.util; import java.io.File; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import de.craften.craftenlauncher.logic.Logger; public final class OSHelper { private static String operatingSystem; private static OSHelper instance; private static String pS = File.separator; private static String[] mOsArch32 = {"x86", "i386", "i686"}, //32-bit mOsArch64 = {"x64", "ia64", "amd64"}; //64-bit private OSHelper() { operatingSystem = System.getProperty("os.name"); if (operatingSystem.contains("Win")) { operatingSystem = "windows"; } else if (operatingSystem.contains("Linux")) { operatingSystem = "linux"; } else if (operatingSystem.contains("Mac")) { operatingSystem = "osx"; } } public synchronized static OSHelper getInstance() { if (instance == null) { instance = new OSHelper(); } return instance; } public static OSHelper TEST_CreateInstance() { return new OSHelper(); } public boolean isJava32bit(){ String archInfo = System.getProperty("os.arch"); if (archInfo != null && !archInfo.equals("")) { for (String aMOsArch32 : mOsArch32) { if (archInfo.equals(aMOsArch32)) { return true; } } } return false; } public boolean isJava64bit(){ String archInfo = System.getProperty("os.arch"); if (archInfo != null && !archInfo.equals("")) { for (String aMOsArch64 : mOsArch64) { if (archInfo.equals(aMOsArch64)) { return true; } } } return false; } public String getOSArch(){ String arch = System.getenv("PROCESSOR_ARCHITECTURE"); String wow64Arch = System.getenv("PROCESSOR_ARCHITEW6432"); String realArch = null; if(arch != null) { if(arch.endsWith("64") || wow64Arch != null && wow64Arch.endsWith("64")) { realArch = "64"; } else { realArch = "32"; } } else { if(wow64Arch != null && wow64Arch.endsWith("64")) { realArch = "64"; } } return realArch; } public String getMinecraftPath() { String path = ""; if (operatingSystem.equals("windows")) { path = System.getenv("APPDATA") + pS + ".minecraft" + pS; if (new File(path).exists()) { return path; } } else if (operatingSystem.equals("linux")) { path = System.getProperty("user.home") + pS + ".minecraft" + pS; if (new File(path).exists()) { return path; } } else if (operatingSystem.equals("mac")) { path = System.getProperty("user.home") + pS + "Library" + pS + "Application Support" + pS + "minecraft" + pS; if (new File(path).exists()) { return path; } } new File(path).mkdirs(); return path; } public String getOS() { return operatingSystem; } public String getOSasString(){ return os.toString().toLowerCase(); } public String getJavaPath() { String fs = File.separator; String path = System.getProperty("java.home") + fs + "bin" + fs; if (os.equals(OS.WINDOWS) && (new File(path + "javaw.exe").isFile())) { return path + "javaw.exe"; } return path + "java"; } }
package org.wyona.webapp.services; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.wyona.webapp.mail.EmailSender; import org.wyona.webapp.models.Email; import javax.mail.MessagingException; @Component public class MailerService { private static final Logger logger = LogManager.getLogger("MailerService"); private final EmailSender emailSender; @Autowired public MailerService(EmailSender emailSender) { this.emailSender = emailSender; } /** * Send email greeting * @param email Email address * @param subject Email subject * @param text Email body text */ public void sendEmailGreeting(String email, String subject, String text) throws MessagingException { emailSender.sendEmailGreeting(email, subject, text); logger.info("Email greeting sent to {}", email); } /** * @param object Email object, containing email address, subject and body text */ public void sendEmailToUser(Email object) throws MessagingException { emailSender.sendEmailGreeting(object.getEmail(), object.getSubject(), object.getText()); logger.info("Email sent to {}", object.getEmail()); } }
package edu.one.core.infra; import org.vertx.java.core.MultiMap; import org.vertx.java.core.eventbus.Message; import org.vertx.java.core.json.JsonArray; import org.vertx.java.core.json.JsonObject; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.Scanner; public class Utils { public static <T> T getOrElse(T value, T defaultValue) { return getOrElse(value, defaultValue, true); } public static <T> T getOrElse(T value, T defaultValue, boolean allowEmpty) { if (value != null && (allowEmpty || !value.toString().trim().isEmpty())) { return value; } return defaultValue; } public static String inputStreamToString(InputStream in) { Scanner scanner = new Scanner(in, "UTF-8"); String content = scanner.useDelimiter("\\A").next(); scanner.close(); return content; } public static JsonObject validAndGet(JsonObject json, List<String> fields, List<String> requiredFields) { if (json != null) { JsonObject e = json.copy(); for (String attr: json.getFieldNames()) { if (!fields.contains(attr) || e.getValue(attr) == null) { e.removeField(attr); } } if (e.toMap().keySet().containsAll(requiredFields)) { return e; } } return null; } public static Either<String, JsonObject> validResult(Message<JsonObject> res) { if ("ok".equals(res.body().getString("status"))) { JsonObject r = res.body().getObject("result"); if (r == null) { r = res.body(); r.removeField("status"); } return new Either.Right<>(r); } else { return new Either.Left<>(res.body().getString("message", "")); } } public static Either<String, JsonArray> validResults(Message<JsonObject> res) { if ("ok".equals(res.body().getString("status"))) { return new Either.Right<>(res.body().getArray("results", new JsonArray())); } else { return new Either.Left<>(res.body().getString("message", "")); } } // TODO improve with type and validation public static JsonObject jsonFromMultimap(MultiMap attributes) { JsonObject json = new JsonObject(); if (attributes != null) { for (Map.Entry<String, String> e: attributes.entries()) { json.putString(e.getKey(), e.getValue()); } } return json; } public static <T extends Enum<T>> T stringToEnum(String name, T defaultValue, Class<T> type) { if (name != null) { try { return Enum.valueOf(type, name); } catch (IllegalArgumentException | NullPointerException e) { return defaultValue; } } return defaultValue; } }
package org.zalando.nakadi.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.google.common.collect.ImmutableList; import org.zalando.nakadi.partitioning.PartitionStrategy; import javax.annotation.Nullable; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import java.util.Collections; import java.util.List; import static java.util.Collections.unmodifiableList; public class EventTypeBase { private static final List<String> EMPTY_PARTITION_KEY_FIELDS = ImmutableList.of(); @NotNull @Pattern(regexp = "[a-zA-Z][-0-9a-zA-Z_]*(\\.[0-9a-zA-Z][-0-9a-zA-Z_]*)*", message = "format not allowed") @Size(min = 1, max = 255, message = "the length of the name must be >= 1 and <= 255") private String name; @NotNull private String owningApplication; @NotNull private EventCategory category; @JsonIgnore private List<ValidationStrategyConfiguration> validationStrategies; @NotNull private List<EnrichmentStrategyDescriptor> enrichmentStrategies; private String partitionStrategy; @Nullable private List<String> partitionKeyFields; @Valid @NotNull private EventTypeSchemaBase schema; @Valid @Nullable private EventTypeStatistics defaultStatistic; @Valid private EventTypeOptions options; @Valid private ResourceAuthorization authorization; @NotNull private CompatibilityMode compatibilityMode; @Nullable @JsonInclude(JsonInclude.Include.NON_NULL) private Audience audience; public EventTypeBase() { this.validationStrategies = Collections.emptyList(); this.enrichmentStrategies = Collections.emptyList(); this.partitionStrategy = PartitionStrategy.RANDOM_STRATEGY; this.options = new EventTypeOptions(); this.compatibilityMode = CompatibilityMode.FORWARD; } public EventTypeBase(final String name, final String owningApplication, final EventCategory category, final List<ValidationStrategyConfiguration> validationStrategies, final List<EnrichmentStrategyDescriptor> enrichmentStrategies, final String partitionStrategy, final List<String> partitionKeyFields, final EventTypeSchemaBase schema, final EventTypeStatistics defaultStatistic, final EventTypeOptions options, final CompatibilityMode compatibilityMode) { this.name = name; this.owningApplication = owningApplication; this.category = category; this.validationStrategies = validationStrategies; this.enrichmentStrategies = enrichmentStrategies; this.partitionStrategy = partitionStrategy; this.partitionKeyFields = partitionKeyFields; this.schema = schema; this.defaultStatistic = defaultStatistic; this.options = options; this.compatibilityMode = compatibilityMode; } public EventTypeBase(final EventTypeBase eventType) { this.setName(eventType.getName()); this.setOwningApplication(eventType.getOwningApplication()); this.setCategory(eventType.getCategory()); this.setValidationStrategies(eventType.getValidationStrategies()); this.setEnrichmentStrategies(eventType.getEnrichmentStrategies()); this.setPartitionStrategy(eventType.getPartitionStrategy()); this.setPartitionKeyFields(eventType.getPartitionKeyFields()); this.setSchema(eventType.getSchema()); this.setDefaultStatistic(eventType.getDefaultStatistic()); this.setOptions(eventType.getOptions()); this.setCompatibilityMode(eventType.getCompatibilityMode()); this.setAuthorization(eventType.getAuthorization()); this.setAudience(eventType.getAudience()); } public String getName() { return name; } public void setName(final String name) { this.name = name; } public String getOwningApplication() { return owningApplication; } public void setOwningApplication(final String owningApplication) { this.owningApplication = owningApplication; } public EventCategory getCategory() { return category; } public void setCategory(final EventCategory category) { this.category = category; } public List<ValidationStrategyConfiguration> getValidationStrategies() { return validationStrategies; } public String getPartitionStrategy() { return partitionStrategy; } public void setPartitionStrategy(final String partitionStrategy) { this.partitionStrategy = partitionStrategy; } public EventTypeSchemaBase getSchema() { return schema; } public void setSchema(final EventTypeSchemaBase schema) { this.schema = schema; } public EventTypeStatistics getDefaultStatistic() { return defaultStatistic; } public void setDefaultStatistic(final EventTypeStatistics defaultStatistic) { this.defaultStatistic = defaultStatistic; } public List<String> getPartitionKeyFields() { return unmodifiableList(partitionKeyFields != null ? partitionKeyFields : EMPTY_PARTITION_KEY_FIELDS); } public void setPartitionKeyFields(final List<String> partitionKeyFields) { this.partitionKeyFields = partitionKeyFields; } public List<EnrichmentStrategyDescriptor> getEnrichmentStrategies() { return enrichmentStrategies; } public void setEnrichmentStrategies(final List<EnrichmentStrategyDescriptor> enrichmentStrategies) { this.enrichmentStrategies = enrichmentStrategies; } public EventTypeOptions getOptions() { return options; } public void setOptions(final EventTypeOptions options) { this.options = options; } public CompatibilityMode getCompatibilityMode() { return compatibilityMode; } public void setCompatibilityMode(final CompatibilityMode compatibilityMode) { this.compatibilityMode = compatibilityMode; } public void setValidationStrategies(final List<ValidationStrategyConfiguration> validationStrategies) { this.validationStrategies = validationStrategies; } @Nullable public ResourceAuthorization getAuthorization() { return authorization; } @Nullable public Audience getAudience() { return audience; } public void setAudience(@Nullable final Audience audience) { this.audience = audience; } public void setAuthorization(final ResourceAuthorization authorization) { this.authorization = authorization; } }
package main.java.edugit; import com.sun.xml.internal.ws.api.pipe.FiberContextSwitchInterceptor; import javafx.fxml.FXML; import main.java.edugit.exceptions.CancelledLoginException; import main.java.edugit.exceptions.NoOwnerInfoException; import main.java.edugit.exceptions.NoRepoSelectedException; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.scene.control.Button; import javafx.scene.control.*; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.TextArea; import javafx.scene.paint.RadialGradient; import javafx.scene.shape.Circle; import javafx.scene.text.Text; import org.controlsfx.control.ListSelectionView; import org.controlsfx.control.NotificationPane; import org.controlsfx.control.action.Action; import org.eclipse.jgit.api.errors.*; import org.eclipse.jgit.lib.Config; import java.awt.*; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.prefs.BackingStoreException; /** * The controller for the entire session. */ public class SessionController extends Controller { public ComboBox<BranchHelper> branchSelector; public Text currentRepoLabel; public NotificationPane notificationPane; private SessionModel theModel; public Button openRepoDirButton; public Button gitStatusButton; public Button commitButton; public Button mergeFromFetchButton; public Button pushButton; public Button fetchButton; public TextArea commitMessageField; public WorkingTreePanelView workingTreePanelView; public CommitTreePanelView localCommitTreePanelView; public CommitTreePanelView remoteCommitTreePanelView; public Circle remoteCircle; private static final RadialGradient startGradient = RadialGradient.valueOf("center 50% 50%, radius 50%, #52B3D9 60%, #3498DB"); private static final RadialGradient hoverGradient = RadialGradient.valueOf("center 50% 50%, radius 50%, #81CFE0 60%, #52B3D9"); private static final RadialGradient clickGradient = RadialGradient.valueOf("center 50% 50%, radius 50%, #3498DB 60%, #52B3D9"); CommitTreeModel localCommitTreeModel; CommitTreeModel remoteCommitTreeModel; // The menu bar public MenuBar menuBar; private Menu newRepoMenu; private Menu openRecentRepoMenu; /** * Initializes the environment by obtaining the model * and putting the views on display. * * This method is automatically called by JavaFX. */ public void initialize() throws Exception { this.initializeLayoutParameters(); this.theModel = SessionModel.getSessionModel(); this.workingTreePanelView.setSessionModel(this.theModel); this.localCommitTreeModel = new LocalCommitTreeModel(this.theModel, this.localCommitTreePanelView); this.remoteCommitTreeModel = new RemoteCommitTreeModel(this.theModel, this.remoteCommitTreePanelView); // Buttons start out disabled, since no repo is loaded this.setButtonsDisabled(true); // Branch selector and trigger button starts invisible, since there's no repo and no branches this.branchSelector.setVisible(false); this.initializeMenuBar(); this.theModel.loadRecentRepoHelpersFromStoredPathStrings(); this.theModel.loadMostRecentRepoHelper(); this.initPanelViews(); this.updateUIEnabledStatus(); } private void initializeLayoutParameters(){ openRepoDirButton.setMinSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE); gitStatusButton.setMinSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE); commitButton.setMinSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE); mergeFromFetchButton.setMinSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE); pushButton.setMinSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE); fetchButton.setMinSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE); gitStatusButton.setMaxWidth(Double.MAX_VALUE); commitMessageField.setMinSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE); workingTreePanelView.setMinSize(Control.USE_PREF_SIZE, 200); branchSelector.setMinSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE); remoteCommitTreePanelView.heightProperty().addListener((observable, oldValue, newValue) -> { remoteCircle.setCenterY(newValue.doubleValue() / 2.0); if (oldValue.doubleValue() == 0) { remoteCircle.setRadius(newValue.doubleValue() / 5.0); } }); remoteCircle.setFill(startGradient); } @FXML private void updateBranchDropdown() throws GitAPIException, IOException { this.branchSelector.setVisible(true); List<LocalBranchHelper> branches = this.theModel.getCurrentRepoHelper().getLocalBranchesFromManager(); System.out.println(this.theModel.getCurrentRepoHelper().getLocalBranchesFromManager()); this.branchSelector.getItems().setAll(branches); BranchHelper currentBranch = this.theModel.getCurrentRepoHelper().getCurrentBranch(); if (currentBranch == null) { // This block will run when the app first opens and there is no selection in the dropdown. // It finds the repoHelper that matches the currently checked-out branch. String branchName = this.theModel.getCurrentRepo().getFullBranch(); LocalBranchHelper current = new LocalBranchHelper(branchName, this.theModel.getCurrentRepo()); for (BranchHelper branchHelper : branches) { if (branchHelper.getBranchName().equals(current.getBranchName())) { currentBranch = current; this.theModel.getCurrentRepoHelper().setCurrentBranch(currentBranch); break; } } if(currentBranch != null){ CommitTreeController.focusCommit(this.theModel.currentRepoHelper.getCommitByBranchName(currentBranch.refPathString)); } } this.branchSelector.setValue(currentBranch); // TODO: do a commit-focus on the initial load, too! } /** * Sets up the MenuBar by adding some options to it (for cloning). * * Each option offers a different way of loading a repository, and each * option instantiates the appropriate RepoHelper class for the chosen * loading method. * * Since each option creates a new repo, this method handles errors. * * TODO: split this method up or something. it's getting too big? */ private void initializeMenuBar() throws GitAPIException, IOException { this.newRepoMenu = new Menu("Load new Repository"); MenuItem cloneOption = new MenuItem("Clone"); cloneOption.setOnAction(t -> { try{ ClonedRepoHelperBuilder builder = new ClonedRepoHelperBuilder(this.theModel); RepoHelper repoHelper = builder.getRepoHelperFromDialogs(); // this creates and sets the RepoHelper this.theModel.openRepoFromHelper(repoHelper); this.initPanelViews(); this.updateUIEnabledStatus(); }catch(IllegalArgumentException e){ e.printStackTrace(); this.showInvalidRepoNotification(); }catch(JGitInternalException e){ e.printStackTrace(); this.showNonEmptyFolderNotification(); }catch(InvalidRemoteException e){ e.printStackTrace(); this.showInvalidRemoteNotification(); }catch(TransportException e){ e.printStackTrace(); this.showNotAuthorizedNotification(); } catch (NoRepoSelectedException e) { // The user pressed cancel on the dialog box. Do nothing! }catch(NoOwnerInfoException e){ e.printStackTrace(); this.showNotLoggedInNotification(); }catch(NullPointerException e){ this.showGenericErrorNotification(); e.printStackTrace(); // This block used to catch the NoOwnerInfo case, // but now that has its own Exception. Not sure when // a NullPointer would be thrown, so the dialog isn't // very helpful. Todo: investigate. } catch(Exception e){ // The generic error is totally unhelpful, so try not to ever reach this catch statement this.showGenericErrorNotification(); e.printStackTrace(); } }); MenuItem existingOption = new MenuItem("Load existing repository"); existingOption.setOnAction(t -> { ExistingRepoHelperBuilder builder = new ExistingRepoHelperBuilder(this.theModel); try{ RepoHelper repoHelper = builder.getRepoHelperFromDialogs(); this.theModel.openRepoFromHelper(repoHelper); this.initPanelViews(); this.updateUIEnabledStatus(); }catch(IllegalArgumentException e){ e.printStackTrace(); this.showInvalidRepoNotification(); } catch(NoRepoSelectedException e){ // The user pressed cancel on the dialog box. Do nothing! }catch(NoOwnerInfoException e){ this.showNotLoggedInNotification(); e.printStackTrace(); }catch(NullPointerException e){ // TODO: figure out when nullpointer is thrown (if at all?) this.showRepoWasNotLoadedNotification(); e.printStackTrace(); }catch(Exception e){ this.showGenericErrorNotification(); System.out.println("***** FIGURE OUT WHY THIS EXCEPTION IS NEEDED *******"); e.printStackTrace(); } }); // TODO: implement New Repository option. MenuItem newOption = new MenuItem("Start a new repository"); newOption.setDisable(true); this.newRepoMenu.getItems().addAll(cloneOption, existingOption, newOption); // Initialize it with no repos to choose from. This gets updated when there are repos present. this.openRecentRepoMenu = new Menu("Open recent repository"); MenuItem noOptionsAvailable = new MenuItem("No recent repositories"); noOptionsAvailable.setDisable(true); this.openRecentRepoMenu.getItems().add(noOptionsAvailable); this.menuBar.getMenus().addAll(newRepoMenu, openRecentRepoMenu); if (this.theModel.getAllRepoHelpers().size() != 0) { // If there are repos from previous sessions, put them in the menu bar this.updateMenuBarWithRecentRepos(); } } private void updateMenuBarWithRecentRepos() { this.openRecentRepoMenu.getItems().clear(); ArrayList<RepoHelper> repoHelpers = this.theModel.getAllRepoHelpers(); for (RepoHelper repoHelper : repoHelpers) { MenuItem recentRepoHelperMenuItem = new MenuItem(repoHelper.toString()); recentRepoHelperMenuItem.setOnAction(t -> { try { this.theModel.openRepoFromHelper(repoHelper); this.initPanelViews(); this.updateUIEnabledStatus(); } catch (BackingStoreException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch(GitAPIException e){ e.printStackTrace(); } }); openRecentRepoMenu.getItems().add(recentRepoHelperMenuItem); } this.menuBar.getMenus().clear(); this.menuBar.getMenus().addAll(this.newRepoMenu, this.openRecentRepoMenu); } /** * Perform the updateFileStatusInRepo() method for each file whose * checkbox is checked. Then commit with the commit message and push. * * @param actionEvent the button click event. * @throws GitAPIException if the updateFileStatusInRepo() call fails. * @throws IOException if the onGitStatusButton() fails. */ //todo: since there's a try/catch, should this method signature not throw exceptions? public void handleCommitButton(ActionEvent actionEvent) throws GitAPIException, IOException { try { String commitMessage = commitMessageField.getText(); for (RepoFile checkedFile : this.workingTreePanelView.getCheckedFilesInDirectory()) { checkedFile.updateFileStatusInRepo(); } this.theModel.currentRepoHelper.commit(commitMessage); // Now clear the commit text and a view reload ( or `git status`) to show that something happened commitMessageField.clear(); this.onGitStatusButton(); } catch (NullPointerException e) { this.showNoRepoLoadedNotification(); } catch (TransportException e) { this.showNotAuthorizedNotification(); } catch (WrongRepositoryStateException e) { System.out.println("Threw a WrongRepositoryStateException"); e.printStackTrace(); // TODO remove the above debug statements // This should only come up when the user chooses to resolve conflicts in a file. // Do nothing. } } public void handleMergeFromFetchButton(ActionEvent actionEvent) throws IOException, GitAPIException { try { this.theModel.currentRepoHelper.mergeFromFetch(); // Refresh panel views this.onGitStatusButton(); } catch (NullPointerException e) { this.showNoRepoLoadedNotification(); } catch (TransportException e) { this.showNotAuthorizedNotification(); } } public void handlePushButton(ActionEvent actionEvent) throws GitAPIException, IOException { try { this.theModel.currentRepoHelper.pushAll(); // Refresh panel views this.onGitStatusButton(); } catch (NullPointerException e) { this.showNoRepoLoadedNotification(); } catch (TransportException e) { this.showNotAuthorizedNotification(); } } public void handleFetchButton(ActionEvent actionEvent) throws GitAPIException, IOException { try { this.theModel.currentRepoHelper.fetch(); // Refresh panel views this.onGitStatusButton(); } catch (NullPointerException e) { this.showNoRepoLoadedNotification(); } catch (TransportException e) { this.showNotAuthorizedNotification(); } } /** * Loads the panel views when the "git status" button is clicked. * * @throws GitAPIException if the drawDirectoryView() call fails. * @throws IOException if the drawDirectoryView() call fails. */ public void onGitStatusButton() throws GitAPIException, IOException{ try { this.workingTreePanelView.drawDirectoryView(); this.localCommitTreeModel.update(); this.remoteCommitTreeModel.update(); this.updateBranchDropdown(); } catch (NullPointerException e) { this.showNoRepoLoadedNotification(); } } /** * When the circle representing the remote repo is clicked, go to the * corresponding remote url * @param event */ public void handleRemoteCircleMouseClick(Event event){ Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null; if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) { try { Config storedConfig = this.theModel.getCurrentRepo().getConfig(); Set<String> remotes = storedConfig.getSubsections("remote"); for (String remoteName : remotes) { String url = storedConfig.getString("remote", remoteName, "url"); if(url.contains("@")){ url = "https://"+url.replace(":","/").split("@")[1]; } desktop.browse(new URI(url)); } } catch (Exception e) { // TODO: real error message e.printStackTrace(); System.out.println("Couldn't open the remote repo"); } finally{ remoteCircle.setFill(startGradient); } } } public void handleRemoteCircleMouseEnter(Event event){ remoteCircle.setFill(hoverGradient); } public void handleRemoteCircleMouseExit(Event event){ remoteCircle.setFill(startGradient); } public void handleRemoteCircleMousePressed(Event event){ remoteCircle.setFill(clickGradient); } /** * Initializes each panel of the view * @throws GitAPIException * @throws IOException */ private void initPanelViews() throws GitAPIException, IOException{ this.workingTreePanelView.drawDirectoryView(); this.localCommitTreeModel.init(); this.remoteCommitTreeModel.init(); } /** * A helper method for enabling/disabling buttons. * * @param disable a boolean for whether or not to disable the buttons. */ private void setButtonsDisabled(boolean disable) { openRepoDirButton.setDisable(disable); gitStatusButton.setDisable(disable); commitButton.setDisable(disable); mergeFromFetchButton.setDisable(disable); pushButton.setDisable(disable); fetchButton.setDisable(disable); remoteCircle.setVisible(!disable); } /** * * @param actionEvent * @throws GitAPIException * @throws IOException from updateBranchDropdown() */ public void loadSelectedBranch(ActionEvent actionEvent) throws GitAPIException, IOException { BranchHelper selectedBranch = this.branchSelector.getValue(); if(selectedBranch == null) return; try { selectedBranch.checkoutBranch(); RepoHelper repoHelper = this.theModel.getCurrentRepoHelper(); CommitTreeController.focusCommit(repoHelper.getCommitByBranchName(selectedBranch.refPathString)); this.theModel.getCurrentRepoHelper().setCurrentBranch(selectedBranch); } catch (CheckoutConflictException e) { this.showCheckoutConflictsNotification(e.getConflictingPaths()); this.updateBranchDropdown(); } } /** * A helper helper method to enable or disable buttons/UI elements * depending on whether there is a repo open for the buttons to * interact with. */ private void updateUIEnabledStatus() throws GitAPIException, IOException { RepoHelper currentRepoHelper = this.theModel.getCurrentRepoHelper(); if (currentRepoHelper == null && this.theModel.getAllRepoHelpers().size() == 0) { // (There's no repo for the buttons to interact with) setButtonsDisabled(true); this.branchSelector.setVisible(false); } else if (currentRepoHelper == null && this.theModel.getAllRepoHelpers().size() > 0) { // (There's no repo for buttons to interact with, but there are repos in the menu bar) setButtonsDisabled(true); this.updateMenuBarWithRecentRepos(); } else { setButtonsDisabled(false); this.updateBranchDropdown(); this.updateMenuBarWithRecentRepos(); this.updateCurrentRepoLabel(); } } private void updateCurrentRepoLabel() { String name = this.theModel.getCurrentRepoHelper().toString(); this.currentRepoLabel.setText(name); } /// THIS IS JUST A DEBUG METHOD FOR A DEBUG BUTTON. TEMPORARY! // todo: set up more permanent data clearing functionality public void clearSavedStuff(ActionEvent actionEvent) throws BackingStoreException, IOException, ClassNotFoundException { this.theModel.clearStoredPreferences(); } public void switchUser() { // Begin with a nullified RepoOwner: RepoOwner newOwner = new RepoOwner(null, null); try { newOwner = new RepoOwner(); } catch (CancelledLoginException e) { // User cancelled the login, so we'll leave the owner full of nullness. } if (theModel.getCurrentRepoHelper() != null) { // The currentRepoHelper could be null, say, // on the first run of the program. this.theModel.getCurrentRepoHelper().setOwner(newOwner); } this.theModel.setCurrentDefaultOwner(newOwner); } public void openRepoDirectory(ActionEvent actionEvent){ if (Desktop.isDesktopSupported()) { try{ Desktop.getDesktop().open(this.theModel.currentRepoHelper.localPath.toFile()); }catch(IOException e){ e.printStackTrace(); // TODO: real error message System.out.println("Couldn't open the local repo. Real error message here eventually"); } } } private void showNotLoggedInNotification() { this.notificationPane.setText("You need to log in to do that."); Action loginAction = new Action("Enter login info", e -> { this.notificationPane.hide(); this.switchUser(); }); this.notificationPane.getActions().clear(); this.notificationPane.getActions().setAll(loginAction); this.notificationPane.show(); } private void showNoRepoLoadedNotification() { this.notificationPane.setText("You need to load a repository before you can perform operations on it!"); this.notificationPane.getActions().clear(); this.notificationPane.show(); } private void showInvalidRepoNotification() { this.notificationPane.setText("Make sure the directory you selected contains an existing Git repository."); this.notificationPane.getActions().clear(); this.notificationPane.show(); } private void showNonEmptyFolderNotification() { this.notificationPane.setText("Make sure the directory you selected is completely empty. The best" + "way to do this is to create a new folder from the directory chooser."); this.notificationPane.getActions().clear(); this.notificationPane.show(); } private void showInvalidRemoteNotification() { this.notificationPane.setText("Make sure you entered the correct remote URL."); this.notificationPane.getActions().clear(); this.notificationPane.show(); } private void showGenericErrorNotification() { this.notificationPane.setText("Sorry, there was an error."); this.notificationPane.getActions().clear(); this.notificationPane.show(); } private void showNotAuthorizedNotification() { this.notificationPane.setText("The login information you gave does not allow you to modify this repository. Try switching your login and trying again."); Action loginAction = new Action("Log in", e -> { this.notificationPane.hide(); this.switchUser(); }); this.notificationPane.getActions().clear(); this.notificationPane.getActions().setAll(loginAction); this.notificationPane.show(); } private void showRepoWasNotLoadedNotification() { this.notificationPane.setText("No repository was loaded."); this.notificationPane.getActions().clear(); this.notificationPane.show(); } private void showCheckoutConflictsNotification(List<String> conflictingPaths) { String conflictList = ""; for (String pathName : conflictingPaths) { conflictList += "\n" + pathName; } Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Conflicting files"); alert.setHeaderText("Can't checkout that branch"); alert.setContentText("You can't switch to that branch because of the following conflicting files between that branch and your current branch: " + conflictList); this.notificationPane.setText("You can't switch to that branch because there would be a merge conflict. Stash your changes or resolve conflicts first."); Action seeConflictsAction = new Action("See conflicts", e -> { this.notificationPane.hide(); alert.showAndWait(); }); this.notificationPane.getActions().clear(); this.notificationPane.getActions().setAll(seeConflictsAction); this.notificationPane.show(); } public void showBranchChooser(ActionEvent actionEvent) throws IOException { this.theModel.getCurrentRepoHelper().getBranchManager().showBranchChooser(); } }
package ee.ttu.geocollection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.Banner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.i18n.SessionLocaleResolver; import javax.net.ssl.*; import java.net.Socket; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Locale; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @Configuration @ComponentScan(basePackages = { "ee.ttu.geocollection" }) @EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) @EnableScheduling @EnableAsync @Import(value = IndexConfig.class) public class App extends SpringBootServletInitializer { private static final Logger logger = LoggerFactory.getLogger(App.class); public static void main(String[] args) throws Exception { SpringApplication app = new SpringApplication(App.class); app.setBannerMode(Banner.Mode.OFF); app.addListeners(new ApplicationListener<ContextRefreshedEvent>() { @Override public void onApplicationEvent(ContextRefreshedEvent event) { ApplicationContext context = event.getApplicationContext(); logger.info("Application refreshed"); } }); app.run(args); TrustManager[] trustAllCerts = new TrustManager[]{ new X509ExtendedTrustManager() { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException { } @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException { } } }; SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(App.class); } @Bean public LocaleResolver localeResolver() { SessionLocaleResolver slr = new SessionLocaleResolver(); slr.setDefaultLocale(new Locale("et")); return slr; } @Bean public ExecutorService asyncThreadPoolExecutor() { return Executors.newFixedThreadPool(15); } }
package picard.illumina.parser; import htsjdk.samtools.util.CloserUtil; import htsjdk.samtools.util.IOUtil; import picard.PicardException; import picard.illumina.parser.fakers.*; import picard.illumina.parser.readers.TileMetricsOutReader; import java.io.File; import java.util.*; import java.util.regex.Pattern; import java.util.stream.Collectors; public class IlluminaFileUtil { public static final Pattern CYCLE_SUBDIRECTORY_PATTERN = Pattern.compile("^C(\\d+)\\.1$"); public enum SupportedIlluminaFormat { Bcl, Locs, Clocs, Pos, Filter, Barcode, MultiTileFilter, MultiTileLocs, MultiTileBcl } private final File basecallLaneDir; private final File intensityLaneDir; private final File basecallDir; private final File barcodeDir; private final File intensityDir; private final int lane; private final File tileMetricsOut; private final Map<SupportedIlluminaFormat, ParameterizedFileUtil> utils = new EnumMap<>(SupportedIlluminaFormat.class); public IlluminaFileUtil(final File basecallDir, final int lane) { this(basecallDir, null, lane); } public IlluminaFileUtil(final File basecallDir, final File barcodeDir, final int lane) { this.lane = lane; this.basecallDir = basecallDir; this.barcodeDir = barcodeDir; this.intensityDir = basecallDir.getParentFile(); final File dataDir = intensityDir.getParentFile(); this.basecallLaneDir = new File(basecallDir, longLaneStr(lane)); this.intensityLaneDir = new File(intensityDir, longLaneStr(lane)); final File interopDir = new File(dataDir.getParentFile(), "InterOp"); tileMetricsOut = new File(interopDir, "TileMetricsOut.bin"); } /** * Return the lane we're inspecting */ public int getLane() { return lane; } /** * Given a file type, get the Parameterized File Util object associated with it */ public ParameterizedFileUtil getUtil(final SupportedIlluminaFormat format) { ParameterizedFileUtil parameterizedFileUtil = utils.get(format); if (parameterizedFileUtil == null) { switch (format) { case Bcl: final ParameterizedFileUtil bclFileUtil = new PerTilePerCycleFileUtil(".bcl", basecallLaneDir, new BclFileFaker(), lane); final ParameterizedFileUtil gzBclFileUtil = new PerTilePerCycleFileUtil(".bcl.gz", basecallLaneDir, new BclFileFaker(), lane); if (bclFileUtil.filesAvailable() && !gzBclFileUtil.filesAvailable()) { parameterizedFileUtil = bclFileUtil; } else if (!bclFileUtil.filesAvailable() && gzBclFileUtil.filesAvailable()) { parameterizedFileUtil = gzBclFileUtil; } else if (!bclFileUtil.filesAvailable() && !gzBclFileUtil.filesAvailable()) { parameterizedFileUtil = bclFileUtil; } else { throw new PicardException( "Not all BCL files in " + basecallLaneDir.getAbsolutePath() + " have the same extension!"); } utils.put(SupportedIlluminaFormat.Bcl, parameterizedFileUtil); break; case Locs: parameterizedFileUtil = new PerTileOrPerRunFileUtil(".locs", intensityLaneDir, new LocsFileFaker(), lane); utils.put(SupportedIlluminaFormat.Locs, parameterizedFileUtil); break; case Clocs: parameterizedFileUtil = new PerTileFileUtil(".clocs", intensityLaneDir, new ClocsFileFaker(), lane); utils.put(SupportedIlluminaFormat.Clocs, parameterizedFileUtil); break; case Pos: parameterizedFileUtil = new PerTileFileUtil("_pos.txt", intensityDir, new PosFileFaker(), lane); utils.put(SupportedIlluminaFormat.Pos, parameterizedFileUtil); break; case Filter: parameterizedFileUtil = new PerTileFileUtil(".filter", basecallLaneDir, new FilterFileFaker(), lane); utils.put(SupportedIlluminaFormat.Filter, parameterizedFileUtil); break; case Barcode: parameterizedFileUtil = new PerTileFileUtil("_barcode.txt", barcodeDir != null ? barcodeDir : basecallDir, new BarcodeFileFaker(), lane, false); utils.put(SupportedIlluminaFormat.Barcode, parameterizedFileUtil); break; case MultiTileFilter: parameterizedFileUtil = new MultiTileFilterFileUtil(basecallLaneDir, lane); utils.put(SupportedIlluminaFormat.MultiTileFilter, parameterizedFileUtil); break; case MultiTileLocs: parameterizedFileUtil = new MultiTileLocsFileUtil(new File(intensityDir, basecallLaneDir.getName()), basecallLaneDir, lane); utils.put(SupportedIlluminaFormat.MultiTileLocs, parameterizedFileUtil); break; case MultiTileBcl: parameterizedFileUtil = new MultiTileBclFileUtil(basecallLaneDir, lane); utils.put(SupportedIlluminaFormat.MultiTileBcl, parameterizedFileUtil); break; } } return parameterizedFileUtil; } /** * Return the list of tiles we would expect for this lane based on the metrics found in InterOp/TileMetricsOut.bin */ public List<Integer> getExpectedTiles() { IOUtil.assertFileIsReadable(tileMetricsOut); //Used just to ensure predictable ordering final TreeSet<Integer> expectedTiles = new TreeSet<>(); final Iterator<TileMetricsOutReader.IlluminaTileMetrics> tileMetrics = new TileMetricsOutReader(tileMetricsOut, TileMetricsOutReader.TileMetricsVersion.TWO); while (tileMetrics.hasNext()) { final TileMetricsOutReader.IlluminaTileMetrics tileMetric = tileMetrics.next(); if (tileMetric.getLaneNumber() == lane && !expectedTiles.contains(tileMetric.getTileNumber())) { expectedTiles.add(tileMetric.getTileNumber()); } } CloserUtil.close(tileMetrics); return new ArrayList<>(expectedTiles); } /** * Get the available tiles for the given formats, if the formats have tile lists that differ then * throw an exception, if any of the format */ public List<Integer> getActualTiles(final List<SupportedIlluminaFormat> formats) { if (formats == null) { throw new PicardException("Format list provided to getTiles was null!"); } if (formats.isEmpty()) { throw new PicardException( "0 Formats were specified. You need to specify at least SupportedIlluminaFormat to use getTiles"); } final List<ParameterizedFileUtil> tileBasedFormats = formats .stream() .map(this::getUtil) .filter(ParameterizedFileUtil::checkTileCount).collect(Collectors.toList()); if( tileBasedFormats.size() > 0) { final List<Integer> expectedTiles = tileBasedFormats.get(0).getTiles(); tileBasedFormats.forEach(util -> { if (expectedTiles.size() != util.getTiles().size() || !expectedTiles.containsAll(util.getTiles())) { throw new PicardException( "Formats do not have the same number of tiles! " + summarizeTileCounts(formats)); }}); return expectedTiles; } else { //we have no tile based file formats so we have no tiles. return new ArrayList<>(); } } public File tileMetricsOut() { return tileMetricsOut; } /* * Return a string representing the Lane in the format "L00<lane>" * * @param lane The lane to transform * @return A long string representation of the name */ public static String longLaneStr(final int lane) { final StringBuilder lstr = new StringBuilder(String.valueOf(lane)); final int zerosToAdd = 3 - lstr.length(); for (int i = 0; i < zerosToAdd; i++) { lstr.insert(0, "0"); } return "L" + lstr; } private String liToStr(final List<Integer> intList) { if (intList.isEmpty()) { return ""; } final StringBuilder summary = new StringBuilder(String.valueOf(intList.get(0))); for (int i = 1; i < intList.size(); i++) { summary.append(", ").append(String.valueOf(intList.get(i))); } return summary.toString(); } private String summarizeTileCounts(final List<SupportedIlluminaFormat> formats) { final StringBuilder summary; ParameterizedFileUtil pfu = getUtil(formats.get(0)); List<Integer> tiles = pfu.getTiles(); summary = new StringBuilder(pfu.extension + "(" + liToStr(tiles) + ")"); for (final SupportedIlluminaFormat format : formats) { pfu = getUtil(format); tiles = pfu.getTiles(); summary.append(", ").append(pfu.extension).append("(").append(liToStr(tiles)).append(")"); } return summary.toString(); } public static boolean hasCbcls(final File basecallDir, final int lane) { final File laneDir = new File(basecallDir, IlluminaFileUtil.longLaneStr(lane)); final File[] cycleDirs = IOUtil.getFilesMatchingRegexp(laneDir, IlluminaFileUtil.CYCLE_SUBDIRECTORY_PATTERN); // Either the lane or the cycle directory do not exist! if (cycleDirs == null) { return false; } //CBCLs final List<File> cbcls = new ArrayList<>(); Arrays.asList(cycleDirs) .forEach(cycleDir -> cbcls.addAll( Arrays.asList(IOUtil.getFilesMatchingRegexp( cycleDir, "^" + IlluminaFileUtil.longLaneStr(lane) + "_(\\d{1,5}).cbcl$")))); return cbcls.size() > 0; } }
package endpoints; import controller.AgencyController; import io.swagger.annotations.Api; import model.Agency; import model.Vehicle; import security.SecuredAdmin; import security.SecuredAgency; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.ws.rs.*; import javax.ws.rs.core.Application; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; @Stateless @ApplicationPath("/api") @Path("/agency") @Api("agency") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class AgencyEndpoint extends Application { @EJB protected AgencyController controller; @POST @SecuredAgency @Path("/create") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createAgency (Agency agency){ try { return Response.status(200).entity(controller.createAgency(agency)).build(); } catch (Exception ex) { return Response.status(400).type("text/plain") .entity("Format de l'entité invalide").build(); } } @PUT @SecuredAgency @Path("/edit") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response editAgency (Agency agency) { try { return Response.status(200).entity(controller.updateAgency(agency)).build(); } catch (Exception ex) { return Response.status(400).type("text/plain") .entity("Format de l'entité invalide").build(); } } @GET @SecuredAgency @Path("/view/{id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response consultAgency (@PathParam("id") Integer id) { try { return Response.status(200).entity(controller.getAgency(id)).build(); } catch (Exception ex) { return Response.status(400).type("text/plain") .entity("Aucune entité correspondant à cet Id").build(); } } @PUT @SecuredAdmin @Path("/activate/{id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response activateAgency (@PathParam("id") Integer id) { try { return Response.status(200).entity(controller.activateAgency(id)).build(); } catch (Exception ex) { return Response.status(400).type("text/plain") .entity("Aucune entité correspondant à cet Id").build(); } } @DELETE @SecuredAdmin @Consumes(MediaType.APPLICATION_JSON) @Path("/delete/{id}") @Produces(MediaType.APPLICATION_JSON) public Response deleteAgency (@PathParam("id") Integer id) { try { return Response.status(200).entity(controller.deleteAgency(id)).build(); } catch (Exception ex) { return Response.status(400).type("text/plain") .entity("Aucune entité correspondant à cet Id").build(); } } @GET @SecuredAgency @Path("/vehicle/{id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response View_Vehicles (@PathParam("id") Integer id) { try { return Response.status(200).entity(controller.getAgencyVehicles(id)).build(); } catch (Exception ex) { return Response.status(400).type("text/plain") .entity("Aucune entité correspondant à cet Id").build(); } } @GET @SecuredAgency @Path("/list/{id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response View_Agency (@PathParam("id") Integer id) { try { return Response.status(200).entity(controller.getChildAgencies(id)).build(); } catch (Exception ex) { return Response.status(400).type("text/plain") .entity("Aucune entité correspondant à cet Id").build(); } } }
package javaslang.collection; import javaslang.Function1; import javaslang.Tuple2; import javaslang.Tuple3; import javaslang.control.Option; import java.util.*; import java.util.function.*; /** * An immutable {@code Map} interface. * * @param <K> Key type * @param <V> Value type * @author Daniel Dietrich, Ruslan Sennov * @since 2.0.0 */ public interface Map<K, V> extends Traversable<Tuple2<K, V>>, Function1<K, V> { long serialVersionUID = 1L; @Override default V apply(K key) { return get(key).orElseThrow(NoSuchElementException::new); } /** * Returns <code>true</code> if this map contains a mapping for the specified key. * * @param key key whose presence in this map is to be tested * @return <code>true</code> if this map contains a mapping for the specified key */ boolean containsKey(K key); /** * Returns <code>true</code> if this map maps one or more keys to the * specified value. This operation will require time linear in the map size. * * @param value value whose presence in this map is to be tested * @return <code>true</code> if this map maps one or more keys to the * specified value */ boolean containsValue(V value); /** * FlatMaps this {@code Map} to a new {@code Map} with different component type. * * @param mapper A mapper * @param <U> Keys component type of the mapped {@code Map} * @param <W> Values component type of the mapped {@code Map} * @return A new {@code Map}. * @throws NullPointerException if {@code mapper} is null */ <U, W> Map<U, W> flatMap(BiFunction<? super K, ? super V, ? extends Iterable<? extends Tuple2<? extends U, ? extends W>>> mapper); /** * Returns the {@code Some} of value to which the specified key * is mapped, or {@code None} if this map contains no mapping for the key. * * @param key the key whose associated value is to be returned * @return the {@code Some} of value to which the specified key * is mapped, or {@code None} if this map contains no mapping * for the key */ Option<V> get(K key); /** * Returns the keys contained in this map. * @return {@code Set} of the keys contained in this map. */ Set<K> keySet(); /** * Maps this {@code Map} to a new {@code Map} with different component type. * * @param mapper A {@code Function} that maps entries of type {@code <K, V>} to entries of type {@code <U, W>}. * @param <U> Keys component type of the mapped {@code Map} * @param <W> Values component type of the mapped {@code Map} * @return A new {@code Map}. * @throws NullPointerException if {@code mapper} is null */ <U, W> Map<U, W> map(BiFunction<? super K, ? super V, ? extends Tuple2<? extends U, ? extends W>> mapper); /** * Maps the values of this {@code Map} while preserving the corresponding keys. * * @param <W> The new value type. * @param mapper A {@code Function} that maps values of type {@code K} to values of type {@code W}. * @return A new {@code Map}. * @throws NullPointerException if {@code mapper} is null */ <W> Map<K, W> mapValues(Function<? super V, ? extends W> mapper); /** * Associates the specified value with the specified key in this map. * If the map previously contained a mapping for the key, the old value is * replaced by the specified value. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return A new Map containing these elements and that entry. */ Map<K, V> put(K key, V value); /** * Convenience method for {@code put(entry._1, entry._2)}. * * @param entry A Map.Tuple2 * @return A new Map containing these elements and that entry. */ Map<K, V> put(Tuple2<? extends K, ? extends V> entry); /** * Removes the mapping for a key from this map if it is present. * * @param key key whose mapping is to be removed from the map * @return A new Map containing these elements without the entry * specified by that key. */ Map<K, V> remove(K key); /** * Removes the mapping for a key from this map if it is present. * * @param keys keys are to be removed from the map * @return A new Map containing these elements without the entries * specified by that keys. */ Map<K, V> removeAll(Iterable<? extends K> keys); @Override int size(); /** * Transforms this {@code Map}. * * @param f A transformation * @param <U> Type of transformation result * @return An instance of type {@code U} * @throws NullPointerException if {@code f} is null */ default <U> U transform(Function<? super Map<? super K, ? super V>, ? extends U> f) { Objects.requireNonNull(f, "f is null"); return f.apply(this); } default <U> Seq<U> traverse(BiFunction<K, V, ? extends U> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return foldLeft(List.empty(), (acc, entry) -> acc.append(mapper.apply(entry._1, entry._2))); } default <T1, T2> Tuple2<Seq<T1>, Seq<T2>> unzip(BiFunction<? super K, ? super V, Tuple2<? extends T1, ? extends T2>> unzipper) { Objects.requireNonNull(unzipper, "unzipper is null"); return unzip(entry -> unzipper.apply(entry._1, entry._2)); } default <T1, T2, T3> Tuple3<Seq<T1>, Seq<T2>, Seq<T3>> unzip3(BiFunction<? super K, ? super V, Tuple3<? extends T1, ? extends T2, ? extends T3>> unzipper) { Objects.requireNonNull(unzipper, "unzipper is null"); return unzip3(entry -> unzipper.apply(entry._1, entry._2)); } Seq<V> values(); // -- Adjusted return types of Traversable methods @Override Map<K, V> clear(); @Override default boolean contains(Tuple2<K, V> element) { return get(element._1).map(v -> Objects.equals(v, element._2)).orElse(false); } @Override Map<K, V> distinct(); @Override Map<K, V> distinctBy(Comparator<? super Tuple2<K, V>> comparator); @Override <U> Map<K, V> distinctBy(Function<? super Tuple2<K, V>, ? extends U> keyExtractor); @Override Map<K, V> drop(int n); @Override Map<K, V> dropRight(int n); @Override Map<K, V> dropUntil(Predicate<? super Tuple2<K, V>> predicate); @Override Map<K, V> dropWhile(Predicate<? super Tuple2<K, V>> predicate); @Override Map<K, V> filter(Predicate<? super Tuple2<K, V>> predicate); @Override Map<K, V> filterNot(Predicate<? super Tuple2<K, V>> predicate); @Override <U> Seq<U> flatMap(Function<? super Tuple2<K, V>, ? extends Iterable<? extends U>> mapper); @Override <C> Map<C, ? extends Map<K, V>> groupBy(Function<? super Tuple2<K, V>, ? extends C> classifier); @Override Iterator<? extends Map<K, V>> grouped(int size); @Override Map<K, V> init(); @Override Option<? extends Map<K, V>> initOption(); @Override Iterator<Tuple2<K, V>> iterator(); @Override default int length() { return size(); } @Override <U> Seq<U> map(Function<? super Tuple2<K, V>, ? extends U> mapper); /** * Creates a new map which by merging the entries of {@code this} map and {@code that} map. * <p> * If collisions occur, the value of {@code this} map is taken. * * @param that the other map * @return A merged map * @throws NullPointerException if that map is null */ Map<K, V> merge(Map<? extends K, ? extends V> that); /** * Creates a new map which by merging the entries of {@code this} map and {@code that} map. * <p> * Uses the specified collision resolution function if two keys are the same. * The collision resolution function will always take the first argument from <code>this</code> map * and the second from <code>that</code> map. * * @param <U> value type of that Map * @param that the other map * @param collisionResolution the collision resolution function * @return A merged map * @throws NullPointerException if that map or the given collision resolution function is null */ <U extends V> Map<K, V> merge(Map<? extends K, U> that, BiFunction<? super V, ? super U, ? extends V> collisionResolution); @Override Tuple2<? extends Map<K, V>, ? extends Map<K, V>> partition(Predicate<? super Tuple2<K, V>> predicate); @Override Map<K, V> peek(Consumer<? super Tuple2<K, V>> action); @Override Map<K, V> replace(Tuple2<K, V> currentElement, Tuple2<K, V> newElement); @Override Map<K, V> replaceAll(Tuple2<K, V> currentElement, Tuple2<K, V> newElement); @Override Map<K, V> retainAll(Iterable<? extends Tuple2<K, V>> elements); @Override Map<K, V> scan(Tuple2<K, V> zero, BiFunction<? super Tuple2<K, V>, ? super Tuple2<K, V>, ? extends Tuple2<K, V>> operation); @Override <U> Seq<U> scanLeft(U zero, BiFunction<? super U, ? super Tuple2<K, V>, ? extends U> operation); @Override <U> Seq<U> scanRight(U zero, BiFunction<? super Tuple2<K, V>, ? super U, ? extends U> operation); @Override Iterator<? extends Map<K, V>> sliding(int size); @Override Iterator<? extends Map<K, V>> sliding(int size, int step); @Override Tuple2<? extends Map<K, V>, ? extends Map<K, V>> span(Predicate<? super Tuple2<K, V>> predicate); @Override default Spliterator<Tuple2<K, V>> spliterator() { return Spliterators.spliterator(iterator(), length(), Spliterator.ORDERED | Spliterator.IMMUTABLE); } @Override Map<K, V> tail(); @Override Option<? extends Map<K, V>> tailOption(); @Override Map<K, V> take(int n); @Override Map<K, V> takeRight(int n); @Override Map<K, V> takeUntil(Predicate<? super Tuple2<K, V>> predicate); @Override Map<K, V> takeWhile(Predicate<? super Tuple2<K, V>> predicate); @Override default <T1, T2> Tuple2<Seq<T1>, Seq<T2>> unzip(Function<? super Tuple2<K, V>, Tuple2<? extends T1, ? extends T2>> unzipper) { Objects.requireNonNull(unzipper, "unzipper is null"); return iterator().unzip(unzipper).map(Stream::ofAll, Stream::ofAll); } @Override default <T1, T2, T3> Tuple3<Seq<T1>, Seq<T2>, Seq<T3>> unzip3( Function<? super Tuple2<K, V>, Tuple3<? extends T1, ? extends T2, ? extends T3>> unzipper) { Objects.requireNonNull(unzipper, "unzipper is null"); return iterator().unzip3(unzipper).map(Stream::ofAll, Stream::ofAll, Stream::ofAll); } @Override default <U> Seq<Tuple2<Tuple2<K, V>, U>> zip(Iterable<U> that) { Objects.requireNonNull(that, "that is null"); return Stream.ofAll(iterator().zip(that)); } @Override default <U> Seq<Tuple2<Tuple2<K, V>, U>> zipAll(Iterable<U> that, Tuple2<K, V> thisElem, U thatElem) { Objects.requireNonNull(that, "that is null"); return Stream.ofAll(iterator().zipAll(that, thisElem, thatElem)); } @Override default Seq<Tuple2<Tuple2<K, V>, Integer>> zipWithIndex() { return Stream.ofAll(iterator().zipWithIndex()); } /** * Performs an action on key, value pair. * * @param action A {@code BiConsumer} * @throws NullPointerException if {@code action} is null */ default void forEach(BiConsumer<K, V> action) { Objects.requireNonNull(action, "action is null"); for (Tuple2<K, V> t : this) { action.accept(t._1, t._2); } } }
package seedu.taskell.logic.commands; import java.util.HashSet; import java.util.Set; import seedu.taskell.commons.exceptions.IllegalValueException; import seedu.taskell.model.HistoryManager; import seedu.taskell.model.tag.Tag; import seedu.taskell.model.tag.UniqueTagList; import seedu.taskell.model.task.*; //@@author A0139257X /** * Adds a task to the task manager. */ public class AddCommand extends Command { public static final String COMMAND_WORD = "add"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Adds a task to the task manager. " + "Parameters: DESCRIPTION by/on[DATE] from[START_TIME] to[END_TIME] [p/PRIORITY] [r/daily] [#TAG]...\n" + "Example: " + COMMAND_WORD + " go for meeting on 1-1-2100 from 12.30AM to 12.45AM p/3 r/daily #work"; public static final String MESSAGE_SUCCESS = "New task added: %1$s"; public static final String MESSAGE_DUPLICATE_TASK = "This task already exists in the task manager"; private final Task toAdd; public AddCommand(String taskType, String[] taskComponentArray, boolean[] hasTaskComponentArray, Set<String> tags) throws IllegalValueException { final Set<Tag> tagSet = new HashSet<>(); for (String tagName : tags) { tagSet.add(new Tag(tagName)); } switch (taskType) { case Task.FLOATING_TASK: this.toAdd = new FloatingTask(taskComponentArray, hasTaskComponentArray, new UniqueTagList(tagSet)); break; case Task.EVENT_TASK: this.toAdd = new EventTask(taskComponentArray, hasTaskComponentArray, new UniqueTagList(tagSet)); break; default: toAdd = null; } } //@@author A0139257X-reused @Override public CommandResult execute() { assert model != null; try { model.addTask(toAdd); HistoryManager.getInstance().addTask(toAdd); jumpToNewTaskIndex(); return new CommandResult(String.format(MESSAGE_SUCCESS, toAdd)); } catch (UniqueTaskList.DuplicateTaskException e) { HistoryManager.getInstance().deleteLatestCommand(); return new CommandResult(MESSAGE_DUPLICATE_TASK); } } private void jumpToNewTaskIndex() { int indexOfNewTask = model.getFilteredTaskList().size()-1; jumpToIndex(indexOfNewTask); } }
package mytown.commands; import com.google.common.collect.ImmutableList; import mytown.api.interfaces.IFlagsContainer; import mytown.core.Localization; import mytown.core.command.CommandManager; import mytown.datasource.MyTownDatasource; import mytown.datasource.MyTownUniverse; import mytown.entities.*; import mytown.entities.flag.Flag; import mytown.entities.flag.FlagType; import mytown.proxies.DatasourceProxy; import mytown.proxies.EconomyProxy; import mytown.proxies.LocalizationProxy; import mytown.util.MyTownUtils; import mytown.util.exceptions.MyTownCommandException; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ChatComponentText; import java.util.*; /** * Base class for all classes that hold command methods... Mostly for some utils */ public abstract class Commands { protected Commands() { } public static MyTownDatasource getDatasource() { return DatasourceProxy.getDatasource(); } public static MyTownUniverse getUniverse() { return MyTownUniverse.instance; } public static Localization getLocal() { return LocalizationProxy.getLocalization(); } /** * Calls the method to which the set of arguments corresponds to. */ public static boolean callSubFunctions(ICommandSender sender, List<String> args, String callersPermNode) { List<String> subCommands = CommandManager.getSubCommandsList(callersPermNode); if (!args.isEmpty()) { for (String s : subCommands) { String name = CommandManager.commandNames.get(s); // Checking if name corresponds and if parent's if (name.equals(args.get(0)) && CommandManager.getParentPermNode(s).equals(callersPermNode)) { CommandManager.commandCall(s, sender, args.subList(1, args.size())); return true; } } } sendHelpMessage(sender, callersPermNode, null); return false; } public static void sendHelpMessage(ICommandSender sender, String permBase, List<String> args) { String node; if (args == null || args.isEmpty()) { node = permBase; } else { node = CommandManager.getPermissionNodeFromArgs(args, permBase); } String command = "/" + CommandManager.commandNames.get(permBase); if(args != null) { String prevNode = permBase; for (String s : args) { String t = CommandManager.getSubCommandNode(s, prevNode); if (t != null) { command += " " + s; prevNode = t; } else break; } } sendMessageBackToSender(sender, command); List<String> scList = CommandManager.getSubCommandsList(node); if (scList == null || scList.isEmpty()) { sendMessageBackToSender(sender, " " + getLocal().getLocalization(node + ".help")); } else { List<String> nameList = new ArrayList<String>(); for(String s : scList) { nameList.add(CommandManager.commandNames.get(s)); } Collections.sort(nameList); for (String s : nameList) { sendMessageBackToSender(sender, " " + s + ": " + getLocal().getLocalization(CommandManager.getSubCommandNode(s, node) + ".help")); } } } public static boolean firstPermissionBreach(String permission, ICommandSender sender) { if ("mytown.cmd".equals(permission)) return true; if (!(sender instanceof EntityPlayer)) return true; Resident res = getDatasource().getOrMakeResident(sender); Rank rank = res.getTownRank(res.getSelectedTown()); if (rank == null) { return true; } return rank.hasPermissionOrSuperPermission(permission); } /** * Populates the tab completion map. */ public static void populateCompletionMap() { List<String> populator = new ArrayList<String>(); populator.addAll(getUniverse().getTownsMap().keySet()); populator.add("@a"); CommandManager.completionMap.put("townCompletionAndAll", populator); populator = new ArrayList<String>(); populator.addAll(getUniverse().getTownsMap().keySet()); CommandManager.completionMap.put("townCompletion", populator); populator = new ArrayList<String>(); for (Resident res : getUniverse().getResidentsMap().values()) { populator.add(res.getPlayerName()); } CommandManager.completionMap.put("residentCompletion", populator); populator = new ArrayList<String>(); for (FlagType flag : FlagType.values()) { populator.add(flag.toString().toLowerCase()); } CommandManager.completionMap.put("flagCompletion", populator); populator = new ArrayList<String>(); for (FlagType flag : FlagType.values()) { if (flag.isWhitelistable()) populator.add(flag.toString().toLowerCase()); } CommandManager.completionMap.put("flagCompletionWhitelist", populator); populator.clear(); populator.addAll(Rank.defaultRanks.keySet()); CommandManager.completionMap.put("rankCompletion", populator); } public static Town getTownFromResident(Resident res) { Town town = res.getSelectedTown(); if (town == null) throw new MyTownCommandException("mytown.cmd.err.partOfTown"); return town; } public static Town getTownFromName(String name) { Town town = getUniverse().getTownsMap().get(name); if (town == null) throw new MyTownCommandException("mytown.cmd.err.town.notexist", name); return town; } public static Resident getResidentFromName(String playerName) { Resident res = getDatasource().getOrMakeResident(playerName); if (res == null) throw new MyTownCommandException("mytown.cmd.err.resident.notexist", playerName); return res; } public static Plot getPlotAtResident(Resident res) { Town town = getTownFromResident(res); Plot plot = town.getPlotAtResident(res); if (plot == null) throw new MyTownCommandException("mytown.cmd.err.plot.notInPlot"); return plot; } public static ImmutableList<Town> getInvitesFromResident(Resident res) { ImmutableList<Town> list = res.getInvites(); if (list == null || list.isEmpty()) throw new MyTownCommandException("mytown.cmd.err.invite.noinvitations"); return list; } public static Flag getFlagFromType(IFlagsContainer hasFlags, FlagType flagType) { Flag flag = hasFlags.getFlag(flagType); if (flag == null) throw new MyTownCommandException("mytown.cmd.err.flagNotExists", flagType.toString()); return flag; } public static Flag getFlagFromName(IFlagsContainer hasFlags, String name) { Flag flag; try { flag = hasFlags.getFlag(FlagType.valueOf(name.toUpperCase())); } catch (IllegalArgumentException ex) { throw new MyTownCommandException("mytown.cmd.err.flagNotExists", ex, name); } if (flag == null) throw new MyTownCommandException("mytown.cmd.err.flagNotExists", name); return flag; } public static TownBlock getBlockAtResident(Resident res) { TownBlock block = getDatasource().getBlock(res.getPlayer().dimension, ((int) res.getPlayer().posX) >> 4, ((int) res.getPlayer().posZ >> 4)); if (block == null) throw new MyTownCommandException("mytown.cmd.err.claim.notexist", res.getSelectedTown()); return block; } public static Rank getRankFromTown(Town town, String rankName) { Rank rank = town.getRank(rankName); if (rank == null) { throw new MyTownCommandException("mytown.cmd.err.rank.notexist", rankName, town.getName()); } return rank; } public static Rank getRankFromResident(Resident res) { Rank rank = res.getTownRank(); if (rank == null) { throw new MyTownCommandException("mytown.cmd.err.partOfTown"); } return rank; } public static Plot getPlotAtPosition(int dim, int x, int y, int z) { Town town = MyTownUtils.getTownAtPosition(dim, x >> 4, z >> 4); if (town == null) throw new MyTownCommandException("mytown.cmd.err.blockNotInPlot"); Plot plot = town.getPlotAtCoords(dim, x, y, z); if (plot == null) throw new MyTownCommandException("mytown.cmd.err.blockNotInPlot"); return plot; } public static FlagType getFlagTypeFromName(String name) { try { return FlagType.valueOf(name.toUpperCase()); } catch (IllegalArgumentException e) { throw new MyTownCommandException("mytown.cmd.err.flagNotExists", e, name); } } public static void sendMessageBackToSender(ICommandSender sender, String message) { if (sender instanceof EntityPlayer) { Resident res = getDatasource().getOrMakeResident(sender); res.sendMessage(message); } else { sender.addChatMessage(new ChatComponentText(message)); } } public static void makePayment(EntityPlayer player, int amount) { if(amount == 0) return; Resident res = DatasourceProxy.getDatasource().getOrMakeResident(player); if(!EconomyProxy.getEconomy().takeMoneyFromPlayer(player, amount)){ throw new MyTownCommandException("mytown.cmd.err.payment", EconomyProxy.getCurrency(amount)); } res.sendMessage(getLocal().getLocalization("mytown.notification.payment", EconomyProxy.getCurrency(amount))); } public static void makeRefund(EntityPlayer player, int amount) { if(amount == 0) return; Resident res = DatasourceProxy.getDatasource().getOrMakeResident(player); EconomyProxy.getEconomy().giveMoneyToPlayer(player, amount); res.sendMessage(getLocal().getLocalization("mytown.notification.refund", EconomyProxy.getCurrency(amount))); } }
package seedu.todo.controllers; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.joestelmach.natty.DateGroup; import com.joestelmach.natty.Parser; import seedu.todo.commons.EphemeralDB; import seedu.todo.models.Task; import seedu.todo.models.TodoListDB; import seedu.todo.ui.UiManager; import seedu.todo.ui.views.IndexView; public class UpdateController implements Controller { private static String NAME = "Update"; private static String DESCRIPTION = "Updates a task by listed index."; private static String COMMAND_SYNTAX = "update <index> <task> by <deadline>"; private static CommandDefinition commandDefinition = new CommandDefinition(NAME, DESCRIPTION, COMMAND_SYNTAX); public static CommandDefinition getCommandDefinition() { return commandDefinition; } @Override public float inputConfidence(String input) { // TODO return (input.startsWith("update")) ? 1 : 0; } @Override public void process(String args) { // TODO: Example of last minute work args = args.replaceFirst("update", "").trim(); // Get index. System.out.println(args); Matcher matcher = Pattern.compile("^\\d+").matcher(args); matcher.find(); String indexStr = matcher.group(); int index = Integer.decode(indexStr.trim()); // Parse name and date. args = args.replaceFirst(indexStr, "").trim(); String[] splitted = args.split("( at | by )", 2); String name = splitted[0].trim(); String naturalDate = splitted[1].trim(); // Parse natural date using Natty. Parser parser = new Parser(); List<DateGroup> groups = parser.parse(naturalDate); Date date = groups.get(0).getDates().get(0); LocalDateTime ldt = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); // Get record EphemeralDB edb = EphemeralDB.getInstance(); Task task = edb.getTaskByDisplayedId(index); TodoListDB db = TodoListDB.getInstance(); if (task != null) { task.setName(name); task.setCalendarDT(ldt); db.save(); } // Re-render IndexView view = UiManager.loadView(IndexView.class); view.tasks = db.getAllTasks(); view.render(); } }
package net.pwall.json; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Objects; /** * A JSON array. * * @author Peter Wall */ public class JSONArray extends ArrayList<JSONValue> implements JSONComposite { private static final long serialVersionUID = -6963671812529472759L; /** * Construct an empty JSON array. */ public JSONArray() { } /** * Construct a JSON array by copying another JSON array. * * @param array the source {@code JSONArray} * @throws NullPointerException if the collection is {@code null} */ public JSONArray(JSONValue[] array) { for (JSONValue item : Objects.requireNonNull(array)) add(item); } /** * Construct a JSON array from a {@link Collection} of JSON values. * * @param collection the source {@link Collection} * @throws NullPointerException if the collection is {@code null} */ public JSONArray(Collection<JSONValue> collection) { super(collection); } /** * Add a {@link JSONString} to the JSON array representing the supplied {@link CharSequence} * ({@link String}, {@link StringBuilder} etc.). * * @param cs the {@link CharSequence} * @return {@code this} (for chaining) * @throws NullPointerException if the value is {@code null} */ public JSONArray addValue(CharSequence cs) { add(new JSONString(cs)); return this; } /** * Add a {@link JSONInteger} to the JSON array representing the supplied {@code int}. * * @param value the value * @return {@code this} (for chaining) */ public JSONArray addValue(int value) { add(JSONInteger.valueOf(value)); return this; } /** * Add a {@link JSONLong} to the JSON array representing the supplied {@code long}. * * @param value the value * @return {@code this} (for chaining) */ public JSONArray addValue(long value) { add(JSONLong.valueOf(value)); return this; } /** * Add a {@link JSONFloat} to the JSON array representing the supplied {@code float}. * * @param value the value * @return {@code this} (for chaining) */ public JSONArray addValue(float value) { add(JSONFloat.valueOf(value)); return this; } /** * Add a {@link JSONDouble} to the JSON array representing the supplied {@code double}. * * @param value the value * @return {@code this} (for chaining) */ public JSONArray addValue(double value) { add(JSONDouble.valueOf(value)); return this; } public JSONArray addJSONValues(Collection<JSONValue> collection) { for (JSONValue value : collection) add(value); return this; } public JSONArray addJSONValues(JSONValue[] array) { for (int i = 0, n = array.length; i < n; i++) add(array[i]); return this; } public <T extends CharSequence> JSONArray addValues(Collection<T> collection) { for (CharSequence value : collection) addValue(value); return this; } public <T extends CharSequence> JSONArray addValues(T[] array) { for (int i = 0, n = array.length; i < n; i++) addValue(array[i]); return this; } // /** // * Add a {@link JSONNumber} to the JSON array representing the supplied {@link Number}. // * // * @param value the value // * @return {@code this} (for chaining) // * @throws NullPointerException if the value is {@code null} // */ // public JSONArray addValue(Number value) { // add(new JSONNumber(value)); // return this; /** * Add a {@link JSONBoolean} to the JSON array representing the supplied {@code boolean}. * * @param value the value * @return {@code this} (for chaining) */ public JSONArray addValue(boolean value) { add(JSONBoolean.valueOf(value)); return this; } /** * Add a {@link JSONBoolean} to the JSON array representing the supplied {@link Boolean}. * * @param value the value * @return {@code this} (for chaining) * @throws NullPointerException if the value is {@code null} */ public JSONArray addValue(Boolean value) { add(JSONBoolean.valueOf(Objects.requireNonNull(value).booleanValue())); return this; } /** * Add a {@code null} value to the JSON array. * * @return {@code this} (for chaining) */ public JSONArray addNull() { add(null); return this; } public String getString(int index) { return JSON.getString(get(index)); } public int getInt(int index) { return JSON.getInt(get(index)); } public long getLong(int index) { return JSON.getLong(get(index)); } public float getFloat(int index) { return JSON.getFloat(get(index)); } public double getDouble(int index) { return JSON.getDouble(get(index)); } public boolean getBoolean(int index) { return JSON.getBoolean(get(index)); } public JSONArray getArray(int index) { return JSON.getArray(get(index)); } public JSONObject getObject(int index) { return JSON.getObject(get(index)); } /** * Create the external representation for this JSON array. * * @return the JSON representation for this array * @see JSONValue#toJSON() */ @Override public String toJSON() { int estimate = size() * 20; StringBuilder sb = new StringBuilder(estimate); try { appendJSON(sb); } catch (IOException e) { // can't happen - StringBuilder does not throw IOException } return sb.toString(); } /** * Append the external representation for this JSON array to a given {@link Appendable}. * * @param a the {@link Appendable} * @throws IOException if thrown by the {@link Appendable} * @see JSONValue#appendJSON(Appendable) */ @Override public void appendJSON(Appendable a) throws IOException { a.append('['); if (size() > 0) { int i = 0; for (;;) { JSON.appendJSON(a, get(i++)); if (i >= size()) break; a.append(','); } } a.append(']'); } /** * Test whether the composite is "simple", i.e. it contains only non-composite values (to * assist with formatting). * * @return {@code true} if the composite is simple * @see JSONComposite#isSimple() */ @Override public boolean isSimple() { for (int i = 0; i < size(); i++) if (get(i) instanceof JSONComposite) return false; return true; } /** * Return a string representation of the JSON array. This is the same as the JSON format. * * @return the JSON string */ @Override public String toString() { return toJSON(); } /** * Compare two JSON arrays for equality. * * @param other the other JSON array * @return {@code true} if the other object is a JSON array and the contents are equal */ @Override public boolean equals(Object other) { return other instanceof JSONArray && super.equals(other); } /** * Convenience method to create a {@code JSONArray}. Supports the idiom: * <pre> * JSONArray arr = JSONArray.create().addValue(0).addValue(1).addValue(2); * </pre> * * @return the new {@code JSONArray} */ public static JSONArray create() { return new JSONArray(); } }
package org.asu.apmg; import hudson.EnvVars; import hudson.Extension; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Builder; import org.apache.commons.io.FileUtils; import org.kohsuke.stapler.DataBoundConstructor; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Properties; /** * @author aesanch2 */ public class APMGBuilder extends Builder { private APMGGit git; private boolean rollbackEnabled, updatePackageEnabled; // Fields in config.jelly must match the parameter names in the "DataBoundConstructor" @DataBoundConstructor public APMGBuilder(Boolean rollbackEnabled, Boolean updatePackageEnabled) { this.rollbackEnabled = rollbackEnabled; this.updatePackageEnabled = updatePackageEnabled; } @Override public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) { String newCommit; String prevCommit; String workspaceDirectory; String jobName; String buildNumber; String jenkinsHome; ArrayList<String> listOfDestructions, listOfUpdates; ArrayList<APMGMetadataObject> members; try{ //Load our environment variables for the job EnvVars envVars = build.getEnvironment(listener); newCommit = envVars.get("GIT_COMMIT"); workspaceDirectory = envVars.get("WORKSPACE"); jobName = envVars.get("JOB_NAME"); buildNumber = envVars.get("BUILD_NUMBER"); jenkinsHome = envVars.get("JENKINS_HOME"); //Create a deployment space for this job within the workspace File deployStage = new File(workspaceDirectory + "/apmg"); if(deployStage.exists()){ FileUtils.deleteDirectory(deployStage); }deployStage.mkdirs(); //Set up our repository connection String pathToRepo = workspaceDirectory + "/.git"; //Read this job's property file and setup the appropriate APMGGit wrapper String jobRoot = jenkinsHome + "/jobs/"; File lastSuccess = new File(jobRoot + jobName + "/lastSuccessful/apmgBuilder.properties"); File newSuccess = new File(jobRoot + jobName + "/builds/" + buildNumber + "/apmgBuilder.properties"); OutputStream output = new FileOutputStream(newSuccess); Properties jobProperties = new Properties(); if (lastSuccess.exists() && !lastSuccess.isDirectory()){ jobProperties.load(new FileInputStream(lastSuccess)); prevCommit = jobProperties.getProperty("LAST_SUCCESSFUL_COMMIT"); git = new APMGGit(pathToRepo, prevCommit, newCommit); } //This was the initial commit to the repo or the first build else{ prevCommit = null; git = new APMGGit(pathToRepo, newCommit); } //Get our lists listOfDestructions = git.getDeletions(); listOfUpdates = git.getNewChangeSet(); //Generate the manifests members = APMGUtility.generateManifests(listOfDestructions, listOfUpdates, deployStage.getPath()); listener.getLogger().println("APMG created deployment package."); //Copy the files to the deployStage APMGUtility.replicateMembers(members, workspaceDirectory, deployStage.getPath()); //Check for rollback if (getRollbackEnabled() && prevCommit != null){ String rollbackDirectory = newSuccess.getParent() + "/rollback"; File rollbackStage = new File(rollbackDirectory); if(rollbackStage.exists()){ FileUtils.deleteDirectory(rollbackStage); }rollbackStage.mkdirs(); //Get our lists ArrayList<String> listOfOldItems = git.getOldChangeSet(); ArrayList<String> listOfAdditions = git.getAdditions(); //Generate the manifests for the rollback package ArrayList<APMGMetadataObject> rollbackMembers = APMGUtility.generateManifests(listOfAdditions, listOfOldItems, rollbackDirectory); //Copy the files to the rollbackStage and zip up the rollback stage git.getPrevCommitFiles(rollbackMembers, rollbackDirectory); APMGUtility.zipRollbackPackage(rollbackDirectory, jobName, buildNumber); listener.getLogger().println("APMG created rollback package."); } //Check to see if we need to update the repository's package.xml file if(updatePackageEnabled){ boolean updateRequired = git.updatePackageXML(workspaceDirectory + "/src/package.xml"); if (updateRequired) listener.getLogger().println("APMG updated repository package.xml file."); } //Store the commit jobProperties.setProperty("LAST_SUCCESSFUL_COMMIT", newCommit); jobProperties.store(output, null); }catch(Exception e){ e.printStackTrace(listener.getLogger()); return false; } return true; } // Overridden for better type safety. // If your plugin doesn't really define any property on Descriptor, // you don't have to do this. @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl)super.getDescriptor(); } /** * Descriptor for {@link APMGBuilder}. Used as a singleton. * The class is marked as public so that it can be accessed from views. */ @Extension // This indicates to Jenkins that this is an implementation of an extension point. public static final class DescriptorImpl extends BuildStepDescriptor<Builder> { /** * In order to load the persisted global configuration, you have to * call load() in the constructor. */ public DescriptorImpl() { load(); } public boolean isApplicable(Class<? extends AbstractProject> aClass) { // Indicates that this builder can be used with all kinds of project types return true; } /** * This human readable name is used in the configuration screen. */ public String getDisplayName() { return "APMG"; } } public boolean getRollbackEnabled() { return rollbackEnabled;} public boolean getUpdatePackageEnabled() {return updatePackageEnabled; } }
package uk.co.eluinhost.ultrahardcore; import com.google.inject.AbstractModule; import org.bukkit.plugin.Plugin; import uk.co.eluinhost.commands.CommandHandler; import uk.co.eluinhost.commands.CommandMap; import uk.co.eluinhost.commands.RealCommandHandler; import uk.co.eluinhost.commands.RealCommandMap; import uk.co.eluinhost.configuration.ConfigManager; import uk.co.eluinhost.configuration.RealConfigManager; import uk.co.eluinhost.features.FeatureManager; import uk.co.eluinhost.features.RealFeatureManager; import uk.co.eluinhost.ultrahardcore.borders.BorderTypeManager; import uk.co.eluinhost.ultrahardcore.borders.RealBorderTypeManager; import uk.co.eluinhost.ultrahardcore.scatter.FallProtector; import uk.co.eluinhost.ultrahardcore.scatter.Protector; public class UHCModule extends AbstractModule { private final Plugin m_plugin; /** * Guice bindings * @param plugin the plugin to run for */ public UHCModule(Plugin plugin){ m_plugin = plugin; } @SuppressWarnings("OverlyCoupledMethod") @Override protected void configure() { bind(Plugin.class).toInstance(m_plugin); //bind(Logger.class).toInstance(m_plugin.getLogger()); bind(CommandHandler.class).to(RealCommandHandler.class); bind(CommandMap.class).to(RealCommandMap.class); bind(ConfigManager.class).to(RealConfigManager.class); bind(FeatureManager.class).to(RealFeatureManager.class); bind(BorderTypeManager.class).to(RealBorderTypeManager.class); bind(Protector.class).to(FallProtector.class); } }
package org.cri.redmetrics.db; import com.j256.ormlite.jdbc.JdbcConnectionSource; import org.cri.redmetrics.model.*; import java.sql.SQLException; public class Db { public static final String URL = "jdbc:postgresql://localhost:5432/redmetrics"; public static final Class[] ENTITY_TYPES = { Address.class, Event.class, Snapshot.class, Game.class, GameVersion.class, Group.class, Player.class}; public static JdbcConnectionSource newConnectionSource() throws SQLException { return new JdbcConnectionSource(URL, DbUser.NAME, DbUser.PASSWORD); } }
package org.graylog2; import org.json.simple.JSONValue; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.zip.GZIPOutputStream; public class GelfMessage { private static final String ID_NAME = "id"; private static final String GELF_VERSION = "1.0"; private static final byte[] GELF_CHUNKED_ID = new byte[]{0x1e, 0x0f}; private static final int MAXIMUM_CHUNK_SIZE = 1420; private static final BigDecimal TIME_DIVISOR = new BigDecimal(1000); private String version = GELF_VERSION; private String host; private byte[] hostBytes = lastFourAsciiBytes("none"); private String shortMessage; private String fullMessage; private long javaTimestamp; private String level; private String facility = "gelf-java"; private String line; private String file; private Map<String, Object> additonalFields = new HashMap<String, Object>(); public GelfMessage() { } public GelfMessage(String shortMessage, String fullMessage, long timestamp, String level) { this(shortMessage, fullMessage, timestamp, level, null, null); } public GelfMessage(String shortMessage, String fullMessage, Long timestamp, String level, String line, String file) { this.shortMessage = shortMessage; this.fullMessage = fullMessage; this.javaTimestamp = timestamp; this.level = level; this.line = line; this.file = file; } public String toJson() { Map<String, Object> map = new HashMap<String, Object>(); map.put("version", getVersion()); map.put("host", getHost()); map.put("short_message", getShortMessage()); map.put("full_message", getFullMessage()); map.put("timestamp", getTimestamp()); map.put("level", getLevel()); map.put("facility", getFacility()); if( null != getFile() ) { map.put("file", getFile()); } if( null != getLine() ) { map.put("line", getLine()); } for (Map.Entry<String, Object> additionalField : additonalFields.entrySet()) { if (!ID_NAME.equals(additionalField.getKey())) { map.put("_" + additionalField.getKey(), additionalField.getValue()); } } return JSONValue.toJSONString(map); } public ByteBuffer[] toDatagrams() { byte[] messageBytes = gzipMessage( toJson() ); ByteBuffer[] datagrams = new ByteBuffer[ messageBytes.length / MAXIMUM_CHUNK_SIZE + 1 ]; if ( messageBytes.length > MAXIMUM_CHUNK_SIZE ) { sliceDatagrams( messageBytes, datagrams ); } else { datagrams[0] = ByteBuffer.allocate( messageBytes.length ); datagrams[0].put( messageBytes ); datagrams[0].flip(); } return datagrams; } private void sliceDatagrams(byte[] messageBytes, ByteBuffer[] datagrams) { int messageLength = messageBytes.length; byte[] messageId = ByteBuffer.allocate(8) .putInt(getCurrentMillis()) // 4 least-significant-bytes of the time in millis .put(hostBytes) // 4 least-significant-bytes of the host .array(); int num = ((Double) Math.ceil((double) messageLength / MAXIMUM_CHUNK_SIZE)).intValue(); for (int idx = 0; idx < num; idx++) { byte[] header = concatByteArray(GELF_CHUNKED_ID, concatByteArray(messageId, new byte[]{(byte) idx, (byte) num})); int from = idx * MAXIMUM_CHUNK_SIZE; int to = from + MAXIMUM_CHUNK_SIZE; if (to >= messageLength) { to = messageLength; } byte[] datagram = concatByteArray( header, Arrays.copyOfRange( messageBytes, from, to ) ); datagrams[idx] = ByteBuffer.allocate( datagram.length ); datagrams[idx].put(datagram); datagrams[idx].flip(); } } public int getCurrentMillis() { return (int) System.currentTimeMillis(); } private byte[] gzipMessage(String message) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { GZIPOutputStream stream = new GZIPOutputStream(bos); byte[] bytes = null; try { bytes = message.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("No UTF-8 support available.", e); } stream.write(bytes); stream.finish(); stream.close(); byte[] zipped = bos.toByteArray(); bos.close(); return zipped; } catch (IOException e) { return null; } } private byte[] lastFourAsciiBytes(String host) { final String shortHost = host.length() >= 4 ? host.substring(host.length() - 4) : host; try { return shortHost.getBytes("ASCII"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("JVM without ascii support?", e); } } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getHost() { return host; } public void setHost(String host) { this.host = host; this.hostBytes = lastFourAsciiBytes(host); } public String getShortMessage() { return shortMessage; } public void setShortMessage(String shortMessage) { this.shortMessage = shortMessage; } public String getFullMessage() { return fullMessage; } public void setFullMessage(String fullMessage) { this.fullMessage = fullMessage; } public String getTimestamp() { return new BigDecimal(javaTimestamp).divide(TIME_DIVISOR).toPlainString(); } public Long getJavaTimestamp() { return javaTimestamp; } public void setJavaTimestamp(long javaTimestamp) { this.javaTimestamp = javaTimestamp; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public String getFacility() { return facility; } public void setFacility(String facility) { this.facility = facility; } public String getLine() { return line; } public void setLine(String line) { this.line = line; } public String getFile() { return file; } public void setFile(String file) { this.file = file; } public GelfMessage addField(String key, String value) { getAdditonalFields().put(key, value); return this; } public GelfMessage addField(String key, Object value) { getAdditonalFields().put(key, value); return this; } public Map<String, Object> getAdditonalFields() { return additonalFields; } public void setAdditonalFields(Map<String, Object> additonalFields) { this.additonalFields = additonalFields; } public boolean isValid() { return !isEmpty(version) && !isEmpty(host) && !isEmpty(shortMessage) && !isEmpty(facility); } public boolean isEmpty(String str) { return str == null || "".equals(str.trim()); } private byte[] concatByteArray(byte[] first, byte[] second) { byte[] result = Arrays.copyOf(first, first.length + second.length); System.arraycopy(second, 0, result, first.length, second.length); return result; } }
package org.hcjf.service; import org.hcjf.errors.HCJFRuntimeException; import org.hcjf.errors.HCJFServiceTimeoutException; import org.hcjf.log.Log; import org.hcjf.log.debug.Agent; import org.hcjf.log.debug.Agents; import org.hcjf.properties.SystemProperties; import java.util.*; import java.util.concurrent.*; /** * This abstract class contains all the implementations and * the interfaces that describe the behavior of the system service. * @author javaito */ public abstract class Service<C extends ServiceConsumer> { protected static final String SERVICE_LOG_TAG = "SERVICE"; private static final String MAIN_EXECUTOR_NAME = "Main Thread Pool %s"; private final String serviceName; private final ThreadFactory serviceThreadFactory; private final ThreadPoolExecutor serviceExecutor; private final Map<String, ThreadPoolExecutor> registeredExecutors; private final Integer priority; /** * Service constructor. * @param serviceName Name of the service, can't be null. * @param priority Service execution priority. * @throws NullPointerException If the name is null. */ protected Service(String serviceName, Integer priority) { if(serviceName == null) { throw new NullPointerException("Service name can't be null"); } if(SystemServices.instance.exist(serviceName)) { throw new IllegalArgumentException("The service name (" + serviceName + ") is already register"); } this.serviceName = serviceName; this.priority = priority; this.serviceThreadFactory = createThreadFactory(); this.serviceExecutor = (ThreadPoolExecutor) Executors.newCachedThreadPool(this.serviceThreadFactory); this.serviceExecutor.setCorePoolSize(SystemProperties.getInteger(SystemProperties.Service.THREAD_POOL_CORE_SIZE)); this.serviceExecutor.setMaximumPoolSize(SystemProperties.getInteger(SystemProperties.Service.THREAD_POOL_MAX_SIZE)); this.serviceExecutor.setKeepAliveTime(SystemProperties.getLong(SystemProperties.Service.THREAD_POOL_KEEP_ALIVE_TIME), TimeUnit.SECONDS); this.registeredExecutors = new HashMap<>(); init(); if(!getClass().equals(Log.class)) { SystemServices.instance.register(this); } else { SystemServices.instance.setLog((Log)this); } Agents.register(new ThreadPoolAgent(String.format(MAIN_EXECUTOR_NAME, serviceName), serviceExecutor)); } /** * Create the default thread factory for any service. * @return Thread factory. */ protected ThreadFactory createThreadFactory() { return r -> new ServiceThread(this, r, getServiceName() + UUID.randomUUID()); } /** * Return the internal thread pool threadPoolExecutor of the service. * @return Thread pool threadPoolExecutor. */ private ThreadPoolExecutor getServiceExecutor() { return serviceExecutor; } /** * This method execute any callable over service thread with a service session. * @param callable Callable to execute. * @param <R> Expected result. * @return Callable's future. */ protected final <R extends Object> Future<R> fork(Callable<R> callable) { return fork(callable, null, getServiceExecutor()); } /** * This method register a new thread pool executor into the service instance. * @param executorName Executor name. * @param executor Executor instance. */ private void registerExecutor(String executorName, ThreadPoolExecutor executor) { if(!executor.equals(serviceExecutor)) { if(executorName == null) { throw new NullPointerException("Executor name is null"); } synchronized (this) { if (!registeredExecutors.containsKey(executorName)) { registeredExecutors.put(executorName, executor); Agents.register(new ThreadPoolAgent(executorName, executor)); } } } } /** * Returns the service session instance. If the current thread is not a service thread instance then the session * instance is the guest session instance. * @return Service session instance. */ private ServiceSession getSession() { ServiceSession session = ServiceSession.getGuestSession(); if(Thread.currentThread() instanceof ServiceThread) { session = ((ServiceThread) Thread.currentThread()).getSession(); } return session; } /** * Returns the invoker properties. * @return Invoker properties. */ private Map<String,Object> getInvokerProperties() { Map<String,Object> result = null; if(Thread.currentThread() instanceof ServiceThread) { result = getSession().getProperties(); } return result; } /** * This method execute any callable over service thread with a service session using an * custom thread pool threadPoolExecutor. This thread pool threadPoolExecutor must create only Service thread implementations. * @param callable Callable to execute. * @param executorName Name of the executor. * @param executor Custom thread pool threadPoolExecutor. * @param <R> Expected return type. * @return Callable's future. */ protected final <R extends Object> Future<R> fork(Callable<R> callable, String executorName, ThreadPoolExecutor executor) { registerExecutor(executorName, executor); return executor.submit(new CallableWrapper<>(callable, getSession(), getInvokerProperties())); } /** * This method execute any runnable over service thread with a service session. * @param runnable Runnable to execute. * @return Runnable's future. */ protected final Future fork(Runnable runnable) { return fork(runnable, null, getServiceExecutor()); } /** * This method execute any runnnable over service thread with a service session using an * custom thread pool threadPoolExecutor. This thread pool threadPoolExecutor must create only Service thread implementations. * @param runnable Runnable to execute. * @param executorName Name of the executor. * @param executor Custom thread pool threadPoolExecutor. * @return Runnable's future. */ protected final Future fork(Runnable runnable, String executorName, ThreadPoolExecutor executor) { registerExecutor(executorName, executor); return executor.submit(new RunnableWrapper(runnable, getSession(), getInvokerProperties())); } /** * Return the service name. * @return Service name. */ public final String getServiceName() { return serviceName; } /** * Return the service priority. * @return Service priority. */ public final Integer getPriority() { return priority; } /** * This method will be called immediately after * of the execution of the service's constructor method */ protected void init(){} /** * This method will be called for the global shutdown process * in each stage. * @param stage Shutdown stage. */ protected void shutdown(ShutdownStage stage) {} /** * This method will be called for the global shutdown process * when the process try to finalize the registered thread pool executors. * @param executor Thread pool threadPoolExecutor to finalize. */ protected void shutdownExecutor(ThreadPoolExecutor executor) { long shutdownTimeout = SystemProperties.getLong(SystemProperties.Service.SHUTDOWN_TIME_OUT); //In the first attempt the shutdown procedure wait for all the thread //ends naturally. executor.shutdown(); long startTime = System.currentTimeMillis(); while (!executor.isTerminated() && (System.currentTimeMillis() - startTime) < shutdownTimeout) { try { Thread.sleep(100); } catch (InterruptedException e) { break; } } if(!executor.isTerminated()) { //If some threads does not ends naturally then the shutdown procedure //send the interrupt signal for all the pool. executor.shutdownNow(); startTime = System.currentTimeMillis(); while (!executor.isTerminated() && (System.currentTimeMillis() - startTime) < shutdownTimeout) { try { Thread.sleep(100); } catch (InterruptedException e) { break; } } } } /** * This method register the consumer in the service. * @param consumer Object with the logic to consume the service. * @throws RuntimeException It contains exceptions generated by * the particular logic of each implementation. */ public abstract void registerConsumer(C consumer); /** * Unregister a specific consumer. * @param consumer Consumer to unregister. */ public abstract void unregisterConsumer(C consumer); /** * This method start the global shutdown process. */ public static final void systemShutdown() { SystemServices.instance.shutdown(); } /** * This method is the gateway to the service subsystem from context out of * the hcjf domain. * @param runnable Custom runnable. * @param session Custom session. */ public static final void run(Runnable runnable, ServiceSession session) { run(runnable, session, false, 0); } /** * This method is the gateway to the service subsystem from context out of * the hcjf domain. * @param runnable Custom runnable. * @param session Custom session. * @param waitFor Wait fot the execution ends. * @param timeout Wait time out, if this value is lower than 0 then the timeout is infinite. */ public static final void run(Runnable runnable, ServiceSession session, boolean waitFor, long timeout) { RunnableWrapper serviceRunnable = new RunnableWrapper(runnable, session.getClone()); Future future = SystemServices.instance.serviceExecutor.submit(serviceRunnable); if(waitFor) { try { if(timeout > 0) { future.get(timeout, TimeUnit.MILLISECONDS); } else { future.get(); } } catch (TimeoutException ex) { future.cancel(true); throw new HCJFServiceTimeoutException("Service run timout", ex); } catch (Exception ex) { throw new HCJFRuntimeException("Service run fail", ex); } } } /** * This method execute a callable instance and wait for the response. * @param callable Callable instance. * @param serviceSession Service session. * @param <O> Expected response. * @return Result instance. */ public static final <O extends Object> O call(Callable<O> callable, ServiceSession serviceSession) { return call(callable, serviceSession, 0); } /** * This method execute a callable instance and wait for the response. * @param callable Callable instance. * @param serviceSession Service session. * @param timeout Max time for the execution. * @param <O> Expected response. * @return Result instance. */ public static final <O extends Object> O call(Callable<O> callable, ServiceSession serviceSession, long timeout) { O result; CallableWrapper callableWrapper = new CallableWrapper(callable, serviceSession.getClone()); Future<O> future = SystemServices.instance.serviceExecutor.submit(callableWrapper); try { if (timeout > 0) { result = future.get(timeout, TimeUnit.MILLISECONDS); } else { result = future.get(); } } catch (TimeoutException ex) { future.cancel(true); throw new HCJFServiceTimeoutException("Service call timout", ex); } catch (Exception ex) { throw new HCJFRuntimeException("Service call fail", ex); } return result; } /** * This internal class contains all the services registered * in the system. */ private static class SystemServices { private static final SystemServices instance; static { instance = new SystemServices(); } private final ThreadPoolExecutor serviceExecutor; private final Map<String, Service> services; private Log log; /** * Constructor. */ private SystemServices() { this.serviceExecutor = (ThreadPoolExecutor) Executors.newCachedThreadPool( runnable -> new StaticServiceThread(runnable, SystemProperties.get(SystemProperties.Service.STATIC_THREAD_NAME))); this.serviceExecutor.setCorePoolSize(SystemProperties.getInteger(SystemProperties.Service.STATIC_THREAD_POOL_CORE_SIZE)); this.serviceExecutor.setMaximumPoolSize(SystemProperties.getInteger(SystemProperties.Service.STATIC_THREAD_POOL_MAX_SIZE)); this.serviceExecutor.setKeepAliveTime(SystemProperties.getLong(SystemProperties.Service.STATIC_THREAD_POOL_KEEP_ALIVE_TIME), TimeUnit.SECONDS); services = new HashMap<>(); //Adding service shutdown hook Runtime.getRuntime().addShutdownHook(new Thread(() -> shutdown())); } /** * Set the unique instance of the system log service. * @param log Instance of the system log. */ public void setLog(Log log) { this.log = log; } /** * This method save the instance of the service in the internal * map indexed by the name of the service. * @param service Instance of the service. */ private void register(Service service) { services.put(service.getServiceName(), service); Log.i(Service.SERVICE_LOG_TAG, "Service registered: %s", service.getServiceName()); } /** * Return true if the service name exist in the registered services. * @param serviceName Name of the service. * @return Return true if exist and false in otherwise */ private boolean exist(String serviceName) { return services.containsKey(serviceName); } /** * Start the shutdown process for all the services registered */ private void shutdown() { Set<Service> sortedServices = new TreeSet<>((s1, s2) -> { int result = s1.getPriority() - s2.getPriority(); if(result == 0) { result = s1.hashCode() - s2.hashCode(); } return result * -1; }); int errors = 0; Log.i(Service.SERVICE_LOG_TAG, "Starting shutdown"); sortedServices.addAll(services.values()); for(Service<?> service : sortedServices) { Log.i(Service.SERVICE_LOG_TAG, "Starting service shutdown (%s)", service.getServiceName()); Log.i(Service.SERVICE_LOG_TAG, "Starting service shutdown custom process"); try { service.shutdown(ShutdownStage.START); Log.i(Service.SERVICE_LOG_TAG, "Start stage: Shutdown custom process done"); } catch (Exception ex) { Log.i(Service.SERVICE_LOG_TAG, "Start stage: Shutdown custom process done with errors", ex); errors++; } Log.i(Service.SERVICE_LOG_TAG, "Ending custom executors"); service.registeredExecutors.values().forEach(service::shutdownExecutor); Log.i(Service.SERVICE_LOG_TAG, "Custom executors finalized"); try { service.shutdown(ShutdownStage.END); Log.i(Service.SERVICE_LOG_TAG, "End stage: Shutdown custom process done"); } catch (Exception ex) { Log.i(Service.SERVICE_LOG_TAG, "End stage: Shutdown custom process done with errors", ex); errors++; } Log.i(Service.SERVICE_LOG_TAG, "Ending main service threadPoolExecutor"); service.shutdownExecutor(serviceExecutor); Log.i(Service.SERVICE_LOG_TAG, "Main service threadPoolExecutor finalized"); } try { Thread.sleep(1000); } catch (InterruptedException e) {} try { ((Service)log).shutdown(ShutdownStage.START); log.shutdownExecutor(serviceExecutor); ((Service)log).shutdown(ShutdownStage.END); } catch (Exception ex) { errors++; } System.out.println("Shutdown completed! See you"); Runtime.getRuntime().halt(errors); } } public final static class StaticServiceThread extends ServiceThread { private StaticServiceThread(Runnable target, String name) { super(target, name); } } /** * Enum all the shutting down stages */ protected enum ShutdownStage { START, END } /** * This comparator gets priority to service runnable. */ public static class RunnableWrapperComparator implements Comparator<Runnable> { @Override public int compare(Runnable o1, Runnable o2) { int result = (int)(((RunnableWrapper)o1).creationTime - ((RunnableWrapper)o2).creationTime) * -1; if(result == 0) { result = o1.hashCode() - o2.hashCode(); } return result; } } /** * This wrapper encapsulate any other runnable in order to set the environment * session on the service thread. */ private static class RunnableWrapper implements Runnable { private final Runnable runnable; private final ServiceSession session; private final Map<String, Object> invokerProperties; private final long creationTime; public RunnableWrapper(Runnable runnable, ServiceSession session) { this(runnable, session, new HashMap<>()); } public RunnableWrapper(Runnable runnable, ServiceSession session, Map<String, Object> invokerProperties) { this.runnable = runnable; this.invokerProperties = invokerProperties; this.creationTime = System.currentTimeMillis(); if(session != null) { this.session = session; } else { this.session = ServiceSession.getGuestSession(); } } @Override public void run() { if(!(Thread.currentThread() instanceof ServiceThread)) { throw new IllegalArgumentException("All the service executions must be over ServiceThread implementation"); } try { ((ServiceThread) Thread.currentThread()).setSession(session); if(invokerProperties != null) { session.putAll(invokerProperties); } runnable.run(); } finally { ((ServiceThread) Thread.currentThread()).setSession(null); } } } /** * This wrapper encapsulate any other callable in order to set the environment * session on the service thread. */ private static class CallableWrapper<O extends Object> implements Callable<O> { private final Callable<O> callable; private final ServiceSession session; private final Map<String, Object> invokerProperties; public CallableWrapper(Callable<O> callable, ServiceSession session) { this(callable, session, new HashMap<>()); } public CallableWrapper(Callable<O> callable, ServiceSession session, Map<String, Object> invokerProperties) { this.callable = callable; this.invokerProperties = invokerProperties; if(session != null) { this.session = session; } else { this.session = ServiceSession.getGuestSession(); } } @Override public O call() throws Exception { if(!(Thread.currentThread() instanceof ServiceThread)) { throw new IllegalArgumentException("All the service executions must be over ServiceThread implementation"); } try { ((ServiceThread) Thread.currentThread()).setSession(session); if(invokerProperties != null) { session.putAll(invokerProperties); } return callable.call(); } finally { ((ServiceThread) Thread.currentThread()).setSession(null); } } } public interface ThreadPoolAgentMBean { long getActiveCount(); long getCompletedTaskCount(); long getTaskCount(); int getCorePoolSize(); int getMaximumPoolSize(); int getLargestPoolSize(); int getPoolSize(); } public static class ThreadPoolAgent extends Agent implements ThreadPoolAgentMBean { private static final String PACKAGE_NAME = Service.class.getPackageName(); private final ThreadPoolExecutor threadPoolExecutor; public ThreadPoolAgent(String name, ThreadPoolExecutor threadPoolExecutor) { super(name, PACKAGE_NAME); this.threadPoolExecutor = threadPoolExecutor; } @Override public long getActiveCount() { return threadPoolExecutor.getActiveCount(); } @Override public long getCompletedTaskCount() { return threadPoolExecutor.getCompletedTaskCount(); } @Override public long getTaskCount() { return threadPoolExecutor.getTaskCount(); } @Override public int getCorePoolSize() { return threadPoolExecutor.getCorePoolSize(); } @Override public int getMaximumPoolSize() { return threadPoolExecutor.getMaximumPoolSize(); } @Override public int getLargestPoolSize() { return threadPoolExecutor.getLargestPoolSize(); } @Override public int getPoolSize() { return threadPoolExecutor.getPoolSize(); } } }
package org.jasonnet.logln; import java.io.PrintStream; import java.util.Date; import java.lang.reflect.Field; import java.text.SimpleDateFormat; /** * A set of helper functions for logging progress of a * program. These functions make a point of logging the line * number of the calling code. * * @author jasonnet (1/26/2015) */ public class Logln { final static PrintStream ps; static { String fn = System.getenv().get("LOGLN_FILE"); if (fn!=null) { try { ps = new PrintStream( new java.io.FileOutputStream(fn)); } catch (java.io.IOException exc) { throw new RuntimeException(exc); } } else { ps = System.out; } } /** * hiding default constructor by declaring it private. * * @author jasonnet (1/269/2015) */ private Logln() { } /** * A simple static logging method that prefixes the log line * with the file name and linenumber of the caller. It also * indents the message by the depth of caller on the stack. * * One can facilitate calling this routine by including a * <pre> * import static org.jasonnet.logln.Logln.logln; * </pre> * at the top of the source java file. * * @author jasonnet (01/26/2015) * * @param msg the diagnostic message to display */ public static void logln( String msg) { StackTraceElement els[] = Thread.currentThread().getStackTrace(); _logln(msg, els, null); } /** * This is similar tot he logln(msg) method except that the * caller can provide a shortened version of the filename to * display. * * One can facilitate calling this routine by including a * <pre> * import static org.jasonnet.logln.Logln.logln; * </pre> * at the top of the source java file. * * @author jasonnet (01/26/2015) * * @param msg the diagnostic message to display * @param SHORTFN the filename to display when logging */ public static void logln( String msg, String SHORTFN) { StackTraceElement els[] = Thread.currentThread().getStackTrace(); _logln(msg, els, SHORTFN ); } private static void _logln( String msg, StackTraceElement els[], String fn) { StringBuffer sb = new StringBuffer(); if (null==fn) { // todo: provide code that looks in the class for SHORTFN static value. String clsnm = els[2].getClassName(); try { Class cls = Class.forName(clsnm); if (cls!=null) { Field fld = cls.getDeclaredField("SHORTFN"); if (fld!=null) { Object oo = fld.get(null); if (oo instanceof String) { fn = (String)oo; } } } } catch (Exception exc) {} if (fn==null) { int idx = clsnm.lastIndexOf('.'); if (idx>0) { fn = clsnm.substring(idx+1); } else { fn = clsnm; // we shouldn't reach this line } } } if (dateformat!=null) ps.print(dateformat.format(new Date())); ps.printf("%10s:%4d: ", fn, els[2].getLineNumber() ); for (int i=0; i<els.length; i++) sb.append(' '); sb.append(els[2].getMethodName()); sb.append(": "); sb.append(msg); ps.print(sb); ps.println(); } protected static final String initial_datetemplate = "yyyy-MM-dd kk:mm:ss "; protected static SimpleDateFormat dateformat = new SimpleDateFormat(initial_datetemplate); /** * Set the template for how to display the date in subsequent * log lines. * * @author ccjason (2/11/2015) * * @param template This should be expressed in the same way that * it is for the constructor of the {@link * SimpleDateFormat} class. */ public static void setDateTemplate(String template) { if (template==null) { dateformat = null; } else { dateformat = new SimpleDateFormat(template); } } }
package org.jtrfp.trcl.flow; import java.awt.Color; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import javax.swing.JOptionPane; import org.jtrfp.jtrfp.FileLoadException; import org.jtrfp.trcl.BriefingScreen; import org.jtrfp.trcl.Camera; import org.jtrfp.trcl.DisplayModeHandler; import org.jtrfp.trcl.EarlyLoadingScreen; import org.jtrfp.trcl.GLFont; import org.jtrfp.trcl.HUDSystem; import org.jtrfp.trcl.LevelLoadingScreen; import org.jtrfp.trcl.NAVSystem; import org.jtrfp.trcl.SatelliteDashboard; import org.jtrfp.trcl.UpfrontDisplay; import org.jtrfp.trcl.beh.MatchDirection; import org.jtrfp.trcl.beh.MatchPosition; import org.jtrfp.trcl.core.Features; import org.jtrfp.trcl.core.ResourceManager; import org.jtrfp.trcl.core.TR; import org.jtrfp.trcl.core.TRFutureTask; import org.jtrfp.trcl.file.NDXFile; import org.jtrfp.trcl.file.VOXFile; import org.jtrfp.trcl.file.VOXFile.MissionLevel; import org.jtrfp.trcl.file.Weapon; import org.jtrfp.trcl.gui.BriefingLayout; import org.jtrfp.trcl.gui.DashboardLayout; import org.jtrfp.trcl.gui.F3BriefingLayout; import org.jtrfp.trcl.gui.F3DashboardLayout; import org.jtrfp.trcl.gui.TVBriefingLayout; import org.jtrfp.trcl.gui.TVDashboardLayout; import org.jtrfp.trcl.obj.DebrisSystem; import org.jtrfp.trcl.obj.Explosion.ExplosionType; import org.jtrfp.trcl.obj.ExplosionSystem; import org.jtrfp.trcl.obj.Player; import org.jtrfp.trcl.obj.PowerupSystem; import org.jtrfp.trcl.obj.ProjectileFactory; import org.jtrfp.trcl.obj.SmokeSystem; import org.jtrfp.trcl.prop.IntroScreen; import org.jtrfp.trcl.prop.RedFlash; import org.jtrfp.trcl.snd.SoundSystem; public class Game { //// PROPERTIES public static final String PAUSED = "paused"; public static final String CURRENT_MISSION= "currentMission"; public static final String PLAYER = "player"; public static final String RUN_MODE = "runMode"; private TR tr; private VOXFile vox; private int levelIndex = 0; private String playerName="DEBUG"; private Difficulty difficulty; private Mission currentMission; HUDSystem hudSystem; NAVSystem navSystem; private SatelliteDashboard satDashboard; private Player player; private GLFont upfrontFont; UpfrontDisplay upfrontDisplay; LevelLoadingScreen levelLoadingScreen; BriefingScreen briefingScreen; private IntroScreen introScreen; private final RedFlash redFlash; private final DisplayModeHandler displayModes; private Object[] earlyLoadingMode, titleScreenMode, missionMode, emptyMode; private final PropertyChangeSupport pcSupport = new PropertyChangeSupport(this); private boolean paused=false; private volatile boolean aborting=false; private TRFutureTask<Void>[] startupTask = new TRFutureTask[]{null}; private RunMode runMode; private static final int UPFRONT_HEIGHT = 23; private final double FONT_SIZE=.07; private boolean inGameplay =false; private DashboardLayout dashboardLayout; public interface RunMode{} public interface GameConstructingMode extends RunMode{} public interface GameConstructedMode extends RunMode{} public interface GameDestructingMode extends RunMode{} public interface GameDestructedMode extends RunMode{} public Game(TR tr, VOXFile vox) { Features.init(this); setRunMode(new GameConstructingMode(){}); setTr(tr); displayModes = new DisplayModeHandler(tr.getDefaultGrid()); setVox(vox); setRunMode(new GameConstructingMode(){}); redFlash = new RedFlash(tr); tr.getDefaultGrid().add(redFlash); if (!tr.config.isDebugMode()) setupNameWithUser(); emptyMode = missionMode = new Object[]{}; setRunMode(new GameConstructedMode(){}); }// end constructor private void setupNameWithUser() { setPlayerName((String) JOptionPane.showInputDialog(tr.getRootWindow(), "Callsign:", "Pilot Registration", JOptionPane.PLAIN_MESSAGE, null, null, "Councilor")); String difficulty = (String) JOptionPane.showInputDialog( tr.getRootWindow(), "Difficulty:", "Pilot Registration", JOptionPane.PLAIN_MESSAGE, null, new String[] { "Easy", "Normal", "Hard", "Furious" }, "Normal"); if (difficulty.contentEquals("Easy")) { setDifficulty(Difficulty.EASY); } if (difficulty.contentEquals("Normal")) { setDifficulty(Difficulty.NORMAL); } if (difficulty.contentEquals("Hard")) { setDifficulty(Difficulty.HARD); } if (difficulty.contentEquals("Furious")) { setDifficulty(Difficulty.FURIOUS); } }// end setupNameWithUser() public void save(File fileToSaveTo) { // TODO } /** * @return the tr */ public TR getTr() { return tr; } /** * @param tr * the tr to set */ public synchronized void setTr(TR tr) { this.tr = tr; } /** * @return the vox */ public synchronized VOXFile getVox() { return vox; } /** * @param vox * the vox to set */ public synchronized void setVox(VOXFile vox) { if(this.vox==vox) return;//No change. pcSupport.firePropertyChange("vox", this.vox, vox); this.vox = vox; } /** * @return the levelIndex */ public synchronized int getLevelIndex() { return levelIndex; } public boolean isInGameplay(){ return inGameplay; } private boolean setInGameplay(boolean newValue){ boolean old = inGameplay; inGameplay=newValue; pcSupport.firePropertyChange("inGameplay", old, newValue); return old; } public void setLevelIndex(int levelIndex) throws IllegalAccessException, FileNotFoundException, IOException, FileLoadException { this.levelIndex = levelIndex; if (levelIndex != -1) {// -1 means 'abort' MissionLevel lvl = vox.getLevels()[getLevelIndex()]; final String lvlFileName = lvl.getLvlFile(); setCurrentMission(new Mission(tr, this, tr.getResourceManager() .getLVL(lvlFileName), lvlFileName.substring(0, lvlFileName.lastIndexOf('.')), getLevelIndex() % 3 == 0)); }//end if(levelIndex!=-1) }// end setLevelIndex(...) /** * @return the playerName */ public synchronized String getPlayerName() { return playerName; } /** * @param playerName * the playerName to set */ public synchronized void setPlayerName(String playerName) { this.playerName = playerName; } enum Difficulty { EASY, NORMAL, HARD, FURIOUS } /** * @return the difficulty */ public synchronized Difficulty getDifficulty() { return difficulty; } /** * @param difficulty * the difficulty to set */ public synchronized void setDifficulty(Difficulty difficulty) { this.difficulty = difficulty; } public NAVSystem getNavSystem(){ return navSystem; } public synchronized void setLevel(String skipToLevel) throws IllegalAccessException, FileNotFoundException, IOException, FileLoadException { final MissionLevel[] levs = vox.getLevels(); for (int index = 0; index < levs.length; index++) { if (levs[index].getLvlFile().toUpperCase() .contentEquals(skipToLevel.toUpperCase())) setLevelIndex(index); }// end for(levs) }// end setLevel() public HUDSystem getHUDSystem(){ if(hudSystem==null) try{hudSystem = new HUDSystem(tr,tr.getGameShell().getGreenFont(),getDashboardLayout());} catch(Exception e){e.printStackTrace();return null;} return hudSystem; } public synchronized void boot() throws IllegalAccessException, FileNotFoundException, IOException, FileLoadException { // Set up player, HUD, fonts... System.out.println("Booting..."); NDXFile ndx = tr.getResourceManager().getNDXFile("STARTUP\\FONT.NDX"); upfrontFont = new GLFont(tr.getResourceManager().getFontBIN("STARTUP\\FONT.BIN", ndx), UPFRONT_HEIGHT, ndx.getWidths(), 32,tr); final EarlyLoadingScreen earlyLoadingScreen = tr.getGameShell().getEarlyLoadingScreen(); earlyLoadingScreen.setStatusText("Reticulating Splines..."); earlyLoadingMode = new Object []{ earlyLoadingScreen }; displayModes.setDisplayMode(earlyLoadingMode); upfrontDisplay = new UpfrontDisplay(tr.getDefaultGrid(),tr); satDashboard = new SatelliteDashboard(tr); satDashboard.setVisible(false); tr.getDefaultGrid().add(satDashboard); //hudSystem = new HUDSystem(tr,tr.getGameShell().getGreenFont(),layout); System.out.println("GameVersion="+tr.config.getGameVersion()); navSystem = new NAVSystem(tr.getDefaultGrid(), tr,getDashboardLayout()); // Make color zero translucent. final ResourceManager rm = tr.getResourceManager(); final Color[] pal = tr.getGlobalPalette(); pal[0] = new Color(0, 0, 0, 0); tr.setGlobalPalette(pal); // POWERUPS earlyLoadingScreen.setStatusText("Loading powerup assets..."); rm.setPowerupSystem(new PowerupSystem(tr)); // EXPLOSIONS earlyLoadingScreen.setStatusText("Loading explosion assets..."); rm.setExplosionFactory(new ExplosionSystem(tr)); // SMOKE earlyLoadingScreen.setStatusText("Loading smoke assets..."); rm.setSmokeSystem(new SmokeSystem(tr)); // DEBRIS earlyLoadingScreen.setStatusText("Loading debris assets..."); rm.setDebrisSystem(new DebrisSystem(tr)); // SETUP PROJECTILE FACTORIES earlyLoadingScreen.setStatusText("Setting up projectile factories..."); Weapon[] w = Weapon.values(); ProjectileFactory[] pf = new ProjectileFactory[w.length]; for (int i = 0; i < w.length; i++) { pf[i] = new ProjectileFactory(tr, w[i], ExplosionType.Blast); }// end for(weapons) rm.setProjectileFactories(pf); setPlayer(new Player(tr, tr.getResourceManager().getBINModel( "SHIP.BIN", tr.getGlobalPaletteVL(),null, tr.gpu.get().getGl()))); final Camera camera = tr.mainRenderer.get().getCamera(); camera.probeForBehavior(MatchPosition.class).setTarget(player); camera.probeForBehavior(MatchDirection.class).setTarget(player); tr.getDefaultGrid().add(player); System.out.println("\t...Done."); levelLoadingScreen = new LevelLoadingScreen(tr.getDefaultGrid(),tr); final BriefingLayout briefingLayout = tr.config.getGameVersion()==GameVersion.TV?new TVBriefingLayout():new F3BriefingLayout(); briefingScreen = new BriefingScreen(tr,tr.getGameShell().getGreenFont(), briefingLayout); earlyLoadingScreen.setStatusText("Starting game..."); introScreen = new IntroScreen(tr,"TITLE.RAW","SEX.MOD"); titleScreenMode = new Object[]{ introScreen }; displayModes.setDisplayMode(titleScreenMode); introScreen.startMusic(); setLevelIndex(0); }// end boot() public void setPlayer(Player player) { final Player oldPlayer = this.player; this.player = player; pcSupport.firePropertyChange(PLAYER, oldPlayer, player); } public synchronized void doGameplay() throws IllegalAccessException, FileNotFoundException, IOException, FileLoadException { setInGameplay(true); try { MissionLevel[] levels = vox.getLevels(); tr.getThreadManager().setPaused(false); while (getLevelIndex() < levels.length && getLevelIndex() != -1) { Mission.Result result = null; final Mission mission = getCurrentMission(); if (mission == null) break; while (result == null){ displayModes.setDisplayMode(missionMode); result = getCurrentMission().go();} if (result.isAbort()) break; // Rube Goldberg style increment setLevelIndex(getLevelIndex() + 1); }// end while(getLevelIndex<length) System.out.println("Escaping game loop."); tr.getThreadManager().setPaused(true); setInGameplay(false); } catch (IllegalAccessException e) { throw e; } catch (FileNotFoundException e) { throw e; } catch (IOException e) { throw e; } catch (FileLoadException e) { throw e; } finally { tr.getThreadManager().setPaused(true); setInGameplay(false); }//end finally{} }// end beginGameplay() public void setCurrentMission(Mission mission) { pcSupport.firePropertyChange("currentMission", this.currentMission, mission); this.currentMission=mission; } public void abort(){ setRunMode(new GameDestructingMode(){}); try{setLevelIndex(-1);} catch(Exception e){tr.showStopper(e);}//Shouldn't happen. abortCurrentMission(); cleanup(); displayModes.setDisplayMode(emptyMode); tr.getGameShell().applyGFXState(); setRunMode(new GameDestructedMode(){}); } public DashboardLayout getDashboardLayout(){ if(dashboardLayout==null) dashboardLayout = tr.config.getGameVersion()==GameVersion.TV?new TVDashboardLayout():new F3DashboardLayout(); return dashboardLayout; }//end getDashboardLayout() private void cleanup() { if(introScreen.isMusicPlaying()) introScreen.stopMusic(); if(player!=null) tr.getDefaultGrid().remove(player); } public void abortCurrentMission(){//TODO: Replace with RunMode PCL tr.getThreadManager().setPaused(true); synchronized(startupTask){ if(startupTask[0]!=null) startupTask[0].get();//Don't abort while setting up. }//end sync{} if(currentMission!=null) currentMission.abort(); setCurrentMission(null); }//end abortCurrentMission() public Mission getCurrentMission() { return currentMission; }//end getCurrentMission public Player getPlayer(){ return player; } public GLFont getUpfrontFont() { return upfrontFont; } /** * @return the upfrontDisplay */ public UpfrontDisplay getUpfrontDisplay() { return upfrontDisplay; } public LevelLoadingScreen getLevelLoadingScreen() { return levelLoadingScreen; } public Game setDisplayMode(Object[] mode) { displayModes.setDisplayMode(mode); return this; } public BriefingScreen getBriefingScreen(){ return briefingScreen; } /** * @return the paused */ public boolean isPaused() { return paused; } /** * @param paused the paused to set */ public Game setPaused(boolean paused) {//TODO: This feature should be in Mission if(paused==this.paused) return this;//nothing to do. pcSupport.firePropertyChange(PAUSED, this.paused, paused); this.paused = paused; final SoundSystem ss = getTr().soundSystem.get(); ss.setPaused(paused); getTr().getThreadManager().setPaused(paused); if(paused) upfrontDisplay.submitPersistentMessage("Paused--F3 to Resume"); else upfrontDisplay.removePersistentMessage(); return this; } public Game addPropertyChangeListener(String propertyName, PropertyChangeListener l){ pcSupport.addPropertyChangeListener(propertyName, l); return this; } public Game removePropertyChangeListener(PropertyChangeListener l){ pcSupport.removePropertyChangeListener(l); return this; } /** * @return the mapDashboard */ public SatelliteDashboard getSatDashboard() { return satDashboard; } /** * @param satDashboard the mapDashboard to set */ public void setSatDashboard(SatelliteDashboard satDashboard) { this.satDashboard = satDashboard; } /** * @return the redFlash */ public RedFlash getRedFlash() { return redFlash; } public void levelLoadingMode() { introScreen.stopMusic(); } public RunMode getRunMode() { return runMode; } public void setRunMode(RunMode runMode) { final RunMode oldRunMode = this.runMode; this.runMode = runMode; pcSupport.firePropertyChange(RUN_MODE, oldRunMode, runMode); } }// end Game
package org.lantern; import java.awt.Desktop; import java.awt.Dimension; import java.awt.Point; import java.awt.Toolkit; import java.io.Console; import java.io.File; import java.io.FileInputStream; import java.io.IOError; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.concurrent.atomic.AtomicInteger; import javax.crypto.Cipher; import javax.net.ssl.SSLSocket; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.httpclient.URIException; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOExceptionWithCause; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.SystemUtils; import org.apache.commons.lang.math.NumberUtils; import org.codehaus.jackson.map.ObjectMapper; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.handler.codec.http.HttpHeaders; import org.jboss.netty.handler.codec.http.HttpMessage; import org.jboss.netty.handler.codec.http.HttpMethod; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpRequestEncoder; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.packet.Packet; import org.lantern.state.StaticSettings; import org.lastbamboo.common.offer.answer.NoAnswerException; import org.lastbamboo.common.p2p.P2PClient; import org.lastbamboo.common.stun.client.PublicIpAddress; import org.littleshoot.commom.xmpp.XmppUtils; import org.littleshoot.util.ByteBufferUtils; import org.littleshoot.util.FiveTuple; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.io.Files; /** * Utility methods for use with Lantern. */ public class LanternUtils { private static final Logger LOG = LoggerFactory.getLogger(LanternUtils.class); private static final SecureRandom secureRandom = new SecureRandom(); private static String MAC_ADDRESS; private static boolean amFallbackProxy = false; private static String keystorePath = "<UNSET>"; private static String fallbackServerHost; private static int fallbackServerPort; public static boolean isDevMode() { return LanternClientConstants.isDevMode(); } /* public static Socket openRawOutgoingPeerSocket( final URI uri, final P2PClient p2pClient, final Map<URI, AtomicInteger> peerFailureCount) throws IOException { return openOutgoingPeerSocket(uri, p2pClient, peerFailureCount, true); } */ static { addFallbackProxy(); } private static void addFallbackProxy() { try { copyFallback(); } catch (final IOException e) { LOG.error("Could not copy fallback?", e); } final ObjectMapper om = new ObjectMapper(); InputStream is = null; try { final File file = new File(LanternClientConstants.CONFIG_DIR, "fallback.json"); if (!file.isFile()) { LOG.error("No fallback proxy to load!"); return; } is = new FileInputStream(file); final String proxy = IOUtils.toString(is); final FallbackProxy fp = om.readValue(proxy, FallbackProxy.class); fallbackServerHost = fp.getIp(); fallbackServerPort = fp.getPort(); LOG.debug("Set fallback proxy to {}", fallbackServerHost); } catch (final IOException e) { LOG.error("Could not load fallback", e); } finally { IOUtils.closeQuietly(is); } } private static void copyFallback() throws IOException { LOG.debug("Copying fallback file"); final File from = new File(new File(SystemUtils.USER_HOME), "fallback.json"); if (!from.isFile()) { LOG.debug("No fallback proxy found in root..."); return; } final File par = LanternClientConstants.CONFIG_DIR; final File to = new File(par, from.getName()); if (!par.isDirectory() && !par.mkdirs()) { throw new IOException("Could not make config dir?"); } Files.move(from, to); } public static FiveTuple openOutgoingPeer( final URI uri, final P2PClient<FiveTuple> p2pClient, final Map<URI, AtomicInteger> peerFailureCount) throws IOException { if (p2pClient == null) { LOG.info("P2P client is null. Testing?"); throw new IOException("P2P client not connected"); } // Start the connection attempt. try { LOG.debug("Creating a new socket to {}", uri); return p2pClient.newSocket(uri); } catch (final NoAnswerException nae) { // This is tricky, as it can mean two things. First, it can mean // the XMPP message was somehow lost. Second, it can also mean // the other side is actually not there and didn't respond as a // result. LOG.info("Did not get answer!! Closing channel from browser", nae); final AtomicInteger count = peerFailureCount.get(uri); if (count == null) { LOG.debug("Incrementing failure count"); peerFailureCount.put(uri, new AtomicInteger(0)); } else if (count.incrementAndGet() > 5) { LOG.info("Got a bunch of failures in a row to this peer. " + "Removing it."); // We still reset it back to zero. Note this all should // ideally never happen, and we should be able to use the // XMPP presence alerts to determine if peers are still valid // or not. peerFailureCount.put(uri, new AtomicInteger(0)); //proxyStatusListener.onCouldNotConnectToPeer(uri); } throw new IOExceptionWithCause(nae); } catch (final IOException ioe) { //proxyStatusListener.onCouldNotConnectToPeer(uri); LOG.debug("Could not connect to peer", ioe); throw ioe; } } public static Socket openOutgoingPeerSocket(final URI uri, final P2PClient<Socket> p2pClient, final Map<URI, AtomicInteger> peerFailureCount) throws IOException { return openOutgoingPeerSocket(uri, p2pClient, peerFailureCount, false); } private static Socket openOutgoingPeerSocket( final URI uri, final P2PClient<Socket> p2pClient, final Map<URI, AtomicInteger> peerFailureCount, final boolean raw) throws IOException { if (p2pClient == null) { LOG.info("P2P client is null. Testing?"); throw new IOException("P2P client not connected"); } // Start the connection attempt. try { LOG.info("Creating a new socket to {}", uri); final Socket sock; if (raw) { sock = p2pClient.newRawSocket(uri); } else { sock = p2pClient.newSocket(uri); } // Note that it's OK that this prints SSL_NULL_WITH_NULL_NULL -- // the handshake doesn't actually happen until the first IO, so // the SSL ciphers and such should be all null at this point. LOG.debug("Got outgoing peer socket {}", sock); if (sock instanceof SSLSocket) { LOG.debug("Socket has ciphers {}", ((SSLSocket)sock).getEnabledCipherSuites()); } else { LOG.warn("Not an SSL socket..."); } //startReading(sock, browserToProxyChannel, recordStats); return sock; } catch (final NoAnswerException nae) { // This is tricky, as it can mean two things. First, it can mean // the XMPP message was somehow lost. Second, it can also mean // the other side is actually not there and didn't respond as a // result. LOG.info("Did not get answer!! Closing channel from browser", nae); final AtomicInteger count = peerFailureCount.get(uri); if (count == null) { LOG.info("Incrementing failure count"); peerFailureCount.put(uri, new AtomicInteger(0)); } else if (count.incrementAndGet() > 5) { LOG.info("Got a bunch of failures in a row to this peer. " + "Removing it."); // We still reset it back to zero. Note this all should // ideally never happen, and we should be able to use the // XMPP presence alerts to determine if peers are still valid // or not. peerFailureCount.put(uri, new AtomicInteger(0)); //proxyStatusListener.onCouldNotConnectToPeer(uri); } throw new IOExceptionWithCause(nae); } catch (final IOException ioe) { //proxyStatusListener.onCouldNotConnectToPeer(uri); LOG.info("Could not connect to peer", ioe); throw ioe; } } public static byte[] utf8Bytes(final String str) { try { return str.getBytes("UTF-8"); } catch (final UnsupportedEncodingException e) { LOG.error("No UTF-8?", e); throw new RuntimeException("No UTF-8?", e); } } /** * This is the local proxy port data is relayed to on the "server" side * of P2P connections. * * NOT IN CONSTANTS BECAUSE LanternUtils INITIALIZES THE LOGGER, WHICH * CAN'T HAPPEN IN CONSTANTS DUE TO THE CONFIGURATION SEQUENCE IN * PRODUCTION. */ public static final int PLAINTEXT_LOCALHOST_PROXY_PORT = LanternUtils.randomPort(); public static boolean isTransferEncodingChunked(final HttpMessage m) { final List<String> chunked = m.getHeaders(HttpHeaders.Names.TRANSFER_ENCODING); if (chunked.isEmpty()) { return false; } for (String v: chunked) { if (v.equalsIgnoreCase(HttpHeaders.Values.CHUNKED)) { return true; } } return false; } /** * We subclass here purely to expose the encoding method of the built-in * request encoder. */ private static final class RequestEncoder extends HttpRequestEncoder { private ChannelBuffer encode(final HttpRequest request, final Channel ch) throws Exception { return (ChannelBuffer) super.encode(null, ch, request); } } public static byte[] toByteBuffer(final HttpRequest request, final ChannelHandlerContext ctx) throws Exception { // We need to convert the Netty message to raw bytes for sending over // the socket. final RequestEncoder encoder = new RequestEncoder(); final ChannelBuffer cb = encoder.encode(request, ctx.getChannel()); return toRawBytes(cb); } public static byte[] toRawBytes(final ChannelBuffer cb) { final ByteBuffer buf = cb.toByteBuffer(); return ByteBufferUtils.toRawBytes(buf); } public static Collection<String> toHttpsCandidates(final String uriStr) { final Collection<String> segments = new LinkedHashSet<String>(); try { final org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(uriStr, false); final String host = uri.getHost(); //LOG.info("Using host: {}", host); segments.add(host); final String[] segmented = host.split("\\."); //LOG.info("Testing segments: {}", Arrays.asList(segmented)); for (int i = 0; i < segmented.length; i++) { final String tmp = segmented[i]; segmented[i] = "*"; final String segment = StringUtils.join(segmented, '.'); //LOG.info("Adding segment: {}", segment); segments.add(segment); segmented[i] = tmp; } for (int i = 1; i < segmented.length - 1; i++) { final String segment = "*." + StringUtils.join(segmented, '.', i, segmented.length);//segmented.slice(i,segmented.length).join("."); //LOG.info("Checking segment: {}", segment); segments.add(segment); } } catch (final URIException e) { LOG.error("Could not create URI?", e); } return segments; } public static void waitForInternet() { while (true) { if (hasNetworkConnection()) { return; } try { Thread.sleep(50); } catch (final InterruptedException e) { LOG.error("Interrupted?", e); } } } public static boolean hasNetworkConnection() { LOG.debug("Checking for network connection by looking up public IP"); final InetAddress ip = new PublicIpAddress().getPublicIpAddress(); LOG.debug("Returning result: "+ip); return ip != null; } public static int randomPort() { if (LanternConstants.ON_APP_ENGINE) { // Can't create server sockets on app engine. return -1; } for (int i = 0; i < 20; i++) { int randomInt = secureRandom.nextInt(); if (randomInt == Integer.MIN_VALUE) { // Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE -- caught // by FindBugs. randomInt = 0; } final int randomPort = 1024 + (Math.abs(randomInt) % 60000); ServerSocket sock = null; try { sock = new ServerSocket(); sock.bind(new InetSocketAddress("127.0.0.1", randomPort)); final int port = sock.getLocalPort(); return port; } catch (final IOException e) { LOG.info("Could not bind to port: {}", randomPort); } finally { if (sock != null) { try { sock.close(); } catch (IOException e) { } } } } // If we can't grab one of our securely chosen random ports, use // whatever port the OS assigns. ServerSocket sock = null; try { sock = new ServerSocket(); sock.bind(null); final int port = sock.getLocalPort(); return port; } catch (final IOException e) { LOG.info("Still could not bind?"); int randomInt = secureRandom.nextInt(); if (randomInt == Integer.MIN_VALUE) { // see above randomInt = 0; } return 1024 + (Math.abs(randomInt) % 60000); } finally { if (sock != null) { try { sock.close(); } catch (IOException e) { } } } } /** * Execute keytool, returning the output. * * @throws IOException If the executable cannot be found. */ public static String runKeytool(final String... args) { try { final CommandLine command = new CommandLine(findKeytoolPath(), args); command.execute(); final String output = command.getStdOut(); if (!command.isSuccessful()) { LOG.info("Command failed!! -- {}", Arrays.asList(args)); } return output; } catch (IOException e) { LOG.warn("Could not run key tool?", e); } return ""; } private static String findKeytoolPath() { if (SystemUtils.IS_OS_MAC_OSX) { // try to explicitly select the 1.6 keytool -- // The user may have 1.5 selected as the default // javavm (default in os x 10.5.8) // in this case, the default location below will // point to the 1.5 keytool instead. final File keytool16 = new File( "/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Commands/keytool"); if (keytool16.exists()) { return keytool16.getAbsolutePath(); } } final File jh = new File(System.getProperty("java.home"), "bin"); if (jh.isDirectory()) { final String name; if (SystemUtils.IS_OS_WINDOWS) { name = "keytool.exe"; } else { name = "keytool"; } try { return new File(jh, name).getCanonicalPath(); } catch (final IOException e) { LOG.warn("Error getting canonical path: " + jh); } } else { LOG.warn("java.home/bin not a directory? "+jh); } final File defaultLocation = new File("/usr/bin/keytool"); if (defaultLocation.exists()) { return defaultLocation.getAbsolutePath(); } final String networkSetupBin = CommandLine.findExecutable("keytool"); if (networkSetupBin != null) { return networkSetupBin; } LOG.error("Could not find keytool?!?!?!?"); return null; } public static boolean isLanternHub(final String jabberid) { final String userid = LanternXmppUtils.jidToUserId(jabberid); return LanternClientConstants.LANTERN_JID.equals(userid); } public static Packet activateOtr(final XMPPConnection conn) { return XmppUtils.goOffTheRecord(LanternClientConstants.LANTERN_JID, conn); } public static Packet deactivateOtr(final XMPPConnection conn) { return XmppUtils.goOnTheRecord(LanternClientConstants.LANTERN_JID, conn); } public static void browseUrl(final String uri) { if( !Desktop.isDesktopSupported() ) { LOG.error("Desktop not supported?"); LinuxBrowserLaunch.openURL(uri); return; } final Desktop desktop = Desktop.getDesktop(); if( !desktop.isSupported(Desktop.Action.BROWSE )) { LOG.error("Browse not supported?"); } try { desktop.browse(new URI(uri)); } catch (final IOException e) { LOG.warn("Error opening browser", e); } catch (final URISyntaxException e) { LOG.warn("Could not load URI", e); } } public static char[] readPasswordCLI() throws IOException { Console console = System.console(); if (console == null) { LOG.debug("No console -- using System.in..."); final Scanner sc = new Scanner(System.in, "UTF-8"); final char[] line = sc.nextLine().toCharArray(); sc.close(); return line; } try { return console.readPassword(); } catch (final IOError e) { throw new IOException("Could not read pass from console", e); } } public static String readLineCLI() throws IOException { Console console = System.console(); if (console == null) { return readLineCliNoConsole(); } try { return console.readLine(); } catch (final IOError e) { throw new IOException("Could not read line from console", e); } } public static String readLineCliNoConsole() { LOG.debug("No console -- using System.in..."); final Scanner sc = new Scanner(System.in, "UTF-8"); //sc.useDelimiter("\n"); //return sc.next(); final String line = sc.nextLine(); sc.close(); return line; } /** * Returns <code>true</code> if the specified string is either "true" or * "on" ignoring case. * * @param val The string in question. * @return <code>true</code> if the specified string is either "true" or * "on" ignoring case, otherwise <code>false</code>. */ public static boolean isTrue(final String val) { return checkTrueOrFalse(val, "true", "on"); } /** * Returns <code>true</code> if the specified string is either "false" or * "off" ignoring case. * * @param val The string in question. * @return <code>true</code> if the specified string is either "false" or * "off" ignoring case, otherwise <code>false</code>. */ public static boolean isFalse(final String val) { return checkTrueOrFalse(val, "false", "off"); } private static boolean checkTrueOrFalse(final String val, final String str1, final String str2) { final String str = val.trim(); return StringUtils.isNotBlank(str) && (str.equalsIgnoreCase(str1) || str.equalsIgnoreCase(str2)); } /** * Replaces the first instance of the specified regex in the given file * with the replacement string and writes out the new complete file. * * @param file The file to modify. * @param regex The regular expression to search for. * @param replacement The replacement string. */ public static void replaceInFile(final File file, final String regex, final String replacement) { LOG.debug("Replacing "+regex+" with "+replacement+" in "+file); try { final String cur = FileUtils.readFileToString(file, "UTF-8"); final String noStart = cur.replaceFirst(regex, replacement); FileUtils.writeStringToFile(file, noStart, "UTF-8"); } catch (final IOException e) { LOG.warn("Could not replace string in file", e); } } public static void loadJarLibrary(final Class<?> jarRepresentative, final String fileName) throws IOException { File tempDir = null; InputStream is = null; try { tempDir = Files.createTempDir(); final File tempLib = new File(tempDir, fileName); is = jarRepresentative.getResourceAsStream("/" + fileName); if (is == null) { final String msg = "No file in jar named: "+fileName; LOG.warn(msg); throw new IOException(msg); } FileUtils.copyInputStreamToFile(is, tempLib); System.load(tempLib.getAbsolutePath()); } finally { FileUtils.deleteQuietly(tempDir); IOUtils.closeQuietly(is); } } public static String fileInJarToString(final String fileName) throws IOException { InputStream is = null; try { is = LanternUtils.class.getResourceAsStream("/" + fileName); return IOUtils.toString(is); } finally { IOUtils.closeQuietly(is); } } /** * Creates a typed object from the specified string. If the string is a * boolean, this returns a boolean, if an int, an int, etc. * * @param val The string. * @return A typed object. */ public static Object toTyped(final String val) { if (LanternUtils.isTrue(val)) { return true; } else if (LanternUtils.isFalse(val)) { return false; } else if (NumberUtils.isNumber(val)) { return Integer.parseInt(val); } return val; } /** * Prints request headers. * * @param request The request. */ public static void printRequestHeaders(final HttpServletRequest request) { LOG.info(getRequestHeaders(request).toString()); } /** * Gets request headers as a string. * * @param request The request. * @return The request headers as a string. */ public static String getRequestHeaders(final HttpServletRequest request) { final Enumeration<String> headers = request.getHeaderNames(); final StringBuilder sb = new StringBuilder(); sb.append("\n"); sb.append(request.getRequestURL().toString()); sb.append("\n"); while (headers.hasMoreElements()) { final String headerName = headers.nextElement(); sb.append(headerName); sb.append(": "); sb.append(request.getHeader(headerName)); sb.append("\n"); } return sb.toString(); } public static void zeroFill(char[] array) { if (array != null) { Arrays.fill(array, '\0'); } } public static void zeroFill(byte[] array) { if (array != null) { Arrays.fill(array, (byte) 0); } } public static boolean isUnlimitedKeyStrength() { try { return Cipher.getMaxAllowedKeyLength("AES") == Integer.MAX_VALUE; } catch (final NoSuchAlgorithmException e) { LOG.error("No AES?", e); return false; } } public static String toEmail(final XMPPConnection conn) { final String jid = conn.getUser().trim(); return XmppUtils.jidToUser(jid); } public static boolean isNotJid(final String email) { final boolean isEmail = !email.contains(".talk.google.com"); /* if (isEmail) { LOG.debug("Allowing email {}", email); } else { LOG.debug("Is a JID {}", email); } */ return isEmail; } public static Point getScreenCenter(final int width, final int height) { final Toolkit toolkit = Toolkit.getDefaultToolkit(); final Dimension screenSize = toolkit.getScreenSize(); final int x = (screenSize.width - width) / 2; final int y = (screenSize.height - height) / 2; return new Point(x, y); } public static boolean waitForServer(final int port) { return waitForServer(port, 60 * 1000); } public static boolean waitForServer(final int port, final int millis) { final long start = System.currentTimeMillis(); while (System.currentTimeMillis() - start < millis) { final Socket sock = new Socket(); try { final SocketAddress isa = new InetSocketAddress("127.0.0.1", port); sock.connect(isa, 2000); sock.close(); return true; } catch (final IOException e) { } try { Thread.sleep(100); } catch (final InterruptedException e) { LOG.info("Interrupted?"); } } LOG.error("Never able to connect with local server! " + "Maybe couldn't bind?"); return false; } /* public static boolean isLanternMessage(final Presence pres) { final Object prop = pres.getProperty(XmppMessageConstants.PROFILE); return prop != null; } */ /** * Determines whether or not oauth data should be persisted to disk. It is * only persisted if we can do so safely and securely but also cleanly. * * Fixme: this should actually be a user preference refs #586 * * @return <code>true</code> if credentials should be persisted to disk, * otherwise <code>false</code>. */ public static boolean persistCredentials() { return true; } /** * Accesses the object to set a property on with a trivial json-pointer * syntax as in /object1/object2. * * Public for testing. Note this is actually not use in favor of * ModelMutables that consolidates all accessible methods. */ public static Object getTargetForPath(final Object root, final String path) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (!path.contains("/")) { return root; } final String curProp = StringUtils.substringBefore(path, "/"); final Object propObject; if (curProp.isEmpty()) { propObject = root; } else { propObject = PropertyUtils.getProperty(root, curProp); } final String nextProp = StringUtils.substringAfter(path, "/"); if (nextProp.contains("/")) { return getTargetForPath(propObject, nextProp); } return propObject; } public static void setFromPath(final Object root, final String path, final Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (!path.contains("/")) { PropertyUtils.setProperty(root, path, value); return; } final String curProp = StringUtils.substringBefore(path, "/"); final Object propObject; if (curProp.isEmpty()) { propObject = root; } else { propObject = PropertyUtils.getProperty(root, curProp); } final String nextProp = StringUtils.substringAfter(path, "/"); if (nextProp.contains("/")) { setFromPath(propObject, nextProp, value); return; } PropertyUtils.setProperty(propObject, nextProp, value); } public static boolean isLocalHost(final Channel channel) { final InetSocketAddress remote = (InetSocketAddress) channel.getRemoteAddress(); return remote.getAddress().isLoopbackAddress(); } public static boolean isLocalHost(final Socket sock) { final InetSocketAddress remote = (InetSocketAddress) sock.getRemoteSocketAddress(); return remote.getAddress().isLoopbackAddress(); } /** * Returns whether or not the string is either true of false. If it's some * other random string, this returns false. * * @param str The string to test. * @return <code>true</code> if the string is either true or false * (or on or off), otherwise false. */ public static boolean isTrueOrFalse(final String str) { if (LanternUtils.isTrue(str)) { return true; } else if (LanternUtils.isFalse(str)) { return true; } return false; } /** * The completion of the native calls is dependent on OS process * scheduling, so we need to wait until files actually exist. * * @param file The file to wait for. */ public static void waitForFile(final File file) { int i = 0; while (!file.isFile() && i < 100) { try { Thread.sleep(80); i++; } catch (final InterruptedException e) { LOG.error("Interrupted?", e); } } if (!file.isFile()) { LOG.error("Still could not create file at: {}", file); } else { LOG.info("Successfully created file at: {}", file); } } public static void fullDelete(final File file) { file.deleteOnExit(); if (file.isFile() && !file.delete()) { LOG.error("Could not delete file {}!!", file); } } public static void addCert(final String alias, final File cert, final File trustStore, final String storePass) { if (!cert.isFile()) { LOG.error("No cert at "+cert); return; } LOG.debug("Importing cert"); // Quick not on '-import' versus '-importcert' from the oracle docs: // "This command was named -import in previous releases. This old name // is still supported in this release and will be supported in future // releases, but for clarify the new name, -importcert, is preferred // going forward." // We use import for backwards compatibility. final String result = LanternUtils.runKeytool("-import", "-noprompt", "-file", cert.getAbsolutePath(), "-alias", alias, "-keystore", trustStore.getAbsolutePath(), "-storepass", storePass); LOG.debug("Result of running keytool: {}", result); } public static boolean isConnect(final HttpRequest request) { return request.getMethod() == HttpMethod.CONNECT; } public static InetSocketAddress isa(final String host, final int port) { final InetAddress ia; try { ia = InetAddress.getByName(host); } catch (final UnknownHostException e) { LOG.error("Bad host?", e); throw new Error("Bad host", e); } return new InetSocketAddress(ia, port); } public static URI newURI(final String userId) { try { return new URI(userId); } catch (URISyntaxException e) { LOG.error("Could not create URI from "+userId); throw new Error("Bad URI: "+userId); } } /** * We call this dynamically instead of using a constant because the API * PORT is set at startup, and we don't want to create a race condition * for retrieving it. * * @return The base URL for photos. */ public static String photoUrlBase() { return StaticSettings.getLocalEndpoint()+"/photo/"; } public static String defaultPhotoUrl() { return LanternUtils.photoUrlBase() + "?email=default"; } public static boolean fileContains(final File file, final String str) { InputStream fis = null; try { fis = new FileInputStream(file); final String text = IOUtils.toString(fis); return text.contains(str); } catch (final IOException e) { LOG.warn("Could not read file?", e); } finally { IOUtils.closeQuietly(fis); } return false; } /** * Modifies .desktop files on Ubuntu with out hack to set our icon. * * @param path The path to the file. */ public static void addStartupWMClass(final String path) { final File desktopFile = new File(path); if (!desktopFile.isFile()) { LOG.warn("No lantern desktop file at: {}", desktopFile); return; } final Collection<?> lines = Arrays.asList("StartupWMClass=127.0.0.1__"+ // We use the substring here to get rid of the leading "/" StaticSettings.getPrefix().substring(1)+"_index.html"); try { FileUtils.writeLines(desktopFile, "UTF-8", lines, true); } catch (final IOException e) { LOG.warn("Error writing to: "+desktopFile, e); } } public static String photoUrl(final String email) { try { return LanternUtils.photoUrlBase() + "?email=" + URLEncoder.encode(email, "UTF-8"); } catch (final UnsupportedEncodingException e) { LOG.error("Unsupported encoding?", e); throw new RuntimeException(e); } } public static String runCommand(final String cmd, final String... args) throws IOException { LOG.debug("Command: {}\nargs: {}", cmd, Arrays.asList(args)); final CommandLine command; if (SystemUtils.IS_OS_WINDOWS) { String[] cmdline = new String[args.length + 3]; cmdline[0] = "cmd.exe"; cmdline[1] = "/C"; cmdline[2] = cmd; for (int i=0; i<args.length; ++i) { cmdline[3+i] = args[i]; } command = new CommandLine(cmdline); } else { command = new CommandLine(cmd, args); } command.execute(); final String output = command.getStdOut(); if (!command.isSuccessful()) { final String msg = "Command failed!! Args: " + Arrays.asList(args) + " Result: " + output; LOG.error(msg); throw new IOException(msg); } return output; } public static void addCSPHeader(HttpServletResponse resp) { String[] paths = {"ws://127.0.0.1", "http://127.0.0.1", "ws://localhost", "http://localhost" }; List<String> policies = new ArrayList<String>(); for (String path : paths) { policies.add(path + ":" + StaticSettings.getApiPort()); } resp.addHeader("Content-Security-Policy", "default-src " + StringUtils.join(policies, " ") + " 'unsafe-inline' 'unsafe-eval'"); } /** * Returns whether or not this Lantern is running as a fallback proxy. * * @return <code>true</code> if it's a fallback proxy, otherwise * <code>false</code>. */ public static boolean isFallbackProxy() { return amFallbackProxy; } public static void setFallbackProxy() { // To check whether this is set in time for it to be picked up. LOG.info("I am a fallback proxy"); amFallbackProxy = true; } public static String getKeystorePath() { return keystorePath; } public static void setKeystorePath(final String path) { LOG.info("Setting keystorePath to '" + path + "'"); keystorePath = path; } /** * Compare two strings for equality securely. The first string is the * expected result, and the second string is the user input. The comparison * takes time proportional to the user input, so that (hopefully) the length * of the expected string is not leaked. * * @param expected * @param got * @return */ public static boolean constantTimeEquals(String expected, String got) { boolean equals = true; if (got == null) { return false; } for (int i = 0; i < got.length(); ++i) { if (i < expected.length()) { equals &= expected.charAt(i) == got.charAt(i); } else { // this is never true, but hopefully, the compiler // won't optimize it away; we want to make the same // number of calls to charAt regardless of the length // of expected equals &= expected.charAt(0) == (-1 | got.charAt(i)); } } return equals & expected.length() == got.length(); } public static String getFallbackServerHost() { return fallbackServerHost; } public static void setFallbackServerHost(final String fallbackServerHost) { LanternUtils.fallbackServerHost = fallbackServerHost; } public static int getFallbackServerPort() { return fallbackServerPort; } public static void setFallbackServerPort(final int fallbackServerPort) { LanternUtils.fallbackServerPort = fallbackServerPort; } }
package org.shirolang.base; import javafx.util.Pair; import org.shirolang.exceptions.OptionNotFoundException; import org.shirolang.exceptions.PathNotFoundException; import org.shirolang.values.Path; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Specifies a node in a subjunctive dependency graph. A node is simply a * reference to a collection of ports * */ public class SNode extends SFuncBase implements Scope{ // the node's parent scope; The value maybe another node or the global parametric system. private Scope parentScope; // type string for the node private String type; // options - could be nodes, or ports private Map<String, SFunc> options; // active option private SFunc activeOption; // default option private SFunc defaultOption; // nested nodes private Map<String, SNode> nestedNodes; // ports mapped localname -> Port private Map<String, SFunc> ports; private Map<Integer, String> portNameByIndex; private int portIndex; /** * Creates a new node with it's name and * type add to the empty string. * It's scope is null. */ public SNode() { super(); initializeVars("", "", null); } public SNode(String type, String name){ initializeVars(type, name, null); } /** * Creates a new node * @param type type of the node * @param name name of node ( the same as the type for prototype instances) * @param scope scope the node is in */ public SNode(String type, String name, Scope scope) { initializeVars(type, name, scope); } /** * Initializes variables. This is a work around to using this() in * a constructor with super * @param type type of node * @param name name of node ( the same as the type for prototype instances) * @param scope scope the node is in */ private final void initializeVars(String type, String name, Scope scope) { // type of node this.type = type; // add the enclosing scope this.parentScope = scope; // add the parent's full name based on the scope if (scope != null) { this.fullName.set(Path.createFullName(scope.getFullName(), name)); } else { this.fullName.set(name); } // add the name of the node this.name.set(name); // create map of options options = new HashMap<>(); // initialize the first option to null activeOption = null; // initialize default option defaultOption = null; // map of nested nodes nestedNodes = new HashMap<>(); // create map for the node's ports ports = new HashMap<>(); portNameByIndex = new HashMap<>(); portIndex = 0; symbolType = SymbolType.NODE; } /** * Gets the scope of the node * @return the scope of the node */ public Scope getScope() { return parentScope; } /** * Sets the parent scope * @param enclosingScope the scope the node is enclosed within */ public void setScope(Scope enclosingScope) { this.parentScope = enclosingScope; } /** * Adds a port to the node * @param port the port to be added */ public void addPort(SFunc port){ port.setFullName(Path.createFullName(fullName.get(), port.getName())); ports.put(port.getName(), port); portNameByIndex.put(portIndex, port.getName()); // increment so it's ready for the next time add is called portIndex++; } /** * Gets whether the node has ports * @return true if the node has ports, otherwise false */ public boolean hasPorts() { return !ports.isEmpty(); } /** * Gets a port by it's local name * @param name local name of the port * @return the port with the passed name. Returns null if a port with the given * name is not found. */ public SFunc getPort(String name){ return ports.get(name); } /** * Gets port by index * Ports are assigned indices in the order they are added to the node, starting with 0 * @param index of port to return * @return the port for the given index */ public SFunc getPort(int index){ return getPort(portNameByIndex.get(index)); } public Set<SFunc> getPorts(){ Set<SFunc> allPorts = new HashSet<>(); for(SFunc f: ports.values()){ if(f.isActive()) { allPorts.add(f); } } // get the ports of the tree of nested nodes for(SNode nested: nestedNodes.values()){ allPorts.addAll(nested.getPorts()); } return allPorts; } /** * Gets the default option for the node * @return a reference to the default option. Returns null * if no default is add. */ public SFunc getDefaultOption(){ return defaultOption; } /** * Sets the node's default option. * @param name name of node or port to add as default * @throws OptionNotFoundException */ public void setDefaultOption(String name) throws OptionNotFoundException { SFunc option = options.get(name); if(option == null){ throw new OptionNotFoundException(this.getFullName() + " does not have an option " + name); } defaultOption = option; } /** * Adds the option and makes it the default * @param option option to be added */ public void addOptionAsDefault(SFunc option){ addOption(option); defaultOption = option; } /** * Adds an option to the node The option is renamed to have the correct full * name. If another option exists that has the same name, it is overwritten. * * @param option option to be added */ public void addOption(SFunc option) { if(option.getName().isEmpty()){ throw new RuntimeException(option + " has no name. Cannot add an option with an empty name"); } // add the option to the appropriate collection if (option.getSymbolType().isNode()) { SNode n = (SNode) option; addNestedNode(n); } else { // option is a port addPort(option); } options.put(option.getName(), option); } /** * Gets the option with the given name * @param name name of the option * @return a reference to the option, or null it is not found */ public SFunc getOption(String name){ return options.get(name); } /** * Gets the options for the node * @return a reference to a new map containing the node's options */ public Map<String, SFunc> getOptions(){ return new HashMap<>(options); } /** * Gets the node name to option name pairs used * @return a add containing pairs of (nodename, optionName) for each * option in the node */ public Set<Pair<String, String>> getOptionPairs(){ Set<Pair<String, String>> pairs = new HashSet<>(); for(SFunc s: getOptions().values()){ pairs.add(new Pair<>(name.get(), s.getName())); } return pairs; } /** * Gets whether the node has options * @return true if the node has options, otherwise false */ public boolean hasOptions() { return !options.isEmpty(); } /** * Gets the node's active option * * @return Returns the SFunc of the node's active option. If no option is * active returns null. */ public SFunc getActiveOption() { return activeOption; } /** * Adds an option and makes it active * @param option option to be added */ public void addOptionAsActive(SFunc option){ addOption(option); activateOption(option); } /** * Sets the node's active option. Options are stored in a node in map by the * options name. To add the active option use the symbol's name, not it's * full name * * @param name name of symbol to add active * @return the symbol add active, returns null if name is not found * @throws OptionNotFoundException */ public SFunc setActiveOption(String name) throws OptionNotFoundException { SFunc activeItem = options.get(name); if(activeItem == null){ throw new OptionNotFoundException(this.getFullName() + " does not have an option " + name); } activateOption(activeItem); return activeOption; } /** * Activates the passed option * Deactivates all other options * @param option the option to activate */ private void activateOption(SFunc option) { // Create a add of the inactive options Set<SFunc> inactive = new HashSet<>(options.values()); inactive.remove(option); // deactivate the inactive options inactive.stream().forEach((s) -> s.setActive(false)); // activate the passed option option.setActive(true); activeOption = option; } /** * Gets the nested node of the given name * @param name name of the node * @return null if node is not found */ public SNode getNestedNode(String name){ return nestedNodes.get(name); } /** * Gets whether the node has nested nodes * * @return true if there are nested nodes, otherwise false */ public boolean hasNestedNodes() { return !nestedNodes.isEmpty(); } /** * Adds a nested node. The node is stored in a map by its name. When a node * is nested it's name is changed to reflect its position in the hierarchy * * @param n node to nest */ public void addNestedNode(SNode n) { n.setScope(this); n.setFullName(Path.createFullName(fullName.get(), n.getName())); nestedNodes.put(n.getName(), n); } /** * Set the node's full name * * @param fullName name to be add */ @Override public void setFullName(String fullName) { super.setFullName(fullName); updateNames(this.fullName.get()); } @Override public void setName(String name) { super.setName(name); // update all the contained nodes and options updateNames(fullName.get()); } /** * Updates the names of all nested nodes and ports * @param fullName */ private void updateNames(String fullName) { // update both the nested nodes and ports // Since they both implement SFunc, create // one list and update Set<SFunc> itemsToUpdate = new HashSet<>(); itemsToUpdate.addAll(ports.values()); itemsToUpdate.addAll(nestedNodes.values()); for(SFunc p: itemsToUpdate){ p.setFullName(Path.createFullName(fullName, p.getName())); } } @Override public void evaluate() { // LEAVE empty. A node should never be evaluated // Evaluation in shiro happens based on ports. // todo handle node evaluation. // This is where we will deal with the mechanics of having a // node evaluate itself when it's not attached to a graph. // this will happen when a node is passed as a lambda } @Override public int getMaxArgs() { return 0; } @Override public int getMinArgs() { return 0; } @Override public String getType() { return type; } @Override public SFunc resolvePath(Path path) throws PathNotFoundException { SFunc portReferenced = null; String pathHead = path.getCurrentPathHead(); if(pathHead.equals("active") || pathHead.equals("this") || path.isAtEnd()){ if(pathHead.equals("active")){ // if active refers to a port if(path.isAtEnd()){ portReferenced = activeOption; path.resetPathHead(); }else if (activeOption.getSymbolType().isNode()){ // if active refers to a node path.popPathHead(); SNode subjunct = (SNode) activeOption; portReferenced = subjunct.resolvePath(path); } }else { if (pathHead.equals("this")) { // move up the path path.popPathHead(); } String portName = path.getCurrentPathHead(); portReferenced = ports.get(portName); if(path.hasIndex()){ if(path.hasIntegerIndex()){ portReferenced = portReferenced.getResult(path.getIndex()); } if(path.hasStringIndex()){ portReferenced = portReferenced.getResult(path.getIndexKey()); } } // reset the path for future use path.resetPathHead(); } }else{ // check the nested nodes if(hasNestedNodes()){ Scope nestedNodeMatch = nestedNodes.get(path.getCurrentPathHead()); if (nestedNodeMatch != null) { // pop the head and search the nested node path.popPathHead(); portReferenced = nestedNodeMatch.resolvePath(path); } }else{ path.resetPathHead(); portReferenced = parentScope.resolvePath(path); } } if(portReferenced == null){ throw new PathNotFoundException(path + " was not found."); } return portReferenced; } @Override public SFunc resolvePath(String path) throws PathNotFoundException { return resolvePath(Path.create(path)); } @Override public boolean isRoot() { return false; } }
package rocks.matchmaker; import rocks.matchmaker.util.Util; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Predicate; public class Matcher<T> { public static Matcher<Object> $() { return $(Object.class); } public static <T> Matcher<T> equalTo(T expectedValue) { Util.checkArgument(expectedValue != null, "expectedValue can't be null. Use `Matcher.isNull()` instead"); Class<T> expectedClass = (Class<T>) expectedValue.getClass(); return $(expectedClass).$(x -> x.equals(expectedValue)); } public static <T> Matcher<T> $(Class<T> expectedClass) { BiFunction<Object, Captures, Match<T>> matchFunction = (x, captures) -> Match.of(x, captures) .filter(expectedClass::isInstance) .map(expectedClass::cast); return new Matcher<>(expectedClass, matchFunction, null); } @SuppressWarnings("unchecked cast") public static <T> Matcher<T> isNull() { return (Matcher<T>) nullable(Object.class).$(Objects::isNull); } public static <T> Matcher<T> nullable(Class<T> expectedClass) { BiFunction<Object, Captures, Match<T>> matchFunction = (x, captures) -> Match.of(x, captures) .filter(value -> value == null || expectedClass.isInstance(value)) .map(expectedClass::cast); return new Matcher<>(expectedClass, matchFunction, null); } //This expresses the fact that Matcher is covariant on T. //This is saying "Matcher<? extends T> is a Matcher<T>". @SuppressWarnings("unchecked cast") public static <T> Matcher<T> upcast(Matcher<? extends T> matcher) { return (Matcher<T>) matcher; } //scopeType unused for now, but will help in debugging and structural equalTo later private final Class<?> scopeType; private final BiFunction<Object, Captures, Match<T>> matchFunction; private final Capture<T> capture; //TODO think how to not have this package-private? Make Matcher an interface? Matcher(Class<?> scopeType, BiFunction<Object, Captures, Match<T>> matchFunction, Capture<T> capture) { this.scopeType = scopeType; this.matchFunction = matchFunction; this.capture = capture; } protected static <T> Match<T> createMatch(Capture<T> capture, T matchedValue, Captures captures) { return Match.of(matchedValue, captures.addAll(Captures.ofNullable(capture, matchedValue))); } public Matcher<T> as(Capture<T> capture) { if (this.capture != null) { throw new IllegalStateException("This matcher already has a capture alias"); } BiFunction<Object, Captures, Match<T>> newMatchFunction = matchFunction.andThen(match -> match.flatMap(value -> createMatch(capture, value, match.captures()))); return new Matcher<>(scopeType, newMatchFunction, capture); } public Matcher<T> $(Predicate<? super T> predicate) { return flatMap((value, captures) -> Match.of(value, captures) .filter(predicate)); } /** * For cases when evaluating a property is needed to check * if it's possible to construct an object and that object's * construction largely repeats checking the property. * <p> * E.g. let's say we have a set and we'd like to match * other sets having a non-empty intersection with it. * If the intersection is not empty, we'd like to use it * in further computations. Extractors allow for exactly that. * <p> * An adequate extractor for the example above would compute * the intersection and return it wrapped in a Match * (think: null-capable Optional with a field for storing captures). * If the intersection would be empty, the extractor should * would a non-match by returning Match.empty(). * * @param extractor * @param <R> type of the extracted value * @return */ public <R> Matcher<R> $(Extractor<T, R> extractor) { return flatMap((value, captures) -> extractor.apply(value, captures) .map(v -> Match.of(v, captures)) .orElse(Match.empty())); } public <R> Matcher<R> $(Matcher<R> matcher) { return flatMap(matcher.matchFunction); } public <R> Matcher<T> $(PropertyMatcher<? super T, R> matcher) { PropertyMatcher<T, R> castMatcher = PropertyMatcher.upcast(matcher); return this.flatMap((selfMatchValue, captures) -> { Option<?> propertyOption = castMatcher.getProperty().apply(selfMatchValue); Match<R> propertyMatch = propertyOption .map(value -> castMatcher.getMatcher().match(value, captures)) .orElse(Match.empty()); return propertyMatch.map(__ -> selfMatchValue); }); } protected <R> Matcher<R> flatMap(BiFunction<? super T, Captures, Match<R>> mapper) { BiFunction<Object, Captures, Match<R>> newMatchFunction = (object, captures) -> { Match<T> originalMatch = matchFunction.apply(object, captures); return originalMatch.flatMap(value -> mapper.apply(value, originalMatch.captures())); }; return new Matcher<>(scopeType, newMatchFunction, null); } //Usage of this method within the library's code almost always means an error because of lost captures. public Match<T> match(Object object) { return match(object, Captures.empty()); } public Match<T> match(Object object, Captures captures) { return matchFunction.apply(object, captures); } Class<?> getScopeType() { return scopeType; } }
package seedu.jimi.ui; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.MenuItem; import javafx.scene.input.KeyCombination; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; import seedu.jimi.commons.core.Config; import seedu.jimi.commons.core.GuiSettings; import seedu.jimi.commons.events.ui.ExitAppRequestEvent; import seedu.jimi.logic.Logic; import seedu.jimi.model.UserPrefs; import seedu.jimi.model.task.ReadOnlyTask; /** * The Main Window. Provides the basic application layout containing * a menu bar and space where other JavaFX elements can be placed. */ public class MainWindow extends UiPart { private static final String ICON = "/images/jimi_icon_32.png"; private static final String FXML = "MainWindow.fxml"; public static final int MIN_HEIGHT = 600; public static final int MIN_WIDTH = 450; private Logic logic; // Independent Ui parts residing in this Ui container private BrowserPanel browserPanel; private TaskListPanel taskListPanel; private ResultDisplay resultDisplay; private StatusBarFooter statusBarFooter; private CommandBox commandBox; private Config config; private UserPrefs userPrefs; // Handles to elements of this Ui container private VBox rootLayout; private Scene scene; private String addressBookName; @FXML private AnchorPane browserPlaceholder; @FXML private AnchorPane commandBoxPlaceholder; @FXML private MenuItem helpMenuItem; @FXML private AnchorPane personListPanelPlaceholder; @FXML private AnchorPane resultDisplayPlaceholder; @FXML private AnchorPane statusbarPlaceholder; public MainWindow() { super(); } @Override public void setNode(Node node) { rootLayout = (VBox) node; } @Override public String getFxmlPath() { return FXML; } public static MainWindow load(Stage primaryStage, Config config, UserPrefs prefs, Logic logic) { MainWindow mainWindow = UiPartLoader.loadUiPart(primaryStage, new MainWindow()); mainWindow.configure(config.getAppTitle(), config.getTaskBookName(), config, prefs, logic); return mainWindow; } private void configure(String appTitle, String addressBookName, Config config, UserPrefs prefs, Logic logic) { //Set dependencies this.logic = logic; this.addressBookName = addressBookName; this.config = config; this.userPrefs = prefs; //Configure the UI setTitle(appTitle); setIcon(ICON); setWindowMinSize(); setWindowDefaultSize(prefs); scene = new Scene(rootLayout); primaryStage.setScene(scene); setAccelerators(); } private void setAccelerators() { helpMenuItem.setAccelerator(KeyCombination.valueOf("F1")); } void fillInnerParts() { browserPanel = BrowserPanel.load(browserPlaceholder); taskListPanel = TaskListPanel.load(primaryStage, getPersonListPlaceholder(), logic.getFilteredTaskList()); resultDisplay = ResultDisplay.load(primaryStage, getResultDisplayPlaceholder()); statusBarFooter = StatusBarFooter.load(primaryStage, getStatusbarPlaceholder(), config.getTaskBookFilePath()); commandBox = CommandBox.load(primaryStage, getCommandBoxPlaceholder(), resultDisplay, logic); } private AnchorPane getCommandBoxPlaceholder() { return commandBoxPlaceholder; } private AnchorPane getStatusbarPlaceholder() { return statusbarPlaceholder; } private AnchorPane getResultDisplayPlaceholder() { return resultDisplayPlaceholder; } public AnchorPane getPersonListPlaceholder() { return personListPanelPlaceholder; } public void hide() { primaryStage.hide(); } private void setTitle(String appTitle) { primaryStage.setTitle(appTitle); } /** * Sets the default size based on user preferences. */ protected void setWindowDefaultSize(UserPrefs prefs) { primaryStage.setHeight(prefs.getGuiSettings().getWindowHeight()); primaryStage.setWidth(prefs.getGuiSettings().getWindowWidth()); if (prefs.getGuiSettings().getWindowCoordinates() != null) { primaryStage.setX(prefs.getGuiSettings().getWindowCoordinates().getX()); primaryStage.setY(prefs.getGuiSettings().getWindowCoordinates().getY()); } } private void setWindowMinSize() { primaryStage.setMinHeight(MIN_HEIGHT); primaryStage.setMinWidth(MIN_WIDTH); } /** * Returns the current size and the position of the main Window. */ public GuiSettings getCurrentGuiSetting() { return new GuiSettings(primaryStage.getWidth(), primaryStage.getHeight(), (int) primaryStage.getX(), (int) primaryStage.getY()); } @FXML public void handleHelp() { HelpWindow helpWindow = HelpWindow.load(primaryStage); helpWindow.show(); } public void show() { primaryStage.show(); } /** * Closes the application. */ @FXML private void handleExit() { raise(new ExitAppRequestEvent()); } public TaskListPanel getTaskListPanel() { return this.taskListPanel; } public void loadPersonPage(ReadOnlyTask person) { browserPanel.loadPersonPage(person); } public void releaseResources() { browserPanel.freeResources(); } }