answer
stringlengths
17
10.2M
package enmasse.systemtest; import io.vertx.proton.ProtonClient; import io.vertx.proton.ProtonConnection; import io.vertx.proton.ProtonReceiver; import org.apache.qpid.proton.amqp.Symbol; import org.apache.qpid.proton.amqp.messaging.AmqpSequence; import org.apache.qpid.proton.amqp.messaging.Source; import org.junit.Test; import java.util.*; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; public class ConfigServTest extends VertxTestBase { @SuppressWarnings("unchecked") @Test public void testPodSense() throws Exception { Endpoint configserv = getConfigServEndpoint(); BlockingQueue<List<String>> latestPods = new LinkedBlockingDeque<>(); ProtonClient.create(vertx).connect(configserv.getHost(), configserv.getPort(), event -> { if (event.succeeded()) { ProtonConnection connection = event.result().open(); Source source = new Source(); source.setAddress("podsense"); source.setFilter(Collections.singletonMap(Symbol.getSymbol("role"), "broker")); ProtonReceiver receiver = connection.createReceiver("podsense").setSource(source); receiver.handler((protonDelivery, message) -> { List<String> pods = new ArrayList<>(); AmqpSequence seq = (AmqpSequence) message.getBody(); for (Object obj : seq.getValue()) { Map<String, Object> pod = (Map<String, Object>) obj; pods.add((String) pod.get("host")); } try { latestPods.put(pods); } catch (InterruptedException e) { fail(); } }); receiver.open(); } }); deploy(Destination.queue("testqueue")); assertPods(latestPods, 1, new TimeoutBudget(2, TimeUnit.MINUTES)); deploy(Destination.queue("testqueue"), Destination.queue("anotherqueue")); assertPods(latestPods, 2, new TimeoutBudget(2, TimeUnit.MINUTES)); deploy(Destination.queue("anotherqueue")); assertPods(latestPods, 1, new TimeoutBudget(2, TimeUnit.MINUTES)); } private void assertPods(BlockingQueue<List<String>> latestPods, int numPods, TimeoutBudget timeoutBudget) throws InterruptedException { List<String> pods = null; do { pods = latestPods.poll(timeoutBudget.timeLeft(), TimeUnit.MILLISECONDS); } while ((pods == null || pods.size() != numPods) && timeoutBudget.timeLeft() >= 0); assertNotNull(pods); assertThat(pods.size(), is(numPods)); } private Endpoint getConfigServEndpoint() { if (openShift.isFullTemplate()) { return openShift.getEndpoint("configuration", "amqp"); } else { return openShift.getEndpoint("admin", "configuration"); } } }
package net.aeronica.mods.mxtune.init; import net.aeronica.mods.mxtune.MXTuneMain; import net.aeronica.mods.mxtune.blocks.BlockPiano; import net.aeronica.mods.mxtune.blocks.TilePiano; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.util.CompoundDataFixer; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.registries.IForgeRegistry; import java.util.HashSet; import java.util.Set; @SuppressWarnings("unused") public class ModBlocks { public static final BlockPiano SPINET_PIANO = registerBlock(new BlockPiano(), "spinet_piano"); private ModBlocks() {} @Mod.EventBusSubscriber public static class RegistrationHandler { protected static final Set<Item> ITEM_BLOCKS = new HashSet<>(); private RegistrationHandler() {} /** * Register this mod's {@link Block}s. * * @param event The event */ @SubscribeEvent public static void registerBlocks(RegistryEvent.Register<Block> event) { final IForgeRegistry<Block> registry = event.getRegistry(); final Block[] blocks = { SPINET_PIANO, }; registry.registerAll(blocks); } /** * Register this mod's {@link ItemBlock}s. * * @param event The event */ @SubscribeEvent public static void registerItemBlocks(RegistryEvent.Register<Item> event) { final ItemBlock[] items = { }; final IForgeRegistry<Item> registry = event.getRegistry(); for (final ItemBlock item : items) { registry.register(item.setRegistryName(item.getBlock().getRegistryName())); ITEM_BLOCKS.add(item); } registerTileEntities(); } } private static void registerTileEntities() { GameRegistry.registerTileEntity(TilePiano.class, new ResourceLocation(MXTuneMain.MODID,"tile_piano")); CompoundDataFixer x; } private static <T extends Block> T registerBlock(T block, String name) { block.setRegistryName(name.toLowerCase()); block.setTranslationKey(block.getRegistryName().toString()); return block; } private static <T extends Block> T registerBlock(T block) { return registerBlock(block, block.getClass().getSimpleName()); } private static void registerTileEntity(Class<? extends TileEntity> tileEntityClass, String name) { GameRegistry.registerTileEntity(tileEntityClass, MXTuneMain.prependModID(name)); } }
package net.imagej.legacy.search; import net.imagej.legacy.LegacyService; import org.scijava.Priority; import org.scijava.command.Command; import org.scijava.plugin.Menu; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; /** * Command which focuses the ImageJ search bar. * <p> * This overrides the old ImageJ 1.x Command Finder plugin. * </p> * * @author Curtis Rueden */ @Plugin(type = Command.class, menu = { @Menu(label = "Plugins"), @Menu( label = "Utilities"), @Menu(label = "Focus Search Bar", accelerator = "meta L") }, priority = Priority.HIGH) public class FocusSearchBar implements Command { @Parameter private LegacyService legacyService; @Override public void run() { final SearchBar searchBar = legacyService.getIJ1Helper().getSearchBar(); if (searchBar != null) searchBar.activate(); } }
package liquibase.ext.spatial; import static org.testng.Assert.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import liquibase.Contexts; import liquibase.Liquibase; import liquibase.changelog.ChangeSet; import liquibase.database.jvm.JdbcConnection; import liquibase.exception.LiquibaseException; import liquibase.logging.LogFactory; import liquibase.resource.ClassLoaderResourceAccessor; import liquibase.resource.ResourceAccessor; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Performs a full integration test of all preconditions, changes, statements and SQL generators * with Liquibase. */ public abstract class LiquibaseIT { /** * Returns the database name. * * @return the database name. */ protected String getDatabaseName() { return "test"; } /** * Returns the database connection URL. * * @return the connection URL. */ protected abstract String getUrl(); /** * Returns the login user name. * * @return the user name. */ protected String getUserName() { return null; } /** * Returns the login password. * * @return the password. */ protected String getPassword() { return null; } /** * Returns the database connection to the current database. * * @return the database connection. * @throws SQLException * if unable to get the current database connection. */ protected final Connection getConnection() throws SQLException { final String url = getUrl(); final String username = getUserName(); final String password = getPassword(); if (username != null) { return DriverManager.getConnection(url, username, password); } return DriverManager.getConnection(url); } @BeforeMethod @AfterMethod public void cleanUpDatabase() throws SQLException { System.out.println("Cleaning up the database"); Connection connection = null; try { connection = getConnection(); // Drop the TEST table. Statement statement = connection.createStatement(); try { statement.execute("DROP TABLE TEST"); } catch (final Exception ignore) { } finally { statement.close(); } // Drop the DATABASECHANGELOG table. statement = connection.createStatement(); try { statement.execute("DROP TABLE DATABASECHANGELOG"); } catch (final Exception ignore) { } finally { statement.close(); } // Drop the DATABASECHANGELOGLOCK table. statement = connection.createStatement(); try { statement.execute("DROP TABLE DATABASECHANGELOGLOCK"); } catch (final Exception ignore) { } finally { statement.close(); } } catch (final Exception ignore) { } finally { if (connection != null) { connection.close(); } } } /** * Initialization for each test. */ @SuppressWarnings("deprecation") @BeforeTest public void setUp() throws Exception { LogFactory.setLoggingLevel("debug"); } /** * Tests Liquibase updating and rolling back the database. * * @param changeLogFile * the database change log to use in the {@link Liquibase#update(Contexts) update}. * @throws LiquibaseException * if Liquibase fails to initialize or run the update. * @throws SQLException * if unable to get the database connection. */ @Test(dataProvider = "databaseUrlProvider") public void testLiquibaseUpdateTestingRollback(final String changeLogFile) throws LiquibaseException, SQLException { final Connection connection = getConnection(); final JdbcConnection jdbcConnection = new JdbcConnection(connection); try { final ResourceAccessor resourceAccessor = new ClassLoaderResourceAccessor(); final Liquibase liquibase = new Liquibase(changeLogFile, resourceAccessor, jdbcConnection); liquibase.updateTestingRollback((Contexts) null); final List<ChangeSet> unrunChangeSets = liquibase.listUnrunChangeSets((Contexts) null); assertTrue(unrunChangeSets.isEmpty(), "All change sets should have run"); } finally { jdbcConnection.rollback(); jdbcConnection.close(); } } /** * Provides the test data for {@link #testLiquibase(String)}. * * @return the test data. */ @DataProvider public Object[][] databaseUrlProvider() { return new Object[][] { new Object[] { "create-table-index-drop-index-table.xml" }, new Object[] { "create-table-index-drop-table.xml" }, new Object[] { "add-column-create-index-drop-column.xml" } }; } }
package net.imagej.ops; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import net.imagej.ops.OpCandidate.StatusCode; import org.scijava.Context; import org.scijava.InstantiableException; import org.scijava.command.CommandInfo; import org.scijava.command.CommandService; import org.scijava.convert.ConvertService; import org.scijava.log.LogService; import org.scijava.module.Module; import org.scijava.module.ModuleInfo; import org.scijava.module.ModuleItem; import org.scijava.module.ModuleService; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; import org.scijava.service.AbstractService; import org.scijava.service.Service; /** * Default service for finding {@link Op}s which match a request. * * @author Curtis Rueden */ @Plugin(type = Service.class) public class DefaultOpMatchingService extends AbstractService implements OpMatchingService { @Parameter private Context context; @Parameter private ModuleService moduleService; @Parameter private CommandService commandService; @Parameter private ConvertService convertService; @Parameter private LogService log; // -- OpMatchingService methods -- @Override public List<CommandInfo> getOps() { return commandService.getCommandsOfType(Op.class); } @Override public <OP extends Op> Module findModule(final OpRef<OP> ref) { // find candidates with matching name & type final List<OpCandidate<OP>> candidates = findCandidates(ref); if (candidates.isEmpty()) { throw new IllegalArgumentException("No candidate '" + ref.getLabel() + "' ops"); } // narrow down candidates to the exact matches final List<Module> matches = findMatches(candidates); if (matches.size() == 1) { // a single match: return it if (log.isDebug()) { log.debug("Selected '" + ref.getLabel() + "' op: " + matches.get(0).getDelegateObject().getClass().getName()); } return matches.get(0); } final String analysis = OpUtils.matchInfo(candidates, matches); throw new IllegalArgumentException(analysis); } @Override public <OP extends Op> List<OpCandidate<OP>> findCandidates( final OpRef<OP> ref) { final ArrayList<OpCandidate<OP>> candidates = new ArrayList<OpCandidate<OP>>(); for (final CommandInfo info : getOps()) { if (isCandidate(info, ref)) { candidates.add(new OpCandidate<OP>(ref, info)); } } return candidates; } @Override public <OP extends Op> List<Module> findMatches( final List<OpCandidate<OP>> candidates) { final ArrayList<Module> matches = new ArrayList<Module>(); double priority = Double.NaN; for (final OpCandidate<?> candidate : candidates) { final ModuleInfo info = candidate.getInfo(); final double p = info.getPriority(); if (p != priority && !matches.isEmpty()) { // NB: Lower priority was reached; stop looking for any more matches. break; } priority = p; final Module module = match(candidate); if (module != null) matches.add(module); } return matches; } @Override public <OP extends Op> Module match(final OpCandidate<OP> candidate) { if (!valid(candidate)) return null; final Object[] args = padArgs(candidate); return args == null ? null : match(candidate, args); } @Override public <OP extends Op> boolean typesMatch(final OpCandidate<OP> candidate) { if (!valid(candidate)) return false; final Object[] args = padArgs(candidate); return args == null ? false : typesMatch(candidate, args); } @Override public Module assignInputs(final Module module, final Object... args) { int i = 0; for (final ModuleItem<?> item : module.getInfo().inputs()) { assign(module, args[i++], item); } return module; } @Override public <OP extends Op> Object[] padArgs(final OpCandidate<OP> candidate) { int inputCount = 0, requiredCount = 0; for (final ModuleItem<?> item : candidate.getInfo().inputs()) { inputCount++; if (item.isRequired()) requiredCount++; } final Object[] args = candidate.getRef().getArgs(); if (args.length == inputCount) { // correct number of arguments return args; } if (args.length > inputCount) { // too many arguments candidate.setStatus(StatusCode.TOO_MANY_ARGS, args.length + " > " + inputCount); return null; } if (args.length < requiredCount) { // too few arguments candidate.setStatus(StatusCode.TOO_FEW_ARGS, args.length + " < " + requiredCount); return null; } // pad optional parameters with null (from right to left) final int argsToPad = inputCount - args.length; final int optionalCount = inputCount - requiredCount; final int optionalsToFill = optionalCount - argsToPad; final Object[] paddedArgs = new Object[inputCount]; int argIndex = 0, paddedIndex = 0, optionalIndex = 0; for (final ModuleItem<?> item : candidate.getInfo().inputs()) { if (!item.isRequired() && optionalIndex++ >= optionalsToFill) { // skip this optional parameter (pad with null) paddedIndex++; continue; } paddedArgs[paddedIndex++] = args[argIndex++]; } return paddedArgs; } // -- Helper methods -- /** Helper method of {@link #findCandidates}. */ private <OP extends Op> boolean isCandidate(final CommandInfo info, final OpRef<OP> ref) { if (!nameMatches(info, ref.getName())) return false; // the name matches; now check the class final Class<?> opClass; try { opClass = info.loadClass(); } catch (final InstantiableException exc) { log.error("Invalid op: " + info.getClassName()); return false; } return ref.getType() == null || ref.getType().isAssignableFrom(opClass); } /** Verifies that the given candidate's module is valid. */ private <OP extends Op> boolean valid(final OpCandidate<OP> candidate) { if (candidate.getInfo().isValid()) return true; candidate.setStatus(StatusCode.INVALID_MODULE); return false; } /** Helper method of {@link #match(OpCandidate)}. */ private <OP extends Op> Module match(final OpCandidate<OP> candidate, final Object[] args) { // check that each parameter is compatible with its argument if (!typesMatch(candidate, args)) return null; // create module and assign the inputs final Module module = createModule(candidate.getInfo(), args); candidate.setModule(module); // make sure the op itself is happy with these arguments final Object op = module.getDelegateObject(); if (op instanceof Contingent) { final Contingent c = (Contingent) op; if (!c.conforms()) { candidate.setStatus(StatusCode.DOES_NOT_CONFORM); return null; } } // found a match! return module; } /** * Checks that each parameter is type-compatible with its corresponding * argument. */ private <OP extends Op> boolean typesMatch(final OpCandidate<OP> candidate, final Object[] args) { int i = 0; for (final ModuleItem<?> item : candidate.getInfo().inputs()) { final Object arg = args[i++]; if (!canAssign(candidate, arg, item)) return false; } return true; } /** Helper method of {@link #isCandidate}. */ private boolean nameMatches(final ModuleInfo info, final String name) { if (name == null) return true; // not filtering on name // check if name matches exactly final String infoName = info.getName(); if (name.equals(infoName)) return true; // check if name matches w/o namespace (e.g., 'add' matches 'math.add') if (infoName != null) { final int dot = infoName.lastIndexOf("."); if (dot >= 0 && name.equals(infoName.substring(dot + 1))) return true; } // check for an alias final String alias = info.get("alias"); if (name.equals(alias)) return true; // check for a list of aliases final String aliases = info.get("aliases"); if (aliases != null) { for (final String a : aliases.split(",")) { if (name.equals(a.trim())) return true; } } return false; } /** Helper method of {@link #match(OpCandidate, Object[])}. */ private Module createModule(final ModuleInfo info, final Object... args) { final Module module = moduleService.createModule(info); context.inject(module.getDelegateObject()); return assignInputs(module, args); } /** Helper method of {@link #match(OpCandidate, Object[])}. */ private boolean canAssign(final OpCandidate<?> candidate, final Object arg, final ModuleItem<?> item) { if (arg == null) { if (item.isRequired()) { candidate.setStatus(StatusCode.REQUIRED_ARG_IS_NULL, null, item); return false; } return true; } final Type type = item.getGenericType(); if (!canConvert(arg, type)) { candidate.setStatus(StatusCode.CANNOT_CONVERT, arg.getClass().getName() + " => " + type, item); return false; } return true; } /** Helper method of {@link #canAssign}. */ private boolean canConvert(final Object arg, final Type type) { if (isMatchingClass(arg, type)) { // NB: Class argument for matching, to help differentiate op signatures. return true; } return convertService.supports(arg, type); } /** Helper method of {@link #assignInputs}. */ private void assign(final Module module, final Object arg, final ModuleItem<?> item) { if (arg != null) { final Type type = item.getGenericType(); final Object value = convert(arg, type); module.setInput(item.getName(), value); } module.setResolved(item.getName(), true); } /** Helper method of {@link #assign}. */ private Object convert(final Object arg, final Type type) { if (isMatchingClass(arg, type)) { // NB: Class argument for matching; fill with null. return null; } return convertService.convert(arg, type); } /** Determines whether the argument is a matching class instance. */ private boolean isMatchingClass(final Object arg, final Type type) { return arg instanceof Class && convertService.supports((Class<?>) arg, type); } }
package me.abeyta.it; import java.util.List; import org.springframework.stereotype.Component; import me.abeyta.deckmanager.model.Deck; import net.serenitybdd.core.Serenity; @Component public class IntegrationTestState { public void clear() { Serenity.getCurrentSession().clear(); } @SuppressWarnings("unchecked") private <T> T getFromSession(String key) { try { return (T) Serenity.getCurrentSession().get(key); } catch (Exception e) { return null; //nothing in session } } private void putInSession(String key, Object value) { Serenity.getCurrentSession().put(key, value); } public void setDeckName(String deckName) { putInSession("deckName", deckName); } public String getDeckName() { return getFromSession("deckName"); } public Deck getDeck() { return getFromSession("deck"); } public void setDeck(Deck deck) { putInSession("deck", deck); } public Deck getShuffledDeck() { return getFromSession("shuffledDeck"); } public void setShuffledDeck(Deck deck) { putInSession("shuffledDeck", deck); } public void setDeckList(List<String> decks) { putInSession("deckList", decks); } public List<String> getDeckList(){ return getFromSession("deckList"); } }
package net.imagej.ops.image.ascii; import net.imagej.ops.Ops; import net.imagej.ops.special.function.AbstractUnaryFunctionOp; import net.imagej.ops.special.function.Functions; import net.imagej.ops.special.function.UnaryFunctionOp; import net.imglib2.Cursor; import net.imglib2.IterableInterval; import net.imglib2.type.numeric.RealType; import net.imglib2.util.Pair; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; /** * Generates an ASCII version of an image. * <p> * Only the first two dimensions of the image are considered. * </p> * * @author Curtis Rueden */ @Plugin(type = Ops.Image.ASCII.class) public class DefaultASCII<T extends RealType<T>> extends AbstractUnaryFunctionOp<IterableInterval<T>, String> implements Ops.Image.ASCII { private static final String CHARS = " @Parameter(required = false) private T min; @Parameter(required = false) private T max; private UnaryFunctionOp<IterableInterval<T>, Pair<T, T>> minMaxFunc; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public void initialize() { minMaxFunc = (UnaryFunctionOp) Functions.unary(ops(), Ops.Stats.MinMax.class, Pair.class, in()); } @Override public String calculate(final IterableInterval<T> input) { if (min == null || max == null) { final Pair<T, T> minMax = minMaxFunc.calculate(input); if (min == null) min = minMax.getA(); if (max == null) max = minMax.getB(); } return ascii(input, min, max); } // -- Utility methods -- public static <T extends RealType<T>> String ascii( final IterableInterval<T> image, final T min, final T max) { final long dim0 = image.dimension(0); final long dim1 = image.dimension(1); // TODO: Check bounds. final int w = (int) (dim0 + 1); final int h = (int) dim1; // span = max - min final T span = max.copy(); span.sub(min); // allocate ASCII character array final char[] c = new char[w * h]; for (int y = 1; y <= h; y++) { c[w * y - 1] = '\n'; // end of row } // loop over all available positions final Cursor<T> cursor = image.localizingCursor(); final int[] pos = new int[image.numDimensions()]; final T tmp = image.firstElement().copy(); while (cursor.hasNext()) { cursor.fwd(); cursor.localize(pos); final int index = w * pos[1] + pos[0]; // normalized = (value - min) / (max - min) tmp.set(cursor.get()); tmp.sub(min); final double normalized = tmp.getRealDouble() / span.getRealDouble(); final int charLen = CHARS.length(); final int charIndex = (int) (charLen * normalized); c[index] = CHARS.charAt(charIndex < charLen ? charIndex : charLen - 1); } return new String(c); } }
package net.sf.gaboto.test; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import net.sf.json.JSONObject; import net.sf.json.test.JSONAssert; import org.custommonkey.xmlunit.XMLAssert; import junit.framework.TestCase; /** * @author Tim Pizey * @since 15 May 2009 * */ public class GabotoTestCase extends TestCase { protected static String referenceOutputDir = "src/test/reference"; protected static String actualOutputDir = "target"; /** * Default constructor. */ public GabotoTestCase() { super(); } /** * Constructor, with name. * @param name */ public GabotoTestCase(String name) { super(name); } protected boolean generateReferenceCopy() { return false; } protected void assertXmlEqual(String actual, String fileName) throws Exception { File actualFile = new File(actualOutputDir, fileName); FileOutputStream actualOutputStream = new FileOutputStream(actualFile); actualOutputStream.write(actual.getBytes()); actualOutputStream.close(); File referenceFile = new File(referenceOutputDir, fileName); if (referenceFile.exists() && ! generateReferenceCopy()) { FileInputStream file = new FileInputStream (referenceFile); byte[] b = new byte[file.available()]; file.read(b); file.close (); String cached = new String(b); XMLAssert.assertXMLEqual("Cached not equal to generated", cached, actual); } else { actualFile.renameTo(referenceFile); fail("Reference output file generated: " + referenceFile.getCanonicalPath() + " modify generateCached and rerun"); } } protected void assertPageJsonEqual(String actual, String referenceFileName) throws Exception { JSONObject actualJson = JSONObject.fromObject(tidy(actual)); File generatedFile = new File(actualOutputDir, referenceFileName); FileOutputStream generatedOutput = new FileOutputStream(generatedFile); generatedOutput.write(actual.getBytes()); generatedOutput.close(); File referenceFile = new File(referenceOutputDir, referenceFileName); if (referenceFile.exists() && ! generateReferenceCopy()) { FileInputStream file = new FileInputStream (referenceFile); byte[] b = new byte[file.available()]; file.read(b); file.close (); String cached = new String(b); JSONObject expectedJson = JSONObject.fromObject(tidy(cached)); JSONAssert.assertEquals(expectedJson, actualJson); } else { generatedFile.renameTo(referenceFile); fail("Reference output file generated: " + referenceFile.getCanonicalPath() + " modify generateCached and rerun"); } } protected static String tidy(String json) { json = json.trim(); if (json.startsWith("[")) { json = json.substring(1); if (json.endsWith("]")) json = json.substring(0, json.length() -1); else throw new RuntimeException("Unbalanced square brackets"); } return json; } }
package net.malisis.core.network; import java.util.List; import net.malisis.core.IMalisisMod; import net.malisis.core.MalisisCore; import net.malisis.core.inventory.message.OpenInventoryMessage; import net.malisis.core.util.EntityUtils; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.world.chunk.Chunk; import net.minecraftforge.fml.common.discovery.ASMDataTable; import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; import net.minecraftforge.fml.relauncher.Side; import com.google.common.base.Function; import com.google.common.collect.Ordering; /** * {@link MalisisNetwork} is a wrapper around {@link SimpleNetworkWrapper} in order to ease the handling of discriminators.<br> * Each mod should instantiate a {@code MalisisNetwork} instance when constructed, and {@link IMessageHandler} should be annotated with * {@link MalisisMessage} and register their packets inside their own public paramless constructors.<br> * <br> * Example : {@link OpenInventoryMessage}. * * * @author Ordinastie */ public class MalisisNetwork extends SimpleNetworkWrapper { /** The global discriminator for each packet. */ private int discriminator = 0; /** Name of the channel used **/ protected String name; /** * Instantiates a new {@link MalisisNetwork}. * * @param channelName the channel name */ public MalisisNetwork(String channelName) { super(channelName); name = channelName; } /** * Instantiates a new {@link MalisisNetwork} * * @param mod the mod */ public MalisisNetwork(IMalisisMod mod) { this(mod.getModId()); } /** * Send the {@link IMessage} to all the players currently watching that specific chunk.<br> * The {@link IMessageHandler} for the message type should be on the CLIENT side. * * @param message the message * @param chunk the chunk */ public void sendToPlayersWatchingChunk(IMessage message, Chunk chunk) { for (EntityPlayerMP player : EntityUtils.getPlayersWatchingChunk(chunk)) sendTo(message, player); } /** * Register a message with the next discriminator available. * * @param <REQ> the generic type * @param <REPLY> the generic type * @param messageHandler the message handler * @param requestMessageType the request message type * @param side the side */ public <REQ extends IMessage, REPLY extends IMessage> void registerMessage(Class<? extends IMessageHandler<REQ, REPLY>> messageHandler, Class<REQ> requestMessageType, Side side) { super.registerMessage(messageHandler, requestMessageType, discriminator++, side); MalisisCore.log.info("Registering " + messageHandler.getSimpleName() + " for " + requestMessageType.getSimpleName() + " with discriminator " + discriminator + " in channel " + name); } /** * Register a message with the next discriminator available. * * @param <REQ> the generic type * @param <REPLY> the generic type * @param messageHandler the message handler * @param requestMessageType the request message type * @param side the side */ public <REQ extends IMessage, REPLY extends IMessage> void registerMessage(IMessageHandler<? super REQ, ? extends REPLY> messageHandler, Class<REQ> requestMessageType, Side side) { super.registerMessage(messageHandler, requestMessageType, discriminator++, side); MalisisCore.log.info("Registering " + messageHandler.getClass().getSimpleName() + " for " + requestMessageType.getSimpleName() + " with discriminator " + discriminator + " in channel " + name); } /** * Gets the next discriminator available. * * @return the next discriminator */ public int getNextDiscriminator() { return discriminator++; } /** * Instantiates every {@link IMessageHandler} annotated with {@link MalisisMessage}.<br> * * @param asmDataTable the asm data table */ public static void createMessages(ASMDataTable asmDataTable) { List<ASMData> classes = Ordering.natural().onResultOf(new Function<ASMData, String>() { @Override public String apply(ASMData data) { return data.getClassName(); } }).sortedCopy(asmDataTable.getAll(MalisisMessage.class.getName())); for (ASMData data : classes) { try { Class clazz = Class.forName(data.getClassName()); if (IMessageHandler.class.isAssignableFrom(clazz)) clazz.newInstance(); else MalisisCore.log.error("@MalisisMessage found on {} that does not implement IMessageHandler", data.getClassName()); } catch (Exception e) { MalisisCore.log.error("Could not create {} message.", data.getClassName(), e); } } } }
package net.openhft.chronicle.wire; import net.openhft.chronicle.bytes.Bytes; import net.openhft.chronicle.bytes.util.UTF8StringInterner; import net.openhft.chronicle.core.Maths; import net.openhft.chronicle.core.pool.ClassAliasPool; import net.openhft.chronicle.core.pool.ClassLookup; import net.openhft.chronicle.threads.BusyPauser; import net.openhft.chronicle.threads.Pauser; import org.jetbrains.annotations.NotNull; import java.io.EOFException; import java.io.StreamCorruptedException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public abstract class AbstractWire implements Wire { protected static final UTF8StringInterner UTF8_INTERNER = new UTF8StringInterner(512); protected final Bytes<?> bytes; protected final boolean use8bit; protected Pauser pauser = BusyPauser.INSTANCE; protected ClassLookup classLookup = ClassAliasPool.CLASS_ALIASES; public AbstractWire(Bytes bytes, boolean use8bit) { this.bytes = bytes; this.use8bit = use8bit; } @Override public Pauser pauser() { return pauser; } @Override public void pauser(Pauser pauser) { this.pauser = pauser; } @Override public void clear() { bytes.clear(); } @Override public void classLookup(ClassLookup classLookup) { this.classLookup = classLookup; } @Override public ClassLookup classLookup() { return classLookup; } @NotNull @Override public Bytes<?> bytes() { return bytes; } @Override public boolean hasMore() { consumePadding(); return bytes.readRemaining() > 0; } @Override public boolean readDataHeader() throws EOFException { bytes.readLimit(bytes.capacity()); for (; ; ) { int header = bytes.readVolatileInt(bytes.readPosition()); if (Wires.isReady(header)) { if (header == Wires.NOT_INITIALIZED) return false; if (Wires.isReadyData(header)) { return true; } bytes.readSkip(Wires.lengthOf(header) + Wires.SPB_HEADER_SIZE); } else { if (header == Wires.END_OF_DATA) throw new EOFException(); return false; } } } @Override public void readAndSetLength(long position) { int header = bytes.readVolatileInt(bytes.readPosition()); if (Wires.isReady(header)) { if (header == Wires.NOT_INITIALIZED) throw new IllegalStateException(); long start = position + Wires.SPB_HEADER_SIZE; bytes.readPositionRemaining(start, Wires.lengthOf(header)); return; } throw new IllegalStateException(); } @Override public void readMetaDataHeader() { int header = bytes.readVolatileInt(bytes.readPosition()); if (Wires.isReady(header)) { if (header == Wires.NOT_INITIALIZED) throw new IllegalStateException("Meta data not initialised"); if (Wires.isReadyMetaData(header)) { setLimitPosition(header); return; } } throw new IllegalStateException("Meta data not ready " + Integer.toHexString(header)); } private void setLimitPosition(int header) { bytes.readLimit(bytes.readPosition() + Wires.lengthOf(header) + Wires.SPB_HEADER_SIZE) .readSkip(Wires.SPB_HEADER_SIZE); } @Override public void readFirstHeader(long timeout, TimeUnit timeUnit) throws TimeoutException, StreamCorruptedException { int header; for (; ; ) { header = bytes.readVolatileInt(0L); if (Wires.isReady(header)) { break; } pauser.pause(timeout, timeUnit); } pauser.reset(); int len = Wires.lengthOf(header); if (!Wires.isReadyMetaData(header) || len > 64 << 10) throw new StreamCorruptedException("Unexpected magic number " + Integer.toHexString(header)); bytes.readPositionRemaining(Wires.SPB_HEADER_SIZE, len); } @Override public long writeHeader(int length, long timeout, TimeUnit timeUnit) throws TimeoutException, EOFException { if (length < 0 || length > Wires.MAX_LENGTH) throw new IllegalArgumentException(); long pos = bytes.writePosition(); try { for (; ; ) { if (bytes.compareAndSwapInt(pos, 0, Wires.NOT_READY | length)) { bytes.writePosition(pos + Wires.SPB_HEADER_SIZE); int maxlen = length == Wires.UNKNOWN_LENGTH ? Wires.MAX_LENGTH : length; if (maxlen > bytes.writeRemaining()) throw new IllegalStateException("not enough space to write " + maxlen + " was " + bytes.writeRemaining()); bytes.writeLimit(bytes.writePosition() + maxlen); return pos; } pauser.pause(timeout, timeUnit); int header = bytes.readVolatileInt(pos); // two states where it is unable to continue. if (header == Wires.END_OF_DATA) throw new EOFException(); if (header == Wires.NOT_READY_UNKNOWN_LENGTH) continue; int len = Wires.lengthOf(header); pos += len + Wires.SPB_HEADER_SIZE; // length of message plus length of header } } finally { pauser.reset(); } } @Override public void updateHeader(int length, long position, boolean metaData) throws StreamCorruptedException { int expectedHeader = Wires.NOT_READY | length; long pos = bytes.writePosition(); int actualLength = Maths.toUInt31(pos - position - 4); if (length == Wires.UNKNOWN_LENGTH) { length = actualLength; } else if (length < actualLength) throw new StreamCorruptedException("Wrote " + actualLength + " when " + length + " was set initially."); int header = length; if (metaData) header |= Wires.META_DATA; if (!bytes.compareAndSwapInt(position, expectedHeader, header)) throw new StreamCorruptedException("Data at " + position + " overwritten? Expected: " + Integer.toHexString(expectedHeader) + " was " + Integer.toHexString(bytes.readVolatileInt(position))); bytes.writeLimit(bytes.capacity()); } @Override public boolean writeFirstHeader() { boolean cas = bytes.compareAndSwapInt(0L, 0, Wires.NOT_READY_UNKNOWN_LENGTH); if (cas) bytes.writeSkip(Wires.SPB_HEADER_SIZE); return cas; } @Override public void updateFirstHeader() { long pos = bytes.writePosition(); long actualLength = pos - Wires.SPB_HEADER_SIZE; if (actualLength >= 1 << 30) throw new IllegalStateException("Header too large was " + actualLength); int header = (int) (Wires.META_DATA | actualLength); if (!bytes.compareAndSwapInt(0L, Wires.NOT_READY_UNKNOWN_LENGTH, header)) throw new IllegalStateException("Data at 0 overwritten? Expected: " + Integer.toHexString(Wires.NOT_READY_UNKNOWN_LENGTH) + " was " + Integer.toHexString(bytes.readVolatileInt(0L))); } @Override public void writeEndOfWire(long timeout, TimeUnit timeUnit) throws TimeoutException { long pos = bytes.writePosition(); try { for (; ; ) { if (bytes.compareAndSwapInt(pos, 0, Wires.END_OF_DATA)) { bytes.writePosition(pos + Wires.SPB_HEADER_SIZE); return; } pauser.pause(timeout, timeUnit); int header = bytes.readVolatileInt(pos); // two states where it is unable to continue. if (header == Wires.END_OF_DATA) return; // already written. if (header == Wires.NOT_READY_UNKNOWN_LENGTH) continue; int len = Wires.lengthOf(header); pos += len + Wires.SPB_HEADER_SIZE; // length of message plus length of header } } finally { pauser.reset(); } } }
package org.cactoos.io; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.concurrent.atomic.AtomicBoolean; import org.cactoos.scalar.LengthOf; import org.cactoos.text.TextOf; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.hamcrest.core.IsEqual; import org.junit.Test; /** * Test case for {@link TeeInputStream}. * @since 0.1 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ public final class TeeInputStreamTest { @Test public void copiesContentByteByByte() throws Exception { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final String content = "Hello, товарищ!"; MatcherAssert.assertThat( "Can't copy InputStream to OutputStream byte by byte", new TextOf( new ReaderOf( new TeeInputStream( new ByteArrayInputStream( content.getBytes(StandardCharsets.UTF_8) ), baos ) ) ).asString(), Matchers.allOf( Matchers.equalTo(content), Matchers.equalTo( new String(baos.toByteArray(), StandardCharsets.UTF_8) ) ) ); } @Test public void leftInputClosed() { try (StringWriterMock write = new StringWriterMock()) { new LengthOf( new TeeInput( "foo", new OutputTo(write) ) ).intValue(); MatcherAssert.assertThat( "Can't use output after usage from TeeInput", write.isClosed(), new IsEqual<>(true) ); } } /** * Mock object around StringWriter for checking closing state. */ private static final class StringWriterMock extends StringWriter { /** * Closing state. */ private final AtomicBoolean closed = new AtomicBoolean(false); @Override public void close() { this.closed.set(true); } public boolean isClosed() { return this.closed.get(); } } }
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.KeyEvent; import java.awt.event.WindowEvent; import java.io.IOException; import java.net.InetSocketAddress; 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:[email protected]'>Daniel Pitts</a> */ public class Terminal { public static final String IBM_437 = "IBM437"; public static final String TITLE_PREFIX = "VirtualInfiniterm"; public static final String DISCONNECTED_TITLE = TITLE_PREFIX + " - (Disconnected)"; 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 final Action connectAction = new AbstractAction("Connect") { @Override public void actionPerformed(ActionEvent e) { connect(); view.requestFocusInWindow(); } }; private final Action disconnectAction = new AbstractAction("Disconnect") { { setEnabled(false); } @Override public void actionPerformed(ActionEvent e) { disconnect(); hostInput.requestFocusInWindow(); } }; private State state = State.DISCONNECTED; private final int id; private static int nextId = 0; private Decoder decoder; private Encoder encoder; private TelnetSession telnetSession; { synchronized (Terminal.class) { id = nextId++; } } public Terminal() throws IOException { this.eventLoop = new EventLoop(this::handleException); this.frame = new JFrame(DISCONNECTED_TITLE); 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); toolBar.add(hostInput); toolBar.add(new JButton(connectAction)); toolBar.add(new JButton(disconnectAction)); 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(KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), "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() { onGuiThread(() -> { disconnectAction.setEnabled(true); 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; } final InetSocketAddress address = parseAddress(selectedItem.toString()); hostInput.setEnabled(false); connectAction.setEnabled(false); frame.setTitle(TITLE_PREFIX + " - " + addressName(address) + " (Connecting...)"); onIOThread(() -> { state = State.CONNECTING; SocketChannel channel = null; try { channel = SocketChannel.open(address); channel.configureBlocking(false); finishConnect(selectedCharset(), channel); frame.setTitle(TITLE_PREFIX + " - " + addressName(address) + " (Connected)"); } catch (Exception e) { displayConnectError(e); disconnect(); if (channel != null) { try { channel.close(); } catch (IOException ignore) { } } } }); }); } private String addressName(InetSocketAddress address) { if (address.getPort() != 23) { return address.getHostString() + ":" + address.getPort(); } return address.getHostString(); } 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) { displayConnectError(e); disconnect(); return; } state = State.CONNECTED; final OutputDeviceImpl device = new OutputDeviceImpl(view.getModel()); device.inputDevice(inputDevice); decoder = new Decoder(device); telnetSession = createTelnetSession(channel, decoder); encoder = new Encoder(new TelnetSessionDispatcher(telnetSession, eventLoop)); setCharSet(charset); onGuiThread(() -> inputDevice.setEncoder(encoder)); } private void setCharSet(Charset charset) { onIOThread(() -> { 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, this::disconnect)); 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 InetSocketAddress 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() { onGuiThread(() -> { disconnectAction.setEnabled(false); hostInput.setEnabled(true); connectAction.setEnabled(true); frame.setTitle(DISCONNECTED_TITLE); }); onIOThread(() -> { state = State.DISCONNECTED; if (telnetSession != null) { telnetSession.close(); telnetSession = null; decoder = null; encoder = null; } }); } 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.fairdom; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Test; import ch.systemsx.cisd.common.parser.MemorySizeFormatter; public class DataStoreDownloadTest { private static String endpoint; private static String sessionToken; @Before public void setUp() throws AuthenticationException{ Authentication au = new Authentication("https://openbis-api.fair-dom.org/openbis/openbis", "apiuser", "apiuser"); endpoint = "https://openbis-api.fair-dom.org/datastore_server"; sessionToken = au.sessionToken(); } @Test public void downloadSingleFile() throws Exception { DataStoreDownload download = new DataStoreDownload(endpoint, sessionToken); String permId = "20151217153943290-5"; String source = "original/api-test"; String basePath = new File("").getAbsolutePath(); String destination = basePath + "/src/test/java/resources/api-test"; File file = new File(destination); if (file.exists()){ file.delete(); } assertFalse(file.exists()); download.downloadSingleFile(permId, source, destination); assertTrue(file.exists()); BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class); assertEquals(25, attr.size()); } @Test public void downloadUtf8File() throws Exception { DataStoreDownload download = new DataStoreDownload(endpoint, sessionToken); String permId = "20160210130359377-22"; String source = "original/utf8.txt"; String basePath = new File("").getAbsolutePath(); String destination = basePath + "/src/test/java/resources/utf8.txt"; File file = new File(destination); if (file.exists()){ file.delete(); } assertFalse(file.exists()); download.downloadSingleFile(permId, source, destination); assertTrue(file.exists()); BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class); assertEquals(49, attr.size()); } @Test public void downloadChineseCharatersFile() throws Exception { DataStoreDownload download = new DataStoreDownload(endpoint, sessionToken); String permId = "20160212141703195-28"; String source = "original/chinese"; String basePath = new File("").getAbsolutePath(); String destination = basePath + "/src/test/java/resources/chinese"; File file = new File(destination); if (file.exists()){ file.delete(); } assertFalse(file.exists()); download.downloadSingleFile(permId, source, destination); assertTrue(file.exists()); BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class); assertEquals(44, attr.size()); } @Test public void downloadWesternEncodeFile() throws Exception { DataStoreDownload download = new DataStoreDownload(endpoint, sessionToken); String permId = "20160212140647105-27"; String source = "original/western.txt"; String basePath = new File("").getAbsolutePath(); String destination = basePath + "/src/test/java/resources/western.txt"; File file = new File(destination); if (file.exists()){ file.delete(); } assertFalse(file.exists()); download.downloadSingleFile(permId, source, destination); assertTrue(file.exists()); BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class); assertEquals(44, attr.size()); } @Test public void downloadImageFile() throws Exception { DataStoreDownload download = new DataStoreDownload(endpoint, sessionToken); String permId = "20160210130454955-23"; String source = "original/autumn.jpg"; String basePath = new File("").getAbsolutePath(); String destination = basePath + "/src/test/java/resources/autumn.jpg"; File file = new File(destination); if (file.exists()){ file.delete(); } assertFalse(file.exists()); download.downloadSingleFile(permId, source, destination); assertTrue(file.exists()); BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class); assertEquals("537k", MemorySizeFormatter.format(attr.size())); } @Test public void downloadFileWithSpaceInName() throws Exception { DataStoreDownload download = new DataStoreDownload(endpoint, sessionToken); String permId = "20160322172551664-35"; String source = "original/Genes List Nature Paper Test.docx"; String basePath = new File("").getAbsolutePath(); String destination = basePath + "/src/test/java/resources/Genes List Nature Paper Test.docx"; File file = new File(destination); if (file.exists()){ file.delete(); } assertFalse(file.exists()); download.downloadSingleFile(permId, source, destination); assertTrue(file.exists()); BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class); assertEquals("27.4k", MemorySizeFormatter.format(attr.size())); } /* * Comment this test out, to avoid time for downloading a big file @Test public void downloadSingleLargeFile() throws Exception { DataStoreDownload download = new DataStoreDownload(dss, sessionToken); String permId = "20160212120108123-26"; String source = "original/SEEK-v0.23.0.ova"; String basePath = new File("").getAbsolutePath(); String destination = basePath + "/src/test/java/resources/SEEK-v0.23.0.ova"; File file = new File(destination); if (file.exists()){ file.delete(); } assertFalse(file.exists()); download.downloadSingleFile(permId, source, destination); assertTrue(file.exists()); BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class); assertEquals("2.3gb", MemorySizeFormatter.format(attr.size())); } */ @Test public void downloadFolder() throws Exception { DataStoreDownload download = new DataStoreDownload(endpoint, sessionToken); String permId = "20160215111736723-31"; String sourceRelativeFolder = "original/DEFAULT"; String basePath = new File("").getAbsolutePath(); String destinationFolder = basePath + "/src/test/java/resources/"; File file = new File(destinationFolder + sourceRelativeFolder); if (file.exists()){ FileUtils.deleteDirectory(file); } download.downloadFolder(permId, sourceRelativeFolder, destinationFolder); Path path = Paths.get(destinationFolder + sourceRelativeFolder); DirectoryStream<Path> stream = Files.newDirectoryStream(path); List<String> filesInFolder = new ArrayList<String>(); for (Path outputFile: stream) { filesInFolder.add(outputFile.getFileName().toString()); } assertEquals("fairdom-logo-compact.svg", filesInFolder.get(0)); assertEquals("Stanford_et_al-2015-Molecular_Systems_Biology.pdf", filesInFolder.get(1)); } @Test public void downloadDataSetFiles() throws Exception { DataStoreDownload download = new DataStoreDownload(endpoint, sessionToken); String permId = "20151217153943290-5"; String sourceRelativeFolder = "original"; String basePath = new File("").getAbsolutePath(); String destinationFolder = basePath + "/src/test/java/resources/"; File file = new File(destinationFolder + sourceRelativeFolder); if (file.exists()){ FileUtils.deleteDirectory(file); } download.downloadDataSetFiles(permId, destinationFolder); Path path = Paths.get(destinationFolder + sourceRelativeFolder); DirectoryStream<Path> stream = Files.newDirectoryStream(path); List<String> filesInFolder = new ArrayList<String>(); for (Path outputFile: stream) { filesInFolder.add(outputFile.getFileName().toString()); } assertEquals("api-test", filesInFolder.get(0)); } }
package org.agmip.core.translators; import java.io.IOException; import java.io.File; import java.io.FileWriter; import java.io.BufferedWriter; import java.util.Calendar; import java.util.Map; import java.util.ArrayList; import java.util.HashMap; import java.util.Set; import org.agmip.core.types.*; import org.agmip.core.types.weather.*; import org.agmip.util.JSONAdapter; /** * DSSAT Weather Data I/O API Class * * @author Meng Zhang * @version 1.0 */ public class DssatWeather implements WeatherFile { public static String jsonExample = "{\"observed\": {\"hwah\": 2929.0, \"adap\": 76.0, \"cwam\": 5532.0, \"mdap\": 129.0}, \"management\": {\"management\": [{\"fedep\": 10.0, \"feamn\": 27.0, \"feacd\": \"AP001\", \"feamk\": 0.0, \"fecd\": \"FE001\", \"feamp\": 0.0, \"fdate\": \"4/7/82\"}, {\"fedep\": 10.0, \"feamn\": 35.0, \"feacd\": \"AP001\", \"feamk\": 0.0, \"fecd\": \"FE001\", \"feamp\": 0.0, \"fdate\": \"4/12/82\"}, {\"fedep\": 10.0, \"feamn\": 54.0, \"feacd\": \"AP001\", \"feamk\": 0.0, \"fecd\": \"FE001\", \"feamp\": 0.0, \"fdate\": \"5/17/82\"}, {\"fedep\": \"\", \"feamn\": \"\", \"feacd\": \"\", \"feamk\": \"\", \"fecd\": \"\", \"feamp\": \"\", \"fdate\": \"\"}, {\"fedep\": \"\", \"feamn\": \"\", \"feacd\": \"\", \"feamk\": \"\", \"fecd\": \"\", \"feamp\": \"\", \"fdate\": \"\"}, {\"fedep\": \"\", \"feamn\": \"\", \"feacd\": \"\", \"feamk\": \"\", \"fecd\": \"\", \"feamp\": \"\", \"fdate\": \"\"}], \"plrs\": 61.0, \"plpoe\": 7.2, \"hacom\": \"H\", \"icpcr\": \"MZ\", \"ninumm\": 3.0, \"fen_tot\": 116.0}, \"meta\": {\"cul_id\": \"IB0035\", \"people\": \" BENNET,J.M. ZUR,B. HAMMOND,L.C. JONES,J.W.\", \"fl_long\": -82.37, \"cr\": \"MZ\", \"institutes\": \"University of Florida\", \"main_factor\": \"NxW\", \"num_years\": 1.0, \"wsta_long\": -82.37, \"wsta_source\": \"Measured\", \"data_source\": \"DSSAT\", \"exname\": \"UFGA8201.MZX\", \"flele\": 40.0, \"fertilizer\": \"P\", \"wsta_insi\": \"UFGA\", \"wsta_dist\": 0.0, \"fl_loc_1\": \"USA\", \"fl_loc_2\": \"FLA\", \"fl_loc_3\": \"Gainesville\", \"soil_id\": \"IBMZ910014\", \"hdate\": \"7/4/82\", \"fl_name\": \"Irrigation Park\", \"pdate\": \"2/25/82\", \"wsta_name\": \"Gainesville, FL\", \"exp_factors\": \"N; W\", \"id_field\": \"UFGA0002\", \"sltx\": \"LS\", \"eid\": 1.0, \"local_name\": \"Gainesville, FL\", \"irrig\": \"N\", \"distribution\": \"None\", \"wsta_lat\": 29.63, \"fl_lat\": 29.63, \"sl_source\": \"SCS\"}, \"weather\": {\"tav\": 20.9, \"wndht\": 3.0, \"wsta_name\": \"Gainesville, FL\", \"refht\": 2.0, \"weather\": [{\"w_date\": \"1/1/82\", \"srad\": 5.9, \"tmax\": 24.4, \"tmin\": 15.6, \"rain\": 19.0}, {\"w_date\": \"1/2/82\", \"srad\": 7.0, \"tmax\": 22.2, \"tmin\": 15.0, \"rain\": 0.0}, {\"w_date\": \"1/3/82\", \"srad\": 9.0, \"tmax\": 27.8, \"tmin\": 17.2, \"rain\": 0.0}, {\"w_date\": \"1/4/82\", \"srad\": 3.1, \"tmax\": 26.1, \"tmin\": 15.0, \"rain\": 9.4}, {\"w_date\": \"1/5/82\", \"srad\": 12.9, \"tmax\": 17.2, \"tmin\": 2.2, \"rain\": 0.0}, {\"w_date\": \"1/6/82\", \"srad\": 11.4, \"tmax\": 25.0, \"tmin\": 4.4, \"rain\": 0.0}, {\"w_date\": \"1/7/82\", \"srad\": 8.5, \"tmax\": 26.7, \"tmin\": 11.7, \"rain\": 0.0}, {\"w_date\": \"1/8/82\", \"srad\": 3.0, \"tmax\": 22.8, \"tmin\": 14.4, \"rain\": 5.3}, {\"w_date\": \"1/9/82\", \"srad\": 14.4, \"tmax\": 16.7, \"tmin\": 8.9, \"rain\": 0.0}, {\"w_date\": \"1/10/82\", \"srad\": 12.0, \"tmax\": 14.4, \"tmin\": 1.1, \"rain\": 0.0}, {\"w_date\": \"1/11/82\", \"srad\": 15.0, \"tmax\": 14.4, \"tmin\": -6.7, \"rain\": 0.0}, {\"w_date\": \"1/12/82\", \"srad\": 10.8, \"tmax\": 10.0, \"tmin\": -7.8, \"rain\": 0.0}, {\"w_date\": \"1/13/82\", \"srad\": 4.8, \"tmax\": 20.0, \"tmin\": 3.9, \"rain\": 19.8}, {\"w_date\": \"1/14/82\", \"srad\": 6.2, \"tmax\": 18.9, \"tmin\": 6.1, \"rain\": 81.0}, {\"w_date\": \"1/15/82\", \"srad\": 14.4, \"tmax\": 12.2, \"tmin\": -3.3, \"rain\": 0.0}, {\"w_date\": \"1/16/82\", \"srad\": 12.6, \"tmax\": 19.4, \"tmin\": -1.7, \"rain\": 0.0}, {\"w_date\": \"1/17/82\", \"srad\": 14.6, \"tmax\": 19.4, \"tmin\": 5.6, \"rain\": 2.8}, {\"w_date\": \"1/18/82\", \"srad\": 11.2, \"tmax\": 20.6, \"tmin\": 1.1, \"rain\": 0.0}, {\"w_date\": \"1/19/82\", \"srad\": 13.3, \"tmax\": 25.6, \"tmin\": 8.9, \"rain\": 0.0}, {\"w_date\": \"1/20/82\", \"srad\": 13.4, \"tmax\": 27.8, \"tmin\": 8.3, \"rain\": 0.0}, {\"w_date\": \"1/21/82\", \"srad\": 11.6, \"tmax\": 27.8, \"tmin\": 10.0, \"rain\": 0.0}, {\"w_date\": \"1/22/82\", \"srad\": 10.7, \"tmax\": 25.6, \"tmin\": 12.2, \"rain\": 0.0}, {\"w_date\": \"1/23/82\", \"srad\": 10.1, \"tmax\": 26.1, \"tmin\": 14.4, \"rain\": 0.0}, {\"w_date\": \"1/24/82\", \"srad\": 12.9, \"tmax\": 23.9, \"tmin\": 10.0, \"rain\": 0.0}, {\"w_date\": \"1/25/82\", \"srad\": 14.1, \"tmax\": 21.1, \"tmin\": 0.0, \"rain\": 0.0}, {\"w_date\": \"1/26/82\", \"srad\": 14.2, \"tmax\": 20.0, \"tmin\": 4.4, \"rain\": 0.0}, {\"w_date\": \"1/27/82\", \"srad\": 13.9, \"tmax\": 15.6, \"tmin\": -1.1, \"rain\": 0.0}, {\"w_date\": \"1/28/82\", \"srad\": 13.8, \"tmax\": 21.7, \"tmin\": 2.2, \"rain\": 0.0}, {\"w_date\": \"1/29/82\", \"srad\": 13.3, \"tmax\": 22.2, \"tmin\": 3.3, \"rain\": 0.0}, {\"w_date\": \"1/30/82\", \"srad\": 12.5, \"tmax\": 25.6, \"tmin\": 8.9, \"rain\": 0.0}, {\"w_date\": \"1/31/82\", \"srad\": 12.6, \"tmax\": 28.9, \"tmin\": 13.3, \"rain\": 0.0}, {\"w_date\": \"2/1/82\", \"srad\": 14.0, \"tmax\": 26.1, \"tmin\": 12.2, \"rain\": 0.3}, {\"w_date\": \"2/2/82\", \"srad\": 7.6, \"tmax\": 26.7, \"tmin\": 12.8, \"rain\": 2.0}, {\"w_date\": \"2/3/82\", \"srad\": 3.3, \"tmax\": 27.2, \"tmin\": 15.6, \"rain\": 25.9}, {\"w_date\": \"2/4/82\", \"srad\": 12.5, \"tmax\": 24.4, \"tmin\": 14.4, \"rain\": 1.0}, {\"w_date\": \"2/5/82\", \"srad\": 8.5, \"tmax\": 27.8, \"tmin\": 14.4, \"rain\": 0.0}, {\"w_date\": \"2/6/82\", \"srad\": 6.3, \"tmax\": 26.7, \"tmin\": 17.2, \"rain\": 0.0}, {\"w_date\": \"2/7/82\", \"srad\": 8.0, \"tmax\": 26.7, \"tmin\": 10.6, \"rain\": 0.0}, {\"w_date\": \"2/8/82\", \"srad\": 12.5, \"tmax\": 25.0, \"tmin\": 10.0, \"rain\": 0.0}, {\"w_date\": \"2/9/82\", \"srad\": 7.9, \"tmax\": 26.7, \"tmin\": 16.1, \"rain\": 0.0}, {\"w_date\": \"2/10/82\", \"srad\": 4.0, \"tmax\": 25.6, \"tmin\": 14.4, \"rain\": 0.8}, {\"w_date\": \"2/11/82\", \"srad\": 6.5, \"tmax\": 18.9, \"tmin\": 12.8, \"rain\": 0.0}, {\"w_date\": \"2/12/82\", \"srad\": 7.4, \"tmax\": 25.0, \"tmin\": 10.6, \"rain\": 0.8}, {\"w_date\": \"2/13/82\", \"srad\": 13.3, \"tmax\": 25.6, \"tmin\": 10.6, \"rain\": 18.0}, {\"w_date\": \"2/14/82\", \"srad\": 16.1, \"tmax\": 26.1, \"tmin\": 5.6, \"rain\": 0.0}, {\"w_date\": \"2/15/82\", \"srad\": 9.6, \"tmax\": 26.7, \"tmin\": 13.3, \"rain\": 0.0}, {\"w_date\": \"2/16/82\", \"srad\": 10.8, \"tmax\": 27.8, \"tmin\": 16.1, \"rain\": 67.3}, {\"w_date\": \"2/17/82\", \"srad\": 13.4, \"tmax\": 27.2, \"tmin\": 14.4, \"rain\": 10.9}, {\"w_date\": \"2/18/82\", \"srad\": 17.0, \"tmax\": 26.1, \"tmin\": 11.1, \"rain\": 0.0}, {\"w_date\": \"2/19/82\", \"srad\": 15.5, \"tmax\": 25.6, \"tmin\": 12.2, \"rain\": 0.0}, {\"w_date\": \"2/20/82\", \"srad\": 16.9, \"tmax\": 25.6, \"tmin\": 10.0, \"rain\": 0.0}, {\"w_date\": \"2/21/82\", \"srad\": 16.6, \"tmax\": 24.4, \"tmin\": 9.4, \"rain\": 0.0}, {\"w_date\": \"2/22/82\", \"srad\": 17.0, \"tmax\": 21.1, \"tmin\": 7.8, \"rain\": 0.0}, {\"w_date\": \"2/23/82\", \"srad\": 17.7, \"tmax\": 23.9, \"tmin\": 1.1, \"rain\": 0.0}, {\"w_date\": \"2/24/82\", \"srad\": 17.5, \"tmax\": 26.7, \"tmin\": 3.3, \"rain\": 0.0}, {\"w_date\": \"2/25/82\", \"srad\": 14.8, \"tmax\": 27.2, \"tmin\": 10.6, \"rain\": 0.0}, {\"w_date\": \"2/26/82\", \"srad\": 3.4, \"tmax\": 26.7, \"tmin\": 11.1, \"rain\": 0.0}, {\"w_date\": \"2/27/82\", \"srad\": 8.9, \"tmax\": 25.6, \"tmin\": 8.9, \"rain\": 0.0}, {\"w_date\": \"2/28/82\", \"srad\": 9.3, \"tmax\": 24.4, \"tmin\": 15.6, \"rain\": 0.0}, {\"w_date\": \"3/1/82\", \"srad\": 10.9, \"tmax\": 17.8, \"tmin\": 8.3, \"rain\": 0.0}, {\"w_date\": \"3/2/82\", \"srad\": 18.4, \"tmax\": 22.8, \"tmin\": 1.7, \"rain\": 0.0}, {\"w_date\": \"3/3/82\", \"srad\": 17.6, \"tmax\": 25.0, \"tmin\": 6.1, \"rain\": 0.0}, {\"w_date\": \"3/4/82\", \"srad\": 16.2, \"tmax\": 28.3, \"tmin\": 9.4, \"rain\": 0.0}, {\"w_date\": \"3/5/82\", \"srad\": 6.3, \"tmax\": 27.8, \"tmin\": 16.1, \"rain\": 8.4}, {\"w_date\": \"3/6/82\", \"srad\": 10.3, \"tmax\": 25.0, \"tmin\": 16.1, \"rain\": 35.1}, {\"w_date\": \"3/7/82\", \"srad\": 9.0, \"tmax\": 24.4, \"tmin\": 15.0, \"rain\": 14.2}, {\"w_date\": \"3/8/82\", \"srad\": 19.8, \"tmax\": 16.7, \"tmin\": 1.1, \"rain\": 0.0}, {\"w_date\": \"3/9/82\", \"srad\": 19.6, \"tmax\": 21.7, \"tmin\": 3.9, \"rain\": 0.0}, {\"w_date\": \"3/10/82\", \"srad\": 16.1, \"tmax\": 25.6, \"tmin\": 10.6, \"rain\": 0.0}, {\"w_date\": \"3/11/82\", \"srad\": 17.7, \"tmax\": 27.8, \"tmin\": 9.4, \"rain\": 0.0}, {\"w_date\": \"3/12/82\", \"srad\": 20.0, \"tmax\": 28.9, \"tmin\": 11.1, \"rain\": 0.0}, {\"w_date\": \"3/13/82\", \"srad\": 19.0, \"tmax\": 30.6, \"tmin\": 10.0, \"rain\": 0.0}, {\"w_date\": \"3/14/82\", \"srad\": 18.4, \"tmax\": 31.7, \"tmin\": 15.6, \"rain\": 0.0}, {\"w_date\": \"3/15/82\", \"srad\": 17.5, \"tmax\": 30.0, \"tmin\": 16.7, \"rain\": 0.0}, {\"w_date\": \"3/16/82\", \"srad\": 15.9, \"tmax\": 30.0, \"tmin\": 16.1, \"rain\": 0.0}, {\"w_date\": \"3/17/82\", \"srad\": 19.5, \"tmax\": 30.6, \"tmin\": 15.6, \"rain\": 0.0}, {\"w_date\": \"3/18/82\", \"srad\": 17.4, \"tmax\": 31.7, \"tmin\": 17.2, \"rain\": 0.0}, {\"w_date\": \"3/19/82\", \"srad\": 16.7, \"tmax\": 30.6, \"tmin\": 18.3, \"rain\": 1.8}, {\"w_date\": \"3/20/82\", \"srad\": 17.4, \"tmax\": 30.6, \"tmin\": 18.9, \"rain\": 0.0}, {\"w_date\": \"3/21/82\", \"srad\": 13.6, \"tmax\": 30.0, \"tmin\": 15.6, \"rain\": 0.0}, {\"w_date\": \"3/22/82\", \"srad\": 10.0, \"tmax\": 28.3, \"tmin\": 17.2, \"rain\": 0.3}, {\"w_date\": \"3/23/82\", \"srad\": 13.2, \"tmax\": 26.1, \"tmin\": 16.1, \"rain\": 9.4}, {\"w_date\": \"3/24/82\", \"srad\": 4.3, \"tmax\": 26.1, \"tmin\": 16.1, \"rain\": 4.3}, {\"w_date\": \"3/25/82\", \"srad\": 17.0, \"tmax\": 27.8, \"tmin\": 16.1, \"rain\": 26.2}, {\"w_date\": \"3/26/82\", \"srad\": 18.8, \"tmax\": 26.7, \"tmin\": 14.4, \"rain\": 2.8}, {\"w_date\": \"3/27/82\", \"srad\": 12.9, \"tmax\": 22.2, \"tmin\": 5.6, \"rain\": 0.0}, {\"w_date\": \"3/28/82\", \"srad\": 3.8, \"tmax\": 15.6, \"tmin\": 8.9, \"rain\": 9.7}, {\"w_date\": \"3/29/82\", \"srad\": 9.9, \"tmax\": 21.1, \"tmin\": 10.0, \"rain\": 25.7}, {\"w_date\": \"3/30/82\", \"srad\": 21.5, \"tmax\": 26.1, \"tmin\": 13.3, \"rain\": 0.0}, {\"w_date\": \"3/31/82\", \"srad\": 16.1, \"tmax\": 26.7, \"tmin\": 14.4, \"rain\": 0.0}, {\"w_date\": \"4/1/82\", \"srad\": 21.0, \"tmax\": 30.6, \"tmin\": 12.8, \"rain\": 0.0}, {\"w_date\": \"4/2/82\", \"srad\": 22.1, \"tmax\": 29.4, \"tmin\": 14.4, \"rain\": 0.0}, {\"w_date\": \"4/3/82\", \"srad\": 11.4, \"tmax\": 28.9, \"tmin\": 17.8, \"rain\": 0.0}, {\"w_date\": \"4/4/82\", \"srad\": 23.8, \"tmax\": 28.3, \"tmin\": 9.4, \"rain\": 0.0}, {\"w_date\": \"4/5/82\", \"srad\": 18.9, \"tmax\": 29.4, \"tmin\": 11.1, \"rain\": 0.0}, {\"w_date\": \"4/6/82\", \"srad\": 24.1, \"tmax\": 25.6, \"tmin\": 17.2, \"rain\": 0.0}, {\"w_date\": \"4/7/82\", \"srad\": 25.1, \"tmax\": 22.2, \"tmin\": 6.7, \"rain\": 0.0}, {\"w_date\": \"4/8/82\", \"srad\": 0.8, \"tmax\": 21.1, \"tmin\": 11.1, \"rain\": 48.0}, {\"w_date\": \"4/9/82\", \"srad\": 8.8, \"tmax\": 23.3, \"tmin\": 17.2, \"rain\": 98.8}, {\"w_date\": \"4/10/82\", \"srad\": 3.8, \"tmax\": 23.9, \"tmin\": 10.6, \"rain\": 3.6}, {\"w_date\": \"4/11/82\", \"srad\": 23.0, \"tmax\": 20.6, \"tmin\": 8.9, \"rain\": 42.7}, {\"w_date\": \"4/12/82\", \"srad\": 25.4, \"tmax\": 25.0, \"tmin\": 6.1, \"rain\": 0.0}, {\"w_date\": \"4/13/82\", \"srad\": 21.6, \"tmax\": 28.3, \"tmin\": 11.7, \"rain\": 0.0}, {\"w_date\": \"4/14/82\", \"srad\": 21.6, \"tmax\": 27.2, \"tmin\": 15.0, \"rain\": 0.0}, {\"w_date\": \"4/15/82\", \"srad\": 16.6, \"tmax\": 28.3, \"tmin\": 15.0, \"rain\": 0.0}, {\"w_date\": \"4/16/82\", \"srad\": 20.7, \"tmax\": 30.6, \"tmin\": 17.8, \"rain\": 0.0}, {\"w_date\": \"4/17/82\", \"srad\": 21.0, \"tmax\": 31.1, \"tmin\": 19.4, \"rain\": 0.5}, {\"w_date\": \"4/18/82\", \"srad\": 18.9, \"tmax\": 30.0, \"tmin\": 18.9, \"rain\": 0.5}, {\"w_date\": \"4/19/82\", \"srad\": 21.6, \"tmax\": 30.0, \"tmin\": 15.0, \"rain\": 0.0}, {\"w_date\": \"4/20/82\", \"srad\": 20.7, \"tmax\": 31.1, \"tmin\": 18.9, \"rain\": 0.0}, {\"w_date\": \"4/21/82\", \"srad\": 24.3, \"tmax\": 32.2, \"tmin\": 17.2, \"rain\": 0.0}, {\"w_date\": \"4/22/82\", \"srad\": 23.7, \"tmax\": 31.7, \"tmin\": 17.8, \"rain\": 0.0}, {\"w_date\": \"4/23/82\", \"srad\": 8.6, \"tmax\": 31.1, \"tmin\": 15.6, \"rain\": 0.0}, {\"w_date\": \"4/24/82\", \"srad\": 7.5, \"tmax\": 22.2, \"tmin\": 13.9, \"rain\": 0.0}, {\"w_date\": \"4/25/82\", \"srad\": 7.7, \"tmax\": 25.6, \"tmin\": 16.7, \"rain\": 4.3}, {\"w_date\": \"4/26/82\", \"srad\": 10.7, \"tmax\": 25.6, \"tmin\": 19.4, \"rain\": 23.1}, {\"w_date\": \"4/27/82\", \"srad\": 23.4, \"tmax\": 29.4, \"tmin\": 15.6, \"rain\": 0.3}, {\"w_date\": \"4/28/82\", \"srad\": 23.7, \"tmax\": 28.9, \"tmin\": 13.3, \"rain\": 0.0}, {\"w_date\": \"4/29/82\", \"srad\": 18.5, \"tmax\": 27.2, \"tmin\": 14.4, \"rain\": 0.0}, {\"w_date\": \"4/30/82\", \"srad\": 20.7, \"tmax\": 26.7, \"tmin\": 15.6, \"rain\": 0.0}, {\"w_date\": \"5/1/82\", \"srad\": 18.2, \"tmax\": 26.7, \"tmin\": 15.6, \"rain\": 0.0}, {\"w_date\": \"5/2/82\", \"srad\": 19.9, \"tmax\": 27.8, \"tmin\": 15.0, \"rain\": 0.0}, {\"w_date\": \"5/3/82\", \"srad\": 21.8, \"tmax\": 28.9, \"tmin\": 15.0, \"rain\": 0.0}, {\"w_date\": \"5/4/82\", \"srad\": 23.6, \"tmax\": 28.9, \"tmin\": 12.8, \"rain\": 0.0}, {\"w_date\": \"5/5/82\", \"srad\": 24.4, \"tmax\": 28.3, \"tmin\": 14.4, \"rain\": 0.0}, {\"w_date\": \"5/6/82\", \"srad\": 21.7, \"tmax\": 27.8, \"tmin\": 12.2, \"rain\": 0.0}, {\"w_date\": \"5/7/82\", \"srad\": 23.6, \"tmax\": 28.9, \"tmin\": 11.7, \"rain\": 0.0}, {\"w_date\": \"5/8/82\", \"srad\": 18.2, \"tmax\": 29.4, \"tmin\": 17.8, \"rain\": 1.0}, {\"w_date\": \"5/9/82\", \"srad\": 26.3, \"tmax\": 29.4, \"tmin\": 15.0, \"rain\": 0.0}, {\"w_date\": \"5/10/82\", \"srad\": 26.3, \"tmax\": 29.4, \"tmin\": 13.3, \"rain\": 0.0}, {\"w_date\": \"5/11/82\", \"srad\": 24.9, \"tmax\": 30.0, \"tmin\": 11.1, \"rain\": 0.0}, {\"w_date\": \"5/12/82\", \"srad\": 23.5, \"tmax\": 31.1, \"tmin\": 13.3, \"rain\": 0.0}, {\"w_date\": \"5/13/82\", \"srad\": 24.2, \"tmax\": 30.6, \"tmin\": 13.3, \"rain\": 0.0}, {\"w_date\": \"5/14/82\", \"srad\": 26.7, \"tmax\": 31.1, \"tmin\": 12.8, \"rain\": 0.0}, {\"w_date\": \"5/15/82\", \"srad\": 23.9, \"tmax\": 32.2, \"tmin\": 15.6, \"rain\": 0.0}, {\"w_date\": \"5/16/82\", \"srad\": 22.8, \"tmax\": 33.3, \"tmin\": 15.6, \"rain\": 0.0}, {\"w_date\": \"5/17/82\", \"srad\": 22.7, \"tmax\": 32.8, \"tmin\": 15.6, \"rain\": 0.0}, {\"w_date\": \"5/18/82\", \"srad\": 21.5, \"tmax\": 31.1, \"tmin\": 16.7, \"rain\": 0.0}, {\"w_date\": \"5/19/82\", \"srad\": 22.4, \"tmax\": 30.6, \"tmin\": 16.7, \"rain\": 0.0}, {\"w_date\": \"5/20/82\", \"srad\": 22.5, \"tmax\": 31.7, \"tmin\": 16.1, \"rain\": 0.0}, {\"w_date\": \"5/21/82\", \"srad\": 22.6, \"tmax\": 32.2, \"tmin\": 16.1, \"rain\": 0.0}, {\"w_date\": \"5/22/82\", \"srad\": 17.4, \"tmax\": 32.8, \"tmin\": 16.7, \"rain\": 2.0}, {\"w_date\": \"5/23/82\", \"srad\": 13.2, \"tmax\": 33.3, \"tmin\": 20.0, \"rain\": 35.1}, {\"w_date\": \"5/24/82\", \"srad\": 21.5, \"tmax\": 32.8, \"tmin\": 18.9, \"rain\": 3.6}, {\"w_date\": \"5/25/82\", \"srad\": 20.3, \"tmax\": 32.8, \"tmin\": 20.0, \"rain\": 2.5}, {\"w_date\": \"5/26/82\", \"srad\": 15.0, \"tmax\": 31.7, \"tmin\": 20.6, \"rain\": 1.0}, {\"w_date\": \"5/27/82\", \"srad\": 18.2, \"tmax\": 32.2, \"tmin\": 21.1, \"rain\": 0.0}, {\"w_date\": \"5/28/82\", \"srad\": 22.1, \"tmax\": 33.3, \"tmin\": 20.6, \"rain\": 4.3}, {\"w_date\": \"5/29/82\", \"srad\": 19.3, \"tmax\": 34.4, \"tmin\": 22.2, \"rain\": 0.0}, {\"w_date\": \"5/30/82\", \"srad\": 7.0, \"tmax\": 32.2, \"tmin\": 22.8, \"rain\": 5.6}, {\"w_date\": \"5/31/82\", \"srad\": 11.8, \"tmax\": 30.0, \"tmin\": 20.6, \"rain\": 23.9}, {\"w_date\": \"6/1/82\", \"srad\": 20.0, \"tmax\": 31.1, \"tmin\": 21.1, \"rain\": 15.2}, {\"w_date\": \"6/2/82\", \"srad\": 24.9, \"tmax\": 33.3, \"tmin\": 20.0, \"rain\": 0.0}, {\"w_date\": \"6/3/82\", \"srad\": 15.8, \"tmax\": 33.3, \"tmin\": 22.8, \"rain\": 1.8}, {\"w_date\": \"6/4/82\", \"srad\": 21.6, \"tmax\": 33.3, \"tmin\": 22.2, \"rain\": 0.0}, {\"w_date\": \"6/5/82\", \"srad\": 23.8, \"tmax\": 33.9, \"tmin\": 18.3, \"rain\": 0.0}, {\"w_date\": \"6/6/82\", \"srad\": 26.5, \"tmax\": 34.4, \"tmin\": 18.3, \"rain\": 0.0}, {\"w_date\": \"6/7/82\", \"srad\": 26.9, \"tmax\": 33.9, \"tmin\": 18.3, \"rain\": 0.0}, {\"w_date\": \"6/8/82\", \"srad\": 26.3, \"tmax\": 34.4, \"tmin\": 17.2, \"rain\": 0.0}, {\"w_date\": \"6/9/82\", \"srad\": 24.4, \"tmax\": 34.4, \"tmin\": 19.4, \"rain\": 0.0}, {\"w_date\": \"6/10/82\", \"srad\": 25.5, \"tmax\": 34.4, \"tmin\": 21.1, \"rain\": 0.0}, {\"w_date\": \"6/11/82\", \"srad\": 23.6, \"tmax\": 35.0, \"tmin\": 19.4, \"rain\": 0.0}, {\"w_date\": \"6/12/82\", \"srad\": 15.2, \"tmax\": 31.1, \"tmin\": 20.0, \"rain\": 50.8}, {\"w_date\": \"6/13/82\", \"srad\": 21.1, \"tmax\": 33.3, \"tmin\": 21.1, \"rain\": 0.0}, {\"w_date\": \"6/14/82\", \"srad\": 25.5, \"tmax\": 33.3, \"tmin\": 18.3, \"rain\": 0.0}, {\"w_date\": \"6/15/82\", \"srad\": 23.2, \"tmax\": 33.9, \"tmin\": 20.6, \"rain\": 0.0}, {\"w_date\": \"6/16/82\", \"srad\": 25.5, \"tmax\": 33.9, \"tmin\": 22.2, \"rain\": 0.0}, {\"w_date\": \"6/17/82\", \"srad\": 6.0, \"tmax\": 31.1, \"tmin\": 21.1, \"rain\": 8.1}, {\"w_date\": \"6/18/82\", \"srad\": 13.5, \"tmax\": 27.8, \"tmin\": 21.1, \"rain\": 70.1}, {\"w_date\": \"6/19/82\", \"srad\": 24.3, \"tmax\": 33.3, \"tmin\": 20.0, \"rain\": 0.0}, {\"w_date\": \"6/20/82\", \"srad\": 25.9, \"tmax\": 33.9, \"tmin\": 21.1, \"rain\": 0.0}, {\"w_date\": \"6/21/82\", \"srad\": 20.9, \"tmax\": 32.8, \"tmin\": 20.0, \"rain\": 3.3}, {\"w_date\": \"6/22/82\", \"srad\": 18.5, \"tmax\": 28.3, \"tmin\": 23.3, \"rain\": 2.0}, {\"w_date\": \"6/23/82\", \"srad\": 11.7, \"tmax\": 27.8, \"tmin\": 21.7, \"rain\": 26.9}, {\"w_date\": \"6/24/82\", \"srad\": 18.6, \"tmax\": 30.6, \"tmin\": 22.2, \"rain\": 6.4}, {\"w_date\": \"6/25/82\", \"srad\": 22.9, \"tmax\": 32.2, \"tmin\": 19.4, \"rain\": 10.9}, {\"w_date\": \"6/26/82\", \"srad\": 10.5, \"tmax\": 31.7, \"tmin\": 21.7, \"rain\": 23.4}, {\"w_date\": \"6/27/82\", \"srad\": 24.6, \"tmax\": 32.2, \"tmin\": 21.1, \"rain\": 1.8}, {\"w_date\": \"6/28/82\", \"srad\": 24.6, \"tmax\": 32.8, \"tmin\": 21.7, \"rain\": 0.0}, {\"w_date\": \"6/29/82\", \"srad\": 24.8, \"tmax\": 33.3, \"tmin\": 22.2, \"rain\": 0.0}, {\"w_date\": \"6/30/82\", \"srad\": 16.0, \"tmax\": 32.8, \"tmin\": 22.8, \"rain\": 1.3}, {\"w_date\": \"7/1/82\", \"srad\": 23.7, \"tmax\": 33.9, \"tmin\": 22.2, \"rain\": 0.0}, {\"w_date\": \"7/2/82\", \"srad\": 18.7, \"tmax\": 33.9, \"tmin\": 23.9, \"rain\": 0.0}, {\"w_date\": \"7/3/82\", \"srad\": 24.6, \"tmax\": 35.0, \"tmin\": 21.1, \"rain\": 0.0}, {\"w_date\": \"7/4/82\", \"srad\": 21.1, \"tmax\": 35.0, \"tmin\": 22.2, \"rain\": 0.0}, {\"w_date\": \"7/5/82\", \"srad\": 23.7, \"tmax\": 34.4, \"tmin\": 21.1, \"rain\": 0.0}, {\"w_date\": \"7/6/82\", \"srad\": 19.0, \"tmax\": 32.2, \"tmin\": 20.6, \"rain\": 4.1}, {\"w_date\": \"7/7/82\", \"srad\": 16.0, \"tmax\": 31.7, \"tmin\": 21.1, \"rain\": 4.8}, {\"w_date\": \"7/8/82\", \"srad\": 19.8, \"tmax\": 32.2, \"tmin\": 21.1, \"rain\": 1.3}, {\"w_date\": \"7/9/82\", \"srad\": 13.7, \"tmax\": 32.2, \"tmin\": 22.2, \"rain\": 7.1}, {\"w_date\": \"7/10/82\", \"srad\": 17.4, \"tmax\": 32.8, \"tmin\": 21.7, \"rain\": 1.3}, {\"w_date\": \"7/11/82\", \"srad\": 18.3, \"tmax\": 32.8, \"tmin\": 21.1, \"rain\": 0.0}, {\"w_date\": \"7/12/82\", \"srad\": 21.0, \"tmax\": 32.8, \"tmin\": 21.1, \"rain\": 2.3}, {\"w_date\": \"7/13/82\", \"srad\": 23.2, \"tmax\": 33.9, \"tmin\": 22.2, \"rain\": 0.0}, {\"w_date\": \"7/14/82\", \"srad\": 25.4, \"tmax\": 34.4, \"tmin\": 22.2, \"rain\": 0.0}, {\"w_date\": \"7/15/82\", \"srad\": 18.3, \"tmax\": 33.9, \"tmin\": 23.3, \"rain\": 55.9}, {\"w_date\": \"7/16/82\", \"srad\": 14.9, \"tmax\": 32.8, \"tmin\": 22.8, \"rain\": 1.0}, {\"w_date\": \"7/17/82\", \"srad\": 13.6, \"tmax\": 31.1, \"tmin\": 22.8, \"rain\": 0.0}, {\"w_date\": \"7/18/82\", \"srad\": 14.3, \"tmax\": 32.2, \"tmin\": 22.8, \"rain\": 2.5}, {\"w_date\": \"7/19/82\", \"srad\": 17.0, \"tmax\": 32.2, \"tmin\": 22.2, \"rain\": 30.0}, {\"w_date\": \"7/20/82\", \"srad\": 10.9, \"tmax\": 31.1, \"tmin\": 21.7, \"rain\": 20.8}, {\"w_date\": \"7/21/82\", \"srad\": 13.2, \"tmax\": 31.1, \"tmin\": 21.1, \"rain\": 1.5}, {\"w_date\": \"7/22/82\", \"srad\": 17.9, \"tmax\": 31.1, \"tmin\": 22.2, \"rain\": 0.3}, {\"w_date\": \"7/23/82\", \"srad\": 16.1, \"tmax\": 32.8, \"tmin\": 22.8, \"rain\": 16.0}, {\"w_date\": \"7/24/82\", \"srad\": 18.4, \"tmax\": 32.2, \"tmin\": 21.7, \"rain\": 4.1}, {\"w_date\": \"7/25/82\", \"srad\": 19.7, \"tmax\": 33.3, \"tmin\": 21.7, \"rain\": 0.0}, {\"w_date\": \"7/26/82\", \"srad\": 19.4, \"tmax\": 33.9, \"tmin\": 22.2, \"rain\": 0.8}, {\"w_date\": \"7/27/82\", \"srad\": 5.2, \"tmax\": 34.4, \"tmin\": 23.3, \"rain\": 10.7}, {\"w_date\": \"7/28/82\", \"srad\": 9.5, \"tmax\": 27.8, \"tmin\": 22.8, \"rain\": 7.4}, {\"w_date\": \"7/29/82\", \"srad\": 14.9, \"tmax\": 31.7, \"tmin\": 22.8, \"rain\": 0.0}, {\"w_date\": \"7/30/82\", \"srad\": 19.4, \"tmax\": 32.8, \"tmin\": 21.7, \"rain\": 0.0}, {\"w_date\": \"7/31/82\", \"srad\": 20.1, \"tmax\": 33.9, \"tmin\": 21.1, \"rain\": 0.0}, {\"w_date\": \"8/1/82\", \"srad\": 23.5, \"tmax\": 33.9, \"tmin\": 23.3, \"rain\": 0.0}, {\"w_date\": \"8/2/82\", \"srad\": 9.6, \"tmax\": 32.8, \"tmin\": 22.8, \"rain\": 13.0}, {\"w_date\": \"8/3/82\", \"srad\": 22.5, \"tmax\": 32.2, \"tmin\": 22.8, \"rain\": 20.1}, {\"w_date\": \"8/4/82\", \"srad\": 21.0, \"tmax\": 32.2, \"tmin\": 20.6, \"rain\": 0.0}, {\"w_date\": \"8/5/82\", \"srad\": 14.7, \"tmax\": 32.2, \"tmin\": 21.7, \"rain\": 0.0}, {\"w_date\": \"8/6/82\", \"srad\": 18.5, \"tmax\": 32.2, \"tmin\": 21.1, \"rain\": 4.1}, {\"w_date\": \"8/7/82\", \"srad\": 23.0, \"tmax\": 33.9, \"tmin\": 21.7, \"rain\": 0.3}, {\"w_date\": \"8/8/82\", \"srad\": 21.0, \"tmax\": 33.9, \"tmin\": 26.1, \"rain\": 0.0}, {\"w_date\": \"8/9/82\", \"srad\": 17.1, \"tmax\": 32.8, \"tmin\": 22.8, \"rain\": 1.3}, {\"w_date\": \"8/10/82\", \"srad\": 16.6, \"tmax\": 33.3, \"tmin\": 23.3, \"rain\": 0.0}, {\"w_date\": \"8/11/82\", \"srad\": 25.6, \"tmax\": 33.3, \"tmin\": 18.9, \"rain\": 0.0}, {\"w_date\": \"8/12/82\", \"srad\": 19.0, \"tmax\": 33.3, \"tmin\": 20.6, \"rain\": 0.3}, {\"w_date\": \"8/13/82\", \"srad\": 16.1, \"tmax\": 32.2, \"tmin\": 20.6, \"rain\": 0.8}, {\"w_date\": \"8/14/82\", \"srad\": 16.4, \"tmax\": 31.7, \"tmin\": 22.2, \"rain\": 0.0}, {\"w_date\": \"8/15/82\", \"srad\": 20.3, \"tmax\": 35.0, \"tmin\": 20.6, \"rain\": 0.8}, {\"w_date\": \"8/16/82\", \"srad\": 20.3, \"tmax\": 33.9, \"tmin\": 21.1, \"rain\": 0.0}, {\"w_date\": \"8/17/82\", \"srad\": 19.0, \"tmax\": 32.2, \"tmin\": 22.2, \"rain\": 13.7}, {\"w_date\": \"8/18/82\", \"srad\": 16.6, \"tmax\": 26.7, \"tmin\": 20.6, \"rain\": 3.3}, {\"w_date\": \"8/19/82\", \"srad\": 7.9, \"tmax\": 28.3, \"tmin\": 21.7, \"rain\": 20.3}, {\"w_date\": \"8/20/82\", \"srad\": 20.4, \"tmax\": 32.2, \"tmin\": 21.1, \"rain\": 0.0}, {\"w_date\": \"8/21/82\", \"srad\": 11.8, \"tmax\": 32.2, \"tmin\": 21.7, \"rain\": 5.1}, {\"w_date\": \"8/22/82\", \"srad\": 16.6, \"tmax\": 32.2, \"tmin\": 22.2, \"rain\": 1.3}, {\"w_date\": \"8/23/82\", \"srad\": 15.2, \"tmax\": 31.7, \"tmin\": 22.2, \"rain\": 64.5}, {\"w_date\": \"8/24/82\", \"srad\": 18.9, \"tmax\": 33.3, \"tmin\": 22.8, \"rain\": 1.3}, {\"w_date\": \"8/25/82\", \"srad\": 18.8, \"tmax\": 33.3, \"tmin\": 22.2, \"rain\": 0.0}, {\"w_date\": \"8/26/82\", \"srad\": 21.4, \"tmax\": 35.6, \"tmin\": 23.9, \"rain\": 0.0}, {\"w_date\": \"8/27/82\", \"srad\": 11.0, \"tmax\": 35.6, \"tmin\": 22.8, \"rain\": 3.6}, {\"w_date\": \"8/28/82\", \"srad\": 18.6, \"tmax\": 35.0, \"tmin\": 22.2, \"rain\": 0.0}, {\"w_date\": \"8/29/82\", \"srad\": 15.8, \"tmax\": 35.0, \"tmin\": 22.2, \"rain\": 3.6}, {\"w_date\": \"8/30/82\", \"srad\": 22.5, \"tmax\": 31.1, \"tmin\": 21.1, \"rain\": 0.0}, {\"w_date\": \"8/31/82\", \"srad\": 21.1, \"tmax\": 32.2, \"tmin\": 20.6, \"rain\": 0.0}, {\"w_date\": \"9/1/82\", \"srad\": 13.2, \"tmax\": 32.2, \"tmin\": 20.6, \"rain\": 0.0}, {\"w_date\": \"9/2/82\", \"srad\": 15.6, \"tmax\": 33.3, \"tmin\": 18.3, \"rain\": 0.0}, {\"w_date\": \"9/3/82\", \"srad\": 16.9, \"tmax\": 34.4, \"tmin\": 22.2, \"rain\": 0.0}, {\"w_date\": \"9/4/82\", \"srad\": 17.0, \"tmax\": 34.4, \"tmin\": 22.2, \"rain\": 0.0}, {\"w_date\": \"9/5/82\", \"srad\": 12.2, \"tmax\": 33.9, \"tmin\": 21.7, \"rain\": 11.9}, {\"w_date\": \"9/6/82\", \"srad\": 9.0, \"tmax\": 34.4, \"tmin\": 21.1, \"rain\": 2.0}, {\"w_date\": \"9/7/82\", \"srad\": 11.1, \"tmax\": 30.0, \"tmin\": 20.0, \"rain\": 0.0}, {\"w_date\": \"9/8/82\", \"srad\": 9.6, \"tmax\": 30.6, \"tmin\": 20.6, \"rain\": 19.0}, {\"w_date\": \"9/9/82\", \"srad\": 7.1, \"tmax\": 30.0, \"tmin\": 21.1, \"rain\": 39.9}, {\"w_date\": \"9/10/82\", \"srad\": 5.5, \"tmax\": 30.0, \"tmin\": 21.1, \"rain\": 24.1}, {\"w_date\": \"9/11/82\", \"srad\": 13.4, \"tmax\": 32.8, \"tmin\": 21.7, \"rain\": 7.6}, {\"w_date\": \"9/12/82\", \"srad\": 14.6, \"tmax\": 33.3, \"tmin\": 22.8, \"rain\": 0.0}, {\"w_date\": \"9/13/82\", \"srad\": 14.5, \"tmax\": 33.3, \"tmin\": 22.8, \"rain\": 2.5}, {\"w_date\": \"9/14/82\", \"srad\": 12.3, \"tmax\": 32.8, \"tmin\": 22.2, \"rain\": 1.8}, {\"w_date\": \"9/15/82\", \"srad\": 13.0, \"tmax\": 32.2, \"tmin\": 19.4, \"rain\": 0.0}, {\"w_date\": \"9/16/82\", \"srad\": 12.6, \"tmax\": 32.8, \"tmin\": 21.7, \"rain\": 0.0}, {\"w_date\": \"9/17/82\", \"srad\": 13.9, \"tmax\": 32.8, \"tmin\": 21.7, \"rain\": 0.0}, {\"w_date\": \"9/18/82\", \"srad\": 12.2, \"tmax\": 32.8, \"tmin\": 21.1, \"rain\": 0.0}, {\"w_date\": \"9/19/82\", \"srad\": 12.2, \"tmax\": 32.8, \"tmin\": 21.1, \"rain\": 15.7}, {\"w_date\": \"9/20/82\", \"srad\": 11.1, \"tmax\": 31.7, \"tmin\": 21.1, \"rain\": 7.4}, {\"w_date\": \"9/21/82\", \"srad\": 5.2, \"tmax\": 29.4, \"tmin\": 21.1, \"rain\": 12.7}, {\"w_date\": \"9/22/82\", \"srad\": 11.4, \"tmax\": 27.8, \"tmin\": 19.4, \"rain\": 0.0}, {\"w_date\": \"9/23/82\", \"srad\": 8.9, \"tmax\": 27.2, \"tmin\": 15.0, \"rain\": 0.0}, {\"w_date\": \"9/24/82\", \"srad\": 11.2, \"tmax\": 30.0, \"tmin\": 17.8, \"rain\": 0.0}, {\"w_date\": \"9/25/82\", \"srad\": 5.0, \"tmax\": 28.9, \"tmin\": 20.0, \"rain\": 8.9}, {\"w_date\": \"9/26/82\", \"srad\": 7.6, \"tmax\": 25.0, \"tmin\": 16.7, \"rain\": 24.1}, {\"w_date\": \"9/27/82\", \"srad\": 15.6, \"tmax\": 28.9, \"tmin\": 14.4, \"rain\": 0.0}, {\"w_date\": \"9/28/82\", \"srad\": 13.9, \"tmax\": 29.4, \"tmin\": 16.7, \"rain\": 0.0}, {\"w_date\": \"9/29/82\", \"srad\": 12.1, \"tmax\": 29.4, \"tmin\": 18.3, \"rain\": 0.0}, {\"w_date\": \"9/30/82\", \"srad\": 6.7, \"tmax\": 28.9, \"tmin\": 21.1, \"rain\": 2.5}, {\"w_date\": \"10/1/82\", \"srad\": 8.0, \"tmax\": 26.7, \"tmin\": 21.7, \"rain\": 0.0}, {\"w_date\": \"10/2/82\", \"srad\": 10.0, \"tmax\": 28.3, \"tmin\": 19.4, \"rain\": 0.0}, {\"w_date\": \"10/3/82\", \"srad\": 19.0, \"tmax\": 30.0, \"tmin\": 18.3, \"rain\": 0.0}, {\"w_date\": \"10/4/82\", \"srad\": 16.0, \"tmax\": 31.7, \"tmin\": 20.6, \"rain\": 0.0}, {\"w_date\": \"10/5/82\", \"srad\": 9.0, \"tmax\": 31.1, \"tmin\": 22.8, \"rain\": 0.0}, {\"w_date\": \"10/6/82\", \"srad\": 16.0, \"tmax\": 31.1, \"tmin\": 21.7, \"rain\": 13.0}, {\"w_date\": \"10/7/82\", \"srad\": 13.0, \"tmax\": 30.0, \"tmin\": 21.1, \"rain\": 0.0}, {\"w_date\": \"10/8/82\", \"srad\": 17.0, \"tmax\": 31.7, \"tmin\": 17.2, \"rain\": 0.0}, {\"w_date\": \"10/9/82\", \"srad\": 15.0, \"tmax\": 31.7, \"tmin\": 18.9, \"rain\": 0.0}, {\"w_date\": \"10/10/82\", \"srad\": 15.0, \"tmax\": 32.8, \"tmin\": 20.0, \"rain\": 0.0}, {\"w_date\": \"10/11/82\", \"srad\": 13.0, \"tmax\": 32.2, \"tmin\": 21.7, \"rain\": 0.0}, {\"w_date\": \"10/12/82\", \"srad\": 11.0, \"tmax\": 29.4, \"tmin\": 21.7, \"rain\": 0.0}, {\"w_date\": \"10/13/82\", \"srad\": 14.0, \"tmax\": 30.6, \"tmin\": 18.9, \"rain\": 0.0}, {\"w_date\": \"10/14/82\", \"srad\": 10.0, \"tmax\": 28.9, \"tmin\": 16.7, \"rain\": 0.0}, {\"w_date\": \"10/15/82\", \"srad\": 15.0, \"tmax\": 27.8, \"tmin\": 11.7, \"rain\": 0.0}, {\"w_date\": \"10/16/82\", \"srad\": 9.0, \"tmax\": 26.1, \"tmin\": 10.0, \"rain\": 0.0}, {\"w_date\": \"10/17/82\", \"srad\": 14.0, \"tmax\": 26.7, \"tmin\": 13.3, \"rain\": 0.0}, {\"w_date\": \"10/18/82\", \"srad\": 6.0, \"tmax\": 25.6, \"tmin\": 15.0, \"rain\": 0.0}, {\"w_date\": \"10/19/82\", \"srad\": 14.0, \"tmax\": 28.3, \"tmin\": 16.1, \"rain\": 0.0}, {\"w_date\": \"10/20/82\", \"srad\": 13.0, \"tmax\": 30.0, \"tmin\": 16.7, \"rain\": 0.0}, {\"w_date\": \"10/21/82\", \"srad\": 14.0, \"tmax\": 30.0, \"tmin\": 15.0, \"rain\": 0.0}, {\"w_date\": \"10/22/82\", \"srad\": 11.0, \"tmax\": 29.4, \"tmin\": 16.1, \"rain\": 0.0}, {\"w_date\": \"10/23/82\", \"srad\": 2.0, \"tmax\": 27.8, \"tmin\": 14.4, \"rain\": 16.5}, {\"w_date\": \"10/24/82\", \"srad\": 14.0, \"tmax\": 18.9, \"tmin\": 8.9, \"rain\": 1.3}, {\"w_date\": \"10/25/82\", \"srad\": 16.0, \"tmax\": 20.6, \"tmin\": 5.6, \"rain\": 0.0}, {\"w_date\": \"10/26/82\", \"srad\": 15.0, \"tmax\": 22.8, \"tmin\": 6.1, \"rain\": 0.0}, {\"w_date\": \"10/27/82\", \"srad\": 15.0, \"tmax\": 23.9, \"tmin\": 7.2, \"rain\": 0.0}, {\"w_date\": \"10/28/82\", \"srad\": 14.0, \"tmax\": 25.6, \"tmin\": 11.7, \"rain\": 0.0}, {\"w_date\": \"10/29/82\", \"srad\": 14.0, \"tmax\": 27.8, \"tmin\": 13.3, \"rain\": 0.0}, {\"w_date\": \"10/30/82\", \"srad\": 9.0, \"tmax\": 27.8, \"tmin\": 16.1, \"rain\": 0.0}, {\"w_date\": \"10/31/82\", \"srad\": 7.0, \"tmax\": 27.8, \"tmin\": 18.9, \"rain\": 0.0}, {\"w_date\": \"11/1/82\", \"srad\": 11.0, \"tmax\": 29.4, \"tmin\": 20.0, \"rain\": 0.3}, {\"w_date\": \"11/2/82\", \"srad\": 9.0, \"tmax\": 29.4, \"tmin\": 20.6, \"rain\": 0.0}, {\"w_date\": \"11/3/82\", \"srad\": 9.0, \"tmax\": 28.9, \"tmin\": 19.4, \"rain\": 21.6}, {\"w_date\": \"11/4/82\", \"srad\": 9.0, \"tmax\": 26.7, \"tmin\": 17.8, \"rain\": 16.5}, {\"w_date\": \"11/5/82\", \"srad\": 10.0, \"tmax\": 18.3, \"tmin\": 7.2, \"rain\": 0.0}, {\"w_date\": \"11/6/82\", \"srad\": 12.0, \"tmax\": 18.9, \"tmin\": 2.2, \"rain\": 0.0}, {\"w_date\": \"11/7/82\", \"srad\": 12.0, \"tmax\": 21.1, \"tmin\": 7.8, \"rain\": 0.0}, {\"w_date\": \"11/8/82\", \"srad\": 13.0, \"tmax\": 24.4, \"tmin\": 12.8, \"rain\": 0.0}, {\"w_date\": \"11/9/82\", \"srad\": 11.0, \"tmax\": 25.0, \"tmin\": 12.8, \"rain\": 0.0}, {\"w_date\": \"11/10/82\", \"srad\": 12.0, \"tmax\": 25.6, \"tmin\": 10.6, \"rain\": 0.0}, {\"w_date\": \"11/11/82\", \"srad\": 8.0, \"tmax\": 26.7, \"tmin\": 15.6, \"rain\": 0.0}, {\"w_date\": \"11/12/82\", \"srad\": 7.0, \"tmax\": 27.8, \"tmin\": 14.4, \"rain\": 0.0}, {\"w_date\": \"11/13/82\", \"srad\": 11.0, \"tmax\": 31.1, \"tmin\": 13.3, \"rain\": 3.6}, {\"w_date\": \"11/14/82\", \"srad\": 12.0, \"tmax\": 25.0, \"tmin\": 6.7, \"rain\": 0.0}, {\"w_date\": \"11/15/82\", \"srad\": 10.0, \"tmax\": 23.9, \"tmin\": 15.0, \"rain\": 0.0}, {\"w_date\": \"11/16/82\", \"srad\": 11.0, \"tmax\": 23.9, \"tmin\": 9.4, \"rain\": 0.0}, {\"w_date\": \"11/17/82\", \"srad\": 13.0, \"tmax\": 26.7, \"tmin\": 15.6, \"rain\": 0.0}, {\"w_date\": \"11/18/82\", \"srad\": 13.0, \"tmax\": 28.3, \"tmin\": 17.8, \"rain\": 0.0}, {\"w_date\": \"11/19/82\", \"srad\": 11.0, \"tmax\": 26.7, \"tmin\": 17.8, \"rain\": 0.0}, {\"w_date\": \"11/20/82\", \"srad\": 12.0, \"tmax\": 25.6, \"tmin\": 17.2, \"rain\": 0.0}, {\"w_date\": \"11/21/82\", \"srad\": 14.0, \"tmax\": 27.2, \"tmin\": 17.2, \"rain\": 0.0}, {\"w_date\": \"11/22/82\", \"srad\": 13.0, \"tmax\": 26.1, \"tmin\": 18.3, \"rain\": 0.0}, {\"w_date\": \"11/23/82\", \"srad\": 13.0, \"tmax\": 27.2, \"tmin\": 14.4, \"rain\": 0.0}, {\"w_date\": \"11/24/82\", \"srad\": 13.0, \"tmax\": 27.8, \"tmin\": 12.2, \"rain\": 0.0}, {\"w_date\": \"11/25/82\", \"srad\": 15.0, \"tmax\": 27.2, \"tmin\": 12.8, \"rain\": 0.0}, {\"w_date\": \"11/26/82\", \"srad\": 12.0, \"tmax\": 26.7, \"tmin\": 15.6, \"rain\": 0.0}, {\"w_date\": \"11/27/82\", \"srad\": 3.0, \"tmax\": 27.8, \"tmin\": 15.6, \"rain\": 0.0}, {\"w_date\": \"11/28/82\", \"srad\": 10.0, \"tmax\": 28.9, \"tmin\": 15.6, \"rain\": 0.0}, {\"w_date\": \"11/29/82\", \"srad\": 10.0, \"tmax\": 27.2, \"tmin\": 18.9, \"rain\": 0.0}, {\"w_date\": \"11/30/82\", \"srad\": 9.0, \"tmax\": 29.4, \"tmin\": 19.4, \"rain\": 0.0}, {\"w_date\": \"12/1/82\", \"srad\": 8.0, \"tmax\": 28.9, \"tmin\": 20.6, \"rain\": 0.0}, {\"w_date\": \"12/2/82\", \"srad\": 10.0, \"tmax\": 29.4, \"tmin\": 21.1, \"rain\": 0.0}, {\"w_date\": \"12/3/82\", \"srad\": 11.0, \"tmax\": 29.4, \"tmin\": 18.9, \"rain\": 0.0}, {\"w_date\": \"12/4/82\", \"srad\": 11.0, \"tmax\": 28.9, \"tmin\": 18.3, \"rain\": 0.0}, {\"w_date\": \"12/5/82\", \"srad\": 8.0, \"tmax\": 28.9, \"tmin\": 17.2, \"rain\": 0.0}, {\"w_date\": \"12/6/82\", \"srad\": 2.0, \"tmax\": 27.2, \"tmin\": 15.6, \"rain\": 0.0}, {\"w_date\": \"12/7/82\", \"srad\": 5.0, \"tmax\": 21.7, \"tmin\": 14.4, \"rain\": 0.0}, {\"w_date\": \"12/8/82\", \"srad\": 2.0, \"tmax\": 20.0, \"tmin\": 17.2, \"rain\": 0.0}, {\"w_date\": \"12/9/82\", \"srad\": 7.0, \"tmax\": 23.3, \"tmin\": 14.4, \"rain\": 0.0}, {\"w_date\": \"12/10/82\", \"srad\": 2.0, \"tmax\": 22.2, \"tmin\": 15.6, \"rain\": 3.3}, {\"w_date\": \"12/11/82\", \"srad\": 5.0, \"tmax\": 26.1, \"tmin\": 17.2, \"rain\": 0.0}, {\"w_date\": \"12/12/82\", \"srad\": 2.0, \"tmax\": 23.9, \"tmin\": 10.0, \"rain\": 19.0}, {\"w_date\": \"12/13/82\", \"srad\": 11.0, \"tmax\": 12.8, \"tmin\": 2.8, \"rain\": 0.0}, {\"w_date\": \"12/14/82\", \"srad\": 6.0, \"tmax\": 18.9, \"tmin\": 3.3, \"rain\": 0.0}, {\"w_date\": \"12/15/82\", \"srad\": 8.0, \"tmax\": 25.0, \"tmin\": 12.8, \"rain\": 0.0}, {\"w_date\": \"12/16/82\", \"srad\": 6.0, \"tmax\": 23.9, \"tmin\": 15.6, \"rain\": 13.7}, {\"w_date\": \"12/17/82\", \"srad\": 11.0, \"tmax\": 20.0, \"tmin\": 2.8, \"rain\": 0.0}, {\"w_date\": \"12/18/82\", \"srad\": 11.0, \"tmax\": 15.6, \"tmin\": -1.1, \"rain\": 0.0}, {\"w_date\": \"12/19/82\", \"srad\": 9.0, \"tmax\": 20.0, \"tmin\": -1.1, \"rain\": 0.0}, {\"w_date\": \"12/20/82\", \"srad\": 11.0, \"tmax\": 18.9, \"tmin\": 1.1, \"rain\": 0.0}, {\"w_date\": \"12/21/82\", \"srad\": 11.0, \"tmax\": 19.4, \"tmin\": 0.6, \"rain\": 0.0}, {\"w_date\": \"12/22/82\", \"srad\": 11.0, \"tmax\": 19.4, \"tmin\": 0.6, \"rain\": 0.0}, {\"w_date\": \"12/23/82\", \"srad\": 9.0, \"tmax\": 23.3, \"tmin\": 4.4, \"rain\": 0.0}, {\"w_date\": \"12/24/82\", \"srad\": 9.0, \"tmax\": 26.7, \"tmin\": 13.3, \"rain\": 0.0}, {\"w_date\": \"12/25/82\", \"srad\": 11.0, \"tmax\": 27.2, \"tmin\": 15.6, \"rain\": 0.0}, {\"w_date\": \"12/26/82\", \"srad\": 10.0, \"tmax\": 27.2, \"tmin\": 15.6, \"rain\": 0.0}, {\"w_date\": \"12/27/82\", \"srad\": 6.0, \"tmax\": 25.0, \"tmin\": 16.7, \"rain\": 0.0}, {\"w_date\": \"12/28/82\", \"srad\": 8.0, \"tmax\": 26.7, \"tmin\": 16.1, \"rain\": 0.0}, {\"w_date\": \"12/29/82\", \"srad\": 7.0, \"tmax\": 26.7, \"tmin\": 14.4, \"rain\": 0.0}, {\"w_date\": \"12/30/82\", \"srad\": 2.0, \"tmax\": 23.3, \"tmin\": 13.9, \"rain\": 0.5}, {\"w_date\": \"12/31/82\", \"srad\": 2.0, \"tmax\": 16.7, \"tmin\": 12.8, \"rain\": 0.8}], \"elev\": 10.0, \"wsta_insi\": \"UFGA\", \"tamp\": 7.5}, \"soil\": {\"soil_id\": \"IBMZ910014\", \"sl_system\": \"SCS\", \"soillong\": -82.37, \"name\": \"Millhopper Fine Sand\", \"sldr\": 0.65, \"soil\": [{\"silt\": 11.8, \"sldul\": 0.086, \"slll\": 0.02, \"clay\": 0.9, \"slbdm\": 7.4, \"slcf\": 2.0, \"sloc\": 5.3, \"slphw\": 1.36, \"slsat\": 0.23, \"sllb\": 5.0}, {\"silt\": 11.8, \"sldul\": 0.086, \"slll\": 0.023, \"clay\": 0.9, \"slbdm\": 7.4, \"slcf\": 1.0, \"sloc\": 5.4, \"slphw\": 1.4, \"slsat\": 0.23, \"sllb\": 15.0}, {\"silt\": 6.4, \"sldul\": 0.086, \"slll\": 0.023, \"clay\": 4.6, \"slbdm\": 15.8, \"slcf\": 1.0, \"sloc\": 5.7, \"slphw\": 1.46, \"slsat\": 0.23, \"sllb\": 30.0}, {\"silt\": 5.4, \"sldul\": 0.086, \"slll\": 0.023, \"clay\": 5.8, \"slbdm\": 28.0, \"slcf\": 0.5, \"sloc\": 5.8, \"slphw\": 1.46, \"slsat\": 0.23, \"sllb\": 45.0}, {\"silt\": 5.4, \"sldul\": 0.086, \"slll\": 0.023, \"clay\": 5.8, \"slbdm\": 28.0, \"slcf\": 0.5, \"sloc\": 5.8, \"slphw\": 1.47, \"slsat\": 0.23, \"sllb\": 60.0}, {\"silt\": 4.2, \"sldul\": 0.076, \"slll\": 0.021, \"clay\": 9.6, \"slbdm\": 27.6, \"slcf\": 0.1, \"sloc\": 5.9, \"slphw\": 1.43, \"slsat\": 0.23, \"sllb\": 90.0}, {\"silt\": 4.2, \"sldul\": 0.076, \"slll\": 0.02, \"clay\": 9.6, \"slbdm\": 17.5, \"slcf\": 0.1, \"sloc\": 5.9, \"slphw\": 1.48, \"slsat\": 0.23, \"sllb\": 120.0}, {\"silt\": 3.6, \"sldul\": 0.13, \"slll\": 0.027, \"clay\": 8.3, \"slbdm\": 0.3, \"slcf\": 0.04, \"sloc\": 5.9, \"slphw\": 1.57, \"slsat\": 0.23, \"sllb\": 150.0}, {\"silt\": 3.6, \"sldul\": 0.258, \"slll\": 0.07, \"clay\": 8.3, \"slbdm\": 0.1, \"slcf\": 0.24, \"sloc\": 5.9, \"slphw\": 1.79, \"slsat\": 0.36, \"sllb\": 180.0}, {\"silt\": \"\", \"sldul\": \"\", \"slll\": \"\", \"clay\": \"\", \"slbdm\": \"\", \"slcf\": \"\", \"sloc\": \"\", \"slphw\": \"\", \"slsat\": \"\", \"sllb\": \"\"}], \"salb\": 0.18, \"slnf\": 1.0, \"soillat\": 29.63, \"classifcation\": \"LS\"}}"; // Default value for each type of value (R: real number; C: String; I: Integer; D: Date) private static String defValR = "0.00"; private static String defValC = ""; private static String defValI = "0"; private static String defValD = "1/1/11"; /** * DSSAT Weather Data Input method * * @author Meng Zhang * @version 0.1 * @param arg0 file name(?) * @return data holder object */ @Override public AdvancedHashMap<String, Object> readFile(String arg0) { return null; } /** * DSSAT Weather Data Output method * * @author Meng Zhang * @version 1.0 * @param arg0 file name(?) * @param result data holder object */ @Override public void writeFile(String arg0, AdvancedHashMap result) { // Initial variables JSONAdapter adapter = new JSONAdapter(); // JSON Adapter AdvancedHashMap<String, Object> record; // Data holder for daily data AdvancedHashMap<String, Object> data; // Data holder for whole weather data BufferedWriter br; // output object //String[] optDailyId = {"tdew", "wind", "pard"}; // Define optional daily data fields HashMap optDaily = new HashMap(); optDaily.put("tdew", " DEWP"); optDaily.put("wind", " WIND"); optDaily.put("pard", " PAR"); Set<String> optDailyIds = optDaily.keySet(); //StringBuilder optDailyTitle = new StringBuilder(); // File file; // FileWriter output; try { // Set default value for missing data setDefVal(); // Get Data from input holder data = result; ArrayList weatherRecords = (ArrayList) data.getOr("WeatherDaily", new ArrayList()); // Initial BufferedWriter br = new BufferedWriter(new FileWriter(new File("a.tmp"))); // Output Weather File // Titel Section br.write(String.format(" %1$-60s\r\n", data.getOr("wst_name", defValC).toString())); // Weather Station Section br.write("@ INSI LAT LONG ELEV TAV AMP REFHT WNDHT\r\n"); br.write(String.format(" %1$-4s %2$8s %3$8s %4$5s %5$5s %6$5s %7$5s %8$5s\r\n", data.getOr("wst_insi", defValC).toString(), data.getOr("wst_lat", defValR).toString(), data.getOr("wst_long", defValR).toString(), data.getOr("elev", defValR).toString(), data.getOr("tav", defValR).toString(), data.getOr("tamp", defValR).toString(), data.getOr("refht", defValR).toString(), data.getOr("wndht", defValR).toString())); // Daily weather data section // Fixed Title br.write("@DATE SRAD TMAX TMIN RAIN"); // Optional Title for (String optDailyId : optDailyIds) { // check which optional data is exist, if not, remove from map if (!data.getOr(optDailyId, "").toString().equals("")) { br.write(optDaily.get(optDailyId).toString()); } else { optDaily.remove(optDailyId); } } br.write("\r\n"); optDailyIds = optDaily.keySet(); for (int i = 0; i < weatherRecords.size(); i++) { record = adapter.exportRecord((Map) weatherRecords.get(i)); // if date is missing, jump the record if (!record.getOr("w_date", "").toString().equals("")) { // Fixed data part br.write(String.format("%1$5s %2$5s %3$5s %4$5s %5$5s", formatDateStr(record.getOr("w_date", defValD).toString()), record.getOr("srad", defValR).toString(), record.getOr("tmax", defValR).toString(), record.getOr("tmin", defValR).toString(), record.getOr("rain", defValR).toString())); // Optional data part for (String optDailyId : optDailyIds) { br.write(String.format(" %1$5s", record.getOr(optDailyId, defValR).toString())); } br.write("\r\n"); } else { // TODO Throw exception here System.out.println("A daily record has the missing date in it."); } } // Output finish br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Translate data str from "yyyymmdd" to "yyddd" * * 2012/3/19 change input format from "yy/mm/dd" to "yyyymmdd" * * @author Meng Zhang * @version 1.1 * @param str date string with format of "yyyymmdd" * @return result date string with format of "yyddd" */ private String formatDateStr(String str) { // Initial Calendar object Calendar cal = Calendar.getInstance(); str = str.replaceAll("/", ""); try { // Set date with input value cal.set(Integer.valueOf(str.substring(0,4)), Integer.valueOf(str.substring(4,6)), Integer.valueOf(str.substring(6))); // translatet to yyddd format return String.format("%1$02d%2$03d", cal.get(Calendar.YEAR), cal.get(Calendar.DAY_OF_YEAR)); } catch (Exception e) { // if tranlate failed, then use default value for date return defValD; } } /** * Set default value for missing data * * @author Meng Zhang * @version 1.0 */ private void setDefVal() { // defValD = ""; No need to set default value for Date type in weather file defValR = "-99.0"; defValC = ""; defValI = "-99"; } }
package org.altbeacon.beacon.service; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.PendingIntent; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.bluetooth.le.ScanFilter; import android.bluetooth.le.ScanSettings; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.os.AsyncTask; import android.os.Build; import android.support.annotation.MainThread; import android.support.annotation.NonNull; import android.support.annotation.RequiresApi; import android.support.annotation.WorkerThread; import android.support.annotation.RestrictTo; import android.support.annotation.RestrictTo.Scope; import org.altbeacon.beacon.Beacon; import org.altbeacon.beacon.BeaconManager; import org.altbeacon.beacon.BeaconParser; import org.altbeacon.beacon.Region; import org.altbeacon.beacon.logging.LogManager; import org.altbeacon.beacon.service.scanner.CycledLeScanCallback; import org.altbeacon.beacon.service.scanner.CycledLeScanner; import org.altbeacon.beacon.service.scanner.DistinctPacketDetector; import org.altbeacon.beacon.service.scanner.NonBeaconLeScanCallback; import org.altbeacon.beacon.service.scanner.ScanFilterUtils; import org.altbeacon.beacon.startup.StartupBroadcastReceiver; import org.altbeacon.bluetooth.BluetoothCrashResolver; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; class ScanHelper { private static final String TAG = ScanHelper.class.getSimpleName(); private ExecutorService mExecutor; private BeaconManager mBeaconManager; private CycledLeScanner mCycledScanner; private MonitoringStatus mMonitoringStatus; private final Map<Region, RangeState> mRangedRegionState = new HashMap<>(); private DistinctPacketDetector mDistinctPacketDetector = new DistinctPacketDetector(); private ExtraDataBeaconTracker mExtraDataBeaconTracker; private Set<BeaconParser> mBeaconParsers = new HashSet<>(); private List<Beacon> mSimulatedScanData = null; private Context mContext; ScanHelper(Context context) { mContext = context; mBeaconManager = BeaconManager.getInstanceForApplication(context); mExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1); } CycledLeScanner getCycledScanner() { return mCycledScanner; } MonitoringStatus getMonitoringStatus() { return mMonitoringStatus; } void setMonitoringStatus(MonitoringStatus monitoringStatus) { mMonitoringStatus = monitoringStatus; } Map<Region, RangeState> getRangedRegionState() { return mRangedRegionState; } void setRangedRegionState(Map<Region, RangeState> rangedRegionState) { synchronized (mRangedRegionState) { mRangedRegionState.clear(); mRangedRegionState.putAll(rangedRegionState); } } void setExtraDataBeaconTracker(ExtraDataBeaconTracker extraDataBeaconTracker) { mExtraDataBeaconTracker = extraDataBeaconTracker; } void setBeaconParsers(Set<BeaconParser> beaconParsers) { mBeaconParsers = beaconParsers; } void setSimulatedScanData(List<Beacon> simulatedScanData) { mSimulatedScanData = simulatedScanData; } void createCycledLeScanner(boolean backgroundMode, BluetoothCrashResolver crashResolver) { mCycledScanner = CycledLeScanner.createScanner(mContext, BeaconManager.DEFAULT_FOREGROUND_SCAN_PERIOD, BeaconManager.DEFAULT_FOREGROUND_BETWEEN_SCAN_PERIOD, backgroundMode, mCycledLeScanCallback, crashResolver); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) void processScanResult(BluetoothDevice device, int rssi, byte[] scanRecord) { NonBeaconLeScanCallback nonBeaconLeScanCallback = mBeaconManager.getNonBeaconLeScanCallback(); try { new ScanHelper.ScanProcessor(nonBeaconLeScanCallback).executeOnExecutor(mExecutor, new ScanHelper.ScanData(device, rssi, scanRecord)); } catch (RejectedExecutionException e) { LogManager.w(TAG, "Ignoring scan result because we cannot keep up."); } } void reloadParsers() { HashSet<BeaconParser> newBeaconParsers = new HashSet<>(); //flatMap all beacon parsers boolean matchBeaconsByServiceUUID = true; newBeaconParsers.addAll(mBeaconManager.getBeaconParsers()); for (BeaconParser beaconParser : mBeaconManager.getBeaconParsers()) { if (beaconParser.getExtraDataParsers().size() > 0) { matchBeaconsByServiceUUID = false; newBeaconParsers.addAll(beaconParser.getExtraDataParsers()); } } mBeaconParsers = newBeaconParsers; //initialize the extra data beacon tracker mExtraDataBeaconTracker = new ExtraDataBeaconTracker(matchBeaconsByServiceUUID); } @RequiresApi(api = Build.VERSION_CODES.O) void startAndroidOBackgroundScan(Set<BeaconParser> beaconParsers) { ScanSettings settings = (new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)).build(); List<ScanFilter> filters = new ScanFilterUtils().createScanFiltersForBeaconParsers( new ArrayList<BeaconParser>(beaconParsers)); try { final BluetoothManager bluetoothManager = (BluetoothManager) mContext.getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE); BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter(); if (bluetoothAdapter == null) { LogManager.w(TAG, "Failed to construct a BluetoothAdapter"); } else if (!bluetoothAdapter.isEnabled()) { LogManager.w(TAG, "Failed to start background scan on Android O: BluetoothAdapter is not enabled"); } else { int result = bluetoothAdapter.getBluetoothLeScanner().startScan(filters, settings, getScanCallbackIntent()); if (result != 0) { LogManager.e(TAG, "Failed to start background scan on Android O. Code: "+result); } else { LogManager.d(TAG, "Started passive beacon scan"); } } } catch (SecurityException e) { LogManager.e(TAG, "SecurityException making Android O background scanner"); } } @RequiresApi(api = Build.VERSION_CODES.O) void stopAndroidOBackgroundScan() { try { final BluetoothManager bluetoothManager = (BluetoothManager) mContext.getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE); BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter(); if (bluetoothAdapter == null) { LogManager.w(TAG, "Failed to construct a BluetoothAdapter"); } else if (!bluetoothAdapter.isEnabled()) { LogManager.w(TAG, "BluetoothAdapter is not enabled"); } else { bluetoothAdapter.getBluetoothLeScanner().stopScan(getScanCallbackIntent()); } } catch (SecurityException e) { LogManager.e(TAG, "SecurityException stopping Android O background scanner"); } } // Low power scan results in the background will be delivered via Intent PendingIntent getScanCallbackIntent() { Intent intent = new Intent(mContext, StartupBroadcastReceiver.class); intent.putExtra("o-scan", true); return PendingIntent.getBroadcast(mContext,0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } private final CycledLeScanCallback mCycledLeScanCallback = new CycledLeScanCallback() { @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override @MainThread public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) { processScanResult(device, rssi, scanRecord); } @Override @MainThread @SuppressLint("WrongThread") public void onCycleEnd() { mDistinctPacketDetector.clearDetections(); mMonitoringStatus.updateNewlyOutside(); processRangeData(); // If we want to use simulated scanning data, do it here. This is used for testing in an emulator if (mSimulatedScanData != null) { // if simulatedScanData is provided, it will be seen every scan cycle. *in addition* to anything actually seen in the air // it will not be used if we are not in debug mode LogManager.w(TAG, "Simulated scan data is deprecated and will be removed in a future release. Please use the new BeaconSimulator interface instead."); if (0 != (mContext.getApplicationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE)) { for (Beacon beacon : mSimulatedScanData) { // This is an expensive call and we do not want to block the main thread. // But here we are in debug/test mode so we allow it on the main thread. //noinspection WrongThread processBeaconFromScan(beacon); } } else { LogManager.w(TAG, "Simulated scan data provided, but ignored because we are not running in debug mode. Please remove simulated scan data for production."); } } if (BeaconManager.getBeaconSimulator() != null) { // if simulatedScanData is provided, it will be seen every scan cycle. *in addition* to anything actually seen in the air // it will not be used if we are not in debug mode if (BeaconManager.getBeaconSimulator().getBeacons() != null) { if (0 != (mContext.getApplicationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE)) { for (Beacon beacon : BeaconManager.getBeaconSimulator().getBeacons()) { // This is an expensive call and we do not want to block the main thread. // But here we are in debug/test mode so we allow it on the main thread. //noinspection WrongThread processBeaconFromScan(beacon); } } else { LogManager.w(TAG, "Beacon simulations provided, but ignored because we are not running in debug mode. Please remove beacon simulations for production."); } } else { LogManager.w(TAG, "getBeacons is returning null. No simulated beacons to report."); } } } }; @RestrictTo(Scope.TESTS) CycledLeScanCallback getCycledLeScanCallback() { return mCycledLeScanCallback; } private void processRangeData() { synchronized (mRangedRegionState) { for (Region region : mRangedRegionState.keySet()) { RangeState rangeState = mRangedRegionState.get(region); LogManager.d(TAG, "Calling ranging callback"); rangeState.getCallback().call(mContext, "rangingData", new RangingData(rangeState.finalizeBeacons(), region).toBundle()); } } } /** * Helper for processing BLE beacons. This has been extracted from {@link ScanHelper.ScanProcessor} to * support simulated scan data for test and debug environments. * <p> * Processing beacons is a frequent and expensive operation. It should not be run on the main * thread to avoid UI contention. */ @WorkerThread private void processBeaconFromScan(@NonNull Beacon beacon) { if (Stats.getInstance().isEnabled()) { Stats.getInstance().log(beacon); } if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, "beacon detected : %s", beacon.toString()); } beacon = mExtraDataBeaconTracker.track(beacon); // If this is a Gatt beacon that should be ignored, it will be set to null as a result of // the above if (beacon == null) { if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, "not processing detections for GATT extra data beacon"); } } else { mMonitoringStatus.updateNewlyInsideInRegionsContaining(beacon); List<Region> matchedRegions; Iterator<Region> matchedRegionIterator; LogManager.d(TAG, "looking for ranging region matches for this beacon"); synchronized (mRangedRegionState) { matchedRegions = matchingRegions(beacon, mRangedRegionState.keySet()); matchedRegionIterator = matchedRegions.iterator(); while (matchedRegionIterator.hasNext()) { Region region = matchedRegionIterator.next(); LogManager.d(TAG, "matches ranging region: %s", region); RangeState rangeState = mRangedRegionState.get(region); if (rangeState != null) { rangeState.addBeacon(beacon); } } } } } /** * <strong>This class is not thread safe.</strong> */ private class ScanData { ScanData(@NonNull BluetoothDevice device, int rssi, @NonNull byte[] scanRecord) { this.device = device; this.rssi = rssi; this.scanRecord = scanRecord; } final int rssi; @NonNull BluetoothDevice device; @NonNull byte[] scanRecord; } private class ScanProcessor extends AsyncTask<ScanHelper.ScanData, Void, Void> { final DetectionTracker mDetectionTracker = DetectionTracker.getInstance(); private final NonBeaconLeScanCallback mNonBeaconLeScanCallback; ScanProcessor(NonBeaconLeScanCallback nonBeaconLeScanCallback) { mNonBeaconLeScanCallback = nonBeaconLeScanCallback; } @WorkerThread @Override protected Void doInBackground(ScanHelper.ScanData... params) { ScanHelper.ScanData scanData = params[0]; Beacon beacon = null; for (BeaconParser parser : ScanHelper.this.mBeaconParsers) { beacon = parser.fromScanData(scanData.scanRecord, scanData.rssi, scanData.device); if (beacon != null) { break; } } if (beacon != null) { if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, "Beacon packet detected for: "+beacon+" with rssi "+beacon.getRssi()); } mDetectionTracker.recordDetection(); if (mCycledScanner != null && !mCycledScanner.getDistinctPacketsDetectedPerScan()) { if (!mDistinctPacketDetector.isPacketDistinct(scanData.device.getAddress(), scanData.scanRecord)) { LogManager.i(TAG, "Non-distinct packets detected in a single scan. Restarting scans unecessary."); mCycledScanner.setDistinctPacketsDetectedPerScan(true); } } processBeaconFromScan(beacon); } else { if (mNonBeaconLeScanCallback != null) { mNonBeaconLeScanCallback.onNonBeaconLeScan(scanData.device, scanData.rssi, scanData.scanRecord); } } return null; } @Override protected void onPostExecute(Void result) { } @Override protected void onPreExecute() { } @Override protected void onProgressUpdate(Void... values) { } } private List<Region> matchingRegions(Beacon beacon, Collection<Region> regions) { List<Region> matched = new ArrayList<>(); for (Region region : regions) { if (region.matchesBeacon(beacon)) { matched.add(region); } else { LogManager.d(TAG, "This region (%s) does not match beacon: %s", region, beacon); } } return matched; } }
package org.oakgp.examples.gridwar; import static org.oakgp.examples.gridwar.GridWar.GRID_WIDTH; import org.oakgp.node.Node; /** Represents the current state of a player in a GridWar game. */ class Player { private final Node logic; private int x; private int y; private int previousMove; Player(int x, int y, int previousMove, Node logic) { this.x = x; this.y = y; this.previousMove = previousMove; this.logic = logic; } void updateState(int nextMove) { previousMove = nextMove; switch (nextMove) { case 0: up(); break; case 1: right(); break; case 2: down(); break; case 3: left(); break; default: throw new IllegalArgumentException("Invalid move: " + nextMove); } } private void up() { if (y > 0) { y } } private void down() { if (y < GRID_WIDTH - 1) { y++; } } private void left() { if (x > 0) { x } } private void right() { if (x < GRID_WIDTH - 1) { x++; } } int getPreviousMove() { return previousMove; } void setPreviousMove(int previousMove) { this.previousMove = previousMove; } Node getLogic() { return logic; } int getX() { return x; } int getY() { return y; } }
package ru.stqa.ol.sel3.litecart; import com.google.common.collect.Ordering; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.Select; import org.testng.annotations.Test; import java.io.File; import java.util.List; import java.util.Random; import java.util.Set; import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated; import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; public class Litecart extends TestBase { @Test adminLogin(); wd.get("http://localhost/litecart/admin/?app=countries&doc=countries"); wd.findElement(By.cssSelector("tr.row td a")).click(); String originalWindow = wd.getWindowHandle(); Set<String> existingWindows = wd.getWindowHandles(); wd.findElement(By.cssSelector("form[metod='post'] a[target='_blank']")).click(); //String newWindow = wait.until(anyWindowOtherThan(existingWindows)); //wd.switchTo().window(newWindow); wd.close(); wd.switchTo().window(originalWindow); try { Thread.sleep(2000); } catch (Exception e) { throw new RuntimeException(e); } } @Test for (int i =1 ; i<=3; i++) { wd.get("http://localhost/litecart/"); wd.findElement(By.cssSelector("ul.products a")).click(); wait.until(presenceOfElementLocated(By.xpath("//h1[contains(text(),'Duck')]"))); if (isElementPresent(By.cssSelector("select"))) { Select size = new Select(wd.findElement(By.cssSelector("select[name='options[Size]']"))); size.selectByValue("Small"); }; wd.findElement(By.cssSelector("[name='add_cart_product']")).click(); //try { Thread.sleep(2000); } catch (Exception e) { throw new RuntimeException(e); } wait.until (presenceOfElementLocated(By.xpath(String.format("//span[.='%s']", i)))) ; assertTrue ( Integer.parseInt (wd.findElement(By.cssSelector("span.quantity")).getAttribute("textContent")) == i) ; } wd.findElement(By.cssSelector("div#cart a")).click(); wait.until(presenceOfElementLocated(By.cssSelector("span.phone"))); for (int i=0; i<=3; i++) { wd.findElement(By.cssSelector("button[name='remove_cart_item']")).click(); wait.until(presenceOfElementLocated(By.cssSelector("div#order_confirmation-wrapper"))); if (! isElementPresent(By.cssSelector("button[name='remove_cart_item']"))) { break; } } } @Test adminLogin(); Random rnd = new Random(); wd.get("http://localhost/litecart/"); wd.findElement(By.cssSelector("div#box-account-login a")).click(); wd.findElement(By.cssSelector("input[name='firstname']")).sendKeys(generateString(rnd, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 5 )); wd.findElement(By.cssSelector("input[name='lastname']")).sendKeys(generateString(rnd, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 10 )); wd.findElement(By.cssSelector("input[name='address1']")).sendKeys(generateString(rnd, "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789", 30 )); wd.findElement(By.cssSelector("input[name='postcode'")).sendKeys(generateString(rnd, "123456789", 5 )); wd.findElement(By.cssSelector("input[name='city']")).sendKeys(generateString(rnd, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 11 )); wd.findElement(By.name("country_code")).findElement(By.cssSelector("[value='US']")).click(); String email= generateString(rnd, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 6) + "@" + generateString(rnd, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4) + "com"; wd.findElement(By.cssSelector("input[name='email']")).sendKeys(email); String placeholder= wd.findElement(By.cssSelector("input[name='phone']")).getAttribute("placeholder"); wd.findElement(By.cssSelector("input[name='phone']")).sendKeys(placeholder + generateString(rnd, "0123456789", 11 )); String pwd= generateString(rnd, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcd0123456789! wd.findElement(By.cssSelector("input[name='password']")).sendKeys(pwd); wd.findElement(By.cssSelector("input[name='confirmed_password']")).sendKeys(pwd); wd.findElement(By.cssSelector("button[name='create_account']")).click(); if (isElementPresent(By.xpath("//a[.='Logout']")) ) { wd.findElement(By.xpath("//a[.='Logout']")).click(); wd.findElement(By.cssSelector("input[name='email']")).sendKeys(email); wd.findElement(By.cssSelector("input[name='password']")).sendKeys(pwd); wd.findElement(By.cssSelector("button[name='login']")).click(); //try { Thread.sleep(2000); } catch (Exception e) { throw new RuntimeException(e); } assertFalse(isElementPresent(By.xpath("//div[.=' Wrong password or the account is disabled, or does not exist']"))); wd.findElement(By.xpath("//a[.='Logout']")).click(); } } @Test public void zadanie10() { wd.get("http://localhost/litecart/"); WebElement duck= wd.findElement(By.cssSelector("div#box-campaigns div.name")); WebElement duckRegular = wd.findElement(By.cssSelector("div#box-campaigns s.regular-price")); WebElement duckCampaign = wd.findElement(By.cssSelector("div String duckName = duck.getAttribute("textContent"); //dlq parametra getAttribute smotri tab Properties v Chrome! String duckRegularPrice = duckRegular.getAttribute("textContent"); String duckCampaignPrice = duckCampaign.getAttribute("textContent"); assertTrue(duckRegular.getCssValue("color").contains("119, 119, 119")); assertEquals( duckRegular.getCssValue("text-decoration"),"line-through"); assertTrue( duckCampaign.getCssValue("color").contains("204, 0, 0")); assertTrue(fontSize(duckRegular.getCssValue("font-size")) < fontSize(duckCampaign.getCssValue("font-size"))); System.out.println(fontSize(duckRegular.getCssValue("font-size")) +" " + fontSize(duckCampaign.getCssValue("font-size"))); wd.findElement(By.cssSelector("div#box-campaigns a.link")).click(); try { Thread.sleep(1000); } catch (Exception e) { throw new RuntimeException(e); } WebElement duckRegularDuckPage = wd.findElement(By.cssSelector("s.regular-price")); WebElement duckCampaignDuckPage = wd.findElement(By.cssSelector("strong.campaign-price")); assertEquals(wd.findElement(By.cssSelector("h1.title")).getAttribute("textContent"), duckName); assertEquals(duckRegularDuckPage.getAttribute("textContent"), duckRegularPrice); assertEquals(duckCampaignDuckPage.getAttribute("textContent"), duckCampaignPrice); assertTrue( wd.findElement(By.cssSelector("body")).getCssValue("color").contains("102, 102, 102")); assertEquals( duckRegularDuckPage.getCssValue("text-decoration"),"line-through"); assertTrue( duckCampaignDuckPage.getCssValue("color").contains("204, 0, 0")) ; assertTrue(fontSize(duckRegularDuckPage.getCssValue("font-size")) < fontSize(duckCampaignDuckPage.getCssValue("font-size"))); System.out.println(fontSize(duckRegularDuckPage.getCssValue("font-size")) +" " + fontSize(duckCampaignDuckPage.getCssValue("font-size"))); } @Test public void zadanie9() { adminLogin(); wd.get("http://localhost/litecart/admin/?app=countries&doc=countries"); List<WebElement> rows = wd.findElements(By.cssSelector("tr[class='row']")); List<String> countries = null; for (WebElement row : rows) { String country = row.findElement(By.cssSelector("tr[class='row']")).getText(); countries.add(country); } boolean sorted = Ordering.natural().isOrdered(countries); } @Test(enabled = true) public void zadanie8() { wd.get("http://localhost/litecart"); List<WebElement> ducks = wd.findElements(By.xpath("//div[@class='image-wrapper']")); for (WebElement duck : ducks) { List<WebElement> duck1 = duck.findElements(By.cssSelector("div.sticker")); System.out.println(duck.getTagName() + duck.getText() + "\n"); //esli iwem vse "sale" to: $$("div .sale") ili "div.sticker.sale" assertEquals(duck1.size(), 1); } } @Test(enabled = true) public void zadanie7() { adminLogin(); List<WebElement> rows = wd.findElements(By.cssSelector("li#app-")); int i = 0; while (rows.size() != i) { rows.get(i).findElement(By.cssSelector("a")).click(); assertTrue(isElementPresent(By.cssSelector("h1"))); i++; if (isElementPresent(By.cssSelector("li#app-[class='selected'] ul"))) { List<WebElement> rowsSelected = wd.findElements(By.cssSelector("li#app-[class='selected'] ul li")); int j = 0; while (rowsSelected.size() != j) { rowsSelected.get(j).findElement(By.cssSelector("a")).click(); assertTrue(isElementPresent(By.cssSelector("h1"))); rowsSelected = wd.findElements(By.cssSelector("li#app-[class='selected'] ul li")); j++; } } rows = wd.findElements(By.cssSelector("li#app-")); } } @Test(enabled = false) public void google() { wd.get("http: wd.findElement(By.id("gs_ok0")).click(); //otkrivaem klaviaturu for (int i = 1; i < 5; i++) { wd.findElement(By.id("K32")).click(); // probel } WebElement q = wd.findElement(By.name("q")); //ili wd.findElement(By.name("q")).sendKeys("webdriver"); // wd.navigate().refresh(); // esli obnovim stranicu to polu4im "stale exception" (stale element reference: element is not attached to the page document) takogo elementa net! q.sendKeys("webdriver"); //Assert.assertFalse(areElementsPresent(By.name("XXX"))); //Assert.assertFalse(areElementsPresent(By.xpath("//div[")));//l4_m8 net parnoi skobki. Togda vibrasit'sq isklu4enie //Assert.assertFalse(isElementPresent(By.xpath("//div[")));//l4_m8 net parnoi skobki. Togda ne vibrasit'sq isklu4enie t.k. est' ego perehvat v metode. 4tobi test padal nado dobavit' catch InvalidSelectorException wd.findElement(By.name("btnG")).click(); wait.until(titleIs("webdriver - Sök på Google")); Assert.assertTrue(isElementPresent(By.cssSelector(".rc"))); //l5_m9 Nawelsq element klassa rc. Na stranice mnogo takih blokov, no mi iwem odin } }
package org.caleydo.view.domino.internal; import gleem.linalg.Vec2f; import java.awt.geom.Rectangle2D; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.caleydo.core.data.selection.SelectionType; import org.caleydo.core.event.EventListenerManager.DeepScan; import org.caleydo.core.event.EventPublisher; import org.caleydo.core.util.base.ICallback; import org.caleydo.core.util.color.Color; import org.caleydo.core.view.opengl.canvas.IGLKeyListener; import org.caleydo.core.view.opengl.canvas.IGLMouseListener.IMouseEvent; import org.caleydo.core.view.opengl.layout2.GLElement; import org.caleydo.core.view.opengl.layout2.GLElementContainer; import org.caleydo.core.view.opengl.layout2.GLGraphics; import org.caleydo.core.view.opengl.layout2.IGLElementContext; import org.caleydo.core.view.opengl.layout2.basic.ScrollingDecorator; import org.caleydo.core.view.opengl.layout2.dnd.EDnDType; import org.caleydo.core.view.opengl.layout2.dnd.IDnDItem; import org.caleydo.core.view.opengl.layout2.dnd.IDragGLSource.IDragEvent; import org.caleydo.core.view.opengl.layout2.dnd.IDragInfo; import org.caleydo.core.view.opengl.layout2.dnd.IDropGLTarget; import org.caleydo.core.view.opengl.layout2.geom.Rect; import org.caleydo.core.view.opengl.layout2.layout.GLLayouts; import org.caleydo.core.view.opengl.layout2.layout.IGLLayout2; import org.caleydo.core.view.opengl.layout2.layout.IGLLayoutElement; import org.caleydo.core.view.opengl.picking.IPickingListener; import org.caleydo.core.view.opengl.picking.Pick; import org.caleydo.core.view.opengl.picking.PickingMode; import org.caleydo.view.domino.api.model.EDirection; import org.caleydo.view.domino.internal.dnd.ADragInfo; import org.caleydo.view.domino.internal.dnd.BlockDragInfo; import org.caleydo.view.domino.internal.dnd.DragElement; import org.caleydo.view.domino.internal.dnd.MultiNodeGroupDragInfo; import org.caleydo.view.domino.internal.dnd.NodeDragInfo; import org.caleydo.view.domino.internal.dnd.NodeGroupDragInfo; import org.caleydo.view.domino.internal.dnd.TablePerspectiveRemoveDragCreator; import org.caleydo.view.domino.internal.event.HideNodeEvent; import org.caleydo.view.domino.internal.toolbar.DynamicToolBar; import org.caleydo.view.domino.internal.toolbar.LeftToolBar; import org.caleydo.view.domino.internal.toolbar.ToolBar; import org.caleydo.view.domino.internal.undo.AddLazyBlockCmd; import org.caleydo.view.domino.internal.undo.AddLazyMultiBlockCmd; import org.caleydo.view.domino.internal.undo.CmdComposite; import org.caleydo.view.domino.internal.undo.MoveBlockCmd; import org.caleydo.view.domino.internal.undo.RemoveNodeCmd; import org.caleydo.view.domino.internal.undo.RemoveNodeGroupCmd; import org.caleydo.view.domino.internal.undo.ZoomCmd; import com.google.common.collect.ImmutableList; /** * @author Samuel Gratzl * */ public class Domino extends GLElementContainer implements IDropGLTarget, IPickingListener, IGLLayout2, IGLKeyListener { private GLElementContainer placeholders; private final Bands bands; private final Blocks blocks; private final ToolBar toolBar; private final LeftToolBar leftToolBar; private final DominoCanvas content; private SelectLayer select; private DragElement currentlyDraggedVis; private boolean showDebugInfos = true; private boolean showMiniMap = false; private boolean showBlockLabels = false; private EToolState tool = EToolState.MOVE; private final UndoStack undo = new UndoStack(this); @DeepScan private final NodeSelections selections = new NodeSelections(); public Domino() { setLayout(this); this.toolBar = new ToolBar(undo, selections); this.toolBar.setSize(-1, 24); this.add(toolBar); this.leftToolBar = new LeftToolBar(undo); this.leftToolBar.setSize(24, -1); this.add(leftToolBar); this.content = new DominoCanvas(GLLayouts.LAYERS); content.setVisibility(EVisibility.PICKABLE); content.onPick(new IPickingListener() { @Override public void pick(Pick pick) { if (pick.getPickingMode() == PickingMode.MOUSE_OUT) removePlaceholder(); } }); ScrollingDecorator scroll = ScrollingDecorator.wrap(content, 10); this.add(scroll); // fakeData(); this.blocks = new Blocks(selections); scroll.setMinSizeProvider(blocks); scroll.setAutoResetViewport(false); blocks.setzDelta(0.1f); content.add(blocks); this.bands = new Bands(selections); this.bands.setVisibility(EVisibility.PICKABLE); this.bands.setzDelta(0.01f); this.bands.onPick(this); content.add(this.bands); selections.onNodeGroupSelectionChanges(new ICallback<SelectionType>() { @Override public void on(SelectionType data) { NodeDataItem.update(selections.getSelection(SelectionType.MOUSE_OVER), selections.getSelection(SelectionType.SELECTION)); } }); DynamicToolBar dynToolBar = new DynamicToolBar(undo, selections); content.add(dynToolBar); } @Override public boolean doLayout(List<? extends IGLLayoutElement> children, float w, float h, IGLLayoutElement parent, int deltaTimeMs) { children.get(0).setBounds(0, 0, w, 24); children.get(1).setBounds(0, 24, 24, h - 24); for (IGLLayoutElement elem : children.subList(2, children.size())) elem.setBounds(24, 24, w - 24, h - 24); return false; } @Override protected void init(IGLElementContext context) { context.getMouseLayer().addRemoteDragInfoUICreator(new TablePerspectiveRemoveDragCreator(this)); super.init(context); } /** * @return the toolBar, see {@link #toolBar} */ public ToolBar getToolBar() { return toolBar; } /** * @return the bands, see {@link #bands} */ public Bands getBands() { return bands; } /** * @return the showDebugInfos, see {@link #showDebugInfos} */ public boolean isShowDebugInfos() { return showDebugInfos; } /** * @return */ public boolean isShowBlockLabels() { return showBlockLabels; } /** * @param showBlockLabels * setter, see {@link showBlockLabels} */ public void setShowBlockLabels(boolean showBlockLabels) { this.showBlockLabels = showBlockLabels; } /** * @param showDebugInfos * setter, see {@link showDebugInfos} */ public void setShowDebugInfos(boolean showDebugInfos) { this.showDebugInfos = showDebugInfos; } @Override protected boolean hasPickAbles() { return true; } @Override public void pick(Pick pick) { IMouseEvent event = ((IMouseEvent) pick); switch (pick.getPickingMode()) { case MOUSE_OVER: context.getMouseLayer().addDropTarget(this); break; case MOUSE_OUT: context.getMouseLayer().removeDropTarget(this); break; case MOUSE_WHEEL: if (event.getWheelRotation() != 0) undo.push(new ZoomCmd(ScaleLogic.shiftLogic(event, new Vec2f(100, 100)))); break; case DRAG_DETECTED: pick.setDoDragging(true); this.select = new SelectLayer(bands.toRelative(pick.getPickedPoint())); content.add(this.select); break; case DRAGGED: if (pick.isDoDragging() && this.select != null) { this.select.dragTo(pick.getDx(), pick.getDy(), event.isCtrlDown()); } break; case MOUSE_RELEASED: if (pick.isDoDragging() && this.select != null) { this.select.dragTo(pick.getDx(), pick.getDy(), event.isCtrlDown()); content.remove(this.select); this.select = null; } break; default: break; } } public void zoom(Vec2f shift) { blocks.zoom(shift); bands.relayout(); } @Override public boolean canSWTDrop(IDnDItem item) { return item.getInfo() instanceof ADragInfo || Nodes.canExtract(item); } @Override public void onDrop(IDnDItem item) { IDragInfo info = item.getInfo(); final Vec2f pos = toDropPosition(item); if (info instanceof NodeGroupDragInfo) { NodeGroupDragInfo g = (NodeGroupDragInfo) info; dropNode(pos, g.getGroup().toNode(), item.getType() == EDnDType.MOVE ? g.getGroup() : null); } else if (info instanceof NodeDragInfo) { NodeDragInfo g = (NodeDragInfo) info; dropNode(pos, item.getType() == EDnDType.COPY ? new Node(g.getNode()) : g.getNode(), null); } else if (info instanceof MultiNodeGroupDragInfo) { MultiNodeGroupDragInfo g = (MultiNodeGroupDragInfo) info; Node start = g.getPrimary().toNode(); undo.push(new AddLazyMultiBlockCmd(start, pos, g.getPrimary(), g.getGroups())); } else if (info instanceof BlockDragInfo) { final Block start = ((BlockDragInfo) info).getStart(); undo.push(new MoveBlockCmd(((BlockDragInfo) info).getBlocks(), pos.minus(start.getLocation()))); } else { Node node = Nodes.extract(item); dropNode(pos, node, null); } } private Block dropNode(Vec2f pos, Node node, NodeGroup groupToRemove) { Block block = node.getBlock(); if (block != null && block.nodeCount() == 1) { Vec2f shift = pos.minus(block.getLocation()); undo.push(new MoveBlockCmd(Collections.singleton(block), shift)); return block; } final AddLazyBlockCmd cmd = new AddLazyBlockCmd(node, pos); if (block != null) undo.push(CmdComposite.chain(new RemoveNodeCmd(node), cmd)); else if (groupToRemove != null) undo.push(CmdComposite.chain(cmd, new RemoveNodeGroupCmd(groupToRemove))); else { undo.push(cmd); } removePlaceholder(); bands.relayout(); content.getParent().relayout(); return null; // FIXME } /** * @return the undo, see {@link #undo} */ public UndoStack getUndo() { return undo; } public void moveBlocks(Set<Block> blocks, Vec2f shift) { for (Block b : blocks) { Vec2f loc = b.getLocation(); b.setLocation(loc.x() + shift.x(), loc.y() + shift.y()); } bands.relayout(); content.getParent().relayout(); } private Vec2f toDropPosition(IDnDItem item) { Vec2f pos = blocks.toRelative(item.getMousePos()); if (currentlyDraggedVis != null) pos.add(currentlyDraggedVis.getLocation()); return pos; } public boolean containsNode(Node node) { return node.getBlock() != null; } /** * @param node */ public void removeNode(Node node) { Block block = node.getBlock(); if (block != null && block.removeNode(node)) { blocks.remove(block); bands.relayout(); } cleanup(node); } public void cleanup(Node node) { selections.cleanup(node); } public void addPlaceholdersFor(Node node) { if (placeholders != null) return; if (tool == EToolState.BANDS) return; placeholders = new GLElementContainer(new ToRelativeLayout()); content.add(placeholders); final List<GLElement> l = placeholders.asList(); for (Block block : blocks.getBlocks()) { l.addAll(block.addPlaceholdersFor(node)); } if (l.isEmpty()) { Vec2f size = getSize(); Rect r = new Rect(); r.x(50); r.y(size.y() * 0.25f); r.width(Block.DETACHED_OFFSET); r.height(size.y() * 0.5f); l.add(new FreePlaceholder(EDirection.EAST, r)); } } @Override public void onItemChanged(IDnDItem item) { if (placeholders == null) { if (item.getInfo() instanceof NodeDragInfo) addPlaceholdersFor(((NodeDragInfo) item.getInfo()).getNode()); else if (item.getInfo() instanceof NodeGroupDragInfo) addPlaceholdersFor(((NodeGroupDragInfo) item.getInfo()).getNode()); else { Node node = Nodes.extract(item); if (node != null) addPlaceholdersFor(node); } } // update drag to grid if (currentlyDraggedVis != null) { blocks.snapDraggedVis(currentlyDraggedVis); } } @Override public EDnDType defaultSWTDnDType(IDnDItem item) { if (item.getInfo() instanceof NodeGroupDragInfo) return EDnDType.COPY; return EDnDType.MOVE; } /** * @param neighbor * @param dir * @param node * @param transpose * @param detached */ public void placeAt(Node neighbor, EDirection dir, Node node) { removeNode(node); Block block = neighbor.getBlock(); block.addNode(neighbor, dir, node); } private void removePlaceholder() { content.remove(placeholders); placeholders = null; } /** * @return the selections, see {@link #selections} */ public NodeSelections getSelections() { return selections; } @Override protected void renderImpl(GLGraphics g, float w, float h) { super.renderImpl(g, w, h); if (showMiniMap) { g.incZ(); g.save().move(w * 0.8f - 10, h * 0.8f - 10); renderMiniMap(g, w * 0.2f, h * 0.2f); g.restore(); g.decZ(); } } private void renderMiniMap(GLGraphics g, float w, float h) { g.color(Color.WHITE).fillRect(0, 0, w, h); g.color(Color.BLACK).drawRect(0, 0, w, h); Vec2f size = getSize(); computeMiniMapFactor(g, size, w, h); blocks.renderMiniMap(g); bands.renderMiniMap(g); final ScrollingDecorator s = (ScrollingDecorator) content.getParent(); if (s != null) { Rect clip = s.getClipingArea(); g.color(Color.BLACK).drawRect(clip.x(), clip.y(), clip.width(), clip.height()); } } private void computeMiniMapFactor(GLGraphics g, Vec2f size, float w, float h) { float wi = w / size.x(); float hi = h / size.y(); if (wi < hi) { g.move(0, (h - size.y() * wi) * 0.5f).gl.glScalef(wi, wi, 1); } else { g.move((w - size.x() * hi) * 0.5f, 0).gl.glScalef(hi, hi, 1); } } public void updateBands() { bands.relayout(); } /** * @param rect * @param clear */ public void selectByBounds(Rect rect, boolean clear) { final Rectangle2D r = rect.asRectangle2D(); switch (this.tool) { case MOVE: selectNodesByBounds(clear, r); break; case SELECT: selectBandsByBounds(clear, r); break; case BANDS: selectNodesByBounds(clear, r); break; } } /** * @param clear * @param r */ private void selectBandsByBounds(boolean clear, Rectangle2D r) { bands.selectBandsByBounds(clear, r); } private void selectNodesByBounds(boolean clear, final Rectangle2D r) { if (clear) { if (tool == EToolState.BANDS) selections.clear(SelectionType.SELECTION, (Block) null); else selections.clear(SelectionType.SELECTION, (NodeGroup) null); } for (Block block : blocks.getBlocks()) { if (block.getRectangleBounds().intersects(r)) { block.selectByBounds(r, tool); } } } public void toggleShowMiniMap() { this.showMiniMap = !showMiniMap; repaint(); } /** * @param dragElement */ public void setCurrentlyDragged(DragElement dragElement) { currentlyDraggedVis = dragElement; } /** * @return the currentlyDraggedVis, see {@link #currentlyDraggedVis} */ public DragElement getCurrentlyDraggedVis() { return currentlyDraggedVis; } /** * @return */ public List<Block> getBlocks() { return ImmutableList.copyOf(blocks.getBlocks()); } /** * @param tool * setter, see {@link tool} */ public void setTool(EToolState tool) { if (this.tool == tool) return; this.tool = tool; blocks.setTool(tool); bands.relayout(); if (tool == EToolState.BANDS) { selections.clear(SelectionType.MOUSE_OVER, (NodeGroup) null); selections.clear(SelectionType.SELECTION, (NodeGroup) null); } else { selections.clear(SelectionType.MOUSE_OVER, (Block) null); selections.clear(SelectionType.SELECTION, (Block) null); } } /** * @return the tool, see {@link #tool} */ public EToolState getTool() { return tool; } /** * @param block */ public void removeBlock(Block block) { blocks.remove(block); selections.cleanup(block); updateBands(); } public void addBlock(Block block) { block.setTool(tool); blocks.addBlock(block); updateBands(); } public IDragInfo startSWTDrag(IDragEvent event, Block block) { Set<Block> selected = selections.getBlockSelection(SelectionType.SELECTION); selected = new HashSet<>(selected); selected.add(block); for (Block b : selected) EventPublisher.trigger(new HideNodeEvent().to(b)); return new BlockDragInfo(event.getMousePos(), selected, block); } /** * @param event * @param nodeGroup */ public IDragInfo startSWTDrag(IDragEvent event, NodeGroup nodeGroup) { Set<NodeGroup> selected = selections.getSelection(SelectionType.SELECTION); selected = new HashSet<>(selected); selected.add(nodeGroup); Node single = NodeSelections.getSingleNode(selected); if (single != null) { EventPublisher.trigger(new HideNodeEvent().to(single)); return new NodeDragInfo(event.getMousePos(), single); } Set<Block> blocks = NodeSelections.getFullBlocks(selected); if (!blocks.isEmpty()) { for (Block block : blocks) EventPublisher.trigger(new HideNodeEvent().to(block)); return new BlockDragInfo(event.getMousePos(), blocks, nodeGroup.getNode().getBlock()); } Set<NodeGroup> s = NodeSelections.compress(nodeGroup, selected); if (s.size() <= 1) return new NodeGroupDragInfo(event.getMousePos(), nodeGroup); return new MultiNodeGroupDragInfo(event.getMousePos(), nodeGroup, s); } /** * @param leftOf */ private void moveSelection(EDirection dir, float factor) { Set<NodeGroup> selected = selections.getSelection(SelectionType.SELECTION); if (selected.isEmpty()) return; Set<Block> blocks = NodeSelections.getFullBlocks(selected); if (blocks.isEmpty()) return; Vec2f change; switch (dir) { case NORTH: change = new Vec2f(0, -20); break; case SOUTH: change = new Vec2f(0, 20); break; case WEST: change = new Vec2f(-20, 0); break; case EAST: change = new Vec2f(+20, 0); break; default: throw new IllegalStateException(); } change.scale(factor); undo.push(new MoveBlockCmd(blocks, change)); } @Override public void keyPressed(IKeyEvent e) { float f = e.isAltDown() ? 2 : e.isControlDown() ? 0.5f : 1.f; if (e.isKey(ESpecialKey.LEFT)) moveSelection(EDirection.WEST, f); else if (e.isKey(ESpecialKey.RIGHT)) moveSelection(EDirection.EAST, f); else if (e.isKey(ESpecialKey.UP)) moveSelection(EDirection.NORTH, f); else if (e.isKey(ESpecialKey.DOWN)) moveSelection(EDirection.SOUTH, f); else if (e.isControlDown() && (e.isKey('z') || e.isKey('Z'))) undo.undo(); else if (e.isControlDown() && (e.isKey('y') || e.isKey('Y'))) undo.redo(); else if (e.isControlDown() && (e.isKey('a') || e.isKey('A'))) selectAll(); } private void selectAll() { for (Block b : blocks.getBlocks()) b.selectAll(); } @Override public void keyReleased(IKeyEvent e) { } /** * @param neighbor */ public void removePreview(Node node) { removeNode(node); removePlaceholder(); bands.relayout(); } /** * @param dir * @param preview */ public void persistPreview(Node preview) { preview.setPreviewing(false); removePlaceholder(); bands.relayout(); } public void addPreview(Node neighbor, EDirection dir, Node preview) { preview.setPreviewing(true); placeAt(neighbor, dir, preview); } }
package seedu.jimi.logic; import com.google.common.eventbus.Subscribe; import seedu.jimi.commons.core.EventsCenter; import seedu.jimi.commons.events.model.AddressBookChangedEvent; import seedu.jimi.commons.events.ui.JumpToListRequestEvent; import seedu.jimi.commons.events.ui.ShowHelpRequestEvent; import seedu.jimi.logic.Logic; import seedu.jimi.logic.LogicManager; import seedu.jimi.logic.commands.*; import seedu.jimi.model.TaskBook; import seedu.jimi.model.Model; import seedu.jimi.model.ModelManager; import seedu.jimi.model.ReadOnlyTaskBook; import seedu.jimi.model.tag.Tag; import seedu.jimi.model.tag.UniqueTagList; import seedu.jimi.model.task.*; import seedu.jimi.storage.StorageManager; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static seedu.jimi.commons.core.Messages.*; public class LogicManagerTest { @Rule public TemporaryFolder saveFolder = new TemporaryFolder(); private Model model; private Logic logic; //These are for checking the correctness of the events raised private ReadOnlyTaskBook latestSavedTaskBook; private boolean helpShown; private int targetedJumpIndex; @Subscribe private void handleLocalModelChangedEvent(AddressBookChangedEvent abce) { latestSavedTaskBook = new TaskBook(abce.data); } @Subscribe private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) { helpShown = true; } @Subscribe private void handleJumpToListRequestEvent(JumpToListRequestEvent je) { targetedJumpIndex = je.targetIndex; } @Before public void setup() { model = new ModelManager(); String tempAddressBookFile = saveFolder.getRoot().getPath() + "TempAddressBook.xml"; String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json"; logic = new LogicManager(model, new StorageManager(tempAddressBookFile, tempPreferencesFile)); EventsCenter.getInstance().registerHandler(this); latestSavedTaskBook = new TaskBook(model.getTaskBook()); // last saved assumed to be up to date before. helpShown = false; targetedJumpIndex = -1; // non yet } @After public void teardown() { EventsCenter.clearSubscribers(); } @Test public void execute_invalid() throws Exception { String invalidCommand = " "; assertCommandBehavior(invalidCommand, String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } /** * Executes the command and confirms that the result message is correct. * Both the 'address book' and the 'last shown list' are expected to be empty. * @see #assertCommandBehavior(String, String, ReadOnlyTaskBook, List) */ private void assertCommandBehavior(String inputCommand, String expectedMessage) throws Exception { assertCommandBehavior(inputCommand, expectedMessage, new TaskBook(), Collections.emptyList()); } /** * Executes the command and confirms that the result message is correct and * also confirms that the following three parts of the LogicManager object's state are as expected:<br> * - the internal address book data are same as those in the {@code expectedAddressBook} <br> * - the backing list shown by UI matches the {@code shownList} <br> * - {@code expectedAddressBook} was saved to the storage file. <br> */ private void assertCommandBehavior(String inputCommand, String expectedMessage, ReadOnlyTaskBook expectedTaskBook, List<? extends ReadOnlyTask> expectedShownList) throws Exception { //Execute the command CommandResult result = logic.execute(inputCommand); //Confirm the ui display elements should contain the right data assertEquals(expectedMessage, result.feedbackToUser); assertEquals(expectedShownList, model.getFilteredTaskList()); //Confirm the state of data (saved and in-memory) is as expected assertEquals(expectedTaskBook, model.getTaskBook()); assertEquals(expectedTaskBook, latestSavedTaskBook); } @Test public void execute_unknownCommandWord() throws Exception { String unknownCommand = "uicfhmowqewca"; assertCommandBehavior(unknownCommand, MESSAGE_UNKNOWN_COMMAND); /* exit and clear should have the user type the full command word for it to be valid */ unknownCommand = "ex"; assertCommandBehavior(unknownCommand, MESSAGE_UNKNOWN_COMMAND); unknownCommand = "exi"; assertCommandBehavior(unknownCommand, MESSAGE_UNKNOWN_COMMAND); unknownCommand = "c"; assertCommandBehavior(unknownCommand, MESSAGE_UNKNOWN_COMMAND); unknownCommand = "cl"; assertCommandBehavior(unknownCommand, MESSAGE_UNKNOWN_COMMAND); unknownCommand = "cle"; assertCommandBehavior(unknownCommand, MESSAGE_UNKNOWN_COMMAND); unknownCommand = "clea"; assertCommandBehavior(unknownCommand, MESSAGE_UNKNOWN_COMMAND); } @Test public void execute_help() throws Exception { assertCommandBehavior("help", HelpCommand.SHOWING_HELP_MESSAGE); assertTrue(helpShown); assertCommandBehavior("h", HelpCommand.SHOWING_HELP_MESSAGE); assertTrue(helpShown); assertCommandBehavior("he", HelpCommand.SHOWING_HELP_MESSAGE); assertTrue(helpShown); assertCommandBehavior("hel", HelpCommand.SHOWING_HELP_MESSAGE); assertTrue(helpShown); } @Test public void execute_exit() throws Exception { assertCommandBehavior("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT); } @Test public void execute_clear() throws Exception { TestDataHelper helper = new TestDataHelper(); model.addTask(helper.generateFloatingTask(1)); model.addTask(helper.generateFloatingTask(2)); model.addTask(helper.generateFloatingTask(3)); assertCommandBehavior("clear", ClearCommand.MESSAGE_SUCCESS, new TaskBook(), Collections.emptyList()); } @Test public void execute_add_invalidArgsFormat() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE); assertCommandBehavior( "add \"do dishes\" t/impt t/asd", expectedMessage); assertCommandBehavior( "add \"wash //plates\"", expectedMessage); assertCommandBehavior( "a \"do dishes\" t/impt t/asd", expectedMessage); assertCommandBehavior( "a \"wash //plates\"", expectedMessage); assertCommandBehavior( "ad \"do dishes\" t/impt t/asd", expectedMessage); assertCommandBehavior( "ad \"wash //plates\"", expectedMessage); } @Test public void execute_add_invalidPersonData() throws Exception { assertCommandBehavior( "add \"Valid task\" t/invalid_-[.tag", Tag.MESSAGE_TAG_CONSTRAINTS); assertCommandBehavior( "a \"Valid task\" t/invalid_-[.tag", Tag.MESSAGE_TAG_CONSTRAINTS); assertCommandBehavior( "ad \"Valid task\" t/invalid_-[.tag", Tag.MESSAGE_TAG_CONSTRAINTS); } @Test public void execute_add_successful() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); FloatingTask toBeAdded = helper.adam(); TaskBook expectedAB = new TaskBook(); expectedAB.addTask(toBeAdded); // execute command and verify result assertCommandBehavior(helper.generateAddCommand(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedAB, expectedAB.getTaskList()); toBeAdded = helper.laundry(); expectedAB.addTask(toBeAdded); assertCommandBehavior( helper.generateAddCommand_A(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedAB, expectedAB.getTaskList()); toBeAdded = helper.homework(); expectedAB.addTask(toBeAdded); assertCommandBehavior( helper.generateAddCommand_Ad(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedAB, expectedAB.getTaskList()); } @Test public void execute_addDuplicate_notAllowed() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); FloatingTask toBeAdded = helper.adam(); TaskBook expectedAB = new TaskBook(); expectedAB.addTask(toBeAdded); // setup starting state model.addTask(toBeAdded); // person already in internal address book // execute command and verify result assertCommandBehavior( helper.generateAddCommand(toBeAdded), AddCommand.MESSAGE_DUPLICATE_TASK, expectedAB, expectedAB.getTaskList()); assertCommandBehavior( helper.generateAddCommand_A(toBeAdded), AddCommand.MESSAGE_DUPLICATE_TASK, expectedAB, expectedAB.getTaskList()); assertCommandBehavior( helper.generateAddCommand_Ad(toBeAdded), AddCommand.MESSAGE_DUPLICATE_TASK, expectedAB, expectedAB.getTaskList()); } @Test public void execute_list_showsAllPersons() throws Exception { // prepare expectations TestDataHelper helper = new TestDataHelper(); TaskBook expectedAB = helper.generateTaskBook(2); List<? extends ReadOnlyTask> expectedList = expectedAB.getTaskList(); // prepare address book state helper.addToModel(model, 2); assertCommandBehavior("list", ListCommand.MESSAGE_SUCCESS, expectedAB, expectedList); assertCommandBehavior("l", ListCommand.MESSAGE_SUCCESS, expectedAB, expectedList); assertCommandBehavior("li", ListCommand.MESSAGE_SUCCESS, expectedAB, expectedList); assertCommandBehavior("lis", ListCommand.MESSAGE_SUCCESS, expectedAB, expectedList); } /** * Confirms the 'invalid argument index number behaviour' for the given command * targeting a single person in the shown list, using visible index. * @param commandWord to test assuming it targets a single person in the last shown list based on visible index. */ private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage) throws Exception { assertCommandBehavior(commandWord , expectedMessage); //index missing assertCommandBehavior(commandWord + " +1", expectedMessage); //index should be unsigned assertCommandBehavior(commandWord + " -1", expectedMessage); //index should be unsigned assertCommandBehavior(commandWord + " 0", expectedMessage); //index cannot be 0 assertCommandBehavior(commandWord + " not_a_number", expectedMessage); } /** * Confirms the 'invalid argument index number behaviour' for the given command * targeting a single person in the shown list, using visible index. * @param commandWord to test assuming it targets a single person in the last shown list based on visible index. */ private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception { String expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX; TestDataHelper helper = new TestDataHelper(); List<FloatingTask> floatingTaskList = helper.generateFloatingTaskList(2); // set AB state to 2 persons model.resetData(new TaskBook()); for (FloatingTask p : floatingTaskList) { model.addTask(p); } assertCommandBehavior(commandWord + " 3", expectedMessage, model.getTaskBook(), floatingTaskList); } @Test public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage); assertIncorrectIndexFormatBehaviorForCommand("s", expectedMessage); assertIncorrectIndexFormatBehaviorForCommand("se", expectedMessage); assertIncorrectIndexFormatBehaviorForCommand("sel", expectedMessage); assertIncorrectIndexFormatBehaviorForCommand("sele", expectedMessage); assertIncorrectIndexFormatBehaviorForCommand("selec", expectedMessage); } @Test public void execute_selectIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("select"); assertIndexNotFoundBehaviorForCommand("s"); assertIndexNotFoundBehaviorForCommand("se"); assertIndexNotFoundBehaviorForCommand("sel"); assertIndexNotFoundBehaviorForCommand("sele"); assertIndexNotFoundBehaviorForCommand("selec"); } @Test public void execute_select_jumpsToCorrectPerson() throws Exception { TestDataHelper helper = new TestDataHelper(); List<FloatingTask> threeFloatingTasks = helper.generateFloatingTaskList(3); TaskBook expectedAB = helper.generateFloatingTaskBook(threeFloatingTasks); helper.addToModel(model, threeFloatingTasks); assertCommandBehavior("select 2", String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2), expectedAB, expectedAB.getTaskList()); assertEquals(1, targetedJumpIndex); assertEquals(model.getFilteredTaskList().get(1), threeFloatingTasks.get(1)); assertCommandBehavior("s 1", String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 1), expectedAB, expectedAB.getTaskList()); assertEquals(0, targetedJumpIndex); assertEquals(model.getFilteredTaskList().get(0), threeFloatingTasks.get(0)); assertCommandBehavior("se 2", String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2), expectedAB, expectedAB.getTaskList()); assertEquals(1, targetedJumpIndex); assertEquals(model.getFilteredTaskList().get(1), threeFloatingTasks.get(1)); assertCommandBehavior("sel 1", String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 1), expectedAB, expectedAB.getTaskList()); assertEquals(0, targetedJumpIndex); assertEquals(model.getFilteredTaskList().get(0), threeFloatingTasks.get(0)); assertCommandBehavior("sele 2", String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2), expectedAB, expectedAB.getTaskList()); assertEquals(1, targetedJumpIndex); assertEquals(model.getFilteredTaskList().get(1), threeFloatingTasks.get(1)); assertCommandBehavior("selec 1", String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 1), expectedAB, expectedAB.getTaskList()); assertEquals(0, targetedJumpIndex); assertEquals(model.getFilteredTaskList().get(0), threeFloatingTasks.get(0)); } @Test public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage); assertIncorrectIndexFormatBehaviorForCommand("d", expectedMessage); assertIncorrectIndexFormatBehaviorForCommand("de", expectedMessage); assertIncorrectIndexFormatBehaviorForCommand("del", expectedMessage); assertIncorrectIndexFormatBehaviorForCommand("dele", expectedMessage); assertIncorrectIndexFormatBehaviorForCommand("delet", expectedMessage); } @Test public void execute_deleteIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("delete"); assertIndexNotFoundBehaviorForCommand("d"); assertIndexNotFoundBehaviorForCommand("de"); assertIndexNotFoundBehaviorForCommand("del"); assertIndexNotFoundBehaviorForCommand("dele"); assertIndexNotFoundBehaviorForCommand("delet"); } @Test public void execute_delete_removesCorrectPerson() throws Exception { TestDataHelper helper = new TestDataHelper(); List<FloatingTask> threeFloatingTasks = helper.generateFloatingTaskList(3); TaskBook expectedAB = helper.generateFloatingTaskBook(threeFloatingTasks); expectedAB.removeTask(threeFloatingTasks.get(1)); helper.addToModel(model, threeFloatingTasks); assertCommandBehavior("delete 2", String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, threeFloatingTasks.get(1)), expectedAB, expectedAB.getTaskList()); } @Test public void execute_find_invalidArgsFormat() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE); assertCommandBehavior("find ", expectedMessage); assertCommandBehavior("f ", expectedMessage); assertCommandBehavior("fi ", expectedMessage); assertCommandBehavior("fin ", expectedMessage); } @Test public void execute_find_onlyMatchesFullWordsInNames() throws Exception { TestDataHelper helper = new TestDataHelper(); FloatingTask pTarget1 = helper.generateFloatingTaskWithName("bla bla KEY bla"); FloatingTask pTarget2 = helper.generateFloatingTaskWithName("bla KEY bla bceofeia"); FloatingTask p1 = helper.generateFloatingTaskWithName("KE Y"); FloatingTask p2 = helper.generateFloatingTaskWithName("KEYKEYKEY sduauo"); List<FloatingTask> fourFloatingTasks = helper.generateFloatingTaskList(p1, pTarget1, p2, pTarget2); TaskBook expectedAB = helper.generateFloatingTaskBook(fourFloatingTasks); List<FloatingTask> expectedList = helper.generateFloatingTaskList(pTarget1, pTarget2); helper.addToModel(model, fourFloatingTasks); assertCommandBehavior("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); assertCommandBehavior("fi KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); assertCommandBehavior("fin KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); assertCommandBehavior("f KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } @Test public void execute_find_isNotCaseSensitive() throws Exception { TestDataHelper helper = new TestDataHelper(); FloatingTask p1 = helper.generateFloatingTaskWithName("bla bla KEY bla"); FloatingTask p2 = helper.generateFloatingTaskWithName("bla KEY bla bceofeia"); FloatingTask p3 = helper.generateFloatingTaskWithName("key key"); FloatingTask p4 = helper.generateFloatingTaskWithName("KEy sduauo"); List<FloatingTask> fourFloatingTasks = helper.generateFloatingTaskList(p3, p1, p4, p2); TaskBook expectedAB = helper.generateFloatingTaskBook(fourFloatingTasks); List<FloatingTask> expectedList = fourFloatingTasks; helper.addToModel(model, fourFloatingTasks); assertCommandBehavior("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); assertCommandBehavior("fi KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); assertCommandBehavior("fin KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); assertCommandBehavior("f KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } @Test public void execute_find_matchesIfAnyKeywordPresent() throws Exception { TestDataHelper helper = new TestDataHelper(); FloatingTask pTarget1 = helper.generateFloatingTaskWithName("bla bla KEY bla"); FloatingTask pTarget2 = helper.generateFloatingTaskWithName("bla rAnDoM bla bceofeia"); FloatingTask pTarget3 = helper.generateFloatingTaskWithName("key key"); FloatingTask p1 = helper.generateFloatingTaskWithName("sduauo"); List<FloatingTask> fourFloatingTasks = helper.generateFloatingTaskList(pTarget1, p1, pTarget2, pTarget3); TaskBook expectedAB = helper.generateFloatingTaskBook(fourFloatingTasks); List<FloatingTask> expectedList = helper.generateFloatingTaskList(pTarget1, pTarget2, pTarget3); helper.addToModel(model, fourFloatingTasks); assertCommandBehavior("find key rAnDoM", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); assertCommandBehavior("f key rAnDoM", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); assertCommandBehavior("fi key rAnDoM", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); assertCommandBehavior("fin key rAnDoM", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } /** * A utility class to generate test data. */ class TestDataHelper{ FloatingTask adam() throws Exception { Name name = new Name("Adam Brown"); Tag tag1 = new Tag("tag1"); UniqueTagList tags = new UniqueTagList(tag1); return new FloatingTask(name, tags); } FloatingTask laundry() throws Exception { Name name = new Name("laundry"); Tag tag1 = new Tag("dothem"); UniqueTagList tags = new UniqueTagList(tag1); return new FloatingTask(name, tags); } FloatingTask homework() throws Exception { Name name = new Name("homework"); Tag tag1 = new Tag("impt"); UniqueTagList tags = new UniqueTagList(tag1); return new FloatingTask(name, tags); } /** * Generates a valid person using the given seed. * Running this function with the same parameter values guarantees the returned person will have the same state. * Each unique seed will generate a unique FloatingTask object. * * @param seed used to generate the person data field values */ FloatingTask generateFloatingTask(int seed) throws Exception { return new FloatingTask( new Name("FloatingTask " + seed), new UniqueTagList(new Tag("tag" + Math.abs(seed)), new Tag("tag" + Math.abs(seed + 1))) ); } /** Generates the correct add command based on the person given */ String generateAddCommand(FloatingTask p) { StringBuffer cmd = new StringBuffer(); cmd.append("add "); cmd.append("\""); cmd.append(p.getName().toString()); cmd.append("\""); UniqueTagList tags = p.getTags(); for(Tag t: tags){ cmd.append(" t/").append(t.tagName); } return cmd.toString(); } String generateAddCommand_A(FloatingTask p) { StringBuffer cmd = new StringBuffer(); cmd.append("a "); cmd.append("\""); cmd.append(p.getName().toString()); cmd.append("\""); UniqueTagList tags = p.getTags(); for(Tag t: tags){ cmd.append(" t/").append(t.tagName); } return cmd.toString(); } String generateAddCommand_Ad(FloatingTask p) { StringBuffer cmd = new StringBuffer(); cmd.append("ad "); cmd.append("\""); cmd.append(p.getName().toString()); cmd.append("\""); UniqueTagList tags = p.getTags(); for(Tag t: tags){ cmd.append(" t/").append(t.tagName); } return cmd.toString(); } /** * Generates an TaskBook with auto-generated persons. */ TaskBook generateTaskBook(int numGenerated) throws Exception{ TaskBook taskBook = new TaskBook(); addToTaskBook(taskBook, numGenerated); return taskBook; } /** * Generates an TaskBook based on the list of Persons given. */ TaskBook generateFloatingTaskBook(List<FloatingTask> floatingTasks) throws Exception{ TaskBook taskBook = new TaskBook(); addToFloatingTaskBook(taskBook, floatingTasks); return taskBook; } /** * Adds auto-generated FloatingTask objects to the given TaskBook * @param taskBook The TaskBook to which the Persons will be added */ void addToTaskBook(TaskBook taskBook, int numGenerated) throws Exception{ addToFloatingTaskBook(taskBook, generateFloatingTaskList(numGenerated)); } /** * Adds the given list of Persons to the given TaskBook */ void addToFloatingTaskBook(TaskBook taskBook, List<FloatingTask> floatingTasksToAdd) throws Exception{ for(FloatingTask p: floatingTasksToAdd){ taskBook.addTask(p); } } /** * Adds auto-generated FloatingTask objects to the given model * @param model The model to which the Persons will be added */ void addToModel(Model model, int numGenerated) throws Exception{ addToModel(model, generateFloatingTaskList(numGenerated)); } /** * Adds the given list of Persons to the given model */ void addToModel(Model model, List<FloatingTask> floatingTasksToAdd) throws Exception{ for(FloatingTask p: floatingTasksToAdd){ model.addTask(p); } } /** * Generates a list of Persons based on the flags. */ List<FloatingTask> generateFloatingTaskList(int numGenerated) throws Exception{ List<FloatingTask> floatingTasks = new ArrayList<>(); for(int i = 1; i <= numGenerated; i++){ floatingTasks.add(generateFloatingTask(i)); } return floatingTasks; } List<FloatingTask> generateFloatingTaskList(FloatingTask... persons) { return Arrays.asList(persons); } /** * Generates a FloatingTask object with given name. Other fields will have some dummy values. */ FloatingTask generateFloatingTaskWithName(String name) throws Exception { return new FloatingTask( new Name(name), new UniqueTagList(new Tag("tag")) ); } } }
package seedu.task.logic; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.task.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.task.commons.core.Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX; import static seedu.task.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.google.common.eventbus.Subscribe; import seedu.task.commons.core.EventsCenter; import seedu.task.commons.events.model.TaskManagerChangedEvent; import seedu.task.commons.events.ui.JumpToListRequestEvent; import seedu.task.commons.events.ui.ShowHelpRequestEvent; import seedu.task.commons.util.NattyDateUtil; import seedu.task.logic.commands.AddCommand; import seedu.task.logic.commands.ClearCommand; import seedu.task.logic.commands.Command; import seedu.task.logic.commands.CommandResult; import seedu.task.logic.commands.DeleteCommand; import seedu.task.logic.commands.ExitCommand; import seedu.task.logic.commands.FindCommand; import seedu.task.logic.commands.HelpCommand; import seedu.task.logic.commands.ListCheckedCommand; import seedu.task.logic.commands.ListCommand; import seedu.task.logic.commands.ListUncheckedCommand; import seedu.task.logic.commands.RedoCommand; import seedu.task.logic.commands.SelectCommand; import seedu.task.logic.commands.UndoCommand; import seedu.task.logic.commands.exceptions.CommandException; import seedu.task.model.Model; import seedu.task.model.ModelManager; import seedu.task.model.ReadOnlyTaskManager; import seedu.task.model.TaskManager; import seedu.task.model.tag.Tag; import seedu.task.model.tag.UniqueTagList; import seedu.task.model.task.CompletionStatus; import seedu.task.model.task.EndTime; import seedu.task.model.task.Name; import seedu.task.model.task.ReadOnlyTask; import seedu.task.model.task.StartTime; import seedu.task.model.task.Task; import seedu.task.storage.StorageManager; public class LogicManagerTest { @Rule public TemporaryFolder saveFolder = new TemporaryFolder(); private Model model; private Logic logic; //These are for checking the correctness of the events raised private ReadOnlyTaskManager latestSavedAddressBook; private boolean helpShown; private int targetedJumpIndex; @Subscribe private void handleLocalModelChangedEvent(TaskManagerChangedEvent abce) { latestSavedAddressBook = new TaskManager(abce.data); } @Subscribe private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) { helpShown = true; } @Subscribe private void handleJumpToListRequestEvent(JumpToListRequestEvent je) { targetedJumpIndex = je.targetIndex; } @Before public void setUp() { model = new ModelManager(); String tempAddressBookFile = saveFolder.getRoot().getPath() + "TempAddressBook.xml"; String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json"; logic = new LogicManager(model, new StorageManager(tempAddressBookFile, tempPreferencesFile)); EventsCenter.getInstance().registerHandler(this); latestSavedAddressBook = new TaskManager(model.getTaskManager()); // last saved assumed to be up to date helpShown = false; targetedJumpIndex = -1; // non yet } @After public void tearDown() { EventsCenter.clearSubscribers(); } @Test public void execute_invalid() { String invalidCommand = " "; assertCommandFailure(invalidCommand, String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } /** * Executes the command, confirms that a CommandException is not thrown and that the result message is correct. * Also confirms that both the 'address book' and the 'last shown list' are as specified. * @see #assertCommandBehavior(boolean, String, String, ReadOnlyTaskManager, List) */ private void assertCommandSuccess(String inputCommand, String expectedMessage, ReadOnlyTaskManager expectedAddressBook, List<? extends ReadOnlyTask> expectedShownList) { assertCommandBehavior(false, inputCommand, expectedMessage, expectedAddressBook, expectedShownList); } /** * Executes the command, confirms that a CommandException is thrown and that the result message is correct. * Both the 'address book' and the 'last shown list' are verified to be unchanged. * @see #assertCommandBehavior(boolean, String, String, ReadOnlyTaskManager, List) */ private void assertCommandFailure(String inputCommand, String expectedMessage) { TaskManager expectedTaskManager = new TaskManager(model.getTaskManager()); List<ReadOnlyTask> expectedShownList = new ArrayList<>(model.getFilteredTaskList()); assertCommandBehavior(true, inputCommand, expectedMessage, expectedTaskManager, expectedShownList); } /** * Executes the command, confirms that the result message is correct * and that a CommandException is thrown if expected * and also confirms that the following three parts of the LogicManager object's state are as expected:<br> * - the internal address book data are same as those in the {@code expectedAddressBook} <br> * - the backing list shown by UI matches the {@code shownList} <br> * - {@code expectedAddressBook} was saved to the storage file. <br> */ private void assertCommandBehavior(boolean isCommandExceptionExpected, String inputCommand, String expectedMessage, ReadOnlyTaskManager expectedAddressBook, List<? extends ReadOnlyTask> expectedShownList) { try { CommandResult result = logic.execute(inputCommand); assertFalse("CommandException expected but was not thrown.", isCommandExceptionExpected); assertEquals(expectedMessage, result.feedbackToUser); } catch (CommandException e) { assertTrue("CommandException not expected but was thrown.", isCommandExceptionExpected); assertEquals(expectedMessage, e.getMessage()); } //Confirm the ui display elements should contain the right data assertEquals(expectedShownList, model.getFilteredTaskList()); //Confirm the state of data (saved and in-memory) is as expected assertEquals(expectedAddressBook, model.getTaskManager()); assertEquals(expectedAddressBook, latestSavedAddressBook); } @Test public void execute_unknownCommandWord() { String unknownCommand = "uicfhmowqewca"; assertCommandFailure(unknownCommand, MESSAGE_UNKNOWN_COMMAND); } @Test public void execute_help() { assertCommandSuccess("help", HelpCommand.SHOWING_HELP_MESSAGE, new TaskManager(), Collections.emptyList()); assertTrue(helpShown); } @Test public void execute_exit() { assertCommandSuccess("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT, new TaskManager(), Collections.emptyList()); } @Test public void execute_clear() throws Exception { TestDataHelper helper = new TestDataHelper(); model.addTask(helper.generateTask(1)); model.addTask(helper.generateTask(2)); model.addTask(helper.generateTask(3)); assertCommandSuccess("clear", ClearCommand.MESSAGE_SUCCESS, new TaskManager(), Collections.emptyList()); } @Test public void execute_add_successful() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); TaskManager expectedAB = new TaskManager(); expectedAB.addTask(toBeAdded); // execute command and verify result assertCommandSuccess(helper.generateAddCommand(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedAB, expectedAB.getTaskList()); } @Test public void execute_addDuplicate_notAllowed() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); // setup starting state model.addTask(toBeAdded); // person already in internal address book // execute command and verify result assertCommandFailure(helper.generateAddCommand(toBeAdded), AddCommand.MESSAGE_DUPLICATE_TASK); } @Test public void execute_list_showsAllTasks() throws Exception { // prepare expectations TestDataHelper helper = new TestDataHelper(); TaskManager expectedAB = helper.generateTaskManager(2); List<? extends ReadOnlyTask> expectedList = expectedAB.getTaskList(); // prepare task manager state helper.addToModel(model, 2); assertCommandSuccess("list", ListCommand.MESSAGE_SUCCESS, expectedAB, expectedList); } //@@author A0139410N @Test public void execute_listUnchecked_showsUnchecked() throws Exception { // prepare expectations, only supposed to show 2 unchecked task with 3 task in total TestDataHelper helper = new TestDataHelper(); Task unchecked1 = helper.generateTaskWithName("not done"); Task unchecked2 = helper.generateTaskWithName("Also not done"); Task checked = helper.completedTask(); List<Task> threeTasks = helper.generateTaskList(unchecked1, unchecked2, checked); TaskManager expectedAB = helper.generateTaskManager(threeTasks); List<Task> expectedList = helper.generateTaskList(unchecked1, unchecked2); // prepare address book state comprising of 2 unchecked task and 1 checked helper.addToModel(model, threeTasks); assertCommandSuccess("list unchecked", ListUncheckedCommand.MESSAGE_SUCCESS, expectedAB, expectedList); } //@@ author A0139410N @Test public void execute_listChecked_showsChecked() throws Exception { // prepare expectations, only supposed to show 1 checked task with 3 task in total TestDataHelper helper = new TestDataHelper(); Task unchecked1 = helper.generateTaskWithName("not done"); Task unchecked2 = helper.generateTaskWithName("Also not done"); Task checked = helper.completedTask(); List<Task> threeTasks = helper.generateTaskList(unchecked1, unchecked2, checked); TaskManager expectedAB = helper.generateTaskManager(threeTasks); List<Task> expectedList = helper.generateTaskList(checked); // prepare address book state comprising of 2 unchecked task and 1 checked helper.addToModel(model, threeTasks); assertCommandSuccess("list checked", ListCheckedCommand.MESSAGE_SUCCESS, expectedAB, expectedList); } //@@author //@@author A0138664W @Test public void execute_undo_noPreviousCommandInput() throws Exception { assertCommandSuccess("undo", UndoCommand.NOTHING_TO_UNDO, new TaskManager(), Collections.emptyList()); } @Test public void execute_redo_noPreviousCommandInput() throws Exception { assertCommandSuccess("redo", RedoCommand.NOTHING_TO_REDO, new TaskManager(), Collections.emptyList()); } @Test public void execcute_undoredo_add_delete() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); TaskManager expectedAB = new TaskManager(); expectedAB.addTask(toBeAdded); // execute command and verify result assertCommandSuccess(helper.generateAddCommand(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedAB, expectedAB.getTaskList()); expectedAB.removeTask(toBeAdded); assertCommandSuccess("delete 1", String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, toBeAdded), expectedAB, expectedAB.getTaskList()); expectedAB.addTask(toBeAdded); assertCommandSuccess("undo", String.format(UndoCommand.MESSAGE_UNDO_SUCCESS_ADD, toBeAdded), expectedAB, expectedAB.getTaskList()); expectedAB.removeTask(toBeAdded); assertCommandSuccess("undo", String.format(UndoCommand.MESSAGE_UNDO_SUCCESS_DELETE, toBeAdded), expectedAB, expectedAB.getTaskList()); expectedAB.addTask(toBeAdded); assertCommandSuccess("redo", String.format(RedoCommand.MESSAGE_REDO_SUCCESS_ADD, toBeAdded), expectedAB, expectedAB.getTaskList()); expectedAB.removeTask(toBeAdded); assertCommandSuccess("redo", String.format(RedoCommand.MESSAGE_REDO_SUCCESS_DELETE, toBeAdded), expectedAB, expectedAB.getTaskList()); } //@@author /** * Confirms the 'invalid argument index number behaviour' for the given command * targeting a single person in the shown list, using visible index. * @param commandWord to test assuming it targets a single person in the last shown list * based on visible index. */ private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage) throws Exception { assertCommandFailure(commandWord , expectedMessage); //index missing assertCommandFailure(commandWord + " +1", expectedMessage); //index should be unsigned assertCommandFailure(commandWord + " -1", expectedMessage); //index should be unsigned assertCommandFailure(commandWord + " 0", expectedMessage); //index cannot be 0 assertCommandFailure(commandWord + " not_a_number", expectedMessage); } /** * Confirms the 'invalid argument index number behaviour' for the given command * targeting a single person in the shown list, using visible index. * @param commandWord to test assuming it targets a single person in the last shown list * based on visible index. */ private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception { String expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX; TestDataHelper helper = new TestDataHelper(); List<Task> taskList = helper.generateTaskList(2); // set AB state to 2 persons model.resetData(new TaskManager()); for (Task p : taskList) { model.addTask(p); } assertCommandFailure(commandWord + " 3", expectedMessage); } @Test public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage); } @Test public void execute_selectIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("select"); } @Test public void execute_select_jumpsToCorrectPerson() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); TaskManager expectedAB = helper.generateTaskManager(threeTasks); helper.addToModel(model, threeTasks); assertCommandSuccess("select 2", String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2), expectedAB, expectedAB.getTaskList()); assertEquals(1, targetedJumpIndex); assertEquals(model.getFilteredTaskList().get(1), threeTasks.get(1)); } @Test public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage); } @Test public void execute_deleteIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("delete"); } @Test public void execute_delete_removesCorrectPerson() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); TaskManager expectedAB = helper.generateTaskManager(threeTasks); expectedAB.removeTask(threeTasks.get(1)); helper.addToModel(model, threeTasks); assertCommandSuccess("delete 2", String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, threeTasks.get(1)), expectedAB, expectedAB.getTaskList()); } @Test public void execute_find_invalidArgsFormat() { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE); assertCommandFailure("find ", expectedMessage); } @Test public void execute_find_onlyMatchesFullWordsInNames() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p1 = helper.generateTaskWithName("KE Y"); Task p2 = helper.generateTaskWithName("KEYKEYKEY sduauo"); List<Task> fourTasks = helper.generateTaskList(p1, pTarget1, p2, pTarget2); TaskManager expectedAB = helper.generateTaskManager(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2); helper.addToModel(model, fourTasks); assertCommandSuccess("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } @Test public void execute_find_isNotCaseSensitive() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateTaskWithName("bla bla KEY bla"); Task p2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p3 = helper.generateTaskWithName("key key"); Task p4 = helper.generateTaskWithName("KEy sduauo"); List<Task> fourTasks = helper.generateTaskList(p3, p1, p4, p2); TaskManager expectedAB = helper.generateTaskManager(fourTasks); List<Task> expectedList = fourTasks; helper.addToModel(model, fourTasks); assertCommandSuccess("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } @Test public void execute_find_matchesIfAnyKeywordPresent() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla rAnDoM bla bceofeia"); Task pTarget3 = helper.generateTaskWithName("key key"); Task p1 = helper.generateTaskWithName("sduauo"); List<Task> fourTasks = helper.generateTaskList(pTarget1, p1, pTarget2, pTarget3); TaskManager expectedAB = helper.generateTaskManager(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2, pTarget3); helper.addToModel(model, fourTasks); assertCommandSuccess("find key rAnDoM", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } /** * A utility class to generate test data. */ class TestDataHelper { Task adam() throws Exception { Name name = new Name("Adam Brown"); StartTime startDate = new StartTime(NattyDateUtil.parseSingleDate("12/11/11 0909")); EndTime endDate = new EndTime(NattyDateUtil.parseSingleDate("12/11/11 0909")); CompletionStatus completion = new CompletionStatus(false); Tag tag1 = new Tag("tag1"); Tag tag2 = new Tag("longertag2"); UniqueTagList tags = new UniqueTagList(tag1, tag2); return new Task(name, startDate, endDate, completion, tags); } //@@author A0139410N Task completedTask() throws Exception { Name name = new Name("I am done"); StartTime startDate = new StartTime(NattyDateUtil.parseSingleDate("12/11/11 0909")); EndTime endDate = new EndTime(NattyDateUtil.parseSingleDate("12/11/11 0909")); CompletionStatus completion = new CompletionStatus(true); Tag tag1 = new Tag("tag1"); Tag tag2 = new Tag("longertag2"); UniqueTagList tags = new UniqueTagList(tag1, tag2); return new Task(name, startDate, endDate, completion, tags); } //@@author A0138664W Task incompletedTask() throws Exception { Name name = new Name("I am done"); StartTime startDate = new StartTime(NattyDateUtil.parseSingleDate("12/11/11 0909")); EndTime endDate = new EndTime(NattyDateUtil.parseSingleDate("12/11/11 0909")); CompletionStatus completion = new CompletionStatus(false); Tag tag1 = new Tag("tag1"); Tag tag2 = new Tag("longertag2"); UniqueTagList tags = new UniqueTagList(tag1, tag2); return new Task(name, startDate, endDate, completion, tags); } //@@author A0146789H /** * Generates a valid person using the given seed. * Running this function with the same parameter values guarantees the returned person will have the same state. * Each unique seed will generate a unique Task object. * * @param seed used to generate the person data field values */ Task generateTask(int seed) throws Exception { return new Task( new Name("Task " + seed), new StartTime(NattyDateUtil.parseSingleDate("12/11/11 0909")), new EndTime(NattyDateUtil.parseSingleDate("12/11/11 0909")), new CompletionStatus(false), new UniqueTagList(new Tag("tag" + Math.abs(seed)), new Tag("tag" + Math.abs(seed + 1))) ); } /** Generates the correct add command based on the person given */ String generateAddCommand(Task p) { StringBuffer cmd = new StringBuffer(); cmd.append("add "); cmd.append(p.getName().toString()); cmd.append(" from ").append(p.getEndTime()); cmd.append(" to ").append(p.getStartTime()); UniqueTagList tags = p.getTags(); for (Tag t: tags) { cmd.append(" #").append(t.tagName); } return cmd.toString(); } //@@author /** * Generates an TaskManager with auto-generated persons. */ TaskManager generateTaskManager(int numGenerated) throws Exception { TaskManager taskManager = new TaskManager(); addToTaskManager(taskManager, numGenerated); return taskManager; } /** * Generates an TaskManager based on the list of Persons given. */ TaskManager generateTaskManager(List<Task> tasks) throws Exception { TaskManager taskManager = new TaskManager(); addToTaskManager(taskManager, tasks); return taskManager; } /** * Adds auto-generated Task objects to the given TaskManager * @param taskManager The TaskManager to which the Persons will be added */ void addToTaskManager(TaskManager taskManager, int numGenerated) throws Exception { addToTaskManager(taskManager, generateTaskList(numGenerated)); } /** * Adds the given list of Persons to the given TaskManager */ void addToTaskManager(TaskManager taskManager, List<Task> tasksToAdd) throws Exception { for (Task p: tasksToAdd) { taskManager.addTask(p); } } /** * Adds auto-generated Task objects to the given model * @param model The model to which the Persons will be added */ void addToModel(Model model, int numGenerated) throws Exception { addToModel(model, generateTaskList(numGenerated)); } /** * Adds the given list of Persons to the given model */ void addToModel(Model model, List<Task> tasksToAdd) throws Exception { for (Task p: tasksToAdd) { model.addTask(p); } } /** * Generates a list of Persons based on the flags. */ List<Task> generateTaskList(int numGenerated) throws Exception { List<Task> tasks = new ArrayList<>(); for (int i = 1; i <= numGenerated; i++) { tasks.add(generateTask(i)); } return tasks; } List<Task> generateTaskList(Task... persons) { return Arrays.asList(persons); } /** * Generates a Task object with given name. Other fields will have some dummy values. */ Task generateTaskWithName(String name) throws Exception { return new Task( new Name(name), new StartTime(NattyDateUtil.parseSingleDate("11/12/12 0000")), new EndTime(NattyDateUtil.parseSingleDate("11/12/12 0000")), new CompletionStatus(false), new UniqueTagList(new Tag("tag")) ); } } }
package org.granitepowered.granite; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigRenderOptions; import com.typesafe.config.ConfigValueFactory; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; public class ServerConfig { public Config config; public File configLocation; public ServerConfig() { configLocation = new File("granite.conf"); config = ConfigFactory.parseFile(configLocation); try (Reader confReader = new InputStreamReader(getClass().getResourceAsStream("/granite.conf"))) { config = config.withFallback(ConfigFactory.parseReader(confReader)); } catch (IOException e) { e.printStackTrace(); } save(); getPluginDataDirectory().mkdirs(); getPluginDirectory().mkdirs(); getLibrariesDirectory().mkdirs(); } public void save() { String saved = config.root().render(ConfigRenderOptions.defaults().setOriginComments(false)); try { FileUtils.write(configLocation, saved); } catch (IOException e) { e.printStackTrace(); } } public File getPluginDataDirectory() { return new File(config.getString("plugin-data-directory")); } public File getPluginDirectory() { return new File(config.getString("plugin-directory")); } public File getMinecraftJar() { return new File(config.getString("minecraft-jar")); } public File getLibrariesDirectory() { return new File(config.getString("libraries-directory")); } public File getMappingsFile() { return new File(config.getString("mappings-file")); } public String getLatestMappingsEtag() { return config.getString("latest-mappings-etag"); } public boolean getAutomaticMappingsUpdating() { return config.getBoolean("automatic-mappings-updating"); } public void set(String key, Object value) { config = config.withValue(key, ConfigValueFactory.fromAnyRef(value)); } }
package org.jenkinsci.plugins.ghprb; import hudson.model.AbstractBuild; import hudson.model.Cause; import hudson.model.Result; import hudson.model.TaskListener; import hudson.model.queue.QueueTaskFuture; import hudson.plugins.git.util.BuildData; import org.apache.commons.io.FileUtils; import org.jenkinsci.plugins.ghprb.manager.GhprbBuildManager; import org.jenkinsci.plugins.ghprb.manager.configuration.JobConfiguration; import org.jenkinsci.plugins.ghprb.manager.factory.GhprbBuildManagerFactoryUtil; import org.kohsuke.github.GHCommitState; import org.kohsuke.github.GHIssueState; import org.kohsuke.github.GHPullRequest; import org.kohsuke.github.GHUser; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * @author janinko */ public class GhprbBuilds { private static final Logger logger = Logger.getLogger(GhprbBuilds.class.getName()); private final GhprbTrigger trigger; private final GhprbRepository repo; public GhprbBuilds(GhprbTrigger trigger, GhprbRepository repo) { this.trigger = trigger; this.repo = repo; } public String build(GhprbPullRequest pr, GHUser triggerSender, String commentBody) { StringBuilder sb = new StringBuilder(); if (cancelBuild(pr.getId())) { sb.append("Previous build stopped."); } sb.append(" Build triggered."); if (pr.isMergeable()) { sb.append(" sha1 is merged."); } else { sb.append(" sha1 is original commit."); } GhprbCause cause = new GhprbCause( pr.getHead(), pr.getId(), pr.isMergeable(), pr.getTarget(), pr.getSource(), pr.getAuthorEmail(), pr.getTitle(), pr.getUrl(), triggerSender, commentBody, pr.getCommitAuthor()); QueueTaskFuture<?> build = trigger.startJob(cause, repo); if (build == null) { logger.log(Level.SEVERE, "Job did not start"); } return sb.toString(); } private boolean cancelBuild(int id) { return false; } private GhprbCause getCause(AbstractBuild<?, ?> build) { Cause cause = build.getCause(GhprbCause.class); if (cause == null || (!(cause instanceof GhprbCause))) { return null; } return (GhprbCause) cause; } public void onStarted(AbstractBuild<?, ?> build, PrintStream logger) { GhprbCause c = getCause(build); if (c == null) { return; } repo.createCommitStatus(build, GHCommitState.PENDING, (c.isMerged() ? "Build started, sha1 is merged" : "Build started, sha1 is original commit."), c.getPullID(), trigger.getCommitStatusContext(), logger); try { build.setDescription("<a title=\"" + c.getTitle() + "\" href=\"" + c.getUrl() + "\">PR #" + c.getPullID() + "</a>: " + c.getAbbreviatedTitle()); } catch (IOException ex) { logger.println("Can't update build description"); ex.printStackTrace(logger); } } public void onCompleted(AbstractBuild<?, ?> build, TaskListener listener) { GhprbCause c = getCause(build); if (c == null) { return; } // remove the BuildData action that we may have added earlier to avoid // having two of them, and because the one we added isn't correct // @see GhprbTrigger BuildData fakeOne = null; for (BuildData data : build.getActions(BuildData.class)) { if (data.getLastBuiltRevision() != null && !data.getLastBuiltRevision().getSha1String().equals(c.getCommit())) { fakeOne = data; break; } } if (fakeOne != null) { build.getActions().remove(fakeOne); } GHCommitState state; if (build.getResult() == Result.SUCCESS) { state = GHCommitState.SUCCESS; } else if (build.getResult() == Result.UNSTABLE) { state = GHCommitState.valueOf(GhprbTrigger.getDscp().getUnstableAs()); } else { state = GHCommitState.FAILURE; } repo.createCommitStatus(build, state, "Build finished.", c.getPullID(), trigger.getCommitStatusContext(), listener.getLogger()); String publishedURL = GhprbTrigger.getDscp().getPublishedURL(); if (publishedURL != null && !publishedURL.isEmpty()) { buildResultMessage(build, listener, state, c); } // close failed pull request automatically if (state == GHCommitState.FAILURE && trigger.isAutoCloseFailedPullRequests()) { closeFailedRequest(listener, c); } } private void closeFailedRequest(TaskListener listener, GhprbCause c) { try { GHPullRequest pr = repo.getPullRequest(c.getPullID()); if (pr.getState().equals(GHIssueState.OPEN)) { repo.closePullRequest(c.getPullID()); } } catch (IOException ex) { listener.getLogger().println("Can't close pull request"); ex.printStackTrace(listener.getLogger()); } } private void buildResultMessage(AbstractBuild<?, ?> build, TaskListener listener, GHCommitState state, GhprbCause c) { StringBuilder msg = new StringBuilder(); String commentFilePath = trigger.getCommentFilePath(); if (commentFilePath != null && !commentFilePath.isEmpty()) { try { String scriptFilePathResolved = Ghprb.replaceMacros(build, commentFilePath); String content = FileUtils.readFileToString(new File(scriptFilePathResolved)); msg.append("Build comment file: \n msg.append(content); msg.append("\n } catch (IOException e) { msg.append("\n!!! Couldn't read commit file !!!\n"); listener.getLogger().println("Couldn't read comment file"); e.printStackTrace(listener.getLogger()); } } msg.append("\nRefer to this link for build results (access rights to CI server needed): \n"); msg.append(generateCustomizedMessage(build)); int numLines = GhprbTrigger.getDscp().getlogExcerptLines(); if (state != GHCommitState.SUCCESS && numLines > 0) { // on failure, append an excerpt of the build log try { // wrap log in "code" markdown msg.append("\n\n**Build Log**\n*last ").append(numLines).append(" lines*\n"); msg.append("\n ```\n"); List<String> log = build.getLog(numLines); for (String line : log) { msg.append(line).append('\n'); } msg.append("```\n"); } catch (IOException ex) { listener.getLogger().println("Can't add log excerpt to commit comments"); ex.printStackTrace(listener.getLogger()); } } String buildMessage = null; if (state == GHCommitState.SUCCESS) { if (trigger.getMsgSuccess() != null && !trigger.getMsgSuccess().isEmpty()) { buildMessage = trigger.getMsgSuccess(); } else if (GhprbTrigger.getDscp().getMsgSuccess(build) != null && !GhprbTrigger.getDscp().getMsgSuccess(build).isEmpty()) { buildMessage = GhprbTrigger.getDscp().getMsgSuccess(build); } } else if (state == GHCommitState.FAILURE) { if (trigger.getMsgFailure() != null && !trigger.getMsgFailure().isEmpty()) { buildMessage = trigger.getMsgFailure(); } else if (GhprbTrigger.getDscp().getMsgFailure(build) != null && !GhprbTrigger.getDscp().getMsgFailure(build).isEmpty()) { buildMessage = GhprbTrigger.getDscp().getMsgFailure(build); } } // Only Append the build's custom message if it has been set. if (buildMessage != null && !buildMessage.isEmpty()) { // When the msg is not empty, append a newline first, to seperate it from the rest of the String if (!"".equals(msg.toString())) { msg.append("\n"); } msg.append(buildMessage); } if (msg.length() > 0) { listener.getLogger().println(msg); repo.addComment(c.getPullID(), msg.toString(), build, listener); } } private String generateCustomizedMessage(AbstractBuild<?, ?> build) { JobConfiguration jobConfiguration = JobConfiguration.builder() .printStackTrace(trigger.isDisplayBuildErrorsOnDownstreamBuilds()).build(); GhprbBuildManager buildManager = GhprbBuildManagerFactoryUtil.getBuildManager(build, jobConfiguration); StringBuilder sb = new StringBuilder(); sb.append(buildManager.calculateBuildUrl()); if (build.getResult() != Result.SUCCESS) { sb.append(buildManager.getTestResults()); } return sb.toString(); } }
package org.jhove2.core.source; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteOrder; import org.jhove2.annotation.ReportableProperty; import org.jhove2.core.io.Input; import org.jhove2.core.io.Input.Type; /** JHOVE2 byte stream source. A byte stream source is always a child of * some other source unit. * * @author mstrong, slabrams */ public class ByteStreamSource extends AbstractSource { /** Starting offset relative to parent source. */ protected long endingOffset; /** Starting offset relative to parent source. */ protected long startingOffset; /** Parent source. */ protected Source parent; /** Size of the byte stream, in bytes. */ protected long size; /** Instantiate a new <code>ByteStreamSource</code>. The new byte stream * is automatically added as a child reportable of its parent source unit. * * @param parent Parent source * @param offset Starting offset relative to parent * @param size Size of the byte stream * @throws IOException */ public ByteStreamSource(Source parent, long offset, long size) throws IOException { super(); this.parent = parent; this.startingOffset = offset; this.endingOffset = offset + size; this.size = size; /* Make this byte stream a child of its parent. */ parent.addChildSource(this); /* Re-use the existing open input of the parent. */ this.input = parent.getInput(); /* Set the position to the start of the byte stream. */ this.input.setPosition(offset); } /** * Get {@link org.jhove2.core.io.Input} for the source unit. Concrete * classes extending this abstract class must provide an implementation of * this method if they are are based on parsable input. Classes without * parsable input (e.g. {@link org.jhove2.core.source.ClumpSource} or * {@link org.jhove2.core.source.DirectorySource} can let this inherited * method return null. * * @param bufferSize * Input maximum buffer size, in bytes * @param bufferType * Input buffer type * @param order * Byte order * @return null * @throws FileNotFoundException * File not found * @throws IOException * I/O exception getting input */ public Input getInput(int bufferSize, Type bufferType, ByteOrder order) throws FileNotFoundException, IOException { return this.input; } /** Get ending offset of the byte stream, relative to its parent. * @return Ending offset */ @ReportableProperty(order=1, value="Ending offset of the byte stream, relative to its parent.") public long getEndingOffset() { return this.endingOffset; } /** Get starting offset of the byte stream, relative to its parent. * @return Starting offset */ @ReportableProperty(order=2, value="Starting offset of the byte stream, relative to its parent.") public long getStartingOffset() { return this.startingOffset; } /** Get byte stream size, in bytes. * @return Byte stream size */ @ReportableProperty(order=3, value="Byte stream size, in bytes.") public long getSize() { return this.size; } }
package org.kohsuke.groovy.sandbox.impl; import groovy.lang.Closure; import groovy.lang.GroovyRuntimeException; import groovy.lang.MetaClass; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import groovy.lang.MissingMethodException; import groovy.lang.MissingPropertyException; import java.io.File; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import org.codehaus.groovy.classgen.asm.BinaryExpressionHelper; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.CallSiteArray; import org.codehaus.groovy.syntax.Types; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import static org.codehaus.groovy.runtime.InvokerHelper.getMetaClass; import static org.codehaus.groovy.runtime.MetaClassHelper.convertToTypeArray; import org.kohsuke.groovy.sandbox.SandboxTransformer; import static org.kohsuke.groovy.sandbox.impl.ClosureSupport.BUILTIN_PROPERTIES; /** * Intercepted Groovy script calls into this class. * * @author Kohsuke Kawaguchi */ public class Checker { /*TODO: specify the proper owner value*/ private static CallSite fakeCallSite(String method) { CallSiteArray csa = new CallSiteArray(Checker.class, new String[]{method}); return csa.array[0]; } // TODO: we need an owner class public static Object checkedCall(Object _receiver, boolean safe, boolean spread, String _method, Object[] _args) throws Throwable { if (safe && _receiver==null) return null; _args = fixNull(_args); if (spread) { List<Object> r = new ArrayList<Object>(); Iterator itr = InvokerHelper.asIterator(_receiver); while (itr.hasNext()) { Object it = itr.next(); if (it!=null) r.add(checkedCall(it, true, false, _method, _args)); } return r; } else { // the first try // but this fails to properly intercept 5.class.forName('java.lang.String') // def m = receiver.&"${method}"; // return m(args) // but it still doesn't resolve static method // def m = receiver.metaClass.getMetaMethod(method.toString(),args) // return m.invoke(receiver,args); /* When Groovy evaluates expression like "FooClass.bar()", it routes the call here. (as to why we cannot rewrite the expression to statically route the call to checkedStaticCall, consider "def x = FooClass.class; x.bar()", which still resolves to FooClass.bar() if it is present!) So this is where we really need to distinguish a call to a static method defined on the class vs an instance method call to a method on java.lang.Class. Then the question is how do we know when to do which, which one takes precedence, etc. Groovy doesn't commit to any specific logic at the level of MetaClass. In MetaClassImpl, the logic is defined in MetaClassImpl.pickStaticMethod. BTW, this makes me wonder if StaticMethodCallExpression is used at all in AST, and it looks like this is no longer used. */ if (_receiver instanceof Class) { MetaClass mc = getMetaClass((Class) _receiver); if (mc instanceof MetaClassImpl) { MetaClassImpl mci = (MetaClassImpl) mc; MetaMethod m = mci.retrieveStaticMethod(_method,_args); if (m!=null) { if (m.isStatic()) { // Foo.forName() still finds Class.forName() method, so we need to test for that if (m.getDeclaringClass().getTheClass()==Class.class) return checkedStaticCall(Class.class,_method,_args); else return checkedStaticCall((Class)_receiver,_method,_args); } } } } if (_receiver instanceof Closure) { if (_method.equals("invokeMethod") && isInvokingMethodOnClosure(_receiver,_method,_args)) { // if someone is calling closure.invokeMethod("foo",args), map that back to closure.foo("args") _method = _args[0].toString(); _args = (Object[])_args[1]; } MetaMethod m = getMetaClass(_receiver).pickMethod(_method, convertToTypeArray(_args)); if (m==null) { // if we are trying to call a method that's actually defined in Closure, then we'll get non-null 'm' // in that case, treat it like normal method call // if we are here, that means we are trying to delegate the call to 'owner', 'delegate', etc. // is going to, and check access accordingly. Groovy's corresponding code is in MetaClassImpl.invokeMethod(...) List<Object> targets = ClosureSupport.targetsOf((Closure) _receiver); Class[] argTypes = convertToTypeArray(_args); // in the first phase, we look for exact method match for (Object candidate : targets) { if (InvokerHelper.getMetaClass(candidate).pickMethod(_method,argTypes)!=null) return checkedCall(candidate,false,false, _method, _args); } // in the second phase, we try to call invokeMethod on them for (Object candidate : targets) { try { return checkedCall(candidate,false,false,"invokeMethod",new Object[]{_method,_args}); } catch (MissingMethodException e) { // try the next one } } // we tried to be smart about Closure.invokeMethod, but we are just not finding any. // so we'll have to treat this like any other method. } } /* The third try: Groovyc produces one CallSites instance per a call site, then pack them into a single array and put them as a static field in a class. this encapsulates the actual method dispatching logic. Ideally we'd like to get the CallSite object that would have been used for a call, but because it's packed in an array and the index in that array is determined only at the code generation time, I can't get the access to it. So here we are faking it by creating a new CallSite object. */ return new VarArgInvokerChain(_receiver) { public Object call(Object receiver, String method, Object... args) throws Throwable { if (chain.hasNext()) return chain.next().onMethodCall(this,receiver,method,args); else return fakeCallSite(method).call(receiver,args); } }.call(_receiver,_method,_args); } } /** * Are we trying to invoke a method defined on Closure or its super type? * (If so, we'll need to chase down which method we are actually invoking.) * * <p> * Used for invokeMethod/getProperty/setProperty. * * <p> * If the receiver overrides this method, return false since we don't know how such methods behave. */ private static boolean isInvokingMethodOnClosure(Object receiver, String method, Object... args) { if (receiver instanceof Closure) { MetaMethod m = getMetaClass(receiver).pickMethod(method, convertToTypeArray(args)); if (m!=null && m.getDeclaringClass().isAssignableFrom(Closure.class)) return true; } return false; } public static Object checkedStaticCall(Class _receiver, String _method, Object[] _args) throws Throwable { return new VarArgInvokerChain(_receiver) { public Object call(Object receiver, String method, Object... args) throws Throwable { if (chain.hasNext()) return chain.next().onStaticCall(this,(Class)receiver,method,args); else return fakeCallSite(method).callStatic((Class)receiver,args); } }.call(_receiver,_method,fixNull(_args)); } public static Object checkedConstructor(Class _type, Object[] _args) throws Throwable { return new VarArgInvokerChain(_type) { public Object call(Object receiver, String method, Object... args) throws Throwable { if (chain.hasNext()) return chain.next().onNewInstance(this,(Class)receiver,args); else // I believe the name is unused return fakeCallSite("<init>").callConstructor((Class)receiver,args); } }.call(_type,null,fixNull(_args)); } public static Object checkedSuperCall(Class _senderType, Object _receiver, String _method, Object[] _args) throws Throwable { Super s = new Super(_senderType, _receiver); return new VarArgInvokerChain(s) { public Object call(Object _s, String method, Object... args) throws Throwable { Super s = (Super)_s; if (chain.hasNext()) { return chain.next().onSuperCall(this, s.senderType, s.receiver, method, args); } else { try { MetaClass mc = InvokerHelper.getMetaClass(s.receiver.getClass()); return mc.invokeMethod(s.senderType.getSuperclass(), s.receiver, method, args, true, true); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } } }.call(s,_method,fixNull(_args)); } public static class SuperConstructorWrapper { private final Object[] args; SuperConstructorWrapper(Object[] args) { this.args = args; } public Object arg(int idx) { return args[idx]; } } public static SuperConstructorWrapper checkedSuperConstructor(final Class<?> superClass, Object[] args) throws Throwable { new VarArgInvokerChain(superClass) { public Object call(Object receiver, String method, Object... args) throws Throwable { if (chain.hasNext()) { chain.next().onSuperConstructor(this, superClass, args); } return null; } }.call(superClass, null, fixNull(args)); return new SuperConstructorWrapper(args); } public static Object checkedGetProperty(final Object _receiver, boolean safe, boolean spread, Object _property) throws Throwable { if (safe && _receiver==null) return null; if (spread) { List<Object> r = new ArrayList<Object>(); Iterator itr = InvokerHelper.asIterator(_receiver); while (itr.hasNext()) { Object it = itr.next(); if (it!=null) r.add(checkedGetProperty(it,true,false,_property)); } return r; } // 1st try: do the same call site stuff // return fakeCallSite(property.toString()).callGetProperty(receiver); if (isInvokingMethodOnClosure(_receiver, "getProperty", _property) && !BUILTIN_PROPERTIES.contains(_property)) { // if we are trying to invoke Closure.getProperty(), // we want to find out where the call is going to, and check that target MissingPropertyException x=null; for (Object candidate : ClosureSupport.targetsOf((Closure) _receiver)) { try { return checkedGetProperty(candidate, false, false, _property); } catch (MissingPropertyException e) { x = e; // try the next one } } if (x!=null) throw x; throw new MissingPropertyException(_property.toString(), _receiver.getClass()); } if (_receiver instanceof Map) { /* MetaClassImpl.getProperty looks for Map subtype and handles it as Map.get call, so dispatch that call accordingly. */ return checkedCall(_receiver,false,false,"get",new Object[]{_property}); } return new ZeroArgInvokerChain(_receiver) { public Object call(Object receiver, String property) throws Throwable { if (chain.hasNext()) return chain.next().onGetProperty(this,receiver,property); else return ScriptBytecodeAdapter.getProperty(null, receiver, property); } }.call(_receiver,_property.toString()); } public static Object checkedSetProperty(Object _receiver, Object _property, boolean safe, boolean spread, int op, Object _value) throws Throwable { if (op!=Types.ASSIGN) { // a compound assignment operator is decomposed into get+op+set // for example, a.x += y => a.x=a.x+y Object v = checkedGetProperty(_receiver, safe, spread, _property); return checkedSetProperty(_receiver, _property, safe, spread, Types.ASSIGN, checkedBinaryOp(v, Ops.compoundAssignmentToBinaryOperator(op), _value)); } if (safe && _receiver==null) return _value; if (spread) { Iterator itr = InvokerHelper.asIterator(_receiver); while (itr.hasNext()) { Object it = itr.next(); if (it!=null) checkedSetProperty(it, _property, true, false, op, _value); } return _value; } if (isInvokingMethodOnClosure(_receiver, "setProperty", _property, _value) && !BUILTIN_PROPERTIES.contains(_property)) { // if we are trying to invoke Closure.setProperty(), // we want to find out where the call is going to, and check that target GroovyRuntimeException x=null; for (Object candidate : ClosureSupport.targetsOf((Closure) _receiver)) { try { return checkedSetProperty(candidate, _property, false, false, op, _value); } catch (GroovyRuntimeException e) { // Cathing GroovyRuntimeException feels questionable, but this is how Groovy does it in // Closure.setPropertyTryThese(). x = e; // try the next one } } if (x!=null) throw x; throw new MissingPropertyException(_property.toString(), _receiver.getClass()); } if (_receiver instanceof Map) { /* MetaClassImpl.setProperty looks for Map subtype and handles it as Map.put call, so dispatch that call accordingly. */ checkedCall(_receiver,false,false,"put",new Object[]{_property,_value}); return _value; } return new SingleArgInvokerChain(_receiver) { public Object call(Object receiver, String property, Object value) throws Throwable { if (chain.hasNext()) return chain.next().onSetProperty(this,receiver,property,value); else { // according to AsmClassGenerator this is how the compiler maps it to ScriptBytecodeAdapter.setProperty(value,null,receiver,property); return value; } } }.call(_receiver,_property.toString(),_value); } public static Object checkedGetAttribute(Object _receiver, boolean safe, boolean spread, Object _property) throws Throwable { if (safe && _receiver==null) return null; if (spread) { List<Object> r = new ArrayList<Object>(); Iterator itr = InvokerHelper.asIterator(_receiver); while (itr.hasNext()) { Object it = itr.next(); if (it!=null) r.add(checkedGetAttribute(it, true, false, _property)); } return r; } else { return new ZeroArgInvokerChain(_receiver) { public Object call(Object receiver, String property) throws Throwable { if (chain.hasNext()) return chain.next().onGetAttribute(this,receiver,property); else // according to AsmClassGenerator this is how the compiler maps it to return ScriptBytecodeAdapter.getField(null,receiver,property); } }.call(_receiver,_property.toString()); } } /** * Intercepts the attribute assignment of the form "receiver.@property = value" * * @param op * One of the assignment operators of {@link Types} */ public static Object checkedSetAttribute(Object _receiver, Object _property, boolean safe, boolean spread, int op, Object _value) throws Throwable { if (op!=Types.ASSIGN) { // a compound assignment operator is decomposed into get+op+set // for example, a.@x += y => a.@x=a.@x+y Object v = checkedGetAttribute(_receiver, safe, spread, _property); return checkedSetAttribute(_receiver, _property, safe, spread, Types.ASSIGN, checkedBinaryOp(v, Ops.compoundAssignmentToBinaryOperator(op), _value)); } if (safe && _receiver==null) return _value; if (spread) { Iterator itr = InvokerHelper.asIterator(_receiver); while (itr.hasNext()) { Object it = itr.next(); if (it!=null) checkedSetAttribute(it,_property,true,false,op,_value); } } else { return new SingleArgInvokerChain(_receiver) { public Object call(Object receiver, String property, Object value) throws Throwable { if (chain.hasNext()) return chain.next().onSetAttribute(this,receiver,property,value); else { ScriptBytecodeAdapter.setField(value,null,receiver,property); return value; } } }.call(_receiver,_property.toString(),_value); } return _value; } public static Object checkedGetArray(Object _receiver, Object _index) throws Throwable { return new SingleArgInvokerChain(_receiver) { public Object call(Object receiver, String method, Object index) throws Throwable { if (chain.hasNext()) return chain.next().onGetArray(this,receiver,index); else // BinaryExpressionHelper.eval maps this to "getAt" call return fakeCallSite("getAt").call(receiver,index); } }.call(_receiver,null,_index); } /** * Intercepts the array assignment of the form "receiver[index] = value" * * @param op * One of the assignment operators of {@link Types} */ public static Object checkedSetArray(Object _receiver, Object _index, int op, Object _value) throws Throwable { if (op!=Types.ASSIGN) { // a compound assignment operator is decomposed into get+op+set // for example, a[x] += y => a[x]=a[x]+y Object v = checkedGetArray(_receiver, _index); return checkedSetArray(_receiver, _index, Types.ASSIGN, checkedBinaryOp(v, Ops.compoundAssignmentToBinaryOperator(op), _value)); } else { return new TwoArgInvokerChain(_receiver) { public Object call(Object receiver, String method, Object index, Object value) throws Throwable { if (chain.hasNext()) return chain.next().onSetArray(this,receiver,index,value); else { // BinaryExpressionHelper.assignToArray maps this to "putAt" call fakeCallSite("putAt").call(receiver,index,value); return value; } } }.call(_receiver,null,_index,_value); } } /** * a[i]++ / a[i]-- * * @param op * "next" for ++, "previous" for --. These names are defined by Groovy. */ public static Object checkedPostfixArray(Object r, Object i, String op) throws Throwable { Object o = checkedGetArray(r, i); Object n = checkedCall(o, false, false, op, new Object[0]); checkedSetArray(r,i,Types.ASSIGN,n); return o; } /** * ++a[i] / --a[i] */ public static Object checkedPrefixArray(Object r, Object i, String op) throws Throwable { Object o = checkedGetArray(r, i); Object n = checkedCall(o, false, false, op, new Object[0]); checkedSetArray(r,i,Types.ASSIGN,n); return n; } /** * a.x++ / a.x-- */ public static Object checkedPostfixProperty(Object receiver, Object property, boolean safe, boolean spread, String op) throws Throwable { Object o = checkedGetProperty(receiver, safe, spread, property); Object n = checkedCall(o, false, false, op, new Object[0]); checkedSetProperty(receiver, property, safe, spread, Types.ASSIGN, n); return o; } /** * ++a.x / --a.x */ public static Object checkedPrefixProperty(Object receiver, Object property, boolean safe, boolean spread, String op) throws Throwable { Object o = checkedGetProperty(receiver, safe, spread, property); Object n = checkedCall(o, false, false, op, new Object[0]); checkedSetProperty(receiver, property, safe, spread, Types.ASSIGN, n); return n; } /** * Intercepts the binary expression of the form {@code lhs op rhs} like {@code lhs+rhs}, {@code lhs>>rhs}, etc. * * In Groovy, binary operators are method calls. * * @param op * One of the binary operators of {@link Types} * @see BinaryExpressionHelper#evaluateBinaryExpressionWithAssignment */ public static Object checkedBinaryOp(Object lhs, int op, Object rhs) throws Throwable { return checkedCall(lhs,false,false,Ops.binaryOperatorMethods(op),new Object[]{rhs}); } /** * A compare method that invokes a.equals(b) or a.compareTo(b)==0 */ public static Object checkedComparison(Object lhs, final int op, Object rhs) throws Throwable { if (lhs==null) {// bypass the checker if lhs is null, as it will not result in any calls that will require protection anyway return InvokerHelper.invokeStaticMethod(ScriptBytecodeAdapter.class, Ops.binaryOperatorMethods(op), new Object[]{lhs,rhs}); } return new SingleArgInvokerChain(lhs) { public Object call(Object lhs, String method, Object rhs) throws Throwable { if (chain.hasNext()) { // based on what ScriptBytecodeAdapter actually does return chain.next().onMethodCall(this, lhs, lhs instanceof Comparable ? "compareTo" : "equals",rhs); } else { return InvokerHelper.invokeStaticMethod(ScriptBytecodeAdapter.class, Ops.binaryOperatorMethods(op), new Object[]{lhs,rhs}); } } }.call(lhs, null, rhs); } /** * Runs {@link ScriptBytecodeAdapter#asType} but only after giving interceptors the chance to reject any possible interface methods as applied to the receiver. * For example, might run {@code receiver.method1(null, false)} and {@code receiver.method2(0, null)} if methods with matching signatures were defined in the interfaces. * @see SandboxTransformer#mightBePositionalArgumentConstructor */ public static Object checkedCast(Class<?> clazz, Object exp, boolean ignoreAutoboxing, boolean coerce, boolean strict) throws Throwable { if (coerce && exp != null && !(Collection.class.isAssignableFrom(clazz) && clazz.getPackage().getName().equals("java.util"))) { if (clazz.isInterface()) { for (Method m : clazz.getMethods()) { Object[] args = new Object[m.getParameterTypes().length]; for (int i = 0; i < args.length; i++) { args[i] = getDefaultValue(m.getParameterTypes()[i]); } // Yes we are deliberately ignoring the return value here: new VarArgInvokerChain(exp) { public Object call(Object receiver, String method, Object... args) throws Throwable { if (chain.hasNext()) { if (receiver instanceof Class) { return chain.next().onStaticCall(this, (Class) receiver, method, args); } else { return chain.next().onMethodCall(this, receiver, method, args); } } else { return null; } } }.call(exp, m.getName(), args); } } else if (!clazz.isArray() && clazz != Object.class && !Modifier.isAbstract(clazz.getModifiers()) && (exp instanceof Collection || exp.getClass().isArray() || exp instanceof Map)) { // cf. mightBePositionalArgumentConstructor Object[] args = null; if (exp instanceof Collection) { args = ((Collection) exp).toArray(); } else if (exp instanceof Map) { args = new Object[] {exp}; } else { // arrays // TODO tricky to determine which constructor will actually be called; array might be expanded, or might not throw new UnsupportedOperationException("casting arrays to types via constructor is not yet supported"); } if (args != null) { // Again we are deliberately ignoring the return value: new VarArgInvokerChain(clazz) { public Object call(Object receiver, String method, Object... args) throws Throwable { if (chain.hasNext()) { return chain.next().onNewInstance(this, (Class) receiver, args); } else { return null; } } }.call(clazz, null, args); } } else if (clazz == File.class && exp instanceof CharSequence) { Object[] args = new Object[]{exp.toString()}; // Again we are deliberately ignoring the return value: new VarArgInvokerChain(clazz) { public Object call(Object receiver, String method, Object... args) throws Throwable { if (chain.hasNext()) { return chain.next().onNewInstance(this, (Class) receiver, args); } else { return null; } } }.call(clazz, null, args); } } // TODO what does ignoreAutoboxing do? return strict ? clazz.cast(exp) : coerce ? ScriptBytecodeAdapter.asType(exp, clazz) : ScriptBytecodeAdapter.castToType(exp, clazz); } @SuppressWarnings("unchecked") private static <T> T getDefaultValue(Class<T> clazz) { return (T) Array.get(Array.newInstance(clazz, 1), 0); } /** * Issue #2 revealed that Groovy can call methods with null in the var-arg array, * when it should be passing an Object array of length 1 with null value. */ private static Object[] fixNull(Object[] args) { return args==null ? new Object[1] : args; } }
package org.lightmare.cache; import java.io.IOException; import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.persistence.EntityManagerFactory; import org.apache.log4j.Logger; import org.lightmare.jndi.JndiManager; import org.lightmare.jpa.JpaManager; import org.lightmare.jpa.datasource.Initializer; import org.lightmare.jpa.datasource.PoolConfig; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.utils.LogUtils; import org.lightmare.utils.NamingUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; /** * Container class to cache connections and connection types * * @author Levan Tsinadze * @since 0.0.65-SNAPSHOT * @see org.lightmare.deploy.BeanLoader#initializeDatasource(org.lightmare.deploy.BeanLoader.DataSourceParameters) * @see org.lightmare.deploy.BeanLoader#loadBean(org.lightmare.deploy.BeanLoader.BeanParameters) * @see org.lightmare.ejb.EjbConnector */ public class ConnectionContainer { // Keeps unique EntityManagerFactories builded by unit names private static final ConcurrentMap<String, ConnectionSemaphore> CONNECTIONS = new ConcurrentHashMap<String, ConnectionSemaphore>(); // Keeps unique PoolConfigs builded by unit names private static final ConcurrentMap<String, PoolProviderType> POOL_CONFIG_TYPES = new ConcurrentHashMap<String, PoolProviderType>(); private static final Logger LOG = Logger .getLogger(ConnectionContainer.class); /** * Checks if connection with passed unit name is cached * * @param unitName * @return <code>boolean</code> */ public static boolean checkForEmf(String unitName) { boolean check = StringUtils.valid(unitName); if (check) { check = CONNECTIONS.containsKey(unitName); } return check; } /** * Gets {@link ConnectionSemaphore} from cache without waiting for lock * * @param unitName * @return {@link ConnectionSemaphore} */ public static ConnectionSemaphore getSemaphore(String unitName) { return CONNECTIONS.get(unitName); } /** * Checks if deployed {@link ConnectionSemaphore} componnents * * @param semaphore * @return <code>boolean</code> */ private static boolean checkOnProgress(ConnectionSemaphore semaphore) { return semaphore.isInProgress() && ObjectUtils.notTrue(semaphore.isBound()); } /** * Creates and locks {@link ConnectionSemaphore} instance * * @param unitName * @return {@link ConnectionSemaphore} */ private static ConnectionSemaphore createSemaphore(String unitName) { ConnectionSemaphore semaphore = CONNECTIONS.get(unitName); ConnectionSemaphore current = null; if (semaphore == null) { semaphore = new ConnectionSemaphore(); semaphore.setUnitName(unitName); semaphore.setInProgress(Boolean.TRUE); semaphore.setCached(Boolean.TRUE); current = CONNECTIONS.putIfAbsent(unitName, semaphore); } if (current == null) { current = semaphore; } current.incrementUser(); return current; } /** * Caches {@link ConnectionSemaphore} with lock * * @param unitName * @param jndiName * @return {@link ConnectionSemaphore} */ public static ConnectionSemaphore cacheSemaphore(String unitName, String jndiName) { ConnectionSemaphore semaphore; // Creates and caches ConnectionSemaphore instance for passed unit and // JNDI names if (StringUtils.valid(unitName)) { semaphore = createSemaphore(unitName); if (StringUtils.valid(jndiName)) { ConnectionSemaphore existent = CONNECTIONS.putIfAbsent( jndiName, semaphore); if (existent == null) { semaphore.setJndiName(jndiName); } } } else { semaphore = null; } return semaphore; } /** * Waits until {@link ConnectionSemaphore} is in progress (locked) * * @param semaphore */ private static void awaitConnection(ConnectionSemaphore semaphore) { synchronized (semaphore) { boolean inProgress = checkOnProgress(semaphore); while (inProgress) { try { semaphore.wait(); inProgress = checkOnProgress(semaphore); } catch (InterruptedException ex) { inProgress = Boolean.FALSE; LOG.error(ex.getMessage(), ex); } } } } /** * Checks if {@link ConnectionSemaphore} is in progress and if it is waits * while lock is released * * @param semaphore * @return <code>boolean</code> */ private static boolean isInProgress(ConnectionSemaphore semaphore) { boolean inProgress = ObjectUtils.notNull(semaphore); if (inProgress) { inProgress = checkOnProgress(semaphore); if (inProgress) { awaitConnection(semaphore); } } return inProgress; } /** * Checks if {@link ConnectionSemaphore#isInProgress()} for appropriated * unit name * * @param jndiName * @return <code>boolean</code> */ public static boolean isInProgress(String jndiName) { boolean inProgress; ConnectionSemaphore semaphore = CONNECTIONS.get(jndiName); inProgress = isInProgress(semaphore); return inProgress; } /** * Gets {@link ConnectionSemaphore} from cache, awaits if connection * instantiation is in progress * * @param unitName * @return {@link ConnectionSemaphore} * @throws IOException */ public static ConnectionSemaphore getConnection(String unitName) throws IOException { ConnectionSemaphore semaphore = CONNECTIONS.get(unitName); isInProgress(semaphore); return semaphore; } /** * Gets {@link EntityManagerFactory} from {@link ConnectionSemaphore}, * awaits if connection * * @param unitName * @return {@link EntityManagerFactory} * @throws IOException */ public static EntityManagerFactory getEntityManagerFactory(String unitName) throws IOException { EntityManagerFactory emf; ConnectionSemaphore semaphore = CONNECTIONS.get(unitName); boolean inProgress = ObjectUtils.notNull(semaphore); if (inProgress) { inProgress = checkOnProgress(semaphore); if (inProgress) { awaitConnection(semaphore); } emf = semaphore.getEmf(); } else { emf = null; } return emf; } /** * Removes connection from {@link javax.naming.Context} cache * * @param semaphore */ private static void unbindConnection(ConnectionSemaphore semaphore) { String jndiName = semaphore.getJndiName(); if (ObjectUtils.notNull(jndiName) && semaphore.isBound()) { JndiManager jndiManager = new JndiManager(); try { String fullJndiName = NamingUtils.createJpaJndiName(jndiName); Object boundData = jndiManager.lookup(fullJndiName); if (ObjectUtils.notNull(boundData)) { jndiManager.unbind(fullJndiName); } } catch (IOException ex) { LogUtils.error(LOG, ex, NamingUtils.COULD_NOT_UNBIND_NAME_ERROR, jndiName, ex.getMessage()); } } } /** * Closes all existing {@link EntityManagerFactory} instances kept in cache */ public static void closeEntityManagerFactories() { Collection<ConnectionSemaphore> semaphores = CONNECTIONS.values(); EntityManagerFactory emf; for (ConnectionSemaphore semaphore : semaphores) { emf = semaphore.getEmf(); JpaManager.closeEntityManagerFactory(emf); } synchronized (CONNECTIONS) { CONNECTIONS.clear(); } } /** * Closes all {@link javax.persistence.EntityManagerFactory} cached * instances * * @throws IOException */ public static void closeConnections() throws IOException { ConnectionContainer.closeEntityManagerFactories(); Initializer.closeAll(); } /** * Closes connection ({@link EntityManagerFactory}) in passed * {@link ConnectionSemaphore} * * @param semaphore */ private static void closeConnection(ConnectionSemaphore semaphore) { int users = semaphore.decrementUser(); // Checks if users (EJB beans) for appropriated ConnectionSemaphore is // less or equals minimal amount to close appropriated connection if (users < ConnectionSemaphore.MINIMAL_USERS) { EntityManagerFactory emf = semaphore.getEmf(); JpaManager.closeEntityManagerFactory(emf); unbindConnection(semaphore); synchronized (CONNECTIONS) { CONNECTIONS.remove(semaphore.getUnitName()); String jndiName = semaphore.getJndiName(); if (StringUtils.valid(jndiName)) { CONNECTIONS.remove(jndiName); semaphore.setBound(Boolean.FALSE); semaphore.setCached(Boolean.FALSE); } } } } /** * Removes {@link ConnectionSemaphore} from cache and unbinds name from * {@link javax.naming.Context} * * @param unitName */ public static void removeConnection(String unitName) { // Removes appropriate connection from cache and JNDI lookup ConnectionSemaphore semaphore = CONNECTIONS.get(unitName); if (ObjectUtils.notNull(semaphore)) { awaitConnection(semaphore); closeConnection(semaphore); } } /** * Caches {@link PoolProviderType} to use for data source deployment * * @param jndiName * @param type */ public static void setPollProviderType(String jndiName, PoolProviderType type) { POOL_CONFIG_TYPES.put(jndiName, type); } /** * Gets configured {@link PoolProviderType} for data sources deployment * * @param jndiName * @return {@link PoolProviderType} */ public static PoolProviderType getAndRemovePoolProviderType(String jndiName) { PoolProviderType type = POOL_CONFIG_TYPES.get(jndiName); if (type == null) { type = new PoolConfig().getPoolProviderType(); POOL_CONFIG_TYPES.put(jndiName, type); } POOL_CONFIG_TYPES.remove(jndiName); return type; } /** * Closes all connections and data sources and clears all cached data * * @throws IOException */ public static void clear() throws IOException { closeConnections(); CONNECTIONS.clear(); POOL_CONFIG_TYPES.clear(); } }
package org.owasp.esapi.waf.rules; import java.util.Collection; import java.util.Enumeration; import java.util.Map; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import org.owasp.esapi.waf.actions.Action; import org.owasp.esapi.waf.actions.DefaultAction; import org.owasp.esapi.waf.actions.DoNothingAction; import org.owasp.esapi.waf.configuration.AppGuardianConfiguration; import org.owasp.esapi.waf.internal.InterceptingHTTPServletRequest; import org.owasp.esapi.waf.internal.InterceptingHTTPServletResponse; public class MustMatchRule extends Rule { private static final String REQUEST_PARAMETERS = "request.parameters."; private static final String REQUEST_HEADERS = "request.headers."; private static final String REQUEST_URI = "request.uri"; private static final String REQUEST_URL = "request.url"; private static final String SESSION_ATTRIBUTES = "session."; private Pattern path; private String variable; private int operator; private String value; public MustMatchRule(String id, Pattern path, String variable, int operator, String value) { this.path = path; this.variable = variable; this.operator = operator; this.value = value; setId(id); } public Action check(HttpServletRequest req, InterceptingHTTPServletResponse response) { InterceptingHTTPServletRequest request = (InterceptingHTTPServletRequest)req; String uri = request.getRequestURI(); if ( ! path.matcher(uri).matches() ) { return new DoNothingAction(); } else { String target = null; /* * First check if we're going to be dealing with request parameters */ if ( variable.startsWith( REQUEST_PARAMETERS ) ) { if ( operator == AppGuardianConfiguration.OPERATOR_EXISTS ) { target = variable.substring(REQUEST_PARAMETERS.length()); if ( request.getParameter(target) != null ) { return new DoNothingAction(); } } else if ( operator == AppGuardianConfiguration.OPERATOR_IN_LIST ) { /* * This doesn't make sense. The variable to test is a request parameter * but the rule is looking for a List. Let the control fall through * to the bottom where we'll return false. */ } else if ( operator == AppGuardianConfiguration.OPERATOR_EQ || operator == AppGuardianConfiguration.OPERATOR_CONTAINS ) { /** * Working with request parameters. If we detect * simple regex characters, we treat it as a regex. * Otherwise we treat it as a single parameter. */ target = variable.substring(REQUEST_PARAMETERS.length()); if ( target.contains("*") || target.contains("?") ) { target = target.replaceAll("*", ".*"); Pattern p = Pattern.compile(target); Enumeration e = request.getParameterNames(); while(e.hasMoreElements()) { String param = (String)e.nextElement(); if ( p.matcher(param).matches() ) { String s = request.getParameter(param); if ( ! RuleUtil.testValue(s, value, operator) ) { log(request, "MustMatch rule failed (operator="+operator+"), value='" + value + "', input='" + s + "' parameter='"+param+"'"); return new DefaultAction(); } } } } else { String s = request.getParameter(target); if ( ! RuleUtil.testValue(s, value, operator) ) { log(request, "MustMatch rule failed (operator="+operator+"), value='" + value + "', input='" + s + "', parameter='"+target+"'"); return new DefaultAction(); } } } } else if ( variable.startsWith( REQUEST_HEADERS ) ) { /** * Do the same for request headers. */ if ( operator == AppGuardianConfiguration.OPERATOR_EXISTS ) { target = variable.substring(REQUEST_HEADERS.length()); if ( request.getHeader(target) != null ) { return new DoNothingAction(); } } else if ( operator == AppGuardianConfiguration.OPERATOR_IN_LIST ) { /* * This doesn't make sense. The variable to test is a request header * but the rule is looking for a List. Let the control fall through * to the bottom where we'll return false. */ } else if ( operator == AppGuardianConfiguration.OPERATOR_EQ || operator == AppGuardianConfiguration.OPERATOR_CONTAINS ) { target = variable.substring(REQUEST_HEADERS.length()); if ( target.contains("*") || target.contains("?") ) { target = target.replaceAll("*", ".*"); Pattern p = Pattern.compile(target); Enumeration e = request.getHeaderNames(); while(e.hasMoreElements()) { String header = (String)e.nextElement(); if ( p.matcher(header).matches() ) { String s = request.getHeader(header); if ( ! RuleUtil.testValue(s, value, operator) ) { log(request, "MustMatch rule failed (operator="+operator+"), value='" + value + "', input='" + s + "', header='"+header+"'"); return new DefaultAction(); } } } } else { String s = request.getHeader(target); if ( s == null || ! RuleUtil.testValue(s, value, operator) ) { log(request, "MustMatch rule failed (operator="+operator+"), value='" + value + "', input='" + s + "', header='"+target+"'"); return new DefaultAction(); } } } } else if ( variable.startsWith(SESSION_ATTRIBUTES) ) { /** * Do the same for session attributes. Can't possibly match * ANY rule if there is no session object. */ if ( request.getSession(false) == null ) { return new DefaultAction(); } target = variable.substring(SESSION_ATTRIBUTES.length()+1); if ( operator == AppGuardianConfiguration.OPERATOR_IN_LIST ) { /* * Want to check if the List/Enumeration/whatever stored * in "target" contains the value in "value". */ Object o = request.getSession(false).getAttribute(target); if ( o instanceof Collection ) { if ( RuleUtil.isInList((Collection)o, value) ) { return new DoNothingAction(); } else { return new DefaultAction(); } } else if ( o instanceof Map ) { if ( RuleUtil.isInList((Map)o, value) ) { return new DoNothingAction(); } else { return new DefaultAction(); } } else if ( o instanceof Enumeration ) { if ( RuleUtil.isInList((Enumeration)o, value) ) { return new DoNothingAction(); } else { return new DefaultAction(); } } /* * The attribute was not a common list-type of Java object s * let the control fall through to the bottom where it will * fail. */ } else if ( operator == AppGuardianConfiguration.OPERATOR_EXISTS) { Object o = request.getSession(false).getAttribute(target); if ( o != null ) { return new DoNothingAction(); } else { return new DefaultAction(); } } else if ( operator == AppGuardianConfiguration.OPERATOR_EQ || operator == AppGuardianConfiguration.OPERATOR_CONTAINS ) { if ( target.contains("*") || target.contains("?") ) { target = target.replaceAll("*", ".*"); Pattern p = Pattern.compile(target); Enumeration e = request.getSession(false).getAttributeNames(); while(e.hasMoreElements()) { String attr = (String)e.nextElement(); if (p.matcher(attr).matches() ) { Object o = request.getSession(false).getAttribute(attr); if ( ! RuleUtil.testValue((String)o, value, operator) ) { return new DefaultAction(); } } } } else { Object o = request.getSession(false).getAttribute(target); if ( ! RuleUtil.testValue((String)o, value, operator) ) { return new DefaultAction(); } } } } else if ( variable.equals( REQUEST_URI ) ) { if ( operator == AppGuardianConfiguration.OPERATOR_EQ || operator == AppGuardianConfiguration.OPERATOR_CONTAINS ) { if ( RuleUtil.testValue(request.getRequestURI(), value, operator) ) { return new DoNothingAction(); } else { return new DefaultAction(); } } /* * Any other operator doesn't make sense. */ } else if ( variable.equals( REQUEST_URL ) ) { if ( operator == AppGuardianConfiguration.OPERATOR_EQ || operator == AppGuardianConfiguration.OPERATOR_CONTAINS ) { if ( RuleUtil.testValue(request.getRequestURL().toString(), value, operator) ) { return new DoNothingAction(); } else { return new DefaultAction(); } } /* * Any other operator doesn't make sense. */ } } log(request, "MustMatch rule failed on URL '" + request.getRequestURL() + "'"); return new DefaultAction(); } }
package org.spongepowered.api.util; import java.util.UUID; /** * An identifiable object has a UUID that can be retrieved. */ public interface Identifiable { /** * Gets the unique ID for this object. * * @return The {@link UUID} */ UUID getUniqueId(); /** * Checks if this is a flowerpot. * * @return Whether this is a flowerpot */ boolean isFlowerPot(); }
package org.threeten.extra.chrono; import java.io.Serializable; import java.time.DateTimeException; import java.time.chrono.AbstractChronology; import java.time.chrono.Era; import java.time.temporal.ChronoField; import java.time.temporal.TemporalAccessor; import java.time.temporal.ValueRange; import java.util.Arrays; import java.util.List; public final class PaxChronology extends AbstractChronology implements Serializable { /** * Singleton instance of the Pax chronology. */ public static final PaxChronology INSTANCE = new PaxChronology(); /** * The leap-month of Pax is only one week long. */ private static final int WEEKS_IN_LEAP_MONTH = 1; /** * Standard 7-day week. */ static final int DAYS_IN_WEEK = 7; /** * In all months (except Pax), there are 4 complete weeks. */ private static final int WEEKS_IN_MONTH = 4; /** * There are 13 months in a (non-leap) year. */ static final int MONTHS_IN_YEAR = 13; /** * There are 4 weeks of 7 days, or 28 total days in a month. */ static final int DAYS_IN_MONTH = WEEKS_IN_MONTH * DAYS_IN_WEEK; /** * There are 13 months of 28 days, or 364 days in a (non-leap) year. */ static final int DAYS_IN_YEAR = MONTHS_IN_YEAR * DAYS_IN_MONTH; /** * There are 52 weeks in a (non-leap) year. */ private static final int WEEKS_IN_YEAR = DAYS_IN_YEAR / DAYS_IN_WEEK; /** * Serialization version. */ private static final long serialVersionUID = -7021464635577802085L; /** * Restricted constructor. */ private PaxChronology() { } /** * Obtains a local date in Pax calendar system from the * era, year-of-era, month-of-year and day-of-month fields. * * @param era the Pax era, not null * @param yearOfEra the year-of-era * @param month the month-of-year * @param dayOfMonth the day-of-month * @return the Pax local date, not null * @throws DateTimeException if unable to create the date * @throws ClassCastException if the {@code era} is not a {@code PaxEra} */ @Override public PaxDate date(Era era, int yearOfEra, int month, int dayOfMonth) { return date(prolepticYear(era, yearOfEra), month, dayOfMonth); } @Override public PaxDate date(final int prolepticYear, final int month, final int dayOfMonth) { return PaxDate.of(prolepticYear, month, dayOfMonth); } @Override public PaxDate date(final TemporalAccessor temporal) { return PaxDate.from(temporal); } @Override public PaxDate dateEpochDay(final long epochDay) { return PaxDate.ofEpochDay(epochDay); } @Override public PaxDate dateYearDay(final int prolepticYear, final int dayOfYear) { return PaxDate.ofYearDay(prolepticYear, dayOfYear); } @Override public PaxEra eraOf(final int era) { return PaxEra.of(era); } @Override public List<Era> eras() { return Arrays.<Era> asList(PaxEra.values()); } @Override public String getCalendarType() { return null; } @Override public String getId() { return "Pax"; } /** * Checks if the year is a leap year, according to the Pax proleptic calendar system rules. * <p> * This method applies the current rules for leap years across the whole time-line. In general, a year is a leap year if the last two digits are divisible * by 6 without remainder, or are 99. Years with the last two digits of 00 are also leap years, with the exception of years divisible by 400 which are not. * <p> * For example, 2012 is a leap year becuase the last two digits (12) are divisible by 6. 1999 is a leap year as the last two digits are both 9's (99). 1900 * is a leap year as the last two digits are both 0's (00), however 2000 was not a leap year as it is divisible by 400. The year 0 is not a leap year. * <p> * The calculation is proleptic - applying the same rules into the far future and far past. * * @param prolepticYear * the Pax proleptic year to check * @return true if the year is leap, false otherwise */ @Override @SuppressWarnings("checkstyle:magicnumber") public boolean isLeapYear(final long prolepticYear) { final long lastTwoDigits = prolepticYear % 100; return lastTwoDigits == 99 || (lastTwoDigits % 6 == 0) || (lastTwoDigits == 0 && prolepticYear % 400 != 0); } @Override public int prolepticYear(final Era era, final int yearOfEra) { if (!(era instanceof PaxEra)) { throw new ClassCastException("Era must be PaxEra"); } return (era == PaxEra.CE ? yearOfEra : 1 - yearOfEra); } @Override public ValueRange range(final ChronoField field) { switch (field) { case ALIGNED_WEEK_OF_MONTH: return ValueRange.of(1, WEEKS_IN_LEAP_MONTH, WEEKS_IN_MONTH); case ALIGNED_WEEK_OF_YEAR: return ValueRange.of(1, WEEKS_IN_YEAR, WEEKS_IN_YEAR + 1); case DAY_OF_MONTH: return ValueRange.of(1, DAYS_IN_WEEK, DAYS_IN_MONTH); case DAY_OF_YEAR: return ValueRange.of(1, DAYS_IN_YEAR, DAYS_IN_YEAR + DAYS_IN_WEEK); case MONTH_OF_YEAR: return ValueRange.of(1, MONTHS_IN_YEAR, MONTHS_IN_YEAR + 1); default: return field.range(); } } /** * Resolve singleton. * * @return the singleton instance, not null */ private Object readResolve() { return INSTANCE; } }
package de.gurkenlabs.litiengine.resources; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; public class DataFormatTests { @ParameterizedTest @MethodSource("getImageFormat") public void testImageFormat(String fileName, boolean assertValue) { assertEquals(ImageFormat.isSupported(fileName), assertValue); String[] expected = new String[] { "gif", "png", "jpg", "bmp" }; for (String actual : ImageFormat.getAllExtensions()) { assertTrue(Arrays.stream(expected).anyMatch(actual::equals)); } } private static Stream<Arguments> getImageFormat() { return Stream.of( Arguments.of("test.gif", true), Arguments.of("test.png", true), Arguments.of("test.jpg", true), Arguments.of("test.bmp", true), Arguments.of("test.test", false), Arguments.of("test.undefined", false) ); } @Test public void testAudioFormat() { assertTrue(SoundFormat.isSupported("test.ogg")); assertTrue(SoundFormat.isSupported("test.mp3")); assertTrue(SoundFormat.isSupported("test.wav")); assertFalse(SoundFormat.isSupported("test.test")); assertFalse(SoundFormat.isSupported("test.undefined")); String[] expected = new String[] { "ogg", "mp3", "wav" }; for (String actual : SoundFormat.getAllExtensions()) { assertTrue(Arrays.stream(expected).anyMatch(actual::equals)); } } }
package pl.hycom.pip.messanger; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.messenger4j.MessengerPlatform; import com.github.messenger4j.exceptions.MessengerApiException; import com.github.messenger4j.exceptions.MessengerIOException; import com.github.messenger4j.send.MessengerSendClient; import lombok.extern.log4j.Log4j2; import okhttp3.*; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import pl.hycom.model.MessageRequestBody; import pl.hycom.model.MessageResponse; import javax.ws.rs.core.*; import javax.ws.rs.core.MediaType; import java.io.IOException; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static org.springframework.web.bind.annotation.RequestMethod.POST; import org.apache.commons.lang3.StringUtils; @Controller @Log4j2 public class WebhookMessenger { //Temporary for testing, acessToken must is different for each user private final String accessToken = "EAASEpnxfYrwBAK7MZAPvt0awlzY8Ph8yDTHVe41QnBJDflZAgBQxD5U6T2Y6AG3z8nKTswiF5qPIevrZA8ftjoHRHQZABCCzcgWxwrOUBAU5ZBoQZA4IuHo1prqzZCgGZBIF1N07gdORcU9cVbLcScLUNAYccwTl67Dk40UMZClI6QQZDZD"; @RequestMapping(value = "/webhook", method = GET, produces = MediaType.TEXT_PLAIN) @ResponseBody public String verify(@RequestParam("hub.verify_token") final String verifyToken, @RequestParam("hub.mode") final String mode, @RequestParam("hub.challenge") final String challenge){ if (StringUtils.equals(verifyToken,"token") && StringUtils.equals(mode,"subscribe")){ return challenge; } else { return "Failed validation. Make sure the validation tokens match."; } } @RequestMapping(value = "/webhook", method = POST, consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON) public void sendMessage(@RequestBody final MessageRequestBody body) { if(StringUtils.equals(body.object,"page")) { for(MessageRequestBody.Entry entry : body.entry) { String pageID=entry.id; String time=entry.time; for(MessageRequestBody.Messaging messaging : entry.messaging) { if(messaging!=null) { receivedMessage(messaging); } else { log.info("Webhook received unknown event: "); } } } } // try { // for (MessageRequestBody.Entry entry : body.entry) { // for (MessageRequestBody.Messaging messaging : entry.messaging) { // MessageResponse messageResponse = new MessageResponse(); // messageResponse.recipient = new MessageResponse.Recipient(); // messageResponse.recipient.id = messaging.sender.id; // messageResponse.message = new MessageResponse.MessageData(); // if (messaging.message != null && messaging.message.text != null) { // messageResponse.message.text = "Hello World!"; // ObjectMapper objectMapper = new ObjectMapper(); // String responseString = objectMapper.writeValueAsString(messageResponse); // okhttp3.RequestBody requestBody = okhttp3.RequestBody. // create(okhttp3.MediaType.parse("application/json; charset=utf-8"), responseString); // Request request = new Request.Builder(). // post(requestBody).build(); // OkHttpClient client = new OkHttpClient(); // Response response = client.newCall(request).execute(); // log.info("Sending response:"); // log.info(response.toString()); // } catch (IOException e) { // e.printStackTrace(); } private void receivedMessage(MessageRequestBody.Messaging messaging ) { if(messaging.message.text!=null) { sendTextMessage(messaging.sender.id, messaging.message.text); } } private void sendTextMessage(String id,String message) { MessageResponse messageResponse=new MessageResponse(); messageResponse.recipient.id=id; messageResponse.message.text=message; callSendApi(messageResponse); } private void callSendApi(MessageResponse messageResponse) { MessengerSendClient sendClient = MessengerPlatform.newSendClientBuilder(accessToken).build(); try { sendClient.sendTextMessage(messageResponse.recipient.id, messageResponse.message.text); } catch (MessengerApiException | MessengerIOException e) { e.printStackTrace(); } } }
package romelo333.notenoughwands; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.apache.logging.log4j.Logger; import romelo333.notenoughwands.proxy.CommonProxy; import java.io.File; @Mod(modid = NotEnoughWands.MODID, name="Not Enough Wands", dependencies = "required-after:Forge@["+ NotEnoughWands.MIN_FORGE_VER+",)", version = NotEnoughWands.VERSION) public class NotEnoughWands { public static final String MODID = "notenoughwands"; public static final String VERSION = "1.2.3"; public static final String MIN_FORGE_VER = "11.15.0.1600"; @SidedProxy(clientSide="romelo333.notenoughwands.proxy.ClientProxy", serverSide="romelo333.notenoughwands.proxy.ServerProxy") public static CommonProxy proxy; @Mod.Instance("NotEnoughWands") public static NotEnoughWands instance; public static Logger logger; public static File mainConfigDir; public static File modConfigDir; public static Configuration config; public static CreativeTabs tabNew = new CreativeTabs("NotEnoughWands") { @Override @SideOnly(Side.CLIENT) public Item getTabIconItem() { return ModItems.teleportationWand; } }; /** * Run before anything else. Read your config, create blocks, items, etc, and * register them with the GameRegistry. */ @Mod.EventHandler public void preInit(FMLPreInitializationEvent e) { logger = e.getModLog(); mainConfigDir = e.getModConfigurationDirectory(); modConfigDir = new File(mainConfigDir.getPath()); config = new Configuration(new File(modConfigDir, "notenoughwands.cfg")); proxy.preInit(e); // FMLInterModComms.sendMessage("Waila", "register", "mcjty.wailasupport.WailaCompatibility.load"); } /** * Do your mod setup. Build whatever data structures you care about. Register recipes. */ @Mod.EventHandler public void init(FMLInitializationEvent e) { proxy.init(e); } /** * Handle interaction with other mods, complete your setup based on this. */ @Mod.EventHandler public void postInit(FMLPostInitializationEvent e) { proxy.postInit(e); } }
package seedu.todo.controllers; import java.time.LocalDateTime; import java.util.HashMap; import java.util.Map; import seedu.todo.commons.EphemeralDB; import seedu.todo.commons.exceptions.ParseException; import seedu.todo.commons.util.DateUtil; import seedu.todo.commons.util.ParseUtil; import seedu.todo.commons.util.StringUtil; import seedu.todo.controllers.concerns.Renderer; import seedu.todo.controllers.concerns.Tokenizer; import seedu.todo.models.CalendarItem; import seedu.todo.models.Event; import seedu.todo.models.Task; import seedu.todo.models.TodoListDB; /** * Controller to update a CalendarItem. * * @@author A0139922Y */ public class UpdateController implements Controller { private static final String NAME = "Update"; private static final String DESCRIPTION = "Updates a task by listed index."; private static final String COMMAND_SYNTAX = "update <index> <task/event> by <deadline>"; private static final String UPDATE_EVENT_SYNTAX = "update <index> <name> event from <date/time> to <date/time>"; private static final String UPDATE_TASK_SYNTAX = "update <index> <name> task on <date/time>"; private static final String COMMAND_WORD = "update"; private static final String MESSAGE_INDEX_OUT_OF_RANGE = "Could not update task/event: Invalid index provided!"; private static final String MESSAGE_MISSING_INDEX_AND_PARAMETERS = "Please specify the index of the item and details to update."; private static final String MESSAGE_INDEX_NOT_NUMBER = "Index has to be a number!"; private static final String MESSAGE_INVALID_ITEMTYPE = "Unable to update!\nTry updating with the syntax provided!"; private static final String MESSAGE_DATE_CONFLICT = "Unable to update!\nMore than 1 date criteria is provided!"; private static final String MESSAGE_NO_DATE_DETECTED = "Unable to update!\nThe natural date entered is not supported."; private static final String MESSAGE_UPDATE_SUCCESS = "Item successfully updated!"; private static final int COMMAND_INPUT_INDEX = 0; private static final int TOKENIZER_DEFAULT_INDEX = 1; private static final int ITEM_INDEX = 0; //use to access parsing of dates private static final int NUM_OF_DATES_FOUND_INDEX = 0; private static final int DATE_ON_INDEX = 1; private static final int DATE_FROM_INDEX = 2; private static final int DATE_TO_INDEX = 3; private static CommandDefinition commandDefinition = new CommandDefinition(NAME, DESCRIPTION, COMMAND_SYNTAX); public static CommandDefinition getCommandDefinition() { return commandDefinition; } @Override public float inputConfidence(String input) { return (StringUtil.splitStringBySpace(input.toLowerCase())[COMMAND_INPUT_INDEX]).equals(COMMAND_WORD) ? 1 : 0; } /** * Get the token definitions for use with <code>tokenizer</code>.<br> * This method exists primarily because Java does not support HashMap * literals... * * @return tokenDefinitions */ private static Map<String, String[]> getTokenDefinitions() { Map<String, String[]> tokenDefinitions = new HashMap<String, String[]>(); tokenDefinitions.put("default", new String[] {"update"}); //tokenDefinitions.put("eventType", new String[] { "event", "events", "task", "tasks"}); //tokenDefinitions.put("taskStatus", new String[] { "complete" , "completed", "incomplete", "incompleted"}); tokenDefinitions.put("time", new String[] { "at", "by", "on", "time", "date" }); tokenDefinitions.put("timeFrom", new String[] { "from" }); tokenDefinitions.put("timeTo", new String[] { "to", "before", "until" }); tokenDefinitions.put("itemName", new String[] { "name" }); tokenDefinitions.put("tagName", new String [] { "tag" }); return tokenDefinitions; } @Override public void process(String input) throws ParseException { input = input.replaceFirst(COMMAND_WORD, ""); if (input.length() <= 0) { Renderer.renderDisambiguation(COMMAND_SYNTAX, MESSAGE_MISSING_INDEX_AND_PARAMETERS); return; } int index = 0; String params = null; try { index = Integer.decode(StringUtil.splitStringBySpace(input)[ITEM_INDEX]); params = input.replaceFirst(Integer.toString(index), "").trim(); params = COMMAND_WORD + " " + params; } catch (NumberFormatException e) { Renderer.renderDisambiguation(COMMAND_SYNTAX, MESSAGE_INDEX_NOT_NUMBER); return; } Map<String, String[]> parsedResult; parsedResult = Tokenizer.tokenize(getTokenDefinitions(), params); String itemName = parsedResult.get("default")[TOKENIZER_DEFAULT_INDEX]; if (ParseUtil.getTokenResult(parsedResult, "itemName") != null && itemName != null) { itemName = itemName + ParseUtil.getTokenResult(parsedResult, "itemName"); } else if (itemName == null) { itemName = ParseUtil.getTokenResult(parsedResult, "itemName"); } String[] parsedDates = ParseUtil.parseDates(parsedResult); //no details provided to update if (parsedDates == null && itemName == null) { Renderer.renderDisambiguation(UPDATE_TASK_SYNTAX, MESSAGE_INVALID_ITEMTYPE); return ; } int numOfDatesFound = 0; LocalDateTime dateOn = null; LocalDateTime dateFrom = null; LocalDateTime dateTo = null; if (parsedDates != null) { numOfDatesFound = Integer.parseInt(parsedDates[NUM_OF_DATES_FOUND_INDEX]); String naturalOn = parsedDates[DATE_ON_INDEX]; String naturalFrom = parsedDates[DATE_FROM_INDEX]; String naturalTo = parsedDates[DATE_TO_INDEX]; if (naturalOn != null && numOfDatesFound > 1) { //date conflict detected Renderer.renderDisambiguation(COMMAND_SYNTAX, MESSAGE_DATE_CONFLICT); return; } // Parse natural date using Natty. dateOn = naturalOn == null ? null : DateUtil.parseNatural(naturalOn); dateFrom = naturalFrom == null ? null : DateUtil.parseNatural(naturalFrom); dateTo = naturalTo == null ? null : DateUtil.parseNatural(naturalTo); } if (parsedDates != null && dateOn == null && dateFrom == null && dateTo == null) { //Natty failed to parse date Renderer.renderDisambiguation(COMMAND_SYNTAX, MESSAGE_NO_DATE_DETECTED); return ; } // Get record EphemeralDB edb = EphemeralDB.getInstance(); CalendarItem calendarItem = edb.getCalendarItemsByDisplayedId(index); TodoListDB db = TodoListDB.getInstance(); if (calendarItem == null) { Renderer.renderDisambiguation(COMMAND_SYNTAX, MESSAGE_INDEX_OUT_OF_RANGE); return; } boolean isCalendarItemTask = calendarItem instanceof Task; //update task date , error found if (isCalendarItemTask && dateOn == null && numOfDatesFound > 0) { Renderer.renderDisambiguation(UPDATE_TASK_SYNTAX, MESSAGE_INVALID_ITEMTYPE); return ; } //update event date , error found if (!isCalendarItemTask && (dateFrom == null || dateTo == null) && numOfDatesFound > 0) { Renderer.renderDisambiguation(UPDATE_EVENT_SYNTAX, MESSAGE_INVALID_ITEMTYPE); return ; } updateCalendarItem(itemName, dateOn, dateFrom, dateTo, calendarItem, isCalendarItemTask); db.save(); // Re-render Renderer.renderIndex(db, MESSAGE_UPDATE_SUCCESS); } /* * Update calendarItem according to user input * */ private void updateCalendarItem(String itemName, LocalDateTime dateOn, LocalDateTime dateFrom, LocalDateTime dateTo, CalendarItem calendarItem, boolean isCalendarItemTask) { //update name if (itemName != null) { calendarItem.setName(itemName); } //update task date if (isCalendarItemTask && dateOn != null) { calendarItem.setCalendarDT(DateUtil.parseTimeStamp(dateOn, dateTo, true)); } //update event date if (dateFrom != null && dateTo !=null && !isCalendarItemTask) { LocalDateTime parsedDateFrom = DateUtil.parseTimeStamp(dateFrom, dateTo, true); LocalDateTime parsedDateTo = DateUtil.parseTimeStamp(dateTo, dateFrom, false); dateFrom = parsedDateFrom; dateTo = parsedDateTo; Event event = (Event) calendarItem; event.setStartDate(dateFrom); event.setEndDate(dateTo); } } }
package stream.flarebot.flarebot.mod; import io.netty.util.internal.ConcurrentSet; import net.dv8tion.jda.core.entities.Member; import stream.flarebot.flarebot.mod.modlog.ModlogAction; import stream.flarebot.flarebot.mod.modlog.ModlogEvent; import stream.flarebot.flarebot.objects.GuildWrapper; import java.util.Iterator; import java.util.Set; public class Moderation { // Having this as something like a Map<Long, Set<ModlogAction>> and having that as the channel ID would make a // little more sense memory wise but efficiency wise it is much better to get the channel from the action itself. private Set<ModlogAction> enabledActions; /** * Check if the passed channel ID is a "valid", this means that the channel ID belongs to that guild and that it * still is a valid channel. * * @param wrapper GuildWrapper that needs to be checked * @param channelId The channel ID that should belong to that guild. * @return If the channel ID is valid and belongs to the associated Guild. */ private boolean isValidChannelId(GuildWrapper wrapper, long channelId) { return wrapper.getGuild().getTextChannelById(channelId) != null; } /** * This is a map of the enabled modlog actions and which channel they post to. * This will never be an none-set channel (-1). * * @return The map of channelId(s) and actions to log to them channels. */ public Set<ModlogAction> getEnabledActions() { if (enabledActions == null) enabledActions = new ConcurrentSet<>(); return enabledActions; } public boolean isEventEnabled(GuildWrapper wrapper, ModlogEvent event) { for (ModlogAction action : getEnabledActions()) { if (action.getEvent() == event) { if (isValidChannelId(wrapper, action.getModlogChannelId())) return true; else { getEnabledActions().remove(action); return false; } } } return false; } /** * Enable an event, the channel passed here cannot be -1 or an invalid channel ID. * If the channel ID is invalid or the channel ID does not belong to the Guild that is associated ith the * GuildWrapper passed then this method will return false. * * @param wrapper GuildWrapper of the executed guild. * @param channelId The channel ID that the user wants the event enabled in. * @param event The Event to be enabled and set in a certain channel. * @return This will either return true or false which indicated if it was successful. */ public boolean enableEvent(GuildWrapper wrapper, long channelId, ModlogEvent event) { return channelId != -1 && isValidChannelId(wrapper, channelId) && getEnabledActions().add(event.getAction(channelId)); } public void enableAllEvents(GuildWrapper wrapper, long channelId) { for (ModlogEvent event : ModlogEvent.values) enableEvent(wrapper, channelId, event); } public void enableDefaultEvents(GuildWrapper guild, long channelId) { for (ModlogEvent event : ModlogEvent.values) { if (event.isDefaultEvent()) enableEvent(guild, channelId, event); } } public void disableEvent(ModlogEvent event) { for (ModlogAction action : getEnabledActions()) { if (action.getEvent() == event) getEnabledActions().remove(action); } } public void disableAllEvents() { this.enabledActions = new ConcurrentSet<>(); } public void disableDefaultEvents() { for (ModlogEvent event : ModlogEvent.values) { if (event.isDefaultEvent()) disableEvent(event); } } public boolean isEventCompacted(ModlogEvent modlogEvent) { for (ModlogAction action : getEnabledActions()) { if (action.getEvent() == modlogEvent) return action.isCompacted(); } return false; } public boolean setEventCompact(ModlogEvent modlogEvent, boolean b) { for (ModlogAction action : getEnabledActions()) if (action.getEvent() == modlogEvent) action.setCompacted(b); return b; } public void muteUser(GuildWrapper guild, Member member) { if (guild.getMutedRole() != null) guild.getGuild().getController().addRolesToMember(member, guild.getMutedRole()).queue(); } }
package su.litvak.chromecast.api.v2; import org.codehaus.jackson.annotate.JsonProperty; public class MediaStatus { public enum PlayerState { IDLE, BUFFERING, PLAYING, PAUSED } public final long mediaSessionId; public final int playbackRate; public final PlayerState playerState; public final float currentTime; public final int supportedMediaCommands; public final Volume volume; public final Media media; MediaStatus(@JsonProperty("mediaSessionId") long mediaSessionId, @JsonProperty("playbackRate") int playbackRate, @JsonProperty("playerState") PlayerState playerState, @JsonProperty("currentTime") float currentTime, @JsonProperty("supportedMediaCommands") int supportedMediaCommands, @JsonProperty("volume") Volume volume, @JsonProperty("media") Media media) { this.mediaSessionId = mediaSessionId; this.playbackRate = playbackRate; this.playerState = playerState; this.currentTime = currentTime; this.supportedMediaCommands = supportedMediaCommands; this.volume = volume; this.media = media; } }
package tonius.simplyjetpacks.item.meta; import java.util.List; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.EnumRarity; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ChatComponentText; import net.minecraft.world.World; import net.minecraftforge.common.config.Configuration; import tonius.simplyjetpacks.client.model.PackModelType; import tonius.simplyjetpacks.config.Config; import tonius.simplyjetpacks.handler.SyncHandler; import tonius.simplyjetpacks.item.ItemPack; import tonius.simplyjetpacks.setup.ParticleType; import tonius.simplyjetpacks.util.StackUtils; import tonius.simplyjetpacks.util.StringUtils; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class Jetpack extends PackBase { protected static final String TAG_HOVERMODE_ON = "JetpackHoverModeOn"; protected static final String TAG_EHOVER_ON = "JetpackEHoverOn"; protected static final String TAG_PARTICLE = "JetpackParticleType"; public double speedVertical = 0.0D; public double accelVertical = 0.0D; public double speedVerticalHover = 0.0D; public double speedVerticalHoverSlow = 0.0D; public double speedSideways = 0.0D; public double sprintSpeedModifier = 0.0D; public double sprintFuelModifier = 0.0D; public boolean emergencyHoverMode = false; public ParticleType defaultParticleType = ParticleType.DEFAULT; public Jetpack(int tier, EnumRarity rarity, String defaultConfigKey) { super("jetpack", tier, rarity, defaultConfigKey); this.setArmorModel(PackModelType.JETPACK); } public Jetpack setDefaultParticleType(ParticleType defaultParticleType) { this.defaultParticleType = defaultParticleType; return this; } @Override public void tickArmor(World world, EntityPlayer player, ItemStack stack, ItemPack item) { this.flyUser(player, stack, item, false); } public void flyUser(EntityLivingBase user, ItemStack stack, ItemPack item, boolean force) { if (this.isOn(stack)) { boolean hoverMode = this.isHoverModeOn(stack); double hoverSpeed = Config.invertHoverSneakingBehavior == SyncHandler.isDescendKeyDown(user) ? this.speedVerticalHoverSlow : this.speedVerticalHover; boolean flyKeyDown = force || SyncHandler.isFlyKeyDown(user); boolean descendKeyDown = SyncHandler.isDescendKeyDown(user); double currentAccel = user.motionY < 0.3D ? this.accelVertical * 2.5 : this.accelVertical; if (flyKeyDown || hoverMode && !user.onGround) { if (this.usesFuel) { item.useFuel(stack, (int) (user.isSprinting() ? Math.round(this.fuelUsage * this.sprintFuelModifier) : this.fuelUsage), false); } if (item.getFuelStored(stack) > 0) { if (flyKeyDown) { if (!hoverMode) { user.motionY = Math.min(user.motionY + currentAccel, this.speedVertical); } else { if (descendKeyDown) { user.motionY = Math.min(user.motionY + currentAccel, -this.speedVerticalHoverSlow); } else { user.motionY = Math.min(user.motionY + currentAccel, this.speedVerticalHover); } } } else { user.motionY = Math.min(user.motionY + currentAccel, -hoverSpeed); } float speedSideways = (float) (user.isSneaking() ? this.speedSideways * 0.5F : this.speedSideways); float speedForward = (float) (user.isSprinting() ? speedSideways * this.sprintSpeedModifier : speedSideways); if (SyncHandler.isForwardKeyDown(user)) { user.moveFlying(0, speedForward, speedForward); } if (SyncHandler.isBackwardKeyDown(user)) { user.moveFlying(0, -speedSideways, speedSideways * 0.8F); } if (SyncHandler.isLeftKeyDown(user)) { user.moveFlying(speedSideways, 0, speedSideways); } if (SyncHandler.isRightKeyDown(user)) { user.moveFlying(-speedSideways, 0, speedSideways); } if (!user.worldObj.isRemote) { user.fallDistance = 0.0F; if (user instanceof EntityPlayerMP) { ((EntityPlayerMP) user).playerNetServerHandler.floatingTickCount = 0; } } } } } if (!user.worldObj.isRemote && this.emergencyHoverMode && this.isEHoverOn(stack)) { if (item.getEnergyStored(stack) > 0 && (!this.isHoverModeOn(stack) || !this.isOn(stack))) { if (user.posY < -5) { this.doEHover(stack, user); } else if (user instanceof EntityPlayer) { if (!((EntityPlayer) user).capabilities.isCreativeMode && user.fallDistance - 1.2F >= user.getHealth()) { for (int i = 0; i <= 16; i++) { if (!user.worldObj.isAirBlock(Math.round((float) user.posX - 0.5F), Math.round((float) user.posY) - i, Math.round((float) user.posZ - 0.5F))) { this.doEHover(stack, user); break; } } } } } } } public void doEHover(ItemStack armor, EntityLivingBase user) { StackUtils.getNBT(armor).setBoolean(TAG_ON, true); StackUtils.getNBT(armor).setBoolean(TAG_HOVERMODE_ON, true); if (user instanceof EntityPlayer) { ((EntityPlayer) user).addChatMessage(new ChatComponentText(StringUtils.LIGHT_RED + StringUtils.translate("chat.jetpack.emergencyHoverMode.msg"))); } } public void setMobMode(ItemStack itemStack) { itemStack.stackTagCompound.setBoolean("JetpackOn", true); itemStack.stackTagCompound.setBoolean("JetpackHoverModeOn", false); } public boolean isHoverModeOn(ItemStack stack) { return StackUtils.getNBTBoolean(stack, TAG_HOVERMODE_ON, false); } public boolean isEHoverOn(ItemStack stack) { return StackUtils.getNBTBoolean(stack, TAG_EHOVER_ON, true); } @Override public void switchMode(ItemStack stack, EntityPlayer player, boolean sneakChangesToggleBehavior, boolean showInChat) { if (!player.isSneaking() || !this.emergencyHoverMode || !sneakChangesToggleBehavior) { this.switchHoverMode(stack, player, showInChat); } else { this.switchEHover(stack, player); } } protected void switchHoverMode(ItemStack stack, EntityPlayer player, boolean showInChat) { this.toggleState(this.isHoverModeOn(stack), stack, "hoverMode", TAG_HOVERMODE_ON, player, showInChat); } public void switchEHover(ItemStack stack, EntityPlayer player) { this.toggleState(this.isEHoverOn(stack), stack, "emergencyHoverMode", TAG_EHOVER_ON, player, true); } public void setParticleType(ItemStack stack, ParticleType particle) { StackUtils.getNBT(stack).setInteger(TAG_PARTICLE, particle.ordinal()); } protected ParticleType getParticleType(ItemStack stack) { if (stack.stackTagCompound != null && stack.stackTagCompound.hasKey(TAG_PARTICLE)) { int particle = StackUtils.getNBT(stack).getInteger(TAG_PARTICLE); ParticleType particleType = ParticleType.values()[particle]; if (particleType != null) { return particleType; } } StackUtils.getNBT(stack).setInteger(TAG_PARTICLE, this.defaultParticleType.ordinal()); return this.defaultParticleType; } public ParticleType getDisplayParticleType(ItemStack stack, ItemPack item, EntityLivingBase user) { boolean flyKeyDown = SyncHandler.isFlyKeyDown(user); if (this.isOn(stack) && item.getFuelStored(stack) > 0 && (flyKeyDown || this.isHoverModeOn(stack) && !user.onGround && user.motionY < 0)) { return this.getParticleType(stack); } return null; } @Override @SideOnly(Side.CLIENT) public void addShiftInformation(ItemStack stack, ItemPack item, EntityPlayer player, List list) { list.add(StringUtils.getStateText(this.isOn(stack))); list.add(StringUtils.getHoverModeText(this.isHoverModeOn(stack))); if (this.fuelUsage > 0) { list.add(StringUtils.getFuelUsageText(this.fuelType, this.fuelUsage)); } list.add(StringUtils.getArmoredText(this.isArmored)); list.add(StringUtils.getParticlesText(this.getParticleType(stack))); StringUtils.addDescriptionLines(list, "jetpack", StringUtils.BRIGHT_GREEN); } @Override @SideOnly(Side.CLIENT) public String getHUDStatesInfo(ItemStack stack, ItemPack item) { Boolean engine = this.isOn(stack); Boolean hover = this.isHoverModeOn(stack); return StringUtils.getHUDStateText(engine, hover, null); } // start configuration @Override protected void loadConfig(Configuration config) { super.loadConfig(config); if (this.defaults.speedVertical != null) { this.speedVertical = config.get(this.defaults.section.name, "Vertical Speed", this.defaults.speedVertical, "The maximum vertical speed of this jetpack when flying.").setMinValue(0.0D).getDouble(this.defaults.speedVertical); } if (this.defaults.accelVertical != null) { this.accelVertical = config.get(this.defaults.section.name, "Vertical Acceleration", this.defaults.accelVertical, "The vertical acceleration of this jetpack when flying; every tick, this amount of vertical speed will be added until maximum speed is reached.").setMinValue(0.0D).getDouble(this.defaults.accelVertical); } if (this.defaults.speedVerticalHover != null) { this.speedVerticalHover = config.get(this.defaults.section.name, "Vertical Speed (Hover Mode)", this.defaults.speedVerticalHover, "The maximum vertical speed of this jetpack when flying in hover mode.").setMinValue(0.0D).getDouble(this.defaults.speedVerticalHover); } if (this.defaults.speedVerticalHoverSlow != null) { this.speedVerticalHoverSlow = config.get(this.defaults.section.name, "Vertical Speed (Hover Mode / Slow Descent)", this.defaults.speedVerticalHoverSlow, "The maximum vertical speed of this jetpack when slowly descending in hover mode.").setMinValue(0.0D).getDouble(this.defaults.speedVerticalHoverSlow); } if (this.defaults.speedSideways != null) { this.speedSideways = config.get(this.defaults.section.name, "Sideways Speed", this.defaults.speedSideways, "The speed of this jetpack when flying sideways. This is mostly noticeable in hover mode.").setMinValue(0.0D).getDouble(this.defaults.speedSideways); } if (this.defaults.sprintSpeedModifier != null) { this.sprintSpeedModifier = config.get(this.defaults.section.name, "Sprint Speed Multiplier", this.defaults.sprintSpeedModifier, "How much faster this jetpack will fly forward when sprinting. Setting this to 1.0 will make sprinting have no effect apart from the added speed from vanilla.").setMinValue(0.0D).getDouble(this.defaults.sprintSpeedModifier); } if (this.defaults.sprintFuelModifier != null) { this.sprintFuelModifier = config.get(this.defaults.section.name, "Sprint Fuel Usage Multiplier", this.defaults.sprintFuelModifier, "How much more energy this jetpack will use when sprinting. Setting this to 1.0 will make sprinting have no effect on energy usage.").setMinValue(0.0D).getDouble(this.defaults.sprintFuelModifier); } if (this.defaults.emergencyHoverMode != null) { this.emergencyHoverMode = config.get(this.defaults.section.name, "Emergency Hover Mode", this.defaults.emergencyHoverMode, "When enabled, this jetpack will activate hover mode automatically when the wearer is about to die from a fall.").getBoolean(this.defaults.emergencyHoverMode); } } @Override protected void writeConfigToNBT(NBTTagCompound tag) { super.writeConfigToNBT(tag); if (this.defaults.speedVertical != null) { tag.setDouble("SpeedVertical", this.speedVertical); } if (this.defaults.accelVertical != null) { tag.setDouble("AccelVertical", this.accelVertical); } if (this.defaults.speedVerticalHover != null) { tag.setDouble("SpeedVerticalHover", this.speedVerticalHover); } if (this.defaults.speedVerticalHoverSlow != null) { tag.setDouble("SpeedVerticalHoverSlow", this.speedVerticalHoverSlow); } if (this.defaults.speedSideways != null) { tag.setDouble("SpeedSideways", this.speedSideways); } if (this.defaults.sprintSpeedModifier != null) { tag.setDouble("SprintSpeedModifier", this.sprintSpeedModifier); } if (this.defaults.sprintFuelModifier != null) { tag.setDouble("SprintFuelModifier", this.sprintFuelModifier); } if (this.defaults.emergencyHoverMode != null) { tag.setBoolean("EmergencyHoverMode", this.emergencyHoverMode); } } @Override protected void readConfigFromNBT(NBTTagCompound tag) { super.readConfigFromNBT(tag); if (this.defaults.speedVertical != null) { this.speedVertical = tag.getDouble("SpeedVertical"); } if (this.defaults.accelVertical != null) { this.accelVertical = tag.getDouble("AccelVertical"); } if (this.defaults.speedVerticalHover != null) { this.speedVerticalHover = tag.getDouble("SpeedVerticalHover"); } if (this.defaults.speedVerticalHoverSlow != null) { this.speedVerticalHoverSlow = tag.getDouble("SpeedVerticalHoverSlow"); } if (this.defaults.speedSideways != null) { this.speedSideways = tag.getDouble("SpeedSideways"); } if (this.defaults.sprintSpeedModifier != null) { this.sprintSpeedModifier = tag.getDouble("SprintSpeedModifier"); } if (this.defaults.sprintFuelModifier != null) { this.sprintFuelModifier = tag.getDouble("SprintFuelModifier"); } if (this.defaults.emergencyHoverMode != null) { this.emergencyHoverMode = tag.getBoolean("EmergencyHoverMode"); } } }
package uk.ac.nottingham.createStream; import java.sql.SQLException; import java.util.HashSet; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import twitter4j.DirectMessage; import twitter4j.FilterQuery; import twitter4j.JSONObject; import twitter4j.StallWarning; import twitter4j.Status; import twitter4j.StatusDeletionNotice; import twitter4j.StatusListener; import twitter4j.TwitterException; import twitter4j.TwitterObjectFactory; import twitter4j.TwitterStream; import twitter4j.TwitterStreamFactory; import twitter4j.User; import twitter4j.UserList; import twitter4j.UserMentionEntity; import twitter4j.UserStreamListener; import twitter4j.conf.Configuration; import twitter4j.conf.ConfigurationBuilder; import static uk.ac.nottingham.createStream.Event.*; public class GetStream { public static interface StreamCallback { public void onShutdown(); } private static Logger logger = LogManager.getLogger(GetStream.class); private static String msgToString(Object o) { try { return TwitterObjectFactory.getRawJSON(o).toString(); } catch (Exception e) { if(o == null) { return "EXCEPTION [" + e.getMessage() +"]"; } else { return o.toString(); } } } private final Database database; private final WordPressUtil.OAuthSettings oauth; public GetStream( final Database database, final WordPressUtil.OAuthSettings oauth) { this.database = database; this.oauth = oauth; } public TwitterStream createStream( final WordPressUtil.WpUser wpUser, final StreamCallback callback) throws TwitterException { final TwitterStream stream = new TwitterStreamFactory( getConfiguration(wpUser.oauthToken, wpUser.oauthTokenSecret)).getInstance(); long uid; long sleep = 10000; // 10 seconds while(true) { try { uid = stream.getId(); break; } catch (TwitterException e) { logger.warn(e.getErrorMessage(), e); int code = e.getStatusCode(); if(code > 499 && code < 600) { try{ Thread.sleep(sleep); } catch(InterruptedException ie) { } sleep *= 2; continue; } throw e; } } final long userID = uid; UserStreamListener userListener = new UserStreamListener() { private void store(Event event, JSONObject json) { database.store(wpUser.id, userID, event, json.toString()); } private void store(Event event, Object msg) { database.store(wpUser.id, userID, event, msgToString(msg)); } private boolean userInArray(UserMentionEntity[] entities, long id) { for(UserMentionEntity entity : entities) { if(entity.getId() == id) return true; } return false; } /** * Capture status changes for authenticated user and write to data store. * @param status */ public void onStatus(Status msg) { if(userID == msg.getUser().getId()) { store(TWEET, msgToString(msg)); } else if(msg.isRetweet() && msg.getRetweetedStatus().getUser().getId() == userID) { store(RETWEET, msgToString(msg)); } else if(msg.getUserMentionEntities().length > 0 && userInArray(msg.getUserMentionEntities(), userID)) { store(MENTION, msgToString(msg)); } } public void onDeletionNotice(StatusDeletionNotice msg) { /* * djp - 26.01.16 * I think we'll ignore these notices for now, there * seems to be an excessive number of these and I don't * quite understand what they mean. They also aren't * currently being used in the display application. */ /*ExceptionlessJSONObject json = new ExceptionlessJSONObject(); json.put("userId", msg.getUserId()); json.put("messageId", msg.getStatusId()); store(STATUS_DELETION, json);*/ } public void onDeletionNotice(long directMessageId, long userId) { ExceptionlessJSONObject json = new ExceptionlessJSONObject(); json.put("userId", userId); json.put("messageId", directMessageId); store(MESSAGE_DELETION, json); } /** * Captures when authenticated user favourites a tweet or when a tweet * is 'favourited' by authenticated users follower. */ public void onFavorite(User source, User target, Status msg) { store(FAVOURITE, msg); } public void onUnfavorite(User source, User target, Status msg) { store(UNFAVOURITE, msg); } /** * Captures when authenticated user follows someone or is followed. */ public void onFollow(User source, User followedUser) { ExceptionlessJSONObject json = new ExceptionlessJSONObject(); json.put("sourceId", source.getId()); json.put("sourceName", source.getScreenName()); json.put("followedUserId", followedUser.getId()); json.put("followedUserName", followedUser.getScreenName()); store(FOLLOW, json); } /** * Captures when authenticated user unfollows someone but does NOT capture * when a follower unfollows authenticated user. */ public void onUnfollow(User source, User unfollowedUser) { ExceptionlessJSONObject json = new ExceptionlessJSONObject(); json.put("sourceId", source.getId()); json.put("sourceName", source.getScreenName()); json.put("unfollowedUserId", unfollowedUser.getId()); json.put("unfollowedUserName", unfollowedUser.getScreenName()); store(UNFOLLOW, json); } /** * Captures when authenticated user send or receives a direct message. * */ public void onDirectMessage(DirectMessage directMessage) { ExceptionlessJSONObject json = new ExceptionlessJSONObject(); json.put("messageId", directMessage.getId()); json.put("messageSenderId", directMessage.getSenderId()); json.put("messageRecipientId", directMessage.getRecipientId()); json.put("messageText", directMessage.getText()); store(MESSAGE, json); } public void onBlock(User source, User blockedUser) { ExceptionlessJSONObject json = new ExceptionlessJSONObject(); json.put("sourceId", source.getId()); json.put("sourceName", source.getScreenName()); json.put("blockedUserId", blockedUser.getId()); json.put("blockedUserName", blockedUser.getScreenName()); store(BLOCK, json); } public void onUnblock(User source, User unblockedUser) { ExceptionlessJSONObject json = new ExceptionlessJSONObject(); json.put("sourceId", source.getId()); json.put("sourceName", source.getScreenName()); json.put("unblockedUserId", unblockedUser.getId()); json.put("unblockedUserName", unblockedUser.getScreenName()); store(UNBLOCK, json); } public void onRetweetedRetweet(User source, User target, Status msg) { store(RETWEETED_RETWEET, msgToString(msg)); } public void onFavoritedRetweet(User source, User target, Status msg) { store(FAVOURITED_RETWEET, msgToString(msg)); } public void onQuotedTweet(User source, User target, Status msg) { store(QUOTED_TWEET, msgToString(msg)); } private final StatusListener statusListener = new StatusListener() { public void onStatus(Status msg) { if(msg.isRetweet() && msg.getRetweetedStatus().getUser().getId() == userID) { if(friends.contains(new Long(msg.getUser().getId()))) { store(FRIEND_RETWEET, msg); } else { store(FRIEND_OF_FRIEND_RETWEET, msg); } } } public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { } public void onTrackLimitationNotice(int numberOfLimitedStatuses) { } public void onScrubGeo(long userId, long upToStatusId) { } public void onStallWarning(StallWarning warning) { } public void onException(Exception ex) { } }; private final HashSet<Long> friends = new HashSet<>(); /** * Get the users friend list and invoke the Status listener to capture friends status changes * @return * */ public void onFriendList(long[] ids) { friends.clear(); for(long id : ids) friends.add(id); logger.debug("Friends list updated"); stream.replaceListener(statusListener, statusListener); FilterQuery query = new FilterQuery(); query.follow(ids); stream.filter(query); } public void onException(Exception ex) { logger.error(ex.getMessage(), ex); stream.clearListeners(); stream.cleanUp(); callback.onShutdown(); } public void onUserListMemberAddition(User addedMember, User listOwner, UserList list) {} public void onUserListMemberDeletion(User deletedMember, User listOwner, UserList list) {} public void onUserListSubscription(User subscriber, User listOwner, UserList list) {} public void onUserListUnsubscription(User subscriber, User listOwner, UserList list) {} public void onUserListCreation(User listOwner, UserList list) {} public void onUserListUpdate(User listOwner, UserList list) {} public void onUserListDeletion(User listOwner, UserList list) {} public void onUserProfileUpdate(User updatedUser) {} public void onUserDeletion(long deletedUser) {} public void onUserSuspension(long suspendedUser) {} public void onTrackLimitationNotice(int numberOfLimitedStatuses) {} public void onScrubGeo(long userId, long upToStatusId) {} public void onStallWarning(StallWarning warning) {} }; stream.addListener(userListener); stream.user(); return stream; } /** * Authorise Twitter OAuth credentials * * @param token * @param tokenSecret * @return */ private Configuration getConfiguration(String token, String tokenSecret) { return new ConfigurationBuilder() .setDebugEnabled(true) .setApplicationOnlyAuthEnabled(false) .setJSONStoreEnabled(true) .setOAuthConsumerKey(oauth.consumerKey) .setOAuthConsumerSecret(oauth.consumerSecret) .setOAuthAccessToken(token) .setOAuthAccessTokenSecret(tokenSecret).build(); } }
import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.THttpClient; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import datahub.*; /** * Sample DataHub Java Client * * @author anantb * @date 11/07/2013 * */ public class DHClient { public static void main(String [] args) { try { TTransport transport = new THttpClient("http://datahub.csail.mit.edu/service"); TProtocol protocol = new TBinaryProtocol(transport); DataHub.Client client = new DataHub.Client(protocol); System.out.println(client.get_version()); DHConnectionParams con_params = new DHConnectionParams(); con_params.setUser("anantb"); con_params.setPassword("anant"); DHConnection con = client.connect(con_params); DHQueryResult res = client.execute_sql(con, "select * from anantb.demo.team", null); for (DHRow row : res.getData().getTable().getRows()) { for (DHCell cell : row.getCells()) { System.out.print(new String(cell.getValue()) + "\t"); } System.out.println(); } } catch(Exception e) { e.printStackTrace(); } } }
package ActiveMQ; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.TransportConnector; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.network.NetworkConnector; import org.slf4j.LoggerFactory; import shared.RandomString; import ch.qos.logback.classic.Level; import java.io.IOException; import java.net.DatagramSocket; import java.net.ServerSocket; import java.net.URI; public class ActiveBroker { public static BrokerService broker; private NetworkConnector bridge(BrokerService from, BrokerService to) throws Exception { TransportConnector toConnector = to.getTransportConnectors().get(0); NetworkConnector bridge = from.addNetworkConnector("static://" + toConnector.getPublishableConnectString()); //bridge.addStaticallyIncludedDestination(sendQ); //bridge.addStaticallyIncludedDestination(replyQWildcard); return bridge; } /* protected NetworkConnector bridgeBrokers(String localBrokerName, String remoteBrokerName, boolean dynamicOnly, int networkTTL) throws Exception { NetworkConnector connector = super.bridgeBrokers(localBrokerName, remoteBrokerName, dynamicOnly, networkTTL, true); connector.setBridgeTempDestinations(true); connector.setAdvisoryForFailedForward(true); connector.setDuplex(useDuplex); connector.setAlwaysSyncSend(true); networkConnectors.add(connector); return connector; } */ public ActiveBroker(String brokerName) { //ch.qos.logback.classic.Logger rootLogger = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); //rootLogger.setLevel(Level.toLevel("debug")); //rootLogger.setLevel(Level.OFF); try { if(portAvailable(1099)) { broker = new BrokerService(); broker.setPersistent(false); broker.setBrokerName(brokerName); broker.setUseJmx(true); broker.getManagementContext().setConnectorPort(1099); //NetworkConnector connector = bridge //connector. // = new NetworkConnector(); //TransportConnector connectorIPv4 = new TransportConnector(); TransportConnector connector = new TransportConnector(); //connectorIPv4.setUri(new URI("tcp://0.0.0.0:32010")); //all ipv4 addresses connector.setUri(new URI("tcp://[::]:32010")); //connector.setDiscoveryUri(new URI("multicast://default?group=test")); //broker.addConnector(connectorIPv4); broker.addConnector(connector); //broker.addNetworkConnector(new URI("multicast://default?group=test")); //NetworkConnector bridge = broker.addNetworkConnector(new URI("static://" + remoteIP + ":32010")); //bridge.setUserName(userName); broker.start(); } } catch(Exception ex) { System.out.println("ActiveBroker Init : " + ex.toString()); } } public boolean RemoteNetworkConnector(NetworkConnector bridge) { //boolean isRemoved = false; return broker.removeNetworkConnector(bridge); //return isRemoved; } public NetworkConnector AddNetworkConnector(String URI) { NetworkConnector bridge = null; try { bridge = broker.addNetworkConnector(new URI("static:tcp://" + URI + ":32010")); RandomString rs = new RandomString(5); bridge.setName(rs.nextString()); bridge.setDuplex(false); //TransportConnector connector = new TransportConnector(); //connector.setUri(new URI(URI)); //connector.setDiscoveryUri(new URI("multicast://default?group=test")); //broker.addConnector(connector); //broker.requestRestart(); //broker.startAllConnectors(); //broker.startTransportConnector(connector); //System.out.println("BorkerNAme: " + bridge.getBrokerName() + " " + bridge.getBrokerService().getBrokerName()); //bridge.start(); //System.out.println("BorkerNAme: " + bridge.getBrokerName() + " " + bridge.getBrokerService().getDefaultSocketURIString()); } catch(Exception ex) { System.out.println("ActiveBroker : AddNetworkConnector Error : " + ex.toString()); } return bridge; } public static void AddTransportConnector(String URI) { try { TransportConnector connector = new TransportConnector(); connector.setUri(new URI(URI)); //connector.setDiscoveryUri(new URI("multicast://default?group=test")); broker.addConnector(connector); //broker.requestRestart(); //broker.startAllConnectors(); broker.startTransportConnector(connector); } catch(Exception ex) { } } public static boolean portAvailable(int port) { if (port < 0 || port > 65535) { throw new IllegalArgumentException("Invalid start port: " + port); } ServerSocket ss = null; DatagramSocket ds = null; try { ss = new ServerSocket(port); ss.setReuseAddress(true); ds = new DatagramSocket(port); ds.setReuseAddress(true); return true; } catch (IOException e) { } finally { if (ds != null) { ds.close(); } if (ss != null) { try { ss.close(); } catch (IOException e) { /* should not be thrown */ } } } return false; } }
package abra; import joptsimple.OptionParser; /** * Manages ABRA command line options * * @author Lisle E. Mose (lmose at unc dot edu) */ public class ReAlignerOptions extends Options { private static final String INPUT_SAM = "in"; private static final String OUTPUT_SAM = "out"; private static final String REFERENCE = "ref"; private static final String BWA_INDEX = "bwa-ref"; private static final String TARGET_REGIONS = "targets"; private static final String TARGET_REGIONS_WITH_KMERS = "target-kmers"; private static final String WORKING_DIR = "working"; private static final String KMER_SIZE = "kmer"; private static final String MIN_NODE_FREQUENCY = "mnf"; private static final String MIN_UNALIGNED_NODE_FREQUENCY = "umnf"; private static final String MIN_CONTIG_LENGTH = "mcl"; private static final String MAX_POTENTIAL_CONTIGS = "mpc"; private static final String MIN_CONTIG_MAPQ = "mc-mapq"; private static final String MIN_MAPQ = "mapq"; private static final String NUM_THREADS = "threads"; private static final String UNALIGNED_ASSEMBLY = "aur"; private static final String MAX_UNALIGNED_READS = "mur"; private static final String SINGLE_END = "single"; private static final String RNA = "rna"; private static final String RNA_OUTPUT = "rna-out"; private static final String MIN_BASE_QUALITY = "mbq"; private static final String MIN_READ_CANDIDATE_FRACTION = "rcf"; private static final String MAX_AVERAGE_REGION_DEPTH = "mad"; private static final String SEARCH_FOR_STRUCTURAL_VARIATION = "sv"; private static final String SEARCH_FOR_LOCAL_REPEATS = "lr"; private static final String AVERAGE_DEPTH_CEILING = "adc"; private static final String MIN_EDGE_RATIO = "mer"; private OptionParser parser; private boolean isValid; @Override protected OptionParser getOptionParser() { if (parser == null) { parser = new OptionParser(); parser.accepts(INPUT_SAM, "Required list of input sam or bam file(s) separated by comma").withRequiredArg().ofType(String.class); parser.accepts(OUTPUT_SAM, "Required list of output sam or bam file(s) separated by comma").withRequiredArg().ofType(String.class); parser.accepts(REFERENCE, "Genome reference location").withRequiredArg().ofType(String.class); parser.accepts(BWA_INDEX, "BWA index prefix. Use this only if the bwa index prefix does not match the ref option.").withRequiredArg().ofType(String.class); parser.accepts(TARGET_REGIONS, "BED file containing target regions").withRequiredArg().ofType(String.class); parser.accepts(TARGET_REGIONS_WITH_KMERS, "BED-like file containing target regions with per region kmer sizes in 4th column").withRequiredArg().ofType(String.class); parser.accepts(WORKING_DIR, "Working directory for intermediate output. Must not already exist").withRequiredArg().ofType(String.class); parser.accepts(KMER_SIZE, "Optional assembly kmer size(delimit with commas if multiple sizes specified)").withOptionalArg().ofType(String.class); parser.accepts(MIN_NODE_FREQUENCY, "Assembly minimum node frequency").withRequiredArg().ofType(Integer.class).defaultsTo(2); parser.accepts(MIN_UNALIGNED_NODE_FREQUENCY, "Assembly minimum unaligned node frequency").withOptionalArg().ofType(Integer.class).defaultsTo(2); parser.accepts(MIN_CONTIG_LENGTH, "Assembly minimum contig length").withOptionalArg().ofType(Integer.class).defaultsTo(-1); parser.accepts(MAX_POTENTIAL_CONTIGS, "Maximum number of potential contigs for a region").withOptionalArg().ofType(Integer.class).defaultsTo(5000); parser.accepts(NUM_THREADS, "Number of threads").withRequiredArg().ofType(Integer.class).defaultsTo(4); parser.accepts(MIN_CONTIG_MAPQ, "Minimum contig mapping quality").withOptionalArg().ofType(Integer.class).defaultsTo(25); parser.accepts(MIN_MAPQ, "Minimum mapping quality for a read to be used in assembly and be eligible for realignment").withOptionalArg().ofType(Integer.class).defaultsTo(20); parser.accepts(UNALIGNED_ASSEMBLY, "Assemble unaligned reads (currently disabled)."); parser.accepts(MAX_UNALIGNED_READS, "Maximum number of unaligned reads to assemble").withOptionalArg().ofType(Integer.class).defaultsTo(50000000); parser.accepts(SINGLE_END, "Input is single end"); parser.accepts(RNA, "Input RNA sam or bam file (currently disabled)").withOptionalArg().ofType(String.class); parser.accepts(RNA_OUTPUT, "Output RNA sam or bam file (required if RNA input file specified)").withRequiredArg().ofType(String.class); parser.accepts(MIN_BASE_QUALITY, "Minimum base quality for inclusion in assembly. This value is compared against the sum of base qualities per kmer position").withOptionalArg().ofType(Integer.class).defaultsTo(60); parser.accepts(MIN_READ_CANDIDATE_FRACTION, "Minimum read candidate fraction for triggering assembly").withRequiredArg().ofType(Double.class).defaultsTo(.01); parser.accepts(MAX_AVERAGE_REGION_DEPTH, "Regions with average depth exceeding this value will be downsampled").withRequiredArg().ofType(Integer.class).defaultsTo(250); parser.accepts(SEARCH_FOR_STRUCTURAL_VARIATION, "Enable Structural Variation searching (experimental, only supported for paired end)").withRequiredArg().ofType(String.class); parser.accepts(SEARCH_FOR_LOCAL_REPEATS, "Search for potential larger local repeats and output to specified file (only for multiple samples)").withRequiredArg().ofType(String.class); parser.accepts(AVERAGE_DEPTH_CEILING, "Skip regions with average depth greater than this value").withOptionalArg().ofType(Integer.class).defaultsTo(100000); parser.accepts(MIN_EDGE_RATIO, "Min edge pruning ratio. Default value is appropriate for relatively sensitive somatic cases. May be increased for improved speed in germline only cases.").withRequiredArg().ofType(Double.class).defaultsTo(.02); } return parser; } @Override protected void validate() { isValid = true; if (!getOptions().hasArgument(INPUT_SAM)) { isValid = false; System.out.println("Missing required input SAM/BAM file"); } if (!getOptions().hasArgument(OUTPUT_SAM)) { isValid = false; System.out.println("Missing required input SAM/BAM file"); } if (getInputFiles().length != getOutputFiles().length) { System.out.println("Number of input files must equal number of output files"); } if (!getOptions().hasArgument(REFERENCE)) { isValid = false; System.out.println("Missing required reference"); } if (getOptions().hasArgument(TARGET_REGIONS) && getOptions().hasArgument(TARGET_REGIONS_WITH_KMERS)) { isValid = false; System.out.println("Please specifiy only one of: " + TARGET_REGIONS + ", " + TARGET_REGIONS_WITH_KMERS); } if (!getOptions().hasArgument(TARGET_REGIONS) && !getOptions().hasArgument(TARGET_REGIONS_WITH_KMERS)) { isValid = false; System.out.println("Missing required target regions"); } if (!getOptions().hasArgument(WORKING_DIR)) { isValid = false; System.out.println("Missing required working directory"); } if ((getOptions().hasArgument(NUM_THREADS) && (Integer) getOptions().valueOf(NUM_THREADS) < 1)) { isValid = false; System.out.println("Num threads must be greater than zero."); } if (!isValid) { printHelp(); } } public String[] getInputFiles() { String[] files = new String[0]; String sams = (String) getOptions().valueOf(INPUT_SAM); if (sams != null) { files = sams.split(","); } return files; } public String[] getOutputFiles() { String[] files = new String[0]; String sams = (String) getOptions().valueOf(OUTPUT_SAM); if (sams != null) { files = sams.split(","); } return files; } public String getReference() { return (String) getOptions().valueOf(REFERENCE); } public String getBwaIndex() { String index = null; if (getOptions().hasArgument(BWA_INDEX)) { index = (String) getOptions().valueOf(BWA_INDEX); } else { index = (String) getOptions().valueOf(REFERENCE); } return index; } public String getTargetRegionFile() { String file = null; if (getOptions().hasArgument(TARGET_REGIONS_WITH_KMERS)) { file = (String) getOptions().valueOf(TARGET_REGIONS_WITH_KMERS); } else { file = (String) getOptions().valueOf(TARGET_REGIONS); } return file; } public boolean hasPresetKmers() { return getOptions().hasArgument(TARGET_REGIONS_WITH_KMERS); } public String getWorkingDir() { return (String) getOptions().valueOf(WORKING_DIR); } public int[] getKmerSizes() { int[] kmers; if (getOptions().has(KMER_SIZE)) { String[] kmerStr = ((String) getOptions().valueOf(KMER_SIZE)).split(","); kmers = new int[kmerStr.length]; for (int i=0; i<kmerStr.length; i++) { kmers[i] = Integer.parseInt(kmerStr[i]); } } else { kmers = new int[0]; } return kmers; } public int getMinNodeFrequency() { return (Integer) getOptions().valueOf(MIN_NODE_FREQUENCY); } public int getMinUnalignedNodeFrequency() { return (Integer) getOptions().valueOf(MIN_UNALIGNED_NODE_FREQUENCY); } public int getMinContigLength() { return (Integer) getOptions().valueOf(MIN_CONTIG_LENGTH); } public int getMaxPotentialContigs() { return (Integer) getOptions().valueOf(MAX_POTENTIAL_CONTIGS); } public int getNumThreads() { return getOptions().hasArgument(NUM_THREADS) ? (Integer) getOptions().valueOf(NUM_THREADS) : 4; } public int getMinContigMapq() { return (Integer) getOptions().valueOf(MIN_CONTIG_MAPQ); } public boolean isSkipUnalignedAssembly() { return !getOptions().has(UNALIGNED_ASSEMBLY); } public int getMaxUnalignedReads() { return (Integer) getOptions().valueOf(MAX_UNALIGNED_READS); } public boolean isPairedEnd() { return !getOptions().has(SINGLE_END); } public String getRnaSam() { return (String) getOptions().valueOf(RNA); } public String getRnaSamOutput() { return (String) getOptions().valueOf(RNA_OUTPUT); } public int getMinBaseQuality() { return (Integer) getOptions().valueOf(MIN_BASE_QUALITY); } public double getMinReadCandidateFraction() { return (Double) getOptions().valueOf(MIN_READ_CANDIDATE_FRACTION); } public double getMinEdgeRatio() { return (Double) getOptions().valueOf(MIN_EDGE_RATIO); } public int getMaxAverageRegionDepth() { return (Integer) getOptions().valueOf(MAX_AVERAGE_REGION_DEPTH); } public boolean shouldSearchForStructuralVariation() { return getOptions().has(SEARCH_FOR_STRUCTURAL_VARIATION); } public String getStructuralVariantFile() { return (String) getOptions().valueOf(SEARCH_FOR_STRUCTURAL_VARIATION); } public String getLocalRepeatFile() { return (String) getOptions().valueOf(SEARCH_FOR_LOCAL_REPEATS); } public int getAverageDepthCeiling() { return (Integer) getOptions().valueOf(AVERAGE_DEPTH_CEILING); } public int getMinimumMappingQuality() { return (Integer) getOptions().valueOf(MIN_MAPQ); } public boolean isValid() { return isValid; } }
package org.jboss.as.threads; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.controller.parsing.ParseUtils.invalidAttributeValue; import static org.jboss.as.controller.parsing.ParseUtils.missingRequired; import static org.jboss.as.controller.parsing.ParseUtils.missingRequiredElement; import static org.jboss.as.controller.parsing.ParseUtils.requireNoNamespaceAttribute; import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute; import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement; import static org.jboss.as.threads.CommonAttributes.ALLOW_CORE_TIMEOUT; import static org.jboss.as.threads.CommonAttributes.BLOCKING; import static org.jboss.as.threads.CommonAttributes.BOUNDED_QUEUE_THREAD_POOL; import static org.jboss.as.threads.CommonAttributes.CORE_THREADS; import static org.jboss.as.threads.CommonAttributes.COUNT; import static org.jboss.as.threads.CommonAttributes.GROUP_NAME; import static org.jboss.as.threads.CommonAttributes.HANDOFF_EXECUTOR; import static org.jboss.as.threads.CommonAttributes.KEEPALIVE_TIME; import static org.jboss.as.threads.CommonAttributes.MAX_THREADS; import static org.jboss.as.threads.CommonAttributes.NAME; import static org.jboss.as.threads.CommonAttributes.PER_CPU; import static org.jboss.as.threads.CommonAttributes.PRIORITY; import static org.jboss.as.threads.CommonAttributes.PROPERTIES; import static org.jboss.as.threads.CommonAttributes.QUEUELESS_THREAD_POOL; import static org.jboss.as.threads.CommonAttributes.QUEUE_LENGTH; import static org.jboss.as.threads.CommonAttributes.SCHEDULED_THREAD_POOL; import static org.jboss.as.threads.CommonAttributes.THREAD_FACTORY; import static org.jboss.as.threads.CommonAttributes.THREAD_NAME_PATTERN; import static org.jboss.as.threads.CommonAttributes.TIME; import static org.jboss.as.threads.CommonAttributes.UNBOUNDED_QUEUE_THREAD_POOL; import static org.jboss.as.threads.CommonAttributes.UNIT; import java.math.BigDecimal; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import org.jboss.as.controller.persistence.SubsystemMarshallingContext; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.dmr.Property; import org.jboss.staxmapper.XMLElementReader; import org.jboss.staxmapper.XMLElementWriter; import org.jboss.staxmapper.XMLExtendedStreamReader; import org.jboss.staxmapper.XMLExtendedStreamWriter; public final class ThreadsParser implements XMLStreamConstants, XMLElementReader<List<ModelNode>>, XMLElementWriter<SubsystemMarshallingContext> { static final ThreadsParser INSTANCE = new ThreadsParser(); private static String SUBSYSTEM_NAME = "threads"; public static ThreadsParser getInstance() { return INSTANCE; } @Override public void readElement(final XMLExtendedStreamReader reader, final List<ModelNode> list) throws XMLStreamException { final ModelNode address = new ModelNode(); address.add(SUBSYSTEM, SUBSYSTEM_NAME); address.protect(); final ModelNode subsystem = new ModelNode(); subsystem.get(OP).set(ADD); subsystem.get(OP_ADDR).set(address); list.add(subsystem); while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { switch (Namespace.forUri(reader.getNamespaceURI())) { case THREADS_1_0: { readSingleElement(reader, list, address); break; } default: { throw unexpectedElement(reader); } } } } private String readSingleElement(final XMLExtendedStreamReader reader, final List<ModelNode> list, final ModelNode address) throws XMLStreamException { String name = null; final Element element = Element.forName(reader.getLocalName()); switch (element) { case BOUNDED_QUEUE_THREAD_POOL: { name = parseBoundedQueueThreadPool(reader, address, list); break; } case THREAD_FACTORY: { // Add connector updates name = parseThreadFactory(reader, address, list); break; } case QUEUELESS_THREAD_POOL: { name = parseQueuelessThreadPool(reader, address, list); break; } case SCHEDULED_THREAD_POOL: { name = parseScheduledThreadPool(reader, address, list); break; } case UNBOUNDED_QUEUE_THREAD_POOL: { name = parseUnboundedQueueThreadPool(reader, address, list); break; } default: { throw unexpectedElement(reader); } } return name; } public String parseThreadFactory(final XMLExtendedStreamReader reader, final ModelNode parentAddress, final List<ModelNode> list) throws XMLStreamException { return parseThreadFactory(reader, parentAddress, list, THREAD_FACTORY, null); } public String parseThreadFactory(final XMLExtendedStreamReader reader, final ModelNode parentAddress, final List<ModelNode> list, final String childAddress, final String providedName) throws XMLStreamException { final ModelNode op = new ModelNode(); list.add(op); op.get(OP).set(ADD); String name = null; int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case NAME: { name = value; break; } case GROUP_NAME: { op.get(GROUP_NAME).set(value); break; } case THREAD_NAME_PATTERN: { op.get(THREAD_NAME_PATTERN).set(value); break; } case PRIORITY: { try { int priority = Integer.valueOf(value); op.get(PRIORITY).set(priority); } catch (NumberFormatException e) { invalidAttributeValue(reader, i); } } break; default: throw unexpectedAttribute(reader, i); } } if (providedName != null) { name = providedName; } else if (name == null) { throw missingRequired(reader, Collections.singleton(Attribute.NAME)); } final ModelNode address = parentAddress.clone(); address.add(childAddress, name); address.protect(); op.get(OP_ADDR).set(address); while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { switch (Element.forName(reader.getLocalName())) { case PROPERTIES: { ModelNode props = parseProperties(reader); if (props.isDefined()) { op.get(PROPERTIES).set(props); } break; } default: { throw unexpectedElement(reader); } } break; } return name; } public String parseBoundedQueueThreadPool(final XMLExtendedStreamReader reader, final ModelNode parentAddress, final List<ModelNode> list) throws XMLStreamException { return parseBoundedQueueThreadPool(reader, parentAddress, list, BOUNDED_QUEUE_THREAD_POOL, null); } public String parseBoundedQueueThreadPool(final XMLExtendedStreamReader reader, final ModelNode parentAddress, final List<ModelNode> list, final String childAddress, final String providedName) throws XMLStreamException { final ModelNode op = new ModelNode(); list.add(op); op.get(OP).set(ADD); String name = null; int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case NAME: { name = value; break; } case BLOCKING: { op.get(BLOCKING).set(Boolean.valueOf(value)); break; } case ALLOW_CORE_TIMEOUT: { op.get(ALLOW_CORE_TIMEOUT).set(Boolean.valueOf(value)); break; } default: throw unexpectedAttribute(reader, i); } } if (providedName != null) { name = providedName; } else if(name == null) { throw missingRequired(reader, Collections.singleton(Attribute.NAME)); } final ModelNode address = parentAddress.clone(); address.add(childAddress, name); address.protect(); op.get(OP_ADDR).set(address); boolean foundQueueLength = false; boolean foundMaxThreads = false; while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { switch (Element.forName(reader.getLocalName())) { case CORE_THREADS: { op.get(CORE_THREADS).set(parseScaledCount(reader)); break; } case HANDOFF_EXECUTOR: { op.get(HANDOFF_EXECUTOR).set(parseRef(reader)); break; } case MAX_THREADS: { op.get(MAX_THREADS).set(parseScaledCount(reader)); foundMaxThreads = true; break; } case KEEPALIVE_TIME: { op.get(KEEPALIVE_TIME).set(parseTimeSpec(reader)); break; } case THREAD_FACTORY: { op.get(CommonAttributes.THREAD_FACTORY).set(parseRef(reader)); break; } case PROPERTIES: { ModelNode props = parseProperties(reader); if (props.isDefined()) { op.get(PROPERTIES).set(props); } break; } case QUEUE_LENGTH: { op.get(QUEUE_LENGTH).set(parseScaledCount(reader)); foundQueueLength = true; break; } default: { throw unexpectedElement(reader); } } } if (!foundMaxThreads || !foundQueueLength) { Set<Element> missing = new HashSet<Element>(); if (!foundMaxThreads) { missing.add(Element.MAX_THREADS); } if (!foundQueueLength) { missing.add(Element.QUEUE_LENGTH); } throw missingRequiredElement(reader, missing); } return name; } public String parseUnboundedQueueThreadPool(final XMLExtendedStreamReader reader, final ModelNode parentAddress, final List<ModelNode> list) throws XMLStreamException { return parseUnboundedQueueThreadPool(reader, parentAddress, list, UNBOUNDED_QUEUE_THREAD_POOL, null); } public String parseUnboundedQueueThreadPool(final XMLExtendedStreamReader reader, final ModelNode parentAddress, final List<ModelNode> list, final String childAddress, final String providedName) throws XMLStreamException { final ModelNode op = new ModelNode(); list.add(op); op.get(OP).set(ADD); String name = null; int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case NAME: { name = value; break; } default: throw unexpectedAttribute(reader, i); } } if (providedName != null) { name = providedName; } else if (name == null) { throw missingRequired(reader, Collections.singleton(Attribute.NAME)); } // FIXME Make relative and use this scheme to add the addresses // address.add("profile", "test).add("subsystem", "threads") final ModelNode address = parentAddress.clone(); address.add(childAddress, name); address.protect(); op.get(OP_ADDR).set(address); boolean foundMaxThreads = false; while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { switch (Element.forName(reader.getLocalName())) { case MAX_THREADS: { op.get(MAX_THREADS).set(parseScaledCount(reader)); foundMaxThreads = true; break; } case KEEPALIVE_TIME: { op.get(KEEPALIVE_TIME).set(parseTimeSpec(reader)); break; } case THREAD_FACTORY: { op.get(CommonAttributes.THREAD_FACTORY).set(parseRef(reader)); break; } case PROPERTIES: { ModelNode props = parseProperties(reader); if (props.isDefined()) { op.get(PROPERTIES).set(props); } break; } default: { throw unexpectedElement(reader); } } } if (!foundMaxThreads) { throw missingRequiredElement(reader, Collections.singleton(Element.MAX_THREADS)); } return name; } public String parseScheduledThreadPool(final XMLExtendedStreamReader reader, final ModelNode parentAddress, final List<ModelNode> list) throws XMLStreamException { return parseScheduledThreadPool(reader, parentAddress, list, SCHEDULED_THREAD_POOL, null); } public String parseScheduledThreadPool(final XMLExtendedStreamReader reader, final ModelNode parentAddress, final List<ModelNode> list, final String childAddress, final String providedName) throws XMLStreamException { final ModelNode op = new ModelNode(); list.add(op); op.get(OP).set(ADD); String name = null; int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case NAME: { name = value; break; } default: throw unexpectedAttribute(reader, i); } } if (providedName != null) { name = providedName; } else if (name == null) { throw missingRequired(reader, Collections.singleton(Attribute.NAME)); } // FIXME Make relative and use this scheme to add the addresses // address.add("profile", "test).add("subsystem", "threads") final ModelNode address = parentAddress.clone(); address.add(childAddress, name); address.protect(); op.get(OP_ADDR).set(address); boolean foundMaxThreads = false; while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { switch (Element.forName(reader.getLocalName())) { case MAX_THREADS: { op.get(MAX_THREADS).set(parseScaledCount(reader)); foundMaxThreads = true; break; } case KEEPALIVE_TIME: { op.get(KEEPALIVE_TIME).set(parseTimeSpec(reader)); break; } case THREAD_FACTORY: { op.get(CommonAttributes.THREAD_FACTORY).set(parseRef(reader)); break; } case PROPERTIES: { ModelNode props = parseProperties(reader); if (props.isDefined()) { op.get(PROPERTIES).set(props); } break; } default: { throw unexpectedElement(reader); } } } if (!foundMaxThreads) { throw missingRequiredElement(reader, Collections.singleton(Element.MAX_THREADS)); } return name; } public String parseQueuelessThreadPool(final XMLExtendedStreamReader reader, final ModelNode parentAddress, final List<ModelNode> list) throws XMLStreamException { return parseQueuelessThreadPool(reader, parentAddress, list, QUEUELESS_THREAD_POOL, null); } public String parseQueuelessThreadPool(final XMLExtendedStreamReader reader, final ModelNode parentAddress, final List<ModelNode> list, final String childAddress, final String providedName) throws XMLStreamException { final ModelNode op = new ModelNode(); list.add(op); op.get(OP).set(ADD); String name = null; int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case NAME: { name = value; break; } case BLOCKING: { op.get(BLOCKING).set(Boolean.valueOf(value)); break; } default: throw unexpectedAttribute(reader, i); } } if (providedName != null) { name = providedName; } else if (name == null) { throw missingRequired(reader, Collections.singleton(Attribute.NAME)); } // FIXME Make relative and use this scheme to add the addresses // address.add("profile", "test).add("subsystem", "threads") final ModelNode address = parentAddress.clone(); address.add(childAddress, name); address.protect(); op.get(OP_ADDR).set(address); boolean foundMaxThreads = false; while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { switch (Element.forName(reader.getLocalName())) { case HANDOFF_EXECUTOR: { op.get(HANDOFF_EXECUTOR).set(parseRef(reader)); break; } case MAX_THREADS: { op.get(MAX_THREADS).set(parseScaledCount(reader)); foundMaxThreads = true; break; } case KEEPALIVE_TIME: { op.get(KEEPALIVE_TIME).set(parseTimeSpec(reader)); break; } case THREAD_FACTORY: { op.get(CommonAttributes.THREAD_FACTORY).set(parseRef(reader)); break; } case PROPERTIES: { ModelNode props = parseProperties(reader); if (props.isDefined()) { op.get(PROPERTIES).set(props); } break; } default: { throw unexpectedElement(reader); } } } if (!foundMaxThreads) { throw missingRequiredElement(reader, Collections.singleton(Element.MAX_THREADS)); } return name; } private ModelNode parseScaledCount(final XMLExtendedStreamReader reader) throws XMLStreamException { final int attrCount = reader.getAttributeCount(); BigDecimal count = null; BigDecimal perCpu = null; for (int i = 0; i < attrCount; i++) { requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case COUNT: { try { count = new BigDecimal(value); } catch (NumberFormatException e) { throw invalidAttributeValue(reader, i); } break; } case PER_CPU: { try { perCpu = new BigDecimal(value); } catch (NumberFormatException e) { throw invalidAttributeValue(reader, i); } break; } default: throw unexpectedAttribute(reader, i); } } if (count == null || perCpu == null) { Set<Attribute> missing = new HashSet<Attribute>(); if (count == null) { missing.add(Attribute.COUNT); } if (perCpu == null) { missing.add(Attribute.PER_CPU); } throw missingRequired(reader, missing); } if (reader.hasNext() && reader.nextTag() != END_ELEMENT) { throw unexpectedElement(reader); } ModelNode node = new ModelNode(); node.get(COUNT).set(count); node.get(PER_CPU).set(perCpu); return node; } private ModelNode parseTimeSpec(final XMLExtendedStreamReader reader) throws XMLStreamException { final int attrCount = reader.getAttributeCount(); TimeUnit unit = null; Long duration = null; for (int i = 0; i < attrCount; i++) { requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case TIME: { duration = reader.getLongAttributeValue(i); break; } case UNIT: { unit = Enum.valueOf(TimeUnit.class, value.toUpperCase()); break; } default: throw unexpectedAttribute(reader, i); } } if (duration == null || unit == null) { Set<Attribute> missing = new HashSet<Attribute>(); if (duration == null) { missing.add(Attribute.TIME); } if (unit == null) { missing.add(Attribute.UNIT); } } if (reader.hasNext() && reader.nextTag() != END_ELEMENT) { throw unexpectedElement(reader); } ModelNode node = new ModelNode(); node.get(TIME).set(duration); node.get(UNIT).set(unit.toString()); return node; } private String parseRef(XMLExtendedStreamReader reader) throws XMLStreamException { final int attrCount = reader.getAttributeCount(); String refName = null; for (int i = 0; i < attrCount; i++) { requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case NAME: { refName = value; break; } default: throw unexpectedAttribute(reader, i); } } if (refName == null) { throw missingRequired(reader, Collections.singleton(NAME)); } if (reader.hasNext() && reader.nextTag() != END_ELEMENT) { throw unexpectedElement(reader); } return refName; } private ModelNode parseProperties(final XMLExtendedStreamReader reader) throws XMLStreamException { ModelNode node = new ModelNode(); while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { switch (Element.forName(reader.getLocalName())) { case PROPERTY: { final int attrCount = reader.getAttributeCount(); String propName = null; String propValue = null; for (int i = 0; i < attrCount; i++) { requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case NAME: { propName = value; break; } case VALUE: { propValue = value; } break; default: throw unexpectedAttribute(reader, i); } } if (propName == null || propValue == null) { Set<Attribute> missing = new HashSet<Attribute>(); if (propName == null) { missing.add(Attribute.NAME); } if (propValue == null) { missing.add(Attribute.VALUE); } throw missingRequired(reader, missing); } node.add(propName, propValue); if (reader.hasNext() && reader.nextTag() != END_ELEMENT) { throw unexpectedElement(reader); } } } } return node; } /** {@inheritDoc} */ @Override public void writeContent(final XMLExtendedStreamWriter writer, final SubsystemMarshallingContext context) throws XMLStreamException { context.startSubsystemElement(Namespace.CURRENT.getUriString(), false); ModelNode node = context.getModelNode(); writeThreadsElement(writer, node); writer.writeEndElement(); } public void writeThreadsElement(final XMLExtendedStreamWriter writer, ModelNode node) throws XMLStreamException { if (node.hasDefined(THREAD_FACTORY)) { for (String name : node.get(THREAD_FACTORY).keys()) { final ModelNode child = node.get(THREAD_FACTORY, name); if (child.isDefined()) { writeThreadFactory(writer, child); } } } if (node.hasDefined(BOUNDED_QUEUE_THREAD_POOL)) { for (String name : node.get(BOUNDED_QUEUE_THREAD_POOL).keys()) { final ModelNode child = node.get(BOUNDED_QUEUE_THREAD_POOL, name); if (child.isDefined()) { writeBoundedQueueThreadPool(writer, child); } } } if (node.hasDefined(QUEUELESS_THREAD_POOL)) { for (String name : node.get(QUEUELESS_THREAD_POOL).keys()) { final ModelNode child = node.get(QUEUELESS_THREAD_POOL, name); if (child.isDefined()) { writeQueuelessThreadPool(writer, child); } } } if (node.hasDefined(SCHEDULED_THREAD_POOL)) { for (String name : node.get(SCHEDULED_THREAD_POOL).keys()) { final ModelNode child = node.get(SCHEDULED_THREAD_POOL, name); if (child.isDefined()) { writeScheduledQueueThreadPool(writer, child); } } } if (node.hasDefined(UNBOUNDED_QUEUE_THREAD_POOL)) { for (String name : node.get(UNBOUNDED_QUEUE_THREAD_POOL).keys()) { final ModelNode child = node.get(UNBOUNDED_QUEUE_THREAD_POOL, name); if (child.isDefined()) { writeUnboundedQueueThreadPool(writer, child); } } } } public void writeThreadFactory(final XMLExtendedStreamWriter writer, final ModelNode node) throws XMLStreamException { writeThreadFactory(writer, node, Element.THREAD_FACTORY.getLocalName(), true); } public void writeThreadFactory(final XMLExtendedStreamWriter writer, final ModelNode node, final String elementName, final boolean includeName) throws XMLStreamException { writer.writeStartElement(elementName); if (includeName && node.hasDefined(NAME)) { writeAttribute(writer, Attribute.NAME, node.get(NAME)); } if (node.hasDefined(GROUP_NAME)) { writeAttribute(writer, Attribute.GROUP_NAME, node.get(GROUP_NAME)); } if (node.hasDefined(THREAD_NAME_PATTERN)) { writeAttribute(writer, Attribute.THREAD_NAME_PATTERN, node.get(THREAD_NAME_PATTERN)); } if (node.hasDefined(PRIORITY)) { writeAttribute(writer, Attribute.PRIORITY, node.get(PRIORITY)); } if (node.hasDefined(PROPERTIES)) { writeProperties(writer, node.get(PROPERTIES)); } writer.writeEndElement(); } public void writeBoundedQueueThreadPool(final XMLExtendedStreamWriter writer, final ModelNode node) throws XMLStreamException { writeBoundedQueueThreadPool(writer, node, Element.BOUNDED_QUEUE_THREAD_POOL.getLocalName(), true); } public void writeBoundedQueueThreadPool(final XMLExtendedStreamWriter writer, final ModelNode node, final String elementName, final boolean includeName) throws XMLStreamException { writer.writeStartElement(elementName); if (includeName && node.hasDefined(NAME)) { writeAttribute(writer, Attribute.NAME, node.get(NAME)); } if (node.hasDefined(BLOCKING)) { writeAttribute(writer, Attribute.BLOCKING, node.get(BLOCKING)); } if (node.hasDefined(ALLOW_CORE_TIMEOUT)) { writeAttribute(writer, Attribute.ALLOW_CORE_TIMEOUT, node.get(ALLOW_CORE_TIMEOUT)); } writeRef(writer, node, Element.HANDOFF_EXECUTOR, HANDOFF_EXECUTOR); writeRef(writer, node, Element.THREAD_FACTORY, THREAD_FACTORY); writeThreads(writer, node, Element.CORE_THREADS); writeThreads(writer, node, Element.QUEUE_LENGTH); writeThreads(writer, node, Element.MAX_THREADS); writeTime(writer, node, Element.KEEPALIVE_TIME); if (node.hasDefined(PROPERTIES)) { writeProperties(writer, node.get(PROPERTIES)); } writer.writeEndElement(); } public void writeQueuelessThreadPool(final XMLExtendedStreamWriter writer, final ModelNode node) throws XMLStreamException { writeQueuelessThreadPool(writer, node, Element.QUEUELESS_THREAD_POOL.getLocalName(), true); } public void writeQueuelessThreadPool(final XMLExtendedStreamWriter writer, final ModelNode node, final String elementName, final boolean includeName) throws XMLStreamException { writer.writeStartElement(elementName); if (includeName && node.hasDefined(NAME)) { writeAttribute(writer, Attribute.NAME, node.get(NAME)); } if (node.hasDefined(BLOCKING)) { writeAttribute(writer, Attribute.BLOCKING, node.get(BLOCKING)); } writeRef(writer, node, Element.HANDOFF_EXECUTOR, HANDOFF_EXECUTOR); writeRef(writer, node, Element.THREAD_FACTORY, THREAD_FACTORY); writeThreads(writer, node, Element.MAX_THREADS); writeTime(writer, node, Element.KEEPALIVE_TIME); if (node.hasDefined(PROPERTIES)) { writeProperties(writer, node.get(PROPERTIES)); } writer.writeEndElement(); } public void writeScheduledQueueThreadPool(final XMLExtendedStreamWriter writer, final ModelNode node) throws XMLStreamException { writeScheduledQueueThreadPool(writer, node, Element.SCHEDULED_THREAD_POOL.getLocalName(), true); } public void writeScheduledQueueThreadPool(final XMLExtendedStreamWriter writer, final ModelNode node, final String elementName, final boolean includeName) throws XMLStreamException { writer.writeStartElement(elementName); if (includeName && node.hasDefined(NAME)) { writeAttribute(writer, Attribute.NAME, node.get(NAME)); } writeRef(writer, node, Element.THREAD_FACTORY, THREAD_FACTORY); writeThreads(writer, node, Element.MAX_THREADS); writeTime(writer, node, Element.KEEPALIVE_TIME); if (node.hasDefined(PROPERTIES)) { writeProperties(writer, node.get(PROPERTIES)); } writer.writeEndElement(); } public void writeUnboundedQueueThreadPool(final XMLExtendedStreamWriter writer, final ModelNode node) throws XMLStreamException { writeUnboundedQueueThreadPool(writer, node, Element.UNBOUNDED_QUEUE_THREAD_POOL.getLocalName(), true); } public void writeUnboundedQueueThreadPool(final XMLExtendedStreamWriter writer, final ModelNode node, final String elementName, final boolean includeName) throws XMLStreamException { writer.writeStartElement(elementName); if (includeName && node.hasDefined(NAME)) { writeAttribute(writer, Attribute.NAME, node.get(NAME)); } writeRef(writer, node, Element.THREAD_FACTORY, THREAD_FACTORY); writeThreads(writer, node, Element.MAX_THREADS); writeTime(writer, node, Element.KEEPALIVE_TIME); if (node.hasDefined(PROPERTIES)) { writeProperties(writer, node.get(PROPERTIES)); } writer.writeEndElement(); } private void writeRef(final XMLExtendedStreamWriter writer, final ModelNode node, Element element, String name) throws XMLStreamException { if (node.hasDefined(name)) { writer.writeStartElement(element.getLocalName()); writeAttribute(writer, Attribute.NAME, node.get(name)); writer.writeEndElement(); } } private void writeThreads(final XMLExtendedStreamWriter writer, final ModelNode node, Element element) throws XMLStreamException { if (node.hasDefined(element.getLocalName())) { writer.writeStartElement(element.getLocalName()); ModelNode threads = node.get(element.getLocalName()); if (threads.hasDefined(COUNT)) { writeAttribute(writer, Attribute.COUNT, threads.get(COUNT)); } if (threads.hasDefined(PER_CPU)) { writeAttribute(writer, Attribute.PER_CPU, threads.get(PER_CPU)); } writer.writeEndElement(); } } private void writeTime(final XMLExtendedStreamWriter writer, final ModelNode node, Element element) throws XMLStreamException { if (node.hasDefined(element.getLocalName())) { writer.writeStartElement(element.getLocalName()); ModelNode keepalive = node.get(element.getLocalName()); if (keepalive.hasDefined(TIME)) { writeAttribute(writer, Attribute.TIME, keepalive.get(TIME)); } if (keepalive.hasDefined(UNIT)) { writeAttribute(writer, Attribute.UNIT, keepalive.get(UNIT)); } writer.writeEndElement(); } } private void writeProperties(final XMLExtendedStreamWriter writer, final ModelNode node) throws XMLStreamException { writer.writeStartElement(Element.PROPERTIES.getLocalName()); if (node.getType() == ModelType.LIST) { for (ModelNode prop : node.asList()) { if (prop.getType() == ModelType.PROPERTY) { writer.writeStartElement(Element.PROPERTY.getLocalName()); final Property property = prop.asProperty(); writer.writeAttribute(Attribute.NAME.getLocalName(), property.getName()); writeAttribute(writer, Attribute.VALUE, property.getValue()); writer.writeEndElement(); } } } writer.writeEndElement(); } private void writeAttribute(final XMLExtendedStreamWriter writer, final Attribute attr, final ModelNode value) throws XMLStreamException { writer.writeAttribute(attr.getLocalName(), value.asString()); } }
package belight; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import com.amazon.speech.speechlet.Session; /** * Created 4/16/16. Description... * * @author Neo Li. <[email protected]> */ public class SessionHelper { public static Integer caloriesMax = 3000; public static final String CURRENT_INTAKE_CALORIES = "CURRENT_INTAKE_CALORIES"; public static final String CURRENT_INTAKE_FOOD_NAMES = "CURRENT_INTAKE_FOOD_NAMES"; public static Integer getCurrentIntakeCalories(Session session) { Integer currentIntake = (Integer) session.getAttribute(CURRENT_INTAKE_CALORIES); if (currentIntake == null) { return 0; } return currentIntake; } public static String getCurrentIntakeFoodNames(Session session) { return (String) session.getAttribute(CURRENT_INTAKE_FOOD_NAMES); } public static void addCurrentInTake(Session session, FoodItem foodItem) { Integer calTaken = getCurrentIntakeCalories(session); if(calTaken == null) { calTaken = 0; } session.setAttribute(CURRENT_INTAKE_CALORIES, calTaken + foodItem.getCalories()); String foodTakens = getCurrentIntakeFoodNames(session); if(foodTakens == null) { foodTakens = ""; } foodTakens = foodItem.getName() + foodTakens; session.setAttribute(CURRENT_INTAKE_FOOD_NAMES, foodTakens); } public static int getResidualInCalories(Session session, FoodItem foodItem) { Integer calTaken = getCurrentIntakeCalories(session); if(calTaken == null) { calTaken = 0; } return caloriesMax - (calTaken + foodItem.getCalories()); } public static String getUserName() { return "Neo"; } }
package broadwick.data; import broadwick.BroadwickException; import broadwick.data.MovementDatabaseFacade.MovementRelationship; import com.google.common.base.Predicate; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.Collections2; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.joda.time.Days; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.tooling.GlobalGraphOperations; /** * This class works as an interface to the databases holding the movements, locations and animal data read from the * configuration file. When the methods to retrieve all the data in the DB (e.g. getMovements()) are called the results * are stored in a cache for speedier retrieval. This cache is not permanent however, freeing memory when required. */ @Slf4j public final class Lookup { /** * Create the lookup object for accessing data in the internal databases. * @param dbFacade the object that is responsible for accessing the internal databases. */ public Lookup(final MovementDatabaseFacade dbFacade) { this.dbFacade = dbFacade; final GraphDatabaseService internalDb = dbFacade.getDbService(); if (internalDb != null) { this.ops = GlobalGraphOperations.at(internalDb); } else { this.ops = null; } } /** * Get all the movements that have been read from the file(s) specified in the configuration file. * @return a collection of movement events that have been recorded. */ public Collection<Movement> getMovements() { final Iterable<Relationship> allRelationships = ops.getAllRelationships(); final Iterator<Relationship> movementRelationships = Iterables.filter(allRelationships, MOVEMENT_PREDICATE).iterator(); final Collection<Movement> movements = new ArrayList<>(); while (movementRelationships.hasNext()) { final Relationship movementRelationship = movementRelationships.next(); // create a Movement and add it to the collection... final Movement movement = createMovement(movementRelationship); movements.add(movement); // store the movements for the animal in the cache. // Collection<Movement> movementsForAnimal = movementsCache.getIfPresent(movement.getId()); // if (movementsForAnimal == null) { // movementsForAnimal = new TreeSet<>(new MovementsComparator()); // movementsForAnimal.add(movement); // movementsCache.put(movement.getId(), movementsForAnimal); // } else { // movementsForAnimal.add(movement); } return movements; } /** * Get all the movements that have been read from the file(s) specified in the configuration file filtered on a date * range. * @param startDate the first date in the range with which we will filter the movements * @param endDate the final date in the range with which we will filter the movements * @return a collection of movement events that have been recorded. */ public Collection<Movement> getMovements(final int startDate, final int endDate) { final Iterable<Relationship> allRelationships = ops.getAllRelationships(); final Iterator<Relationship> movementRelationships = Iterables.filter(allRelationships, MOVEMENT_PREDICATE).iterator(); Integer date = null; final Collection<Movement> movements = new ArrayList<>(); while (movementRelationships.hasNext()) { final Relationship movementRelationship = movementRelationships.next(); final ArrayList<String> relationshipProperties = Lists.newArrayList(movementRelationship.getPropertyKeys()); if (relationshipProperties.size() == directedMovementKeys.size() && relationshipProperties.containsAll(directedMovementKeys)) { //is a directed movement so read the date. date = (Integer) movementRelationship.getProperty(DirectedMovementsFileReader.getMOVEMENT_DATE()); } else if (relationshipProperties.size() == fullMovementKeys.size() && relationshipProperties.containsAll(fullMovementKeys)) { //is a full movement so read the departure date. date = (Integer) movementRelationship.getProperty(FullMovementsFileReader.getDEPARTURE_DATE()); } else if (relationshipProperties.size() == batchedMovementKeys.size() && relationshipProperties.containsAll(batchedMovementKeys)) { //is a batched movement so read the departure date. date = (Integer) movementRelationship.getProperty(BatchedMovementsFileReader.getDEPARTURE_DATE()); } else { log.error("Could not determine type of movement for {}. Properties {} do not match known list.", movementRelationship.toString(), movementRelationship.getPropertyKeys()); } if ((date != null) && (date <= endDate) && (date >= startDate)) { // create a Movement and add it to the collection... final Movement movement = createMovement(movementRelationship); movements.add(movement); } } return movements; } /** * Get all the movements that have been read from the file(s) specified in the configuration file. * @return a collection of movement events that have been recorded. */ public Collection<Test> getTests() { final Collection<Test> tests = new ArrayList<>(); final Iterable<Node> allNodes = ops.getAllNodes(); final Iterator<Node> testNodes = Iterables.filter(allNodes, TEST_PREDICATE).iterator(); while (testNodes.hasNext()) { final Node testNode = testNodes.next(); // create an animal and add it to the collection... final Test test = createTest(testNode); tests.add(test); if (testsCache.getIfPresent(test.getId()) == null) { testsCache.put(test.getId(), test); } } log.trace("Found {} tests.", tests.size()); return tests; } /** * Get all the movements that have been read from the file(s) specified in the configuration file. * @return a collection of movement events that have been recorded. */ public Collection<Animal> getAnimals() { final Collection<Animal> animals = new ArrayList<>(); final Iterable<Node> allNodes = ops.getAllNodes(); final Iterator<Node> animalNodes = Iterables.filter(allNodes, ANIMAL_PREDICATE).iterator(); while (animalNodes.hasNext()) { final Node animalNode = animalNodes.next(); // create an animal and add it to the collection... final Animal animal = createAnimal(animalNode); animals.add(animal); if (animalsCache.getIfPresent(animal.getId()) == null) { animalsCache.put(animal.getId(), animal); } } log.trace("Found {} animals.", animals.size()); return animals; } /** * Get all the movements that have been read from the file(s) specified in the configuration file. * @return a collection of movement events that have been recorded. */ public Collection<Location> getLocations() { final Collection<Location> locations = new ArrayList<>(); final Iterable<Node> allNodes = ops.getAllNodes(); final Iterator<Node> locationNodes = Iterables.filter(allNodes, LOCATION_PREDICATE).iterator(); while (locationNodes.hasNext()) { final Node locationNode = locationNodes.next(); // create a Movement and add it to the collection... final Location location = createLocation(locationNode); locations.add(location); if (locationsCache.getIfPresent(location.getId()) == null) { locationsCache.put(location.getId(), location); } } return locations; } /** * Get a location from the list of locations in the system. If there is no location matching the id a * BroadwickException is thrown because we should only be looking for valid locations. Note, this method returns a * live view of the movements so changes to one affect the other and in a worst case scenario can cause a * ConcurrentModificationException. The returned collection isn't threadsafe or serializable, even if unfiltered is. * @param locationId the id of the location we are looking for. * @return the Location object with the required id. */ public Location getLocation(final String locationId) { Location location = locationsCache.getIfPresent(locationId); if (location == null) { try { location = Iterables.find(getLocations(), new Predicate<Location>() { @Override public boolean apply(final Location loc) { return loc.getId().equals(locationId); } }); } catch (NoSuchElementException e) { // this is an error, we are looking for a location that does not exist. log.error("No location with id {} exists.", locationId); throw new BroadwickException("No location with id " + locationId + " exists."); } } return location; } /** * Get an animal from the list of animals in the system. If there is no animal matching the id a BroadwickException * is thrown because we should only be looking for valid animals. Note, this method returns a live view of the * movements so changes to one affect the other and in a worst case scenario can cause a * ConcurrentModificationException. The returned collection isn't threadsafe or serializable, even if unfiltered is. * @param animalId the id of the animal we are looking for. * @return the Animal object with the required id. */ public Animal getAnimal(final String animalId) { Animal animal = animalsCache.getIfPresent(animalId); if (animal == null) { try { final Collection<Animal> animals = getAnimals(); animal = Iterables.find(animals, new Predicate<Animal>() { @Override public boolean apply(final Animal anm) { return anm.getId().equals(animalId); } }); } catch (NoSuchElementException e) { // this is an error, we are looking for a animal that does not exist. log.error("No animal with id {} exists.", animalId); return null; } } return animal; } /** * Get all the recorded movements for a given animal. Note, this method returns a live view of the movements so * changes to one affect the other and in a worst case scenario can cause a ConcurrentModificationException. The * returned collection isn't threadsafe or serializable, even if unfiltered is. * @param animalId the id of the animal whose movements are to be returned. * @return a collection of movement events that have been recorded for the animal with the given id. */ public Collection<Movement> getMovementsForAnimal(final String animalId) { final Collection<Movement> movementsForAnimal = movementsCache.getIfPresent(animalId); if (movementsForAnimal == null) { // the cache have been destryed so do the long lookup return Collections2.filter(getMovements(), new Predicate<Movement>() { @Override public boolean apply(final Movement movement) { return animalId.equals(movement.getId()); } }); } return movementsForAnimal; } /** * Get an animals location at a specified date. If the animal does not have a specified location, e.g. if we are * asking for its location before it's born or in the middle of a movement where the departure and destination dates * span several days then a null location will be returned. * @param animalId the id of the animal. * @param date the date for which we want the animals location. * @return the location of the animal on date or Location.getNullLocation if there isn't a valid location. */ public Location getAnimalLocationAtDate(final String animalId, final int date) { final Collection<Movement> movements = getMovementsForAnimal(animalId); String locationId = ""; // Simply iterate over all the movements up to and including this date setting the Location // as we go. This should be ok since we are have ordered the movements. for (Movement movement : movements) { if (movement.getDestinationDate() != null && movement.getDestinationDate() <= date) { final String departureId = movement.getDepartureId(); final String destinationId = movement.getDestinationId(); if (destinationId.isEmpty()) { locationId = departureId; } else { locationId = destinationId; } } else if (movement.getDepartureDate() != null && movement.getDepartureDate() <= date) { // we might have a movement that straddles the required date if so the animal moved off the departure // location but not arrived at the destination so they have no location for this date. locationId = ""; } } if ("".equals(locationId)) { return Location.getNullLocation(); } return getLocation(locationId); } /** * Convert a date object to an integer (number of days from a fixed start date, here 1/1/1900). All dates in the * database are stored as integer values using this method. * @param date the date object we are converting. * @return the number of days from a fixed 'zero date'. */ public int getDate(final DateTime date) { return Days.daysBetween(dbFacade.getZeroDate(), date).getDays(); } /** * Convert an integer (number of days from a fixed start date, here 1/1/1900) to a DateTime object. All dates in the * database are stored as integer values, this method converts that integer to a DateTime object. * @param date the integer date offset. * @return the datetime object corresponding to the 'zero date' plus date. */ public DateTime toDate(final int date) { return dbFacade.getZeroDate().plus(date); } /** * Convert a date object to an integer (number of days from a fixed start date, here 1/1/1900). All dates in the * database are stored as integer values using this method. * @param date the date object we are converting. * @param dateFormat the format the date is in when doing the conversion. * @return the number of days from a fixed 'zero date'. */ public int getDate(final String date, final String dateFormat) { final DateTimeFormatter pattern = DateTimeFormat.forPattern(dateFormat); final DateTime dateTime = pattern.parseDateTime(date); return this.getDate(dateTime); } /** * Create a location object from the node object defining it in the graph database. * @param locationNode the node object from the database defining the location. * @return the created location object. */ private Location createLocation(final Node locationNode) { log.trace("Creating location object from data node: {}", locationNode.getPropertyKeys()); final String id = (String) locationNode.getProperty(LocationsFileReader.getID()); final Double easting = (Double) locationNode.getProperty(LocationsFileReader.getEASTING()); final Double northing = (Double) locationNode.getProperty(LocationsFileReader.getNORTHING()); final Map<String, Integer> populations = new HashMap<>(); return new Location(id, easting, northing, populations); } /** * Create an animal object from the node object defining it in the graph database. * @param animalNode the node object from the database defining the animal. * @return the created animal object. */ private Animal createAnimal(final Node animalNode) { log.trace("Creating animal object for {} using {}", animalNode.getProperty(PopulationsFileReader.getID()), animalNode.getPropertyKeys()); if (Iterables.contains(animalNode.getPropertyKeys(), PopulationsFileReader.getID())) { final String id = (String) animalNode.getProperty(PopulationsFileReader.getID()); final Integer dateOfBirth = (Integer) animalNode.getProperty(PopulationsFileReader.getDATE_OF_BIRTH()); final String locationOfBirth = (String) animalNode.getProperty(PopulationsFileReader.getLOCATION_OF_BIRTH()); String species = StringUtils.EMPTY; if (animalNode.hasProperty(PopulationsFileReader.getSPECIES())) { species = (String) animalNode.getProperty(PopulationsFileReader.getSPECIES()); } String locationOfDeath = StringUtils.EMPTY; if (animalNode.hasProperty(PopulationsFileReader.getLOCATION_OF_DEATH())) { locationOfDeath = (String) animalNode.getProperty(PopulationsFileReader.getLOCATION_OF_DEATH()); } Integer dateOfDeath = Integer.MAX_VALUE; if (animalNode.hasProperty(PopulationsFileReader.getDATE_OF_DEATH())) { dateOfDeath = (Integer) animalNode.getProperty(PopulationsFileReader.getDATE_OF_DEATH()); } return new Animal(id, species, dateOfBirth, locationOfBirth, dateOfDeath, locationOfDeath); } return null; } /** * Create a Test object from the node object defining it in the graph database. * @param testNode the node object from the database defining the test. * @return the created test object. */ private Test createTest(final Node testNode) { log.trace("Creating test object for {} using {}", testNode.getProperty(PopulationsFileReader.getID()), testNode.getPropertyKeys()); if (Iterables.contains(testNode.getPropertyKeys(), PopulationsFileReader.getID())) { String id = StringUtils.EMPTY; if (testNode.hasProperty(TestsFileReader.getID())) { id = (String) testNode.getProperty(TestsFileReader.getID()); } String groupId = StringUtils.EMPTY; if (testNode.hasProperty(TestsFileReader.getGROUP_ID())) { groupId = (String) testNode.getProperty(TestsFileReader.getGROUP_ID()); } String locationId = StringUtils.EMPTY; if (testNode.hasProperty(TestsFileReader.getLOCATION_ID())) { locationId = (String) testNode.getProperty(TestsFileReader.getLOCATION_ID()); } Integer dateOfTest = Integer.MAX_VALUE; if (testNode.hasProperty(TestsFileReader.getTEST_DATE())) { dateOfTest = (Integer) testNode.getProperty(TestsFileReader.getTEST_DATE()); } Boolean positiveResult = Boolean.FALSE; if (testNode.hasProperty(TestsFileReader.getPOSITIVE_RESULT())) { positiveResult = (Boolean) testNode.getProperty(TestsFileReader.getPOSITIVE_RESULT()); } Boolean negativeResult = Boolean.FALSE; if (testNode.hasProperty(TestsFileReader.getNEGATIVE_RESULT())) { negativeResult = (Boolean) testNode.getProperty(TestsFileReader.getNEGATIVE_RESULT()); } return new Test(id, groupId, locationId, dateOfTest, positiveResult, negativeResult); } return null; } /** * Create a movement object from the relationship object defining it in the graph database. * @param relationship the relationship object from the database defining the movement. * @return the created movement object. */ private Movement createMovement(final Relationship relationship) { final ArrayList<String> relationshipProperties = Lists.newArrayList(relationship.getPropertyKeys()); if (relationshipProperties.size() == directedMovementKeys.size() && relationshipProperties.containsAll(directedMovementKeys)) { //is a directed movement so read the elements. return createMovementFromDirectedMovementData(relationship); } else if (relationshipProperties.size() == fullMovementKeys.size() && relationshipProperties.containsAll(fullMovementKeys)) { //is a full movement so read the elements. return createMovementFromFullMovementData(relationship); } else if (relationshipProperties.size() == batchedMovementKeys.size() && relationshipProperties.containsAll(batchedMovementKeys)) { //is a batched movement so read the elements. return createMovementFromBatchedMovementData(relationship); } else { log.error("Could not determine type of movement for {}. Properties {} do not match known list.", relationship.toString(), relationship.getPropertyKeys()); } try { // The nodes at both ends should have been read already, if they haven't been then it means that the // location or animal id does not exist in the data files specified in the configuration file. // If the nodes have been read and stored correctly they will have a 'TYPE' attribute, as a simple check // we will check for it and catch the resulting NotFoundException and log the resulting error if // necessary. if (relationship.getStartNode().getProperty(MovementDatabaseFacade.TYPE) == null || relationship.getEndNode().getProperty(MovementDatabaseFacade.TYPE) == null) { log.error("Invalid movement. Either the source, destination or individual of the move does not appear in the data files."); } } catch (org.neo4j.graphdb.NotFoundException nfe) { log.error("Invalid movement. Either the source, destination or individual of the move does not appear in the data files. {}", nfe.getLocalizedMessage()); } finally { return null; } } /** * Create a movement object from the [directed movement] relationship object defining it in the graph database. * @param relationship the relationship object from the database defining the movement. * @return the created movement object. */ private Movement createMovementFromDirectedMovementData(final Relationship relationship) { log.trace("Creating movement object from directed movement data: {}", relationship.getPropertyKeys()); final String locationId = (String) relationship.getProperty(DirectedMovementsFileReader.getLOCATION_ID()); final String direction = (String) relationship.getProperty(DirectedMovementsFileReader.getMOVEMENT_DIRECTION()); final String id = (String) relationship.getProperty(DirectedMovementsFileReader.getID()); final String species = (String) relationship.getProperty(DirectedMovementsFileReader.getSPECIES()); final Integer date = (Integer) relationship.getProperty(DirectedMovementsFileReader.getMOVEMENT_DATE()); String departureId = ""; Integer departureDate = null; String destinationId = ""; Integer destinationDate = null; if ("OFF".equalsIgnoreCase(direction) || "DEATH".equalsIgnoreCase(direction)) { // the end node is the departure node departureId = locationId; departureDate = date; } else { // the end node is the destination node destinationId = locationId; destinationDate = date; } return new Movement(id, 1, departureDate, departureId, destinationDate, destinationId, null, "", species); } /** * Create a movement object from the [batched movement] relationship object defining it in the graph database. * @param relationship the relationship object from the database defining the movement. * @return the created movement object. */ private Movement createMovementFromBatchedMovementData(final Relationship relationship) { log.trace("Creating movement object from batched movement data: {}", relationship.getPropertyKeys()); final Integer batchSize = (Integer) relationship.getProperty(BatchedMovementsFileReader.getBATCH_SIZE()); final String departureId = (String) relationship.getProperty(BatchedMovementsFileReader.getDEPARTURE_ID()); final Integer departureDate = (Integer) relationship.getProperty(BatchedMovementsFileReader.getDEPARTURE_DATE()); final String destinationId = (String) relationship.getProperty(BatchedMovementsFileReader.getDESTINATION_ID()); final Integer destinationDate = (Integer) relationship.getProperty(BatchedMovementsFileReader.getDESTINATION_DATE()); final String marketId = (String) relationship.getProperty(BatchedMovementsFileReader.getMARKET_ID()); final Integer marketDate = (Integer) relationship.getProperty(BatchedMovementsFileReader.getMARKET_DATE()); final String species = (String) relationship.getProperty(BatchedMovementsFileReader.getSPECIES()); return new Movement("", batchSize, departureDate, departureId, destinationDate, destinationId, marketDate, marketId, species); } /** * Create a movement object from the [full movement] relationship object defining it in the graph database. * @param relationship the relationship object from the database defining the movement. * @return the created movement object. */ private Movement createMovementFromFullMovementData(final Relationship relationship) { log.trace("Creating movement object from full movement data: {}", relationship.getPropertyKeys()); final String id = (String) relationship.getProperty(FullMovementsFileReader.getID()); final String departureId = (String) relationship.getProperty(FullMovementsFileReader.getDEPARTURE_ID()); final Integer departureDate = (Integer) relationship.getProperty(FullMovementsFileReader.getDEPARTURE_DATE()); final String destinationId = (String) relationship.getProperty(FullMovementsFileReader.getDESTINATION_ID()); final Integer destinationDate = (Integer) relationship.getProperty(FullMovementsFileReader.getDESTINATION_DATE()); Integer marketDate = 0; if (relationship.hasProperty(FullMovementsFileReader.getMARKET_DATE())) { marketDate = (Integer) relationship.getProperty(FullMovementsFileReader.getMARKET_DATE()); } String marketId = ""; if (relationship.hasProperty(FullMovementsFileReader.getMARKET_ID())) { marketId = (String) relationship.getProperty(FullMovementsFileReader.getMARKET_ID()); } String species = ""; if (relationship.hasProperty(FullMovementsFileReader.getSPECIES())) { species = (String) relationship.getProperty(FullMovementsFileReader.getSPECIES()); } return new Movement(id, 1, departureDate, departureId, destinationDate, destinationId, marketDate, marketId, species); } public static final Predicate<Node> ANIMAL_PREDICATE = new Predicate<Node>() { @Override public boolean apply(final Node node) { return node.hasProperty(MovementDatabaseFacade.TYPE) && MovementDatabaseFacade.ANIMAL.equals(node.getProperty(MovementDatabaseFacade.TYPE)); } }; public static final Predicate<Node> TEST_PREDICATE = new Predicate<Node>() { @Override public boolean apply(final Node node) { return node.hasProperty(MovementDatabaseFacade.TYPE) && MovementDatabaseFacade.TEST.equals(node.getProperty(MovementDatabaseFacade.TYPE)); } }; public static final Predicate<Node> LOCATION_PREDICATE = new Predicate<Node>() { @Override public boolean apply(final Node node) { return node.hasProperty(MovementDatabaseFacade.TYPE) && MovementDatabaseFacade.LOCATION.equals(node.getProperty(MovementDatabaseFacade.TYPE)); } }; public static final Predicate<Relationship> MOVEMENT_PREDICATE = new Predicate<Relationship>() { @Override public boolean apply(final Relationship input) { return input.isType(MovementRelationship.MOVES); } }; private final List<String> directedMovementKeys = Arrays.asList( DirectedMovementsFileReader.getLOCATION_ID(), DirectedMovementsFileReader.getMOVEMENT_DIRECTION(), DirectedMovementsFileReader.getID(), DirectedMovementsFileReader.getSPECIES(), DirectedMovementsFileReader.getMOVEMENT_DATE()); private final List<String> fullMovementKeys = Arrays.asList( FullMovementsFileReader.getID(), FullMovementsFileReader.getDEPARTURE_DATE(), FullMovementsFileReader.getDEPARTURE_ID(), FullMovementsFileReader.getDESTINATION_DATE(), FullMovementsFileReader.getDESTINATION_ID()); private final List<String> batchedMovementKeys = Arrays.asList( BatchedMovementsFileReader.getBATCH_SIZE(), BatchedMovementsFileReader.getDEPARTURE_DATE(), BatchedMovementsFileReader.getDEPARTURE_ID(), BatchedMovementsFileReader.getDESTINATION_DATE(), BatchedMovementsFileReader.getDESTINATION_ID(), BatchedMovementsFileReader.getMARKET_ID(), BatchedMovementsFileReader.getMARKET_DATE(), BatchedMovementsFileReader.getSPECIES()); Cache<String, Collection<Movement>> movementsCache = CacheBuilder.newBuilder().maximumSize(1000).build(); Cache<String, Location> locationsCache = CacheBuilder.newBuilder().maximumSize(1000).build(); Cache<String, Animal> animalsCache = CacheBuilder.newBuilder().maximumSize(1000).build(); Cache<String, Test> testsCache = CacheBuilder.newBuilder().maximumSize(1000).build(); private final MovementDatabaseFacade dbFacade; private final GlobalGraphOperations ops; } /** * Implement a comparator for movements so that movements can be stored in ascending date order with OFF movements * appearing before ON movements in the movements cache. */ class MovementsComparator implements Comparator<Movement> { @Override public int compare(final Movement m1, final Movement m2) { // it's probably easiest to use the natural ordering determined by the toString() methods. // The departure information appears in the string before the destination information so we, in effect are // ordering by departure date. return m1.toString().compareTo(m2.toString()); } }
package com.emc.mongoose; import com.emc.mongoose.concurrent.ServiceTaskExecutor; import com.emc.mongoose.config.AliasingUtil; import com.emc.mongoose.config.CliArgUtil; import com.emc.mongoose.config.ConfigUtil; import com.emc.mongoose.config.IllegalArgumentNameException; import com.emc.mongoose.env.CoreResourcesToInstall; import com.emc.mongoose.env.Extension; import com.emc.mongoose.exception.InterruptRunException; import com.emc.mongoose.load.step.ScriptEngineUtil; import com.emc.mongoose.load.step.service.LoadStepManagerServiceImpl; import com.emc.mongoose.load.step.service.file.FileManagerServiceImpl; import com.emc.mongoose.logging.LogUtil; import com.emc.mongoose.logging.Loggers; import com.emc.mongoose.metrics.MetricsManager; import com.emc.mongoose.metrics.MetricsManagerImpl; import com.emc.mongoose.svc.Service; import com.github.akurilov.confuse.Config; import com.github.akurilov.confuse.SchemaProvider; import com.github.akurilov.confuse.exceptions.InvalidValuePathException; import com.github.akurilov.confuse.exceptions.InvalidValueTypeException; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.Level; import org.eclipse.jetty.server.Server; import javax.script.ScriptEngine; import javax.script.ScriptException; import java.io.IOException; import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import static com.emc.mongoose.Constants.APP_NAME; import static com.emc.mongoose.Constants.DIR_EXAMPLE_SCENARIO; import static com.emc.mongoose.Constants.DIR_EXT; import static com.emc.mongoose.Constants.KEY_CLASS_NAME; import static com.emc.mongoose.Constants.KEY_STEP_ID; import static com.emc.mongoose.Constants.PATH_DEFAULTS; import static com.emc.mongoose.config.CliArgUtil.allCliArgs; import static com.emc.mongoose.load.step.Constants.ATTR_CONFIG; import static javax.script.ScriptContext.ENGINE_SCOPE; import static org.apache.logging.log4j.CloseableThreadContext.Instance; import static org.apache.logging.log4j.CloseableThreadContext.put; public final class Main { public static void main(final String... args) { final Server server = new Server(1234); final CoreResourcesToInstall coreResources = new CoreResourcesToInstall(); final Path appHomePath = coreResources.appHomePath(); final String initialStepId = "none-" + LogUtil.getDateTimeStamp(); LogUtil.init(appHomePath.toString()); try( final Instance logCtx = put(KEY_STEP_ID, initialStepId) .put(KEY_CLASS_NAME, Main.class.getSimpleName()) ) { // install the core resources coreResources.install(appHomePath); // resolve the initial config schema final Map<String, Object> mainConfigSchema = SchemaProvider .resolve(APP_NAME, Thread.currentThread().getContextClassLoader()) .stream() .findFirst() .orElseThrow(IllegalStateException::new); // load the defaults final Config mainDefaults = ConfigUtil.loadConfig( Paths.get(appHomePath.toString(), PATH_DEFAULTS).toFile(), mainConfigSchema ); // extensions try( final URLClassLoader extClsLoader = Extension.extClassLoader( Paths.get(appHomePath.toString(), DIR_EXT).toFile() ) ) { final List<Extension> extensions = Extension.load(extClsLoader); // install the extensions final StringBuilder availExtMsg = new StringBuilder("Available/installed extensions:\n"); extensions.forEach( ext -> { ext.install(appHomePath); final String extId = ext.id(); final String extFqcn = ext.getClass().getCanonicalName(); availExtMsg .append('\t') .append(extId) .append(' ') .append(StringUtils.repeat("-", extId.length() < 30 ? 30 - extId.length() : 1)) .append("> ") .append(extFqcn).append('\n'); } ); Loggers.MSG.info(availExtMsg); // apply the extensions defaults final Config config; try { final List<Config> allDefaults = extensions .stream() .map(ext -> ext.defaults(appHomePath)) .filter(Objects::nonNull) .collect(Collectors.toList()); allDefaults.add(mainDefaults); config = ConfigUtil.merge(mainDefaults.pathSep(), allDefaults); } catch(final Exception e) { LogUtil.exception(Level.ERROR, e, "Failed to load the defaults"); return; } // parse the CLI args and apply them to the config instance try { final Map<String, String> parsedArgs = CliArgUtil.parseArgs(args); final List<Map<String, Object>> aliasingConfig = config.listVal("aliasing"); final Map<String, String> aliasedArgs = AliasingUtil.apply(parsedArgs, aliasingConfig); aliasedArgs.forEach(config::val); } catch(final IllegalArgumentNameException e) { final String formattedAllCliArgs = allCliArgs(config.schema(), config.pathSep()) .stream() .collect(Collectors.joining("\n", "\t", "")); Loggers.ERR.fatal( "Invalid argument: \"{}\"\nThe list of all possible args:\n{}", e.getMessage(), formattedAllCliArgs ); return; } catch(final InvalidValuePathException e) { Loggers.ERR.fatal("Invalid configuration option: \"{}\"", e.path()); return; } catch(final InvalidValueTypeException e) { Loggers.ERR.fatal( "Invalid configuration value type for the option \"{}\", expected: {}, " + "actual: {}", e.path(), e.expectedType(), e.actualType() ); return; } if(null == config.val("load-step-id")) { config.val("load-step-id", initialStepId); config.val("load-step-idAutoGenerated", true); } Arrays.stream(args).forEach(Loggers.CLI::info); Loggers.CONFIG.info(ConfigUtil.toString(config)); // init the metrics manager final MetricsManager metricsMgr = new MetricsManagerImpl(ServiceTaskExecutor.INSTANCE, server); if(config.boolVal("run-node")) { runNode(config, extensions, metricsMgr); } else { runScenario(config, extensions, extClsLoader, metricsMgr, appHomePath); } } } catch(final InterruptedException | InterruptRunException e) { Loggers.MSG.debug("Interrupted", e); } catch(final Exception e) { LogUtil.exception(Level.FATAL, e, "Unexpected failure"); e.printStackTrace(); } } private static void runNode(final Config config, final List<Extension> extensions, final MetricsManager metricsMgr) throws InterruptRunException, InterruptedException { final int listenPort = config.intVal("load-step-node-port"); try( final Service fileMgrSvc = new FileManagerServiceImpl(listenPort); final Service scenarioStepSvc = new LoadStepManagerServiceImpl(listenPort, extensions, metricsMgr) ) { fileMgrSvc.start(); scenarioStepSvc.start(); scenarioStepSvc.await(); } catch(final InterruptedException | InterruptRunException e) { throw e; } catch(final Throwable cause) { cause.printStackTrace(System.err); } } @SuppressWarnings("StringBufferWithoutInitialCapacity") private static void runScenario( final Config config, final List<Extension> extensions, final ClassLoader extClsLoader, final MetricsManager metricsMgr, final Path appHomePath ) { // get the scenario file/path final Path scenarioPath; final String scenarioFile = config.stringVal("run-scenario"); if(scenarioFile != null && ! scenarioFile.isEmpty()) { scenarioPath = Paths.get(scenarioFile); } else { scenarioPath = Paths.get(appHomePath.toString(), DIR_EXAMPLE_SCENARIO, "js", "default.js"); } final StringBuilder strb = new StringBuilder(); try { Files .lines(scenarioPath) .forEach(line -> strb.append(line).append(System.lineSeparator())); } catch(final IOException e) { LogUtil.exception( Level.FATAL, e, "Failed to read the scenario file \"{}\"", scenarioPath ); } final String scenarioText = strb.toString(); Loggers.SCENARIO.log(Level.INFO, scenarioText); final ScriptEngine scriptEngine = ScriptEngineUtil.resolve(scenarioPath, extClsLoader); if(scriptEngine == null) { Loggers.ERR.fatal("Failed to resolve the scenario engine for the file \"{}\"", scenarioPath); } else { Loggers.MSG.info("Using the \"{}\" scenario engine", scriptEngine.getFactory().getEngineName()); // expose the environment values System.getenv().forEach(scriptEngine::put); // expose the loaded configuration scriptEngine.getContext().setAttribute(ATTR_CONFIG, config, ENGINE_SCOPE); // expose the step types ScriptEngineUtil.registerStepTypes(scriptEngine, extensions, config, metricsMgr); try { scriptEngine.eval(scenarioText); } catch(final ScriptException e) { e.printStackTrace(); LogUtil.exception( Level.ERROR, e, "\nScenario failed @ file \"{}\", line #{}, column #{}:\n{}", scenarioPath, e.getLineNumber(), e.getColumnNumber(), e.getMessage() ); } } } }
package com.jcabi.github; import com.jcabi.aspects.Immutable; import com.jcabi.aspects.Loggable; import java.io.IOException; import java.net.URL; import java.text.ParseException; import java.util.Date; import javax.json.Json; import javax.json.JsonObject; import javax.validation.constraints.NotNull; import lombok.EqualsAndHashCode; import lombok.ToString; @Immutable @SuppressWarnings("PMD.TooManyMethods") public interface Pull extends Comparable<Pull>, JsonReadable, JsonPatchable { /** * Repository we're in. * @return Repo */ @NotNull(message = "repository is never NULL") Repo repo(); /** * Get its number. * @return Pull request number */ int number(); @NotNull(message = "commits are never NULL") Iterable<Commit> commits() throws IOException; @NotNull(message = "iterable of files is never NULL") Iterable<JsonObject> files() throws IOException; void merge(@NotNull(message = "message can't be NULL") String msg) throws IOException; /** * Smart pull request with extra features. */ @Immutable @ToString @Loggable(Loggable.DEBUG) @EqualsAndHashCode(of = "pull") final class Smart implements Pull { /** * Encapsulated pull request. */ private final transient Pull pull; /** * Public ctor. * @param pll Pull request */ public Smart(final Pull pll) { this.pull = pll; } /** * Is it open? * @return TRUE if it's open * @throws IOException If there is any I/O problem */ public boolean isOpen() throws IOException { return Issue.OPEN_STATE.equals(this.state()); } /** * Get its state. * @return State of pull request * @throws IOException If there is any I/O problem */ public String state() throws IOException { return new SmartJson(this).text("state"); } /** * Change its state. * @param state State of pull request * @throws IOException If there is any I/O problem */ public void state(final String state) throws IOException { this.pull.patch( Json.createObjectBuilder().add("state", state).build() ); } /** * Get its body. * @return Body of pull request * @throws IOException If there is any I/O problem */ public String title() throws IOException { return new SmartJson(this).text("title"); } /** * Change its state. * @param text Text of pull request * @throws IOException If there is any I/O problem */ public void title(final String text) throws IOException { this.pull.patch( Json.createObjectBuilder().add("title", text).build() ); } /** * Get its title. * @return Title of pull request * @throws IOException If there is any I/O problem */ public String body() throws IOException { return new SmartJson(this).text("body"); } /** * Change its body. * @param text Body of pull request * @throws IOException If there is any I/O problem */ public void body(final String text) throws IOException { this.pull.patch( Json.createObjectBuilder().add("body", text).build() ); } /** * Get its URL. * @return URL of pull request * @throws IOException If there is any I/O problem */ public URL url() throws IOException { return new URL(new SmartJson(this).text("url")); } /** * Get its HTML URL. * @return URL of pull request * @throws IOException If there is any I/O problem */ public URL htmlUrl() throws IOException { return new URL(new SmartJson(this).text("html_url")); } /** * When this pull request was created. * @return Date of creation * @throws IOException If there is any I/O problem */ public Date createdAt() throws IOException { try { return new Github.Time( new SmartJson(this).text("created_at") ).date(); } catch (ParseException ex) { throw new IllegalStateException(ex); } } /** * When this pull request was updated. * @return Date of update * @throws IOException If there is any I/O problem */ public Date updatedAt() throws IOException { try { return new Github.Time( new SmartJson(this).text("updated_at") ).date(); } catch (ParseException ex) { throw new IllegalStateException(ex); } } /** * When this pull request was closed. * @return Date of closing * @throws IOException If there is any I/O problem */ public Date closedAt() throws IOException { try { return new Github.Time( new SmartJson(this).text("closed_at") ).date(); } catch (ParseException ex) { throw new IllegalStateException(ex); } } /** * When this pull request was merged. * @return Date of merging * @throws IOException If there is any I/O problem */ public Date mergedAt() throws IOException { try { return new Github.Time( new SmartJson(this).text("merged_at") ).date(); } catch (ParseException ex) { throw new IllegalStateException(ex); } } /** * Get an issue where the pull request is submitted. * @return Issue */ @NotNull(message = "issue is never NULL") public Issue issue() { return this.pull.repo().issues().get(this.pull.number()); } /** * Get comments count. * @return Count of comments * @throws IOException If there is any I/O problem * @since 0.8 */ public int comments() throws IOException { return new SmartJson(this).number("comments"); } @Override public Repo repo() { return this.pull.repo(); } @Override public int number() { return this.pull.number(); } @Override public Iterable<Commit> commits() throws IOException { return this.pull.commits(); } @Override public Iterable<JsonObject> files() throws IOException { return this.pull.files(); } @Override public void merge(final String msg) throws IOException { this.pull.merge(msg); } @Override public JsonObject json() throws IOException { return this.pull.json(); } @Override public void patch(final JsonObject json) throws IOException { this.pull.patch(json); } @Override public int compareTo(final Pull obj) { return this.pull.compareTo(obj); } } }
package com.k13n.lt_codes; import java.io.File; public class App { private final File file; public App(String[] args) { String filename = parseFilename(args); file = ensureFileExists(filename); } private String parseFilename(String[] args) { if (args.length == 0) throw new IllegalArgumentException("No file provided"); return args[0]; } private File ensureFileExists(String filename) { File file = new File(filename); if (!file.exists()) throw new IllegalArgumentException("File does not exist"); return file; } public void execute() { // FIXME } public static void main(String[] args) { new App(args).execute(); } }
package com.soycasino.app; import static spark.Spark.*; /** * Hello world! * */ public class App { public static void main( String[] args ) { get("/hello", (req, res) -> "Hello World"); get("/exit", (req, res) -> { stop(); return ""; }); } }
package controller; import com.fasterxml.jackson.core.JsonProcessingException; import com.google.gson.Gson; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.ObjectMapper; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import dto.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONObject; import utils.Props; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class Controller { private final static Logger log = LogManager.getLogger(Controller.class); private final static boolean sortByName = Boolean .valueOf(Props.getGlobalProperty(Props.GlobalProperties.SORT_BY_NAME)); static { Unirest.setObjectMapper(new ObjectMapper() { private com.fasterxml.jackson.databind.ObjectMapper jacksonObjectMapper = new com.fasterxml.jackson.databind.ObjectMapper(); public <T> T readValue(String value, Class<T> valueType) { try { return jacksonObjectMapper.readValue(value, valueType); } catch (IOException e) { throw new RuntimeException(e); } } public String writeValue(Object value) { try { return jacksonObjectMapper.writeValueAsString(value); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }); } public List<DTOBranch> getBranches(LoginUser lu) throws UnirestException { HttpResponse<DTOBranch[]> asObject = Unirest.get(lu.getServerIPPort() + "/rest/servicepoint/branches/") .basicAuth(lu.getUsername(), lu.getPassword()) .asObject(DTOBranch[].class); return sortAndRemove(asObject.getBody(), sortByName); } public List<DTOWorkProfile> getWorkProfile(LoginUser lu, DTOBranch branchId) throws UnirestException { HttpResponse<DTOWorkProfile[]> asObject = Unirest .get(lu.getServerIPPort() + "/rest/servicepoint/branches/{branchId}/workProfiles/") .routeParam("branchId", branchId.getIdAsString()) .basicAuth(lu.getUsername(), lu.getPassword()) .asObject(DTOWorkProfile[].class); return sortAndRemove(asObject.getBody(), sortByName); } public List<DTOServicePoint> getServicePoints(LoginUser lu, DTOBranch branchId) throws UnirestException { HttpResponse<DTOServicePoint[]> asObject = Unirest .get(lu.getServerIPPort() + "/rest/servicepoint/branches/{branchID}/servicePoints/deviceTypes/SW_SERVICE_POINT") .routeParam("branchID", branchId.getIdAsString()) .basicAuth(lu.getUsername(), lu.getPassword()) .asObject(DTOServicePoint[].class); return sortAndRemove(asObject.getBody(), sortByName); } public List<DTOEntryPoint> getEntryPoints(LoginUser lu, DTOBranch branchId) throws UnirestException { HttpResponse<DTOEntryPoint[]> asObject = Unirest .get(lu.getServerIPPort() + "/rest/entrypoint/branches/{branchID}/entryPoints/deviceTypes/SW_RECEPTION") .routeParam("branchID", branchId.getIdAsString()) .basicAuth(lu.getUsername(), lu.getPassword()) .asObject(DTOEntryPoint[].class); return sortAndRemove(asObject.getBody(), sortByName); } public HttpResponse<JsonNode> startSession(LoginUser lu, DTOBranch branchId, DTOServicePoint spId) throws UnirestException { HttpResponse<JsonNode> asJson = Unirest .put(lu.getServerIPPort() + "/rest/servicepoint/branches/{branchId}/servicePoints/{servicePointId}/users/{username}/") .routeParam("branchId", branchId.getIdAsString()) .routeParam("servicePointId", spId.getIdAsString()) .routeParam("username", lu.getUsername()) .basicAuth(lu.getUsername(), lu.getPassword()) .asJson(); log.info(asJson.getStatus()); log.info(asJson.getStatusText()); log.info(asJson.getHeaders()); log.info(asJson.getBody()); return asJson; } public HttpResponse<JsonNode> endSession(LoginUser lu, DTOBranch branchId, DTOServicePoint spId) throws UnirestException { HttpResponse<JsonNode> asJson = Unirest .delete(lu.getServerIPPort() + "/rest/servicepoint/branches/{branchId}/servicePoints/{servicePointId}/users/{username}/") .routeParam("branchId", branchId.getIdAsString()). routeParam("servicePointId", spId.getIdAsString()) .routeParam("username", lu.getUsername()) .basicAuth(lu.getUsername(), lu.getPassword()) .asJson(); log.info(asJson.getStatus()); log.info(asJson.getStatusText()); log.info(asJson.getHeaders()); log.info(asJson.getBody()); return asJson; } public DTOUserStatus callNext(LoginUser lu, DTOBranch branch, DTOServicePoint spId) throws UnirestException { HttpResponse<JsonNode> asJson = Unirest .post(lu.getServerIPPort() + "/rest/servicepoint/branches/{branchID}/servicePoints/{servicePointId}/visits/next/") .routeParam("branchID", branch.getIdAsString()) .routeParam("servicePointId", spId.getIdAsString()) .header("Allow", "POST") .basicAuth(lu.getUsername(), lu.getPassword()) .asJson(); log.info(asJson.getStatus()); log.info(asJson.getStatusText()); log.info(asJson.getHeaders()); log.info(asJson.getBody()); JSONObject object = new JSONObject(asJson.getBody()); DTOUserStatus userStat = new Gson().fromJson(object.getJSONObject("object").toString(), DTOUserStatus.class); DTOUserStatus.Visit visi = new Gson().fromJson(object.getJSONObject("object").getJSONObject("visit").toString(), DTOUserStatus.Visit.class); userStat.setVisit(visi); return userStat; } public HttpResponse<JsonNode> callNextAndEnd(LoginUser lu, DTOBranch branch, DTOServicePoint spId, Integer serviceId) throws UnirestException { String json = "{\"services\" : [\""+serviceId.toString() + "\"]}"; String url = lu.getServerIPPort() + "/rest/servicepoint/branches/{branchID}/servicePoints/{servicePointId}/visits/createAndEnd?transactionTime=600"; HttpResponse<JsonNode> asJson = Unirest .post(url) .routeParam("branchID", branch.getIdAsString()) .routeParam("servicePointId", spId.getIdAsString()) .header("Allow", "POST") .header("accept", "application/json") .header("Content-Type", "application/json") .basicAuth(lu.getUsername(), lu.getPassword()) .body(json) .asJson(); log.info(asJson.getStatus()); log.info(asJson.getStatusText()); log.info(asJson.getHeaders()); log.info(asJson.getBody()); return asJson; } public DTOUserStatus recall(LoginUser lu, DTOBranch branchId, DTOServicePoint spId) throws UnirestException { HttpResponse<JsonNode> asJson = Unirest .put(lu.getServerIPPort() + "/rest/servicepoint/branches/{branchID}/servicePoints/{servicePointId}/visit/recall/") .routeParam("branchID", branchId.getIdAsString()) .routeParam("servicePointId", spId.getIdAsString()) .header("Allow", "PUT") .basicAuth(lu.getUsername(), lu.getPassword()) .asJson(); log.info(asJson.getStatus()); log.info(asJson.getStatusText()); log.info(asJson.getHeaders()); log.info(asJson.getBody()); JSONObject object = new JSONObject(asJson.getBody()); DTOUserStatus userStat = new Gson().fromJson(object.getJSONObject("object").toString(), DTOUserStatus.class); DTOUserStatus.Visit visi = new Gson().fromJson(object.getJSONObject("object").getJSONObject("visit").toString(), DTOUserStatus.Visit.class); userStat.setVisit(visi); return userStat; } public DTOVisit createVisit(LoginUser lu, DTOBranch branch, DTOEntryPoint epId, DTOService service) throws UnirestException { HttpResponse<JsonNode> asJson = Unirest .post(lu.getServerIPPort() + "/rest/entrypoint/branches/{branchID}/entryPoints/{entryPointId}/visits/") .routeParam("branchID", branch.getIdAsString()) .routeParam("entryPointId", epId.getIdAsString()) .header("Allow", "POST") .header("accept", "application/json") .header("Content-Type", "application/json") .basicAuth(lu.getUsername(), lu.getPassword()) .body("{\"services\" : [" + service.getId() + "]}") .asJson(); log.info(asJson.getStatus()); log.info(asJson.getStatusText()); log.info(asJson.getHeaders()); log.info(asJson.getBody()); JSONObject object = new JSONObject(asJson.getBody()); DTOVisit vsist = new Gson().fromJson(object.getJSONObject("object").toString(), DTOVisit.class); return vsist; } public HttpResponse<JsonNode> setWorkProfile(LoginUser lu, DTOBranch branchId, DTOWorkProfile wpId) throws UnirestException { HttpResponse<JsonNode> asJson = Unirest .put(lu.getServerIPPort() + "/rest/servicepoint/branches/{branchID}/users/{userName}/workProfile/{workProfileId}/") .routeParam("branchID", branchId.getIdAsString()) .routeParam("userName", lu.getUsername()) .routeParam("workProfileId", wpId.getIdAsString()) .header("Allow", "PUT") .basicAuth(lu.getUsername(), lu.getPassword()) .asJson(); log.info("SetWP"); log.info(asJson.getStatus()); log.info(asJson.getStatusText()); log.info(asJson.getHeaders()); log.info(asJson.getBody()); return asJson; } public HttpResponse<JsonNode> endVisit(LoginUser lu, DTOBranch branchId, String visitId) throws UnirestException { HttpResponse<JsonNode> asJson = Unirest .put(lu.getServerIPPort() + "/rest/servicepoint/branches/{branchID}/visits/{visitId}/end/") .routeParam("branchID", branchId.getIdAsString()) .routeParam("visitId", visitId) .header("Allow", "PUT") .basicAuth(lu.getUsername(), lu.getPassword()) .asJson(); log.info(asJson.getStatus()); log.info(asJson.getStatusText()); log.info(asJson.getHeaders()); log.info(asJson.getBody()); return asJson; } public List<DTOQueue> getQueueInfoForWorkprofile(LoginUser lu, DTOBranch branch, DTOWorkProfile wp) throws UnirestException { HttpResponse<DTOQueue[]> asObject = Unirest .get(lu.getServerIPPort() + "/rest/servicepoint/branches/{branchID}/workProfiles/{workProfileId}/queues/") .routeParam("branchID", branch.getIdAsString()) .routeParam("workProfileId", wp.getIdAsString()) .basicAuth(lu.getUsername(), lu.getPassword()) .asObject(DTOQueue[].class); return sortAndRemove(asObject.getBody(), sortByName); } public List<DTOQueue> getQueueInfo(LoginUser lu, DTOBranch branch) throws UnirestException { HttpResponse<DTOQueue[]> asObject = Unirest .get(lu.getServerIPPort() + "/rest/servicepoint/branches/{branchID}/queues/") .routeParam("branchID", branch.getIdAsString()) .basicAuth(lu.getUsername(), lu.getPassword()) .asObject(DTOQueue[].class); return sortAndRemove(asObject.getBody(), sortByName); } public HttpResponse<JsonNode> logout(LoginUser lu) throws UnirestException, IOException { HttpResponse<JsonNode> asJson = Unirest.put(lu.getServerIPPort() + "/rest/servicepoint/logout") .basicAuth(lu.getUsername(), lu.getPassword()) .asJson(); Unirest.shutdown(); return asJson; } public List<DTOService> getServices(LoginUser lu, DTOBranch dtoBranch) throws UnirestException { HttpResponse<DTOService[]> asObject = Unirest .get(lu.getServerIPPort() + "/rest/entrypoint/branches/{branchID}/services/") .routeParam("branchID", dtoBranch.getIdAsString()) .basicAuth(lu.getUsername(), lu.getPassword()) .asObject(DTOService[].class); return sortAndRemove(asObject.getBody(), sortByName); } @SuppressWarnings("unchecked") private <T extends OrchestraDTO> ArrayList<T> sortAndRemove(OrchestraDTO[] obj, boolean sortByName) { List<T> ret = new ArrayList<T>(); for (OrchestraDTO orchestraDTO : obj) { ret.add((T) orchestraDTO); } if (sortByName) { ret.sort(Comparator.comparing(OrchestraDTO::getName)); } else { ret.sort((arg0, arg1) -> { Integer i1 = arg0.getId(); Integer i2 = arg1.getId(); return i1.compareTo(i2); }); } // Remove casual called (J8 FTW) ret.removeIf(p -> p.getName().toLowerCase().equals("casual caller")); return (ArrayList<T>) ret; } }
package csci599; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; public class JSONGenerator { static int noOfMIMETypes=15; static int charSetSize=256; public static String generateJSON(HashMap<String,ArrayList<Double>> fingerprint,HashMap<String,ArrayList<Double>> correlationStrengths) { String json="{"; for(Object MIMEType:fingerprint.keySet()) { json=json+"\""+MIMEType+"\": "; json=json+"{"; json=json+"\"BFD\": "; json=json+"["; Iterator i1=fingerprint.get(MIMEType).iterator(); while(i1.hasNext()) json=json+i1.next()+","; json=json.substring(0, json.length()-1); json=json+"],"; json=json+"\"CS\": "; json=json+"["; Iterator i2=correlationStrengths.get(MIMEType).iterator(); while(i2.hasNext()) json=json+i2.next()+","; json=json.substring(0, json.length()-1); json=json+"]"; json=json+"},"; } json=json.substring(0, json.length()-2); json=json+"}"; return json; } public static double[][] getJSONFingerptint(String filePath) throws FileNotFoundException, IOException { double[][] fingerprint=new double[noOfMIMETypes][charSetSize]; BufferedReader br=new BufferedReader(new FileReader(filePath)); String input="",inputFile=""; while((input=br.readLine())!=null) { inputFile=inputFile+input; } int i=0,j=0; String[] MIMETypes=inputFile.split("},"); MIMETypes[0]=MIMETypes[0].substring(1, MIMETypes[0].length()); MIMETypes[14]=MIMETypes[14].substring(0,MIMETypes[14].length()-1); return fingerprint; } }
package framework; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.sql.DriverManager; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import app.config.Sys; import app.controller.Main; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import framework.Response.Status; import framework.Tuple.Tuple3; import framework.annotation.Config; import framework.annotation.Content; import framework.annotation.Job; import framework.annotation.Letters; import framework.annotation.Only; import framework.annotation.Route; import framework.annotation.Valid; import framework.annotation.Validator; import framework.annotation.Validator.Errors; /** * application scoped object */ @SuppressWarnings("serial") public abstract class Application implements Attributes<Object> { /** * Singleton */ static Application CURRENT; /** * Shutdown actions */ protected List<Runnable> shutdowns = Tool .list(Log::shutdown, Job.Scheduler::shutdown, Try.r(Db::shutdown, e -> Log.warning("Db shutdown error")), () -> Tool.stream(DriverManager.getDrivers()) .forEach(Try.c(DriverManager::deregisterDriver))); /** * routing table{{request method, pattern, bind map}: {class: method}} */ static Map<Tuple3<Set<Route.Method>, Pattern, Map<String, String>>, Tuple<Class<?>, Method>> routing; /** * @return singleton */ public static Optional<Application> current() { return Tool.of(CURRENT); } /** * @return context path */ public abstract String getContextPath(); @Override public String toString() { return "real path: " + Tool.val(Tool.trim(null, Tool.toURL("framework") .get() .toString(), "/"), s -> s.substring(0, s.length() - "framework".length())) + ", context path: " + getContextPath(); } /** * @return Routes(method, path, action) */ public static Stream<String[]> routes() { return routing.entrySet() .stream() .map(route -> Tool.array(route.getKey().l.isEmpty() ? "*" : route.getKey().l.stream() .map(Object::toString) .collect(Collectors.joining(", ")), route.getKey().r.l .pattern(), route.getValue().l.getName() + "." + route.getValue().r.getName(), route.getKey().r.r.toString())) .sorted(Comparator.<String[], String>comparing(a -> a[1]) .thenComparing(a -> a[0])); } /** * setup * * @param factory response factory */ @SuppressFBWarnings({ "LI_LAZY_INIT_STATIC" }) void setup(Supplier<Response> factory) { /* check to enabled of method parameters name */ try { if (!"factory".equals(Application.class.getDeclaredMethod("setup", Supplier.class) .getParameters()[0].getName())) { throw new InternalError("must to enable compile option `-parameters`"); } } catch (NoSuchMethodException | SecurityException e) { throw new InternalError(e); } /* setup log */ Log.startup(); Log.info(Application.current() .get()::toString); /* setup for response creator */ if (Response.factory == null) { Response.factory = factory; } /* setup routing */ if (routing == null) { routing = new HashMap<>(); try (Stream<Class<?>> cs = Tool.getClasses(Main.class.getPackage() .getName())) { cs.flatMap(c -> Stream.of(c.getDeclaredMethods()) .map(m -> Tuple.of(m, m.getAnnotation(Route.class))) .filter(pair -> pair.r != null) .map(pair -> Tuple.of(c, pair.l, pair.r))) .collect(() -> routing, (map, trio) -> { Class<?> clazz = trio.l; Method method = trio.r.l; String path = Tool.path("/", Tool.of(clazz.getAnnotation(Route.class)) .map(Route::value) .orElse(""), trio.r.r.value()) .apply("/"); Map<String, String> renameMap = new HashMap<>(); ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(out); Tool.printReplace(writer, path, (w, to, prefix) -> { String from; if (!to.chars() .allMatch(i -> (Letters.ALPHABETS + Letters.DIGITS).indexOf(i) >= 0)) { from = String.format("HasH%08x", to.hashCode()); renameMap.put(from, to); } else { from = to; } writer.print("(?<" + from + ">"); }, "(?<", ">"); writer.flush(); path = out.toString(); method.setAccessible(true); map.compute(Tuple.of(Tool.set(trio.r.r.method()), Pattern.compile(out.toString()), renameMap), (k, v) -> { if (v != null) { Log.warning("duplicated route: " + k + " [disabled] " + v.r + " [enabled] " + method); } return Tuple.of(clazz, method); }); }, Map::putAll); } Log.info(() -> Tool.print(writer -> { writer.println(" routes().forEach(a -> writer.println(a[0] + " " + a[1] + " -> " + a[2] + " " + Tool.trim("{", a[3], "}"))); })); } /* start h2 tcp server */ Sys.h2_tcp_port.ifPresent(port -> { try { List<String> parameters = Tool.list("-tcpPort", String.valueOf(port)); if (Sys.h2_tcp_allow_remote) { parameters.add("-tcpAllowOthers"); } if (Sys.h2_tcp_ssl) { parameters.add("-tcpSSL"); } Object tcp = Reflector.invoke("org.h2.tools.Server.createTcpServer", Tool .array(String[].class), new Object[] { parameters.toArray(new String[parameters.size()]) }); Reflector.invoke(tcp, "start", Tool.array()); shutdowns.add(Try.r(() -> Reflector.invoke(tcp, "stop", Tool.array()), e -> Log.warning(e, () -> "h2 tcp server stop error"))); Log.info("h2 tcp server started on port " + port); } catch (Exception e) { Log.warning(e, () -> "h2 tcp server error"); } }); /* start H2 web interface */ Sys.h2_web_port.ifPresent(port -> { try { File config = new File(Tool.suffix(System.getProperty("java.io.tmpdir"), File.separator) + ".h2.server.properties"); List<String> lines = new ArrayList<>(); lines.add("webAllowOthers=" + Sys.h2_web_allow_remote); lines.add("webPort=" + port); lines.add("webSSL=" + Sys.h2_web_ssl); AtomicInteger index = new AtomicInteger(-1); Tool.val(Config.Injector.getSource(Sys.class, Session.currentLocale()), properties -> properties.stringPropertyNames() .stream() .sorted(String::compareTo) .map(p -> Tuple.of(p, properties.getProperty(p))) .filter(t -> t.l.startsWith("Sys.Db") && t.r.startsWith("jdbc:")) .<String>map(t -> index.incrementAndGet() + "=" + t.l + "|" + Db.Type.fromUrl(t.r).driver + "|" + t.r.replace(":", "\\:") .replace("=", "\\="))) .forEach(lines::add); Files.write(config.toPath(), lines, StandardCharsets.UTF_8); config.deleteOnExit(); Object db = Reflector .invoke("org.h2.tools.Server.createWebServer", Tool.array(String[].class), new Object[] { Tool.array("-properties", config.getParent()) }); Reflector.invoke(db, "start", Tool.array()); shutdowns.add(Try.r(() -> Reflector.invoke(db, "stop", Tool.array()), e -> Log.warning(e, () -> "h2 web interface stop error"))); Log.info("h2 web interface started on port " + port); } catch (Exception e) { Log.warning(e, () -> "h2 web interface error"); } }); /* database setup */ Db.setup(Sys.Db.setup); /* load database config */ Config.Injector.loadDb(); Log.info(() -> " .map(c -> String.join(Letters.CRLF, Config.Injector.dumpConfig(c, true))) .collect(Collectors.joining(Letters.CRLF))); Log.info(() -> " /* job scheduler setup */ List<Class<?>> cs = new ArrayList<>(); Sys.job_packages.stream() .forEach(p -> { try (Stream<Class<?>> classes = Tool.getClasses(p)) { classes.forEach(cs::add); } }); Job.Scheduler.setup(cs.toArray(new Class<?>[cs.size()])); Job.Scheduler.trigger(Job.OnApplicationStart); } /** * shutdown */ void shutdown() { Job.Scheduler.trigger(Job.OnApplicationEnd); Collections.reverse(shutdowns); shutdowns.forEach(action -> action.run()); } /** * request handle * * @param request request * @param session session */ void handle(Request request, Session session) { Log.info(request::toString); final String path = request.getPath(); /* no slash root access */ if (path == null) { Response.redirect(getContextPath(), Status.Moved_Permamently) .flush(); return; } Job.Scheduler.trigger(Job.OnRequest); /* action */ final Optional<String> mime = Tool.string(Tool.getExtension(path)) .map(Tool::getContentType); Map<String, List<String>> parameters = new HashMap<>(request.getParameters()); final String normalizedPath = Tool.prefix(Tool.trim(null, path, "/"), "/"); final Tuple<Class<?>, Method> pair = routing.entrySet() .stream() .filter(e -> e.getKey().l.isEmpty() || e.getKey().l.contains(request.getMethod())) .map(e -> Tuple.of(e.getKey().r.l.matcher(normalizedPath), e.getKey().r.r, e.getValue())) .filter(p -> p.l.matches()) .sorted(Comparator.comparing(c -> c.getValue() .getValue() .getValue() .getAnnotation(Route.class) .priority(), Comparator.reverseOrder())) .findFirst() .map(p -> { Reflector.<Map<String, Integer>>invoke(p.l.pattern(), "namedGroups", Tool.array()) .forEach((k, v) -> Tool.setValue(parameters, p.r.l.getOrDefault(k, k), p.l.group(v), ArrayList::new)); return p.r.r; }) .orElse(null); if (pair != null && Tool.of(pair.r.getAnnotation(Content.class)) .map(Content::value) .map(i -> Tool.list(i) .contains(mime.orElse(""))) .orElse(true)) { do { Method method = pair.r; Only only = Tool.or(method.getAnnotation(Only.class), () -> method.getDeclaringClass() .getAnnotation(Only.class)) .orElse(null); /* go login page if not logged in */ if (only != null && Sys.redirect_if_not_login.filter(i -> !i.equals(path)) .isPresent() && !session.isLoggedIn()) { String host = Tool.getFirst(request.getHeaders(), "Host") .orElse("localhost"); String referer = Tool.getFirst(request.getHeaders(), "Referer") .orElse(""); if (referer.contains(host) && !session.containsKey("alert")) { session.put("alert", Sys.Alert.timeout); } if(Tool.getFirst(request.getHeaders(), "X-requested-with").filter(i -> i.equals("XMLHttpRequest")).isPresent()) { Response.error(Status.No_Content).flush(); return; } Response.redirect(Tool.path(getContextPath(), Sys.redirect_if_not_login.get()) .apply("/")) .flush(); return; } /* forbidden check */ boolean forbidden = only != null && !session.isLoggedIn(); if (!forbidden && only != null && only.value().length > 0) { forbidden = !session.getAccount() .hasAnyRole(only.value()); } if (forbidden) { session.setAttr("alert", Sys.Alert.forbidden); Response.template("error.html") .flush(); return; } try (Lazy<Db> db = new Lazy<>(Db::connect)) { try { Log.config("[invoke method] " + method.getDeclaringClass() .getName() + "." + method.getName()); Binder binder = new Binder(parameters).files(request.getFiles()); Object[] args = Stream.of(method.getParameters()) .map(p -> { Class<?> type = p.getType(); if (Request.class.isAssignableFrom(type)) { return request; } if (Session.class.isAssignableFrom(type)) { return session; } if (Application.class.isAssignableFrom(type)) { return this; } if (Db.class.isAssignableFrom(type)) { return db.get(); } if (Errors.class.isAssignableFrom(type)) { return binder.errors; } String name = p.getName(); Tool.of(p.getAnnotation(Valid.class)).ifPresent(valid -> Validator.Manager.validateClass(valid.value(), p.getType(), name, binder.parameters, binder)); return binder.validator(value -> Stream.of(p.getAnnotations()) .forEach(a -> Validator.Manager.instance(a).ifPresent( v -> v.validate(Valid.All.class, name, value, binder)))) .bind(name, type, Reflector.getGenericParameters(p)); }) .toArray(); Object response = method.invoke(Modifier.isStatic(method.getModifiers()) ? null : Reflector.instance(pair.l), args); Consumer<Response> setContentType = r -> { Content content = method.getAnnotation(Content.class); String[] accept = request.getHeaders() .getOrDefault("accept", Collections.emptyList()) .stream() .flatMap(i -> Stream.of(i.split("\\s*,\\s*")) .map(j -> j.replaceAll(";.*$", "") .trim() .toLowerCase(Locale.ENGLISH))) .toArray(String[]::new); Tool.ifPresentOr(Tool.or(mime, () -> Stream.of(accept) .filter(i -> content == null || Stream.of(content.value()) .anyMatch(i::equals)) .findFirst()), m -> r.contentType(m, Tool.isTextContent(path) ? StandardCharsets.UTF_8 : null), () -> { throw new RuntimeException("not accept mime type: " + Arrays.toString(accept)); }); }; if (response instanceof Response) { Tool.peek((Response) response, r -> { if (r.headers == null || !r.headers.containsKey("Content-Type")) { setContentType.accept(r); } }) .flush(); } else { Tool.peek(Response.of(response), setContentType::accept) .flush(); } return; } catch (InvocationTargetException e) { db.ifGot(Db::rollback); Throwable t = e.getCause(); if (t instanceof RuntimeException) { throw (RuntimeException) t; } throw new RuntimeException(t); } catch (IllegalAccessException e) { db.ifGot(Db::rollback); throw new RuntimeException(e); } catch (RuntimeException e) { db.ifGot(Db::rollback); throw e; } } catch(Exception e) { Throwable t = e.getCause(); if (t != null && ("ClientAbortException".equals(t.getClass().getSimpleName()) || t.getMessage().startsWith("") || t.getMessage().startsWith("An established connection"))) { Log.warning(t.toString()); return; } else { throw e; } } } while (false); } /* static file */ try { Response.file(path).flush(); } catch(Exception e) { Throwable t = e.getCause(); if (t != null && "ClientAbortException".equals(t.getClass().getSimpleName())) { Log.warning(t.toString()); } else { throw e; } } } }
package io.bitsquare; import io.bitsquare.msg.SeedNodeAddress; import java.io.IOException; import java.util.List; import net.tomp2p.dht.PeerBuilderDHT; import net.tomp2p.futures.BaseFuture; import net.tomp2p.futures.BaseFutureListener; import net.tomp2p.nat.PeerBuilderNAT; import net.tomp2p.p2p.Peer; import net.tomp2p.p2p.PeerBuilder; import net.tomp2p.peers.Number160; import net.tomp2p.peers.PeerAddress; import net.tomp2p.peers.PeerMapChangeListener; import net.tomp2p.peers.PeerStatatistic; import net.tomp2p.relay.RconRPC; import net.tomp2p.relay.RelayRPC; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Well known node which is reachable for all peers for bootstrapping. * There will be several SeedNodes running on several servers. * <p> * TODO: Alternative bootstrap methods will follow later (save locally list of known nodes reported form other peers...) */ public class SeedNode extends Thread { private static final Logger log = LoggerFactory.getLogger(SeedNode.class); private static final List<SeedNodeAddress.StaticSeedNodeAddresses> staticSedNodeAddresses = SeedNodeAddress .StaticSeedNodeAddresses.getAllSeedNodeAddresses(); /** * @param args If no args passed we use localhost, otherwise the param is used as index for selecting an address * from seedNodeAddresses */ public static void main(String[] args) { SeedNodeAddress seedNodeAddress; if (args.length > 0) { int index = 0; // use host index passes as param int param = Integer.valueOf(args[0]); if (param < staticSedNodeAddresses.size()) index = param; seedNodeAddress = new SeedNodeAddress(staticSedNodeAddresses.get(index)); } else { seedNodeAddress = new SeedNodeAddress(SeedNodeAddress.StaticSeedNodeAddresses.LOCALHOST); } SeedNode seedNode = new SeedNode(seedNodeAddress); seedNode.setDaemon(true); seedNode.start(); try { // keep main thread up Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException e) { log.error(e.toString()); } } private final SeedNodeAddress seedNodeAddress; // Constructor public SeedNode(SeedNodeAddress seedNodeAddress) { this.seedNodeAddress = seedNodeAddress; } // Public Methods public void run() { startupPeer(); for (; ; ) { try { // ping(peer); Thread.sleep(300); } catch (InterruptedException e) { log.error(e.toString()); } } } public void startupPeer() { Peer peer; try { peer = new PeerBuilder( Number160.createHash(seedNodeAddress.getId())).ports(seedNodeAddress.getPort()).start(); // Need to add all features the clients will use (otherwise msg type is UNKNOWN_ID) new PeerBuilderDHT(peer).start(); //PeerNAT nodeBehindNat = new PeerBuilderNAT(peer).start(); new PeerBuilderNAT(peer); RconRPC rconRPC = new RconRPC(peer); new RelayRPC(peer, rconRPC); //new PeerBuilderTracker(peer); //nodeBehindNat.startSetupRelay(new FutureRelay()); log.debug("Peer started. " + peer.peerAddress()); peer.peerBean().peerMap().addPeerMapChangeListener(new PeerMapChangeListener() { @Override public void peerInserted(PeerAddress peerAddress, boolean verified) { log.debug("Peer inserted: peerAddress=" + peerAddress + ", verified=" + verified); } @Override public void peerRemoved(PeerAddress peerAddress, PeerStatatistic peerStatistics) { log.debug("Peer removed: peerAddress=" + peerAddress + ", peerStatistics=" + peerStatistics); } @Override public void peerUpdated(PeerAddress peerAddress, PeerStatatistic peerStatistics) { // log.debug("Peer updated: peerAddress=" + peerAddress + ", peerStatistics=" + peerStatistics); } }); } catch (IOException e) { log.info("If the second client has been started that message is ok, as we cannot start the seed node twice." + e.getMessage()); // e.printStackTrace(); } } private void ping(Peer peer) { if (peer != null) return; try { // Optional pinging for (PeerAddress peerAddress : peer.peerBean().peerMap().all()) { BaseFuture future = peer.ping().peerAddress(peerAddress).tcpPing().start(); future.addListener(new BaseFutureListener<BaseFuture>() { @Override public void operationComplete(BaseFuture future) throws Exception { if (future.isSuccess()) { log.debug("peer online (TCP):" + peerAddress); } else { log.debug("offline " + peerAddress); } } @Override public void exceptionCaught(Throwable t) throws Exception { log.error("exceptionCaught " + t); } }); future = peer.ping().peerAddress(peerAddress).start(); future.addListener(new BaseFutureListener<BaseFuture>() { @Override public void operationComplete(BaseFuture future) throws Exception { if (future.isSuccess()) { log.debug("peer online (UDP):" + peerAddress); } else { log.debug("offline " + peerAddress); } } @Override public void exceptionCaught(Throwable t) throws Exception { log.error("exceptionCaught " + t); } }); Thread.sleep(1500); } } catch (Exception e) { log.error("Exception: " + e); } } }
package mcjty.rftools; import mcjty.lib.base.ModBase; import mcjty.lib.compat.MainCompatHandler; import mcjty.lib.varia.Logging; import mcjty.rftools.api.screens.IScreenModuleRegistry; import mcjty.rftools.api.teleportation.ITeleportationManager; import mcjty.rftools.apiimpl.ScreenModuleRegistry; import mcjty.rftools.apiimpl.TeleportationManager; import mcjty.rftools.blocks.blockprotector.BlockProtectorConfiguration; import mcjty.rftools.blocks.blockprotector.BlockProtectors; import mcjty.rftools.blocks.logic.wireless.RedstoneChannels; import mcjty.rftools.blocks.powercell.PowerCellNetwork; import mcjty.rftools.blocks.security.SecurityChannels; import mcjty.rftools.blocks.security.SecurityConfiguration; import mcjty.rftools.blocks.storage.RemoteStorageIdRegistry; import mcjty.rftools.blocks.teleporter.TeleportDestinations; import mcjty.rftools.commands.CommandRftCfg; import mcjty.rftools.commands.CommandRftDb; import mcjty.rftools.commands.CommandRftShape; import mcjty.rftools.commands.CommandRftTp; import mcjty.rftools.integration.computers.OpenComputersIntegration; import mcjty.rftools.items.ModItems; import mcjty.rftools.items.manual.GuiRFToolsManual; import mcjty.rftools.proxy.CommonProxy; import mcjty.rftools.shapes.ScanDataManager; import mcjty.rftools.wheelsupport.WheelSupport; import mcjty.rftools.xnet.XNetSupport; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.*; import java.util.Optional; import java.util.function.Function; @Mod(modid = RFTools.MODID, name = "RFTools", dependencies = "required-after:mcjtylib_ng@[" + RFTools.MIN_MCJTYLIB_VER + ",);" + "before:xnet@[" + RFTools.MIN_XNET_VER + ",);" + "after:forge@[" + RFTools.MIN_FORGE_VER + ",)", acceptedMinecraftVersions = "[1.12,1.13)", version = RFTools.VERSION) public class RFTools implements ModBase { public static final String MODID = "rftools"; public static final String VERSION = "7.22"; public static final String MIN_FORGE_VER = "14.22.0.2464"; public static final String MIN_MCJTYLIB_VER = "2.6.1"; public static final String MIN_XNET_VER = "1.6.0"; @SidedProxy(clientSide = "mcjty.rftools.proxy.ClientProxy", serverSide = "mcjty.rftools.proxy.ServerProxy") public static CommonProxy proxy; @Mod.Instance("rftools") public static RFTools instance; // Are some mods loaded?. public boolean rftoolsDimensions = false; public boolean xnet = false; public static boolean redstoneflux = false; public static ScreenModuleRegistry screenModuleRegistry = new ScreenModuleRegistry(); /** * This is used to keep track of GUIs that we make */ private static int modGuiIndex = 0; public ClientInfo clientInfo = new ClientInfo(); @Override public String getModId() { return MODID; } public static CreativeTabs tabRfTools = new CreativeTabs("RfTools") { @Override public ItemStack getTabIconItem() { return new ItemStack(ModItems.rfToolsManualItem); } }; public static final String SHIFT_MESSAGE = "<Press Shift>"; /** * Set our custom inventory Gui index to the next available Gui index */ public static final int GUI_MANUAL_MAIN = modGuiIndex++; public static final int GUI_MANUAL_SHAPE = modGuiIndex++; public static final int GUI_COALGENERATOR = modGuiIndex++; public static final int GUI_CRAFTER = modGuiIndex++; public static final int GUI_MODULAR_STORAGE = modGuiIndex++; public static final int GUI_REMOTE_STORAGE = modGuiIndex++; public static final int GUI_STORAGE_FILTER = modGuiIndex++; public static final int GUI_MODIFIER_MODULE = modGuiIndex++; public static final int GUI_REMOTE_STORAGE_ITEM = modGuiIndex++; public static final int GUI_MODULAR_STORAGE_ITEM = modGuiIndex++; public static final int GUI_REMOTE_STORAGESCANNER_ITEM = modGuiIndex++; public static final int GUI_DIALING_DEVICE = modGuiIndex++; public static final int GUI_MATTER_RECEIVER = modGuiIndex++; public static final int GUI_MATTER_TRANSMITTER = modGuiIndex++; public static final int GUI_ADVANCEDPORTER = modGuiIndex++; public static final int GUI_TELEPORTPROBE = modGuiIndex++; public static final int GUI_SCREEN = modGuiIndex++; public static final int GUI_SCREENCONTROLLER = modGuiIndex++; public static final int GUI_COUNTER = modGuiIndex++; public static final int GUI_SEQUENCER = modGuiIndex++; public static final int GUI_TIMER = modGuiIndex++; public static final int GUI_THREE_LOGIC = modGuiIndex++; public static final int GUI_MACHINE_INFUSER = modGuiIndex++; public static final int GUI_BUILDER = modGuiIndex++; public static final int GUI_SHAPECARD = modGuiIndex++; public static final int GUI_SHAPECARD_COMPOSER = modGuiIndex++; public static final int GUI_CHAMBER_DETAILS = modGuiIndex++; public static final int GUI_POWERCELL = modGuiIndex++; public static final int GUI_RELAY = modGuiIndex++; public static final int GUI_LIQUID_MONITOR = modGuiIndex++; public static final int GUI_RF_MONITOR = modGuiIndex++; public static final int GUI_SHIELD = modGuiIndex++; public static final int GUI_ENVIRONMENTAL_CONTROLLER = modGuiIndex++; public static final int GUI_MATTER_BEAMER = modGuiIndex++; public static final int GUI_SPAWNER = modGuiIndex++; public static final int GUI_BLOCK_PROTECTOR = modGuiIndex++; public static final int GUI_ITEMFILTER = modGuiIndex++; public static final int GUI_SECURITY_MANAGER = modGuiIndex++; public static final int GUI_DEVELOPERS_DELIGHT = modGuiIndex++; public static final int GUI_LIST_BLOCKS = modGuiIndex++; public static final int GUI_ENDERGENIC = modGuiIndex++; public static final int GUI_PEARL_INJECTOR = modGuiIndex++; public static final int GUI_ENDERMONITOR = modGuiIndex++; public static final int GUI_STORAGE_SCANNER = modGuiIndex++; public static final int GUI_BOOSTER = modGuiIndex++; public static final int GUI_INVCHECKER = modGuiIndex++; public static final int GUI_SENSOR = modGuiIndex++; public static final int GUI_STORAGE_TERMINAL = modGuiIndex++; public static final int GUI_STORAGE_TERMINAL_SCANNER = modGuiIndex++; public static final int GUI_ELEVATOR = modGuiIndex++; public static final int GUI_COMPOSER = modGuiIndex++; public static final int GUI_SCANNER = modGuiIndex++; public static final int GUI_PROJECTOR = modGuiIndex++; public static final int GUI_LOCATOR = modGuiIndex++; /** * Run before anything else. Read your config, create blocks, items, etc, and * register them with the GameRegistry. */ @Mod.EventHandler public void preInit(FMLPreInitializationEvent e) { proxy.preInit(e); MainCompatHandler.registerWaila(); MainCompatHandler.registerTOP(); WheelSupport.registerWheel(); } /** * Do your mod setup. Build whatever data structures you care about. Register recipes. */ @Mod.EventHandler public void init(FMLInitializationEvent e) { proxy.init(e); Achievements.init(); rftoolsDimensions = Loader.isModLoaded("rftoolsdim"); if (rftoolsDimensions) { Logging.log("RFTools Detected Dimensions addon: enabling support"); FMLInterModComms.sendFunctionMessage("rftoolsdim", "getDimensionManager", "mcjty.rftools.apideps.RFToolsDimensionChecker$GetDimensionManager"); } FMLInterModComms.sendFunctionMessage("theoneprobe", "getTheOneProbe", "mcjty.rftools.theoneprobe.TheOneProbeSupport"); redstoneflux = Loader.isModLoaded("redstoneflux"); if (redstoneflux) { Logging.log("RFTools Detected RedstoneFlux: enabling support"); } xnet = Loader.isModLoaded("xnet"); if (xnet) { Logging.log("RFTools Detected XNet: enabling support"); FMLInterModComms.sendFunctionMessage("xnet", "getXNet", XNetSupport.GetXNet.class.getName()); } if (Loader.isModLoaded("opencomputers")) { OpenComputersIntegration.init(); } } @Mod.EventHandler public void serverLoad(FMLServerStartingEvent event) { event.registerServerCommand(new CommandRftTp()); event.registerServerCommand(new CommandRftShape()); event.registerServerCommand(new CommandRftDb()); event.registerServerCommand(new CommandRftCfg()); } @Mod.EventHandler public void serverStopped(FMLServerStoppedEvent event) { Logging.log("RFTools: server is stopping. Shutting down gracefully"); TeleportDestinations.clearInstance(); RemoteStorageIdRegistry.clearInstance(); RedstoneChannels.clearInstance(); PowerCellNetwork.clearInstance(); ScanDataManager.clearInstance(); if(SecurityConfiguration.enabled) SecurityChannels.clearInstance(); if(BlockProtectorConfiguration.enabled) BlockProtectors.clearInstance(); } /** * Handle interaction with other mods, complete your setup based on this. */ @Mod.EventHandler public void postInit(FMLPostInitializationEvent e) { proxy.postInit(e); } @Mod.EventHandler public void imcCallback(FMLInterModComms.IMCEvent event) { for (FMLInterModComms.IMCMessage message : event.getMessages()) { if (message.key.equalsIgnoreCase("getApi") || message.key.equalsIgnoreCase("getTeleportationManager")) { Optional<Function<ITeleportationManager, Void>> value = message.getFunctionValue(ITeleportationManager.class, Void.class); value.get().apply(new TeleportationManager()); } else if (message.key.equalsIgnoreCase("getScreenModuleRegistry")) { Optional<Function<IScreenModuleRegistry, Void>> value = message.getFunctionValue(IScreenModuleRegistry.class, Void.class); value.get().apply(screenModuleRegistry); } } } @Override public void openManual(EntityPlayer player, int bookIndex, String page) { GuiRFToolsManual.locatePage = page; player.openGui(RFTools.instance, bookIndex, player.getEntityWorld(), (int) player.posX, (int) player.posY, (int) player.posZ); } }
package model.job; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; /** * Represents the progress of a Job. Job Workers can fire update to the progress * of a Job throughout Job Processing to keep users and other components current * with the processing. * * @author Patrick.Doody * */ @JsonInclude(Include.NON_NULL) public class JobProgress { public Integer percentComplete; public String timeRemaining; public String timeSpent; public JobProgress() { } public JobProgress(Integer percentComplete) { this.percentComplete = percentComplete; } public Integer getPercentComplete() { return percentComplete; } }
package hu.webarticum.treeprinter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class TraditionalTreePrinter extends AbstractTreePrinter { static public final Aligner DEFAULT_ALIGNER = new DefaultAligner(); static public final Liner DEFAULT_LINER = new DefaultLiner(); private final Aligner aligner; private final Liner liner; public TraditionalTreePrinter() { this(DEFAULT_ALIGNER, DEFAULT_LINER); } public TraditionalTreePrinter(Aligner aligner, Liner liner) { this.aligner = aligner; this.liner = liner; } @Override public void print(TreeNode rootNode, Appendable out) { Map<TreeNode, Integer> widthMap = new HashMap<TreeNode, Integer>(); int rootWidth = aligner.collectWidths(widthMap, rootNode); Map<TreeNode, Position> positionMap = new HashMap<TreeNode, Position>(); String rootContent = rootNode.getContent(); int[] rootContentDimension = Util.getContentDimension(rootContent); Align rootAlign = aligner.alignNode(rootNode, 0, rootWidth, rootContentDimension[0]); positionMap.put(rootNode, new Position(0, 0, rootAlign.bottomConnection, rootAlign.left, rootContentDimension[1])); LineBuffer buffer = new LineBuffer(out); buffer.write(0, rootAlign.left, rootContent); buffer.flush(); while (true) { Map<TreeNode, Position> newPositionMap = new HashMap<TreeNode, Position>(); List<Integer> childBottoms = new ArrayList<Integer>(); for (Map.Entry<TreeNode, Position> entry: positionMap.entrySet()) { TreeNode node = entry.getKey(); Position position = entry.getValue(); Map<TreeNode, Position> childrenPositionMap = new HashMap<TreeNode, Position>(); List<TreeNode> children = node.getChildren(); children.removeAll(Collections.singleton(null)); int[] childrenAlign = aligner.alignChildren(node, children, position.col, widthMap); if (!children.isEmpty()) { int childCount = children.size(); List<Integer> childConnections = new ArrayList<Integer>(childCount); for (int i = 0; i < childCount; i++) { int childCol = childrenAlign[i]; TreeNode childNode = children.get(i); int childWidth = widthMap.get(childNode); String childContent = childNode.getContent(); int[] childContentDimension = Util.getContentDimension(childContent); Align childAlign = aligner.alignNode(childNode, childCol, childWidth, childContentDimension[0]); Position childPositioning = new Position( position.row + position.height, childCol, childAlign.bottomConnection, childAlign.left, childContentDimension[1] ); childrenPositionMap.put(childNode, childPositioning); childConnections.add(childAlign.topConnection); } int connectionRows = liner.printConnections( buffer, position.row + position.height, position.connection, childConnections ); for (Map.Entry<TreeNode, Position> childEntry: childrenPositionMap.entrySet()) { TreeNode childNode = childEntry.getKey(); Position childPositionItem = childEntry.getValue(); childPositionItem.row += connectionRows; buffer.write(childPositionItem.row, childPositionItem.left, childNode.getContent()); childBottoms.add(childPositionItem.row + childPositionItem.height); } newPositionMap.putAll(childrenPositionMap); } } if (newPositionMap.isEmpty()) { break; } else { int minimumChildBottom = Integer.MAX_VALUE; for (int bottomValue: childBottoms) { if (bottomValue < minimumChildBottom) { minimumChildBottom = bottomValue; } } buffer.flush(minimumChildBottom); positionMap = newPositionMap; } } buffer.flush(); } public interface Aligner { public Align alignNode(TreeNode node, int position, int width, int contentWidth); public int[] alignChildren(TreeNode parentNode, List<TreeNode> children, int position, Map<TreeNode, Integer> widthMap); public int collectWidths(Map<TreeNode, Integer> widthMap, TreeNode node); } public static class DefaultAligner implements Aligner { public static int LEFT = 0; public static int CENTER = 1; public static int RIGHT = 2; public static int CONNECT_TO_CONTENT = 0; public static int CONNECT_TO_CONTEXT = 1; private final int contentAlign; private final int contentOffset; private final int topConnectionConnect; private final int topConnectionAlign; private final int topConnectionOffset; private final int bottomConnectionConnect; private final int bottomConnectionAlign; private final int bottomConnectionOffset; private final int childrenAlign; private final int gap; public DefaultAligner() { this(CENTER); } public DefaultAligner(int align) { this(align, 1); } public DefaultAligner(int align, int gap) { this(align, 0, CONNECT_TO_CONTENT, align, 0, CONNECT_TO_CONTENT, align, 0, align, gap); } public DefaultAligner( int contentAlign, int contentOffset, int topConnectionConnect, int topConnectionAlign, int topConnectionOffset, int bottomConnectionConnect, int bottomConnectionAlign, int bottomConnectionOffset, int childrenAlign, int gap ) { this.contentAlign = contentAlign; this.contentOffset = contentOffset; this.topConnectionConnect = topConnectionConnect; this.topConnectionAlign = topConnectionAlign; this.topConnectionOffset = topConnectionOffset; this.bottomConnectionConnect = bottomConnectionConnect; this.bottomConnectionAlign = bottomConnectionAlign; this.bottomConnectionOffset = bottomConnectionOffset; this.childrenAlign = childrenAlign; this.gap = gap; } @Override public Align alignNode(TreeNode node, int position, int width, int contentWidth) { int contentMaxLeft = position + width - contentWidth; int connectionMaxLeft = position + width - 1; int left; if (contentAlign == LEFT) { left = position; } else if (contentAlign == RIGHT) { left = contentMaxLeft; } else { left = position + (width - contentWidth) / 2; } left = Math.max(0, Math.min(contentMaxLeft, left + contentOffset)); int topConnection; if (topConnectionConnect == CONNECT_TO_CONTENT) { if (topConnectionAlign == LEFT) { topConnection = left; } else if (topConnectionAlign == RIGHT) { topConnection = left + contentWidth - 1; } else { topConnection = left + (contentWidth / 2); } } else { if (topConnectionAlign == LEFT) { topConnection = position; } else if (topConnectionAlign == RIGHT) { topConnection = connectionMaxLeft; } else { topConnection = position + ((width - contentWidth) / 2); } } topConnection = Math.max(0, Math.min(connectionMaxLeft, topConnection + topConnectionOffset)); int bottomConnection; if (bottomConnectionConnect == CONNECT_TO_CONTENT) { if (bottomConnectionAlign == LEFT) { bottomConnection = left; } else if (bottomConnectionAlign == RIGHT) { bottomConnection = left + contentWidth - 1; } else { bottomConnection = left + (contentWidth / 2); } } else { if (bottomConnectionAlign == LEFT) { bottomConnection = position; } else if (bottomConnectionAlign == RIGHT) { bottomConnection = connectionMaxLeft; } else { bottomConnection = position + ((width - contentWidth) / 2); } } bottomConnection = Math.max(0, Math.min(connectionMaxLeft, bottomConnection + bottomConnectionOffset)); return new Align(left, topConnection, bottomConnection); } @Override public int[] alignChildren(TreeNode parentNode, List<TreeNode> children, int position, Map<TreeNode, Integer> widthMap) { int[] result = new int[children.size()]; int childrenCount = children.size(); int childrenWidth = 0; boolean first = true; for (int i = 0; i < childrenCount; i++) { TreeNode childNode = children.get(i); if (first) { first = false; } else { childrenWidth += gap; } int childWidth = widthMap.get(childNode); result[i] = position + childrenWidth; childrenWidth += childWidth; } int parentWidth = widthMap.get(parentNode); int offset = 0; if (childrenAlign == RIGHT) { offset = parentWidth - childrenWidth; } else if (childrenAlign == CENTER) { offset = (parentWidth - childrenWidth) / 2; } if (offset > 0) { for (int i = 0; i < childrenCount; i++) { result[i] += offset; } } return result; } @Override public int collectWidths(Map<TreeNode, Integer> widthMap, TreeNode node) { int contentWidth = Util.getContentDimension(node.getContent())[0]; int childrenWidth = 0; boolean first = true; List<TreeNode> children = node.getChildren(); children.removeAll(Collections.singleton(null)); for (TreeNode childNode: children) { if (first) { first = false; } else { childrenWidth += gap; } childrenWidth += collectWidths(widthMap, childNode); } int nodeWidth = Math.max(contentWidth, childrenWidth); widthMap.put(node, nodeWidth); return nodeWidth; } } public static class Align { final int left; final int topConnection; final int bottomConnection; public Align(int left, int topConnection, int bottomConnection) { this.left = left; this.topConnection = topConnection; this.bottomConnection = bottomConnection; } } public interface Liner { public int printConnections(LineBuffer buffer, int row, int topConnection, List<Integer> bottomConnections); } public static class DefaultLiner implements Liner { private final char topConnectionChar; private final char bracketLeftChar; private final char bracketChar; private final char bracketTopChar; private final char bracketTopLeftChar; private final char bracketTopRightChar; private final char bracketBottomChar; private final char bracketTopAndBottomChar; private final char bracketTopAndBottomLeftChar; private final char bracketTopAndBottomRightChar; private final char bracketRightChar; private final char bracketOnlyChar; private final char bottomConnectionChar; private final int topHeight; private final int bottomHeight; private final boolean displayBracket; public DefaultLiner() { this('|', ' ', '_', '|', '|', '|', '_', '|', '|', '|', ' ', '|', '|', 0, 1, true); } public DefaultLiner( char topConnectionChar, char bracketLeftChar, char bracketChar, char bracketTopChar, char bracketTopLeftChar, char bracketTopRightChar, char bracketBottomChar, char bracketTopAndBottomChar, char bracketTopAndBottomLeftChar, char bracketTopAndBottomRightChar, char bracketRightChar, char bracketOnlyChar, char bottomConnectionChar, int topHeight, int bottomHeight, boolean displayBracket ) { this.topConnectionChar = topConnectionChar; this.bracketLeftChar = bracketLeftChar; this.bracketChar = bracketChar; this.bracketTopChar = bracketTopChar; this.bracketTopLeftChar = bracketTopLeftChar; this.bracketTopRightChar = bracketTopRightChar; this.bracketBottomChar = bracketBottomChar; this.bracketTopAndBottomChar = bracketTopAndBottomChar; this.bracketTopAndBottomLeftChar = bracketTopAndBottomLeftChar; this.bracketTopAndBottomRightChar = bracketTopAndBottomRightChar; this.bracketRightChar = bracketRightChar; this.bracketOnlyChar = bracketOnlyChar; this.bottomConnectionChar = bottomConnectionChar; this.topHeight = topHeight; this.bottomHeight = bottomHeight; this.displayBracket = displayBracket; } @Override public int printConnections(LineBuffer buffer, int row, int topConnection, List<Integer> bottomConnections) { int start = Math.min(topConnection, bottomConnections.get(0)); int end = Math.max(topConnection, bottomConnections.get(bottomConnections.size() - 1)); int topHeightWithBracket = topHeight + (displayBracket ? 1 : 0); int fullHeight = topHeightWithBracket + bottomHeight; { StringBuilder topConnectionLineBuilder = new StringBuilder(); Util.repeat(topConnectionLineBuilder, ' ', topConnection - start); topConnectionLineBuilder.append(topConnectionChar); String topConnectionLine = topConnectionLineBuilder.toString(); for (int i = 0; i < topHeight; i++) { buffer.write(row + i, start, topConnectionLine); } } { StringBuilder bracketLineBuilder = new StringBuilder(); for (int i = start; i <= end; i++) { char character; if (start == end) { character = bracketOnlyChar; } else if (i == topConnection) { if (bottomConnections.contains(i)) { if (i == start) { character = bracketTopAndBottomLeftChar; } else if (i == end) { character = bracketTopAndBottomRightChar; } else { character = bracketTopAndBottomChar; } } else { if (i == start) { character = bracketTopLeftChar; } else if (i == end) { character = bracketTopRightChar; } else { character = bracketTopChar; } } } else if (i == start) { character = bracketLeftChar; } else if (i == end) { character = bracketRightChar; } else { if (bottomConnections.contains(i)) { character = bracketBottomChar; } else { character = bracketChar; } } bracketLineBuilder.append(character); } buffer.write(row + topHeight, start, bracketLineBuilder.toString()); } { StringBuilder bottomConnectionLineBuilder = new StringBuilder(); int position = start; for (int bottomConnection: bottomConnections) { for (int i = position; i < bottomConnection; i++) { bottomConnectionLineBuilder.append(' '); } bottomConnectionLineBuilder.append(bottomConnectionChar); position = bottomConnection + 1; } String bottomConnectionLine = bottomConnectionLineBuilder.toString(); for (int i = topHeightWithBracket; i < fullHeight; i++) { buffer.write(row + i, start, bottomConnectionLine); } } return fullHeight; } } private class Position { int row; int col; int connection; int left; int height; Position(int row, int col, int connection, int left, int height) { this.row = row; this.col = col; this.connection = connection; this.left = left; this.height = height; } } }
package org.apache.james.transport.mailets; import org.apache.mailet.GenericMailet; import org.apache.mailet.Mail; import org.apache.mailet.MailAddress; import org.apache.mailet.MailetException; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import java.io.IOException; import java.util.Collection; import java.util.Vector; /** * An abstract implementation of a listserv. The underlying implementation must define * various settings, and can vary in their individual configuration. Supports restricting * to members only, allowing attachments or not, sending replies back to the list, and an * optional subject prefix. */ public abstract class GenericListserv extends GenericMailet { /** * Returns a Collection of MailAddress objects of members to receive this email */ public abstract Collection getMembers() throws MessagingException; /** * Returns whether this list should restrict to senders only */ public abstract boolean isMembersOnly() throws MessagingException; /** * Returns whether this listserv allow attachments */ public abstract boolean isAttachmentsAllowed() throws MessagingException; /** * Returns whether listserv should add reply-to header */ public abstract boolean isReplyToList() throws MessagingException; /** * The email address that this listserv processes on. If returns null, will use the * recipient of the message, which hopefully will be the correct email address assuming * the matcher was properly specified. */ public MailAddress getListservAddress() throws MessagingException { return null; } /** * An optional subject prefix which will be surrounded by []. */ public abstract String getSubjectPrefix() throws MessagingException; /** * Processes the message. Assumes it is the only recipient of this forked message. */ public final void service(Mail mail) throws MessagingException { try { Collection members = new Vector(); members.addAll(getMembers()); //Check for members only flag.... if (isMembersOnly() && !members.contains(mail.getSender())) { //Need to bounce the message to say they can't send to this list getMailetContext().bounce(mail, "Only members of this listserv are allowed to send a message to this address."); mail.setState(Mail.GHOST); return; } //Check for no attachments if (!isAttachmentsAllowed() && mail.getMessage().getContent() instanceof MimeMultipart) { getMailetContext().bounce(mail, "You cannot send attachments to this listserv."); mail.setState(Mail.GHOST); return; } //Create a copy of this message to send out MimeMessage message = new MimeMessage(mail.getMessage()); //We need to remove this header from the copy we're sending around message.removeHeader("Return-Path"); //Figure out the listserv address. MailAddress listservAddr = getListservAddress(); if (listservAddr == null) { //Use the recipient listservAddr = (MailAddress)mail.getRecipients().iterator().next(); } //Check if the X-been-there header is set to the listserv's name // (the address). If it has, this means it's a message from this // listserv that's getting bounced back, so we need to swallow it if (listservAddr.equals(message.getHeader("X-been-there"))) { mail.setState(Mail.GHOST); return; } //Set the subject if set if (getSubjectPrefix() != null) { String prefix = "[" + getSubjectPrefix() + "]"; String subj = message.getSubject(); if (subj == null) { subj = ""; } //replace Re: with RE: String re ="Re:"; int index = subj.indexOf(re); while(index > -1){ subj = subj.substring(0, index) +"RE:"+ subj.substring(index + re.length() + 1); index = subj.indexOf(re); } //reduce them to one at the beginning re ="RE:"; index = subj.indexOf(re,re.length()); System.err.println("3i-"+index); while(index > 0){ subj = subj.substring(0, index) + subj.substring(index + re.length() + 1); index = subj.indexOf(re,1); } //If the "prefix" is in the subject line, remove it and everything before it int index = subj.indexOf(prefix); if (index > -1) { if (index == 0) { subj = prefix + ' ' + subj.substring(index + prefix.length() + 1); } else { subj = prefix + ' ' + subj.substring(0, index) + subj.substring(index + prefix.length() + 1); } } else { subj = prefix + ' ' + subj; } message.setSubject(subj); } //If replies should go to this list, we need to set the header if (isReplyToList()) { message.setHeader("Reply-To", listservAddr.toString()); } //We're going to set this special header to avoid bounces // getting sent back out to the list message.setHeader("X-been-there", listservAddr.toString()); //Send the message to the list members //We set the postmaster as the sender for now so bounces go to him/her getMailetContext().sendMail(getMailetContext().getPostmaster(), members, message); //Kill the old message mail.setState(Mail.GHOST); } catch (IOException ioe) { throw new MailetException("Error creating listserv message", ioe); } } }
package org.basex; import static org.basex.core.Text.*; import java.io.*; import java.net.*; import java.util.*; import org.basex.core.*; import org.basex.io.*; import org.basex.io.in.*; import org.basex.server.*; import org.basex.util.*; import org.basex.util.list.*; public final class BaseXServer extends Main implements Runnable { /** Flag for server activity. */ private volatile boolean running; /** Event server socket. */ private ServerSocket esocket; /** Stop file. */ private IOFile stop; /** New sessions. */ private final HashSet<ClientListener> auth = new HashSet<ClientListener>(); /** Stopped flag. */ private volatile boolean stopped; /** EventsListener. */ private EventListener events; /** Initial commands. */ private StringList commands; /** Server socket. */ private ServerSocket socket; /** Start as daemon. */ private boolean service; /** * Main method, launching the server process. * Command-line arguments are listed with the {@code -h} argument. * @param args command-line arguments */ public static void main(final String[] args) { try { new BaseXServer(args); } catch(final IOException ex) { Util.errln(ex); System.exit(1); } } /** * Constructor. * @param args command-line arguments * @throws IOException I/O exception */ public BaseXServer(final String... args) throws IOException { this(null, args); } /** * Constructor. * @param ctx database context * @param args command-line arguments * @throws IOException I/O exception */ public BaseXServer(final Context ctx, final String... args) throws IOException { super(args, ctx); final MainProp mprop = context.mprop; final int port = mprop.num(MainProp.SERVERPORT); final int eport = mprop.num(MainProp.EVENTPORT); // check if ports are distinct if(port == eport) throw new BaseXException(PORT_TWICE_X, port); final String host = mprop.get(MainProp.SERVERHOST); final InetAddress addr = host.isEmpty() ? null : InetAddress.getByName(host); if(service) { start(port, args); Util.outln(SRV_STARTED_PORT_X, port); Performance.sleep(1000); return; } if(stopped) { stop(port, eport); Util.outln(SRV_STOPPED_PORT_X, port); Performance.sleep(1000); return; } try { // execute command-line arguments for(final String c : commands) execute(c); socket = new ServerSocket(); // reuse address (on non-Windows machines: !Prop.WIN); socket.setReuseAddress(true); socket.bind(new InetSocketAddress(addr, port)); esocket = new ServerSocket(); esocket.setReuseAddress(true); esocket.bind(new InetSocketAddress(addr, eport)); stop = stopFile(port); // show info when server is aborted context.log.writeServer(OK, Util.info(SRV_STARTED_PORT_X, port)); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { context.log.writeServer(OK, Util.info(SRV_STOPPED_PORT_X, port)); Util.outln(SRV_STOPPED_PORT_X, port); } }); new Thread(this).start(); while(!running) Performance.sleep(10); Util.outln(CONSOLE + (console ? TRY_MORE_X : Util.info(SRV_STARTED_PORT_X, port)), SERVERMODE); if(console) { console(); quit(); } } catch(final IOException ex) { context.log.writeError(ex); throw ex; } } @Override public void run() { running = true; while(running) { try { final Socket s = socket.accept(); if(stop.exists()) { if(!stop.delete()) { context.log.writeServer(ERROR_C + Util.info(FILE_NOT_DELETED_X, stop)); } quit(); } else { // drop inactive connections final long ka = context.mprop.num(MainProp.KEEPALIVE) * 1000L; if(ka > 0) { final long ms = System.currentTimeMillis(); for(final ClientListener cs : context.sessions) { if(ms - cs.last > ka) cs.quit(); } } final ClientListener cl = new ClientListener(s, context, this); // start authentication timeout final long to = context.mprop.num(MainProp.KEEPALIVE) * 1000L; if(to > 0) { cl.auth.schedule(new TimerTask() { @Override public void run() { cl.quitAuth(); } }, to); auth.add(cl); } cl.start(); } } catch(final SocketException ex) { break; } catch(final Throwable ex) { // socket may have been unexpectedly closed context.log.writeError(ex); break; } } } /** * Generates a stop file for the specified port. * @param port server port * @return stop file */ private static IOFile stopFile(final int port) { return new IOFile(Prop.TMP, Util.name(BaseXServer.class) + port); } @Override protected synchronized void quit() throws IOException { if(!running) return; running = false; for(final ClientListener cs : auth) { remove(cs); cs.quitAuth(); } for(final ClientListener cs : context.sessions) { cs.quit(); } super.quit(); try { // close interactive input if server was stopped by another process if(console) System.in.close(); esocket.close(); socket.close(); } catch(final IOException ex) { context.log.writeError(ex); } console = false; } @Override protected Session session() { if(session == null) session = new LocalSession(context, out); return session; } @Override protected void parseArguments(final String... args) throws IOException { final Args arg = new Args(args, this, SERVERINFO, Util.info(CONSOLE, SERVERMODE)); commands = new StringList(); boolean daemon = false; while(arg.more()) { if(arg.dash()) { switch(arg.next()) { case 'c': // send database commands commands.add(arg.string()); break; case 'd': // activate debug mode Prop.debug = true; break; case 'D': // hidden flag: daemon mode daemon = true; break; case 'e': // parse event port context.mprop.set(MainProp.EVENTPORT, arg.number()); break; case 'i': // activate interactive mode console = true; break; case 'n': // parse host the server is bound to context.mprop.set(MainProp.SERVERHOST, arg.string()); break; case 'p': // parse server port context.mprop.set(MainProp.SERVERPORT, arg.number()); break; case 'S': // set service flag service = !daemon; break; case 'z': // suppress logging context.mprop.set(MainProp.LOG, false); break; default: arg.usage(); } } else { if(arg.string().equalsIgnoreCase("stop")) { stopped = true; } else { arg.usage(); } } } } /** * Stops the server of this instance. * @throws IOException I/O exception */ public void stop() throws IOException { final MainProp mprop = context.mprop; stop(mprop.num(MainProp.SERVERPORT), mprop.num(MainProp.EVENTPORT)); } /** * Starts the database server in a separate process. * @param port server port * @param args command-line arguments * @throws BaseXException database exception */ public static void start(final int port, final String... args) throws BaseXException { // check if server is already running (needs some time) if(ping(LOCALHOST, port)) throw new BaseXException(SRV_RUNNING); Util.start(BaseXServer.class, args); // try to connect to the new server instance for(int c = 1; c < 10; ++c) { if(ping(LOCALHOST, port)) return; Performance.sleep(c * 100); } throw new BaseXException(CONNECTION_ERROR); } /** * Checks if a server is running. * @param host host * @param port server port * @return boolean success */ public static boolean ping(final String host, final int port) { try { // connect server with invalid login data new ClientSession(host, port, "", ""); return false; } catch(final LoginException ex) { // if login was checked, server is running return true; } catch(final IOException ex) { return false; } } /** * Stops the server. * @param port server port * @param eport event port * @throws IOException I/O exception */ public static void stop(final int port, final int eport) throws IOException { final IOFile stop = stopFile(port); try { stop.touch(); new Socket(LOCALHOST, eport).close(); new Socket(LOCALHOST, port).close(); // wait and check if server was really stopped do Performance.sleep(50); while(ping(LOCALHOST, port)); } catch(final IOException ex) { stop.delete(); throw ex; } } /** * Removes an authenticated session. * @param client client to be removed */ public void remove(final ClientListener client) { synchronized(auth) { auth.remove(client); client.auth.cancel(); } } /** * Initializes the event listener. */ public void initEvents() { if(events == null) { events = new EventListener(); events.start(); } } final class EventListener extends Thread { @Override public void run() { while(running) { try { final Socket es = esocket.accept(); if(stop.exists()) { esocket.close(); break; } final BufferInput bi = new BufferInput(es.getInputStream()); final long id = Token.toLong(bi.readString()); for(final ClientListener s : context.sessions) { if(s.getId() == id) { s.register(es); break; } } } catch(final IOException ex) { break; } } } } }
package com.itranswarp.shici.util; import java.awt.image.BufferedImage; import java.io.IOException; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Pattern; import com.itranswarp.shici.exception.APIArgumentException; import com.itranswarp.shici.model.User; import com.itranswarp.warpdb.IdUtil; public class ValidateUtil { static final Pattern ALIAS_PATTERN = Pattern.compile("^[a-z0-9]{1,50}$"); static final Pattern EMAIL_NAME_PATTERN = Pattern.compile("^[a-z0-9][a-z0-9_.-]*$"); static final Pattern EMAIL_DOMAIN_PATTERN = Pattern.compile("^[a-z0-9][a-z0-9-]*$"); // 1MB: static final int MAX_FILE_BASE64_LENGTH = 1026 * 1026 * 4 / 3; public static String checkId(String id) { return checkId(id, "id"); } public static String checkId(String id, String argName) { if (!IdUtil.isValidId(id)) { throw new APIArgumentException(argName); } return id; } public static String checkIdOrEmpty(String id) { return checkIdOrEmpty(id, "id"); } public static String checkIdOrEmpty(String id, String argName) { if (id == null || id.equals("")) { return ""; } return checkId(id, argName); } public static List<String> checkIds(List<String> ids) { if (ids == null) { throw new APIArgumentException("ids", "Ids cannot be null."); } Set<String> sets = new HashSet<String>(ids.size()); for (String id : ids) { if (!IdUtil.isValidId(id)) { throw new APIArgumentException("ids", "Ids contains invalid id."); } sets.add(id); } if (sets.size() != ids.size()) { throw new APIArgumentException("ids", "Contains duplicate id."); } return ids; } public static String checkNotes(String notes) { if (notes == null) { notes = ""; } notes = notes.trim(); // max to 512K: if (notes.length() > 524288) { throw new APIArgumentException("notes"); } return notes; } public static String checkAlias(String alias) { if (alias == null) { throw new APIArgumentException("alias"); } alias = alias.trim().toLowerCase(); if (alias.isEmpty() || alias.length() > 50) { throw new APIArgumentException("alias"); } if (!ALIAS_PATTERN.matcher(alias).matches()) { throw new APIArgumentException("alias"); } return alias; } public static String checkName(String name) { if (name == null) { throw new APIArgumentException("name"); } name = normalizeChinese(name); if (name.isEmpty() || name.length() > 100) { throw new APIArgumentException("name"); } return name; } public static String checkDescription(String description) { if (description == null) { return ""; } description = normalizeChinese(description); if (description.length() > 1000) { throw new APIArgumentException("description"); } return description; } public static String checkContent(String content) { if (content != null) { content = normalizeChinese(content); } // max to 512K: if (content == null || content.isEmpty() || content.length() > 524288) { throw new APIArgumentException("content"); } return content; } public static String checkAppreciation(String appreciation) { if (appreciation == null) { return ""; } appreciation = normalizeChinese(appreciation); if (appreciation.length() > 1000) { throw new APIArgumentException("appreciation"); } return appreciation; } public static String checkGender(String gender) { if (gender == null) { return User.Gender.UNKNOWN; } gender = gender.toLowerCase(); if (!User.Gender.SET.contains(gender)) { throw new APIArgumentException("gender"); } return gender; } public static long checkAdminRole(long role) { if (role != User.Role.ADMIN) { throw new APIArgumentException("role"); } return role; } public static String checkEmail(String email) { if (email == null) { throw new APIArgumentException("email"); } email = email.trim(); if (email.length() > 50) { throw new APIArgumentException("email"); } email = email.toLowerCase(); int pos = email.indexOf('@'); if (pos == (-1)) { throw new APIArgumentException("email"); } if (!EMAIL_NAME_PATTERN.matcher(email.substring(0, pos)).matches()) { throw new APIArgumentException("email"); } String[] ss = email.substring(pos + 1).split("\\."); if (ss.length <= 1 || ss.length >= 5) { throw new APIArgumentException("email"); } for (String s : ss) { if (!EMAIL_DOMAIN_PATTERN.matcher(s).matches()) { throw new APIArgumentException("email"); } } return email; } public static LocalDate checkDate(LocalDate date, String name) { if (date == null) { throw new APIArgumentException(name, name + " is empty."); } if (date.isBefore(LocalDate.of(2000, 1, 1))) { throw new APIArgumentException(name, name + " is out of range."); } if (date.isAfter(LocalDate.of(2099, 12, 31))) { throw new APIArgumentException(name, name + " is out of range."); } return date; } public static String checkTags(String tags) { if (tags == null) { return ""; } String[] ss = tags.split("[\\,\\;\\s\u00a0\u3000]+"); List<String> tagList = new ArrayList<String>(ss.length); for (String s : ss) { if (!s.isEmpty()) { tagList.add(s); } } return String.join(",", tagList); } public static String checkBase64Data(String data) { if (data == null) { return null; } if (data.isEmpty()) { throw new APIArgumentException("data", "data is empty."); } if (data.length() > MAX_FILE_BASE64_LENGTH) { throw new APIArgumentException("data", "data is too large."); } return data; } public static String checkImageData(String imageData) throws IOException { if (imageData == null || imageData.isEmpty()) { return null; } if (imageData.length() > MAX_FILE_BASE64_LENGTH) { throw new APIArgumentException("imageData", "File is too large."); } BufferedImage bi = ImageUtil.loadImage(Base64Util.decode(imageData)); if (bi == null) { throw new APIArgumentException("imageData", "Invalid image."); } // TODO: check format if (bi.getWidth() == 640 && bi.getHeight() == 360) { return imageData; } if (bi.getWidth() < 640 || bi.getHeight() < 360) { throw new APIArgumentException("imageData", "image is too small."); } BufferedImage scaled = ImageUtil.fitToSize(bi, 640, 360); byte[] scaledData = ImageUtil.toJpeg(scaled); String scaledB64Data = Base64Util.encodeToString(scaledData); if (scaledB64Data.length() > MAX_FILE_BASE64_LENGTH) { throw new APIArgumentException("imageData", "Scaled image is too large."); } return scaledB64Data; } public static String checkDateString(String name, String date) { if (date == null) { return ""; } date = date.trim(); if (date.length() > 10) { throw new APIArgumentException(name, "Date is too long."); } return date; } static final String TRIM_STRING = " " + "" + "\"\'“”[](){}0123456789\u00a0\u3000\t\r\n\0" + "⑴⑵⑶⑷⑸⑹⑺⑻⑼⑽⑾⑿⒀⒁⒂⒃⒄⒅⒆⒇" + "⒈⒉⒊⒋⒌⒍⒎⒏⒐⒑⒒⒓⒔⒕⒖⒗⒘⒙⒚⒛" + "①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳"; static final Set<String> SHOULD_REMOVE = new HashSet<String>(Arrays.asList(TRIM_STRING.split(""))); static final char[][] SHOULD_REPLACE = { { ',', '' }, { '.', '' }, { ';', '' }, { '?', '' }, { '!', '' }, { '\u25cf', '\u00b7' }, { '\u25cb', '\u00b7' }, { '\u2299', '\u00b7' }, { '\u00b0', '\u00b7' }, { '\u25aa', '\u00b7' }, { '\u25ab', '\u00b7' }, { '\u2022', '\u00b7' } }; public static String normalizeChinese(String s) { if (s == null) { return ""; } StringBuilder sb = new StringBuilder(s.length()); for (int i = 0; i < s.length(); i++) { String ch = s.substring(i, i + 1); if (!SHOULD_REMOVE.contains(ch)) { sb.append(ch); } } String r = sb.toString(); for (char[] repl : SHOULD_REPLACE) { r = r.replace(repl[0], repl[1]); } return r; } }
package org.ethereum.util; import java.math.BigInteger; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Queue; import static java.util.Arrays.copyOfRange; import static org.ethereum.util.ByteUtil.byteArrayToInt; import static org.spongycastle.util.Arrays.concatenate; import java.util.List; import org.ethereum.util.RLP; import org.ethereum.util.RLPItem; import org.ethereum.util.RLPList; public class RLP { /** Allow for content up to size of 2^64 bytes **/ private static double MAX_ITEM_LENGTH = Math.pow(256, 8); /** * Reason for threshold according to Vitalik Buterin: * - 56 bytes maximizes the benefit of both options * - if we went with 60 then we would have only had 4 slots for long strings * so RLP would not have been able to store objects above 4gb * - if we went with 48 then RLP would be fine for 2^128 space, but that's way too much * - so 56 and 2^64 space seems like the right place to put the cutoff * - also, that's where Bitcoin's varint does the cutof **/ private static int SIZE_THRESHOLD = 56; /** RLP encoding rules are defined as follows: */ /* * For a single byte whose value is in the [0x00, 0x7f] range, that byte is * its own RLP encoding. */ /* * If a string is 0-55 bytes long, the RLP encoding consists of a single * byte with value 0x80 plus the length of the string followed by the * string. The range of the first byte is thus [0x80, 0xb7]. */ private static int OFFSET_SHORT_ITEM = 0x80; /* * If a string is more than 55 bytes long, the RLP encoding consists of a * single byte with value 0xb7 plus the length of the length of the string * in binary form, followed by the length of the string, followed by the * string. For example, a length-1024 string would be encoded as * \xb9\x04\x00 followed by the string. The range of the first byte is thus * [0xb8, 0xbf]. */ private static int OFFSET_LONG_ITEM = 0xb8; /* * If the total payload of a list (i.e. the combined length of all its * items) is 0-55 bytes long, the RLP encoding consists of a single byte * with value 0xc0 plus the length of the list followed by the concatenation * of the RLP encodings of the items. The range of the first byte is thus * [0xc0, 0xf7]. */ private static int OFFSET_SHORT_LIST = 0xc0; /* * If the total payload of a list is more than 55 bytes long, the RLP * encoding consists of a single byte with value 0xf7 plus the length of the * length of the list in binary form, followed by the length of the list, * followed by the concatenation of the RLP encodings of the items. The * range of the first byte is thus [0xf8, 0xff]. */ private static int OFFSET_LONG_LIST = 0xf7; private static byte decodeOneByteItem(byte[] data, int index) { // null item if ((data[index] & 0xFF) == OFFSET_SHORT_ITEM) { return (byte) (data[index] - OFFSET_SHORT_ITEM); } // single byte item if ((data[index] & 0xFF) < OFFSET_SHORT_ITEM) { return (byte) (data[index]); } // single byte item if ((data[index] & 0xFF) == OFFSET_SHORT_ITEM+1) { return (byte) (data[index + 1]); } return 0; } public static int decodeInt(byte[] data, int index) { int value = 0; if ((data[index] & 0xFF) > OFFSET_SHORT_ITEM && (data[index] & 0xFF) < 0xB7) { byte length = (byte) (data[index] - OFFSET_SHORT_ITEM); byte pow = (byte) (length - 1); for (int i = 1; i <= length; ++i) { value += data[index + i] << (8 * pow); pow } } else { throw new RuntimeException("wrong decode attempt"); } return value; } private static short decodeShort(byte[] data, int index) { short value = 0; if ((data[index] & 0xFF) > OFFSET_SHORT_ITEM && (data[index] & 0xFF) < 0xB7) { byte length = (byte) (data[index] - OFFSET_SHORT_ITEM); value = ByteBuffer.wrap(data, index, length).getShort(); } else { value = data[index]; } return value; } private static long decodeLong(byte[] data, int index) { long value = 0; if ((data[index] & 0xFF) > OFFSET_SHORT_ITEM && (data[index] & 0xFF) < 0xB7) { byte length = (byte) (data[index] - OFFSET_SHORT_ITEM); byte pow = (byte) (length - 1); for (int i = 1; i <= length; ++i) { value += data[index + i] << (8 * pow); pow } } else { throw new RuntimeException("wrong decode attempt"); } return value; } private static String decodeStringItem(byte[] data, int index) { String value = null; if ((data[index] & 0xFF) >= 0xB7 && (data[index] & 0xFF) < OFFSET_SHORT_LIST) { byte lengthOfLength = (byte) (data[index] - 0xB7); int length = calcLengthRaw(lengthOfLength, data, index); value = new String(data, index + lengthOfLength + 1, length); } else if ((data[index] & 0xFF) > OFFSET_SHORT_ITEM && (data[index] & 0xFF) < 0xB7) { byte length = (byte) ((data[index] & 0xFF) - OFFSET_SHORT_ITEM); value = new String(data, index + 1, length); } else { throw new RuntimeException("wrong decode attempt"); } return value; } private static byte[] decodeItemBytes(byte[] data, int index) { byte[] value = null; int length = 0; if ((data[index] & 0xFF) >= 0xB7 && (data[index] & 0xFF) < OFFSET_SHORT_LIST) { byte lengthOfLength = (byte) (data[index] - 0xB7); length = calcLengthRaw(lengthOfLength, data, index); } else if ((data[index] & 0xFF) > OFFSET_SHORT_ITEM && (data[index] & 0xFF) < 0xB7) { length = (byte) (data[index] - OFFSET_SHORT_ITEM); } else { throw new RuntimeException("wrong decode attempt"); } byte[] valueBytes = new byte[length]; System.arraycopy(data, index, valueBytes, 0, length); value = valueBytes; return value; } public static BigInteger decodeBigInteger(byte[] data, int index) { BigInteger value = null; int length = 0; if ((data[index] & 0xFF) >= 0xB7 && (data[index] & 0xFF) < OFFSET_SHORT_LIST) { byte lengthOfLength = (byte) (data[index] - 0xB7); length = calcLengthRaw(lengthOfLength, data, index); } else if ((data[index] & 0xFF) > OFFSET_SHORT_ITEM && (data[index] & 0xFF) < 0xB7) { length = (byte) (data[index] - OFFSET_SHORT_ITEM); } else { throw new RuntimeException("wrong decode attempt"); } byte[] valueBytes = new byte[length]; System.arraycopy(data, index, valueBytes, 0, length); value = new BigInteger(valueBytes); return value; } private static byte[] decodeByteArray(byte[] data, int index) { byte[] value = null; int length = 0; if ((data[index] & 0xFF) >= 0xB7 && (data[index] & 0xFF) < OFFSET_SHORT_LIST) { byte lengthOfLength = (byte) (data[index] - 0xB7); length = calcLengthRaw(lengthOfLength, data, index); } else if ((data[index] & 0xFF) > OFFSET_SHORT_ITEM && (data[index] & 0xFF) < 0xB7) { length = (byte) (data[index] - OFFSET_SHORT_ITEM); } else { throw new RuntimeException("wrong decode attempt"); } byte[] valueBytes = new byte[length]; System.arraycopy(data, index, valueBytes, 0, length); value = valueBytes; return value; } private static int nextItemLength(byte[] data, int index) { if (index >= data.length) return -1; if ((data[index] & 0xFF) >= 0xF7) { byte lengthOfLength = (byte) (data[index] - 0xF7); int length = calcLength(lengthOfLength, data, index); return length; } if ((data[index] & 0xFF) >= OFFSET_SHORT_LIST && (data[index] & 0xFF) < 0xF7) { byte length = (byte) ((data[index] & 0xFF) - OFFSET_SHORT_LIST); return length; } if ((data[index] & 0xFF) >= 0xB7 && (data[index] & 0xFF) < OFFSET_SHORT_LIST) { byte lengthOfLength = (byte) (data[index] - 0xB7); int length = calcLength(lengthOfLength, data, index); return length; } if ((data[index] & 0xFF) > OFFSET_SHORT_ITEM && (data[index] & 0xFF) < 0xB7) { byte length = (byte) ((data[index] & 0xFF) - OFFSET_SHORT_ITEM); return length; } if ((data[index] & 0xFF) == OFFSET_SHORT_ITEM) { return 1; } if ((data[index] & 0xFF) < OFFSET_SHORT_ITEM) { return 1; } return -1; } public static byte[] decodeIP4Bytes(byte[] data, int index) { int length = (data[index] & 0xFF) - OFFSET_SHORT_LIST; int offset = 1; byte aByte = decodeOneByteItem(data, index + offset); if ((data[index + offset] & 0xFF) > OFFSET_SHORT_ITEM) offset = offset + 2; else offset = offset + 1; byte bByte = decodeOneByteItem(data, index + offset); if ((data[index + offset] & 0xFF) > OFFSET_SHORT_ITEM) offset = offset + 2; else offset = offset + 1; byte cByte = decodeOneByteItem(data, index + offset); if ((data[index + offset] & 0xFF) > OFFSET_SHORT_ITEM) offset = offset + 2; else offset = offset + 1; byte dByte = decodeOneByteItem(data, index + offset); // return IP address return new byte[] { aByte, bByte, cByte, dByte } ; } public static int getFirstListElement(byte[] payload, int pos) { if (pos >= payload.length) return -1; if ((payload[pos] & 0xFF) >= 0xF7) { byte lengthOfLength = (byte) (payload[pos] - 0xF7); return pos + lengthOfLength + 1; } if ((payload[pos] & 0xFF) >= OFFSET_SHORT_LIST && (payload[pos] & 0xFF) < 0xF7) { return pos + 1; } if ((payload[pos] & 0xFF) >= 0xB7 && (payload[pos] & 0xFF) < OFFSET_SHORT_LIST) { byte lengthOfLength = (byte) (payload[pos] - 0xB7); return pos + lengthOfLength + 1; } return -1; } public static int getNextElementIndex(byte[] payload, int pos) { if (pos >= payload.length) return -1; if ((payload[pos] & 0xFF) >= 0xF7) { byte lengthOfLength = (byte) (payload[pos] - 0xF7); int length = calcLength(lengthOfLength, payload, pos); return pos + lengthOfLength + length + 1; } if ((payload[pos] & 0xFF) >= OFFSET_SHORT_LIST && (payload[pos] & 0xFF) < 0xF7) { byte length = (byte) ((payload[pos] & 0xFF) - OFFSET_SHORT_LIST); return pos + 1 + length; } if ((payload[pos] & 0xFF) >= 0xB7 && (payload[pos] & 0xFF) < OFFSET_SHORT_LIST) { byte lengthOfLength = (byte) (payload[pos] - 0xB7); int length = calcLength(lengthOfLength, payload, pos); return pos + lengthOfLength + length + 1; } if ((payload[pos] & 0xFF) > OFFSET_SHORT_ITEM && (payload[pos] & 0xFF) < 0xB7) { byte length = (byte) ((payload[pos] & 0xFF) - OFFSET_SHORT_ITEM); return pos + 1 + length; } if ((payload[pos] & 0xFF) == OFFSET_SHORT_ITEM) { return pos + 1; } if ((payload[pos] & 0xFF) < OFFSET_SHORT_ITEM) { return pos + 1; } return -1; } /** * Get exactly one message payload */ public static void fullTraverse(byte[] msgData, int level, int startPos, int endPos, int levelToIndex, Queue<Integer> index) { try { if (msgData == null || msgData.length == 0) return; int pos = startPos; while (pos < endPos) { if (level == levelToIndex) index.add(new Integer(pos)); // It's a list with a payload more than 55 bytes // data[0] - 0xF7 = how many next bytes allocated // for the length of the list if ((msgData[pos] & 0xFF) >= 0xF7) { byte lengthOfLength = (byte) (msgData[pos] - 0xF7); int length = calcLength(lengthOfLength, msgData, pos); // now we can parse an item for data[1]..data[length] System.out.println("-- level: [" + level + "] Found big list length: " + length); fullTraverse(msgData, level + 1, pos + lengthOfLength + 1, pos + lengthOfLength + length, levelToIndex, index); pos += lengthOfLength + length + 1; continue; } // It's a list with a payload less than 55 bytes if ((msgData[pos] & 0xFF) >= OFFSET_SHORT_LIST && (msgData[pos] & 0xFF) < 0xF7) { byte length = (byte) ((msgData[pos] & 0xFF) - OFFSET_SHORT_LIST); System.out.println("-- level: [" + level + "] Found small list length: " + length); fullTraverse(msgData, level + 1, pos + 1, pos + length + 1, levelToIndex, index); pos += 1 + length; continue; } // It's an item with a payload more than 55 bytes // data[0] - 0xB7 = how much next bytes allocated for // the length of the string if ((msgData[pos] & 0xFF) >= 0xB7 && (msgData[pos] & 0xFF) < OFFSET_SHORT_LIST) { byte lengthOfLength = (byte) (msgData[pos] - 0xB7); int length = calcLength(lengthOfLength, msgData, pos); // now we can parse an item for data[1]..data[length] System.out.println("-- level: [" + level + "] Found big item length: " + length); pos += lengthOfLength + length + 1; continue; } // It's an item less than 55 bytes long, // data[0] - 0x80 == length of the item if ((msgData[pos] & 0xFF) > OFFSET_SHORT_ITEM && (msgData[pos] & 0xFF) < 0xB7) { byte length = (byte) ((msgData[pos] & 0xFF) - OFFSET_SHORT_ITEM); System.out.println("-- level: [" + level + "] Found small item length: " + length); pos += 1 + length; continue; } // null item if ((msgData[pos] & 0xFF) == OFFSET_SHORT_ITEM) { System.out.println("-- level: [" + level + "] Found null item: "); pos += 1; continue; } // single byte item if ((msgData[pos] & 0xFF) < OFFSET_SHORT_ITEM) { System.out.println("-- level: [" + level + "] Found single item: "); pos += 1; continue; } } } catch (Throwable th) { throw new RuntimeException("wire packet not parsed correctly", th.fillInStackTrace()); } } private static int calcLength(int lengthOfLength, byte[] msgData, int pos) { byte pow = (byte) (lengthOfLength - 1); int length = 0; for (int i = 1; i <= lengthOfLength; ++i) { length += (msgData[pos + i] & 0xFF) << (8 * pow); pow } return length; } private static int calcLengthRaw(int lengthOfLength, byte[] msgData, int index) { byte pow = (byte) (lengthOfLength - 1); int length = 0; for (int i = 1; i <= lengthOfLength; ++i) { length += msgData[index + i] << (8 * pow); pow } return length; } public static byte getCommandCode(byte[] data) { byte command = 0; int index = getFirstListElement(data, 0); command = data[index]; command = ((int) (command & 0xFF) == OFFSET_SHORT_ITEM) ? 0 : command; return command; } /** * Parse wire byte[] message into RLP elements * * @param msgData * - raw RLP data * @param rlpList * - outcome of recursive RLP structure */ public static RLPList decode2(byte[] msgData) { RLPList rlpList = new RLPList(); fullTraverse(msgData, 0, 0, msgData.length, 1, rlpList); return rlpList; } /** * Get exactly one message payload */ private static void fullTraverse(byte[] msgData, int level, int startPos, int endPos, int levelToIndex, RLPList rlpList) { try { if (msgData == null || msgData.length == 0) return; int pos = startPos; while (pos < endPos) { // It's a list with a payload more than 55 bytes // data[0] - 0xF7 = how many next bytes allocated // for the length of the list if ((msgData[pos] & 0xFF) >= 0xF7) { byte lengthOfLength = (byte) (msgData[pos] - 0xF7); int length = calcLength(lengthOfLength, msgData, pos); byte[] rlpData = new byte[lengthOfLength + length + 1]; System.arraycopy(msgData, pos, rlpData, 0, lengthOfLength + length + 1); RLPList newLevelList = new RLPList(); newLevelList.setRLPData(rlpData); // todo: this done to get some data for testing should be // delete // byte[] subList = Arrays.copyOfRange(msgData, pos, pos + // lengthOfLength + length + 1); // System.out.println(Utils.toHexString(subList)); fullTraverse(msgData, level + 1, pos + lengthOfLength + 1, pos + lengthOfLength + length + 1, levelToIndex, newLevelList); rlpList.add(newLevelList); pos += lengthOfLength + length + 1; continue; } // It's a list with a payload less than 55 bytes if ((msgData[pos] & 0xFF) >= OFFSET_SHORT_LIST && (msgData[pos] & 0xFF) < 0xF7) { byte length = (byte) ((msgData[pos] & 0xFF) - OFFSET_SHORT_LIST); byte[] rlpData = new byte[length + 1]; System.arraycopy(msgData, pos, rlpData, 0, length + 1); RLPList newLevelList = new RLPList(); newLevelList.setRLPData(rlpData); if (length > 0) fullTraverse(msgData, level + 1, pos + 1, pos + length + 1, levelToIndex, newLevelList); rlpList.add(newLevelList); pos += 1 + length; continue; } // It's an item with a payload more than 55 bytes // data[0] - 0xB7 = how much next bytes allocated for // the length of the string if ((msgData[pos] & 0xFF) >= 0xB7 && (msgData[pos] & 0xFF) < OFFSET_SHORT_LIST) { byte lengthOfLength = (byte) (msgData[pos] - 0xB7); int length = calcLength(lengthOfLength, msgData, pos); // now we can parse an item for data[1]..data[length] byte[] item = new byte[length]; System.arraycopy(msgData, pos + lengthOfLength + 1, item, 0, length); byte[] rlpPrefix = new byte[lengthOfLength + 1]; System.arraycopy(msgData, pos, rlpPrefix, 0, lengthOfLength + 1); RLPItem rlpItem = new RLPItem(item); rlpList.add(rlpItem); pos += lengthOfLength + length + 1; continue; } // It's an item less than 55 bytes long, // data[0] - 0x80 == length of the item if ((msgData[pos] & 0xFF) > OFFSET_SHORT_ITEM && (msgData[pos] & 0xFF) < 0xB7) { byte length = (byte) ((msgData[pos] & 0xFF) - OFFSET_SHORT_ITEM); byte[] item = new byte[length]; System.arraycopy(msgData, pos + 1, item, 0, length); byte[] rlpPrefix = new byte[2]; System.arraycopy(msgData, pos, rlpPrefix, 0, 2); RLPItem rlpItem = new RLPItem(item); rlpList.add(rlpItem); pos += 1 + length; continue; } // null item if ((msgData[pos] & 0xFF) == OFFSET_SHORT_ITEM) { byte[] item = new byte[0]; RLPItem rlpItem = new RLPItem(item); rlpList.add(rlpItem); pos += 1; continue; } // single byte item if ((msgData[pos] & 0xFF) < OFFSET_SHORT_ITEM) { byte[] item = { (byte) (msgData[pos] & 0xFF) }; RLPItem rlpItem = new RLPItem(item); rlpList.add(rlpItem); pos += 1; continue; } } } catch (Exception e) { throw new RuntimeException("wire packet not parsed correctly", e); } } /** * Reads any RLP encoded byte-array and returns all objects as byte-array or list of byte-arrays * * @param data RLP encoded byte-array * @param pos position in the array to start reading * @return DecodeResult encapsulates the decoded items as a single Object and the final read position */ public static DecodeResult decode(byte[] data, int pos) { if (data == null || data.length < 1) { return null; } int prefix = data[pos] & 0xFF; if (prefix == OFFSET_SHORT_ITEM) { return new DecodeResult(pos+1, new byte[0]); // means no length or 0 } else if (prefix < OFFSET_SHORT_ITEM) { return new DecodeResult(pos+1, new byte[] { data[pos] }); // byte is its own RLP encoding } else if (prefix < OFFSET_LONG_ITEM){ int len = prefix - OFFSET_SHORT_ITEM; // length of the encoded bytes return new DecodeResult(pos+1+len, copyOfRange(data, pos+1, pos+1+len)); } else if (prefix < OFFSET_SHORT_LIST) { int lenlen = prefix - OFFSET_LONG_ITEM + 1; // length of length the encoded bytes int lenbytes = byteArrayToInt(copyOfRange(data, pos+1, pos+1+lenlen)); // length of encoded bytes return new DecodeResult(pos+1+lenlen+lenbytes, copyOfRange(data, pos+1+lenlen, pos+1+lenlen+lenbytes)); } else if (prefix < OFFSET_LONG_LIST) { int len = prefix - OFFSET_SHORT_LIST; // length of the encoded list int prevPos = pos; pos++; return decodeList(data, pos, prevPos, len); } else if (prefix < 0xFF) { int lenlen = prefix - OFFSET_LONG_LIST; // length of length the encoded list int lenlist = byteArrayToInt(copyOfRange(data, pos+1, pos+1+lenlen)); // length of encoded bytes pos = pos + lenlen + 1; // start at position of first element in list int prevPos = lenlist; return decodeList(data, pos, prevPos, lenlist); } else { throw new RuntimeException("Only byte values between 0x00 and 0xFF are supported, but got: " + prefix); } } private static DecodeResult decodeList(byte[] data, int pos, int prevPos, int len) { List<Object> slice = new ArrayList<Object>(); for (int i = 0; i < len;) { // Get the next item in the data list and append it DecodeResult result = decode(data, pos); slice.add(result.getDecoded()); // Increment pos by the amount bytes in the previous read prevPos = result.getPos(); i += (prevPos - pos); pos = prevPos; } return new DecodeResult(pos, slice.toArray()); } /** * Turn Object into its RLP encoded equivalent of a byte-array * Support for String, Integer, BigInteger and Lists of any of these types. * * @param item as object or List of objects * @return byte[] RLP encoded */ public static byte[] encode(Object input) { Value val = new Value(input); if (val.isList()) { List<Object> inputArray = val.asList(); if (inputArray.size() == 0) { return encodeLength(inputArray.size(), OFFSET_SHORT_LIST); } byte[] output = new byte[0]; for (Object object : inputArray) { output = concatenate(output, encode(object)); } byte[] prefix = encodeLength(output.length, OFFSET_SHORT_LIST); return concatenate(prefix, output); } else { byte[] inputAsBytes = toBytes(input); if(inputAsBytes.length == 1) { return inputAsBytes; } else { byte[] firstByte = encodeLength(inputAsBytes.length, OFFSET_SHORT_ITEM); return concatenate(firstByte, inputAsBytes); } } } /** Integer limitation goes up to 2^31-1 so length can never be bigger than MAX_ITEM_LENGTH */ public static byte[] encodeLength(int length, int offset) { if (length < SIZE_THRESHOLD) { byte firstByte = (byte) (length + offset); return new byte[] { firstByte }; } else if (length < MAX_ITEM_LENGTH) { byte[] binaryLength; if(length > 0xFF) binaryLength = BigInteger.valueOf(length).toByteArray(); else binaryLength = new byte[] { (byte) length }; byte firstByte = (byte) (binaryLength.length + offset + SIZE_THRESHOLD - 1 ); return concatenate(new byte[] { firstByte }, binaryLength); } else { throw new RuntimeException("Input too long"); } } public static byte[] encodeByte(byte singleByte) { if ((singleByte & 0xFF) == 0) { return new byte[] { (byte) OFFSET_SHORT_ITEM }; } else if ((singleByte & 0xFF) < 0x7F) { return new byte[] { singleByte }; } else { return new byte[] { (byte) (OFFSET_SHORT_ITEM+1), singleByte }; } } public static byte[] encodeShort(short singleShort) { if (singleShort <= 0xFF) return encodeByte((byte) singleShort); else { return new byte[] { (byte) (OFFSET_SHORT_ITEM + 2), (byte) (singleShort >> 8 & 0xFF), (byte) (singleShort >> 0 & 0xFF) }; } } public static byte[] encodeString(String srcString) { return encodeElement(srcString.getBytes()); } public static byte[] encodeBigInteger(BigInteger srcBigInteger) { if(srcBigInteger == BigInteger.ZERO) return encodeByte((byte)0); else return encodeElement(srcBigInteger.toByteArray()); } public static byte[] encodeElement(byte[] srcData) { if (srcData == null) { return new byte[]{(byte) 0x80}; } if (srcData.length == 1 && srcData[0] < 0x80) { return srcData; } else if (srcData.length <= 0x37) { // length = 8X byte length = (byte) (OFFSET_SHORT_ITEM + srcData.length); byte[] data = Arrays.copyOf(srcData, srcData.length + 1); System.arraycopy(data, 0, data, 1, srcData.length); data[0] = length; return data; } else { // length of length = BX // prefix = [BX, [length]] int tmpLength = srcData.length; byte byteNum = 0; while (tmpLength != 0) { ++byteNum; tmpLength = tmpLength >> 8; } byte[] lenBytes = new byte[byteNum]; for (int i = 0; i < byteNum; ++i) { lenBytes[byteNum - 1 - i] = (byte) ((srcData.length >> (8 * i)) & 0xFF); } // first byte = F7 + bytes.length byte[] data = Arrays.copyOf(srcData, srcData.length + 1 + byteNum); System.arraycopy(data, 0, data, 1 + byteNum, srcData.length); data[0] = (byte) (0xB7 + byteNum); System.arraycopy(lenBytes, 0, data, 1, lenBytes.length); return data; } } public static byte[] encodeList(byte[]... elements) { int totalLength = 0; for (int i = 0; i < elements.length; ++i) { totalLength += elements[i].length; } byte[] data; int copyPos = 0; if (totalLength <= 0x37) { data = new byte[1 + totalLength]; data[0] = (byte) (OFFSET_SHORT_LIST + totalLength); copyPos = 1; } else { // length of length = BX // prefix = [BX, [length]] int tmpLength = totalLength; byte byteNum = 0; while (tmpLength != 0) { ++byteNum; tmpLength = tmpLength >> 8; } tmpLength = totalLength; byte[] lenBytes = new byte[byteNum]; for (int i = 0; i < byteNum; ++i) { lenBytes[byteNum - 1 - i] = (byte) ((tmpLength >> (8 * i)) & 0xFF); } // first byte = F7 + bytes.length data = new byte[1 + lenBytes.length + totalLength]; data[0] = (byte) (0xF7 + byteNum); System.arraycopy(lenBytes, 0, data, 1, lenBytes.length); copyPos = lenBytes.length + 1; } for (int i = 0; i < elements.length; ++i) { System.arraycopy(elements[i], 0, data, copyPos, elements[i].length); copyPos += elements[i].length; } return data; } /* * Utility function to convert Objects into byte arrays */ private static byte[] toBytes(Object input) { if (input instanceof byte[]) { return (byte[]) input; } else if (input instanceof String) { String inputString = (String) input; return inputString.getBytes(); } else if(input instanceof Long) { Long inputLong = (Long) input; return (inputLong == 0) ? new byte[0] : BigInteger.valueOf(inputLong).toByteArray(); } else if(input instanceof Integer) { Integer inputInt = (Integer) input; return (inputInt == 0) ? new byte[0] : BigInteger.valueOf(inputInt.longValue()).toByteArray(); } else if(input instanceof BigInteger) { BigInteger inputBigInt = (BigInteger) input; return (inputBigInt == BigInteger.ZERO) ? new byte[0] : inputBigInt.toByteArray(); } else if (input instanceof Value) { Value val = (Value) input; return toBytes(val.asObj()); } throw new RuntimeException("Unsupported type: Only accepting String, Integer and BigInteger for now"); } }
package org.lantern; import java.io.File; import java.io.IOException; import java.util.Arrays; import org.apache.commons.lang.SystemUtils; import org.apache.commons.lang.math.RandomUtils; import org.lantern.event.Events; import org.lantern.event.ModeChangedEvent; import org.lantern.event.ProxyConnectionEvent; import org.lantern.event.QuitEvent; import org.lantern.event.ResetEvent; import org.lantern.event.SetupCompleteEvent; import org.lantern.event.SystemProxyChangedEvent; import org.lantern.proxy.ProxyTracker; import org.lantern.state.Connectivity; import org.lantern.state.Model; import org.lantern.state.ModelUtils; import org.lantern.state.StaticSettings; import org.lantern.state.SyncPath; import org.lantern.win.WinProxy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.eventbus.Subscribe; import com.google.common.io.Files; import com.google.inject.Inject; import com.google.inject.Singleton; /** * Class that handles turning proxying on and off for all platforms. */ @Singleton public class Proxifier implements ProxyService, LanternService { public class ProxyConfigurationError extends Exception {} public class ProxyConfigurationCancelled extends ProxyConfigurationError {}; private final Logger LOG = LoggerFactory.getLogger(getClass()); private final File LANTERN_PROXYING_FILE = new File(LanternClientConstants.CONFIG_DIR, "lanternProxying"); private boolean interactiveUnproxyCalled; public final static File PROXY_ON = new File(LanternClientConstants.CONFIG_DIR, "proxy_on.pac"); public final static File PROXY_OFF = new File(LanternClientConstants.CONFIG_DIR, "proxy_off.pac"); public final static File PROXY_GOOGLE = new File(LanternClientConstants.CONFIG_DIR, "proxy_google.pac"); public final static File PROXY_ALL = new File(LanternClientConstants.CONFIG_DIR, "proxy_all.pac"); private final WinProxy WIN_PROXY = new WinProxy(LanternClientConstants.CONFIG_DIR); private final MessageService messageService; private final ModelUtils modelUtils; private final Model model; private ProxyConnectionEvent lastProxyConnectionEvent; private final ProxyTracker proxyTracker; @Inject public Proxifier(final MessageService messageService, final ModelUtils modelUtils, final Model model, final ProxyTracker proxyTracker) { this.messageService = messageService; this.modelUtils = modelUtils; this.model = model; this.proxyTracker = proxyTracker; copyFromLocal(PROXY_ALL); copyFromLocal(PROXY_OFF); Events.register(this); LANTERN_PROXYING_FILE.delete(); LANTERN_PROXYING_FILE.deleteOnExit(); if (!PROXY_OFF.isFile()) { final String msg = "No pac at: "+PROXY_OFF.getAbsolutePath() +"\nfrom: " + new File(".").getAbsolutePath(); LOG.error(msg); throw new IllegalStateException(msg); } LOG.debug("Both pac files are in their expected locations"); } @Subscribe public void onQuit(final QuitEvent quit) { LOG.debug("Got quit event!"); interactiveUnproxy(); } /** * Synchronized setup complete handler because it has to coordinate with * proxy connection events. This is designed so either the setup complete * event or the proxy connection event can happen first. * * @param event The setup complete event. */ @Subscribe public synchronized void onSetupComplete(final SetupCompleteEvent event) { LOG.debug("Got setup complete!"); if (this.lastProxyConnectionEvent != null && this.proxyTracker.hasProxy()) { LOG.debug("Re-firing last proxy connection event..."); onProxyConnectionEvent(this.lastProxyConnectionEvent); } else { LOG.debug("No proxy connection event to refire or no proxy {}, {}", this.lastProxyConnectionEvent, this.proxyTracker.hasProxy()); } } @Subscribe public synchronized void onSystemProxyChanged( final SystemProxyChangedEvent spe) { LOG.debug("Got system proxy changed event {}", spe); if (spe.isSystemProxy()) { proxyWithChecks(); } else { try { stopProxying(); } catch (final ProxyConfigurationError e) { LOG.warn("Error stopping proxy!", e); } } } /** * Synchronized proxy connection event handler because it has to sync up * with setup complete events (see above). This is designed so either * the setup complete event or the proxy connection event can happen first. * * @param pce The proxy connection event. */ @Subscribe public synchronized void onProxyConnectionEvent( final ProxyConnectionEvent pce) { this.lastProxyConnectionEvent = pce; final ConnectivityStatus stat = pce.getConnectivityStatus(); switch (stat) { case CONNECTED: LOG.debug("Got connected event"); proxyWithChecks(); break; case CONNECTING: LOG.debug("Got connecting event"); break; case DISCONNECTED: LOG.debug("Got disconnected event"); try { stopProxying(); } catch (final ProxyConfigurationError e) { LOG.warn("Could not unproxy?", e); } break; default: break; } } /** * Starts proxying, but does a few checks of the overall state first and * only proxies if everything's good to go. */ private void proxyWithChecks() { if (!this.model.isSetupComplete()) { LOG.debug("Not proxying when setup up not complete"); return; } if (!this.proxyTracker.hasProxy()) { LOG.debug("Not proxying when we have no proxies!"); return; } if (modelUtils.shouldProxy()) { try { startProxying(); } catch (final ProxyConfigurationError e) { LOG.warn("Could not proxy?", e); } } else { LOG.debug("Ignoring proxy call! System proxy? "+ model.getSettings().isSystemProxy()+" get mode? "+ this.model.getSettings().getMode()); } } @Override public void start() throws Exception { // Nothing to do in this case; } @Override public void stop() { interactiveUnproxy(); } private void copyFromLocal(final File dest) { final File local = new File(dest.getName()); if (!local.isFile()) { LOG.error("No file at: {}", local); return; } if (!dest.getParentFile().isDirectory()) { LOG.error("No directory at: {}", dest.getParentFile()); return; } try { Files.copy(local, dest); } catch (final IOException e) { LOG.error("Error copying file from "+local+" to "+ dest, e); } } /** * Configures Lantern to proxy all sites, not just the ones on the * whitelist. * * @param proxyAll Whether or not to proxy all sites. * @throws ProxyConfigurationError If there's an error configuring the * proxy. */ @Override public void proxyAllSites(final boolean proxyAll) throws ProxyConfigurationError { if (proxyAll) { startProxying(true, PROXY_ALL); } else { // In this case the user is still in GET mode (in order to have that // option available at all), so we need to go back to proxying // using the normal pac file. startProxying(true, PROXY_ON); } } /** * This method is private because it should only be called in response to * proxy connection events and setup complete events. * * @throws ProxyConfigurationError If there's an error configuring the * proxy. */ private void startProxying() throws ProxyConfigurationError { if (this.model.getSettings().isProxyAllSites()) { // If we were previously configured to proxy all sites, then we // need to force the override. startProxying(true, PROXY_ALL); } else { startProxying(false, PROXY_ON); } } @Override public void startProxying(final boolean force, final File pacFile) throws ProxyConfigurationError { if (isProxying() && !force) { LOG.debug("Already proxying!"); return; } if (!modelUtils.shouldProxy()) { LOG.debug("Not proxying in current mode...{}", pacFile); final String url = getPacFileUrl(pacFile); final Connectivity connectivity = this.model.getConnectivity(); connectivity.setPacUrl(url); Events.sync(SyncPath.CONNECTIVITY, connectivity); return; } LOG.debug("Starting to proxy!"); // Always update the pac file to make sure we've got all the latest // entries -- only recreates proxy_on. if (pacFile.equals(PROXY_ON)) { PacFileGenerator.generatePacFile( this.model.getSettings().getWhitelist().getEntriesAsStrings(), PROXY_ON); } LOG.debug("Autoconfiguring local to proxy Lantern"); final String url = getAndSetPacFileUrl(pacFile); if (SystemUtils.IS_OS_MAC_OSX) { proxyOsx(url); } else if (SystemUtils.IS_OS_WINDOWS) { proxyWindows(url); } else if (SystemUtils.IS_OS_LINUX) { proxyLinux(url); } Events.syncModel(this.model); // success try { if (!LANTERN_PROXYING_FILE.isFile() && !LANTERN_PROXYING_FILE.createNewFile()) { LOG.error("Could not create proxy file?"); } } catch (final IOException e) { LOG.error("Could not create proxy file?", e); } } public void interactiveUnproxy() { if (interactiveUnproxyCalled) { LOG.debug("Interactive unproxy already called!"); return; } interactiveUnproxyCalled = true; if (!model.getSettings().isUiEnabled()) { try { stopProxying(); } catch (final Proxifier.ProxyConfigurationError e) { LOG.error("Failed to unconfigure proxy: {}", e); } } else { // The following often happens as the result of the quit event // because we need the UI to still be up to interact with the // user -- that's not always the case with System.exit/shutdown // hooks. boolean finished = false; while (!finished) { try { stopProxying(); finished = true; } catch (final Proxifier.ProxyConfigurationError e) { LOG.error("Failed to unconfigure proxy."); // XXX i18n final String question = "Failed to change the system proxy settings.\n\n" + "If Lantern remains as the system proxy after being shut down, " + "you will need to manually change the system's network proxy settings " + "in order to access the web.\n\nTry again?"; // TODO: Don't think this will work on Linux. boolean retry = messageService.askQuestion("Proxy Settings", question); if (!retry) { finished = true; } else { LOG.debug("Trying again"); } } } } } @Override public void stopProxying() throws ProxyConfigurationError { if (!isProxying()) { LOG.debug("Ignoring call since we're not proxying"); return; } LOG.debug("Unproxying Lantern"); LANTERN_PROXYING_FILE.delete(); if (SystemUtils.IS_OS_MAC_OSX) { unproxyOsx(); } else if (SystemUtils.IS_OS_WINDOWS) { unproxyWindows(); } else if (SystemUtils.IS_OS_LINUX) { unproxyLinux(); } } public boolean isProxying() { return LANTERN_PROXYING_FILE.isFile(); } private void proxyLinux(final String url) throws ProxyConfigurationError { try { final String result1 = LanternUtils.runCommand("gsettings", "set", "org.gnome.system.proxy", "mode", "'auto'"); LOG.debug("Result of Ubuntu gsettings mode call: {}", result1); final String result2 = LanternUtils.runCommand("gsettings", "set", "org.gnome.system.proxy", "autoconfig-url", url); LOG.debug("Result of Ubuntu gsettings pac file call: {}", result2); } catch (final IOException e) { LOG.warn("Error calling Ubuntu proxy script!", e); throw new ProxyConfigurationError(); } } private void proxyOsx(final String url) throws ProxyConfigurationError { configureOsxProxyViaScript(true, url); } private void configureOsxProxyViaScript(final boolean proxy, final String url) throws ProxyConfigurationError { final String onOrOff; if (proxy) { onOrOff = "on"; } else { onOrOff = "off"; } try { final String result = LanternUtils.runCommand("./configureNetworkServices", onOrOff, url); LOG.debug("Result of command is {}", result); } catch (final IOException e) { LOG.debug("Exception running script", e); throw new ProxyConfigurationCancelled(); } } private void proxyWindows(final String url) { if (!SystemUtils.IS_OS_WINDOWS) { LOG.debug("Not running on Windows"); return; } // Note we don't use toURI().toASCIIString here because the URL encoding // of spaces causes problems. //final String url = "file://"+pacFile.getAbsolutePath(); //ACTIVE_PAC.toURI().toASCIIString().replace("file:/", "file://"); LOG.debug("Using pac path: {}", url); WIN_PROXY.setPacFile(url); } protected void unproxyWindows() { LOG.info("Unproxying windows"); WIN_PROXY.unproxy(); } private void unproxyLinux() throws ProxyConfigurationError { try { final String result1 = LanternUtils.runCommand("gsettings", "set", "org.gnome.system.proxy", "mode", "'none'"); LOG.debug("Result of Ubuntu gsettings mode call: {}", result1); final String result2 = LanternUtils.runCommand("gsettings", "reset", "org.gnome.system.proxy", "autoconfig-url"); LOG.debug("Result of Ubuntu gsettings pac file call: {}", result2); } catch (final IOException e) { LOG.warn("Error calling Ubuntu proxy script!", e); throw new ProxyConfigurationError(); } } private void unproxyOsx() throws ProxyConfigurationError { // Note that this is a bit of overkill in that we both turn of the // PAC file-based proxying and set the PAC file to one that doesn't // proxy anything. configureOsxProxyViaScript(false, getPacFileUrl(PROXY_OFF)); } private String getPacFileUrl(final File pacFile) { final String url = StaticSettings.getLocalEndpoint()+"/"+ pacFile.getName() + "-" + RandomUtils.nextLong(); return url; } private String getAndSetPacFileUrl(final File pacFile) { final String url = getPacFileUrl(pacFile); this.model.getConnectivity().setPacUrl(url); return url; } /** * This will refresh the proxy entries for things like new additions to * the whitelist. */ @Override public void refresh() { if (isProxying()) { if (model.getSettings().isProxyAllSites()) { // If we were previously configured to proxy all sites, then we // need to force the override. try { startProxying(true, PROXY_ALL); } catch (final ProxyConfigurationError e) { LOG.warn("Could not proxy", e); } } else { try { startProxying(true, PROXY_ON); } catch (final ProxyConfigurationError e) { LOG.warn("Could not proxy", e); } } } } @Override public void proxyGoogle() { PacFileGenerator.generatePacFile( Arrays.asList("google.com", "youtube.com"), Proxifier.PROXY_GOOGLE); try { startProxying(true, Proxifier.PROXY_GOOGLE); } catch (final ProxyConfigurationError e) { // Not too much we can do here if we're unable to set up the proxy. LOG.error("Could not proxy?", e); } } @Subscribe public void onReset(final ResetEvent event) { try { stopProxying(); } catch (final ProxyConfigurationError e) { LOG.warn("Could not stop proxying", e); } } @Subscribe public void onModeChangedEvent(final ModeChangedEvent event) { switch (event.getNewMode()) { case get: LOG.debug("Nothing to do on proxifier when switched to get mode"); return; case give: LOG.debug("Switched to give mode"); try { stopProxying(); } catch (final ProxyConfigurationError e) { LOG.debug("Error stopping proxying!", e); } break; case unknown: break; default: break; }; } }
package org.petapico.npop; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.zip.GZIPOutputStream; import net.trustyuri.TrustyUriException; import net.trustyuri.TrustyUriResource; import org.nanopub.MalformedNanopubException; import org.nanopub.MultiNanopubRdfHandler; import org.nanopub.MultiNanopubRdfHandler.NanopubHandler; import org.nanopub.Nanopub; import org.nanopub.NanopubImpl; import org.nanopub.NanopubUtils; import org.openrdf.model.Statement; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFParseException; import com.beust.jcommander.JCommander; import com.beust.jcommander.ParameterException; public class Run { @com.beust.jcommander.Parameter(description = "input-nanopubs", required = true) private List<File> inputNanopubs = new ArrayList<File>(); @com.beust.jcommander.Parameter(names = "-f", description = "Filter by URI or literal") private String filter = null; public static void main(String[] args) { NanopubImpl.ensureLoaded(); Run obj = new Run(); JCommander jc = new JCommander(obj); try { jc.parse(args); } catch (ParameterException ex) { jc.usage(); System.exit(1); } try { obj.run(); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } } private RDFFormat format; private OutputStream out; private void run() throws IOException, RDFParseException, RDFHandlerException, MalformedNanopubException, TrustyUriException { for (File inputFile : inputNanopubs) { File outFile = new File(inputFile.getParent(), "op." + inputFile.getName()); if (inputFile.getName().matches(".*\\.(gz|gzip)")) { out = new GZIPOutputStream(new FileOutputStream(outFile)); } else { out = new FileOutputStream(outFile); } format = new TrustyUriResource(inputFile).getFormat(RDFFormat.TRIG); MultiNanopubRdfHandler.process(format, inputFile, new NanopubHandler() { @Override public void handleNanopub(Nanopub np) { try { process(np); } catch (RDFHandlerException ex) { throw new RuntimeException(ex); } } }); out.close(); } } private void process(Nanopub np) throws RDFHandlerException { if (filter != null) { boolean keep = false; for (Statement st : NanopubUtils.getStatements(np)) { if (st.getSubject().stringValue().equals(filter)) { keep = true; break; } if (st.getPredicate().stringValue().equals(filter)) { keep = true; break; } if (st.getObject().stringValue().equals(filter)) { keep = true; break; } if (st.getContext().stringValue().equals(filter)) { keep = true; break; } } if (!keep) return; } NanopubUtils.writeToStream(np, out, format); } }
package com.bosi.chineseclass.su.db; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.provider.UserDictionary.Words; import android.text.TextUtils; import android.util.Log; import u.aly.cu; import java.util.ArrayList; import java.util.List; import com.bosi.chineseclass.R; public class DbUtils { private static DbUtils sDbUtils; private Context mContext; private DbUtils(Context context) { mContext = context; } public static DbUtils getInstance(Context ctx) { if (sDbUtils == null) { sDbUtils = new DbUtils(ctx); } return sDbUtils; } public ArrayList<String> getFilterListByPy(String string) { try { if (!TextUtils.isEmpty(string)) { String res = string.toLowerCase(); SQLiteDatabase database = new DicOpenHelper(mContext).getReadableDatabase(); Cursor cursor = database.query("orderpy", null, "head = ?", new String[] { res }, null, null, null); ArrayList<String> list = new ArrayList<String>(); while (cursor.moveToNext()) { list.add(cursor.getString(cursor.getColumnIndex("py"))); } return list; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public ArrayList<String> getFilterWordsByPy(String string) { try { if (!TextUtils.isEmpty(string)) { String res = string.toLowerCase(); SQLiteDatabase database = new DicOpenHelper(mContext).getReadableDatabase(); Cursor cursor = database.query("py", null, "py = ?", new String[] { res }, null, null, null); ArrayList<String> list = new ArrayList<String>(); while (cursor.moveToNext()) { list.add(cursor.getString(cursor.getColumnIndex("zi"))); } cursor.close(); cursor = null; return list; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public ArrayList<Entity> getFilterListByStoke(String begin) { if (!TextUtils.isEmpty(begin)) { ArrayList<Entity> list = new ArrayList<Entity>(); DicOpenHelper openHelper = new DicOpenHelper(mContext); SQLiteDatabase database = openHelper.getReadableDatabase(); Cursor curosr = database.query("zbh", null, "begin = ?", new String[] { begin }, null, null, "bihua"); while (curosr.moveToNext()) { Entity temp = new Entity(); temp.id = curosr.getString(curosr.getColumnIndex("xuhao")); temp.stokes = curosr.getString(curosr.getColumnIndex("bihua")); temp.word = curosr.getString(curosr.getColumnIndex("zi")); list.add(temp); } return list; } return null; } public ArrayList<String> getFilterListByRadical(String valueOf) { if (!TextUtils.isEmpty(valueOf)) { ArrayList<String> list = new ArrayList<String>(); Cursor cursor = null; DicOpenHelper openHelper = new DicOpenHelper(mContext); SQLiteDatabase database = openHelper.getReadableDatabase(); if (valueOf.equals("0")) { cursor = database.query("bsbh", null, "bihua > 0", null, null, null, "bihua"); } else { cursor = database.query("bsbh", null, "bihua=?", new String[] { valueOf }, null, null, null); } while (cursor.moveToNext()) { list.add(cursor.getString(cursor.getColumnIndex("bushow"))); } cursor.close(); cursor = null; return list; } return null; } public List<String> getFilterBu(String string) { try { if (!TextUtils.isEmpty(string)) { ArrayList<String> list = new ArrayList<String>(); Cursor cursor = null; DicOpenHelper openHelper = new DicOpenHelper(mContext); SQLiteDatabase database = openHelper.getReadableDatabase(); cursor = database.query("bsbh", null, "bushow = ?", new String[] { string }, null, null, null); while (cursor.moveToNext()) { String temp = cursor.getString(cursor.getColumnIndex("bushow")); Log.e("print", "temp" + temp); list.add(cursor.getString(cursor.getColumnIndex("bushow"))); } cursor.close(); cursor = null; return list; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public ArrayList<Entity> getFilterRadicalsBy(String bu) { try { if (!TextUtils.isEmpty(bu)) { ArrayList<Entity> list = new ArrayList<Entity>(); Cursor cursor = null; DicOpenHelper openHelper = new DicOpenHelper(mContext); SQLiteDatabase database = openHelper.getReadableDatabase(); cursor = database.query("bushou", null, "bu = ?", new String[] { bu }, null, null, null); while (cursor.moveToNext()) { Entity temp = new Entity(); temp.word = cursor.getString(cursor.getColumnIndex("zi")); temp.stokes = cursor.getString(cursor.getColumnIndex("sbh")); list.add(temp); } cursor.close(); cursor = null; return list; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public Word getExplain(String word, String id) { Cursor cursor =null; try { DicOpenHelper openHelper = new DicOpenHelper(mContext); SQLiteDatabase database = openHelper.getReadableDatabase(); String sql = mContext.getResources() .getString(R.string.select_fromzidian_basezitouorid); String sqlFormat = String.format(sql, word, id); cursor = database.rawQuery(sqlFormat, null); Word words = new Word(); if (cursor != null && cursor.moveToFirst()) { words.refid = cursor.getString(cursor.getColumnIndex("refid")); words.pinyin = cursor.getString(cursor.getColumnIndex("pinyin")); words.cy = cursor.getString(cursor.getColumnIndex("cy")); words.cysy = cursor.getString(cursor.getColumnIndex("cysy")); words.yanbian = cursor.getString(cursor.getColumnIndex("yanbian")); words.shiyi = cursor.getString(cursor.getColumnIndex("shiyi")); words.ytzi = cursor.getString(cursor.getColumnIndex("ytzi")); } return words; } catch (Exception e) { e.printStackTrace(); }finally{ if(cursor!=null&&!cursor.isClosed()){ cursor.close(); } } return null; } public List<String> getPyList(String pinyin) { try { String[] pys = pinyin.split("/"); if (pys != null) { DicOpenHelper openHelper = DicOpenHelper.getInstance(mContext); SQLiteDatabase database = openHelper.getReadableDatabase(); List<String> pyList = new ArrayList<String>(); for (String temp : pys) { Cursor cursor = database.query("unipy", null, "pinyin = ?", new String[] { temp }, null, null, null); while (cursor.moveToNext()) { String tempString = cursor.getString(cursor.getColumnIndex("pyj")); Log.e("print", tempString); pyList.add(tempString); } } return pyList; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); Log.e("print", e.getMessage()); } return null; } }
package javax.jmi.reflect; import java.util.Collection; import java.util.List; public interface RefClass extends RefFeatured { public RefObject refCreateInstance(List args); public Collection refAllOfType(); public Collection refAllOfClass(); public RefStruct refCreateStruct(RefObject struct, List params); public RefStruct refCreateStruct(String structName, List params); public RefEnum refGetEnum(RefObject enum_, String name); public RefEnum refGetEnum(String enumName, String name); }
package ua.ikonovalov.Sorting; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.TreeSet; /** * Class SortUser. * * @author ru.sbulygin. * @since 25.04.2017. * @version 1.0. */ public class SortUser { /** * The method sorts the list of users by age and returns the TreeSet collection. * * @param userList the list of users. * @return TreeSet collection with users. */ public Set<User> sort(List<User> userList) { Set<User> userSet = new TreeSet<>(); for (User user : userList) { userSet.add(user); } return userSet; } /** * The method sorts the list of users by name length. * @param userList the list of users. * @return A list of users sorted by name length. */ public List<User> sortLength(List<User> userList) { Collections.sort(userList, new Comparator<User>() { @Override public int compare(User o1, User o2) { return o1.getName().length() - o2.getName().length(); } }); return userList; } /** * The method sorts the list of users by hash code. * @param userList the list of users. * @return A list of users sorted by hash code. */ public List<User> sortByAllFields (List<User> userList) { Collections.sort(userList, new Comparator<User>() { @Override public int compare(User o1, User o2) { int i = o1.getName().compareTo(o2.getName()); return i != 0 ? i : Integer.compare(o1.getAge(), o2.getAge()); } }); return userList; } }
package de.uka.ipd.sdq.beagle.core; import java.io.Serializable; public class SeffBranch extends MeasurableSeffElement implements Serializable { /** * Serialisation version UID, see {@link java.io.Serializable}. */ private static final long serialVersionUID = -1525692970296450080L; }
// V e r t i c a l s B u i l d e r // // Please contact author at [email protected] for bugs & suggestions // package omr.sheet; import omr.Main; import omr.check.Check; import omr.check.CheckBoard; import omr.check.CheckSuite; import omr.check.FailureResult; import omr.check.SuccessResult; import omr.constant.Constant; import omr.constant.ConstantSet; import omr.glyph.Glyph; import omr.glyph.GlyphLag; import omr.glyph.GlyphModel; import omr.glyph.GlyphSection; import omr.glyph.Shape; import omr.glyph.ui.GlyphBoard; import omr.glyph.ui.GlyphLagView; import omr.lag.RunBoard; import omr.lag.ScrollLagView; import omr.lag.Section; import omr.lag.SectionBoard; import omr.score.visitor.SheetPainter; import omr.script.ScriptRecording; import static omr.script.ScriptRecording.*; import omr.selection.GlyphEvent; import omr.selection.UserEvent; import omr.step.StepException; import omr.stick.Stick; import omr.ui.BoardsPane; import omr.ui.PixelBoard; import static omr.ui.field.SpinnerUtilities.*; import omr.util.Implement; import omr.util.Logger; import omr.util.Predicate; import omr.util.Synchronicity; import static omr.util.Synchronicity.*; import org.bushe.swing.event.EventService; import java.awt.*; import java.util.ArrayList; import java.util.Collection; /** * Class <code>VerticalsBuilder</code> is in charge of retrieving all the * vertical sticks of all systems in the sheet at hand. Bars are assumed to have * been already recognized, so this accounts for stems, vertical edges of * endings, and potentially parts of alterations (sharp, natural, flat). * * @author Herv&eacute; Bitteur * @version $Id$ */ public class VerticalsBuilder extends GlyphModel { /** Specific application parameters */ private static final Constants constants = new Constants(); /** Usual logger utility */ private static final Logger logger = Logger.getLogger( VerticalsBuilder.class); /** Events this entity is interested in */ private static final Collection<Class<?extends UserEvent>> eventClasses = new ArrayList<Class<?extends UserEvent>>(); static { eventClasses.add(GlyphEvent.class); } // Success codes private static final SuccessResult STEM = new SuccessResult("Stem"); // Failure codes private static final FailureResult TOO_LIMITED = new FailureResult( "Stem-TooLimited"); private static final FailureResult TOO_SHORT = new FailureResult( "Stem-TooShort"); private static final FailureResult TOO_FAT = new FailureResult( "Stem-TooFat"); private static final FailureResult TOO_HIGH_ADJACENCY = new FailureResult( "Stem-TooHighAdjacency"); private static final FailureResult OUTSIDE_SYSTEM = new FailureResult( "Stem-OutsideSystem"); private static final FailureResult TOO_HOLLOW = new FailureResult( "Stem-TooHollow"); /** Related user display if any */ private MyView view; /** Global sheet scale */ private final Scale scale; // VerticalsBuilder // /** * Creates a new VerticalsBuilder object. * * @param sheet the related sheet * * @throws StepException when processing had to stop */ public VerticalsBuilder (Sheet sheet) { // We work with the sheet vertical lag super(sheet, sheet.getVerticalLag()); scale = sheet.getScale(); } // deassignGlyphShape // /** * This method is limited to deassignment of stems * * @param glyph the glyph to deassign * @param record request to record this action in the script */ @Override public void deassignGlyphShape (Synchronicity processing, final Glyph glyph, final ScriptRecording record) { Shape shape = glyph.getShape(); switch (shape) { case COMBINING_STEM : sheet.getSymbolsBuilder() .deassignGlyphShape(processing, glyph, record); break; default : } } // deassignSetShape // /** * This method is limited to deassignment of stems * * @param glyphs the collection of glyphs to be de-assigned * @param record true if this action is to be recorded in the script */ @Override public void deassignSetShape (Synchronicity processing, Collection<Glyph> glyphs, ScriptRecording record) { sheet.getSymbolsBuilder() .deassignSetShape(processing, glyphs, record); } // refresh // /** * Refresh the display if any, with proper colors for sections */ public void refresh () { if (Main.getGui() != null) { if ((view == null) && constants.displayFrame.getValue()) { displayFrame(); } else if (view != null) { view.colorize(); view.repaint(); } } } // retrieveAllVerticals // public void retrieveAllVerticals () throws StepException { // Process each system area on turn int nb = 0; for (SystemInfo system : sheet.getSystems()) { nb += retrieveSystemVerticals(system); } if (constants.displayFrame.getValue() && (Main.getGui() != null)) { displayFrame(); } if (nb > 0) { logger.info(nb + " stem" + ((nb > 1) ? "s" : "") + " found"); } else { logger.info("No stem found"); } } // retrieveSystemVerticals // public int retrieveSystemVerticals (SystemInfo system) throws StepException { // Get rid of former symbols sheet.getGlyphsBuilder() .removeSystemInactives(system); // We cannot reuse the sticks, since thick sticks are allowed for bars // but not for stems. VerticalArea verticalsArea = new VerticalArea( system.getVerticalSections(), sheet, lag, new MySectionPredicate(), scale.toPixels(constants.maxStemThickness)); return retrieveVerticals(verticalsArea.getSticks(), system, true); } // stemSegment // public void stemSegment (Collection<Glyph> glyphs, SystemInfo system, boolean isShort) { // Gather all sections to be browsed Collection<GlyphSection> sections = new ArrayList<GlyphSection>(); for (Glyph glyph : glyphs) { sections.addAll(glyph.getMembers()); } if (logger.isFineEnabled()) { logger.fine("Sections browsed: " + Section.toString(sections)); } // Retrieve vertical sticks as stem candidates try { VerticalArea verticalsArea = new VerticalArea( sections, sheet, lag, new MySectionPredicate(), scale.toPixels(constants.maxStemThickness)); // Retrieve stems int nb = retrieveVerticals( verticalsArea.getSticks(), system, isShort); if (logger.isFineEnabled()) { if (nb > 0) { logger.fine(nb + " stem" + ((nb > 1) ? "s" : "")); } else { logger.fine("No stem found"); } } } catch (StepException ex) { logger.warning("stemSegment. Error in retrieving verticals"); } } // displayFrame // private void displayFrame () { // Specific rubber display view = new MyView(lag); view.colorize(); // Create a hosting frame for the view final String unit = sheet.getRadix() + ":VerticalsBuilder"; sheet.getAssembly() .addViewTab( "Verticals", new ScrollLagView(view), new BoardsPane( sheet, view, new PixelBoard(unit, sheet), new RunBoard(unit, lag), new SectionBoard(unit, lag.getLastVertexId(), lag), new GlyphBoard(unit, this, null), new MyCheckBoard(unit, lag.getEventService(), eventClasses))); } // retrieveVerticals // /** * This method retrieve compliant vertical entities (stems) within a * collection of vertical sticks, and in the context of a system * * @param sticks the provided collection of vertical sticks * @param system the containing system whose "glyphs" collection will be * augmented by the stems found * @param isShort true for short stems * @return the number of stems found * @throws StepException */ private int retrieveVerticals (Collection<Stick> sticks, SystemInfo system, boolean isShort) throws StepException { /** Suite of checks for a stem glyph */ StemCheckSuite suite = new StemCheckSuite(system, isShort); double minResult = constants.minCheckResult.getValue(); int stemNb = 0; if (logger.isFineEnabled()) { logger.fine( "Searching verticals among " + sticks.size() + " sticks from " + Glyph.toString(sticks)); } for (Stick stick : sticks) { // Run the various Checks double res = suite.pass(stick); if (logger.isFineEnabled()) { logger.fine("suite=> " + res + " for " + stick); } if (res >= minResult) { stick.setResult(STEM); stick.setShape(Shape.COMBINING_STEM); stemNb++; } else { stick.setResult(TOO_LIMITED); } sheet.getGlyphsBuilder() .insertGlyph(stick, system); } if (logger.isFineEnabled()) { logger.fine("Found " + stemNb + " stems"); } return stemNb; } // Constants // private static final class Constants extends ConstantSet { Constant.Boolean displayFrame = new Constant.Boolean( true, "Should we display a frame on the stem sticks"); Constant.Ratio maxStemAdjacencyHigh = new Constant.Ratio( 0.70, "High Maximum adjacency ratio for a stem stick"); Constant.Ratio maxStemAdjacencyLow = new Constant.Ratio( 0.60, "Low Maximum adjacency ratio for a stem stick"); Check.Grade minCheckResult = new Check.Grade( 0.50, "Minimum result for suite of check"); Constant.Ratio minDensityHigh = new Constant.Ratio( 0.9, "High Minimum density for a stem"); Constant.Ratio minDensityLow = new Constant.Ratio( 0.8, "Low Minimum density for a stem"); Constant.Ratio minStemAspectHigh = new Constant.Ratio( 12.5, "High Minimum aspect ratio for a stem stick"); Constant.Ratio minStemAspectLow = new Constant.Ratio( 10.0, "Low Minimum aspect ratio for a stem stick"); Scale.Fraction minStemLengthHigh = new Scale.Fraction( 3.5, "High Minimum length for a stem"); Scale.Fraction minStemLengthLow = new Scale.Fraction( 2.5, "Low Minimum length for a stem"); Scale.Fraction minShortStemLengthLow = new Scale.Fraction( 1.5, "Low Minimum length for a short stem"); Scale.Fraction maxStemThickness = new Scale.Fraction( 0.4, "Maximum thickness of an interesting vertical stick"); Scale.Fraction minStaffDxHigh = new Scale.Fraction( 0, "HighMinimum horizontal distance between a stem and a staff edge"); Scale.Fraction minStaffDxLow = new Scale.Fraction( 0, "LowMinimum horizontal distance between a stem and a staff edge"); } // FirstAdjacencyCheck // private static class FirstAdjacencyCheck extends Check<Stick> { protected FirstAdjacencyCheck () { super( "LeftAdj", "Check that stick is open on left side", constants.maxStemAdjacencyLow, constants.maxStemAdjacencyHigh, false, TOO_HIGH_ADJACENCY); } // Retrieve the adjacency value @Implement(Check.class) protected double getValue (Stick stick) { return (double) stick.getFirstStuck() / stick.getLength(); } } // LastAdjacencyCheck // private static class LastAdjacencyCheck extends Check<Stick> { protected LastAdjacencyCheck () { super( "RightAdj", "Check that stick is open on right side", constants.maxStemAdjacencyLow, constants.maxStemAdjacencyHigh, false, TOO_HIGH_ADJACENCY); } // Retrieve the adjacency value @Implement(Check.class) protected double getValue (Stick stick) { return (double) stick.getLastStuck() / stick.getLength(); } } // MinAspectCheck // private static class MinAspectCheck extends Check<Stick> { protected MinAspectCheck () { super( "MinAspect", "Check that stick aspect (length/thickness) is high enough", constants.minStemAspectLow, constants.minStemAspectHigh, true, TOO_FAT); } // Retrieve the ratio length / thickness @Implement(Check.class) protected double getValue (Stick stick) { return stick.getAspect(); } } // LeftCheck // private class LeftCheck extends Check<Stick> { private final SystemInfo system; protected LeftCheck (SystemInfo system) throws StepException { super( "LeftLimit", "Check stick is on right of the system beginning bar", constants.minStaffDxLow, constants.minStaffDxHigh, true, OUTSIDE_SYSTEM); this.system = system; } // Retrieve the stick abscissa @Implement(Check.class) protected double getValue (Stick stick) { int x = stick.getMidPos(); return sheet.getScale() .pixelsToFrac(x - system.getLeft()); } } // MinDensityCheck // private static class MinDensityCheck extends Check<Stick> { protected MinDensityCheck () { super( "MinDensity", "Check that stick fills its bounding rectangle", constants.minDensityLow, constants.minDensityHigh, true, TOO_HOLLOW); } // Retrieve the density @Implement(Check.class) protected double getValue (Stick stick) { Rectangle rect = stick.getBounds(); double area = rect.width * rect.height; return (double) stick.getWeight() / area; } } // MinLengthCheck // private class MinLengthCheck extends Check<Stick> { protected MinLengthCheck (boolean isShort) throws StepException { super( "MinLength", "Check that stick is long enough", isShort ? constants.minShortStemLengthLow : constants.minStemLengthLow, constants.minStemLengthHigh, true, TOO_SHORT); } // Retrieve the length data @Implement(Check.class) protected double getValue (Stick stick) { return sheet.getScale() .pixelsToFrac(stick.getLength()); } } // MyCheckBoard // private class MyCheckBoard extends CheckBoard<Stick> { public MyCheckBoard (String unit, EventService eventService, Collection<Class<?extends UserEvent>> eventList) { super(unit, null, eventService, eventList); } @Override public void onEvent (UserEvent event) { if (event instanceof GlyphEvent) { GlyphEvent glyphEvent = (GlyphEvent) event; Glyph glyph = glyphEvent.getData(); if (glyph instanceof Stick) { try { Stick stick = (Stick) glyph; SystemInfo system = sheet.getSystemOf(stick); // Get a fresh suite setSuite(new StemCheckSuite(system, true)); tellObject(stick); } catch (StepException ex) { logger.warning("Glyph cannot be processed"); } } else { tellObject(null); } } } } // MySectionPredicate // private static class MySectionPredicate implements Predicate<GlyphSection> { public boolean check (GlyphSection section) { // We process section for which glyph is null, NOISE, STRUCTURE boolean result = (section.getGlyph() == null) || !section.getGlyph() .isWellKnown(); return result; } } // MyView // private class MyView extends GlyphLagView { public MyView (GlyphLag lag) { super(lag, null, null, VerticalsBuilder.this, null); setName("VerticalsBuilder-MyView"); } // colorize // @Override public void colorize () { super.colorize(); // Use light gray color for past successful entities sheet.colorize(lag, viewIndex, Color.lightGray); // Use bright yellow color for recognized stems for (Glyph glyph : sheet.getActiveGlyphs()) { if (glyph.isStem()) { Stick stick = (Stick) glyph; stick.colorize(lag, viewIndex, Color.yellow); } } } // renderItems // @Override public void renderItems (Graphics g) { // Render all physical info known so far sheet.accept(new SheetPainter(g, getZoom())); super.renderItems(g); } } // RightCheck // private class RightCheck extends Check<Stick> { private final SystemInfo system; protected RightCheck (SystemInfo system) throws StepException { super( "RightLimit", "Check stick is on left of the system ending bar", constants.minStaffDxLow, constants.minStaffDxHigh, true, OUTSIDE_SYSTEM); this.system = system; } // Retrieve the stick abscissa @Implement(Check.class) protected double getValue (Stick stick) { return sheet.getScale() .pixelsToFrac( (system.getLeft() + system.getWidth()) - stick.getMidPos()); } } // StemCheckSuite // private class StemCheckSuite extends CheckSuite<Stick> { private final SystemInfo system; public StemCheckSuite (SystemInfo system, boolean isShort) throws StepException { super("Stem", constants.minCheckResult.getValue()); add(1, new MinLengthCheck(isShort)); add(1, new MinAspectCheck()); add(1, new FirstAdjacencyCheck()); add(1, new LastAdjacencyCheck()); add(0, new LeftCheck(system)); add(0, new RightCheck(system)); add(2, new MinDensityCheck()); this.system = system; if (logger.isFineEnabled()) { dump(); } } @Override protected void dumpSpecific () { System.out.println(system.toString()); } } }
package rapture.server; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import rapture.common.CallingContext; import rapture.common.DispatchReturn; import rapture.common.ErrorWrapper; import rapture.common.ErrorWrapperFactory; import rapture.common.RaptureEntitlementsContext; import rapture.common.exception.RaptNotLoggedInException; import rapture.common.exception.RaptureException; import rapture.common.impl.jackson.JacksonUtil; import rapture.common.model.BasePayload; import rapture.common.model.GeneralResponse; import rapture.kernel.Kernel; import rapture.kernel.stat.StatHelper; public abstract class BaseDispatcher { private static Logger log = Logger.getLogger(BaseDispatcher.class); public static String error(RaptureException raptException) { log.error("ERROR WHEN SERVICING API CALL"); try { log.error(raptException.getFormattedMessage()); ErrorWrapper ew = ErrorWrapperFactory.create(raptException); return JacksonUtil.jsonFromObject(new GeneralResponse(ew, true)); } catch (Exception e1) { log.error("Fatal server error - ", e1); return String.format("{\"response\":{\"id\":\"null\",\"status\":500,\"message\":\"Fatal server error - %s\"},\"inError\":true,\"success\":false}", e1.getMessage()); } } public abstract DispatchReturn dispatch(String params, HttpServletRequest req, HttpServletResponse resp); public static String getContextIdFromRequest(HttpServletRequest req) { Cookie[] cookies = req.getCookies(); if (cookies == null || cookies.length == 0) { //log.info("No cookies sent"); } else { for (Cookie c : cookies) { if (c.getName().equals("raptureContext")) { log.debug("RaptureContext is " + c.getValue()); return c.getValue(); } } } // Maybe it's in an id String header = req.getHeader("x-rapture"); return header; } public static CallingContext validateSession(HttpServletRequest req, BasePayload payload) { CallingContext validatedContext = null; if (payload != null && payload.getContext() != null) { validatedContext = Kernel.getKernel().loadContext(payload.getContext().getContext()); if (validatedContext == null) { log.warn("Bad Context ID: " + payload.getContext().getContext()); CallingContext heldContext = validateSession(req); return heldContext; } else { if (log.isDebugEnabled()) { log.debug("validateSession lookup returns " + validatedContext.debug()); } return validatedContext; } } else { CallingContext heldContext = validateSession(req); log.debug("validateSession direct returns " + heldContext.debug()); return heldContext; } } public static CallingContext validateSession(HttpServletRequest req) { // Will throw new RaptNotLoggedInException if the session isn't valid log.debug("Validating request"); String context = getContextIdFromRequest(req); if (context == null) { throw new RaptNotLoggedInException("Not logged in"); } // Load context CallingContext heldContext = Kernel.getKernel().loadContext(context); if (heldContext == null) { throw new RaptNotLoggedInException("Invalid context"); } return heldContext; } private RaptureEntitlementsContext getEntitlementsContext(BasePayload payload) { return new RaptureEntitlementsContext(payload); } protected void preHandlePayload(CallingContext context, BasePayload payload, String path) { validateContext(context, payload, path); recordUsageStats(payload); } protected String processResponse(GeneralResponse generalResponse) { String ret = JacksonUtil.jsonFromObject(generalResponse); try { StatHelper statApi = Kernel.getKernel().getStat(); statApi.registerApiThroughput((long) ret.length()); } catch (Exception e) { } return ret; } private static void recordUsageStats(BasePayload payload) { try { StatHelper statApi = Kernel.getKernel().getStat(); statApi.registerUser(payload.getContext().getUser()); statApi.registerApiCall(); } catch (Exception e) { } } private void validateContext(CallingContext context, BasePayload payload, String path) { Kernel.getKernel().validateContext(context, path, getEntitlementsContext(payload)); } }
package com.inf8405.tp1.flowfree; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TableRow.LayoutParams; import android.widget.TextView; import java.util.ArrayList; public class Game extends Activity { TableLayout table_game; int size = 8; int level = 2; Cell[][] ArrayCell; // Tableau qui contient les cellules du jeu ArrayList<Cell> cell_used = new ArrayList<>(); int game_score = 0; boolean active_draw = false; int color_chosen; int IndexPreviousCellRow = 0; int IndexPreviousCellCol = 0; Cell previous_cell; Cell current_cell; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game); table_game = (TableLayout) findViewById(R.id.table_game); // Remplir la table selon le niveau et la taille passee en parametres InitArrayCell(size, level); BuildTable(size); // Recupperer la taille de TableLayout table_game table_game.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(final View v, final MotionEvent event) { // Receppurer les parametres de TableLayout table_game.setMeasureWithLargestChildEnabled(true); int cellWidth = table_game.getMeasuredWidth() / Game.this.size; int cellHeight = table_game.getMeasuredHeight() / Game.this.size; // position de la case appuyee int IndexRow = (int) event.getY() / cellWidth; int IndexCol = (int) event.getX() / cellHeight; if (event.getAction() == MotionEvent.ACTION_DOWN) { if (ArrayCell[IndexRow][IndexCol].getColor() != Color.WHITE && ArrayCell[IndexRow][IndexCol].isUsed()) { IndexPreviousCellRow = IndexRow; IndexPreviousCellCol = IndexCol; active_draw = true; color_chosen = ArrayCell[IndexRow][IndexCol].getColor(); ArrayCell[IndexRow][IndexCol].setType(Cell.CellType.First); addCellUsed(ArrayCell[IndexRow][IndexCol]); previous_cell = cell_used.get(cell_used.size() - 1); current_cell = cell_used.get(cell_used.size() - 1); } } if (event.getAction() == MotionEvent.ACTION_UP) { // color_chosen = Color.WHITE; if (ArrayCell[IndexRow][IndexCol].getColor() != color_chosen || !ArrayCell[IndexRow][IndexCol].isUsed()) { active_draw = false; clearCellDrawen(); System.out.println("ACTIONUP ****"); } else { // TODO : Increment score ArrayCell[IndexRow][IndexCol].setType(Cell.CellType.Second); cell_used.clear(); } } if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) { if (cell_used.size() > 3) { } if (cell_used.size() > 0) { addCellUsed(ArrayCell[IndexRow][IndexCol]); } if (cell_used.size() > 1) { previous_cell = cell_used.get(cell_used.size() - 2); current_cell = cell_used.get(cell_used.size() - 1); IndexPreviousCellRow = previous_cell.getIndexRow(); IndexPreviousCellCol = previous_cell.getIndexCol(); // System.out.println("previous_cell : X " + previous_cell.getIndexRow() + // " Y " + previous_cell.getIndexCol()); // System.out.println("current_cell : X " + current_cell.getIndexRow() + " // " " + current_cell.getIndexCol()); } // From Down to Up if (IndexPreviousCellRow > IndexRow && IndexPreviousCellCol == IndexCol) { drawTube(IndexPreviousCellRow, IndexPreviousCellCol, color_chosen, active_draw, Cell.Sharp.UpDown); if (ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].isUsed() && ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].getSharp() == Cell.Sharp.Circle) ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].setSharp(Cell .Sharp.CircleUp); } // From Up to Down if (IndexPreviousCellRow < IndexRow && IndexPreviousCellCol == IndexCol) { drawTube(IndexPreviousCellRow, IndexPreviousCellCol, color_chosen, active_draw, Cell.Sharp.UpDown); if (ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].isUsed() && ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].getSharp() == Cell.Sharp.Circle) ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].setSharp(Cell .Sharp.CircleDown); } // From Right to Left if (IndexPreviousCellRow == IndexRow && IndexPreviousCellCol > IndexCol) { drawTube(IndexPreviousCellRow, IndexPreviousCellCol, color_chosen, active_draw, Cell.Sharp.LeftRight); if (ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].isUsed() && ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].getSharp() == Cell.Sharp.Circle) ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].setSharp(Cell .Sharp.CircleLeft); } // From Left to Right if (IndexPreviousCellRow == IndexRow && IndexPreviousCellCol < IndexCol) { drawTube(IndexPreviousCellRow, IndexPreviousCellCol, color_chosen, active_draw, Cell.Sharp.LeftRight); if (ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].isUsed() && ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].getSharp() == Cell.Sharp.Circle) ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].setSharp(Cell .Sharp.CircleRight); } // Corners // From Down to Right if (IndexPreviousCellRow > IndexRow && IndexPreviousCellCol < IndexCol) { drawTube(IndexPreviousCellRow, IndexPreviousCellCol, color_chosen, active_draw, Cell.Sharp.RightDown); if (ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].isUsed() && ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].getSharp() == Cell.Sharp.Circle) ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].setSharp(Cell .Sharp.CircleUp); } // From Up to Right if (IndexPreviousCellRow < IndexRow && IndexPreviousCellCol < IndexCol) { drawTube(IndexPreviousCellRow, IndexPreviousCellCol, color_chosen, active_draw, Cell.Sharp.RightUp); if (ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].isUsed() && ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].getSharp() == Cell.Sharp.Circle) ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].setSharp(Cell .Sharp.CircleDown); } // From Down to Left if (IndexPreviousCellRow > IndexRow && IndexPreviousCellCol > IndexCol) { drawTube(IndexPreviousCellRow, IndexPreviousCellCol, color_chosen, active_draw, Cell.Sharp.LeftDown); if (ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].isUsed() && ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].getSharp() == Cell.Sharp.Circle) ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].setSharp(Cell .Sharp.CircleLeft); } // From Up to Left if (IndexPreviousCellRow < IndexRow && IndexPreviousCellCol > IndexCol) { drawTube(IndexPreviousCellRow, IndexPreviousCellCol, color_chosen, active_draw, Cell.Sharp.LeftUp); if (ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].isUsed() && ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].getSharp() == Cell.Sharp.Circle) ArrayCell[IndexPreviousCellRow][IndexPreviousCellCol].setSharp(Cell .Sharp.CircleRight); } setScore(100); return true; } return false; } }); } private void addCellUsed(Cell cell_to_add) { boolean exist = false; for (Cell item : cell_used) { if (item.getIndexRow() == cell_to_add.getIndexRow() && item.getIndexCol() == cell_to_add.getIndexCol()) { exist = true; } } if (!exist) { cell_used.add(cell_to_add); } } private void clearCellDrawen() { System.out.println("Size :" + cell_used.size()); for (Cell item : cell_used) { int IndexCol = item.getIndexCol(); int IndexRow = item.getIndexRow(); if (!(ArrayCell[IndexRow][IndexCol].getSharp() == Cell.Sharp.Circle || ArrayCell[IndexRow][IndexCol].getSharp() == Cell.Sharp.CircleUp || ArrayCell[IndexRow][IndexCol].getSharp() == Cell.Sharp.CircleDown || ArrayCell[IndexRow][IndexCol].getSharp() == Cell.Sharp.CircleRight || ArrayCell[IndexRow][IndexCol].getSharp() == Cell.Sharp.CircleLeft)) { ArrayCell[IndexRow][IndexCol].setColor(Color.WHITE); } ArrayCell[IndexRow][IndexCol].setSharp(Cell.Sharp.Circle); ArrayCell[IndexRow][IndexCol].setType(Cell.CellType.None); System.out.println("Array : Row " + IndexRow + " -" + " Col " + IndexCol); System.out.println("get : Row " + ArrayCell[IndexRow][IndexCol].getIndexRow() + " -" + " Col " + ArrayCell[IndexRow][IndexCol].getIndexCol()); } cell_used.clear(); clearTableLayout(); BuildTable(size); } private void drawTube(int IndexRow, int IndexCol, int color_chosen, boolean active, Cell .Sharp sharp) { if (active_draw && !ArrayCell[IndexRow][IndexCol].isUsed()) { if (sharp == Cell.Sharp.UpDown && (IndexRow != 0 && IndexRow != size - 1)) { ArrayCell[IndexRow][IndexCol].setSharp(sharp); ArrayCell[IndexRow][IndexCol].setColor(color_chosen); clearTableLayout(); BuildTable(size); } else if (sharp == Cell.Sharp.LeftRight && (IndexCol != 0 && IndexCol != size - 1)) { ArrayCell[IndexRow][IndexCol].setSharp(sharp); ArrayCell[IndexRow][IndexCol].setColor(color_chosen); clearTableLayout(); BuildTable(size); } } } private void setScore(int score) { game_score = score; TextView text_score = (TextView) findViewById(R.id.score_id); text_score.setText(" " + game_score); } private void BuildTable(int size) { clearTableLayout(); // Remplir la TableLayout for (int i = 0; i < size; i++) { TableRow row = new TableRow(this); row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams .WRAP_CONTENT)); for (int col = 0; col < size; col++) { row.addView(ArrayCell[i][col]); } table_game.addView(row); } } private void clearTableLayout() { int count = table_game.getChildCount(); for (int i = 0; i < size; i++) { View child = table_game.getChildAt(i); if (child instanceof TableRow) ((ViewGroup) child).removeAllViews(); } table_game.removeAllViewsInLayout(); } private void InitArrayCell(int size, int level) { ArrayCell = new Cell[size][size]; // Remplir le tableau for (int row = 0; row < size; row++) { for (int col = 0; col < size; col++) { // Tables de size == 7 if (size == 7) { // Level 1 if (level == 1) { if ((row == 1 && col == 0) || (row == 6 && col == 0)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.RoyalBlue), row, col, true); } else if ((row == 2 && col == 2) || (row == 3 && col == 4)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.Red), row, col, true); } else if ((row == 4 && col == 2) || (row == 5 && col == 4)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.Yellow), row, col, true); } else if ((row == 4 && col == 4) || (row == 5 && col == 1)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.Orange), row, col, true); } else if ((row == 5 && col == 0) || (row == 5 && col == 5)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.LimeGreen), row, col, true); } else { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, Color.WHITE, row, col, false); } } // Level 2 if (level == 2) { if ((row == 5 && col == 0) || (row == 3 && col == 6)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.RoyalBlue), row, col, true); } else if ((row == 4 && col == 6) || (row == 6 && col == 6)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.Red), row, col, true); } else if ((row == 5 && col == 1) || (row == 2 && col == 6)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.Yellow), row, col, true); } else if ((row == 5 && col == 3) || (row == 2 && col == 5)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.Orange), row, col, true); } else if ((row == 4 && col == 5) || (row == 6 && col == 5)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.LimeGreen), row, col, true); } else if ((row == 1 && col == 1) || (row == 5 && col == 2)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.PaleTurquoise), row, col, true); } else if ((row == 2 && col == 2) || (row == 1 && col == 5)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.Gray), row, col, true); } else { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, Color.WHITE, row, col, false); } } // Level 3 if (level == 3) { if ((row == 5 && col == 0) || (row == 4 && col == 3)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.RoyalBlue), row, col, true); } else if ((row == 5 && col == 3) || (row == 6 && col == 6)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.Red), row, col, true); } else if ((row == 2 && col == 2) || (row == 2 && col == 4)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.Yellow), row, col, true); } else if ((row == 5 && col == 1) || (row == 5 && col == 4)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.Orange), row, col, true); } else if ((row == 3 && col == 1) || (row == 4 && col == 4)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.LimeGreen), row, col, true); } else if ((row == 2 && col == 1) || (row == 4 && col == 5)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.PaleTurquoise), row, col, true); } else { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, Color.WHITE, row, col, false); } } } // Tables de size == 8 if (size == 8) { // Level 1 if (level == 1) { if ((row == 1 && col == 5) || (row == 1 && col == 7)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.RoyalBlue), row, col, true); } else if ((row == 0 && col == 4) || (row == 5 && col == 4)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.Red), row, col, true); } else if ((row == 3 && col == 0) || (row == 3 && col == 6)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.Yellow), row, col, true); } else if ((row == 4 && col == 3) || (row == 5 && col == 2)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.Orange), row, col, true); } else if ((row == 1 && col == 0) || (row == 2 && col == 2)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.LimeGreen), row, col, true); } else if ((row == 0 && col == 0) || (row == 2 && col == 0)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.Maroon), row, col, true); } else if ((row == 2 && col == 7) || (row == 7 && col == 7)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.PaleTurquoise), row, col, true); } else if ((row == 1 && col == 6) || (row == 2 && col == 5)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.Gray), row, col, true); } else if ((row == 3 && col == 5) || (row == 4 && col == 2)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.PaleGreen), row, col, true); } else { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, Color.WHITE, row, col, false); } } // Level 2 if (level == 2) { if ((row == 6 && col == 2) || (row == 5 && col == 5)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.RoyalBlue), row, col, true); } else if ((row == 6 && col == 1) || (row == 4 && col == 3)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.Red), row, col, true); } else if ((row == 0 && col == 5) || (row == 3 && col == 5)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.Yellow), row, col, true); } else if ((row == 1 && col == 4) || (row == 6 && col == 3)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.Orange), row, col, true); } else if ((row == 1 && col == 6) || (row == 3 && col == 6)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.LimeGreen), row, col, true); } else if ((row == 0 && col == 4) || (row == 0 && col == 6)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.PaleTurquoise), row, col, true); } else if ((row == 2 && col == 2) || (row == 4 && col == 2)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.PaleGreen), row, col, true); } else { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, Color.WHITE, row, col, false); } } // Level 3 if (level == 3) { if ((row == 1 && col == 1) || (row == 6 && col == 2)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.RoyalBlue), row, col, true); } else if ((row == 5 && col == 2) || (row == 4 && col == 4)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.Red), row, col, true); } else if ((row == 1 && col == 5) || (row == 5 && col == 3)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.Yellow), row, col, true); } else if ((row == 1 && col == 3) || (row == 3 && col == 4)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.Orange), row, col, true); } else if ((row == 3 && col == 0) || (row == 0 && col == 3)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.LimeGreen), row, col, true); } else if ((row == 1 && col == 2) || (row == 3 && col == 3)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.Maroon), row, col, true); } else if ((row == 4 && col == 0) || (row == 1 && col == 4)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.PaleTurquoise), row, col, true); } else if ((row == 2 && col == 5) || (row == 5 && col == 4)) { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, ContextCompat.getColor(this, R.color.PaleGreen), row, col, true); } else { ArrayCell[row][col] = new Cell(this, Cell.Sharp.Circle, Cell.CellType .None, Color.WHITE, row, col, false); } } } } } } }
package com.elmakers.mine.bukkit.block; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.Set; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import org.bukkit.util.BlockVector; import com.elmakers.mine.bukkit.api.block.ModifyType; import com.elmakers.mine.bukkit.api.block.UndoList; import com.elmakers.mine.bukkit.api.magic.MaterialSet; import com.elmakers.mine.bukkit.utility.CompatibilityUtils; import com.elmakers.mine.bukkit.utility.ConfigurationUtils; import com.elmakers.mine.bukkit.utility.DeprecatedUtils; /** * Stores a cached Block. Stores the coordinates and world, but will look up a block reference on demand. * * <p>This also stores the block state using the MaterialAndData structure as a base, and can be * used to restore a previously stored state. * * <p>In addition, BlockData instances can be linked to each other for layered undo queues that work * even when undone out of order. * */ public class BlockData extends MaterialAndData implements com.elmakers.mine.bukkit.api.block.BlockData { public static final BlockFace[] FACES = new BlockFace[]{BlockFace.WEST, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.UP, BlockFace.DOWN}; public static final BlockFace[] SIDES = new BlockFace[]{BlockFace.WEST, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST}; public static boolean undoing = false; // Transient protected com.elmakers.mine.bukkit.api.block.BlockData nextState; protected com.elmakers.mine.bukkit.api.block.BlockData priorState; protected Collection<WeakReference<Player>> fakeSentToPlayers; // Persistent protected BlockVector location; protected String worldName; // Used for UndoList lookups protected WeakReference<UndoList> undoList = null; protected double damage; public static long getBlockId(Block block) { return getBlockId(block.getWorld().getName(), block.getX(), block.getY(), block.getZ()); } public static long getBlockId(Location location) { return getBlockId(location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ()); } public static long getBlockId(String world, int x, int y, int z) { // Long is 63 bits // 15 sets of F's (4-bits) // world gets 4 bits // y gets 8 bits // and x and z get 24 bits each long worldHashCode = world == null ? 0 : world.hashCode(); return ((worldHashCode & 0xF) << 56) | (((long) x & 0xFFFFFF) << 32) | (((long) z & 0xFFFFFF) << 8) | ((long) y & 0xFF); } @Override public int hashCode() { return (int) getId(); } @Override public boolean equals(Object other) { if (other instanceof BlockData) { return getId() == ((BlockData) other).getId(); } return super.equals(other); } @Override public long getId() { if (location == null) return 0; return getBlockId(worldName, location.getBlockX(), location.getBlockY(), location.getBlockZ()); } public static BlockFace getReverseFace(BlockFace blockFace) { switch (blockFace) { case NORTH: return BlockFace.SOUTH; case WEST: return BlockFace.EAST; case SOUTH: return BlockFace.NORTH; case EAST: return BlockFace.WEST; case UP: return BlockFace.DOWN; case DOWN: return BlockFace.UP; default: return BlockFace.SELF; } } public BlockData() { } public BlockData(Block block) { super(block); location = new BlockVector(block.getX(), block.getY(), block.getZ()); worldName = block.getWorld().getName(); } public BlockData(com.elmakers.mine.bukkit.api.block.BlockData copy) { super(copy); location = copy.getPosition(); worldName = copy.getWorldName(); } public BlockData(int x, int y, int z, String world, String key) { super(key); this.location = new BlockVector(x, y, z); this.worldName = world; } public void save(ConfigurationSection node) { if (worldName == null) return; node.set("material", ConfigurationUtils.fromMaterial(material)); node.set("data", data); Location location = new Location(Bukkit.getWorld(worldName), this.location.getX(), this.location.getY(), this.location.getZ()); node.set("location", ConfigurationUtils.fromLocation(location)); } public void setPosition(BlockVector location) { this.location = location; } @Override public void unlink() { if (priorState != null) { priorState.setNextState(nextState); } if (nextState != null) { // Pass state up the chain nextState.updateFrom(this); nextState.setPriorState(priorState); } priorState = null; nextState = null; } @Override public boolean undo() { return undo(false); } @Override public boolean undo(boolean applyPhysics) { return undo(applyPhysics ? ModifyType.NORMAL : ModifyType.NO_PHYSICS); } @Override public boolean undo(ModifyType modifyType) { Location location = getWorldLocation(); if (location == null) { return true; } if (!CompatibilityUtils.checkChunk(location)) { return false; } Block block = getBlock(); if (block == null) { return true; } if (fakeSentToPlayers != null) { if (nextState == null) { for (WeakReference<Player> playerRef : fakeSentToPlayers) { Player player = playerRef.get(); if (player != null) { DeprecatedUtils.sendBlockChange(player, block); } } } fakeSentToPlayers = null; unlink(); return true; } // Don't undo if not the top of the stack // Otherwise, state will be pushed up in unlink if (nextState == null && isDifferent(block)) { undoing = true; try { modify(block, modifyType); } finally { undoing = false; } } unlink(); return true; } @Override public void commit() { if (nextState != null) { nextState.setPriorState(null); nextState.updateFrom(this); nextState = null; } if (priorState != null) { // Very important for recursion! priorState.setNextState(null); // Cascade the commit downward, unlinking everything, // in case other BlockLists contain these records priorState.commit(); priorState = null; } UndoList list = undoList.get(); if (list != null) { list.remove(this); } } @Override public String toString() { return location.getBlockX() + "," + location.getBlockY() + "," + location.getBlockZ() + "," + worldName + "|" + getKey(); } @Nullable public static BlockData fromString(String s) { BlockData result = null; if (s == null) return null; try { String[] pieces = StringUtils.split(s, '|'); String[] locationPieces = StringUtils.split(pieces[0], ','); int x = Integer.parseInt(locationPieces[0]); int y = Integer.parseInt(locationPieces[1]); int z = Integer.parseInt(locationPieces[2]); String world = locationPieces[3]; result = new BlockData(x, y, z, world, pieces[1]); if (!result.isValid()) { result = null; } } catch (Exception ignored) { } return result; } @Override public com.elmakers.mine.bukkit.api.block.BlockData getNextState() { return nextState; } @Override public void setNextState(com.elmakers.mine.bukkit.api.block.BlockData next) { nextState = next; } @Override public com.elmakers.mine.bukkit.api.block.BlockData getPriorState() { return priorState; } @Override public void setPriorState(com.elmakers.mine.bukkit.api.block.BlockData prior) { priorState = prior; } @Override public void restore() { restore(false); } @Override public void restore(boolean applyPhysics) { modify(getBlock(), applyPhysics); } @Override public String getWorldName() { return worldName; } @Override public BlockVector getPosition() { return location; } @Nullable @Override public World getWorld() { if (worldName == null || worldName.length() == 0) return null; return Bukkit.getWorld(worldName); } @Nullable @Override public Block getBlock() { Block block = null; if (location != null) { World world = getWorld(); if (world != null) { block = world.getBlockAt(location.getBlockX(), location.getBlockY(), location.getBlockZ()); } } return block; } @Nullable @Override public Location getWorldLocation() { Location blockLocation = null; if (location != null) { World world = getWorld(); if (world != null) { blockLocation = new Location(world, location.getBlockX(), location.getBlockY(), location.getBlockZ()); } } return blockLocation; } @Nullable @Override public Chunk getChunk() { Chunk chunk = null; if (location != null) { World world = getWorld(); if (world != null) { chunk = world.getChunkAt(location.getBlockX() >> 4, location.getBlockZ() >> 4); } } return chunk; } @Override public boolean isDifferent() { return isDifferent(getBlock()); } @Nullable @Override public UndoList getUndoList() { return undoList != null ? undoList.get() : null; } @Override public void setUndoList(UndoList list) { if (list == null) { undoList = null; return; } undoList = new WeakReference<>(list); } @Override public BlockVector getLocation() { return location; } @Override @Deprecated public boolean containsAny(Set<Material> materials) { if (materials.contains(material)) { return true; } else if (priorState != null) { return priorState.containsAny(materials); } return false; } @Override public boolean containsAny(MaterialSet materials) { if (materials.testMaterialAndData(this)) { return true; } else if (priorState != null) { return priorState.containsAny(materials); } return false; } @Override public double getDamage() { return damage; } @Override public void addDamage(double damage) { this.damage += damage; } @Override public void setFake(Collection<WeakReference<Player>> players) { this.fakeSentToPlayers = players; } @Override public boolean isFake() { return fakeSentToPlayers != null; } }
package me.ryanhamshire.GriefPrevention; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.*; import org.bukkit.*; //manages data stored in the file system public class DatabaseDataStore extends DataStore { private Connection databaseConnection = null; private String databaseUrl; private String userName; private String password; DatabaseDataStore(String url, String userName, String password) throws Exception { this.databaseUrl = url; this.userName = userName; this.password = password; this.initialize(); } @Override void initialize() throws Exception { try { //load the java driver for mySQL Class.forName("com.mysql.jdbc.Driver"); } catch(Exception e) { GriefPrevention.AddLogEntry("ERROR: Unable to load Java's mySQL database driver. Check to make sure you've installed it properly."); throw e; } try { this.refreshDataConnection(); } catch(Exception e2) { GriefPrevention.AddLogEntry("ERROR: Unable to connect to database. Check your config file settings."); throw e2; } try { //ensure the data tables exist Statement statement = databaseConnection.createStatement(); statement.execute("CREATE TABLE IF NOT EXISTS griefprevention_nextclaimid (nextid INT(15));"); statement.execute("CREATE TABLE IF NOT EXISTS griefprevention_claimdata (id INT(15), owner VARCHAR(50), lessercorner VARCHAR(100), greatercorner VARCHAR(100), builders VARCHAR(1000), containers VARCHAR(1000), accessors VARCHAR(1000), managers VARCHAR(1000), parentid INT(15));"); statement.execute("CREATE TABLE IF NOT EXISTS griefprevention_playerdata (name VARCHAR(50), lastlogin DATETIME, accruedblocks INT(15), bonusblocks INT(15));"); statement.execute("CREATE TABLE IF NOT EXISTS griefprevention_schemaversion (version INT(15));"); //if the next claim id table is empty, this is a brand new database which will write using the latest schema //otherwise, schema version is determined by schemaversion table (or =0 if table is empty, see getSchemaVersion()) ResultSet results = statement.executeQuery("SELECT * FROM griefprevention_nextclaimid;"); if(!results.next()) { this.setSchemaVersion(latestSchemaVersion); } } catch(Exception e3) { GriefPrevention.AddLogEntry("ERROR: Unable to create the necessary database table. Details:"); GriefPrevention.AddLogEntry(e3.getMessage()); e3.printStackTrace(); throw e3; } //load group data into memory Statement statement = databaseConnection.createStatement(); ResultSet results = statement.executeQuery("SELECT * FROM griefprevention_playerdata;"); while(results.next()) { String name = results.getString("name"); //ignore non-groups. all group names start with a dollar sign. if(!name.startsWith("$")) continue; String groupName = name.substring(1); if(groupName == null || groupName.isEmpty()) continue; //defensive coding, avoid unlikely cases int groupBonusBlocks = results.getInt("bonusblocks"); this.permissionToBonusBlocksMap.put(groupName, groupBonusBlocks); } //load next claim number into memory results = statement.executeQuery("SELECT * FROM griefprevention_nextclaimid;"); //if there's nothing yet, add it if(!results.next()) { statement.execute("INSERT INTO griefprevention_nextclaimid VALUES(0);"); this.nextClaimID = (long)0; } //otherwise load it else { this.nextClaimID = results.getLong("nextid"); } if(this.getSchemaVersion() == 0) { try { this.refreshDataConnection(); //pull ALL player data from the database statement = this.databaseConnection.createStatement(); results = statement.executeQuery("SELECT * FROM griefprevention_playerdata;"); //make a list of changes to be made HashMap<String, UUID> changes = new HashMap<String, UUID>(); ArrayList<String> namesToConvert = new ArrayList<String>(); while(results.next()) { //get the id String playerName = results.getString("name"); //add to list of names to convert to UUID namesToConvert.add(playerName); } //resolve and cache as many as possible through various means try { UUIDFetcher fetcher = new UUIDFetcher(namesToConvert); fetcher.call(); } catch(Exception e) { GriefPrevention.AddLogEntry("Failed to resolve a batch of names to UUIDs. Details:" + e.getMessage()); e.printStackTrace(); } //reset results cursor results.beforeFirst(); //for each result while(results.next()) { //get the id String playerName = results.getString("name"); //try to convert player name to UUID try { UUID playerID = UUIDFetcher.getUUIDOf(playerName); //if successful, update the playerdata row by replacing the player's name with the player's UUID if(playerID != null) { changes.put(playerName, playerID); } } //otherwise leave it as-is. no harm done - it won't be requested by name, and this update only happens once. catch(Exception ex){ } } for(String name : changes.keySet()) { statement = this.databaseConnection.createStatement(); statement.execute("UPDATE griefprevention_playerdata SET name = '" + changes.get(name).toString() + "' WHERE name = '" + name + "';"); } } catch(SQLException e) { GriefPrevention.AddLogEntry("Unable to convert player data. Details:"); GriefPrevention.AddLogEntry(e.getMessage()); e.printStackTrace(); } } //load claims data into memory results = statement.executeQuery("SELECT * FROM griefprevention_claimdata;"); ArrayList<Claim> claimsToRemove = new ArrayList<Claim>(); ArrayList<Claim> subdivisionsToLoad = new ArrayList<Claim>(); while(results.next()) { try { long parentId = results.getLong("parentid"); long claimID = results.getLong("id"); Location lesserBoundaryCorner = null; Location greaterBoundaryCorner = null; try { String lesserCornerString = results.getString("lessercorner"); lesserBoundaryCorner = this.locationFromString(lesserCornerString); String greaterCornerString = results.getString("greatercorner"); greaterBoundaryCorner = this.locationFromString(greaterCornerString); } catch(Exception e) { if(e.getMessage().contains("World not found")) { Claim claim = new Claim(); claim.id = claimID; claimsToRemove.add(claim); continue; } else { throw e; } } String ownerName = results.getString("owner"); UUID ownerID = null; if(ownerName.isEmpty()) { ownerID = null; //administrative land claim or subdivision } else if(this.getSchemaVersion() < 1) { try { ownerID = UUIDFetcher.getUUIDOf(ownerName); } catch(Exception ex) { GriefPrevention.AddLogEntry("This owner name did not convert to aUUID: " + ownerName + "."); GriefPrevention.AddLogEntry(" Converted land claim to administrative @ " + lesserBoundaryCorner.toString()); } } else { try { ownerID = UUID.fromString(ownerName); } catch(Exception ex) { GriefPrevention.AddLogEntry("This owner entry is not a UUID: " + ownerName + "."); GriefPrevention.AddLogEntry(" Converted land claim to administrative @ " + lesserBoundaryCorner.toString()); } } String buildersString = results.getString("builders"); String [] builderNames = buildersString.split(";"); builderNames = this.convertNameListToUUIDList(builderNames); String containersString = results.getString("containers"); String [] containerNames = containersString.split(";"); containerNames = this.convertNameListToUUIDList(containerNames); String accessorsString = results.getString("accessors"); String [] accessorNames = accessorsString.split(";"); accessorNames = this.convertNameListToUUIDList(accessorNames); String managersString = results.getString("managers"); String [] managerNames = managersString.split(";"); managerNames = this.convertNameListToUUIDList(managerNames); Claim claim = new Claim(lesserBoundaryCorner, greaterBoundaryCorner, ownerID, builderNames, containerNames, accessorNames, managerNames, claimID); if(parentId == -1) { //top level claim this.addClaim(claim, false); } else { //subdivision subdivisionsToLoad.add(claim); } } catch(SQLException e) { GriefPrevention.AddLogEntry("Unable to load a claim. Details: " + e.getMessage() + " ... " + results.toString()); e.printStackTrace(); } } //add subdivisions to their parent claims for(Claim childClaim : subdivisionsToLoad) { //find top level claim parent Claim topLevelClaim = this.getClaimAt(childClaim.getLesserBoundaryCorner(), true, null); if(topLevelClaim == null) { claimsToRemove.add(childClaim); continue; } //add this claim to the list of children of the current top level claim childClaim.parent = topLevelClaim; topLevelClaim.children.add(childClaim); childClaim.inDataStore = true; } for(int i = 0; i < claimsToRemove.size(); i++) { this.deleteClaimFromSecondaryStorage(claimsToRemove.get(i)); } super.initialize(); } @Override synchronized void writeClaimToStorage(Claim claim) //see datastore.cs. this will ALWAYS be a top level claim { try { this.refreshDataConnection(); //wipe out any existing data about this claim this.deleteClaimFromSecondaryStorage(claim); //write top level claim data to the database this.writeClaimData(claim); //for each subdivision for(int i = 0; i < claim.children.size(); i++) { //write the subdivision's data to the database this.writeClaimData(claim.children.get(i)); } } catch(SQLException e) { GriefPrevention.AddLogEntry("Unable to save data for claim at " + this.locationToString(claim.lesserBoundaryCorner) + ". Details:"); GriefPrevention.AddLogEntry(e.getMessage()); } } //actually writes claim data to the database synchronized private void writeClaimData(Claim claim) throws SQLException { String lesserCornerString = this.locationToString(claim.getLesserBoundaryCorner()); String greaterCornerString = this.locationToString(claim.getGreaterBoundaryCorner()); String owner = ""; if(claim.ownerID != null) owner = claim.ownerID.toString(); ArrayList<String> builders = new ArrayList<String>(); ArrayList<String> containers = new ArrayList<String>(); ArrayList<String> accessors = new ArrayList<String>(); ArrayList<String> managers = new ArrayList<String>(); claim.getPermissions(builders, containers, accessors, managers); String buildersString = ""; for(int i = 0; i < builders.size(); i++) { buildersString += builders.get(i) + ";"; } String containersString = ""; for(int i = 0; i < containers.size(); i++) { containersString += containers.get(i) + ";"; } String accessorsString = ""; for(int i = 0; i < accessors.size(); i++) { accessorsString += accessors.get(i) + ";"; } String managersString = ""; for(int i = 0; i < managers.size(); i++) { managersString += managers.get(i) + ";"; } long parentId; if(claim.parent == null) { parentId = -1; } else { parentId = claim.parent.id; } long id; if(claim.id == null) { id = -1; } else { id = claim.id; } try { this.refreshDataConnection(); Statement statement = databaseConnection.createStatement(); statement.execute("INSERT INTO griefprevention_claimdata (id, owner, lessercorner, greatercorner, builders, containers, accessors, managers, parentid) VALUES(" + id + ", '" + owner + "', '" + lesserCornerString + "', '" + greaterCornerString + "', '" + buildersString + "', '" + containersString + "', '" + accessorsString + "', '" + managersString + "', " + parentId + ");"); } catch(SQLException e) { GriefPrevention.AddLogEntry("Unable to save data for claim at " + this.locationToString(claim.lesserBoundaryCorner) + ". Details:"); GriefPrevention.AddLogEntry(e.getMessage()); } } //deletes a top level claim from the database @Override synchronized void deleteClaimFromSecondaryStorage(Claim claim) { try { this.refreshDataConnection(); Statement statement = this.databaseConnection.createStatement(); statement.execute("DELETE FROM griefprevention_claimdata WHERE id=" + claim.id + ";"); statement.execute("DELETE FROM griefprevention_claimdata WHERE parentid=" + claim.id + ";"); } catch(SQLException e) { GriefPrevention.AddLogEntry("Unable to delete data for claim " + claim.id + ". Details:"); GriefPrevention.AddLogEntry(e.getMessage()); e.printStackTrace(); } } @Override synchronized PlayerData getPlayerDataFromStorage(UUID playerID) { PlayerData playerData = new PlayerData(); playerData.playerID = playerID; try { this.refreshDataConnection(); Statement statement = this.databaseConnection.createStatement(); ResultSet results = statement.executeQuery("SELECT * FROM griefprevention_playerdata WHERE name='" + playerID.toString() + "';"); //if data for this player exists, use it if(results.next()) { playerData.lastLogin = results.getTimestamp("lastlogin"); playerData.accruedClaimBlocks = results.getInt("accruedblocks"); playerData.bonusClaimBlocks = results.getInt("bonusblocks"); } } catch(SQLException e) { GriefPrevention.AddLogEntry("Unable to retrieve data for player " + playerID.toString() + ". Details:"); GriefPrevention.AddLogEntry(e.getMessage()); } return playerData; } //saves changes to player data. MUST be called after you're done making changes, otherwise a reload will lose them @Override public void asyncSavePlayerData(UUID playerID, PlayerData playerData) { //never save data for the "administrative" account. an empty string for player name indicates administrative account if(playerID == null) return; this.savePlayerData(playerID.toString(), playerData); } private void savePlayerData(String playerID, PlayerData playerData) { try { this.refreshDataConnection(); SimpleDateFormat sqlFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateString = sqlFormat.format(playerData.lastLogin); Statement statement = databaseConnection.createStatement(); statement.execute("DELETE FROM griefprevention_playerdata WHERE name='" + playerID.toString() + "';"); statement.execute("INSERT INTO griefprevention_playerdata (name, lastlogin, accruedblocks, bonusblocks) VALUES ('" + playerID.toString() + "', '" + dateString + "', " + playerData.accruedClaimBlocks + ", " + playerData.bonusClaimBlocks + ");"); } catch(SQLException e) { GriefPrevention.AddLogEntry("Unable to save data for player " + playerID.toString() + ". Details:"); GriefPrevention.AddLogEntry(e.getMessage()); } } @Override synchronized void incrementNextClaimID() { this.setNextClaimID(this.nextClaimID + 1); } //sets the next claim ID. used by incrementNextClaimID() above, and also while migrating data from a flat file data store synchronized void setNextClaimID(long nextID) { this.nextClaimID = nextID; try { this.refreshDataConnection(); Statement statement = databaseConnection.createStatement(); statement.execute("DELETE FROM griefprevention_nextclaimid;"); statement.execute("INSERT INTO griefprevention_nextclaimid VALUES (" + nextID + ");"); } catch(SQLException e) { GriefPrevention.AddLogEntry("Unable to set next claim ID to " + nextID + ". Details:"); GriefPrevention.AddLogEntry(e.getMessage()); } } //updates the database with a group's bonus blocks @Override synchronized void saveGroupBonusBlocks(String groupName, int currentValue) { //group bonus blocks are stored in the player data table, with player name = $groupName String playerName = "$" + groupName; PlayerData playerData = new PlayerData(); playerData.bonusClaimBlocks = currentValue; this.savePlayerData(playerName, playerData); } @Override synchronized void close() { if(this.databaseConnection != null) { try { if(!this.databaseConnection.isClosed()) { this.databaseConnection.close(); } } catch(SQLException e){}; } this.databaseConnection = null; } private synchronized void refreshDataConnection() throws SQLException { if(this.databaseConnection == null || this.databaseConnection.isClosed()) { //set username/pass properties Properties connectionProps = new Properties(); connectionProps.put("user", this.userName); connectionProps.put("password", this.password); //establish connection this.databaseConnection = DriverManager.getConnection(this.databaseUrl, connectionProps); } } @Override protected int getSchemaVersionFromStorage() { try { this.refreshDataConnection(); Statement statement = this.databaseConnection.createStatement(); ResultSet results = statement.executeQuery("SELECT * FROM griefprevention_schemaversion;"); //if there's nothing yet, assume 0 and add it if(!results.next()) { this.setSchemaVersion(0); return 0; } //otherwise return the value that's in the table else { return results.getInt("version"); } } catch(SQLException e) { GriefPrevention.AddLogEntry("Unable to retrieve schema version from database. Details:"); GriefPrevention.AddLogEntry(e.getMessage()); e.printStackTrace(); return 0; } } @Override protected void updateSchemaVersionInStorage(int versionToSet) { try { this.refreshDataConnection(); Statement statement = databaseConnection.createStatement(); statement.execute("DELETE FROM griefprevention_schemaversion;"); statement.execute("INSERT INTO griefprevention_schemaversion VALUES (" + versionToSet + ");"); } catch(SQLException e) { GriefPrevention.AddLogEntry("Unable to set next schema version to " + versionToSet + ". Details:"); GriefPrevention.AddLogEntry(e.getMessage()); } } }
package org.waterforpeople.mapping.domain; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.jdo.annotations.IdentityType; import javax.jdo.annotations.NotPersistent; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import org.akvo.flow.domain.DataUtils; import org.akvo.flow.domain.SecuredObject; import org.apache.commons.lang.StringUtils; import org.waterforpeople.mapping.analytics.dao.SurveyQuestionSummaryDao; import org.waterforpeople.mapping.analytics.domain.SurveyQuestionSummary; import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto.QuestionType; import org.waterforpeople.mapping.dao.SurveyInstanceDAO; import com.gallatinsystems.device.domain.DeviceFiles; import com.gallatinsystems.framework.domain.BaseDomain; import com.gallatinsystems.gis.map.MapUtils; import com.gallatinsystems.survey.dao.QuestionDao; import com.gallatinsystems.survey.dao.SurveyDAO; import com.gallatinsystems.survey.domain.Question; import static com.gallatinsystems.common.Constants.MAX_LENGTH; @PersistenceCapable(identityType = IdentityType.APPLICATION) public class SurveyInstance extends BaseDomain implements SecuredObject { private static final long serialVersionUID = 5840846001731305734L; @Persistent private Long userID; @Persistent private Date collectionDate; private Long deviceFileId; @NotPersistent private DeviceFiles deviceFile; @NotPersistent private List<QuestionAnswerStore> questionAnswersStore; private Long surveyId; private String deviceIdentifier; private String submitterName; private String approvedFlag; private String uuid; private String approximateLocationFlag; private Long surveyedLocaleId; private String surveyedLocaleIdentifier; private String surveyedLocaleDisplayName; private String countryCode; private String community; private String localeGeoLocation; private String sublevel1; private String sublevel2; private String sublevel3; private String sublevel4; private String sublevel5; private String sublevel6; private Long surveyalTime; public String getCountryCode() { return countryCode; } public void setCountryCode(String countryCode) { this.countryCode = countryCode; } public String getCommunity() { return community; } public void setCommunity(String community) { this.community = community; } public String getSublevel1() { return sublevel1; } public void setSublevel1(String sublevel1) { this.sublevel1 = sublevel1; } public String getSublevel2() { return sublevel2; } public void setSublevel2(String sublevel2) { this.sublevel2 = sublevel2; } public String getSublevel3() { return sublevel3; } public void setSublevel3(String sublevel3) { this.sublevel3 = sublevel3; } public String getSublevel4() { return sublevel4; } public void setSublevel4(String sublevel4) { this.sublevel4 = sublevel4; } public String getSublevel5() { return sublevel5; } public void setSublevel5(String sublevel5) { this.sublevel5 = sublevel5; } public String getSublevel6() { return sublevel6; } public void setSublevel6(String sublevel6) { this.sublevel6 = sublevel6; } public Long getSurveyedLocaleId() { return surveyedLocaleId; } public void setSurveyedLocaleId(Long surveyedLocaleId) { this.surveyedLocaleId = surveyedLocaleId; } @Deprecated public String getApproximateLocationFlag() { return approximateLocationFlag; } @Deprecated public void setApproximateLocationFlag(String approximateLocationFlag) { this.approximateLocationFlag = approximateLocationFlag; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public String getApprovedFlag() { return approvedFlag; } public void setApprovedFlag(String approvedFlag) { this.approvedFlag = approvedFlag; } public Long getSurveyId() { return surveyId; } public void setSurveyId(Long surveyId) { this.surveyId = surveyId; } public Long getUserID() { return userID; } public void setUserID(Long userID) { this.userID = userID; } public Date getCollectionDate() { return collectionDate; } public void setCollectionDate(Date collectionDate) { this.collectionDate = collectionDate; } public DeviceFiles getDeviceFile() { return deviceFile; } public void setDeviceFile(DeviceFiles deviceFile) { this.deviceFile = deviceFile; if (deviceFile.getKey() != null) deviceFileId = deviceFile.getKey().getId(); } public List<QuestionAnswerStore> getQuestionAnswersStore() { return questionAnswersStore; } public void setQuestionAnswersStore( List<QuestionAnswerStore> questionAnswersStore) { this.questionAnswersStore = questionAnswersStore; } public void setSubmitterName(String name) { submitterName = name; } public String getSubmitterName() { return submitterName; } public void setDeviceIdentifier(String id) { deviceIdentifier = id; } public String getDeviceIdentifier() { return deviceIdentifier; } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty("line.separator"); result.append(this.getClass().getName()); result.append(" Object {"); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { result.append(" "); try { result.append(field.getName()); result.append(": "); // requires access to private field: result.append(field.get(this)); } catch (IllegalAccessException ex) { System.out.println(ex); } result.append(newLine); } result.append("}"); return result.toString(); } public void setDeviceFileId(Long deviceFileId) { this.deviceFileId = deviceFileId; } public Long getDeviceFileId() { return deviceFileId; } public void setSurveyalTime(Long survetalTime) { this.surveyalTime = survetalTime; } public Long getSurveyalTime() { return surveyalTime; } public String getSurveyedLocaleIdentifier() { return surveyedLocaleIdentifier; } public void setSurveyedLocaleIdentifier(String surveyedLocaleIdentifier) { this.surveyedLocaleIdentifier = surveyedLocaleIdentifier; } public String getLocaleGeoLocation() { return localeGeoLocation; } public void setLocaleGeoLocation(String localeGeoLocation) { this.localeGeoLocation = localeGeoLocation; } public String getSurveyedLocaleDisplayName() { return surveyedLocaleDisplayName; } public void setSurveyedLocaleDisplayName(String surveyedLocaleDisplayName) { this.surveyedLocaleDisplayName = surveyedLocaleDisplayName.length() > MAX_LENGTH ? surveyedLocaleDisplayName .substring(0, MAX_LENGTH).trim() : surveyedLocaleDisplayName; } /** * Extract geolocation information from a survey instance * * @param surveyInstance * @return a map containing latitude and longitude entries null if a null string is provided */ public static Map<String, Object> retrieveGeoLocation( SurveyInstance surveyInstance) throws NumberFormatException { Map<String, Object> geoLocationMap = null; // retrieve geo location string String geoLocationString = null; // if the GEO information was present as Meta data, get it from there if (StringUtils.isNotBlank(surveyInstance.getLocaleGeoLocation())) { geoLocationString = surveyInstance.getLocaleGeoLocation(); } else { // else, try to look for a GEO question List<QuestionAnswerStore> geoAnswers = new SurveyInstanceDAO() .listQuestionAnswerStoreByType(surveyInstance.getKey() .getId(), QuestionType.GEO.toString()); if (geoAnswers != null && !geoAnswers.isEmpty()) { geoLocationString = geoAnswers.get(0).getValue(); } } String[] tokens = StringUtils.split(geoLocationString, "\\|"); if (tokens != null && tokens.length >= 2) { geoLocationMap = new HashMap<String, Object>(); geoLocationMap.put(MapUtils.LATITUDE, Double.parseDouble(tokens[0])); geoLocationMap.put(MapUtils.LONGITUDE, Double.parseDouble(tokens[1])); // if(tokens.length > 2) { // TODO: currently a string is generated for altitude. need to fix // geoLocationMap.put(ALTITUDE, Long.parseLong(tokens[2])); } return geoLocationMap; } /** * Update counts of SurveyQuestionSummary entities related to responses from this survey * instance. */ public void updateSummaryCounts(boolean increment) { // retrieve all summary objects SurveyQuestionSummaryDao summaryDao = new SurveyQuestionSummaryDao(); QuestionDao qDao = new QuestionDao(); List<SurveyQuestionSummary> saveList = new ArrayList<SurveyQuestionSummary>(); List<SurveyQuestionSummary> deleteList = new ArrayList<SurveyQuestionSummary>(); for (QuestionAnswerStore response : questionAnswersStore) { final Long questionId = Long.parseLong(response.getQuestionID()); Question question = qDao.getByKey(questionId); if (question == null || !question.canBeCharted()) { continue; } final String questionIdStr = response.getQuestionID(); final String[] questionResponse = DataUtils.optionResponsesTextArray(response .getValue()); for (int i = 0; i < questionResponse.length; i++) { List<SurveyQuestionSummary> questionSummaryList = summaryDao .listByResponse(questionIdStr, questionResponse[i]); SurveyQuestionSummary questionSummary = null; if (questionSummaryList.isEmpty()) { questionSummary = new SurveyQuestionSummary(); questionSummary.setQuestionId(response.getQuestionID()); questionSummary.setResponse(questionResponse[i]); questionSummary.setCount(0L); } else { questionSummary = questionSummaryList.get(0); } // update and save or delete long count = questionSummary.getCount() == null ? 0 : questionSummary.getCount(); count = increment ? ++count : --count; questionSummary.setCount(count); if (count > 0) { saveList.add(questionSummary); } else { deleteList.add(questionSummary); } } } summaryDao.save(saveList); summaryDao.delete(deleteList); } @Override public SecuredObject getParentObject() { if (surveyId == null) { return null; } return new SurveyDAO().getByKey(surveyId); } @Override public Long getObjectId() { if (key == null) { return null; } return key.getId(); } @Override public List<Long> listAncestorIds() { if (surveyId == null) { return Collections.emptyList(); } SecuredObject s = new SurveyDAO().getByKey(surveyId); if (s == null) { return Collections.emptyList(); } return s.listAncestorIds(); } @Override public List<BaseDomain> updateAncestorIds(boolean cascade) { // do not update or return any child objects. Survey entities are the leaves return Collections.emptyList(); } }
package org.opennms.install; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.net.InetAddress; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.sql.DataSource; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import org.apache.commons.io.IOUtils; import org.opennms.bootstrap.Bootstrap; import org.opennms.core.db.DataSourceConfigurationFactory; import org.opennms.core.db.install.InstallerDb; import org.opennms.core.db.install.SimpleDataSource; import org.opennms.core.logging.Logging; import org.opennms.core.schema.ExistingResourceAccessor; import org.opennms.core.schema.Migration; import org.opennms.core.schema.Migrator; import org.opennms.core.utils.ConfigFileConstants; import org.opennms.core.utils.ProcessExec; import org.opennms.netmgt.config.opennmsDataSources.JdbcDataSource; import org.opennms.netmgt.icmp.Pinger; import org.opennms.netmgt.icmp.PingerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.io.Resource; import org.springframework.util.StringUtils; /* * TODO: * - Fix all of the XXX items (some coding, some discussion) * - Change the Exceptions to something more reasonable * - Do exception handling where it makes sense (give users reasonable error messages for common problems) * - Javadoc */ /** * <p>Installer class.</p> */ public class Installer { private static final Logger LOG = LoggerFactory.getLogger(Installer.class); static final String LIBRARY_PROPERTY_FILE = "libraries.properties"; String m_opennms_home = null; boolean m_update_database = false; boolean m_do_inserts = false; boolean m_skip_constraints = false; boolean m_update_iplike = false; boolean m_update_unicode = false; boolean m_do_full_vacuum = false; boolean m_do_vacuum = false; boolean m_install_webapp = false; boolean m_fix_constraint = false; boolean m_force = false; boolean m_ignore_not_null = false; boolean m_ignore_database_version = false; boolean m_do_not_revert = false; boolean m_remove_database = false; boolean m_skip_upgrade_tools = false; String m_etc_dir = ""; String m_tomcat_conf = null; String m_webappdir = null; String m_import_dir = null; String m_install_servletdir = null; String m_library_search_path = null; String m_fix_constraint_name = null; boolean m_fix_constraint_remove_rows = false; protected Options options = new Options(); protected CommandLine m_commandLine; private Migration m_migration = new Migration(); private Migrator m_migrator = new Migrator(); Properties m_properties = null; String m_required_options = "At least one of -d, -i, -s, -y, -C, or -T is required."; private InstallerDb m_installerDb = new InstallerDb(); private static final String OPENNMS_DATA_SOURCE_NAME = "opennms"; private static final String ADMIN_DATA_SOURCE_NAME = "opennms-admin"; /** * <p>Constructor for Installer.</p> */ public Installer() { } /** * <p>install</p> * * @param argv an array of {@link java.lang.String} objects. * @throws java.lang.Exception if any. */ public void install(final String[] argv) throws Exception { printHeader(); loadProperties(); parseArguments(argv); final boolean doDatabase = (m_update_database || m_do_inserts || m_update_iplike || m_update_unicode || m_fix_constraint); if (!doDatabase && m_tomcat_conf == null && !m_install_webapp && m_library_search_path == null) { usage(options, m_commandLine, "Nothing to do. Use -h for help.", null); System.exit(1); } if (doDatabase) { final File cfgFile = ConfigFileConstants.getFile(ConfigFileConstants.OPENNMS_DATASOURCE_CONFIG_FILE_NAME); InputStream is = new FileInputStream(cfgFile); final JdbcDataSource adminDsConfig = new DataSourceConfigurationFactory(is).getJdbcDataSource(ADMIN_DATA_SOURCE_NAME); final DataSource adminDs = new SimpleDataSource(adminDsConfig); is.close(); is = new FileInputStream(cfgFile); final JdbcDataSource dsConfig = new DataSourceConfigurationFactory(is).getJdbcDataSource(OPENNMS_DATA_SOURCE_NAME); final DataSource ds = new SimpleDataSource(dsConfig); is.close(); m_installerDb.setForce(m_force); m_installerDb.setIgnoreNotNull(m_ignore_not_null); m_installerDb.setNoRevert(m_do_not_revert); m_installerDb.setAdminDataSource(adminDs); m_installerDb.setPostgresOpennmsUser(dsConfig.getUserName()); m_installerDb.setDataSource(ds); m_installerDb.setDatabaseName(dsConfig.getDatabaseName()); m_migrator.setDataSource(ds); m_migrator.setAdminDataSource(adminDs); m_migrator.setValidateDatabaseVersion(!m_ignore_database_version); m_migration.setDatabaseName(dsConfig.getDatabaseName()); m_migration.setSchemaName(dsConfig.getSchemaName()); m_migration.setAdminUser(adminDsConfig.getUserName()); m_migration.setAdminPassword(adminDsConfig.getPassword()); m_migration.setDatabaseUser(dsConfig.getUserName()); m_migration.setDatabasePassword(dsConfig.getPassword()); m_migration.setChangeLog("changelog.xml"); } checkIPv6(); /* * Make sure we can execute the rrdtool binary when the * JniRrdStrategy is enabled. */ boolean using_jni_rrd_strategy = System.getProperty("org.opennms.rrd.strategyClass", "") .contains("JniRrdStrategy"); if (using_jni_rrd_strategy) { File rrd_binary = new File(System.getProperty("rrd.binary")); if (!rrd_binary.canExecute()) { throw new Exception("Cannot execute the rrdtool binary '" + rrd_binary.getAbsolutePath() + "' required by the current RRD strategy. Update the rrd.binary field in opennms.properties appropriately."); } } /* * make sure we can load the ICMP library before we go any farther */ if (!Boolean.getBoolean("skip-native")) { String icmp_path = findLibrary("jicmp", m_library_search_path, false); String icmp6_path = findLibrary("jicmp6", m_library_search_path, false); String jrrd_path = findLibrary("jrrd", m_library_search_path, false); String jrrd2_path = findLibrary("jrrd2", m_library_search_path, false); writeLibraryConfig(icmp_path, icmp6_path, jrrd_path, jrrd2_path); } /* * Everything needs to use the administrative data source until we * verify that the opennms database is created below (and where we * create it if it doesn't already exist). */ verifyFilesAndDirectories(); if (m_install_webapp) { checkWebappOldOpennmsDir(); checkServerXmlOldOpennmsContext(); } if (m_update_database || m_fix_constraint) { // OLDINSTALL m_installerDb.readTables(); } m_installerDb.disconnect(); if (doDatabase) { m_migrator.validateDatabaseVersion(); System.out.println(String.format("* using '%s' as the PostgreSQL user for OpenNMS", m_migration.getAdminUser())); System.out.println(String.format("* using '%s' as the PostgreSQL database name for OpenNMS", m_migration.getDatabaseName())); if (m_migration.getSchemaName() != null) { System.out.println(String.format("* using '%s' as the PostgreSQL schema name for OpenNMS", m_migration.getSchemaName())); } } if (m_update_database) { m_migrator.prepareDatabase(m_migration); } if (doDatabase) { m_installerDb.checkUnicode(); } handleConfigurationChanges(); final GenericApplicationContext context = new GenericApplicationContext(); context.setClassLoader(Bootstrap.loadClasses(new File(m_opennms_home), true)); if (m_update_database) { m_installerDb.databaseSetUser(); m_installerDb.disconnect(); for (final Resource resource : context.getResources("classpath*:/changelog.xml")) { System.out.println("- Running migration for changelog: " + resource.getDescription()); m_migration.setAccessor(new ExistingResourceAccessor(resource)); m_migrator.migrate(m_migration); } } if (m_update_unicode) { System.out.println("WARNING: the -U option is deprecated, it does nothing now"); } if (m_do_vacuum) { m_installerDb.vacuumDatabase(m_do_full_vacuum); } if (m_install_webapp) { installWebApp(); } if (m_tomcat_conf != null) { updateTomcatConf(); } if (m_update_iplike) { m_installerDb.updateIplike(); } if (m_update_database && m_remove_database) { m_installerDb.disconnect(); m_installerDb.databaseRemoveDB(); } if (doDatabase) { m_installerDb.disconnect(); } if (m_update_database) { createConfiguredFile(); } System.out.println(); System.out.println("Installer completed successfully!"); if (!m_skip_upgrade_tools) { System.setProperty("opennms.manager.class", "org.opennms.upgrade.support.Upgrade"); Bootstrap.main(new String[] {}); } context.close(); } private void checkIPv6() { final IPv6Validator v6Validator = new IPv6Validator(); if (!v6Validator.isPlatformIPv6Ready()) { System.out.println("Your OS does not support IPv6."); } } private void handleConfigurationChanges() { File etcDir = new File(m_opennms_home + File.separator + "etc"); File importDir = new File(m_import_dir); File[] files = etcDir.listFiles(getImportFileFilter()); if (!importDir.exists()) { System.out.print("- Creating imports directory (" + importDir.getAbsolutePath() + "... "); if (!importDir.mkdirs()) { System.out.println("FAILED"); System.exit(1); } System.out.println("OK"); } System.out.print("- Checking for old import files in " + etcDir.getAbsolutePath() + "... "); if (files.length > 0) { System.out.println("FOUND"); for (File f : files) { String newFileName = f.getName().replace("imports-", ""); File newFile = new File(importDir, newFileName); System.out.print(" - moving " + f.getName() + " to " + importDir.getPath() + "... "); if (f.renameTo(newFile)) { System.out.println("OK"); } else { System.out.println("FAILED"); } } } else { System.out.println("DONE"); } } private FilenameFilter getImportFileFilter() { return new FilenameFilter() { public boolean accept(File dir, String name) { return name.matches("imports-.*\\.xml"); } }; } /** * <p>createConfiguredFile</p> * * @throws java.io.IOException if any. */ public void createConfiguredFile() throws IOException { File f = new File(m_opennms_home + File.separator + "etc" + File.separator + "configured"); if (!f.createNewFile()) { LOG.warn("Could not create file: {}", f.getPath()); } } /** * <p>printHeader</p> */ public void printHeader() { System.out.println("=============================================================================="); System.out.println("OpenNMS Installer"); System.out.println("=============================================================================="); System.out.println(""); System.out.println("Configures PostgreSQL tables, users, and other miscellaneous settings."); System.out.println(""); } /** * <p>loadProperties</p> * * @throws java.lang.Exception if any. */ public void loadProperties() throws Exception { m_properties = new Properties(); m_properties.load(Installer.class.getResourceAsStream("/installer.properties")); /* * Do this if we want to merge our properties with the system * properties... */ final Properties sys = System.getProperties(); m_properties.putAll(sys); m_opennms_home = fetchProperty("install.dir"); m_etc_dir = fetchProperty("install.etc.dir"); loadEtcPropertiesFile("opennms.properties"); loadEtcPropertiesFile("model-importer.properties"); // Used to retrieve 'org.opennms.rrd.strategyClass' loadEtcPropertiesFile("rrd-configuration.properties"); m_install_servletdir = fetchProperty("install.servlet.dir"); m_import_dir = fetchProperty("importer.requisition.dir"); final String pg_lib_dir = m_properties.getProperty("install.postgresql.dir"); if (pg_lib_dir != null) { m_installerDb.setPostgresPlPgsqlLocation(pg_lib_dir + File.separator + "plpgsql"); m_installerDb.setPostgresIpLikeLocation(pg_lib_dir + File.separator + "iplike"); } m_installerDb.setStoredProcedureDirectory(m_etc_dir); m_installerDb.setCreateSqlLocation(m_etc_dir + File.separator + "create.sql"); } private void loadEtcPropertiesFile(final String propertiesFile) throws IOException { try { final Properties opennmsProperties = new Properties(); final InputStream ois = new FileInputStream(m_etc_dir + File.separator + propertiesFile); opennmsProperties.load(ois); // We only want to put() things that weren't already overridden in installer.properties for (final Entry<Object,Object> p : opennmsProperties.entrySet()) { if (!m_properties.containsKey(p.getKey())) { m_properties.put(p.getKey(), p.getValue()); } } } catch (final FileNotFoundException e) { System.out.println("WARNING: unable to load " + m_etc_dir + File.separator + propertiesFile); } } /** * <p>fetchProperty</p> * * @param property a {@link java.lang.String} object. * @return a {@link java.lang.String} object. * @throws java.lang.Exception if any. */ public String fetchProperty(String property) throws Exception { String value; if ((value = m_properties.getProperty(property)) == null) { throw new Exception("property \"" + property + "\" not set " + "from bundled installer.properties file"); } return value; } /** * <p>parseArguments</p> * * @param argv an array of {@link java.lang.String} objects. * @throws java.lang.Exception if any. */ public void parseArguments(String[] argv) throws Exception { options.addOption("h", "help", false, "this help"); // database-related options options.addOption("d", "do-database", false, "perform database actions"); options.addOption("Z", "remove-database", false, "remove the OpenNMS database"); options.addOption("u", "username", true, "username of the database account (default: 'opennms')"); options.addOption("p", "password", true, "password of the database account (default: 'opennms')"); options.addOption("a", "admin-username", true, "username of the database administrator (default: 'postgres')"); options.addOption("A", "admin-password", true, "password of the database administrator (default: '')"); options.addOption("D", "database-url", true, "JDBC database URL (default: jdbc:postgresql://localhost:5432/"); options.addOption("P", "database-name", true, "name of the PostgreSQL database (default: opennms)"); options.addOption("c", "clean-database", false, "this option does nothing"); options.addOption("i", "insert-data", false, "insert (or upgrade) default data including database and XML configuration"); options.addOption("s", "stored-procedure", false, "add the IPLIKE stored procedure if it's missing"); options.addOption("U", "unicode", false, "upgrade the database to Unicode (deprecated, does nothing)"); options.addOption("v", "vacuum", false, "vacuum (optimize) the database"); options.addOption("f", "vacuum-full", false, "vacuum full the database (recovers unused disk space)"); options.addOption("N", "ignore-not-null", false, "ignore NOT NULL constraint when transforming data"); options.addOption("Q", "ignore-database-version", false, "disable the database version check"); options.addOption("x", "database-debug", false, "turn on debugging for the database data transformation"); options.addOption("R", "do-not-revert", false, "do not revert a table to the original if an error occurs"); options.addOption("n", "skip-constraint", false, ""); options.addOption("C", "repair-constraint", true, "fix rows that violate the specified constraint (sets key column to NULL)"); options.addOption("X", "drop-constraint", false, "drop rows that match the constraint specified in -C, instead of fixing them"); options.addOption("e", "extended-repairs", false, "enable extended repairs of old schemas"); // tomcat-related options options.addOption("y", "do-webapp", false, "install web application (see '-w')"); options.addOption("T", "tomcat-conf", true, "location of tomcat.conf"); options.addOption("w", "tomcat-context", true, "location of the tomcat context (eg, conf/Catalina/localhost)"); // general installation options options.addOption("l", "library-path", true, "library search path (directories separated by '" + File.pathSeparator + "')"); options.addOption("r", "rpm-install", false, "RPM install (deprecated)"); // upgrade tools options options.addOption("S", "skip-upgrade-tools", false, "Skip the execution of the upgrade tools (post-processing tasks)"); CommandLineParser parser = new PosixParser(); m_commandLine = parser.parse(options, argv); if (m_commandLine.hasOption("h")) { usage(options, m_commandLine); System.exit(0); } options.addOption("u", "username", true, "replaced by opennms-datasources.xml"); options.addOption("p", "password", true, "replaced by opennms-datasources.xml"); options.addOption("a", "admin-username", true, "replaced by opennms-datasources.xml"); options.addOption("A", "admin-password", true, "replaced by opennms-datasources.xml"); options.addOption("D", "database-url", true, "replaced by opennms-datasources.xml"); options.addOption("P", "database-name", true, "replaced by opennms-datasources.xml"); if (m_commandLine.hasOption("c")) { usage(options, m_commandLine, "The 'c' option was deprecated in 1.6, and disabled in 1.8. You should backup and then drop the database before running install to reset your data.", null); System.exit(1); } if (m_commandLine.hasOption("u") || m_commandLine.hasOption("p") || m_commandLine.hasOption("a") || m_commandLine.hasOption("A") || m_commandLine.hasOption("D") || m_commandLine.hasOption("P")) { usage( options, m_commandLine, "The 'u', 'p', 'a', 'A', 'D', and 'P' options have all been superceded.\nPlease edit $OPENNMS_HOME/etc/opennms-datasources.xml instead.", null); System.exit(1); } // m_force = m_commandLine.hasOption("c"); m_fix_constraint = m_commandLine.hasOption("C"); m_fix_constraint_name = m_commandLine.getOptionValue("C"); if (m_commandLine.hasOption("e")) { System.setProperty("opennms.contexts", "production,repair"); } m_update_database = m_commandLine.hasOption("d"); m_remove_database = m_commandLine.hasOption("Z"); m_do_full_vacuum = m_commandLine.hasOption("f"); m_do_inserts = m_commandLine.hasOption("i"); m_library_search_path = m_commandLine.getOptionValue("l", m_library_search_path); m_skip_constraints = m_commandLine.hasOption("n"); m_ignore_not_null = m_commandLine.hasOption("N"); m_ignore_database_version = m_commandLine.hasOption("Q"); m_do_not_revert = m_commandLine.hasOption("R"); m_update_iplike = m_commandLine.hasOption("s"); m_tomcat_conf = m_commandLine.getOptionValue("T", m_tomcat_conf); m_update_unicode = m_commandLine.hasOption("U"); m_do_vacuum = m_commandLine.hasOption("v"); m_webappdir = m_commandLine.getOptionValue("w", m_webappdir); m_installerDb.setDebug(m_commandLine.hasOption("x")); if (m_commandLine.hasOption("x")) { m_migrator.enableDebug(); } m_fix_constraint_remove_rows = m_commandLine.hasOption("X"); m_install_webapp = m_commandLine.hasOption("y"); m_skip_upgrade_tools = m_commandLine.hasOption("S"); if (m_commandLine.getArgList().size() > 0) { usage(options, m_commandLine, "Unknown command-line arguments: " + Arrays.toString(m_commandLine.getArgs()), null); System.exit(1); } } /** * <p>verifyFilesAndDirectories</p> * * @throws java.io.FileNotFoundException if any. */ public void verifyFilesAndDirectories() throws FileNotFoundException { if (m_update_database) { verifyFileExists(true, m_installerDb.getStoredProcedureDirectory(), "SQL directory", "install.etc.dir property"); verifyFileExists(false, m_installerDb.getCreateSqlLocation(), "create.sql", "install.etc.dir property"); } if (m_tomcat_conf != null) { verifyFileExists(false, m_tomcat_conf, "Tomcat startup configuration file tomcat4.conf", "-T option"); } if (m_install_webapp) { verifyFileExists(true, m_webappdir, "Tomcat context directory", "-w option"); verifyFileExists(true, m_install_servletdir, "OpenNMS servlet directory", "install.servlet.dir property"); } } /** * <p>verifyFileExists</p> * * @param isDir a boolean. * @param file a {@link java.lang.String} object. * @param description a {@link java.lang.String} object. * @param option a {@link java.lang.String} object. * @throws java.io.FileNotFoundException if any. */ public void verifyFileExists(boolean isDir, String file, String description, String option) throws FileNotFoundException { File f; if (file == null) { throw new FileNotFoundException("The user most provide the location of " + description + ", but this is not specified. Use the " + option + " to specify this file."); } System.out.print("- using " + description + "... "); f = new File(file); if (!f.exists()) { throw new FileNotFoundException(description + " does not exist at \"" + file + "\". Use the " + option + " to specify another location."); } if (!isDir) { if (!f.isFile()) { throw new FileNotFoundException(description + " not a file at \"" + file + "\". Use the " + option + " to specify another file."); } } else { if (!f.isDirectory()) { throw new FileNotFoundException(description + " not a directory at \"" + file + "\". Use the " + option + " to specify " + "another directory."); } } System.out.println(f.getAbsolutePath()); } /** * <p>checkWebappOldOpennmsDir</p> * * @throws java.lang.Exception if any. */ public void checkWebappOldOpennmsDir() throws Exception { File f = new File(m_webappdir + File.separator + "opennms"); System.out.print("- Checking for old opennms webapp directory in " + f.getAbsolutePath() + "... "); if (f.exists()) { throw new Exception("Old OpenNMS web application exists: " + f.getAbsolutePath() + ". You need to remove this " + "before continuing."); } System.out.println("OK"); } /** * <p>checkServerXmlOldOpennmsContext</p> * * @throws java.lang.Exception if any. */ public void checkServerXmlOldOpennmsContext() throws Exception { String search_regexp = "(?ms).*<Context\\s+path=\"/opennms\".*"; StringBuffer b = new StringBuffer(); File f = new File(m_webappdir + File.separator + ".." + File.separator + "conf" + File.separator + "server.xml"); System.out.print("- Checking for old opennms context in " + f.getAbsolutePath() + "... "); if (!f.exists()) { System.out.println("DID NOT CHECK (file does not exist)"); return; } Reader fr = new InputStreamReader(new FileInputStream(f), "UTF-8"); BufferedReader r = new BufferedReader(fr); String line; while ((line = r.readLine()) != null) { b.append(line); b.append("\n"); } r.close(); fr.close(); if (b.toString().matches(search_regexp)) { throw new Exception("Old OpenNMS context found in " + f.getAbsolutePath() + ". You must remove this context from server.xml and re-run the installer."); } System.out.println("OK"); return; } /** * <p>installWebApp</p> * * @throws java.lang.Exception if any. */ public void installWebApp() throws Exception { System.out.println("- Install OpenNMS webapp... "); copyFile(m_install_servletdir + File.separator + "META-INF" + File.separator + "context.xml", m_webappdir + File.separator + "opennms.xml", "web application context", false); System.out.println("- Installing OpenNMS webapp... DONE"); } /** * <p>copyFile</p> * * @param source a {@link java.lang.String} object. * @param destination a {@link java.lang.String} object. * @param description a {@link java.lang.String} object. * @param recursive a boolean. * @throws java.lang.Exception if any. */ public void copyFile(String source, String destination, String description, boolean recursive) throws Exception { File sourceFile = new File(source); File destinationFile = new File(destination); if (!sourceFile.exists()) { throw new Exception("source file (" + source + ") does not exist!"); } if (!sourceFile.isFile()) { throw new Exception("source file (" + source + ") is not a file!"); } if (!sourceFile.canRead()) { throw new Exception("source file (" + source + ") is not readable!"); } if (destinationFile.exists()) { System.out.print(" - " + destination + " exists, removing... "); if (destinationFile.delete()) { System.out.println("REMOVED"); } else { System.out.println("FAILED"); throw new Exception("unable to delete existing file: " + sourceFile); } } System.out.print(" - copying " + source + " to " + destination + "... "); if (!destinationFile.getParentFile().exists()) { if (!destinationFile.getParentFile().mkdirs()) { throw new Exception("unable to create directory: " + destinationFile.getParent()); } } if (!destinationFile.createNewFile()) { throw new Exception("unable to create file: " + destinationFile); } FileChannel from = null; FileInputStream fisFrom = null; FileChannel to = null; FileOutputStream fisTo = null; try { fisFrom = new FileInputStream(sourceFile); from = fisFrom.getChannel(); fisTo = new FileOutputStream(destinationFile); to = fisTo.getChannel(); to.transferFrom(from, 0, from.size()); } catch (FileNotFoundException e) { throw new Exception("unable to copy " + sourceFile + " to " + destinationFile, e); } finally { IOUtils.closeQuietly(fisTo); IOUtils.closeQuietly(to); IOUtils.closeQuietly(fisFrom); IOUtils.closeQuietly(from); } System.out.println("DONE"); } /** * <p>installLink</p> * * @param source a {@link java.lang.String} object. * @param destination a {@link java.lang.String} object. * @param description a {@link java.lang.String} object. * @param recursive a boolean. * @throws java.lang.Exception if any. */ public void installLink(String source, String destination, String description, boolean recursive) throws Exception { String[] cmd; ProcessExec e = new ProcessExec(System.out, System.out); if (new File(destination).exists()) { System.out.print(" - " + destination + " exists, removing... "); removeFile(destination, description, recursive); System.out.println("REMOVED"); } System.out.print(" - creating link to " + destination + "... "); cmd = new String[4]; cmd[0] = "ln"; cmd[1] = "-sf"; cmd[2] = source; cmd[3] = destination; if (e.exec(cmd) != 0) { throw new Exception("Non-zero exit value returned while " + "linking " + description + ", " + source + " into " + destination); } System.out.println("DONE"); } /** * <p>updateTomcatConf</p> * * @throws java.lang.Exception if any. */ public void updateTomcatConf() throws Exception { File f = new File(m_tomcat_conf); // XXX give the user the option to set the user to something else? // if so, should we chown the appropriate OpenNMS files to the // tomcat user? // XXX should we have the option to automatically try to determine // the tomcat user and chown the OpenNMS files to that user? System.out.print("- setting tomcat4 user to 'root'... "); BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8")); StringBuffer b = new StringBuffer(); String line; while ((line = r.readLine()) != null) { if (line.startsWith("TOMCAT_USER=")) { b.append("TOMCAT_USER=\"root\"\n"); } else { b.append(line); b.append("\n"); } } r.close(); if(!f.renameTo(new File(m_tomcat_conf + ".before-opennms-" + System.currentTimeMillis()))) { LOG.warn("Could not rename file: {}", f.getPath()); } f = new File(m_tomcat_conf); PrintWriter w = new PrintWriter(new FileOutputStream(f)); w.print(b.toString()); w.close(); System.out.println("DONE"); } /** * <p>removeFile</p> * * @param destination a {@link java.lang.String} object. * @param description a {@link java.lang.String} object. * @param recursive a boolean. * @throws java.io.IOException if any. * @throws java.lang.InterruptedException if any. * @throws java.lang.Exception if any. */ public void removeFile(String destination, String description, boolean recursive) throws IOException, InterruptedException, Exception { String[] cmd; ProcessExec e = new ProcessExec(System.out, System.out); if (recursive) { cmd = new String[3]; cmd[0] = "rm"; cmd[1] = "-r"; cmd[2] = destination; } else { cmd = new String[2]; cmd[0] = "rm"; cmd[1] = destination; } if (e.exec(cmd) != 0) { throw new Exception("Non-zero exit value returned while " + "removing " + description + ", " + destination + ", using \"" + StringUtils.arrayToDelimitedString(cmd, " ") + "\""); } if (new File(destination).exists()) { usage(options, m_commandLine, "Could not delete existing " + description + ": " + destination, null); System.exit(1); } } private void usage(Options options, CommandLine cmd) { usage(options, cmd, null, null); } private void usage(Options options, CommandLine cmd, String error, Exception e) { HelpFormatter formatter = new HelpFormatter(); PrintWriter pw = new PrintWriter(System.out); if (error != null) { pw.println("An error occurred: " + error + "\n"); } formatter.printHelp("usage: install [options]", options); if (e != null) { pw.println(e.getMessage()); e.printStackTrace(pw); } pw.close(); } /** * <p>main</p> * * @param argv an array of {@link java.lang.String} objects. * @throws java.lang.Exception if any. */ public static void main(String[] argv) throws Exception { final Map<String,String> mdc = Logging.getCopyOfContextMap(); Logging.putPrefix("install"); new Installer().install(argv); Logging.setContextMap(mdc); } /** * <p>checkServerVersion</p> * * @return a {@link java.lang.String} object. * @throws java.io.IOException if any. */ public String checkServerVersion() throws IOException { File catalinaHome = new File(m_webappdir).getParentFile(); String readmeVersion = getTomcatVersion(new File(catalinaHome, "README.txt")); String runningVersion = getTomcatVersion(new File(catalinaHome, "RUNNING.txt")); if (readmeVersion == null && runningVersion == null) { return null; } else if (readmeVersion != null && runningVersion != null) { return readmeVersion; // XXX what should be done here? } else if (readmeVersion != null && runningVersion == null) { return readmeVersion; } else { return runningVersion; } } /** * <p>getTomcatVersion</p> * * @param file a {@link java.io.File} object. * @return a {@link java.lang.String} object. * @throws java.io.IOException if any. */ public String getTomcatVersion(File file) throws IOException { if (file == null || !file.exists()) { return null; } Pattern p = Pattern.compile("The Tomcat (\\S+) Servlet/JSP Container"); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); for (int i = 0; i < 5; i++) { String line = in.readLine(); if (line == null) { // EOF in.close(); return null; } Matcher m = p.matcher(line); if (m.find()) { in.close(); return m.group(1); } } in.close(); return null; } /** * <p>findLibrary</p> * * @param libname a {@link java.lang.String} object. * @param path a {@link java.lang.String} object. * @param isRequired a boolean. * @return a {@link java.lang.String} object. * @throws java.lang.Exception if any. */ public String findLibrary(String libname, String path, boolean isRequired) throws Exception { String fullname = System.mapLibraryName(libname); ArrayList<String> searchPaths = new ArrayList<String>(); if (path != null) { for (String entry : path.split(File.pathSeparator)) { searchPaths.add(entry); } } try { File confFile = new File(m_opennms_home + File.separator + "etc" + File.separator + LIBRARY_PROPERTY_FILE); final Properties p = new Properties(); final InputStream is = new FileInputStream(confFile); p.load(is); is.close(); for (final Object k : p.keySet()) { String key = (String)k; if (key.startsWith("opennms.library")) { String value = p.getProperty(key); value = value.replaceAll(File.separator + "[^" + File.separator + "]*$", ""); searchPaths.add(value); } } } catch (Throwable e) { // ok if we can't read these, we'll try to find them } if (System.getProperty("java.library.path") != null) { for (final String entry : System.getProperty("java.library.path").split(File.pathSeparator)) { searchPaths.add(entry); } } if (!System.getProperty("os.name").contains("Windows")) { String[] defaults = { "/usr/lib/jni", "/usr/lib", "/usr/local/lib", "/opt/NMSjicmp/lib/32", "/opt/NMSjicmp/lib/64", "/opt/NMSjicmp6/lib/32", "/opt/NMSjicmp6/lib/64" }; for (final String entry : defaults) { searchPaths.add(entry); } } System.out.println("- searching for " + fullname + ":"); for (String dirname : searchPaths) { File entry = new File(dirname); if (entry.isFile()) { // if they specified a file, try the parent directory instead dirname = entry.getParent(); } String fullpath = dirname + File.separator + fullname; if (loadLibrary(fullpath)) { return fullpath; } if (fullname.endsWith(".dylib")) { final String fullPathOldExtension = fullpath.replace(".dylib", ".jnilib"); if (loadLibrary(fullPathOldExtension)) { return fullPathOldExtension; } } } if (isRequired) { StringBuffer buf = new StringBuffer(); for (final String pathEntry : System.getProperty("java.library.path").split(File.pathSeparator)) { buf.append(" "); buf.append(pathEntry); } throw new Exception("Failed to load the required " + libname + " library that is required at runtime. By default, we search the Java library path:" + buf.toString() + ". For more information, see http: } else { System.out.println("- Failed to load the optional " + libname + " library."); System.out.println(" - This error is not fatal, since " + libname + " is only required for optional features."); System.out.println(" - For more information, see http: } return null; } /** * <p>loadLibrary</p> * * @param path a {@link java.lang.String} object. * @return a boolean. */ public boolean loadLibrary(final String path) { try { System.out.print(" - trying to load " + path + ": "); System.load(path); System.out.println("OK"); return true; } catch (final UnsatisfiedLinkError ule) { System.out.println("NO"); } return false; } /** * <p>writeLibraryConfig</p> * * @param jicmp_path a {@link java.lang.String} object. * @param jicmp6_path TODO * @param jrrd_path a {@link java.lang.String} object. * @throws java.io.IOException if any. */ public void writeLibraryConfig(final String jicmp_path, final String jicmp6_path, final String jrrd_path, final String jrrd2_path) throws IOException { Properties libraryProps = new Properties(); if (jicmp_path != null && jicmp_path.length() != 0) { libraryProps.put("opennms.library.jicmp", jicmp_path); } if (jicmp6_path != null && jicmp6_path.length() != 0) { libraryProps.put("opennms.library.jicmp6", jicmp6_path); } if (jrrd_path != null && jrrd_path.length() != 0) { libraryProps.put("opennms.library.jrrd", jrrd_path); } if (jrrd2_path != null && jrrd2_path.length() != 0) { libraryProps.put("opennms.library.jrrd2", jrrd2_path); } File f = null; try { f = new File(m_opennms_home + File.separator + "etc" + File.separator + LIBRARY_PROPERTY_FILE); if(!f.createNewFile()) { LOG.warn("Could not create file: {}", f.getPath()); } FileOutputStream os = new FileOutputStream(f); libraryProps.store(os, null); } catch (IOException e) { System.out.println("unable to write to " + f.getPath()); throw e; } } /** * <p>pingLocalhost</p> * * @throws java.io.IOException if any. */ public void pingLocalhost() throws Exception { String host = "127.0.0.1"; java.net.InetAddress addr = null; try { addr = InetAddress.getByName(host); } catch (java.net.UnknownHostException e) { System.out.println("UnknownHostException when looking up " + host + "."); throw e; } Pinger pinger; try { pinger = PingerFactory.getInstance(); } catch (UnsatisfiedLinkError e) { System.out.println("UnsatisfiedLinkError while creating an ICMP Pinger. Most likely failed to load " + "libjicmp.so. Try setting the property 'opennms.library.jicmp' to point at the " + "full path name of the libjicmp.so shared library or switch to using the JnaPinger " + "(e.g. 'java -Dopennms.library.jicmp=/some/path/libjicmp.so ...')\n" + "You can also set the 'opennms.library.jicmp6' property in the same manner to specify " + "the location of the JICMP6 library."); throw e; } catch (NoClassDefFoundError e) { System.out.println("NoClassDefFoundError while creating an IcmpSocket. Most likely failed to load libjicmp.so" + "or libjicmp6.so."); throw e; } catch (Exception e) { System.out.println("Exception while creating an Pinger."); throw e; } // using regular InetAddress toString here since is just printed for the users benefit System.out.print("Pinging " + host + " (" + addr + ")..."); Number rtt = pinger.ping(addr); if (rtt == null) { System.out.println("failed.!"); } else { System.out.printf("successful.. round trip time: %.3f ms%n", rtt.doubleValue() / 1000.0); } } }
package net.hillsdon.reviki.wiki.renderer; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import com.google.common.base.Supplier; import net.hillsdon.reviki.vc.PageInfo; import net.hillsdon.reviki.vc.PageStore; import net.hillsdon.reviki.web.urls.URLOutputFilter; import net.hillsdon.reviki.wiki.MarkupRenderer; import net.hillsdon.reviki.wiki.renderer.creole.CreoleRenderer; import net.hillsdon.reviki.wiki.renderer.creole.LinkParts; import net.hillsdon.reviki.wiki.renderer.creole.LinkPartsHandler; import net.hillsdon.reviki.wiki.renderer.creole.ast.*; import net.hillsdon.reviki.wiki.renderer.macro.Macro; public class DocbookRenderer extends MarkupRenderer<Document> { private final PageStore _pageStore; private final LinkPartsHandler _linkHandler; private final LinkPartsHandler _imageHandler; private final Supplier<List<Macro>> _macros; public DocbookRenderer(PageStore pageStore, LinkPartsHandler linkHandler, LinkPartsHandler imageHandler, Supplier<List<Macro>> macros) { _pageStore = pageStore; _linkHandler = linkHandler; _imageHandler = imageHandler; _macros = macros; } @Override public ASTNode render(final PageInfo page) { return CreoleRenderer.render(_pageStore, page, _linkHandler, _imageHandler, _macros); } @Override public Document build(ASTNode ast, URLOutputFilter urlOutputFilter) { Document document; try { document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); document.setXmlVersion("1.0"); } catch (ParserConfigurationException e) { // Not nice, but what can we do? throw new RuntimeException(e); } DocbookVisitor renderer = new DocbookVisitor(document); renderer.setUrlOutputFilter(urlOutputFilter); // The renderer builds the root element, in this case. document.appendChild(renderer.visit(ast).get(0)); return document; } private final class DocbookVisitor extends ASTRenderer<List<Node>> { private final Document _document; public DocbookVisitor(Document document) { super(new ArrayList<Node>()); _document = document; } @Override protected List<Node> combine(List<Node> x1, List<Node> x2) { List<Node> combined = new ArrayList<Node>(); combined.addAll(x1); combined.addAll(x2); return combined; } @Override public List<Node> visitPage(Page node) { Element article = _document.createElement("article"); article.setAttribute("xmlns", "http://docbook.org/ns/docbook"); article.setAttribute("xmlns:xl", "http: article.setAttribute("version", "5.0"); article.setAttribute("xml:lang", "en"); // Render the contents Element section = null; for (ASTNode child : node.getChildren()) { // Upon hitting a heading, the section is committed to the document and // a new section begun. if (child instanceof Heading) { // The null section (and this check) is so that if the document starts // with a title, we don't commit an empty section. if (section != null) { article.appendChild(section); } section = _document.createElement("section"); } // But after the initial check, we definitely need a section. if (section == null) { section = _document.createElement("section"); } for (Node sibling : visit(child)) { section.appendChild(sibling); } } if (section != null) { article.appendChild(section); } // And we're done. return singleton(article); } /** * Helper function: build a node from an element type name and an ASTNode * containing children. */ public Element wraps(String element, ASTNode node) { return (Element) build(_document.createElement(element), visitASTNode(node)).get(0); } /** * Helper function: build a node list from an element and some children. */ public List<Node> build(Element container, List<Node> siblings) { for (Node sibling : siblings) { container.appendChild(sibling); } return singleton(container); } /** * Helper function: build a singleton list. */ public List<Node> singleton(Node n) { List<Node> out = new ArrayList<Node>(); out.add(n); return out; } @Override public List<Node> visitBold(Bold node) { Element strong = _document.createElement("emphasis"); strong.setAttribute("role", "bold"); return build(strong, visitASTNode(node)); } @Override public List<Node> visitCode(Code node) { Element out = _document.createElement("programlisting"); out.setAttribute("language", "c++"); if (node.getLanguage().isPresent()) { out.setAttribute("language", node.getLanguage().get().toString()); } out.appendChild(_document.createCDATASection(node.getText())); return singleton(out); } @Override public List<Node> visitHeading(Heading node) { Element out = _document.createElement("info"); Element title = wraps("title", node); out.appendChild(title); return singleton(out); } @Override public List<Node> visitHorizontalRule(HorizontalRule node) { Element out = _document.createElement("bridgehead"); out.setAttribute("role", "separator"); return singleton(out); } @Override public List<Node> visitImage(Image node) { LinkPartsHandler handler = node.getHandler(); PageInfo page = node.getPage(); LinkParts parts = node.getParts(); Element out = _document.createElement("imageobject"); // Header Element info = _document.createElement("info"); Element title = _document.createElement("title"); title.appendChild(_document.createTextNode(node.getTitle())); info.appendChild(title); // Image data Element imagedata = _document.createElement("imagedata"); try { String uri = handler.handle(page, parts, urlOutputFilter()); imagedata.setAttribute("fileref", uri); } catch (Exception e) { // Just display the image as text. String imageText; if (node.getTitle().equals(node.getTarget())) { imageText = "{{" + node.getTarget() + "}}"; } else { imageText = "{{" + node.getTarget() + "|" + node.getTitle() + "}}"; } out.appendChild(_document.createTextNode(imageText)); System.err.println("Failed to insert image " + imageText); return singleton(out); } // Done out.appendChild(info); out.appendChild(imagedata); return singleton(out); } @Override public List<Node> visitInlineCode(InlineCode node) { Element out = _document.createElement("code"); out.setAttribute("language", "c++"); if (node.getLanguage().isPresent()) { out.setAttribute("language", node.getLanguage().get().toString()); } out.appendChild(_document.createCDATASection(node.getText())); return singleton(out); } @Override public List<Node> visitItalic(Italic node) { return singleton(wraps("emphasis", node)); } @Override public List<Node> visitLinebreak(Linebreak node) { return singleton(_document.createElement("sbr")); } @Override public List<Node> visitLink(Link node) { LinkPartsHandler handler = node.getHandler(); PageInfo page = node.getPage(); LinkParts parts = node.getParts(); String title = node.getTitle(); String target = node.getTarget(); String uri; Element out = _document.createElement("link"); try { uri = handler.handle(page, parts, urlOutputFilter()); out.setAttribute("xl:href", uri); out.appendChild(_document.createTextNode(title)); } catch (Exception e) { // Treat mailto links specially. if (target.startsWith("mailto:")) { out.setAttribute("xl:href", target); out.appendChild(_document.createTextNode(title)); } else { // Just display the link as text. String linkText; if (title.equals(target)) { linkText = "[[" + target + "]]"; } else { linkText = "[[" + target + "|" + title + "]]"; } System.err.println("Failed to insert link " + linkText); e.printStackTrace(); throw new RuntimeException(e); // return singleton(_document.createTextNode(linkText)); } } return singleton(out); } @Override public List<Node> visitListItem(ListItem node) { return singleton(wraps("listitem", node)); } @Override public List<Node> visitMacroNode(MacroNode node) { return singleton(wraps(node.isBlock() ? "pre" : "code", node)); } @Override public List<Node> visitOrderedList(OrderedList node) { return singleton(wraps("orderedlist", node)); } @Override public List<Node> visitParagraph(Paragraph node) { return singleton(wraps("para", node)); } @Override public List<Node> visitStrikethrough(Strikethrough node) { Element strong = _document.createElement("emphasis"); strong.setAttribute("role", "strike"); return build(strong, visitASTNode(node)); } @Override public List<Node> visitTable(Table node) { return singleton(wraps("table", node)); } @Override public List<Node> visitTableCell(TableCell node) { Element out = (Element) wraps("td", node); if (isEnabled(TABLE_ALIGNMENT_DIRECTIVE)) { try { out.setAttribute("valign", unsafeGetArgs(TABLE_ALIGNMENT_DIRECTIVE).get(0)); } catch (Exception e) { System.err.println("Error when handling directive " + TABLE_ALIGNMENT_DIRECTIVE); } } return singleton(out); } @Override public List<Node> visitTableHeaderCell(TableHeaderCell node) { Element out = (Element) wraps("th", node); if (isEnabled(TABLE_ALIGNMENT_DIRECTIVE)) { try { out.setAttribute("valign", unsafeGetArgs(TABLE_ALIGNMENT_DIRECTIVE).get(0)); } catch (Exception e) { System.err.println("Error when handling directive " + TABLE_ALIGNMENT_DIRECTIVE); } } return singleton(out); } @Override public List<Node> visitTableRow(TableRow node) { return singleton(wraps("tr", node)); } @Override public List<Node> visitTextNode(TextNode node) { String text = node.getText(); return singleton(node.isEscaped() ? _document.createCDATASection(text) : _document.createTextNode(text)); } @Override public List<Node> visitUnorderedList(UnorderedList node) { return singleton(wraps("itemizedlist", node)); } } }
package net.java.sip.communicator.impl.media; import java.io.*; import java.net.*; import javax.media.*; import javax.media.protocol.*; import net.java.sip.communicator.impl.media.device.*; import net.java.sip.communicator.util.*; import javax.sdp.*; import net.java.sip.communicator.service.media.MediaException; import java.util.*; import net.java.sip.communicator.service.configuration.*; import javax.media.control.*; import javax.media.format.*; import javax.media.rtp.*; import java.awt.Dimension; /** * This class is intended to provide a generic way to control media package. * * @author Martin Andre * @author Emil Ivov * @author Damian Minkov * @author Jean Lorchat * @author Ryan Ricard * @author Ken Larson */ public class MediaControl { private Logger logger = Logger.getLogger(MediaControl.class); /** * Our configuration helper. */ private DeviceConfiguration deviceConfiguration = null; /** * The device that we use for audio capture */ private CaptureDevice audioCaptureDevice = null; /** * The device the we use for video capture. */ private CaptureDevice videoCaptureDevice = null; /** * A data source merging our audio and video data sources. */ private DataSource avDataSource = null; /** * SDP Codes of all video formats that JMF supports. */ private String[] supportedVideoEncodings = new String[] { // javax.media.format.VideoFormat.H263_RTP Integer.toString(SdpConstants.H263), // javax.media.format.VideoFormat.JPEG_RTP Integer.toString(SdpConstants.JPEG), // javax.media.format.VideoFormat.H261_RTP Integer.toString(SdpConstants.H261) }; /** * SDP Codes of all audio formats that JMF supports. */ private String[] supportedAudioEncodings = new String[] { // ILBC Integer.toString(97), // javax.media.format.AudioFormat.G723_RTP Integer.toString(SdpConstants.G723), // javax.media.format.AudioFormat.GSM_RTP; Integer.toString(SdpConstants.GSM), // javax.media.format.AudioFormat.ULAW_RTP; Integer.toString(SdpConstants.PCMU), // javax.media.format.AudioFormat.DVI_RTP; Integer.toString(SdpConstants.DVI4_8000), // javax.media.format.AudioFormat.DVI_RTP; Integer.toString(SdpConstants.DVI4_16000), // javax.media.format.AudioFormat.ALAW; Integer.toString(SdpConstants.PCMA), Integer.toString(110), // javax.media.format.AudioFormat.G728_RTP; Integer.toString(SdpConstants.G728) // javax.media.format.AudioFormat.G729_RTP // g729 is not suppported by JMF //Integer.toString(SdpConstants.G729) }; private static final String PROP_SDP_PREFERENCE = "net.java.sip.communicator.impl.media.sdppref"; /** * That's where we keep format preferences matching SDP formats to integers. * We keep preferences for both audio and video formats here in case we'd * ever need to compare them to one another. In most cases however both * would be decorelated and other components (such as the UI) should * present them separately. */ private Hashtable encodingPreferences = new Hashtable(); /** * The processor that will be handling content coming from our capture data * sources. */ private Processor sourceProcessor = null; /** * The list of readers currently using our processor. */ private Vector processorReaders = new Vector(); /** * An object that we use for. */ private ProcessorUtility processorUtility = new ProcessorUtility(); /** * The name of the property that could contain the name of a media file * to use instead of capture devices. */ private static final String DEBUG_DATA_SOURCE_URL_PROPERTY_NAME = "net.java.sip.communicator.impl.media.DEBUG_DATA_SOURCE_URL"; private static String[] customCodecs = new String[] { FMJConditionals.FMJ_CODECS ? "net.sf.fmj.media.codec.audio.alaw.Encoder" : "net.java.sip.communicator.impl.media.codec.audio.alaw.JavaEncoder", FMJConditionals.FMJ_CODECS ? "net.sf.fmj.media.codec.audio.alaw.DePacketizer" : "net.java.sip.communicator.impl.media.codec.audio.alaw.DePacketizer", FMJConditionals.FMJ_CODECS ? "net.sf.fmj.media.codec.audio.alaw.Packetizer" : "net.java.sip.communicator.impl.media.codec.audio.alaw.Packetizer", FMJConditionals.FMJ_CODECS ? "net.sf.fmj.media.codec.audio.ulaw.Packetizer" : "net.java.sip.communicator.impl.media.codec.audio.ulaw.Packetizer", "net.java.sip.communicator.impl.media.codec.audio.speex.JavaEncoder", "net.java.sip.communicator.impl.media.codec.audio.speex.JavaDecoder", "net.java.sip.communicator.impl.media.codec.audio.ilbc.JavaEncoder", "net.java.sip.communicator.impl.media.codec.audio.ilbc.JavaDecoder" // "net.java.sip.communicator.impl.media.codec.audio.g729.JavaDecoder", // "net.java.sip.communicator.impl.media.codec.audio.g729.JavaEncoder", // "net.java.sip.communicator.impl.media.codec.audio.g729.DePacketizer", // "net.java.sip.communicator.impl.media.codec.audio.g729.Packetizer" }; /** * Custom Packages provided by Sip-Communicator */ private static String[] customPackages = new String[] { // datasource for low latency ALSA input "net.java.sip.communicator.impl" }; /** * The default constructor. */ public MediaControl() { } /** * Returns the duration of the output data source. Usually this will be * DURATION_UNKNOWN, but if the current data source is set to an audio * file, then this value will be of some use. * @return the output duration */ public javax.media.Time getOutputDuration() { if (sourceProcessor == null) return Duration.DURATION_UNKNOWN; else return sourceProcessor.getDuration(); } /** * Initializes the media control. * * @param deviceConfig the <tt>DeviceConfiguration</tt> that we should use * when retrieving device handlers. * * @throws MediaException if initialization fails. */ public void initialize(DeviceConfiguration deviceConfig) throws MediaException { this.deviceConfiguration = deviceConfig; initializeFormatPreferences(); // register our own datasources registerCustomPackages(); String debugDataSourceURL = MediaActivator.getConfigurationService().getString( DEBUG_DATA_SOURCE_URL_PROPERTY_NAME); if(debugDataSourceURL == null) { initCaptureDevices(); } else { initDebugDataSource(debugDataSourceURL); } } /** * Retrieves (from the configuration service) preferences specified for * various formats and assigns default ones to those that haven't been * mentioned. */ private void initializeFormatPreferences() { //first init default preferences //video setEncodingPreference(SdpConstants.H263, 1000); setEncodingPreference(SdpConstants.JPEG, 950); setEncodingPreference(SdpConstants.H261, 800); //audio setEncodingPreference(97, 500); setEncodingPreference(SdpConstants.GSM, 450); setEncodingPreference(SdpConstants.PCMU, 400); setEncodingPreference(110, 350); setEncodingPreference(SdpConstants.DVI4_8000, 300); setEncodingPreference(SdpConstants.DVI4_16000, 250); setEncodingPreference(SdpConstants.PCMA, 200); setEncodingPreference(SdpConstants.G723, 150); setEncodingPreference(SdpConstants.G728, 100); //now override with those that are specified by the user. ConfigurationService confService = MediaActivator.getConfigurationService(); List sdpPreferences = confService.getPropertyNamesByPrefix( PROP_SDP_PREFERENCE, false); Iterator sdpPreferencesIter = sdpPreferences.iterator(); while(sdpPreferencesIter.hasNext()) { String pName = (String)sdpPreferencesIter.next(); String prefStr = confService.getString(pName); String fmtName = pName.substring(pName.lastIndexOf('.')); int preference = -1; int fmt = -1; try { preference = Integer.parseInt(prefStr); fmt = Integer.parseInt(fmtName); } catch (NumberFormatException exc) { logger.warn("Failed to parse format (" + fmtName +") or preference(" + prefStr + ").", exc); continue; } setEncodingPreference(fmt, preference); //now sort the arrays so that they are returned by order of //preference. sortEncodingsArray( this.supportedAudioEncodings); sortEncodingsArray( this.supportedVideoEncodings); } } /** * Compares the two formats for order. Returns a negative integer, * zero, or a positive integer as the first format has been assigned a * preference higher, equal to, or greater than the one of the second.<p> * * @param enc1 the first format to compare for preference. * @param enc2 the second format to compare for preference. * * @return a negative integer, zero, or a positive integer as the first * format has been assigned a preference higher, equal to, or greater than * the one of the second. */ private int compareEncodingPreferences(String enc1, String enc2) { Integer pref1 = (Integer)this.encodingPreferences.get(enc1); if(pref1 == null) pref1 = new Integer(0); Integer pref2 = (Integer)this.encodingPreferences.get(enc2); if(pref2 == null) pref2 = new Integer(0); return pref2.intValue() - pref1.intValue(); } /** * Sorts the <tt>encodingsArray</tt> according to user specified * preferences. * * @param encodingsArray the array of encodings that we'd like to sort * according to encoding preferences specifies by the user. */ private void sortEncodingsArray(String[] encodingsArray) { Arrays.sort( encodingsArray, new Comparator() { public int compare(Object o1, Object o2) { return compareEncodingPreferences((String)o1, (String)o2); } } ); } /** * Sets <tt>pref</tt> as the preference associated with <tt>encoding</tt>. * Use this method for both audio and video encodings and don't worry if * preferences are equal since we rarely need to compare prefs of video * encodings to those of audio encodings. * * @param encoding the SDP int of the encoding whose pref we're setting. * @param pref a positive int indicating the preference for that encoding. */ private void setEncodingPreference(int encoding, int pref) { setEncodingPreference(Integer.toString(encoding), new Integer(pref)); } /** * Sets <tt>pref</tt> as the preference associated with <tt>encoding</tt>. * Use this method for both audio and video encodings and don't worry if * preferences are equal since we rarely need to compare prefs of video * encodings to those of audio encodings. * * @param encoding a string containing the SDP int of the encoding whose * pref we're setting. * @param pref a positive int indicating the preference for that encoding. */ private void setEncodingPreference(String encoding, Integer pref) { this.encodingPreferences.put(encoding, pref); } /** * Opens all detected capture devices making them ready to capture. * * @throws MediaException if opening the devices fails. */ public void initCaptureDevices() throws MediaException { // Init Capture devices DataSource audioDataSource = null; DataSource videoDataSource = null; CaptureDeviceInfo audioDeviceInfo = null; CaptureDeviceInfo videoDeviceInfo = null; // audio device audioDeviceInfo = deviceConfiguration.getAudioCaptureDevice(); if (audioDeviceInfo != null) { audioDataSource = createDataSource(audioDeviceInfo.getLocator()); audioCaptureDevice = (CaptureDevice) audioDataSource; } // video device videoDeviceInfo = deviceConfiguration.getVideoCaptureDevice(); if (videoDeviceInfo != null) { videoDataSource = createDataSource(videoDeviceInfo.getLocator()); videoCaptureDevice = (CaptureDevice) videoDataSource; } // Create the av data source if (audioDataSource != null && videoDataSource != null) { DataSource[] allDS = new DataSource[] { audioDataSource, videoDataSource }; try { avDataSource = Manager.createMergingDataSource(allDS); } catch (IncompatibleSourceException exc) { logger.fatal( "Failed to create a media data source!" + "Media transmission won't be enabled!", exc); throw new InternalError("Failed to create a media data source!" + "Media transmission won't be enabled!" + exc.getMessage()); } } else { if (audioDataSource != null) { avDataSource = audioDataSource; } if (videoDataSource != null) { avDataSource = videoDataSource; } } //avDataSource may be null (Bug report Vince Fourcade) if (avDataSource != null) { initProcessor(avDataSource); } } /** * Opens the source pointed to by the <tt>debugMediaSource</tt> URL and * prepares to use it instead of capture devices. * * @param debugMediaSource an url (e.g. file:/home/user/movie.mov) pointing * to a media file to use instead of capture devices. * * @throws MediaException if opening the devices fails. */ public void initDebugDataSource(String debugMediaSource) throws MediaException { try { URL url = new URL(debugMediaSource); initDataSourceFromURL(url); } catch (MalformedURLException e) { logger.fatal("Failed to Create the Debug Media Data Source!",e); } } /** * Opens the source pointed to by the <tt>dataSourceURL</tt> URL and * prepares to use it instead of capture devices * * @param dataSourceURL an URL (e.g. file:/home/user/outgoing_message.wav) * pointing to a media file to use instead of capture devices * * @throws MediaException if opening the devices fails */ public void initDataSourceFromURL(URL dataSourceURL) throws MediaException { logger.debug("Using a data source from url: " + dataSourceURL); MediaLocator locator = new MediaLocator(dataSourceURL); avDataSource = createDataSource(locator); //avDataSource may be null (Bug report Vince Fourcade) if (avDataSource != null) { initProcessor(avDataSource); } } /** * Initialize the processor that we will be using for transmission. The * method also updates the list of supported formats limiting it to the * formats supported by <tt>dataSource</tt> * @param dataSource the source to use for our source processor. * @throws MediaException if connecting the data source or initializing the * processor fails. */ private void initProcessor(DataSource dataSource) throws MediaException { // register our custom codecs registerCustomCodecs(); try { try { dataSource.connect(); } //Thrown when operation is not supported by the OS catch (NullPointerException ex) { logger.error( "An internal error occurred while" + " trying to connec to to datasource!" , ex); throw new MediaException( "An internal error occurred while" + " trying to connec to to datasource!" , MediaException.INTERNAL_ERROR , ex); } // 1. Changing buffer size. The default buffer size (for javasound) // is 125 milliseconds - 1/8 sec. On MacOS this leeds to exception and // no audio capture. 30 value of buffer fix the problem and is ok // when using some pstn gateways // 2. Changing to 60. When it is 30 there are some issues // with asterisk and nat(we don't start to send stream and so // asterisk rtp part doesn't notice that we are behind nat) Control ctl = (Control) dataSource.getControl("javax.media.control.BufferControl"); if(ctl != null) { ((BufferControl)ctl).setBufferLength(60);//buffers in } sourceProcessor = Manager.createProcessor(dataSource); if (!processorUtility.waitForState(sourceProcessor, Processor.Configured)) { throw new MediaException( "Media manager could not configure processor\n" + "for the specified data source", MediaException.INTERNAL_ERROR); } } catch (NoProcessorException ex) { logger.error( "Media manager could not create a processor\n" + "for the specified data source" , ex ); throw new MediaException( "Media manager could not create a processor\n" + "for the specified data source" , MediaException.INTERNAL_ERROR , ex); } catch (IOException ex) { logger.error( "Media manager could not connect " + "to the specified data source" , ex); throw new MediaException("Media manager could not connect " + "to the specified data source" , MediaException.INTERNAL_ERROR , ex); } sourceProcessor.setContentDescriptor(new ContentDescriptor( ContentDescriptor.RAW_RTP)); //check out the formats that our processor supports and update our //supported formats arrays. TrackControl[] trackControls = sourceProcessor.getTrackControls(); logger.debug("We will be able to transmit in:"); List transmittableAudioEncodings = new ArrayList(); List transmittableVideoEncodings = new ArrayList(); for (int i = 0; i < trackControls.length; i++) { Format[] formats = trackControls[i].getSupportedFormats(); for (int j = 0; j < formats.length; j++) { Format format = formats[j]; String encoding = format.getEncoding(); int sdpInt = MediaUtils.jmfToSdpEncoding(encoding); if (sdpInt != MediaUtils.UNKNOWN_ENCODING) { String sdp = String.valueOf(sdpInt); if (format instanceof AudioFormat) { if (!transmittableAudioEncodings.contains(sdp)) { if (logger.isDebugEnabled()) { logger.debug("Audio=[" + (j + 1) + "]=" + encoding + "; sdp=" + sdp); } transmittableAudioEncodings.add(sdp); } } if (format instanceof VideoFormat) { if (!transmittableVideoEncodings.contains(sdp)) { if (logger.isDebugEnabled()) { logger.debug("Video=[" + (j + 1) + "]=" + encoding + "; sdp=" + sdp); } transmittableVideoEncodings.add(sdp); } } } else { logger.debug("unknown encoding format " + encoding); } } } //now update the supported encodings arrays. if(transmittableAudioEncodings.size() > 0) { supportedAudioEncodings = new String[transmittableAudioEncodings.size()]; for (int i = 0; i < supportedAudioEncodings.length; i++) { supportedAudioEncodings[i] = (String) transmittableAudioEncodings.get(i); } //sort the supported encodings according to user preferences. this.sortEncodingsArray(supportedAudioEncodings); } //else { //just leave supportedAudioEncodings as it was in the beginning //as it will be only receiving so it could say it supports //everything. } if(transmittableVideoEncodings.size() > 0) { supportedVideoEncodings = new String[transmittableVideoEncodings.size()]; for (int i = 0; i < supportedVideoEncodings.length; i++) { supportedVideoEncodings[i] = (String) transmittableVideoEncodings.get(i); } //sort the supported encodings according to user preferences. this.sortEncodingsArray(supportedVideoEncodings); } //else { //just leave supportedVideoEncodings as it was in the beginning //as it will be only receiving so it could say it supports //everything. } } /** * Closes all curently used capture devices and data sources so that they * would be usable by other applications. * * @throws MediaException if closing the devices fails with an IO * Exception. */ public void closeCaptureDevices() throws MediaException { try { if(avDataSource != null) avDataSource.stop(); } catch (IOException exc) { logger.error("Failed to close a capture date source.", exc); throw new MediaException("Failed to close a capture date source." , MediaException.INTERNAL_ERROR , exc); } } /** * Returns a JMF DataSource object over the device that <tt>locator</tt> * points to. * @param locator the MediaLocator of the device/movie that we'd like to * transmit from. * @return a connected <tt>DataSource</tt> for the media specified by the * locator. */ private DataSource createDataSource(MediaLocator locator) { try { logger.info("Creating datasource for:" + ((locator != null) ? locator.toExternalForm() : "null")); return Manager.createDataSource(locator); } catch (NoDataSourceException ex) { // The failure only concens us logger.error("Could not create data source for " + locator.toExternalForm() , ex); return null; } catch (IOException ex) { // The failure only concerns us logger.error("Could not create data source for " + locator.toExternalForm() , ex); return null; } } /** * Creates a processing data source using the <tt>encodingSets</tt> map * to determine the formats/encodings allowed for the various media types. * * @param encodingSets a hashtable mapping media types such as "audio" or * "video" to <tt>List</tt>a of encodings (ordered by preference) accepted * for the corresponding type. * * @return a processing data source set to generate flows in the encodings * specified by the encodingSets map. * * @throws MediaException if creating the data source fails for some reason. */ public DataSource createDataSourceForEncodings(Hashtable encodingSets) throws MediaException { if (sourceProcessor == null) { logger.error("Processor is null."); throw new MediaException("The source Processor has not been " + "initialized." , MediaException.INTERNAL_ERROR); } // Wait for the sourceProcessor to configure boolean processorIsReady = true; if (sourceProcessor.getState() < Processor.Configured) { processorIsReady = processorUtility .waitForState(sourceProcessor, Processor.Configured); } if (!processorIsReady) { logger.error("Couldn't configure sourceProcessor"); throw new MediaException("Couldn't configure sourceProcessor" , MediaException.INTERNAL_ERROR); } // Get the tracks from the sourceProcessor TrackControl[] tracks = sourceProcessor.getTrackControls(); // Do we have atleast one track? if (tracks == null || tracks.length < 1) { logger.error("Couldn't find any tracks in sourceProcessor"); throw new MediaException( "Couldn't find any tracks in sourceProcessor" , MediaException.INTERNAL_ERROR); } // Set the output content descriptor to RAW_RTP // This will limit the supported formats reported from // Track.getSupportedFormats to only valid RTP formats. ContentDescriptor cd = new ContentDescriptor(ContentDescriptor. RAW_RTP); sourceProcessor.setContentDescriptor(cd); Format supported[]; Format chosenFormat; boolean atLeastOneTrack = false; // Program the tracks. for (int i = 0; i < tracks.length; i++) { Format format = tracks[i].getFormat(); if (tracks[i].isEnabled()) { supported = tracks[i].getSupportedFormats(); if (logger.isDebugEnabled()) { logger.debug("Available encodings are:"); for (int j = 0; j < supported.length; j++) { logger.debug("track[" + (i + 1) + "] format[" + (j + 1) + "]=" + supported[j].getEncoding()); } } // We've set the output content to the RAW_RTP. // So all the supported formats should work with RTP. // We'll pick one that matches those specified by the // constructor. if (supported.length > 0) { if (supported[0] instanceof VideoFormat) { // For video formats, we should double check the // sizes since not all formats work in all sizes. int index = findFirstMatchingFormat(supported, encodingSets); if (index != -1) { chosenFormat = assertSize( (VideoFormat)supported[index]); tracks[i].setFormat(chosenFormat); logger.debug("Track " + i + " is set to transmit " + "as: " + chosenFormat); atLeastOneTrack = true; } else { tracks[i].setEnabled(false); } } else { if (FMJConditionals.FORCE_AUDIO_FORMAT != null) { tracks[i].setFormat(FMJConditionals.FORCE_AUDIO_FORMAT); atLeastOneTrack = true; } else { int index = findFirstMatchingFormat(supported, encodingSets); if (index != -1) { tracks[i].setFormat(supported[index]); if (logger.isDebugEnabled()) { logger.debug("Track " + i + " is set to transmit as: " + supported[index]); } atLeastOneTrack = true; } else { tracks[i].setEnabled(false); } } } } else { tracks[i].setEnabled(false); } } else { tracks[i].setEnabled(false); } } if (!atLeastOneTrack) { logger.error( "Couldn't set any of the tracks to a valid RTP format"); throw new MediaException( "Couldn't set any of the tracks to a valid RTP format" , MediaException.INTERNAL_ERROR); } // Realize the sourceProcessor. This will internally create a flow // graph and attempt to create an output datasource processorIsReady = processorUtility.waitForState(sourceProcessor , Controller.Realized); if (!processorIsReady) { logger.error("Couldn't realize sourceProcessor"); throw new MediaException("Couldn't realize sourceProcessor" , MediaException.INTERNAL_ERROR); } // Set the JPEG quality. /** @todo set JPEG quality through a property */ setJpegQuality(sourceProcessor, 1f); // Get the output data source of the sourceProcessor return sourceProcessor.getDataOutput(); } /** * Setting the encoding quality to the specified value on the JPEG encoder. * 0.5 is a good default. * * @param player the player that we're setting the quality on. * @param val a float between 0 (for minimum quality) and 1 (for maximum * quality). */ private void setJpegQuality(Player player, float val) { if (player == null || player.getState() < Player.Realized) return; Control cs[] = player.getControls(); QualityControl qc = null; VideoFormat jpegFmt = new VideoFormat(VideoFormat.JPEG); // Loop through the controls to find the Quality control for // the JPEG encoder. for (int i = 0; i < cs.length; i++) { if (cs[i] instanceof QualityControl && cs[i] instanceof Owned) { Object owner = ( (Owned) cs[i]).getOwner(); // Check to see if the owner is a Codec. // Then check for the output format. if (owner instanceof Codec) { Format fmts[] = ( (Codec) owner) .getSupportedOutputFormats(null); for (int j = 0; j < fmts.length; j++) { if (fmts[j].matches(jpegFmt)) { qc = (QualityControl) cs[i]; qc.setQuality(val); logger.debug("Setting quality to " + val + " on " + qc); break; } } } if (qc != null) { break; } } } } /** * For JPEG and H263, we know that they only work for particular * sizes. So we'll perform extra checking here to make sure they * are of the right sizes. * * @param sourceFormat the original format that we'd like to check for * size. * * @return the modified <tt>VideoFormat</tt> set to the size we support. */ private VideoFormat assertSize(VideoFormat sourceFormat) { int width, height; Dimension size = sourceFormat.getSize(); Format jpegFmt = new Format(VideoFormat.JPEG_RTP); Format h263Fmt = new Format(VideoFormat.H263_RTP); if (sourceFormat.matches(jpegFmt)) { // For JPEG, make sure width and height are divisible by 8. width = (size.width % 8 == 0) ? size.width : ( ( (size.width / 8)) * 8); height = (size.height % 8 == 0) ? size.height : (size.height / 8) * 8; } else if (sourceFormat.matches(h263Fmt)) { // For H.263, we only support some specific sizes. //if (size.width < 128) // width = 128; // height = 96; //else if (size.width < 176) // width = 176; // height = 144; //else width = 352; height = 288; } else { // We don't know this particular format. We'll just // leave it alone then. return sourceFormat; } VideoFormat result = new VideoFormat(null, new Dimension(width, height), Format.NOT_SPECIFIED, null, Format.NOT_SPECIFIED); return (VideoFormat) result.intersects(sourceFormat); } /** * Looks for the first encoding (amont the requested encodings elements) * that is also present in the <tt>availableFormats</tt> array and returns * the index of the corresponding <tt>Format</tt>. * * @param availableFormats an array of JMF <tt>Format</tt>s that we're * currently able to transmit. * @param requestedEncodings a table mapping media types (e.g. audio or * video) to a list of encodings that our interlocutor has sent in order of * preference. * * @return the index of the format corresponding to the first encoding that * had a marching format in the <tt>availableFormats</tt> array. */ protected int findFirstMatchingFormat(Format[] availableFormats, Hashtable requestedEncodings) { if (availableFormats == null || requestedEncodings == null) { return -1; } Enumeration formatSets = requestedEncodings.elements(); while(formatSets.hasMoreElements()) { ArrayList currentSet = (ArrayList) formatSets.nextElement(); for (int k = 0; k < currentSet.size(); k++) { for (int i = 0; i < availableFormats.length; i++) { if (availableFormats[i].getEncoding() .equals( (String)currentSet.get(k))) { return i; } } } } return -1; } /** * Returns an array of Strings containing video formats in the order of * preference. * @return an array of Strings containing video formats in the order of * preference. */ public String[] getSupportedVideoEncodings() { return this.supportedVideoEncodings; } /** * Returns an array of Strings containing audio formats in the order of * preference. * @return an array of Strings containing audio formats in the order of * preference. */ public String[] getSupportedAudioEncodings() { return this.supportedAudioEncodings; } /** * Starts reading media from the source data sources. If someone is * already reading, then simply add the reader to the list of readers so * that we don't pull the plug from underneath their feet. * * @param reader a reference to the object calling this method, that we * could use for keeping the number of simulaneous active readers. */ public void startProcessingMedia(Object reader) { if( sourceProcessor.getState() != Processor.Started ) sourceProcessor.start(); if(!processorReaders.contains(reader)) processorReaders.add(reader); } /** * Stops reading media from the source data sources. If there is someone * else still reading, then we simply remove the local reference to the * reader and wait for the last reader to call stopProcessing before we * really stop the processor. * * @param reader a reference to the object calling this method, that we * could use for keeping the number of simulaneous active readers. */ public void stopProcessingMedia(Object reader) { if(sourceProcessor == null) return; if( sourceProcessor.getState() == Processor.Started ) sourceProcessor.stop(); if(processorReaders.contains(reader)) processorReaders.remove(reader); } /** * Register in JMF the custom codecs we provide */ private void registerCustomCodecs() { // use a set to check if the codecs are already // registered in jmf.properties Set registeredPlugins = new HashSet(); for ( Iterator plugins = PlugInManager .getPlugInList( null, null, PlugInManager.CODEC).iterator(); plugins.hasNext(); ) { registeredPlugins.add(plugins.next()); } for (int i = 0; i < customCodecs.length; i++) { String className = customCodecs[i]; if (registeredPlugins.contains(className)) { logger.debug("Codec : " + className + " is already registered"); } else { try { Class pic = Class.forName(className); Object instance = pic.newInstance(); boolean result = PlugInManager.addPlugIn( className, ( (Codec) instance).getSupportedInputFormats(), ( (Codec) instance).getSupportedOutputFormats(null), PlugInManager.CODEC); logger.debug("Codec : " + className + " is succsefully registered : " + result); } catch (Throwable ex) { logger.debug("Codec : " + className + " is NOT succsefully registered"); } } } try { PlugInManager.commit(); } catch (IOException ex) { logger.error("Cannot commit to PlugInManager", ex); } // Register the custom codec formats with the RTP manager once at // initialization. This is needed for the Sun JMF implementation. It // causes the registration of the formats with the static FormatInfo // instance of com.sun.media.rtp.RTPSessionMgr, which in turn makes the // formats available when the supported encodings arrays are generated // in initProcessor(). In other JMF implementations this might not be // needed, but should do no harm. //Commented as it fails to load alaw codec // RTPManager rtpManager = RTPManager.newInstance(); // CallSessionImpl.registerCustomCodecFormats(rtpManager); // rtpManager.dispose(); } /** * Register in JMF the custom packages we provide */ private void registerCustomPackages() { Vector currentPackagePrefix = PackageManager.getProtocolPrefixList(); for (int i = 0; i < customPackages.length; i++) { String className = customPackages[i]; // linear search in a loop, but it doesn't have to scale since the // list is always short if (!currentPackagePrefix.contains(className)) { currentPackagePrefix.addElement(className); logger.debug("Adding package : " + className); } } PackageManager.setProtocolPrefixList(currentPackagePrefix); PackageManager.commitProtocolPrefixList(); logger.debug("Registering new protocol prefix list : " + currentPackagePrefix); } }
package net.neevek.android.widget; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.view.View; import android.view.ViewTreeObserver; import android.view.animation.Animation; import android.view.animation.RotateAnimation; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import net.neevek.android.R; /** * @author neevek <i at neevek.net> * * The default implementation of a pull-to-refresh header view for OverScrollListView. * this can be taken as a reference. * */ public class PullToRefreshHeaderView extends LinearLayout implements OverScrollListView.PullToRefreshCallback { private final static int ROTATE_ANIMATION_DURATION = 300; private View mArrowView; private TextView mTvRefresh; private ProgressBar mProgressBar; private Animation mAnimRotateUp; private Animation mAnimRotateDown; public PullToRefreshHeaderView(Context context) { super(context); init(); } public PullToRefreshHeaderView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public PullToRefreshHeaderView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public void init() { getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { mArrowView = findViewById(R.id.iv_down_arrow); mTvRefresh = (TextView)findViewById(R.id.tv_refresh); mProgressBar = (ProgressBar)findViewById(R.id.pb_refreshing); if (Build.VERSION.SDK_INT >= 16) { getViewTreeObserver().removeOnGlobalLayoutListener(this); } else { getViewTreeObserver().removeGlobalOnLayoutListener(this); } } }); mAnimRotateUp = new RotateAnimation(0, -180f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); mAnimRotateUp.setDuration(ROTATE_ANIMATION_DURATION); mAnimRotateUp.setFillAfter(true); mAnimRotateDown = new RotateAnimation(-180f, 0, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); mAnimRotateDown.setDuration(ROTATE_ANIMATION_DURATION); mAnimRotateDown.setFillAfter(true); } /** * @param scrollY [screenHeight, 0] */ @Override public void onPull(int scrollY) { } @Override public void onReachAboveHeaderViewHeight() { mTvRefresh.setText("Release To Refresh"); mArrowView.startAnimation(mAnimRotateUp); } @Override public void onReachBelowHeaderViewHeight() { mTvRefresh.setText("Pull To Refresh"); mArrowView.startAnimation(mAnimRotateDown); } @Override public void onStartRefreshing() { mArrowView.clearAnimation(); mArrowView.setVisibility(GONE); mProgressBar.setVisibility(VISIBLE); mTvRefresh.setText("Loading..."); } @Override public void onEndRefreshing() { mArrowView.setVisibility(VISIBLE); mProgressBar.setVisibility(GONE); mTvRefresh.setText("Pull To Refresh"); } }
package com.notipon; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import android.content.Context; import android.util.Log; import com.notipon.Deal; import com.notipon.Filter; public class DealFetcher { private static final String EXAMPLE_JSON_FILE = "example_deals.json"; private static final String TAG = "DealFetcher"; private Context context; private static final String grouponKey = "8a42c4f943043ffe9cb59defb3f51bc30e4c59a3"; public DealFetcher(Context context) { this.context = context; } public ArrayList<Deal> getDeals() { return getJsonExampleDeals(); } public ArrayList<Deal> getDeals(Filter filter) { return filter.apply(getDeals()); } private ArrayList<Deal> getJsonExampleDeals() { return Deal.parseJsonDeals(loadExampleJson()); } private String loadStreamAsString(InputStream binaryInput) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(binaryInput)); StringBuilder builder = new StringBuilder(); String line; while ((line = in.readLine()) != null) { builder.append(line); } in.close(); return builder.toString(); } private String loadExampleJson() { try { return loadStreamAsString(context.getAssets().open(EXAMPLE_JSON_FILE)); } catch (IOException e) { Log.e(TAG, "Failed to load example Json"); } return ""; } private URL buildDealRequestUrl() throws MalformedURLException { return new URL("http://api.groupon.com/v2/deals/?client_id=" + grouponKey); } private String fetchCurrentDeals() { try { URL dealUrl = buildDealRequestUrl(); return loadStreamAsString(dealUrl.openStream()); } catch (MalformedURLException e) { Log.e(TAG, "Bad deal URL:", e); } catch (IOException e) { Log.e(TAG, "Failed to load URL:", e); } Log.e(TAG, "Error in fetching current deals, falling back to example Json."); return loadExampleJson(); } }
package org.appwork.swing.exttable.columns; import java.awt.Dimension; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import javax.swing.ComboBoxModel; import javax.swing.Icon; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import net.miginfocom.swing.MigLayout; import org.appwork.resources.AWUTheme; import org.appwork.swing.action.BasicAction; import org.appwork.swing.exttable.ExtTableModel; import sun.swing.SwingUtilities2; public abstract class ExtComboColumn<E, ModelType> extends ExtTextColumn<E> implements ActionListener { private static final long serialVersionUID = 2114805529462086691L; private ComboBoxModel<ModelType> dataModel; public ExtComboColumn(final String name, final ComboBoxModel<ModelType> model) { this(name, null, model); } public ExtComboColumn(final String name, final ExtTableModel<E> table, final ComboBoxModel<ModelType> model) { super(name, table); renderer.removeAll(); renderer.setLayout(new MigLayout("ins 0", "[grow,fill]0[12]5", "[grow,fill]")); renderer.add(rendererField); renderer.add(rendererIcon); this.dataModel = model; } @Override public void configureRendererComponent(final E value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { // TODO Auto-generated method stub if (isEditable(value)) { rendererIcon.setIcon(this.getIcon(value)); } else { rendererIcon.setIcon(null); } String str = this.getStringValue(value); if (str == null) { // under substance, setting setText(null) somehow sets the label // opaque. str = ""; } if (getTableColumn() != null) { rendererField.setText(SwingUtilities2.clipStringIfNecessary(rendererField, rendererField.getFontMetrics(rendererField.getFont()), str, getTableColumn().getWidth() - 18 - 5)); } else { rendererField.setText(str); } } public boolean onSingleClick(final MouseEvent e, final E value) { if (!isEditable(value)) { return false; } final JPopupMenu popup = new JPopupMenu(); try { final ModelType selected = getSelectedItem(value); for (int i = 0; i < dataModel.getSize(); i++) { final ModelType o = dataModel.getElementAt(i); popup.add(new JMenuItem(new BasicAction(o.toString()) { { setName(modelItemToString(o)); if (selected == o) { setSmallIcon(AWUTheme.I().getIcon("enable", 16)); } } @Override public void actionPerformed(final ActionEvent e) { setValue(o, value); } })); } final Rectangle bounds = getModel().getTable().getCellRect(getModel().getTable().rowAtPoint(new Point(e.getX(), e.getY())), getModel().getTable().columnAtPoint(new Point(e.getX(), e.getY())), true); final Dimension pref = popup.getPreferredSize(); popup.setPreferredSize(new Dimension(Math.max(pref.width, bounds.width), pref.height)); popup.show(getModel().getTable(), bounds.x, bounds.y + bounds.height); return true; } catch (final Exception e1) { e1.printStackTrace(); } return false; } protected Icon getIcon(final E value) { return AWUTheme.I().getIcon("popdownButton", -1); } @Override public String getStringValue(final E value) { return modelItemToString(getSelectedItem(value)); } /** * @param value * @param comboBoxModel * @return */ protected abstract ModelType getSelectedItem(final E object); protected abstract void setSelectedItem(final E object, final ModelType value); /** * @param selectedItem * @return */ protected String modelItemToString(final ModelType selectedItem) { return selectedItem.toString(); } @Override protected String getTooltipText(final E obj) { // TODO Auto-generated method stub return super.getTooltipText(obj); } @Override public boolean isEditable(final E obj) { return this.dataModel.getSize() > 1; } @Override public boolean isEnabled(final E obj) { return true; } public boolean isCellEditable(final int rowIndex, final int columnIndex) { return false; } @Override public boolean isSortable(final E obj) { return true; } @Override final public void setValue(final Object value, final E object) { try { setSelectedItem(object, (ModelType) value); } catch (final Exception e) { e.printStackTrace(); } } /** * overwrite this method to implement different dropdown boxes * * @param dataModel */ public ComboBoxModel<ModelType> updateModel(final ComboBoxModel<ModelType> dataModel, final E value) { return dataModel; } }
/* * @author <a href="mailto:[email protected]">Jason Novotny</a> * @version $Id$ */ package org.gridlab.gridsphere.servlets; import org.gridlab.gridsphere.core.persistence.PersistenceManagerFactory; import org.gridlab.gridsphere.core.persistence.PersistenceManagerRdbms; import org.gridlab.gridsphere.core.persistence.hibernate.DBTask; import org.gridlab.gridsphere.layout.PortletLayoutEngine; import org.gridlab.gridsphere.layout.PortletPageFactory; import org.gridlab.gridsphere.portlet.*; import org.gridlab.gridsphere.portlet.impl.*; import org.gridlab.gridsphere.portlet.service.PortletServiceException; import org.gridlab.gridsphere.portlet.service.spi.impl.SportletServiceFactory; import org.gridlab.gridsphere.portletcontainer.impl.GridSphereEventImpl; import org.gridlab.gridsphere.portletcontainer.impl.SportletMessageManager; import org.gridlab.gridsphere.portletcontainer.*; import org.gridlab.gridsphere.services.core.registry.PortletManagerService; import org.gridlab.gridsphere.services.core.security.acl.AccessControlManagerService; import org.gridlab.gridsphere.services.core.security.auth.AuthorizationException; import org.gridlab.gridsphere.services.core.security.auth.AuthenticationException; import org.gridlab.gridsphere.services.core.user.LoginService; import org.gridlab.gridsphere.services.core.user.UserManagerService; import org.gridlab.gridsphere.services.core.user.UserSessionManager; import org.gridlab.gridsphere.services.core.request.RequestService; import org.gridlab.gridsphere.services.core.request.GenericRequest; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.servlet.*; import javax.servlet.http.*; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; import java.net.SocketException; /** * The <code>GridSphereServlet</code> is the GridSphere portlet container. * All portlet requests get proccessed by the GridSphereServlet before they * are rendered. */ public class GridSphereServlet extends HttpServlet implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener, HttpSessionActivationListener { /* GridSphere logger */ private static PortletLog log = SportletLog.getInstance(GridSphereServlet.class); /* GridSphere service factory */ private static SportletServiceFactory factory = null; /* GridSphere Portlet Registry Service */ private static PortletManagerService portletManager = null; /* GridSphere Access Control Service */ private static AccessControlManagerService aclService = null; private static UserManagerService userManagerService = null; private static LoginService loginService = null; private PortletMessageManager messageManager = SportletMessageManager.getInstance(); /* GridSphere Portlet layout Engine handles rendering */ private static PortletLayoutEngine layoutEngine = null; /* Session manager maps users to sessions */ private UserSessionManager userSessionManager = UserSessionManager.getInstance(); /* creates cookie requests */ private RequestService requestService = null; private PortletContext context = null; private static Boolean firstDoGet = Boolean.TRUE; private static PortletSessionManager sessionManager = PortletSessionManager.getInstance(); //private static PortletRegistry registry = PortletRegistry.getInstance(); private static final String COOKIE_REQUEST = "cookie-request"; private int COOKIE_EXPIRATION_TIME = 60 * 60 * 24 * 7; // 1 week (in secs) private PortletGroup coreGroup = null; private boolean isTCK = false; /** * Initializes the GridSphere portlet container * * @param config the <code>ServletConfig</code> * @throws ServletException if an error occurs during initialization */ public final void init(ServletConfig config) throws ServletException { super.init(config); GridSphereConfig.setServletConfig(config); //SportletLog.setConfigureURL(GridSphereConfig.getServletContext().getRealPath("/WEB-INF/classes/log4j.properties")); this.context = new SportletContext(config); factory = SportletServiceFactory.getInstance(); layoutEngine = PortletLayoutEngine.getInstance(); log.debug("in init of GridSphereServlet"); } public synchronized void initializeServices() throws PortletServiceException { requestService = (RequestService) factory.createPortletService(RequestService.class, getServletConfig().getServletContext(), true); log.debug("Creating access control manager service"); aclService = (AccessControlManagerService) factory.createPortletService(AccessControlManagerService.class, getServletConfig().getServletContext(), true); // create root user in default group if necessary log.debug("Creating user manager service"); userManagerService = (UserManagerService) factory.createPortletService(UserManagerService.class, getServletConfig().getServletContext(), true); loginService = (LoginService) factory.createPortletService(LoginService.class, getServletConfig().getServletContext(), true); log.debug("Creating portlet manager service"); portletManager = (PortletManagerService) factory.createPortletService(PortletManagerService.class, getServletConfig().getServletContext(), true); } /** * Processes GridSphere portal framework requests * * @param req the <code>HttpServletRequest</code> * @param res the <code>HttpServletResponse</code> * @throws IOException if an I/O error occurs * @throws ServletException if a servlet error occurs */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { processRequest(req, res); } public void setHeaders(HttpServletResponse res) { res.setContentType("text/html; charset=utf-8"); // Necessary to display UTF-8 encoded characters res.setHeader("Cache-Control","no-cache"); //Forces caches to obtain a new copy of the page from the origin server res.setHeader("Cache-Control","no-store"); //Directs caches not to store the page under any circumstance res.setDateHeader("Expires", 0); //Causes the proxy cache to see the page as "stale" res.setHeader("Pragma","no-cache"); //HTTP 1.0 backward compatibility } public void processRequest(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { setHeaders(res); GridSphereEvent event = new GridSphereEventImpl(context, req, res); PortletRequest portletReq = event.getPortletRequest(); // If first time being called, instantiate all portlets if (firstDoGet.equals(Boolean.TRUE)) { synchronized (firstDoGet) { firstDoGet = Boolean.FALSE; log.debug("Testing Database"); // checking if database setup is correct DBTask dt = new DBTask(); dt.setAction(DBTask.ACTION_CHECKDB); dt.setConfigDir(GridSphereConfig.getServletContext().getRealPath("")); try { dt.execute(); } catch (Exception e) { RequestDispatcher rd = req.getRequestDispatcher("/jsp/errors/database_error.jsp"); log.error("Check DB failed: ", e); req.setAttribute("error", "DB Error! Please contact your GridSphere/Database Administrator!"); rd.forward(req, res); return; } log.debug("Initializing portlets and services"); try { // initialize portlet service factory factory.init(); // initialize needed services initializeServices(); // create a root user if none available userManagerService.initRootUser(); // initialize all portlets PortletResponse portletRes = event.getPortletResponse(); PortletInvoker.initAllPortlets(portletReq, portletRes); // deep inside a service is used which is why this must follow the factory.init layoutEngine.init(); } catch (Exception e) { log.error("GridSphere initialization failed!", e); RequestDispatcher rd = req.getRequestDispatcher("/jsp/errors/init_error.jsp"); req.setAttribute("error", e); rd.forward(req, res); return; } coreGroup = aclService.getCoreGroup(); } } setUserAndGroups(portletReq); checkUserHasCookie(event); // Used for TCK tests //setTCKUser(portletReq); // Handle user login and logout if (event.hasAction()) { if (event.getAction().getName().equals(SportletProperties.LOGIN)) { login(event); //event = new GridSphereEventImpl(aclService, context, req, res); } if (event.getAction().getName().equals(SportletProperties.LOGOUT)) { logout(event); // since event is now invalidated, must create new one event = new GridSphereEventImpl(context, req, res); } } layoutEngine.actionPerformed(event); // is this a file download operation? downloadFile(event); // Handle any outstanding messages // This needs work certainly!!! Map portletMessageLists = messageManager.retrieveAllMessages(); if (!portletMessageLists.isEmpty()) { Set keys = portletMessageLists.keySet(); Iterator it = keys.iterator(); String concPortletID = null; List messages = null; while (it.hasNext()) { concPortletID = (String) it.next(); messages = (List) portletMessageLists.get(concPortletID); Iterator newit = messages.iterator(); while (newit.hasNext()) { PortletMessage msg = (PortletMessage) newit.next(); layoutEngine.messageEvent(concPortletID, msg, event); } } messageManager.removeAllMessages(); } setUserAndGroups(portletReq); // Used for TCK tests //setTCKUser(portletReq); layoutEngine.service(event); //log.debug("Session stats"); //userSessionManager.dumpSessions(); //log.debug("Portlet service factory stats"); //factory.logStatistics(); /* log.debug("Portlet page factory stats"); try { PortletPageFactory pageFactory = PortletPageFactory.getInstance(); pageFactory.logStatistics(); } catch (Exception e) { log.error("Unable to get page factory", e); } */ } public void setTCKUser(PortletRequest req) { //String tck = (String)req.getPortletSession(true).getAttribute("tck"); String[] portletNames = req.getParameterValues("portletName"); if ((isTCK) || (portletNames != null)) { log.info("Setting a TCK user"); SportletUserImpl u = new SportletUserImpl(); u.setUserName("tckuser"); u.setUserID("tckuser"); u.setID("500"); Map l = new HashMap(); l.put(coreGroup, PortletRole.USER); req.setAttribute(SportletProperties.PORTLET_USER, u); req.setAttribute(SportletProperties.PORTLETGROUPS, l); req.setAttribute(SportletProperties.PORTLET_ROLE, PortletRole.USER); isTCK = true; } } public void setUserAndGroups(PortletRequest req) { // Retrieve user if there is one User user = null; if (req.getPortletSession() != null) { String uid = (String) req.getPortletSession().getAttribute(SportletProperties.PORTLET_USER); if (uid != null) { user = userManagerService.getUser(uid); } } HashMap groups = new HashMap(); PortletRole role = PortletRole.GUEST; if (user == null) { user = GuestUser.getInstance(); groups = new HashMap(); groups.put(coreGroup, PortletRole.GUEST); } else { List mygroups = aclService.getGroups(user); Iterator it = mygroups.iterator(); while (it.hasNext()) { PortletGroup g = (PortletGroup) it.next(); role = aclService.getRoleInGroup(user, g); groups.put(g, role); } } // req.getPortletRole returns the role user has in core gridsphere group role = aclService.getRoleInGroup(user, coreGroup); // set user, role and groups in request req.setAttribute(SportletProperties.PORTLET_GROUP, coreGroup); req.setAttribute(SportletProperties.PORTLET_USER, user); req.setAttribute(SportletProperties.PORTLETGROUPS, groups); req.setAttribute(SportletProperties.PORTLET_ROLE, role); } protected void checkUserHasCookie(GridSphereEvent event) { PortletRequest req = event.getPortletRequest(); User user = req.getUser(); if (user instanceof GuestUser) { Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; System.err.println("found a cookie:"); System.err.println("name=" + c.getName()); System.err.println("value=" + c.getValue()); if (c.getName().equals("gsuid")) { String cookieVal = c.getValue(); int hashidx = cookieVal.indexOf(" if (hashidx > 0) { String uid = cookieVal.substring(0, hashidx); System.err.println("uid = " + uid); String reqid = cookieVal.substring(hashidx+1); System.err.println("reqid = " + reqid); GenericRequest genreq = requestService.getRequest(reqid, COOKIE_REQUEST); if (genreq != null) { if (genreq.getUserID().equals(uid)) { User newuser = userManagerService.getUser(uid); if (newuser != null) { setUserSettings(event, newuser); } } } } } } } } } protected void setUserCookie(GridSphereEvent event) { PortletRequest req = event.getPortletRequest(); PortletResponse res = event.getPortletResponse(); User user = req.getUser(); GenericRequest request = requestService.createRequest(COOKIE_REQUEST); Cookie cookie = new Cookie("gsuid", user.getID() + "#" + request.getOid()); request.setUserID(user.getID()); long time = Calendar.getInstance().getTime().getTime() + COOKIE_EXPIRATION_TIME * 1000; request.setLifetime(new Date(time)); requestService.saveRequest(request); // COOKIE_EXPIRATION_TIME is specified in secs cookie.setMaxAge(COOKIE_EXPIRATION_TIME); res.addCookie(cookie); System.err.println("adding a cookie"); } protected void removeUserCookie(GridSphereEvent event) { PortletRequest req = event.getPortletRequest(); PortletResponse res = event.getPortletResponse(); Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; if (c.getName().equals("gsuid")) { int idx = c.getValue().indexOf(" if (idx > 0) { String reqid = c.getValue().substring(idx+1); System.err.println("reqid= " + reqid); GenericRequest request = requestService.getRequest(reqid, COOKIE_REQUEST); if (request != null) requestService.deleteRequest(request); } c.setMaxAge(0); res.addCookie(c); } } } } /** * Handles login requests * * @param event a <code>GridSphereEvent</code> */ protected void login(GridSphereEvent event) { log.debug("in login of GridSphere Servlet"); String LOGIN_ERROR_FLAG = "LOGIN_FAILED"; PortletRequest req = event.getPortletRequest(); String username = req.getParameter("username"); String password = req.getParameter("password"); try { User user = loginService.login(username, password); // null out passwd password = null; setUserSettings(event, user); String remme = req.getParameter("remlogin"); if (remme != null) { setUserCookie(event); } else { removeUserCookie(event); } } catch (AuthorizationException err) { log.debug(err.getMessage()); req.setAttribute(LOGIN_ERROR_FLAG, err.getMessage()); } catch (AuthenticationException err) { log.debug(err.getMessage()); req.setAttribute(LOGIN_ERROR_FLAG, err.getMessage()); } } public void setUserSettings(GridSphereEvent event, User user) { PortletRequest req = event.getPortletRequest(); PortletSession session = req.getPortletSession(true); req.setAttribute(SportletProperties.PORTLET_USER, user); session.setAttribute(SportletProperties.PORTLET_USER, user.getID()); if (user.getAttribute(User.LOCALE) != null) { session.setAttribute(User.LOCALE, new Locale((String)user.getAttribute(User.LOCALE), "", "")); } if (aclService.hasSuperRole(user)) { log.debug("User: " + user.getUserName() + " logged in as SUPER"); } setUserAndGroups(req); log.debug("Adding User: " + user.getID() + " with session:" + session.getId() + " to usersessionmanager"); userSessionManager.addSession(user, session); layoutEngine.loginPortlets(event); } /** * Handles logout requests * * @param event a <code>GridSphereEvent</code> */ protected void logout(GridSphereEvent event) { log.debug("in logout of GridSphere Servlet"); PortletRequest req = event.getPortletRequest(); removeUserCookie(event); PortletSession session = req.getPortletSession(); session.removeAttribute(SportletProperties.PORTLET_USER); userSessionManager.removeSessions(req.getUser()); layoutEngine.logoutPortlets(event); } /** * Method to set the response headers to perform file downloads to a browser * * @param event the gridsphere event * @throws PortletException */ public void downloadFile(GridSphereEvent event) throws PortletException { PortletResponse res = event.getPortletResponse(); PortletRequest req = event.getPortletRequest(); try { String fileName = (String) req.getAttribute(SportletProperties.FILE_DOWNLOAD_NAME); String path = (String) req.getAttribute(SportletProperties.FILE_DOWNLOAD_PATH); if ((fileName == null) || (path == null)) return; log.debug("in downloadFile"); log.debug("filename: " + fileName + " filepath= " + path); File f = new File(path); FileDataSource fds = new FileDataSource(f); res.setContentType(fds.getContentType()); res.setHeader("Content-Disposition", "attachment; filename=" + fileName); res.setHeader("Content-Length", String.valueOf(f.length())); DataHandler handler = new DataHandler(fds); handler.writeTo(res.getOutputStream()); } catch (FileNotFoundException e) { log.error("Unable to find file!", e); } catch (SecurityException e) { // this gets thrown if a security policy applies to the file. see java.io.File for details. log.error("A security exception occured!", e); } catch (SocketException e) { log.error("Caught SocketException: " + e.getMessage()); } catch (IOException e) { log.error("Caught IOException", e); //response.sendError(HttpServletResponse.SC_INTERNAL_SERVER,e.getMessage()); } } /** * @see #doGet */ public final void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { doGet(req, res); } /** * Return the servlet info. * * @return a string with the servlet information. */ public final String getServletInfo() { return "GridSphere Servlet 2.0.1"; } /** * Shuts down the GridSphere portlet container */ public final void destroy() { log.debug("in destroy: Shutting down services"); userSessionManager.destroy(); layoutEngine.destroy(); // Shutdown services factory.shutdownServices(); // shutdown the persistencemanagers PersistenceManagerFactory.shutdown(); System.gc(); } /** * Record the fact that a servlet context attribute was added. * * @param event The session attribute event */ public void attributeAdded(HttpSessionBindingEvent event) { log.debug("attributeAdded('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that a servlet context attribute was removed. * * @param event The session attribute event */ public void attributeRemoved(HttpSessionBindingEvent event) { log.debug("attributeRemoved('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that a servlet context attribute was replaced. * * @param event The session attribute event */ public void attributeReplaced(HttpSessionBindingEvent event) { log.debug("attributeReplaced('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that this ui application has been destroyed. * * @param event The servlet context event */ public void contextDestroyed(ServletContextEvent event) { ServletContext ctx = event.getServletContext(); log.debug("contextDestroyed()"); log.debug("contextName: " + ctx.getServletContextName()); log.debug("context path: " + ctx.getRealPath("")); } /** * Record the fact that this ui application has been initialized. * * @param event The servlet context event */ public void contextInitialized(ServletContextEvent event) { log.debug("contextInitialized()"); ServletContext ctx = event.getServletContext(); GridSphereConfig.setServletContext(ctx); log.debug("contextName: " + ctx.getServletContextName()); log.debug("context path: " + ctx.getRealPath("")); } /** * Record the fact that a session has been created. * * @param event The session event */ public void sessionCreated(HttpSessionEvent event) { log.debug("sessionCreated('" + event.getSession().getId() + "')"); sessionManager.sessionCreated(event); } /** * Record the fact that a session has been destroyed. * * @param event The session event */ public void sessionDestroyed(HttpSessionEvent event) { sessionManager.sessionDestroyed(event); log.debug("sessionDestroyed('" + event.getSession().getId() + "')"); } /** * Record the fact that a session has been created. * * @param event The session event */ public void sessionDidActivate(HttpSessionEvent event) { log.debug("sessionDidActivate('" + event.getSession().getId() + "')"); sessionManager.sessionCreated(event); } /** * Record the fact that a session has been destroyed. * * @param event The session event */ public void sessionWillPassivate(HttpSessionEvent event) { sessionManager.sessionDestroyed(event); log.debug("sessionWillPassivate('" + event.getSession().getId() + "')"); } }
package com.grandmaapp.notification; import com.example.grandmaapp.R; import com.grandmaapp.activities.GrandmaActivity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; public class Notifications { static private Notifications instance; NotificationManager notificationManager; private int notifyId; //Notification id for updating notification private int numMessages; // Counts messages private Notification.InboxStyle inBoxStyle; static public Notifications getInstance() { if(instance == null) { instance = new Notifications( ); instance.inBoxStyle = new Notification.InboxStyle(); instance.notifyId = 1337; instance.numMessages = 0; } return instance; } private Notifications (){}; public void newNotification(String subject, Context myActivity) { //Creating intent, notification opens activity if touched Intent resultIntent = new Intent (myActivity, GrandmaActivity.class); // Creating an extra for the intent for resetting the counter on app resum resultIntent.putExtra( "Notify", "reset" ); resultIntent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent pResultIntent = PendingIntent.getActivity( myActivity, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT ); // Creating the Notification object Notification.Builder notiB = new Notification.Builder(myActivity) .setContentTitle( "Grandmaapp" ) .setContentText( subject ) .setSmallIcon( R.drawable.ic_launcher ) .setContentIntent(pResultIntent) .setNumber( ++numMessages ); // Sets a title for the Inbox style big view inBoxStyle.setBigContentTitle("Brunhildes Wnsche:"); // Moves events into the big view inBoxStyle.addLine( subject ); inBoxStyle.setBuilder( notiB ); // Moves the big view style object into the notification object. Notification noti = inBoxStyle.build( ); // Hide the notification after its selected noti.flags |= Notification.FLAG_AUTO_CANCEL; // notify the notification manager notificationManager = (NotificationManager) myActivity.getSystemService( Context.NOTIFICATION_SERVICE ); notificationManager.notify(1337, noti); } public int getNotifyId () { return notifyId; } public void resetMessageCounter() { numMessages = 0; inBoxStyle = new Notification.InboxStyle( ); } public int getNumMessages( ) { return numMessages; } }
/** * @author <a href="mailto:[email protected]">Jason Novotny</a> * @version $Id$ */ package org.gridsphere.provider.portletui.beans; /** * An abstract <code>InputBean</code> provides a generic input HTML element */ public abstract class InputBean extends BaseComponentBean implements TagBean { public static final String INPUT_STYLE = "portlet-form-input-field"; protected String inputtype = ""; protected int size = 0; protected int maxlength = 0; protected String onFocus = null; protected String onClick = null; protected String onDblClick = null; protected String onChange = null; protected String onBlur = null; protected String onSelect = null; protected String onmousedown = null; protected String onmousemove = null; protected String onmouseout = null; protected String onmouseover = null; protected String onmouseup = null; /** * Constructs a default input bean */ public InputBean() { super(); this.cssClass = INPUT_STYLE; } /** * Constructs an input bean with a supplied name * * @param name the bean name */ public InputBean(String name) { super(name); this.cssClass = INPUT_STYLE; } /** * Returns the onChange JavaScript function * * @return onChange JavaScript function */ public String getOnChange() { return onChange; } /** * Sets the onChange JavaScript function * * @param onChange the onChange JavaScript function */ public void setOnChange(String onChange) { this.onChange = onChange; } /** * Returns the onBlur JavaScript function * * @return onBlur JavaScript function */ public String getOnBlur() { return onBlur; } /** * Sets the onBlur JavaScript function * * @param onBlur the onBlur JavaScript function */ public void setOnBlur(String onBlur) { this.onBlur = onBlur; } /** * Returns the onSelect JavaScript function * * @return onSelect JavaScript function */ public String getOnSelect() { return onSelect; } /** * Sets the onSelect JavaScript function * * @param onSelect the onSelect JavaScript function */ public void setOnSelect(String onSelect) { this.onSelect = onSelect; } /** * Sets the onFocus JavaScript function * * @param onFocus the onFocus JavaScript function */ public void setOnFocus(String onFocus) { this.onFocus = onFocus; } /** * Returns the onFocus JavaScript function * * @return onFocus JavaScript function */ public String getOnFocus() { return onFocus; } /** * Returns the onClick javascript function * * @return the onClick javascript function */ public String getOnClick() { return onClick; } /** * Sets the onClick JavaScript function * * @param onClick the onFocus JavaScript function */ public void setOnClick(String onClick) { this.onClick = onClick; } /** * Returns the onDblClick javascript function * * @return the onDblClick javascript function */ public String getOnDblClick() { return onDblClick; } /** * Sets the onDblClick JavaScript function * * @param onDblClick the onDblClick JavaScript function */ public void setOnDblClick(String onDblClick) { this.onDblClick = onDblClick; } /** * Returns the onmousedown event * * @return the onmousedown function */ public String getOnMouseDown() { return onmousedown; } /** * Sets the onmousedown event * * @param onmousedown the onmousedown function */ public void setOnMouseDown(String onmousedown) { this.onmousedown = onmousedown; } /** * Returns the onmousemove function * * @return the onmousemove function */ public String getOnMouseMove() { return onmousemove; } /** * Sets the onmousemove function * * @param onmousemove the onmousemove function */ public void setOnMouseMove(String onmousemove) { this.onmousemove = onmousemove; } /** * Returns the onmouseout function * * @return the onmouseout function */ public String getOnMouseOut() { return onmouseout; } /** * Sets the onmouseout function * * @param onmouseout the onmouseout function */ public void setOnMouseOut(String onmouseout) { this.onmouseout = onmouseout; } /** * Returns the onmouseover function * * @return the onmouseover function */ public String getOnMouseOver() { return onmouseover; } /** * Sets the onmouseover javascript function * * @param onmouseover the onmouseover function */ public void setOnMouseOver(String onmouseover) { this.onmouseover = onmouseover; } /** * Returns the onMouseUp javascript function * * @return the onmouseup event */ public String getOnMouseUp() { return onmouseup; } /** * Sets the onMouseUp javascript function * * @param onmouseup a mouseup event */ public void setOnMouseUp(String onmouseup) { this.onmouseup = onmouseup; } /** * Returns the size of this input element * * @return the size of this input element */ public int getSize() { return size; } /** * Sets the size of this input element * * @param size the size of this input element */ public void setSize(int size) { this.size = size; } /** * Returns the maximum length of this input element * * @return the maximum length of this input element */ public int getMaxLength() { return maxlength; } /** * Sets the maximum length of this input element * * @param maxlength the maximum length of this input element */ public void setMaxLength(int maxlength) { this.maxlength = maxlength; } public String getEncodedName() { return createTagName(name); } /** * Returns the bean value * * @return the bean value */ public String getValue() { return value; // returning typed in value instead of changed value because // there is no possibility to distinguish the correct value. // If a user user HTML entity and characters (e.g. for commands) // the portlet can't know the correct value (e.g. the command // >>>echo "Test data &gt; sdlj" > test.html<<< will be transformed // to >>>echo "Test data &gt; sdlj" &gt; test.html<<< and an HTML unescape creates // a wrong result: >>>echo "Test data > sdlj" > test.html"! // return parseUserInput(value); } /** * An attempt to parse user supplied input for any HTML arrow tags and convert them * * @param userInput some user supplied input * @return the parsed user input text */ private static String parseUserInput(String userInput) { if (userInput == null) return null; userInput = userInput.replaceAll("<", "&lt;"); userInput = userInput.replaceAll(">", "&gt;"); return userInput; } public String toStartString() { StringBuffer sb = new StringBuffer(); sb.append("<input "); if (id != null) sb.append("id=\"").append(id).append("\" "); sb.append(getFormattedCss()); sb.append(" type=\""); sb.append(inputtype); sb.append("\" "); String sname = createTagName(name); sb.append("name=\""); sb.append(sname); sb.append("\" "); if (value != null) sb.append("value=\"").append(value).append("\" "); if (size != 0) sb.append("size=\"").append(size).append("\" "); if (maxlength != 0) sb.append("maxlength=\"").append(maxlength).append("\" "); if (onFocus != null) sb.append("onfocus=\"").append(onFocus).append("\" "); if (onClick != null) sb.append("onclick=\"").append(onClick).append("\" "); if (onDblClick != null) sb.append("ondblclick=\"").append(onDblClick).append("\" "); if (onChange != null) sb.append("onchange=\"").append(onChange).append("\" "); if (onBlur != null) sb.append("onblur=\"").append(onBlur).append("\" "); if (onSelect != null) sb.append("onselect=\"").append(onSelect).append("\" "); if (onmouseout != null) sb.append("onmouseout=\"").append(onmouseout).append("\" "); if (onmousedown != null) sb.append("onmousedown=\"").append(onmousedown).append("\" "); if (onmouseup != null) sb.append("onmouseup=\"").append(onmouseup).append("\" "); if (onmousemove != null) sb.append("onmousemove=\"").append(onmousemove).append("\" "); if (onmouseover != null) sb.append("onmouseover=\"").append(onmouseover).append("\" "); sb.append(checkReadOnly()); sb.append(checkDisabled()); sb.append("/>"); return sb.toString(); } public String toEndString() { return ""; } }
package org.jitsi.impl.neomedia.device; import java.awt.*; import java.io.*; import java.util.*; import java.util.List; import java.util.concurrent.locks.*; import javax.media.*; import javax.media.control.*; import javax.media.format.*; import javax.media.protocol.*; import javax.media.rtp.*; import org.jitsi.impl.neomedia.*; import org.jitsi.impl.neomedia.control.*; import org.jitsi.impl.neomedia.format.*; import org.jitsi.impl.neomedia.protocol.*; import org.jitsi.service.neomedia.*; import org.jitsi.service.neomedia.codec.*; import org.jitsi.service.neomedia.control.*; import org.jitsi.service.neomedia.device.*; import org.jitsi.service.neomedia.format.*; import org.jitsi.util.*; import org.jitsi.util.event.*; /** * Represents the use of a specific <tt>MediaDevice</tt> by a * <tt>MediaStream</tt>. * * @author Lyubomir Marinov * @author Damian Minkov * @author Emil Ivov * @author Boris Grozev */ public class MediaDeviceSession extends PropertyChangeNotifier { /** * The <tt>Logger</tt> used by the <tt>MediaDeviceSession</tt> class and its * instances for logging output. */ private static final Logger logger = Logger.getLogger(MediaDeviceSession.class); /** * The name of the <tt>MediaDeviceSession</tt> instance property the value * of which represents the output <tt>DataSource</tt> of the * <tt>MediaDeviceSession</tt> instance which provides the captured (RTP) * data to be sent by <tt>MediaStream</tt> to <tt>MediaStreamTarget</tt>. */ public static final String OUTPUT_DATA_SOURCE = "OUTPUT_DATA_SOURCE"; /** * The name of the property that corresponds to the array of SSRC * identifiers that we store in this <tt>MediaDeviceSession</tt> instance * and that we update upon adding and removing <tt>ReceiveStream</tt> */ public static final String SSRC_LIST = "SSRC_LIST"; /** * The JMF <tt>DataSource</tt> of {@link #device} through which this * instance accesses the media captured by it. */ private DataSource captureDevice; /** * The indicator which determines whether {@link DataSource#connect()} has * been successfully executed on {@link #captureDevice}. */ private boolean captureDeviceIsConnected; /** * The <tt>ContentDescriptor</tt> which specifies the content type in which * this <tt>MediaDeviceSession</tt> is to output the media captured by its * <tt>MediaDevice</tt>. */ private ContentDescriptor contentDescriptor; /** * The <tt>MediaDevice</tt> used by this instance to capture and play back * media. */ private final AbstractMediaDevice device; /** * The last JMF <tt>Format</tt> set to this instance by a call to its * {@link #setFormat(MediaFormat)} and to be set as the output format of * {@link #processor}. */ private MediaFormatImpl<? extends Format> format; /** * The indicator which determines whether this <tt>MediaDeviceSession</tt> * is set to output "silence" instead of the actual media captured from * {@link #captureDevice}. */ private boolean mute = false; /** * The list of playbacks of <tt>ReceiveStream</tt>s and/or * <tt>DataSource</tt>s performed by respective <tt>Player</tt>s on the * <tt>MediaDevice</tt> represented by this instance. The (read and write) * accesses to the field are to be synchronized using * {@link #playbacksLock}. */ private final List<Playback> playbacks = new LinkedList<Playback>(); /** * The <tt>ReadWriteLock</tt> which is used to synchronize the (read and * write) accesses to {@link #playbacks}. */ private final ReadWriteLock playbacksLock = new ReentrantReadWriteLock(); /** * The <tt>ControllerListener</tt> which listens to the <tt>Player</tt>s of * {@link #playbacks} for <tt>ControllerEvent</tt>s. */ private final ControllerListener playerControllerListener = new ControllerListener() { /** * Notifies this <tt>ControllerListener</tt> that the * <tt>Controller</tt> which it is registered with has * generated an event. * * @param ev the <tt>ControllerEvent</tt> specifying the * <tt>Controller</tt> which is the source of the event and * the very type of the event * @see ControllerListener#controllerUpdate(ControllerEvent) */ public void controllerUpdate(ControllerEvent ev) { playerControllerUpdate(ev); } }; /** * The JMF <tt>Processor</tt> which transcodes {@link #captureDevice} into * the format of this instance. */ private Processor processor; /** * The <tt>ControllerListener</tt> which listens to {@link #processor} for * <tt>ControllerEvent</tt>s. */ private ControllerListener processorControllerListener; /** * The indicator which determines whether {@link #processor} has received * a <tt>ControllerClosedEvent</tt> at an unexpected time in its execution. * A value of <tt>false</tt> does not mean that <tt>processor</tt> exists * or that it is not closed, it just means that if <tt>processor</tt> failed * to be initialized or it received a <tt>ControllerClosedEvent</tt>, it was * at an expected time of its execution and that the fact in question was * reflected, for example, by setting <tt>processor</tt> to <tt>null</tt>. * If there is no <tt>processorIsPrematurelyClosed</tt> field and * <tt>processor</tt> is set to <tt>null</tt> or left existing after the * receipt of <tt>ControllerClosedEvent</tt>, it will either lead to not * firing a <tt>PropertyChangeEvent</tt> for <tt>OUTPUT_DATA_SOURCE</tt> * when it has actually changed and, consequently, cause the * <tt>SendStream</tt>s of <tt>MediaStreamImpl</tt> to not be recreated or * it will be impossible to detect that <tt>processor</tt> cannot have its * format set and will thus be left broken even for subsequent calls to * {@link #setFormat(MediaFormat)}. */ private boolean processorIsPrematurelyClosed; /** * The list of SSRC identifiers representing the parties that we are * currently handling receive streams from. */ private long[] ssrcList = null; /** * The <tt>MediaDirection</tt> in which this <tt>MediaDeviceSession</tt> has * been started. */ private MediaDirection startedDirection = MediaDirection.INACTIVE; /** * If the player have to be disposed when we {@link #close()} this instance. */ private boolean disposePlayerOnClose = true; /** * Whether output size has changed after latest processor config. * Used for video streams. */ protected boolean outputSizeChanged = false; /** * Initializes a new <tt>MediaDeviceSession</tt> instance which is to * represent the use of a specific <tt>MediaDevice</tt> by a * <tt>MediaStream</tt>. * * @param device the <tt>MediaDevice</tt> the use of which by a * <tt>MediaStream</tt> is to be represented by the new instance */ protected MediaDeviceSession(AbstractMediaDevice device) { checkDevice(device); this.device = device; } /** * Sets the indicator which determines whether this instance is to dispose * of its associated player upon closing. * * @param disposePlayerOnClose <tt>true</tt> to have this instance dispose * of its associated player upon closing; otherwise, <tt>false</tt> */ public void setDisposePlayerOnClose(boolean disposePlayerOnClose) { this.disposePlayerOnClose = disposePlayerOnClose; } /** * Adds <tt>ssrc</tt> to the array of SSRC identifiers representing parties * that this <tt>MediaDeviceSession</tt> is currently receiving streams * from. We use this method mostly as a way of to caching SSRC identifiers * during a conference call so that the streams that are sending CSRC lists * could have them ready for use rather than have to construct them for * every RTP packet. * * @param ssrc the new SSRC identifier that we'd like to add to the array of * <tt>ssrc</tt> identifiers stored by this session. */ protected void addSSRC(long ssrc) { //init if necessary if (ssrcList == null) { setSsrcList(new long[] { ssrc }); return; } //check whether we already have this ssrc for (int i = 0; i < ssrcList.length; i++) { if (ssrc == ssrcList[i]) return; } //resize the array and add the new ssrc to the end. long[] newSsrcList = new long[ssrcList.length + 1]; System.arraycopy(ssrcList, 0, newSsrcList, 0, ssrcList.length); newSsrcList[newSsrcList.length - 1] = ssrc; setSsrcList(newSsrcList); } /** * For JPEG and H263, we know that they only work for particular sizes. So * we'll perform extra checking here to make sure they are of the right * sizes. * * @param sourceFormat the original format to check the size of * @return the modified <tt>VideoFormat</tt> set to the size we support */ private static VideoFormat assertSize(VideoFormat sourceFormat) { int width, height; // JPEG if (sourceFormat.matches(new Format(VideoFormat.JPEG_RTP))) { Dimension size = sourceFormat.getSize(); // For JPEG, make sure width and height are divisible by 8. width = (size.width % 8 == 0) ? size.width : ((size.width / 8) * 8); height = (size.height % 8 == 0) ? size.height : ((size.height / 8) * 8); } // H.263 else if (sourceFormat.matches(new Format(VideoFormat.H263_RTP))) { // For H.263, we only support some specific sizes. // if (size.width < 128) // width = 128; // height = 96; // else if (size.width < 176) // width = 176; // height = 144; // else width = 352; height = 288; } else { // We don't know this particular format. We'll just leave it alone // then. return sourceFormat; } VideoFormat result = new VideoFormat( null, new Dimension(width, height), Format.NOT_SPECIFIED, null, Format.NOT_SPECIFIED); return (VideoFormat) result.intersects(sourceFormat); } /** * Asserts that a specific <tt>MediaDevice</tt> is acceptable to be set as * the <tt>MediaDevice</tt> of this instance. Allows extenders to override * and customize the check. * * @param device the <tt>MediaDevice</tt> to be checked for suitability to * become the <tt>MediaDevice</tt> of this instance */ protected void checkDevice(AbstractMediaDevice device) { } /** * Releases the resources allocated by this instance in the course of its * execution and prepares it to be garbage collected. */ public void close() { try { stop(MediaDirection.SENDRECV); } finally { /* * XXX The order of stopping the playback and capture is important * here because when we use echo cancellation the capture accesses * data from the playback and thus there is synchronization to avoid * segfaults but this synchronization can sometimes lead to a slow * stop of the playback. That is why we stop the capture first. */ // capture disconnectCaptureDevice(); closeProcessor(); // playback if (disposePlayerOnClose) disposePlayer(); processor = null; captureDevice = null; } } /** * Makes sure {@link #processor} is closed. */ private void closeProcessor() { if (processor != null) { if (processorControllerListener != null) processor.removeControllerListener(processorControllerListener); processor.stop(); if (logger.isTraceEnabled()) logger .trace( "Stopped Processor with hashCode " + processor.hashCode()); if (processor.getState() == Processor.Realized) { DataSource dataOutput; try { dataOutput = processor.getDataOutput(); } catch (NotRealizedError nre) { dataOutput = null; } if (dataOutput != null) dataOutput.disconnect(); } processor.deallocate(); processor.close(); processorIsPrematurelyClosed = false; /* * Once the processor uses the captureDevice, the captureDevice has * to be reconnected on its next use. */ disconnectCaptureDevice(); } } /** * Creates the <tt>DataSource</tt> that this instance is to read captured * media from. * * @return the <tt>DataSource</tt> that this instance is to read captured * media from */ protected DataSource createCaptureDevice() { DataSource captureDevice = getDevice().createOutputDataSource(); if (captureDevice != null) { MuteDataSource muteDataSource = AbstractControls.queryInterface( captureDevice, MuteDataSource.class); if (muteDataSource == null) { // Try to enable muting. if (captureDevice instanceof PushBufferDataSource) { captureDevice = new RewritablePushBufferDataSource( (PushBufferDataSource) captureDevice); } else if (captureDevice instanceof PullBufferDataSource) { captureDevice = new RewritablePullBufferDataSource( (PullBufferDataSource) captureDevice); } muteDataSource = AbstractControls.queryInterface( captureDevice, MuteDataSource.class); } if (muteDataSource != null) muteDataSource.setMute(mute); } return captureDevice; } /** * Creates a new <tt>Player</tt> for a specific <tt>DataSource</tt> so that * it is played back on the <tt>MediaDevice</tt> represented by this * instance. * * @param dataSource the <tt>DataSource</tt> to create a new <tt>Player</tt> * for * @return a new <tt>Player</tt> for the specified <tt>dataSource</tt> */ protected Player createPlayer(DataSource dataSource) { Processor player = null; Throwable exception = null; try { player = getDevice().createPlayer(dataSource); } catch (Exception ex) { exception = ex; } if (exception != null) { logger.error( "Failed to create Player for " + MediaStreamImpl.toString(dataSource), exception); } else if (player != null) { /* * We cannot wait for the Player to get configured (e.g. with * waitForState) because it will stay in the Configuring state until * it reads some media. In the case of a ReceiveStream not sending * media (e.g. abnormally stopped), it will leave us blocked. */ player.addControllerListener(playerControllerListener); player.configure(); if (logger.isTraceEnabled()) { logger.trace( "Created Player with hashCode " + player.hashCode() + " for " + MediaStreamImpl.toString(dataSource)); } } return player; } /** * Initializes a new FMJ <tt>Processor</tt> which is to transcode * {@link #captureDevice} into the format of this instance. * * @return a new FMJ <tt>Processor</tt> which is to transcode * <tt>captureDevice</tt> into the format of this instance */ protected Processor createProcessor() { DataSource captureDevice = getConnectedCaptureDevice(); if (captureDevice != null) { Processor processor = null; Throwable exception = null; try { processor = Manager.createProcessor(captureDevice); } catch (IOException ioe) { // TODO exception = ioe; } catch (NoProcessorException npe) { // TODO exception = npe; } if (exception != null) logger .error( "Failed to create Processor for " + captureDevice, exception); else { if (processorControllerListener == null) processorControllerListener = new ControllerListener() { /** * Notifies this <tt>ControllerListener</tt> that * the <tt>Controller</tt> which it is registered * with has generated an event. * * @param event the <tt>ControllerEvent</tt> * specifying the <tt>Controller</tt> which is the * source of the event and the very type of the * event * @see ControllerListener#controllerUpdate( * ControllerEvent) */ public void controllerUpdate(ControllerEvent event) { processorControllerUpdate(event); } }; processor .addControllerListener(processorControllerListener); if (waitForState(processor, Processor.Configured)) { this.processor = processor; processorIsPrematurelyClosed = false; } else { if (processorControllerListener != null) processor .removeControllerListener( processorControllerListener); processor = null; } } } return this.processor; } /** * Creates a <tt>ContentDescriptor</tt> to be set on a specific * <tt>Processor</tt> of captured media to be sent to the remote peer. * Allows extenders to override. The default implementation returns * {@link ContentDescriptor#RAW_RTP}. * * @param processor the <tt>Processor</tt> of captured media to be sent to * the remote peer which is to have its <tt>contentDescriptor</tt> set to * the returned <tt>ContentDescriptor</tt> * @return a <tt>ContentDescriptor</tt> to be set on the specified * <tt>processor</tt> of captured media to be sent to the remote peer */ protected ContentDescriptor createProcessorContentDescriptor( Processor processor) { return (contentDescriptor == null) ? new ContentDescriptor(ContentDescriptor.RAW_RTP) : contentDescriptor; } /** * Initializes a <tt>Renderer</tt> instance which is to be utilized by a * specific <tt>Player</tt> in order to play back the media represented by * a specific <tt>TrackControl</tt>. Allows extenders to override and, * optionally, perform additional configuration of the returned * <tt>Renderer</tt>. * * @param player the <tt>Player</tt> which is to utilize the * initialized/returned <tt>Renderer</tt> * @param trackControl the <tt>TrackControl</tt> which represents the media * to be played back (and, technically, on which the initialized/returned * <tt>Renderer</tt> is to be set) * @return the <tt>Renderer</tt> which is to be set on the specified * <tt>trackControl</tt>. If <tt>null</tt>, * {@link TrackControl#setRenderer(Renderer)} is not invoked on the * specified <tt>trackControl</tt>. */ protected Renderer createRenderer(Player player, TrackControl trackControl) { return getDevice().createRenderer(); } /** * Makes sure {@link #captureDevice} is disconnected. */ private void disconnectCaptureDevice() { if (captureDevice != null) { /* * As reported by Carlos Alexandre, stopping before disconnecting * resolves a slow disconnect on Linux. */ try { captureDevice.stop(); } catch (IOException ioe) { /* * We cannot do much about the exception because we're not * really interested in the stopping but rather in calling * DataSource#disconnect() anyway. */ logger .error( "Failed to properly stop captureDevice " + captureDevice, ioe); } captureDevice.disconnect(); captureDeviceIsConnected = false; } } /** * Releases the resources allocated by the <tt>Player</tt>s of * {@link #playbacks} in the course of their execution and prepares them to * be garbage collected. */ private void disposePlayer() { Lock writeLock = playbacksLock.writeLock(); writeLock.lock(); try { for (Playback playback : playbacks) { if (playback.player != null) { disposePlayer(playback.player); playback.player = null; } } } finally { writeLock.unlock(); } } /** * Releases the resources allocated by a specific <tt>Player</tt> in the * course of its execution and prepares it to be garbage collected. * * @param player the <tt>Player</tt> to dispose of */ protected void disposePlayer(Player player) { if (playerControllerListener != null) player.removeControllerListener(playerControllerListener); player.stop(); player.deallocate(); player.close(); } /** * Finds the first <tt>Format</tt> instance in a specific list of * <tt>Format</tt>s which matches a specific <tt>Format</tt>. The * implementation considers a pair of <tt>Format</tt>s matching if they have * the same encoding. * * @param formats the array of <tt>Format</tt>s to be searched for a match * to the specified <tt>format</tt> * @param format the <tt>Format</tt> to search for a match in the specified * <tt>formats</tt> * @return the first element of <tt>formats</tt> which matches * <tt>format</tt> i.e. is of the same encoding */ private static Format findFirstMatchingFormat( Format[] formats, Format format) { double formatSampleRate = (format instanceof AudioFormat) ? ((AudioFormat) format).getSampleRate() : Format.NOT_SPECIFIED; ParameterizedVideoFormat parameterizedVideoFormat = (format instanceof ParameterizedVideoFormat) ? (ParameterizedVideoFormat) format : null; for (Format match : formats) { if (match.isSameEncoding(format)) { /* * The encoding alone is, of course, not enough. For example, * AudioFormats may have different sample rates (i.e. clock * rates as we call them in MediaFormat). */ if (match instanceof AudioFormat) { if (formatSampleRate != Format.NOT_SPECIFIED) { double matchSampleRate = ((AudioFormat) match).getSampleRate(); if ((matchSampleRate != Format.NOT_SPECIFIED) && (matchSampleRate != formatSampleRate)) continue; } } else if (match instanceof ParameterizedVideoFormat) { if (!((ParameterizedVideoFormat) match) .formatParametersMatch(format)) continue; } else if (parameterizedVideoFormat != null) { if (!parameterizedVideoFormat.formatParametersMatch(match)) continue; } return match; } } return null; } /** * Gets the <tt>DataSource</tt> that this instance uses to read captured * media from. If it does not exist yet, it is created. * * @return the <tt>DataSource</tt> that this instance uses to read captured * media from */ public synchronized DataSource getCaptureDevice() { if (captureDevice == null) captureDevice = createCaptureDevice(); return captureDevice; } /** * Gets {@link #captureDevice} in a connected state. If this instance is not * connected to <tt>captureDevice</tt> yet, first tries to connect to it. * Returns <tt>null</tt> if this instance fails to create * <tt>captureDevice</tt> or to connect to it. * * @return {@link #captureDevice} in a connected state; <tt>null</tt> if * this instance fails to create <tt>captureDevice</tt> or to connect to it */ protected DataSource getConnectedCaptureDevice() { DataSource captureDevice = getCaptureDevice(); if ((captureDevice != null) && !captureDeviceIsConnected) { /* * Give this instance a chance to set up an optimized media codec * chain by setting the output Format on the input CaptureDevice. */ try { if (this.format != null) setCaptureDeviceFormat(captureDevice, this.format); } catch (Throwable t) { logger.warn( "Failed to setup an optimized media codec chain" + " by setting the output Format" + " on the input CaptureDevice", t); } Throwable exception = null; try { getDevice().connect(captureDevice); } catch (IOException ioex) { exception = ioex; } if (exception == null) captureDeviceIsConnected = true; else { logger.error( "Failed to connect to " + MediaStreamImpl.toString(captureDevice), exception); captureDevice = null; } } return captureDevice; } /** * Gets the <tt>MediaDevice</tt> associated with this instance and the work * of a <tt>MediaStream</tt> with which is represented by it. * * @return the <tt>MediaDevice</tt> associated with this instance and the * work of a <tt>MediaStream</tt> with which is represented by it */ public AbstractMediaDevice getDevice() { return device; } /** * Gets the JMF <tt>Format</tt> in which this instance captures media. * * @return the JMF <tt>Format</tt> in which this instance captures media. */ public Format getProcessorFormat() { Processor processor = getProcessor(); if ((processor != null) && (this.processor == processor) && !processorIsPrematurelyClosed) { MediaType mediaType = getMediaType(); for (TrackControl trackControl : processor.getTrackControls()) { if (!trackControl.isEnabled()) continue; Format jmfFormat = trackControl.getFormat(); MediaType type = (jmfFormat instanceof VideoFormat) ? MediaType.VIDEO : MediaType.AUDIO; if (mediaType.equals(type)) return jmfFormat; } } return null; } /** * Gets the <tt>MediaFormat</tt> in which this instance captures media from * its associated <tt>MediaDevice</tt>. * * @return the <tt>MediaFormat</tt> in which this instance captures media * from its associated <tt>MediaDevice</tt> */ public MediaFormatImpl<? extends Format> getFormat() { /* * If the Format of the processor is different than the format of this * MediaDeviceSession, we'll likely run into unexpected issues so debug * whether there are such cases. */ if (logger.isDebugEnabled() && (processor != null)) { Format processorFormat = getProcessorFormat(); Format format = (this.format == null) ? null : this.format.getFormat(); boolean processorFormatMatchesFormat = (processorFormat == null) ? (format == null) : processorFormat.matches(format); if (!processorFormatMatchesFormat) { logger.debug( "processorFormat != format; processorFormat= `" + processorFormat + "`; format= `" + format + "`"); } } return format; } /** * Gets the <tt>MediaType</tt> of the media captured and played back by this * instance. It is the same as the <tt>MediaType</tt> of its associated * <tt>MediaDevice</tt>. * * @return the <tt>MediaType</tt> of the media captured and played back by * this instance as reported by {@link MediaDevice#getMediaType()} of its * associated <tt>MediaDevice</tt> */ private MediaType getMediaType() { return getDevice().getMediaType(); } /** * Gets the output <tt>DataSource</tt> of this instance which provides the * captured (RTP) data to be sent by <tt>MediaStream</tt> to * <tt>MediaStreamTarget</tt>. * * @return the output <tt>DataSource</tt> of this instance which provides * the captured (RTP) data to be sent by <tt>MediaStream</tt> to * <tt>MediaStreamTarget</tt> */ public DataSource getOutputDataSource() { Processor processor = getProcessor(); DataSource outputDataSource; if ((processor == null) || ((processor.getState() < Processor.Realized) && !waitForState(processor, Processor.Realized))) outputDataSource = null; else { outputDataSource = processor.getDataOutput(); if (logger.isTraceEnabled() && (outputDataSource != null)) { logger.trace( "Processor with hashCode " + processor.hashCode() + " provided " + MediaStreamImpl.toString(outputDataSource)); } /* * Whoever wants the outputDataSource, they expect it to be started * in accord with the previously-set direction. */ startProcessorInAccordWithDirection(processor); } return outputDataSource; } /** * Gets the information related to the playback of a specific * <tt>DataSource</tt> on the <tt>MediaDevice</tt> represented by this * <tt>MediaDeviceSession</tt>. * * @param dataSource the <tt>DataSource</tt> to get the information related * to the playback of * @return the information related to the playback of the specified * <tt>DataSource</tt> on the <tt>MediaDevice</tt> represented by this * <tt>MediaDeviceSession</tt> */ private Playback getPlayback(DataSource dataSource) { Lock readLock = playbacksLock.readLock(); readLock.lock(); try { for (Playback playback : playbacks) { if (playback.dataSource == dataSource) return playback; } } finally { readLock.unlock(); } return null; } /** * Gets the information related to the playback of a specific * <tt>ReceiveStream</tt> on the <tt>MediaDevice</tt> represented by this * <tt>MediaDeviceSession</tt>. * * @param receiveStream the <tt>ReceiveStream</tt> to get the information * related to the playback of * @return the information related to the playback of the specified * <tt>ReceiveStream</tt> on the <tt>MediaDevice</tt> represented by this * <tt>MediaDeviceSession</tt> */ private Playback getPlayback(ReceiveStream receiveStream) { Lock readLock = playbacksLock.readLock(); readLock.lock(); try { for (Playback playback : playbacks) { if (playback.receiveStream == receiveStream) return playback; } } finally { readLock.unlock(); } return null; } /** * Gets the <tt>Player</tt> rendering the <tt>ReceiveStream</tt> with a * specific SSRC. * * @param ssrc the SSRC of the <tt>ReceiveStream</tt> to get the rendering * the <tt>Player</tt> of * @return the <tt>Player</tt> rendering the <tt>ReceiveStream</tt> with the * specified <tt>ssrc</tt> */ protected Player getPlayer(long ssrc) { Lock readLock = playbacksLock.readLock(); readLock.lock(); try { for (Playback playback : playbacks) { long playbackSSRC = 0xFFFFFFFFL & playback.receiveStream.getSSRC(); if (playbackSSRC == ssrc) return playback.player; } } finally { readLock.unlock(); } return null; } /** * Gets the <tt>Player</tt>s rendering the <tt>ReceiveStream</tt>s of this * instance on its associated <tt>MediaDevice</tt>. * * @return the <tt>Player</tt>s rendering the <tt>ReceiveStream</tt>s of * this instance on its associated <tt>MediaDevice</tt> */ protected List<Player> getPlayers() { Lock readLock = playbacksLock.readLock(); List<Player> players; readLock.lock(); try { players = new ArrayList<Player>(playbacks.size()); for (Playback playback : playbacks) { if (playback.player != null) players.add(playback.player); } } finally { readLock.unlock(); } return players; } /** * Gets the JMF <tt>Processor</tt> which transcodes the <tt>MediaDevice</tt> * of this instance into the format of this instance. If the * <tt>Processor</tt> in question does not exist, the method will create it. * <p> * <b>Warning</b>: Because the method will unconditionally create the * <tt>Processor</tt> if it does not exist and because the creation of the * <tt>Processor</tt> will connect to the <tt>CaptureDevice</tt> of this * instance, extreme care is to be taken when invoking the method in order * to ensure that the existence of the <tt>Processor</tt> is really in * accord with the rest of the state of this instance. Overall, the method * is to be considered private and is to not be invoked outside the * <tt>MediaDeviceSession</tt> class. * </p> * * @return the JMF <tt>Processor</tt> which transcodes the * <tt>MediaDevice</tt> of this instance into the format of this instance */ private Processor getProcessor() { if (processor == null) processor = createProcessor(); return processor; } /** * Gets a list of the <tt>ReceiveStream</tt>s being played back on the * <tt>MediaDevice</tt> represented by this instance. * * @return a list of <tt>ReceiveStream</tt>s being played back on the * <tt>MediaDevice</tt> represented by this instance */ public List<ReceiveStream> getReceiveStreams() { Lock readLock = playbacksLock.readLock(); List<ReceiveStream> receiveStreams; readLock.lock(); try { receiveStreams = new ArrayList<ReceiveStream>(playbacks.size()); for (Playback playback : playbacks) { if (playback.receiveStream != null) receiveStreams.add(playback.receiveStream); } } finally { readLock.unlock(); } return receiveStreams; } /** * Returns the list of SSRC identifiers that this device session is handling * streams from. In this case (i.e. the case of a device session handling * a single remote party) we would rarely (if ever) have more than a single * SSRC identifier returned. However, we would also be using the same method * to query a device session operating over a mixer in which case we would * have the SSRC IDs of all parties currently contributing to the mixing. * * @return a <tt>long[]</tt> array of SSRC identifiers that this device * session is handling streams from. */ public long[] getRemoteSSRCList() { return ssrcList; } /** * Gets the <tt>MediaDirection</tt> in which this instance has been started. * For example, a <tt>MediaDirection</tt> which returns <tt>true</tt> for * <tt>allowsSending()</tt> signals that this instance is capturing media * from its <tt>MediaDevice</tt>. * * @return the <tt>MediaDirection</tt> in which this instance has been * started */ public MediaDirection getStartedDirection() { return startedDirection; } /** * Gets a list of the <tt>MediaFormat</tt>s in which this instance is * capable of capturing media from its associated <tt>MediaDevice</tt>. * * @return a new list of <tt>MediaFormat</tt>s in which this instance is * capable of capturing media from its associated <tt>MediaDevice</tt> */ public List<MediaFormat> getSupportedFormats() { Processor processor = getProcessor(); Set<Format> supportedFormats = new HashSet<Format>(); if ((processor != null) && (this.processor == processor) && !processorIsPrematurelyClosed) { MediaType mediaType = getMediaType(); for (TrackControl trackControl : processor.getTrackControls()) { if (!trackControl.isEnabled()) continue; for (Format supportedFormat : trackControl.getSupportedFormats()) { switch (mediaType) { case AUDIO: if (supportedFormat instanceof AudioFormat) supportedFormats.add(supportedFormat); break; case VIDEO: if (supportedFormat instanceof VideoFormat) supportedFormats.add(supportedFormat); break; default: // FMJ and LibJitsi handle audio and video only and it // seems unlikely that support for any other types of // media will be added here. break; } } } } List<MediaFormat> supportedMediaFormats = new ArrayList<MediaFormat>(supportedFormats.size()); for (Format format : supportedFormats) supportedMediaFormats.add(MediaFormatImpl.createInstance(format)); return supportedMediaFormats; } /** * Determines whether this <tt>MediaDeviceSession</tt> is set to output * "silence" instead of the actual media fed from its * <tt>CaptureDevice</tt>. * * @return <tt>true</tt> if this <tt>MediaDeviceSession</tt> is set to * output "silence" instead of the actual media fed from its * <tt>CaptureDevice</tt>; otherwise, <tt>false</tt> */ public boolean isMute() { DataSource captureDevice = this.captureDevice; if (captureDevice == null) return mute; MuteDataSource muteDataSource = AbstractControls.queryInterface( captureDevice, MuteDataSource.class); return (muteDataSource == null) ? false : muteDataSource.isMute(); } /** * Notifies this <tt>MediaDeviceSession</tt> that a <tt>DataSource</tt> has * been added for playback on the represented <tt>MediaDevice</tt>. * * @param playbackDataSource the <tt>DataSource</tt> which has been added * for playback on the represented <tt>MediaDevice</tt> */ protected void playbackDataSourceAdded(DataSource playbackDataSource) { } /** * Notifies this <tt>MediaDeviceSession</tt> that a <tt>DataSource</tt> has * been removed from playback on the represented <tt>MediaDevice</tt>. * * @param playbackDataSource the <tt>DataSource</tt> which has been removed * from playback on the represented <tt>MediaDevice</tt> */ protected void playbackDataSourceRemoved(DataSource playbackDataSource) { } /** * Notifies this <tt>MediaDeviceSession</tt> that a <tt>DataSource</tt> has * been changed on the represented <tt>MediaDevice</tt>. * * @param playbackDataSource the <tt>DataSource</tt> which has been added * for playback on the represented <tt>MediaDevice</tt> */ protected void playbackDataSourceUpdated(DataSource playbackDataSource) { } /** * Notifies this <tt>MediaDeviceSession</tt> that a <tt>DataSource</tt> has * been changed on the represented <tt>MediaDevice</tt>. * * @param playbackDataSource the <tt>DataSource</tt> which has been added * for playback on the represented <tt>MediaDevice</tt> */ public void playbackDataSourceChanged(DataSource playbackDataSource) { playbackDataSourceUpdated(playbackDataSource); } /** * Notifies this instance that a specific <tt>Player</tt> of remote content * has generated a <tt>ConfigureCompleteEvent</tt>. Allows extenders to * carry out additional processing on the <tt>Player</tt>. * * @param player the <tt>Player</tt> which is the source of a * <tt>ConfigureCompleteEvent</tt> */ protected void playerConfigureComplete(Processor player) { TrackControl[] tcs = player.getTrackControls(); if ((tcs != null) && (tcs.length != 0)) { for (int i = 0; i < tcs.length; i++) { TrackControl tc = tcs[i]; Renderer renderer = createRenderer(player, tc); if (renderer != null) { try { tc.setRenderer(renderer); } catch (UnsupportedPlugInException upie) { logger.warn( "Failed to set " + renderer.getClass().getName() + " renderer on track " + i, upie); } } } } } /** * Gets notified about <tt>ControllerEvent</tt>s generated by a specific * <tt>Player</tt> of remote content. * <p> * Extenders who choose to override are advised to override more specialized * methods such as {@link #playerConfigureComplete(Processor)} and * {@link #playerRealizeComplete(Processor)}. In any case, extenders * overriding this method should call the super implementation. * </p> * * @param ev the <tt>ControllerEvent</tt> specifying the * <tt>Controller</tt> which is the source of the event and the very type of * the event */ protected void playerControllerUpdate(ControllerEvent ev) { if (ev instanceof ConfigureCompleteEvent) { Processor player = (Processor) ev.getSourceController(); if (player != null) { playerConfigureComplete(player); /* * To use the processor as a Player we must set its * ContentDescriptor to null. */ try { player.setContentDescriptor(null); } catch (NotConfiguredError nce) { logger.error( "Failed to set ContentDescriptor to Player.", nce); return; } player.realize(); } } else if (ev instanceof RealizeCompleteEvent) { Processor player = (Processor) ev.getSourceController(); if (player != null) { playerRealizeComplete(player); player.start(); } } } /** * Notifies this instance that a specific <tt>Player</tt> of remote content * has generated a <tt>RealizeCompleteEvent</tt>. Allows extenders to carry * out additional processing on the <tt>Player</tt>. * * @param player the <tt>Player</tt> which is the source of a * <tt>RealizeCompleteEvent</tt> */ protected void playerRealizeComplete(Processor player) { } /** * Gets notified about <tt>ControllerEvent</tt>s generated by * {@link #processor}. * * @param ev the <tt>ControllerEvent</tt> specifying the * <tt>Controller</tt> which is the source of the event and the very type of * the event */ protected void processorControllerUpdate(ControllerEvent ev) { if (ev instanceof ConfigureCompleteEvent) { Processor processor = (Processor) ev.getSourceController(); if (processor != null) { try { processor.setContentDescriptor( createProcessorContentDescriptor(processor)); } catch (NotConfiguredError nce) { logger.error( "Failed to set ContentDescriptor to Processor.", nce); } if (format != null) setProcessorFormat(processor, format); } } else if (ev instanceof ControllerClosedEvent) { Processor processor = (Processor) ev.getSourceController(); /* * If everything goes according to plan, we should've removed the * ControllerListener from the processor by now. */ logger.warn(ev); // TODO Should the access to processor be synchronized? if ((processor != null) && (this.processor == processor)) processorIsPrematurelyClosed = true; } else if (ev instanceof RealizeCompleteEvent) { Processor processor = (Processor) ev.getSourceController(); for (FormatParametersAwareCodec fpac : getAllTrackControls( FormatParametersAwareCodec.class, processor)) { Map<String, String> formatParameters = format == null ? null : format.getFormatParameters(); if (formatParameters != null) fpac.setFormatParameters(formatParameters); } for (AdvancedAttributesAwareCodec aaac : getAllTrackControls( AdvancedAttributesAwareCodec.class, processor)) { Map<String, String> advanceAttrs = format == null ? null : format.getAdvancedAttributes(); if (advanceAttrs != null) aaac.setAdvancedAttributes(advanceAttrs); } } } /** * Removes <tt>ssrc</tt> from the array of SSRC identifiers representing * parties that this <tt>MediaDeviceSession</tt> is currently receiving * streams from. * * @param ssrc the SSRC identifier that we'd like to remove from the array * of <tt>ssrc</tt> identifiers stored by this session. */ protected void removeSSRC(long ssrc) { //find the ssrc int index = -1; if (ssrcList == null || ssrcList.length == 0) { //list is already empty so there's nothing to do. return; } for (int i = 0; i < ssrcList.length; i++) { if (ssrcList[i] == ssrc) { index = i; break; } } if (index < 0 || index >= ssrcList.length) { //the ssrc we are trying to remove is not in the list so there's //nothing to do. return; } //if we get here and the list has a single element this would mean we //simply need to empty it as the only element is the one we are removing if (ssrcList.length == 1) { setSsrcList(null); return; } long[] newSsrcList = new long[ssrcList.length - 1]; System.arraycopy(ssrcList, 0, newSsrcList, 0, index); if (index < ssrcList.length - 1) { System.arraycopy(ssrcList, index + 1, newSsrcList, index, ssrcList.length - index - 1); } setSsrcList(newSsrcList); } /** * Notifies this instance that a specific <tt>ReceiveStream</tt> has been * added to the list of playbacks of <tt>ReceiveStream</tt>s and/or * <tt>DataSource</tt>s performed by respective <tt>Player</tt>s on the * <tt>MediaDevice</tt> represented by this instance. * * @param receiveStream the <tt>ReceiveStream</tt> which has been added to * the list of playbacks of <tt>ReceiveStream</tt>s and/or * <tt>DataSource</tt>s performed by respective <tt>Player</tt>s on the * <tt>MediaDevice</tt> represented by this instance */ protected void receiveStreamAdded(ReceiveStream receiveStream) { } /** * Notifies this instance that a specific <tt>ReceiveStream</tt> has been * removed from the list of playbacks of <tt>ReceiveStream</tt>s and/or * <tt>DataSource</tt>s performed by respective <tt>Player</tt>s on the * <tt>MediaDevice</tt> represented by this instance. * * @param receiveStream the <tt>ReceiveStream</tt> which has been removed * from the list of playbacks of <tt>ReceiveStream</tt>s and/or * <tt>DataSource</tt>s performed by respective <tt>Player</tt>s on the * <tt>MediaDevice</tt> represented by this instance */ protected void receiveStreamRemoved(ReceiveStream receiveStream) { } protected void setCaptureDeviceFormat( DataSource captureDevice, MediaFormatImpl<? extends Format> mediaFormat) { Format format = mediaFormat.getFormat(); if (format instanceof AudioFormat) { AudioFormat audioFormat = (AudioFormat) format; int channels = audioFormat.getChannels(); double sampleRate = OSUtils.IS_ANDROID ? audioFormat.getSampleRate() : Format.NOT_SPECIFIED; if ((channels != Format.NOT_SPECIFIED) || (sampleRate != Format.NOT_SPECIFIED)) { FormatControl formatControl = (FormatControl) captureDevice.getControl( FormatControl.class.getName()); if (formatControl != null) { Format[] supportedFormats = formatControl.getSupportedFormats(); if ((supportedFormats != null) && (supportedFormats.length != 0)) { if (sampleRate != Format.NOT_SPECIFIED) { /* * As per RFC 3551.4.5.2, because of a mistake in * RFC 1890 and for backward compatibility, G.722 * should always be announced as 8000 even though it * is wideband. */ String encoding = audioFormat.getEncoding(); if ((Constants.G722.equalsIgnoreCase(encoding) || Constants.G722_RTP.equalsIgnoreCase( encoding)) && (sampleRate == 8000)) { sampleRate = 16000; } } Format supportedAudioFormat = null; for (int i = 0; i < supportedFormats.length; i++) { Format sf = supportedFormats[i]; if (sf instanceof AudioFormat) { AudioFormat saf = (AudioFormat) sf; if ((Format.NOT_SPECIFIED != channels) && (saf.getChannels() != channels)) continue; if ((Format.NOT_SPECIFIED != sampleRate) && (saf.getSampleRate() != sampleRate)) continue; supportedAudioFormat = saf; break; } } if (supportedAudioFormat != null) formatControl.setFormat(supportedAudioFormat); } } } } } /** * Sets the <tt>ContentDescriptor</tt> which specifies the content type in * which this <tt>MediaDeviceSession</tt> is to output the media captured by * its <tt>MediaDevice</tt>. The default content type in which * <tt>MediaDeviceSession</tt> outputs the media captured by its * <tt>MediaDevice</tt> is {@link ContentDescriptor#RAW_RTP}. * * @param contentDescriptor the <tt>ContentDescriptor</tt> which specifies * the content type in which this <tt>MediaDeviceSession</tt> is to output * the media captured by its <tt>MediaDevice</tt> */ public void setContentDescriptor(ContentDescriptor contentDescriptor) { if (contentDescriptor == null) throw new NullPointerException("contentDescriptor"); this.contentDescriptor = contentDescriptor; } /** * Sets the <tt>MediaFormat</tt> in which this <tt>MediaDeviceSession</tt> * outputs the media captured by its <tt>MediaDevice</tt>. * * @param format the <tt>MediaFormat</tt> in which this * <tt>MediaDeviceSession</tt> is to output the media captured by its * <tt>MediaDevice</tt> */ public void setFormat(MediaFormat format) { if (!getMediaType().equals(format.getMediaType())) throw new IllegalArgumentException("format"); /* * We need javax.media.Format and we know how to convert MediaFormat to * it only for MediaFormatImpl so assert early. */ @SuppressWarnings("unchecked") MediaFormatImpl<? extends Format> mediaFormatImpl = (MediaFormatImpl<? extends Format>) format; this.format = mediaFormatImpl; if (logger.isTraceEnabled()) { logger.trace( "Set format " + this.format + " on " + getClass().getSimpleName() + " " + hashCode()); } /* * If the processor is after Configured, setting a different format will * silently fail. Recreate the processor in order to be able to set the * different format. */ if (processor != null) { int processorState = processor.getState(); if (processorState == Processor.Configured) setProcessorFormat(processor, this.format); else if (processorIsPrematurelyClosed || ((processorState > Processor.Configured) && !this.format.getFormat().equals( getProcessorFormat())) || outputSizeChanged) { outputSizeChanged = false; setProcessor(null); } } } /** * Sets the <tt>MediaFormatImpl</tt> in which a specific <tt>Processor</tt> * producing media to be streamed to the remote peer is to output. * * @param processor the <tt>Processor</tt> to set the output * <tt>MediaFormatImpl</tt> of * @param mediaFormat the <tt>MediaFormatImpl</tt> to set on * <tt>processor</tt> */ protected void setProcessorFormat( Processor processor, MediaFormatImpl<? extends Format> mediaFormat) { TrackControl[] trackControls = processor.getTrackControls(); MediaType mediaType = getMediaType(); Format format = mediaFormat.getFormat(); for (int trackIndex = 0; trackIndex < trackControls.length; trackIndex++) { TrackControl trackControl = trackControls[trackIndex]; if (!trackControl.isEnabled()) continue; Format[] supportedFormats = trackControl.getSupportedFormats(); if ((supportedFormats == null) || (supportedFormats.length < 1)) { trackControl.setEnabled(false); continue; } Format supportedFormat = null; switch (mediaType) { case AUDIO: if (supportedFormats[0] instanceof AudioFormat) { supportedFormat = findFirstMatchingFormat(supportedFormats, format); /* * We've failed to find a supported format so try to use * whatever we've been told and, if it fails, the caller * will at least know why. */ if (supportedFormat == null) supportedFormat = format; } break; case VIDEO: if (supportedFormats[0] instanceof VideoFormat) { supportedFormat = findFirstMatchingFormat(supportedFormats, format); /* * We've failed to find a supported format so try to use * whatever we've been told and, if it fails, the caller * will at least know why. */ if (supportedFormat == null) supportedFormat = format; if (supportedFormat != null) supportedFormat = assertSize((VideoFormat) supportedFormat); } break; default: // FMJ and LibJitsi handle audio and video only and it seems // unlikely that support for any other types of media will be // added here. break; } if (supportedFormat == null) trackControl.setEnabled(false); else if (!supportedFormat.equals(trackControl.getFormat())) { Format setFormat = setProcessorFormat( trackControl, mediaFormat, supportedFormat); if (setFormat == null) logger.error( "Failed to set format of track " + trackIndex + " to " + supportedFormat + ". Processor is in state " + processor.getState()); else if (setFormat != supportedFormat) logger.warn( "Failed to change format of track " + trackIndex + " from " + setFormat + " to " + supportedFormat + ". Processor is in state " + processor.getState()); else if (logger.isTraceEnabled()) logger.trace( "Set format of track " + trackIndex + " to " + setFormat); } } } /** * Sets the <tt>MediaFormatImpl</tt> of a specific <tt>TrackControl</tt> of * the <tt>Processor</tt> which produces the media to be streamed by this * <tt>MediaDeviceSession</tt> to the remote peer. Allows extenders to * override the set procedure and to detect when the JMF <tt>Format</tt> of * the specified <tt>TrackControl</tt> changes. * * @param trackControl the <tt>TrackControl</tt> to set the JMF * <tt>Format</tt> of * @param mediaFormat the <tt>MediaFormatImpl</tt> to be set on the * specified <tt>TrackControl</tt>. Though <tt>mediaFormat</tt> encapsulates * a JMF <tt>Format</tt>, <tt>format</tt> is to be set on the specified * <tt>trackControl</tt> because it may be more specific. In any case, the * two JMF <tt>Format</tt>s match. The <tt>MediaFormatImpl</tt> is provided * anyway because it carries additional information such as format * parameters. * @param format the JMF <tt>Format</tt> to be set on the specified * <tt>TrackControl</tt>. Though <tt>mediaFormat</tt> encapsulates a JMF * <tt>Format</tt>, the specified <tt>format</tt> is to be set on the * specified <tt>trackControl</tt> because it may be more specific than the * JMF <tt>Format</tt> of the <tt>mediaFormat</tt> * @return the JMF <tt>Format</tt> set on <tt>TrackControl</tt> after the * attempt to set the specified <tt>format</tt> or <tt>null</tt> if the * specified <tt>format</tt> was found to be incompatible with * <tt>trackControl</tt> */ protected Format setProcessorFormat( TrackControl trackControl, MediaFormatImpl<? extends Format> mediaFormat, Format format) { return trackControl.setFormat(format); } /** * Sets the indicator which determines whether this * <tt>MediaDeviceSession</tt> is set to output "silence" instead of the * actual media fed from its <tt>CaptureDevice</tt>. * * @param mute <tt>true</tt> to set this <tt>MediaDeviceSession</tt> to * output "silence" instead of the actual media fed from its * <tt>CaptureDevice</tt>; otherwise, <tt>false</tt> */ public void setMute(boolean mute) { if (this.mute != mute) { this.mute = mute; MuteDataSource muteDataSource = AbstractControls.queryInterface( captureDevice, MuteDataSource.class); if (muteDataSource != null) muteDataSource.setMute(this.mute); } } /** * Adds a new inband DTMF tone to send. * * @param tone the DTMF tone to send. */ public void addDTMF(DTMFInbandTone tone) { InbandDTMFDataSource inbandDTMFDataSource = AbstractControls.queryInterface( captureDevice, InbandDTMFDataSource.class); if (inbandDTMFDataSource != null) inbandDTMFDataSource.addDTMF(tone); } /** * Adds a specific <tt>DataSource</tt> to the list of playbacks of * <tt>ReceiveStream</tt>s and/or <tt>DataSource</tt>s performed by * respective <tt>Player</tt>s on the <tt>MediaDevice</tt> represented by * this instance. * * @param playbackDataSource the <tt>DataSource</tt> which to be added to * the list of playbacks of <tt>ReceiveStream</tt>s and/or * <tt>DataSource</tt>s performed by respective <tt>Player</tt>s on the * <tt>MediaDevice</tt> represented by this instance */ public void addPlaybackDataSource(DataSource playbackDataSource) { Lock writeLock = playbacksLock.writeLock(); Lock readLock = playbacksLock.readLock(); boolean added = false; writeLock.lock(); try { Playback playback = getPlayback(playbackDataSource); if (playback == null) { if (playbackDataSource instanceof ReceiveStreamPushBufferDataSource) { ReceiveStream receiveStream = ((ReceiveStreamPushBufferDataSource) playbackDataSource) .getReceiveStream(); playback = getPlayback(receiveStream); } if (playback == null) { playback = new Playback(playbackDataSource); playbacks.add(playback); } else playback.dataSource = playbackDataSource; playback.player = createPlayer(playbackDataSource); readLock.lock(); added = true; } } finally { writeLock.unlock(); } if (added) { try { playbackDataSourceAdded(playbackDataSource); } finally { readLock.unlock(); } } } /** * Removes a specific <tt>DataSource</tt> from the list of playbacks of * <tt>ReceiveStream</tt>s and/or <tt>DataSource</tt>s performed by * respective <tt>Player</tt>s on the <tt>MediaDevice</tt> represented by * this instance. * * @param playbackDataSource the <tt>DataSource</tt> which to be removed * from the list of playbacks of <tt>ReceiveStream</tt>s and/or * <tt>DataSource</tt>s performed by respective <tt>Player</tt>s on the * <tt>MediaDevice</tt> represented by this instance */ public void removePlaybackDataSource(DataSource playbackDataSource) { Lock writeLock = playbacksLock.writeLock(); Lock readLock = playbacksLock.readLock(); boolean removed = false; writeLock.lock(); try { Playback playback = getPlayback(playbackDataSource); if (playback != null) { if (playback.player != null) { disposePlayer(playback.player); playback.player = null; } playback.dataSource = null; if (playback.receiveStream == null) playbacks.remove(playback); readLock.lock(); removed = true; } } finally { writeLock.unlock(); } if (removed) { try { playbackDataSourceRemoved(playbackDataSource); } finally { readLock.unlock(); } } } /** * Sets the JMF <tt>Processor</tt> which is to transcode * {@link #captureDevice} into the format of this instance. * * @param processor the JMF <tt>Processor</tt> which is to transcode * {@link #captureDevice} into the format of this instance */ private void setProcessor(Processor processor) { if (this.processor != processor) { closeProcessor(); this.processor = processor; /* * Since the processor has changed, its output DataSource known to * the public has also changed. */ firePropertyChange(OUTPUT_DATA_SOURCE, null, null); } } /** * Adds a specific <tt>ReceiveStream</tt> to the list of playbacks of * <tt>ReceiveStream</tt>s and/or <tt>DataSource</tt>s performed by * respective <tt>Player</tt>s on the <tt>MediaDevice</tt> represented by * this instance. * * @param receiveStream the <tt>ReceiveStream</tt> which to be added to the * list of playbacks of <tt>ReceiveStream</tt>s and/or <tt>DataSource</tt>s * performed by respective <tt>Player</tt>s on the <tt>MediaDevice</tt> * represented by this instance */ public void addReceiveStream(ReceiveStream receiveStream) { Lock writeLock = playbacksLock.writeLock(); Lock readLock = playbacksLock.readLock(); boolean added = false; writeLock.lock(); try { if (getPlayback(receiveStream) == null) { playbacks.add(new Playback(receiveStream)); addSSRC(0xFFFFFFFFL & receiveStream.getSSRC()); // playbackDataSource DataSource receiveStreamDataSource = receiveStream.getDataSource(); if (receiveStreamDataSource != null) { if (receiveStreamDataSource instanceof PushBufferDataSource) { receiveStreamDataSource = new ReceiveStreamPushBufferDataSource( receiveStream, (PushBufferDataSource) receiveStreamDataSource, true); } else { logger.warn( "Adding ReceiveStream with DataSource not of" + " type PushBufferDataSource but " + receiveStreamDataSource.getClass() .getSimpleName() + " which may prevent the ReceiveStream" + " from properly transferring to another" + " MediaDevice if such a need arises."); } addPlaybackDataSource(receiveStreamDataSource); } readLock.lock(); added = true; } } finally { writeLock.unlock(); } if (added) { try { receiveStreamAdded(receiveStream); } finally { readLock.unlock(); } } } /** * Removes a specific <tt>ReceiveStream</tt> from the list of playbacks of * <tt>ReceiveStream</tt>s and/or <tt>DataSource</tt>s performed by * respective <tt>Player</tt>s on the <tt>MediaDevice</tt> represented by * this instance. * * @param receiveStream the <tt>ReceiveStream</tt> which to be removed from * the list of playbacks of <tt>ReceiveStream</tt>s and/or * <tt>DataSource</tt>s performed by respective <tt>Player</tt>s on the * <tt>MediaDevice</tt> represented by this instance */ public void removeReceiveStream(ReceiveStream receiveStream) { Lock writeLock = playbacksLock.writeLock(); Lock readLock = playbacksLock.readLock(); boolean removed = false; writeLock.lock(); try { Playback playback = getPlayback(receiveStream); if (playback != null) { removeSSRC(0xFFFFFFFFL & receiveStream.getSSRC()); if (playback.dataSource != null) removePlaybackDataSource(playback.dataSource); if (playback.dataSource != null) { logger.warn( "Removing ReceiveStream with an associated" + " DataSource."); } playbacks.remove(playback); readLock.lock(); removed = true; } } finally { writeLock.unlock(); } if (removed) { try { receiveStreamRemoved(receiveStream); } finally { readLock.unlock(); } } } /** * Sets the list of SSRC identifiers that this device stores to * <tt>newSsrcList</tt> and fires a <tt>PropertyChangeEvent</tt> for the * <tt>SSRC_LIST</tt> property. * * @param newSsrcList that SSRC array that we'd like to replace the existing * SSRC list with. */ private void setSsrcList(long[] newSsrcList) { // use getRemoteSSRCList() instead of direct access to ssrcList // as the extender may override it long[] oldSsrcList = getRemoteSSRCList(); ssrcList = newSsrcList; firePropertyChange(SSRC_LIST, oldSsrcList, getRemoteSSRCList()); } /** * Starts the processing of media in this instance in a specific direction. * * @param direction a <tt>MediaDirection</tt> value which represents the * direction of the processing of media to be started. For example, * {@link MediaDirection#SENDRECV} to start both capture and playback of * media in this instance or {@link MediaDirection#SENDONLY} to only start * the capture of media in this instance */ public void start(MediaDirection direction) { if (direction == null) throw new NullPointerException("direction"); MediaDirection oldValue = startedDirection; startedDirection = startedDirection.or(direction); if (!oldValue.equals(startedDirection)) startedDirectionChanged(oldValue, startedDirection); } /** * Notifies this instance that the value of its <tt>startedDirection</tt> * property has changed from a specific <tt>oldValue</tt> to a specific * <tt>newValue</tt>. Allows extenders to override and perform additional * processing of the change. Overriding implementations must call this * implementation in order to ensure the proper execution of this * <tt>MediaDeviceSession</tt>. * * @param oldValue the <tt>MediaDirection</tt> which used to be the value of * the <tt>startedDirection</tt> property of this instance * @param newValue the <tt>MediaDirection</tt> which is the value of the * <tt>startedDirection</tt> property of this instance */ protected void startedDirectionChanged( MediaDirection oldValue, MediaDirection newValue) { if (newValue.allowsSending()) { Processor processor = getProcessor(); if (processor != null) startProcessorInAccordWithDirection(processor); } else if ((processor != null) && (processor.getState() > Processor.Configured)) { processor.stop(); if (logger.isTraceEnabled()) { logger.trace( "Stopped Processor with hashCode " + processor.hashCode()); } } } /** * Starts a specific <tt>Processor</tt> if this <tt>MediaDeviceSession</tt> * has been started and the specified <tt>Processor</tt> is not started. * * @param processor the <tt>Processor</tt> to start */ protected void startProcessorInAccordWithDirection(Processor processor) { if (startedDirection.allowsSending() && (processor.getState() != Processor.Started)) { processor.start(); if (logger.isTraceEnabled()) { logger.trace( "Started Processor with hashCode " + processor.hashCode()); } } } /** * Stops the processing of media in this instance in a specific direction. * * @param direction a <tt>MediaDirection</tt> value which represents the * direction of the processing of media to be stopped. For example, * {@link MediaDirection#SENDRECV} to stop both capture and playback of * media in this instance or {@link MediaDirection#SENDONLY} to only stop * the capture of media in this instance */ public void stop(MediaDirection direction) { if (direction == null) throw new NullPointerException("direction"); MediaDirection oldValue = startedDirection; switch (startedDirection) { case SENDRECV: if (direction.allowsReceiving()) startedDirection = direction.allowsSending() ? MediaDirection.INACTIVE : MediaDirection.SENDONLY; else if (direction.allowsSending()) startedDirection = MediaDirection.RECVONLY; break; case SENDONLY: if (direction.allowsSending()) startedDirection = MediaDirection.INACTIVE; break; case RECVONLY: if (direction.allowsReceiving()) startedDirection = MediaDirection.INACTIVE; break; case INACTIVE: /* * This MediaDeviceSession is already inactive so there's nothing to * stop. */ break; default: throw new IllegalArgumentException("direction"); } if (!oldValue.equals(startedDirection)) startedDirectionChanged(oldValue, startedDirection); } /** * Waits for the specified JMF <tt>Processor</tt> to enter the specified * <tt>state</tt> and returns <tt>true</tt> if <tt>processor</tt> has * successfully entered <tt>state</tt> or <tt>false</tt> if <tt>process</tt> * has failed to enter <tt>state</tt>. * * @param processor the JMF <tt>Processor</tt> to wait on * @param state the state as defined by the respective <tt>Processor</tt> * state constants to wait <tt>processor</tt> to enter * @return <tt>true</tt> if <tt>processor</tt> has successfully entered * <tt>state</tt>; otherwise, <tt>false</tt> */ private static boolean waitForState(Processor processor, int state) { return new ProcessorUtility().waitForState(processor, state); } /** * Copies the playback part of a specific <tt>MediaDeviceSession</tt> into * this instance. * * @param deviceSession the <tt>MediaDeviceSession</tt> to copy the playback * part of into this instance */ public void copyPlayback(MediaDeviceSession deviceSession) { if (deviceSession.disposePlayerOnClose) { logger.error( "Cannot copy playback if MediaDeviceSession has closed it"); } else { /* * TODO Technically, we should be synchronizing the (read and write) * accesses to the playbacks fields. In practice, we are not doing * it because it likely was the easiest to not bother with it at the * time of its writing. */ playbacks.addAll(deviceSession.playbacks); setSsrcList(deviceSession.ssrcList); } } /** * Represents the information related to the playback of a * <tt>DataSource</tt> on the <tt>MediaDevice</tt> represented by a * <tt>MediaDeviceSession</tt>. The <tt>DataSource</tt> may have an * associated <tt>ReceiveStream</tt>. */ private static class Playback { /** * The <tt>DataSource</tt> the information related to the playback of * which is represented by this instance and which is associated with * {@link #receiveStream}. */ public DataSource dataSource; /** * The <tt>ReceiveStream</tt> the information related to the playback of * which is represented by this instance and which is associated with * {@link #dataSource}. */ public ReceiveStream receiveStream; /** * The <tt>Player</tt> which performs the actual playback. */ public Player player; /** * Initializes a new <tt>Playback</tt> instance which is to represent * the information related to the playback of a specific * <tt>DataSource</tt>. * * @param dataSource the <tt>DataSource</tt> the information related to * the playback of which is to be represented by the new instance */ public Playback(DataSource dataSource) { this.dataSource = dataSource; } /** * Initializes a new <tt>Playback</tt> instance which is to represent * the information related to the playback of a specific * <tt>ReceiveStream</tt>. * * @param receiveStream the <tt>ReceiveStream</tt> the information * related to the playback of which is to be represented by the new * instance */ public Playback(ReceiveStream receiveStream) { this.receiveStream = receiveStream; } } /** * Returns the <tt>TranscodingDataSource</tt> associated with * <tt>receiveStream</tt>. * * @param receiveStream the <tt>ReceiveStream</tt> to use * * @return the <tt>TranscodingDataSource</tt> associated with * <tt>receiveStream</tt>. */ public TranscodingDataSource getTranscodingDataSource( ReceiveStream receiveStream) { TranscodingDataSource transcodingDataSource = null; if(device instanceof AudioMixerMediaDevice) { transcodingDataSource = ((AudioMixerMediaDevice) device) .getTranscodingDataSource(receiveStream.getDataSource()); } return transcodingDataSource; } /** * Searches for controls of type <tt>controlType</tt> in the * <tt>TrackControl</tt>s of the <tt>Processor</tt> used to transcode the * <tt>MediaDevice</tt> of this instance into the format of this instance. * Returns a <tt>Set</tt> of instances of class <tt>controlType</tt>, * always non-null. * * @param controlType the name of the class to search for. * @return A non-null <tt>Set</tt> of all <tt>controlType</tt>s found. */ public <T> Set<T> getEncoderControls(Class<T> controlType) { return getAllTrackControls(controlType, this.processor); } /** * Searches for controls of type <tt>controlType</tt> in the * <tt>TrackControl</tt>s of the <tt>Processor</tt> used to decode * <tt>receiveStream</tt>. Returns a <tt>Set</tt> of instances of class * <tt>controlType</tt>, always non-null. * * @param receiveStream the <tt>ReceiveStream</tt> whose <tt>Processor</tt>'s * <tt>TrackControl</tt>s are to be searched. * @param controlType the name of the class to search for. * @return A non-null <tt>Set</tt> of all <tt>controlType</tt>s found. */ public <T> Set<T> getDecoderControls( ReceiveStream receiveStream, Class<T> controlType) { TranscodingDataSource transcodingDataSource = getTranscodingDataSource(receiveStream); if (transcodingDataSource == null) return Collections.emptySet(); else { return getAllTrackControls( controlType, transcodingDataSource.getTranscodingProcessor()); } } /** * Returns the <tt>Set</tt> of controls of type <tt>controlType</tt>, which * are controls for some of <tt>processor</tt>'s <tt>TrackControl</tt>s. * * @param controlType the name of the class to search for. * @param processor the <tt>Processor</tt> whose <tt>TrackControls</tt>s * will be searched. * @return A non-null <tt>Set</tt> of all <tt>controlType</tt>s found. */ private <T> Set<T> getAllTrackControls( Class<T> controlType, Processor processor) { Set<T> controls = null; if ((processor != null) && (processor.getState() >= Processor.Realized)) { TrackControl[] trackControls = processor.getTrackControls(); if ((trackControls != null) && (trackControls.length != 0)) { String className = controlType.getName(); for (TrackControl trackControl : trackControls) { Object o = trackControl.getControl(className); if (controlType.isInstance(o)) { @SuppressWarnings("unchecked") T t = (T) o; if (controls == null) controls = new HashSet<T>(); controls.add(t); } } } } if (controls == null) controls = Collections.emptySet(); return controls; } }
package cz.vutbr.fit.iha.activity; import java.util.ArrayList; import java.util.List; import se.emilsjolander.stickylistheaders.StickyListHeadersListView; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.text.format.Time; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.view.ActionMode; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.Window; import cz.vutbr.fit.iha.MenuListAdapter; import cz.vutbr.fit.iha.R; import cz.vutbr.fit.iha.SensorListAdapter; import cz.vutbr.fit.iha.activity.dialog.AddAdapterActivityDialog; import cz.vutbr.fit.iha.activity.dialog.AddSensorActivityDialog; import cz.vutbr.fit.iha.activity.dialog.CustomAlertDialog; import cz.vutbr.fit.iha.activity.dialog.InfoDialogFragment; import cz.vutbr.fit.iha.activity.menuItem.AdapterMenuItem; import cz.vutbr.fit.iha.activity.menuItem.EmptyMenuItem; import cz.vutbr.fit.iha.activity.menuItem.GroupImageMenuItem; import cz.vutbr.fit.iha.activity.menuItem.LocationMenuItem; import cz.vutbr.fit.iha.activity.menuItem.ProfileMenuItem; import cz.vutbr.fit.iha.activity.menuItem.SeparatorMenuItem; import cz.vutbr.fit.iha.activity.menuItem.SettingMenuItem; import cz.vutbr.fit.iha.adapter.Adapter; import cz.vutbr.fit.iha.adapter.device.BaseDevice; import cz.vutbr.fit.iha.adapter.location.Location; import cz.vutbr.fit.iha.controller.Controller; import cz.vutbr.fit.iha.household.ActualUser; /** * Activity class for choosing location * * @author ThinkDeep * @author Robyer * */ public class LocationScreenActivity extends BaseActivity { private static final String TAG = LocationScreenActivity.class.getSimpleName(); private Controller mController; private LocationScreenActivity mActivity; private List<Location> mLocations; private DrawerLayout mDrawerLayout; private StickyListHeadersListView mDrawerList; private ActionBarDrawerToggle mDrawerToggle; private MenuListAdapter mMenuAdapter; private CharSequence mDrawerTitle; private SensorListAdapter mSensorAdapter; private ListView mSensorList; private CharSequence mTitle; private static boolean inBackground = false; private static boolean isPaused = false; /** * Instance save state tags */ private static final String BKG = "activityinbackground"; private static final String LCTN = "lastlocation"; private static final String IS_DRAWER_OPEN = "draweropen"; private final static int REQUEST_SENSOR_DETAIL = 1; private final static int REQUEST_ADD_ADAPTER = 2; /** * saved instance states */ private Location mActiveLocation; private String mActiveLocationId; private static boolean mOrientation = false; private static boolean mIsDrawerOpen; private List<BaseDevice> mSensors; private Handler mTimeHandler = new Handler(); private Runnable mTimeRun; /** * Tasks which can be running in this activity and after finishing can try * to change GUI -> must be cancelled when activity stop */ private DevicesTask mDevicesTask; private ChangeLocationTask mChangeLocationTask; private SwitchAdapter mSwitchAdapter; ActionMode mMode; protected TextView mDrawerItemText; protected EditText mDrawerItemEdit; private boolean backPressed = false; /** * Constant to tag InfoDIalogFragment */ private final static String TAG_INFO = "tag_info"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.activity_location_screen); // Get controller mController = Controller.getInstance(this); // Get Activity mActivity = this; setSupportProgressBarIndeterminate(true); setSupportProgressBarIndeterminateVisibility(true); getSupportActionBar().setIcon(R.drawable.ic_launcher_white); if (savedInstanceState != null) { inBackground = savedInstanceState.getBoolean(BKG); mIsDrawerOpen = savedInstanceState.getBoolean(IS_DRAWER_OPEN); mActiveLocationId = savedInstanceState.getString(LCTN); if (mActiveLocationId != null) mOrientation = true; } initMenu(); } public void onResume() { super.onResume(); Log.d(TAG, "onResume , inBackground: " + String.valueOf(inBackground)); setLocationOrEmpty(); redrawMenu(); backPressed = false; isPaused = false; } public void onPause() { super.onPause(); isPaused = true; mTimeHandler.removeCallbacks(mTimeRun); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy"); this.setSupportProgressBarIndeterminateVisibility(false); if (mDevicesTask != null) { mDevicesTask.cancel(true); if (mDevicesTask.getDialog() != null) { mDevicesTask.getDialog().dismiss(); } } if (mChangeLocationTask != null) { mChangeLocationTask.cancel(true); } if (mSwitchAdapter != null) { mSwitchAdapter.cancel(true); } } @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (backPressed) { backPressed = false; } return super.dispatchTouchEvent(ev); } /** * Handling first tap back button */ private void firstTapBack() { Toast.makeText(this, getString(R.string.toast_tap_again_exit), Toast.LENGTH_SHORT).show(); backPressed = true; if (mDrawerLayout != null) mDrawerLayout.openDrawer(mDrawerList); } /** * Handling second tap back button - exiting */ private void secondTapBack() { // Toast.makeText(this, getString(R.string.toast_leaving_app), // Toast.LENGTH_LONG).show(); // super.onBackPressed(); // this.finish(); android.os.Process.killProcess(android.os.Process.myPid()); } @Override public void onBackPressed() { // second click if (backPressed) { secondTapBack(); } // first click else { firstTapBack(); } Log.d(TAG, "BackPressed - onBackPressed " + String.valueOf(backPressed)); return; } @Override public void onSaveInstanceState(Bundle savedInstaceState) { savedInstaceState.putBoolean(BKG, inBackground); savedInstaceState.putString(LCTN, mActiveLocationId); savedInstaceState.putBoolean(IS_DRAWER_OPEN, mDrawerLayout.isDrawerOpen(mDrawerList)); super.onSaveInstanceState(savedInstaceState); } public static void healActivity() { inBackground = false; } public void onOrientationChanged() { if (mOrientation) { mActiveLocation = mController.getLocation(mActiveLocationId); refreshListing(); if (!mIsDrawerOpen) { // Close drawer mDrawerLayout.closeDrawer(mDrawerList); Log.d(TAG, "LifeCycle: onOrientation"); } } mOrientation = false; } /** * Use Thread to call it or for refreshing Menu use redrawMenu() instead. */ private MenuListAdapter getMenuAdapter() { MenuListAdapter menuAdapter = new MenuListAdapter(LocationScreenActivity.this); ActualUser actUser = mController.getActualUser(); // // FIXME zmenit obrazek na obrazek uzivatele // Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), // R.drawable.person_siluete); // Adding profile header menuAdapter.addHeader(new ProfileMenuItem(actUser.getName(), actUser.getEmail(), actUser.getPicture(this))); List<Adapter> adapters = mController.getAdapters(); if (adapters.size() > 1) { // Adding separator as item (we don't want to let it float as // header) menuAdapter.addItem(new SeparatorMenuItem()); // Adding adapters Adapter chosenAdapter = mController.getActiveAdapter(); for (Adapter actAdapter : adapters) { menuAdapter.addItem(new AdapterMenuItem(actAdapter.getName(), actAdapter.getRole().name(), chosenAdapter.getId().equals(actAdapter.getId()), actAdapter.getId())); } } // Adding separator as item (we don't want to let it float as header) menuAdapter.addItem(new SeparatorMenuItem()); // Adding location header menuAdapter.addHeader(new GroupImageMenuItem(getResources().getString(R.string.location), R.drawable.add_custom_view, new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(LocationScreenActivity.this, "Not implemented yet", Toast.LENGTH_SHORT).show(); } })); if (mLocations.size() > 0) { // Adding location for (int i = 0; i < mLocations.size(); i++) { Location actLoc = mLocations.get(i); menuAdapter.addItem(new LocationMenuItem(actLoc.getName(), actLoc.getIconResource(), i != 0, actLoc.getId())); } } else { menuAdapter.addItem(new EmptyMenuItem(mActivity.getResources().getString(R.string.no_location))); } // Adding custom view header menuAdapter.addHeader(new GroupImageMenuItem(getResources().getString(R.string.custom_view), R.drawable.add_custom_view, new OnClickListener() { @Override public void onClick(View v) { // TODO doplnit spusteni dialogu pro vytvoreni custom // view Toast.makeText(LocationScreenActivity.this, "Not implemented yet", Toast.LENGTH_SHORT).show(); } })); // Adding custom views // TODO pridat custom views menuAdapter.addItem(new EmptyMenuItem(mActivity.getResources().getString(R.string.no_custom_view))); // Adding separator as header menuAdapter.addItem(new SeparatorMenuItem()); // Adding settings, about etc. menuAdapter.addItem(new SettingMenuItem(getResources().getString(R.string.action_settings), R.drawable.loc_unknown, cz.vutbr.fit.iha.activity.menuItem.MenuItem.ID_SETTINGS)); menuAdapter.addItem(new SettingMenuItem(getResources().getString(R.string.action_about), R.drawable.loc_unknown, cz.vutbr.fit.iha.activity.menuItem.MenuItem.ID_ABOUT)); // menuAdapter.log(); return menuAdapter; } public boolean initMenu() { Log.d(TAG, "ready to work with Locations"); mTitle = mDrawerTitle = "IHA"; // Locate DrawerLayout in activity_location_screen.xml mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); // Locate ListView in activity_location_screen.xml mDrawerList = (StickyListHeadersListView) findViewById(R.id.listview_drawer); // Set a custom shadow that overlays the main content when the drawer // opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); mDrawerLayout.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) { Log.d(TAG, "BackPressed = " + String.valueOf(backPressed)); if (mDrawerLayout.isDrawerOpen(mDrawerList) && !backPressed) { firstTapBack(); return true; } else if (mDrawerLayout.isDrawerOpen(mDrawerList) && backPressed) { secondTapBack(); return true; } } return false; } }); // // Set the MenuListAdapter to the ListView // mDrawerList.setAdapter(mMenuAdapter); // Capture listview menu item click mDrawerList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Controller controller = Controller.getInstance(LocationScreenActivity.this); cz.vutbr.fit.iha.activity.menuItem.MenuItem item = (cz.vutbr.fit.iha.activity.menuItem.MenuItem) mMenuAdapter.getItem(position); switch (item.getType()) { case ADAPTER: // if it is not chosen, switch to selected adapter if (!controller.getActiveAdapter().getId().equals(item.getId())) { setSupportProgressBarIndeterminateVisibility(true); mSwitchAdapter = new LocationScreenActivity.SwitchAdapter(); mSwitchAdapter.execute(item.getId()); } break; case CUSTOM_VIEW: // TODO otevrit custom view, jeste nedelame s customView // taze pozdeji break; case SETTING: if (item.getId().equals(cz.vutbr.fit.iha.activity.menuItem.MenuItem.ID_ABOUT)) { InfoDialogFragment dialog = new InfoDialogFragment(); dialog.show(getSupportFragmentManager(), TAG_INFO); } else if (item.getId().equals(cz.vutbr.fit.iha.activity.menuItem.MenuItem.ID_SETTINGS)) { Intent intent = new Intent(LocationScreenActivity.this, SettingsMainActivity.class); startActivity(intent); } break; case LOCATION: // Get the title followed by the position mActiveLocationId = item.getId(); changeLocation(mController.getLocation(mActiveLocationId), true); break; default: break; } } }); mDrawerList.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { Log.d(TAG, "Item Long press"); cz.vutbr.fit.iha.activity.menuItem.MenuItem item = (cz.vutbr.fit.iha.activity.menuItem.MenuItem) mMenuAdapter.getItem(position); switch (item.getType()) { case LOCATION: Bundle bundle = new Bundle(); String myMessage = item.getId(); bundle.putString("locationID", myMessage); Intent intent = new Intent(mActivity, LocationDetailActivity.class); intent.putExtras(bundle); startActivityForResult(intent, REQUEST_SENSOR_DETAIL); break; default: // do nothing break; } return true; } }); // Enable ActionBar app icon to behave as action to toggle nav drawer getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); // getSupportActionBar().setIcon(R.drawable.ic_launcher_white); // ActionBarDrawerToggle ties together the the proper interactions // between the sliding drawer and the action bar app icon mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) { public void onDrawerClosed(View view) { if (backPressed) onBackPressed(); // Set the title on the action when drawer closed if (mActiveLocation != null) getSupportActionBar().setTitle(mActiveLocation.getName()); super.onDrawerClosed(view); Log.d(TAG, "BackPressed - onDrawerClosed " + String.valueOf(backPressed)); } public void onDrawerOpened(View drawerView) { // Set the title on the action when drawer open getSupportActionBar().setTitle(mDrawerTitle); super.onDrawerOpened(drawerView); // backPressed = true; } }; mDrawerLayout.setDrawerListener(mDrawerToggle); mDrawerToggle.syncState(); this.setSupportProgressBarIndeterminateVisibility(false); mDrawerLayout.openDrawer(mDrawerList); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.content_frame, new MainFragment()); ft.commit(); return true; } private void setEmptySensors() { getSensors(new ArrayList<BaseDevice>()); } private void changeLocation(Location location, boolean closeDrawer) { mActiveLocation = location; refreshListing(); // mDrawerList.setItemChecked(position, true); // Close drawer if (closeDrawer) { mDrawerLayout.closeDrawer(mDrawerList); } } public boolean getSensors(final List<BaseDevice> sensors) { Log.d(TAG, "LifeCycle: getsensors start"); String[] title; String[] value; String[] unit; Time[] time; int[] icon; mTitle = mDrawerTitle = "IHA"; // TODO: this works, but its not the best solution if (!ListOfSensors.ready) { mSensors = sensors; mTimeRun = new Runnable() { @Override public void run() { getSensors(mSensors); Log.d(TAG, "LifeCycle: getsensors in timer"); } }; if(!isPaused) mTimeHandler.postDelayed(mTimeRun, 500); Log.d(TAG, "LifeCycle: getsensors timer run"); return false; } mTimeHandler.removeCallbacks(mTimeRun); Log.d(TAG, "LifeCycle: getsensors timer remove"); mSensorList = (ListView) findViewById(R.id.listviewofsensors); TextView nosensor = (TextView) findViewById(R.id.nosensorlistview); title = new String[sensors.size()]; value = new String[sensors.size()]; unit = new String[sensors.size()]; icon = new int[sensors.size()]; time = new Time[sensors.size()]; for (int i = 0; i < sensors.size(); i++) { title[i] = sensors.get(i).getName(); value[i] = sensors.get(i).getStringValue(); unit[i] = sensors.get(i).getStringUnit(this); icon[i] = sensors.get(i).getTypeIconResource(); time[i] = sensors.get(i).lastUpdate; } if (mSensorList == null) { setSupportProgressBarIndeterminateVisibility(false); Log.e(TAG, "LifeCycle: bad timing or what?"); return false; // TODO: this happens when we're in different activity // (detail), fix that by changing that activity // (fragment?) first? } // If no sensor - display text only if (sensors.size() == 0) { if (nosensor != null) { nosensor.setVisibility(View.VISIBLE); mSensorList.setVisibility(View.GONE); } this.setSupportProgressBarIndeterminateVisibility(false); return true; } else { nosensor.setVisibility(View.GONE); mSensorList.setVisibility(View.VISIBLE); } mSensorAdapter = new SensorListAdapter(LocationScreenActivity.this, title, value, unit, time, icon); mSensorList.setAdapter(mSensorAdapter); // Capture listview menu item click mSensorList.setOnItemClickListener(new ListView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final BaseDevice selectedItem = sensors.get(position); // setSupportProgressBarIndeterminateVisibility(true); Bundle bundle = new Bundle(); String myMessage = selectedItem.getLocationId(); bundle.putString("LocationOfSensorID", myMessage); bundle.putInt("SensorPosition", position); Intent intent = new Intent(mActivity, SensorDetailActivity.class); intent.putExtras(bundle); startActivityForResult(intent, REQUEST_SENSOR_DETAIL); // startActivity(intent); // finish(); } }); this.setSupportProgressBarIndeterminateVisibility(false); Log.d(TAG, "LifeCycle: getsensors end"); return true; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_SENSOR_DETAIL) { inBackground = true; setSupportProgressBarIndeterminateVisibility(false); mController.reloadAdapters(); refreshListing(); Log.d(TAG, "Here"); } else if (requestCode == REQUEST_ADD_ADAPTER) { redrawMenu(); } } /** * New thread, it takes changes from server and refresh menu items */ protected void redrawMenu() { setSupportProgressBarIndeterminate(true); setSupportProgressBarIndeterminateVisibility(true); // if (!inBackground) { mDevicesTask = new DevicesTask(); mDevicesTask.execute(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Pass any configuration change to the drawer toggles mDrawerToggle.onConfigurationChanged(newConfig); } @Override public void setTitle(CharSequence title) { mTitle = title; getSupportActionBar().setTitle(mTitle); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getSupportMenuInflater(); inflater.inflate(R.menu.location_screen, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: if (mDrawerLayout.isDrawerOpen(mDrawerList)) { mDrawerLayout.closeDrawer(mDrawerList); } else { mDrawerLayout.openDrawer(mDrawerList); } break; case R.id.action_refreshlist: { mController.reloadAdapters(); refreshListing(); break; } case R.id.action_addadapter: { inBackground = true; Intent intent = new Intent(LocationScreenActivity.this, AddAdapterActivityDialog.class); Bundle bundle = new Bundle(); bundle.putBoolean("Cancel", true); intent.putExtras(bundle); startActivityForResult(intent, REQUEST_ADD_ADAPTER); break; } case R.id.action_addsensor: { // Show also ignored devices mController.unignoreUninitialized(); inBackground = true; Intent intent = new Intent(LocationScreenActivity.this, AddSensorActivityDialog.class); startActivity(intent); break; } case R.id.action_settings: { Intent intent = new Intent(LocationScreenActivity.this, SettingsMainActivity.class); startActivity(intent); break; } case R.id.action_logout: { mController.logout(); inBackground = false; Intent intent = new Intent(LocationScreenActivity.this, LoginActivity.class); startActivity(intent); this.finish(); break; } } return super.onOptionsItemSelected(item); } protected void renameLocation(final String location, final TextView view) { AlertDialog.Builder builder = new AlertDialog.Builder(LocationScreenActivity.this); // TODO: use better layout than just single EditText final EditText edit = new EditText(LocationScreenActivity.this); edit.setText(location); edit.selectAll(); // TODO: show keyboard automatically builder.setCancelable(false).setView(edit).setTitle("Rename location").setNegativeButton("Cancel", null).setPositiveButton("Rename", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String newName = edit.getText().toString(); // TODO: show loading while saving new name to // server (+ use // asynctask) Location location = new Location(); // FIXME: // get that // original // location // from // somewhere location.setName(newName); boolean saved = mController.saveLocation(location); String message = saved ? String.format("Location was renamed to '%s'", newName) : "Location wasn't renamed due to error"; Toast.makeText(LocationScreenActivity.this, message, Toast.LENGTH_LONG).show(); // Redraw item in list view.setText(newName); } }); AlertDialog dialog = builder.create(); dialog.show(); } /** * Refresh sensors in actual location */ private void refreshListing() { if (mActiveLocation == null) return; setSupportProgressBarIndeterminateVisibility(true); mChangeLocationTask = new ChangeLocationTask(); mChangeLocationTask.execute(new Location[] { mActiveLocation }); } private void setNewAdapterRedraw(MenuListAdapter adapter) { mMenuAdapter = adapter; mDrawerList.setAdapter(mMenuAdapter); } private void setLocationOnStart(List<Location> locations) { if (locations.size() > 0) { Log.d("default", "DEFAULT POSITION: first position selected"); changeLocation(locations.get(0), false); } else { Log.d("default", "DEFAULT POSITION: Empty sensor set"); Log.d("default", "EMPTY SENSOR SET"); setEmptySensors(); } } private void setLocationOrEmpty() { Adapter actAdapter = mController.getActiveAdapter(); // FIXME opravit na posledni pouzivany if (actAdapter != null) { setLocationOnStart(actAdapter.getLocations()); Log.d("default", "DEFAULT POSITION: active adapter found"); } else { if (mController.getAdapters().size() > 0) { Log.d("default", "DEFAULT POSITION: selected first adapter"); setLocationOnStart(mController.getAdapters().get(0).getLocations()); } } } /** * Loads locations, checks for uninitialized devices and eventually shows * dialog for adding them */ private class SwitchAdapter extends AsyncTask<String, Void, List<BaseDevice>> { @Override protected List<BaseDevice> doInBackground(String... params) { mController.setActiveAdapter(params[0]); return null; } @Override protected void onPostExecute(List<BaseDevice> result) { setLocationOrEmpty(); redrawMenu(); setSupportProgressBarIndeterminateVisibility(false); } } /** * Loads locations, checks for uninitialized devices and eventually shows * dialog for adding them */ private class DevicesTask extends AsyncTask<Void, Void, List<BaseDevice>> { private final CustomAlertDialog mDialog = new CustomAlertDialog(LocationScreenActivity.this); /** * @return the dialog */ public CustomAlertDialog getDialog() { return mDialog; } @Override protected List<BaseDevice> doInBackground(Void... unused) { // Load locations mLocations = mController.getActiveAdapter().getLocations(); Log.d(TAG, String.format("Found %d locations", mLocations.size())); // Load uninitialized devices List<BaseDevice> devices = mController.getUninitializedDevices(); Log.d(TAG, String.format("Found %d uninitialized devices", devices.size())); return devices; } @Override protected void onPostExecute(final List<BaseDevice> uninitializedDevices) { // Redraw locations setNewAdapterRedraw(getMenuAdapter()); onOrientationChanged(); setSupportProgressBarIndeterminate(false); setSupportProgressBarIndeterminateVisibility(false); // Do something with uninitialized devices if (uninitializedDevices.size() == 0) return; mDialog.setCancelable(false).setTitle(getString(R.string.notification_title)).setMessage(getResources().getQuantityString(R.plurals.notification_new_sensors, uninitializedDevices.size(), uninitializedDevices.size())); mDialog.setCustomNeutralButton(getString(R.string.notification_ingore), new OnClickListener() { @Override public void onClick(View v) { mController.ignoreUninitialized(uninitializedDevices); // TODO: Get this string from resources Toast.makeText(LocationScreenActivity.this, "You can add these devices later through 'Menu / Add sensor'", Toast.LENGTH_LONG).show(); mDialog.dismiss(); } }); mDialog.setCustomPositiveButton(getString(R.string.notification_add), new OnClickListener() { @Override public void onClick(View v) { // Open activity for adding new device inBackground = true; Intent intent = new Intent(LocationScreenActivity.this, AddSensorActivityDialog.class); startActivity(intent); mDialog.dismiss(); } }); mDialog.show(); Log.d(TAG, "LifeCycle: devicetask"); } } /** * Changes selected location and redraws list of adapters there */ private class ChangeLocationTask extends AsyncTask<Location, Void, List<BaseDevice>> { @Override protected List<BaseDevice> doInBackground(Location... locations) { List<BaseDevice> devices = mController.getDevicesByLocation(locations[0].getId()); Log.d(TAG, String.format("Found %d devices in location '%s'", devices.size(), locations[0].getName())); return devices; } @Override protected void onPostExecute(final List<BaseDevice> devices) { if(!isPaused) getSensors(devices); } } class AnActionModeOfEpicProportions implements ActionMode.Callback { @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { // TODO Auto-generated method stub menu.add("Save").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); menu.add("Cancel").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { // TODO Auto-generated method stub return false; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { // TODO Auto-generated method stub if (item.getTitle().equals("Save")) { // sName.setText(sNameEdit.getText()); } // sNameEdit.setVisibility(View.GONE); // sName.setVisibility(View.VISIBLE); // sNameEdit.clearFocus(); // getSherlockActivity().getCurrentFocus().clearFocus(); // InputMethodManager imm = (InputMethodManager) getSystemService( // getBaseContext().INPUT_METHOD_SERVICE); // imm.hideSoftInputFromWindow(mDrawerItemEdit.getWindowToken(), 0); mode.finish(); return true; } @Override public void onDestroyActionMode(ActionMode mode) { // TODO Auto-generated method stub // sNameEdit.clearFocus(); // sNameEdit.setVisibility(View.GONE); // sName.setVisibility(View.VISIBLE); mMode = null; } } }
package tn.taha.smsdemo; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.telephony.SmsMessage; import com.varma.samples.smsdemo.R; public class BinarySMSReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); SmsMessage[] msgs = null; if (null != bundle) { String contentMessage = ""; String sender = ""; Object[] pdus = (Object[]) bundle.get("pdus"); msgs = new SmsMessage[pdus.length]; byte[] data = null; for (int i = 0; i < msgs.length; i++) { msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); sender = msgs[i].getOriginatingAddress(); contentMessage += ""; data = msgs[i].getUserData(); for (int index = 0; index < data.length; ++index) { contentMessage += Character.toString((char) data[index]); } } showNotification(context, sender, contentMessage); } } private void showNotification(Context context, String numberFrom, String Message) { PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.mail) .setContentTitle("From:"+numberFrom) .setContentText(Message); mBuilder.setContentIntent(contentIntent); mBuilder.setDefaults(Notification.DEFAULT_SOUND); mBuilder.setAutoCancel(true); NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(1, mBuilder.build()); } }
package org.usfirst.frc.team1306.robot.subsystems; import org.usfirst.frc.team1306.robot.Constants; import org.usfirst.frc.team1306.robot.RobotMap; import edu.wpi.first.wpilibj.CANTalon; import edu.wpi.first.wpilibj.CANTalon.FeedbackDevice; import edu.wpi.first.wpilibj.CANTalon.TalonControlMode; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * Subsystem representing the shooter and its controllers. "Shooter" in this * case means the flywheel. * * @author Finn Voichick, James Tautges */ public class Shooter extends Subsystem { /** The Talon SRX that controls the flywheel motor. */ private CANTalon flywheel; /** * Constructs a new shooter that uses a quadrature encoder as its feedback * device. It controls for speed, making sure that the flywheel is spinning * at the same speed each time it fires. It also has a tolerance that stops * controlling for speed when the speed is within a certain range. */ public Shooter() { flywheel = new CANTalon(RobotMap.flyWheelTalonPort); // flywheel.reverseOutput(false); // flywheel.reverseSensor(true); flywheel.setFeedbackDevice(FeedbackDevice.QuadEncoder); flywheel.setSafetyEnabled(false); flywheel.enableBrakeMode(false); flywheel.setAllowableClosedLoopErr(Constants.SHOOTER_TOLERANCE); flywheel.enable(); spinDown(); } /** * Sets the default command for the Shooter. Nothing is done to the shooter * until commands are called, so no default command must be specified. */ public void initDefaultCommand() { } /** * Set the Talon to its set speed. In this case, it's 95% of the maximum * velocity so that it doesn't drop over the course of a match */ public void spinUp() { double speed = SmartDashboard.getNumber("flywheel power"); flywheel.changeControlMode(TalonControlMode.Speed); // flywheel.set(-Constants.SHOOTER_SET_SPEED * Constants.SHOOTER_MAX_SPEED); } /** * Stop the flywheel Talon. It is put into PercentVbus mode and allowed to * coast to a stop. */ public void spinDown() { flywheel.changeControlMode(TalonControlMode.PercentVbus); flywheel.set(0.0); } /** * Gets the current speed of the flywheel, on a scale from 0.0 to 1.0. * * @return the current flywheel speed. */ public double getSpeed() { return -flywheel.getSpeed() / Constants.SHOOTER_MAX_SPEED; } /** * Gets the amperage going through the flywheel motor. Used to see if it's * too high. * * @return the output current of the flywheel Talon. */ public double getCurrent() { return flywheel.getOutputCurrent(); } /** * Return whether or not the measured speed is within tolerance of our * target value. This means we can fire when ready. * * @return Whether or not the measured speed is within tolerance of the * target */ public boolean isSpunUp() { return getSpeed() > 0.5 && Math.abs(flywheel.getError()) <= Constants.SHOOTER_TOLERANCE; } }
package org.wisdom.test.parents; import org.wisdom.api.http.Context; import org.wisdom.api.http.Result; import org.wisdom.api.http.Results; /** * Allow configuring an invocation of an action. */ public class Action { /** * The invocation. */ private final Invocation invocation; /** * The fake context. */ private final FakeContext context; /** * Creates an invocation. * * @param invocation the invocation */ public Action(Invocation invocation) { this.invocation = invocation; this.context = new FakeContext(); } /** * Gets a new action using the given invocation. * * @param invocation the invocation * @return the new action */ public static Action action(Invocation invocation) { return new Action(invocation); } /** * Just there for cosmetic reason. * * @return the current action */ public Action with() { return this; } /** * Sets a parameter. * * @param name the parameter name * @param value the parameter value * @return the current action */ public Action parameter(String name, String value) { context.setParameter(name, value); return this; } /** * Sets the body. * * @param object the body * @return the current action */ public Action body(Object object) { context.setBody(object); return this; } /** * Sets a parameter. * * @param name the parameter name * @param value the parameter value * @return the current action */ public Action parameter(String name, int value) { context.setParameter(name, Integer.toString(value)); return this; } /** * Sets a parameter. * * @param name the parameter name * @param value the parameter value * @return the current action */ public Action parameter(String name, boolean value) { context.setParameter(name, Boolean.toString(value)); return this; } /** * Sets a parameter. * * @param name the parameter name * @param value the parameter value * @return the current action */ public Action attribute(String name, String value) { context.setAttribute(name, value); return this; } /** * Sets a header. * * @param name the header name * @param value the header value * @return the current action */ public Action header(String name, String value) { context.setHeader(name, value); return this; } /** * Invokes the configured action. * * @return the result */ public ActionResult invoke() { // Set the fake context. Context.CONTEXT.set(context); // Create the request // Invoke try { return new ActionResult( invocation.invoke(), context); } catch (Throwable e) { //NOSONAR return new ActionResult(Results.internalServerError(e), context); } finally { Context.CONTEXT.remove(); } } /** * Action's result. */ public static class ActionResult { private final Result result; private final Context context; /** * Creates a new action result. * * @param result the result * @param context the context */ public ActionResult(Result result, Context context) { this.result = result; this.context = context; } /** * Gets the result. * * @return the result */ public Result getResult() { return result; } /** * Gets the context. * * @return the context */ public Context getContext() { return context; } } }
/* * $Log: ReceiverBase.java,v $ * Revision 1.66 2008-09-23 12:05:58 europe\L190409 * send answer to separate sender for errors too * * Revision 1.65 2008/09/22 13:36:26 Gerrit van Brakel <[email protected]> * use CounterStatistics for counters * removed redundant names from statistics * * Revision 1.64 2008/09/08 07:21:34 Gerrit van Brakel <[email protected]> * support interval statistics * * Revision 1.63 2008/09/02 12:15:04 Gerrit van Brakel <[email protected]> * escaped errormessage contents * * Revision 1.62 2008/08/27 16:20:36 Gerrit van Brakel <[email protected]> * modified event registration * modified delivery count calculation * introduced queing statistics * * Revision 1.61 2008/08/18 13:15:28 Gerrit van Brakel <[email protected]> * fixed another NPE * * Revision 1.60 2008/08/18 11:20:50 Gerrit van Brakel <[email protected]> * avoid NPE in processRequest * * Revision 1.59 2008/08/13 17:50:01 Gerrit van Brakel <[email protected]> * perform PipeLineSession.setListenerParameters for processRequest() too * * Revision 1.58 2008/08/13 13:50:36 Gerrit van Brakel <[email protected]> * no changes * * Revision 1.57 2008/08/13 13:43:02 Gerrit van Brakel <[email protected]> * added numRetries * added iterateOverStatistics * * Revision 1.56 2008/08/07 11:42:38 Gerrit van Brakel <[email protected]> * removed ReceiverBaseClassic * renamed ReceiverBaseSpring into ReceiverBase * * Revision 1.31 2008/07/24 14:43:08 Gerrit van Brakel <[email protected]> * avoid NPE * * Revision 1.30 2008/07/24 12:23:05 Gerrit van Brakel <[email protected]> * fix transactional FXF * modified correlation ID calculation, should work with all listeners now * * Revision 1.29 2008/07/14 17:27:44 Gerrit van Brakel <[email protected]> * use flexible monitoring * * Revision 1.28 2008/06/30 13:42:57 Gerrit van Brakel <[email protected]> * only warn for suspension >1 sec * * Revision 1.27 2008/06/30 09:08:48 Gerrit van Brakel <[email protected]> * increase max retry interval to 10 minutes * * Revision 1.26 2008/06/24 07:59:48 Gerrit van Brakel <[email protected]> * only check for duplicates in errorStore when explicitly instructed * * Revision 1.25 2008/06/19 11:09:38 Gerrit van Brakel <[email protected]> * changed two harmless messages to critical * * Revision 1.24 2008/06/19 08:12:20 Gerrit van Brakel <[email protected]> * other message when message seen too many times * * Revision 1.23 2008/06/18 12:38:07 Gerrit van Brakel <[email protected]> * reduced suspension threshold for monitoring event from 10 to 1 minute * set default maxRetries to 1 * modified logging statements * put messages with unsuccesful ExitState in errorStorage, for non transacted receivers * no retry for non transacted receivers * * Revision 1.22 2008/05/22 07:27:45 Gerrit van Brakel <[email protected]> * set default poll interval to 10 seconds * * Revision 1.21 2008/05/21 10:51:12 Gerrit van Brakel <[email protected]> * modified monitorAdapter interface * * Revision 1.20 2008/04/17 13:03:34 Gerrit van Brakel <[email protected]> * do not drop messages that cannot be stored in errorStorage * * Revision 1.19 2008/03/28 14:23:52 Gerrit van Brakel <[email protected]> * removed 'returnIfStopped' attributes, now just throw exception * * Revision 1.18 2008/02/28 16:25:01 Gerrit van Brakel <[email protected]> * modified handling of Business Correlation ID * * Revision 1.17 2008/02/22 14:33:37 Gerrit van Brakel <[email protected]> * added feature to extract correlationId from message * * Revision 1.16 2008/02/08 09:49:22 Gerrit van Brakel <[email protected]> * cacheProcessResult for non-transacted too * * Revision 1.15 2008/02/07 11:47:24 Gerrit van Brakel <[email protected]> * removed unnessecary cast to serializable * * Revision 1.14 2008/02/06 16:01:34 Gerrit van Brakel <[email protected]> * added support for setting of transaction timeout * * Revision 1.13 2008/01/29 12:16:16 Gerrit van Brakel <[email protected]> * added support for thread number control * call afterMessageProcessed after moving to error store under XA * * Revision 1.12 2008/01/18 13:49:22 Gerrit van Brakel <[email protected]> * transacted: once and only once, move to error in same transaction * * Revision 1.11 2008/01/17 16:16:24 Gerrit van Brakel <[email protected]> * added attribute checkForDuplicates * * Revision 1.10 2008/01/11 14:54:40 Gerrit van Brakel <[email protected]> * added retry function * * Revision 1.9 2008/01/11 10:22:20 Gerrit van Brakel <[email protected]> * corrected receiver.isOnErrorStop to isOnErrorContinue * corrected transaction handling * reduced default maxRetries to 2 * * Revision 1.8 2007/12/10 10:20:57 Gerrit van Brakel <[email protected]> * added monitoring * fixed poisonMessage handling * * Revision 1.7 2007/11/23 14:18:31 Gerrit van Brakel <[email protected]> * progagate transacted attribute to Jms and Jdbc Listeners * * Revision 1.6 2007/11/22 13:36:53 Gerrit van Brakel <[email protected]> * improved logging * * Revision 1.5 2007/11/05 13:06:55 Tim van der Leeuw <[email protected]> * Rename and redefine methods in interface IListenerConnector to remove 'jms' from names * * Revision 1.4 2007/10/23 12:58:23 Tim van der Leeuw <[email protected]> * Improve changing InProcessStorage to ErrorStorge: Do it before propagating names, and add logging * * Revision 1.3 2007/10/22 13:24:54 Tim van der Leeuw <[email protected]> * Restore the ability to use the in-process storage as error-storage. * * Revision 1.2 2007/10/18 15:56:48 Gerrit van Brakel <[email protected]> * added pollInterval attribute * * Revision 1.1 2007/10/16 13:02:09 Tim van der Leeuw <[email protected]> * Add ReceiverBaseSpring from EJB branch * * Revision 1.44.2.12 2007/09/28 13:38:13 Tim van der Leeuw <[email protected]> * Remove unnecessary cast and fix type-name on some JavaDoc * * Revision 1.44.2.11 2007/09/28 10:50:29 Tim van der Leeuw <[email protected]> * Updates for more robust and correct transaction handling * Update Xerces dependency to modern Xerces * * Revision 1.44.2.10 2007/09/26 14:59:03 Tim van der Leeuw <[email protected]> * Updates for more robust and correct transaction handling * * Revision 1.44.2.9 2007/09/26 06:05:18 Tim van der Leeuw <[email protected]> * Add exception-propagation to new JMS Listener; increase robustness of JMS configuration * * Revision 1.44.2.8 2007/09/21 14:22:15 Tim van der Leeuw <[email protected]> * Apply a number of fixes so that the framework starts again * * Revision 1.44.2.7 2007/09/21 13:48:59 Tim van der Leeuw <[email protected]> * Enhancement to checking ErrorStorage for known bad messages: internal in-memory cache of bad messages which is checked always, even if there is no ErrorStorage for the receiver. * This should help to protect against poison-messages when a Receiver does not have an ErrorStorage. * * Revision 1.44.2.6 2007/09/21 13:23:34 Tim van der Leeuw <[email protected]> * * Add method to ITransactionalStorage to check if original message ID can be found in it * * Check for presence of original message id in ErrorStorage before processing, so it can be removed from queue if it has already once been recorded as unprocessable (but the TX in which it ran could no longer be committed). * * Revision 1.44.2.5 2007/09/21 12:29:34 Tim van der Leeuw <[email protected]> * Move threaded processing from ReceiverBase into new class, PullingListenerContainer, to get better seperation of concerns. * * Revision 1.44.2.4 2007/09/21 09:20:34 Tim van der Leeuw <[email protected]> * * Remove UserTransaction from Adapter * * Remove InProcessStorage; refactor a lot of code in Receiver * * Revision 1.44.2.3 2007/09/19 14:19:43 Tim van der Leeuw <[email protected]> * * More objects from Spring Factory * * Fixes for Spring JMS Container * * Quartz Scheduler from Spring Factory * * Revision 1.44.2.2 2007/09/18 11:20:38 Tim van der Leeuw <[email protected]> * * Update a number of method-signatures to take a java.util.Map instead of HashMap * * Rewrite JmsListener to be instance of IPushingListener; use Spring JMS Container * * Revision 1.44.2.1 2007/09/13 13:27:17 Tim van der Leeuw <[email protected]> * First commit of work to use Spring for creating objects * * Revision 1.44 2007/08/27 11:51:43 Gerrit van Brakel <[email protected]> * modified afterMessageProcessed handling * added attribute 'returnedSessionKeys' * * Revision 1.43 2007/08/10 11:21:49 Gerrit van Brakel <[email protected]> * catch more exceptions * * Revision 1.42 2007/06/26 12:06:08 Gerrit van Brakel <[email protected]> * tuned logging * * Revision 1.41 2007/06/26 06:56:59 Gerrit van Brakel <[email protected]> * set inProcessStorage type to 'E' if combined with errorStorage * * Revision 1.40 2007/06/21 07:07:06 Gerrit van Brakel <[email protected]> * removed warnings about not transacted=true * * Revision 1.39 2007/06/19 12:07:32 Gerrit van Brakel <[email protected]> * modifiy retryinterval handling * * Revision 1.38 2007/06/14 08:49:35 Gerrit van Brakel <[email protected]> * catch less specific types of exception * * Revision 1.37 2007/06/12 11:24:04 Gerrit van Brakel <[email protected]> * corrected typeSettings of transactional storages * * Revision 1.36 2007/06/08 12:49:03 Gerrit van Brakel <[email protected]> * updated javadoc * * Revision 1.35 2007/06/08 12:17:40 Gerrit van Brakel <[email protected]> * improved error handling * introduced retry mechanisme with increasing wait interval * * Revision 1.34 2007/06/08 07:49:13 Gerrit van Brakel <[email protected]> * changed error to warning * * Revision 1.33 2007/06/07 15:22:44 Gerrit van Brakel <[email protected]> * made stopping after receiving an exception configurable * * Revision 1.32 2007/05/23 09:25:17 Gerrit van Brakel <[email protected]> * added support for attribute 'active' on transactional storages * * Revision 1.31 2007/05/21 12:22:47 Gerrit van Brakel <[email protected]> * added setMessageLog() * * Revision 1.30 2007/05/02 11:37:51 Gerrit van Brakel <[email protected]> * added attribute 'active' * * Revision 1.29 2007/02/12 14:03:45 Gerrit van Brakel <[email protected]> * Logger from LogUtil * * Revision 1.28 2007/02/05 15:01:44 Gerrit van Brakel <[email protected]> * configure inProcessStorage when it is present, not only when transacted * * Revision 1.27 2006/12/13 16:30:41 Gerrit van Brakel <[email protected]> * added maxRetries to configuration javadoc * * Revision 1.26 2006/08/24 07:12:42 Gerrit van Brakel <[email protected]> * documented METT tracing event numbers * * Revision 1.25 2006/06/20 14:10:43 Gerrit van Brakel <[email protected]> * added stylesheet attribute * * Revision 1.24 2006/04/12 16:17:43 Gerrit van Brakel <[email protected]> * retry after failed storing of message in inProcessStorage * * Revision 1.23 2006/02/20 15:42:41 Gerrit van Brakel <[email protected]> * moved METT-support to single entry point for tracing * * Revision 1.22 2006/02/09 07:57:47 Gerrit van Brakel <[email protected]> * METT tracing support * * Revision 1.21 2005/10/27 08:46:45 Gerrit van Brakel <[email protected]> * introduced RunStateEnquiries * * Revision 1.20 2005/10/26 08:52:31 Gerrit van Brakel <[email protected]> * allow for transacted="true" without inProcessStorage, (ohne Gew?hr!) * * Revision 1.19 2005/10/17 11:29:24 Gerrit van Brakel <[email protected]> * fixed nullpointerexception in startRunning * * Revision 1.18 2005/09/26 11:42:10 Gerrit van Brakel <[email protected]> * added fileNameIfStopped attribute and replace from/to processing when stopped * * Revision 1.17 2005/09/13 15:42:14 Gerrit van Brakel <[email protected]> * improved handling of non-serializable messages like Poison-messages * * Revision 1.16 2005/08/08 09:44:11 Gerrit van Brakel <[email protected]> * start transactions if needed and not already started * * Revision 1.15 2005/07/19 15:27:14 Gerrit van Brakel <[email protected]> * modified closing procedure * added errorStorage * modified implementation of transactionalStorage * allowed exceptions to bubble up * assume rawmessages to be serializable for transacted processing * added ibis42compatibility attribute, avoiding exception bubbling * * Revision 1.14 2005/07/05 12:54:38 Gerrit van Brakel <[email protected]> * allow to set parameters from context for processRequest() methods * * Revision 1.13 2005/06/02 11:52:24 Gerrit van Brakel <[email protected]> * limited number of actively polling threads to value of attriubte numThreadsPolling * * Revision 1.12 2005/04/13 12:53:09 Gerrit van Brakel <[email protected]> * removed unused imports * * Revision 1.11 2005/03/31 08:22:49 Gerrit van Brakel <[email protected]> * fixed bug in getIdleStatistics * * Revision 1.10 2005/03/07 11:04:36 Johan Verrips <[email protected]> * PipeLineSession became a extension of Map, using other iterator * * Revision 1.9 2005/03/04 08:53:29 Johan Verrips <[email protected]> * Fixed IndexOutOfBoundException in getProcessStatistics due to multi threading. * Adjusted this too for getIdleStatistics * * Revision 1.8 2005/02/10 08:17:34 Gerrit van Brakel <[email protected]> * included context dump in debug * * Revision 1.7 2005/01/13 08:56:04 Gerrit van Brakel <[email protected]> * Make threadContext-attributes available in PipeLineSession * * Revision 1.6 2004/10/12 15:14:11 Gerrit van Brakel <[email protected]> * removed unused code * * Revision 1.5 2004/08/25 09:11:33 unknown <[email protected]> * Add waitForRunstate with timeout * * Revision 1.4 2004/08/23 13:10:48 Gerrit van Brakel <[email protected]> * updated JavaDoc * * Revision 1.3 2004/08/16 14:09:58 unknown <[email protected]> * Return returnIfStopped value in case adapter is stopped * * Revision 1.2 2004/08/09 13:46:52 Gerrit van Brakel <[email protected]> * various changes * * Revision 1.1 2004/08/03 13:04:30 Gerrit van Brakel <[email protected]> * introduction of GenericReceiver * */ package nl.nn.adapterframework.receivers; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.Map.Entry; import javax.xml.transform.TransformerConfigurationException; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.Adapter; import nl.nn.adapterframework.core.HasPhysicalDestination; import nl.nn.adapterframework.core.HasSender; import nl.nn.adapterframework.core.IAdapter; import nl.nn.adapterframework.core.IBulkDataListener; import nl.nn.adapterframework.core.IKnowsDeliveryCount; import nl.nn.adapterframework.core.IListener; import nl.nn.adapterframework.core.IMessageHandler; import nl.nn.adapterframework.core.INamedObject; import nl.nn.adapterframework.core.IPortConnectedListener; import nl.nn.adapterframework.core.IPullingListener; import nl.nn.adapterframework.core.IPushingListener; import nl.nn.adapterframework.core.IReceiver; import nl.nn.adapterframework.core.IReceiverStatistics; import nl.nn.adapterframework.core.ISender; import nl.nn.adapterframework.core.IThreadCountControllable; import nl.nn.adapterframework.core.ITransactionalStorage; import nl.nn.adapterframework.core.IbisExceptionListener; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.core.PipeLineResult; import nl.nn.adapterframework.core.PipeLineSession; import nl.nn.adapterframework.core.SenderException; import nl.nn.adapterframework.jdbc.JdbcFacade; import nl.nn.adapterframework.jms.JMSFacade; import nl.nn.adapterframework.monitoring.EventHandler; import nl.nn.adapterframework.monitoring.EventThrowing; import nl.nn.adapterframework.monitoring.MonitorManager; import nl.nn.adapterframework.util.Counter; import nl.nn.adapterframework.util.DateUtils; import nl.nn.adapterframework.util.HasStatistics; import nl.nn.adapterframework.util.LogUtil; import nl.nn.adapterframework.util.Misc; import nl.nn.adapterframework.util.RunStateEnquiring; import nl.nn.adapterframework.util.RunStateEnum; import nl.nn.adapterframework.util.RunStateManager; import nl.nn.adapterframework.util.CounterStatistic; import nl.nn.adapterframework.util.StatisticsKeeper; import nl.nn.adapterframework.util.StatisticsKeeperIterationHandler; import nl.nn.adapterframework.util.TracingEventNumbers; import nl.nn.adapterframework.util.TransformerPool; import nl.nn.adapterframework.util.XmlUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.apache.log4j.Logger; import org.apache.log4j.NDC; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.core.task.TaskExecutor; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionException; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; /** * This {@link IReceiver Receiver} may be used as a base-class for developing receivers. * * <p><b>Configuration:</b> * <table border="1"> * <tr><th>attributes</th><th>description</th><th>default</th></tr> * <tr><td>classname</td><td>name of the class, mostly a class that extends this class</td><td>&nbsp;</td></tr> * <tr><td>{@link #setName(String) name}</td> <td>name of the receiver as known to the adapter</td><td>&nbsp;</td></tr> * <tr><td>{@link #setActive(boolean) active}</td> <td>when set <code>false</code> or set to something else as "true", (even set to the empty string), the receiver is not included in the configuration</td><td>true</td></tr> * <tr><td>{@link #setNumThreads(int) numThreads}</td><td>the number of threads that may execute a pipeline concurrently (only for pulling listeners)</td><td>1</td></tr> * <tr><td>{@link #setNumThreadsPolling(int) numThreadsPolling}</td><td>the number of threads that are activily polling for messages concurrently. '0' means 'limited only by <code>numThreads</code>' (only for pulling listeners)</td><td>1</td></tr> * <tr><td>{@link #setOnError(String) onError}</td><td>one of 'continue' or 'close'. Controls the behaviour of the receiver when it encounters an error sending a reply or receives an exception asynchronously</td><td>continue</td></tr> * <tr><td>{@link #setReturnedSessionKeys(String) returnedSessionKeys}</td><td>comma separated list of keys of session variables that should be returned to caller, for correct results as well as for erronous results. (Only for listeners that support it, like JavaListener)</td><td>&nbsp;</td></tr> * <tr><td>{@link #setTransacted(boolean) transacted}</td><td>if set to <code>true</code>, messages will be received and processed under transaction control. If processing fails, messages will be sent to the error-sender. (see below)</code></td><td><code>false</code></td></tr> * <tr><td>{@link #setTransactionTimeout(int) transactionTimeout}</td><td>Timeout (in seconds) of transaction started to receive and process a message.</td><td><code>0</code> (use system default)</code></td></tr> * <tr><td>{@link #setMaxRetries(int) maxRetries}</td><td>The number of times a processing attempt is retried after an exception is caught or rollback is experienced</td><td>1</td></tr> * <tr><td>{@link #setCheckForDuplicates(boolean) checkForDuplicates}</td><td>if set to <code>true</code>, each message is checked for presence in the message log. If already present, it is not processed again. (only required for non XA compatible messaging). Requires messagelog!</code></td><td><code>false</code></td></tr> * <tr><td>{@link #setPollInterval(int) pollInterval}</td><td>The number of seconds waited after an unsuccesful poll attempt before another poll attempt is made. (only for polling listeners, not for e.g. IFSA, JMS, WebService or JavaListeners)</td><td>10</td></tr> * <tr><td>{@link #setIbis42compatibility(boolean) ibis42compatibility}</td><td>if set to <code>true</code>, the result of a failed processing of a message is a formatted errormessage. Otherwise a listener specific error handling is performed</code></td><td><code>false</code></td></tr> * <tr><td>{@link #setBeforeEvent(int) beforeEvent}</td> <td>METT eventnumber, fired just before a message is processed by this Receiver</td><td>-1 (disabled)</td></tr> * <tr><td>{@link #setAfterEvent(int) afterEvent}</td> <td>METT eventnumber, fired just after message processing by this Receiver is finished</td><td>-1 (disabled)</td></tr> * <tr><td>{@link #setExceptionEvent(int) exceptionEvent}</td><td>METT eventnumber, fired when message processing by this Receiver resulted in an exception</td><td>-1 (disabled)</td></tr> * <tr><td>{@link #setCorrelationIDXPath(String) correlationIDXPath}</td><td>xpath expression to extract correlationID from message</td><td>&nbsp;</td></tr> * </table> * </p> * <p> * <table border="1"> * <tr><th>nested elements (accessible in descender-classes)</th><th>description</th></tr> * <tr><td>{@link nl.nn.adapterframework.core.IPullingListener listener}</td><td>the listener used to receive messages from</td></tr> * <tr><td>{@link nl.nn.adapterframework.core.ITransactionalStorage inProcessStorage}</td><td>mandatory for {@link #setTransacted(boolean) transacted} receivers: place to store messages during processing.</td></tr> * <tr><td>{@link nl.nn.adapterframework.core.ITransactionalStorage errorStorage}</td><td>optional for {@link #setTransacted(boolean) transacted} receivers: place to store messages if message processing has gone wrong. If no errorStorage is specified, the inProcessStorage is used for errorStorage</td></tr> * <tr><td>{@link nl.nn.adapterframework.core.ISender errorSender}</td><td>optional for {@link #setTransacted(boolean) transacted} receviers: * will be called to store messages that failed to process. If no errorSender is specified, failed messages will remain in inProcessStorage</td></tr> * </table> * </p> * <p><b>Transaction control</b><br> * If {@link #setTransacted(boolean) transacted} is set to <code>true</code>, messages will be received and processed under transaction control. * This means that after a message has been read and processed and the transaction has ended, one of the following apply: * <ul> * <table border="1"> * <tr><th>situation</th><th>input listener</th><th>Pipeline</th><th>inProcess storage</th><th>errorSender</th><th>summary of effect</th></tr> * <tr><td>successful</td><td>message read and committed</td><td>message processed</td><td>unchanged</td><td>unchanged</td><td>message processed</td></tr> * <tr><td>procesing failed</td><td>message read and committed</td><td>message processing failed and rolled back</td><td>unchanged</td><td>message sent</td><td>message only transferred from listener to errroSender</td></tr> * <tr><td>listening failed</td><td>unchanged: listening rolled back</td><td>no processing performed</td><td>unchanged</td><td>unchanged</td><td>no changes, input message remains on input available for listener</td></tr> * <tr><td>transfer to inprocess storage failed</td><td>unchanged: listening rolled back</td><td>no processing performed</td><td>unchanged</td><td>unchanged</td><td>no changes, input message remains on input available for listener</td></tr> * <tr><td>transfer to errorSender failed</td><td>message read and committed</td><td>message processing failed and rolled back</td><td>message present</td><td>unchanged</td><td>message only transferred from listener to inProcess storage</td></tr> * </table> * If the application or the server crashes in the middle of one or more transactions, these transactions * will be recovered and rolled back after the server/application is restarted. Then allways exactly one of * the following applies for any message touched at any time by Ibis by a transacted receiver: * <ul> * <li>It is processed correctly by the pipeline and removed from the input-queue, * not present in inProcess storage and not send to the errorSender</li> * <li>It is not processed at all by the pipeline, or processing by the pipeline has been rolled back; * the message is removed from the input queue and either (one of) still in inProcess storage <i>or</i> sent to the errorSender</li> * </ul> * </p> * * <p><b>commit or rollback</b><br> * If {@link #setTransacted(boolean) transacted} is set to <code>true</code>, messages will be either committed or rolled back. * All message-processing transactions are committed, unless one or more of the following apply: * <ul> * <li>The PipeLine is transacted and the exitState of the pipeline is not equal to {@link nl.nn.adapterframework.core.PipeLine#setCommitOnState(String) commitOnState} (that defaults to 'success')</li> * <li>a PipeRunException or another runtime-exception has been thrown by any Pipe or by the PipeLine</li> * <li>the setRollBackOnly() method has been called on the userTransaction (not accessible by Pipes)</li> * </ul> * </p> * * @version Id * @author Gerrit van Brakel * @since 4.2 */ public class ReceiverBase implements IReceiver, IReceiverStatistics, IMessageHandler, EventThrowing, IbisExceptionListener, HasSender, HasStatistics, TracingEventNumbers, IThreadCountControllable, BeanFactoryAware { public static final String version="$RCSfile: ReceiverBase.java,v $ $Revision: 1.66 $ $Date: 2008-09-23 12:05:58 $"; protected Logger log = LogUtil.getLogger(this); public final static TransactionDefinition TXNEW = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW); public final static TransactionDefinition TXREQUIRED = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED); public final static TransactionDefinition TXSUPPORTS = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_SUPPORTS); public static final String RCV_CONFIGURED_MONITOR_EVENT = "Receiver Configured"; public static final String RCV_CONFIGURATIONEXCEPTION_MONITOR_EVENT = "Exception Configuring Receiver"; public static final String RCV_STARTED_RUNNING_MONITOR_EVENT = "Receiver Started Running"; public static final String RCV_SHUTDOWN_MONITOR_EVENT = "Receiver Shutdown"; public static final String RCV_SUSPENDED_MONITOR_EVENT = "Receiver Operation Suspended"; public static final String RCV_RESUMED_MONITOR_EVENT = "Receiver Operation Resumed"; public static final String RCV_THREAD_EXIT_MONITOR_EVENT = "Receiver Thread Exited"; public static final String RCV_MESSAGE_TO_ERRORSTORE_EVENT = "Receiver Moved Message to ErrorStorage"; public static final int RCV_SUSPENSION_MESSAGE_THRESHOLD=60; public static final int MAX_RETRY_INTERVAL=600; private boolean suspensionMessagePending=false; private BeanFactory beanFactory; private int pollInterval=10; private String returnedSessionKeys=null; private boolean checkForDuplicates=false; private String correlationIDXPath; public static final String ONERROR_CONTINUE = "continue"; public static final String ONERROR_CLOSE = "close"; private boolean active=true; private int transactionTimeout=0; private String name; private String onError = ONERROR_CONTINUE; protected RunStateManager runState = new RunStateManager(); private boolean ibis42compatibility=false; // the number of threads that may execute a pipeline concurrently (only for pulling listeners) private int numThreads = 1; // the number of threads that are activily polling for messages (concurrently, only for pulling listeners) private int numThreadsPolling = 1; private PullingListenerContainer listenerContainer; private Counter threadsProcessing = new Counter(0); // number of messages received private CounterStatistic numReceived = new CounterStatistic(0); private CounterStatistic numRetried = new CounterStatistic(0); // private ScalarStatistic numRejected = new ScalarStatistic(0); private List processStatistics = new ArrayList(); private List idleStatistics = new ArrayList(); private List queueingStatistics; // private StatisticsKeeper requestSizeStatistics = new StatisticsKeeper("request size"); // private StatisticsKeeper responseSizeStatistics = new StatisticsKeeper("response size"); // the adapter that handles the messages and initiates this listener private IAdapter adapter; private IListener listener; private ISender errorSender=null; private ITransactionalStorage errorStorage=null; // See configure() for explanation on this field private ITransactionalStorage tmpInProcessStorage=null; private ISender sender=null; // answer-sender private ITransactionalStorage messageLog=null; private int maxRetries=1; private boolean transacted=false; private TransformerPool correlationIDTp=null; // METT event numbers private int beforeEvent=-1; private int afterEvent=-1; private int exceptionEvent=-1; int retryInterval=1; private int poisonMessageIdCacheSize = 100; private int processResultCacheSize = 100; private PlatformTransactionManager txManager; private EventHandler eventHandler=null; /** * The thread-pool for spawning threads, injected by Spring */ private TaskExecutor taskExecutor; /** * Map containing message-ids which are currently being processed. */ private Map messageRetryCounters = new HashMap(); /** * The cache for poison messages acts as a sort of poor-mans error * storage and is always available, even if an error-storage is not. * Thus messages might be lost if they cannot be put in the error * storage, but unless the server crashes, a message that has been * put in the poison-cache will not be reprocessed even if it's * offered again. */ private LinkedHashMap poisonMessageIdCache = new LinkedHashMap() { protected boolean removeEldestEntry(Entry eldest) { return size() > getPoisonMessageIdCacheSize(); } }; private LinkedHashMap processResultCache = new LinkedHashMap() { protected boolean removeEldestEntry(Entry eldest) { return size() > getProcessResultCacheSize(); } }; private class ProcessResultCacheItem { int tryCount; Date receiveDate; String correlationId; String comments; } private PipeLineSession createProcessingContext(String correlationId, Map threadContext, String messageId) { PipeLineSession pipelineSession = new PipeLineSession(); if (threadContext != null) { pipelineSession.putAll(threadContext); if (log.isDebugEnabled()) { String contextDump = "PipeLineSession variables for messageId [" + messageId + "] correlationId [" + correlationId + "]:"; for (Iterator it = pipelineSession.keySet().iterator(); it.hasNext();) { String key = (String) it.next(); Object value = pipelineSession.get(key); if (key.equals("messageText")) { value = "(... see elsewhere ...)"; } contextDump += " " + key + "=[" + String.valueOf(value) + "]"; } log.debug(getLogPrefix()+contextDump); } } return pipelineSession; } private TransactionStatus getTransactionForProcessing() throws ListenerException { TransactionStatus txStatus; // Latch on to existing TX, or start new one if needed // We prefer _not_ do to any transaction-management on this, // but we want to enquire on the status of the TX. try { if (isTransacted()) { txStatus = txManager.getTransaction(TXREQUIRED); } else { txStatus = txManager.getTransaction(TXSUPPORTS); } if (txStatus.isNewTransaction()) { log.debug(getLogPrefix()+"started transaction as no one was yet present"); } } catch (TransactionException e) { throw new ListenerException(getLogPrefix()+"Exception obtaining Spring transaction", e); } return txStatus; } private void putSessionKeysIntoThreadContext(Map threadContext, PipeLineSession pipelineSession) { if (StringUtils.isNotEmpty(getReturnedSessionKeys()) && threadContext != null) { if (log.isDebugEnabled()) { log.debug(getLogPrefix()+"setting returned session keys [" + getReturnedSessionKeys() + "]"); } StringTokenizer st = new StringTokenizer(getReturnedSessionKeys(), " ,;"); while (st.hasMoreTokens()) { String key = st.nextToken(); Object value = pipelineSession.get(key); if (log.isDebugEnabled()) { log.debug(getLogPrefix()+"returning session key [" + key + "] value [" + value + "]"); } threadContext.put(key, value); } } } protected String getLogPrefix() { return "Receiver ["+getName()+"] "; } /** * sends an informational message to the log and to the messagekeeper of the adapter */ protected void info(String msg) { log.info(msg); if (adapter != null) adapter.getMessageKeeper().add(msg); } /** * sends a warning to the log and to the messagekeeper of the adapter */ protected void warn(String msg) { log.warn(msg); if (adapter != null) adapter.getMessageKeeper().add("WARNING: " + msg); } /** * sends a warning to the log and to the messagekeeper of the adapter */ protected void error(String msg, Throwable t) { log.error(msg, t); if (adapter != null) adapter.getMessageKeeper().add("ERROR: " + msg+(t!=null?": "+t.getMessage():"")); } protected void openAllResources() throws ListenerException { // on exit resouces must be in a state that runstate is or can be set to 'STARTED' try { if (getSender()!=null) { getSender().open(); } if (getErrorSender()!=null) { getErrorSender().open(); } if (getErrorStorage()!=null) { getErrorStorage().open(); } if (getMessageLog()!=null) { getMessageLog().open(); } } catch (SenderException e) { throw new ListenerException(e); } getListener().open(); throwEvent(RCV_STARTED_RUNNING_MONITOR_EVENT); if (getListener() instanceof IPullingListener){ // start all threads if (getNumThreads() > 1) { for (int i = 1; i <= getNumThreads(); i++) { addThread("[" + i+"]"); } } else { addThread(""); } } } private void addThread(String nameSuffix) { if (getListener() instanceof IPullingListener){ //Thread t = new Thread(this, getName() + (nameSuffix==null ? "" : nameSuffix)); //t.start(); taskExecutor.execute(listenerContainer); } } protected void tellResourcesToStop() throws ListenerException { // must lead to a 'closeAllResources()' // runstate is 'STOPPING' // default just calls 'closeAllResources()' if (getListener() instanceof IPushingListener) { closeAllResources(); } // IPullingListeners stop as their threads finish, as the runstate is set to stopping } protected void closeAllResources() { // on exit resouces must be in a state that runstate can be set to 'STOPPED' try { log.debug(getLogPrefix()+"closing"); getListener().close(); if (getSender()!=null) { getSender().close(); } if (getErrorSender()!=null) { getErrorSender().close(); } if (getErrorStorage()!=null) { getErrorStorage().close(); } if (getMessageLog()!=null) { getMessageLog().close(); } log.debug(getLogPrefix()+"closed"); } catch (Exception e) { error(getLogPrefix()+"error closing connection", e); } runState.setRunState(RunStateEnum.STOPPED); throwEvent(RCV_SHUTDOWN_MONITOR_EVENT); resetRetryInterval(); info(getLogPrefix()+"stopped"); } protected void propagateName() { IListener listener=getListener(); if (listener!=null && StringUtils.isEmpty(listener.getName())) { listener.setName("listener of ["+getName()+"]"); } ISender errorSender = getErrorSender(); if (errorSender != null) { errorSender.setName("errorSender of ["+getName()+"]"); } ITransactionalStorage errorStorage = getErrorStorage(); if (errorStorage != null) { errorStorage.setName("errorStorage of ["+getName()+"]"); } ISender answerSender = getSender(); if (answerSender != null) { answerSender.setName("answerSender of ["+getName()+"]"); } } public void configure() throws ConfigurationException { try { eventHandler = MonitorManager.getEventHandler(); registerEvent(RCV_CONFIGURED_MONITOR_EVENT); registerEvent(RCV_CONFIGURATIONEXCEPTION_MONITOR_EVENT); registerEvent(RCV_STARTED_RUNNING_MONITOR_EVENT); registerEvent(RCV_SHUTDOWN_MONITOR_EVENT); registerEvent(RCV_SUSPENDED_MONITOR_EVENT); registerEvent(RCV_RESUMED_MONITOR_EVENT); registerEvent(RCV_THREAD_EXIT_MONITOR_EVENT); // Check if we need to use the in-process storage as // error-storage. // In-process storage is no longer used, but is often // still configured to be used as error-storage. // The rule is: // 1. if error-storage is configured, use it. // 2. If error-storage is not configure but an error-sender is, // then use the error-sender. // 3. If neither error-storage nor error-sender are configured, // but the in-process storage is, then use the in-process storage // for error-storage. // Member variables are accessed directly, to avoid any possible // aliasing-effects applied by getter methods. (These have been // removed for now, but since the getter-methods were not // straightforward in the earlier versions, I felt it was safer // to use direct member variables). if (this.tmpInProcessStorage != null) { if (this.errorSender == null && this.errorStorage == null) { this.errorStorage = this.tmpInProcessStorage; info(getLogPrefix()+"has errorStorage in inProcessStorage, setting inProcessStorage's type to 'errorStorage'. Please update the configuration to change the inProcessStorage element to an errorStorage element, since the inProcessStorage is no longer used."); errorStorage.setType("E"); } else { info(getLogPrefix()+"has inProcessStorage defined but also has an errorStorage or errorSender. InProcessStorage is not used and can be removed from the configuration."); } // Set temporary in-process storage pointer to null this.tmpInProcessStorage = null; } // Do propagate-name AFTER changing the errorStorage! propagateName(); if (getListener()==null) { throw new ConfigurationException(getLogPrefix()+"has no listener"); } if (getListener() instanceof IPushingListener) { IPushingListener pl = (IPushingListener)getListener(); pl.setHandler(this); pl.setExceptionListener(this); } if (getListener() instanceof IPortConnectedListener) { IPortConnectedListener pcl = (IPortConnectedListener) getListener(); pcl.setReceiver(this); } if (getListener() instanceof IPullingListener) { setListenerContainer(createListenerContainer()); } if (getListener() instanceof JdbcFacade) { ((JdbcFacade)getListener()).setTransacted(isTransacted()); } if (getListener() instanceof JMSFacade) { ((JMSFacade)getListener()).setTransacted(isTransacted()); } getListener().configure(); if (getListener() instanceof HasPhysicalDestination) { info(getLogPrefix()+"has listener on "+((HasPhysicalDestination)getListener()).getPhysicalDestinationName()); } if (getListener() instanceof HasSender) { // only informational ISender sender = ((HasSender)getListener()).getSender(); if (sender instanceof HasPhysicalDestination) { info("Listener of receiver ["+getName()+"] has answer-sender on "+((HasPhysicalDestination)sender).getPhysicalDestinationName()); } } ISender sender = getSender(); if (sender!=null) { sender.configure(); if (sender instanceof HasPhysicalDestination) { info(getLogPrefix()+"has answer-sender on "+((HasPhysicalDestination)sender).getPhysicalDestinationName()); } } ISender errorSender = getErrorSender(); if (errorSender!=null) { errorSender.configure(); if (errorSender instanceof HasPhysicalDestination) { info(getLogPrefix()+"has errorSender to "+((HasPhysicalDestination)errorSender).getPhysicalDestinationName()); } } ITransactionalStorage errorStorage = getErrorStorage(); if (errorStorage!=null) { errorStorage.configure(); if (errorStorage instanceof HasPhysicalDestination) { info(getLogPrefix()+"has errorStorage to "+((HasPhysicalDestination)errorStorage).getPhysicalDestinationName()); } registerEvent(RCV_MESSAGE_TO_ERRORSTORE_EVENT); } ITransactionalStorage messageLog = getMessageLog(); if (messageLog!=null) { messageLog.configure(); if (messageLog instanceof HasPhysicalDestination) { info(getLogPrefix()+"has messageLog in "+((HasPhysicalDestination)messageLog).getPhysicalDestinationName()); } } if (isTransacted()) { // if (!(getListener() instanceof IXAEnabled && ((IXAEnabled)getListener()).isTransacted())) { // warn(getLogPrefix()+"sets transacted=true, but listener not. Transactional integrity is not guaranteed"); if (errorSender==null && errorStorage==null) { warn(getLogPrefix()+"sets transacted=true, but has no errorSender or errorStorage. Messages processed with errors will be lost"); } else { // if (errorSender!=null && !(errorSender instanceof IXAEnabled && ((IXAEnabled)errorSender).isTransacted())) { // warn(getLogPrefix()+"sets transacted=true, but errorSender is not. Transactional integrity is not guaranteed"); // if (errorStorage!=null && !(errorStorage instanceof IXAEnabled && ((IXAEnabled)errorStorage).isTransacted())) { // warn(getLogPrefix()+"sets transacted=true, but errorStorage is not. Transactional integrity is not guaranteed"); } } if (StringUtils.isNotEmpty(getCorrelationIDXPath())) { try { correlationIDTp = new TransformerPool(XmlUtils.createXPathEvaluatorSource(getCorrelationIDXPath())); } catch (TransformerConfigurationException e) { throw new ConfigurationException(getLogPrefix() + "cannot create transformer for correlationID ["+getCorrelationIDXPath()+"]",e); } } if (adapter != null) { adapter.getMessageKeeper().add(getLogPrefix()+"initialization complete"); } throwEvent(RCV_CONFIGURED_MONITOR_EVENT); } catch(ConfigurationException e){ throwEvent(RCV_CONFIGURATIONEXCEPTION_MONITOR_EVENT); log.debug(getLogPrefix()+"Errors occured during configuration, setting runstate to ERROR"); runState.setRunState(RunStateEnum.ERROR); throw e; } } public void startRunning() { // if this receiver is on an adapter, the StartListening method // may only be executed when the adapter is started. if (adapter != null) { RunStateEnum adapterRunState = adapter.getRunState(); if (!adapterRunState.equals(RunStateEnum.STARTED)) { log.warn(getLogPrefix()+"on adapter [" + adapter.getName() + "] was tried to start, but the adapter is in state ["+adapterRunState+"]. Ignoring command."); adapter.getMessageKeeper().add( "ignored start command on [" + getName() + "]; adapter is in state ["+adapterRunState+"]"); return; } } try { String msg=(getLogPrefix()+"starts listening."); log.info(msg); if (adapter != null) { adapter.getMessageKeeper().add(msg); } runState.setRunState(RunStateEnum.STARTING); openAllResources(); runState.setRunState(RunStateEnum.STARTED); } catch (ListenerException e) { error(getLogPrefix()+"error occured while starting", e); runState.setRunState(RunStateEnum.ERROR); } } public void stopRunning() { if (getRunState().equals(RunStateEnum.STOPPED)){ return; } if (!getRunState().equals(RunStateEnum.ERROR)) { runState.setRunState(RunStateEnum.STOPPING); try { tellResourcesToStop(); } catch (ListenerException e) { warn("exception stopping receiver: "+e.getMessage()); } } else { closeAllResources(); runState.setRunState(RunStateEnum.STOPPED); } NDC.remove(); } protected void startProcessingMessage(long waitingDuration) { synchronized (threadsProcessing) { int threadCount = (int) threadsProcessing.getValue(); if (waitingDuration>=0) { getIdleStatistics(threadCount).addValue(waitingDuration); } threadsProcessing.increase(); } log.debug(getLogPrefix()+"starts processing message"); } protected void finishProcessingMessage(long processingDuration) { synchronized (threadsProcessing) { int threadCount = (int) threadsProcessing.decrease(); getProcessStatistics(threadCount).addValue(processingDuration); } log.debug(getLogPrefix()+"finishes processing message"); } private void moveInProcessToError(String originalMessageId, String correlationId, String message, Date receivedDate, String comments, Object rawMessage, TransactionDefinition txDef) { throwEvent(RCV_MESSAGE_TO_ERRORSTORE_EVENT); log.info(getLogPrefix()+"moves message id ["+originalMessageId+"] correlationId ["+correlationId+"] to errorSender/errorStorage"); cachePoisonMessageId(originalMessageId); ISender errorSender = getErrorSender(); ITransactionalStorage errorStorage = getErrorStorage(); if (errorSender==null && errorStorage==null) { log.warn(getLogPrefix()+"has no errorSender or errorStorage, message with id [" + originalMessageId + "] will be lost"); return; } TransactionStatus txStatus = null; try { txStatus = txManager.getTransaction(txDef); } catch (Exception e) { log.error(getLogPrefix()+"Exception preparing to move input message with id [" + originalMessageId + "] to error sender", e); // no use trying again to send message on errorSender, will cause same exception! return; } try { if (errorSender!=null) { errorSender.sendMessage(correlationId, message); } Serializable sobj; if (rawMessage instanceof Serializable) { sobj=(Serializable)rawMessage; } else { try { sobj = new MessageWrapper(rawMessage, getListener()); } catch (ListenerException e) { log.error(getLogPrefix()+"could not wrap non serializable message for messageId ["+originalMessageId+"]",e); sobj=message; } } if (errorStorage!=null) { errorStorage.storeMessage(originalMessageId, correlationId, receivedDate, comments, sobj); } txManager.commit(txStatus); } catch (Exception e) { log.error(getLogPrefix()+"Exception moving message with id ["+originalMessageId+"] correlationId ["+correlationId+"] to error sender, original message: ["+message+"]",e); try { if (!txStatus.isCompleted()) { txManager.rollback(txStatus); } } catch (Exception rbe) { log.error(getLogPrefix()+"Exception while rolling back transaction for message with id ["+originalMessageId+"] correlationId ["+correlationId+"], original message: ["+message+"]", rbe); } } } /** * Process the received message with {@link #processRequest(IListener, String, String)}. * A messageId is generated that is unique and consists of the name of this listener and a GUID */ public String processRequest(IListener origin, String message) throws ListenerException { return processRequest(origin, null, message, null, -1); } public String processRequest(IListener origin, String correlationId, String message) throws ListenerException{ return processRequest(origin, correlationId, message, null, -1); } public String processRequest(IListener origin, String correlationId, String message, Map context) throws ListenerException { return processRequest(origin, correlationId, message, context, -1); } public String processRequest(IListener origin, String correlationId, String message, Map context, long waitingTime) throws ListenerException { if (getRunState() != RunStateEnum.STARTED) { throw new ListenerException(getLogPrefix()+"is not started"); } Date tsReceived = null; Date tsSent = null; if (context!=null) { tsReceived = (Date)context.get(PipeLineSession.tsReceivedKey); tsSent = (Date)context.get(PipeLineSession.tsSentKey); } else { context=new HashMap(); } PipeLineSession.setListenerParameters(context, null, correlationId, tsReceived, tsSent); return processMessageInAdapter(origin, message, message, null, correlationId, context, waitingTime, false); } public void processRawMessage(IListener origin, Object message) throws ListenerException { processRawMessage(origin, message, null, -1); } public void processRawMessage(IListener origin, Object message, Map context) throws ListenerException { processRawMessage(origin, message, context, -1); } public void processRawMessage(IListener origin, Object rawMessage, Map threadContext, long waitingDuration) throws ListenerException { processRawMessage(origin, rawMessage, threadContext, waitingDuration, false); } /** * All messages that for this receiver are pumped down to this method, so it actually * calls the {@link nl.nn.adapterframework.core.Adapter adapter} to process the message.<br/> * Assumes that a transation has been started where necessary */ private void processRawMessage(IListener origin, Object rawMessage, Map threadContext, long waitingDuration, boolean retry) throws ListenerException { if (rawMessage==null) { log.debug(getLogPrefix()+"received null message, returning directly"); return; } if (threadContext==null) { threadContext = new HashMap(); } String message = origin.getStringFromRawMessage(rawMessage, threadContext); String technicalCorrelationId = origin.getIdFromRawMessage(rawMessage, threadContext); String messageId = (String)threadContext.get("id"); processMessageInAdapter(origin, rawMessage, message, messageId, technicalCorrelationId, threadContext, waitingDuration, retry); } public void retryMessage(String messageId) throws ListenerException { if (getErrorStorage()==null) { throw new ListenerException(getLogPrefix()+"has no errorStorage, cannot retry messageId ["+messageId+"]"); } PlatformTransactionManager txManager = getTxManager(); TransactionStatus txStatus = txManager.getTransaction(TXNEW); Map threadContext = new HashMap(); Object msg=null; try { try { ITransactionalStorage errorStorage = getErrorStorage(); msg = errorStorage.getMessage(messageId); processRawMessage(getListener(), msg, threadContext, -1, true); } catch (Exception e) { txStatus.setRollbackOnly(); throw new ListenerException(e); } finally { txManager.commit(txStatus); } } catch (ListenerException e) { txStatus = txManager.getTransaction(TXNEW); try { if (msg instanceof Serializable) { String correlationId = (String)threadContext.get(PipeLineSession.businessCorrelationIdKey); String receivedDateStr = (String)threadContext.get(PipeLineSession.tsReceivedKey); Date receivedDate = DateUtils.parseToDate(receivedDateStr,DateUtils.FORMAT_FULL_GENERIC); errorStorage.deleteMessage(messageId); errorStorage.storeMessage(messageId,correlationId,receivedDate,"after retry: "+e.getMessage(),(Serializable)msg); } else { log.warn(getLogPrefix()+"retried message is not serializable, cannot update comments"); } } catch (SenderException e1) { txStatus.setRollbackOnly(); log.warn(getLogPrefix()+"could not update comments in errorStorage",e1); } finally { txManager.commit(txStatus); } throw e; } } /* * assumes message is read, and when transacted, transation is still open. */ private String processMessageInAdapter(IListener origin, Object rawMessage, String message, String messageId, String technicalCorrelationId, Map threadContext, long waitingDuration, boolean retry) throws ListenerException { String result=null; PipeLineResult pipeLineResult=null; long startProcessingTimestamp = System.currentTimeMillis(); // if (message==null) { // requestSizeStatistics.addValue(0); // } else { // requestSizeStatistics.addValue(message.length()); log.debug(getLogPrefix()+"received message with messageId ["+messageId+"] (technical) correlationId ["+technicalCorrelationId+"]"); if (StringUtils.isEmpty(messageId)) { messageId=getName()+"-"+Misc.createSimpleUUID(); if (log.isDebugEnabled()) log.debug(getLogPrefix()+"generated messageId ["+messageId+"]"); } String businessCorrelationId=technicalCorrelationId; if (correlationIDTp!=null) { try { businessCorrelationId=correlationIDTp.transform(message,null); } catch (Exception e) { throw new ListenerException(getLogPrefix()+"could not extract businessCorrelationId",e); } if (StringUtils.isEmpty(businessCorrelationId)) { if (StringUtils.isNotEmpty(technicalCorrelationId)) { log.warn(getLogPrefix()+"did not find correlationId using XpathExpression ["+getCorrelationIDXPath()+"], reverting to correlationId of transfer ["+technicalCorrelationId+"]"); businessCorrelationId=technicalCorrelationId; } else { if (StringUtils.isNotEmpty(messageId)) { log.warn(getLogPrefix()+"did not find correlationId using XpathExpression ["+getCorrelationIDXPath()+"] or technical correlationId, reverting to messageId ["+messageId+"]"); businessCorrelationId=messageId; } } } log.info(getLogPrefix()+"messageId [" + messageId + "] technicalCorrelationId [" + technicalCorrelationId + "] businessCorrelationId [" + businessCorrelationId + "]"); } if (StringUtils.isEmpty(businessCorrelationId)) { if (log.isDebugEnabled()) { log.debug(getLogPrefix()+"did not find businessCorrelationId, reverting to correlationId of transfer ["+technicalCorrelationId+"]"); } businessCorrelationId=messageId; } if (checkTryCount(messageId, retry, rawMessage, message, threadContext, businessCorrelationId)) { if (!isTransacted()) { log.warn(getLogPrefix()+"received message with messageId [" + messageId + "] which is already stored in error storage or messagelog; aborting processing"); } return result; } if (getCachedProcessResult(messageId)!=null) { numRetried.increase(); } TransactionStatus txStatus = getTransactionForProcessing(); // update processing statistics // count in processing statistics includes messages that are rolled back to input startProcessingMessage(waitingDuration); String errorMessage=""; boolean messageInError = false; try { String pipelineMessage; if (origin instanceof IBulkDataListener) { try { IBulkDataListener bdl = (IBulkDataListener)origin; pipelineMessage=bdl.retrieveBulkData(rawMessage,message,threadContext); } catch (Throwable t) { errorMessage = t.getMessage(); messageInError = true; ListenerException l = wrapExceptionAsListenerException(t); throw l; } } else { pipelineMessage=message; } numReceived.increase(); // Note: errorMessage is used to pass value from catch-clause to finally-clause! PipeLineSession pipelineSession = createProcessingContext(businessCorrelationId, threadContext, messageId); try { // TODO: What about Ibis42 compat mode? if (isIbis42compatibility()) { pipeLineResult = adapter.processMessage(businessCorrelationId, pipelineMessage, pipelineSession); result=pipeLineResult.getResult(); errorMessage = result; if (pipeLineResult.getState().equals(adapter.getErrorState())) { messageInError = true; } } else { // TODO: Find the right catch-clause where we decide about // retrying or swallowing and pushing to error-storage // Right now we make the decision before pushing a response // back which might be too early. try { if (getMessageLog()!=null) { getMessageLog().storeMessage(messageId, businessCorrelationId, new Date(),"log",pipelineMessage); } pipeLineResult = adapter.processMessageWithExceptions(businessCorrelationId, pipelineMessage, pipelineSession); result=pipeLineResult.getResult(); errorMessage = "exitState ["+pipeLineResult.getState()+"], result ["+result+"]"; if (log.isDebugEnabled()) { log.debug(getLogPrefix()+"received result: "+errorMessage); } messageInError=txStatus.isRollbackOnly(); if (!messageInError && !isTransacted()) { String commitOnState=((Adapter)adapter).getPipeLine().getCommitOnState(); if (StringUtils.isNotEmpty(commitOnState) && !commitOnState.equalsIgnoreCase(pipeLineResult.getState())) { messageInError=true; } } } catch (Throwable t) { log.debug("<*>"+getLogPrefix() + "TX Update: Received failure, transaction " + (txStatus.isRollbackOnly()?"already":"not yet") + " marked for rollback-only"); errorMessage = t.getMessage(); messageInError = true; ListenerException l = wrapExceptionAsListenerException(t); throw l; } } } finally { putSessionKeysIntoThreadContext(threadContext, pipelineSession); } // if (result==null) { // responseSizeStatistics.addValue(0); // } else { // responseSizeStatistics.addValue(result.length()); if (getSender()!=null) { String sendMsg = sendResultToSender(technicalCorrelationId, result); if (sendMsg != null) { errorMessage = sendMsg; } } } finally { cacheProcessResult(messageId, businessCorrelationId, errorMessage, new Date(startProcessingTimestamp)); if (!isTransacted() && messageInError) { // NB: Because the below happens from a finally-clause, any // exception that has occurred will still be propagated even // if we decide not to retry the message. // This should perhaps be avoided retryOrErrorStorage(rawMessage, startProcessingTimestamp, txStatus, errorMessage, message, messageId, businessCorrelationId, retry); } try { // TODO: Should this be done in a finally, unconditionally? // Perhaps better to have separate methods for correct processing, // and cleanup after an error? origin.afterMessageProcessed(pipeLineResult,rawMessage, threadContext); } finally { long finishProcessingTimestamp = System.currentTimeMillis(); finishProcessingMessage(finishProcessingTimestamp-startProcessingTimestamp); if (!txStatus.isCompleted()) { // Log what we're about to do if (txStatus.isRollbackOnly()) { log.debug(getLogPrefix() + "transaction marked for rollback, so rolling back the transaction"); } else { log.debug(getLogPrefix() + "transaction is not marked for rollback, so committing the transaction"); } // NB: Spring will take care of executing a commit or a rollback; // Spring will also ONLY commit the transaction if it was newly created // by the above call to txManager.getTransaction(). txManager.commit(txStatus); } else { throw new ListenerException(getLogPrefix()+"Transaction already completed; we didn't expect this"); } } } if (log.isDebugEnabled()) log.debug(getLogPrefix()+"messageId ["+messageId+"] correlationId ["+businessCorrelationId+"] returning result ["+result+"]"); return result; } private synchronized void cachePoisonMessageId(String messageId) { poisonMessageIdCache.put(messageId, messageId); } private synchronized boolean isMessageIdInPoisonCache(String messageId) { return poisonMessageIdCache.containsKey(messageId); } private synchronized void cacheProcessResult(String messageId, String correlationId, String errorMessage, Date receivedDate) { ProcessResultCacheItem cacheItem=getCachedProcessResult(messageId); if (cacheItem==null) { if (log.isDebugEnabled()) log.debug(getLogPrefix()+"caching first result for correlationId ["+correlationId+"]"); cacheItem= new ProcessResultCacheItem(); cacheItem.tryCount=1; cacheItem.correlationId=correlationId; cacheItem.receiveDate=receivedDate; } else { cacheItem.tryCount++; if (log.isDebugEnabled()) log.debug(getLogPrefix()+"increased try count for correlationId ["+correlationId+"] to ["+cacheItem.tryCount+"]"); } cacheItem.comments=errorMessage; processResultCache.put(messageId, cacheItem); } private synchronized boolean isMessageIdInProcessResultCache(String messageId) { return processResultCache.containsKey(messageId); } private synchronized ProcessResultCacheItem getCachedProcessResult(String messageId) { return (ProcessResultCacheItem)processResultCache.get(messageId); } private long getAndIncrementMessageRetryCount(String messageId) { Counter retries; synchronized (messageRetryCounters) { retries = (Counter) messageRetryCounters.get(messageId); if (retries == null) { retries = new Counter(0); messageRetryCounters.put(messageId, retries); return 0L; } } retries.increase(); return retries.getValue(); } private long removeMessageRetryCount(String messageId) { synchronized (messageRetryCounters) { Counter retries = (Counter) messageRetryCounters.get(messageId); if (retries == null) { return 0; } else { messageRetryCounters.remove(messageId); return retries.getValue(); } } } /* * returns true if message is already processed */ private boolean checkTryCount(String messageId, boolean retry, Object rawMessage, String message, Map threadContext, String correlationId) throws ListenerException { if (!retry) { if (log.isDebugEnabled()) log.debug(getLogPrefix()+"checking try count for messageId ["+messageId+"]"); // if (isTransacted()) { int deliveryCount=-1; if (getListener() instanceof IKnowsDeliveryCount) { deliveryCount = ((IKnowsDeliveryCount)getListener()).getDeliveryCount(rawMessage); } ProcessResultCacheItem prci = getCachedProcessResult(messageId); if (prci==null) { if (deliveryCount<=1) { resetRetryInterval(); return false; } } else { if (deliveryCount<1) { deliveryCount=prci.tryCount; } prci.tryCount++; } if (deliveryCount<=getMaxRetries()+1) { log.warn(getLogPrefix()+"message with messageId ["+messageId+"] has already been processed ["+(deliveryCount-1)+"] times, will try again"); resetRetryInterval(); return false; } warn(getLogPrefix()+"message with messageId ["+messageId+"] has already been processed ["+(deliveryCount-1)+"] times, will not try again; maxRetries=["+getMaxRetries()+"]"); if (deliveryCount>getMaxRetries()+2) { increaseRetryIntervalAndWait(null,getLogPrefix()+"saw message with messageId ["+messageId+"] too many times ["+deliveryCount+"]; maxRetries=["+getMaxRetries()+"]"); } String comments="too many retries"; Date rcvDate; if (prci!=null) { comments+="; "+prci.comments; rcvDate=prci.receiveDate; } else { rcvDate=new Date(); } if (isTransacted() || (getErrorStorage() != null && (!isCheckForDuplicates() || !getErrorStorage().containsMessageId(messageId)))) { moveInProcessToError(messageId, correlationId, message, rcvDate, comments, rawMessage, TXREQUIRED); } PipeLineResult plr = new PipeLineResult(); String result="<error>"+XmlUtils.encodeChars(comments)+"</error>"; plr.setResult(result); plr.setState("ERROR"); if (getSender()!=null) { // TODO correlationId should be technical correlationID! String sendMsg = sendResultToSender(correlationId, result); if (sendMsg != null) { log.warn("problem sending result:"+sendMsg); } } getListener().afterMessageProcessed(plr, rawMessage, threadContext); return true; // } else { // if (isMessageIdInPoisonCache(messageId)) { // return true; // if (getErrorStorage() != null && getErrorStorage().containsMessageId(messageId)) { // return true; } if (isCheckForDuplicates() && getMessageLog()!= null && getMessageLog().containsMessageId(messageId)) { return true; } return false; } /** * Decide if a failed message can be retried, or should be removed from the * queue and put to the error-storage. * * <p> * In the former case, the current transaction is marked rollback-onle. * </p> * <p> * In the latter case, the message is also moved to the error-storage and * it's message-id is 'blacklisted' in the internal cache of poison-messages. * </p> * <p> * NB: Because the current global transaction might have already been marked for * rollback-only, even if we decide not to retry the message it might still * be redelivered to us. In that case, the poison-cache will save the day. * </p> * * @return Returns <code>true</code> if the message can still be retried, * or <code>false</code> if the message will not be retried. */ private boolean retryOrErrorStorage(Object rawMessage, long startProcessingTimestamp, TransactionStatus txStatus, String errorMessage, String message, String messageId, String correlationId, boolean wasRetry) { long retryCount = getAndIncrementMessageRetryCount(messageId); log.error(getLogPrefix()+"message with id ["+messageId+"] had error in processing; current retry-count: " + retryCount); // Mark TX as rollback-only, because in any case updates done in the // transaction may not be performed. txStatus.setRollbackOnly(); if (wasRetry) { return false; } if (isTransacted()) { // If not yet exceeded the max retry count, // mark TX as rollback-only and throw an // exception if (retryCount < maxRetries) { log.error(getLogPrefix()+"message with id ["+messageId+"] will be retried; transaction marked rollback-only"); return true; } else { // Max retries exceeded; message to be moved // to error location (OR LOST!) log.error(getLogPrefix()+"message with id ["+messageId+"] retry count exceeded;"); //removeMessageRetryCount(messageId); moveInProcessToError(messageId, correlationId, message, new Date(startProcessingTimestamp), errorMessage, rawMessage, TXNEW); return false; } } else { log.error(getLogPrefix()+"not transacted, message with id ["+messageId+"] will not be retried"); moveInProcessToError(messageId, correlationId, message, new Date(startProcessingTimestamp), errorMessage, rawMessage, TXNEW); return false; } } public void exceptionThrown(INamedObject object, Throwable t) { String msg = getLogPrefix()+"received exception ["+t.getClass().getName()+"] from ["+object.getName()+"]"; if (ONERROR_CONTINUE.equalsIgnoreCase(getOnError())) { warn(msg+", will continue processing messages when they arrive: "+ t.getMessage()); } else { error(msg+", stopping receiver", t); stopRunning(); } } public String getEventSourceName() { return getLogPrefix().trim(); } protected void registerEvent(String eventCode) { if (eventHandler!=null) { eventHandler.registerEvent(this,eventCode); } } protected void throwEvent(String eventCode) { if (eventHandler!=null) { eventHandler.fireEvent(this,eventCode); } } public void resetRetryInterval() { synchronized (this) { if (suspensionMessagePending) { suspensionMessagePending=false; throwEvent(RCV_RESUMED_MONITOR_EVENT); } retryInterval = 1; } } public void increaseRetryIntervalAndWait(Throwable t, String description) { long currentInterval; synchronized (this) { currentInterval = retryInterval; retryInterval = retryInterval * 2; if (retryInterval > MAX_RETRY_INTERVAL) { retryInterval = MAX_RETRY_INTERVAL; } } if (currentInterval>1) { error(description+", will continue retrieving messages in [" + currentInterval + "] seconds", t); } else { log.warn(getLogPrefix()+"will continue retrieving messages in [" + currentInterval + "] seconds", t); } if (currentInterval*2 > RCV_SUSPENSION_MESSAGE_THRESHOLD) { if (!suspensionMessagePending) { suspensionMessagePending=true; throwEvent(RCV_SUSPENDED_MONITOR_EVENT); } } while (isInRunState(RunStateEnum.STARTED) && currentInterval try { Thread.sleep(1000); } catch (Exception e2) { error("sleep interupted", e2); stopRunning(); } } } public void iterateOverStatistics(StatisticsKeeperIterationHandler hski, Object data, int action) { Object recData=hski.openGroup(data,getName(),"receiver"); hski.handleScalar(recData,"messagesReceived", getMessagesReceived()); hski.handleScalar(recData,"messagesRetried", getMessagesRetried()); // hski.handleScalar(recData,"messagesRejected", numRejected.getValue()); hski.handleScalar(recData,"messagesReceivedThisInterval", numReceived.getIntervalValue()); hski.handleScalar(recData,"messagesRetriedThisInterval", numRetried.getIntervalValue()); // hski.handleScalar(recData,"messagesRejectedThisInterval", numRejected.getIntervalValue()); numReceived.performAction(action); numRetried.performAction(action); // numRejected.performAction(action); Iterator statsIter=getProcessStatisticsIterator(); Object pstatData=hski.openGroup(recData,null,"procStats"); if (statsIter != null) { while(statsIter.hasNext()) { StatisticsKeeper pstat = (StatisticsKeeper) statsIter.next(); hski.handleStatisticsKeeper(pstatData,pstat); pstat.performAction(action); } } hski.closeGroup(pstatData); statsIter = getIdleStatisticsIterator(); if (statsIter != null) { Object istatData=hski.openGroup(recData,null,"idleStats"); while(statsIter.hasNext()) { StatisticsKeeper pstat = (StatisticsKeeper) statsIter.next(); hski.handleStatisticsKeeper(istatData,pstat); pstat.performAction(action); } hski.closeGroup(istatData); } statsIter = getQueueingStatisticsIterator(); if (statsIter!=null) { Object qstatData=hski.openGroup(recData,null,"queueingStats"); while(statsIter.hasNext()) { StatisticsKeeper qstat = (StatisticsKeeper) statsIter.next(); hski.handleStatisticsKeeper(qstatData,qstat); qstat.performAction(action); } hski.closeGroup(qstatData); } hski.closeGroup(recData); } public boolean isThreadCountReadable() { if (getListener() instanceof IThreadCountControllable) { IThreadCountControllable tcc = (IThreadCountControllable)getListener(); return tcc.isThreadCountReadable(); } if (getListener() instanceof IPullingListener) { return true; } return false; } public boolean isThreadCountControllable() { if (getListener() instanceof IThreadCountControllable) { IThreadCountControllable tcc = (IThreadCountControllable)getListener(); return tcc.isThreadCountControllable(); } return false; } public int getCurrentThreadCount() { if (getListener() instanceof IThreadCountControllable) { IThreadCountControllable tcc = (IThreadCountControllable)getListener(); return tcc.getCurrentThreadCount(); } if (getListener() instanceof IPullingListener) { return listenerContainer.getThreadsRunning(); } return -1; } public int getMaxThreadCount() { if (getListener() instanceof IThreadCountControllable) { IThreadCountControllable tcc = (IThreadCountControllable)getListener(); return tcc.getMaxThreadCount(); } if (getListener() instanceof IPullingListener) { return getNumThreads(); } return -1; } public void increaseThreadCount() { if (getListener() instanceof IThreadCountControllable) { IThreadCountControllable tcc = (IThreadCountControllable)getListener(); tcc.increaseThreadCount(); } } public void decreaseThreadCount() { if (getListener() instanceof IThreadCountControllable) { IThreadCountControllable tcc = (IThreadCountControllable)getListener(); tcc.decreaseThreadCount(); } } public void setRunState(RunStateEnum state) { runState.setRunState(state); } public void waitForRunState(RunStateEnum requestedRunState) throws InterruptedException { runState.waitForRunState(requestedRunState); } public boolean waitForRunState(RunStateEnum requestedRunState, long timeout) throws InterruptedException { return runState.waitForRunState(requestedRunState, timeout); } /** * Get the {@link RunStateEnum runstate} of this receiver. */ public RunStateEnum getRunState() { return runState.getRunState(); } public boolean isInRunState(RunStateEnum someRunState) { return runState.isInState(someRunState); } protected synchronized StatisticsKeeper getProcessStatistics(int threadsProcessing) { StatisticsKeeper result; try { result = ((StatisticsKeeper)processStatistics.get(threadsProcessing)); } catch (IndexOutOfBoundsException e) { result = null; } if (result==null) { while (processStatistics.size()<threadsProcessing+1){ result = new StatisticsKeeper((processStatistics.size()+1)+" threads processing"); processStatistics.add(processStatistics.size(), result); } } return (StatisticsKeeper) processStatistics.get(threadsProcessing); } protected synchronized StatisticsKeeper getIdleStatistics(int threadsProcessing) { StatisticsKeeper result; try { result = ((StatisticsKeeper)idleStatistics.get(threadsProcessing)); } catch (IndexOutOfBoundsException e) { result = null; } if (result==null) { while (idleStatistics.size()<threadsProcessing+1){ result = new StatisticsKeeper((idleStatistics.size())+" threads processing"); idleStatistics.add(idleStatistics.size(), result); } } return (StatisticsKeeper) idleStatistics.get(threadsProcessing); } /** * Returns an iterator over the process-statistics * @return iterator */ public Iterator getProcessStatisticsIterator() { return processStatistics.iterator(); } /** * Returns an iterator over the idle-statistics * @return iterator */ public Iterator getIdleStatisticsIterator() { return idleStatistics.iterator(); } public Iterator getQueueingStatisticsIterator() { if (queueingStatistics==null) { return null; } return queueingStatistics.iterator(); } public ISender getSender() { return sender; } protected void setSender(ISender sender) { this.sender = sender; } public void setAdapter(IAdapter adapter) { this.adapter = adapter; } /** * Returns the listener * @return IListener */ public IListener getListener() { return listener; protected void setListener(IListener newListener) { listener = newListener; if (StringUtils.isEmpty(listener.getName())) { listener.setName("listener of ["+getName()+"]"); } if (listener instanceof RunStateEnquiring) { ((RunStateEnquiring) listener).SetRunStateEnquirer(runState); } } /** * Sets the inProcessStorage. * @param inProcessStorage The inProcessStorage to set * @deprecated */ protected void setInProcessStorage(ITransactionalStorage inProcessStorage) { log.warn(getLogPrefix()+"<*> In-Process Storage is not used anymore. Please remove from configuration. <*>"); // We do not use an in-process storage anymore, but we temporarily // store it if it's set by the configuration. // During configure, we check if we need to use the in-process storage // as error-storage. this.tmpInProcessStorage = inProcessStorage; } /** * Returns the errorSender. * @return ISender */ public ISender getErrorSender() { return errorSender; } public ITransactionalStorage getErrorStorage() { return errorStorage; } /** * Sets the errorSender. * @param errorSender The errorSender to set */ protected void setErrorSender(ISender errorSender) { this.errorSender = errorSender; errorSender.setName("errorSender of ["+getName()+"]"); } protected void setErrorStorage(ITransactionalStorage errorStorage) { if (errorStorage.isActive()) { this.errorStorage = errorStorage; errorStorage.setName("errorStorage of ["+getName()+"]"); if (StringUtils.isEmpty(errorStorage.getSlotId())) { errorStorage.setSlotId(getName()); } errorStorage.setType("E"); } } /** * Sets the messageLog. */ protected void setMessageLog(ITransactionalStorage messageLog) { if (messageLog.isActive()) { this.messageLog = messageLog; messageLog.setName("messageLog of ["+getName()+"]"); if (StringUtils.isEmpty(messageLog.getSlotId())) { messageLog.setSlotId(getName()); } messageLog.setType("L"); } } public ITransactionalStorage getMessageLog() { return messageLog; } /** * Get the number of messages received. * @return long */ public long getMessagesReceived() { return numReceived.getValue(); } /** * Get the number of messages retried. * @return long */ public long getMessagesRetried() { return numRetried.getValue(); } // public StatisticsKeeper getRequestSizeStatistics() { // return requestSizeStatistics; // public StatisticsKeeper getResponseSizeStatistics() { // return responseSizeStatistics; /** * Sets the name of the Receiver. * If the listener implements the {@link nl.nn.adapterframework.core.INamedObject name} interface and <code>getName()</code> * of the listener is empty, the name of this object is given to the listener. */ public void setName(String newName) { name = newName; propagateName(); } public String getName() { return name; } /** * Controls the use of XA-transactions. */ public void setTransacted(boolean transacted) { this.transacted = transacted; } public boolean isTransacted() { return transacted; } public void setOnError(String newOnError) { onError = newOnError; } public String getOnError() { return onError; } public boolean isOnErrorContinue() { return ONERROR_CONTINUE.equalsIgnoreCase(getOnError()); } protected IAdapter getAdapter() { return adapter; } /** * Returns a toString of this class by introspection and the toString() value of its listener. * * @return Description of the Return Value */ public String toString() { String result = super.toString(); ToStringBuilder ts=new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE); ts.append("name", getName() ); result += ts.toString(); result+=" listener ["+(listener==null ? "-none-" : listener.toString())+"]"; return result; } /** * The number of threads that this receiver is configured to work with. */ public void setNumThreads(int newNumThreads) { numThreads = newNumThreads; } public int getNumThreads() { return numThreads; } public String formatException(String extrainfo, String correlationId, String message, Throwable t) { return getAdapter().formatErrorMessage(extrainfo,t,message,correlationId,null,0); } public int getNumThreadsPolling() { return numThreadsPolling; } public void setNumThreadsPolling(int i) { numThreadsPolling = i; } public boolean isIbis42compatibility() { return ibis42compatibility; } public void setIbis42compatibility(boolean b) { ibis42compatibility = b; } // event numbers for tracing public void setBeforeEvent(int i) { beforeEvent = i; } public int getBeforeEvent() { return beforeEvent; } public void setAfterEvent(int i) { afterEvent = i; } public int getAfterEvent() { return afterEvent; } public void setExceptionEvent(int i) { exceptionEvent = i; } public int getExceptionEvent() { return exceptionEvent; } public int getMaxRetries() { return maxRetries; } public void setMaxRetries(int i) { maxRetries = i; } public void setActive(boolean b) { active = b; } public boolean isActive() { return active; } public void setReturnedSessionKeys(String string) { returnedSessionKeys = string; } public String getReturnedSessionKeys() { return returnedSessionKeys; } public void setTaskExecutor(TaskExecutor executor) { taskExecutor = executor; } public TaskExecutor getTaskExecutor() { return taskExecutor; } public void setTxManager(PlatformTransactionManager manager) { txManager = manager; } public PlatformTransactionManager getTxManager() { return txManager; } private String sendResultToSender(String correlationId, String result) { String errorMessage = null; try { if (getSender() != null) { if (log.isDebugEnabled()) { log.debug("Receiver ["+getName()+"] sending result to configured sender"); } getSender().sendMessage(correlationId, result); } } catch (Exception e) { String msg = "receiver [" + getName() + "] caught exception in message post processing"; error(msg, e); errorMessage = msg + ": " + e.getMessage(); if (ONERROR_CLOSE.equalsIgnoreCase(getOnError())) { log.info("receiver [" + getName() + "] closing after exception in post processing"); stopRunning(); } } return errorMessage; } private ListenerException wrapExceptionAsListenerException(Throwable t) { ListenerException l; if (t instanceof ListenerException) { l = (ListenerException) t; } else { l = new ListenerException(t); } return l; } public BeanFactory getBeanFactory() { return beanFactory; } public void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; } public PullingListenerContainer getListenerContainer() { return listenerContainer; } public void setListenerContainer(PullingListenerContainer listenerContainer) { this.listenerContainer = listenerContainer; } public PullingListenerContainer createListenerContainer() { PullingListenerContainer plc = (PullingListenerContainer) beanFactory.getBean("listenerContainer"); plc.setReceiver(this); plc.configure(); return plc; } public int getPoisonMessageIdCacheSize() { return poisonMessageIdCacheSize; } public void setPoisonMessageIdCacheSize(int poisonMessageIdCacheSize) { this.poisonMessageIdCacheSize = poisonMessageIdCacheSize; } public int getProcessResultCacheSize() { return processResultCacheSize; } public void setProcessResultCacheSize(int processResultCacheSize) { this.processResultCacheSize = processResultCacheSize; } public void setPollInterval(int i) { pollInterval = i; } public int getPollInterval() { return pollInterval; } public void setCheckForDuplicates(boolean b) { checkForDuplicates = b; } public boolean isCheckForDuplicates() { return checkForDuplicates; } public void setTransactionTimeout(int i) { transactionTimeout = i; } public int getTransactionTimeout() { return transactionTimeout; } public void setCorrelationIDXPath(String string) { correlationIDXPath = string; } public String getCorrelationIDXPath() { return correlationIDXPath; } }
package org.unitime.timetable.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.hibernate.Session; import org.unitime.commons.Debug; import org.unitime.timetable.model.dao._RootDAO; import net.sf.cpsolver.ifs.util.JProf; public class HibSessionFilter implements Filter { private FilterConfig filterConfig = null; /** * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) */ public void init(FilterConfig arg0) throws ServletException { filterConfig = arg0; Debug.debug("Initializing filter, obtaining Hibernate SessionFactory from HibernateUtil"); } /** * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) */ public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException { if (filterConfig==null) return; if (request.getAttribute("TimeStamp")==null) request.setAttribute("TimeStamp", new Double(JProf.currentTimeSec())); Session hibSession = null; try { hibSession = new _RootDAO().getSession(); //if(!hibSession.getTransaction().isActive()) { //Debug.info("Starting transaction"); //hibSession.beginTransaction(); // Process request chain.doFilter(request,response); // Close hibernate session, after request is processed //if(!hibSession.getTransaction().isActive()) { //Debug.info("Committing transaction"); //hibSession.getTransaction().commit(); if(hibSession!=null && hibSession.isOpen()) { hibSession.close(); } } catch (Throwable ex) { // Rollback only //ex.printStackTrace(); try { if (hibSession!=null && hibSession.isOpen() && hibSession.getTransaction().isActive()) { Debug.debug("Trying to rollback database transaction after exception"); hibSession.getTransaction().rollback(); } } catch (Throwable rbEx) { Debug.error(rbEx); } finally { if(hibSession!=null && hibSession.isOpen()) { hibSession.close(); } } if (ex instanceof ServletException) throw (ServletException)ex; if (ex instanceof IOException) throw (IOException)ex; if (ex instanceof RuntimeException) throw (RuntimeException)ex; // Let others handle it... maybe another interceptor for exceptions? throw new ServletException(ex); } } /** * @see javax.servlet.Filter#destroy() */ public void destroy() { this.filterConfig = null; } }
package org.gluu.ldap; import java.text.ParseException; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.log4j.Logger; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.status.StatusLogger; import org.gluu.persist.exception.mapping.EntryPersistenceException; import org.gluu.persist.ldap.impl.LdapEntryManager; import org.gluu.persist.ldap.operation.impl.LdapBatchOperation; import org.gluu.persist.model.SearchScope; import org.gluu.persist.model.base.CustomAttribute; import org.gluu.search.filter.Filter; import org.xdi.log.LoggingHelper; import com.unboundid.util.StaticUtils; public class LdapSampleBatchJob { private static final Logger log; static { StatusLogger.getLogger().setLevel(Level.OFF); LoggingHelper.configureConsoleAppender(); log = Logger.getLogger(LdapSample.class); } public static void main(String[] args) { // Prepare sample connection details LdapSampleEntryManager ldapSampleEntryManager = new LdapSampleEntryManager(); // Create LDAP entry manager final LdapEntryManager ldapEntryManager = ldapSampleEntryManager.createLdapEntryManager(); LdapBatchOperation<SimpleTokenLdap> tokenLdapBatchOperation = new LdapBatchOperation<SimpleTokenLdap>() { private int processedCount = 0; @Override public List<SimpleTokenLdap> getChunkOrNull(int batchSize) { log.info("Processed: " + processedCount); final Filter filter = Filter.createPresenceFilter("oxAuthExpiration"); return ldapEntryManager.findEntries("o=gluu", SimpleTokenLdap.class, filter, SearchScope.SUB, new String[]{"oxAuthExpiration"}, this, 0, batchSize, batchSize); } @Override public void performAction(List<SimpleTokenLdap> objects) { for (SimpleTokenLdap simpleTokenLdap : objects) { try { CustomAttribute customAttribute = getUpdatedAttribute(ldapEntryManager, "oxAuthExpiration", simpleTokenLdap.getAttribute("oxAuthExpiration")); simpleTokenLdap.setCustomAttributes(Arrays.asList(new CustomAttribute[]{customAttribute})); ldapEntryManager.merge(simpleTokenLdap); processedCount++; } catch (EntryPersistenceException ex) { log.error("Failed to update entry", ex); } } } }; tokenLdapBatchOperation.iterateAllByChunks(100); LdapBatchOperation<SimpleSession> sessionBatchOperation = new LdapBatchOperation<SimpleSession>() { private int processedCount = 0; @Override public List<SimpleSession> getChunkOrNull(int batchSize) { log.info("Processed: " + processedCount); final Filter filter = Filter.createPresenceFilter("oxLastAccessTime"); return ldapEntryManager.findEntries("o=gluu", SimpleSession.class, filter, SearchScope.SUB, new String[]{"oxLastAccessTime"}, this, 0, batchSize, batchSize); } @Override public void performAction(List<SimpleSession> objects) { for (SimpleSession simpleSession : objects) { try { CustomAttribute customAttribute = getUpdatedAttribute(ldapEntryManager, "oxLastAccessTime", simpleSession.getAttribute("oxLastAccessTime")); simpleSession.setCustomAttributes(Arrays.asList(new CustomAttribute[]{customAttribute})); ldapEntryManager.merge(simpleSession); processedCount++; } catch (EntryPersistenceException ex) { log.error("Failed to update entry", ex); } } } }; sessionBatchOperation.iterateAllByChunks(100); } private static CustomAttribute getUpdatedAttribute(LdapEntryManager ldapEntryManager, String attributeName, String attributeValue) { try { Calendar calendar = Calendar.getInstance(); Date oxLastAccessTimeDate = StaticUtils.decodeGeneralizedTime(attributeValue); calendar.setTime(oxLastAccessTimeDate); calendar.add(Calendar.SECOND, -1); CustomAttribute customAttribute = new CustomAttribute(); customAttribute.setName(attributeName); customAttribute.setValue(ldapEntryManager.encodeGeneralizedTime(calendar.getTime())); return customAttribute; } catch (ParseException e) { log.error("Can't parse attribute", e); } return null; } }
package pack.block.server; import java.io.Closeable; import java.io.File; import java.io.FileFilter; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.security.PrivilegedExceptionAction; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; 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.security.UserGroupInformation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.event.Level; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; import com.google.common.collect.ImmutableMap; import com.google.common.io.Closer; import pack.PackServer; import pack.PackStorage; import pack.block.blockstore.BlockStoreMetaData; import pack.block.blockstore.hdfs.CreateVolumeRequest; import pack.block.blockstore.hdfs.HdfsBlockStoreAdmin; import pack.block.blockstore.hdfs.lock.PackLockFactory; import pack.block.blockstore.hdfs.util.HdfsSnapshotStrategy; import pack.block.blockstore.hdfs.util.HdfsSnapshotUtil; import pack.block.blockstore.hdfs.util.LastestHdfsSnapshotStrategy; import pack.block.fuse.FuseFileSystemSingleMount; import pack.block.server.fs.LinuxFileSystem; import pack.block.server.json.BlockPackFuseConfig; import pack.block.server.json.BlockPackFuseConfig.BlockPackFuseConfigBuilder; import pack.block.util.FileCounter; import pack.block.util.Utils; import pack.json.Err; import pack.json.MountUnmountRequest; import pack.json.PathResponse; import pack.util.ExecUtil; import pack.util.Result; import spark.Route; import spark.Service; public class BlockPackStorage implements PackStorage { private static final Logger LOGGER = LoggerFactory.getLogger(BlockPackStorage.class); public static final String VOLUME_DRIVER_MOUNT_DEVICE = "/VolumeDriver.MountDevice"; public static final String VOLUME_DRIVER_UNMOUNT_DEVICE = "/VolumeDriver.UnmountDevice"; public static final String CLONE_PATH = "clonePath"; public static final String SYMLINK_CLONE = "symlinkClone"; public static final String MOUNT_COUNT = "mountCount"; public static final String MOUNT = "mount"; public static final String METRICS = "metrics"; public static final String SUDO = "sudo"; public static final String SYNC = "sync"; public static final String CONFIG_JSON = "config.json"; private static final String LOCKED = "locked"; private static final String UNLOCKED = "unlocked"; private static final String BRICK = "brick"; private static final String VOLUMES = "volumes"; private static final String FS = "fs"; private static final String DEV = "dev"; private static final String SHUTDOWN = "shutdown"; private static final long MAX_AGE = TimeUnit.MINUTES.toMillis(20); private static final String BASH = "bash"; private static final String LS = "ls"; private static final String ERROR = ".error."; private static final String SNAPSHOT = "snapshot"; private static final String RF = "-rf"; private static final String RM = "rm"; protected final Configuration _configuration; protected final Path _root; protected final File _localLogDir; protected final Set<String> _currentMountedVolumes = Collections.newSetFromMap(new ConcurrentHashMap<>()); protected final int _numberOfMountSnapshots; protected final File _workingDir; protected final HdfsSnapshotStrategy _snapshotStrategy; protected final Timer _cleanupTimer; protected final Map<String, Long> _cleanUpMap = new ConcurrentHashMap<>(); protected final Map<String, Long> _shutdownMap = new ConcurrentHashMap<>(); protected final Map<String, Object> _volumeLocks = new ConcurrentHashMap<>(); public BlockPackStorage(BlockPackStorageConfig config) throws IOException, InterruptedException { addServiceExtras(config.getService()); _snapshotStrategy = config.getStrategy(); _numberOfMountSnapshots = config.getNumberOfMountSnapshots(); LastestHdfsSnapshotStrategy.setMaxNumberOfMountSnapshots(_numberOfMountSnapshots); Closer closer = Closer.create(); closer.register((Closeable) () -> { for (String volumeName : _currentMountedVolumes) { try { unmount(volumeName, null); } catch (Exception e) { LOGGER.error("Unknown error while trying to umount volume " + volumeName); } } }); addShutdownHook(closer); _configuration = config.getConfiguration(); FileSystem fileSystem = getFileSystem(config.getRemotePath()); Path remotePath = config.getRemotePath() .makeQualified(fileSystem.getUri(), fileSystem.getWorkingDirectory()); _root = remotePath; LOGGER.info("Creating hdfs root path {}", _root); getUgi().doAs(HdfsPriv.create(() -> getFileSystem(_root).mkdirs(_root))); _localLogDir = config.getLogDir(); _localLogDir.mkdirs(); _workingDir = config.getWorkingDir(); _workingDir.mkdirs(); long period = TimeUnit.SECONDS.toMillis(30); _cleanupTimer = new Timer("Pack cleanup", true); _cleanupTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { cleanup(); } catch (Throwable t) { LOGGER.error("Unknown error", t); } } }, period, period); } void cleanup() throws IOException, InterruptedException { LOGGER.debug("cleanup"); File volumesDir = getVolumesDir(); if (!volumesDir.exists()) { return; } for (File volumeDir : volumesDir.listFiles()) { cleanup(volumeDir); } } private void cleanup(File volumeDir) throws IOException, InterruptedException { if (!volumeDir.exists()) { return; } File[] ids = volumeDir.listFiles(); for (File idFile : ids) { cleanup(volumeDir.getName(), idFile); } } private void cleanup(String volumeName, File idFile) throws IOException, InterruptedException { if (!idFile.exists()) { return; } String id = idFile.getName(); LOGGER.debug("cleanup for volume {} id {}", volumeName, id); synchronized (getVolumeLock(volumeName)) { if (!isVolumeStillInUse(id)) { LOGGER.debug("volume {} id {} is not running", volumeName, id); if (shouldPerformCleanup(volumeName, id)) { LOGGER.debug("volume {} id {} cleanup", volumeName, id); ExecUtil.execAsResult(LOGGER, Level.DEBUG, SUDO, RM, RF, idFile.getCanonicalPath()); LOGGER.info("delete {} {}", idFile, idFile.delete()); removeCleanupEntry(volumeName, id); } else { addCleanupEntry(volumeName, id); } } else { LOGGER.debug("volume {} id {} is still in use", volumeName, id); } } } private boolean isVolumeStillInUse(String id) throws IOException { Result result = ExecUtil.execAsResult(LOGGER, Level.DEBUG, SUDO, MOUNT); if (result.exitCode == 0) { return result.stdout.contains(id); } return false; } private boolean shouldPerformCleanup(String volumeName, String id) { Long ts = _cleanUpMap.get(volumeName + id); if (ts == null) { return false; } return ts + MAX_AGE < System.currentTimeMillis(); } private void removeCleanupEntry(String volumeName, String id) { LOGGER.info("add cleanup entry volume {} id {}", volumeName, id); _cleanUpMap.remove(volumeName + id); } private void addCleanupEntry(String volumeName, String id) { if (_cleanUpMap.putIfAbsent(volumeName + id, System.currentTimeMillis()) == null) { LOGGER.info("add cleanup entry volume {} id {}", volumeName, id); } } private UserGroupInformation getUgi() throws IOException { return Utils.getUserGroupInformation(); } private void addServiceExtras(Service service) { if (service == null) { return; } service.post(VOLUME_DRIVER_MOUNT_DEVICE, (Route) (request, response) -> { PackServer.debugInfo(request); MountUnmountRequest mountUnmountRequest = PackServer.read(request, MountUnmountRequest.class); try { String deviceMountPoint = getUgi().doAs( (PrivilegedExceptionAction<String>) () -> mountVolume(mountUnmountRequest.getVolumeName(), mountUnmountRequest.getId(), true)); return PathResponse.builder() .mountpoint(deviceMountPoint) .build(); } catch (Throwable t) { LOGGER.error("error", t); return PathResponse.builder() .mountpoint("<unknown>") .error(t.getMessage()) .build(); } }, PackServer.TRANSFORMER); service.post(VOLUME_DRIVER_UNMOUNT_DEVICE, (Route) (request, response) -> { PackServer.debugInfo(request); MountUnmountRequest mountUnmountRequest = PackServer.read(request, MountUnmountRequest.class); try { getUgi().doAs(HdfsPriv.create( () -> umountVolume(mountUnmountRequest.getVolumeName(), mountUnmountRequest.getId(), true))); return Err.builder() .build(); } catch (Throwable t) { LOGGER.error("error", t); return PathResponse.builder() .mountpoint("<unknown>") .error(t.getMessage()) .build(); } }, PackServer.TRANSFORMER); } private void addShutdownHook(Closer closer) { Runtime.getRuntime() .addShutdownHook(new Thread(() -> { try { closer.close(); } catch (IOException e) { LOGGER.error("Unknown error while trying to umount volumes"); } })); } @Override public void create(String volumeName, Map<String, Object> options) throws Exception { getUgi().doAs(HdfsPriv.create(() -> createVolume(volumeName, options))); } @Override public void remove(String volumeName) throws Exception { getUgi().doAs(HdfsPriv.create(() -> removeVolume(volumeName))); } @Override public String mount(String volumeName, String id) throws Exception { return getUgi().doAs((PrivilegedExceptionAction<String>) () -> mountVolume(volumeName, id, false)); } @Override public void unmount(String volumeName, String id) throws Exception { getUgi().doAs(HdfsPriv.create(() -> umountVolume(volumeName, id, false))); } @Override public boolean exists(String volumeName) throws Exception { return getUgi().doAs((PrivilegedExceptionAction<Boolean>) () -> existsVolume(volumeName)); } @Override public String getMountPoint(String volumeName) throws IOException { LOGGER.info("get mountPoint volume {}", volumeName); List<String> ids = getPossibleVolumeIds(volumeName); for (String id : ids) { File localFileSystemMount = getLocalFileSystemMount(volumeName, id); if (isMounted(localFileSystemMount)) { LOGGER.info("volume {} is mounted {}", volumeName, localFileSystemMount); return localFileSystemMount.getCanonicalPath(); } } return null; } private List<String> getPossibleVolumeIds(String volumeName) { File file = new File(getVolumesDir(), volumeName); if (!file.exists()) { return ImmutableList.of(); } Builder<String> builder = ImmutableList.builder(); for (File f : file.listFiles((FileFilter) pathname -> pathname.isDirectory())) { builder.add(f.getName()); } return builder.build(); } @Override public List<String> listVolumes() throws Exception { return getUgi().doAs((PrivilegedExceptionAction<List<String>>) () -> listHdfsVolumes(getFileSystem(_root), _root)); } public static List<String> listHdfsVolumes(FileSystem fileSystem, Path root) throws IOException, FileNotFoundException { LOGGER.info("list volumes"); FileStatus[] listStatus = fileSystem.listStatus(root); List<String> result = new ArrayList<>(); for (FileStatus fileStatus : listStatus) { Path path = fileStatus.getPath(); if (HdfsBlockStoreAdmin.hasMetaData(fileSystem, path)) { result.add(path.getName()); } } return result; } protected boolean existsVolume(String volumeName) throws IOException { LOGGER.info("exists {}", volumeName); FileSystem fileSystem = getFileSystem(_root); return HdfsBlockStoreAdmin.hasMetaData(fileSystem, getVolumePath(volumeName)); } protected void createVolume(String volumeName, Map<String, Object> options) throws IOException { LOGGER.info("create volume {}", volumeName); BlockStoreMetaData defaultmetaData = BlockStoreMetaData.DEFAULT_META_DATA; BlockStoreMetaData metaData = BlockStoreMetaData.setupOptions(defaultmetaData, options); Path volumePath = getVolumePath(volumeName); FileSystem fileSystem = getFileSystem(volumePath); CreateVolumeRequest request = CreateVolumeRequest.builder() .metaData(metaData) .volumeName(volumeName) .volumePath(volumePath) .clonePath(getClonePath(options)) .symlinkClone(getSymlinkClone(options)) .build(); HdfsBlockStoreAdmin.createVolume(fileSystem, request); } private boolean getSymlinkClone(Map<String, Object> options) { Object object = options.get(SYMLINK_CLONE); if (object == null) { return false; } return Boolean.parseBoolean(object.toString() .toLowerCase()); } private Path getClonePath(Map<String, Object> options) { Object object = options.get(CLONE_PATH); if (object == null) { return null; } return new Path(object.toString()); } protected void removeVolume(String volumeName) throws IOException { LOGGER.info("Remove Volume {}", volumeName); Path volumePath = getVolumePath(volumeName); FileSystem fileSystem = getFileSystem(volumePath); Utils.dropVolume(volumePath, fileSystem); } protected String mountVolume(String volumeName, String id, boolean deviceOnly) throws Exception { LOGGER.info("mountVolume {} id {} deviceOnly {}", volumeName, id, deviceOnly); if (!existsVolume(volumeName)) { createVolume(volumeName, ImmutableMap.of()); } LOGGER.debug("Mount Id {} volumeName {}", id, volumeName); Path volumePath = getVolumePath(volumeName); LOGGER.debug("Mount Id {} volumePath {}", id, volumePath); File logDir = getLogDir(volumeName); LOGGER.debug("Mount Id {} logDir {}", id, logDir); File localMetrics = getLocalMetrics(logDir); LOGGER.debug("Mount Id {} localMetrics {}", id, localMetrics); File localFileSystemMount = getLocalFileSystemMount(volumeName, id); LOGGER.debug("Mount Id {} localFileSystemMount {}", id, localFileSystemMount); File localDevice = getLocalDevice(volumeName, id); LOGGER.debug("Mount Id {} localDevice {}", id, localDevice); File localIndex = getLocalIndex(volumeName, id); LOGGER.debug("Mount Id {} localIndex {}", id, localIndex); File localCache = getLocalCache(volumeName, id); LOGGER.debug("Mount Id {} localCache {}", id, localCache); File libDir = getLibDir(volumeName, id); LOGGER.debug("Mount Id {} libDir {}", id, libDir); File configFile = getConfigFile(volumeName, id); LOGGER.debug("Mount Id {} configFile {}", id, configFile); File volumeDir = getVolumeDir(volumeName, id); LOGGER.debug("Mount Id {} volumeDir {}", id, volumeDir); FileSystem fileSystem = getFileSystem(volumePath); BlockStoreMetaData metaData = HdfsBlockStoreAdmin.readMetaData(fileSystem, volumePath); if (metaData == null) { throw new IOException("No metadata found for path " + volumePath); } FileCounter counter = getFileCounter(volumeName, id); try { synchronized (getVolumeLock(volumeName)) { counter.inc(); libDir.mkdirs(); localCache.mkdirs(); localIndex.mkdirs(); localFileSystemMount.mkdirs(); localDevice.mkdirs(); localMetrics.mkdirs(); if (isMounted(localFileSystemMount)) { LOGGER.info("volume {} id {} already mounted {}", volumeName, id, localFileSystemMount.getCanonicalPath()); return localFileSystemMount.getCanonicalPath(); } String path = volumePath.toUri() .getPath(); BlockPackFuseConfigBuilder configBuilder = BlockPackFuseConfig.builder(); BlockPackFuseConfig config = configBuilder.volumeName(volumeName) .fuseMountLocation(localDevice.getCanonicalPath()) .fsMetricsLocation(localMetrics.getCanonicalPath()) .fsLocalCache(localCache.getCanonicalPath()) .fsLocalIndex(localIndex.getCanonicalPath()) .hdfsVolumePath(path) .numberOfMountSnapshots(_numberOfMountSnapshots) .build(); BlockPackFuseProcessBuilder.startProcess(volumeName, volumeDir.getCanonicalPath(), logDir.getCanonicalPath(), libDir.getCanonicalPath(), configFile.getCanonicalPath(), _configuration, config); File brick = new File(localDevice, BRICK); if (!waitForDevice(brick, true, 60)) { Path lockPath = Utils.getLockPathForVolumeMount(volumePath); boolean lock = PackLockFactory.isLocked(_configuration, lockPath); throw new IOException( "Error waiting for device " + brick.getCanonicalPath() + " volume is " + (lock ? LOCKED : UNLOCKED)); } } File device = new File(localDevice, FuseFileSystemSingleMount.BRICK); if (deviceOnly) { return device.getCanonicalPath(); } mkfsIfNeeded(metaData, volumeName, device); tryToAssignUuid(metaData, device); mountFs(metaData, device, localFileSystemMount, volumeName, id); waitForMount(localDevice); HdfsSnapshotUtil.cleanupOldMountSnapshots(fileSystem, volumePath, _snapshotStrategy); return localFileSystemMount.getCanonicalPath(); } catch (Exception e) { counter.dec(); throw e; } } private File getLocalIndex(String volumeName, String id) { return new File(getVolumeDir(volumeName, id), "index"); } private void umountVolume(String volumeName, String id, boolean deviceOnly) throws Exception { LOGGER.info("umountVolume {} id {} deviceOnly {}", volumeName, id, deviceOnly); Path volumePath = getVolumePath(volumeName); File localDevice = getLocalDevice(volumeName, id); synchronized (getVolumeLock(volumeName)) { FileCounter counter = getFileCounter(volumeName, id); counter.dec(); long value = counter.getValue(); if (value == 0) { LOGGER.info("ref counter {}, shutdown", value); shutdownPack(volumeName, id); File brick = new File(localDevice, BRICK); if (!waitForDevice(brick, false, 60)) { Path lockPath = Utils.getLockPathForVolumeMount(volumePath); boolean lock = PackLockFactory.isLocked(_configuration, lockPath); throw new IOException( "Error waiting for device " + brick.getCanonicalPath() + " volume is " + (lock ? LOCKED : UNLOCKED)); } } else { LOGGER.info("ref counter {}, ref too high for shutdown", value); } } } private FileCounter getFileCounter(String volumeName, String id) { File file = new File(getVolumeDir(volumeName, id), "mount.ref"); file.getParentFile() .mkdirs(); return new FileCounter(file); } private synchronized Object getVolumeLock(String volumeName) { _volumeLocks.putIfAbsent(volumeName, new Object()); return _volumeLocks.get(volumeName); } private static boolean waitForDevice(File brick, boolean toExist, int timeInSeconds) throws InterruptedException, IOException { for (int i = 0; i < timeInSeconds; i++) { if (toExist) { if (ExecUtil.execReturnExitCode(LOGGER, Level.DEBUG, SUDO, LS, brick.getCanonicalPath()) == 0) { return true; } } else { if (ExecUtil.execReturnExitCode(LOGGER, Level.DEBUG, SUDO, LS, brick.getCanonicalPath()) != 0) { return true; } } LOGGER.info("Waiting for device {}", brick); Thread.sleep(TimeUnit.SECONDS.toMillis(1)); } return false; } private File getConfigFile(String volumeName, String id) { return new File(getVolumeDir(volumeName, id), CONFIG_JSON); } private void tryToAssignUuid(BlockStoreMetaData metaData, File device) throws IOException { LinuxFileSystem linuxFileSystem = metaData.getFileSystemType() .getLinuxFileSystem(); if (linuxFileSystem.isUuidAssignmentSupported()) { linuxFileSystem.assignUuid(metaData.getUuid(), device); } } private void mountFs(BlockStoreMetaData metaData, File device, File localFileSystemMount, String volumeName, String id) throws IOException, InterruptedException { String mountOptions = metaData.getMountOptions(); LinuxFileSystem linuxFileSystem = metaData.getFileSystemType() .getLinuxFileSystem(); try { linuxFileSystem.mount(device, localFileSystemMount, mountOptions); } catch (IOException e) { LOGGER.error("Error while trying to mount device {} to {}", device, localFileSystemMount); createMountErrorSnapshot(volumeName, id); LOGGER.info("Repairing device {}", device); linuxFileSystem.repair(device); LOGGER.info("Retrying mount device {} to {}", device, localFileSystemMount); linuxFileSystem.mount(device, localFileSystemMount, mountOptions); } if (linuxFileSystem.isFstrimSupported()) { linuxFileSystem.fstrim(localFileSystemMount); } if (linuxFileSystem.isGrowOnlineSupported()) { linuxFileSystem.growOnline(localFileSystemMount); } } private void mkfsIfNeeded(BlockStoreMetaData metaData, String volumeName, File device) throws IOException { LinuxFileSystem linuxFileSystem = metaData.getFileSystemType() .getLinuxFileSystem(); if (!linuxFileSystem.isFileSystemExists(device)) { linuxFileSystem.mkfs(device, metaData.getFileSystemBlockSize()); } } private File getLibDir(String volumeName, String id) { return new File(getVolumeDir(volumeName, id), "lib"); } private File getVolumesDir() { return new File(_workingDir, VOLUMES); } private File getVolumeDir(String volumeName, String id) { return new File(new File(getVolumesDir(), volumeName), id); } private static boolean isMounted(File localFileSystemMount) throws IOException { Result result = ExecUtil.execAsResult(LOGGER, Level.DEBUG, SUDO, MOUNT); return result.stdout.contains(localFileSystemMount.getCanonicalPath()); } private File getLocalCache(String volumeName, String id) { return new File(getVolumeDir(volumeName, id), "cache"); } private File getLocalMetrics(File logDir) { File file = new File(logDir, METRICS); file.mkdirs(); return file; } private File getLogDir(String volumeName) { File logDir = new File(_localLogDir, volumeName); logDir.mkdirs(); return logDir; } public static void waitForMount(File localFileSystemMount) throws InterruptedException, IOException { while (!isMounted(localFileSystemMount)) { LOGGER.info("Waiting for mount {}", localFileSystemMount); Thread.sleep(TimeUnit.SECONDS.toMillis(1)); } } private void shutdownPack(String volumeName, String id) throws IOException, InterruptedException { File localDevice = getLocalDevice(volumeName, id); File shutdownFile = new File(localDevice, SHUTDOWN); Process process = ExecUtil.execAsInteractive(LOGGER, Level.DEBUG, SUDO, BASH); try (PrintWriter writer = new PrintWriter(process.getOutputStream())) { writer.println("echo 1>" + shutdownFile.getCanonicalPath()); } if (process.waitFor() != 0) { throw new IOException("Unknown error on shutdown"); } } private void createMountErrorSnapshot(String volumeName, String id) throws FileNotFoundException, IOException, InterruptedException { File localDevice = getLocalDevice(volumeName, id); File snapshotFile = new File(localDevice, SNAPSHOT); SimpleDateFormat dateFormat = new SimpleDateFormat(HdfsSnapshotStrategy.YYYYMMDDKKMMSS); String format = dateFormat.format(new Date()); String name = ERROR + format; Process process = ExecUtil.execAsInteractive(LOGGER, Level.DEBUG, SUDO, BASH); LOGGER.info("Creating mount error snapshot {} for volume {} id {}", name, volumeName, id); try (PrintWriter writer = new PrintWriter(process.getOutputStream())) { writer.println("echo " + name + ">" + snapshotFile.getCanonicalPath()); } if (process.waitFor() != 0) { throw new IOException("Unknown error on shutdown"); } } private File getLocalFileSystemMount(String volumeName, String id) { return new File(getVolumeDir(volumeName, id), FS); } private File getLocalDevice(String volumeName, String id) { return new File(getVolumeDir(volumeName, id), DEV); } private FileSystem getFileSystem(Path path) throws IOException { return path.getFileSystem(_configuration); } static class HdfsPriv implements PrivilegedExceptionAction<Void> { private final Exec exec; private HdfsPriv(Exec exec) { this.exec = exec; } @Override public Void run() throws Exception { exec.exec(); return null; } static PrivilegedExceptionAction<Void> create(Exec exec) { return new HdfsPriv(exec); } } static interface Exec { void exec() throws Exception; } private Path getVolumePath(String volumeName) { return new Path(_root, volumeName); } }
package edu.wustl.catissuecore.util; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import net.sf.ehcache.CacheException; import edu.wustl.catissuecore.actionForm.SpecimenArrayForm; import edu.wustl.catissuecore.bizlogic.SpecimenArrayBizLogic; import edu.wustl.catissuecore.domain.Container; import edu.wustl.catissuecore.domain.Specimen; import edu.wustl.catissuecore.domain.SpecimenPosition; import edu.wustl.catissuecore.domain.StorageContainer; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.beans.NameValueBean; import edu.wustl.common.dao.DAO; import edu.wustl.common.util.dbManager.DAOException; import edu.wustl.common.util.global.ApplicationProperties; import edu.wustl.common.util.logger.Logger; public class StorageContainerUtil { /** * This functions updates the storage container map when a new position is to be added in map * @param storageContainer - Storage container whose position is freed * @param continerMap - map of storage container * @param x - x position which is updated * @param y - y position which is updated */ public static synchronized void insertSinglePositionInContainerMap(Container storageContainer, Map containerMap, int x, int y) { NameValueBean storageContainerId = new NameValueBean(storageContainer.getName(), (storageContainer.getId())); TreeMap storageContainerMap = (TreeMap) containerMap.get(storageContainerId); Integer xObj = new Integer(x); NameValueBean nvb = new NameValueBean(xObj, xObj); if (storageContainerMap == null) { storageContainerMap = new TreeMap(); containerMap.put(storageContainerId, storageContainerMap); } List yPosList = (List) storageContainerMap.get(nvb); if (yPosList == null || yPosList.size() == 0) { yPosList = new ArrayList(); yPosList.add(new NameValueBean(new Integer(y), new Integer(y))); } else { Collections.sort(yPosList); int size = yPosList.size(); boolean insertFlag = true; for (int i = 0; i < size; i++) { NameValueBean yPosNvb = (NameValueBean) yPosList.get(i); if (Integer.parseInt(yPosNvb.getName()) == y) { insertFlag = false; break; } } if (insertFlag) { yPosList.add(new NameValueBean(new Integer(y), new Integer(y))); Collections.sort(yPosList); } } storageContainerMap.put(nvb, yPosList); } /** * This functions updates the storage container map when a new position is to be deleted in map * @param storageContainer - Storage container whose position is occupied * @param continerMap - map of storage container * @param x - x position which is updated * @param y - y position which is updated */ public static synchronized void deleteSinglePositionInContainerMap(Container storageContainer, Map continersMap, int x, int y) { NameValueBean storageContainerId = new NameValueBean(storageContainer.getName(), storageContainer.getId()); TreeMap storageContainerMap = (TreeMap) continersMap.get(storageContainerId); Integer xObj = new Integer(x); NameValueBean nvb = new NameValueBean(xObj, xObj); List yPosList = (List) storageContainerMap.get(nvb); if (yPosList != null) { for (int i = 0; i < yPosList.size(); i++) { NameValueBean yPosnvb = (NameValueBean) yPosList.get(i); if (yPosnvb.getValue().equals("" + y)) { //Logger.out.debug("Removing value:" + y); yPosList.remove(i); break; } //yPosList.remove(new NameValueBean(new Integer(y), new Integer(y))); } } if (yPosList == null || yPosList.size() == 0) { storageContainerMap.remove(nvb); } if (storageContainerMap == null || storageContainerMap.size() == 0) { continersMap.remove(storageContainerId); } } /** * This functions updates the storage container map when a new container is added * @param storageContainer - Storage container which is added * @param continerMap - map of storage container * @param x - x position of parent storage container * @param y - y position of parent storage container */ public static synchronized void addStorageContainerInContainerMap(StorageContainer storageContainer, Map continersMap) throws DAOException { NameValueBean storageContainerId = new NameValueBean(storageContainer.getName(), storageContainer.getId()); TreeMap availabelPositionsMap = (TreeMap) getAvailablePositionMapForNewContainer(storageContainer); if (availabelPositionsMap != null && availabelPositionsMap.size() != 0) { continersMap.put(storageContainerId, availabelPositionsMap); } if (storageContainer.getLocatedAtPosition() != null && storageContainer.getLocatedAtPosition().getParentContainer() != null) { Container parentContainer = storageContainer.getLocatedAtPosition().getParentContainer(); int x = storageContainer.getLocatedAtPosition().getPositionDimensionOne().intValue(); int y = storageContainer.getLocatedAtPosition().getPositionDimensionTwo().intValue(); deleteSinglePositionInContainerMap((StorageContainer) parentContainer, continersMap, x, y); } } /** * This functions updates the storage container map when a new container is deleted or disabled * @param storageContainer - Storage container which is deleted or disabled * @param continerMap - map of storage container * @param x - x position of parent storage container * @param y - y position of parent storage container */ public static synchronized void removeStorageContainerInContainerMap(StorageContainer storageContainer, Map continersMap) throws DAOException { NameValueBean storageContainerId = new NameValueBean(storageContainer.getName(), storageContainer.getId()); continersMap.remove(storageContainerId); if (storageContainer.getLocatedAtPosition() != null && storageContainer.getLocatedAtPosition().getParentContainer() != null) { Container parentContainer = storageContainer.getLocatedAtPosition().getParentContainer(); int x = storageContainer.getLocatedAtPosition().getPositionDimensionOne().intValue(); int y = storageContainer.getLocatedAtPosition().getPositionDimensionTwo().intValue(); insertSinglePositionInContainerMap((StorageContainer) parentContainer, continersMap, x, y); } } /** * This functions returns a map of containers from the cache. * @return Returns a map of allocated containers vs. their respective free locations. * @throws DAOException */ public static Map getContainerMapFromCache() throws CacheException { // TODO if map is null // TODO move all code to common utility // getting instance of catissueCoreCacheManager and getting participantMap from cache CatissueCoreCacheManager catissueCoreCacheManager = CatissueCoreCacheManager.getInstance(); Map containerMap = (TreeMap) catissueCoreCacheManager.getObjectFromCache(Constants.MAP_OF_STORAGE_CONTAINERS); return containerMap; } /** * This functions returns a list of disabled containers from the cache. * @return Returns a list of disabled. * @throws DAOException */ public static List getListOfDisabledContainersFromCache() throws Exception { // TODO if map is null // TODO move all code to common utility // getting instance of catissueCoreCacheManager and getting participantMap from cache CatissueCoreCacheManager catissueCoreCacheManager = CatissueCoreCacheManager.getInstance(); List disabledconts = (ArrayList) catissueCoreCacheManager.getObjectFromCache(Constants.MAP_OF_DISABLED_CONTAINERS); return disabledconts; } /** * This functions returns a map of available rows vs. available columns. * @param container The container. * @return Returns a map of available rows vs. available columns. * @throws DAOException */ public static Map getAvailablePositionMapForNewContainer(StorageContainer container) throws DAOException { Map map = new TreeMap(); if (!container.isFull().booleanValue()) { final int dimX = container.getCapacity().getOneDimensionCapacity().intValue() + 1; final int dimY = container.getCapacity().getTwoDimensionCapacity().intValue() + 1; for (int x = 1; x < dimX; x++) { List list = new ArrayList(); for (int y = 1; y < dimY; y++) { list.add(new NameValueBean(new Integer(y), new Integer(y))); } if (!list.isEmpty()) { Integer xObj = new Integer(x); NameValueBean nvb = new NameValueBean(xObj, xObj); map.put(nvb, list); } } } return map; } public static LinkedList<Integer> getFirstAvailablePositionsInContainer( StorageContainer storageContainer, Map continersMap, HashSet<String> allocatedPositions) throws DAOException { //kalpana bug#6001 NameValueBean storageContainerId = new NameValueBean(storageContainer.getName(), storageContainer.getId()); TreeMap storageContainerMap = (TreeMap) continersMap.get(storageContainerId); Integer xpos= null; Integer ypos=null; String containerName = storageContainer.getName(); if (storageContainerMap == null || storageContainerMap.isEmpty()) { throw new DAOException("Storagecontainer information not found!"); } Iterator containerPosIterator = storageContainerMap.keySet().iterator(); while (containerPosIterator.hasNext()) { NameValueBean nvb = (NameValueBean) containerPosIterator.next(); xpos = new Integer(nvb.getValue()); List yposValues = (List) storageContainerMap.get(nvb); Iterator yposIterator = yposValues.iterator(); while(yposIterator.hasNext()) { nvb =(NameValueBean) yposIterator.next(); ypos= new Integer(nvb.getValue()); //bug 8294 String containerValue = null; Long containerId = storageContainer.getId(); if(containerId!=null) { containerValue = StorageContainerUtil.getStorageValueKey(null, containerId.toString(), xpos, ypos); } else { containerValue = StorageContainerUtil.getStorageValueKey(containerName,null,xpos, ypos); } if (!allocatedPositions.contains(containerValue)) { LinkedList<Integer> positions = new LinkedList<Integer>(); positions.add(xpos); positions.add(ypos); return positions; } } } throw new DAOException("Either Storagecontainer is full! or it cannot accomodate all the specimens."); } public static synchronized void updateStoragePositions(Map containerMap, StorageContainer currentContainer, StorageContainer oldContainer) { int xOld = oldContainer.getCapacity().getOneDimensionCapacity().intValue(); int xNew = currentContainer.getCapacity().getOneDimensionCapacity().intValue(); int yOld = oldContainer.getCapacity().getTwoDimensionCapacity().intValue(); int yNew = currentContainer.getCapacity().getTwoDimensionCapacity().intValue(); NameValueBean storageContainerId = new NameValueBean(currentContainer.getName(), (currentContainer.getId())); TreeMap storageContainerMap = (TreeMap) containerMap.get(storageContainerId); if (storageContainerMap == null) { storageContainerMap = new TreeMap(); containerMap.put(storageContainerId, storageContainerMap); } if (xNew > xOld) { for (int i = xOld + 1; i <= xNew; i++) { NameValueBean xNvb = new NameValueBean(new Integer(i), new Integer(i)); List yPosList = new ArrayList(); for (int j = 1; j <= yOld; j++) { NameValueBean yNvb = new NameValueBean(new Integer(j), new Integer(j)); yPosList.add(yNvb); } if (yPosList.size() > 0) { storageContainerMap.put(xNvb, yPosList); } } } if (yNew > yOld) { for (int i = 1; i <= xNew; i++) { NameValueBean xNvb = new NameValueBean(new Integer(i), new Integer(i)); List yPosList = new ArrayList(); for (int j = yOld + 1; j <= yNew; j++) { NameValueBean yNvb = new NameValueBean(new Integer(j), new Integer(j)); yPosList.add(yNvb); } List yList = (ArrayList) storageContainerMap.get(xNvb); if (yList == null) { storageContainerMap.put(xNvb, yPosList); } else { yList.addAll(yPosList); } } } if (xNew < xOld) { for (int i = xNew + 1; i <= xOld; i++) { NameValueBean xNvb = new NameValueBean(new Integer(i), new Integer(i)); storageContainerMap.remove(xNvb); } } if (yNew < yOld) { for (int i = 1; i <= xNew; i++) { NameValueBean xNvb = new NameValueBean(new Integer(i), new Integer(i)); List yPosList = new ArrayList(); for (int j = yNew + 1; j <= yOld; j++) { NameValueBean yNvb = new NameValueBean(new Integer(j), new Integer(j)); yPosList.add(yNvb); } List yList = (ArrayList) storageContainerMap.get(xNvb); if (yList != null) { yList.removeAll(yPosList); } } } } public static synchronized void updateNameInCache(Map containerMap, StorageContainer currentContainer, StorageContainer oldContainer) { //Using treeMap , so can't directly update the key contents. Map positionMap = new TreeMap(); boolean keyRemoved = false; Set keySet = containerMap.keySet(); Iterator itr = keySet.iterator(); while (itr.hasNext()) { NameValueBean nvb = (NameValueBean) itr.next(); if (nvb.getValue().equals(oldContainer.getId().toString()) && nvb.getName().equals(oldContainer.getName().toString())) { positionMap = (Map) containerMap.get(nvb); containerMap.remove(nvb); keyRemoved = true; break; } } if (keyRemoved) { NameValueBean nvbUpdated = new NameValueBean(currentContainer.getName(), currentContainer.getId()); containerMap.put(nvbUpdated, positionMap); } } public static boolean chkContainerFull(String storageContainerId, String storageContainerName) throws Exception { Map containerMap = getContainerMapFromCache(); NameValueBean nvb = new NameValueBean(storageContainerName, storageContainerId); if (containerMap.containsKey(nvb)) return false; else return true; } public static boolean isPostionAvaialble(String storageContainerId , String storageContainerName , String x , String y) throws CacheException { Map containerMap = getContainerMapFromCache(); NameValueBean nvb = new NameValueBean(storageContainerName, storageContainerId); Map positionMap = (Map)containerMap.get(nvb); if(positionMap != null && !positionMap.isEmpty()) { NameValueBean xNvb = new NameValueBean(new Integer(x),new Integer(x)); List yList = (List) positionMap.get(xNvb); if(yList != null && !yList.isEmpty()) { NameValueBean yNvb = new NameValueBean(y ,y); if(!yList.contains(yNvb)) return false; } else { return false; } } else { return false; } return true; } /** * This method gives first valid storage position to a specimen if it is not given. * If storage position is given it validates the storage position * @param specimen * @throws DAOException */ public static void validateStorageLocationForSpecimen(Specimen specimen) throws DAOException { if (specimen.getSpecimenPosition() != null && specimen.getSpecimenPosition().getStorageContainer() != null) { //Long storageContainerId = specimen.getStorageContainer().getId(); Integer xPos = null; Integer yPos = null; if(specimen.getSpecimenPosition() != null) { xPos = specimen.getSpecimenPosition().getPositionDimensionOne(); yPos = specimen.getSpecimenPosition().getPositionDimensionTwo(); } boolean isContainerFull = false; /** * Following code is added to set the x and y dimension in case only storage container is given * and x and y positions are not given */ if (xPos == null || yPos == null) { isContainerFull = true; Map containerMapFromCache = null; try { containerMapFromCache = (TreeMap) StorageContainerUtil.getContainerMapFromCache(); } catch (CacheException e) { e.printStackTrace(); } if (containerMapFromCache != null) { Iterator itr = containerMapFromCache.keySet().iterator(); while (itr.hasNext()) { NameValueBean nvb = (NameValueBean) itr.next(); if(nvb.getValue().toString().equals(specimen.getSpecimenPosition().getStorageContainer().getId().toString())) { Map tempMap = (Map) containerMapFromCache.get(nvb); Iterator tempIterator = tempMap.keySet().iterator();; NameValueBean nvb1 = (NameValueBean) tempIterator.next(); List list = (List) tempMap.get(nvb1); NameValueBean nvb2 = (NameValueBean) list.get(0); SpecimenPosition specPos = specimen.getSpecimenPosition(); specPos.setPositionDimensionOne(new Integer(nvb1.getValue())); specPos.setPositionDimensionTwo(new Integer(nvb2.getValue())); specPos.setSpecimen(specimen); isContainerFull = false; break; } } } if(specimen.getSpecimenPosition() != null) { xPos = specimen.getSpecimenPosition().getPositionDimensionOne(); yPos = specimen.getSpecimenPosition().getPositionDimensionTwo(); } } if(isContainerFull) { throw new DAOException("The Storage Container you specified is full"); } else if (xPos == null || yPos == null || xPos.intValue() < 0 || yPos.intValue() < 0) { throw new DAOException(ApplicationProperties.getValue("errors.item.format", ApplicationProperties .getValue("specimen.positionInStorageContainer"))); } } } /** * * Method which checks whether capacity of a container can be reduced * @param oldContainer * @param container * @return */ public static boolean checkCanReduceDimension(StorageContainer oldContainer, StorageContainer container) { Integer oldContainerDimOne = oldContainer.getCapacity().getOneDimensionCapacity(); Integer oldContainerDimTwo = oldContainer.getCapacity().getTwoDimensionCapacity(); Integer newContainerDimOne = container.getCapacity().getOneDimensionCapacity(); Integer newContainerDimTwo = container.getCapacity().getTwoDimensionCapacity(); List deletedPositions = new ArrayList(); if(newContainerDimOne < oldContainerDimOne) { for(int i=newContainerDimOne+1;i<oldContainerDimOne+1;i++) { for(int j=1;j<oldContainerDimTwo+1;j++) { deletedPositions.add(i+"@"+j); } } } if(newContainerDimTwo < oldContainerDimTwo) { for(int i=newContainerDimTwo+1;i<oldContainerDimTwo+1;i++) { for(int j=1;j<oldContainerDimOne+1;j++) { if(!deletedPositions.contains(j+"@"+i)) { deletedPositions.add(j+"@"+i); } } } } int count = 0; Map containerMapFromCache = null; try { containerMapFromCache = (TreeMap) StorageContainerUtil.getContainerMapFromCache(); } catch (CacheException e) { e.printStackTrace(); } if (containerMapFromCache != null) { Iterator itr = containerMapFromCache.keySet().iterator(); while (itr.hasNext()) { NameValueBean nvb = (NameValueBean) itr.next(); if (nvb.getValue().toString().equals(container.getId().toString())) { Map tempMap = (Map) containerMapFromCache.get(nvb); Iterator tempIterator = tempMap.keySet().iterator(); while(tempIterator.hasNext()) { NameValueBean nvb1 = (NameValueBean) tempIterator.next(); List list = (List) tempMap.get(nvb1); for(int i=0;i<list.size();i++) { NameValueBean nvb2 = (NameValueBean) list.get(i); String formatedPosition = nvb1.getValue() + "@" + nvb2.getValue(); if(deletedPositions.contains(formatedPosition)) { count++; } } } } } } if(count!=deletedPositions.size()) { return false; } return true; } /** * @param dao * @param similarContainerMap * @param containerPrefixKey * @param positionsToBeAllocatedList * @param usedPositionsList * @param iCount * @throws DAOException */ public static void prepareContainerMap(DAO dao, Map similarContainerMap, String containerPrefixKey, List positionsToBeAllocatedList, List usedPositionsList, int iCount, String contId) throws DAOException { String radioButonKey = "radio_" + iCount; String containerIdKey = containerPrefixKey + iCount + contId; String containerNameKey = containerPrefixKey + iCount + "_StorageContainer_name"; String posDim1Key = containerPrefixKey + iCount + "_positionDimensionOne"; String posDim2Key = containerPrefixKey + iCount + "_positionDimensionTwo"; String containerName = null; String containerId = null; String posDim1 = null; String posDim2 = null; //get the container values based on user selection from dropdown or map if (similarContainerMap.get(radioButonKey)!=null && similarContainerMap.get(radioButonKey).equals("1")) { containerId = (String) similarContainerMap.get(containerIdKey); posDim1 = (String) similarContainerMap.get(posDim1Key); posDim2 = (String) similarContainerMap.get(posDim2Key); usedPositionsList.add(containerId + Constants.STORAGE_LOCATION_SAPERATOR + posDim1 + Constants.STORAGE_LOCATION_SAPERATOR + posDim2); } else if (similarContainerMap.get(radioButonKey)!=null && similarContainerMap.get(radioButonKey).equals("2")) { containerName = (String) similarContainerMap.get(containerNameKey + "_fromMap"); String sourceObjectName = StorageContainer.class.getName(); String[] selectColumnName = {"id"}; String[] whereColumnName = {"name"}; String[] whereColumnCondition = {"="}; Object[] whereColumnValue = {containerName}; String joinCondition = null; List list = dao.retrieve(sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition); if (!list.isEmpty()) { containerId = list.get(0).toString(); } else { String message = ApplicationProperties.getValue("specimen.storageContainer"); throw new DAOException(ApplicationProperties.getValue("errors.invalid", message)); } posDim1 = (String) similarContainerMap.get(posDim1Key + "_fromMap"); posDim2 = (String) similarContainerMap.get(posDim2Key + "_fromMap"); if (posDim1 == null || posDim1.trim().equals("") || posDim2 == null || posDim2.trim().equals("")) { positionsToBeAllocatedList.add(new Integer(iCount)); } else { usedPositionsList.add(containerId + Constants.STORAGE_LOCATION_SAPERATOR + posDim1 + Constants.STORAGE_LOCATION_SAPERATOR + posDim2); similarContainerMap.put(containerIdKey, containerId); similarContainerMap.put(posDim1Key, posDim1); similarContainerMap.put(posDim2Key, posDim2); similarContainerMap.remove(containerIdKey + "_fromMap"); similarContainerMap.remove(posDim1Key + "_fromMap"); similarContainerMap.remove(posDim2Key + "_fromMap"); } } } /** * check for initial values for storage container. * @param containerMap container map * @return list of initial values */ public static List checkForInitialValues(Map containerMap) { List initialValues = null; if (containerMap.size() > 0) { String[] startingPoints = new String[3]; Set keySet = containerMap.keySet(); Iterator itr = keySet.iterator(); NameValueBean nvb = (NameValueBean) itr.next(); startingPoints[0] = nvb.getValue(); Map map1 = (Map) containerMap.get(nvb); keySet = map1.keySet(); itr = keySet.iterator(); nvb = (NameValueBean) itr.next(); startingPoints[1] = nvb.getValue(); List list = (List) map1.get(nvb); nvb = (NameValueBean) list.get(0); startingPoints[2] = nvb.getValue(); Logger.out.info("Starting points[0]" + startingPoints[0]); Logger.out.info("Starting points[1]" + startingPoints[1]); Logger.out.info("Starting points[2]" + startingPoints[2]); initialValues = new ArrayList(); initialValues.add(startingPoints); } return initialValues; } /** * @param containerMap * @param aliquotCount * @param counter * @return */ public static int checkForLocation(Map containerMap, int aliquotCount, int counter) { Object[] containerId = containerMap.keySet().toArray(); for (int i = 0; i < containerId.length; i++) { Map xDimMap = (Map) containerMap.get(containerId[i]); if (!xDimMap.isEmpty()) { Object[] xDim = xDimMap.keySet().toArray(); for (int j = 0; j < xDim.length; j++) { List yDimList = (List) xDimMap.get(xDim[j]); counter = counter + yDimList.size(); if (counter >= aliquotCount) { i = containerId.length; break; } } } } return counter; } /** * @param form * @param containerMap * @param aliquotMap */ public static void populateAliquotMap(String objectKey, Map containerMap, Map aliquotMap, String noOfAliquots) { int counter = 1; if (!containerMap.isEmpty()) { Object[] containerId = containerMap.keySet().toArray(); for (int i = 0; i < containerId.length; i++) { Map xDimMap = (Map) containerMap.get(containerId[i]); counter = setAliquotMap(objectKey, xDimMap,containerId, noOfAliquots,counter,aliquotMap, i); if (counter <= Integer.parseInt(noOfAliquots)) { i=containerId.length; } } } } public static int setAliquotMap(String objectKey,Map xDimMap, Object[] containerId, String noOfAliquots, int counter, Map aliquotMap, int i) { objectKey = objectKey + ":"; if (!xDimMap.isEmpty()) { Object[] xDim = xDimMap.keySet().toArray(); for (int j = 0; j < xDim.length; j++) { List yDimList = (List) xDimMap.get(xDim[j]); for (int k = 0; k < yDimList.size(); k++) { if (counter <= Integer.parseInt(noOfAliquots)) { String containerKey = objectKey + counter + "_StorageContainer_id"; String pos1Key = objectKey + counter + "_positionDimensionOne"; String pos2Key = objectKey + counter + "_positionDimensionTwo"; aliquotMap.put(containerKey, ((NameValueBean) containerId[i]).getValue()); aliquotMap.put(pos1Key, ((NameValueBean) xDim[j]).getValue()); aliquotMap.put(pos2Key, ((NameValueBean) yDimList.get(k)).getValue()); counter++; } else { j = xDim.length; //i = containerId.length; break; } } } } //counter = new Integer(intCounter); return counter; } /** * @param specimenArrayBizLogic * @param specimenArrayForm * @param containerMap * @return * @throws DAOException */ public static List setInitialValue(SpecimenArrayBizLogic specimenArrayBizLogic, SpecimenArrayForm specimenArrayForm, TreeMap containerMap) throws DAOException { List initialValues = null; String[] startingPoints = new String[]{"-1", "-1", "-1"}; String containerName = null; if (specimenArrayForm.getStorageContainer() != null && !specimenArrayForm.getStorageContainer().equals("-1")) { startingPoints[0] = specimenArrayForm.getStorageContainer(); String[] selectColumnName = {"name"}; String[] whereColumnName = {Constants.SYSTEM_IDENTIFIER}; String[] whereColumnCondition = {"="}; Object[] whereColumnValue = {Long.valueOf(startingPoints[0])}; String joinCondition = Constants.AND_JOIN_CONDITION; List containerList = specimenArrayBizLogic.retrieve(StorageContainer.class.getName(),selectColumnName,whereColumnName,whereColumnCondition,whereColumnValue,joinCondition); if ((containerList != null) && (!containerList.isEmpty())) { containerName = (String) containerList.get(0); } } if (specimenArrayForm.getPositionDimensionOne() != -1) { startingPoints[1] = String.valueOf(specimenArrayForm.getPositionDimensionOne()); } if (specimenArrayForm.getPositionDimensionTwo() != -1) { startingPoints[2] = String.valueOf(specimenArrayForm.getPositionDimensionTwo()); } initialValues = new ArrayList(); initialValues.add(startingPoints); // if not null if (containerName != null) { addPostions(containerMap,Long.valueOf(startingPoints[0]),containerName,Integer.valueOf(startingPoints[1]),Integer.valueOf(startingPoints[2])); } return initialValues; } /** * add positions while in edit mode * @param containerMap * @param id * @param containerName * @param pos1 * @param pos2 */ public static void addPostions(Map containerMap, Long id, String containerName, Integer pos1, Integer pos2) { int flag = 0; NameValueBean xpos = new NameValueBean(pos1, pos1); NameValueBean ypos = new NameValueBean(pos2, pos2); NameValueBean parentId = new NameValueBean(containerName, id); Set keySet = containerMap.keySet(); Iterator itr = keySet.iterator(); while (itr.hasNext()) { NameValueBean nvb = (NameValueBean) itr.next(); if (nvb.getValue().equals(id.toString())) { Map pos1Map = (Map) containerMap.get(nvb); Set keySet1 = pos1Map.keySet(); Iterator itr1 = keySet1.iterator(); while (itr1.hasNext()) { NameValueBean nvb1 = (NameValueBean) itr1.next(); if (nvb1.getValue().equals(pos1.toString())) { List pos2List = (List) pos1Map.get(nvb1); pos2List.add(ypos); flag = 1; break; } } if (flag != 1) { List pos2List = new ArrayList(); pos2List.add(ypos); pos1Map.put(xpos, pos2List); flag = 1; } } } if (flag != 1) { List pos2List = new ArrayList(); pos2List.add(ypos); Map pos1Map = new TreeMap(); pos1Map.put(xpos, pos2List); containerMap.put(parentId, pos1Map); } } /** * This method allocates available position to single specimen * @param object * @param aliquotMap * @param usedPositionsList * @throws DAOException */ public static void allocatePositionToSingleContainerOrSpecimen(Object object, Map aliquotMap, List usedPositionsList,String spKey,String scId) throws DAOException { int specimenNumber = ((Integer) object).intValue(); String specimenKey = spKey; String containerNameKey = specimenKey + specimenNumber + "_StorageContainer_name"; String containerIdKey = specimenKey + specimenNumber + scId; String posDim1Key = specimenKey + specimenNumber + "_positionDimensionOne"; String posDim2Key = specimenKey + specimenNumber + "_positionDimensionTwo"; String containerName = (String) aliquotMap.get(containerNameKey + "_fromMap"); boolean isContainerFull = false; Map containerMapFromCache = null; try { containerMapFromCache = (TreeMap) StorageContainerUtil.getContainerMapFromCache(); } catch (CacheException e) { e.printStackTrace(); } if (containerMapFromCache != null) { Iterator itr = containerMapFromCache.keySet().iterator(); while (itr.hasNext()) { NameValueBean nvb = (NameValueBean) itr.next(); String containerNameFromCacheName = nvb.getName().toString(); // TODO if (containerNameFromCacheName.equalsIgnoreCase(containerName.trim())) { String containerId = nvb.getValue(); Map tempMap = (Map) containerMapFromCache.get(nvb); Iterator tempIterator = tempMap.keySet().iterator(); while (tempIterator.hasNext()) { NameValueBean nvb1 = (NameValueBean) tempIterator.next(); List yPosList = (List) tempMap.get(nvb1); for (int i = 0; i < yPosList.size(); i++) { NameValueBean nvb2 = (NameValueBean) yPosList.get(i); String availaleStoragePosition = containerId + Constants.STORAGE_LOCATION_SAPERATOR + nvb1.getValue() + Constants.STORAGE_LOCATION_SAPERATOR + nvb2.getValue(); int j = 0; for (; j < usedPositionsList.size(); j++) { if (usedPositionsList.get(j).toString().equals(availaleStoragePosition)) break; } if (j==usedPositionsList.size()) { usedPositionsList.add(availaleStoragePosition); aliquotMap.put(containerIdKey,containerId); aliquotMap.put(posDim1Key, nvb1.getValue()); aliquotMap.put(posDim2Key, nvb2.getValue()); aliquotMap.remove(containerIdKey+"_fromMap"); aliquotMap.remove(posDim1Key+"_fromMap"); aliquotMap.remove(posDim2Key+"_fromMap"); return; } } } } } } throw new DAOException("The container you specified does not have enough space to allocate storage position for Container Number " + specimenNumber); } /** * @return */ public static boolean checkPos1AndPos2(String pos1, String pos2) { boolean flag = false; if(pos1!=null&&!pos1.trim().equals("")) { long l = 1; try { l = Long.parseLong(pos1); } catch(Exception e) { flag = true; } if(l<=0) { flag = true; } } if(pos2!=null&&!pos2.trim().equals("")) { long l = 1; try { l = Long.parseLong(pos2); } catch(Exception e) { flag = true; } if(l<=0) { flag = true; } } return flag; } /** * @param dao * @param containerId * @return * @throws DAOException * @throws ClassNotFoundException */ public static Collection getChildren(DAO dao,Long containerId) throws DAOException { String hql = "select cntPos.occupiedContainer from ContainerPosition cntPos, StorageContainer container where cntPos.occupiedContainer.id=container.id and cntPos.parentContainer.id ="+containerId; List childrenColl = new ArrayList(); try { childrenColl = dao.executeQuery(hql, null, false, null); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return childrenColl; } /** * @param children * @param dao * @param containerId * @throws DAOException */ public static void setChildren(Collection children, DAO dao, Long containerId) throws DAOException { if(children != null) { getChildren(dao, containerId).addAll(children); } } /** * Description: This method is used to create storage loaction key value. * Used while updating or inserting Specimen * @param containerName - storage container name * @param containerID - storage container id * @param containerPos1 - storage container Position 1 * @param containerPos2 - storage container Position 2 * @return storageValue : container name or container id:container Position 1,container Position 2 */ //bug 8294 public static String getStorageValueKey(String containerName,String containerID,Integer containerPos1,Integer containerPos2) { StringBuffer storageValue = new StringBuffer(); if(containerName!=null) { storageValue.append(containerName); storageValue.append(":"); storageValue.append(containerPos1); storageValue.append(" ,"); storageValue.append(containerPos2); } else if(containerID!=null) { storageValue.append(containerID); storageValue.append(":"); storageValue.append(containerPos1); storageValue.append(" ,"); storageValue.append(containerPos2); } return storageValue.toString(); } }
package org.emerjoin.hi.web.i18n; import org.emerjoin.ioutils.Mappings; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import java.util.Properties; public class DictionaryBuilder { private Map<String,String> dictionary = new HashMap<>(); protected DictionaryBuilder(){ } public void put(InputStream dictionaryFile, I18nConfiguration configuration){ Map<String,String> map = new HashMap<>(); try { map = Mappings.load(dictionaryFile); dictionary.putAll(map); }catch (Exception ex){ throw new I18nException("Failed to load a Language dictionary file",ex); } } public Map<String,String> build(){ return dictionary; } }
package com.xpn.xwiki.doc; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; import java.lang.ref.SoftReference; import java.lang.reflect.Method; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.UUID; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ecs.filter.CharacterFilter; import org.apache.velocity.VelocityContext; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.dom.DOMDocument; import org.dom4j.dom.DOMElement; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.suigeneris.jrcs.diff.Diff; import org.suigeneris.jrcs.diff.DifferentiationFailedException; import org.suigeneris.jrcs.diff.Revision; import org.suigeneris.jrcs.diff.delta.Delta; import org.suigeneris.jrcs.rcs.Version; import org.suigeneris.jrcs.util.ToString; import org.xwiki.bridge.DocumentModelBridge; import org.xwiki.model.EntityType; import org.xwiki.model.reference.DocumentReference; import org.xwiki.context.Execution; import org.xwiki.context.ExecutionContext; import org.xwiki.context.ExecutionContextException; import org.xwiki.context.ExecutionContextManager; import org.xwiki.model.reference.DocumentReferenceResolver; import org.xwiki.model.reference.EntityReference; import org.xwiki.model.reference.EntityReferenceSerializer; import org.xwiki.model.reference.WikiReference; import org.xwiki.rendering.block.Block; import org.xwiki.rendering.block.HeaderBlock; import org.xwiki.rendering.block.LinkBlock; import org.xwiki.rendering.block.MacroBlock; import org.xwiki.rendering.block.SectionBlock; import org.xwiki.rendering.block.XDOM; import org.xwiki.rendering.listener.HeaderLevel; import org.xwiki.rendering.listener.LinkType; import org.xwiki.rendering.parser.ParseException; import org.xwiki.rendering.parser.Parser; import org.xwiki.rendering.renderer.BlockRenderer; import org.xwiki.rendering.renderer.printer.DefaultWikiPrinter; import org.xwiki.rendering.renderer.printer.WikiPrinter; import org.xwiki.rendering.syntax.Syntax; import org.xwiki.rendering.syntax.SyntaxFactory; import org.xwiki.rendering.transformation.TransformationException; import org.xwiki.rendering.transformation.TransformationManager; import org.xwiki.rendering.util.ParserUtils; import org.xwiki.velocity.VelocityManager; import com.xpn.xwiki.CoreConfiguration; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiConstant; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.api.DocumentSection; import com.xpn.xwiki.content.Link; import com.xpn.xwiki.content.parsers.DocumentParser; import com.xpn.xwiki.content.parsers.LinkParser; import com.xpn.xwiki.content.parsers.RenamePageReplaceLinkHandler; import com.xpn.xwiki.content.parsers.ReplacementResultCollection; import com.xpn.xwiki.criteria.impl.RevisionCriteria; import com.xpn.xwiki.doc.rcs.XWikiRCSNodeInfo; import com.xpn.xwiki.objects.BaseCollection; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.BaseProperty; import com.xpn.xwiki.objects.LargeStringProperty; import com.xpn.xwiki.objects.ListProperty; import com.xpn.xwiki.objects.ObjectDiff; import com.xpn.xwiki.objects.classes.BaseClass; import com.xpn.xwiki.objects.classes.ListClass; import com.xpn.xwiki.objects.classes.PropertyClass; import com.xpn.xwiki.objects.classes.StaticListClass; import com.xpn.xwiki.objects.classes.TextAreaClass; import com.xpn.xwiki.plugin.query.XWikiCriteria; import com.xpn.xwiki.render.XWikiRenderingEngine; import com.xpn.xwiki.render.XWikiVelocityRenderer; import com.xpn.xwiki.store.XWikiAttachmentStoreInterface; import com.xpn.xwiki.store.XWikiStoreInterface; import com.xpn.xwiki.store.XWikiVersioningStoreInterface; import com.xpn.xwiki.user.api.XWikiRightService; import com.xpn.xwiki.util.Util; import com.xpn.xwiki.validation.XWikiValidationInterface; import com.xpn.xwiki.validation.XWikiValidationStatus; import com.xpn.xwiki.web.EditForm; import com.xpn.xwiki.web.ObjectAddForm; import com.xpn.xwiki.web.Utils; import com.xpn.xwiki.web.XWikiMessageTool; import com.xpn.xwiki.web.XWikiRequest; public class XWikiDocument implements DocumentModelBridge { private static final Log LOG = LogFactory.getLog(XWikiDocument.class); /** * Regex Pattern to recognize if there's HTML code in a XWiki page. */ private static final Pattern HTML_TAG_PATTERN = Pattern.compile("</?(html|body|img|a|i|b|embed|script|form|input|textarea|object|" + "font|li|ul|ol|table|center|hr|br|p) ?([^>]*)>"); /** Regex for finding the first level 1 or 2 heading in the document title, to be used as the document title. */ private static final Pattern HEADING_PATTERN_10 = Pattern.compile("^\\s*+1(?:\\.1)?\\s++(.++)$", Pattern.MULTILINE); public static final String XWIKI10_SYNTAXID = Syntax.XWIKI_1_0.toIdString(); public static final String XWIKI20_SYNTAXID = Syntax.XWIKI_2_0.toIdString(); private String title; private DocumentReference parentReference; private DocumentReference documentReference; private String content; private String meta; private String format; /** * First author of the document. */ private String creator; /** * The Author is changed when any part of the document changes (content, objects, attachments). */ private String author; /** * The last user that has changed the document's content (ie not object, attachments). The Content author is only * changed when the document content changes. Note that Content Author is used to check programming rights on a * document and this is the reason we need to know the last author who's modified the content since programming * rights depend on this. */ private String contentAuthor; private String customClass; private Date contentUpdateDate; private Date updateDate; private Date creationDate; protected Version version; private long id = 0; private boolean mostRecent = true; private boolean isNew = true; /** * The reference to the document that is the template for the current document. * * @todo this field is not used yet since it's not currently saved in the database. */ private DocumentReference templateDocumentReference; protected String language; private String defaultLanguage; private int translation; private BaseObject tags; /** * Indicates whether the document is 'hidden', meaning that it should not be returned in public search results. * WARNING: this is a temporary hack until the new data model is designed and implemented. No code should rely on or * use this property, since it will be replaced with a generic metadata. */ private boolean hidden = false; /** * Comment on the latest modification. */ private String comment; /** * Wiki syntax supported by this document. This is used to support different syntaxes inside the same wiki. For * example a page can use the Confluence 2.0 syntax while another one uses the XWiki 1.0 syntax. In practice our * first need is to support the new rendering component. To use the old rendering implementation specify a * "xwiki/1.0" syntaxId and use a "xwiki/2.0" syntaxId for using the new rendering component. */ private Syntax syntax; /** * Is latest modification a minor edit */ private boolean isMinorEdit = false; /** * Used to make sure the MetaData String is regenerated. */ private boolean isContentDirty = true; /** * Used to make sure the MetaData String is regenerated */ private boolean isMetaDataDirty = true; public static final int HAS_ATTACHMENTS = 1; public static final int HAS_OBJECTS = 2; public static final int HAS_CLASS = 4; private int elements = HAS_OBJECTS | HAS_ATTACHMENTS; /** * Separator string between database name and space name. */ public static final String DB_SPACE_SEP = ":"; /** * Separator string between space name and page name. */ public static final String SPACE_NAME_SEP = "."; // Meta Data private BaseClass xClass; private String xClassXML; /** * Map holding document objects indexed by XClass references (i.e. Document References since a XClass reference * points to a document). The map is not synchronized, and uses a TreeMap implementation to preserve index ordering * (consistent sorted order for output to XML, rendering in velocity, etc.) */ private Map<DocumentReference, List<BaseObject>> xObjects = new TreeMap<DocumentReference, List<BaseObject>>(); private List<XWikiAttachment> attachmentList; // Caching private boolean fromCache = false; private List<BaseObject> xObjectsToRemove = new ArrayList<BaseObject>(); /** * The view template (vm file) to use. When not set the default view template is used. * * @see com.xpn.xwiki.web.ViewAction#render(XWikiContext) */ private String defaultTemplate; private String validationScript; private Object wikiNode; // We are using a SoftReference which will allow the archive to be // discarded by the Garbage collector as long as the context is closed (usually during the // request) private SoftReference<XWikiDocumentArchive> archive; private XWikiStoreInterface store; /** * @see #getOriginalDocument() */ private XWikiDocument originalDocument; /** * The document structure expressed as a tree of Block objects. We store it for performance reasons since parsing is * a costly operation that we don't want to repeat whenever some code ask for the XDOM information. */ private XDOM xdom; /** * Used to resolve a string into a proper Document Reference using the current document's reference to fill the * blanks. */ private DocumentReferenceResolver<String> currentDocumentReferenceResolver = Utils.getComponent( DocumentReferenceResolver.class, "current"); /** * Used to resolve a string into a proper Document Reference using the current document's reference to fill the * blanks, except for the page name for which the default page name is used instead and for the wiki name for which * the current wiki is used instead of the current document reference's wiki. */ private DocumentReferenceResolver<String> currentMixedDocumentReferenceResolver = Utils.getComponent( DocumentReferenceResolver.class, "currentmixed"); /** * Used to normalize references. */ private DocumentReferenceResolver<EntityReference> currentReferenceDocumentReferenceResolver = Utils.getComponent( DocumentReferenceResolver.class, "current/reference"); /** * Used to convert a proper Document Reference to string (compact form). */ private EntityReferenceSerializer<String> compactEntityReferenceSerializer = Utils.getComponent( EntityReferenceSerializer.class, "compact"); /** * Used to convert a proper Document Reference to string (standard form). */ private EntityReferenceSerializer<String> defaultEntityReferenceSerializer = Utils.getComponent(EntityReferenceSerializer.class); /** * Used to convert a Document Reference to string (compact form without the wiki part if it matches the current * wiki). */ private EntityReferenceSerializer<String> compactWikiEntityReferenceSerializer = Utils.getComponent( EntityReferenceSerializer.class, "compactwiki"); /** * Used to convert a proper Document Reference to a string but without the wiki name. */ private EntityReferenceSerializer<String> localEntityReferenceSerializer = Utils.getComponent( EntityReferenceSerializer.class, "local"); /* * Used to emulate an inline parsing. */ private ParserUtils parserUtils = new ParserUtils(); /** * Used to create proper {@link Syntax} objects. */ private SyntaxFactory syntaxFactory = Utils.getComponent(SyntaxFactory.class); private Execution execution = Utils.getComponent(Execution.class); /** * @since 2.2M1 */ public XWikiDocument(DocumentReference reference) { init(reference); } /** * @deprecated since 2.2M1 use {@link #XWikiDocument(org.xwiki.model.reference.DocumentReference)} instead */ @Deprecated public XWikiDocument() { this(null); } /** * Constructor that specifies the local document identifier: space name, document name. {@link #setDatabase(String)} * must be called afterwards to specify the wiki name. * * @param space the space this document belongs to * @param name the name of the document * @deprecated since 2.2M1 use {@link #XWikiDocument(org.xwiki.model.reference.DocumentReference)} instead */ @Deprecated public XWikiDocument(String space, String name) { this(null, space, name); } /** * Constructor that specifies the full document identifier: wiki name, space name, document name. * * @param wiki The wiki this document belongs to. * @param space The space this document belongs to. * @param name The name of the document (can contain either the page name or the space and page name) * @deprecated since 2.2M1 use {@link #XWikiDocument(org.xwiki.model.reference.DocumentReference)} instead */ @Deprecated public XWikiDocument(String wiki, String space, String name) { // We allow to specify the space in the name (eg name = "space.page"). In this case the passed space is // ignored. // Build an entity reference that will serve as a current context reference against which to resolve if the // passed name doesn't contain a space. EntityReference contextReference = null; if (!StringUtils.isEmpty(space)) { contextReference = new EntityReference(space, EntityType.SPACE); if (!StringUtils.isEmpty(wiki)) { contextReference.setParent(new WikiReference(wiki)); } } else if (!StringUtils.isEmpty(wiki)) { contextReference = new WikiReference(wiki); } DocumentReference reference; if (contextReference != null) { reference = resolveReference(name, this.currentDocumentReferenceResolver, this.currentReferenceDocumentReferenceResolver.resolve(contextReference)); // Replace the resolved wiki by the passed wiki if not empty/null if (!StringUtils.isEmpty(wiki)) { reference.setWikiReference(new WikiReference(wiki)); } } else { // Both the wiki and space params are empty/null, thus don't use a context reference. reference = this.currentDocumentReferenceResolver.resolve(name); } init(reference); } public XWikiStoreInterface getStore(XWikiContext context) { return context.getWiki().getStore(); } public XWikiAttachmentStoreInterface getAttachmentStore(XWikiContext context) { return context.getWiki().getAttachmentStore(); } public XWikiVersioningStoreInterface getVersioningStore(XWikiContext context) { return context.getWiki().getVersioningStore(); } public XWikiStoreInterface getStore() { return this.store; } public void setStore(XWikiStoreInterface store) { this.store = store; } /** * @return the unique id used to represent the document, as a number. This id is technical and is equivalent to the * Document Reference + the language of the Document. This technical id should only be used for the storage * layer and all user APIs should instead use Document Reference and language as they are model-related * while the id isn't (it's purely technical). */ public long getId() { // TODO: The implemented below doesn't guarantee a unique id since it uses the hashCode() method which doesn't // guarantee unicity. From the JDK's javadoc: "It is not required that if two objects are unequal according to // the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must // produce distinct integer results.". This needs to be fixed to produce a real unique id since otherwise we // can have clashes in the database. // Note: We don't use the wiki name in the document id's computation. The main historical reason is so // that all things saved in a given wiki's database are always stored relative to that wiki so that // changing that wiki's name is simpler. if ((this.language == null) || this.language.trim().equals("")) { this.id = this.localEntityReferenceSerializer.serialize(getDocumentReference()).hashCode(); } else { this.id = (this.localEntityReferenceSerializer.serialize(getDocumentReference()) + ":" + this.language).hashCode(); } return this.id; } /** * @see #getId() */ public void setId(long id) { this.id = id; } /** * Note that this method cannot be removed for now since it's used by Hibernate for saving a XWikiDocument. * * @return the name of the space of the document * @deprecated since 2.2M1 used {@link #getDocumentReference()} instead */ @Deprecated public String getSpace() { return getDocumentReference().getLastSpaceReference().getName(); } /** * Note that this method cannot be removed for now since it's used by Hibernate for loading a XWikiDocument. * * @deprecated since 2.2M1 used {@link #setDocumentReference(DocumentReference)} instead */ @Deprecated public void setSpace(String space) { if (space != null) { getDocumentReference().getLastSpaceReference().setName(space); } } /** * Note that this method cannot be removed for now since it's used by Hibernate for saving a XWikiDocument. * * @return the name of the space of the document * @deprecated use {@link #getDocumentReference()} instead */ @Deprecated public String getWeb() { return getSpace(); } /** * Note that this method cannot be removed for now since it's used by Hibernate for loading a XWikiDocument. * * @deprecated use {@link #setDocumentReference(DocumentReference)} instead */ @Deprecated public void setWeb(String space) { setSpace(space); } public String getVersion() { return getRCSVersion().toString(); } public void setVersion(String version) { if (!StringUtils.isEmpty(version)) { this.version = new Version(version); } } public Version getRCSVersion() { if (this.version == null) { return new Version("1.1"); } return this.version; } public void setRCSVersion(Version version) { this.version = version; } /** * @return the copy of this XWikiDocument instance before any modification was made to it. It is reset to the actual * values when the document is saved in the database. This copy is used for finding out differences made to * this document (useful for example to send the correct notifications to document change listeners). */ public XWikiDocument getOriginalDocument() { return this.originalDocument; } /** * @param originalDocument the original document representing this document instance before any change was made to * it, prior to the last time it was saved * @see #getOriginalDocument() */ public void setOriginalDocument(XWikiDocument originalDocument) { this.originalDocument = originalDocument; } /** * @return the parent reference or null if the parent is not set * @since 2.2M1 */ public DocumentReference getParentReference() { return this.parentReference; } /** * Note that this method cannot be removed for now since it's used by Hibernate for saving a XWikiDocument. * * @return the parent reference or an empty string ("") if the parent is not set * @deprecated since 2.2M1 used {@link #getParentReference()} instead */ @Deprecated public String getParent() { String parentReferenceAsString; if (getParentReference() != null) { parentReferenceAsString = this.compactWikiEntityReferenceSerializer.serialize(getParentReference()); } else { parentReferenceAsString = ""; } return parentReferenceAsString; } /** * @deprecated since 2.2M1 used {@link #getParentReference()} instead */ @Deprecated public XWikiDocument getParentDoc() { return new XWikiDocument(getParentReference()); } /** * @since 2.2M1 */ public void setParentReference(DocumentReference parentReference) { if ((parentReference == null && getParentReference() != null) || (parentReference != null && !parentReference.equals(getParentReference()))) { this.parentReference = parentReference; setMetaDataDirty(true); } } /** * Note that this method cannot be removed for now since it's used by Hibernate for loading a XWikiDocument. * * @deprecated since 2.2M1 used {@link #setParentReference(DocumentReference)} instead */ @Deprecated public void setParent(String parent) { // If the passed parent is an empty string we also need to set the reference to null. The reason is that // in the database we store "" when the parent is empty and thus when Hibernate loads this class it'll call // setParent with "" if the parent had not been set when saved. if (StringUtils.isEmpty(parent)) { setParentReference(null); } else { setParentReference(this.currentMixedDocumentReferenceResolver.resolve(parent)); } } public String getContent() { return this.content; } public void setContent(String content) { if (content == null) { content = ""; } if (!content.equals(this.content)) { setContentDirty(true); setWikiNode(null); } this.content = content; // invalidate parsed xdom this.xdom = null; } public void setContent(XDOM content) throws XWikiException { setContent(renderXDOM(content, getSyntax())); } public String getRenderedContent(Syntax targetSyntax, XWikiContext context) throws XWikiException { // Note: We are currently duplicating code from the other getRendered signature because some calling // code is expecting that the rendering will happen in the calling document's context and not in this // document's context. For example this is true for the Admin page, see String renderedContent; Object isInRenderingEngine = context.get("isInRenderingEngine"); try { // This tells display() methods that we are inside the rendering engine and thus // that they can return wiki syntax and not HTML syntax (which is needed when // outside the rendering engine, i.e. when we're inside templates using only // Velocity for example). context.put("isInRenderingEngine", true); // If the Syntax id is "xwiki/1.0" then use the old rendering subsystem. Otherwise use the new one. if (is10Syntax()) { renderedContent = context.getWiki().getRenderingEngine().renderDocument(this, context); } else { renderedContent = performSyntaxConversion(getTranslatedContent(context), getSyntaxId(), targetSyntax, true); } } finally { if (isInRenderingEngine != null) { context.put("isInRenderingEngine", isInRenderingEngine); } else { context.remove("isInRenderingEngine"); } } return renderedContent; } public String getRenderedContent(XWikiContext context) throws XWikiException { return getRenderedContent(Syntax.XHTML_1_0, context); } /** * @param text the text to render * @param syntaxId the id of the Syntax used by the passed text (for example: "xwiki/1.0") * @param context the XWiki Context object * @return the given text rendered in the context of this document using the passed Syntax * @since 1.6M1 */ public String getRenderedContent(String text, String syntaxId, XWikiContext context) { return getRenderedContent(text, syntaxId, Syntax.XHTML_1_0.toIdString(), context); } /** * @param text the text to render * @param sourceSyntaxId the id of the Syntax used by the passed text (for example: "xwiki/1.0") * @param targetSyntaxId the id of the syntax in which to render the document content * @return the given text rendered in the context of this document using the passed Syntax * @since 2.0M3 */ public String getRenderedContent(String text, String sourceSyntaxId, String targetSyntaxId, XWikiContext context) { String result; HashMap<String, Object> backup = new HashMap<String, Object>(); Object isInRenderingEngine = context.get("isInRenderingEngine"); try { backupContext(backup, context); setAsContextDoc(context); // This tells display() methods that we are inside the rendering engine and thus // that they can return wiki syntax and not HTML syntax (which is needed when // outside the rendering engine, i.e. when we're inside templates using only // Velocity for example). context.put("isInRenderingEngine", true); // If the Syntax id is "xwiki/1.0" then use the old rendering subsystem. Otherwise use the new one. if (is10Syntax(sourceSyntaxId)) { result = context.getWiki().getRenderingEngine().renderText(text, this, context); } else { SyntaxFactory syntaxFactory = Utils.getComponent(SyntaxFactory.class); result = performSyntaxConversion(text, sourceSyntaxId, syntaxFactory.createSyntaxFromIdString(targetSyntaxId), true); } } catch (Exception e) { // Failed to render for some reason. This method should normally throw an exception but this // requires changing the signature of calling methods too. LOG.warn(e); result = ""; } finally { restoreContext(backup, context); if (isInRenderingEngine != null) { context.put("isInRenderingEngine", isInRenderingEngine); } else { context.remove("isInRenderingEngine"); } } return result; } public String getEscapedContent(XWikiContext context) throws XWikiException { CharacterFilter filter = new CharacterFilter(); return filter.process(getTranslatedContent(context)); } /** * Note that this method cannot be removed for now since it's used by Hibernate for saving a XWikiDocument. * * @deprecated since 2.2M1 used {@link #getDocumentReference()} instead */ @Deprecated public String getName() { return getDocumentReference().getName(); } /** * Note that this method cannot be removed for now since it's used by Hibernate for loading a XWikiDocument. * * @deprecated since 2.2M1 used {@link #setDocumentReference(DocumentReference)} instead */ @Deprecated public void setName(String name) { if (name != null) { getDocumentReference().setName(name); } } /** * {@inheritDoc} * * @see org.xwiki.bridge.DocumentModelBridge#getDocumentReference() * @since 2.2M1 */ public DocumentReference getDocumentReference() { return this.documentReference; } /** * @return the document's space + page name (eg "space.page") * @deprecated since 2.2M1 use {@link #getDocumentReference()} instead */ @Deprecated public String getFullName() { return this.localEntityReferenceSerializer.serialize(getDocumentReference()); } /** * @return the docoument's wiki + space + page name (eg "wiki:space.page") * @deprecated since 2.2M1 use {@link #getDocumentReference()} instead */ @Deprecated public String getPrefixedFullName() { return this.defaultEntityReferenceSerializer.serialize(getDocumentReference()); } /** * @since 2.2M1 */ public void setDocumentReference(DocumentReference reference) { // Don't allow setting a null reference for now, ie. don't do anything to preserve backward compatibility // with previous behavior (i.e. {@link #setFullName}. if (reference != null) { if (!reference.equals(getDocumentReference())) { this.documentReference = reference; setMetaDataDirty(true); } } } /** * @deprecated since 2.2M1 use {@link #setDocumentReference(org.xwiki.model.reference.DocumentReference)} instead */ @Deprecated public void setFullName(String name) { setFullName(name, null); } /** * @deprecated since 2.2M1 use {@link #setDocumentReference(org.xwiki.model.reference.DocumentReference)} instead */ @Deprecated public void setFullName(String fullName, XWikiContext context) { // We ignore the passed full name if it's null to be backward compatible with previous behaviors and to be // consistent with {@link #setName} and {@link #setSpace}. if (fullName != null) { // Note: We use the CurrentMixed Resolver since we want to use the default page name if the page isn't // specified in the passed string, rather than use the current document's page name. setDocumentReference(this.currentMixedDocumentReferenceResolver.resolve(fullName)); } } /** * {@inheritDoc} * * @see org.xwiki.bridge.DocumentModelBridge#getDocumentName() * @deprecated replaced by {@link #getDocumentReference()} since 2.2M1 */ @Deprecated public org.xwiki.bridge.DocumentName getDocumentName() { return new org.xwiki.bridge.DocumentName(getWikiName(), getSpaceName(), getPageName()); } /** * {@inheritDoc} * * @see DocumentModelBridge#getWikiName() * @deprecated since 2.2M1 use {@link #getDocumentReference()} instead */ @Deprecated public String getWikiName() { return getDatabase(); } /** * {@inheritDoc} * * @see DocumentModelBridge#getSpaceName() * @deprecated since 2.2M1 use {@link #getDocumentReference()} instead */ @Deprecated public String getSpaceName() { return this.getSpace(); } /** * {@inheritDoc} * * @see DocumentModelBridge#getSpaceName() * @deprecated since 2.2M1 use {@link #getDocumentReference()} instead */ @Deprecated public String getPageName() { return this.getName(); } public String getTitle() { return (this.title != null) ? this.title : ""; } /** * @param context the XWiki context used to get access to the XWikiRenderingEngine object * @return the document title. If a title has not been provided, look for a section title in the document's content * and if not found return the page name. The returned title is also interpreted which means it's allowed to * use Velocity, Groovy, etc syntax within a title. * @deprecated use {@link #getRenderedContentTitle(Syntax, XWikiContext)} instead */ @Deprecated public String getDisplayTitle(XWikiContext context) { return getRenderedTitle(Syntax.XHTML_1_0, context); } /** * The first found first or second level header content is rendered with * {@link XWikiRenderingEngine#interpretText(String, XWikiDocument, XWikiContext)}. * * @param context the XWiki context * @return the rendered version of the found header content. Empty string if not can be found. */ private String getRenderedContentTitle10(XWikiContext context) { // 1) Check if the user has provided a title String title = extractTitle10(); // 3) Last if a title has been found renders it as it can contain macros, velocity code, // groovy, etc. if (title.length() > 0) { // Only needed for xwiki 1.0 syntax, for other syntaxes it's already rendered in #extractTitle // This will not completely work for scripting code in title referencing variables // defined elsewhere. In that case it'll only work if those variables have been // parsed and put in the corresponding scripting context. This will not work for // breadcrumbs for example. title = context.getWiki().getRenderingEngine().interpretText(title, this, context); } return title; } /** * Get the rendered version of the first of second level first found header content in the document content. * <ul> * <li>xwiki/1.0: the first found first or second level header content is rendered with * {@link XWikiRenderingEngine#interpretText(String, XWikiDocument, XWikiContext)}</li> * <li>xwiki/2.0: the first found first or seconf level content is executed and rendered with renderer for the * provided syntax</li> * </ul> * * @param outputSyntax the syntax to render to. This is not taken into account for xwiki/1.0 syntax. * @param context the XWiki context * @return the rendered version of the title. null or empty (when xwiki/1.0 syntax) string if none can be found * @throws XWikiException failed to render content */ private String getRenderedContentTitle(Syntax outputSyntax, XWikiContext context) throws XWikiException { String title = null; if (is10Syntax()) { title = getRenderedContentTitle10(context); } else { List<HeaderBlock> blocks = getXDOM().getChildrenByType(HeaderBlock.class, true); if (blocks.size() > 0) { HeaderBlock header = blocks.get(0); if (header.getLevel().compareTo(HeaderLevel.LEVEL2) <= 0) { XDOM headerXDOM = new XDOM(Collections.<Block> singletonList(header)); // transform try { Utils.getComponent(TransformationManager.class).performTransformations(headerXDOM, getSyntax()); } catch (TransformationException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_UNKNOWN, "Failed to transform document", e); } // render Block headerBlock = headerXDOM.getChildren().get(0); if (headerBlock instanceof HeaderBlock) { title = renderXDOM(new XDOM(headerBlock.getChildren()), outputSyntax); } } } } return title; } /** * Get the rendered version of the title of the document. * <ul> * <li>if document <code>title</code> field is not empty: it's returned after a call to * {@link XWikiRenderingEngine#interpretText(String, XWikiDocument, XWikiContext)}</li> * <li>if document <code>title</code> field is empty: see {@link #getRenderedContentTitle(Syntax, XWikiContext)}</li> * <li>if after the two first step the title is still empty, the page name is returned</li> * </ul> * * @param outputSyntax the syntax to render to. This is not taken into account for xwiki/1.0 syntax. * @param context the XWiki context * @return the rendered version of the title */ public String getRenderedTitle(Syntax outputSyntax, XWikiContext context) { // 1) Check if the user has provided a title String title = getTitle(); try { if (!StringUtils.isEmpty(title)) { title = context.getWiki().getRenderingEngine().interpretText(title, this, context); if (!outputSyntax.equals(Syntax.HTML_4_01) && !outputSyntax.equals(Syntax.XHTML_1_0)) { XDOM xdom = parseContent(Syntax.HTML_4_01.toIdString(), title); this.parserUtils.removeTopLevelParagraph(xdom.getChildren()); title = renderXDOM(xdom, outputSyntax); } return title; } } catch (Exception e) { LOG.warn("Failed to interpret title of document [" + this.defaultEntityReferenceSerializer.serialize(getDocumentReference()) + "]", e); } try { // 2) If not, then try to extract the title from the first document section title title = getRenderedContentTitle(outputSyntax, context); } catch (Exception e) { LOG.warn("Failed to extract title from content of document [" + this.defaultEntityReferenceSerializer.serialize(getDocumentReference()) + "]", e); } // 3) No title has been found, return the page name as the title if (StringUtils.isEmpty(title)) { title = getDocumentReference().getName(); } return title; } public String extractTitle() { String title = ""; try { if (is10Syntax()) { title = extractTitle10(); } else { List<HeaderBlock> blocks = getXDOM().getChildrenByType(HeaderBlock.class, true); if (blocks.size() > 0) { HeaderBlock header = blocks.get(0); if (header.getLevel().compareTo(HeaderLevel.LEVEL2) <= 0) { XDOM headerXDOM = new XDOM(Collections.<Block> singletonList(header)); // transform Utils.getComponent(TransformationManager.class).performTransformations(headerXDOM, getSyntax()); // render Block headerBlock = headerXDOM.getChildren().get(0); if (headerBlock instanceof HeaderBlock) { title = renderXDOM(new XDOM(headerBlock.getChildren()), Syntax.XHTML_1_0); } } } } } catch (Exception e) { } return title; } /** * @return the first level 1 or level 1.1 title text in the document's content or "" if none are found * @todo this method has nothing to do in this class and should be moved elsewhere */ private String extractTitle10() { String content = getContent(); Matcher m = HEADING_PATTERN_10.matcher(content); if (m.find()) { return m.group(1).trim(); } return ""; } public void setTitle(String title) { if (title != null && !title.equals(this.title)) { setContentDirty(true); } this.title = title; } public String getFormat() { return this.format != null ? this.format : ""; } public void setFormat(String format) { this.format = format; if (!format.equals(this.format)) { setMetaDataDirty(true); } } public String getAuthor() { return this.author != null ? this.author.trim() : ""; } public String getContentAuthor() { return this.contentAuthor != null ? this.contentAuthor.trim() : ""; } public void setAuthor(String author) { if (!getAuthor().equals(author)) { setMetaDataDirty(true); } this.author = author; } public void setContentAuthor(String contentAuthor) { if (!getContentAuthor().equals(contentAuthor)) { setMetaDataDirty(true); } this.contentAuthor = contentAuthor; } public String getCreator() { return this.creator != null ? this.creator.trim() : ""; } public void setCreator(String creator) { if (!getCreator().equals(creator)) { setMetaDataDirty(true); } this.creator = creator; } public Date getDate() { if (this.updateDate == null) { return new Date(); } else { return this.updateDate; } } public void setDate(Date date) { if ((date != null) && (!date.equals(this.updateDate))) { setMetaDataDirty(true); } // Make sure we drop milliseconds for consistency with the database if (date != null) { date.setTime((date.getTime() / 1000) * 1000); } this.updateDate = date; } public Date getCreationDate() { if (this.creationDate == null) { return new Date(); } else { return this.creationDate; } } public void setCreationDate(Date date) { if ((date != null) && (!date.equals(this.creationDate))) { setMetaDataDirty(true); } // Make sure we drop milliseconds for consistency with the database if (date != null) { date.setTime((date.getTime() / 1000) * 1000); } this.creationDate = date; } public Date getContentUpdateDate() { if (this.contentUpdateDate == null) { return new Date(); } else { return this.contentUpdateDate; } } public void setContentUpdateDate(Date date) { if ((date != null) && (!date.equals(this.contentUpdateDate))) { setMetaDataDirty(true); } // Make sure we drop milliseconds for consistency with the database if (date != null) { date.setTime((date.getTime() / 1000) * 1000); } this.contentUpdateDate = date; } public String getMeta() { return this.meta; } public void setMeta(String meta) { if (meta == null) { if (this.meta != null) { setMetaDataDirty(true); } } else if (!meta.equals(this.meta)) { setMetaDataDirty(true); } this.meta = meta; } public void appendMeta(String meta) { StringBuffer buf = new StringBuffer(this.meta); buf.append(meta); buf.append("\n"); this.meta = buf.toString(); setMetaDataDirty(true); } public boolean isContentDirty() { return this.isContentDirty; } public void incrementVersion() { if (this.version == null) { this.version = new Version("1.1"); } else { if (isMinorEdit()) { this.version = this.version.next(); } else { this.version = this.version.getBranchPoint().next().newBranch(1); } } } public void setContentDirty(boolean contentDirty) { this.isContentDirty = contentDirty; } public boolean isMetaDataDirty() { return this.isMetaDataDirty; } public void setMetaDataDirty(boolean metaDataDirty) { this.isMetaDataDirty = metaDataDirty; } public String getAttachmentURL(String filename, XWikiContext context) { return getAttachmentURL(filename, "download", context); } public String getAttachmentURL(String filename, String action, XWikiContext context) { URL url = context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, null, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getExternalAttachmentURL(String filename, String action, XWikiContext context) { URL url = context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, null, getDatabase(), context); return url.toString(); } public String getAttachmentURL(String filename, String action, String querystring, XWikiContext context) { URL url = context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, querystring, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getAttachmentRevisionURL(String filename, String revision, XWikiContext context) { URL url = context.getURLFactory().createAttachmentRevisionURL(filename, getSpace(), getName(), revision, null, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getAttachmentRevisionURL(String filename, String revision, String querystring, XWikiContext context) { URL url = context.getURLFactory().createAttachmentRevisionURL(filename, getSpace(), getName(), revision, querystring, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getURL(String action, String params, boolean redirect, XWikiContext context) { URL url = context.getURLFactory().createURL(getSpace(), getName(), action, params, null, getDatabase(), context); if (redirect) { if (url == null) { return null; } else { return url.toString(); } } else { return context.getURLFactory().getURL(url, context); } } public String getURL(String action, boolean redirect, XWikiContext context) { return getURL(action, null, redirect, context); } public String getURL(String action, XWikiContext context) { return getURL(action, false, context); } public String getURL(String action, String querystring, XWikiContext context) { URL url = context.getURLFactory().createURL(getSpace(), getName(), action, querystring, null, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getURL(String action, String querystring, String anchor, XWikiContext context) { URL url = context.getURLFactory().createURL(getSpace(), getName(), action, querystring, anchor, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getExternalURL(String action, XWikiContext context) { URL url = context.getURLFactory().createExternalURL(getSpace(), getName(), action, null, null, getDatabase(), context); return url.toString(); } public String getExternalURL(String action, String querystring, XWikiContext context) { URL url = context.getURLFactory().createExternalURL(getSpace(), getName(), action, querystring, null, getDatabase(), context); return url.toString(); } public String getParentURL(XWikiContext context) throws XWikiException { XWikiDocument doc = new XWikiDocument(getParentReference()); URL url = context.getURLFactory().createURL(doc.getSpace(), doc.getName(), "view", null, null, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public XWikiDocumentArchive getDocumentArchive(XWikiContext context) throws XWikiException { loadArchive(context); return getDocumentArchive(); } /** * Create a new protected {@link com.xpn.xwiki.api.Document} public API to access page information and actions from * scripting. * * @param customClassName the name of the custom {@link com.xpn.xwiki.api.Document} class of the object to create. * @param context the XWiki context. * @return a wrapped version of an XWikiDocument. Prefer this function instead of new Document(XWikiDocument, * XWikiContext) */ public com.xpn.xwiki.api.Document newDocument(String customClassName, XWikiContext context) { if (!((customClassName == null) || (customClassName.equals("")))) { try { return newDocument(Class.forName(customClassName), context); } catch (ClassNotFoundException e) { LOG.error("Failed to get java Class object from class name", e); } } return new com.xpn.xwiki.api.Document(this, context); } /** * Create a new protected {@link com.xpn.xwiki.api.Document} public API to access page information and actions from * scripting. * * @param customClass the custom {@link com.xpn.xwiki.api.Document} class the object to create. * @param context the XWiki context. * @return a wrapped version of an XWikiDocument. Prefer this function instead of new Document(XWikiDocument, * XWikiContext) */ public com.xpn.xwiki.api.Document newDocument(Class< ? > customClass, XWikiContext context) { if (customClass != null) { try { Class< ? >[] classes = new Class[] {XWikiDocument.class, XWikiContext.class}; Object[] args = new Object[] {this, context}; return (com.xpn.xwiki.api.Document) customClass.getConstructor(classes).newInstance(args); } catch (Exception e) { LOG.error("Failed to create a custom Document object", e); } } return new com.xpn.xwiki.api.Document(this, context); } public com.xpn.xwiki.api.Document newDocument(XWikiContext context) { String customClass = getCustomClass(); return newDocument(customClass, context); } public void loadArchive(XWikiContext context) throws XWikiException { if (this.archive == null || this.archive.get() == null) { XWikiDocumentArchive arch = getVersioningStore(context).getXWikiDocumentArchive(this, context); // We are using a SoftReference which will allow the archive to be // discarded by the Garbage collector as long as the context is closed (usually during // the request) this.archive = new SoftReference<XWikiDocumentArchive>(arch); } } public XWikiDocumentArchive getDocumentArchive() { // We are using a SoftReference which will allow the archive to be // discarded by the Garbage collector as long as the context is closed (usually during the // request) if (this.archive == null) { return null; } else { return this.archive.get(); } } public void setDocumentArchive(XWikiDocumentArchive arch) { // We are using a SoftReference which will allow the archive to be // discarded by the Garbage collector as long as the context is closed (usually during the // request) if (arch != null) { this.archive = new SoftReference<XWikiDocumentArchive>(arch); } } public void setDocumentArchive(String sarch) throws XWikiException { XWikiDocumentArchive xda = new XWikiDocumentArchive(getId()); xda.setArchive(sarch); setDocumentArchive(xda); } public Version[] getRevisions(XWikiContext context) throws XWikiException { return getVersioningStore(context).getXWikiDocVersions(this, context); } public String[] getRecentRevisions(int nb, XWikiContext context) throws XWikiException { try { Version[] revisions = getVersioningStore(context).getXWikiDocVersions(this, context); int length = nb; // 0 means all revisions if (nb == 0) { length = revisions.length; } if (revisions.length < length) { length = revisions.length; } String[] recentrevs = new String[length]; for (int i = 1; i <= length; i++) { recentrevs[i - 1] = revisions[revisions.length - i].toString(); } return recentrevs; } catch (Exception e) { return new String[0]; } } /** * Get document versions matching criterias like author, minimum creation date, etc. * * @param criteria criteria used to match versions * @return a list of matching versions */ public List<String> getRevisions(RevisionCriteria criteria, XWikiContext context) throws XWikiException { List<String> results = new ArrayList<String>(); Version[] revisions = getRevisions(context); XWikiRCSNodeInfo nextNodeinfo = null; XWikiRCSNodeInfo nodeinfo; for (int i = 0; i < revisions.length; i++) { nodeinfo = nextNodeinfo; nextNodeinfo = getRevisionInfo(revisions[i].toString(), context); if (nodeinfo == null) { continue; } // Minor/Major version matching if (criteria.getIncludeMinorVersions() || !nextNodeinfo.isMinorEdit()) { // Author matching if (criteria.getAuthor().equals("") || criteria.getAuthor().equals(nodeinfo.getAuthor())) { // Date range matching Date versionDate = nodeinfo.getDate(); if (versionDate.after(criteria.getMinDate()) && versionDate.before(criteria.getMaxDate())) { results.add(nodeinfo.getVersion().toString()); } } } } nodeinfo = nextNodeinfo; if (nodeinfo != null) { if (criteria.getAuthor().equals("") || criteria.getAuthor().equals(nodeinfo.getAuthor())) { // Date range matching Date versionDate = nodeinfo.getDate(); if (versionDate.after(criteria.getMinDate()) && versionDate.before(criteria.getMaxDate())) { results.add(nodeinfo.getVersion().toString()); } } } return criteria.getRange().subList(results); } public XWikiRCSNodeInfo getRevisionInfo(String version, XWikiContext context) throws XWikiException { return getDocumentArchive(context).getNode(new Version(version)); } /** * @return Is this version the most recent one. False if and only if there are newer versions of this document in * the database. */ public boolean isMostRecent() { return this.mostRecent; } /** * must not be used unless in store system. * * @param mostRecent - mark document as most recent. */ public void setMostRecent(boolean mostRecent) { this.mostRecent = mostRecent; } /** * @since 2.2M1 */ public BaseClass getXClass() { if (this.xClass == null) { this.xClass = new BaseClass(); this.xClass.setXClassReference(getDocumentReference()); } return this.xClass; } /** * @deprecated since 2.2M1, use {@link #getXClass()} instead */ @Deprecated public BaseClass getxWikiClass() { return getXClass(); } /** * @since 2.2M1 */ public void setXClass(BaseClass xwikiClass) { this.xClass = xwikiClass; } /** * @deprecated since 2.2M1, use {@link #setXClass(BaseClass)} instead */ @Deprecated public void setxWikiClass(BaseClass xwikiClass) { setXClass(xwikiClass); } /** * @since 2.2M1 */ public Map<DocumentReference, List<BaseObject>> getXObjects() { return this.xObjects; } /** * @deprecated since 2.2M1 use {@link #getXObjects()} instead. Warning: if you used to modify the returned Map note * that since 2.2M1 this will no longer work and you'll need to call the setXObject methods instead (or * setxWikiObjects()). Obviously the best is to move to the new API. */ @Deprecated public Map<String, Vector<BaseObject>> getxWikiObjects() { // Use a liked hash map to ensure we keep the order stored from the internal objects map. Map<String, Vector<BaseObject>> objects = new LinkedHashMap<String, Vector<BaseObject>>(); for (Map.Entry<DocumentReference, List<BaseObject>> entry : getXObjects().entrySet()) { objects.put(this.compactWikiEntityReferenceSerializer.serialize(entry.getKey()), new Vector<BaseObject>( entry.getValue())); } return objects; } /** * @since 2.2M1 */ public void setXObjects(Map<DocumentReference, List<BaseObject>> objects) { this.xObjects = objects; } /** * @deprecated since 2.2M1 use {@link #setXObjects(Map)} instead */ @Deprecated public void setxWikiObjects(Map<String, Vector<BaseObject>> objects) { // Use a liked hash map to ensure we keep the order stored from the internal objects map. Map<DocumentReference, List<BaseObject>> newObjects = new LinkedHashMap<DocumentReference, List<BaseObject>>(); for (Map.Entry<String, Vector<BaseObject>> entry : objects.entrySet()) { newObjects.put(resolveClassReference(entry.getKey()), new ArrayList<BaseObject>(entry.getValue())); } setXObjects(newObjects); } /** * @since 2.2M1 */ public BaseObject getXObject() { return getXObject(getDocumentReference()); } /** * @deprecated since 2.2M1 use {@link #getXObject()} instead */ @Deprecated public BaseObject getxWikiObject() { return getXObject(getDocumentReference()); } /** * @since 2.2M1 */ public List<BaseClass> getXClasses(XWikiContext context) { List<BaseClass> list = new ArrayList<BaseClass>(); // getXObjects() is a TreeMap, with elements sorted by className reference for (DocumentReference classReference : getXObjects().keySet()) { BaseClass bclass = null; List<BaseObject> objects = getXObjects(classReference); for (BaseObject obj : objects) { if (obj != null) { bclass = obj.getXClass(context); if (bclass != null) { break; } } } if (bclass != null) { list.add(bclass); } } return list; } /** * @deprecated since 2.2M1 use {@link #getXClasses(XWikiContext)} instead */ @Deprecated public List<BaseClass> getxWikiClasses(XWikiContext context) { return getXClasses(context); } /** * @since 2.2M1 */ public int createXObject(DocumentReference classReference, XWikiContext context) throws XWikiException { String className = this.compactWikiEntityReferenceSerializer.serialize(classReference); BaseObject object = BaseClass.newCustomClassInstance(className, context); object.setDocumentReference(getDocumentReference()); object.setXClassReference(classReference); List<BaseObject> objects = getXObjects(classReference); if (objects == null) { objects = new ArrayList<BaseObject>(); setXObjects(classReference, objects); } objects.add(object); int nb = objects.size() - 1; object.setNumber(nb); setContentDirty(true); return nb; } /** * @deprecated since 2.2M1 use {@link #createXObject(DocumentReference, XWikiContext)} instead */ @Deprecated public int createNewObject(String className, XWikiContext context) throws XWikiException { return createXObject(resolveClassReference(className), context); } /** * @since 2.2M1 */ public int getXObjectSize(DocumentReference classReference) { try { return getXObjects().get(classReference).size(); } catch (Exception e) { return 0; } } /** * @deprecated since 2.2M1 use {@link #getXObjectSize(DocumentReference)} instead */ @Deprecated public int getObjectNumbers(String className) { return getXObjectSize(resolveClassReference(className)); } /** * @since 2.2M1 */ public List<BaseObject> getXObjects(DocumentReference classReference) { if (classReference == null) { return new ArrayList<BaseObject>(); } return getXObjects().get(classReference); } /** * @deprecated since 2.2M1 use {@link #getXObjects(DocumentReference)} instead */ @Deprecated public Vector<BaseObject> getObjects(String className) { List<BaseObject> result = getXObjects(resolveClassReference(className)); return result == null ? null : new Vector<BaseObject>(result); } /** * @since 2.2M1 */ public void setXObjects(DocumentReference classReference, List<BaseObject> objects) { getXObjects().put(classReference, objects); } /** * @deprecated since 2.2M1 use {@link #setXObjects(DocumentReference, List)} instead */ @Deprecated public void setObjects(String className, Vector<BaseObject> objects) { setXObjects(resolveClassReference(className), new ArrayList<BaseObject>(objects)); } /** * @since 2.2M1 */ public BaseObject getXObject(DocumentReference classReference) { BaseObject result = null; List<BaseObject> objects = getXObjects().get(classReference); if (objects != null) { for (int i = 0; i < objects.size(); i++) { BaseObject object = objects.get(i); if (object != null) { result = object; break; } } } return result; } /** * @deprecated since 2.2M1 use {@link #getXObject(DocumentReference)} instead */ @Deprecated public BaseObject getObject(String className) { return getXObject(resolveClassReference(className)); } /** * @since 2.2M1 */ public BaseObject getXObject(DocumentReference classReference, int nb) { try { return getXObjects().get(classReference).get(nb); } catch (Exception e) { return null; } } /** * @deprecated since 2.2M1 use {@link #getXObject(DocumentReference, int)} instead */ @Deprecated public BaseObject getObject(String className, int nb) { return getXObject(resolveClassReference(className), nb); } /** * @since 2.2M1 */ public BaseObject getXObject(DocumentReference classReference, String key, String value) { return getXObject(classReference, key, value, false); } /** * @deprecated since 2.2M1 use {@link #getXObject(DocumentReference, String, String)} instead */ @Deprecated public BaseObject getObject(String className, String key, String value) { return getObject(className, key, value, false); } /** * @since 2.2M1 */ public BaseObject getXObject(DocumentReference classReference, String key, String value, boolean failover) { try { if (value == null) { if (failover) { return getXObject(classReference); } else { return null; } } List<BaseObject> objects = getXObjects().get(classReference); if ((objects == null) || (objects.size() == 0)) { return null; } for (int i = 0; i < objects.size(); i++) { BaseObject obj = objects.get(i); if (obj != null) { if (value.equals(obj.getStringValue(key))) { return obj; } } } if (failover) { return getXObject(classReference); } else { return null; } } catch (Exception e) { if (failover) { return getXObject(classReference); } e.printStackTrace(); return null; } } /** * @deprecated since 2.2M1 use {@link #getXObject(DocumentReference, String, String, boolean)} instead */ @Deprecated public BaseObject getObject(String className, String key, String value, boolean failover) { return getXObject(resolveClassReference(className), key, value, failover); } /** * @since 2.2M1 */ public void addXObject(DocumentReference classReference, BaseObject object) { List<BaseObject> vobj = getXObjects(classReference); if (vobj == null) { setXObject(classReference, 0, object); } else { setXObject(classReference, vobj.size(), object); } } /** * @deprecated since 2.2M1 use {@link #addXObject(DocumentReference, BaseObject)} instead */ @Deprecated public void addObject(String className, BaseObject object) { addXObject(resolveClassReference(className), object); } /** * @since 2.2M1 */ public void setXObject(DocumentReference classReference, int nb, BaseObject object) { if (object != null) { object.setDocumentReference(getDocumentReference()); object.setNumber(nb); } List<BaseObject> objects = getXObjects(classReference); if (objects == null) { objects = new ArrayList<BaseObject>(); setXObjects(classReference, objects); } while (nb >= objects.size()) { objects.add(null); } objects.set(nb, object); setContentDirty(true); } /** * @deprecated since 2.2M1 use {@link #setXObject(DocumentReference, int, BaseObject)} instead */ @Deprecated public void setObject(String className, int nb, BaseObject object) { setXObject(resolveClassReference(className), nb, object); } /** * @return true if the document is a new one (i.e. it has never been saved) or false otherwise */ public boolean isNew() { return this.isNew; } public void setNew(boolean aNew) { this.isNew = aNew; } /** * @since 2.2M1 */ public void mergeXClass(XWikiDocument templatedoc) { BaseClass bclass = getXClass(); BaseClass tbclass = templatedoc.getXClass(); if (tbclass != null) { if (bclass == null) { setXClass((BaseClass) tbclass.clone()); } else { getXClass().merge((BaseClass) tbclass.clone()); } } setContentDirty(true); } /** * @deprecated since 2.2M1 use {@link #mergeXClass(XWikiDocument)} instead */ @Deprecated public void mergexWikiClass(XWikiDocument templatedoc) { mergeXClass(templatedoc); } /** * @since 2.2M1 */ public void mergeXObjects(XWikiDocument templatedoc) { // TODO: look for each object if it already exist and add it if it doesn't for (DocumentReference reference : templatedoc.getXObjects().keySet()) { List<BaseObject> myObjects = getXObjects().get(reference); if (myObjects == null) { myObjects = new ArrayList<BaseObject>(); } for (BaseObject otherObject : templatedoc.getXObjects().get(reference)) { if (otherObject != null) { BaseObject myObject = (BaseObject) otherObject.clone(); // BaseObject.clone copies the GUID, so randomize it for the copied object. myObject.setGuid(UUID.randomUUID().toString()); myObjects.add(myObject); myObject.setNumber(myObjects.size() - 1); } } getXObjects().put(reference, myObjects); } setContentDirty(true); } /** * @deprecated since 2.2M1 use {@link #mergeXObjects(XWikiDocument)} instead */ @Deprecated public void mergexWikiObjects(XWikiDocument templatedoc) { mergeXObjects(templatedoc); } /** * @since 2.2M1 */ public void cloneXObjects(XWikiDocument templatedoc) { for (DocumentReference reference : templatedoc.getXObjects().keySet()) { List<BaseObject> tobjects = templatedoc.getXObjects(reference); List<BaseObject> objects = new ArrayList<BaseObject>(); while (objects.size() < tobjects.size()) { objects.add(null); } for (int i = 0; i < tobjects.size(); i++) { BaseObject otherObject = tobjects.get(i); if (otherObject != null) { BaseObject myObject = (BaseObject) otherObject.clone(); objects.set(i, myObject); } } getXObjects().put(reference, objects); } } /** * @deprecated since 2.2M1 use {@link #cloneXObjects(XWikiDocument)} instead */ @Deprecated public void clonexWikiObjects(XWikiDocument templatedoc) { cloneXObjects(templatedoc); } /** * @since 2.2M1 */ public DocumentReference getTemplateDocumentReference() { return this.templateDocumentReference; } /** * @deprecated since 2.2M1 use {@link #getTemplateDocumentReference()} instead */ @Deprecated public String getTemplate() { String templateReferenceAsString; DocumentReference templateDocumentReference = getTemplateDocumentReference(); if (templateDocumentReference != null) { templateReferenceAsString = this.localEntityReferenceSerializer.serialize(templateDocumentReference); } else { templateReferenceAsString = ""; } return templateReferenceAsString; } /** * @since 2.2M1 */ public void setTemplateDocumentReference(DocumentReference templateDocumentReference) { if ((templateDocumentReference == null && getTemplateDocumentReference() != null) || (templateDocumentReference != null && !templateDocumentReference.equals(getTemplateDocumentReference()))) { this.templateDocumentReference = templateDocumentReference; setMetaDataDirty(true); } } /** * @deprecated since 2.2M1 use {@link #setTemplateDocumentReference(DocumentReference)} instead */ @Deprecated public void setTemplate(String template) { DocumentReference templateReference = null; if (!StringUtils.isEmpty(template)) { templateReference = this.currentMixedDocumentReferenceResolver.resolve(template); } setTemplateDocumentReference(templateReference); } public String displayPrettyName(String fieldname, XWikiContext context) { return displayPrettyName(fieldname, false, true, context); } public String displayPrettyName(String fieldname, boolean showMandatory, XWikiContext context) { return displayPrettyName(fieldname, showMandatory, true, context); } public String displayPrettyName(String fieldname, boolean showMandatory, boolean before, XWikiContext context) { try { BaseObject object = getXObject(); if (object == null) { object = getFirstObject(fieldname, context); } return displayPrettyName(fieldname, showMandatory, before, object, context); } catch (Exception e) { return ""; } } public String displayPrettyName(String fieldname, BaseObject obj, XWikiContext context) { return displayPrettyName(fieldname, false, true, obj, context); } public String displayPrettyName(String fieldname, boolean showMandatory, BaseObject obj, XWikiContext context) { return displayPrettyName(fieldname, showMandatory, true, obj, context); } public String displayPrettyName(String fieldname, boolean showMandatory, boolean before, BaseObject obj, XWikiContext context) { try { PropertyClass pclass = (PropertyClass) obj.getXClass(context).get(fieldname); String dprettyName = ""; if (showMandatory) { dprettyName = context.getWiki().addMandatory(context); } if (before) { return dprettyName + pclass.getPrettyName(context); } else { return pclass.getPrettyName(context) + dprettyName; } } catch (Exception e) { return ""; } } public String displayTooltip(String fieldname, XWikiContext context) { try { BaseObject object = getXObject(); if (object == null) { object = getFirstObject(fieldname, context); } return displayTooltip(fieldname, object, context); } catch (Exception e) { return ""; } } public String displayTooltip(String fieldname, BaseObject obj, XWikiContext context) { String result = ""; try { PropertyClass pclass = (PropertyClass) obj.getXClass(context).get(fieldname); String tooltip = pclass.getTooltip(context); if ((tooltip != null) && (!tooltip.trim().equals(""))) { String img = "<img src=\"" + context.getWiki().getSkinFile("info.gif", context) + "\" class=\"tooltip_image\" align=\"middle\" />"; result = context.getWiki().addTooltip(img, tooltip, context); } } catch (Exception e) { } return result; } /** * @param fieldname the name of the field to display * @param context the XWiki context * @return the rendered field */ public String display(String fieldname, XWikiContext context) { String result = ""; try { BaseObject object = getXObject(); if (object == null) { object = getFirstObject(fieldname, context); } result = display(fieldname, object, context); } catch (Exception e) { LOG.error("Failed to display field [" + fieldname + "] of document [" + this.defaultEntityReferenceSerializer.serialize(getDocumentReference()) + "]", e); } return result; } /** * @param fieldname the name of the field to display * @param obj the object containing the field to display * @param context the XWiki context * @return the rendered field */ public String display(String fieldname, BaseObject obj, XWikiContext context) { String type = null; try { type = (String) context.get("display"); } catch (Exception e) { } if (type == null) { type = "view"; } return display(fieldname, type, obj, context); } /** * @param fieldname the name of the field to display * @param mode the mode to use ("view", "edit", ...) * @param context the XWiki context * @return the rendered field */ public String display(String fieldname, String mode, XWikiContext context) { return display(fieldname, mode, "", context); } /** * @param fieldname the name of the field to display * @param type the type of the field to display * @param obj the object containing the field to display * @param context the XWiki context * @return the rendered field */ public String display(String fieldname, String type, BaseObject obj, XWikiContext context) { return display(fieldname, type, "", obj, context); } /** * @param fieldname the name of the field to display * @param mode the mode to use ("view", "edit", ...) * @param prefix the prefix to add in the field identifier in edit display for example * @param context the XWiki context * @return the rendered field */ public String display(String fieldname, String mode, String prefix, XWikiContext context) { try { BaseObject object = getXObject(); if (object == null) { object = getFirstObject(fieldname, context); } if (object == null) { return ""; } else { return display(fieldname, mode, prefix, object, context); } } catch (Exception e) { return ""; } } /** * @param fieldname the name of the field to display * @param type the type of the field to display * @param obj the object containing the field to display * @param wrappingSyntaxId the syntax of the content in which the result will be included. This to take care of some * escaping depending of the syntax. * @param context the XWiki context * @return the rendered field */ public String display(String fieldname, String type, BaseObject obj, String wrappingSyntaxId, XWikiContext context) { return display(fieldname, type, "", obj, wrappingSyntaxId, context); } /** * @param fieldname the name of the field to display * @param type the type of the field to display * @param pref the prefix to add in the field identifier in edit display for example * @param obj the object containing the field to display * @param context the XWiki context * @return the rendered field */ public String display(String fieldname, String type, String pref, BaseObject obj, XWikiContext context) { return display(fieldname, type, pref, obj, context.getWiki().getCurrentContentSyntaxId(getSyntaxId(), context), context); } /** * @param fieldname the name of the field to display * @param type the type of the field to display * @param pref the prefix to add in the field identifier in edit display for example * @param obj the object containing the field to display * @param wrappingSyntaxId the syntax of the content in which the result will be included. This to take care of some * escaping depending of the syntax. * @param context the XWiki context * @return the rendered field */ public String display(String fieldname, String type, String pref, BaseObject obj, String wrappingSyntaxId, XWikiContext context) { if (obj == null) { return ""; } boolean isInRenderingEngine = BooleanUtils.toBoolean((Boolean) context.get("isInRenderingEngine")); HashMap<String, Object> backup = new HashMap<String, Object>(); try { backupContext(backup, context); setAsContextDoc(context); type = type.toLowerCase(); StringBuffer result = new StringBuffer(); PropertyClass pclass = (PropertyClass) obj.getXClass(context).get(fieldname); String prefix = pref + obj.getXClass(context).getName() + "_" + obj.getNumber() + "_"; if (pclass.isCustomDisplayed(context)) { pclass.displayCustom(result, fieldname, prefix, type, obj, context); } else if (type.equals("view")) { pclass.displayView(result, fieldname, prefix, obj, context); } else if (type.equals("rendered")) { String fcontent = pclass.displayView(fieldname, prefix, obj, context); // This mode is deprecated for the new rendering and should also be removed for the old rendering // since the way to implement this now is to choose the type of rendering to do in the class itself. // Thus for the new rendering we simply make this mode work like the "view" mode. if (is10Syntax(wrappingSyntaxId)) { result.append(getRenderedContent(fcontent, getSyntaxId(), context)); } else { result.append(fcontent); } } else if (type.equals("edit")) { context.addDisplayedField(fieldname); // If the Syntax id is "xwiki/1.0" then use the old rendering subsystem and prevent wiki syntax // rendering using the pre macro. In the new rendering system it's the XWiki Class itself that does the // escaping. For example for a textarea check the TextAreaClass class. // If the Syntax id is not "xwiki/1.0", i.e. if the new rendering engine is used then we need to // protect the content with a <pre> since otherwise whitespaces will be stripped by the HTML macro // used to surround the object property content (see below). if (is10Syntax(wrappingSyntaxId)) { // Don't use pre when not in the rendernig engine since for template we don't evaluate wiki syntax. if (isInRenderingEngine) { result.append("{pre}"); } } else { result.append("<pre>"); } pclass.displayEdit(result, fieldname, prefix, obj, context); if (is10Syntax(wrappingSyntaxId)) { if (isInRenderingEngine) { result.append("{/pre}"); } } else { result.append("</pre>"); } } else if (type.equals("hidden")) { // If the Syntax id is "xwiki/1.0" then use the old rendering subsystem and prevent wiki syntax // rendering using the pre macro. In the new rendering system it's the XWiki Class itself that does the // escaping. For example for a textarea check the TextAreaClass class. if (is10Syntax(wrappingSyntaxId) && isInRenderingEngine) { result.append("{pre}"); } pclass.displayHidden(result, fieldname, prefix, obj, context); if (is10Syntax(wrappingSyntaxId) && isInRenderingEngine) { result.append("{/pre}"); } } else if (type.equals("search")) { // If the Syntax id is "xwiki/1.0" then use the old rendering subsystem and prevent wiki syntax // rendering using the pre macro. In the new rendering system it's the XWiki Class itself that does the // escaping. For example for a textarea check the TextAreaClass class. if (is10Syntax(wrappingSyntaxId) && isInRenderingEngine) { result.append("{pre}"); } prefix = obj.getXClass(context).getName() + "_"; pclass.displaySearch(result, fieldname, prefix, (XWikiCriteria) context.get("query"), context); if (is10Syntax(wrappingSyntaxId) && isInRenderingEngine) { result.append("{/pre}"); } } else { pclass.displayView(result, fieldname, prefix, obj, context); } // If we're in new rendering engine we want to wrap the HTML returned by displayView() in // a {{html/}} macro so that the user doesn't have to do it. // We test if we're inside the rendering engine since it's also possible that this display() method is // called // directly from a template and in this case we only want HTML as a result and not wiki syntax. // TODO: find a more generic way to handle html macro because this works only for XWiki 1.0 and XWiki 2.0 // Add the {{html}}{{/html}} only when result really contains html since it's not needed for pure text if (isInRenderingEngine && !is10Syntax(wrappingSyntaxId) && (result.indexOf("<") != -1 || result.indexOf(">") != -1)) { result.insert(0, "{{html clean=\"false\" wiki=\"false\"}}"); result.append("{{/html}}"); } return result.toString(); } catch (Exception ex) { // TODO: It would better to check if the field exists rather than catching an exception // raised by a NPE as this is currently the case here... LOG.warn("Failed to display field [" + fieldname + "] in [" + type + "] mode for Object of Class [" + this.defaultEntityReferenceSerializer.serialize(obj.getDocumentReference()) + "]"); ex.printStackTrace(); return ""; } finally { restoreContext(backup, context); } } /** * @since 2.2M1 */ public String displayForm(DocumentReference classReference, String header, String format, XWikiContext context) { return displayForm(classReference, header, format, true, context); } /** * @deprecated since 2.2M1, use {@link #displayForm(DocumentReference, String, String, XWikiContext)} instead */ @Deprecated public String displayForm(String className, String header, String format, XWikiContext context) { return displayForm(className, header, format, true, context); } /** * @since 2.2M1 */ public String displayForm(DocumentReference classReference, String header, String format, boolean linebreak, XWikiContext context) { List<BaseObject> objects = getXObjects(classReference); if (format.endsWith("\\n")) { linebreak = true; } BaseObject firstobject = null; Iterator<BaseObject> foit = objects.iterator(); while ((firstobject == null) && foit.hasNext()) { firstobject = foit.next(); } if (firstobject == null) { return ""; } BaseClass bclass = firstobject.getXClass(context); if (bclass.getPropertyList().size() == 0) { return ""; } StringBuffer result = new StringBuffer(); VelocityContext vcontext = new VelocityContext(); for (String propertyName : bclass.getPropertyList()) { PropertyClass pclass = (PropertyClass) bclass.getField(propertyName); vcontext.put(pclass.getName(), pclass.getPrettyName()); } result.append(XWikiVelocityRenderer.evaluate(header, context.getDoc().getPrefixedFullName(), vcontext, context)); if (linebreak) { result.append("\n"); } // display each line for (int i = 0; i < objects.size(); i++) { vcontext.put("id", new Integer(i + 1)); BaseObject object = objects.get(i); if (object != null) { for (String name : bclass.getPropertyList()) { vcontext.put(name, display(name, object, context)); } result.append(XWikiVelocityRenderer.evaluate(format, context.getDoc().getPrefixedFullName(), vcontext, context)); if (linebreak) { result.append("\n"); } } } return result.toString(); } /** * @deprecated since 2.2M1, use {@link #displayForm(DocumentReference, String, String, boolean, XWikiContext)} * instead */ @Deprecated public String displayForm(String className, String header, String format, boolean linebreak, XWikiContext context) { return displayForm(resolveClassReference(className), header, format, linebreak, context); } /** * @since 2.2M1 */ public String displayForm(DocumentReference classReference, XWikiContext context) { List<BaseObject> objects = getXObjects(classReference); if (objects == null) { return ""; } BaseObject firstobject = null; Iterator<BaseObject> foit = objects.iterator(); while ((firstobject == null) && foit.hasNext()) { firstobject = foit.next(); } if (firstobject == null) { return ""; } BaseClass bclass = firstobject.getXClass(context); if (bclass.getPropertyList().size() == 0) { return ""; } StringBuffer result = new StringBuffer(); result.append("{table}\n"); boolean first = true; for (String propertyName : bclass.getPropertyList()) { if (first == true) { first = false; } else { result.append("|"); } PropertyClass pclass = (PropertyClass) bclass.getField(propertyName); result.append(pclass.getPrettyName()); } result.append("\n"); for (int i = 0; i < objects.size(); i++) { BaseObject object = objects.get(i); if (object != null) { first = true; for (String propertyName : bclass.getPropertyList()) { if (first == true) { first = false; } else { result.append("|"); } String data = display(propertyName, object, context); data = data.trim(); data = data.replaceAll("\n", " "); if (data.length() == 0) { result.append("&nbsp;"); } else { result.append(data); } } result.append("\n"); } } result.append("{table}\n"); return result.toString(); } /** * @deprecated since 2.2M1, use {@link #displayForm(DocumentReference, XWikiContext)} instead */ @Deprecated public String displayForm(String className, XWikiContext context) { return displayForm(resolveClassReference(className), context); } public boolean isFromCache() { return this.fromCache; } public void setFromCache(boolean fromCache) { this.fromCache = fromCache; } public void readDocMetaFromForm(EditForm eform, XWikiContext context) throws XWikiException { String defaultLanguage = eform.getDefaultLanguage(); if (defaultLanguage != null) { setDefaultLanguage(defaultLanguage); } String defaultTemplate = eform.getDefaultTemplate(); if (defaultTemplate != null) { setDefaultTemplate(defaultTemplate); } String creator = eform.getCreator(); if ((creator != null) && (!creator.equals(getCreator()))) { if ((getCreator().equals(context.getUser())) || (context.getWiki().getRightService().hasAdminRights(context))) { setCreator(creator); } } String parent = eform.getParent(); if (parent != null) { setParent(parent); } // Read the comment from the form String comment = eform.getComment(); if (comment != null) { setComment(comment); } // Read the minor edit checkbox from the form setMinorEdit(eform.isMinorEdit()); String tags = eform.getTags(); if (tags != null) { setTags(tags, context); } // Set the Syntax id if defined String syntaxId = eform.getSyntaxId(); if (syntaxId != null) { setSyntaxId(syntaxId); } } /** * add tags to the document. */ public void setTags(String tags, XWikiContext context) throws XWikiException { loadTags(context); StaticListClass tagProp = (StaticListClass) this.tags.getXClass(context).getField(XWikiConstant.TAG_CLASS_PROP_TAGS); tagProp.fromString(tags); this.tags.safeput(XWikiConstant.TAG_CLASS_PROP_TAGS, tagProp.fromString(tags)); setMetaDataDirty(true); } public String getTags(XWikiContext context) { ListProperty prop = (ListProperty) getTagProperty(context); if (prop != null) { return prop.getTextValue(); } return null; } public List<String> getTagsList(XWikiContext context) { List<String> tagList = null; BaseProperty prop = getTagProperty(context); if (prop != null) { tagList = (List<String>) prop.getValue(); } return tagList; } private BaseProperty getTagProperty(XWikiContext context) { loadTags(context); return ((BaseProperty) this.tags.safeget(XWikiConstant.TAG_CLASS_PROP_TAGS)); } private void loadTags(XWikiContext context) { if (this.tags == null) { this.tags = getObject(XWikiConstant.TAG_CLASS, true, context); } } public List<String> getTagsPossibleValues(XWikiContext context) { loadTags(context); String possibleValues = ((StaticListClass) this.tags.getXClass(context).getField(XWikiConstant.TAG_CLASS_PROP_TAGS)).getValues(); return ListClass.getListFromString(possibleValues); // ((BaseProperty) this.tags.safeget(XWikiConstant.TAG_CLASS_PROP_TAGS)).toString(); } public void readTranslationMetaFromForm(EditForm eform, XWikiContext context) throws XWikiException { String content = eform.getContent(); if (content != null) { // Cleanup in case we use HTMLAREA // content = context.getUtil().substitute("s/<br class=\\\"htmlarea\\\"\\/>/\\r\\n/g", // content); content = context.getUtil().substitute("s/<br class=\"htmlarea\" \\/>/\r\n/g", content); setContent(content); } String title = eform.getTitle(); if (title != null) { setTitle(title); } } public void readObjectsFromForm(EditForm eform, XWikiContext context) throws XWikiException { for (DocumentReference reference : getXObjects().keySet()) { List<BaseObject> oldObjects = getXObjects(reference); List<BaseObject> newObjects = new ArrayList<BaseObject>(); while (newObjects.size() < oldObjects.size()) { newObjects.add(null); } for (int i = 0; i < oldObjects.size(); i++) { BaseObject oldobject = oldObjects.get(i); if (oldobject != null) { BaseClass baseclass = oldobject.getXClass(context); BaseObject newobject = (BaseObject) baseclass.fromMap(eform.getObject(baseclass.getName() + "_" + i), oldobject); newobject.setNumber(oldobject.getNumber()); newobject.setGuid(oldobject.getGuid()); newobject.setDocumentReference(getDocumentReference()); newObjects.set(newobject.getNumber(), newobject); } } getXObjects().put(reference, newObjects); } setContentDirty(true); } public void readFromForm(EditForm eform, XWikiContext context) throws XWikiException { readDocMetaFromForm(eform, context); readTranslationMetaFromForm(eform, context); readObjectsFromForm(eform, context); } public void readFromTemplate(EditForm eform, XWikiContext context) throws XWikiException { String template = eform.getTemplate(); readFromTemplate(template, context); } /** * @since 2.2M1 */ public void readFromTemplate(DocumentReference templateDocumentReference, XWikiContext context) throws XWikiException { if (templateDocumentReference != null) { String content = getContent(); if ((!content.equals("\n")) && (!content.equals("")) && !isNew()) { Object[] args = {this.defaultEntityReferenceSerializer.serialize(getDocumentReference())}; throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_APP_DOCUMENT_NOT_EMPTY, "Cannot add a template to document {0} because it already has content", null, args); } else { XWiki xwiki = context.getWiki(); XWikiDocument templatedoc = xwiki.getDocument(templateDocumentReference, context); if (templatedoc.isNew()) { Object[] args = {this.defaultEntityReferenceSerializer.serialize(templateDocumentReference), this.compactEntityReferenceSerializer.serialize(getDocumentReference())}; throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_APP_TEMPLATE_DOES_NOT_EXIST, "Template document {0} does not exist when adding to document {1}", null, args); } else { setTemplateDocumentReference(templateDocumentReference); setContent(templatedoc.getContent()); // Set the new document syntax as the syntax of the template since the template content // is copied into the new document setSyntax(templatedoc.getSyntax()); // If the parent is not set in the current document set the template parent as the parent. if (getParentReference() == null) { setParentReference(templatedoc.getParentReference()); } if (isNew()) { // We might have received the object from the cache and the template objects might have been // copied already we need to remove them setXObjects(new TreeMap<DocumentReference, List<BaseObject>>()); } // Merge the external objects. // Currently the choice is not to merge the base class and object because it is not the prefered way // of using external classes and objects. mergeXObjects(templatedoc); } } } setContentDirty(true); } /** * @deprecated since 2.2M1 use {@link #readFromTemplate(DocumentReference, XWikiContext)} instead */ @Deprecated public void readFromTemplate(String template, XWikiContext context) throws XWikiException { // Keep the same behavior for backward compatibility DocumentReference templateDocumentReference = null; if (StringUtils.isNotEmpty(template)) { templateDocumentReference = this.currentMixedDocumentReferenceResolver.resolve(template); } readFromTemplate(templateDocumentReference, context); } /** * Use the document passed as parameter as the new identity for the current document. * * @param document the document containing the new identity * @throws XWikiException in case of error */ private void clone(XWikiDocument document) throws XWikiException { setDocumentReference(document.getDocumentReference()); setRCSVersion(document.getRCSVersion()); setDocumentArchive(document.getDocumentArchive()); setAuthor(document.getAuthor()); setContentAuthor(document.getContentAuthor()); setContent(document.getContent()); setContentDirty(document.isContentDirty()); setCreationDate(document.getCreationDate()); setDate(document.getDate()); setCustomClass(document.getCustomClass()); setContentUpdateDate(document.getContentUpdateDate()); setTitle(document.getTitle()); setFormat(document.getFormat()); setFromCache(document.isFromCache()); setElements(document.getElements()); setId(document.getId()); setMeta(document.getMeta()); setMetaDataDirty(document.isMetaDataDirty()); setMostRecent(document.isMostRecent()); setNew(document.isNew()); setStore(document.getStore()); setTemplateDocumentReference(document.getTemplateDocumentReference()); setParentReference(document.getParentReference()); setCreator(document.getCreator()); setDefaultLanguage(document.getDefaultLanguage()); setDefaultTemplate(document.getDefaultTemplate()); setValidationScript(document.getValidationScript()); setLanguage(document.getLanguage()); setTranslation(document.getTranslation()); setXClass((BaseClass) document.getXClass().clone()); setXClassXML(document.getXClassXML()); setComment(document.getComment()); setMinorEdit(document.isMinorEdit()); setSyntax(document.getSyntax()); setHidden(document.isHidden()); cloneXObjects(document); copyAttachments(document); this.elements = document.elements; this.originalDocument = document.originalDocument; } @Override public Object clone() { XWikiDocument doc = null; try { doc = getClass().newInstance(); doc.setDocumentReference(getDocumentReference()); // use version field instead of getRCSVersion because it returns "1.1" if version==null. doc.version = this.version; doc.setDocumentArchive(getDocumentArchive()); doc.setAuthor(getAuthor()); doc.setContentAuthor(getContentAuthor()); doc.setContent(getContent()); doc.setContentDirty(isContentDirty()); doc.setCreationDate(getCreationDate()); doc.setDate(getDate()); doc.setCustomClass(getCustomClass()); doc.setContentUpdateDate(getContentUpdateDate()); doc.setTitle(getTitle()); doc.setFormat(getFormat()); doc.setFromCache(isFromCache()); doc.setElements(getElements()); doc.setId(getId()); doc.setMeta(getMeta()); doc.setMetaDataDirty(isMetaDataDirty()); doc.setMostRecent(isMostRecent()); doc.setNew(isNew()); doc.setStore(getStore()); doc.setTemplateDocumentReference(getTemplateDocumentReference()); doc.setParentReference(getParentReference()); doc.setCreator(getCreator()); doc.setDefaultLanguage(getDefaultLanguage()); doc.setDefaultTemplate(getDefaultTemplate()); doc.setValidationScript(getValidationScript()); doc.setLanguage(getLanguage()); doc.setTranslation(getTranslation()); doc.setXClass((BaseClass) getXClass().clone()); doc.setXClassXML(getXClassXML()); doc.setComment(getComment()); doc.setMinorEdit(isMinorEdit()); doc.setSyntax(getSyntax()); doc.setHidden(isHidden()); doc.cloneXObjects(this); doc.copyAttachments(this); doc.elements = this.elements; doc.originalDocument = this.originalDocument; } catch (Exception e) { // This should not happen LOG.error("Exception while doc.clone", e); } return doc; } public void copyAttachments(XWikiDocument sourceDocument) { getAttachmentList().clear(); Iterator<XWikiAttachment> attit = sourceDocument.getAttachmentList().iterator(); while (attit.hasNext()) { XWikiAttachment attachment = attit.next(); XWikiAttachment newattachment = (XWikiAttachment) attachment.clone(); newattachment.setDoc(this); if (newattachment.getAttachment_content() != null) { newattachment.getAttachment_content().setContentDirty(true); } getAttachmentList().add(newattachment); } setContentDirty(true); } public void loadAttachments(XWikiContext context) throws XWikiException { for (XWikiAttachment attachment : getAttachmentList()) { attachment.loadContent(context); attachment.loadArchive(context); } } @Override public boolean equals(Object object) { // Same Java object, they sure are equal if (this == object) { return true; } XWikiDocument doc = (XWikiDocument) object; if (!getDocumentReference().equals(doc.getDocumentReference())) { return false; } if (!getAuthor().equals(doc.getAuthor())) { return false; } if (!getContentAuthor().equals(doc.getContentAuthor())) { return false; } if ((getParentReference() != null && !getParentReference().equals(doc.getParentReference())) || (getParentReference() == null && doc.getParentReference() != null)) { return false; } if (!getCreator().equals(doc.getCreator())) { return false; } if (!getDefaultLanguage().equals(doc.getDefaultLanguage())) { return false; } if (!getLanguage().equals(doc.getLanguage())) { return false; } if (getTranslation() != doc.getTranslation()) { return false; } if (getDate().getTime() != doc.getDate().getTime()) { return false; } if (getContentUpdateDate().getTime() != doc.getContentUpdateDate().getTime()) { return false; } if (getCreationDate().getTime() != doc.getCreationDate().getTime()) { return false; } if (!getFormat().equals(doc.getFormat())) { return false; } if (!getTitle().equals(doc.getTitle())) { return false; } if (!getContent().equals(doc.getContent())) { return false; } if (!getVersion().equals(doc.getVersion())) { return false; } if ((getTemplateDocumentReference() != null && !getTemplateDocumentReference().equals( doc.getTemplateDocumentReference())) || (getTemplateDocumentReference() == null && doc.getTemplateDocumentReference() != null)) { return false; } if (!getDefaultTemplate().equals(doc.getDefaultTemplate())) { return false; } if (!getValidationScript().equals(doc.getValidationScript())) { return false; } if (!getComment().equals(doc.getComment())) { return false; } if (isMinorEdit() != doc.isMinorEdit()) { return false; } if ((getSyntaxId() != null && !getSyntaxId().equals(doc.getSyntaxId())) || (getSyntaxId() == null && doc.getSyntaxId() != null)) { return false; } if (isHidden() != doc.isHidden()) { return false; } if (!getXClass().equals(doc.getXClass())) { return false; } Set<DocumentReference> myObjectClassReferences = getXObjects().keySet(); Set<DocumentReference> otherObjectClassReferences = doc.getXObjects().keySet(); if (!myObjectClassReferences.equals(otherObjectClassReferences)) { return false; } for (DocumentReference reference : myObjectClassReferences) { List<BaseObject> myObjects = getXObjects(reference); List<BaseObject> otherObjects = doc.getXObjects(reference); if (myObjects.size() != otherObjects.size()) { return false; } for (int i = 0; i < myObjects.size(); i++) { if ((myObjects.get(i) == null && otherObjects.get(i) != null) || (myObjects.get(i) != null && otherObjects.get(i) == null)) { return false; } if (myObjects.get(i) == null && otherObjects.get(i) == null) { continue; } if (!myObjects.get(i).equals(otherObjects.get(i))) { return false; } } } // We consider that 2 documents are still equal even when they have different original // documents (see getOriginalDocument() for more details as to what is an original // document). return true; } public String toXML(Document doc, XWikiContext context) { OutputFormat outputFormat = new OutputFormat("", true); if ((context == null) || (context.getWiki() == null)) { outputFormat.setEncoding("UTF-8"); } else { outputFormat.setEncoding(context.getWiki().getEncoding()); } StringWriter out = new StringWriter(); XMLWriter writer = new XMLWriter(out, outputFormat); try { writer.write(doc); return out.toString(); } catch (IOException e) { e.printStackTrace(); return ""; } } public String getXMLContent(XWikiContext context) throws XWikiException { XWikiDocument tdoc = getTranslatedDocument(context); Document doc = tdoc.toXMLDocument(true, true, false, false, context); return toXML(doc, context); } public String toXML(XWikiContext context) throws XWikiException { Document doc = toXMLDocument(context); return toXML(doc, context); } public String toFullXML(XWikiContext context) throws XWikiException { return toXML(true, false, true, true, context); } public void addToZip(ZipOutputStream zos, boolean withVersions, XWikiContext context) throws IOException { try { String zipname = getDocumentReference().getLastSpaceReference().getName() + "/" + getDocumentReference().getName(); String language = getLanguage(); if (!StringUtils.isEmpty(language)) { zipname += "." + language; } ZipEntry zipentry = new ZipEntry(zipname); zos.putNextEntry(zipentry); zos.write(toXML(true, false, true, withVersions, context).getBytes()); zos.closeEntry(); } catch (Exception e) { e.printStackTrace(); } } public void addToZip(ZipOutputStream zos, XWikiContext context) throws IOException { addToZip(zos, true, context); } public String toXML(boolean bWithObjects, boolean bWithRendering, boolean bWithAttachmentContent, boolean bWithVersions, XWikiContext context) throws XWikiException { Document doc = toXMLDocument(bWithObjects, bWithRendering, bWithAttachmentContent, bWithVersions, context); return toXML(doc, context); } public Document toXMLDocument(XWikiContext context) throws XWikiException { return toXMLDocument(true, false, false, false, context); } public Document toXMLDocument(boolean bWithObjects, boolean bWithRendering, boolean bWithAttachmentContent, boolean bWithVersions, XWikiContext context) throws XWikiException { Document doc = new DOMDocument(); Element docel = new DOMElement("xwikidoc"); doc.setRootElement(docel); Element el = new DOMElement("web"); el.addText(getDocumentReference().getLastSpaceReference().getName()); docel.add(el); el = new DOMElement("name"); el.addText(getDocumentReference().getName()); docel.add(el); el = new DOMElement("language"); el.addText(getLanguage()); docel.add(el); el = new DOMElement("defaultLanguage"); el.addText(getDefaultLanguage()); docel.add(el); el = new DOMElement("translation"); el.addText("" + getTranslation()); docel.add(el); el = new DOMElement("parent"); if (getParentReference() == null) { // No parent have been specified el.addText(""); } else { el.addText(this.localEntityReferenceSerializer.serialize(getParentReference())); } docel.add(el); el = new DOMElement("creator"); el.addText(getCreator()); docel.add(el); el = new DOMElement("author"); el.addText(getAuthor()); docel.add(el); el = new DOMElement("customClass"); el.addText(getCustomClass()); docel.add(el); el = new DOMElement("contentAuthor"); el.addText(getContentAuthor()); docel.add(el); long d = getCreationDate().getTime(); el = new DOMElement("creationDate"); el.addText("" + d); docel.add(el); d = getDate().getTime(); el = new DOMElement("date"); el.addText("" + d); docel.add(el); d = getContentUpdateDate().getTime(); el = new DOMElement("contentUpdateDate"); el.addText("" + d); docel.add(el); el = new DOMElement("version"); el.addText(getVersion()); docel.add(el); el = new DOMElement("title"); el.addText(getTitle()); docel.add(el); el = new DOMElement("template"); if (getTemplateDocumentReference() == null) { // No template doc have been specified el.addText(""); } else { el.addText(this.localEntityReferenceSerializer.serialize(getTemplateDocumentReference())); } docel.add(el); el = new DOMElement("defaultTemplate"); el.addText(getDefaultTemplate()); docel.add(el); el = new DOMElement("validationScript"); el.addText(getValidationScript()); docel.add(el); el = new DOMElement("comment"); el.addText(getComment()); docel.add(el); el = new DOMElement("minorEdit"); el.addText(String.valueOf(isMinorEdit())); docel.add(el); el = new DOMElement("syntaxId"); el.addText(getSyntaxId()); docel.add(el); el = new DOMElement("hidden"); el.addText(String.valueOf(isHidden())); docel.add(el); for (XWikiAttachment attach : getAttachmentList()) { docel.add(attach.toXML(bWithAttachmentContent, bWithVersions, context)); } if (bWithObjects) { // Add Class BaseClass bclass = getXClass(); if (bclass.getFieldList().size() > 0) { // If the class has fields, add class definition and field information to XML docel.add(bclass.toXML(null)); } // Add Objects (THEIR ORDER IS MOLDED IN STONE!) for (List<BaseObject> objects : getXObjects().values()) { for (BaseObject obj : objects) { if (obj != null) { BaseClass objclass; if (StringUtils.equals(getFullName(), obj.getClassName())) { objclass = bclass; } else { objclass = obj.getXClass(context); } docel.add(obj.toXML(objclass)); } } } } // Add Content el = new DOMElement("content"); // Filter filter = new CharacterFilter(); // String newcontent = filter.process(getContent()); // String newcontent = encodedXMLStringAsUTF8(getContent()); String newcontent = this.content; el.addText(newcontent); docel.add(el); if (bWithRendering) { el = new DOMElement("renderedcontent"); try { el.addText(getRenderedContent(context)); } catch (XWikiException e) { el.addText("Exception with rendering content: " + e.getFullMessage()); } docel.add(el); } if (bWithVersions) { el = new DOMElement("versions"); try { el.addText(getDocumentArchive(context).getArchive(context)); docel.add(el); } catch (XWikiException e) { LOG.error("Document [" + this.defaultEntityReferenceSerializer.serialize(getDocumentReference()) + "] has malformed history"); } } return doc; } protected String encodedXMLStringAsUTF8(String xmlString) { if (xmlString == null) { return ""; } int length = xmlString.length(); char character; StringBuffer result = new StringBuffer(); for (int i = 0; i < length; i++) { character = xmlString.charAt(i); switch (character) { case '&': result.append("&amp;"); break; case '"': result.append("&quot;"); break; case '<': result.append("&lt;"); break; case '>': result.append("&gt;"); break; case '\n': result.append("\n"); break; case '\r': result.append("\r"); break; case '\t': result.append("\t"); break; default: if (character < 0x20) { } else if (character > 0x7F) { result.append("& result.append(Integer.toHexString(character).toUpperCase()); result.append(";"); } else { result.append(character); } break; } } return result.toString(); } protected String getElement(Element docel, String name) { Element el = docel.element(name); if (el == null) { return ""; } else { return el.getText(); } } public void fromXML(String xml) throws XWikiException { fromXML(xml, false); } public void fromXML(InputStream is) throws XWikiException { fromXML(is, false); } public void fromXML(String xml, boolean withArchive) throws XWikiException { SAXReader reader = new SAXReader(); Document domdoc; try { StringReader in = new StringReader(xml); domdoc = reader.read(in); } catch (DocumentException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_DOC_XML_PARSING, "Error parsing xml", e, null); } fromXML(domdoc, withArchive); } public void fromXML(InputStream in, boolean withArchive) throws XWikiException { SAXReader reader = new SAXReader(); Document domdoc; try { domdoc = reader.read(in); } catch (DocumentException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_DOC_XML_PARSING, "Error parsing xml", e, null); } fromXML(domdoc, withArchive); } public void fromXML(Document domdoc, boolean withArchive) throws XWikiException { Element docel = domdoc.getRootElement(); // If, for some reason, the document name or space are not set in the XML input, we still ensure that the // constructed XWikiDocument object has a valid name or space (by using current document values if they are // missing). This is important since document name, space and wiki must always be set in a XWikiDocument // instance. String name = getElement(docel, "name"); String space = getElement(docel, "web"); if (StringUtils.isEmpty(name) || StringUtils.isEmpty(space)) { throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_XWIKI_UNKNOWN, "Invalid XML: \"name\" and \"web\" cannot be empty"); } EntityReference reference = new EntityReference(name, EntityType.DOCUMENT, new EntityReference(space, EntityType.SPACE)); reference = this.currentReferenceDocumentReferenceResolver.resolve(reference); setDocumentReference(new DocumentReference(reference)); String parent = getElement(docel, "parent"); if (StringUtils.isNotEmpty(parent)) { setParentReference(this.currentMixedDocumentReferenceResolver.resolve(parent)); } setCreator(getElement(docel, "creator")); setAuthor(getElement(docel, "author")); setCustomClass(getElement(docel, "customClass")); setContentAuthor(getElement(docel, "contentAuthor")); if (docel.element("version") != null) { setVersion(getElement(docel, "version")); } setContent(getElement(docel, "content")); setLanguage(getElement(docel, "language")); setDefaultLanguage(getElement(docel, "defaultLanguage")); setTitle(getElement(docel, "title")); setDefaultTemplate(getElement(docel, "defaultTemplate")); setValidationScript(getElement(docel, "validationScript")); setComment(getElement(docel, "comment")); String minorEdit = getElement(docel, "minorEdit"); setMinorEdit(Boolean.valueOf(minorEdit).booleanValue()); String hidden = getElement(docel, "hidden"); setHidden(Boolean.valueOf(hidden).booleanValue()); String strans = getElement(docel, "translation"); if ((strans == null) || strans.equals("")) { setTranslation(0); } else { setTranslation(Integer.parseInt(strans)); } String archive = getElement(docel, "versions"); if (withArchive && archive != null && archive.length() > 0) { setDocumentArchive(archive); } String sdate = getElement(docel, "date"); if (!sdate.equals("")) { Date date = new Date(Long.parseLong(sdate)); setDate(date); } String contentUpdateDateString = getElement(docel, "contentUpdateDate"); if (!StringUtils.isEmpty(contentUpdateDateString)) { Date contentUpdateDate = new Date(Long.parseLong(contentUpdateDateString)); setContentUpdateDate(contentUpdateDate); } String scdate = getElement(docel, "creationDate"); if (!scdate.equals("")) { Date cdate = new Date(Long.parseLong(scdate)); setCreationDate(cdate); } String syntaxId = getElement(docel, "syntaxId"); if ((syntaxId == null) || (syntaxId.length() == 0)) { // Documents that don't have syntax ids are considered old documents and thus in // XWiki Syntax 1.0 since newer documents always have syntax ids. setSyntax(Syntax.XWIKI_1_0); } else { setSyntaxId(syntaxId); } List<Element> atels = docel.elements("attachment"); for (Element atel : atels) { XWikiAttachment attach = new XWikiAttachment(); attach.setDoc(this); attach.fromXML(atel); getAttachmentList().add(attach); } Element cel = docel.element("class"); BaseClass bclass = new BaseClass(); if (cel != null) { bclass.fromXML(cel); setXClass(bclass); } List<Element> objels = docel.elements("object"); for (Element objel : objels) { BaseObject bobject = new BaseObject(); bobject.fromXML(objel); setXObject(bobject.getXClassReference(), bobject.getNumber(), bobject); } // We have been reading from XML so the document does not need a new version when saved setMetaDataDirty(false); setContentDirty(false); // Note: We don't set the original document as that is not stored in the XML, and it doesn't make much sense to // have an original document for a de-serialized object. } /** * Check if provided xml document is a wiki document. * * @param domdoc the xml document. * @return true if provided xml document is a wiki document. */ public static boolean containsXMLWikiDocument(Document domdoc) { return domdoc.getRootElement().getName().equals("xwikidoc"); } public void setAttachmentList(List<XWikiAttachment> list) { this.attachmentList = list; } public List<XWikiAttachment> getAttachmentList() { return this.attachmentList; } public void saveAllAttachments(XWikiContext context) throws XWikiException { for (XWikiAttachment attachement : this.attachmentList) { saveAttachmentContent(attachement, context); } } public void saveAllAttachments(boolean updateParent, boolean transaction, XWikiContext context) throws XWikiException { for (XWikiAttachment attachement : this.attachmentList) { saveAttachmentContent(attachement, updateParent, transaction, context); } } public void saveAttachmentsContent(List<XWikiAttachment> attachments, XWikiContext context) throws XWikiException { String database = context.getDatabase(); try { // We might need to switch database to get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } context.getWiki().getAttachmentStore().saveAttachmentsContent(attachments, this, true, context, true); } catch (OutOfMemoryError e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE, "Out Of Memory Exception"); } finally { if (database != null) { context.setDatabase(database); } } } public void saveAttachmentContent(XWikiAttachment attachment, XWikiContext context) throws XWikiException { saveAttachmentContent(attachment, true, true, context); } public void saveAttachmentContent(XWikiAttachment attachment, boolean bParentUpdate, boolean bTransaction, XWikiContext context) throws XWikiException { String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } // We need to make sure there is a version upgrade setMetaDataDirty(true); context.getWiki().getAttachmentStore().saveAttachmentContent(attachment, bParentUpdate, context, bTransaction); } catch (OutOfMemoryError e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE, "Out Of Memory Exception"); } finally { if (database != null) { context.setDatabase(database); } } } public void loadAttachmentContent(XWikiAttachment attachment, XWikiContext context) throws XWikiException { String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } context.getWiki().getAttachmentStore().loadAttachmentContent(attachment, context, true); } finally { if (database != null) { context.setDatabase(database); } } } public void deleteAttachment(XWikiAttachment attachment, XWikiContext context) throws XWikiException { deleteAttachment(attachment, true, context); } public void deleteAttachment(XWikiAttachment attachment, boolean toRecycleBin, XWikiContext context) throws XWikiException { String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } try { // We need to make sure there is a version upgrade setMetaDataDirty(true); if (toRecycleBin && context.getWiki().hasAttachmentRecycleBin(context)) { context.getWiki().getAttachmentRecycleBinStore().saveToRecycleBin(attachment, context.getUser(), new Date(), context, true); } context.getWiki().getAttachmentStore().deleteXWikiAttachment(attachment, context, true); } catch (java.lang.OutOfMemoryError e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE, "Out Of Memory Exception"); } } finally { if (database != null) { context.setDatabase(database); } } } /** * Get the wiki document references pointing to this document. * <p> * Theses links are stored to the database when documents are saved. You can use "backlinks" in XWikiPreferences or * "xwiki.backlinks" in xwiki.cfg file to enable links storage in the database. * * @param context the XWiki context. * @return the found wiki document references * @throws XWikiException error when getting pages names from database. * @since 2.2M2 */ public List<DocumentReference> getBackLinkedReferences(XWikiContext context) throws XWikiException { return getStore(context).loadBacklinks(getDocumentReference(), true, context); } /** * @deprecated since 2.2M2 use {@link #getBackLinkedReferences(XWikiContext)} */ @Deprecated public List<String> getBackLinkedPages(XWikiContext context) throws XWikiException { return getStore(context).loadBacklinks(getFullName(), context, true); } /** * Get a list of unique links from this document to others documents. * <p> * <ul> * <li>1.0 content: get the unique links associated to document from database. This is stored when the document is * saved. You can use "backlinks" in XWikiPreferences or "xwiki.backlinks" in xwiki.cfg file to enable links storage * in the database.</li> * <li>Other content: call {@link #getUniqueLinkedPages(XWikiContext)} and generate the List</li>. * </ul> * * @param context the XWiki context * @return the found wiki links. * @throws XWikiException error when getting links from database when 1.0 content. * @since 1.9M2 */ public Set<XWikiLink> getUniqueWikiLinkedPages(XWikiContext context) throws XWikiException { Set<XWikiLink> links; if (is10Syntax()) { links = new LinkedHashSet<XWikiLink>(getStore(context).loadLinks(getId(), context, true)); } else { Set<String> linkedPages = getUniqueLinkedPages(context); links = new LinkedHashSet<XWikiLink>(linkedPages.size()); for (String linkedPage : linkedPages) { XWikiLink wikiLink = new XWikiLink(); wikiLink.setDocId(getId()); wikiLink.setFullName(getFullName()); wikiLink.setLink(linkedPage); links.add(wikiLink); } } return links; } /** * Extract all the unique static (i.e. not generated by macros) wiki links (pointing to wiki page) from this 1.0 * document's content to others documents. * * @param context the XWiki context. * @return the document names for linked pages, if null an error append. * @since 1.9M2 */ private Set<String> getUniqueLinkedPages10(XWikiContext context) { Set<String> pageNames; try { List<String> list = context.getUtil().getUniqueMatches(getContent(), "\\[(.*?)\\]", 1); pageNames = new HashSet<String>(list.size()); DocumentReference currentDocumentReference = getDocumentReference(); for (String name : list) { int i1 = name.indexOf(">"); if (i1 != -1) { name = name.substring(i1 + 1); } i1 = name.indexOf("&gt;"); if (i1 != -1) { name = name.substring(i1 + 4); } i1 = name.indexOf(" if (i1 != -1) { name = name.substring(0, i1); } i1 = name.indexOf("?"); if (i1 != -1) { name = name.substring(0, i1); } // Let's get rid of anything that's not a real link if (name.trim().equals("") || (name.indexOf("$") != -1) || (name.indexOf(": || (name.indexOf("\"") != -1) || (name.indexOf("\'") != -1) || (name.indexOf("..") != -1) || (name.indexOf(":") != -1) || (name.indexOf("=") != -1)) { continue; } // generate the link String newname = StringUtils.replace(Util.noaccents(name), " ", ""); // If it is a local link let's add the space if (newname.indexOf(".") == -1) { newname = getSpace() + "." + name; } if (context.getWiki().exists(newname, context)) { name = newname; } else { // If it is a local link let's add the space if (name.indexOf(".") == -1) { name = getSpace() + "." + name; } } // If the reference is empty, the link is an autolink if (!StringUtils.isEmpty(name)) { // The reference may not have the space or even document specified (in case of an empty // string) // Thus we need to find the fully qualified document name DocumentReference documentReference = this.currentDocumentReferenceResolver.resolve(name); // Verify that the link is not an autolink (i.e. a link to the current document) if (!documentReference.equals(currentDocumentReference)) { pageNames.add(this.compactEntityReferenceSerializer.serialize(documentReference)); } } } return pageNames; } catch (Exception e) { // This should never happen LOG.error("Failed to get linked documents", e); return null; } } /** * Extract all the unique static (i.e. not generated by macros) wiki links (pointing to wiki page) from this * document's content to others documents. * * @param context the XWiki context. * @return the document names for linked pages, if null an error append. * @since 1.9M2 */ public Set<String> getUniqueLinkedPages(XWikiContext context) { Set<String> pageNames; XWikiDocument contextDoc = context.getDoc(); String contextWiki = context.getDatabase(); try { // Make sure the right document is used as context document context.setDoc(this); // Make sure the right wiki is used as context document context.setDatabase(getDatabase()); if (is10Syntax()) { pageNames = getUniqueLinkedPages10(context); } else { XDOM dom = getXDOM(); List<LinkBlock> linkBlocks = dom.getChildrenByType(LinkBlock.class, true); pageNames = new LinkedHashSet<String>(linkBlocks.size()); DocumentReference currentDocumentReference = getDocumentReference(); for (LinkBlock linkBlock : linkBlocks) { org.xwiki.rendering.listener.Link link = linkBlock.getLink(); if (link.getType() == LinkType.DOCUMENT) { // If the reference is empty, the link is an autolink if (!StringUtils.isEmpty(link.getReference()) || (StringUtils.isEmpty(link.getAnchor()) && StringUtils.isEmpty(link.getQueryString()))) { // The reference may not have the space or even document specified (in case of an empty // string) // Thus we need to find the fully qualified document name DocumentReference documentReference = this.currentDocumentReferenceResolver.resolve(link.getReference()); // Verify that the link is not an autolink (i.e. a link to the current document) if (!documentReference.equals(currentDocumentReference)) { // Since this method is used for saving backlinks and since backlinks must be // saved with the space and page name but without the wiki part, we remove the wiki // part before serializing. // This is a bit of a hack since the default serializer should theoretically fail // if it's passed an invalid reference. pageNames.add(this.compactWikiEntityReferenceSerializer.serialize(documentReference)); } } } } } } finally { context.setDoc(contextDoc); context.setDatabase(contextWiki); } return pageNames; } /** * Returns a list of references of all documents which list this document as their parent * {@link #getChildren(int, int, com.xpn.xwiki.XWikiContext)} * * @since 2.2M2 */ public List<DocumentReference> getChildrenReferences(XWikiContext context) throws XWikiException { return getChildrenReferences(0, 0, context); } /** * @deprecated since 2.2M2 use {@link #getChildrenReferences(XWikiContext)} */ @Deprecated public List<String> getChildren(XWikiContext context) throws XWikiException { return getChildren(0, 0, context); } /** * Returns a list of references of all documents which list this document as their parent * * @param nb The number of results to return. * @param start The number of results to skip before we begin returning results. * @param context The {@link com.xpn.xwiki.XWikiContext context}. * @return the list of document references * @throws XWikiException If there's an error querying the database. * @since 2.2M2 */ public List<DocumentReference> getChildrenReferences(int nb, int start, XWikiContext context) throws XWikiException { // Use cases: // - the parent document reference saved in the database matches the reference of this document, in its fully // serialized form (eg "wiki:space.page"). Note that this is normally not required since the wiki part // isn't saved in the database when it matches the current wiki. // - the parent document reference saved in the database matches the reference of this document, in its // serialized form without the wiki part (eg "space.page"). The reason we don't need to specify the wiki // part is because document parents saved in the database don't have the wiki part specified when it matches // the current wiki. // - the parent document reference saved in the database matches the page name part of this document's // reference (eg "page") and the parent document's space is the same as this document's space. List<String> whereParams = Arrays.asList(this.defaultEntityReferenceSerializer.serialize(getDocumentReference()), this.localEntityReferenceSerializer.serialize(getDocumentReference()), getDocumentReference().getName(), getDocumentReference().getLastSpaceReference().getName()); String whereStatement = "doc.parent=? or doc.parent=? or (doc.parent=? and doc.space=?)"; return context.getWiki().getStore().searchDocumentReferences(whereStatement, nb, start, whereParams, context); } /** * @deprecated since 2.2M2 use {@link #getChildrenReferences(XWikiContext)} */ @Deprecated public List<String> getChildren(int nb, int start, XWikiContext context) throws XWikiException { List<String> childrenNames = new ArrayList<String>(); for (DocumentReference reference : getChildrenReferences(nb, start, context)) { childrenNames.add(this.localEntityReferenceSerializer.serialize(reference)); } return childrenNames; } /** * @since 2.2M2 */ public void renameProperties(DocumentReference classReference, Map<String, String> fieldsToRename) { List<BaseObject> objects = getXObjects(classReference); if (objects == null) { return; } for (BaseObject bobject : objects) { if (bobject == null) { continue; } for (Map.Entry<String, String> entry : fieldsToRename.entrySet()) { String origname = entry.getKey(); String newname = entry.getValue(); BaseProperty origprop = (BaseProperty) bobject.safeget(origname); if (origprop != null) { BaseProperty prop = (BaseProperty) origprop.clone(); bobject.removeField(origname); prop.setName(newname); bobject.addField(newname, prop); } } } setContentDirty(true); } /** * @deprecated since 2.2M2 use {@link #renameProperties(DocumentReference, Map)} instead */ @Deprecated public void renameProperties(String className, Map<String, String> fieldsToRename) { renameProperties(resolveClassReference(className), fieldsToRename); } /** * @since 2.2M1 */ public void addXObjectToRemove(BaseObject object) { getXObjectsToRemove().add(object); setContentDirty(true); } /** * @deprecated since 2.2M2 use {@link #addXObjectToRemove(BaseObject)} )} instead */ @Deprecated public void addObjectsToRemove(BaseObject object) { addXObjectToRemove(object); } /** * @since 2.2M2 */ public List<BaseObject> getXObjectsToRemove() { return this.xObjectsToRemove; } /** * @deprecated since 2.2M2 use {@link #getObjectsToRemove()} instead */ @Deprecated public ArrayList<BaseObject> getObjectsToRemove() { return (ArrayList<BaseObject>) getXObjectsToRemove(); } /** * @since 2.2M1 */ public void setXObjectsToRemove(List<BaseObject> objectsToRemove) { this.xObjectsToRemove = objectsToRemove; setContentDirty(true); } /** * @deprecated since 2.2M2 use {@link #setXObjectsToRemove(List)} instead */ @Deprecated public void setObjectsToRemove(ArrayList<BaseObject> objectsToRemove) { setXObjectsToRemove(objectsToRemove); } public List<String> getIncludedPages(XWikiContext context) { if (is10Syntax()) { return getIncludedPagesForXWiki10Syntax(getContent(), context); } else { // Find all include macros listed on the page XDOM dom = getXDOM(); List<String> result = new ArrayList<String>(); for (MacroBlock macroBlock : dom.getChildrenByType(MacroBlock.class, true)) { // - Add each document pointed to by the include macro // - Also add all the included pages found in the velocity macro when using the deprecated #include* // macros // This should be removed when we fully drop support for the XWiki Syntax 1.0 but for now we want to // play // nice with people migrating from 1.0 to 2.0 syntax if (macroBlock.getId().equalsIgnoreCase("include")) { String documentName = macroBlock.getParameters().get("document"); if (documentName.indexOf(".") == -1) { documentName = getSpace() + "." + documentName; } result.add(documentName); } else if (macroBlock.getId().equalsIgnoreCase("velocity") && !StringUtils.isEmpty(macroBlock.getContent())) { // Try to find matching content inside each velocity macro result.addAll(getIncludedPagesForXWiki10Syntax(macroBlock.getContent(), context)); } } return result; } } private List<String> getIncludedPagesForXWiki10Syntax(String content, XWikiContext context) { try { String pattern = "#include(Topic|InContext|Form|Macros|parseGroovyFromPage)\\([\"'](.*?)[\"']\\)"; List<String> list = context.getUtil().getUniqueMatches(content, pattern, 2); for (int i = 0; i < list.size(); i++) { String name = list.get(i); if (name.indexOf(".") == -1) { list.set(i, getSpace() + "." + name); } } return list; } catch (Exception e) { LOG.error("Failed to extract include target from provided content [" + content + "]", e); return null; } } public List<String> getIncludedMacros(XWikiContext context) { return context.getWiki().getIncludedMacros(getSpace(), getContent(), context); } public String displayRendered(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) throws XWikiException { String result = pclass.displayView(pclass.getName(), prefix, object, context); return getRenderedContent(result, XWIKI10_SYNTAXID, context); } public String displayView(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) { return (pclass == null) ? "" : pclass.displayView(pclass.getName(), prefix, object, context); } public String displayEdit(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) { return (pclass == null) ? "" : pclass.displayEdit(pclass.getName(), prefix, object, context); } public String displayHidden(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) { return (pclass == null) ? "" : pclass.displayHidden(pclass.getName(), prefix, object, context); } public String displaySearch(PropertyClass pclass, String prefix, XWikiCriteria criteria, XWikiContext context) { return (pclass == null) ? "" : pclass.displaySearch(pclass.getName(), prefix, criteria, context); } public XWikiAttachment getAttachment(String filename) { for (XWikiAttachment attach : getAttachmentList()) { if (attach.getFilename().equals(filename)) { return attach; } } for (XWikiAttachment attach : getAttachmentList()) { if (attach.getFilename().startsWith(filename + ".")) { return attach; } } return null; } public XWikiAttachment addAttachment(String fileName, InputStream iStream, XWikiContext context) throws XWikiException, IOException { ByteArrayOutputStream bAOut = new ByteArrayOutputStream(); IOUtils.copy(iStream, bAOut); return addAttachment(fileName, bAOut.toByteArray(), context); } public XWikiAttachment addAttachment(String fileName, byte[] data, XWikiContext context) throws XWikiException { int i = fileName.indexOf("\\"); if (i == -1) { i = fileName.indexOf("/"); } String filename = fileName.substring(i + 1); // TODO : avoid name clearing when encoding problems will be solved filename = context.getWiki().clearName(filename, false, true, context); XWikiAttachment attachment = getAttachment(filename); if (attachment == null) { attachment = new XWikiAttachment(); // TODO: Review this code and understand why it's needed. // Add the attachment in the current doc getAttachmentList().add(attachment); } attachment.setContent(data); attachment.setFilename(filename); attachment.setAuthor(context.getUser()); // Add the attachment to the document attachment.setDoc(this); return attachment; } public BaseObject getFirstObject(String fieldname) { // Keeping this function with context null for compatibility reasons. // It should not be used, since it would miss properties which are only defined in the class // and not present in the object because the object was not updated return getFirstObject(fieldname, null); } public BaseObject getFirstObject(String fieldname, XWikiContext context) { Collection<List<BaseObject>> objectscoll = getXObjects().values(); if (objectscoll == null) { return null; } for (List<BaseObject> objects : objectscoll) { for (BaseObject obj : objects) { if (obj != null) { BaseClass bclass = obj.getXClass(context); if (bclass != null) { Set<String> set = bclass.getPropertyList(); if ((set != null) && set.contains(fieldname)) { return obj; } } Set<String> set = obj.getPropertyList(); if ((set != null) && set.contains(fieldname)) { return obj; } } } } return null; } /** * @since 2.2M2 */ public void setProperty(DocumentReference classReference, String fieldName, BaseProperty value) { BaseObject bobject = getXObject(classReference); if (bobject == null) { bobject = new BaseObject(); addXObject(classReference, bobject); } bobject.setDocumentReference(getDocumentReference()); bobject.setXClassReference(classReference); bobject.safeput(fieldName, value); setContentDirty(true); } /** * @deprecated since 2.2M2 use {@link #setProperty(DocumentReference, String, BaseProperty)} instead */ @Deprecated public void setProperty(String className, String fieldName, BaseProperty value) { setProperty(resolveClassReference(className), fieldName, value); } /** * @since 2.2M2 */ public int getIntValue(DocumentReference classReference, String fieldName) { BaseObject obj = getXObject(classReference, 0); if (obj == null) { return 0; } return obj.getIntValue(fieldName); } /** * @deprecated since 2.2M2 use {@link #getIntValue(DocumentReference, String)} instead */ @Deprecated public int getIntValue(String className, String fieldName) { return getIntValue(resolveClassReference(className), fieldName); } /** * @since 2.2M2 */ public long getLongValue(DocumentReference classReference, String fieldName) { BaseObject obj = getXObject(classReference, 0); if (obj == null) { return 0; } return obj.getLongValue(fieldName); } /** * @deprecated since 2.2M2 use {@link #getLongValue(DocumentReference, String)} instead */ @Deprecated public long getLongValue(String className, String fieldName) { return getLongValue(resolveClassReference(className), fieldName); } /** * @since 2.2M2 */ public String getStringValue(DocumentReference classReference, String fieldName) { BaseObject obj = getXObject(classReference); if (obj == null) { return ""; } String result = obj.getStringValue(fieldName); if (result.equals(" ")) { return ""; } else { return result; } } /** * @deprecated since 2.2M2 use {@link #getStringValue(DocumentReference, String)} instead */ @Deprecated public String getStringValue(String className, String fieldName) { return getStringValue(resolveClassReference(className), fieldName); } public int getIntValue(String fieldName) { BaseObject object = getFirstObject(fieldName, null); if (object == null) { return 0; } else { return object.getIntValue(fieldName); } } public long getLongValue(String fieldName) { BaseObject object = getFirstObject(fieldName, null); if (object == null) { return 0; } else { return object.getLongValue(fieldName); } } public String getStringValue(String fieldName) { BaseObject object = getFirstObject(fieldName, null); if (object == null) { return ""; } String result = object.getStringValue(fieldName); if (result.equals(" ")) { return ""; } else { return result; } } /** * @since 2.2M2 */ public void setStringValue(DocumentReference classReference, String fieldName, String value) { BaseObject bobject = getXObject(classReference); if (bobject == null) { bobject = new BaseObject(); addXObject(classReference, bobject); } bobject.setDocumentReference(getDocumentReference()); bobject.setXClassReference(classReference); bobject.setStringValue(fieldName, value); setContentDirty(true); } /** * @deprecated since 2.2M2 use {@link #setStringValue(DocumentReference, String, String)} instead */ @Deprecated public void setStringValue(String className, String fieldName, String value) { setStringValue(resolveClassReference(className), fieldName, value); } /** * @since 2.2M2 */ public List getListValue(DocumentReference classReference, String fieldName) { BaseObject obj = getXObject(classReference); if (obj == null) { return new ArrayList(); } return obj.getListValue(fieldName); } /** * @deprecated since 2.2M2 use {@link #getListValue(DocumentReference, String)} instead */ @Deprecated public List getListValue(String className, String fieldName) { return getListValue(resolveClassReference(className), fieldName); } public List getListValue(String fieldName) { BaseObject object = getFirstObject(fieldName, null); if (object == null) { return new ArrayList(); } return object.getListValue(fieldName); } /** * @since 2.2M2 */ public void setStringListValue(DocumentReference classReference, String fieldName, List value) { BaseObject bobject = getXObject(classReference); if (bobject == null) { bobject = new BaseObject(); addXObject(classReference, bobject); } bobject.setDocumentReference(getDocumentReference()); bobject.setXClassReference(classReference); bobject.setStringListValue(fieldName, value); setContentDirty(true); } /** * @deprecated since 2.2M2 use {@link #setStringListValue(DocumentReference, String, List)} instead */ @Deprecated public void setStringListValue(String className, String fieldName, List value) { setStringListValue(resolveClassReference(className), fieldName, value); } /** * @since 2.2M2 */ public void setDBStringListValue(DocumentReference classReference, String fieldName, List value) { BaseObject bobject = getXObject(classReference); if (bobject == null) { bobject = new BaseObject(); addXObject(classReference, bobject); } bobject.setDocumentReference(getDocumentReference()); bobject.setXClassReference(classReference); bobject.setDBStringListValue(fieldName, value); setContentDirty(true); } /** * @deprecated since 2.2M2 use {@link #setDBStringListValue(DocumentReference, String, List)} instead */ @Deprecated public void setDBStringListValue(String className, String fieldName, List value) { setDBStringListValue(resolveClassReference(className), fieldName, value); } /** * @since 2.2M2 */ public void setLargeStringValue(DocumentReference classReference, String fieldName, String value) { BaseObject bobject = getXObject(classReference); if (bobject == null) { bobject = new BaseObject(); addXObject(classReference, bobject); } bobject.setDocumentReference(getDocumentReference()); bobject.setXClassReference(classReference); bobject.setLargeStringValue(fieldName, value); setContentDirty(true); } /** * @deprecated since 2.2M2 use {@link #setLargeStringValue(DocumentReference, String, String)} instead */ @Deprecated public void setLargeStringValue(String className, String fieldName, String value) { setLargeStringValue(resolveClassReference(className), fieldName, value); } /** * @since 2.2M2 */ public void setIntValue(DocumentReference classReference, String fieldName, int value) { BaseObject bobject = getXObject(classReference); if (bobject == null) { bobject = new BaseObject(); addXObject(classReference, bobject); } bobject.setDocumentReference(getDocumentReference()); bobject.setXClassReference(classReference); bobject.setIntValue(fieldName, value); setContentDirty(true); } /** * @deprecated since 2.2M2 use {@link #setIntValue(DocumentReference, String, int)} instead */ @Deprecated public void setIntValue(String className, String fieldName, int value) { setIntValue(resolveClassReference(className), fieldName, value); } /** * Note that this method cannot be removed for now since it's used by Hibernate for saving a XWikiDocument. * * @deprecated since 2.2M1 use {@link #getDocumentReference()} instead */ @Deprecated public String getDatabase() { return getDocumentReference().getWikiReference().getName(); } /** * Note that this method cannot be removed for now since it's used by Hibernate for loading a XWikiDocument. * * @deprecated since 2.2M1 use {@link #setDocumentReference(DocumentReference)} instead */ @Deprecated public void setDatabase(String database) { if (database != null) { getDocumentReference().getWikiReference().setName(database); } } public String getLanguage() { if (this.language == null) { return ""; } else { return this.language.trim(); } } public void setLanguage(String language) { this.language = language; } public String getDefaultLanguage() { if (this.defaultLanguage == null) { return ""; } else { return this.defaultLanguage.trim(); } } public void setDefaultLanguage(String defaultLanguage) { this.defaultLanguage = defaultLanguage; setMetaDataDirty(true); } public int getTranslation() { return this.translation; } public void setTranslation(int translation) { this.translation = translation; setMetaDataDirty(true); } public String getTranslatedContent(XWikiContext context) throws XWikiException { String language = context.getWiki().getLanguagePreference(context); return getTranslatedContent(language, context); } public String getTranslatedContent(String language, XWikiContext context) throws XWikiException { XWikiDocument tdoc = getTranslatedDocument(language, context); String rev = (String) context.get("rev"); if ((rev == null) || (rev.length() == 0)) { return tdoc.getContent(); } XWikiDocument cdoc = context.getWiki().getDocument(tdoc, rev, context); return cdoc.getContent(); } public XWikiDocument getTranslatedDocument(XWikiContext context) throws XWikiException { String language = context.getWiki().getLanguagePreference(context); return getTranslatedDocument(language, context); } public XWikiDocument getTranslatedDocument(String language, XWikiContext context) throws XWikiException { XWikiDocument tdoc = this; if (!((language == null) || (language.equals("")) || language.equals(this.defaultLanguage))) { tdoc = new XWikiDocument(getDocumentReference()); tdoc.setLanguage(language); String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } tdoc = getStore(context).loadXWikiDoc(tdoc, context); if (tdoc.isNew()) { tdoc = this; } } catch (Exception e) { tdoc = this; } finally { context.setDatabase(database); } } return tdoc; } public String getRealLanguage(XWikiContext context) throws XWikiException { return getRealLanguage(); } public String getRealLanguage() { String lang = getLanguage(); if ((lang.equals("") || lang.equals("default"))) { return getDefaultLanguage(); } else { return lang; } } public List<String> getTranslationList(XWikiContext context) throws XWikiException { return getStore().getTranslationList(this, context); } public List<Delta> getXMLDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException, DifferentiationFailedException { return getDeltas(Diff.diff(ToString.stringToArray(fromDoc.toXML(context)), ToString.stringToArray(toDoc.toXML(context)))); } public List<Delta> getContentDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException, DifferentiationFailedException { return getDeltas(Diff.diff(ToString.stringToArray(fromDoc.getContent()), ToString.stringToArray(toDoc.getContent()))); } public List<Delta> getContentDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException, DifferentiationFailedException { XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context); XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context); return getContentDiff(fromDoc, toDoc, context); } public List<Delta> getContentDiff(String fromRev, XWikiContext context) throws XWikiException, DifferentiationFailedException { XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context); return getContentDiff(revdoc, this, context); } public List<Delta> getLastChanges(XWikiContext context) throws XWikiException, DifferentiationFailedException { Version version = getRCSVersion(); try { String prev = getDocumentArchive(context).getPrevVersion(version).toString(); XWikiDocument prevDoc = context.getWiki().getDocument(this, prev, context); return getDeltas(Diff.diff(ToString.stringToArray(prevDoc.getContent()), ToString.stringToArray(getContent()))); } catch (Exception ex) { LOG.debug("Exception getting differences from previous version: " + ex.getMessage()); } return new ArrayList<Delta>(); } public List<Delta> getRenderedContentDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException, DifferentiationFailedException { String originalContent, newContent; originalContent = context.getWiki().getRenderingEngine().renderText(fromDoc.getContent(), fromDoc, context); newContent = context.getWiki().getRenderingEngine().renderText(toDoc.getContent(), toDoc, context); return getDeltas(Diff.diff(ToString.stringToArray(originalContent), ToString.stringToArray(newContent))); } public List<Delta> getRenderedContentDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException, DifferentiationFailedException { XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context); XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context); return getRenderedContentDiff(fromDoc, toDoc, context); } public List<Delta> getRenderedContentDiff(String fromRev, XWikiContext context) throws XWikiException, DifferentiationFailedException { XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context); return getRenderedContentDiff(revdoc, this, context); } protected List<Delta> getDeltas(Revision rev) { List<Delta> list = new ArrayList<Delta>(); for (int i = 0; i < rev.size(); i++) { list.add(rev.getDelta(i)); } return list; } public List<MetaDataDiff> getMetaDataDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException { XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context); XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context); return getMetaDataDiff(fromDoc, toDoc, context); } public List<MetaDataDiff> getMetaDataDiff(String fromRev, XWikiContext context) throws XWikiException { XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context); return getMetaDataDiff(revdoc, this, context); } public List<MetaDataDiff> getMetaDataDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException { List<MetaDataDiff> list = new ArrayList<MetaDataDiff>(); if ((fromDoc == null) || (toDoc == null)) { return list; } if (!fromDoc.getParent().equals(toDoc.getParent())) { list.add(new MetaDataDiff("parent", fromDoc.getParent(), toDoc.getParent())); } if (!fromDoc.getAuthor().equals(toDoc.getAuthor())) { list.add(new MetaDataDiff("author", fromDoc.getAuthor(), toDoc.getAuthor())); } if (!fromDoc.getSpace().equals(toDoc.getSpace())) { list.add(new MetaDataDiff("web", fromDoc.getSpace(), toDoc.getSpace())); } if (!fromDoc.getName().equals(toDoc.getName())) { list.add(new MetaDataDiff("name", fromDoc.getName(), toDoc.getName())); } if (!fromDoc.getLanguage().equals(toDoc.getLanguage())) { list.add(new MetaDataDiff("language", fromDoc.getLanguage(), toDoc.getLanguage())); } if (!fromDoc.getDefaultLanguage().equals(toDoc.getDefaultLanguage())) { list.add(new MetaDataDiff("defaultLanguage", fromDoc.getDefaultLanguage(), toDoc.getDefaultLanguage())); } return list; } public List<List<ObjectDiff>> getObjectDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException { XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context); XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context); return getObjectDiff(fromDoc, toDoc, context); } public List<List<ObjectDiff>> getObjectDiff(String fromRev, XWikiContext context) throws XWikiException { XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context); return getObjectDiff(revdoc, this, context); } /** * Return the object differences between two document versions. There is no hard requirement on the order of the two * versions, but the results are semantically correct only if the two versions are given in the right order. * * @param fromDoc The old ('before') version of the document. * @param toDoc The new ('after') version of the document. * @param context The {@link com.xpn.xwiki.XWikiContext context}. * @return The object differences. The returned list's elements are other lists, one for each changed object. The * inner lists contain {@link ObjectDiff} elements, one object for each changed property of the object. * Additionally, if the object was added or removed, then the first entry in the list will be an * "object-added" or "object-removed" marker. * @throws XWikiException If there's an error computing the differences. */ public List<List<ObjectDiff>> getObjectDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException { ArrayList<List<ObjectDiff>> difflist = new ArrayList<List<ObjectDiff>>(); // Since objects could have been deleted or added, we iterate on both the old and the new // object collections. // First, iterate over the old objects. for (List<BaseObject> objects : fromDoc.getXObjects().values()) { for (BaseObject originalObj : objects) { // This happens when objects are deleted, and the document is still in the cache // storage. if (originalObj != null) { BaseObject newObj = toDoc.getXObject(originalObj.getXClassReference(), originalObj.getNumber()); List<ObjectDiff> dlist; if (newObj == null) { // The object was deleted. dlist = new BaseObject().getDiff(originalObj, context); ObjectDiff deleteMarker = new ObjectDiff(originalObj.getClassName(), originalObj.getNumber(), originalObj.getGuid(), "object-removed", "", "", "", ""); dlist.add(0, deleteMarker); } else { // The object exists in both versions, but might have been changed. dlist = newObj.getDiff(originalObj, context); } if (dlist.size() > 0) { difflist.add(dlist); } } } } // Second, iterate over the objects which are only in the new version. for (List<BaseObject> objects : toDoc.getXObjects().values()) { for (BaseObject newObj : objects) { // This happens when objects are deleted, and the document is still in the cache // storage. if (newObj != null) { BaseObject originalObj = fromDoc.getXObject(newObj.getXClassReference(), newObj.getNumber()); if (originalObj == null) { // Only consider added objects, the other case was treated above. originalObj = new BaseObject(); originalObj.setXClassReference(newObj.getXClassReference()); originalObj.setNumber(newObj.getNumber()); originalObj.setGuid(newObj.getGuid()); List<ObjectDiff> dlist = newObj.getDiff(originalObj, context); ObjectDiff addMarker = new ObjectDiff(newObj.getClassName(), newObj.getNumber(), newObj.getGuid(), "object-added", "", "", "", ""); dlist.add(0, addMarker); if (dlist.size() > 0) { difflist.add(dlist); } } } } } return difflist; } public List<List<ObjectDiff>> getClassDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException { ArrayList<List<ObjectDiff>> difflist = new ArrayList<List<ObjectDiff>>(); BaseClass oldClass = fromDoc.getXClass(); BaseClass newClass = toDoc.getXClass(); if ((newClass == null) && (oldClass == null)) { return difflist; } List<ObjectDiff> dlist = newClass.getDiff(oldClass, context); if (dlist.size() > 0) { difflist.add(dlist); } return difflist; } /** * @param fromDoc * @param toDoc * @param context * @return * @throws XWikiException */ public List<AttachmentDiff> getAttachmentDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException { List<AttachmentDiff> difflist = new ArrayList<AttachmentDiff>(); for (XWikiAttachment origAttach : fromDoc.getAttachmentList()) { String fileName = origAttach.getFilename(); XWikiAttachment newAttach = toDoc.getAttachment(fileName); if (newAttach == null) { difflist.add(new AttachmentDiff(fileName, origAttach.getVersion(), null)); } else { if (!origAttach.getVersion().equals(newAttach.getVersion())) { difflist.add(new AttachmentDiff(fileName, origAttach.getVersion(), newAttach.getVersion())); } } } for (XWikiAttachment newAttach : toDoc.getAttachmentList()) { String fileName = newAttach.getFilename(); XWikiAttachment origAttach = fromDoc.getAttachment(fileName); if (origAttach == null) { difflist.add(new AttachmentDiff(fileName, null, newAttach.getVersion())); } } return difflist; } /** * Rename the current document and all the backlinks leading to it. Will also change parent field in all documents * which list the document we are renaming as their parent. * <p> * See {@link #rename(String, java.util.List, com.xpn.xwiki.XWikiContext)} for more details. * * @param newDocumentReference the new document reference * @param context the ubiquitous XWiki Context * @throws XWikiException in case of an error * @since 2.2M2 */ public void rename(DocumentReference newDocumentReference, XWikiContext context) throws XWikiException { rename(newDocumentReference, getBackLinkedReferences(context), context); } /** * @deprecated since 2.2M2 use {@link #rename(DocumentReference, XWikiContext)} */ @Deprecated public void rename(String newDocumentName, XWikiContext context) throws XWikiException { rename(newDocumentName, getBackLinkedPages(context), context); } /** * Rename the current document and all the links pointing to it in the list of passed backlink documents. The * renaming algorithm takes into account the fact that there are several ways to write a link to a given page and * all those forms need to be renamed. For example the following links all point to the same page: * <ul> * <li>[Page]</li> * <li>[Page?param=1]</li> * <li>[currentwiki:Page]</li> * <li>[CurrentSpace.Page]</li> * <li>[currentwiki:CurrentSpace.Page]</li> * </ul> * <p> * Note: links without a space are renamed with the space added and all documents which have the document being * renamed as parent have their parent field set to "currentwiki:CurrentSpace.Page". * </p> * * @param newDocumentReference the new document reference * @param backlinkDocumentReferences the list of references of documents to parse and for which links will be * modified to point to the new document reference * @param context the ubiquitous XWiki Context * @throws XWikiException in case of an error * @since 2.2M2 */ public void rename(DocumentReference newDocumentReference, List<DocumentReference> backlinkDocumentReferences, XWikiContext context) throws XWikiException { rename(newDocumentReference, backlinkDocumentReferences, getChildrenReferences(context), context); } /** * @deprecated since 2.2M2 use {@link #rename(DocumentReference, java.util.List, com.xpn.xwiki.XWikiContext)} */ @Deprecated public void rename(String newDocumentName, List<String> backlinkDocumentNames, XWikiContext context) throws XWikiException { rename(newDocumentName, backlinkDocumentNames, getChildren(context), context); } /** * Same as {@link #rename(String, List, XWikiContext)} but the list of documents having the current document as * their parent is passed in parameter. * * @param newDocumentReference the new document reference * @param backlinkDocumentReferences the list of references of documents to parse and for which links will be * modified to point to the new document reference * @param childDocumentReferences the list of references of document whose parent field will be set to the new * document reference * @param context the ubiquitous XWiki Context * @throws XWikiException in case of an error * @since 2.2M2 */ public void rename(DocumentReference newDocumentReference, List<DocumentReference> backlinkDocumentReferences, List<DocumentReference> childDocumentReferences, XWikiContext context) throws XWikiException { // TODO: Do all this in a single DB transaction as otherwise the state will be unknown if // something fails in the middle... // TODO: Why do we verify if the document has just been created and not been saved. // If the user is trying to rename to the same name... In that case, simply exits for efficiency. if (isNew() || getDocumentReference().equals(newDocumentReference)) { return; } // Grab the xwiki object, it gets used a few times. XWiki xwiki = context.getWiki(); // Step 1: Copy the document and all its translations under a new document with the new reference. xwiki.copyDocument(getDocumentReference(), newDocumentReference, false, context); // Step 2: For each child document, update its parent reference. if (childDocumentReferences != null) { for (DocumentReference childDocumentReference : childDocumentReferences) { XWikiDocument childDocument = xwiki.getDocument(childDocumentReference, context); childDocument.setParentReference(newDocumentReference); String saveMessage = context.getMessageTool().get("core.comment.renameParent", Arrays.asList(this.compactEntityReferenceSerializer.serialize(newDocumentReference))); xwiki.saveDocument(childDocument, saveMessage, true, context); } } // Step 3: For each backlink to rename, parse the backlink document and replace the links with the new name. // Note: we ignore invalid links here. Invalid links should be shown to the user so // that they fix them but the rename feature ignores them. DocumentParser documentParser = new DocumentParser(); // This link handler recognizes that 2 links are the same when they point to the same // document (regardless of query string, target or alias). It keeps the query string, // target and alias from the link being replaced. RenamePageReplaceLinkHandler linkHandler = new RenamePageReplaceLinkHandler(); // Used for replacing links in XWiki Syntax 1.0 Link oldLink = new LinkParser().parse(this.localEntityReferenceSerializer.serialize(getDocumentReference())); Link newLink = new LinkParser().parse(this.localEntityReferenceSerializer.serialize(newDocumentReference)); for (DocumentReference backlinkDocumentReference : backlinkDocumentReferences) { XWikiDocument backlinkDocument = xwiki.getDocument(backlinkDocumentReference, context); if (backlinkDocument.is10Syntax()) { // Note: Here we cannot do a simple search/replace as there are several ways to point // to the same document. For example [Page], [Page?param=1], [currentwiki:Page], // [CurrentSpace.Page] all point to the same document. Thus we have to parse the links // to recognize them and do the replace. ReplacementResultCollection result = documentParser.parseLinksAndReplace(backlinkDocument.getContent(), oldLink, newLink, linkHandler, getDocumentReference().getLastSpaceReference().getName()); backlinkDocument.setContent((String) result.getModifiedContent()); } else { backlinkDocument.refactorDocumentLinks(getDocumentReference(), newDocumentReference, context); } String saveMessage = context.getMessageTool().get("core.comment.renameLink", Arrays.asList(this.compactEntityReferenceSerializer.serialize(newDocumentReference))); xwiki.saveDocument(backlinkDocument, saveMessage, true, context); } // Step 4: Delete the old document xwiki.deleteDocument(this, context); // Step 5: The current document needs to point to the renamed document as otherwise it's pointing to an // invalid XWikiDocument object as it's been deleted... clone(xwiki.getDocument(newDocumentReference, context)); } /** * @deprecated since 2.2M2 use {@link #rename(DocumentReference, List, List, com.xpn.xwiki.XWikiContext)} */ @Deprecated public void rename(String newDocumentName, List<String> backlinkDocumentNames, List<String> childDocumentNames, XWikiContext context) throws XWikiException { List<DocumentReference> backlinkDocumentReferences = new ArrayList<DocumentReference>(); for (String backlinkDocumentName : backlinkDocumentNames) { backlinkDocumentReferences.add(this.currentMixedDocumentReferenceResolver.resolve(backlinkDocumentName)); } List<DocumentReference> childDocumentReferences = new ArrayList<DocumentReference>(); for (String childDocumentName : childDocumentNames) { childDocumentReferences.add(this.currentMixedDocumentReferenceResolver.resolve(childDocumentName)); } rename(this.currentMixedDocumentReferenceResolver.resolve(newDocumentName), backlinkDocumentReferences, childDocumentReferences, context); } /** * @since 2.2M1 */ private void refactorDocumentLinks(DocumentReference oldDocumentReference, DocumentReference newDocumentReference, XWikiContext context) throws XWikiException { String contextWiki = context.getDatabase(); XWikiDocument contextDoc = context.getDoc(); try { context.setDatabase(getDocumentReference().getWikiReference().getName()); context.setDoc(this); XDOM xdom = getXDOM(); List<LinkBlock> linkBlockList = xdom.getChildrenByType(LinkBlock.class, true); for (LinkBlock linkBlock : linkBlockList) { org.xwiki.rendering.listener.Link link = linkBlock.getLink(); if (link.getType() == LinkType.DOCUMENT) { DocumentReference documentReference = this.currentDocumentReferenceResolver.resolve(link.getReference()); if (documentReference.equals(oldDocumentReference)) { link.setReference(this.compactEntityReferenceSerializer.serialize(newDocumentReference)); } } } setContent(xdom); } finally { context.setDatabase(contextWiki); context.setDoc(contextDoc); } } /** * @since 2.2M1 */ public XWikiDocument copyDocument(DocumentReference newDocumentReference, XWikiContext context) throws XWikiException { loadAttachments(context); loadArchive(context); XWikiDocument newdoc = (XWikiDocument) clone(); newdoc.setOriginalDocument(null); newdoc.setDocumentReference(newDocumentReference); newdoc.setContentDirty(true); newdoc.getXClass().setDocumentReference(newDocumentReference); Map<DocumentReference, List<BaseObject>> objectClasses = newdoc.getXObjects(); if (objectClasses != null) { for (List<BaseObject> objects : objectClasses.values()) { if (objects != null) { for (BaseObject object : objects) { if (object != null) { object.setDocumentReference(newDocumentReference); // Since GUIDs are supposed to be Unique, although this object holds the same data, it is // not exactly the same object, so it should have a different identifier. object.setGuid(UUID.randomUUID().toString()); } } } } } XWikiDocumentArchive archive = newdoc.getDocumentArchive(); if (archive != null) { newdoc.setDocumentArchive(archive.clone(newdoc.getId(), context)); } return newdoc; } /** * @deprecated since 2.2M1 use {@link #copyDocument(DocumentReference, XWikiContext)} instead */ @Deprecated public XWikiDocument copyDocument(String newDocumentName, XWikiContext context) throws XWikiException { return copyDocument(this.currentMixedDocumentReferenceResolver.resolve(newDocumentName), context); } public XWikiLock getLock(XWikiContext context) throws XWikiException { XWikiLock theLock = getStore(context).loadLock(getId(), context, true); if (theLock != null) { int timeout = context.getWiki().getXWikiPreferenceAsInt("lock_Timeout", 30 * 60, context); if (theLock.getDate().getTime() + timeout * 1000 < new Date().getTime()) { getStore(context).deleteLock(theLock, context, true); theLock = null; } } return theLock; } public void setLock(String userName, XWikiContext context) throws XWikiException { XWikiLock lock = new XWikiLock(getId(), userName); getStore(context).saveLock(lock, context, true); } public void removeLock(XWikiContext context) throws XWikiException { XWikiLock lock = getStore(context).loadLock(getId(), context, true); if (lock != null) { getStore(context).deleteLock(lock, context, true); } } public void insertText(String text, String marker, XWikiContext context) throws XWikiException { setContent(StringUtils.replaceOnce(getContent(), marker, text + marker)); context.getWiki().saveDocument(this, context); } public Object getWikiNode() { return this.wikiNode; } public void setWikiNode(Object wikiNode) { this.wikiNode = wikiNode; } /** * @since 2.2M1 */ public String getXClassXML() { return this.xClassXML; } /** * @deprecated since 2.2M1 use {@link #getXClassXML()} instead */ @Deprecated public String getxWikiClassXML() { return getXClassXML(); } /** * @since 2.2M1 */ public void setXClassXML(String xClassXML) { this.xClassXML = xClassXML; } /** * @deprecated since 2.2M1 use {@link #setXClassXML(String)} ()} instead */ @Deprecated public void setxWikiClassXML(String xClassXML) { setXClassXML(xClassXML); } public int getElements() { return this.elements; } public void setElements(int elements) { this.elements = elements; } public void setElement(int element, boolean toggle) { if (toggle) { this.elements = this.elements | element; } else { this.elements = this.elements & (~element); } } public boolean hasElement(int element) { return ((this.elements & element) == element); } /** * @return "inline" if the document should be edited in inline mode by default or "edit" otherwise. * @throws XWikiException if an error happens when computing the edit mode */ public String getDefaultEditMode(XWikiContext context) throws XWikiException { com.xpn.xwiki.XWiki xwiki = context.getWiki(); if (is10Syntax()) { if (getContent().indexOf("includeForm(") != -1) { return "inline"; } } else { // Algorithm: look in all include macro and for all document included check if one of them // has an SheetClass object attached to it. If so then the edit mode is inline. // Find all include macros and extract the document names for (MacroBlock macroBlock : getXDOM().getChildrenByType(MacroBlock.class, false)) { // TODO: Is there a good way not to hardcode the macro name? The macro itself shouldn't know // its own name since it's a deployment time concern. if ("include".equals(macroBlock.getId())) { String documentName = macroBlock.getParameter("document"); if (documentName != null) { // Resolve the document name into a valid Reference DocumentReference documentReference = this.currentMixedDocumentReferenceResolver.resolve(documentName); XWikiDocument includedDocument = xwiki.getDocument(documentReference, context); if (!includedDocument.isNew()) { BaseObject sheetClassObject = includedDocument.getObject(XWikiConstant.SHEET_CLASS); if (sheetClassObject != null) { // Use the user-defined default edit mode if set. String defaultEditMode = sheetClassObject.getStringValue("defaultEditMode"); if (StringUtils.isBlank(defaultEditMode)) { return "inline"; } else { return defaultEditMode; } } } } } } } return "edit"; } public String getDefaultEditURL(XWikiContext context) throws XWikiException { String editMode = getDefaultEditMode(context); if ("inline".equals(editMode)) { return getEditURL("inline", "", context); } else { com.xpn.xwiki.XWiki xwiki = context.getWiki(); String editor = xwiki.getEditorPreference(context); return getEditURL("edit", editor, context); } } public String getEditURL(String action, String mode, XWikiContext context) throws XWikiException { com.xpn.xwiki.XWiki xwiki = context.getWiki(); String language = ""; XWikiDocument tdoc = (XWikiDocument) context.get("tdoc"); String realLang = tdoc.getRealLanguage(context); if ((xwiki.isMultiLingual(context) == true) && (!realLang.equals(""))) { language = realLang; } return getEditURL(action, mode, language, context); } public String getEditURL(String action, String mode, String language, XWikiContext context) { StringBuffer editparams = new StringBuffer(); if (!mode.equals("")) { editparams.append("xpage="); editparams.append(mode); } if (!language.equals("")) { if (!mode.equals("")) { editparams.append("&"); } editparams.append("language="); editparams.append(language); } return getURL(action, editparams.toString(), context); } public String getDefaultTemplate() { if (this.defaultTemplate == null) { return ""; } else { return this.defaultTemplate; } } public void setDefaultTemplate(String defaultTemplate) { this.defaultTemplate = defaultTemplate; setMetaDataDirty(true); } public Vector<BaseObject> getComments() { return getComments(true); } /** * @return the syntax of the document * @since 2.3M1 */ public Syntax getSyntax() { // Can't be initialized in the XWikiDocument constructor because #getDefaultDocumentSyntax() need to create a // XWikiDocument object to get preferences from wiki preferences pages and would thus generate an infinite loop if (isNew() && this.syntax == null) { this.syntax = getDefaultDocumentSyntax(); } return this.syntax; } /** * Note that this method cannot be removed for now since it's used by Hibernate for saving a XWikiDocument. * * {@inheritDoc} * * @see org.xwiki.bridge.DocumentModelBridge#getSyntaxId() * @deprecated since 2.3M1, use {link #getSyntax()} instead */ public String getSyntaxId() { return getSyntax().toIdString(); } /** * @param syntax the new syntax to set for this document * @see #getSyntax() * @since 2.3M1 */ public void setSyntax(Syntax syntax) { this.syntax = syntax; } /** * Note that this method cannot be removed for now since it's used by Hibernate for saving a XWikiDocument. * * @param syntaxId the new syntax id to set (eg "xwiki/1.0", "xwiki/2.0", etc) * @see #getSyntaxId() * @deprecated since 2.3M1, use {link #setSyntax(Syntax)} instead */ public void setSyntaxId(String syntaxId) { Syntax syntax; try { syntax = this.syntaxFactory.createSyntaxFromIdString(syntaxId); } catch (ParseException e) { syntax = getDefaultDocumentSyntax(); LOG.warn("Failed to set syntax [" + syntaxId + "] for [" + this.defaultEntityReferenceSerializer.serialize(getDocumentReference()) + "], setting syntax [" + syntax.toIdString() + "] instead.", e); } setSyntax(syntax); } public Vector<BaseObject> getComments(boolean asc) { Vector<BaseObject> list = getObjects("XWiki.XWikiComments"); if (asc) { return list; } else { if (list == null) { return list; } Vector<BaseObject> newlist = new Vector<BaseObject>(); for (int i = list.size() - 1; i >= 0; i newlist.add(list.get(i)); } return newlist; } } public boolean isCurrentUserCreator(XWikiContext context) { return isCreator(context.getUser()); } public boolean isCreator(String username) { if (username.equals(XWikiRightService.GUEST_USER_FULLNAME)) { return false; } return username.equals(getCreator()); } public boolean isCurrentUserPage(XWikiContext context) { String username = context.getUser(); if (username.equals(XWikiRightService.GUEST_USER_FULLNAME)) { return false; } return context.getUser().equals(getFullName()); } public boolean isCurrentLocalUserPage(XWikiContext context) { String username = context.getLocalUser(); if (username.equals(XWikiRightService.GUEST_USER_FULLNAME)) { return false; } return context.getUser().equals(getFullName()); } public void resetArchive(XWikiContext context) throws XWikiException { boolean hasVersioning = context.getWiki().hasVersioning(getFullName(), context); if (hasVersioning) { getVersioningStore(context).resetRCSArchive(this, true, context); } } /** * Adds an object from an new object creation form. * * @since 2.2M2 */ public BaseObject addXObjectFromRequest(XWikiContext context) throws XWikiException { // Read info in object ObjectAddForm form = new ObjectAddForm(); form.setRequest((HttpServletRequest) context.getRequest()); form.readRequest(); DocumentReference classReference = this.currentMixedDocumentReferenceResolver.resolve(form.getClassName()); BaseObject object = newXObject(classReference, context); BaseClass baseclass = object.getXClass(context); baseclass.fromMap(form.getObject(this.localEntityReferenceSerializer.serialize(classReference)), object); return object; } /** * @deprecated since 2.2M2 use {@link #addXObjectFromRequest(XWikiContext)} */ @Deprecated public BaseObject addObjectFromRequest(XWikiContext context) throws XWikiException { return addXObjectFromRequest(context); } /** * Adds an object from an new object creation form. * * @since 2.2M2 */ public BaseObject addXObjectFromRequest(DocumentReference classReference, XWikiContext context) throws XWikiException { return addXObjectFromRequest(classReference, "", 0, context); } /** * @deprecated since 2.2M2 use {@link #addXObjectFromRequest(DocumentReference, XWikiContext)} */ @Deprecated public BaseObject addObjectFromRequest(String className, XWikiContext context) throws XWikiException { return addObjectFromRequest(className, "", 0, context); } /** * Adds an object from an new object creation form. * * @since 2.2M2 */ public BaseObject addXObjectFromRequest(DocumentReference classReference, String prefix, XWikiContext context) throws XWikiException { return addXObjectFromRequest(classReference, prefix, 0, context); } /** * @deprecated since 2.2M2 use {@link #addXObjectFromRequest(DocumentReference, String, XWikiContext)} */ @Deprecated public BaseObject addObjectFromRequest(String className, String prefix, XWikiContext context) throws XWikiException { return addObjectFromRequest(className, prefix, 0, context); } /** * Adds multiple objects from an new objects creation form. * * @since 2.2M2 */ public List<BaseObject> addXObjectsFromRequest(DocumentReference classReference, XWikiContext context) throws XWikiException { return addXObjectsFromRequest(classReference, "", context); } /** * @deprecated since 2.2M2 use {@link #addXObjectsFromRequest(DocumentReference, XWikiContext)} */ @Deprecated public List<BaseObject> addObjectsFromRequest(String className, XWikiContext context) throws XWikiException { return addObjectsFromRequest(className, "", context); } /** * Adds multiple objects from an new objects creation form. * * @since 2.2M2 */ public List<BaseObject> addXObjectsFromRequest(DocumentReference classReference, String pref, XWikiContext context) throws XWikiException { Map map = context.getRequest().getParameterMap(); List<Integer> objectsNumberDone = new ArrayList<Integer>(); List<BaseObject> objects = new ArrayList<BaseObject>(); Iterator it = map.keySet().iterator(); String start = pref + this.localEntityReferenceSerializer.serialize(classReference) + "_"; while (it.hasNext()) { String name = (String) it.next(); if (name.startsWith(start)) { int pos = name.indexOf("_", start.length() + 1); String prefix = name.substring(0, pos); int num = Integer.decode(prefix.substring(prefix.lastIndexOf("_") + 1)).intValue(); if (!objectsNumberDone.contains(new Integer(num))) { objectsNumberDone.add(new Integer(num)); objects.add(addXObjectFromRequest(classReference, pref, num, context)); } } } return objects; } /** * @deprecated since 2.2M2 use {@link #addXObjectsFromRequest(DocumentReference, String, XWikiContext)} */ @Deprecated public List<BaseObject> addObjectsFromRequest(String className, String pref, XWikiContext context) throws XWikiException { return addXObjectsFromRequest(resolveClassReference(className), pref, context); } /** * Adds object from an new object creation form. * * @since 2.2M2 */ public BaseObject addXObjectFromRequest(DocumentReference classReference, int num, XWikiContext context) throws XWikiException { return addXObjectFromRequest(classReference, "", num, context); } /** * @deprecated since 2.2M2 use {@link #addXObjectFromRequest(DocumentReference, int, XWikiContext)} */ @Deprecated public BaseObject addObjectFromRequest(String className, int num, XWikiContext context) throws XWikiException { return addObjectFromRequest(className, "", num, context); } /** * Adds object from an new object creation form. * * @since 2.2M2 */ public BaseObject addXObjectFromRequest(DocumentReference classReference, String prefix, int num, XWikiContext context) throws XWikiException { BaseObject object = newXObject(classReference, context); BaseClass baseclass = object.getXClass(context); String newPrefix = prefix + this.localEntityReferenceSerializer.serialize(classReference) + "_" + num; baseclass.fromMap(Util.getObject(context.getRequest(), newPrefix), object); return object; } /** * @deprecated since 2.2M2 use {@link #addXObjectFromRequest(DocumentReference, String, int, XWikiContext)} */ @Deprecated public BaseObject addObjectFromRequest(String className, String prefix, int num, XWikiContext context) throws XWikiException { return addXObjectFromRequest(resolveClassReference(className), prefix, num, context); } /** * Adds an object from an new object creation form. * * @since 2.2M2 */ public BaseObject updateXObjectFromRequest(DocumentReference classReference, XWikiContext context) throws XWikiException { return updateXObjectFromRequest(classReference, "", context); } /** * @deprecated since 2.2M2 use {@link #updateXObjectFromRequest(DocumentReference, XWikiContext)} */ @Deprecated public BaseObject updateObjectFromRequest(String className, XWikiContext context) throws XWikiException { return updateObjectFromRequest(className, "", context); } /** * Adds an object from an new object creation form. * * @since 2.2M2 */ public BaseObject updateXObjectFromRequest(DocumentReference classReference, String prefix, XWikiContext context) throws XWikiException { return updateXObjectFromRequest(classReference, prefix, 0, context); } /** * @deprecated since 2.2M2 use {@link #updateXObjectFromRequest(DocumentReference, String, XWikiContext)} */ @Deprecated public BaseObject updateObjectFromRequest(String className, String prefix, XWikiContext context) throws XWikiException { return updateObjectFromRequest(className, prefix, 0, context); } /** * Adds an object from an new object creation form. * * @since 2.2M2 */ public BaseObject updateXObjectFromRequest(DocumentReference classReference, String prefix, int num, XWikiContext context) throws XWikiException { int nb; BaseObject oldobject = getXObject(classReference, num); if (oldobject == null) { nb = createXObject(classReference, context); oldobject = getXObject(classReference, nb); } else { nb = oldobject.getNumber(); } BaseClass baseclass = oldobject.getXClass(context); String newPrefix = prefix + this.localEntityReferenceSerializer.serialize(classReference) + "_" + nb; BaseObject newobject = (BaseObject) baseclass.fromMap(Util.getObject(context.getRequest(), newPrefix), oldobject); newobject.setNumber(oldobject.getNumber()); newobject.setGuid(oldobject.getGuid()); newobject.setDocumentReference(getDocumentReference()); setXObject(classReference, nb, newobject); return newobject; } /** * @deprecated since 2.2M2 use {@link #updateXObjectFromRequest(DocumentReference, String, int, XWikiContext)} */ @Deprecated public BaseObject updateObjectFromRequest(String className, String prefix, int num, XWikiContext context) throws XWikiException { return updateXObjectFromRequest(resolveClassReference(className), prefix, num, context); } /** * Adds an object from an new object creation form. * * @since 2.2M2 */ public List<BaseObject> updateXObjectsFromRequest(DocumentReference classReference, XWikiContext context) throws XWikiException { return updateXObjectsFromRequest(classReference, "", context); } /** * @deprecated since 2.2M2 use {@link #updateXObjectsFromRequest(DocumentReference, XWikiContext)} */ @Deprecated public List<BaseObject> updateObjectsFromRequest(String className, XWikiContext context) throws XWikiException { return updateObjectsFromRequest(className, "", context); } /** * Adds multiple objects from an new objects creation form. * * @since 2.2M2 */ public List<BaseObject> updateXObjectsFromRequest(DocumentReference classReference, String pref, XWikiContext context) throws XWikiException { Map map = context.getRequest().getParameterMap(); List<Integer> objectsNumberDone = new ArrayList<Integer>(); List<BaseObject> objects = new ArrayList<BaseObject>(); Iterator it = map.keySet().iterator(); String start = pref + this.localEntityReferenceSerializer.serialize(classReference) + "_"; while (it.hasNext()) { String name = (String) it.next(); if (name.startsWith(start)) { int pos = name.indexOf("_", start.length() + 1); String prefix = name.substring(0, pos); int num = Integer.decode(prefix.substring(prefix.lastIndexOf("_") + 1)).intValue(); if (!objectsNumberDone.contains(new Integer(num))) { objectsNumberDone.add(new Integer(num)); objects.add(updateXObjectFromRequest(classReference, pref, num, context)); } } } return objects; } /** * @deprecated since 2.2M2 use {@link #updateXObjectsFromRequest(DocumentReference, String, XWikiContext)} */ @Deprecated public List<BaseObject> updateObjectsFromRequest(String className, String pref, XWikiContext context) throws XWikiException { return updateXObjectsFromRequest(resolveClassReference(className), pref, context); } public boolean isAdvancedContent() { String[] matches = {"<%", "#set", "#include", "#if", "public class", "/* Advanced content */", "## Advanced content", "/* Programmatic content */", "## Programmatic content"}; String content2 = this.content.toLowerCase(); for (int i = 0; i < matches.length; i++) { if (content2.indexOf(matches[i].toLowerCase()) != -1) { return true; } } if (HTML_TAG_PATTERN.matcher(content2).find()) { return true; } return false; } public boolean isProgrammaticContent() { String[] matches = {"<%", "\\$xwiki.xWiki", "$context.context", "$doc.document", "$xwiki.getXWiki()", "$context.getContext()", "$doc.getDocument()", "WithProgrammingRights(", "/* Programmatic content */", "## Programmatic content", "$xwiki.search(", "$xwiki.createUser", "$xwiki.createNewWiki", "$xwiki.addToAllGroup", "$xwiki.sendMessage", "$xwiki.copyDocument", "$xwiki.copyWikiWeb", "$xwiki.copySpaceBetweenWikis", "$xwiki.parseGroovyFromString", "$doc.toXML()", "$doc.toXMLDocument()",}; String content2 = this.content.toLowerCase(); for (int i = 0; i < matches.length; i++) { if (content2.indexOf(matches[i].toLowerCase()) != -1) { return true; } } return false; } /** * Remove an XObject from the document. The changes are not persisted until the document is saved. * * @param object the object to remove * @return {@code true} if the object was successfully removed, {@code false} if the object was not found in the * current document. * @since 2.2M1 */ public boolean removeXObject(BaseObject object) { List<BaseObject> objects = getXObjects(object.getXClassReference()); // No objects at all, nothing to remove if (objects == null) { return false; } // Sometimes the object vector is wrongly indexed, meaning that objects are not at the right position // Check if the right object is in place int objectPosition = object.getNumber(); if (objectPosition < objects.size()) { BaseObject storedObject = objects.get(objectPosition); if (storedObject == null || !storedObject.equals(object)) { // Try to find the correct position objectPosition = objects.indexOf(object); } } else { // The object position is greater than the array, that's invalid! objectPosition = -1; } // If the object is not in the document, simply ignore this request if (objectPosition < 0) { return false; } // We don't remove objects, but set null in their place, so that the object number corresponds to its position // in the vector objects.set(objectPosition, null); // Schedule the object for removal from the storage addObjectsToRemove(object); return true; } /** * Remove an XObject from the document. The changes are not persisted until the document is saved. * * @param object the object to remove * @return {@code true} if the object was successfully removed, {@code false} if the object was not found in the * current document. * @deprecated since 2.2M1, use {@link #removeXObject(com.xpn.xwiki.objects.BaseObject)} instead */ @Deprecated public boolean removeObject(BaseObject object) { return removeXObject(object); } /** * Remove all the objects of a given type (XClass) from the document. The object counter is left unchanged, so that * future objects will have new (different) numbers. However, on some storage engines the counter will be reset if * the document is removed from the cache and reloaded from the persistent storage. * * @param classReference The XClass reference of the XObjects to be removed. * @return {@code true} if the objects were successfully removed, {@code false} if no object from the target class * was in the current document. * @since 2.2M1 */ public boolean removeXObjects(DocumentReference classReference) { List<BaseObject> objects = getXObjects(classReference); // No objects at all, nothing to remove if (objects == null) { return false; } // Schedule the object for removal from the storage for (BaseObject object : objects) { if (object != null) { addObjectsToRemove(object); } } // Empty the vector, retaining its size int currentSize = objects.size(); objects.clear(); for (int i = 0; i < currentSize; i++) { objects.add(null); } return true; } /** * Remove all the objects of a given type (XClass) from the document. The object counter is left unchanged, so that * future objects will have new (different) numbers. However, on some storage engines the counter will be reset if * the document is removed from the cache and reloaded from the persistent storage. * * @param className The class name of the objects to be removed. * @return {@code true} if the objects were successfully removed, {@code false} if no object from the target class * was in the current document. * @deprecated since 2.2M1 use {@link #removeXObjects(org.xwiki.model.reference.DocumentReference)} instead */ @Deprecated public boolean removeObjects(String className) { return removeXObjects(resolveClassReference(className)); } /** * @return the sections in the current document * @throws XWikiException */ public List<DocumentSection> getSections() throws XWikiException { if (is10Syntax()) { return getSections10(); } else { List<DocumentSection> splitSections = new ArrayList<DocumentSection>(); List<HeaderBlock> headers = getFilteredHeaders(); int sectionNumber = 1; for (HeaderBlock header : headers) { // put -1 as index since there is no way to get the position of the header in the source int documentSectionIndex = -1; // Need to do the same thing than 1.0 content here String documentSectionLevel = StringUtils.repeat("1.", header.getLevel().getAsInt() - 1) + "1"; DocumentSection docSection = new DocumentSection(sectionNumber++, documentSectionIndex, documentSectionLevel, renderXDOM( new XDOM(header.getChildren()), getSyntax())); splitSections.add(docSection); } return splitSections; } } /** * Get XWiki context from execution context. * * @return the XWiki context for the current thread */ private XWikiContext getContext() { Execution execution = Utils.getComponent(Execution.class); ExecutionContext ec = execution.getContext(); XWikiContext context = null; if (ec != null) { context = (XWikiContext) ec.getProperty("xwikicontext"); } return context; } /** * Filter the headers from a document XDOM based on xwiki.section.depth property from xwiki.cfg file. * * @return the filtered headers */ private List<HeaderBlock> getFilteredHeaders() { List<HeaderBlock> filteredHeaders = new ArrayList<HeaderBlock>(); // get the headers List<HeaderBlock> headers = getXDOM().getChildrenByType(HeaderBlock.class, true); // get the maximum header level int sectionDepth = 2; XWikiContext context = getContext(); if (context != null) { sectionDepth = (int) context.getWiki().getSectionEditingDepth(); } // filter the headers for (HeaderBlock header : headers) { if (header.getLevel().getAsInt() <= sectionDepth) { filteredHeaders.add(header); } } return filteredHeaders; } /** * @return the sections in the current document */ private List<DocumentSection> getSections10() { // Pattern to match the title. Matches only level 1 and level 2 headings. Pattern headingPattern = Pattern.compile("^[ \\t]*+(1(\\.1){0,1}+)[ \\t]++(.++)$", Pattern.MULTILINE); Matcher matcher = headingPattern.matcher(getContent()); List<DocumentSection> splitSections = new ArrayList<DocumentSection>(); int sectionNumber = 0; // find title to split while (matcher.find()) { ++sectionNumber; String sectionLevel = matcher.group(1); String sectionTitle = matcher.group(3); int sectionIndex = matcher.start(); // Initialize a documentSection object. DocumentSection docSection = new DocumentSection(sectionNumber, sectionIndex, sectionLevel, sectionTitle); // Add the document section to list. splitSections.add(docSection); } return splitSections; } /** * Return a Document section with parameter is sectionNumber. * * @param sectionNumber the index (+1) of the section in the list of all sections in the document. * @return * @throws XWikiException error when extracting sections from document */ public DocumentSection getDocumentSection(int sectionNumber) throws XWikiException { // return a document section according to section number return getSections().get(sectionNumber - 1); } /** * Return the content of a section. * * @param sectionNumber the index (+1) of the section in the list of all sections in the document. * @return the content of a section or null if the section can't be found. * @throws XWikiException error when trying to extract section content */ public String getContentOfSection(int sectionNumber) throws XWikiException { String content = null; if (is10Syntax()) { content = getContentOfSection10(sectionNumber); } else { List<HeaderBlock> headers = getFilteredHeaders(); if (headers.size() >= sectionNumber) { SectionBlock section = headers.get(sectionNumber - 1).getSection(); content = renderXDOM(new XDOM(Collections.<Block> singletonList(section)), getSyntax()); } } return content; } /** * Return the content of a section. * * @param sectionNumber the index (+1) of the section in the list of all sections in the document. * @return the content of a section * @throws XWikiException error when trying to extract section content */ private String getContentOfSection10(int sectionNumber) throws XWikiException { List<DocumentSection> splitSections = getSections(); int indexEnd = 0; // get current section DocumentSection section = splitSections.get(sectionNumber - 1); int indexStart = section.getSectionIndex(); String sectionLevel = section.getSectionLevel(); // Determine where this section ends, which is at the start of the next section of the // same or a higher level. for (int i = sectionNumber; i < splitSections.size(); i++) { DocumentSection nextSection = splitSections.get(i); String nextLevel = nextSection.getSectionLevel(); if (sectionLevel.equals(nextLevel) || sectionLevel.length() > nextLevel.length()) { indexEnd = nextSection.getSectionIndex(); break; } } String sectionContent = null; if (indexStart < 0) { indexStart = 0; } if (indexEnd == 0) { sectionContent = getContent().substring(indexStart); } else { sectionContent = getContent().substring(indexStart, indexEnd); } return sectionContent; } /** * Update a section content in document. * * @param sectionNumber the index (starting at 1) of the section in the list of all sections in the document. * @param newSectionContent the new section content. * @return the new document content. * @throws XWikiException error when updating content */ public String updateDocumentSection(int sectionNumber, String newSectionContent) throws XWikiException { String content; if (is10Syntax()) { content = updateDocumentSection10(sectionNumber, newSectionContent); } else { // Get the current section block HeaderBlock header = getFilteredHeaders().get(sectionNumber - 1); XDOM xdom = (XDOM) header.getRoot(); // newSectionContent -> Blocks List<Block> blocks = parseContent(newSectionContent).getChildren(); int sectionLevel = header.getLevel().getAsInt(); for (int level = 1; level < sectionLevel && blocks.size() == 1 && blocks.get(0) instanceof SectionBlock; ++level) { blocks = blocks.get(0).getChildren(); } // replace old current SectionBlock with new Blocks Block section = header.getSection(); section.getParent().replaceChild(blocks, section); // render back XDOM to document's content syntax content = renderXDOM(xdom, getSyntax()); } return content; } /** * Update a section content in document. * * @param sectionNumber the index (+1) of the section in the list of all sections in the document. * @param newSectionContent the new section content. * @return the new document content. * @throws XWikiException error when updating document content with section content */ private String updateDocumentSection10(int sectionNumber, String newSectionContent) throws XWikiException { StringBuffer newContent = new StringBuffer(); // get document section that will be edited DocumentSection docSection = getDocumentSection(sectionNumber); int numberOfSections = getSections().size(); int indexSection = docSection.getSectionIndex(); if (numberOfSections == 1) { // there is only a sections in document String contentBegin = getContent().substring(0, indexSection); newContent = newContent.append(contentBegin).append(newSectionContent); return newContent.toString(); } else if (sectionNumber == numberOfSections) { // edit lastest section that doesn't contain subtitle String contentBegin = getContent().substring(0, indexSection); newContent = newContent.append(contentBegin).append(newSectionContent); return newContent.toString(); } else { String sectionLevel = docSection.getSectionLevel(); int nextSectionIndex = 0; // get index of next section for (int i = sectionNumber; i < numberOfSections; i++) { DocumentSection nextSection = getDocumentSection(i + 1); // get next section String nextSectionLevel = nextSection.getSectionLevel(); if (sectionLevel.equals(nextSectionLevel)) { nextSectionIndex = nextSection.getSectionIndex(); break; } else if (sectionLevel.length() > nextSectionLevel.length()) { nextSectionIndex = nextSection.getSectionIndex(); break; } } if (nextSectionIndex == 0) {// edit the last section newContent = newContent.append(getContent().substring(0, indexSection)).append(newSectionContent); return newContent.toString(); } else { String contentAfter = getContent().substring(nextSectionIndex); String contentBegin = getContent().substring(0, indexSection); newContent = newContent.append(contentBegin).append(newSectionContent).append(contentAfter); } return newContent.toString(); } } /** * Computes a document hash, taking into account all document data: content, objects, attachments, metadata... TODO: * cache the hash value, update only on modification. */ public String getVersionHashCode(XWikiContext context) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { LOG.error("Cannot create MD5 object", ex); return this.hashCode() + ""; } try { String valueBeforeMD5 = toXML(true, false, true, false, context); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) { sb.append('0'); } sb.append(Integer.toHexString(b)); } return sb.toString(); } catch (Exception ex) { LOG.error("Exception while computing document hash", ex); } return this.hashCode() + ""; } public static String getInternalPropertyName(String propname, XWikiContext context) { XWikiMessageTool msg = context.getMessageTool(); String cpropname = StringUtils.capitalize(propname); return (msg == null) ? cpropname : msg.get(cpropname); } public String getInternalProperty(String propname) { String methodName = "get" + StringUtils.capitalize(propname); try { Method method = getClass().getDeclaredMethod(methodName, (Class[]) null); return (String) method.invoke(this, (Object[]) null); } catch (Exception e) { return null; } } public String getCustomClass() { if (this.customClass == null) { return ""; } return this.customClass; } public void setCustomClass(String customClass) { this.customClass = customClass; setMetaDataDirty(true); } public void setValidationScript(String validationScript) { this.validationScript = validationScript; setMetaDataDirty(true); } public String getValidationScript() { if (this.validationScript == null) { return ""; } else { return this.validationScript; } } public String getComment() { if (this.comment == null) { return ""; } return this.comment; } public void setComment(String comment) { this.comment = comment; } public boolean isMinorEdit() { return this.isMinorEdit; } public void setMinorEdit(boolean isMinor) { this.isMinorEdit = isMinor; } // methods for easy table update. It is need only for hibernate. // when hibernate update old database without minorEdit field, hibernate will create field with // null in despite of notnull in hbm. // so minorEdit will be null for old documents. But hibernate can't convert null to boolean. // so we need convert Boolean to boolean protected Boolean getMinorEdit1() { return Boolean.valueOf(this.isMinorEdit); } protected void setMinorEdit1(Boolean isMinor) { this.isMinorEdit = (isMinor != null && isMinor.booleanValue()); } /** * @since 2.2M2 */ public BaseObject newXObject(DocumentReference classReference, XWikiContext context) throws XWikiException { int nb = createXObject(classReference, context); return getXObject(classReference, nb); } /** * @deprecated since 2.2M2 use {@link #newXObject(DocumentReference, XWikiContext)} */ @Deprecated public BaseObject newObject(String className, XWikiContext context) throws XWikiException { return newXObject(resolveClassReference(className), context); } /** * @since 2.2M2 */ public BaseObject getXObject(DocumentReference classReference, boolean create, XWikiContext context) { try { BaseObject obj = getXObject(classReference); if ((obj == null) && create) { return newXObject(classReference, context); } if (obj == null) { return null; } else { return obj; } } catch (Exception e) { return null; } } /** * @deprecated since 2.2M2 use {@link #getXObject(DocumentReference, boolean, XWikiContext)} */ @Deprecated public BaseObject getObject(String className, boolean create, XWikiContext context) { return getXObject(resolveClassReference(className), create, context); } public boolean validate(XWikiContext context) throws XWikiException { return validate(null, context); } public boolean validate(String[] classNames, XWikiContext context) throws XWikiException { boolean isValid = true; if ((classNames == null) || (classNames.length == 0)) { for (DocumentReference classReference : getXObjects().keySet()) { BaseClass bclass = context.getWiki().getXClass(classReference, context); List<BaseObject> objects = getXObjects(classReference); for (BaseObject obj : objects) { if (obj != null) { isValid &= bclass.validateObject(obj, context); } } } } else { for (int i = 0; i < classNames.length; i++) { List<BaseObject> objects = getXObjects(this.currentMixedDocumentReferenceResolver.resolve(classNames[i])); if (objects != null) { for (BaseObject obj : objects) { if (obj != null) { BaseClass bclass = obj.getXClass(context); isValid &= bclass.validateObject(obj, context); } } } } } String validationScript = ""; XWikiRequest req = context.getRequest(); if (req != null) { validationScript = req.get("xvalidation"); } if ((validationScript == null) || (validationScript.trim().equals(""))) { validationScript = getValidationScript(); } if ((validationScript != null) && (!validationScript.trim().equals(""))) { isValid &= executeValidationScript(context, validationScript); } return isValid; } public static void backupContext(Map<String, Object> backup, XWikiContext context) { backup.put("doc", context.getDoc()); VelocityManager velocityManager = Utils.getComponent(VelocityManager.class); VelocityContext vcontext = velocityManager.getVelocityContext(); if (vcontext != null) { backup.put("vdoc", vcontext.get("doc")); backup.put("vcdoc", vcontext.get("cdoc")); backup.put("vtdoc", vcontext.get("tdoc")); } Map gcontext = (Map) context.get("gcontext"); if (gcontext != null) { backup.put("gdoc", gcontext.get("doc")); backup.put("gcdoc", gcontext.get("cdoc")); backup.put("gtdoc", gcontext.get("tdoc")); } // Clone the Execution Context to provide isolation Execution execution = Utils.getComponent(Execution.class); ExecutionContext clonedEc; try { clonedEc = Utils.getComponent(ExecutionContextManager.class).clone(execution.getContext()); } catch (ExecutionContextException e) { throw new RuntimeException("Failed to clone the Execution Context", e); } execution.pushContext(clonedEc); } public static void restoreContext(Map<String, Object> backup, XWikiContext context) { // Restore the Execution Context Execution execution = Utils.getComponent(Execution.class); execution.popContext(); Map<String, Object> gcontext = (Map<String, Object>) context.get("gcontext"); if (gcontext != null) { if (backup.get("gdoc") != null) { gcontext.put("doc", backup.get("gdoc")); } if (backup.get("gcdoc") != null) { gcontext.put("cdoc", backup.get("gcdoc")); } if (backup.get("gtdoc") != null) { gcontext.put("tdoc", backup.get("gtdoc")); } } VelocityManager velocityManager = Utils.getComponent(VelocityManager.class); VelocityContext vcontext = velocityManager.getVelocityContext(); if (vcontext != null) { if (backup.get("vdoc") != null) { vcontext.put("doc", backup.get("vdoc")); } if (backup.get("vcdoc") != null) { vcontext.put("cdoc", backup.get("vcdoc")); } if (backup.get("vtdoc") != null) { vcontext.put("tdoc", backup.get("vtdoc")); } } if (backup.get("doc") != null) { context.setDoc((XWikiDocument) backup.get("doc")); } } public void setAsContextDoc(XWikiContext context) { try { context.setDoc(this); com.xpn.xwiki.api.Document apidoc = this.newDocument(context); com.xpn.xwiki.api.Document tdoc = apidoc.getTranslatedDocument(); VelocityManager velocityManager = Utils.getComponent(VelocityManager.class); VelocityContext vcontext = velocityManager.getVelocityContext(); Map<String, Object> gcontext = (Map<String, Object>) context.get("gcontext"); if (vcontext != null) { vcontext.put("doc", apidoc); vcontext.put("tdoc", tdoc); } if (gcontext != null) { gcontext.put("doc", apidoc); gcontext.put("tdoc", tdoc); } } catch (XWikiException ex) { LOG.warn("Unhandled exception setting context", ex); } } public String getPreviousVersion() { return getDocumentArchive().getPrevVersion(this.version).toString(); } @Override public String toString() { return getFullName(); } /** * Indicates whether the document should be 'hidden' or not, meaning that it should not be returned in public search * results. WARNING: this is a temporary hack until the new data model is designed and implemented. No code should * rely on or use this property, since it will be replaced with a generic metadata. * * @param hidden The new value of the {@link #hidden} property. */ public void setHidden(Boolean hidden) { if (hidden == null) { this.hidden = false; } else { this.hidden = hidden; } } /** * Indicates whether the document is 'hidden' or not, meaning that it should not be returned in public search * results. WARNING: this is a temporary hack until the new data model is designed and implemented. No code should * rely on or use this property, since it will be replaced with a generic metadata. * * @return <code>true</code> if the document is hidden and does not appear among the results of * {@link com.xpn.xwiki.api.XWiki#searchDocuments(String)}, <code>false</code> otherwise. */ public Boolean isHidden() { return this.hidden; } /** * Convert the current document content from its current syntax to the new syntax passed as parameter. * * @param targetSyntaxId the syntax to convert to (eg "xwiki/2.0", "xhtml/1.0", etc) * @throws XWikiException if an exception occurred during the conversion process */ public void convertSyntax(String targetSyntaxId, XWikiContext context) throws XWikiException { try { convertSyntax(this.syntaxFactory.createSyntaxFromIdString(targetSyntaxId), context); } catch (Exception e) { throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_UNKNOWN, "Failed to convert document to syntax [" + targetSyntaxId + "]", e); } } /** * Convert the current document content from its current syntax to the new syntax passed as parameter. * * @param targetSyntax the syntax to convert to (eg "xwiki/2.0", "xhtml/1.0", etc) * @throws XWikiException if an exception occurred during the conversion process */ public void convertSyntax(Syntax targetSyntax, XWikiContext context) throws XWikiException { // convert content setContent(performSyntaxConversion(getContent(), getSyntaxId(), targetSyntax, false)); // convert objects Map<DocumentReference, List<BaseObject>> objectsByClass = getXObjects(); for (List<BaseObject> objects : objectsByClass.values()) { for (BaseObject bobject : objects) { if (bobject != null) { BaseClass bclass = bobject.getXClass(context); for (Object fieldClass : bclass.getProperties()) { if (fieldClass instanceof TextAreaClass && ((TextAreaClass) fieldClass).isWikiContent()) { TextAreaClass textAreaClass = (TextAreaClass) fieldClass; LargeStringProperty field = (LargeStringProperty) bobject.getField(textAreaClass.getName()); if (field != null) { field.setValue(performSyntaxConversion(field.getValue(), getSyntaxId(), targetSyntax, false)); } } } } } } // change syntax setSyntax(targetSyntax); } /** * @return the XDOM conrrexponding to the document's string content. */ public XDOM getXDOM() { if (this.xdom == null) { try { this.xdom = parseContent(getContent()); } catch (XWikiException e) { LOG.error("Failed to parse document content to XDOM", e); } } return this.xdom.clone(); } /** * @return true if the document has a xwiki/1.0 syntax content */ public boolean is10Syntax() { return is10Syntax(getSyntaxId()); } /** * @return true if the document has a xwiki/1.0 syntax content */ public boolean is10Syntax(String syntaxId) { return XWIKI10_SYNTAXID.equalsIgnoreCase(syntaxId); } private void init(DocumentReference reference) { // if the passed reference is null consider it points to the default reference if (reference == null) { setDocumentReference(Utils.getComponent(DocumentReferenceResolver.class).resolve("")); } else { setDocumentReference(reference); } this.updateDate = new Date(); this.updateDate.setTime((this.updateDate.getTime() / 1000) * 1000); this.contentUpdateDate = new Date(); this.contentUpdateDate.setTime((this.contentUpdateDate.getTime() / 1000) * 1000); this.creationDate = new Date(); this.creationDate.setTime((this.creationDate.getTime() / 1000) * 1000); this.content = "\n"; this.format = ""; this.author = ""; this.language = ""; this.defaultLanguage = ""; this.attachmentList = new ArrayList<XWikiAttachment>(); this.customClass = ""; this.comment = ""; // Note: As there's no notion of an Empty document we don't set the original document // field. Thus getOriginalDocument() may return null. } private boolean executeValidationScript(XWikiContext context, String validationScript) throws XWikiException { try { XWikiValidationInterface validObject = (XWikiValidationInterface) context.getWiki().parseGroovyFromPage(validationScript, context); return validObject.validateDocument(this, context); } catch (Throwable e) { XWikiValidationStatus.addExceptionToContext(getFullName(), "", e, context); return false; } } /** * Convert the passed content from the passed syntax to the passed new syntax. * * @param content the content to convert * @param currentSyntaxId the syntax of the current content to convert * @param targetSyntax the new syntax after the conversion * @param transform indicate if transformations has to be applied or not * @return the converted content in the new syntax * @throws XWikiException if an exception occurred during the conversion process */ private static String performSyntaxConversion(String content, String currentSyntaxId, Syntax targetSyntax, boolean transform) throws XWikiException { try { XDOM dom = parseContent(currentSyntaxId, content); return performSyntaxConversion(dom, currentSyntaxId, targetSyntax, transform); } catch (Exception e) { throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_UNKNOWN, "Failed to convert document to syntax [" + targetSyntax + "]", e); } } /** * Convert the passed content from the passed syntax to the passed new syntax. * * @param content the XDOM content to convert, the XDOM can be modified during the transformation * @param currentSyntaxId the syntax of the current content to convert * @param targetSyntax the new syntax after the conversion * @param transform indicate if transformations has to be applied or not * @return the converted content in the new syntax * @throws XWikiException if an exception occurred during the conversion process */ private static String performSyntaxConversion(XDOM content, String currentSyntaxId, Syntax targetSyntax, boolean transform) throws XWikiException { try { if (transform) { // Transform XDOM TransformationManager transformations = Utils.getComponent(TransformationManager.class); SyntaxFactory syntaxFactory = Utils.getComponent(SyntaxFactory.class); transformations.performTransformations(content, syntaxFactory.createSyntaxFromIdString(currentSyntaxId)); } // Render XDOM return renderXDOM(content, targetSyntax); } catch (Exception e) { throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_UNKNOWN, "Failed to convert document to syntax [" + targetSyntax + "]", e); } } /** * Render privided XDOM into content of the provided syntax identifier. * * @param content the XDOM content to render * @param targetSyntax the syntax identifier of the rendered content * @return the rendered content * @throws XWikiException if an exception occurred during the rendering process */ private static String renderXDOM(XDOM content, Syntax targetSyntax) throws XWikiException { try { BlockRenderer renderer = Utils.getComponent(BlockRenderer.class, targetSyntax.toIdString()); WikiPrinter printer = new DefaultWikiPrinter(); renderer.render(content, printer); return printer.toString(); } catch (Exception e) { throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_UNKNOWN, "Failed to render document to syntax [" + targetSyntax + "]", e); } } private XDOM parseContent(String content) throws XWikiException { return parseContent(getSyntaxId(), content); } private static XDOM parseContent(String syntaxId, String content) throws XWikiException { try { Parser parser = Utils.getComponent(Parser.class, syntaxId); return parser.parse(new StringReader(content)); } catch (ParseException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_UNKNOWN, "Failed to parse content of syntax [" + syntaxId + "]", e); } } private Syntax getDefaultDocumentSyntax() { // If there's no parser available for the specified syntax default to XWiki 2.0 syntax Syntax syntax = Utils.getComponent(CoreConfiguration.class).getDefaultDocumentSyntax(); try { Utils.getComponent(Parser.class, syntax.toIdString()); } catch (Exception e) { LOG.warn("Failed to find parser for syntax [" + syntax.toIdString() + "]. Defaulting to xwiki/2.0 syntax."); syntax = Syntax.XWIKI_2_0; } return syntax; } private DocumentReference resolveReference(String referenceAsString, DocumentReferenceResolver<String> resolver, DocumentReference defaultReference) { XWikiContext xcontext = getXWikiContext(); XWikiDocument originalCurentDocument = xcontext.getDoc(); try { xcontext.setDoc(new XWikiDocument(defaultReference)); return resolver.resolve(referenceAsString); } finally { xcontext.setDoc(originalCurentDocument); } } /** * Backward-compatibility method to use in order to resolve a class reference passed as a String into a * DocumentReference proper. * * @return the resolved class reference but using this document's wiki if the passed String doesn't specify a wiki, * the "XWiki" space if the passed String doesn't specify a space and this document's page if the passed * String doesn't specify a page. */ protected DocumentReference resolveClassReference(String documentName) { DocumentReference defaultReference = new DocumentReference(getDocumentReference().getWikiReference().getName(), "XWiki", getDocumentReference().getName()); return resolveReference(documentName, this.currentDocumentReferenceResolver, defaultReference); } private XWikiContext getXWikiContext() { return (XWikiContext) this.execution.getContext().getProperty("xwikicontext"); } }
package digitalseraphim.tcgc.items; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemMap; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import digitalseraphim.tcgc.TCGCraft; import digitalseraphim.tcgc.core.logic.Card; public class ItemCard extends ItemMap { //can potentially represent a number of cards public static final String NBT_CARDS_ROOT = "cards"; public static final String NBT_SELECTED = "selected"; public static final String NBT_COLLAPSED = "collapsed"; public static final String NBT_COUNT = "count"; public static final String NBT_CARD_BASE = "card"; public ItemCard(int id) { super(id); } @Override public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player) { if(player.isSneaking()){ toggleCollapsed(itemStack); return itemStack; } return super.onItemRightClick(itemStack, world, player); } @Override public boolean onItemUseFirst(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { if(player.isSneaking()){ toggleCollapsed(itemStack); return true; } return super.onItemUseFirst(itemStack, player, world, x, y, z, side, hitX, hitY, hitZ); } // @Override // public boolean onItemUse(ItemStack par1ItemStack, // EntityPlayer par2EntityPlayer, World par3World, int par4, int par5, // int par6, int par7, float par8, float par9, float par10) { // System.out.println("ItemCard.onItemUse()"); // return super.onItemUse(par1ItemStack, par2EntityPlayer, par3World, par4, par5, // par6, par7, par8, par9, par10); @Override public boolean onDroppedByPlayer(ItemStack item, EntityPlayer player) { System.out.println("ItemCard.onDroppedByPlayer()"); return super.onDroppedByPlayer(item, player); } public static ItemStack createItemStack(Card[] cards){ ItemStack is = new ItemStack(TCGCraft.proxy.cardItem); NBTTagCompound tagCompound = new NBTTagCompound(NBT_CARDS_ROOT); tagCompound.setInteger(NBT_COUNT, cards.length); tagCompound.setInteger(NBT_SELECTED, 0); for(int i = 0; i < cards.length; i++){ tagCompound.setString(NBT_CARD_BASE+i, cards[i].getFullName()); } is.setTagCompound(tagCompound); return is; } public static Card[] cardsFromItemStack(ItemStack is){ NBTTagCompound tagCompound = is.getTagCompound(); int count = tagCompound.getInteger(NBT_COUNT); Card[] cards = new Card[count]; for(int i = 0; i < count; i++){ cards[i] = Card.getAllCards().get(tagCompound.getString(NBT_CARD_BASE+i)); } return cards; } @Override public String getItemDisplayName(ItemStack itemStack) { Card c = getSelectedCard(itemStack); return c.getFullName(); } public static Card getCard(ItemStack is, int i){ NBTTagCompound tag = is.getTagCompound(); String name = tag.getString(NBT_CARD_BASE+i); return Card.getAllCards().get(name); } public static Card getSelectedCard(ItemStack is){ NBTTagCompound tag = is.getTagCompound(); int sel = tag.getInteger(NBT_SELECTED); return getCard(is, sel); } public static int getSelectedCardIndex(ItemStack is){ NBTTagCompound tag = is.getTagCompound(); return tag.getInteger(NBT_SELECTED); } public static int getCardCount(ItemStack is){ NBTTagCompound tag = is.getTagCompound(); return tag.getInteger(NBT_SELECTED); } public static void toggleCollapsed(ItemStack is){ NBTTagCompound tag = is.getTagCompound(); boolean collapsed = tag.getBoolean(NBT_COLLAPSED); tag.setBoolean(NBT_COLLAPSED, !collapsed); } public static void scrollSelected(ItemStack is, int amnt){ NBTTagCompound tag = is.getTagCompound(); int sel = tag.getInteger(NBT_SELECTED); int count = tag.getInteger(NBT_COUNT); sel += amnt; while(sel < 0){ sel += count; } sel = sel % count; tag.setInteger(NBT_SELECTED, sel); } public static ItemStack mergeItemStacks(ItemStack dest, ItemStack src){ if(dest == null){ if(src == null){ return null; } return src; } if(src == null){ return dest; } Card[] dstArr = cardsFromItemStack(dest); Card[] srcArr = cardsFromItemStack(src); Card[] newArray = new Card[dstArr.length + srcArr.length]; System.arraycopy(dstArr, 0, newArray, 0, dstArr.length); System.arraycopy(srcArr, 0, newArray, dstArr.length, srcArr.length); return createItemStack(newArray); } }
package UI; import inputs.RobotInput; import javafx.animation.AnimationTimer; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.canvas.Canvas; import javafx.scene.control.Label; import javafx.scene.control.TabPane; import javafx.scene.control.TextArea; import javafx.scene.layout.Pane; import robot.Robot; import simulator.Simulator; import utilities.Point; import utilities.Position; import java.math.RoundingMode; import java.net.URL; import java.text.DecimalFormat; import java.util.ResourceBundle; public class SimulatorController implements Initializable { // TODO: Should this be configurable? in feet private static double WHEEL_RADIUS = 0.25; @FXML private Pane displayPane; @FXML private TabPane controlPane; // System state variables @FXML private Pane systemStatePane; @FXML private Label velocityY; @FXML private Label velocityX; @FXML private Label direction; @FXML private Label position; @FXML private Label wheels; @FXML private Label rotationRate; // TODO: Should we move these? @FXML private Canvas gridCanvas; @FXML private Canvas robotCanvas; @FXML private Canvas pathCanvas; @FXML private TextArea outputTextArea; private long previousTime = 0; // controller for the simulation display private DisplayPaneController displayController; private AnimationTimer timer; // Location of the robot in the global reference frame private Position robotPosition; @Override public void initialize(URL location, ResourceBundle resources) { // Background test = new Background(new BackgroundFill(Color.BURLYWOOD, CornerRadii.EMPTY, Insets.EMPTY)); //displayPane.setBackground(test); // systemStatePane.setBackground(test); // add in the individual controllers displayController = new DisplayPaneController(displayPane, gridCanvas, robotCanvas, pathCanvas); displayController.initializePane(); // add in the tab controller TabController tabControl = new TabController(controlPane, this); tabControl.init(); // force the text area to auto scroll outputTextArea.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { outputTextArea.setScrollTop(Double.MAX_VALUE); } }); // robot always starts in the middle robotPosition = new Position(new Point(7.5, 15), 0.0); } /** * TODO: Should we return error values? */ public void startSimulator(RobotInput input) { // clear the robot path displayController.getPathCanvas().restartCanvas(); // first get the current robot position and orientation Position startPos = displayController.getRobotCanvas().convertLocationToFeet(); final Robot robot = new Robot(WHEEL_RADIUS); robot.setLocation(robotPosition.getPosition()); robot.setAngle(robotPosition.getAngle()); robot.setVelocity(new Point(0, 0)); // update the robot stats updateSystemState(robot); // start the simulator printText("Starting simulation"); System.out.println("Starting Simulator"); final Simulator sim = new Simulator(input, robot); previousTime = 0; // final long previousTime = 0; timer = new AnimationTimer() { @Override public void handle(long now) { // Calculate the delta between this frame and the last double deltaTime = 0; if (previousTime != 0) { deltaTime = now - previousTime; // convert to seconds deltaTime = deltaTime / 1000000000.0; } previousTime = now; // Debug code, need to add logic to only update every x frames // printText("Now: " + now); // TODO: Need to convert the Y position into the canvas coordinates // update the robot position sim.calculateNewPosition(deltaTime); // update the reference position robotPosition = new Position(sim.getRobot().getLocation(), robot.getAngle()); // update the robot data updateSystemState(sim.getRobot()); // update the position based on the global reference frame // displayController.getRobotCanvas().setRobotPosition(sim.getRobot()); displayController.getRobotCanvas().redrawRobot(sim.getRobot()); } }; timer.start(); } /** * TODO: Should we return error values? */ public void stopSimulator() { printText("Stopping Simulator"); // zero out velocities on the system display stopSystemState(); // Kill the timer if (timer != null) { timer.stop(); // clean out this bad boy timer = null; } } /** * Prints out text on the output pane. * * @param text string to print */ public void printText(String text) { outputTextArea.setText(outputTextArea.getText() + text + "\n"); outputTextArea.appendText(""); } private void updateSystemState(Robot robot) { // update the velocity components DecimalFormat df = new DecimalFormat(" df.setRoundingMode(RoundingMode.HALF_UP); velocityY.setText("Velocity Y: " + df.format(robot.getVelocity().getY())); velocityX.setText("Velocity X: " + df.format(robot.getVelocity().getX())); rotationRate.setText("Rotation Rate: " + df.format(robot.getRotationRate())); direction.setText("Direction: " + df.format(robot.getAngle())); position.setText("Position: (" + df.format(robot.getLocation().getX()) + ", " + df.format(robot.getLocation().getY()) + ")"); double[] wheelRates = robot.getWheelRates(); wheels.setText("Wheel One: " + df.format(wheelRates[0]) + ", Wheel Two: " + df.format(wheelRates[1]) + ", Wheel Three: " + df.format(wheelRates[2]) + ", Wheel Four: " + df.format(wheelRates[3])); } private void stopSystemState() { velocityY.setText("Velocity Y: 0.0"); velocityX.setText("Velocity X: 0.0"); rotationRate.setText("Rotation Rate: 0.0"); wheels.setText("Wheel One: " + 0.0 + ", Wheel Two: " + 0.0 + ", Wheel Three: " + 0.0 + ", Wheel Four: " + 0.0); } public Position getRobotPosition() { return robotPosition; } }
package ch.openech.xml.write; import static ch.openech.dm.XmlConstants.ADDRESS; import static ch.openech.dm.XmlConstants.ALIAS_NAME; import static ch.openech.dm.XmlConstants.ALLIANCE_PARTNERSHIP_NAME; import static ch.openech.dm.XmlConstants.ANY_PERSON; import static ch.openech.dm.XmlConstants.ARRIVAL_DATE; import static ch.openech.dm.XmlConstants.CALL_NAME; import static ch.openech.dm.XmlConstants.CANCELATION_REASON; import static ch.openech.dm.XmlConstants.CANTON; import static ch.openech.dm.XmlConstants.COMES_FROM; import static ch.openech.dm.XmlConstants.CONTACT; import static ch.openech.dm.XmlConstants.CONTACT_ADDRESS; import static ch.openech.dm.XmlConstants.CONTACT_VALID_TILL; import static ch.openech.dm.XmlConstants.COREDATA; import static ch.openech.dm.XmlConstants.COUNTRY; import static ch.openech.dm.XmlConstants.DATE_OF_DEATH; import static ch.openech.dm.XmlConstants.DATE_OF_MARITAL_STATUS; import static ch.openech.dm.XmlConstants.DATE_OF_SEPARATION; import static ch.openech.dm.XmlConstants.DEPARTURE_DATE; import static ch.openech.dm.XmlConstants.DWELLING_ADDRESS; import static ch.openech.dm.XmlConstants.FOREIGNER; import static ch.openech.dm.XmlConstants.FOREIGN_BIRTH_TOWN; import static ch.openech.dm.XmlConstants.FOREIGN_COUNTRY; import static ch.openech.dm.XmlConstants.GOES_TO; import static ch.openech.dm.XmlConstants.HAS_MAIN_RESIDENCE; import static ch.openech.dm.XmlConstants.HAS_OTHER_RESIDENCE; import static ch.openech.dm.XmlConstants.HAS_SECONDARY_RESIDENCE; import static ch.openech.dm.XmlConstants.HOUSEHOLD_I_D; import static ch.openech.dm.XmlConstants.LANGUAGE_OF_CORRESPONDANCE; import static ch.openech.dm.XmlConstants.MAIL_ADDRESS; import static ch.openech.dm.XmlConstants.MAIN_RESIDENCE; import static ch.openech.dm.XmlConstants.MARITAL_DATA; import static ch.openech.dm.XmlConstants.MARITAL_STATUS; import static ch.openech.dm.XmlConstants.MOVING_DATE; import static ch.openech.dm.XmlConstants.MUNICIPALITY; import static ch.openech.dm.XmlConstants.NATIONALITY; import static ch.openech.dm.XmlConstants.NATIONALITY_STATUS; import static ch.openech.dm.XmlConstants.ORIGINAL_NAME; import static ch.openech.dm.XmlConstants.ORIGIN_NAME; import static ch.openech.dm.XmlConstants.OTHER_NAME; import static ch.openech.dm.XmlConstants.PERSON; import static ch.openech.dm.XmlConstants.PLACE_OF_BIRTH; import static ch.openech.dm.XmlConstants.PLACE_OF_ORIGIN; import static ch.openech.dm.XmlConstants.RELIGION; import static ch.openech.dm.XmlConstants.REPORTING_MUNICIPALITY; import static ch.openech.dm.XmlConstants.SECONDARY_RESIDENCE; import static ch.openech.dm.XmlConstants.SECONDARY_RESIDENCE_INFORMATION; import static ch.openech.dm.XmlConstants.SEPARATION; import static ch.openech.dm.XmlConstants.SEPARATION_TILL; import static ch.openech.dm.XmlConstants.SWISS; import static ch.openech.dm.XmlConstants.SWISS_TOWN; import static ch.openech.dm.XmlConstants.TOWN; import static ch.openech.dm.XmlConstants.TYPE_OF_HOUSEHOLD; import static ch.openech.dm.XmlConstants.UNKNOWN; import static ch.openech.dm.XmlConstants.WITHOUT_E_G_I_D; import static ch.openech.dm.XmlConstants._E_G_I_D; import static ch.openech.dm.XmlConstants._E_W_I_D; import java.util.List; import java.util.logging.Logger; import ch.openech.dm.common.CountryIdentification; import ch.openech.dm.common.DwellingAddress; import ch.openech.dm.common.MunicipalityIdentification; import ch.openech.dm.common.Place; import ch.openech.dm.person.Foreign; import ch.openech.dm.person.Nationality; import ch.openech.dm.person.Person; import ch.openech.dm.person.PlaceOfOrigin; import ch.openech.mj.util.StringUtils; public class WriterEch0011 { private static final Logger logger = Logger.getLogger(WriterEch0011.class.getName()); private final EchSchema context; public final String URI; public final WriterEch0007 ech7; public final WriterEch0008 ech8; public final WriterEch0010 ech10; public final WriterEch0044 ech44; public WriterEch0011(EchSchema context) { this.context = context; URI = context.getNamespaceURI(11); ech7 = new WriterEch0007(context); ech8 = new WriterEch0008(context); ech10 = new WriterEch0010(context); ech44 = new WriterEch0044(context); } public void country(WriterElement parent, String tagName, CountryIdentification countryIdentification) throws Exception { if (countryIdentification == null || countryIdentification.isEmpty()) return; WriterElement writer = parent.create(URI, tagName); writer.values(countryIdentification); } public void coreData(WriterElement parent, Person person) throws Exception { WriterElement coredata = parent.create(URI, COREDATA); coredata.values(person, ORIGINAL_NAME, ALLIANCE_PARTNERSHIP_NAME, ALIAS_NAME, OTHER_NAME, CALL_NAME); placeOfBirth(coredata, person); coredata.values(person, DATE_OF_DEATH); maritalData(coredata, person); nationality(coredata, person.nationality); contact(coredata, URI, person); coredata.values(person, LANGUAGE_OF_CORRESPONDANCE, RELIGION); } public void placeOfBirth(WriterElement parent, Person values) throws Exception { placeOfBirth(parent, values, URI); } public void placeOfBirth(WriterElement parent, Person values, String uri) throws Exception { Place placeOfBirth = values.placeOfBirth; WriterElement element =parent.create(uri, PLACE_OF_BIRTH); if (placeOfBirth == null || placeOfBirth.isUnknown()) { unknown(element); } else if (placeOfBirth.isSwiss()) { WriterElement swissTown =element.create(uri, SWISS_TOWN); swissTown.text(COUNTRY, "CH"); ech7.municipality(swissTown, MUNICIPALITY, placeOfBirth.municipalityIdentification); } else if (placeOfBirth.isForeign()) { WriterElement foreignCountry = element.create(uri, FOREIGN_COUNTRY); ech8.country(foreignCountry, COUNTRY, placeOfBirth.countryIdentification); foreignCountry.text(FOREIGN_BIRTH_TOWN, placeOfBirth.foreignTown); } } public void maritalData(WriterElement parent, Person person) throws Exception { maritalData(parent, MARITAL_DATA, person); } public void maritalData(WriterElement parent, String tagName, Person person) throws Exception { WriterElement maritalData = parent.create(URI, tagName); maritalData.values(person.maritalStatus, MARITAL_STATUS, DATE_OF_MARITAL_STATUS); if (context.separationTillAvailable()) { maritalData.values(person.separation, SEPARATION, DATE_OF_SEPARATION, SEPARATION_TILL); } else { maritalData.values(person.separation, SEPARATION, DATE_OF_SEPARATION); } maritalData.values(person, CANCELATION_REASON); } public void nationality(WriterElement parent, Nationality nationality) throws Exception { WriterElement element = parent.create(URI, NATIONALITY); element.text(NATIONALITY_STATUS, nationality.nationalityStatus); ech8.country(element, COUNTRY, nationality.nationalityCountry); } public void person(WriterElement parent, Person person) throws Exception { WriterElement element = parent.create(URI, PERSON); ech44.personIdentification(element, person.personIdentification); coreData(element, person); } public void anyPerson(WriterElement parent, Person person) throws Exception { WriterElement anyPerson = parent.create(URI, ANY_PERSON); List<PlaceOfOrigin> origins = person.placeOfOrigin; if (origins != null && !origins.isEmpty()) { swiss(anyPerson, origins); if (person.foreign != null && !person.foreign.isEmpty()) { logger.warning("Person: " +person + " has swiss and foreign. Skipping foreign"); return; } } if (person.foreign != null && !person.foreign.isEmpty()) { foreigner(anyPerson, person.foreign); } } private void swiss(WriterElement anyPerson, List<PlaceOfOrigin> origins) throws Exception { WriterElement swiss = anyPerson.create(URI, SWISS); for (PlaceOfOrigin origin : origins) { placeOfOrigin(swiss, origin); } } private void placeOfOrigin(WriterElement parent, PlaceOfOrigin origin) throws Exception { placeOfOrigin(parent, PLACE_OF_ORIGIN, origin); } public void placeOfOrigin(WriterElement parent, String tagName, PlaceOfOrigin origin) throws Exception { WriterElement placeOfOrigin = parent.create(URI, tagName); placeOfOrigin.values(origin, ORIGIN_NAME, CANTON); // placeOfOrigin.values(origin, ORIGIN_NAME); // placeOfOrigin.text(CANTON, origin.canton.value); } private void foreigner(WriterElement anyPerson, Foreign foreignValues) throws Exception { WriterElement foreign = anyPerson.create(URI, FOREIGNER); foreign.values(foreignValues); } // den Contact"Type" gibt es es als anonymen Type in verschiedenen // Schemas. In Java wird immer dieser aufgerufen (z.B. von ech20) public void contact(WriterElement parent, String uri, Person person) throws Exception { contact(parent, uri, person, false); } public void contact(WriterElement parent, String uri, Person person, boolean withValidTill) throws Exception { if (person.contactPerson.person == null && (person.contactPerson.address == null || person.contactPerson.address.isEmpty())) return; WriterElement contactElement = parent.create(uri, CONTACT); // eCH-0011:partnerIdOrganisationType // eCH-0044:personIdentificationPartnerType // eCH-0044:personIdentificationType if (person.contactPerson.person != null) ech44.personIdentification(contactElement, person.contactPerson.person); ech10.address(contactElement, CONTACT_ADDRESS, person.contactPerson.address); if (withValidTill && person.contactPerson.validTill != null) contactElement.text(CONTACT_VALID_TILL, person.contactPerson.validTill); } public void residence(WriterElement message, Person values) throws Exception { switch (values.typeOfResidence) { case hasMainResidence: mainResidence(message, HAS_MAIN_RESIDENCE, values); break; case hasSecondaryResidence: secondaryResidence(message, HAS_SECONDARY_RESIDENCE, values); break; case hasOtherResidence: otherResidence(message, HAS_OTHER_RESIDENCE, values); break; default: break; } } public void mainResidence(WriterElement parent, String tagName, Person values) throws Exception { // es kommen n Aufenthaltsorte (SecondaryResidence) dazu WriterElement element = parent.create(URI, tagName); WriterElement informationElement = element.create(URI, MAIN_RESIDENCE); ech7.municipality(informationElement, REPORTING_MUNICIPALITY, values.residence.reportingMunicipality); commonResidenceInformation(informationElement, values); if (values.residence.secondary != null) { for (MunicipalityIdentification residence : values.residence.secondary) { ech7.municipality(element, SECONDARY_RESIDENCE, residence); } } } public void secondaryResidence(WriterElement parent, String tagName, Person values) throws Exception { WriterElement element = parent.create(URI, tagName); ech7.municipality(element, MAIN_RESIDENCE, values.residence.reportingMunicipality); WriterElement informationElement = element.create(URI, SECONDARY_RESIDENCE); if (values.residence.secondary != null && !values.residence.secondary.isEmpty()) { ech7.municipality(informationElement, REPORTING_MUNICIPALITY, values.residence.secondary.get(0)); } commonResidenceInformation(informationElement, values); } public void otherResidence(WriterElement parent, String tagName, Person values) throws Exception { WriterElement element = parent.create(URI, tagName); WriterElement informationElement = element.create(URI, SECONDARY_RESIDENCE_INFORMATION); // "Information" ist eine Abweichung von der e20 - Version if (values.residence.secondary != null && !values.residence.secondary.isEmpty()) { ech7.municipality(informationElement, REPORTING_MUNICIPALITY, values.residence.secondary.get(0)); } commonResidenceInformation(informationElement, values); } private void commonResidenceInformation(WriterElement element, Person values) throws Exception { element.values(values, ARRIVAL_DATE); destination(element, COMES_FROM, values.comesFrom, true); dwellingAddress(element, values.dwellingAddress); element.values(values, DEPARTURE_DATE); destination(element, GOES_TO, values.goesTo, false); } public void destination(WriterElement parent, String tagName, Place place, boolean required) throws Exception { if (place == null || (!required && place.isUnknown())) return; WriterElement placeElement = parent.create(URI, tagName); if (place.isUnknown()) unknown(placeElement); else if (place.isSwiss()) { ech7.municipality(placeElement, SWISS_TOWN, place.municipalityIdentification); } else if (place.isForeign()) { WriterElement foreignCountry = placeElement.create(URI, FOREIGN_COUNTRY); ech8.country(foreignCountry, COUNTRY, place.countryIdentification); foreignCountry.text(TOWN, place.foreignTown); } if (place.mailAddress != null && !place.mailAddress.isEmpty()) ech10.addressInformation(placeElement, MAIL_ADDRESS, place.mailAddress); } public void dwellingAddress(WriterElement parent, DwellingAddress dwelingAddress) throws Exception { dwellingAddress(parent, URI, DWELLING_ADDRESS, dwelingAddress); } public void dwellingAddress(WriterElement parent, String uri, String tagName, DwellingAddress dwelingAddress) throws Exception { if (dwelingAddress == null) return; WriterElement element = parent.create(uri, tagName); if (!StringUtils.isBlank(dwelingAddress.EGID)) { element.values(dwelingAddress, _E_G_I_D, _E_W_I_D, HOUSEHOLD_I_D); } else { WriterElement withoutEGID = element.create(URI, WITHOUT_E_G_I_D); withoutEGID.text(HOUSEHOLD_I_D, dwelingAddress.householdID); } if (dwelingAddress.mailAddress != null && !dwelingAddress.mailAddress.isEmpty()) ech10.swissAddressInformation(element, ADDRESS, dwelingAddress.mailAddress); element.values(dwelingAddress, TYPE_OF_HOUSEHOLD, MOVING_DATE); } private static void unknown(WriterElement parent) throws Exception { parent.text(UNKNOWN, "0"); } }
package obvious.ivtk.view; import java.util.Map; import javax.swing.JComponent; import obvious.data.Network; import obvious.data.Table; import obvious.data.util.Predicate; import obvious.ivtk.viz.IvtkVisualizationFactory; import obvious.view.JView; import obvious.view.event.ViewListener; import obvious.viz.Visualization; /** * An implementation of Obvious view interface for ivtk. * @author Hemery * */ public class IvtkObviousView extends JView { /** * ivtk visualization panel. */ private infovis.panel.VisualizationPanel panel; /** * Visualization backing this view. */ private Visualization backingVis; /** * Constructor. * @param vis an obvious visualization * @param predicate an obvious predicate. * @param tech visualization technique name * @param param parameters for the visualization */ public IvtkObviousView(Visualization vis, Predicate predicate, String tech, Map <String, Object> param) { if (vis.getUnderlyingImpl(infovis.Visualization.class) != null) { this.backingVis = vis; } else { IvtkVisualizationFactory factory = new IvtkVisualizationFactory(); if (vis.getData() instanceof Table) { this.backingVis = factory.createVisualization( (Table) vis.getData(), predicate, tech, param); } else if (vis.getData() instanceof Network) { this.backingVis = factory.createVisualization( (Network) vis.getData(), predicate, tech, param); } } panel = new infovis.panel.VisualizationPanel( (infovis.Visualization) backingVis.getUnderlyingImpl( infovis.Visualization.class)); } /** * Constructor. * @param vis an obvious visualization * @param predicate an obvious predicate. */ public IvtkObviousView(Visualization vis, Predicate predicate) { this(vis, predicate, null, null); } @Override public JComponent getViewJComponent() { return panel; } /** * Gets the Visualization backing this view. * @return the Visualization backing this view */ public Visualization getVisualization() { return backingVis; } @Override public void addListener(ViewListener lstnr) { this.getViewListeners().add(lstnr); } @Override public boolean removeListener(ViewListener listener) { return this.getViewListeners().remove(listener); } }
package cx2x.translator.transformation.loop; import cx2x.translator.common.ClawConstant; import cx2x.translator.language.base.ClawLanguage; import cx2x.translator.language.common.ClawConstraint; import cx2x.translator.transformation.ClawTransformation; import cx2x.xcodeml.exception.IllegalTransformationException; import cx2x.xcodeml.helper.XnodeUtil; import cx2x.xcodeml.transformation.Transformation; import cx2x.xcodeml.transformation.Transformer; import cx2x.xcodeml.xnode.Xcode; import cx2x.xcodeml.xnode.XcodeProgram; import cx2x.xcodeml.xnode.Xnode; import java.util.Arrays; import java.util.Collections; /** * A LoopFusion transformation is a dependent transformation. If two LoopFusion * transformation units shared the same fusion group and the same loop iteration * information, they can be merge together. * The transformation consists of merging the body of the second do statement to * the end of the first do statement. * * @author clementval */ public class LoopFusion extends ClawTransformation { // Contains the value of the group option private String _groupClauseLabel = ClawConstant.EMPTY_STRING; // The loop statement involved in the Transformation private Xnode[] _doStmts; private static final String[] prevTodelete = { "acc loop", "omp do" }; private static final String[] nextToDelete = { "omp end do" }; /** * Constructs a new LoopFusion triggered from a specific pragma. * * @param directive The directive that triggered the loop fusion * transformation. */ public LoopFusion(ClawLanguage directive) { super(directive); if(_claw.hasGroupClause()) { _groupClauseLabel = directive.getGroupValue(); } _doStmts = new Xnode[0]; } /** * LoopFusion ctor without pragma. Create a LoopFusion dynamically at runtime. * * @param loop The do statement to be merge by the loop fusion. * @param ghostDirective The generated directive that will be used for the * loop-fusion transformation. */ public LoopFusion(Xnode loop, ClawLanguage ghostDirective) { super(ghostDirective); if(_claw.hasCollapseClause()) { _doStmts = new Xnode[_claw.getCollapseValue()]; _doStmts[0] = loop; for(int i = 1; i < _claw.getCollapseValue(); ++i) { _doStmts[i] = _doStmts[i - 1].body(). matchDirectDescendant(Xcode.FDOSTATEMENT); } } else { _doStmts = new Xnode[]{loop}; } if(_claw.hasGroupClause()) { _groupClauseLabel = ghostDirective.getGroupValue(); } if(_claw.getPragma() != null) { setStartLine(ghostDirective.getPragma().lineNo()); } } /** * Loop fusion analysis: * - Without collapse clause: check whether the pragma statement is followed * by a do statement. * - With collapse clause: Find the n do statements following the pragma. * * @param xcodeml The XcodeML on which the transformations are applied. * @param transformer The transformer used to applied the transformations. * @return True if a do statement is found. False otherwise. */ @Override public boolean analyze(XcodeProgram xcodeml, Transformer transformer) { // With collapse clause if(_claw.hasCollapseClause() && _claw.getCollapseValue() > 0) { _doStmts = new Xnode[_claw.getCollapseValue()]; for(int i = 0; i < _claw.getCollapseValue(); ++i) { if(i == 0) { // Find the outer do statement from pragma _doStmts[0] = _claw.getPragma().matchSibling(Xcode.FDOSTATEMENT); } else { // Find the next i loops _doStmts[i] = _doStmts[i - 1].body(). matchDirectDescendant(Xcode.FDOSTATEMENT); } if(_doStmts[i] == null) { xcodeml.addError("Do statement missing at depth " + i + " after directive.", _claw.getPragma().lineNo()); return false; } } return true; } else { // Without collapse clause, locate the do statement after the pragma Xnode doStmt = _claw.getPragma().matchSibling(Xcode.FDOSTATEMENT); if(doStmt == null) { xcodeml.addError("Do statement missing after directive.", _claw.getPragma().lineNo()); return false; } _doStmts = new Xnode[]{doStmt}; return true; } } @Override public void transform(XcodeProgram xcodeml, Transformer transformer, Transformation transformation) throws IllegalTransformationException { if(!(transformation instanceof LoopFusion)) { throw new IllegalTransformationException("Incompatible transformation", _claw.getPragma().lineNo()); } LoopFusion other = (LoopFusion) transformation; // Apply different transformation if the collapse clause is used if(_claw != null && _claw.hasCollapseClause() && _claw.getCollapseValue() > 0) { // Merge the most inner loop with the most inner loop of the other fusion // unit int innerDoStmtIdx = _claw.getCollapseValue() - 1; if(_doStmts[innerDoStmtIdx] == null || other.getDoStmtAtIndex(innerDoStmtIdx) == null) { throw new IllegalTransformationException( "Cannot apply transformation, one or both do stmt are invalid.", _claw.getPragma().lineNo() ); } XnodeUtil.appendBody(_doStmts[innerDoStmtIdx].body(), other.getDoStmtAtIndex(innerDoStmtIdx).body()); } else { // Without collapse clause, only first do statements are considered. XnodeUtil.appendBody(_doStmts[0].body(), other.getDoStmtAtIndex(0).body()); } other.finalizeTransformation(); XnodeUtil.safeDelete(_claw.getPragma()); // Delete the pragma statement } /** * Call by the transform method of the master loop fusion unit on the slave * loop fusion unit to finalize the transformation. Pragma and loop of the * slave loop fusion unit are deleted. */ private void finalizeTransformation() { // Delete the pragma of the transformed loop XnodeUtil.safeDelete(_claw.getPragma()); // Delete any acc loop / omp do pragma before/after the do statements. XnodeUtil.cleanPragmas(_doStmts[0], prevTodelete, nextToDelete); // Delete the do statement that was merged with the main one XnodeUtil.safeDelete(_doStmts[0]); // Set transformation as done. this.transformed(); } /** * Check whether the loop fusion unit can be merged with the given loop fusion * unit. To be able to be transformed together, the loop fusion units must * share the same parent block, the same iteration range, the same group * option and both units must be not transformed. * * @param transformation The other loop fusion unit to be merge with this one. * @return True if the two loop fusion unit can be merge together. */ @Override public boolean canBeTransformedWith(XcodeProgram xcodeml, Transformation transformation) { if(!(transformation instanceof LoopFusion)) { return false; } LoopFusion other = (LoopFusion) transformation; // No loop is transformed already if(this.isTransformed() || other.isTransformed()) { return false; } // Loop must share the same group option if(!hasSameGroupClause(other)) { return false; } ClawConstraint currentConstraint = ClawConstraint.DIRECT; if(_claw.hasConstraintClause() && other.getLanguageInfo().hasConstraintClause()) { // Check the constraint clause. Must be identical if set. if(_claw.getConstraintClauseValue() != other.getLanguageInfo().getConstraintClauseValue()) { return false; } currentConstraint = _claw.getConstraintClauseValue(); } else { if(_claw.hasConstraintClause() || other.getLanguageInfo().hasConstraintClause()) { // Constraint are not consistent return false; } } // Following constraint are used only in default mode. If constraint clause // is set to none, there are note checked. if(currentConstraint == ClawConstraint.DIRECT) { // Only pragma statement can be between the two loops. if(!XnodeUtil.isDirectSibling(_doStmts[0], other.getDoStmtAtIndex(0), Collections.singletonList(Xcode.FPRAGMASTATEMENT))) { return false; } } else { xcodeml.addWarning("Unconstrained loop-fusion generated", Arrays.asList(_claw.getPragma().lineNo(), other.getLanguageInfo().getPragma().lineNo())); } // Loops can only be merged if they are at the same level if(!XnodeUtil.hasSameParentBlock(_doStmts[0], other.getDoStmtAtIndex(0))) { return false; } if(_claw.hasCollapseClause() && _claw.getCollapseValue() > 0) { for(int i = 0; i < _claw.getCollapseValue(); ++i) { if(!XnodeUtil.hasSameIndexRange(_doStmts[i], other.getDoStmtAtIndex(i))) { return false; } } return true; } else { // Loop must share the same iteration range return XnodeUtil.hasSameIndexRange(_doStmts[0], other.getDoStmtAtIndex(0)); } } /** * Return the do statement associated with this loop fusion unit at given * depth. * * @param depth Integer value representing the depth of the loop from the * pragma statement. * @return A do statement. */ private Xnode getDoStmtAtIndex(int depth) { if(_claw != null && _claw.hasCollapseClause() && depth < _claw.getCollapseValue()) { return _doStmts[depth]; } return _doStmts[0]; } /** * Get the group option associated with this loop fusion unit. * * @return Group option value. */ private String getGroupClauseLabel() { return _groupClauseLabel; } /** * Check whether the given loop fusion unit share the same group fusion option * with this loop fusion unit. * * @param otherLoopUnit The other loop fusion unit to be check with this one. * @return True if the two loop fusion units share the same group fusion * option. */ private boolean hasSameGroupClause(LoopFusion otherLoopUnit) { return (otherLoopUnit.getGroupClauseLabel() == null ? getGroupClauseLabel() == null : otherLoopUnit.getGroupClauseLabel().equals(getGroupClauseLabel())); } }
package com.intellij.ui.mac.foundation; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.SystemInfo; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; public class NSDefaults { private static final Logger LOG = Logger.getInstance(NSDefaults.class); // NOTE: skip call of Foundation.invoke(myDefaults, "synchronize") (when read settings) // It waits for any pending asynchronous updates to the defaults database and returns; this method is unnecessary and shouldn't be used. public static final String ourTouchBarDomain = "com.apple.touchbar.agent"; public static final String ourTouchBarNode = "PresentationModePerApp"; public static final String ourTouchBarShowFnValue = "functionKeys"; private static class Path { private final @NotNull ArrayList<Node> myPath = new ArrayList<Node>(); @Override public String toString() { String res = ""; for (Node pn: myPath) { if (!res.isEmpty()) res += " | "; res += pn.toString(); } return res; } String readStringVal(@NotNull String key) { return readStringVal(key, false); } String readStringVal(@NotNull String key, boolean doSyncronize) { if (myPath.isEmpty()) return null; final Foundation.NSAutoreleasePool pool = new Foundation.NSAutoreleasePool(); try { final ID defaults = Foundation.invoke("NSUserDefaults", "standardUserDefaults"); if (defaults == null || defaults.equals(ID.NIL)) return null; if (doSyncronize) { // NOTE: AppleDoc proposes to skip call of Foundation.invoke(myDefaults, "synchronize") - "this method is unnecessary and shouldn't be used." Foundation.invoke(defaults, "synchronize"); } _readPath(defaults); final Node tail = myPath.get(myPath.size() - 1); if (!tail.isValid()) return null; final ID valObj = Foundation.invoke(tail.cachedNodeObj, "objectForKey:", Foundation.nsString(key)); if (valObj == null || valObj.equals(ID.NIL)) return null; return Foundation.toStringViaUTF8(valObj); } finally { pool.drain(); _resetPathCache(); } } void writeStringValue(@NotNull String key, String val) { if (myPath.isEmpty()) return; final Foundation.NSAutoreleasePool pool = new Foundation.NSAutoreleasePool(); try { final ID defaults = Foundation.invoke("NSUserDefaults", "standardUserDefaults"); if (defaults == null || defaults.equals(ID.NIL)) return; _readPath(defaults); int pos = myPath.size() - 1; Node child = myPath.get(pos if (!child.isValid()) { if (val == null) // nothing to erase return; } child.writeStringValue(key, val); while (pos >= 0) { final Node parent = myPath.get(pos final ID mnode = Foundation.invoke(parent.cachedNodeObj, "mutableCopy"); Foundation.invoke(mnode, "setObject:forKey:", child.cachedNodeObj, Foundation.nsString(child.myNodeName)); parent.cachedNodeObj = mnode; child = parent; } final String topWriteSelector = child.isDomain() ? "setPersistentDomain:forName:" : "setObject:forKey:"; Foundation.invoke(defaults, topWriteSelector, child.cachedNodeObj, Foundation.nsString(child.myNodeName)); } finally { pool.drain(); _resetPathCache(); } } int lastValidPos() { if (myPath.isEmpty()) return -1; final Foundation.NSAutoreleasePool pool = new Foundation.NSAutoreleasePool(); try { final ID defaults = Foundation.invoke("NSUserDefaults", "standardUserDefaults"); if (defaults == null || defaults.equals(ID.NIL)) return -1; _readPath(defaults); for (int pos = 0; pos < myPath.size(); ++pos) { final Node pn = myPath.get(pos); if (!pn.isValid()) return pos - 1; } return myPath.size() - 1; } finally { pool.drain(); _resetPathCache(); } } static @NotNull Path createDomainPath(@NotNull String domain, @NotNull String[] nodes) { final Path result = new Path(); result.myPath.add(new Node("persistentDomainForName:", domain)); for (String nodeName: nodes) result.myPath.add(new Node("objectForKey:", nodeName)); return result; } static @NotNull Path createDomainPath(@NotNull String domain, @NotNull String nodeName) { final Path result = new Path(); result.myPath.add(new Node("persistentDomainForName:", domain)); result.myPath.add(new Node("objectForKey:", nodeName)); return result; } private static class Node { private final @NotNull String mySelector; private final @NotNull String myNodeName; private @NotNull ID cachedNodeObj = ID.NIL; Node(@NotNull String selector, @NotNull String nodeName) { mySelector = selector; myNodeName = nodeName; } @Override public String toString() { return String.format("sel='%s' nodeName='%s'",mySelector, myNodeName); } boolean isValid() { return !cachedNodeObj.equals(ID.NIL); } boolean isDomain() { return mySelector.equals("persistentDomainForName:"); } void readNode(ID parent) { cachedNodeObj = ID.NIL; if (parent == null || parent.equals(ID.NIL)) return; final ID nodeObj = Foundation.invoke(parent, mySelector, Foundation.nsString(myNodeName)); if (nodeObj == null || nodeObj.equals(ID.NIL)) return; cachedNodeObj = nodeObj; } private static ID _createDictionary() { return Foundation.invoke("NSMutableDictionary", "new"); } void writeStringValue(@NotNull String key, String val) { final ID mnode; if (!isValid()) { if (val == null) // nothing to erase return; mnode = _createDictionary(); } else mnode = Foundation.invoke(cachedNodeObj, "mutableCopy"); if (mnode == null || mnode.equals(ID.NIL)) return; if (val != null) Foundation.invoke(mnode, "setObject:forKey:", Foundation.nsString(val), Foundation.nsString(key)); else Foundation.invoke(mnode, "removeObjectForKey:", Foundation.nsString(key)); cachedNodeObj = mnode; } } private void _readPath(ID parent) { if (myPath.isEmpty()) return; for (Node pn: myPath) { pn.readNode(parent); if (!pn.isValid()) return; parent = pn.cachedNodeObj; } } private void _resetPathCache() { for (Node pn: myPath) pn.cachedNodeObj = ID.NIL; } } public static boolean isShowFnKeysEnabled(String appId) { final Path path = Path.createDomainPath(ourTouchBarDomain, ourTouchBarNode); final String sval = path.readStringVal(appId); return sval != null && sval.equals(ourTouchBarShowFnValue); } /** * @return True when value has been changed */ public static boolean setShowFnKeysEnabled(String appId, boolean val) { return setShowFnKeysEnabled(appId, val, false); } public static boolean setShowFnKeysEnabled(String appId, boolean val, boolean performExtraDebugChecks) { final Path path = Path.createDomainPath(ourTouchBarDomain, ourTouchBarNode); String sval = path.readStringVal(appId); final boolean settingEnabled = sval != null && sval.equals(ourTouchBarShowFnValue); final String initDesc = "appId='" + appId + "', value (requested be set) ='" + val + "', initial path (tail) value = '" + sval + "', path='" + path.toString() + "'"; if (val == settingEnabled) { if (performExtraDebugChecks) LOG.error("nothing to change: " + initDesc); return false; } path.writeStringValue(appId, val ? ourTouchBarShowFnValue : null); if (performExtraDebugChecks) { // just for embedded debug: make call of Foundation.invoke(myDefaults, "synchronize") - It waits for any pending asynchronous updates to the defaults database and returns; this method is unnecessary and shouldn't be used. sval = path.readStringVal(appId, true); final boolean isFNEnabled = sval != null && sval.equals(ourTouchBarShowFnValue); if (val != isFNEnabled) LOG.error("can't write value '" + val + "' (was written just now, but read '" + sval + "'): " + initDesc); else LOG.error("value '" + val + "' was written from second attempt: " + initDesc); } return true; } public static String readStringVal(String domain, String key) { final Path result = new Path(); result.myPath.add(new Path.Node("persistentDomainForName:", domain)); return result.readStringVal(key); } public static boolean isDomainExists(String domain) { final Path result = new Path(); result.myPath.add(new Path.Node("persistentDomainForName:", domain)); return result.lastValidPos() >= 0; } public static boolean isDarkMenuBar() { assert SystemInfo.isMac; final Foundation.NSAutoreleasePool pool = new Foundation.NSAutoreleasePool(); try { final ID defaults = Foundation.invoke("NSUserDefaults", "standardUserDefaults"); if (defaults == null || defaults.equals(ID.NIL)) return false; final ID valObj = Foundation.invoke(defaults, "objectForKey:", Foundation.nsString("AppleInterfaceStyle")); if (valObj == null || valObj.equals(ID.NIL)) return false; final String sval = Foundation.toStringViaUTF8(valObj); return sval != null && sval.equals("Dark"); } finally { pool.drain(); } } public static String getAccentColor() { if (!SystemInfo.isMac || !SystemInfo.isOsVersionAtLeast("10.14")) return null; // Blue : default (key doesn't exist) // Purple : 5 // Pink : 6 // Red : 0 // Orange : 1 // Yellow : 2 // Green : 3 // Graphite: -1 final int nval = _getAccentColor(); switch (nval) { case 5: return "purple"; case 6: return "pink"; case 0: return "red"; case 1: return "orange"; case 2: return "yellow"; case 3: return "green"; case -1: return "graphite"; default: return "blue"; } } private static int _getAccentColor() { final String nodeName = "AppleAccentColor"; final Foundation.NSAutoreleasePool pool = new Foundation.NSAutoreleasePool(); try { final ID defaults = Foundation.invoke("NSUserDefaults", "standardUserDefaults"); if (defaults == null || defaults.equals(ID.NIL)) return Integer.MIN_VALUE; final ID domObj = Foundation.invoke(defaults, "persistentDomainForName:", Foundation.nsString("Apple Global Domain")); if (domObj == null || domObj.equals(ID.NIL)) return Integer.MIN_VALUE; final ID nskey = Foundation.nsString(nodeName); final ID resObj = Foundation.invoke(domObj, "objectForKey:", nskey); if (resObj == null || resObj.equals(ID.NIL)) return Integer.MIN_VALUE; // key doesn't exist return Foundation.invoke(domObj, "integerForKey:", nskey).intValue(); } finally { pool.drain(); } } // for debug private List<String> _listAllKeys() { List<String> res = new ArrayList<String>(100); final Foundation.NSAutoreleasePool pool = new Foundation.NSAutoreleasePool(); try { final ID defaults = Foundation.invoke("NSUserDefaults", "standardUserDefaults"); final ID allKeysDict = Foundation.invoke(defaults, "dictionaryRepresentation"); final ID allKeysArr = Foundation.invoke(allKeysDict, "allKeys"); final ID count = Foundation.invoke(allKeysArr, "count"); for (int c = 0; c < count.intValue(); ++c) { final ID nsKeyName = Foundation.invoke(allKeysArr, "objectAtIndex:", c); final String keyName = Foundation.toStringViaUTF8(nsKeyName); // System.out.println(keyName); res.add(keyName); } return res; } finally { pool.drain(); } } }
package me.dreamteam.tardis; public class EnemyEntity extends Entity { // The speed at which the alien moves private double moveSpeed = 100; private Game game; public EnemyEntity(Game game,String ref,int x,int y) { super(ref,x,y); this.game = game; // sets the alien to move downwards at the selected speed dy = moveSpeed; } public void move(long delta) { if ((dy < 0) && (y < 10)) { game.updateLogic(); } if ((dy > 0) && (y > 750)) { game.updateLogic(); } super.move(delta); } public void collidedWith(Entity other) { //collision is handled in other file } }
package com.kyleduo.rabbits; import android.app.Activity; import android.content.Context; import android.net.Uri; import android.support.v4.app.Fragment; import android.util.Log; import com.kyleduo.rabbits.annotations.utils.NameParser; import com.kyleduo.rabbits.navigator.AbstractNavigator; import com.kyleduo.rabbits.navigator.AbstractPageNotFoundHandler; import com.kyleduo.rabbits.navigator.DefaultNavigatorFactory; import com.kyleduo.rabbits.navigator.INavigationInterceptor; import com.kyleduo.rabbits.navigator.INavigatorFactory; import com.kyleduo.rabbits.navigator.IProvider; import com.kyleduo.rabbits.navigator.MuteNavigator; import java.io.File; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @SuppressWarnings({"WeakerAccess", "unused"}) public class Rabbit { private static final String TAG = "Rabbit"; private static final String ROUTER_CLASS = "com.kyleduo.rabbits.Router"; public static final String KEY_ORIGIN_URI = "Rabbits_Origin_Uri"; private static IRouter sRouter; static String sAppScheme; static String sDefaultHost; private static INavigatorFactory sNavigatorFactory; private static List<INavigationInterceptor> sInterceptors; private Object mFrom; private List<INavigationInterceptor> mInterceptors; private Rabbit(Object from) { mFrom = from; if (sRouter == null) { sRouter = (IRouter) Proxy.newProxyInstance(IRouter.class.getClassLoader(), new Class[]{IRouter.class}, new InvocationHandler() { Class<?> clz; Map<String, Method> methods = new LinkedHashMap<>(); @Override public Object invoke(Object o, Method method, Object[] objects) throws Throwable { if (clz == null) { clz = Class.forName(ROUTER_CLASS); } String page = (String) objects[0]; String name = method.getName(); String key = name + "-" + page; Method m = methods.get(key); if (m != null) { return m.invoke(null); } else { if (name.equals(IRouter.METHOD_ROUTE)) { String methodName = NameParser.parseRoute(page); m = clz.getMethod(methodName); if (m != null) { methods.put(key, m); return m.invoke(null); } } else if (name.equals(IRouter.METHOD_OBTAIN)) { String methodName = NameParser.parseObtain(page); m = clz.getMethod(methodName); if (m != null) { methods.put(key, m); return m.invoke(null); } } } return null; } }); } } /** * Initial rabbits with basic elements, using default Navigators. * * @param scheme Scheme for this application. * @param defaultHost Default host when try to match uri without a host. */ public static void init(String scheme, String defaultHost) { init(scheme, defaultHost, new DefaultNavigatorFactory()); } /** * Initial rabbits with basic elements. * * @param scheme Scheme for this application. * @param defaultHost Default host when try to match uri without a host. * @param navigatorFactory Custom navigator factory. */ public static void init(String scheme, String defaultHost, INavigatorFactory navigatorFactory) { sAppScheme = scheme; sDefaultHost = defaultHost; sNavigatorFactory = navigatorFactory; } /** * Setup in sub-thread. * * @param context Used for io operation. * @param callback callback run after setup finished. */ public static void asyncSetup(Context context, Runnable callback) { setup(context, true, callback); } /** * Synchronously setup. * * @param context Used for io operation. */ public static void setup(Context context) { setup(context, false, null); } private static void setup(Context context, boolean async, Runnable callback) { Mappings.setup(context, async, callback); } /** * Update mappings from a file. * * @param context Used for io operation. * @param file Json file. */ public static void updateMappings(Context context, File file) { Mappings.update(context, file); } /** * Update mappings using a json string. * * @param context Used for io operation. * @param json Json string. */ public static void updateMappings(Context context, String json) { Mappings.update(context, json); } /** * Create a rabbit who has ability to navigate through your pages. * * @param from Whether an Activity or a Fragment instance. * @return Rabbit instance. */ public static Rabbit from(Object from) { if (!(from instanceof Activity) && !(from instanceof Fragment || from instanceof android.app.Fragment)) { throw new IllegalArgumentException("From object must be whether an Activity or a Fragment instance."); } return new Rabbit(from); } /** * Add global interceptor. These Interceptors' methods will be invoked in every navigation. * * @param interceptor Interceptor instance. */ public static void addGlobalInterceptor(INavigationInterceptor interceptor) { if (sInterceptors == null) { sInterceptors = new ArrayList<>(); } sInterceptors.add(interceptor); } /** * Add an interceptor used for this navigation. This is useful when you want to check whether a * uri matches a specific page using {@link com.kyleduo.rabbits.Rabbit#tryTo(Uri)} method. * * @param interceptor Interceptor instance. */ public Rabbit addInterceptor(INavigationInterceptor interceptor) { if (mInterceptors == null) { mInterceptors = new ArrayList<>(); } mInterceptors.add(interceptor); return this; } /** * Used for obtain page object. Intent or Fragment instance. * * @param uriStr uriStr * @return IProvider */ public IProvider obtain(String uriStr) { Uri uri = Uri.parse(uriStr); return obtain(uri); } /** * Used for obtain page object. Intent or Fragment instance. * * @param uri uri * @return IProvider */ public IProvider obtain(Uri uri) { Target target = Mappings.match(uri).obtain(sRouter); return dispatch(target, false); } /** * Navigate to page, or perform a not found strategy. * * @param uriStr uri string * @return AbstractNavigator */ public AbstractNavigator to(String uriStr) { Uri uri = Uri.parse(uriStr); return to(uri); } /** * Navigate to page, or perform a not found strategy. * * @param uri uri * @return AbstractNavigator */ public AbstractNavigator to(Uri uri) { Target target = Mappings.match(uri).route(sRouter); return dispatch(target, false); } /** * Navigate to page, or just return null if not found. * * @param uriStr uri * @return AbstractNavigator */ public AbstractNavigator tryTo(String uriStr) { Uri uri = Uri.parse(uriStr); return tryTo(uri); } /** * Only if there was a mapping from uri with app scheme and given path exists a valid navigator * will returned. * * @param uri uri * @return AbstractNavigator */ public AbstractNavigator tryTo(Uri uri) { uri = uri.buildUpon().scheme(sAppScheme).build(); Target target = Mappings.match(uri).route(sRouter); return dispatch(target, true); } /** * Handle the dispatch operation. * * @param target target * @param mute whether mute * @return navigator */ private AbstractNavigator dispatch(Target target, boolean mute) { Log.d(TAG, target.toString()); if (!target.hasMatched()) { if (!mute) { AbstractPageNotFoundHandler pageNotFoundHandler = sNavigatorFactory.createPageNotFoundHandler(mFrom, target.getUri(), target.getPage(), target.getFlags(), target.getExtras(), assembleInterceptor()); if (pageNotFoundHandler != null) { return pageNotFoundHandler; } } else if (target.getTo() == null) { return new MuteNavigator(target.getUri(), mFrom, null, target.getPage(), target.getFlags(), null, mInterceptors); } } return sNavigatorFactory.createNavigator(target.getUri(), mFrom, target.getTo(), target.getPage(), target.getFlags(), target.getExtras(), assembleInterceptor()); } /** * Assemble interceptors and static interceptors. * order static interceptors after instance's interceptors. * * @return a list of valid navigation interceptor */ private List<INavigationInterceptor> assembleInterceptor() { if (sInterceptors == null) { return mInterceptors; } if (mInterceptors == null) { mInterceptors = new ArrayList<>(); } mInterceptors.addAll(sInterceptors); return mInterceptors; } }
package me.dreamteam.tardis; import java.awt.GraphicsConfiguration; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.Transparency; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import java.util.HashMap; import javax.imageio.ImageIO; public class SpriteStore { private static SpriteStore single = new SpriteStore(); public static SpriteStore get() { return single; } private HashMap sprites = new HashMap(); public Sprite getSprite(String ref) { if (sprites.get(ref) != null) { return (Sprite) sprites.get(ref); } BufferedImage sourceImage = null; try { URL url = this.getClass().getClassLoader().getResource(ref); if (url == null) { fail("Can't find sprite or resource: "+ref); } sourceImage = ImageIO.read(url); } catch (IOException e) { fail("Failed to load: "+ref); } GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration(); Image image = gc.createCompatibleImage(sourceImage.getWidth(),sourceImage.getHeight(),Transparency.BITMASK); image.getGraphics().drawImage(sourceImage,0,0,null); Sprite sprite = new Sprite(image); sprites.put(ref,sprite); return sprite; } private void fail(String message) { System.err.println(message); System.exit(0); } }
package com.debortoliwines.odoo.api; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; import java.io.IOException; import java.util.ArrayList; import javax.net.ssl.HttpsURLConnection; import org.apache.xmlrpc.XmlRpcException; import org.assertj.core.api.SoftAssertions; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockserver.integration.ClientAndServer; import org.mockserver.model.RegexBody; import org.mockserver.model.StringBody; import org.mockserver.socket.PortFactory; import org.mockserver.socket.SSLFactory; import org.mockserver.verify.VerificationTimes; import com.debortoliwines.odoo.api.OpenERPXmlRpcProxy.RPCProtocol; public class SessionTest { private static final int MOCKSERVER_PORT = PortFactory.findFreePort(); private static final String WRONG_DB = "wrong_db"; private static final String WRONG_DB_MESSAGE_REGEXP = "[\\w\\W]*[Dd]atabase \"?" + WRONG_DB + "\"? does not exist[\\w\\W]*"; private static final String LOGIN_FAILED_MESSAGE = "Incorrect username and/or password. Login Failed."; private static final String WRONG_PASSWORD = "wrong_password"; private static final String WRONG_USERNAME = "wrong_userName"; private static RPCProtocol protocol; private static String host; private static Integer port; private static String databaseName; private static String userName; private static String password; private Session session; // private static ClientAndProxy proxy; private static ClientAndServer mockServer; @BeforeClass public static void startProxyAndServer() throws Exception { HttpsURLConnection.setDefaultSSLSocketFactory(SSLFactory.getInstance().sslContext().getSocketFactory()); // proxy = // ClientAndProxy.startClientAndProxy(PortFactory.findFreePort()); mockServer = ClientAndServer.startClientAndServer(MOCKSERVER_PORT); mockDeniedDatabaseListing(); mockValidLogin(); mockGetContext(); mockLoginWrongUsername(); mockLoginWrongPassword(); mockLoginWrongDb(); mockServerVersionResponse(); } private static void mockDeniedDatabaseListing() { mockServer .when(request().withMethod("POST").withPath("/xmlrpc/2/db") .withBody(new StringBody( "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall><methodName>list</methodName><params/></methodCall>"))) .respond(response().withStatusCode(200).withBody( "<?xml version='1.0'?>\n<methodResponse>\n<fault>\n<value><struct>\n<member>\n<name>faultCode</name>\n<value><int>3</int></value>\n</member>\n<member>\n<name>faultString</name>\n<value><string>Access denied</string></value>\n</member>\n</struct></value>\n</fault>\n</methodResponse>\n")); } private static void mockValidLogin() { mockServer .when(request().withMethod("POST").withPath("/xmlrpc/2/common") .withBody(new StringBody( "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall><methodName>login</methodName><params><param><value>demo_90_1453880126</value></param><param><value>admin</value></param><param><value>admin</value></param></params></methodCall>"))) .respond(response().withStatusCode(200).withBody( "<?xml version='1.0'?>\n<methodResponse>\n<params>\n<param>\n<value><int>1</int></value>\n</param>\n</params>\n</methodResponse>\n")); } private static void mockGetContext() { mockServer .when(request().withMethod("POST").withPath("/xmlrpc/2/object") .withBody(new StringBody( "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall><methodName>execute</methodName><params><param><value>demo_90_1453880126</value></param><param><value><i4>1</i4></value></param><param><value>admin</value></param><param><value>res.users</value></param><param><value>context_get</value></param></params></methodCall>"))) .respond(response().withStatusCode(200).withBody( "<?xml version='1.0'?>\n<methodResponse>\n<params>\n<param>\n<value><struct>\n<member>\n<name>lang</name>\n<value><string>en_US</string></value>\n</member>\n<member>\n<name>tz</name>\n<value><string>Europe/Brussels</string></value>\n</member>\n</struct></value>\n</param>\n</params>\n</methodResponse>\n")); } private static void mockLoginWrongUsername() { mockServer .when(request().withMethod("POST").withPath("/xmlrpc/2/common") .withBody(new StringBody( "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall><methodName>login</methodName><params><param><value>demo_90_1453880126</value></param><param><value>wrong_userName</value></param><param><value>admin</value></param></params></methodCall>"))) .respond(response().withStatusCode(200).withBody( "<?xml version='1.0'?>\n<methodResponse>\n<params>\n<param>\n<value><boolean>0</boolean></value>\n</param>\n</params>\n</methodResponse>\n")); } private static void mockLoginWrongPassword() { mockServer .when(request().withMethod("POST").withPath("/xmlrpc/2/common") .withBody(new StringBody( "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall><methodName>login</methodName><params><param><value>demo_90_1453880126</value></param><param><value>admin</value></param><param><value>wrong_password</value></param></params></methodCall>"))) .respond(response().withStatusCode(200).withBody( "<?xml version='1.0'?>\n<methodResponse>\n<params>\n<param>\n<value><boolean>0</boolean></value>\n</param>\n</params>\n</methodResponse>\n")); } private static void mockLoginWrongDb() { mockServer .when(request().withMethod("POST").withPath("/xmlrpc/2/common") .withBody(new StringBody( "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall><methodName>login</methodName><params><param><value>wrong_db</value></param><param><value>admin</value></param><param><value>admin</value></param></params></methodCall>"))) .respond(response().withStatusCode(200).withBody( "<?xml version='1.0'?>\n<methodResponse>\n<fault>\n<value><struct>\n<member>\n<name>faultCode</name>\n<value><int>1</int></value>\n</member>\n<member>\n<name>faultString</name>\n<value><string>Traceback (most recent call last):\n File \"/home/odoo/src/odoo/9.0/openerp/service/wsgi_server.py\", line 56, in xmlrpc_return\n result = openerp.http.dispatch_rpc(service, method, params)\n File \"/home/odoo/src/odoo/9.0/openerp/http.py\", line 114, in dispatch_rpc\n result = dispatch(method, params)\n File \"/home/odoo/src/odoo/9.0/openerp/service/common.py\", line 57, in dispatch\n return g[exp_method_name](*params)\n File \"/home/odoo/src/odoo/9.0/openerp/service/common.py\", line 23, in exp_login\n res = security.login(db, login, password)\n File \"/home/odoo/src/odoo/9.0/openerp/service/security.py\", line 8, in login\n res_users = openerp.registry(db)['res.users']\n File \"/home/odoo/src/odoo/9.0/openerp/__init__.py\", line 50, in registry\n return modules.registry.RegistryManager.get(database_name)\n File \"/home/odoo/src/odoo/9.0/openerp/modules/registry.py\", line 354, in get\n update_module)\n File \"/home/odoo/src/odoo/9.0/openerp/modules/registry.py\", line 371, in new\n registry = Registry(db_name)\n File \"/home/odoo/src/odoo/9.0/openerp/modules/registry.py\", line 63, in __init__\n cr = self.cursor()\n File \"/home/odoo/src/odoo/9.0/openerp/modules/registry.py\", line 278, in cursor\n return self._db.cursor()\n File \"/home/odoo/src/odoo/9.0/openerp/sql_db.py\", line 556, in cursor\n return Cursor(self.__pool, self.dbname, self.dsn, serialized=serialized)\n File \"/home/odoo/src/odoo/9.0/openerp/sql_db.py\", line 162, in __init__\n self._cnx = pool.borrow(dsn)\n File \"/home/odoo/src/odoo/9.0/openerp/sql_db.py\", line 445, in _locked\n return fun(self, *args, **kwargs)\n File \"/home/odoo/src/odoo/9.0/openerp/sql_db.py\", line 507, in borrow\n result = psycopg2.connect(dsn=dsn, connection_factory=PsycoConnection)\n File \"/usr/lib/python2.7/dist-packages/psycopg2/__init__.py\", line 179, in connect\n connection_factory=connection_factory, async=async)\nOperationalError: FATAL: database \"wrong_db\" does not exist\n\n</string></value>\n</member>\n</struct></value>\n</fault>\n</methodResponse>\n")); } private static void mockServerVersionResponse() { mockServer .when(request().withMethod("POST").withPath("/xmlrpc/2/db") .withBody(new StringBody( "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall><methodName>server_version</methodName><params/></methodCall>"))) .respond(response().withStatusCode(200).withBody( "<?xml version='1.0'?>\n<methodResponse>\n<params>\n<param>\n<value><string>9.0e</string></value>\n</param>\n</params>\n</methodResponse>\n")); } @AfterClass public static void stopServerAndProxy() { mockServer.stop(); // proxy.dumpToLogAsJava(); // proxy.stop(); } /* * Initialize connection data to demo db only once per test series */ @BeforeClass public static void requestDemoDb() throws IOException, XmlRpcException { // DemoDbGetter.getDemoDb(new DemoDbConnectionDataSetter()); SessionTest.protocol = RPCProtocol.RPC_HTTPS; SessionTest.host = "localhost"; SessionTest.port = MOCKSERVER_PORT; SessionTest.userName = "admin"; SessionTest.password = "admin"; SessionTest.databaseName = "demo_90_1453880126"; } @Before public void setUp() throws Exception { session = new Session(protocol, host, port, databaseName, userName, password); } @Test public void should_throw_when_parameters_are_incorrect() throws Exception { Session badSession = new Session(RPCProtocol.RPC_HTTPS, host, port, databaseName, WRONG_USERNAME, password); Throwable thrown = catchThrowable(() -> badSession.startSession()); Session badSession2 = new Session(RPCProtocol.RPC_HTTPS, host, port, databaseName, userName, WRONG_PASSWORD); Throwable thrown2 = catchThrowable(() -> badSession2.startSession()); Session badSession3 = new Session(RPCProtocol.RPC_HTTPS, host, port, WRONG_DB, userName, password); Throwable thrown3 = catchThrowable(() -> badSession3.startSession()); Session badSession4 = new Session(RPCProtocol.RPC_HTTPS, host, 1234, databaseName, userName, password); Throwable thrown4 = catchThrowable(() -> badSession4.startSession()); // use SoftAssertions instead of direct assertThat methods // to collect all failing assertions in one go SoftAssertions softly = new SoftAssertions(); softly.assertThat(thrown).as("Bad userName").isInstanceOf(Exception.class).hasMessage(LOGIN_FAILED_MESSAGE); softly.assertThat(thrown2).as("Bad password").isInstanceOf(Exception.class).hasMessage(LOGIN_FAILED_MESSAGE); softly.assertThat(thrown3).as("Bad db").isInstanceOf(XmlRpcException.class) .hasMessageMatching(WRONG_DB_MESSAGE_REGEXP); softly.assertThat(thrown4).as("Bad port").isInstanceOf(XmlRpcException.class); // Don't forget to call SoftAssertions global verification ! softly.assertAll(); } @Test public void should_contain_tags_in_context_after_start() throws Exception { // Need to be authenticated to be allowed to fetch the remote context session.authenticate(); session.getRemoteContext(); assertThat(session.getContext()).as("Session context").containsEntry(Context.ActiveTestTag, true) .containsKeys(Context.LangTag, Context.TimezoneTag); } @Test public void should_provide_userId_after_authenticate() throws Exception { int userId = session.authenticate(); assertThat(userId).as("User ID").isNotZero(); } @Test public void shoudl_return_database_list() throws Exception { // Either a list of available databases is returned, or the odoo server // returns an error with a message instead of a fault code, leading to a // ClassCastException try { ArrayList<String> databaseList = session.getDatabaseList(host, port); assertThat(databaseList).as("List of databases on server " + host).contains(databaseName); } catch (XmlRpcException e) { assertThat(e).as("XmlRpcException thrown when access is denied").hasMessage("Access denied"); } } @Test public void shoudl_return_server_version() throws Exception { Version version = session.getServerVersion(); assertThat(version).as("Server version").isNotNull(); } static boolean checkedDatabasePresence = false, authenticated = false, fetchedRemoteContext = false; @Test public void should_authenticate_and_fetch_remote_context_on_session_start() throws Exception { session = new Session(protocol, host, port, databaseName, userName, password) { @Override int authenticate() throws XmlRpcException, Exception { authenticated = true; return 1; } @Override void checkDatabasePresence() { checkedDatabasePresence = true; } @Override void getRemoteContext() throws XmlRpcException { fetchedRemoteContext = true; } }; session.startSession(); // use SoftAssertions instead of direct assertThat methods // to collect all failing assertions in one go SoftAssertions softly = new SoftAssertions(); softly.assertThat(checkedDatabasePresence).as("Checked for database presence").isTrue(); softly.assertThat(authenticated).as("Authenticated").isTrue(); softly.assertThat(fetchedRemoteContext).as("Fetched remote context").isTrue(); // Don't forget to call SoftAssertions global verification ! softly.assertAll(); } @Test public void should_send_given_parameters() throws Exception { mockServer .when(request().withMethod("POST").withPath("/xmlrpc/2/object") .withBody(new RegexBody(".*parameter1.*parameter2.*"))) .respond(response().withStatusCode(200).withBody( "<?xml version='1.0'?>\n<methodResponse>\n<params>\n<param>\n<value><int>1</int></value>\n</param>\n</params>\n</methodResponse>\n")); Object[] parameters = new Object[] { "parameter1", "parameter2" }; session.executeCommand("objectName", "commandName", parameters); mockServer.verify(request().withBody(new RegexBody(".*parameter1.*parameter2.*")), VerificationTimes.once()); } // /** // * Only used to set the static data for connection on the main class // */ // private static class DemoDbConnectionDataSetter implements // DemoDbInfoRequester { // @Override // public void setProtocol(RPCProtocol protocol) { // SessionTest.protocol = protocol; // @Override // public void setHost(String host) { // SessionTest.host = host; // @Override // public void setPort(Integer port) { // SessionTest.port = port; // @Override // public void setDatabaseName(String databaseName) { // SessionTest.databaseName = databaseName; // @Override // public void setUserName(String userName) { // SessionTest.userName = userName; // @Override // public void setPassword(String password) { // SessionTest.password = password; }