answer
stringlengths
17
10.2M
package nom.bdezonia.zorbage.oob.nd; import nom.bdezonia.zorbage.multidim.MultiDimDataSource; import nom.bdezonia.zorbage.procedure.Procedure2; import nom.bdezonia.zorbage.sampling.IntegerIndex; import nom.bdezonia.zorbage.type.algebra.Algebra; /** * * @author Barry DeZonia * */ public class ConstantNdOOB<T extends Algebra<T,U>, U> implements Procedure2<IntegerIndex,U> { private final T alg; private final MultiDimDataSource<U> ds; private final U c; /** * * @param alg * @param ds * @param c */ public ConstantNdOOB(T alg, MultiDimDataSource<U> ds, U c) { this.alg = alg; this.ds = ds; this.c = alg.construct(); this.alg.assign().call(c, this.c); } @Override public void call(IntegerIndex index, U value) { if (index.numDimensions() != ds.numDimensions()) throw new IllegalArgumentException("index does not have same num dims as dataset"); alg.assign().call(c, value); } }
package org.apache.uima.ruta.tag.obo; import static java.util.Arrays.asList; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.uima.ruta.RutaStream; import org.apache.uima.ruta.block.RutaBlock; import org.apache.uima.ruta.RutaStatement; import org.apache.uima.ruta.engine.RutaEngine; import org.apache.uima.ruta.expression.resource.WordTableExpression; import org.apache.uima.ruta.resource.RutaResourceLoader; import org.apache.uima.ruta.resource.RutaTable; import org.apache.uima.ruta.resource.RutaWordList; import org.apache.uima.ruta.resource.TreeWordList; import org.apache.uima.ruta.rule.MatchContext; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; public class OboWordTable extends WordTableExpression { private String oboPath; public OboWordTable(String oboPath) throws IOException { this.oboPath = oboPath; } @Override public RutaTable getTable(final MatchContext matchContext, final RutaStream rutaStream) { RutaBlock parent = matchContext.getParent(); ResourceLoader resourceLoader = new RutaResourceLoader(parent.getEnvironment().getResourcePaths()); Resource resource = resourceLoader.getResource(oboPath); if (!resource.exists()) { throw new RuntimeException("Cannot file obo file " + resource.getFilename() + " [" + oboPath + "]"); } else { try { OBOOntology obo = new OBOOntology().read(resource .getInputStream()); if (resource.getFilename().endsWith("robo")) { RoboExpander.expand(obo); } return new OboRutaTable(obo); } catch (IOException e) { throw new RuntimeException("Error reading obo file " + resource.getFilename(), e); } catch (OboFormatException e) { throw new RuntimeException("OBO format error: " + resource.getFilename(), e); } } } public static class OboRutaTable implements RutaTable { private List<List<String>> tableData = new ArrayList<>(); private Map<Integer, RutaWordList> columnWordLists = new HashMap<>(2); public OboRutaTable(OBOOntology obo) { for (OntologyTerm term : obo.getTerms().values()) { String id = term.getId(); String name = term.getName(); if (name != null) { // /System.out.println(">>" + name); tableData.add(asList(new String[] { name, id })); } for (Synonym s : term.getSynonyms()) { // /System.out.println(">>" + s.getSyn()); tableData.add(asList(new String[] { s.getSyn(), id })); } } } // FIXME below copied from CSVTable :-( --> ask to make fields protected public RutaWordList getWordList(int index, RutaBlock parent) { RutaWordList list = columnWordLists.get(index); if (list == null) { if (index > 0 && index <= tableData.get(0).size()) { Boolean dictRemoveWS = (Boolean) parent.getContext() .getConfigParameterValue( RutaEngine.PARAM_DICT_REMOVE_WS); if (dictRemoveWS == null) { dictRemoveWS = false; } list = new TreeWordList(getColumnData(index - 1), dictRemoveWS); columnWordLists.put(index, list); } } return list; } private List<String> getColumnData(int i) { List<String> result = new LinkedList<String>(); for (List<String> each : tableData) { if (each.size() > i) { result.add(each.get(i)); } else { result.add(""); } } return result; } public String getEntry(int row, int column) { return tableData.get(row).get(column); } public List<String> getRowWhere(int column, String value) { List<String> columnData = getColumnData(column); int i = 0; for (String string : columnData) { if (string.toLowerCase().equals(value.toLowerCase())) { return tableData.get(i); } i++; } i = 0; for (String string : columnData) { if (string.toLowerCase().replaceAll("\\s", "") .equals(value.toLowerCase())) { return tableData.get(i); } i++; } return new ArrayList<String>(); } } }
package org.biacode.jcronofy.api.model; import com.fasterxml.jackson.annotation.JsonProperty; public enum ScopeModel { @JsonProperty("read_events") READ_EVENTS("read_events"), @JsonProperty("create_event") CREATE_EVENT("create_event"), @JsonProperty("delete_event") DELETE_EVENT("delete_event"), @JsonProperty("read_free_busy") READ_FREE_BUSY("read_free_busy"), @JsonProperty("create_calendar") CREATE_CALENDAR("create_calendar"), @JsonProperty("event_reminders") EVENT_REMINDERS("event_reminders"), @JsonProperty("change_participation_status") CHANGE_PARTICIPATION_STATUS("change_participation_status"), @JsonProperty("full_access") FULL_ACCESS("full_access"); final String scope; ScopeModel(final String scope) { this.scope = scope; } public String getScope() { return scope; } }
package org.datacite.mds.web; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.datacite.mds.domain.Allocator; import org.datacite.mds.domain.Datacentre; import org.datacite.mds.util.Converters; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.roo.addon.web.mvc.controller.RooWebScaffold; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @RooWebScaffold(path = "datacentres", formBackingObject = Datacentre.class, delete = false) @RequestMapping("/datacentres") @Controller public class DatacentreController { @InitBinder void registerConverters(WebDataBinder binder) { if (binder.getConversionService() instanceof GenericConversionService) { GenericConversionService conversionService = (GenericConversionService) binder.getConversionService(); conversionService.addConverter(Converters.getSimpleAllocatorConverter()); conversionService.addConverter(Converters.getSimplePrefixConverter()); } } @RequestMapping(params = "form", method = RequestMethod.GET) public String createForm(Model model, HttpServletRequest request) { String symbol = request.getUserPrincipal().getName(); Allocator allocator = (Allocator) Allocator.findAllocatorsBySymbolEquals(symbol).getSingleResult(); Datacentre datacentre = new Datacentre(); datacentre.setAllocator(allocator); model.addAttribute("datacentre", datacentre); List dependencies = new ArrayList(); if (Allocator.countAllocators() == 0) { dependencies.add(new String[] { "allocator", "allocators" }); } model.addAttribute("dependencies", dependencies); return "datacentres/create"; } }
package org.deepsymmetry.beatlink.data; import org.deepsymmetry.beatlink.CdjStatus; import org.deepsymmetry.beatlink.dbserver.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; /** * Provides support for navigating the menu hierarchy offered by the dbserver on a player for a particular media slot. * Note that for historical reasons, loading track metadata, playlists, and the full track list are performed by the * {@link MetadataFinder}, even though those are technically menu operations. * * @since 0.4.0 * * @author James Elliott */ public class MenuLoader { private static final Logger logger = LoggerFactory.getLogger(MenuLoader.class); public List<Message> requestRootMenuFrom(final SlotReference slotReference, final int sortOrder) throws Exception { ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() { @Override public List<Message> useClient(Client client) throws Exception { if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) { try { logger.debug("Requesting root menu."); Message response = client.menuRequest(Message.KnownType.ROOT_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot, new NumberField(sortOrder), new NumberField(0xffffff)); return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response); } finally { client.unlockForMenuOperations(); } } else { throw new TimeoutException("Unable to lock player for menu operations."); } } }; return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting root menu"); } public List<Message> requestPlaylistMenuFrom(final SlotReference slotReference, final int sortOrder) throws Exception { return MetadataFinder.getInstance().requestPlaylistItemsFrom(slotReference.player, slotReference.slot, sortOrder, 0, true); } public List<Message> requestHistoryMenuFrom(final SlotReference slotReference, final int sortOrder) throws Exception { ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() { @Override public List<Message> useClient(Client client) throws Exception { if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) { try { logger.debug("Requesting History menu."); Message response = client.menuRequest(Message.KnownType.HISTORY_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot, new NumberField(sortOrder)); return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response); } finally { client.unlockForMenuOperations(); } } else { throw new TimeoutException("Unable to lock player for menu operations."); } } }; return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting history menu"); } public List<Message> requestHistoryPlaylistFrom(final SlotReference slotReference, final int sortOrder, final int historyId) throws Exception { ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() { @Override public List<Message> useClient(Client client) throws Exception { if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) { try { logger.debug("Requesting History playlist."); Message response = client.menuRequest(Message.KnownType.TRACK_MENU_FOR_HISTORY_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot, new NumberField(sortOrder), new NumberField(historyId)); return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response); } finally { client.unlockForMenuOperations(); } } else { throw new TimeoutException("Unable to lock player for menu operations."); } } }; return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting history playlist"); } public List<Message> requestTrackMenuFrom(final SlotReference slotReference, final int sortOrder) throws Exception { ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() { @Override public List<Message> useClient(Client client) throws Exception { return MetadataFinder.getInstance().getFullTrackList(slotReference.slot, client, sortOrder); } }; return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting track menu"); } public List<Message> requestArtistMenuFrom(final SlotReference slotReference, final int sortOrder) throws Exception { ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() { @Override public List<Message> useClient(Client client) throws Exception { if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) { try { logger.debug("Requesting Artist menu."); Message response = client.menuRequest(Message.KnownType.ARTIST_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot, new NumberField(sortOrder)); return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response); } finally { client.unlockForMenuOperations(); } } else { throw new TimeoutException("Unable to lock player for menu operations."); } } }; return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting artist menu"); } public List<Message> requestArtistAlbumMenuFrom(final SlotReference slotReference, final int sortOrder, final int artistId) throws Exception { ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() { @Override public List<Message> useClient(Client client) throws Exception { if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) { try { logger.debug("Requesting Artist Album menu."); Message response = client.menuRequest(Message.KnownType.ALBUM_MENU_FOR_ARTIST_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot, new NumberField(sortOrder), new NumberField(artistId)); return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response); } finally { client.unlockForMenuOperations(); } } else { throw new TimeoutException("Unable to lock player for menu operations."); } } }; return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting artist album menu"); } public List<Message> requestArtistAlbumTrackMenuFrom(final SlotReference slotReference, final int sortOrder, final int artistId, final int albumId) throws Exception { ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() { @Override public List<Message> useClient(Client client) throws Exception { if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) { try { logger.debug("Requesting Artist Album Track menu."); Message response = client.menuRequest(Message.KnownType.TRACK_MENU_FOR_ARTIST_AND_ALBUM, Message.MenuIdentifier.MAIN_MENU, slotReference.slot, new NumberField(sortOrder), new NumberField(artistId), new NumberField(albumId)); return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response); } finally { client.unlockForMenuOperations(); } } else { throw new TimeoutException("Unable to lock player for menu operations."); } } }; return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting artist album tracks menu"); } public List<Message> requestAlbumTrackMenuFrom(final SlotReference slotReference, final int sortOrder, final int albumId) throws Exception { ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() { @Override public List<Message> useClient(Client client) throws Exception { if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) { try { logger.debug("Requesting Album Track menu."); Message response = client.menuRequest(Message.KnownType.TRACK_MENU_FOR_ALBUM_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot, new NumberField(sortOrder), new NumberField(albumId)); return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response); } finally { client.unlockForMenuOperations(); } } else { throw new TimeoutException("Unable to lock player for menu operations."); } } }; return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting album tracks menu"); } public List<Message> requestGenreMenuFrom(final SlotReference slotReference, final int sortOrder) throws Exception { ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() { @Override public List<Message> useClient(Client client) throws Exception { if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) { try { logger.debug("Requesting Genre menu."); Message response = client.menuRequest(Message.KnownType.GENRE_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot, new NumberField(sortOrder)); return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response); } finally { client.unlockForMenuOperations(); } } else { throw new TimeoutException("Unable to lock player for menu operations."); } } }; return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting genre menu"); } public List<Message> requestGenreArtistMenuFrom(final SlotReference slotReference, final int sortOrder, final int genreId) throws Exception { ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() { @Override public List<Message> useClient(Client client) throws Exception { if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) { try { logger.debug("Requesting Genre Artist menu."); Message response = client.menuRequest(Message.KnownType.ARTIST_MENU_FOR_GENRE_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot, new NumberField(sortOrder), new NumberField(genreId)); return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response); } finally { client.unlockForMenuOperations(); } } else { throw new TimeoutException("Unable to lock player for menu operations."); } } }; return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting genre artists menu"); } public List<Message> requestGenreArtistAlbumMenuFrom(final SlotReference slotReference, final int sortOrder, final int genreId, final int artistId) throws Exception { ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() { @Override public List<Message> useClient(Client client) throws Exception { if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) { try { logger.debug("Requesting Genre Artist Album menu."); Message response = client.menuRequest(Message.KnownType.ALBUM_MENU_FOR_GENRE_AND_ARTIST, Message.MenuIdentifier.MAIN_MENU, slotReference.slot, new NumberField(sortOrder), new NumberField(genreId), new NumberField(artistId)); return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response); } finally { client.unlockForMenuOperations(); } } else { throw new TimeoutException("Unable to lock player for menu operations."); } } }; return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting genre artist albums menu"); } public List<Message> requestGenreArtistAlbumTrackMenuFrom(final SlotReference slotReference, final int sortOrder, final int genreId, final int artistId, final int albumId) throws Exception { ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() { @Override public List<Message> useClient(Client client) throws Exception { if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) { try { logger.debug("Requesting Genre Artist Album Track menu."); Message response = client.menuRequest(Message.KnownType.TRACK_MENU_FOR_GENRE_ARTIST_AND_ALBUM, Message.MenuIdentifier.MAIN_MENU, slotReference.slot, new NumberField(sortOrder), new NumberField(genreId), new NumberField(artistId), new NumberField(albumId)); return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response); } finally { client.unlockForMenuOperations(); } } else { throw new TimeoutException("Unable to lock player for menu operations."); } } }; return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting genre artist album tracks menu"); } public List<Message> requestAlbumMenuFrom(final SlotReference slotReference, final int sortOrder) throws Exception { ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() { @Override public List<Message> useClient(Client client) throws Exception { if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) { try { logger.debug("Requesting Album menu."); Message response = client.menuRequest(Message.KnownType.ALBUM_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot, new NumberField(sortOrder)); return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response); } finally { client.unlockForMenuOperations(); } } else { throw new TimeoutException("Unable to lock player for menu operations."); } } }; return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting album menu"); } private List<Message> getSearchItems(CdjStatus.TrackSourceSlot slot, int sortOrder, String text, AtomicInteger count, Client client) throws IOException, InterruptedException, TimeoutException { if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) { try { final StringField textField = new StringField(text); Message response = client.menuRequest(Message.KnownType.SEARCH_MENU, Message.MenuIdentifier.MAIN_MENU, slot, new NumberField(sortOrder), new NumberField(textField.getSize()), textField, NumberField.WORD_0); final int actualCount = (int)response.getMenuResultsCount(); if (actualCount == Message.NO_MENU_RESULTS_AVAILABLE || actualCount == 0) { if (count != null) { count.set(0); } return Collections.emptyList(); } // Gather the requested number of search menu items if (count == null) { return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slot, CdjStatus.TrackType.REKORDBOX, response); } else { final int desiredCount = Math.min(count.get(), actualCount); count.set(actualCount); if (desiredCount < 1) { return Collections.emptyList(); } return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slot, CdjStatus.TrackType.REKORDBOX, 0, desiredCount); } } finally { client.unlockForMenuOperations(); } } else { throw new TimeoutException("Unable to lock player for menu operations."); } } public List<Message> requestSearchResultsFrom(final int player, final CdjStatus.TrackSourceSlot slot, final int sortOrder, final String text, final AtomicInteger count) throws Exception { ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() { @Override public List<Message> useClient(Client client) throws Exception { return getSearchItems(slot, sortOrder, text.toUpperCase(), count, client); } }; return ConnectionManager.getInstance().invokeWithClientSession(player, task, "performing search"); } private List<Message> getMoreSearchItems(final CdjStatus.TrackSourceSlot slot, final int sortOrder, final String text, final int offset, final int count, final Client client) throws IOException, InterruptedException, TimeoutException { if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) { try { final StringField textField = new StringField(text); Message response = client.menuRequest(Message.KnownType.SEARCH_MENU, Message.MenuIdentifier.MAIN_MENU, slot, new NumberField(sortOrder), new NumberField(textField.getSize()), textField, NumberField.WORD_0); final int actualCount = (int)response.getMenuResultsCount(); if (offset + count > actualCount) { throw new IllegalArgumentException("Cannot request items past the end of the menu."); } // Gather the requested search menu items return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slot, CdjStatus.TrackType.REKORDBOX, offset, count); } finally { client.unlockForMenuOperations(); } } else { throw new TimeoutException("Unable to lock player for menu operations."); } } public List<Message> requestMoreSearchResultsFrom(final int player, final CdjStatus.TrackSourceSlot slot, final int sortOrder, final String text, final int offset, final int count) throws Exception { ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() { @Override public List<Message> useClient(Client client) throws Exception { return getMoreSearchItems(slot, sortOrder, text.toUpperCase(), offset, count, client); } }; return ConnectionManager.getInstance().invokeWithClientSession(player, task, "performing search"); } /** * Holds the singleton instance of this class. */ private static final MenuLoader ourInstance = new MenuLoader(); /** * Get the singleton instance of this class. * * @return the only instance of this class which exists. */ public static MenuLoader getInstance() { return ourInstance; } /** * Prevent direct instantiation. */ private MenuLoader() { // Nothing to do. } }
package org.elasticgremlin.structure; import org.apache.commons.configuration.Configuration; import org.elasticgremlin.elasticservice.ElasticService; import org.elasticgremlin.elasticservice.Predicates; import org.elasticgremlin.process.optimize.ElasticOptimizationStrategy; import org.apache.tinkerpop.gremlin.process.computer.GraphComputer; import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategies; import org.apache.tinkerpop.gremlin.structure.*; import org.apache.tinkerpop.gremlin.structure.util.*; import org.elasticsearch.index.engine.DocumentAlreadyExistsException; import java.io.IOException; import java.util.Iterator; @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.CountTest", method = "g_V_repeatXoutX_timesX8X_count", reason = "Takes too much time. https://github.com/rmagen/elastic-gremlin/issues/21") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.CountTest", method = "g_V_repeatXoutX_timesX3X_count", reason = "Takes too much time. https://github.com/rmagen/elastic-gremlin/issues/21") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.structure.FeatureSupportTest$VertexPropertyFunctionalityTest", method = "shouldSupportNumericIdsIfNumericIdsAreGeneratedFromTheGraph", reason = "https://issues.apache.org/jira/browse/TINKERPOP3-695") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.structure.FeatureSupportTest$EdgeFunctionalityTest", method = "shouldSupportUserSuppliedIdsOfTypeUuid", reason = "https://issues.apache.org/jira/browse/TINKERPOP3-695") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.structure.FeatureSupportTest$EdgeFunctionalityTest", method = "shouldSupportUserSuppliedIdsOfTypeAny", reason = "https://issues.apache.org/jira/browse/TINKERPOP3-695") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.structure.FeatureSupportTest$EdgeFunctionalityTest", method = "shouldSupportUserSuppliedIdsOfTypeNumeric", reason = "https://issues.apache.org/jira/browse/TINKERPOP3-695") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.structure.FeatureSupportTest$VertexFunctionalityTest", method = "shouldSupportUserSuppliedIdsOfTypeUuid", reason = "https://issues.apache.org/jira/browse/TINKERPOP3-695") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.structure.FeatureSupportTest$VertexFunctionalityTest", method = "shouldSupportUserSuppliedIdsOfTypeAny", reason = "https://issues.apache.org/jira/browse/TINKERPOP3-695") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.structure.FeatureSupportTest$VertexFunctionalityTest", method = "shouldSupportUserSuppliedIdsOfTypeNumeric", reason = "https://issues.apache.org/jira/browse/TINKERPOP3-695") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.structure.io.IoTest", method = "shouldReadWriteModernToGryo", reason = "IoTest.assertId(IoTest.java:2362) doesn't call convertId. https://issues.apache.org/jira/browse/TINKERPOP3-695") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.structure.io.IoTest", method = "shouldReadWriteModernToGraphSON", reason = "IoTest.assertId(IoTest.java:2362) doesn't call convertId. https://issues.apache.org/jira/browse/TINKERPOP3-695") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.structure.io.IoTest", method = "shouldReadWriteModernToGryoToFileWithHelpers", reason = "IoTest.assertId(IoTest.java:2362) doesn't call convertId. https://issues.apache.org/jira/browse/TINKERPOP3-695") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.structure.io.IoTest", method = "shouldReadWriteClassicToGraphMLToFileWithHelpers", reason = "IoTest.assertId(IoTest.java:2362) doesn't call convertId. https://issues.apache.org/jira/browse/TINKERPOP3-695") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.structure.io.IoTest", method = "shouldMigrateGraphWithFloat", reason = "IoTest.assertId(IoTest.java:2362) doesn't call convertId. https://issues.apache.org/jira/browse/TINKERPOP3-695") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.structure.io.IoTest", method = "shouldMigrateGraph", reason = "IoTest.assertId(IoTest.java:2362) doesn't call convertId. https://issues.apache.org/jira/browse/TINKERPOP3-695") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.structure.io.IoTest", method = "shouldReadWriteClassicToGraphSON", reason = "IoTest.assertId(IoTest.java:2362) doesn't call convertId. https://issues.apache.org/jira/browse/TINKERPOP3-695") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.structure.io.IoTest", method = "shouldReadWriteClassicToGryo", reason = "IoTest.assertId(IoTest.java:2362) doesn't call convertId. https://issues.apache.org/jira/browse/TINKERPOP3-695") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.structure.io.IoTest", method = "shouldReadWriteModernToGraphSONWithHelpers", reason = "IoTest.assertId(IoTest.java:2362) doesn't call convertId. https://issues.apache.org/jira/browse/TINKERPOP3-695") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.structure.io.IoTest", method = "shouldReadGraphMLAnAllSupportedDataTypes", reason = "https://github.com/rmagen/elastic-gremlin/issues/52") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.structure.io.IoTest", method = "shouldReadWriteVertexWithBOTHEdgesToGraphSONWithTypes", reason = "https://github.com/rmagen/elastic-gremlin/issues/52") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.structure.io.IoTest", method = "shouldReadGraphML", reason = "https://github.com/rmagen/elastic-gremlin/issues/52") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.structure.io.IoTest", method = "shouldReadLegacyGraphSON", reason = "https://github.com/rmagen/elastic-gremlin/issues/52") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.structure.io.IoTest", method = "shouldReadGraphMLUnorderedElements", reason = "https://github.com/rmagen/elastic-gremlin/issues/52") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.structure.GraphConstructionTest", method = "shouldConstructAnEmptyGraph", reason = "need to investigate...") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.ProfileTest$Traversal", method = "g_V_sideEffectXThread_sleepX10XX_sideEffectXThread_sleepX5XX_profile", reason = "need to investigate...") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.SubgraphTest$Traversal", method = "g_V_withSideEffectXsgX_repeatXbothEXcreatedX_subgraphXsgX_outVX_timesX5X_name_dedup", reason = "need to investigate...") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.SubgraphTest$Traversal", method = "g_V_withSideEffectXsgX_outEXknowsX_subgraphXsgX_name_capXsgX", reason = "need to investigate...") @Graph.OptIn(Graph.OptIn.SUITE_STRUCTURE_STANDARD) @Graph.OptIn(Graph.OptIn.SUITE_STRUCTURE_PERFORMANCE) @Graph.OptIn(Graph.OptIn.SUITE_PROCESS_STANDARD) public class ElasticGraph implements Graph { static { TraversalStrategies.GlobalCache.registerStrategies(ElasticGraph.class, TraversalStrategies.GlobalCache.getStrategies(Graph.class).clone().addStrategies(ElasticOptimizationStrategy.instance())); } //for testSuite public static ElasticGraph open(final Configuration configuration) throws IOException { return new ElasticGraph(configuration); } private ElasticFeatures features = new ElasticFeatures(); private final Configuration configuration; public final ElasticService elasticService; public ElasticGraph(Configuration configuration) throws IOException { this.configuration = configuration; configuration.setProperty(Graph.GRAPH, ElasticGraph.class.getName()); elasticService = new ElasticService(this, configuration); } @Override public Configuration configuration() { return this.configuration; } @Override public String toString() { return StringFactory.graphString(this, elasticService.toString()); } @Override public void close() { elasticService.close(); } @Override public Features features() { return features; } @Override public Transaction tx() { throw Exceptions.transactionsNotSupported(); } @Override public Variables variables() { throw Exceptions.variablesNotSupported(); } @Override public <C extends GraphComputer> C compute(Class<C> graphComputerClass) throws IllegalArgumentException { throw Exceptions.graphComputerNotSupported(); } @Override public GraphComputer compute() throws IllegalArgumentException { throw Exceptions.graphComputerNotSupported(); } @Override public Iterator<Vertex> vertices(Object... vertexIds) { if (vertexIds == null || vertexIds.length == 0) return elasticService.searchVertices(new Predicates()); return elasticService.getVertices(null,null,vertexIds); } @Override public Iterator<Edge> edges(Object... edgeIds) { if (edgeIds == null || edgeIds.length == 0) return elasticService.searchEdges(new Predicates(), null); return elasticService.getEdges(null, null, edgeIds); } @Override public Vertex addVertex(final Object... keyValues) { ElementHelper.legalPropertyKeyValueArray(keyValues); Object idValue = ElementHelper.getIdValue(keyValues).orElse(null); final String label = ElementHelper.getLabelValue(keyValues).orElse(Vertex.DEFAULT_LABEL); Vertex v = new ElasticVertex(idValue, label, keyValues, this, false); try { elasticService.addElement(v, true); } catch (DocumentAlreadyExistsException ex) { throw Graph.Exceptions.vertexWithIdAlreadyExists(idValue); } return v; } }
package org.gbif.metrics.tile; import org.gbif.metrics.cube.tile.density.DensityCube; import org.gbif.metrics.cube.tile.density.DensityTile; import org.gbif.metrics.cube.tile.density.Layer; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; import java.util.zip.GZIPOutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.common.base.Optional; import com.google.common.collect.Lists; import com.google.inject.Inject; import com.google.inject.Singleton; import com.urbanairship.datacube.DataCubeIo; import com.yammer.metrics.Metrics; import com.yammer.metrics.core.Meter; import com.yammer.metrics.core.Timer; import com.yammer.metrics.core.TimerContext; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.node.ObjectNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A simple tile rendering servlet that sources it's data from a data cube. */ @SuppressWarnings("serial") @Singleton public class DensityTileRenderer extends CubeTileRenderer { private static final Logger LOG = LoggerFactory.getLogger(DensityTileRenderer.class); private static final String TILE_CUBE_AS_JSON_SUFFIX = ".tcjson"; private static final String JSON_SUFFIX = ".json"; private static final ObjectMapper MAPPER = new ObjectMapper(); // allow monitoring of cube lookup, rendering speed and the throughput per second private final Timer pngRenderTimer = Metrics.newTimer(DensityTileRenderer.class, "pngRenderDuration", TimeUnit.MILLISECONDS, TimeUnit.SECONDS); private final Timer tcJsonRenderTimer = Metrics.newTimer(DensityTileRenderer.class, "tileCubeJsonRenderDuration", TimeUnit.MILLISECONDS, TimeUnit.SECONDS); private final Meter requests = Metrics.newMeter(DensityTileRenderer.class, "requests", "requests", TimeUnit.SECONDS); @Inject public DensityTileRenderer(DataCubeIo<DensityTile> cubeIo) { super(cubeIo); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { requests.mark(); // as a tile server, we support cross domain requests resp.setHeader("Access-Control-Allow-Origin", "*"); resp.setHeader("Access-Control-Allow-Headers", "X-Requested-With, X-Prototype-Version, X-CSRF-Token"); resp.setHeader("Cache-Control", "public,max-age=60"); // encourage a 60 second caching by everybody if (req.getRequestURI().endsWith(TILE_CUBE_AS_JSON_SUFFIX)) { renderTileCubeAsJson(req, resp); } else if (req.getRequestURI().endsWith(JSON_SUFFIX)) { renderMetadata(req, resp); } else { renderPNG(req, resp); } } protected void renderPNG(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setHeader("Content-Type", "image/png"); try { Optional<DensityTile> tile = getTile(req, DensityCube.INSTANCE); if (tile.isPresent()) { // add a header to help in debugging issues resp.setHeader("X-GBIF-Total-Count", String.valueOf(accumulate(tile.get()))); final TimerContext context = pngRenderTimer.time(); try { String[] layerStrings = req.getParameterValues("layer"); List<Layer> l = Lists.newArrayList(); if (layerStrings != null) { for (String ls : layerStrings) { try { l.add(Layer.valueOf(ls)); LOG.debug("Layer requested: {}", Layer.valueOf(ls)); } catch (Exception e) { LOG.warn("Invalid layer supplied, ignoring: " + ls); } } } else { LOG.debug("No layers returned, merging all layers"); } // determine if there is a named palette ColorPalette p = DensityColorPaletteFactory.YELLOWS_REDS; String paletteName = req.getParameter("palette"); if (paletteName != null) { try { p = NamedPalette.valueOf(paletteName).getPalette(); } catch (Exception e) { } } else if (req.getParameter("colors") != null) { p = DensityColorPaletteFactory.build(req.getParameter("colors")); } else if (req.getParameter("saturation") != null) { Float hue = extractFloat(req, "hue", false); if (hue!=null) { p = new HSBPalette(hue); } else { p = new HSBPalette(); } } PNGWriter.write(tile.get(), resp.getOutputStream(), extractInt(req, REQ_Z, true), p, l.toArray(new Layer[] {})); } finally { context.stop(); } } else { resp.getOutputStream().write(PNGWriter.EMPTY_TILE); } } catch (IllegalArgumentException e) { // If we couldn't get the content from the request resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } catch (Exception e) { // We are unable to get or render the tile LOG.error(e.getMessage(), e); resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Tile server is out of action, please try later"); } resp.flushBuffer(); } /** * Accumulates the count represented by the tile. */ private int accumulate(DensityTile tile) { int total = 0; for (Entry<Layer, Map<Integer, Integer>> e : tile.layers().entrySet()) { for (Integer count : e.getValue().values()) { total += count; } } return total; } protected void renderTileCubeAsJson(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setHeader("Content-Type", "application/json"); try { Optional<DensityTile> tile = getTile(req, DensityCube.INSTANCE); if (tile.isPresent()) { resp.setHeader("X-GBIF-Total-Count", String.valueOf(accumulate(tile.get()))); final TimerContext context = tcJsonRenderTimer.time(); try { resp.setHeader("Content-Encoding", "gzip"); GZIPOutputStream os = new GZIPOutputStream(resp.getOutputStream()); TileCubesWriter.jsonNotation(tile.get(), os); os.flush(); } finally { context.stop(); } } else { resp.getOutputStream().write(TileCubesWriter.EMPTY_TILE_CUBE); } } catch (IllegalArgumentException e) { // If we couldn't get the content from the request resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } catch (Exception e) { // We are unable to get or render the tile LOG.error(e.getMessage(), e); resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Tile server is out of action, please try later"); } finally { resp.flushBuffer(); } } protected void renderMetadata(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // as a tile server, we support cross domain requests resp.setHeader("Access-Control-Allow-Origin", "*"); resp.setHeader("Access-Control-Allow-Headers", "X-Requested-With, X-Prototype-Version, X-CSRF-Token"); resp.setHeader("Cache-Control", "public,max-age=60"); // encourage a 60 second caching by everybody resp.setHeader("Content-Type", "application/json"); Optional<DensityTile> tile = getTile(req, DensityCube.INSTANCE); int count = 0; // note: set to opposite extremes to allow efficient comparison double minimumLatitude = 90.0; double minimumLongitude = 180.0; double maximumLatitude = -90.0; double maximumLongitude = -180.0; if (tile.isPresent()) { DensityTile densityTile = tile.get(); // scan over all layers, accumulating the total and extracting the extents for (Map.Entry<Layer, Map<Integer, Integer>> e : densityTile.layers().entrySet()) { for (Map.Entry<Integer, Integer> pixels : e.getValue().entrySet()) { count += pixels.getValue(); // get the pixel and determine the lat and lng for the pixel int pixel = pixels.getKey(); int pixelX = pixel % DensityTile.TILE_SIZE; int pixelY = (int) Math.floor(pixel / DensityTile.TILE_SIZE); double lat = pixelYToLatitude(pixelY, extractInt(req, REQ_Z, true)); double lng = pixelXToLongitude(pixelX, extractInt(req, REQ_Z, true)); minimumLatitude = minimumLatitude < lat ? minimumLatitude : lat; minimumLongitude = minimumLongitude < lng ? minimumLongitude : lng; maximumLatitude = maximumLatitude > lat ? maximumLatitude : lat; maximumLongitude = maximumLongitude > lng ? maximumLongitude : lng; } } } ObjectNode node = MAPPER.createObjectNode(); node.put("count", count); node.put("minimumLatitude", minimumLatitude); node.put("minimumLongitude", minimumLongitude); node.put("maximumLatitude", maximumLatitude); node.put("maximumLongitude", maximumLongitude); MAPPER.writeValue(resp.getOutputStream(), node); resp.flushBuffer(); } public static double pixelYToLatitude(double pixelY, int zoom) { double y = 0.5 - (pixelY / ((long) DensityTile.TILE_SIZE << zoom)); return 90 - 360 * Math.atan(Math.exp(-y * 2 * Math.PI)) / Math.PI; } public static double pixelXToLongitude(double pixelX, int zoom) { return 360 * ((pixelX / ((long) DensityTile.TILE_SIZE << zoom)) - 0.5); } }
package org.jabref.gui.fieldeditors; import javafx.fxml.FXML; import javafx.scene.Parent; import javafx.scene.layout.HBox; import org.jabref.gui.autocompleter.AutoCompleteSuggestionProvider; import org.jabref.gui.autocompleter.AutoCompletionTextInputBinding; import org.jabref.gui.fieldeditors.contextmenu.EditorMenus; import org.jabref.logic.integrity.FieldCheckers; import org.jabref.logic.journals.JournalAbbreviationLoader; import org.jabref.model.entry.BibEntry; import org.jabref.preferences.JabRefPreferences; import com.airhacks.afterburner.views.ViewLoader; public class JournalEditor extends HBox implements FieldEditorFX { @FXML private JournalEditorViewModel viewModel; @FXML private EditorTextArea textArea; public JournalEditor(String fieldName, JournalAbbreviationLoader journalAbbreviationLoader, JabRefPreferences preferences, AutoCompleteSuggestionProvider<?> suggestionProvider, FieldCheckers fieldCheckers) { this.viewModel = new JournalEditorViewModel(fieldName, suggestionProvider, journalAbbreviationLoader, preferences.getJournalAbbreviationPreferences(), fieldCheckers); ViewLoader.view(this) .root(this) .load(); textArea.textProperty().bindBidirectional(viewModel.textProperty()); textArea.addToContextMenu(EditorMenus.getDefaultMenu(textArea)); AutoCompletionTextInputBinding.autoComplete(textArea, viewModel::complete); new EditorValidator(preferences).configureValidation(viewModel.getFieldValidator().getValidationStatus(), textArea); } public JournalEditorViewModel getViewModel() { return viewModel; } @Override public void bindToEntry(BibEntry entry) { viewModel.bindToEntry(entry); } @Override public Parent getNode() { return this; } @FXML private void toggleAbbreviation() { viewModel.toggleAbbreviation(); } }
package org.java_websocket.server; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; import java.nio.channels.CancelledKeyException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; 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.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.java_websocket.SocketChannelIOHelper; import org.java_websocket.WebSocket; import org.java_websocket.WebSocketAdapter; import org.java_websocket.WebSocketFactory; import org.java_websocket.WebSocketImpl; import org.java_websocket.WrappedByteChannel; import org.java_websocket.drafts.Draft; import org.java_websocket.framing.CloseFrame; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.Handshakedata; /** * <tt>WebSocketServer</tt> is an abstract class that only takes care of the * HTTP handshake portion of WebSockets. It's up to a subclass to add * functionality/purpose to the server. * */ public abstract class WebSocketServer extends WebSocketAdapter implements Runnable { public static int DECODERS = Runtime.getRuntime().availableProcessors(); /** * Holds the list of active WebSocket connections. "Active" means WebSocket * handshake is complete and socket can be written to, or read from. */ private final Collection<WebSocket> connections; /** * The port number that this WebSocket server should listen on. Default is * WebSocket.DEFAULT_PORT. */ private final InetSocketAddress address; /** * The socket channel for this WebSocket server. */ private ServerSocketChannel server; /** * The 'Selector' used to get event keys from the underlying socket. */ private Selector selector; /** * The Draft of the WebSocket protocol the Server is adhering to. */ private List<Draft> drafts; private Thread selectorthread; private volatile AtomicBoolean isclosed = new AtomicBoolean( false ); private List<WebSocketWorker> decoders; private List<WebSocketImpl> iqueue; private BlockingQueue<ByteBuffer> buffers; private int queueinvokes = 0; private AtomicInteger queuesize = new AtomicInteger( 0 ); private WebSocketServerFactory wsf = new DefaultWebSocketServerFactory(); /** * Creates a WebSocketServer that will attempt to * listen on port <var>WebSocket.DEFAULT_PORT</var>. * * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here */ public WebSocketServer() throws UnknownHostException { this( new InetSocketAddress( WebSocket.DEFAULT_PORT ), DECODERS, null ); } /** * Creates a WebSocketServer that will attempt to bind/listen on the given <var>address</var>. * * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here */ public WebSocketServer( InetSocketAddress address ) { this( address, DECODERS, null ); } /** * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here */ public WebSocketServer( InetSocketAddress address , int decoders ) { this( address, decoders, null ); } /** * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here */ public WebSocketServer( InetSocketAddress address , List<Draft> drafts ) { this( address, DECODERS, drafts ); } /** * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here */ public WebSocketServer( InetSocketAddress address , int decodercount , List<Draft> drafts ) { this( address, decodercount, drafts, new HashSet<WebSocket>() ); } public WebSocketServer( InetSocketAddress address , int decodercount , List<Draft> drafts , Collection<WebSocket> connectionscontainer ) { if( address == null || decodercount < 1 || connectionscontainer == null ) { throw new IllegalArgumentException( "address and connectionscontainer must not be null and you need at least 1 decoder" ); } if( drafts == null ) this.drafts = Collections.emptyList(); else this.drafts = drafts; this.address = address; this.connections = connectionscontainer; iqueue = new LinkedList<WebSocketImpl>(); decoders = new ArrayList<WebSocketWorker>( decodercount ); buffers = new LinkedBlockingQueue<ByteBuffer>(); for( int i = 0 ; i < decodercount ; i++ ) { WebSocketWorker ex = new WebSocketWorker(); decoders.add( ex ); ex.start(); } } public void start() { if( selectorthread != null ) throw new IllegalStateException( getClass().getName() + " can only be started once." ); new Thread( this ).start();; } /** * Closes all connected clients sockets, then closes the underlying * ServerSocketChannel, effectively killing the server socket selectorthread, * freeing the port the server was bound to and stops all internal workerthreads. * * If this method is called before the server is started it will never start. * * @param timeout * Specifies how many milliseconds shall pass between initiating the close handshakes with the connected clients and closing the servers socket channel. * * @throws IOException * When {@link ServerSocketChannel}.close throws an IOException * @throws InterruptedException */ public void stop( int timeout ) throws IOException , InterruptedException { if( !isclosed.compareAndSet( false, true ) ) { return; } synchronized ( connections ) { for( WebSocket ws : connections ) { ws.close( CloseFrame.GOING_AWAY ); } } synchronized ( this ) { if( selectorthread != null ) { if( Thread.currentThread() != selectorthread ) { } if( selectorthread != Thread.currentThread() ) { selectorthread.interrupt(); selectorthread.join(); } } if( decoders != null ) { for( WebSocketWorker w : decoders ) { w.interrupt(); } } if( server != null ) { server.close(); } } } public void stop() throws IOException , InterruptedException { stop( 0 ); } /** * Returns a WebSocket[] of currently connected clients. * Its iterators will be failfast and its not judicious * to modify it. * * @return The currently connected clients. */ public Collection<WebSocket> connections() { return this.connections; } public InetSocketAddress getAddress() { return this.address; } /** * Gets the port number that this server listens on. * * @return The port number. */ public int getPort() { int port = getAddress().getPort(); if( port == 0 && server != null ) { port = server.socket().getLocalPort(); } return port; } public List<Draft> getDraft() { return Collections.unmodifiableList( drafts ); } // Runnable IMPLEMENTATION ///////////////////////////////////////////////// public void run() { synchronized ( this ) { if( selectorthread != null ) throw new IllegalStateException( getClass().getName() + " can only be started once." ); selectorthread = Thread.currentThread(); if( isclosed.get() ) { return; } } selectorthread.setName( "WebsocketSelector" + selectorthread.getId() ); try { server = ServerSocketChannel.open(); server.configureBlocking( false ); ServerSocket socket = server.socket(); socket.setReceiveBufferSize( WebSocketImpl.RCVBUF ); socket.bind( address ); selector = Selector.open(); server.register( selector, server.validOps() ); } catch ( IOException ex ) { handleFatal( null, ex ); return; } try { while ( !selectorthread.isInterrupted() ) { SelectionKey key = null; WebSocketImpl conn = null; try { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); if( !key.isValid() ) { // Object o = key.attachment(); continue; } if( key.isAcceptable() ) { if( !onConnect( key ) ) { key.cancel(); continue; } SocketChannel channel = server.accept(); channel.configureBlocking( false ); WebSocketImpl w = wsf.createWebSocket( this, drafts, channel.socket() ); w.key = channel.register( selector, SelectionKey.OP_READ, w ); w.channel = wsf.wrapChannel( channel, w.key ); i.remove(); allocateBuffers( w ); continue; } if( key.isReadable() ) { conn = (WebSocketImpl) key.attachment(); ByteBuffer buf = takeBuffer(); try { if( SocketChannelIOHelper.read( buf, conn, (ByteChannel) conn.channel ) ) { conn.inQueue.put( buf ); queue( conn ); i.remove(); if( conn.channel instanceof WrappedByteChannel ) { if( ( (WrappedByteChannel) conn.channel ).isNeedRead() ) { iqueue.add( conn ); } } } else { pushBuffer( buf ); } } catch ( IOException e ) { pushBuffer( buf ); throw e; } catch ( RuntimeException e ) { pushBuffer( buf ); throw e; } } if( key.isWritable() ) { conn = (WebSocketImpl) key.attachment(); if( SocketChannelIOHelper.batch( conn, (ByteChannel) conn.channel ) ) { if( key.isValid() ) key.interestOps( SelectionKey.OP_READ ); } } } while ( !iqueue.isEmpty() ) { conn = iqueue.remove( 0 ); WrappedByteChannel c = ( (WrappedByteChannel) conn.channel ); ByteBuffer buf = takeBuffer(); try { if( SocketChannelIOHelper.readMore( buf, conn, c ) ) iqueue.add( conn ); conn.inQueue.put( buf ); queue( conn ); } finally { pushBuffer( buf ); } } } catch ( CancelledKeyException e ) { // an other thread may cancel the key } catch ( IOException ex ) { if( key != null ) key.cancel(); handleIOException( conn, ex ); } catch ( InterruptedException e ) { return;// FIXME controlled shutdown } } } catch ( RuntimeException e ) { // should hopefully never occur handleFatal( null, e ); } } protected void allocateBuffers( WebSocket c ) throws InterruptedException { if( queuesize.get() >= 2 * decoders.size() + 1 ) { return; } queuesize.incrementAndGet(); buffers.put( createBuffer() ); } protected void releaseBuffers( WebSocket c ) throws InterruptedException { // queuesize.decrementAndGet(); // takeBuffer(); } public ByteBuffer createBuffer() { return ByteBuffer.allocate( WebSocketImpl.RCVBUF ); } private void queue( WebSocketImpl ws ) throws InterruptedException { if( ws.workerThread == null ) { ws.workerThread = decoders.get( queueinvokes % decoders.size() ); queueinvokes++; } ws.workerThread.put( ws ); } private ByteBuffer takeBuffer() throws InterruptedException { return buffers.take(); } private void pushBuffer( ByteBuffer buf ) throws InterruptedException { if( buffers.size() > queuesize.intValue() ) return; buffers.put( buf ); } private void handleIOException( WebSocket conn, IOException ex ) { onWebsocketError( conn, ex );// conn may be null here if( conn != null ) { conn.closeConnection( CloseFrame.ABNORMAL_CLOSE, ex.getMessage() ); } } private void handleFatal( WebSocket conn, Exception e ) { onError( conn, e ); try { stop(); } catch ( IOException e1 ) { onError( null, e1 ); } catch ( InterruptedException e1 ) { Thread.currentThread().interrupt(); onError( null, e1 ); } } protected String getFlashSecurityPolicy() { return "<cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"" + getPort() + "\" /></cross-domain-policy>"; } @Override public final void onWebsocketMessage( WebSocket conn, String message ) { onMessage( conn, message ); } @Override public final void onWebsocketMessage( WebSocket conn, ByteBuffer blob ) { onMessage( conn, blob ); } @Override public final void onWebsocketOpen( WebSocket conn, Handshakedata handshake ) { if( addConnection( conn ) ) { onOpen( conn, (ClientHandshake) handshake ); } } @Override public final void onWebsocketClose( WebSocket conn, int code, String reason, boolean remote ) { selector.wakeup(); try { if( removeConnection( conn ) ) { onClose( conn, code, reason, remote ); } } finally { try { releaseBuffers( conn ); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } } } /** * This method performs remove operations on the connection and therefore also gives control over whether the operation shall be synchronized * <p> * {@link #WebSocketServer(InetSocketAddress, int, List, Collection)} allows to specify a collection which will be used to store current connections in.<br> * Depending on the type on the connection, modifications of that collection may have to be synchronized. **/ protected boolean removeConnection( WebSocket ws ) { synchronized ( connections ) { return this.connections.remove( ws ); } } /** @see #removeConnection(WebSocket) */ protected boolean addConnection( WebSocket ws ) { synchronized ( connections ) { return this.connections.add( ws ); } } /** * @param conn * may be null if the error does not belong to a single connection */ @Override public final void onWebsocketError( WebSocket conn, Exception ex ) { onError( conn, ex ); } @Override public final void onWriteDemand( WebSocket w ) { WebSocketImpl conn = (WebSocketImpl) w; conn.key.interestOps( SelectionKey.OP_READ | SelectionKey.OP_WRITE ); selector.wakeup(); } @Override public void onWebsocketCloseInitiated( WebSocket conn, int code, String reason ) { onCloseInitiated( conn, code, reason ); } @Override public void onWebsocketClosing( WebSocket conn, int code, String reason, boolean remote ) { onClosing( conn, code, reason, remote ); } public void onCloseInitiated( WebSocket conn, int code, String reason ) { } public void onClosing( WebSocket conn, int code, String reason, boolean remote ) { } public final void setWebSocketFactory( WebSocketServerFactory wsf ) { this.wsf = wsf; } public final WebSocketFactory getWebSocketFactory() { return wsf; } /** * Returns whether a new connection shall be accepted or not.<br> * Therefore method is well suited to implement some kind of connection limitation.<br> * * @see {@link #onOpen(WebSocket, ClientHandshake)}, {@link #onWebsocketHandshakeReceivedAsServer(WebSocket, Draft, ClientHandshake)} **/ protected boolean onConnect( SelectionKey key ) { return true; } /** Called after an opening handshake has been performed and the given websocket is ready to be written on. */ public abstract void onOpen( WebSocket conn, ClientHandshake handshake ); /** * Called after the websocket connection has been closed. * * @param code * The codes can be looked up here: {@link CloseFrame} * @param reason * Additional information string * @param remote * Returns whether or not the closing of the connection was initiated by the remote host. **/ public abstract void onClose( WebSocket conn, int code, String reason, boolean remote ); /** * Callback for string messages received from the remote host * * @see #onMessage(WebSocket, ByteBuffer) **/ public abstract void onMessage( WebSocket conn, String message ); /** * Called when errors occurs. If an error causes the websocket connection to fail {@link #onClose(WebSocket, int, String, boolean)} will be called additionally.<br> * This method will be called primarily because of IO or protocol errors.<br> * If the given exception is an RuntimeException that probably means that you encountered a bug.<br> * * @param con * Can be null if there error does not belong to one specific websocket. For example if the servers port could not be bound. **/ public abstract void onError( WebSocket conn, Exception ex ); /** * Callback for binary messages received from the remote host * * @see #onMessage(WebSocket, String) **/ public void onMessage( WebSocket conn, ByteBuffer message ) { }; public class WebSocketWorker extends Thread { private BlockingQueue<WebSocketImpl> iqueue; public WebSocketWorker() { iqueue = new LinkedBlockingQueue<WebSocketImpl>(); setName( "WebSocketWorker-" + getId() ); setUncaughtExceptionHandler( new UncaughtExceptionHandler() { @Override public void uncaughtException( Thread t, Throwable e ) { getDefaultUncaughtExceptionHandler().uncaughtException( t, e ); } } ); } public void put( WebSocketImpl ws ) throws InterruptedException { iqueue.put( ws ); } @Override public void run() { WebSocketImpl ws = null; try { while ( true ) { ByteBuffer buf = null; ws = iqueue.take(); buf = ws.inQueue.poll(); assert ( buf != null ); try { ws.decode( buf ); } finally { pushBuffer( buf ); } } } catch ( InterruptedException e ) { } catch ( RuntimeException e ) { handleFatal( ws, e ); } } } public interface WebSocketServerFactory extends WebSocketFactory { @Override public WebSocketImpl createWebSocket( WebSocketAdapter a, Draft d, Socket s ); public WebSocketImpl createWebSocket( WebSocketAdapter a, List<Draft> drafts, Socket s ); /** * Allows to wrap the Socketchannel( key.channel() ) to insert a protocol layer( like ssl or proxy authentication) beyond the ws layer. * * @param key * a SelectionKey of an open SocketChannel. * @return The channel on which the read and write operations will be performed.<br> */ public ByteChannel wrapChannel( SocketChannel channel, SelectionKey key ) throws IOException; } }
package org.jtrfp.trcl.beh; import java.lang.ref.WeakReference; import org.apache.commons.math3.geometry.euclidean.threed.Rotation; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.jtrfp.trcl.AbstractSubmitter; import org.jtrfp.trcl.Submitter; import org.jtrfp.trcl.core.TR; import org.jtrfp.trcl.gpu.BasicModelSource; import org.jtrfp.trcl.math.Vect3D; import org.jtrfp.trcl.obj.DEFObject; import org.jtrfp.trcl.obj.DEFObject.HitBox; import org.jtrfp.trcl.obj.WorldObject; public class CollidesWithDEFObjects extends Behavior implements CollisionBehavior { private final double boundingRadius; private WeakReference<DEFObject> otherDEF; private final double [] workTriplet = new double[3]; public CollidesWithDEFObjects(double boundingRadius){ this.boundingRadius=boundingRadius; } @Override public void proposeCollision(WorldObject other){ if(other instanceof DEFObject){ final DEFObject def = (DEFObject)other; final HitBox [] hitBoxes = def.getHitBoxes(); final WorldObject parent = getParent(); final double [] defPos = def.getPosition(); final double [] pPos = parent.getPosition(); otherDEF=new WeakReference<DEFObject>(def); if(hitBoxes == null){// No custom hitboxes final Vector3D max = def.getModel().getMaximumVertexDims(), min = def.getModel().getMinimumVertexDims(); if(boxCollision( parent.getPositionWithOffset(), other.getPositionWithOffset(), min,max, boundingRadius, other.getHeading(),other.getTop())) parent.probeForBehaviors(sub, DEFObjectCollisionListener.class); }else{//Custom hitboxes boolean doCollision = false; BasicModelSource mSource = def.getModelSource(); if(mSource == null) throw new NullPointerException("DEF's model source intolerably null."); for(HitBox box:hitBoxes){ final double limit = boundingRadius+box.getSize(); final double [] vPos = Vect3D.add(mSource.getVertex(box.getVertexID()),defPos,workTriplet); Vect3D.subtract(workTriplet, pPos, vPos); Vect3D.abs(workTriplet, workTriplet); boolean localDoCollision = true; for(int i=0; i<3; i++) localDoCollision &= TR.rolloverDistance(workTriplet[i]) < limit; doCollision |= localDoCollision; }//end for(hitBoxes) if(doCollision) parent.probeForBehaviors(sub, DEFObjectCollisionListener.class); }//end if(custom hitboxes) }//end if(DEFObject) }//end _proposeCollision() private static boolean boxCollision(double [] testSpherePos, double [] boxPos, Vector3D min, Vector3D max, double boundingRadius, Vector3D boxHeading, Vector3D boxTop){ //Calculate other object to parent's space. Vector3D relPosThis = new Vector3D(testSpherePos). subtract(new Vector3D(boxPos)); //Factor in rollover relPosThis = new Vector3D( TR.rolloverDistance(relPosThis.getX()), TR.rolloverDistance(relPosThis.getY()), TR.rolloverDistance(relPosThis.getZ()) ); Rotation rot = new Rotation(Vector3D.PLUS_K, Vector3D.PLUS_J,boxHeading,boxTop); //Rotate the other position relative to the parent's heading/top. relPosThis = rot.applyInverseTo(relPosThis); final boolean withinRange = relPosThis.getX()<max.getX() + boundingRadius && relPosThis.getX()>min.getX() - boundingRadius && relPosThis.getY()<max.getY() + boundingRadius && relPosThis.getY()>min.getY() - boundingRadius && relPosThis.getZ()<max.getZ() + boundingRadius && relPosThis.getZ()>min.getZ() - boundingRadius; return withinRange; }//end boxCollision(...) private final Submitter<DEFObjectCollisionListener> sub = new AbstractSubmitter<DEFObjectCollisionListener>(){ @Override public void submit(DEFObjectCollisionListener l){ DEFObject other = otherDEF.get(); if(other!=null)l.collidedWithDEFObject(other); }//end submit(...) };//end Submitter }
package org.lantern.kscope; import java.net.InetSocketAddress; import java.net.URI; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.kaleidoscope.BasicTrustGraphAdvertisement; import org.kaleidoscope.BasicTrustGraphNodeId; import org.kaleidoscope.RandomRoutingTable; import org.kaleidoscope.TrustGraphNode; import org.kaleidoscope.TrustGraphNodeId; import org.lantern.JsonUtils; import org.lantern.LanternTrustStore; import org.lantern.LanternUtils; import org.lantern.ProxyTracker; import org.lantern.XmppHandler; import org.lantern.event.Events; import org.lantern.event.KscopeAdEvent; import org.lantern.state.FriendsHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.google.inject.Singleton; @Singleton public class DefaultKscopeAdHandler implements KscopeAdHandler { private final Logger log = LoggerFactory.getLogger(getClass()); private final XmppHandler xmppHandler; /** * Map of kscope advertisements for which we are awaiting corresponding * certificates. */ private final ConcurrentHashMap<URI, LanternKscopeAdvertisement> awaitingCerts = new ConcurrentHashMap<URI, LanternKscopeAdvertisement>(); private final Set<LanternKscopeAdvertisement> processedAds = new HashSet<LanternKscopeAdvertisement>(); private final ProxyTracker proxyTracker; private final LanternTrustStore trustStore; private final RandomRoutingTable routingTable; private final FriendsHandler friendsHandler; @Inject public DefaultKscopeAdHandler(final ProxyTracker proxyTracker, final LanternTrustStore trustStore, final RandomRoutingTable routingTable, final XmppHandler xmppHandler, final FriendsHandler friendsHandler) { this.proxyTracker = proxyTracker; this.trustStore = trustStore; this.routingTable = routingTable; this.xmppHandler = xmppHandler; this.friendsHandler = friendsHandler; } @Override public boolean handleAd(final String from, final LanternKscopeAdvertisement ad) { // output a bell character to call more attention log.debug("\u0007*** got kscope ad from {} for {}", from, ad.getJid()); Events.asyncEventBus().post(new KscopeAdEvent(ad)); //ignore kscope ads directly or indirectly from untrusted sources //(they might have been relayed via untrusted sources in the middle, //but there is nothing we can do about that) if (!this.friendsHandler.isFriend(ad.getJid())) { log.debug("Ignoring kscope add from non-friend"); return false; } // If the connection we received the kscope add on is rejected, ignore // the add. if (this.friendsHandler.isRejected(from)) { log.debug("Ignoring kscope add from rejected contact"); return false; } awaitingCerts.put(LanternUtils.newURI(ad.getJid()), ad); // do we want to relay this? int inboundTtl = ad.getTtl(); if(inboundTtl <= 0) { log.debug("End of the line for kscope ad for {} from {}.", ad.getJid(), from ); return true; } TrustGraphNodeId nid = new BasicTrustGraphNodeId(ad.getJid()); TrustGraphNodeId nextNid = routingTable.getNextHop(nid); if (nextNid == null) { // This will happen when we're not connected to any other peers, // for example. log.debug("Could not relay ad: Node ID not in routing table"); return true; } LanternKscopeAdvertisement relayAd = LanternKscopeAdvertisement.makeRelayAd(ad); final String relayAdPayload = JsonUtils.jsonify(relayAd); final BasicTrustGraphAdvertisement message = new BasicTrustGraphAdvertisement(nextNid, relayAdPayload, relayAd.getTtl() ); final TrustGraphNode tgn = new LanternTrustGraphNode(xmppHandler); tgn.sendAdvertisement(message, nextNid, relayAd.getTtl()); return true; } @Override public void onBase64Cert(final URI jid, final String base64Cert) { log.debug("Received cert for {}", jid); this.trustStore.addBase64Cert(jid, base64Cert); final LanternKscopeAdvertisement ad = awaitingCerts.remove(jid); if (ad != null) { log.debug("Adding proxy... {}", ad); InetSocketAddress address = ad.hasMappedEndpoint() ? LanternUtils.isa(ad.getAddress(), ad.getPort()) : null; this.proxyTracker.addProxy(jid, address); // Also add the local network advertisement in case they're on // the local network. this.proxyTracker.addProxy(jid, LanternUtils.isa(ad.getLocalAddress(), ad.getLocalPort())); processedAds.add(ad); } else { this.proxyTracker.addProxy(jid); } } }
package org.lightmare.jpa.datasource; /** * Configuration of jdbc driver * * @author levan * */ public class DriverConfig { private static final String ORACLE_DRIVER = "oracle.jdbc.OracleDriver"; private static final String MYSQL_DRIVER = "com.mysql.jdbc.Driver"; private static final String MSSQL_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; private static final String DB2_DRIVER = "com.ibm.db2.jcc.DB2Driver"; private static final String H2_DRIVER = "org.h2.Driver"; private static final String DERBY_DRIVER = "org.apache.derby.jdbc.EmbeddedDriver"; private static final String ORACLE_NAME = "oracle"; private static final String MYSQL_NAME = "mysql"; private static final String DB2_NAME = "db2"; private static final String MSSQL_NAME = "mssql"; private static final String H2_NAME = "h2"; private static final String DERBY_NAME = "derby"; public static String getDriverName(String name) { if (ORACLE_NAME.equals(name)) { return ORACLE_DRIVER; } else if (MYSQL_NAME.equals(name)) { return MYSQL_DRIVER; } else if (DB2_NAME.equals(name)) { return DB2_DRIVER; } else if (MSSQL_NAME.equals(name)) { return MSSQL_DRIVER; } else if (H2_NAME.equals(name)) { return H2_DRIVER; } else if (DERBY_NAME.equals(name)) { return DERBY_DRIVER; } else { return null; } } public static boolean isOracle(String name) { return ORACLE_DRIVER.equals(name); } public static boolean isMySQL(String name) { return MYSQL_DRIVER.equals(name); } public static boolean isDB2(String name) { return DB2_DRIVER.equals(name); } public static boolean isMsSQL(String name) { return MSSQL_DRIVER.equals(name); } public static boolean isH2(String name) { return H2_DRIVER.equals(name); } public static boolean isDerby(String name) { return DERBY_DRIVER.equals(name); } }
package org.lightmare.jpa.jta; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Stack; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.NotSupportedException; import javax.transaction.RollbackException; import javax.transaction.SystemException; import javax.transaction.UserTransaction; import org.lightmare.ejb.handlers.BeanHandler; import org.lightmare.utils.ObjectUtils; /** * {@link UserTransaction} implementation for jndi and ejb beans * * @author levan * */ public class UserTransactionImpl implements UserTransaction { private Stack<EntityTransaction> transactions; private Stack<EntityManager> ems; private Stack<EntityTransaction> requareNews; private Stack<EntityManager> requareNewEms; private Object caller; public UserTransactionImpl(EntityTransaction... transactions) { this.transactions = new Stack<EntityTransaction>(); if (ObjectUtils.available(transactions)) { addTransactions(transactions); } } private void beginAll() throws NotSupportedException, SystemException { for (EntityTransaction transaction : transactions) { transaction.begin(); } } @Override public void begin() throws NotSupportedException, SystemException { if (ObjectUtils.available(transactions)) { beginAll(); } } private void commit(EntityTransaction transaction) throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException { if (transaction.isActive()) { transaction.commit(); } } private void commitAll() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException { EntityTransaction transaction; while (ObjectUtils.notEmpty(transactions)) { transaction = transactions.pop(); commit(transaction); } } @Override public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException { try { if (ObjectUtils.available(transactions)) { commitAll(); } } finally { closeEntityManagers(); } } @Override public int getStatus() throws SystemException { int active = 0; if (ObjectUtils.available(transactions)) { for (EntityTransaction transaction : transactions) { boolean isActive = transaction.isActive(); active += isActive ? 1 : 0; } } if (ObjectUtils.available(requareNews)) { for (EntityTransaction transaction : requareNews) { boolean isActive = transaction.isActive(); active += isActive ? 1 : 0; } } return active; } private void rollback(EntityTransaction transaction) { if (transaction.isActive()) { transaction.rollback(); } } private void rollbackAll() throws IllegalStateException, SecurityException, SystemException { EntityTransaction transaction; while (ObjectUtils.notEmpty(transactions)) { transaction = transactions.pop(); rollback(transaction); } } @Override public void rollback() throws IllegalStateException, SecurityException, SystemException { try { if (ObjectUtils.available(transactions)) { rollbackAll(); } } finally { closeEntityManagers(); } } private void setRollbackOnly(EntityTransaction transaction) throws IllegalStateException, SystemException { if (transaction.isActive()) { transaction.setRollbackOnly(); } } private void setRollbackOnlyAll() throws IllegalStateException, SystemException { for (EntityTransaction transaction : transactions) { setRollbackOnly(transaction); } } @Override public void setRollbackOnly() throws IllegalStateException, SystemException { if (ObjectUtils.available(transactions)) { setRollbackOnlyAll(); } } @Override public void setTransactionTimeout(int time) throws SystemException { throw new UnsupportedOperationException( "Timeouts are not supported yet"); } private Stack<EntityTransaction> getNews() { if (requareNews == null) { requareNews = new Stack<EntityTransaction>(); } return requareNews; } private Stack<EntityManager> getNewEms() { if (requareNewEms == null) { requareNewEms = new Stack<EntityManager>(); } return requareNewEms; } /** * Check if {@link javax.ejb.TransactionAttributeType#REQUIRES_NEW} type * transactions stack is empty * * @return <code>boolean</code> */ private boolean checkNews() { boolean notEmpty = ObjectUtils.available(requareNews); return notEmpty; } /** * Check if {@link javax.ejb.TransactionAttributeType#REQUIRES_NEW} type * transactions referenced {@link EntityManager} stack is empty * * @return <code>boolean</code> */ private boolean checkNewEms() { boolean notEmpty = ObjectUtils.available(requareNewEms); return notEmpty; } /** * Adds new {@link EntityTransaction} for * {@link javax.ejb.TransactionAttributeType#REQUIRES_NEW} annotated bean * methods * * @param entityTransaction */ public void pushReqNew(EntityTransaction entityTransaction) { getNews().push(entityTransaction); } /** * Adds {@link EntityManager} to collection to close after * {@link javax.ejb.TransactionAttributeType#REQUIRES_NEW} type transactions * processing * * @param em */ public void pushReqNewEm(EntityManager em) { getNewEms().push(em); } public void commitReqNew() throws SecurityException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException, SystemException { try { if (checkNews()) { EntityTransaction entityTransaction = getNews().pop(); commit(entityTransaction); } } finally { closeReqNew(); } } private void closeReqNew() { if (checkNewEms()) { EntityManager em = getNewEms().pop(); if (em.isOpen()) { em.close(); } } } /** * Adds {@link EntityTransaction} to transactions {@link List} for further * processing * * @param transaction */ public void addTransaction(EntityTransaction transaction) { transactions.add(transaction); } /** * Adds {@link EntityTransaction}s to transactions {@link List} for further * processing * * @param transactions */ public void addTransactions(EntityTransaction... transactions) { Collections.addAll(this.transactions, transactions); } /** * Adds {@link EntityManager} to collection to close after transactions * processing * * @param em */ public void addEntityManager(EntityManager em) { if (ObjectUtils.notNull(em)) { if (ems == null) { ems = new Stack<EntityManager>(); } ems.push(em); } } /** * Adds {@link EntityManager}'s to collection to close after transactions * processing * * @param em */ public void addEntityManagers(Collection<EntityManager> ems) { if (ObjectUtils.available(ems)) { for (EntityManager em : ems) { addEntityManager(em); } } } private void closeEntityManager(EntityManager em) { if (em.isOpen()) { em.close(); } } private void closeAllEntityManagers() { EntityManager em; while (ObjectUtils.notEmpty(ems)) { em = ems.pop(); closeEntityManager(em); } } /** * Closes all contained {@link EntityManager}s */ public void closeEntityManagers() { if (ObjectUtils.available(ems)) { closeAllEntityManagers(); } } public boolean checkCaller(BeanHandler handler) { boolean check = ObjectUtils.notNull(caller); if (check) { check = caller.equals(handler.getBean()); } return check; } public void setCaller(BeanHandler handler) { caller = handler.getBean(); } public Object getCaller() { return caller; } }
package org.netmelody.jarnia.github; import org.netmelody.jarnia.HttpGetter; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import static com.google.common.collect.Iterables.find; public final class GithubFetcher { private final HttpGetter getter = new HttpGetter(); private final JsonParser jsonParser = new JsonParser(); public String fetchLatestShaFor(String owner, String repo, String branch) { final String url = String.format("https://api.github.com/repos/%s/%s/branches", owner, repo); final JsonArray branches = jsonParser.parse(getter.get(url)).getAsJsonArray(); return find(branches, isBranchNamed(branch)).getAsJsonObject().get("commit").getAsJsonObject().get("sha").getAsString(); } public Iterable<FileRef> fetchFilesFor(String owner, String repo, String sha) { final String url = String.format("https://api.github.com/repos/%s/%s/git/trees/%s?recursive=1", owner, repo, sha); final JsonArray nodes = jsonParser.parse(getter.get(url)).getAsJsonObject().get("tree").getAsJsonArray(); return Iterables.transform(Iterables.filter(nodes, blobs()), toFileRefs()); } private Predicate<JsonElement> isBranchNamed(final String branchName) { return new Predicate<JsonElement>() { @Override public boolean apply(JsonElement input) { return branchName.equals(input.getAsJsonObject().get("name").getAsString()); } }; } private Predicate<JsonElement> blobs() { return new Predicate<JsonElement>() { @Override public boolean apply(JsonElement input) { return "blob".equals(input.getAsJsonObject().get("type").getAsString()); } }; } private Function<JsonElement, FileRef> toFileRefs() { return new Function<JsonElement, FileRef>() { @Override public FileRef apply(JsonElement input) { final JsonObject node = input.getAsJsonObject(); return new FileRef(node.get("path").getAsString(), node.get("size").getAsInt()); } }; } public static final class FileRef { public final String path; public final int size; public FileRef(String path, int size) { this.path = path; this.size = size; } @Override public String toString() { return path + " <" + size + ">"; } } }
package org.numenta.nupic.research; import gnu.trove.set.hash.TIntHashSet; import org.numenta.nupic.data.SparseBinaryMatrix; import org.numenta.nupic.data.SparseDoubleMatrix; import org.numenta.nupic.data.SparseMatrix; import org.numenta.nupic.data.SparseObjectMatrix; import org.numenta.nupic.model.Column; import org.numenta.nupic.model.Lattice; public class SpatialLattice extends Lattice { private int potentialRadius = 16; private double potentialPct = 0.5; private boolean globalInhibition = false; private double localAreaDensity = -1.0; private double numActiveColumnsPerInhArea; private double stimulusThreshold = 0; private double synPermInactiveDec = 0.01; private double synPermActiveInc = 0.10; private double synPermConnected = 0.10; private double synPermBelowStimulusInc = synPermConnected / 10.0; private double minPctOverlapDutyCycle = 0.001; private double minPctActiveDutyCycle = 0.001; private double dutyCyclePeriod = 1000; private double maxBoost = 10.0; private int spVerbosity = 0; private int seed; private int numInputs = 1; //product of input dimensions private int numColumns = 1; //product of column dimensions //Extra parameter settings private double synPermMin = 0.0; private double synPermMax = 1.0; private double synPermTrimThreshold = synPermActiveInc / 2.0; private int updatePeriod = 50; private double initConnectedPct = 0.5; //Internal state private double version = 1.0; private int interationNum = 0; private int iterationLearnNum = 0; /** * Store the set of all inputs that are within each column's potential pool. * 'potentialPools' is a matrix, whose rows represent cortical columns, and * whose columns represent the input bits. if potentialPools[i][j] == 1, * then input bit 'j' is in column 'i's potential pool. A column can only be * connected to inputs in its potential pool. The indices refer to a * flattened version of both the inputs and columns. Namely, irrespective * of the topology of the inputs and columns, they are treated as being a * one dimensional array. Since a column is typically connected to only a * subset of the inputs, many of the entries in the matrix are 0. Therefore * the potentialPool matrix is stored using the SparseBinaryMatrix * class, to reduce memory footprint and computation time of algorithms that * require iterating over the data structure. */ private SparseObjectMatrix<int[]> potentialPools; /** * Initialize the permanences for each column. Similar to the * 'self._potentialPools', the permanences are stored in a matrix whose rows * represent the cortical columns, and whose columns represent the input * bits. If self._permanences[i][j] = 0.2, then the synapse connecting * cortical column 'i' to input bit 'j' has a permanence of 0.2. Here we * also use the SparseMatrix class to reduce the memory footprint and * computation time of algorithms that require iterating over the data * structure. This permanence matrix is only allowed to have non-zero * elements where the potential pool is non-zero. */ private SparseDoubleMatrix permanences; /** * Initialize a tiny random tie breaker. This is used to determine winning * columns where the overlaps are identical. */ private SparseDoubleMatrix tieBreaker; /** * 'self._connectedSynapses' is a similar matrix to 'self._permanences' * (rows represent cortical columns, columns represent input bits) whose * entries represent whether the cortical column is connected to the input * bit, i.e. its permanence value is greater than 'synPermConnected'. While * this information is readily available from the 'self._permanence' matrix, * it is stored separately for efficiency purposes. */ private SparseBinaryMatrix connectedSynapses; /** * Stores the number of connected synapses for each column. This is simply * a sum of each row of 'self._connectedSynapses'. again, while this * information is readily available from 'self._connectedSynapses', it is * stored separately for efficiency purposes. */ private int[] connectedCounts = new int[numColumns]; /** * The inhibition radius determines the size of a column's local * neighborhood. of a column. A cortical column must overcome the overlap * score of columns in his neighborhood in order to become actives. This * radius is updated every learning round. It grows and shrinks with the * average number of connected synapses per column. */ private int inhibitionRadius = 0; /** * Constructs a new {@code SpatialLattice} */ public SpatialLattice(Parameters p) { super(); if(p != null) { Parameters.apply(this, p); } memory = new SparseObjectMatrix<Column>(columnDimensions); inputMatrix = new SparseBinaryMatrix(inputDimensions); for(int i = 0;i < inputDimensions.length;i++) { numInputs *= inputDimensions[i]; } for(int i = 0;i < columnDimensions.length;i++) { numColumns *= columnDimensions[i]; } potentialPools = new SparseObjectMatrix<int[]>(new int[] { numColumns, numInputs } ); permanences = new SparseDoubleMatrix(new int[] { numColumns, numInputs } ); tieBreaker = new SparseDoubleMatrix(new int[] { numColumns, numInputs } ); for(int i = 0;i < numColumns;i++) { for(int j = 0;j < numInputs;j++) { tieBreaker.set(new int[] { i, j }, 0.01 * random.nextDouble()); } } /** * 'connectedSynapses' is a similar matrix to 'permanences' * (rows represent cortical columns, columns represent input bits) whose * entries represent whether the cortical column is connected to the input * bit, i.e. its permanence value is greater than 'synPermConnected'. While * this information is readily available from the 'permanences' matrix, * it is stored separately for efficiency purposes. */ connectedSynapses = new SparseBinaryMatrix(new int[] { numColumns, numInputs } ); connectedCounts = new int[numColumns]; // Initialize the set of permanence values for each column. Ensure that // each column is connected to enough input bits to allow it to be // activated. for(int i = 0;i < numColumns;i++) { int[] potential = SpatialPooler.mapPotential(this, 0, true); potentialPools.set(i, potential); double[] perm = SpatialPooler.initPermanence(this, new TIntHashSet(potential), initConnectedPct); SpatialPooler.updatePermanencesForColumn(this, perm, i, true); } } /** * Returns the {@link SparseMatrix} which contains the model elements * * @return the main memory matrix */ public SparseMatrix<?> getMemory() { return memory; } /** * Sets the {@link SparseMatrix} which contains the model elements * @param matrix */ public void setMemory(SparseMatrix<?> matrix) { this.memory = matrix; } /** * Returns the input column mapping */ public SparseMatrix<?> getInputMatrix() { return inputMatrix; } /** * Sets the input column mapping matrix * @param matrix */ public void setInputMatrix(SparseMatrix<?> matrix) { this.inputMatrix = matrix; } /** * Returns the product of the input dimensions * @return the product of the input dimensions */ public int getNumInputs() { return numInputs; } /** * Returns the product of the column dimensions * @return the product of the column dimensions */ public int getNumColumns() { return numColumns; } /** * This parameter determines the extent of the input * that each column can potentially be connected to. * This can be thought of as the input bits that * are visible to each column, or a 'receptiveField' of * the field of vision. A large enough value will result * in 'global coverage', meaning that each column * can potentially be connected to every input bit. This * parameter defines a square (or hyper square) area: a * column will have a max square potential pool with * sides of length 2 * potentialRadius + 1. * * @param potentialRadius */ public void setPotentialRadius(int potentialRadius) { this.potentialRadius = potentialRadius; } /** * Returns the configured potential radius * @return the configured potential radius * @see {@link #setPotentialRadius(int)} */ public int getPotentialRadius() { return Math.min(numInputs, potentialRadius); } /** * The percent of the inputs, within a column's * potential radius, that a column can be connected to. * If set to 1, the column will be connected to every * input within its potential radius. This parameter is * used to give each column a unique potential pool when * a large potentialRadius causes overlap between the * columns. At initialization time we choose * ((2*potentialRadius + 1)^(# inputDimensions) * * potentialPct) input bits to comprise the column's * potential pool. * * @param potentialPct */ public void setPotentialPct(double potentialPct) { this.potentialPct = potentialPct; } /** * Returns the configured potential pct * * @return the configured potential pct * @see {@link #setPotentialPct(double)} */ public double getPotentialPct() { return potentialPct; } /** * If true, then during inhibition phase the winning * columns are selected as the most active columns from * the region as a whole. Otherwise, the winning columns * are selected with respect to their local * neighborhoods. Using global inhibition boosts * performance x60. * * @param globalInhibition */ public void setGlobalInhibition(boolean globalInhibition) { this.globalInhibition = globalInhibition; } /** * Returns the configured global inhibition flag * @return the configured global inhibition flag * @see {@link #setGlobalInhibition(boolean)} */ public boolean getGlobalInhibition() { return globalInhibition; } /** * The desired density of active columns within a local * inhibition area (the size of which is set by the * internally calculated inhibitionRadius, which is in * turn determined from the average size of the * connected potential pools of all columns). The * inhibition logic will insure that at most N columns * remain ON within a local inhibition area, where N = * localAreaDensity * (total number of columns in * inhibition area). * * @param localAreaDensity */ public void setLocalAreaDensity(double localAreaDensity) { this.localAreaDensity = localAreaDensity; } /** * Returns the configured local area density * @return the configured local area density * @see {@link #setLocalAreaDensity(double)} */ public double getLocalAreaDensity() { return localAreaDensity; } /** * An alternate way to control the density of the active * columns. If numActivePerInhArea is specified then * localAreaDensity must be less than 0, and vice versa. * When using numActivePerInhArea, the inhibition logic * will insure that at most 'numActivePerInhArea' * columns remain ON within a local inhibition area (the * size of which is set by the internally calculated * inhibitionRadius, which is in turn determined from * the average size of the connected receptive fields of * all columns). When using this method, as columns * learn and grow their effective receptive fields, the * inhibitionRadius will grow, and hence the net density * of the active columns will *decrease*. This is in * contrast to the localAreaDensity method, which keeps * the density of active columns the same regardless of * the size of their receptive fields. * * @param numActiveColumnsPerInhArea */ public void setNumActiveColumnsPerInhArea(double numActiveColumnsPerInhArea) { this.numActiveColumnsPerInhArea = numActiveColumnsPerInhArea; } /** * Returns the configured number of active columns per * inhibition area. * @return the configured number of active columns per * inhibition area. * @see {@link #setNumActiveColumnsPerInhArea(double)} */ public double getNumActiveColumnsPerInhArea() { return numActiveColumnsPerInhArea; } /** * This is a number specifying the minimum number of * synapses that must be on in order for a columns to * turn ON. The purpose of this is to prevent noise * input from activating columns. Specified as a percent * of a fully grown synapse. * * @param stimulusThreshold */ public void setStimulusThreshold(double stimulusThreshold) { this.stimulusThreshold = stimulusThreshold; } /** * Returns the stimulus threshold * @return the stimulus threshold * @see {@link #setStimulusThreshold(double)} */ public double getStimulusThreshold() { return stimulusThreshold; } /** * The amount by which an inactive synapse is * decremented in each round. Specified as a percent of * a fully grown synapse. * * @param synPermInactiveDec */ public void setSynPermInactiveDec(double synPermInactiveDec) { this.synPermInactiveDec = synPermInactiveDec; } /** * Returns the synaptic permanence inactive decrement. * @return the synaptic permanence inactive decrement. * @see {@link #setSynPermInactiveDec(double)} */ public double getSynPermInactiveDec() { return synPermInactiveDec; } /** * The amount by which an active synapse is incremented * in each round. Specified as a percent of a * fully grown synapse. * * @param synPermActiveInc */ public void setSynPermActiveInc(double synPermActiveInc) { this.synPermActiveInc = synPermActiveInc; } /** * Returns the configured active permanence increment * @return the configured active permanence increment * @see {@link #setSynPermActiveInc(double)} */ public double getSynPermActiveInc() { return synPermActiveInc; } /** * The default connected threshold. Any synapse whose * permanence value is above the connected threshold is * a "connected synapse", meaning it can contribute to * the cell's firing. * * @param minPctOverlapDutyCycle */ public void setSynPermConnected(double synPermConnected) { this.synPermConnected = synPermConnected; } /** * Returns the synapse permanence connected threshold * @return the synapse permanence connected threshold * @see {@link #setSynPermConnected(double)} */ public double getSynPermConnected() { return synPermConnected; } /** * Returns the stimulus increment for synapse permanences below * the measured threshold. * * @return */ public double getSynPermBelowStimulusInc() { return synPermBelowStimulusInc; } /** * A number between 0 and 1.0, used to set a floor on * how often a column should have at least * stimulusThreshold active inputs. Periodically, each * column looks at the overlap duty cycle of * all other columns within its inhibition radius and * sets its own internal minimal acceptable duty cycle * to: minPctDutyCycleBeforeInh * max(other columns' * duty cycles). * On each iteration, any column whose overlap duty * cycle falls below this computed value will get * all of its permanence values boosted up by * synPermActiveInc. Raising all permanences in response * to a sub-par duty cycle before inhibition allows a * cell to search for new inputs when either its * previously learned inputs are no longer ever active, * or when the vast majority of them have been * "hijacked" by other columns. * * @param minPctOverlapDutyCycle */ public void setMinPctOverlapDutyCycle(double minPctOverlapDutyCycle) { this.minPctOverlapDutyCycle = minPctOverlapDutyCycle; } /** * {@see #setMinPctOverlapDutyCycle(double)} * @return */ public double getMinPctOverlapDutyCycle() { return minPctOverlapDutyCycle; } /** * A number between 0 and 1.0, used to set a floor on * how often a column should be activate. * Periodically, each column looks at the activity duty * cycle of all other columns within its inhibition * radius and sets its own internal minimal acceptable * duty cycle to: * minPctDutyCycleAfterInh * * max(other columns' duty cycles). * On each iteration, any column whose duty cycle after * inhibition falls below this computed value will get * its internal boost factor increased. * * @param minPctActiveDutyCycle */ public void setMinPctActiveDutyCycle(double minPctActiveDutyCycle) { this.minPctActiveDutyCycle = minPctActiveDutyCycle; } /** * Returns the minPctActiveDutyCycle * @return the minPctActiveDutyCycle * @see {@link #setMinPctActiveDutyCycle(double)} */ public double getMinPctActiveDutyCycle() { return minPctActiveDutyCycle; } /** * The period used to calculate duty cycles. Higher * values make it take longer to respond to changes in * boost or synPerConnectedCell. Shorter values make it * more unstable and likely to oscillate. * * @param dutyCyclePeriod */ public void setDutyCyclePeriod(double dutyCyclePeriod) { this.dutyCyclePeriod = dutyCyclePeriod; } /** * Returns the configured duty cycle period * @return the configured duty cycle period * @see {@link #setDutyCyclePeriod(double)} */ public double getDutyCyclePeriod() { return dutyCyclePeriod; } /** * The maximum overlap boost factor. Each column's * overlap gets multiplied by a boost factor * before it gets considered for inhibition. * The actual boost factor for a column is number * between 1.0 and maxBoost. A boost factor of 1.0 is * used if the duty cycle is >= minOverlapDutyCycle, * maxBoost is used if the duty cycle is 0, and any duty * cycle in between is linearly extrapolated from these * 2 endpoints. * * @param maxBoost */ public void setMaxBoost(double maxBoost) { this.maxBoost = maxBoost; } /** * Returns the max boost * @return the max boost * @see {@link #setMaxBoost(double)} */ public double getMaxBoost() { return maxBoost; } /** * Sets the seed used by the random number generator * @param seed */ public void setSeed(int seed) { this.seed = seed; } /** * Returns the seed used to configure the random generator * @return */ public int getSeed() { return seed; } /** * spVerbosity level: 0, 1, 2, or 3 * * @param spVerbosity */ public void setSpVerbosity(int spVerbosity) { this.spVerbosity = spVerbosity; } /** * Returns the verbosity setting. * @return the verbosity setting. * @see {@link #setSpVerbosity(int)} */ public int getSpVerbosity() { return spVerbosity; } /** * Sets the synPermTrimThreshold * @param threshold */ public void setSynPermTrimThreshold(double threshold) { this.synPermTrimThreshold = threshold; } /** * Returns the synPermTrimThreshold * @return */ public double getSynPermTrimThreshold() { return synPermTrimThreshold; } /** * Returns the {@link SparseObjectMatrix} which holds the mapping * of column indexes to their lists of potential inputs. * @return */ public SparseObjectMatrix<int[]> getPotentialPools() { return this.potentialPools; } /** * * @return */ public double getSynPermMin() { return synPermMin; } /** * * @return */ public double getSynPermMax() { return synPermMax; } }
package org.osiam.ng.scim.mvc.user; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.util.JSONPObject; import org.osiam.ng.scim.dao.SCIMUserProvisioning; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.util.UriTemplate; import scim.schema.v2.User; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.IOException; import java.net.URI; @Controller @RequestMapping(value = "/User") public class UserController { @Inject private SCIMUserProvisioning scimUserProvisioning; public void setScimUserProvisioning(SCIMUserProvisioning scimUserProvisioning) { this.scimUserProvisioning = scimUserProvisioning; } @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public User getUser(@PathVariable final String id) { return scimUserProvisioning.getById(id); } @RequestMapping(method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public User createUser(@RequestBody User user, HttpServletRequest request, HttpServletResponse response) { User createdUser = scimUserProvisioning.createUser(user); String requestUrl = request.getRequestURL().toString(); URI uri = new UriTemplate("{requestUrl}/{externalId}").expand(requestUrl, createdUser.getExternalId()); response.setHeader("Location", uri.toASCIIString()); return createdUser; } }
package org.pac4j.demo.undertow; import org.pac4j.cas.client.CasClient; import org.pac4j.core.authorization.authorizer.RequireAnyRoleAuthorizer; import org.pac4j.core.client.Clients; import org.pac4j.core.client.direct.AnonymousClient; import org.pac4j.core.config.Config; import org.pac4j.core.config.ConfigFactory; import org.pac4j.http.client.direct.DirectBasicAuthClient; import org.pac4j.http.client.direct.ParameterClient; import org.pac4j.http.client.indirect.FormClient; import org.pac4j.http.client.indirect.IndirectBasicAuthClient; import org.pac4j.http.credentials.authenticator.test.SimpleTestUsernamePasswordAuthenticator; import org.pac4j.jwt.credentials.authenticator.JwtAuthenticator; import org.pac4j.oauth.client.FacebookClient; import org.pac4j.oauth.client.TwitterClient; import org.pac4j.oidc.client.OidcClient; import org.pac4j.saml.client.SAML2Client; import org.pac4j.saml.client.SAML2ClientConfiguration; public class DemoConfigFactory implements ConfigFactory { public Config build() { final OidcClient oidcClient = new OidcClient(); oidcClient.setClientID("343992089165-sp0l1km383i8cbm2j5nn20kbk5dk8hor.apps.googleusercontent.com"); oidcClient.setSecret("uR3D8ej1kIRPbqAFaxIE3HWh"); oidcClient.setDiscoveryURI("https://accounts.google.com/.well-known/openid-configuration"); oidcClient.setUseNonce(true); //oidcClient.setPreferredJwsAlgorithm(JWSAlgorithm.RS256); oidcClient.addCustomParam("prompt", "consent"); oidcClient.setAuthorizationGenerator(profile -> profile.addRole("ROLE_ADMIN")); final SAML2ClientConfiguration cfg = new SAML2ClientConfiguration("resource:samlKeystore.jks", "pac4j-demo-passwd", "pac4j-demo-passwd", "resource:metadata-okta.xml"); cfg.setMaximumAuthenticationLifetime(3600); cfg.setServiceProviderEntityId("http://localhost:8080/callback?client_name=SAML2Client"); cfg.setServiceProviderMetadataPath("sp-metadata.xml"); final SAML2Client saml2Client = new SAML2Client(cfg); final FacebookClient facebookClient = new FacebookClient("145278422258960", "be21409ba8f39b5dae2a7de525484da8"); final TwitterClient twitterClient = new TwitterClient("CoxUiYwQOSFDReZYdjigBA", "2kAzunH5Btc4gRSaMr7D7MkyoJ5u1VzbOOzE8rBofs"); // HTTP final FormClient formClient = new FormClient("http://localhost:8080/loginForm.html", new SimpleTestUsernamePasswordAuthenticator()); final IndirectBasicAuthClient indirectBasicAuthClient = new IndirectBasicAuthClient(new SimpleTestUsernamePasswordAuthenticator()); // CAS final CasClient casClient = new CasClient("https://casserverpac4j.herokuapp.com/login"); // REST authent with JWT for a token passed in the url as the token parameter ParameterClient parameterClient = new ParameterClient("token", new JwtAuthenticator(DemoServer.JWT_SALT)); parameterClient.setSupportGetRequest(true); parameterClient.setSupportPostRequest(false); // basic auth final DirectBasicAuthClient directBasicAuthClient = new DirectBasicAuthClient(new SimpleTestUsernamePasswordAuthenticator()); final AnonymousClient anonymousClient = new AnonymousClient(); final Clients clients = new Clients("http://localhost:8080/callback", saml2Client, facebookClient, twitterClient, formClient, indirectBasicAuthClient, casClient, parameterClient, directBasicAuthClient, oidcClient, anonymousClient); final Config config = new Config(clients); config.addAuthorizer("admin", new RequireAnyRoleAuthorizer("ROLE_ADMIN")); config.addAuthorizer("custom", new CustomAuthorizer()); return config; } }
package org.robolectric.shadows; import android.util.SparseBooleanArray; import android.view.View; import android.widget.AbsListView; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.annotation.RealObject; import static org.robolectric.Robolectric.directlyOn; @Implements(AbsListView.class) public class ShadowAbsListView extends ShadowAdapterView { @RealObject private AbsListView realAbsListView; private AbsListView.OnScrollListener onScrollListener; private int smoothScrolledPosition; private int lastSmoothScrollByDistance; private int lastSmoothScrollByDuration; @Implementation public void setOnScrollListener(AbsListView.OnScrollListener l) { onScrollListener = l; } @Implementation public void smoothScrollToPosition(int position) { smoothScrolledPosition = position; } @Implementation public void smoothScrollBy(int distance, int duration) { this.lastSmoothScrollByDistance = distance; this.lastSmoothScrollByDuration = duration; } @Implementation public boolean performItemClick(View view, int position, long id) { return ((Boolean) directlyOn(realAbsListView, AbsListView.class, "performItemClick", View.class, int.class, long.class).invoke(view, position, id)); } @Implementation public int getCheckedItemPosition() { return ((Integer) directlyOn(realAbsListView, AbsListView.class, "getCheckedItemPosition").invoke()); } @Implementation public int getCheckedItemCount() { return ((Integer) directlyOn(realAbsListView, AbsListView.class, "getCheckedItemCount").invoke()); } @Implementation public void setItemChecked(int position, boolean value) { directlyOn(realAbsListView, AbsListView.class, "setItemChecked", int.class, boolean.class).invoke(position, value); } @Implementation public int getChoiceMode() { return (Integer) directlyOn(realAbsListView, AbsListView.class, "getChoiceMode").invoke(); } @Implementation public void setChoiceMode(int choiceMode) { directlyOn(realAbsListView, AbsListView.class, "setChoiceMode", int.class).invoke(choiceMode); } @Implementation public SparseBooleanArray getCheckedItemPositions() { return (SparseBooleanArray) directlyOn(realAbsListView, AbsListView.class, "getCheckedItemPositions").invoke(); } @Implementation public long[] getCheckedItemIds() { return (long[]) directlyOn(realAbsListView, AbsListView.class, "getCheckedItemIds").invoke(); } /** * Robolectric accessor for the onScrollListener * * @return AbsListView.OnScrollListener */ public AbsListView.OnScrollListener getOnScrollListener() { return onScrollListener; } /** * Robolectric accessor for the last smoothScrolledPosition * * @return int position */ public int getSmoothScrolledPosition() { return smoothScrolledPosition; } /** * Robolectric accessor for the last smoothScrollBy distance * * @return int distance */ public int getLastSmoothScrollByDistance() { return lastSmoothScrollByDistance; } /** * Robolectric accessor for the last smoothScrollBy duration * * @return int duration */ public int getLastSmoothScrollByDuration() { return lastSmoothScrollByDuration; } }
package org.sfm.jdbc.impl; import org.sfm.jdbc.JdbcMapper; import org.sfm.map.*; import org.sfm.map.impl.DiscriminatorEnumerable; import org.sfm.tuples.Tuple2; import org.sfm.tuples.Tuple3; import org.sfm.utils.*; import org.sfm.utils.conv.Converter; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; public final class DiscriminatorJdbcMapper<T> extends AbstractEnumarableJdbcMapper<T> { private final String discriminatorColumn; private final List<Tuple2<Predicate<String>, JdbcMapper<T>>> mappers; public DiscriminatorJdbcMapper(String discriminatorColumn, List<Tuple2<Predicate<String>, JdbcMapper<T>>> mappers, RowHandlerErrorHandler rowHandlerErrorHandler) { super(rowHandlerErrorHandler); this.discriminatorColumn = discriminatorColumn; this.mappers = mappers; } @Override protected JdbcMapper<T> getMapper(final ResultSet rs) throws MappingException { try { String value = rs.getString(discriminatorColumn); for (Tuple2<Predicate<String>, JdbcMapper<T>> tm : mappers) { if (tm.first().test(value)) { return tm.second(); } } throw new MappingException("No jdbcMapper found for " + discriminatorColumn + " = " + value); } catch(SQLException e) { return ErrorHelper.rethrow(e); } } protected DiscriminatorEnumerable<ResultSet, T> newEnumarableOfT(ResultSet rs) throws SQLException { @SuppressWarnings("unchecked") Tuple3<Predicate<ResultSet>, Mapper<ResultSet, T>, MappingContext<ResultSet>>[] mapperDiscriminators = new Tuple3[this.mappers.size()]; for(int i = 0; i < mapperDiscriminators.length; i++) { Tuple2<Predicate<String>, JdbcMapper<T>> mapper = mappers.get(i); Predicate<ResultSet> discriminatorPredicate = new DiscriminatorPredicate(discriminatorColumn, mapper.first()); mapperDiscriminators[i] = new Tuple3<Predicate<ResultSet>, Mapper<ResultSet, T>, MappingContext<ResultSet>>( discriminatorPredicate, mapper.second(), mapper.second().newMappingContext(rs)); } return new DiscriminatorEnumerable<ResultSet, T>( mapperDiscriminators, new ResultSetEnumarable(rs), new ErrorMessageConverter(discriminatorColumn)); } @Override public String toString() { return "DiscriminatorJdbcMapper{" + "discriminatorColumn='" + discriminatorColumn + '\'' + ", mappers=" + mappers + '}'; } private static class DiscriminatorPredicate implements Predicate<ResultSet> { private String discriminatorColumn; private Predicate<String> predicate; public DiscriminatorPredicate(String discriminatorColumn, Predicate<String> predicate) { this.discriminatorColumn = discriminatorColumn; this.predicate = predicate; } @Override public boolean test(ResultSet resultSet) { try { return predicate.test(resultSet.getString(discriminatorColumn)); } catch (SQLException e) { ErrorHelper.rethrow(e); return false; } } } private static class ErrorMessageConverter implements Converter<ResultSet, String> { private final String discriminatorColumn; private ErrorMessageConverter(String discriminatorColumn) { this.discriminatorColumn = discriminatorColumn; } @Override public String convert(ResultSet in) throws Exception { return " column " + discriminatorColumn + " = " + in.getObject(discriminatorColumn); } } }
package org.signaut.camelback.start; import java.util.concurrent.ConcurrentMap; import javax.servlet.ServletContext; import org.eclipse.jetty.deploy.DeploymentManager; import org.eclipse.jetty.http.ssl.SslContextFactory; import org.eclipse.jetty.security.Authenticator; import org.eclipse.jetty.security.Authenticator.AuthConfiguration; import org.eclipse.jetty.security.Authenticator.Factory; import org.eclipse.jetty.security.IdentityService; import org.eclipse.jetty.security.LoginService; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.SessionManager; import org.eclipse.jetty.server.handler.ContextHandlerCollection; import org.eclipse.jetty.server.handler.DefaultHandler; import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.server.ssl.SslSelectChannelConnector; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.util.thread.ThreadPool; import org.signaut.camelback.configuration.CamelbackConfig; import org.signaut.common.hazelcast.HazelcastFactory; import org.signaut.couchdb.impl.CouchDbAuthenticatorImpl; import org.signaut.jetty.deploy.providers.couchdb.CouchDbAppProvider; import org.signaut.jetty.deploy.providers.couchdb.CouchDbAppProvider.SessionManagerProvider; import org.signaut.jetty.deploy.providers.couchdb.CouchDbAppProvider.ThreadPoolProvider; import org.signaut.jetty.server.security.CouchDbLoginService; import org.signaut.jetty.server.security.authentication.CouchDbSSOAuthenticator; import org.signaut.jetty.server.session.HazelcastSessionIdManager; import org.signaut.jetty.server.session.HazelcastSessionManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hazelcast.core.HazelcastInstance; class JettyInstance { private final CamelbackConfig config; private final Server server = new Server();; private final HazelcastFactory hazelcastFactory = new HazelcastFactory(); private final Authenticator.Factory authenticatorFactory; private final Logger log = LoggerFactory.getLogger(getClass()); public JettyInstance(CamelbackConfig config) { this.config = config; authenticatorFactory = new Factory() { final CouchDbSSOAuthenticator authenticator = new CouchDbSSOAuthenticator(new CouchDbAuthenticatorImpl(JettyInstance.this.config.getLoginConfig() .getAuthenticationUrl())); @Override public Authenticator getAuthenticator(Server server, ServletContext context, AuthConfiguration configuration, IdentityService identityService, LoginService loginService) { return authenticator; } }; } public void start() { final long startingTime = System.currentTimeMillis(); setConnectors(server); final HandlerCollection handlers = new HandlerCollection(); final ContextHandlerCollection contextHandlers = new ContextHandlerCollection(); final Handler defaultHandler = new DefaultHandler(); handlers.setHandlers(new Handler[] { contextHandlers, defaultHandler }); server.setHandler(handlers); final HazelcastInstance hazelcastInstance = hazelcastFactory.loadHazelcastInstance(config.getHazelcastConfig(), getClass()); final ConcurrentMap<String, String> activeUsers = hazelcastInstance.getMap("signaut.activeUsers"); // Authentication final CouchDbLoginService couchDbLoginService = new CouchDbLoginService("couchdb_realm", new CouchDbAuthenticatorImpl(config.getLoginConfig().getAuthenticationUrl()), activeUsers); server.addBean(couchDbLoginService); server.addBean(authenticatorFactory); // Session manager final HazelcastSessionIdManager clusterSessionIdManager = new HazelcastSessionIdManager(hazelcastInstance); final SessionManagerProvider sessionManagerProvider = new SessionManagerProvider() { @Override public SessionManager get() { return new HazelcastSessionManager(clusterSessionIdManager); } }; final ThreadPoolProvider threadPoolProvider = new ThreadPoolProvider() { @Override public ThreadPool get() { return new QueuedThreadPool(config.getThreadPoolSize()); } }; // Deployment handling final DeploymentManager deploymentManager = new DeploymentManager(); deploymentManager.setContexts(contextHandlers); server.addBean(deploymentManager); deploymentManager.addAppProvider(new CouchDbAppProvider().setCouchDeployerProperties(config.getDeployerConfig()) .setAuthenticatorFactory(authenticatorFactory) .setSessionManagerProvider(sessionManagerProvider) .setThreadPoolProvider(threadPoolProvider)); server.setStopAtShutdown(true); server.setGracefulShutdown(5000); final QueuedThreadPool threadPool = new QueuedThreadPool(config.getThreadPoolSize()); server.setThreadPool(threadPool); // Now start server try { server.start(); log.info(String.format("Started camelback in %d milliseconds", System.currentTimeMillis()-startingTime)); } catch (Exception e) { throw new IllegalStateException("While starting jetty", e); } } public void stop() { try { server.stop(); } catch (Exception e) { throw new IllegalStateException("While stopping server", e); } } private void setConnectors(Server server) { server.addConnector(new SelectChannelConnector() { { setPort(config.getPort()); setName("http"); setConfidentialPort(config.getSecurePort()); } }); if (config.getSslConfig() != null && config.getSslConfig().getKeystore()!=null) { server.addConnector(new SslSelectChannelConnector() { { setPort(config.getSecurePort()); setName("https"); setConfidentialPort(config.getSecurePort()); final SslContextFactory sslContextFactory = getSslContextFactory(); sslContextFactory.setKeyStore(config.getSslConfig().getKeystore()); sslContextFactory.setKeyStorePassword(config.getSslConfig().getKeystorePassword()); sslContextFactory.setKeyManagerPassword(config.getSslConfig().getKeyManagerPassword()); sslContextFactory.setTrustStore(config.getSslConfig().getTruststore()); sslContextFactory.setTrustStorePassword(config.getSslConfig().getTruststorePassword()); sslContextFactory.setExcludeCipherSuites(new String[] { "SSL_RSA_WITH_DES_CBC_SHA", "SSL_DHE_RSA_WITH_DES_CBC_SHA", "SSL_DHE_DSS_WITH_DES_CBC_SHA", "SSL_RSA_EXPORT_WITH_RC4_40_MD5", "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA" }); } }); } } }
package pl.polidea.robospock.internal; import org.junit.runner.Description; import org.junit.runner.Runner; import org.junit.runner.manipulation.*; import org.junit.runner.notification.RunNotifier; import org.junit.runners.model.InitializationError; import org.robolectric.*; import org.robolectric.annotation.Config; import org.robolectric.bytecode.AsmInstrumentingClassLoader; import org.robolectric.bytecode.Setup; import org.robolectric.bytecode.ShadowMap; import org.robolectric.res.DocumentLoader; import org.robolectric.res.Fs; import org.robolectric.res.FsFile; import org.robolectric.res.ResourceLoader; import org.robolectric.util.AnnotationUtil; import org.spockframework.runtime.Sputnik; import org.spockframework.runtime.model.SpecInfo; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.security.SecureRandom; import java.util.*; public class RoboSputnik extends Runner implements Filterable, Sortable { private static final MavenCentral MAVEN_CENTRAL = new MavenCentral(); private static final Map<Class<? extends RoboSputnik>, EnvHolder> envHoldersByTestRunner = new HashMap<Class<? extends RoboSputnik>, EnvHolder>(); private static final Map<AndroidManifest, ResourceLoader> resourceLoadersByAppManifest = new HashMap<AndroidManifest, ResourceLoader>(); private static Class<? extends RoboSputnik> lastTestRunnerClass; private static SdkConfig lastSdkConfig; private static SdkEnvironment lastSdkEnvironment; private final EnvHolder envHolder; private Object sputnik; static { new SecureRandom(); // this starts up the Poller SunPKCS11-Darwin thread early, outside of any Robolectric classloader } public RoboSputnik(Class<?> clazz) throws InitializationError { // Ripped from RobolectricTestRunner EnvHolder envHolder; synchronized (envHoldersByTestRunner) { Class<? extends RoboSputnik> testRunnerClass = getClass(); envHolder = envHoldersByTestRunner.get(testRunnerClass); if (envHolder == null) { envHolder = new EnvHolder(); envHoldersByTestRunner.put(testRunnerClass, envHolder); } } this.envHolder = envHolder; final Config config = getConfig(clazz); AndroidManifest appManifest = getAppManifest(config); SdkEnvironment sdkEnvironment = getEnvironment(appManifest, config); // todo: is this really needed? Thread.currentThread().setContextClassLoader(sdkEnvironment.getRobolectricClassLoader()); Class bootstrappedTestClass = sdkEnvironment.bootstrappedClass(clazz); // Since we have bootstrappedClass we may properly initialize try { this.sputnik = sdkEnvironment .bootstrappedClass(Sputnik.class) .getConstructor(Class.class) .newInstance(bootstrappedTestClass); } catch (Exception e) { throw new RuntimeException(e); } // let's manually add our initializers for(Method method : sputnik.getClass().getDeclaredMethods()) { if(method.getName() == "getSpec") { method.setAccessible(true); try { Object spec = method.invoke(sputnik); // Interceptor registers on construction sdkEnvironment .bootstrappedClass(RoboSpockInterceptor.class) .getConstructor( sdkEnvironment.bootstrappedClass(SpecInfo.class), SdkEnvironment.class, Config.class, AndroidManifest.class ).newInstance(spec, sdkEnvironment, config, appManifest); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } } } } public Config getConfig(Class<?> clazz) { Config config = AnnotationUtil.defaultsFor(Config.class); Config globalConfig = Config.Implementation.fromProperties(getConfigProperties()); if (globalConfig != null) { config = new Config.Implementation(config, globalConfig); } Config classConfig = clazz.getAnnotation(Config.class); if (classConfig != null) { config = new Config.Implementation(config, classConfig); } return config; } protected Properties getConfigProperties() { ClassLoader classLoader = getClass().getClassLoader(); InputStream resourceAsStream = classLoader.getResourceAsStream("org.robolectric.Config.properties"); if (resourceAsStream == null) return null; Properties properties = new Properties(); try { properties.load(resourceAsStream); } catch (IOException e) { throw new RuntimeException(e); } return properties; } protected AndroidManifest getAppManifest(Config config) { if (config.manifest().equals(Config.NONE)) { return null; } boolean propertyAvailable = false; FsFile manifestFile = null; String manifestProperty = System.getProperty("android.manifest"); if (config.manifest().equals(Config.DEFAULT) && manifestProperty != null) { manifestFile = Fs.fileFromPath(manifestProperty); propertyAvailable = true; } else { FsFile fsFile = Fs.currentDirectory(); String manifestStr = config.manifest().equals(Config.DEFAULT) ? "AndroidManifest.xml" : config.manifest(); manifestFile = fsFile.join(manifestStr); } synchronized (envHolder) { AndroidManifest appManifest; appManifest = envHolder.appManifestsByFile.get(manifestFile); if (appManifest == null) { long startTime = System.currentTimeMillis(); appManifest = propertyAvailable ? createAppManifestFromProperty(manifestFile) : createAppManifest(manifestFile); if (DocumentLoader.DEBUG_PERF) System.out.println(String.format("%4dms spent in %s", System.currentTimeMillis() - startTime, manifestFile)); envHolder.appManifestsByFile.put(manifestFile, appManifest); } return appManifest; } } protected AndroidManifest createAppManifest(FsFile manifestFile) { if (!manifestFile.exists()) { System.out.print("WARNING: No manifest file found at " + manifestFile.getPath() + "."); System.out.println("Falling back to the Android OS resources only."); System.out.println("To remove this warning, annotate your test class with @Config(manifest=Config.NONE)."); return null; } FsFile appBaseDir = manifestFile.getParent(); return new AndroidManifest(manifestFile, appBaseDir.join("res"), appBaseDir.join("assets")); } protected AndroidManifest createAppManifestFromProperty(FsFile manifestFile) { String resProperty = System.getProperty("android.resources"); String assetsProperty = System.getProperty("android.assets"); AndroidManifest manifest = new AndroidManifest(manifestFile, Fs.fileFromPath(resProperty), Fs.fileFromPath(assetsProperty)); String packageProperty = System.getProperty("android.package"); System.out.println("manifest:" + manifestFile.getPath()); System.out.println("resources:" + resProperty); System.out.println("assets:" + assetsProperty); System.out.println("package:" + packageProperty); try { setPackageName(manifest, packageProperty); } catch (IllegalArgumentException e) { System.out.println("WARNING: Faild to set package name for " + manifestFile.getPath() + "."); } return manifest; } private void setPackageName(AndroidManifest manifest, String packageName) { Class<AndroidManifest> type = AndroidManifest.class; try { Method setPackageNameMethod = type.getMethod("setPackageName", String.class); setPackageNameMethod.setAccessible(true); setPackageNameMethod.invoke(manifest, packageName); return; } catch (NoSuchMethodException e) { try { //Force execute parseAndroidManifest. manifest.getPackageName(); Field packageNameField = type.getDeclaredField("packageName"); packageNameField.setAccessible(true); packageNameField.set(manifest, packageName); return; } catch (Exception fieldError) { throw new IllegalArgumentException(fieldError); } } catch (Exception methodError) { throw new IllegalArgumentException(methodError); } } private SdkEnvironment getEnvironment(final AndroidManifest appManifest, final Config config) { final SdkConfig sdkConfig = pickSdkVersion(appManifest, config); // keep the most recently-used SdkEnvironment strongly reachable to prevent thrashing in low-memory situations. if (getClass().equals(lastTestRunnerClass) && sdkConfig.equals(sdkConfig)) { return lastSdkEnvironment; } lastTestRunnerClass = null; lastSdkConfig = null; lastSdkEnvironment = envHolder.getSdkEnvironment(sdkConfig, new SdkEnvironment.Factory() { @Override public SdkEnvironment create() { return createSdkEnvironment(sdkConfig); } }); lastTestRunnerClass = getClass(); lastSdkConfig = sdkConfig; return lastSdkEnvironment; } public SdkEnvironment createSdkEnvironment(SdkConfig sdkConfig) { Setup setup = createSetup(); ClassLoader robolectricClassLoader = createRobolectricClassLoader(setup, sdkConfig); return new SdkEnvironment(sdkConfig, robolectricClassLoader); } protected ClassLoader createRobolectricClassLoader(Setup setup, SdkConfig sdkConfig) { URL[] urls = MAVEN_CENTRAL.getLocalArtifactUrls( null, sdkConfig.getSdkClasspathDependencies()).values().toArray(new URL[0]); return new AsmInstrumentingClassLoader(setup, urls); } public Setup createSetup() { return new Setup() { @Override public boolean shouldAcquire(String name) { List<String> prefixes = Arrays.asList( MavenCentral.class.getName(), "org.junit", ShadowMap.class.getName() ); if(name != null) { for(String prefix : prefixes) { if (name.startsWith(prefix)) { return false; } } } return super.shouldAcquire(name); } }; } protected SdkConfig pickSdkVersion(AndroidManifest appManifest, Config config) { if (config != null && config.emulateSdk() != -1) { throw new UnsupportedOperationException("Sorry, emulateSdk is not yet supported... coming soon!"); } if (appManifest != null) { // todo: something smarter int useSdkVersion = appManifest.getTargetSdkVersion(); } // right now we only have real jars for Ice Cream Sandwich aka 4.1 aka API 16 return new SdkConfig("4.1.2_r1_rc"); } public Description getDescription() { return ((Runner) sputnik).getDescription(); } public void run(RunNotifier notifier) { ((Runner) sputnik).run(notifier); } public void filter(Filter filter) throws NoTestsRemainException { ((Filterable) sputnik).filter(filter); } public void sort(Sorter sorter) { ((Sortable) sputnik).sort(sorter); } }
package spms.controls; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.ServletContext; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import spms.dao.MemberDao; import spms.dao.OfficeDao; import spms.vo.JsonResult; import spms.vo.Member; import spms.vo.Office; @Controller @RequestMapping("/member") public class MemberControl { Logger log = Logger.getLogger(MemberControl.class); @Autowired ServletContext servletContext; @Autowired(required=false) MemberDao memberDao; @Autowired(required=false) OfficeDao officeDao; @Autowired(required=false) ExcelControl excelControl; @RequestMapping(value="/add",method=RequestMethod.GET) public String form() { //return "member/addForm"; return "member/add"; } @RequestMapping(value="/addtest",method=RequestMethod.GET) public String formTest() { //return "member/addForm"; return "member/addtest"; } @RequestMapping(value="/setPhoto",method=RequestMethod.POST) public String setPhoto( Member member, @RequestParam("file1") MultipartFile photoFile, Model model) throws Exception { System.err.println("asdfasdf"); saveFile(photoFile); return "member/add"; } @RequestMapping(value="/updatePhoto",method=RequestMethod.POST) public String updatePhoto( Member member, @RequestParam("file1") MultipartFile photoFile, Model model) throws Exception { saveFile(photoFile); return "member/memberList"; } @RequestMapping("/delete") public String delete(int no, Model model) throws Exception { memberDao.delete(no); return "member/memberList"; } @RequestMapping("/addImage") public String addImage( ) throws Exception { return "member/add_image"; } @RequestMapping("/searchCompany") public String searchCompany( ) throws Exception { return "member/searchCompany"; } @RequestMapping("/idCheck") public String idCheck( String id , Model model) throws Exception { Member member = memberDao.searchid( id ); model.addAttribute("member", member); return "member/idCheck"; } @RequestMapping("/updateImage") public String updateImage( ) throws Exception { return "member/update_image"; } @RequestMapping("/list") public String list(Model model) throws Exception { // model.addAttribute("members", memberDao.selectList()); return "member/list"; } @RequestMapping("/read") public String read(int no, Model model) throws Exception { Member member = memberDao.selectOne(no); model.addAttribute("member", member); return "member/updateForm"; } @RequestMapping(value="/update",method=RequestMethod.POST) public String update(Member member, Model model) throws Exception { System.err.println(member); int count = memberDao.update(member); // if (count > 0) { // model.addAttribute("message", " !"); // } else { // model.addAttribute("message", " !"); return "member/memberList"; //return "member/update"; } // @RequestMapping(value="/update",method=RequestMethod.POST) // public String update(Member member, // @RequestParam(value="photoFile",required=false) MultipartFile photoFile, // Model model) throws Exception { // System.err.println(member); // System.err.println(photoFile); // if (photoFile.getSize() > 0) { // member.setPhoto( saveFile(photoFile) ); // int count = memberDao.update(member); // if (count > 0) { // model.addAttribute("message", " !"); // } else { // model.addAttribute("message", " !"); // return "member/update"; private String saveFile(MultipartFile photoFile) throws IOException { String originFilename = photoFile.getOriginalFilename(); log.debug(" :" + photoFile.getName() + "=" + originFilename); String ext = originFilename.substring( originFilename.lastIndexOf(".")); Date dt = new Date(); System.out.println(dt.toString()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_hh_mm_ss"); System.out.println(sdf.format(dt).toString()); String newFilename = sdf.format(dt).toString() + "_" + this.getFileCount() + ext; // String newFilename = System.currentTimeMillis() + "_" + // this.getFileCount() + ext; photoFile.transferTo(new File(servletContext.getRealPath( "/files/" + newFilename))); return newFilename; } int fileCount = 0; synchronized private int getFileCount() { if (fileCount > 1000) { fileCount = 0; } return ++fileCount; } @RequestMapping(value="/ajax/update", method=RequestMethod.POST, produces="application/json") public Object ajaxUpdate(Member member) throws Exception { try { memberDao.update(member); return new JsonResult().setResultStatus(JsonResult.SUCCESS); } catch (Throwable ex) { return new JsonResult().setResultStatus(JsonResult.FAILURE) .setError(ex.getMessage()); } } @RequestMapping(value="/ajax/delete", produces="application/json") public String ajaxDelete(int[] no) throws Exception { try { System.out.println("dddd : "+ no.length); for(int i = 0; i< no.length; i++) { memberDao.delete(no[i]); } return "redirect:/member/memberList.do"; } catch (Throwable ex) { return "redirect:/member/memberList.do"; } } @RequestMapping(value="/ajax/read", produces="application/json") public Object ajaxRead(int no) throws Exception { try { return new JsonResult().setResultStatus(JsonResult.SUCCESS) .setData(memberDao.selectOne(no)); } catch (Throwable ex) { return new JsonResult().setResultStatus(JsonResult.FAILURE) .setError(ex.getMessage()); } } @RequestMapping(value="/ajax/list", produces="application/json") public Object ajaxList() throws Exception { try { int mno = excelControl.staticId; return new JsonResult().setResultStatus(JsonResult.SUCCESS) .setData(memberDao.selectList(mno )); } catch (Throwable ex) { return new JsonResult().setResultStatus(JsonResult.FAILURE) .setError(ex.getMessage()); } } @RequestMapping(value="/ajax/officeList.do", produces="application/json") public Object ajaxListmem() throws Exception { try { return new JsonResult().setResultStatus(JsonResult.SUCCESS) .setData(officeDao.selectList()); } catch (Throwable ex) { return new JsonResult().setResultStatus(JsonResult.FAILURE) .setError(ex.getMessage()); } } @RequestMapping("/memberList.do") public String memberList(Model model) throws Exception { return "member/memberList"; } @RequestMapping("/memberAddForm.do") public String officeList(Model model) throws Exception { return "member/addForm"; } @RequestMapping(value="/ajax/addMember", method=RequestMethod.POST, produces="application/json") public String ajaxAdd(Member member) throws Exception { try { memberDao.insert(member); if( member.getRank().equals("3") ) { return "redirect:/member/memberList.do"; } return "redirect:/member/memberList.do"; // return "redirect:../list.do"; } catch (Exception ex) { ex.printStackTrace(); return "redirect:/member/memberList.do"; } } }
package ru.parallel.octotron.generators; import ru.parallel.octotron.core.collections.EntityList; import ru.parallel.octotron.core.model.ModelEntity; import ru.parallel.octotron.core.model.impl.ModelList; import ru.parallel.octotron.core.primitive.SimpleAttribute; import ru.parallel.octotron.core.primitive.exception.ExceptionModelFail; import ru.parallel.octotron.core.primitive.exception.ExceptionParseError; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; /** * read a csv file and and fill a given IEntityList with attributes * 1st csv string must contain names for attributes * rest lines will be taken as values * */ public final class CSVReader { private final static Logger LOGGER = Logger.getLogger("octotron"); private CSVReader() {} public static void Declare(EntityList<? extends ModelEntity, ?> list, String file_name) throws ExceptionParseError, IOException { au.com.bytecode.opencsv.CSVReader reader = new au.com.bytecode.opencsv.CSVReader(new FileReader(file_name)); try { String[] fields = reader.readNext(); if(fields == null) { throw new ExceptionModelFail("csv file has no data"); } String[] next_line; int read = 0; for(ModelEntity entity : list) { next_line = reader.readNext(); if(next_line == null) { throw new ExceptionModelFail("not enough data in csv, read: " + read + " expected: " + list.size()); } if(next_line.length != fields.length) throw new ExceptionModelFail("some fields are missing, read: " + read + " expected: " + list.size()); for(int i = 0; i < fields.length; i++) { String str_val = next_line[i]; Object val = SimpleAttribute.ValueFromStr(str_val); entity.DeclareConstant(fields[i], val); } read++; } if((next_line = reader.readNext()) != null) LOGGER.log(Level.WARNING, "some data from csv " + file_name + " were not assigned, read: " + read + " expected: " + list.size() + " next line: " + Arrays.toString(next_line)); } finally { reader.close(); } } public static <T extends ModelEntity> void Declare(T object, String file_name) throws ExceptionParseError, IOException { ModelList list = new ModelList(); list.add(object); Declare(list, file_name); } }
package seedu.taskitty.logic.commands; import java.time.LocalDate; import seedu.taskitty.model.task.TaskDate; //@@author A0130853L /** * This command has 4 types of functionalities, depending on the following keyword that is entered. * Type 1: view DATE/today * Lists all events for the specified date, deadlines up to the specified date, and all todo tasks. * Type 2: view done * Lists all tasks that have been completed. * Type 3: view * Lists all upcoming and uncompleted tasks in the task manager. * Type 4: view all * Lists all tasks in the task manager. */ public class ViewCommand extends Command { public static final String COMMAND_WORD = "view"; public static final String MESSAGE_PARAMETER = COMMAND_WORD + " [date] | done | all"; public static final String MESSAGE_USAGE = "This command shows upcoming tasks, Meow!" + "\nUse \"view [date]\" for dated tasks, \"view done\" for done tasks, \"view all\" for all tasks!"; public static final String VIEW_ALL_MESSAGE_SUCCESS = "All tasks are listed, Meow!"; private LocalDate date; public enum ViewType { done("done"), // to differentiate between 4 types of command functionalities date("date"), all("all"), normal("default"); private String value; ViewType(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return this.getValue(); } } private ViewType viewType; /** * Constructor for view done and view date command functionalities. * * @param parameter * must not be empty, and will definitely be "done", "all", or a * valid date guaranteed by the command parser. */ public ViewCommand(String parameter) { assert parameter != null; switch (parameter) { case "done": // view done tasks viewType = ViewType.done; break; case "all": viewType = ViewType.all; break; default: // view tasks based on date this.date = LocalDate.parse(parameter, TaskDate.DATE_FORMATTER_STORAGE); viewType = ViewType.date; break; } } /** * Views uncompleted and upcoming tasks, events and deadlines. */ public ViewCommand() { this.viewType = ViewType.normal; } @Override public CommandResult execute() { switch (viewType) { case normal: // view uncompleted and upcoming tasks model.updateToDefaultList(); return new CommandResult(getMessageForTaskListShownSummary(model.getTaskList().size())); case done: // view done model.updateFilteredDoneList(); return new CommandResult(getMessageForTaskListShownSummary(model.getTaskList().size())); case all: // view all model.updateFilteredListToShowAll(); return new CommandResult(VIEW_ALL_MESSAGE_SUCCESS); default: // view date model.updateFilteredDateTaskList(date); return new CommandResult(getMessageForTaskListShownSummary(model.getTaskList().size())); } } }
package sg.ncl.testbed_interface; import org.hibernate.validator.constraints.NotEmpty; import org.hibernate.validator.constraints.Range; import javax.validation.constraints.AssertTrue; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; public class SignUpMergedForm { private static final String DEFAULT = "default"; // Account Details Fields @Size(min=1, message="Email cannot be empty") private String email; // @Pattern(regexp="^((?=.*\\d))*$", message = "Password must contains alphanumeric characters" ) @Size(min=8, message="Password must have at least 8 characters") @Pattern.List({ @Pattern(regexp = "(?=.*[0-9]).+", message = "Password must contain one digit"), @Pattern(regexp = "(?=.*[a-z]).+", message = "Password must contain one alphabet") }) private String password; private String confirmPassword; private String errorMsg = null; // Personal Details Fields @Size(min=1, message = "First name cannot be empty") private String firstName; @Size(min=1, message ="Last name cannot be empty") private String lastName; @Pattern(regexp="^[0-9]*$", message = "Phone cannot have special characters" ) @Range(min=6, message="Phone minimum 6 digits") private String phone; @NotEmpty(message = "Job title cannot be empty") private String jobTitle; @NotEmpty(message = "Institution cannot be empty") private String institution; @NotEmpty(message = "Institution Abbreviation cannot be empty") private String institutionAbbreviation = "defaultAbbrev"; @NotEmpty(message = "Website cannot be empty") private String website = "http://default.com"; @NotEmpty(message = "Address 1 cannot be empty") private String address1 = DEFAULT; private String address2 = DEFAULT; @NotEmpty(message = "Country cannot be empty") private String country; @NotEmpty(message = "City cannot be empty") private String city = DEFAULT; @NotEmpty(message = "Province cannot be empty") private String province = DEFAULT; @Pattern(regexp="^[0-9]*$", message = "Postal code cannot have special characters" ) private String postalCode = "00000000"; // Create New Team Fields @Pattern(regexp="^[a-zA-Z0-9-]*$", message="Team name cannot have special characters") private String teamName; private String teamDescription; private String teamWebsite = "http://default.com"; private String teamOrganizationType; // defaults to public private String isPublic = "PUBLIC"; private boolean hasAcceptTeamOwnerPolicy; // Join New Team Fields @Pattern(regexp="^[a-zA-Z0-9-]*$", message="Team name cannot have special characters") private String joinTeamName; // A way to display error messages for create new team form // Required as the controller cannot use redirectFlashAttributes to display errors; will cause the form fields to reset private String errorTeamName; private String errorTeamDescription; private String errorTeamWebsite; private String errorTeamOwnerPolicy; private boolean isValid; public SignUpMergedForm() { } public SignUpMergedForm(String country, String institution, String jobTitle, String confirmPassword, String password, String postalCode) { this.country = country; this.institution = institution; this.jobTitle = jobTitle; this.confirmPassword = confirmPassword; this.password = password; this.postalCode = postalCode; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getConfirmPassword() { return confirmPassword; } public void setConfirmPassword(String confirmPassword) { this.confirmPassword = confirmPassword; } public String getErrorMsg() { return errorMsg; } public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; } public boolean getIsValid() { return isValid; } public void setIsValid(boolean isValid) { this.isValid = isValid; } @AssertTrue(message="Passwords should matched") public boolean isValid() { isValid = this.password.equals(this.confirmPassword); return this.password.equals(this.confirmPassword); } public String getJobTitle() { return jobTitle; } public void setJobTitle(String jobTitle) { this.jobTitle = jobTitle; } public String getInstitution() { return institution; } public void setInstitution(String institution) { this.institution = institution; } public String getInstitutionAbbreviation() { return institutionAbbreviation; } public void setInstitutionAbbreviation(String institutionAbbreviation) { this.institutionAbbreviation = institutionAbbreviation; } public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website.startsWith("http") ? website : "http://" + website; } public String getAddress1() { return address1; } public void setAddress1(String address1) { this.address1 = address1; } public String getAddress2() { return address2; } public void setAddress2(String address2) { this.address2 = address2; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getTeamName() { return teamName; } public void setTeamName(String teamName) { this.teamName = teamName; } public String getTeamDescription() { return teamDescription; } public void setTeamDescription(String teamDescription) { this.teamDescription = teamDescription; } public String getTeamWebsite() { return teamWebsite; } public void setTeamWebsite(String teamWebsite) { this.teamWebsite = teamWebsite.startsWith("http") ? teamWebsite : "http://" + teamWebsite; } public String getTeamOrganizationType() { return teamOrganizationType; } public void setTeamOrganizationType(String teamOrganizationType) { this.teamOrganizationType = teamOrganizationType; } public String getIsPublic() { return isPublic; } public void setIsPublic(String isPublic) { this.isPublic = isPublic; } public boolean getHasAcceptTeamOwnerPolicy() { return hasAcceptTeamOwnerPolicy; } public void setHasAcceptTeamOwnerPolicy(boolean hasAcceptTeamOwnerPolicy) { this.hasAcceptTeamOwnerPolicy = hasAcceptTeamOwnerPolicy; } public String getJoinTeamName() { return joinTeamName; } public void setJoinTeamName(String joinTeamName) { this.joinTeamName = joinTeamName; } public String getErrorTeamDescription() { return errorTeamDescription; } public void setErrorTeamDescription(String errorTeamDescription) { this.errorTeamDescription = errorTeamDescription; } public String getErrorTeamWebsite() { return errorTeamWebsite; } public void setErrorTeamWebsite(String errorTeamWebsite) { this.errorTeamWebsite = errorTeamWebsite; } public String getErrorTeamOwnerPolicy() { return errorTeamOwnerPolicy; } public void setErrorTeamOwnerPolicy(String errorTeamOwnerPolicy) { this.errorTeamOwnerPolicy = errorTeamOwnerPolicy; } public String getErrorTeamName() { return errorTeamName; } public void setErrorTeamName(String errorTeamName) { this.errorTeamName = errorTeamName; } }
package org.openspaces.pu.service; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; public class InvocationResult implements Externalizable{ private static final long serialVersionUID = 1L; private int instanceId; private boolean executeOnce; private Object executeOnceResult; private Object executeOnAllResult; public int getInstanceId() { return instanceId; } public void setInstanceId(int instanceId) { this.instanceId = instanceId; } public boolean isExecuteOnce() { return executeOnce; } public void setExecuteOnce(boolean executeOnce) { this.executeOnce = executeOnce; } public Object getExecuteOnceResult() { return executeOnceResult; } public void setExecuteOnceResult(Object executeOnceResult) { this.executeOnceResult = executeOnceResult; } public Object getExecuteOnAllResult() { return executeOnAllResult; } public void setExecuteOnAllResult(Object executeOnAllResult) { this.executeOnAllResult = executeOnAllResult; } public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(instanceId); out.writeBoolean(executeOnce); out.writeObject(executeOnceResult); out.writeObject(executeOnAllResult); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { instanceId = in.readInt(); executeOnce = in.readBoolean(); executeOnceResult = in.readObject(); executeOnAllResult = in.readObject(); } }
package org.smoothbuild.lang.object.type; import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.params.provider.Arguments.arguments; import static org.smoothbuild.lang.object.type.TestingTypes.a; import static org.smoothbuild.lang.object.type.TestingTypes.array2A; import static org.smoothbuild.lang.object.type.TestingTypes.array2B; import static org.smoothbuild.lang.object.type.TestingTypes.array2Blob; import static org.smoothbuild.lang.object.type.TestingTypes.array2Bool; import static org.smoothbuild.lang.object.type.TestingTypes.array2Nothing; import static org.smoothbuild.lang.object.type.TestingTypes.array2Person; import static org.smoothbuild.lang.object.type.TestingTypes.array2String; import static org.smoothbuild.lang.object.type.TestingTypes.array2Type; import static org.smoothbuild.lang.object.type.TestingTypes.arrayA; import static org.smoothbuild.lang.object.type.TestingTypes.arrayB; import static org.smoothbuild.lang.object.type.TestingTypes.arrayBlob; import static org.smoothbuild.lang.object.type.TestingTypes.arrayBool; import static org.smoothbuild.lang.object.type.TestingTypes.arrayNothing; import static org.smoothbuild.lang.object.type.TestingTypes.arrayPerson; import static org.smoothbuild.lang.object.type.TestingTypes.arrayString; import static org.smoothbuild.lang.object.type.TestingTypes.arrayType; import static org.smoothbuild.lang.object.type.TestingTypes.b; import static org.smoothbuild.lang.object.type.TestingTypes.blob; import static org.smoothbuild.lang.object.type.TestingTypes.bool; import static org.smoothbuild.lang.object.type.TestingTypes.nothing; import static org.smoothbuild.lang.object.type.TestingTypes.person; import static org.smoothbuild.lang.object.type.TestingTypes.string; import static org.smoothbuild.lang.object.type.TestingTypes.type; import static org.smoothbuild.testing.common.AssertCall.assertCall; import static org.smoothbuild.util.Lists.list; import java.util.List; import java.util.Optional; 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; import org.smoothbuild.lang.object.base.Array; import org.smoothbuild.lang.object.base.Blob; import org.smoothbuild.lang.object.base.Bool; import org.smoothbuild.lang.object.base.Nothing; import org.smoothbuild.lang.object.base.SObject; import org.smoothbuild.lang.object.base.SString; import com.google.common.testing.EqualsTester; public class TypeTest { @ParameterizedTest @MethodSource("names") public void name(Type type, String name) { assertThat(type.name()) .isEqualTo(name); } @ParameterizedTest @MethodSource("names") public void quoted_name(Type type, String name) { assertThat(type.q()) .isEqualTo("'" + name + "'"); } @ParameterizedTest @MethodSource("names") public void to_string(Type type, String name) { if (type instanceof ConcreteType concreteType) { assertThat(concreteType.toString()) .isEqualTo("Type(\"" + name + "\"):" + concreteType.hash()); } else { assertThat(type.toString()) .isEqualTo("Type(\"" + name + "\")"); } } public static Stream<Arguments> names() { return Stream.of( arguments(type, "Type"), arguments(bool, "Bool"), arguments(string, "String"), arguments(blob, "Blob"), arguments(nothing, "Nothing"), arguments(person, "Person"), arguments(a, "a"), arguments(arrayType, "[Type]"), arguments(arrayBool, "[Bool]"), arguments(arrayString, "[String]"), arguments(arrayBlob, "[Blob]"), arguments(arrayNothing, "[Nothing]"), arguments(arrayPerson, "[Person]"), arguments(arrayA, "[a]"), arguments(array2Type, "[[Type]]"), arguments(array2Bool, "[[Bool]]"), arguments(array2String, "[[String]]"), arguments(array2Blob, "[[Blob]]"), arguments(array2Nothing, "[[Nothing]]"), arguments(array2Person, "[[Person]]"), arguments(array2A, "[[a]]") ); } @ParameterizedTest @MethodSource("jType_test_data") public void jType(Type type, Class<?> expected) { assertThat(type.jType()) .isEqualTo(expected); } public static List<Arguments> jType_test_data() { return List.of( arguments(type, ConcreteType.class), arguments(bool, Bool.class), arguments(string, SString.class), arguments(blob, Blob.class), arguments(nothing, Nothing.class), arguments(a, SObject.class), arguments(arrayType, Array.class), arguments(arrayBool, Array.class), arguments(arrayString, Array.class), arguments(arrayBlob, Array.class), arguments(arrayNothing, Array.class), arguments(arrayA, Array.class) ); } @ParameterizedTest @MethodSource("coreType_test_data") public void coreType(Type type, Type expected) { assertThat(type.coreType()) .isEqualTo(expected); } public static List<Arguments> coreType_test_data() { return List.of( arguments(type, type), arguments(bool, bool), arguments(string, string), arguments(blob, blob), arguments(nothing, nothing), arguments(person, person), arguments(a, a), arguments(arrayType, type), arguments(arrayBool, bool), arguments(arrayString, string), arguments(arrayBlob, blob), arguments(arrayNothing, nothing), arguments(arrayPerson, person), arguments(arrayA, a), arguments(array2Type, type), arguments(array2Bool, bool), arguments(array2String, string), arguments(array2Blob, blob), arguments(array2Nothing, nothing), arguments(array2Person, person), arguments(array2A, a) ); } @ParameterizedTest @MethodSource("replaceCoreType_test_data") public void replaceCoreType(Type type, Type coreType, Type expected) { assertThat(type.replaceCoreType(coreType)) .isEqualTo(expected); } public static List<Arguments> replaceCoreType_test_data() { return List.of( arguments(type, type, type), arguments(type, bool, bool), arguments(type, string, string), arguments(type, blob, blob), arguments(type, nothing, nothing), arguments(type, person, person), arguments(type, a, a), arguments(bool, type, type), arguments(bool, bool, bool), arguments(bool, string, string), arguments(bool, blob, blob), arguments(bool, nothing, nothing), arguments(bool, person, person), arguments(bool, a, a), arguments(string, type, type), arguments(string, bool, bool), arguments(string, string, string), arguments(string, blob, blob), arguments(string, nothing, nothing), arguments(string, person, person), arguments(string, a, a), arguments(blob, type, type), arguments(blob, bool, bool), arguments(blob, string, string), arguments(blob, blob, blob), arguments(blob, nothing, nothing), arguments(blob, person, person), arguments(blob, a, a), arguments(nothing, type, type), arguments(nothing, bool, bool), arguments(nothing, string, string), arguments(nothing, blob, blob), arguments(nothing, nothing, nothing), arguments(nothing, person, person), arguments(nothing, a, a), arguments(person, type, type), arguments(person, bool, bool), arguments(person, string, string), arguments(person, blob, blob), arguments(person, nothing, nothing), arguments(person, person, person), arguments(person, a, a), arguments(type, arrayType, arrayType), arguments(type, arrayBool, arrayBool), arguments(type, arrayString, arrayString), arguments(type, arrayBlob, arrayBlob), arguments(type, arrayNothing, arrayNothing), arguments(type, arrayPerson, arrayPerson), arguments(type, arrayA, arrayA), arguments(bool, arrayType, arrayType), arguments(bool, arrayBool, arrayBool), arguments(bool, arrayString, arrayString), arguments(bool, arrayBlob, arrayBlob), arguments(bool, arrayNothing, arrayNothing), arguments(bool, arrayPerson, arrayPerson), arguments(bool, arrayA, arrayA), arguments(string, arrayType, arrayType), arguments(string, arrayBool, arrayBool), arguments(string, arrayString, arrayString), arguments(string, arrayBlob, arrayBlob), arguments(string, arrayNothing, arrayNothing), arguments(string, arrayPerson, arrayPerson), arguments(string, arrayA, arrayA), arguments(blob, arrayType, arrayType), arguments(blob, arrayBool, arrayBool), arguments(blob, arrayString, arrayString), arguments(blob, arrayBlob, arrayBlob), arguments(blob, arrayNothing, arrayNothing), arguments(blob, arrayPerson, arrayPerson), arguments(blob, arrayA, arrayA), arguments(nothing, arrayType, arrayType), arguments(nothing, arrayBool, arrayBool), arguments(nothing, arrayString, arrayString), arguments(nothing, arrayBlob, arrayBlob), arguments(nothing, arrayNothing, arrayNothing), arguments(nothing, arrayPerson, arrayPerson), arguments(nothing, arrayA, arrayA), arguments(person, arrayType, arrayType), arguments(person, arrayBool, arrayBool), arguments(person, arrayString, arrayString), arguments(person, arrayBlob, arrayBlob), arguments(person, arrayNothing, arrayNothing), arguments(person, arrayPerson, arrayPerson), arguments(person, arrayA, arrayA), arguments(a, arrayType, arrayType), arguments(a, arrayBool, arrayBool), arguments(a, arrayString, arrayString), arguments(a, arrayBlob, arrayBlob), arguments(a, arrayNothing, arrayNothing), arguments(a, arrayPerson, arrayPerson), arguments(a, arrayA, arrayA), arguments(arrayType, type, arrayType), arguments(arrayType, bool, arrayBool), arguments(arrayType, string, arrayString), arguments(arrayType, blob, arrayBlob), arguments(arrayType, nothing, arrayNothing), arguments(arrayType, person, arrayPerson), arguments(arrayType, a, arrayA), arguments(arrayBool, type, arrayType), arguments(arrayBool, bool, arrayBool), arguments(arrayBool, string, arrayString), arguments(arrayBool, blob, arrayBlob), arguments(arrayBool, nothing, arrayNothing), arguments(arrayBool, person, arrayPerson), arguments(arrayBool, a, arrayA), arguments(arrayString, type, arrayType), arguments(arrayString, bool, arrayBool), arguments(arrayString, string, arrayString), arguments(arrayString, blob, arrayBlob), arguments(arrayString, nothing, arrayNothing), arguments(arrayString, person, arrayPerson), arguments(arrayString, a, arrayA), arguments(arrayBlob, type, arrayType), arguments(arrayBlob, bool, arrayBool), arguments(arrayBlob, string, arrayString), arguments(arrayBlob, blob, arrayBlob), arguments(arrayBlob, nothing, arrayNothing), arguments(arrayBlob, person, arrayPerson), arguments(arrayBlob, a, arrayA), arguments(arrayNothing, type, arrayType), arguments(arrayNothing, bool, arrayBool), arguments(arrayNothing, string, arrayString), arguments(arrayNothing, blob, arrayBlob), arguments(arrayNothing, nothing, arrayNothing), arguments(arrayNothing, person, arrayPerson), arguments(arrayNothing, a, arrayA), arguments(arrayPerson, type, arrayType), arguments(arrayPerson, bool, arrayBool), arguments(arrayPerson, string, arrayString), arguments(arrayPerson, blob, arrayBlob), arguments(arrayPerson, nothing, arrayNothing), arguments(arrayPerson, person, arrayPerson), arguments(arrayPerson, a, arrayA), arguments(arrayA, type, arrayType), arguments(arrayA, bool, arrayBool), arguments(arrayA, string, arrayString), arguments(arrayA, blob, arrayBlob), arguments(arrayA, nothing, arrayNothing), arguments(arrayA, person, arrayPerson), arguments(arrayA, a, arrayA), arguments(arrayType, arrayType, array2Type), arguments(arrayType, arrayBool, array2Bool), arguments(arrayType, arrayString, array2String), arguments(arrayType, arrayBlob, array2Blob), arguments(arrayType, arrayNothing, array2Nothing), arguments(arrayType, arrayPerson, array2Person), arguments(arrayType, arrayA, array2A), arguments(arrayBool, arrayType, array2Type), arguments(arrayBool, arrayBool, array2Bool), arguments(arrayBool, arrayString, array2String), arguments(arrayBool, arrayBlob, array2Blob), arguments(arrayBool, arrayNothing, array2Nothing), arguments(arrayBool, arrayPerson, array2Person), arguments(arrayBool, arrayA, array2A), arguments(arrayString, arrayType, array2Type), arguments(arrayString, arrayBool, array2Bool), arguments(arrayString, arrayString, array2String), arguments(arrayString, arrayBlob, array2Blob), arguments(arrayString, arrayNothing, array2Nothing), arguments(arrayString, arrayPerson, array2Person), arguments(arrayString, arrayA, array2A), arguments(arrayBlob, arrayType, array2Type), arguments(arrayBlob, arrayBool, array2Bool), arguments(arrayBlob, arrayString, array2String), arguments(arrayBlob, arrayBlob, array2Blob), arguments(arrayBlob, arrayNothing, array2Nothing), arguments(arrayBlob, arrayPerson, array2Person), arguments(arrayBlob, arrayA, array2A), arguments(arrayNothing, arrayType, array2Type), arguments(arrayNothing, arrayBool, array2Bool), arguments(arrayNothing, arrayString, array2String), arguments(arrayNothing, arrayBlob, array2Blob), arguments(arrayNothing, arrayNothing, array2Nothing), arguments(arrayNothing, arrayPerson, array2Person), arguments(arrayNothing, arrayA, array2A), arguments(arrayPerson, arrayType, array2Type), arguments(arrayPerson, arrayBool, array2Bool), arguments(arrayPerson, arrayString, array2String), arguments(arrayPerson, arrayBlob, array2Blob), arguments(arrayPerson, arrayNothing, array2Nothing), arguments(arrayPerson, arrayPerson, array2Person), arguments(arrayPerson, arrayA, array2A), arguments(arrayA, arrayType, array2Type), arguments(arrayA, arrayBool, array2Bool), arguments(arrayA, arrayString, array2String), arguments(arrayA, arrayBlob, array2Blob), arguments(arrayA, arrayNothing, array2Nothing), arguments(arrayA, arrayPerson, array2Person), arguments(arrayA, arrayA, array2A) ); } @ParameterizedTest @MethodSource("coreDepth_test_data") public void coreDepth(Type type, int expected) { assertThat(type.coreDepth()) .isEqualTo(expected); } public static List<Arguments> coreDepth_test_data() { return List.of( arguments(type, 0), arguments(bool, 0), arguments(string, 0), arguments(blob, 0), arguments(nothing, 0), arguments(person, 0), arguments(a, 0), arguments(arrayType, 1), arguments(arrayBool, 1), arguments(arrayString, 1), arguments(arrayBlob, 1), arguments(arrayNothing, 1), arguments(arrayPerson, 1), arguments(arrayA, 1), arguments(array2Type, 2), arguments(array2Bool, 2), arguments(array2String, 2), arguments(array2Blob, 2), arguments(array2Nothing, 2), arguments(array2Person, 2), arguments(array2A, 2)); } @ParameterizedTest @MethodSource("changeCoreDepthBy_test_data_with_illegal_values") public void changeCoreDepthBy_fails_for(Type type, int change) { assertCall(() -> type.changeCoreDepthBy(change)) .throwsException(IllegalArgumentException.class); } public static List<Arguments> changeCoreDepthBy_test_data_with_illegal_values() { return List.of( arguments(type, -2), arguments(bool, -2), arguments(string, -2), arguments(nothing, -2), arguments(person, -2), arguments(a, -2), arguments(type, -1), arguments(bool, -1), arguments(string, -1), arguments(nothing, -1), arguments(person, -1), arguments(a, -1), arguments(arrayType, -2), arguments(arrayBool, -2), arguments(arrayString, -2), arguments(arrayNothing, -2), arguments(arrayPerson, -2), arguments(arrayA, -2), arguments(array2Type, -3), arguments(array2Bool, -3), arguments(array2String, -3), arguments(array2Blob, -3), arguments(array2Nothing, -3), arguments(array2Person, -3), arguments(array2A, -3) ); } @ParameterizedTest @MethodSource("changeCoreDepth_test_data") public void changeCoreDepthBy(Type type, int change, Type expected) { assertThat(type.changeCoreDepthBy(change)) .isEqualTo(expected); } public static List<Arguments> changeCoreDepth_test_data() { return List.of( arguments(type, 0, type), arguments(bool, 0, bool), arguments(string, 0, string), arguments(nothing, 0, nothing), arguments(person, 0, person), arguments(a, 0, a), arguments(type, 1, arrayType), arguments(bool, 1, arrayBool), arguments(string, 1, arrayString), arguments(nothing, 1, arrayNothing), arguments(person, 1, arrayPerson), arguments(a, 1, arrayA), arguments(type, 2, array2Type), arguments(bool, 2, array2Bool), arguments(string, 2, array2String), arguments(nothing, 2, array2Nothing), arguments(person, 2, array2Person), arguments(a, 2, array2A), arguments(arrayType, -1, type), arguments(arrayBool, -1, bool), arguments(arrayString, -1, string), arguments(arrayBlob, -1, blob), arguments(arrayNothing, -1, nothing), arguments(arrayPerson, -1, person), arguments(arrayA, -1, a), arguments(arrayType, 0, arrayType), arguments(arrayBool, 0, arrayBool), arguments(arrayString, 0, arrayString), arguments(arrayBlob, 0, arrayBlob), arguments(arrayNothing, 0, arrayNothing), arguments(arrayPerson, 0, arrayPerson), arguments(arrayA, 0, arrayA), arguments(arrayType, 1, array2Type), arguments(arrayBool, 1, array2Bool), arguments(arrayString, 1, array2String), arguments(arrayBlob, 1, array2Blob), arguments(arrayNothing, 1, array2Nothing), arguments(arrayPerson, 1, array2Person), arguments(arrayA, 1, array2A), arguments(array2Type, -2, type), arguments(array2Bool, -2, bool), arguments(array2String, -2, string), arguments(array2Blob, -2, blob), arguments(array2Nothing, -2, nothing), arguments(array2Person, -2, person), arguments(array2A, -2, a), arguments(array2Type, -1, arrayType), arguments(array2Bool, -1, arrayBool), arguments(array2String, -1, arrayString), arguments(array2Blob, -1, arrayBlob), arguments(array2Nothing, -1, arrayNothing), arguments(array2Person, -1, arrayPerson), arguments(array2A, -1, arrayA), arguments(array2Type, 0, array2Type), arguments(array2Bool, 0, array2Bool), arguments(array2String, 0, array2String), arguments(array2Blob, 0, array2Blob), arguments(array2Nothing, 0, array2Nothing), arguments(array2Person, 0, array2Person), arguments(array2A, 0, array2A) ); } @ParameterizedTest @MethodSource("isGeneric_test_data") public void isGeneric(Type type, boolean expected) { assertThat(type.isGeneric()) .isEqualTo(expected); } public static List<Arguments> isGeneric_test_data() { return List.of( arguments(type, false), arguments(bool, false), arguments(string, false), arguments(blob, false), arguments(nothing, false), arguments(person, false), arguments(arrayType, false), arguments(arrayBool, false), arguments(arrayString, false), arguments(arrayBlob, false), arguments(arrayNothing, false), arguments(arrayPerson, false), arguments(array2Type, false), arguments(array2Bool, false), arguments(array2String, false), arguments(array2Blob, false), arguments(array2Nothing, false), arguments(array2Person, false), arguments(a, true), arguments(arrayA, true), arguments(array2A, true), arguments(b, true), arguments(arrayB, true), arguments(array2B, true) ); } @ParameterizedTest @MethodSource("isArray_test_data") public void isArray(Type type, boolean expected) { assertThat(type.isArray()) .isEqualTo(expected); } public static List<Arguments> isArray_test_data() { return List.of( arguments(type, false), arguments(bool, false), arguments(string, false), arguments(blob, false), arguments(nothing, false), arguments(person, false), arguments(a, false), arguments(arrayType, true), arguments(arrayString, true), arguments(arrayBool, true), arguments(arrayBlob, true), arguments(arrayNothing, true), arguments(arrayPerson, true), arguments(arrayA, true), arguments(array2Type, true), arguments(array2Bool, true), arguments(array2String, true), arguments(array2Blob, true), arguments(array2Nothing, true), arguments(array2Person, true), arguments(array2A, true) ); } @ParameterizedTest @MethodSource("superType_test_data") public void superType(Type type, Type expected) { assertThat(type.superType()) .isEqualTo(expected); } public static List<Arguments> superType_test_data() { return List.of( arguments(type, null), arguments(bool, null), arguments(string, null), arguments(blob, null), arguments(nothing, null), arguments(person, string), arguments(a, null), arguments(arrayType, null), arguments(arrayBool, null), arguments(arrayString, null), arguments(arrayBlob, null), arguments(arrayNothing, null), arguments(arrayPerson, arrayString), arguments(arrayA, null), arguments(array2Type, null), arguments(array2Bool, null), arguments(array2String, null), arguments(array2Blob, null), arguments(array2Nothing, null), arguments(array2Person, array2String), arguments(array2A, null) ); } @ParameterizedTest @MethodSource("hierarchy_test_data") public void hierarchy(List<Type> hierarchy) { Type root = hierarchy.get(hierarchy.size() - 1); assertThat(root.hierarchy()) .isEqualTo(hierarchy); } public static List<Arguments> hierarchy_test_data() { return List.of( arguments(list(type)), arguments(list(string)), arguments(list(bool)), arguments(list(string, person)), arguments(list(nothing)), arguments(list(a)), arguments(list(arrayType)), arguments(list(arrayBool)), arguments(list(arrayString)), arguments(list(arrayString, arrayPerson)), arguments(list(arrayNothing)), arguments(list(arrayA)), arguments(list(array2Type)), arguments(list(array2Bool)), arguments(list(array2String)), arguments(list(array2String, array2Person)), arguments(list(array2Nothing)), arguments(list(array2A))); } @ParameterizedTest @MethodSource("isAssignableFrom_test_data") public void isAssignableFrom(Type destination, Type source, boolean expected) { assertThat(destination.isAssignableFrom(source)) .isEqualTo(expected); } public static List<Arguments> isAssignableFrom_test_data() { return List.of( arguments(type, type, true), arguments(type, bool, false), arguments(type, string, false), arguments(type, blob, false), arguments(type, person, false), arguments(type, nothing, true), arguments(type, a, false), arguments(type, arrayType, false), arguments(type, arrayBool, false), arguments(type, arrayString, false), arguments(type, arrayBlob, false), arguments(type, arrayPerson, false), arguments(type, arrayNothing, false), arguments(type, arrayA, false), arguments(type, array2Type, false), arguments(type, array2Bool, false), arguments(type, array2String, false), arguments(type, array2Blob, false), arguments(type, array2Person, false), arguments(type, array2Nothing, false), arguments(type, array2A, false), arguments(bool, type, false), arguments(bool, bool, true), arguments(bool, string, false), arguments(bool, blob, false), arguments(bool, person, false), arguments(bool, nothing, true), arguments(bool, a, false), arguments(bool, arrayType, false), arguments(bool, arrayBool, false), arguments(bool, arrayString, false), arguments(bool, arrayBlob, false), arguments(bool, arrayPerson, false), arguments(bool, arrayNothing, false), arguments(bool, arrayA, false), arguments(bool, array2Type, false), arguments(bool, array2Bool, false), arguments(bool, array2String, false), arguments(bool, array2Blob, false), arguments(bool, array2Person, false), arguments(bool, array2Nothing, false), arguments(bool, array2A, false), arguments(string, type, false), arguments(string, bool, false), arguments(string, string, true), arguments(string, blob, false), arguments(string, person, true), arguments(string, nothing, true), arguments(string, a, false), arguments(string, arrayType, false), arguments(string, arrayBool, false), arguments(string, arrayString, false), arguments(string, arrayBlob, false), arguments(string, arrayPerson, false), arguments(string, arrayNothing, false), arguments(string, arrayA, false), arguments(string, array2Type, false), arguments(string, array2Bool, false), arguments(string, array2String, false), arguments(string, array2Blob, false), arguments(string, array2Person, false), arguments(string, array2Nothing, false), arguments(string, array2A, false), arguments(blob, type, false), arguments(blob, bool, false), arguments(blob, string, false), arguments(blob, blob, true), arguments(blob, person, false), arguments(blob, nothing, true), arguments(blob, a, false), arguments(blob, arrayType, false), arguments(blob, arrayBool, false), arguments(blob, arrayString, false), arguments(blob, arrayBlob, false), arguments(blob, arrayPerson, false), arguments(blob, arrayNothing, false), arguments(blob, arrayA, false), arguments(blob, array2Type, false), arguments(blob, array2Bool, false), arguments(blob, array2String, false), arguments(blob, array2Blob, false), arguments(blob, array2Person, false), arguments(blob, array2Nothing, false), arguments(blob, array2A, false), arguments(person, type, false), arguments(person, bool, false), arguments(person, string, false), arguments(person, blob, false), arguments(person, person, true), arguments(person, nothing, true), arguments(person, a, false), arguments(person, arrayType, false), arguments(person, arrayBool, false), arguments(person, arrayString, false), arguments(person, arrayBlob, false), arguments(person, arrayPerson, false), arguments(person, arrayNothing, false), arguments(person, arrayA, false), arguments(person, array2Type, false), arguments(person, array2Bool, false), arguments(person, array2String, false), arguments(person, array2Blob, false), arguments(person, array2Person, false), arguments(person, array2Nothing, false), arguments(person, array2A, false), arguments(nothing, type, false), arguments(nothing, bool, false), arguments(nothing, string, false), arguments(nothing, blob, false), arguments(nothing, person, false), arguments(nothing, nothing, true), arguments(nothing, a, false), arguments(nothing, arrayType, false), arguments(nothing, arrayBool, false), arguments(nothing, arrayString, false), arguments(nothing, arrayBlob, false), arguments(nothing, arrayPerson, false), arguments(nothing, arrayNothing, false), arguments(nothing, arrayA, false), arguments(nothing, array2Type, false), arguments(nothing, array2Bool, false), arguments(nothing, array2String, false), arguments(nothing, array2Blob, false), arguments(nothing, array2Person, false), arguments(nothing, array2Nothing, false), arguments(nothing, array2A, false), arguments(a, type, false), arguments(a, bool, false), arguments(a, string, false), arguments(a, blob, false), arguments(a, person, false), arguments(a, nothing, true), arguments(a, a, true), arguments(a, b, false), arguments(a, arrayType, false), arguments(a, arrayBool, false), arguments(a, arrayString, false), arguments(a, arrayBlob, false), arguments(a, arrayPerson, false), arguments(a, arrayNothing, false), arguments(a, arrayA, false), arguments(a, arrayB, false), arguments(a, array2Type, false), arguments(a, array2Bool, false), arguments(a, array2String, false), arguments(a, array2Blob, false), arguments(a, array2Person, false), arguments(a, array2Nothing, false), arguments(a, array2A, false), arguments(a, array2B, false), arguments(arrayType, type, false), arguments(arrayType, bool, false), arguments(arrayType, string, false), arguments(arrayType, blob, false), arguments(arrayType, person, false), arguments(arrayType, nothing, true), arguments(arrayType, a, false), arguments(arrayType, arrayType, true), arguments(arrayType, arrayBool, false), arguments(arrayType, arrayString, false), arguments(arrayType, arrayBlob, false), arguments(arrayType, arrayPerson, false), arguments(arrayType, arrayNothing, true), arguments(arrayType, arrayA, false), arguments(arrayType, array2Type, false), arguments(arrayType, array2Bool, false), arguments(arrayType, array2String, false), arguments(arrayType, array2Blob, false), arguments(arrayType, array2Person, false), arguments(arrayType, array2Nothing, false), arguments(arrayType, array2A, false), arguments(arrayString, type, false), arguments(arrayString, bool, false), arguments(arrayString, string, false), arguments(arrayString, blob, false), arguments(arrayString, person, false), arguments(arrayString, nothing, true), arguments(arrayString, a, false), arguments(arrayString, arrayType, false), arguments(arrayString, arrayBool, false), arguments(arrayString, arrayString, true), arguments(arrayString, arrayBlob, false), arguments(arrayString, arrayPerson, true), arguments(arrayString, arrayNothing, true), arguments(arrayString, arrayA, false), arguments(arrayString, array2Type, false), arguments(arrayString, array2Bool, false), arguments(arrayString, array2String, false), arguments(arrayString, array2Blob, false), arguments(arrayString, array2Person, false), arguments(arrayString, array2Nothing, false), arguments(arrayString, array2A, false), arguments(arrayBool, type, false), arguments(arrayBool, bool, false), arguments(arrayBool, string, false), arguments(arrayBool, blob, false), arguments(arrayBool, person, false), arguments(arrayBool, nothing, true), arguments(arrayBool, a, false), arguments(arrayBool, arrayType, false), arguments(arrayBool, arrayBool, true), arguments(arrayBool, arrayString, false), arguments(arrayBool, arrayBlob, false), arguments(arrayBool, arrayPerson, false), arguments(arrayBool, arrayNothing, true), arguments(arrayBool, arrayA, false), arguments(arrayBool, array2Type, false), arguments(arrayBool, array2Bool, false), arguments(arrayBool, array2String, false), arguments(arrayBool, array2Blob, false), arguments(arrayBool, array2Person, false), arguments(arrayBool, array2Nothing, false), arguments(arrayBool, array2A, false), arguments(arrayBlob, type, false), arguments(arrayBlob, bool, false), arguments(arrayBlob, string, false), arguments(arrayBlob, blob, false), arguments(arrayBlob, person, false), arguments(arrayBlob, nothing, true), arguments(arrayBlob, a, false), arguments(arrayBlob, arrayType, false), arguments(arrayBlob, arrayBool, false), arguments(arrayBlob, arrayString, false), arguments(arrayBlob, arrayBlob, true), arguments(arrayBlob, arrayPerson, false), arguments(arrayBlob, arrayNothing, true), arguments(arrayBlob, arrayA, false), arguments(arrayBlob, array2Type, false), arguments(arrayBlob, array2Bool, false), arguments(arrayBlob, array2String, false), arguments(arrayBlob, array2Blob, false), arguments(arrayBlob, array2Person, false), arguments(arrayBlob, array2Nothing, false), arguments(arrayBlob, array2A, false), arguments(arrayPerson, type, false), arguments(arrayPerson, bool, false), arguments(arrayPerson, string, false), arguments(arrayPerson, blob, false), arguments(arrayPerson, person, false), arguments(arrayPerson, nothing, true), arguments(arrayPerson, a, false), arguments(arrayPerson, arrayType, false), arguments(arrayPerson, arrayBool, false), arguments(arrayPerson, arrayString, false), arguments(arrayPerson, arrayBlob, false), arguments(arrayPerson, arrayPerson, true), arguments(arrayPerson, arrayNothing, true), arguments(arrayPerson, arrayA, false), arguments(arrayPerson, array2Type, false), arguments(arrayPerson, array2Bool, false), arguments(arrayPerson, array2String, false), arguments(arrayPerson, array2Blob, false), arguments(arrayPerson, array2Person, false), arguments(arrayPerson, array2Nothing, false), arguments(arrayPerson, array2A, false), arguments(arrayNothing, type, false), arguments(arrayNothing, bool, false), arguments(arrayNothing, string, false), arguments(arrayNothing, blob, false), arguments(arrayNothing, person, false), arguments(arrayNothing, nothing, true), arguments(arrayNothing, a, false), arguments(arrayNothing, arrayType, false), arguments(arrayNothing, arrayBool, false), arguments(arrayNothing, arrayString, false), arguments(arrayNothing, arrayBlob, false), arguments(arrayNothing, arrayPerson, false), arguments(arrayNothing, arrayNothing, true), arguments(arrayNothing, arrayA, false), arguments(arrayNothing, array2Type, false), arguments(arrayNothing, array2Bool, false), arguments(arrayNothing, array2String, false), arguments(arrayNothing, array2Blob, false), arguments(arrayNothing, array2Person, false), arguments(arrayNothing, array2Nothing, false), arguments(arrayNothing, array2A, false), arguments(arrayA, type, false), arguments(arrayA, bool, false), arguments(arrayA, string, false), arguments(arrayA, blob, false), arguments(arrayA, person, false), arguments(arrayA, nothing, true), arguments(arrayA, a, false), arguments(arrayA, b, false), arguments(arrayA, arrayType, false), arguments(arrayA, arrayBool, false), arguments(arrayA, arrayString, false), arguments(arrayA, arrayBlob, false), arguments(arrayA, arrayPerson, false), arguments(arrayA, arrayNothing, true), arguments(arrayA, arrayA, true), arguments(arrayA, arrayB, false), arguments(arrayA, array2Type, false), arguments(arrayA, array2Bool, false), arguments(arrayA, array2String, false), arguments(arrayA, array2Blob, false), arguments(arrayA, array2Person, false), arguments(arrayA, array2Nothing, false), arguments(arrayA, array2A, false), arguments(arrayA, array2B, false), arguments(array2Type, type, false), arguments(array2Type, bool, false), arguments(array2Type, string, false), arguments(array2Type, blob, false), arguments(array2Type, person, false), arguments(array2Type, nothing, true), arguments(array2Type, a, false), arguments(array2Type, arrayType, false), arguments(array2Type, arrayBool, false), arguments(array2Type, arrayString, false), arguments(array2Type, arrayBlob, false), arguments(array2Type, arrayPerson, false), arguments(array2Type, arrayNothing, true), arguments(array2Type, arrayA, false), arguments(array2Type, array2Type, true), arguments(array2Type, array2Bool, false), arguments(array2Type, array2String, false), arguments(array2Type, array2Blob, false), arguments(array2Type, array2Person, false), arguments(array2Type, array2Nothing, true), arguments(array2Type, array2A, false), arguments(array2Bool, type, false), arguments(array2Bool, bool, false), arguments(array2Bool, string, false), arguments(array2Bool, blob, false), arguments(array2Bool, person, false), arguments(array2Bool, nothing, true), arguments(array2Bool, a, false), arguments(array2Bool, arrayType, false), arguments(array2Bool, arrayBool, false), arguments(array2Bool, arrayString, false), arguments(array2Bool, arrayBlob, false), arguments(array2Bool, arrayPerson, false), arguments(array2Bool, arrayNothing, true), arguments(array2Bool, arrayA, false), arguments(array2Bool, array2Type, false), arguments(array2Bool, array2Bool, true), arguments(array2Bool, array2String, false), arguments(array2Bool, array2Blob, false), arguments(array2Bool, array2Person, false), arguments(array2Bool, array2Nothing, true), arguments(array2Bool, array2A, false), arguments(array2String, type, false), arguments(array2String, bool, false), arguments(array2String, string, false), arguments(array2String, blob, false), arguments(array2String, person, false), arguments(array2String, nothing, true), arguments(array2String, a, false), arguments(array2String, arrayType, false), arguments(array2String, arrayBool, false), arguments(array2String, arrayString, false), arguments(array2String, arrayBlob, false), arguments(array2String, arrayPerson, false), arguments(array2String, arrayNothing, true), arguments(array2String, arrayA, false), arguments(array2String, array2Type, false), arguments(array2String, array2Bool, false), arguments(array2String, array2String, true), arguments(array2String, array2Blob, false), arguments(array2String, array2Person, true), arguments(array2String, array2Nothing, true), arguments(array2String, array2A, false), arguments(array2Blob, type, false), arguments(array2Blob, bool, false), arguments(array2Blob, string, false), arguments(array2Blob, blob, false), arguments(array2Blob, person, false), arguments(array2Blob, nothing, true), arguments(array2Blob, a, false), arguments(array2Blob, arrayType, false), arguments(array2Blob, arrayBool, false), arguments(array2Blob, arrayString, false), arguments(array2Blob, arrayBlob, false), arguments(array2Blob, arrayPerson, false), arguments(array2Blob, arrayNothing, true), arguments(array2Blob, arrayA, false), arguments(array2Blob, array2Type, false), arguments(array2Blob, array2Bool, false), arguments(array2Blob, array2String, false), arguments(array2Blob, array2Blob, true), arguments(array2Blob, array2Person, false), arguments(array2Blob, array2Nothing, true), arguments(array2Blob, array2A, false), arguments(array2Person, type, false), arguments(array2Person, bool, false), arguments(array2Person, string, false), arguments(array2Person, blob, false), arguments(array2Person, person, false), arguments(array2Person, nothing, true), arguments(array2Person, a, false), arguments(array2Person, arrayType, false), arguments(array2Person, arrayBool, false), arguments(array2Person, arrayString, false), arguments(array2Person, arrayBlob, false), arguments(array2Person, arrayPerson, false), arguments(array2Person, arrayNothing, true), arguments(array2Person, arrayA, false), arguments(array2Person, array2Type, false), arguments(array2Person, array2Bool, false), arguments(array2Person, array2String, false), arguments(array2Person, array2Blob, false), arguments(array2Person, array2Person, true), arguments(array2Person, array2Nothing, true), arguments(array2Person, array2A, false), arguments(array2Nothing, type, false), arguments(array2Nothing, bool, false), arguments(array2Nothing, string, false), arguments(array2Nothing, blob, false), arguments(array2Nothing, person, false), arguments(array2Nothing, nothing, true), arguments(array2Nothing, a, false), arguments(array2Nothing, arrayType, false), arguments(array2Nothing, arrayBool, false), arguments(array2Nothing, arrayString, false), arguments(array2Nothing, arrayBlob, false), arguments(array2Nothing, arrayPerson, false), arguments(array2Nothing, arrayNothing, true), arguments(array2Nothing, arrayA, false), arguments(array2Nothing, array2Type, false), arguments(array2Nothing, array2Bool, false), arguments(array2Nothing, array2String, false), arguments(array2Nothing, array2Blob, false), arguments(array2Nothing, array2Person, false), arguments(array2Nothing, array2Nothing, true), arguments(array2Nothing, array2A, false), arguments(array2A, type, false), arguments(array2A, bool, false), arguments(array2A, string, false), arguments(array2A, blob, false), arguments(array2A, person, false), arguments(array2A, nothing, true), arguments(array2A, a, false), arguments(array2A, b, false), arguments(array2A, arrayType, false), arguments(array2A, arrayBool, false), arguments(array2A, arrayString, false), arguments(array2A, arrayBlob, false), arguments(array2A, arrayPerson, false), arguments(array2A, arrayNothing, true), arguments(array2A, arrayA, false), arguments(array2A, arrayB, false), arguments(array2A, array2Type, false), arguments(array2A, array2Bool, false), arguments(array2A, array2String, false), arguments(array2A, array2Blob, false), arguments(array2A, array2Person, false), arguments(array2A, array2Nothing, true), arguments(array2A, array2A, true), arguments(array2A, array2B, false) ); } @ParameterizedTest @MethodSource("isParamAssignableFrom_test_data") public void isParamAssignableFrom(Type destination, Type source, boolean expected) { assertThat(destination.isParamAssignableFrom(source)) .isEqualTo(expected); } public static List<Arguments> isParamAssignableFrom_test_data() { return List.of( arguments(type, type, true), arguments(type, bool, false), arguments(type, string, false), arguments(type, blob, false), arguments(type, person, false), arguments(type, nothing, true), arguments(type, a, false), arguments(type, arrayType, false), arguments(type, arrayBool, false), arguments(type, arrayString, false), arguments(type, arrayBlob, false), arguments(type, arrayPerson, false), arguments(type, arrayNothing, false), arguments(type, arrayA, false), arguments(type, array2Type, false), arguments(type, array2Bool, false), arguments(type, array2String, false), arguments(type, array2Blob, false), arguments(type, array2Person, false), arguments(type, array2Nothing, false), arguments(type, array2A, false), arguments(bool, type, false), arguments(bool, bool, true), arguments(bool, string, false), arguments(bool, blob, false), arguments(bool, person, false), arguments(bool, nothing, true), arguments(bool, a, false), arguments(bool, arrayType, false), arguments(bool, arrayBool, false), arguments(bool, arrayString, false), arguments(bool, arrayBlob, false), arguments(bool, arrayPerson, false), arguments(bool, arrayNothing, false), arguments(bool, arrayA, false), arguments(bool, array2Type, false), arguments(bool, array2Bool, false), arguments(bool, array2String, false), arguments(bool, array2Blob, false), arguments(bool, array2Person, false), arguments(bool, array2Nothing, false), arguments(bool, array2A, false), arguments(string, type, false), arguments(string, bool, false), arguments(string, string, true), arguments(string, blob, false), arguments(string, person, true), arguments(string, nothing, true), arguments(string, a, false), arguments(string, arrayType, false), arguments(string, arrayBool, false), arguments(string, arrayString, false), arguments(string, arrayBlob, false), arguments(string, arrayPerson, false), arguments(string, arrayNothing, false), arguments(string, arrayA, false), arguments(string, array2Type, false), arguments(string, array2Bool, false), arguments(string, array2String, false), arguments(string, array2Blob, false), arguments(string, array2Person, false), arguments(string, array2Nothing, false), arguments(string, array2A, false), arguments(blob, type, false), arguments(blob, bool, false), arguments(blob, string, false), arguments(blob, blob, true), arguments(blob, person, false), arguments(blob, nothing, true), arguments(blob, a, false), arguments(blob, arrayType, false), arguments(blob, arrayBool, false), arguments(blob, arrayString, false), arguments(blob, arrayBlob, false), arguments(blob, arrayPerson, false), arguments(blob, arrayNothing, false), arguments(blob, arrayA, false), arguments(blob, array2Type, false), arguments(blob, array2Bool, false), arguments(blob, array2String, false), arguments(blob, array2Blob, false), arguments(blob, array2Person, false), arguments(blob, array2Nothing, false), arguments(blob, array2A, false), arguments(person, type, false), arguments(person, bool, false), arguments(person, string, false), arguments(person, blob, false), arguments(person, person, true), arguments(person, nothing, true), arguments(person, a, false), arguments(person, arrayType, false), arguments(person, arrayBool, false), arguments(person, arrayString, false), arguments(person, arrayBlob, false), arguments(person, arrayPerson, false), arguments(person, arrayNothing, false), arguments(person, arrayA, false), arguments(person, array2Type, false), arguments(person, array2Bool, false), arguments(person, array2String, false), arguments(person, array2Blob, false), arguments(person, array2Person, false), arguments(person, array2Nothing, false), arguments(person, array2A, false), arguments(nothing, type, false), arguments(nothing, bool, false), arguments(nothing, string, false), arguments(nothing, blob, false), arguments(nothing, person, false), arguments(nothing, nothing, true), arguments(nothing, a, false), arguments(nothing, arrayType, false), arguments(nothing, arrayBool, false), arguments(nothing, arrayString, false), arguments(nothing, arrayBlob, false), arguments(nothing, arrayPerson, false), arguments(nothing, arrayNothing, false), arguments(nothing, arrayA, false), arguments(nothing, array2Type, false), arguments(nothing, array2Bool, false), arguments(nothing, array2String, false), arguments(nothing, array2Blob, false), arguments(nothing, array2Person, false), arguments(nothing, array2Nothing, false), arguments(nothing, array2A, false), arguments(a, type, true), arguments(a, bool, true), arguments(a, string, true), arguments(a, blob, true), arguments(a, person, true), arguments(a, nothing, true), arguments(a, a, true), arguments(a, b, true), arguments(a, arrayType, true), arguments(a, arrayBool, true), arguments(a, arrayString, true), arguments(a, arrayBlob, true), arguments(a, arrayPerson, true), arguments(a, arrayNothing, true), arguments(a, arrayA, true), arguments(a, arrayB, true), arguments(a, array2Type, true), arguments(a, array2Bool, true), arguments(a, array2String, true), arguments(a, array2Blob, true), arguments(a, array2Person, true), arguments(a, array2Nothing, true), arguments(a, array2A, true), arguments(a, array2B, true), arguments(arrayType, type, false), arguments(arrayType, bool, false), arguments(arrayType, string, false), arguments(arrayType, blob, false), arguments(arrayType, person, false), arguments(arrayType, nothing, true), arguments(arrayType, a, false), arguments(arrayType, arrayType, true), arguments(arrayType, arrayBool, false), arguments(arrayType, arrayString, false), arguments(arrayType, arrayBlob, false), arguments(arrayType, arrayPerson, false), arguments(arrayType, arrayNothing, true), arguments(arrayType, arrayA, false), arguments(arrayType, array2Type, false), arguments(arrayType, array2Bool, false), arguments(arrayType, array2String, false), arguments(arrayType, array2Blob, false), arguments(arrayType, array2Person, false), arguments(arrayType, array2Nothing, false), arguments(arrayType, array2A, false), arguments(arrayBool, type, false), arguments(arrayBool, bool, false), arguments(arrayBool, string, false), arguments(arrayBool, blob, false), arguments(arrayBool, person, false), arguments(arrayBool, nothing, true), arguments(arrayBool, a, false), arguments(arrayBool, arrayType, false), arguments(arrayBool, arrayBool, true), arguments(arrayBool, arrayString, false), arguments(arrayBool, arrayBlob, false), arguments(arrayBool, arrayPerson, false), arguments(arrayBool, arrayNothing, true), arguments(arrayBool, arrayA, false), arguments(arrayBool, array2Type, false), arguments(arrayBool, array2Bool, false), arguments(arrayBool, array2String, false), arguments(arrayBool, array2Blob, false), arguments(arrayBool, array2Person, false), arguments(arrayBool, array2Nothing, false), arguments(arrayBool, array2A, false), arguments(arrayString, type, false), arguments(arrayString, bool, false), arguments(arrayString, string, false), arguments(arrayString, blob, false), arguments(arrayString, person, false), arguments(arrayString, nothing, true), arguments(arrayString, a, false), arguments(arrayString, arrayType, false), arguments(arrayString, arrayBool, false), arguments(arrayString, arrayString, true), arguments(arrayString, arrayBlob, false), arguments(arrayString, arrayPerson, true), arguments(arrayString, arrayNothing, true), arguments(arrayString, arrayA, false), arguments(arrayString, array2Type, false), arguments(arrayString, array2Bool, false), arguments(arrayString, array2String, false), arguments(arrayString, array2Blob, false), arguments(arrayString, array2Person, false), arguments(arrayString, array2Nothing, false), arguments(arrayString, array2A, false), arguments(arrayBlob, type, false), arguments(arrayBlob, bool, false), arguments(arrayBlob, string, false), arguments(arrayBlob, blob, false), arguments(arrayBlob, person, false), arguments(arrayBlob, nothing, true), arguments(arrayBlob, a, false), arguments(arrayBlob, arrayType, false), arguments(arrayBlob, arrayBool, false), arguments(arrayBlob, arrayString, false), arguments(arrayBlob, arrayBlob, true), arguments(arrayBlob, arrayPerson, false), arguments(arrayBlob, arrayNothing, true), arguments(arrayBlob, arrayA, false), arguments(arrayBlob, array2Type, false), arguments(arrayBlob, array2Bool, false), arguments(arrayBlob, array2String, false), arguments(arrayBlob, array2Blob, false), arguments(arrayBlob, array2Person, false), arguments(arrayBlob, array2Nothing, false), arguments(arrayBlob, array2A, false), arguments(arrayPerson, type, false), arguments(arrayPerson, bool, false), arguments(arrayPerson, string, false), arguments(arrayPerson, blob, false), arguments(arrayPerson, person, false), arguments(arrayPerson, nothing, true), arguments(arrayPerson, a, false), arguments(arrayPerson, arrayType, false), arguments(arrayPerson, arrayBool, false), arguments(arrayPerson, arrayString, false), arguments(arrayPerson, arrayBlob, false), arguments(arrayPerson, arrayPerson, true), arguments(arrayPerson, arrayNothing, true), arguments(arrayPerson, arrayA, false), arguments(arrayPerson, array2Type, false), arguments(arrayPerson, array2Bool, false), arguments(arrayPerson, array2String, false), arguments(arrayPerson, array2Blob, false), arguments(arrayPerson, array2Person, false), arguments(arrayPerson, array2Nothing, false), arguments(arrayPerson, array2A, false), arguments(arrayNothing, type, false), arguments(arrayNothing, bool, false), arguments(arrayNothing, string, false), arguments(arrayNothing, blob, false), arguments(arrayNothing, person, false), arguments(arrayNothing, nothing, true), arguments(arrayNothing, a, false), arguments(arrayNothing, arrayType, false), arguments(arrayNothing, arrayBool, false), arguments(arrayNothing, arrayString, false), arguments(arrayNothing, arrayBlob, false), arguments(arrayNothing, arrayPerson, false), arguments(arrayNothing, arrayNothing, true), arguments(arrayNothing, arrayA, false), arguments(arrayNothing, array2Type, false), arguments(arrayNothing, array2Bool, false), arguments(arrayNothing, array2String, false), arguments(arrayNothing, array2Blob, false), arguments(arrayNothing, array2Person, false), arguments(arrayNothing, array2Nothing, false), arguments(arrayNothing, array2A, false), arguments(arrayA, type, false), arguments(arrayA, bool, false), arguments(arrayA, string, false), arguments(arrayA, blob, false), arguments(arrayA, person, false), arguments(arrayA, nothing, true), arguments(arrayA, a, false), arguments(arrayA, b, false), arguments(arrayA, arrayType, true), arguments(arrayA, arrayBool, true), arguments(arrayA, arrayString, true), arguments(arrayA, arrayBlob, true), arguments(arrayA, arrayPerson, true), arguments(arrayA, arrayNothing, true), arguments(arrayA, arrayA, true), arguments(arrayA, arrayB, true), arguments(arrayA, array2Type, true), arguments(arrayA, array2Bool, true), arguments(arrayA, array2String, true), arguments(arrayA, array2Blob, true), arguments(arrayA, array2Person, true), arguments(arrayA, array2Nothing, true), arguments(arrayA, array2A, true), arguments(arrayA, array2B, true), arguments(array2Type, type, false), arguments(array2Type, bool, false), arguments(array2Type, string, false), arguments(array2Type, blob, false), arguments(array2Type, person, false), arguments(array2Type, nothing, true), arguments(array2Type, a, false), arguments(array2Type, arrayType, false), arguments(array2Type, arrayBool, false), arguments(array2Type, arrayString, false), arguments(array2Type, arrayBlob, false), arguments(array2Type, arrayPerson, false), arguments(array2Type, arrayNothing, true), arguments(array2Type, arrayA, false), arguments(array2Type, array2Type, true), arguments(array2Type, array2Bool, false), arguments(array2Type, array2String, false), arguments(array2Type, array2Blob, false), arguments(array2Type, array2Person, false), arguments(array2Type, array2Nothing, true), arguments(array2Type, array2A, false), arguments(array2Bool, type, false), arguments(array2Bool, bool, false), arguments(array2Bool, string, false), arguments(array2Bool, blob, false), arguments(array2Bool, person, false), arguments(array2Bool, nothing, true), arguments(array2Bool, a, false), arguments(array2Bool, arrayType, false), arguments(array2Bool, arrayBool, false), arguments(array2Bool, arrayString, false), arguments(array2Bool, arrayBlob, false), arguments(array2Bool, arrayPerson, false), arguments(array2Bool, arrayNothing, true), arguments(array2Bool, arrayA, false), arguments(array2Bool, array2Type, false), arguments(array2Bool, array2Bool, true), arguments(array2Bool, array2String, false), arguments(array2Bool, array2Blob, false), arguments(array2Bool, array2Person, false), arguments(array2Bool, array2Nothing, true), arguments(array2Bool, array2A, false), arguments(array2String, type, false), arguments(array2String, bool, false), arguments(array2String, string, false), arguments(array2String, blob, false), arguments(array2String, person, false), arguments(array2String, nothing, true), arguments(array2String, a, false), arguments(array2String, arrayType, false), arguments(array2String, arrayBool, false), arguments(array2String, arrayString, false), arguments(array2String, arrayBlob, false), arguments(array2String, arrayPerson, false), arguments(array2String, arrayNothing, true), arguments(array2String, arrayA, false), arguments(array2String, array2Type, false), arguments(array2String, array2Bool, false), arguments(array2String, array2String, true), arguments(array2String, array2Blob, false), arguments(array2String, array2Person, true), arguments(array2String, array2Nothing, true), arguments(array2String, array2A, false), arguments(array2Blob, type, false), arguments(array2Blob, bool, false), arguments(array2Blob, string, false), arguments(array2Blob, blob, false), arguments(array2Blob, person, false), arguments(array2Blob, nothing, true), arguments(array2Blob, a, false), arguments(array2Blob, arrayType, false), arguments(array2Blob, arrayBool, false), arguments(array2Blob, arrayString, false), arguments(array2Blob, arrayBlob, false), arguments(array2Blob, arrayPerson, false), arguments(array2Blob, arrayNothing, true), arguments(array2Blob, arrayA, false), arguments(array2Blob, array2Type, false), arguments(array2Blob, array2Bool, false), arguments(array2Blob, array2String, false), arguments(array2Blob, array2Blob, true), arguments(array2Blob, array2Person, false), arguments(array2Blob, array2Nothing, true), arguments(array2Blob, array2A, false), arguments(array2Person, type, false), arguments(array2Person, bool, false), arguments(array2Person, string, false), arguments(array2Person, blob, false), arguments(array2Person, person, false), arguments(array2Person, nothing, true), arguments(array2Person, a, false), arguments(array2Person, arrayType, false), arguments(array2Person, arrayBool, false), arguments(array2Person, arrayString, false), arguments(array2Person, arrayBlob, false), arguments(array2Person, arrayPerson, false), arguments(array2Person, arrayNothing, true), arguments(array2Person, arrayA, false), arguments(array2Person, array2Type, false), arguments(array2Person, array2Bool, false), arguments(array2Person, array2String, false), arguments(array2Person, array2Blob, false), arguments(array2Person, array2Person, true), arguments(array2Person, array2Nothing, true), arguments(array2Person, array2A, false), arguments(array2Nothing, type, false), arguments(array2Nothing, bool, false), arguments(array2Nothing, string, false), arguments(array2Nothing, blob, false), arguments(array2Nothing, person, false), arguments(array2Nothing, nothing, true), arguments(array2Nothing, a, false), arguments(array2Nothing, arrayType, false), arguments(array2Nothing, arrayBool, false), arguments(array2Nothing, arrayString, false), arguments(array2Nothing, arrayBlob, false), arguments(array2Nothing, arrayPerson, false), arguments(array2Nothing, arrayNothing, true), arguments(array2Nothing, arrayA, false), arguments(array2Nothing, array2Type, false), arguments(array2Nothing, array2Bool, false), arguments(array2Nothing, array2String, false), arguments(array2Nothing, array2Blob, false), arguments(array2Nothing, array2Person, false), arguments(array2Nothing, array2Nothing, true), arguments(array2Nothing, array2A, false), arguments(array2A, type, false), arguments(array2A, bool, false), arguments(array2A, string, false), arguments(array2A, blob, false), arguments(array2A, person, false), arguments(array2A, nothing, true), arguments(array2A, a, false), arguments(array2A, b, false), arguments(array2A, arrayType, false), arguments(array2A, arrayBool, false), arguments(array2A, arrayString, false), arguments(array2A, arrayBlob, false), arguments(array2A, arrayPerson, false), arguments(array2A, arrayNothing, true), arguments(array2A, arrayA, false), arguments(array2A, arrayB, false), arguments(array2A, array2Type, true), arguments(array2A, array2Bool, true), arguments(array2A, array2String, true), arguments(array2A, array2Blob, true), arguments(array2A, array2Person, true), arguments(array2A, array2Nothing, true), arguments(array2A, array2A, true), arguments(array2A, array2B, true)); } @ParameterizedTest @MethodSource("commonSuperType_test_data") public void commonSuperType(Type type1, Type type2, Optional<Type> expected) { assertThat(type1.commonSuperType(type2)) .isEqualTo(expected); assertThat(type2.commonSuperType(type1)) .isEqualTo(expected); } public static List<Arguments> commonSuperType_test_data() { return List.of( arguments(type, type, Optional.of(type)), arguments(type, bool, Optional.empty()), arguments(type, string, Optional.empty()), arguments(type, blob, Optional.empty()), arguments(type, nothing, Optional.of(type)), arguments(type, a, Optional.empty()), arguments(type, arrayType, Optional.empty()), arguments(type, arrayBool, Optional.empty()), arguments(type, arrayString, Optional.empty()), arguments(type, arrayBlob, Optional.empty()), arguments(type, arrayNothing, Optional.empty()), arguments(type, arrayA, Optional.empty()), arguments(bool, string, Optional.empty()), arguments(bool, bool, Optional.of(bool)), arguments(bool, blob, Optional.empty()), arguments(bool, nothing, Optional.of(bool)), arguments(bool, a, Optional.empty()), arguments(bool, arrayString, Optional.empty()), arguments(bool, arrayBool, Optional.empty()), arguments(bool, arrayType, Optional.empty()), arguments(bool, arrayBlob, Optional.empty()), arguments(bool, arrayNothing, Optional.empty()), arguments(bool, arrayA, Optional.empty()), arguments(string, string, Optional.of(string)), arguments(string, blob, Optional.empty()), arguments(string, nothing, Optional.of(string)), arguments(string, a, Optional.empty()), arguments(string, arrayString, Optional.empty()), arguments(string, arrayBool, Optional.empty()), arguments(string, arrayType, Optional.empty()), arguments(string, arrayBlob, Optional.empty()), arguments(string, arrayNothing, Optional.empty()), arguments(string, arrayA, Optional.empty()), arguments(blob, blob, Optional.of(blob)), arguments(blob, nothing, Optional.of(blob)), arguments(blob, a, Optional.empty()), arguments(blob, arrayType, Optional.empty()), arguments(blob, arrayString, Optional.empty()), arguments(blob, arrayBlob, Optional.empty()), arguments(blob, arrayNothing, Optional.empty()), arguments(blob, arrayA, Optional.empty()), arguments(nothing, nothing, Optional.of(nothing)), arguments(nothing, a, Optional.of(a)), arguments(nothing, arrayType, Optional.of(arrayType)), arguments(nothing, arrayString, Optional.of(arrayString)), arguments(nothing, arrayBlob, Optional.of(arrayBlob)), arguments(nothing, arrayNothing, Optional.of(arrayNothing)), arguments(nothing, arrayA, Optional.of(arrayA)), arguments(a, a, Optional.of(a)), arguments(a, b, Optional.empty()), arguments(a, arrayType, Optional.empty()), arguments(a, arrayString, Optional.empty()), arguments(a, arrayBlob, Optional.empty()), arguments(a, arrayNothing, Optional.empty()), arguments(a, arrayA, Optional.empty()), arguments(a, arrayB, Optional.empty()), arguments(arrayType, arrayType, Optional.of(arrayType)), arguments(arrayType, arrayString, Optional.empty()), arguments(arrayType, arrayBlob, Optional.empty()), arguments(arrayType, arrayNothing, Optional.of(arrayType)), arguments(arrayType, arrayA, Optional.empty()), arguments(arrayString, arrayString, Optional.of(arrayString)), arguments(arrayString, arrayBlob, Optional.empty()), arguments(arrayString, arrayNothing, Optional.of(arrayString)), arguments(arrayString, nothing, Optional.of(arrayString)), arguments(arrayString, arrayA, Optional.empty()), arguments(arrayBlob, arrayBlob, Optional.of(arrayBlob)), arguments(arrayBlob, arrayNothing, Optional.of(arrayBlob)), arguments(arrayBlob, nothing, Optional.of(arrayBlob)), arguments(arrayBlob, arrayA, Optional.empty()), arguments(arrayNothing, arrayNothing, Optional.of(arrayNothing)), arguments(arrayNothing, array2Nothing, Optional.of(array2Nothing)), arguments(arrayNothing, arrayType, Optional.of(arrayType)), arguments(arrayNothing, arrayString, Optional.of(arrayString)), arguments(arrayNothing, arrayBlob, Optional.of(arrayBlob)), arguments(arrayNothing, arrayA, Optional.of(arrayA)), arguments(arrayA, arrayA, Optional.of(arrayA)), arguments(arrayA, arrayB, Optional.empty())); } @ParameterizedTest @MethodSource("actualCoreTypeWhenAssignedFrom_test_data") public void actualCoreTypeWhenAssignedFrom(GenericType type, Type assigned, Type expected) { if (expected == null) { assertCall(() -> type.actualCoreTypeWhenAssignedFrom(assigned)) .throwsException(IllegalArgumentException.class); } else { assertThat(type.actualCoreTypeWhenAssignedFrom(assigned)) .isEqualTo(expected); } } public static List<Arguments> actualCoreTypeWhenAssignedFrom_test_data() { return List.of( arguments(a, type, type), arguments(a, bool, bool), arguments(a, string, string), arguments(a, blob, blob), arguments(a, person, person), arguments(a, nothing, nothing), arguments(a, a, a), arguments(a, b, b), arguments(a, arrayType, arrayType), arguments(a, arrayBool, arrayBool), arguments(a, arrayString, arrayString), arguments(a, arrayBlob, arrayBlob), arguments(a, arrayPerson, arrayPerson), arguments(a, arrayNothing, arrayNothing), arguments(a, arrayA, arrayA), arguments(a, arrayB, arrayB), arguments(a, array2Type, array2Type), arguments(a, array2Bool, array2Bool), arguments(a, array2String, array2String), arguments(a, array2Blob, array2Blob), arguments(a, array2Person, array2Person), arguments(a, array2Nothing, array2Nothing), arguments(a, array2A, array2A), arguments(a, array2B, array2B), arguments(arrayA, type, null), arguments(arrayA, bool, null), arguments(arrayA, string, null), arguments(arrayA, blob, null), arguments(arrayA, person, null), arguments(arrayA, nothing, nothing), arguments(arrayA, a, null), arguments(arrayA, b, null), arguments(arrayA, arrayType, type), arguments(arrayA, arrayBool, bool), arguments(arrayA, arrayString, string), arguments(arrayA, arrayBlob, blob), arguments(arrayA, arrayPerson, person), arguments(arrayA, arrayNothing, nothing), arguments(arrayA, arrayA, a), arguments(arrayA, arrayB, b), arguments(arrayA, array2Type, arrayType), arguments(arrayA, array2Bool, arrayBool), arguments(arrayA, array2String, arrayString), arguments(arrayA, array2Blob, arrayBlob), arguments(arrayA, array2Person, arrayPerson), arguments(arrayA, array2Nothing, arrayNothing), arguments(arrayA, array2A, arrayA), arguments(arrayA, array2B, arrayB), arguments(array2A, type, null), arguments(array2A, bool, null), arguments(array2A, string, null), arguments(array2A, blob, null), arguments(array2A, person, null), arguments(array2A, nothing, nothing), arguments(array2A, a, null), arguments(array2A, b, null), arguments(array2A, arrayType, null), arguments(array2A, arrayBool, null), arguments(array2A, arrayString, null), arguments(array2A, arrayBlob, null), arguments(array2A, arrayPerson, null), arguments(array2A, arrayNothing, nothing), arguments(array2A, arrayA, null), arguments(array2A, arrayB, null), arguments(array2A, array2Type, type), arguments(array2A, array2Bool, bool), arguments(array2A, array2String, string), arguments(array2A, array2Blob, blob), arguments(array2A, array2Person, person), arguments(array2A, array2Nothing, nothing), arguments(array2A, array2A, a), arguments(array2A, array2B, b)); } @ParameterizedTest @MethodSource("elemType_test_data") public void elemType(ArrayType type, Type expected) { assertThat(type.elemType()) .isEqualTo(expected); } public static List<Arguments> elemType_test_data() { return List.of( arguments(arrayType, type), arguments(arrayBool, bool), arguments(arrayString, string), arguments(arrayBlob, blob), arguments(arrayPerson, person), arguments(arrayNothing, nothing), arguments(array2Type, arrayType), arguments(array2Bool, arrayBool), arguments(array2String, arrayString), arguments(array2Blob, arrayBlob), arguments(array2Person, arrayPerson), arguments(array2Nothing, arrayNothing)); } @Test public void equals_and_hashcode() { EqualsTester tester = new EqualsTester(); tester.addEqualityGroup(type, type); tester.addEqualityGroup(bool, bool); tester.addEqualityGroup(string, string); tester.addEqualityGroup(blob, blob); tester.addEqualityGroup(nothing, nothing); tester.addEqualityGroup(person, person); tester.addEqualityGroup(a, a); tester.addEqualityGroup(arrayType, arrayType); tester.addEqualityGroup(arrayBool, arrayBool); tester.addEqualityGroup(arrayString, arrayString); tester.addEqualityGroup(arrayBlob, arrayBlob); tester.addEqualityGroup(arrayPerson, arrayPerson); tester.addEqualityGroup(arrayA, arrayA); tester.addEqualityGroup(array2Type, array2Type); tester.addEqualityGroup(array2Bool, array2Bool); tester.addEqualityGroup(array2String, array2String); tester.addEqualityGroup(array2Blob, array2Blob); tester.addEqualityGroup(array2Person, array2Person); tester.addEqualityGroup(array2A, array2A); tester.testEquals(); } }
package mobi.hsz.idea.gitignore.file; import com.intellij.ide.fileTemplates.FileTemplateGroupDescriptor; import com.intellij.ide.fileTemplates.FileTemplateGroupDescriptorFactory; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileFactory; import com.intellij.util.IncorrectOperationException; import mobi.hsz.idea.gitignore.IgnoreBundle; import mobi.hsz.idea.gitignore.file.type.IgnoreFileType; import mobi.hsz.idea.gitignore.lang.IgnoreLanguage; import mobi.hsz.idea.gitignore.util.Constants; import org.jetbrains.annotations.Nullable; /** * Templates factory that generates Gitignore file and its content. * * @author Jakub Chrzanowski <jakub@hsz.mobi> * @since 0.1 */ public class IgnoreTemplatesFactory implements FileTemplateGroupDescriptorFactory { /** File's content header. */ private static final String TEMPLATE_NOTE = IgnoreBundle.message("file.templateNote"); /** Current file type. */ private final IgnoreFileType fileType; /** Builds a new instance of {@link IgnoreTemplatesFactory}. */ public IgnoreTemplatesFactory(IgnoreFileType fileType) { this.fileType = fileType; } /** * Returns group descriptor. * * @return descriptor */ @Override public FileTemplateGroupDescriptor getFileTemplatesDescriptor() { final FileTemplateGroupDescriptor templateGroup = new FileTemplateGroupDescriptor( fileType.getIgnoreLanguage().getID(), fileType.getIcon() ); templateGroup.addTemplate(fileType.getIgnoreLanguage().getFilename()); return templateGroup; } /** * Creates new Gitignore file or uses an existing one. * * @param directory working directory * @return file */ @Nullable public PsiFile createFromTemplate(final PsiDirectory directory) throws IncorrectOperationException { final String filename = fileType.getIgnoreLanguage().getFilename(); final PsiFile currentFile = directory.findFile(filename); if (currentFile != null) { return currentFile; } final PsiFileFactory factory = PsiFileFactory.getInstance(directory.getProject()); final IgnoreLanguage language = fileType.getIgnoreLanguage(); String content = StringUtil.join(TEMPLATE_NOTE, Constants.NEWLINE); if (language.isSyntaxSupported() && !IgnoreBundle.Syntax.GLOB.equals(language.getDefaultSyntax())) { content = StringUtil.join( content, IgnoreBundle.Syntax.GLOB.getPresentation(), Constants.NEWLINE, Constants.NEWLINE ); } final PsiFile file = factory.createFileFromText(filename, fileType, content); return (PsiFile) directory.add(file); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.colar.netbeans.fan.handlers; import java.util.Collections; import java.util.List; import java.util.regex.Pattern; import javax.swing.text.BadLocationException; import javax.swing.text.Caret; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import net.colar.netbeans.fan.FanLanguage; import net.colar.netbeans.fan.FanTokenID; import net.colar.netbeans.fan.parboiled.FanLexAstUtils; import net.colar.netbeans.fan.parboiled.FantomLexerTokens.TokenName; import org.netbeans.api.lexer.Token; import org.netbeans.api.lexer.TokenSequence; import org.netbeans.editor.BaseDocument; import org.netbeans.editor.Utilities; import org.netbeans.modules.csl.api.EditorOptions; import org.netbeans.modules.csl.api.KeystrokeHandler; import org.netbeans.modules.csl.api.OffsetRange; import org.netbeans.modules.csl.spi.GsfUtilities; import org.netbeans.modules.csl.spi.ParserResult; import org.netbeans.modules.editor.indent.api.IndentUtils; /** * Impl. of keystrokeHandler * Provides support for closing bracket/quote insertion and the likes * Also deals with trying to guess/insert proper indentation. * @author tcolar */ public class FanKeyStrokeHandler implements KeystrokeHandler { /* Array of special patterns that will cause increased intent on the next line * if/else/while/for/try/finaly/catch without blocks({}) * Switch items (case / default) * Note .*? = match anything NON-greedily */ public static Pattern[] INDENT_AFTER_PATTERNS = { // single line if Pattern.compile("^\\s*if\\s*\\(.*?\\)[^{]*$"), // single line else Pattern.compile("^\\s*else\\s*(if\\s*\\(.*?\\))?[^{]*$"), // switch: case / default Pattern.compile("^\\s*case\\s*[^:]*:\\s*$"), Pattern.compile("^\\s*default\\s*:\\s*$"), // try catch finaly Pattern.compile("^\\s*try\\s*$"), Pattern.compile("^\\s*finally\\s*$"), Pattern.compile("^\\s*catch(\\(.*?\\))?\\s*$"), // while Pattern.compile("^\\s*while\\s*\\(.*?\\)[^{]*$"), // for Pattern.compile("^\\s*for\\s*\\(.*?\\)[^{]*$"), }; /** * Items that should indent one level less that line above * If not immeditaly following a bracket */ private static Pattern[] DEINDENT_PATTERNS = { Pattern.compile("^\\s*else"), Pattern.compile("^\\s*catch"), Pattern.compile("^\\s*finally"), // those could follow a bracket? unlikely Pattern.compile("^\\s*case\\s*[^:]*:\\s*"), Pattern.compile("^\\s*default\\s*:\\s*"), }; // keep track of last auto-insertion (ie: closing brackets) // so if user backspace right away we remove that as well. private int lastInsertStart; private int lastInsertSize; @Override public boolean beforeCharInserted(Document document, int caretOffset, JTextComponent target, char car) throws BadLocationException { lastInsertSize = 0; //reset at each keypressed BaseDocument doc = (BaseDocument) document; if (!isInsertMatchingEnabled(doc)) { return false; } String toInsert = ""; char prev = ' '; if (caretOffset > 0) { prev = doc.getText(caretOffset - 1, 1).charAt(0); } char next = ' '; if (caretOffset < doc.getLength() - 1) { next = doc.getText(caretOffset, 1).charAt(0); } Token<? extends FanTokenID> token = FanLexAstUtils.getFanTokenAt(document, caretOffset); // If User types "over" closing item we closed automaticaly, skip it FanTokenID tokenId = token.id(); //String txt = token.text().toString().trim(); if (token != null) { //For str,uri : if backquoted -> don't skip //System.out.println("prev: "+prev); //System.out.println("next: "+next); //System.out.println("car: "+car); //System.out.println("tk: "+token.id().name()); if ((car == '"' && tokenId.matches(TokenName.STRS) && next == '"' && prev != '\\') || (car == '"' && tokenId.matches(TokenName.STRS) && next == '"' && prev != '\\') || (car == '`' && tokenId.matches(TokenName.URI) && next == '`' && prev != '\\') || //(car == '`' && ord == FanLexer.INC_URI && next=='`' && prev!='\\') || (car == '\'' && tokenId.matches(TokenName.CHAR_) && next == '\'') || (car == ']' && tokenId.matches(TokenName.SQ_BRACKET_R)) || (car == ')' && tokenId.matches(TokenName.PAR_R)) || (car == '}' && tokenId.matches(TokenName.BRACKET_R))) { // just skip the existing same characters target.getCaret().setDot(caretOffset + 1); return true; } } // Same but dual characters if (/*(car == '/' && prev=='*' && token.id().ordinal() == FanLexer.MULTI_COMMENT) ||*/(car == '>' && prev == '|' && tokenId.matches(TokenName.DSL))) { // remove previous char and then skip existing one doc.remove(caretOffset - 1, 1); target.getCaret().setDot(caretOffset + 1); return true; } // If within those tokens, don't do anything special if (tokenId.matches(TokenName.DSL) || tokenId.matches(TokenName.CHAR_) || tokenId.matches(TokenName.DOC) || tokenId.matches(TokenName.UNIXLINE) || tokenId.matches(TokenName.COMMENT) || //token.id().ordinal() == FanLexer.INC_COMMENT || //token.id().ordinal() == FanLexer.INC_DSL || //token.id().ordinal() == FanLexer.INC_STR || //token.id().ordinal() == FanLexer.INC_URI || //token.id().ordinal() == FanLexer.LINE_COMMENT || //token.id().ordinal() == FanLexer.MULTI_COMMENT || //token.id().ordinal() == FanLexer.QUOTSTR || tokenId.matches(TokenName.STRS) || tokenId.matches(TokenName.URI)) { return false; } // Automatically add closing item/brace when opening one entered switch (car) { case '{': toInsert = "}"; break; case '(': toInsert = ")"; break; case '[': toInsert = "]"; break; case '`': toInsert = "`"; break; case '\'': toInsert = "'"; break; case '"':
package net.meisen.dissertation.server; import java.io.EOFException; import java.io.IOException; import java.net.Socket; import java.net.SocketException; import net.meisen.dissertation.exceptions.AuthException; import net.meisen.dissertation.exceptions.PermissionException; import net.meisen.dissertation.exceptions.QueryEvaluationException; import net.meisen.dissertation.impl.parser.query.QueryFactory; import net.meisen.dissertation.jdbc.protocol.DataType; import net.meisen.dissertation.jdbc.protocol.Protocol; import net.meisen.dissertation.jdbc.protocol.QueryStatus; import net.meisen.dissertation.jdbc.protocol.WrappedException; import net.meisen.dissertation.model.auth.IAuthManager; import net.meisen.dissertation.model.auth.permissions.Permission; import net.meisen.dissertation.model.parser.query.IQuery; import net.meisen.dissertation.model.parser.query.IQueryResult; import net.meisen.dissertation.model.parser.query.IQueryResultSet; import net.meisen.dissertation.model.parser.query.IQueryResultSingleInteger; import net.meisen.general.genmisc.exceptions.registry.IExceptionRegistry; import net.meisen.general.genmisc.types.Streams; import net.meisen.general.server.listener.utility.WorkerThread; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A thread used to handle requests to the server. * * @author pmeisen * */ public class RequestHandlerThread extends WorkerThread { private final static Logger LOG = LoggerFactory .getLogger(RequestHandlerThread.class); private final IExceptionRegistry exceptionRegistry; private final QueryFactory queryFactory; private final IAuthManager authManager; private Exception lastException = null; public RequestHandlerThread(final Socket input, final QueryFactory queryFactory, final IAuthManager authManager, final IExceptionRegistry exceptionRegistry) { super(input); this.queryFactory = queryFactory; this.authManager = authManager; this.exceptionRegistry = exceptionRegistry; } @Override public void run() { Protocol p = null; try { p = new Protocol(getSocket()); authenticate(p); handleRequests(p); } catch (final SocketException e) { // ignore any kind of socket exception, it is closed if (LOG.isTraceEnabled()) { LOG.trace("SocketException thrown while handling a request.", e); } } catch (final AuthException e) { try { p.writeException(e); } catch (final IOException ioe) { } } catch (final Exception e) { lastException = e; if (LOG.isErrorEnabled()) { LOG.error("Exception thrown while handling a request.", e); } } finally { // make sure the DataInputStream is closed now Streams.closeIO(p); // close the socket for sure close(); // make sure the user is logged out authManager.logout(); } } /** * Authenticates the handling. Each handling has to be authenticated once * prior to any other activitity. * * @param p * the {@code Protocol} used to validate the authentication * * @throws AuthException * if the authentication fails */ protected void authenticate(final Protocol p) throws AuthException { // read the username and password from the socket final String username; final String password; try { final String[] credential = p.readCredential(); username = credential[0]; password = credential[1]; } catch (final IOException e) { exceptionRegistry.throwRuntimeException(AuthException.class, 1002); return; } // use the authManager to authenticate authManager.login(username, password); if (!authManager.hasPermission(Permission.connectTSQL.create())) { exceptionRegistry.throwRuntimeException(PermissionException.class, 1000, Permission.connectTSQL); } } /** * Handles a request by reading a string using the current {@code Protocol}. * * @param p * the {@code Protocol} used to handle the request * * @throws IOException * if the requests handling fails */ protected void handleRequests(final Protocol p) throws IOException { try { while (!Thread.interrupted()) { final String msg; try { // get the real message that was send msg = p.waitForMessage(); if (LOG.isDebugEnabled()) { LOG.debug("Retrieved query '" + msg + "'."); } } catch (final WrappedException e) { /* * The client send an exception, we can just log it here. * All other exception (not send just occurring) are serious * enough to close the connection completely. */ if (LOG.isErrorEnabled()) { LOG.error("Client send exception '" + e.getMessage() + "'", e); } /* * Read the next one, the client will close the connection * if the error is serious. */ continue; } try { // parse the query and send the type final IQuery query = queryFactory.parseQuery(msg); if (LOG.isTraceEnabled()) { LOG.trace("Writing queryType of '" + msg + "' as '" + query.getQueryType() + "'."); } p.writeQueryType(query.getQueryType()); // check the status final QueryStatus status = p.readQueryStatus(); if (LOG.isTraceEnabled()) { LOG.trace("Got queryStatus '" + status + "' from client for query '" + msg + "'."); } // cancel if wished for if (QueryStatus.CANCEL.equals(status)) { p.writeEndOfResponse(); continue; } // enable identifier collection if needed final boolean enableIdCollection = QueryStatus.PROCESSANDGETIDS .equals(status); query.enableIdCollection(enableIdCollection); // retrieve the result try { final IQueryResult res = queryFactory.evaluateQuery( query, new ClientResourceResolver(p)); // write the identifiers of not canceled if (checkCancellation(p)) { continue; } else if (enableIdCollection && writeIdentifiers(p, res.getCollectedIds())) { continue; } /* * All the methods return true if the process was * cancelled, therefore check the pre-requirements and * the result of execution. */ if (checkCancellation(p)) { continue; } else if (res instanceof IQueryResultSingleInteger && writeSingleInteger(p, msg, (IQueryResultSingleInteger) res)) { continue; } else if (res instanceof IQueryResultSet && writeSet(p, msg, (IQueryResultSet) res)) { continue; } } catch (final CancellationException e) { if (LOG.isTraceEnabled()) { LOG.trace("Handling of '" + msg + "' was canceled during evaluation."); } p.writeEndOfResponse(); continue; } if (LOG.isTraceEnabled()) { LOG.trace("Answer of '" + msg + "' sent, sending eor."); } p.writeEndOfResponse(); } catch (final SocketException e) { if (LOG.isTraceEnabled()) { LOG.trace("SocketException while handling '" + msg + "' sending '" + e.getMessage() + "'."); } } catch (final PermissionException e) { if (LOG.isTraceEnabled()) { LOG.trace( "User tried to execute an invalid operation.", e); } p.writeException(e); } catch (final Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Exception while handling '" + msg + "' sending '" + e.getMessage() + "'."); } p.writeException(e); } } } catch (final EOFException e) { // indicates that the stream was just closed } } /** * Writes a set of results according to the specified {@code Protocol}. * * @param p * the {@code Protocol} used to write the results. * @param msg * the message the integer was written for * @param result * the result to be written * * @return {@code true} if the writing was canceled, otherwise {@code false} * * @throws IOException * if an exception is thrown during the writing */ protected boolean writeSet(final Protocol p, final String msg, final IQueryResultSet result) throws IOException { boolean canceled = false; final IQueryResultSet res = (IQueryResultSet) result; // write the header if (LOG.isTraceEnabled()) { LOG.trace("Writing headers of reply of query '" + msg + "'."); } final DataType[] header = p.writeHeader(res.getTypes()); p.writeHeaderNames(res.getNames()); // send an end of meta, so that the client knows that data will follow p.writeEndOfMeta(); // write the records if (LOG.isTraceEnabled()) { LOG.trace("Writing records of reply of query '" + msg + "'."); } for (final Object[] values : res) { if (!(canceled = canceled || checkCancellation(p))) { p.writeResult(header, values); } else { break; } } return canceled; } /** * Writes a single integer according to the passed {@code Protocol}. * * @param p * the {@code Protocol} used to write the single integer. * @param msg * the message the integer was written for * @param result * the result to be written * * @return {@code true} if the writing was canceled, otherwise {@code false} * * @throws IOException * if an exception is thrown during the writing */ protected boolean writeSingleInteger(final Protocol p, final String msg, final IQueryResultSingleInteger result) throws IOException { if (LOG.isTraceEnabled()) { LOG.trace("Replying to query '" + msg + "' with single integer " + result.getResult() + "."); } p.writeInt(result.getResult()); return false; } /** * Writes the specified identifiers according to the passed {@code Protocol} * . * * @param p * the {@code Protocol} used to write the single integer. * @param collectedIds * the identifiers to be written * * * @return {@code true} if the writing was canceled, otherwise {@code false} * * @throws IOException * if an exception is thrown during the writing */ protected boolean writeIdentifiers(final Protocol p, final int[] collectedIds) throws IOException { if (LOG.isTraceEnabled()) { LOG.trace("Writing the collected identifiers."); } if (collectedIds == null) { p.writeInts(collectedIds); } else { p.writeInts(new int[0]); } return false; } /** * Checks if the currently handled request was cancelled by the client * during evaluation. * * @param p * the protocol to check for cancellation * * @return {@code true} if it was cancelled, otherwise {@code false} * * @throws IOException * if the reading failed */ protected boolean checkCancellation(final Protocol p) throws IOException { final String[] msg = new String[] { null }; final Boolean peek = p.peekForCancel(msg); if (peek == null) { return false; } else if (peek) { if (LOG.isTraceEnabled()) { LOG.trace("Handling of '" + msg + "' canceled."); } p.writeEndOfResponse(); return true; } else { exceptionRegistry.throwRuntimeException( QueryEvaluationException.class, 1017, msg[0]); return false; } } /** * Get the last exception thrown. * * @return the last exception thrown, {@code null} if none was thrown */ public Exception getLastException() { return lastException; } @Override public void close() { if (getSocket().isClosed()) { // even if it's marked close, close it for sure try { getSocket().close(); } catch (final IOException e) { // ignore } return; } // log the closing and do it if (LOG.isDebugEnabled()) { LOG.debug("Closing socket used for request handling..."); } super.close(); } }
package org.openstreetmap.josm.plugins.notes.api; import java.io.IOException; import java.net.URLEncoder; import javax.xml.parsers.ParserConfigurationException; import org.openstreetmap.josm.Main; import org.openstreetmap.josm.plugins.notes.ConfigKeys; import org.openstreetmap.josm.plugins.notes.Note; import org.openstreetmap.josm.plugins.notes.NotesXmlParser; import org.openstreetmap.josm.plugins.notes.api.util.HttpUtils; import org.xml.sax.SAXException; public class EditAction { private final String CHARSET = "UTF-8"; public void execute(Note n, String comment) throws IOException { // create the URI for the data download String uri = new StringBuilder(Main.pref.get(ConfigKeys.NOTES_API_URI_BASE)) .append("/") .append(n.getId()) .append("/comment") .toString(); String post = new StringBuilder("text=") .append(URLEncoder.encode(comment, CHARSET)) .toString(); String result = null; if(Main.pref.getBoolean(ConfigKeys.NOTES_API_DISABLED)) { result = "ok"; } else { result = HttpUtils.post(uri, post, CHARSET); } try { Note note = NotesXmlParser.parseNotes(result).get(0); n.updateWith(note); Main.map.mapView.repaint(); } catch (SAXException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } } }
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: package org.sosy_lab.java_smt.test; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.TruthJUnit.assume; import com.google.common.collect.ImmutableList; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import org.sosy_lab.java_smt.SolverContextFactory.Solvers; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula; import org.sosy_lab.java_smt.api.RegexFormula; import org.sosy_lab.java_smt.api.SolverException; import org.sosy_lab.java_smt.api.StringFormula; @SuppressWarnings("ConstantConditions") @SuppressFBWarnings(value = "DLS_DEAD_LOCAL_STORE", justification = "test code") @RunWith(Parameterized.class) public class StringFormulaManagerTest extends SolverBasedTest0 { private static final ImmutableList<String> WORDS = ImmutableList.of( "", "0", "1", "10", "a", "b", "A", "B", "aa", "Aa", "aA", "AA", "ab", "aB", "Ab", "AB", "ac", "bb", "aaa", "Aaa", "aAa", "aAA", "aab", "aaabbb", "bbbccc", "abcde", "abdde", "abcdf", "abchurrdurr", "abcdefaaaaa"); private StringFormula hello; private RegexFormula a2z; @Parameters(name = "{0}") public static Object[] getAllSolvers() { return Solvers.values(); } @Parameter public Solvers solverUnderTest; @Override protected Solvers solverToUse() { return solverUnderTest; } @Before public void setup() { requireStrings(); hello = smgr.makeString("hello"); a2z = smgr.range('a', 'z'); } // Utility methods private void assertEqual(IntegerFormula num1, IntegerFormula num2) throws SolverException, InterruptedException { assertThatFormula(imgr.equal(num1, num2)).isTautological(); } private void assertDistinct(IntegerFormula num1, IntegerFormula num2) throws SolverException, InterruptedException { assertThatFormula(imgr.distinct(List.of(num1, num2))).isTautological(); } private void assertEqual(StringFormula str1, StringFormula str2) throws SolverException, InterruptedException { assertThatFormula(smgr.equal(str1, str2)).isTautological(); } private void assertDistinct(StringFormula str1, StringFormula str2) throws SolverException, InterruptedException { assertThatFormula(smgr.equal(str1, str2)).isUnsatisfiable(); } // Tests @Test public void testRegexAll() throws SolverException, InterruptedException { RegexFormula regex = smgr.all(); assertThatFormula(smgr.in(hello, regex)).isSatisfiable(); } @Test public void testRegexAll3() throws SolverException, InterruptedException { // This is not ALL_CHAR! This matches ".*" literally! RegexFormula regex = smgr.makeRegex(".*"); assertThatFormula(smgr.in(hello, regex)).isUnsatisfiable(); assertThatFormula(smgr.in(smgr.makeString(".*"), regex)).isSatisfiable(); } @Test public void testRegexAllChar() throws SolverException, InterruptedException { RegexFormula regexAllChar = smgr.allChar(); RegexFormula regexDot = smgr.makeRegex("."); assertThatFormula(smgr.in(smgr.makeString("a"), regexAllChar)).isSatisfiable(); assertThatFormula(smgr.in(smgr.makeString("a"), regexDot)).isUnsatisfiable(); assertThatFormula(smgr.in(smgr.makeString("ab"), regexAllChar)).isUnsatisfiable(); assertThatFormula(smgr.in(smgr.makeString(""), regexAllChar)).isUnsatisfiable(); assertThatFormula(smgr.in(smgr.makeString("ab"), smgr.times(regexAllChar, 2))).isSatisfiable(); assertThatFormula(smgr.in(smgr.makeVariable("x"), smgr.intersection(smgr.range('a', '9'), regexAllChar))).isSatisfiable(); } @Test public void testRegexAllCharUnicode() throws SolverException, InterruptedException { RegexFormula regexAllChar = smgr.allChar(); if (solverUnderTest == Solvers.Z3) { // Z3 supports Unicode characters in the theory of strings. assertThatFormula(smgr.in(smgr.makeString("\\u0394"), regexAllChar)).isSatisfiable(); assertThatFormula(smgr.in(smgr.makeString("\\u{1fa6a}"), regexAllChar)).isSatisfiable(); assertThatFormula(smgr.in(smgr.makeVariable("x"), smgr.intersection(smgr.range('a', 'Δ'), regexAllChar))).isSatisfiable(); // Combining characters are not matched as one character. assertThatFormula(smgr.in(smgr.makeString("a\\u0336"), regexAllChar)).isUnsatisfiable(); // Non-ascii non-printable characters should use the codepoint representation assertThatFormula(smgr.in(smgr.makeString("Δ"), regexAllChar)).isUnsatisfiable(); assertThatFormula(smgr.in(smgr.makeString("\\n"), regexAllChar)).isUnsatisfiable(); } else if (solverUnderTest == Solvers.CVC4){ // CVC4 does not support Unicode characters assertThatFormula(smgr.in(smgr.makeString("\\u0394"), regexAllChar)).isUnsatisfiable(); } } @Test public void testStringRegex2() throws SolverException, InterruptedException { RegexFormula regex = smgr.concat(smgr.closure(a2z), smgr.makeRegex("ll"), smgr.closure(a2z)); assertThatFormula(smgr.in(hello, regex)).isSatisfiable(); } @Test public void testStringRegex3() throws SolverException, InterruptedException { RegexFormula regex = smgr.makeRegex(".*ll.*"); assertThatFormula(smgr.in(hello, regex)).isUnsatisfiable(); } @Test public void testEmptyRegex() throws SolverException, InterruptedException { RegexFormula regex = smgr.none(); assertThatFormula(smgr.in(hello, regex)).isUnsatisfiable(); } @Test public void testStringConcat() throws SolverException, InterruptedException { StringFormula str1 = smgr.makeString("hello"); StringFormula str2 = smgr.makeString("world"); StringFormula concat = smgr.concat(str1, str2); StringFormula complete = smgr.makeString("helloworld"); assertEqual(concat, complete); } @Test public void testStringConcatEmpty() throws SolverException, InterruptedException { StringFormula empty = smgr.makeString(""); assertEqual(empty, smgr.concat(ImmutableList.of())); assertEqual(empty, smgr.concat(empty)); assertEqual(empty, smgr.concat(empty, empty)); assertEqual(empty, smgr.concat(ImmutableList.of(empty, empty, empty, empty))); } @Test public void testStringPrefixSuffixConcat() throws SolverException, InterruptedException { // check whether "prefix + suffix == concat" StringFormula prefix = smgr.makeVariable("prefix"); StringFormula suffix = smgr.makeVariable("suffix"); StringFormula concat = smgr.makeVariable("concat"); assertThatFormula( bmgr.and( smgr.prefix(prefix, concat), smgr.suffix(suffix, concat), imgr.equal( smgr.length(concat), imgr.add(smgr.length(prefix), smgr.length(suffix))))) .implies(smgr.equal(concat, smgr.concat(prefix, suffix))); } @Test public void testStringPrefixSuffix() throws SolverException, InterruptedException { // check whether "prefix == suffix iff equal length" StringFormula prefix = smgr.makeVariable("prefix"); StringFormula suffix = smgr.makeVariable("suffix"); assertThatFormula(bmgr.and(smgr.prefix(prefix, suffix), smgr.suffix(suffix, prefix))) .implies(smgr.equal(prefix, suffix)); assertThatFormula( bmgr.and( smgr.prefix(prefix, suffix), imgr.equal(smgr.length(prefix), smgr.length(suffix)))) .implies(smgr.equal(prefix, suffix)); assertThatFormula( bmgr.and( smgr.suffix(suffix, prefix), imgr.equal(smgr.length(prefix), smgr.length(suffix)))) .implies(smgr.equal(prefix, suffix)); } @Test public void testStringToIntConversion() throws SolverException, InterruptedException { IntegerFormula ten = imgr.makeNumber(10); StringFormula zeroStr = smgr.makeString("0"); for (int i = 0; i < 100; i += 7) { StringFormula str = smgr.makeString(Integer.toString(i)); IntegerFormula num = imgr.makeNumber(i); IntegerFormula numInc = imgr.makeNumber(i + 1); assertEqual(str, smgr.toStringFormula(num)); assertDistinct(str, smgr.toStringFormula(numInc)); assertDistinct(str, smgr.toStringFormula(imgr.add(num, numInc))); assertEqual(num, smgr.toIntegerFormula(str)); assertDistinct(numInc, smgr.toIntegerFormula(str)); assertEqual(imgr.multiply(num, ten), smgr.toIntegerFormula(smgr.concat(str, zeroStr))); assertDistinct(imgr.multiply(numInc, ten), smgr.toIntegerFormula(smgr.concat(str, zeroStr))); assertEqual(num, smgr.toIntegerFormula(smgr.toStringFormula(num))); assertEqual(numInc, smgr.toIntegerFormula(smgr.toStringFormula(numInc))); } } @Test public void testStringToIntConversionCornerCases() throws SolverException, InterruptedException { assertEqual(imgr.makeNumber(-1), smgr.toIntegerFormula(smgr.makeString("-1"))); assertEqual(imgr.makeNumber(-1), smgr.toIntegerFormula(smgr.makeString("-12"))); assertEqual(imgr.makeNumber(-1), smgr.toIntegerFormula(smgr.makeString("-123"))); assertEqual(imgr.makeNumber(-1), smgr.toIntegerFormula(smgr.makeString("-1234"))); assertDistinct(imgr.makeNumber(-12), smgr.toIntegerFormula(smgr.makeString("-1"))); assertDistinct(imgr.makeNumber(-12), smgr.toIntegerFormula(smgr.makeString("-12"))); assertDistinct(imgr.makeNumber(-12), smgr.toIntegerFormula(smgr.makeString("-123"))); assertDistinct(imgr.makeNumber(-12), smgr.toIntegerFormula(smgr.makeString("-1234"))); assertEqual(imgr.makeNumber(-1), smgr.toIntegerFormula(smgr.makeString(""))); assertEqual(imgr.makeNumber(-1), smgr.toIntegerFormula(smgr.makeString("a"))); assertEqual(imgr.makeNumber(-1), smgr.toIntegerFormula(smgr.makeString("1a"))); assertEqual(imgr.makeNumber(-1), smgr.toIntegerFormula(smgr.makeString("a1"))); assertDistinct(imgr.makeNumber(-12), smgr.toIntegerFormula(smgr.makeString(""))); assertDistinct(imgr.makeNumber(-12), smgr.toIntegerFormula(smgr.makeString("a"))); assertDistinct(imgr.makeNumber(-12), smgr.toIntegerFormula(smgr.makeString("1a"))); assertDistinct(imgr.makeNumber(-12), smgr.toIntegerFormula(smgr.makeString("a1"))); } @Test public void testIntToStringConversionCornerCases() throws SolverException, InterruptedException { assertEqual(smgr.makeString("123"), smgr.toStringFormula(imgr.makeNumber(123))); assertEqual(smgr.makeString("1"), smgr.toStringFormula(imgr.makeNumber(1))); assertEqual(smgr.makeString("0"), smgr.toStringFormula(imgr.makeNumber(0))); assertEqual(smgr.makeString(""), smgr.toStringFormula(imgr.makeNumber(-1))); assertEqual(smgr.makeString(""), smgr.toStringFormula(imgr.makeNumber(-123))); assertDistinct(smgr.makeString("1"), smgr.toStringFormula(imgr.makeNumber(-1))); } @Test public void testStringLength() throws SolverException, InterruptedException { assertEqual(imgr.makeNumber(0), smgr.length(smgr.makeString(""))); assertEqual(imgr.makeNumber(1), smgr.length(smgr.makeString("a"))); assertEqual(imgr.makeNumber(2), smgr.length(smgr.makeString("aa"))); assertEqual(imgr.makeNumber(9), smgr.length(smgr.makeString("aaabbbccc"))); assertDistinct(imgr.makeNumber(5), smgr.length(smgr.makeString(""))); assertDistinct(imgr.makeNumber(5), smgr.length(smgr.makeString("a"))); assertDistinct(imgr.makeNumber(5), smgr.length(smgr.makeString("aa"))); assertDistinct(imgr.makeNumber(5), smgr.length(smgr.makeString("aaabbbcc"))); } @Test public void testStringLengthWithVariable() throws SolverException, InterruptedException { StringFormula var = smgr.makeVariable("var"); assertThatFormula(imgr.equal(imgr.makeNumber(0), smgr.length(var))) .implies(smgr.equal(var, smgr.makeString(""))); assertThatFormula( bmgr.and( imgr.equal(imgr.makeNumber(5), smgr.length(var)), smgr.prefix(smgr.makeString("aba"), var), smgr.suffix(smgr.makeString("aba"), var))) .implies(smgr.equal(smgr.makeVariable("var"), smgr.makeString("ababa"))); assertThatFormula( bmgr.and( imgr.equal(imgr.makeNumber(4), smgr.length(var)), smgr.prefix(smgr.makeString("aba"), var), smgr.suffix(smgr.makeString("aba"), var))) .isUnsatisfiable(); assertThatFormula( bmgr.and( imgr.equal(imgr.makeNumber(4), smgr.length(var)), smgr.prefix(smgr.makeString("ab"), var), smgr.suffix(smgr.makeString("ba"), var), smgr.equal(smgr.makeString("c"), smgr.charAt(var, imgr.makeNumber(3))))) .isUnsatisfiable(); assertThatFormula( bmgr.and( imgr.equal(imgr.makeNumber(5), smgr.length(var)), smgr.prefix(smgr.makeString("ab"), var), smgr.suffix(smgr.makeString("ba"), var), smgr.equal(smgr.makeString("c"), smgr.charAt(var, imgr.makeNumber(3))))) .implies(smgr.equal(smgr.makeVariable("var"), smgr.makeString("abcba"))); } @Test public void testStringLengthPositiv() throws SolverException, InterruptedException { assertThatFormula(imgr.lessOrEquals(imgr.makeNumber(0), smgr.length(smgr.makeVariable("x")))) .isTautological(); assertThatFormula(imgr.greaterThan(imgr.makeNumber(0), smgr.length(smgr.makeVariable("x")))) .isUnsatisfiable(); } @Test public void testStringCompare() throws SolverException, InterruptedException { StringFormula var1 = smgr.makeVariable("0"); StringFormula var2 = smgr.makeVariable("1"); assertThatFormula(bmgr.and(smgr.lessOrEquals(var1, var2), smgr.greaterOrEquals(var1, var2))) .implies(smgr.equal(var1, var2)); assertThatFormula(smgr.equal(var1, var2)) .implies(bmgr.and(smgr.lessOrEquals(var1, var2), smgr.greaterOrEquals(var1, var2))); } /** Test const Strings = String variables + prefix and suffix constraints. */ @Test public void testConstStringEqStringVar() throws SolverException, InterruptedException { String string1 = ""; String string2 = "a"; String string3 = "ab"; String string4 = "abcdefghijklmnopqrstuvwxyz"; StringFormula string1c = smgr.makeString(string1); StringFormula string2c = smgr.makeString(string2); StringFormula string3c = smgr.makeString(string3); StringFormula string4c = smgr.makeString(string4); StringFormula string1v = smgr.makeVariable("string1v"); StringFormula string2v = smgr.makeVariable("string1v"); StringFormula string3v = smgr.makeVariable("string1v"); StringFormula string4v = smgr.makeVariable("string1v"); BooleanFormula formula = bmgr.and( smgr.equal(string1c, string1v), smgr.equal(string2c, string2v), smgr.equal(string3c, string3v), smgr.equal(string4c, string4v)); BooleanFormula string1PrefixFormula = bmgr.and( smgr.prefix(string1c, string1v), bmgr.not(smgr.prefix(string2c, string1v)), bmgr.not(smgr.prefix(string3c, string1v)), bmgr.not(smgr.prefix(string4c, string1v))); BooleanFormula string2PrefixFormula = bmgr.and( smgr.prefix(string1c, string2v), smgr.prefix(string2c, string2v), bmgr.not(smgr.prefix(string3c, string2v)), bmgr.not(smgr.prefix(string4c, string2v))); BooleanFormula string3PrefixFormula = bmgr.and( smgr.prefix(string1c, string3v), smgr.prefix(string2c, string3v), smgr.prefix(string3c, string3v), bmgr.not(smgr.prefix(string4c, string3v))); BooleanFormula string4PrefixFormula = bmgr.and( smgr.prefix(string1c, string4v), smgr.prefix(string2c, string4v), smgr.prefix(string3c, string4v), smgr.prefix(string4c, string4v)); BooleanFormula string1SuffixFormula = bmgr.and( smgr.suffix(string1c, string1v), bmgr.not(smgr.suffix(string2c, string1v)), bmgr.not(smgr.suffix(string3c, string1v)), bmgr.not(smgr.suffix(string4c, string1v))); BooleanFormula string2SuffixFormula = bmgr.and( smgr.suffix(string1c, string2v), bmgr.not(smgr.suffix(string3c, string2v)), bmgr.not(smgr.suffix(string4c, string2v))); BooleanFormula string3SuffixFormula = bmgr.and( smgr.suffix(string1c, string3v), smgr.suffix(string3c, string3v), bmgr.not(smgr.suffix(string4c, string3v))); BooleanFormula string4SuffixFormula = bmgr.and(smgr.suffix(string1c, string4v), smgr.suffix(string4c, string4v)); assertThatFormula(bmgr.and(formula)) .implies( bmgr.and( string1PrefixFormula, string2PrefixFormula, string3PrefixFormula, string4PrefixFormula, string1SuffixFormula, string2SuffixFormula, string3SuffixFormula, string4SuffixFormula)); } /** Test String variables with negative length (UNSAT). */ @Test public void testStringVariableLengthNegative() throws SolverException, InterruptedException { StringFormula stringVariable1 = smgr.makeVariable("zeroLength"); StringFormula stringVariable2 = smgr.makeVariable("negLength"); // SAT + UNSAT Formula -> UNSAT assertThatFormula( bmgr.and( imgr.equal(smgr.length(stringVariable1), imgr.makeNumber(0)), imgr.equal(smgr.length(stringVariable2), imgr.makeNumber(-100)))) .isUnsatisfiable(); // UNSAT below assertThatFormula(imgr.equal(smgr.length(stringVariable2), imgr.makeNumber(-1))) .isUnsatisfiable(); assertThatFormula(imgr.equal(smgr.length(stringVariable2), imgr.makeNumber(-100))) .isUnsatisfiable(); } /** * Test String formulas with inequalities in the negative range. * * <p>-10000 < stringVariable length < 0 -> UNSAT * * <p>-10000 < stringVariable length < -1 -> UNSAT * * <p>-10000 <= stringVariable length <= -1 -> UNSAT * * <p>-10000 <= stringVariable length <= 0 AND stringVariable != "" -> UNSAT * * <p>-10000 <= stringVariable length <= 0 -> SAT implies stringVariable = "" */ @Test public void testStringLengthInequalityNegativeRange() throws SolverException, InterruptedException { StringFormula stringVariable = smgr.makeVariable("stringVariable"); IntegerFormula stringVariableLength = smgr.length(stringVariable); IntegerFormula minusTenThousand = imgr.makeNumber(-10000); IntegerFormula minusOne = imgr.makeNumber(-1); IntegerFormula zero = imgr.makeNumber(0); // -10000 < stringVariable length < 0 -> UNSAT assertThatFormula( bmgr.and( imgr.lessThan(minusTenThousand, stringVariableLength), imgr.lessThan(stringVariableLength, zero))) .isUnsatisfiable(); // -10000 < stringVariable length < -1 -> UNSAT assertThatFormula( bmgr.and( imgr.lessThan(minusTenThousand, stringVariableLength), imgr.lessThan(stringVariableLength, minusOne))) .isUnsatisfiable(); // -10000 <= stringVariable length <= -1 -> UNSAT assertThatFormula( bmgr.and( imgr.lessOrEquals(minusTenThousand, stringVariableLength), imgr.lessOrEquals(stringVariableLength, minusOne))) .isUnsatisfiable(); // -10000 <= stringVariable length <= 0 AND stringVariable != "" -> UNSAT assertThatFormula( bmgr.and( imgr.lessOrEquals(minusTenThousand, stringVariableLength), imgr.lessOrEquals(stringVariableLength, zero), bmgr.not(smgr.equal(stringVariable, smgr.makeString(""))))) .isUnsatisfiable(); // -10000 <= stringVariable length <= 0 -> SAT implies stringVariable = "" assertThatFormula( bmgr.and( imgr.lessOrEquals(minusTenThousand, stringVariableLength), imgr.lessOrEquals(stringVariableLength, zero))) .implies(smgr.equal(stringVariable, smgr.makeString(""))); } /** * Test String formulas with inequalities in the negative range. * * <p>0 < stringVariable length < 1 -> UNSAT * * <p>0 < stringVariable length < 2 -> SAT * * <p>0 <= stringVariable length < 1 -> SAT implies stringVariable = "" * * <p>1 < stringVariable length < 3 -> SAT implies stringVariable length = 2 */ @Test public void testStringLengthInequalityPositiveRange() throws SolverException, InterruptedException { StringFormula stringVariable = smgr.makeVariable("stringVariable"); IntegerFormula stringVariableLength = smgr.length(stringVariable); IntegerFormula three = imgr.makeNumber(3); IntegerFormula two = imgr.makeNumber(2); IntegerFormula one = imgr.makeNumber(1); IntegerFormula zero = imgr.makeNumber(0); // 0 < stringVariable length < 1 -> UNSAT assertThatFormula( bmgr.and( imgr.lessThan(zero, stringVariableLength), imgr.lessThan(stringVariableLength, one))) .isUnsatisfiable(); // 0 < stringVariable length < 2 -> SAT assertThatFormula( bmgr.and( imgr.lessThan(zero, stringVariableLength), imgr.lessThan(stringVariableLength, two))) .isSatisfiable(); // 0 <= stringVariable length < 1 -> SAT implies stringVariable = "" assertThatFormula( bmgr.and( imgr.lessOrEquals(zero, stringVariableLength), imgr.lessThan(stringVariableLength, one))) .implies(smgr.equal(stringVariable, smgr.makeString(""))); // 1 < stringVariable length < 3 -> SAT implies stringVariable length = 2 assertThatFormula( bmgr.and( imgr.lessThan(one, stringVariableLength), imgr.lessThan(stringVariableLength, three))) .implies(imgr.equal(smgr.length(stringVariable), two)); } /** Test simple String lexicographic ordering (< <= > >=) for constant Strings. */ @Test public void testSimpleConstStringLexicographicOrdering() throws SolverException, InterruptedException { List<String> words = ImmutableList.sortedCopyOf(WORDS); for (int i = 1; i < words.size(); i++) { StringFormula word1 = smgr.makeString(words.get(i - 1)); StringFormula word2 = smgr.makeString(words.get(i)); assertThatFormula(smgr.lessThan(word1, word1)).isUnsatisfiable(); assertThatFormula(smgr.lessOrEquals(word1, word1)).isSatisfiable(); assertThatFormula(smgr.greaterOrEquals(word1, word1)).isSatisfiable(); assertThatFormula(smgr.lessThan(word1, word2)).isSatisfiable(); assertThatFormula(smgr.lessOrEquals(word1, word2)).isSatisfiable(); assertThatFormula(smgr.greaterThan(word1, word2)).isUnsatisfiable(); assertThatFormula(smgr.greaterOrEquals(word1, word2)).isUnsatisfiable(); } } /** Test simple String lexicographic ordering (< <= > >=) for String variables. */ @Test public void testSimpleStringVariableLexicographicOrdering() throws SolverException, InterruptedException { StringFormula a = smgr.makeString("a"); StringFormula b = smgr.makeString("b"); StringFormula ab = smgr.makeString("ab"); StringFormula abc = smgr.makeString("abc"); StringFormula abd = smgr.makeString("abd"); StringFormula abe = smgr.makeString("abe"); StringFormula abaab = smgr.makeString("abaab"); StringFormula abbab = smgr.makeString("abbab"); StringFormula abcab = smgr.makeString("abcab"); StringFormula stringVariable = smgr.makeVariable("stringVariable"); assertThatFormula( bmgr.and( smgr.lessThan(a, stringVariable), smgr.lessThan(stringVariable, b), imgr.equal(imgr.makeNumber(0), smgr.length(stringVariable)))) .implies(smgr.equal(stringVariable, smgr.makeString(""))); assertThatFormula( bmgr.and( smgr.lessOrEquals(a, stringVariable), smgr.lessThan(stringVariable, b), imgr.equal(imgr.makeNumber(1), smgr.length(stringVariable)))) .implies(smgr.equal(stringVariable, smgr.makeString("a"))); assertThatFormula( bmgr.and( smgr.lessThan(a, stringVariable), smgr.lessOrEquals(stringVariable, b), imgr.equal(imgr.makeNumber(1), smgr.length(stringVariable)))) .implies(smgr.equal(stringVariable, b)); assertThatFormula( bmgr.and( smgr.lessOrEquals(abc, stringVariable), smgr.lessThan(stringVariable, abd), imgr.equal(imgr.makeNumber(3), smgr.length(stringVariable)))) .implies(smgr.equal(stringVariable, abc)); assertThatFormula( bmgr.and( smgr.lessThan(abc, stringVariable), smgr.lessThan(stringVariable, abe), imgr.equal(imgr.makeNumber(3), smgr.length(stringVariable)))) .implies(smgr.equal(stringVariable, abd)); assertThatFormula( bmgr.and( smgr.lessThan(abc, stringVariable), smgr.lessOrEquals(stringVariable, abd), imgr.equal(imgr.makeNumber(3), smgr.length(stringVariable)))) .implies(smgr.equal(stringVariable, abd)); assertThatFormula( bmgr.and( smgr.lessThan(abaab, stringVariable), smgr.lessThan(stringVariable, abcab), smgr.prefix(ab, stringVariable), smgr.suffix(ab, stringVariable), imgr.equal(imgr.makeNumber(5), smgr.length(stringVariable)))) .implies(smgr.equal(stringVariable, abbab)); } /** Takeaway: invalid positions always refer to the empty string! */ @Test public void testCharAtWithConstString() throws SolverException, InterruptedException { StringFormula empty = smgr.makeString(""); StringFormula a = smgr.makeString("a"); StringFormula b = smgr.makeString("b"); StringFormula ab = smgr.makeString("ab"); assertEqual(smgr.charAt(empty, imgr.makeNumber(1)), empty); assertEqual(smgr.charAt(empty, imgr.makeNumber(0)), empty); assertEqual(smgr.charAt(empty, imgr.makeNumber(-1)), empty); assertDistinct(smgr.charAt(a, imgr.makeNumber(-1)), a); assertEqual(smgr.charAt(a, imgr.makeNumber(-1)), empty); assertEqual(smgr.charAt(a, imgr.makeNumber(0)), a); assertDistinct(smgr.charAt(a, imgr.makeNumber(1)), a); assertEqual(smgr.charAt(a, imgr.makeNumber(1)), empty); assertDistinct(smgr.charAt(a, imgr.makeNumber(2)), a); assertEqual(smgr.charAt(a, imgr.makeNumber(2)), empty); assertEqual(smgr.charAt(ab, imgr.makeNumber(0)), a); assertEqual(smgr.charAt(ab, imgr.makeNumber(1)), b); assertDistinct(smgr.charAt(ab, imgr.makeNumber(0)), b); assertDistinct(smgr.charAt(ab, imgr.makeNumber(1)), a); } /** * Test escapecharacter treatment. Escape characters are treated as a single char! Example: * "a\u1234T" has "a" at position 0, "\u1234" at position 1 and "T" at position 2 * * <p>SMTLIB2 uses an escape sequence for the numerals of the sort: {1234}. */ @Test public void testCharAtWithSpecialCharacters() throws SolverException, InterruptedException { assume() .withMessage("Solver %s does only support 2 byte unicode", solverToUse()) .that(solverToUse()) .isNotEqualTo(Solvers.Z3); StringFormula num1 = smgr.makeString("1"); StringFormula u = smgr.makeString("u"); StringFormula curlyOpen = smgr.makeString("{"); StringFormula curlyClose = smgr.makeString("}"); StringFormula u1234WOEscape = smgr.makeString("u1234"); StringFormula au1234WOEscape = smgr.makeString("au1234"); // Java needs a double {{ as the first one is needed as an escape char for the second, this is a // workaround String workaround = "au{1234}"; StringFormula au1234WOEscapeCurly = smgr.makeString(workaround); StringFormula backSlash = smgr.makeString("\\"); StringFormula a = smgr.makeString("a"); StringFormula b = smgr.makeString("b"); StringFormula u1234 = smgr.makeString("\\u{1234}"); StringFormula au1234b = smgr.makeString("a\\u{1234}b"); StringFormula stringVariable = smgr.makeVariable("stringVariable"); // Javas backslash (double written) is just 1 char assertThatFormula(imgr.equal(smgr.length(backSlash), imgr.makeNumber(1))).isSatisfiable(); assertThatFormula(smgr.equal(smgr.charAt(au1234b, imgr.makeNumber(0)), stringVariable)) .implies(smgr.equal(stringVariable, a)); // It seems like CVC4 sees the backslash as its own char! assertThatFormula(smgr.equal(smgr.charAt(au1234b, imgr.makeNumber(1)), stringVariable)) .implies(smgr.equal(stringVariable, u1234)); assertThatFormula(smgr.equal(smgr.charAt(au1234b, imgr.makeNumber(2)), stringVariable)) .implies(smgr.equal(stringVariable, b)); assertThatFormula( bmgr.and( smgr.equal(smgr.charAt(u1234WOEscape, imgr.makeNumber(0)), u), smgr.equal(smgr.charAt(u1234WOEscape, imgr.makeNumber(1)), num1))) .isSatisfiable(); assertThatFormula( bmgr.and( smgr.equal(smgr.charAt(au1234WOEscape, imgr.makeNumber(0)), a), smgr.equal(smgr.charAt(au1234WOEscape, imgr.makeNumber(1)), u), smgr.equal(smgr.charAt(au1234WOEscape, imgr.makeNumber(2)), num1))) .isSatisfiable(); assertThatFormula( bmgr.and( smgr.equal(smgr.charAt(au1234WOEscapeCurly, imgr.makeNumber(0)), a), smgr.equal(smgr.charAt(au1234WOEscapeCurly, imgr.makeNumber(1)), u), smgr.equal(smgr.charAt(au1234WOEscapeCurly, imgr.makeNumber(2)), curlyOpen), smgr.equal(smgr.charAt(au1234WOEscapeCurly, imgr.makeNumber(7)), curlyClose))) .isSatisfiable(); // Check that the unicode is not treated as seperate chars assertThatFormula( bmgr.and( smgr.equal(smgr.charAt(u1234, imgr.makeNumber(0)), smgr.makeString("\\")), smgr.equal(smgr.charAt(u1234, imgr.makeNumber(1)), u), smgr.equal(smgr.charAt(u1234, imgr.makeNumber(2)), num1))) .isUnsatisfiable(); } /** * Same as {@link #testCharAtWithSpecialCharacters} but only with 2 Byte special chars as Z3 only * supports those. */ @Test public void testCharAtWithSpecialCharacters2Byte() throws SolverException, InterruptedException { StringFormula num7 = smgr.makeString("7"); StringFormula u = smgr.makeString("u"); StringFormula curlyOpen2BUnicode = smgr.makeString("\\u{7B}"); StringFormula curlyClose2BUnicode = smgr.makeString("\\u{7D}"); StringFormula acurlyClose2BUnicodeb = smgr.makeString("a\\u{7D}b"); // Java needs a double {{ as the first one is needed as a escape char for the second, this is a // workaround String workaround = "au{7B}"; StringFormula acurlyOpen2BUnicodeWOEscapeCurly = smgr.makeString(workaround); // StringFormula backSlash = smgr.makeString("\\"); StringFormula a = smgr.makeString("a"); StringFormula b = smgr.makeString("b"); StringFormula stringVariable = smgr.makeVariable("stringVariable"); // Curly braces unicode is treated as 1 char assertThatFormula(imgr.equal(smgr.length(curlyOpen2BUnicode), imgr.makeNumber(1))) .isSatisfiable(); assertThatFormula(imgr.equal(smgr.length(curlyClose2BUnicode), imgr.makeNumber(1))) .isSatisfiable(); // check a}b assertThatFormula( smgr.equal(smgr.charAt(acurlyClose2BUnicodeb, imgr.makeNumber(0)), stringVariable)) .implies(smgr.equal(stringVariable, a)); assertThatFormula( smgr.equal(smgr.charAt(acurlyClose2BUnicodeb, imgr.makeNumber(1)), stringVariable)) .implies(smgr.equal(stringVariable, curlyClose2BUnicode)); assertThatFormula( smgr.equal(smgr.charAt(acurlyClose2BUnicodeb, imgr.makeNumber(2)), stringVariable)) .implies(smgr.equal(stringVariable, b)); // Check the unescaped version (missing backslash) assertThatFormula( bmgr.and( smgr.equal(smgr.charAt(acurlyOpen2BUnicodeWOEscapeCurly, imgr.makeNumber(0)), a), smgr.equal(smgr.charAt(acurlyOpen2BUnicodeWOEscapeCurly, imgr.makeNumber(1)), u), smgr.equal( smgr.charAt(acurlyOpen2BUnicodeWOEscapeCurly, imgr.makeNumber(2)), curlyOpen2BUnicode), smgr.equal(smgr.charAt(acurlyOpen2BUnicodeWOEscapeCurly, imgr.makeNumber(3)), num7), smgr.equal( smgr.charAt(acurlyOpen2BUnicodeWOEscapeCurly, imgr.makeNumber(4)), smgr.makeString("B")), smgr.equal( smgr.charAt(acurlyOpen2BUnicodeWOEscapeCurly, imgr.makeNumber(5)), curlyClose2BUnicode))) .isSatisfiable(); } @Test public void testCharAtWithStringVariable() throws SolverException, InterruptedException { StringFormula a = smgr.makeString("a"); StringFormula b = smgr.makeString("b"); StringFormula ab = smgr.makeString("ab"); StringFormula aa = smgr.makeString("aa"); StringFormula abc = smgr.makeString("abc"); StringFormula aabc = smgr.makeString("aabc"); StringFormula abcb = smgr.makeString("abcb"); StringFormula stringVariable = smgr.makeVariable("stringVariable"); assertThatFormula(smgr.equal(smgr.charAt(ab, imgr.makeNumber(0)), stringVariable)) .implies(smgr.equal(stringVariable, a)); assertThatFormula(smgr.equal(smgr.charAt(ab, imgr.makeNumber(1)), stringVariable)) .implies(smgr.equal(stringVariable, b)); assertThatFormula( bmgr.and( smgr.equal(smgr.charAt(ab, imgr.makeNumber(0)), stringVariable), smgr.equal(smgr.charAt(ab, imgr.makeNumber(1)), stringVariable))) .isUnsatisfiable(); assertThatFormula( bmgr.and( smgr.equal(smgr.charAt(aa, imgr.makeNumber(0)), stringVariable), smgr.equal(smgr.charAt(aa, imgr.makeNumber(1)), stringVariable))) .implies(smgr.equal(stringVariable, a)); assertThatFormula( bmgr.and( smgr.equal(smgr.charAt(stringVariable, imgr.makeNumber(0)), a), smgr.equal(smgr.charAt(stringVariable, imgr.makeNumber(1)), b), imgr.equal(imgr.makeNumber(2), smgr.length(stringVariable)))) .implies(smgr.equal(stringVariable, ab)); assertThatFormula( bmgr.and( smgr.equal(smgr.charAt(stringVariable, imgr.makeNumber(0)), a), smgr.equal(smgr.charAt(stringVariable, imgr.makeNumber(2)), b), imgr.equal(imgr.makeNumber(4), smgr.length(stringVariable)), smgr.suffix(abc, stringVariable))) .implies(smgr.equal(stringVariable, aabc)); assertThatFormula( bmgr.and( smgr.equal(smgr.charAt(stringVariable, imgr.makeNumber(0)), a), smgr.equal(smgr.charAt(stringVariable, imgr.makeNumber(3)), b), imgr.equal(imgr.makeNumber(4), smgr.length(stringVariable)), smgr.suffix(abc, stringVariable))) .implies(smgr.equal(stringVariable, abcb)); assertThatFormula( bmgr.and( smgr.equal(smgr.charAt(stringVariable, imgr.makeNumber(0)), a), smgr.equal(smgr.charAt(stringVariable, imgr.makeNumber(3)), b), imgr.equal(imgr.makeNumber(4), smgr.length(stringVariable)), smgr.prefix(abc, stringVariable))) .implies(smgr.equal(stringVariable, abcb)); } @Test public void testConstStringContains() throws SolverException, InterruptedException { StringFormula empty = smgr.makeString(""); StringFormula a = smgr.makeString("a"); StringFormula aUppercase = smgr.makeString("A"); StringFormula bUppercase = smgr.makeString("B"); StringFormula b = smgr.makeString("b"); StringFormula bbbbbb = smgr.makeString("bbbbbb"); StringFormula bbbbbbb = smgr.makeString("bbbbbbb"); StringFormula abbbbbb = smgr.makeString("abbbbbb"); StringFormula aaaaaaaB = smgr.makeString("aaaaaaaB"); StringFormula abcAndSoOn = smgr.makeString("abcdefghijklmnopqrstuVwxyz"); StringFormula curlyOpen2BUnicode = smgr.makeString("\\u{7B}"); StringFormula curlyClose2BUnicode = smgr.makeString("\\u{7D}"); StringFormula multipleCurlys2BUnicode = smgr.makeString("\\u{7B}\\u{7D}\\u{7B}\\u{7B}"); StringFormula curlyClose2BUnicodeEncased = smgr.makeString("blabla\\u{7D}bla"); assertThatFormula(smgr.contains(empty, empty)).isSatisfiable(); assertThatFormula(smgr.contains(empty, a)).isUnsatisfiable(); assertThatFormula(smgr.contains(a, empty)).isSatisfiable(); assertThatFormula(smgr.contains(a, a)).isSatisfiable(); assertThatFormula(smgr.contains(a, aUppercase)).isUnsatisfiable(); assertThatFormula(smgr.contains(aUppercase, a)).isUnsatisfiable(); assertThatFormula(smgr.contains(a, b)).isUnsatisfiable(); assertThatFormula(smgr.contains(b, b)).isSatisfiable(); assertThatFormula(smgr.contains(abbbbbb, a)).isSatisfiable(); assertThatFormula(smgr.contains(abbbbbb, b)).isSatisfiable(); assertThatFormula(smgr.contains(abbbbbb, bbbbbb)).isSatisfiable(); assertThatFormula(smgr.contains(abbbbbb, bbbbbbb)).isUnsatisfiable(); assertThatFormula(smgr.contains(abbbbbb, aUppercase)).isUnsatisfiable(); assertThatFormula(smgr.contains(abbbbbb, aUppercase)).isUnsatisfiable(); assertThatFormula(smgr.contains(aaaaaaaB, a)).isSatisfiable(); assertThatFormula(smgr.contains(aaaaaaaB, b)).isUnsatisfiable(); assertThatFormula(smgr.contains(aaaaaaaB, bUppercase)).isSatisfiable(); assertThatFormula(smgr.contains(aaaaaaaB, curlyOpen2BUnicode)).isUnsatisfiable(); assertThatFormula(smgr.contains(abcAndSoOn, smgr.makeString("xyz"))).isSatisfiable(); assertThatFormula(smgr.contains(abcAndSoOn, smgr.makeString("Vwxyz"))).isSatisfiable(); assertThatFormula(smgr.contains(abcAndSoOn, smgr.makeString("Vwxyza"))).isUnsatisfiable(); assertThatFormula(smgr.contains(abcAndSoOn, smgr.makeString("t Vwxyz"))).isUnsatisfiable(); assertThatFormula(smgr.contains(multipleCurlys2BUnicode, curlyOpen2BUnicode)).isSatisfiable(); assertThatFormula(smgr.contains(multipleCurlys2BUnicode, curlyClose2BUnicode)).isSatisfiable(); assertThatFormula(smgr.contains(curlyClose2BUnicodeEncased, curlyClose2BUnicode)) .isSatisfiable(); } @Test public void testStringVariableContains() throws SolverException, InterruptedException { StringFormula var1 = smgr.makeVariable("var1"); StringFormula var2 = smgr.makeVariable("var2"); StringFormula empty = smgr.makeString(""); StringFormula bUppercase = smgr.makeString("B"); StringFormula ab = smgr.makeString("ab"); StringFormula bbbbbb = smgr.makeString("bbbbbb"); StringFormula abbbbbb = smgr.makeString("abbbbbb"); StringFormula curlyOpen2BUnicode = smgr.makeString("\\u{7B}"); StringFormula curlyClose2BUnicode = smgr.makeString("\\u{7D}"); assertThatFormula( bmgr.and(smgr.contains(var1, empty), imgr.equal(imgr.makeNumber(0), smgr.length(var1)))) .implies(smgr.equal(var1, empty)); assertThatFormula(bmgr.and(smgr.contains(var1, var2), smgr.contains(var2, var1))) .implies(smgr.equal(var1, var2)); // Unicode is treated as 1 char. So \\u{7B} is treated as { and the B inside is not contained! assertThatFormula( bmgr.and( smgr.contains(var1, curlyOpen2BUnicode), smgr.contains(var1, bUppercase), imgr.equal(imgr.makeNumber(1), smgr.length(var1)))) .isUnsatisfiable(); // Same goes for the curly brackets used as escape sequence assertThatFormula( bmgr.and( smgr.contains(var1, curlyOpen2BUnicode), smgr.contains(var1, curlyClose2BUnicode), imgr.equal(imgr.makeNumber(1), smgr.length(var1)))) .isUnsatisfiable(); assertThatFormula( bmgr.and( smgr.contains(var1, bbbbbb), smgr.contains(var1, ab), imgr.equal(imgr.makeNumber(7), smgr.length(var1)))) .implies(smgr.equal(var1, abbbbbb)); } @Test public void testStringContainsOtherVariable() throws SolverException, InterruptedException { assume() .withMessage("Solver %s runs endlessly on this task", solverToUse()) .that(solverToUse()) .isNotEqualTo(Solvers.Z3); StringFormula var1 = smgr.makeVariable("var1"); StringFormula var2 = smgr.makeVariable("var2"); StringFormula abUppercase = smgr.makeString("AB"); StringFormula ab = smgr.makeString("ab"); assertThatFormula( bmgr.and( smgr.contains(var1, ab), smgr.contains(var2, abUppercase), smgr.contains(var1, var2))) .implies(smgr.contains(var1, abUppercase)); } @Test public void testConstStringIndexOf() throws SolverException, InterruptedException { StringFormula empty = smgr.makeString(""); StringFormula a = smgr.makeString("a"); StringFormula aUppercase = smgr.makeString("A"); StringFormula b = smgr.makeString("b"); StringFormula ab = smgr.makeString("ab"); StringFormula bbbbbb = smgr.makeString("bbbbbb"); StringFormula bbbbbbb = smgr.makeString("bbbbbbb"); StringFormula abbbbbb = smgr.makeString("abbbbbb"); StringFormula abcAndSoOn = smgr.makeString("abcdefghijklmnopqrstuVwxyz"); StringFormula curlyOpen2BUnicode = smgr.makeString("\\u{7B}"); StringFormula curlyClose2BUnicode = smgr.makeString("\\u{7D}"); StringFormula multipleCurlys2BUnicode = smgr.makeString("\\u{7B}\\u{7D}\\u{7B}\\u{7B}"); // Z3 transforms this into {}, but CVC4 does not! CVC4 is on the side of the SMTLIB2 standard as // far as I can see. StringFormula curlys2BUnicodeWOEscape = smgr.makeString("\\u7B\\u7D"); IntegerFormula zero = imgr.makeNumber(0); assertEqual(smgr.indexOf(empty, empty, zero), zero); assertEqual(smgr.indexOf(a, empty, zero), zero); assertEqual(smgr.indexOf(a, a, zero), zero); assertEqual(smgr.indexOf(a, aUppercase, zero), imgr.makeNumber(-1)); assertEqual(smgr.indexOf(abbbbbb, a, zero), zero); assertEqual(smgr.indexOf(abbbbbb, b, zero), imgr.makeNumber(1)); assertEqual(smgr.indexOf(abbbbbb, ab, zero), zero); assertEqual(smgr.indexOf(abbbbbb, bbbbbb, zero), imgr.makeNumber(1)); assertEqual(smgr.indexOf(abbbbbb, bbbbbbb, zero), imgr.makeNumber(-1)); assertEqual(smgr.indexOf(abbbbbb, smgr.makeString("c"), zero), imgr.makeNumber(-1)); assertEqual(smgr.indexOf(abcAndSoOn, smgr.makeString("z"), zero), imgr.makeNumber(25)); assertEqual(smgr.indexOf(abcAndSoOn, smgr.makeString("V"), zero), imgr.makeNumber(21)); assertEqual(smgr.indexOf(abcAndSoOn, smgr.makeString("v"), zero), imgr.makeNumber(-1)); assertEqual(smgr.indexOf(multipleCurlys2BUnicode, curlyOpen2BUnicode, zero), zero); assertEqual( smgr.indexOf(multipleCurlys2BUnicode, curlyClose2BUnicode, zero), imgr.makeNumber(1)); // TODO: Z3 and CVC4 handle this differently! // assertEqual(smgr.indexOf(multipleCurlys2BUnicode, curlys2BUnicodeWOEscape, zero), zero); assertEqual( smgr.indexOf(multipleCurlys2BUnicode, curlys2BUnicodeWOEscape, imgr.makeNumber(1)), imgr.makeNumber(-1)); assertEqual( smgr.indexOf(multipleCurlys2BUnicode, smgr.makeString("B"), zero), imgr.makeNumber(-1)); } @Test public void testStringVariableIndexOf() throws SolverException, InterruptedException { StringFormula var1 = smgr.makeVariable("var1"); StringFormula var2 = smgr.makeVariable("var2"); IntegerFormula intVar = imgr.makeVariable("intVar"); StringFormula empty = smgr.makeString(""); StringFormula curlyOpen2BUnicode = smgr.makeString("\\u{7B}"); IntegerFormula zero = imgr.makeNumber(0); // If the index of var2 is not -1, it is contained in var1. assertThatFormula( bmgr.and( bmgr.not(imgr.equal(intVar, imgr.makeNumber(-1))), imgr.equal(intVar, smgr.indexOf(var1, var2, zero)))) .implies(smgr.contains(var1, var2)); // If the index is less than 0 (only -1 possible) it is not contained. assertThatFormula( bmgr.and( imgr.equal(intVar, smgr.indexOf(var1, var2, zero)), imgr.lessThan(intVar, zero))) .implies(bmgr.not(smgr.contains(var1, var2))); // If the index of var2 in var is >= 0 and vice versa, both contain each other. assertThatFormula( bmgr.and( imgr.greaterOrEquals(smgr.indexOf(var1, var2, zero), zero), imgr.greaterOrEquals(smgr.indexOf(var2, var1, zero), zero))) .implies(bmgr.and(smgr.contains(var1, var2), smgr.contains(var2, var1))); // If the are indices equal and one is >= 0 and the strings are not "", both are contained in // each other and the chars at the position must be the same. assertThatFormula( bmgr.and( imgr.equal(smgr.indexOf(var1, var2, zero), smgr.indexOf(var2, var1, zero)), imgr.greaterOrEquals(smgr.indexOf(var1, var2, zero), zero), bmgr.not(smgr.equal(empty, smgr.charAt(var1, smgr.indexOf(var1, var2, zero)))))) .implies( bmgr.and( smgr.contains(var1, var2), smgr.contains(var2, var1), smgr.equal( smgr.charAt(var1, smgr.indexOf(var2, var1, zero)), smgr.charAt(var1, smgr.indexOf(var1, var2, zero))))); // If a String contains {, but not B, the index of B must be -1. (unicode of { contains B) assertThatFormula( bmgr.and( smgr.contains(var1, curlyOpen2BUnicode), bmgr.not(smgr.contains(var1, smgr.makeString("B"))))) .implies( bmgr.and( imgr.greaterOrEquals(smgr.indexOf(var1, curlyOpen2BUnicode, zero), zero), imgr.equal(imgr.makeNumber(-1), smgr.indexOf(var1, smgr.makeString("B"), zero)))); } @Test public void testStringIndexOfWithSubStrings() throws SolverException, InterruptedException { assume() .withMessage("Solver %s runs endlessly on this task", solverToUse()) .that(solverToUse()) .isNotEqualTo(Solvers.Z3); StringFormula var1 = smgr.makeVariable("var1"); IntegerFormula zero = imgr.makeNumber(0); // If the index of the string abba is 0, the index of the string bba is 1, and b is 1, and ba is assertThatFormula(imgr.equal(zero, smgr.indexOf(var1, smgr.makeString("abba"), zero))) .implies( bmgr.and( smgr.contains(var1, smgr.makeString("abba")), imgr.equal(imgr.makeNumber(1), smgr.indexOf(var1, smgr.makeString("bba"), zero)), imgr.equal(imgr.makeNumber(1), smgr.indexOf(var1, smgr.makeString("b"), zero)), imgr.equal(imgr.makeNumber(2), smgr.indexOf(var1, smgr.makeString("ba"), zero)))); } @Test public void testStringPrefixImpliesPrefixIndexOf() throws SolverException, InterruptedException { assume() .withMessage("Solver %s runs endlessly on this task", solverToUse()) .that(solverToUse()) .isNoneOf(Solvers.Z3, Solvers.CVC4); StringFormula var1 = smgr.makeVariable("var1"); StringFormula var2 = smgr.makeVariable("var2"); IntegerFormula zero = imgr.makeNumber(0); // If a prefix (var2) is non empty, the length of the string (var1) has to be larger or equal to // the prefix // and the chars have to be the same for the lenth of the prefix, meaning the indexOf the prefix // must be 0 in the string. assertThatFormula(bmgr.and(imgr.greaterThan(smgr.length(var2), zero), smgr.prefix(var2, var1))) .implies( bmgr.and( smgr.contains(var1, var2), imgr.greaterOrEquals(smgr.length(var1), smgr.length(var2)), imgr.equal(zero, smgr.indexOf(var1, var2, zero)))); } @Test public void testConstStringSubStrings() throws SolverException, InterruptedException { StringFormula empty = smgr.makeString(""); StringFormula a = smgr.makeString("a"); StringFormula aUppercase = smgr.makeString("A"); StringFormula bUppercase = smgr.makeString("B"); StringFormula bbbbbb = smgr.makeString("bbbbbb"); StringFormula curlyOpen2BUnicode = smgr.makeString("\\u{7B}"); StringFormula curlyClose2BUnicode = smgr.makeString("\\u{7D}"); StringFormula multipleCurlys2BUnicode = smgr.makeString("\\u{7B}\\u{7D}\\u{7B}\\u{7B}"); IntegerFormula zero = imgr.makeNumber(0); IntegerFormula one = imgr.makeNumber(1); // Check empty string assertEqual(smgr.substring(empty, zero, zero), empty); // Check length 0 = empty string assertEqual(smgr.substring(a, one, zero), empty); // Check that it correctly recognized uppercase assertDistinct(smgr.substring(a, zero, one), aUppercase); assertDistinct(smgr.substring(aUppercase, zero, one), a); assertDistinct(smgr.substring(bbbbbb, zero, one), bUppercase); // Check smgr length interaction assertEqual(smgr.substring(bbbbbb, zero, smgr.length(bbbbbb)), bbbbbb); // Check unicode substrings assertEqual(smgr.substring(multipleCurlys2BUnicode, zero, one), curlyOpen2BUnicode); assertEqual(smgr.substring(multipleCurlys2BUnicode, one, one), curlyClose2BUnicode); } @Test public void testConstStringAllPossibleSubStrings() throws SolverException, InterruptedException { for (String wordString : WORDS) { StringFormula word = smgr.makeString(wordString); for (int j = 0; j < wordString.length(); j++) { for (int k = j; k < wordString.length(); k++) { // Loop through all combinations of substrings // Note: String.substring uses begin index and end index (non-including) while SMT based // substring uses length! // Length = endIndex - beginIndex String wordSubString = wordString.substring(j, k); assertEqual( smgr.substring(word, imgr.makeNumber(j), imgr.makeNumber(k - j)), smgr.makeString(wordSubString)); } } } } @Test public void testStringSubstringOutOfBounds() throws SolverException, InterruptedException { StringFormula bbbbbb = smgr.makeString("bbbbbb"); StringFormula b = smgr.makeString("b"); StringFormula abbbbbb = smgr.makeString("abbbbbb"); StringFormula multipleCurlys2BUnicode = smgr.makeString("\\u{7B}\\u{7D}\\u{7B}\\u{7B}"); StringFormula multipleCurlys2BUnicodeFromIndex1 = smgr.makeString("\\u{7D}\\u{7B}\\u{7B}"); assertEqual(smgr.substring(abbbbbb, imgr.makeNumber(0), imgr.makeNumber(10000)), abbbbbb); assertEqual(smgr.substring(abbbbbb, imgr.makeNumber(6), imgr.makeNumber(10000)), b); assertEqual(smgr.substring(abbbbbb, imgr.makeNumber(1), imgr.makeNumber(10000)), bbbbbb); assertEqual( smgr.substring(multipleCurlys2BUnicode, imgr.makeNumber(1), imgr.makeNumber(10000)), multipleCurlys2BUnicodeFromIndex1); } @Test public void testStringVariablesSubstring() throws SolverException, InterruptedException { StringFormula var1 = smgr.makeVariable("var1"); StringFormula var2 = smgr.makeVariable("var2"); IntegerFormula intVar1 = imgr.makeVariable("intVar1"); IntegerFormula intVar2 = imgr.makeVariable("intVar2"); // If a Prefix of a certain length exists, the substring over that equals the prefix assertThatFormula(smgr.prefix(var2, var1)) .implies(smgr.equal(var2, smgr.substring(var1, imgr.makeNumber(0), smgr.length(var2)))); // Same with suffix assertThatFormula(smgr.suffix(var2, var1)) .implies( smgr.equal( var2, smgr.substring( var1, imgr.subtract(smgr.length(var1), smgr.length(var2)), smgr.length(var2)))); // If a string has a char at a specified position, a substring beginning with the same index // must have the same char, independent of the length of the substring. // But its not really relevant to check out of bounds cases, hence the exclusion. // So we test substring length 1 (== charAt) and larger assertThatFormula( bmgr.and( imgr.greaterThan(intVar2, imgr.makeNumber(1)), smgr.equal(var2, smgr.charAt(var1, intVar1)), imgr.greaterThan(smgr.length(var1), intVar1))) .implies( smgr.equal( var2, smgr.charAt(smgr.substring(var1, intVar1, intVar2), imgr.makeNumber(0)))); assertThatFormula(smgr.equal(var2, smgr.charAt(var1, intVar1))) .implies(smgr.equal(var2, smgr.substring(var1, intVar1, imgr.makeNumber(1)))); } @Test public void testConstStringReplace() throws SolverException, InterruptedException { for (int i = 0; i < WORDS.size(); i++) { for (int j = 2; j < WORDS.size(); j++) { String word1 = WORDS.get(j - 1); String word2 = WORDS.get(j); String word3 = WORDS.get(i); StringFormula word1F = smgr.makeString(word1); StringFormula word2F = smgr.makeString(word2); StringFormula word3F = smgr.makeString(word3); StringFormula result = smgr.makeString(word3.replaceFirst(word2, word1)); assertEqual(smgr.replace(word3F, word2F, word1F), result); } } } // Neither CVC4 nor Z3 can solve this! @Ignore @Test public void testStringVariableReplacePrefix() throws SolverException, InterruptedException { StringFormula var1 = smgr.makeVariable("var1"); StringFormula var2 = smgr.makeVariable("var2"); StringFormula var3 = smgr.makeVariable("var3"); StringFormula prefix = smgr.makeVariable("prefix"); // If var1 has a prefix, and you replace said prefix with var3 (saved in var2), the prefix of // var2 is var3 assertThatFormula( bmgr.and( smgr.equal(var2, smgr.replace(var1, prefix, var3)), smgr.prefix(prefix, var1), bmgr.not(smgr.equal(prefix, var3)), imgr.greaterThan(smgr.length(prefix), imgr.makeNumber(0)), imgr.greaterThan(smgr.length(var3), imgr.makeNumber(0)))) .implies(bmgr.and(bmgr.not(smgr.equal(var1, var2)), smgr.prefix(var3, var2))); assertThatFormula( bmgr.and( smgr.equal(var2, smgr.replace(var1, prefix, var3)), smgr.prefix(prefix, var1), bmgr.not(smgr.equal(prefix, var3)))) .implies(bmgr.and(smgr.prefix(var3, var2), bmgr.not(smgr.equal(var1, var2)))); } @Test public void testStringVariableReplaceSubstring() throws SolverException, InterruptedException { // I couldn't find stronger constraints in the implication that don't run endlessly..... StringFormula original = smgr.makeVariable("original"); StringFormula prefix = smgr.makeVariable("prefix"); StringFormula replacement = smgr.makeVariable("replacement"); StringFormula replaced = smgr.makeVariable("replaced"); // Set a prefix that does not contain the suffix substring, make sure that the substring that // comes after the prefix is replaced assertThatFormula( bmgr.and( smgr.prefix(prefix, original), imgr.equal( smgr.length(prefix), smgr.indexOf( original, smgr.substring(original, smgr.length(prefix), smgr.length(original)), imgr.makeNumber(0))), imgr.greaterThan(smgr.length(original), smgr.length(prefix)), imgr.greaterThan(smgr.length(prefix), imgr.makeNumber(0)), imgr.greaterThan( smgr.length( smgr.substring(original, smgr.length(prefix), smgr.length(original))), imgr.makeNumber(0)), smgr.equal( replaced, smgr.replace( original, smgr.substring(original, smgr.length(prefix), smgr.length(original)), replacement)))) .implies( smgr.equal( replacement, smgr.substring(replaced, smgr.length(prefix), smgr.length(replaced)))); // In this version it is still possible that parts of the prefix and suffix together build the // suffix, replacing parts of the prefix additionally to the implication above (or the // replacement is empty) assertThatFormula( bmgr.and( smgr.prefix(prefix, original), bmgr.not(smgr.contains(original, replacement)), bmgr.not( smgr.contains( smgr.substring(original, smgr.length(prefix), smgr.length(original)), prefix)), bmgr.not( smgr.contains( prefix, smgr.substring(original, smgr.length(prefix), smgr.length(original)))), imgr.greaterThan(smgr.length(original), smgr.length(prefix)), imgr.greaterThan(smgr.length(prefix), imgr.makeNumber(0)), smgr.equal( replaced, smgr.replace( original, smgr.substring(original, smgr.length(prefix), smgr.length(original)), replacement)))) .implies(smgr.contains(replacement, replacement)); // This version may have the original as a larger version of the prefix; prefix: a, original: // aaa assertThatFormula( bmgr.and( smgr.prefix(prefix, original), bmgr.not(smgr.contains(original, replacement)), bmgr.not( smgr.contains( prefix, smgr.substring(original, smgr.length(prefix), smgr.length(original)))), imgr.greaterThan(smgr.length(original), smgr.length(prefix)), imgr.greaterThan(smgr.length(prefix), imgr.makeNumber(0)), smgr.equal( replaced, smgr.replace( original, smgr.substring(original, smgr.length(prefix), smgr.length(original)), replacement)))) .implies(smgr.contains(replacement, replacement)); // This version can contain the substring in the prefix! assertThatFormula( bmgr.and( smgr.prefix(prefix, original), bmgr.not(smgr.contains(original, replacement)), imgr.greaterThan(smgr.length(original), smgr.length(prefix)), imgr.greaterThan(smgr.length(prefix), imgr.makeNumber(0)), smgr.equal( replaced, smgr.replace( original, smgr.substring(original, smgr.length(prefix), smgr.length(original)), replacement)))) .implies(smgr.contains(replacement, replacement)); } @Test public void testStringVariableReplaceMiddle() throws SolverException, InterruptedException { // TODO: either rework that this terminates, or remove assume() .withMessage("Solver %s runs endlessly on this task.", solverToUse()) .that(solverToUse()) .isNoneOf(Solvers.CVC4, Solvers.Z3); StringFormula original = smgr.makeVariable("original"); StringFormula replacement = smgr.makeVariable("replacement"); StringFormula replaced = smgr.makeVariable("replaced"); StringFormula beginning = smgr.makeVariable("beginning"); StringFormula middle = smgr.makeVariable("middle"); StringFormula end = smgr.makeVariable("end"); // If beginning + middle + end (length of each > 0) get concated (in original), replacing // beginning/middle/end // with replacement (result = replaces; replacement > 0 and != the replaced) results in a // string that is equal to the concat of the 2 remaining start strings and the replaced one // replaced // This is tested with 2 different implications, 1 that only checks wheter or not the // replacement is contained in the string and not in the original and vice verse for the // replaced String BooleanFormula formula = bmgr.and( smgr.equal(original, smgr.concat(beginning, middle, end)), smgr.equal(replaced, smgr.replace(original, middle, replacement)), bmgr.not(smgr.equal(middle, replacement)), bmgr.not(smgr.equal(beginning, replacement)), bmgr.not(smgr.equal(end, replacement)), bmgr.not(smgr.equal(beginning, middle)), imgr.greaterThan(smgr.length(middle), imgr.makeNumber(0)), imgr.greaterThan(smgr.length(replacement), imgr.makeNumber(0)), imgr.greaterThan(smgr.length(beginning), imgr.makeNumber(0))); assertThatFormula(formula) .implies( bmgr.and( bmgr.not(smgr.equal(original, replaced)), smgr.contains(replaced, replacement))); // Same as above, but with concat instead of contains assertThatFormula(formula) .implies( bmgr.and( bmgr.not(smgr.equal(original, replaced)), smgr.equal(replaced, smgr.concat(beginning, replacement, end)))); } @Test public void testStringVariableReplaceFront() throws SolverException, InterruptedException { assume() .withMessage("Solver %s runs endlessly on this task.", solverToUse()) .that(solverToUse()) .isNotEqualTo(Solvers.Z3); StringFormula var1 = smgr.makeVariable("var1"); StringFormula var2 = smgr.makeVariable("var2"); StringFormula var3 = smgr.makeVariable("var3"); StringFormula var4 = smgr.makeVariable("var4"); StringFormula var5 = smgr.makeVariable("var5"); // If var1 and 2 get concated (in var4) such that var1 is in front, replacing var1 with var3 // (var5) results in a // string that is equal to var3 + var2 // First with length constraints, second without assertThatFormula( bmgr.and( smgr.equal(var4, smgr.concat(var1, var2)), smgr.equal(var5, smgr.replace(var4, var1, var3)), bmgr.not(smgr.equal(var1, var3)), imgr.greaterThan(smgr.length(var1), imgr.makeNumber(0)), imgr.greaterThan(smgr.length(var3), imgr.makeNumber(0)))) .implies(bmgr.and(bmgr.not(smgr.equal(var4, var5)), smgr.prefix(var3, var5))); assertThatFormula( bmgr.and( smgr.equal(var4, smgr.concat(var1, var2)), smgr.equal(var5, smgr.replace(var4, var1, var3)), bmgr.not(smgr.equal(var1, var3)))) .implies(bmgr.and(bmgr.not(smgr.equal(var4, var5)), smgr.prefix(var3, var5))); } @Test public void testConstStringReplaceAll() throws SolverException, InterruptedException { assume() .withMessage("Solver %s does not support replaceAll()", solverToUse()) .that(solverToUse()) .isNotEqualTo(Solvers.Z3); for (int i = 0; i < WORDS.size(); i++) { for (int j = 1; j < WORDS.size(); j++) { String word1 = WORDS.get(i); String word2 = WORDS.get(j); String word3 = "replacement"; StringFormula word1F = smgr.makeString(word1); StringFormula word2F = smgr.makeString(word2); StringFormula word3F = smgr.makeString(word3); StringFormula result = smgr.makeString(word3.replaceAll(word2, word1)); assertEqual(smgr.replaceAll(word3F, word2F, word1F), result); } } } /** * Concat a String that consists of a String that is later replaces with replaceAll. The resulting * String should consist of only concatinated versions of itself. */ @Test public void testStringVariableReplaceAllConcatedString() throws SolverException, InterruptedException { assume() .withMessage("Solver %s does not support replaceAll()", solverToUse()) .that(solverToUse()) .isNotEqualTo(Solvers.Z3); // 2 concats is the max number CVC4 supports without running endlessly for (int numOfConcats = 0; numOfConcats < 3; numOfConcats++) { StringFormula original = smgr.makeVariable("original"); StringFormula replacement = smgr.makeVariable("replacement"); StringFormula replaced = smgr.makeVariable("replaced"); StringFormula segment = smgr.makeVariable("segment"); StringFormula[] concatSegments = new StringFormula[numOfConcats]; StringFormula[] concatReplacements = new StringFormula[numOfConcats]; for (int i = 0; i < numOfConcats; i++) { concatSegments[i] = segment; concatReplacements[i] = replacement; } BooleanFormula formula = bmgr.and( smgr.equal(original, smgr.concat(concatSegments)), smgr.equal(replaced, smgr.replaceAll(original, segment, replacement)), bmgr.not(smgr.equal(segment, replacement)), imgr.greaterThan(smgr.length(segment), imgr.makeNumber(0)), imgr.greaterThan(smgr.length(replacement), imgr.makeNumber(0))); assertThatFormula(formula).implies(smgr.equal(replaced, smgr.concat(concatReplacements))); } } @Test public void testStringVariableReplaceAllSubstring() throws SolverException, InterruptedException { assume() .withMessage("Solver %s does not support replaceAll()", solverToUse()) .that(solverToUse()) .isNotEqualTo(Solvers.Z3); // I couldn't find stronger constraints in the implication that don't run endlessly..... StringFormula original = smgr.makeVariable("original"); StringFormula prefix = smgr.makeVariable("prefix"); StringFormula replacement = smgr.makeVariable("replacement"); StringFormula replaced = smgr.makeVariable("replaced"); // Set a prefix that does not contain the suffix substring, make sure that the substring that // comes after the prefix is replaced assertThatFormula( bmgr.and( smgr.prefix(prefix, original), imgr.equal( smgr.length(prefix), smgr.indexOf( original, smgr.substring(original, smgr.length(prefix), smgr.length(original)), imgr.makeNumber(0))), imgr.greaterThan(smgr.length(original), smgr.length(prefix)), imgr.greaterThan(smgr.length(prefix), imgr.makeNumber(0)), imgr.greaterThan( smgr.length( smgr.substring(original, smgr.length(prefix), smgr.length(original))), imgr.makeNumber(0)), smgr.equal( replaced, smgr.replaceAll( original, smgr.substring(original, smgr.length(prefix), smgr.length(original)), replacement)))) .implies( smgr.equal( replacement, smgr.substring(replaced, smgr.length(prefix), smgr.length(replaced)))); } @Test public void testStringConcatWUnicode() throws SolverException, InterruptedException { StringFormula backslash = smgr.makeString("\\"); StringFormula u = smgr.makeString("u"); StringFormula curlyOpen = smgr.makeString("\\u{7B}"); StringFormula sevenB = smgr.makeString("7B"); StringFormula curlyClose = smgr.makeString("\\u{7D}"); StringFormula concat = smgr.concat(backslash, u, curlyOpen, sevenB, curlyClose); StringFormula complete = smgr.makeString("\\u{7B}"); // Concatting parts of unicode does not result in the unicode char! assertDistinct(concat, complete); } @Test public void testStringSimpleRegex() { // TODO } @Test public void testVisitorForStringConstants() { BooleanFormula eq = bmgr.and( smgr.equal(smgr.makeString("x"), smgr.makeString("xx")), smgr.lessThan(smgr.makeString("y"), smgr.makeString("yy"))); Map<String, Formula> freeVars = mgr.extractVariables(eq); assertThat(freeVars).isEmpty(); Map<String, Formula> freeVarsAndUfs = mgr.extractVariablesAndUFs(eq); assertThat(freeVarsAndUfs).isEmpty(); } @Test public void testVisitorForRegexConstants() { RegexFormula concat = smgr.concat(smgr.makeRegex("x"), smgr.makeRegex("xx")); Map<String, Formula> freeVars = mgr.extractVariables(concat); assertThat(freeVars).isEmpty(); Map<String, Formula> freeVarsAndUfs = mgr.extractVariablesAndUFs(concat); assertThat(freeVarsAndUfs).isEmpty(); } @Test public void testVisitorForStringSymbols() { BooleanFormula eq = smgr.equal(smgr.makeVariable("x"), smgr.makeString("xx")); Map<String, Formula> freeVars = mgr.extractVariables(eq); assertThat(freeVars).containsExactly("x", smgr.makeVariable("x")); Map<String, Formula> freeVarsAndUfs = mgr.extractVariablesAndUFs(eq); assertThat(freeVarsAndUfs).containsExactly("x", smgr.makeVariable("x")); } @Test public void testVisitorForRegexSymbols() { BooleanFormula in = smgr.in(smgr.makeVariable("x"), smgr.makeRegex("xx")); Map<String, Formula> freeVars = mgr.extractVariables(in); assertThat(freeVars).containsExactly("x", smgr.makeVariable("x")); Map<String, Formula> freeVarsAndUfs = mgr.extractVariablesAndUFs(in); assertThat(freeVarsAndUfs).containsExactly("x", smgr.makeVariable("x")); } }
package ru.artyushov.jmhPlugin.configuration; import com.intellij.compiler.CompilerConfiguration; import com.intellij.compiler.CompilerConfigurationImpl; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.*; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.util.JavaParametersUtil; import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.ProjectRootManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.jps.model.java.compiler.ProcessorConfigProfile; import static com.intellij.execution.configurations.JavaParameters.CLASSES_AND_TESTS; import static com.intellij.execution.configurations.JavaParameters.CLASSES_ONLY; import static com.intellij.execution.configurations.JavaParameters.JDK_AND_CLASSES; import static com.intellij.execution.configurations.JavaParameters.JDK_AND_CLASSES_AND_TESTS; import static com.intellij.openapi.actionSystem.CommonDataKeys.PROJECT; public class BenchmarkState extends CommandLineState { private final Project project; private final JmhConfiguration configuration; public BenchmarkState(Project project, JmhConfiguration configuration, ExecutionEnvironment environment) { super(environment); this.project = project; this.configuration = configuration; automaticallyEnableAnnotationProcessor(configuration); } private void automaticallyEnableAnnotationProcessor(JmhConfiguration configuration) { Module module = configuration.getConfigurationModule().getModule(); if (module != null) { CompilerConfigurationImpl compilerConfiguration = (CompilerConfigurationImpl) CompilerConfiguration.getInstance(module.getProject()); ProcessorConfigProfile processorConfigProfile = compilerConfiguration.getAnnotationProcessingConfiguration(module); if (!processorConfigProfile.isEnabled()) { processorConfigProfile.setEnabled(true); // refresh compilerConfiguration compilerConfiguration.getState(); } } } protected JavaParameters createJavaParameters() throws ExecutionException { JavaParameters parameters = new JavaParameters(); JavaParametersUtil.configureConfiguration(parameters, configuration); parameters.setMainClass(JmhConfiguration.JMH_START_CLASS); int classPathType = removeJdkClasspath(JavaParametersUtil.getClasspathType(configuration.getConfigurationModule(), configuration.getBenchmarkClass(), true)); JavaParametersUtil.configureModule(configuration.getConfigurationModule(), parameters, classPathType, null); Module module = configuration.getConfigurationModule().getModule(); if (parameters.getJdk() == null){ parameters.setJdk(module != null ? ModuleRootManager.getInstance(module).getSdk() : ProjectRootManager.getInstance(project).getProjectSdk()); } return parameters; } @NotNull @Override protected ProcessHandler startProcess() throws ExecutionException { return JavaCommandLineStateUtil.startProcess(createCommandLine(), false); } private GeneralCommandLine createCommandLine() throws ExecutionException { return CommandLineBuilder.createFromJavaParameters(createJavaParameters(), PROJECT .getData(DataManager.getInstance().getDataContext()), true); } private int removeJdkClasspath(int classpathType) { switch (classpathType) { case JDK_AND_CLASSES: return CLASSES_ONLY; case JDK_AND_CLASSES_AND_TESTS: return CLASSES_AND_TESTS; default: return classpathType; } } }
package sqlancer.cockroachdb.gen; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import sqlancer.Query; import sqlancer.QueryAdapter; import sqlancer.Randomly; import sqlancer.cockroachdb.CockroachDBErrors; import sqlancer.cockroachdb.CockroachDBProvider.CockroachDBGlobalState; import sqlancer.cockroachdb.CockroachDBSchema.CockroachDBColumn; import sqlancer.cockroachdb.CockroachDBSchema.CockroachDBTable; import sqlancer.cockroachdb.CockroachDBVisitor; public class CockroachDBInsertGenerator { public static Query insert(CockroachDBGlobalState globalState) { Set<String> errors = new HashSet<>(); CockroachDBErrors.addExpressionErrors(errors); // e.g., caused by computed columns errors.add("violates not-null constraint"); errors.add("violates unique constraint"); errors.add("primary key column"); errors.add("cannot write directly to computed column"); // TODO: do not select generated columns errors.add("failed to satisfy CHECK constraint"); errors.add("violates foreign key constraint"); errors.add("foreign key violation"); errors.add("multi-part foreign key"); StringBuilder sb = new StringBuilder(); CockroachDBTable table = globalState.getSchema().getRandomTable(t -> !t.isView()); boolean isUpsert = Randomly.getBoolean(); if (!isUpsert) { sb.append("INSERT INTO "); } else { sb.append("UPSERT INTO "); errors.add("UPSERT or INSERT...ON CONFLICT command cannot affect row a second time"); } sb.append(table.getName()); sb.append(" "); CockroachDBExpressionGenerator gen = new CockroachDBExpressionGenerator(globalState); if (Randomly.getBooleanWithSmallProbability()) { sb.append("DEFAULT VALUES"); } else { List<CockroachDBColumn> columns = table.getRandomNonEmptyColumnSubset(); sb.append("("); sb.append(columns.stream().map(c -> c.getName()).collect(Collectors.joining(", "))); sb.append(")"); sb.append(" VALUES"); for (int j = 0; j < Randomly.smallNumber() + 1; j++) { if (j != 0) { sb.append(", "); } sb.append("("); int i = 0; for (CockroachDBColumn c : columns) { if (i++ != 0) { sb.append(", "); } sb.append(CockroachDBVisitor.asString(gen.generateConstant(c.getColumnType()))); } sb.append(")"); } } if (Randomly.getBoolean() && !isUpsert) { sb.append(" ON CONFLICT ("); sb.append(table.getRandomNonEmptyColumnSubset().stream().map(c -> c.getName()).collect(Collectors.joining(", "))); sb.append(")"); sb.append(" DO "); if (Randomly.getBoolean()) { sb.append(" NOTHING "); } else { sb.append(" UPDATE SET "); List<CockroachDBColumn> columns = table.getRandomNonEmptyColumnSubset(); int i = 0; for (CockroachDBColumn c : columns) { if (i++ != 0) { sb.append(", "); } sb.append(c.getName()); sb.append(" = "); sb.append(CockroachDBVisitor.asString(gen.generateConstant(c.getColumnType()))); } errors.add("UPSERT or INSERT...ON CONFLICT command cannot affect row a second time"); } errors.add("there is no unique or exclusion constraint matching the ON CONFLICT specification"); } CockroachDBErrors.addTransactionErrors(errors); return new QueryAdapter(sb.toString(), errors); } }
package com.alibaba.json.bvt.issue_3200; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.serializer.NameFilter; import junit.framework.TestCase; public class Issue3206 extends TestCase { public void test_for_issue() throws Exception { VO vo = new VO(); vo.date = new java.util.Date(1590819204293L); assertEquals(JSON.toJSONString(vo), "{\"date\":\"2020-05-30\"}"); String str = JSON.toJSONString(vo, new NameFilter() { public String process(Object object, String name, Object value) { return name; } }); assertEquals(str, "{\"date\":\"2020-05-30\"}"); } public static class VO { @JSONField(format="yyyy-MM-dd") public java.util.Date date; } }
package com.catalyst.sonar.score.batch; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import junitx.framework.Assert; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * @author lsajeev * */ public class TrophyTest{ Trophy testTrophy; Trophy testTrophyCopy = testTrophy; Trophy testTrophyOne; Trophy testTrophyTwo; Trophy testTrophyThree; Trophy testTrophyFour; Criteria testCriteria; Criteria testCriteriaOne; Criteria testCriteriaTwo; Criteria testCriteriaThree; List<Criteria> testList = new ArrayList<Criteria>(); //trophyName String trophy = "Great Code"; String trophyOne = "Great Code"; String trophyTwo = null; String trophyThree = "No Violation"; String trophyFour = "PointsTrophy"; //criteria values String testMetric = "Violation"; double testRequiredAmt = 10; int testDays = 14; String testMetricOne = "Coverage"; double testRequiredAmtOne = 90; int testDaysOne = 4; String testMetricTwo = "Coverage"; double testRequiredAmtTwo = 90; int testDaysTwo = 4; /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { testTrophy = new Trophy(); testTrophy.setTrophyName(trophy); testCriteriaOne = new Criteria(); testTrophy.addCriteria(testCriteriaOne); Criteria testCriteriaCopy = testCriteriaOne; testTrophyCopy = new Trophy(trophyOne); testTrophyCopy.addCriteria(testCriteriaCopy); testCriteriaTwo = new Criteria(); testTrophyThree = new Trophy(trophyThree); testTrophyThree.addCriteria(testCriteriaThree); testTrophyTwo = new Trophy(trophyTwo); } /** * tests setter and getter for trophyName */ @Test public void testGetTrophyName() { testTrophy.setTrophyName("TrophyOne"); assertEquals("TrophyOne", testTrophy.getTrophyName()); } /** * tests if Criteria can be added to the list */ @Test public void testAddCriteria() { assertEquals(testList.size(), 0); testList.add(testCriteria); testList.add(testCriteriaTwo); assertEquals(testList.size(), 2); } /** * tests getter for Criteria */ @Test public void testGetCriteria() { assertEquals("1",1, testTrophy.getCriteria().size()); } /** * tests if trophy objects are equal */ @Test public void testTrophyEquals() { assertTrue(testTrophy.equals(testTrophyCopy)); } /** * tests if trophy objects are not equal */ @Test public void testTrophyNotEquals() { assertFalse(testTrophy.equals(testTrophyOne)); } /** * tests if a trophy object is null */ @Test public void testTrophyEqualsNull() { assertNull(testTrophyFour); } /** * tests if trophy object's name is null */ @Test public void testTrophyNameEqualsToNull() { assertNull(testTrophyTwo.getTrophyName()); } /** * tests if trophy object has a name and is not null */ @Test public void testTrophyNameNotEqualToNull() { assertNotNull(testTrophy.getTrophyName()); } /** * tests if trophy name is not equal to the trophy object's trophy name */ @Test public void testTrophyNameNotEquals() { assertFalse(trophy.equals(testTrophyThree.getTrophyName())); } /** * tests if trophy name is equal to trophy object's trophy name */ @Test public void testTrophyNameEquals() { assertTrue(trophy.equals(testTrophy.getTrophyName())); } /** * tests if the haschCode of two trophyObjects are equal */ @Test public void testHashCodeIsEqual(){ assertEquals("Expected same as actual", testTrophy.hashCode(), testTrophyCopy.hashCode()); } /** * tests if the hashCode of two objects are not equal */ @Test public void testHashCodeIsNotEqual(){ Assert.assertNotEquals(testTrophy.hashCode(), testTrophyThree.hashCode()); } /** * @throws java.lang.Exception */ @After public void tearDown() throws Exception { } }
package com.github.dakusui.actionunit; import com.github.dakusui.actionunit.TestOutput.Text; import com.github.dakusui.actionunit.connectors.Connectors; import com.github.dakusui.actionunit.connectors.Sink; import com.github.dakusui.actionunit.visitors.ActionRunner; import com.google.common.base.Function; import org.junit.ComparisonFailure; import org.junit.Test; import java.io.IOException; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import static com.github.dakusui.actionunit.Action.ForEach.Mode.CONCURRENTLY; import static com.github.dakusui.actionunit.Action.ForEach.Mode.SEQUENTIALLY; import static com.github.dakusui.actionunit.Actions.*; import static com.github.dakusui.actionunit.Utils.describe; import static com.github.dakusui.actionunit.Utils.transform; import static com.google.common.base.Throwables.propagate; import static com.google.common.collect.Iterables.toArray; import static java.lang.System.currentTimeMillis; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static java.util.Collections.synchronizedList; import static java.util.concurrent.TimeUnit.*; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; public class ActionsTest { @Test public void simpleTest() { final List<String> arr = new ArrayList<>(); simple(new Runnable() { @Override public void run() { arr.add("Hello"); } }).accept(new ActionRunner.Impl()); assertArrayEquals(arr.toArray(), new Object[] { "Hello" }); } @Test public void sequentialTest() { final List<String> arr = new ArrayList<>(); sequential( simple(new Runnable() { @Override public void run() { arr.add("Hello A"); } }), simple(new Runnable() { @Override public void run() { arr.add("Hello B"); } }) ).accept(new ActionRunner.Impl()); assertEquals(asList("Hello A", "Hello B"), arr); } @Test public void givenSequentialAction$whenSize$thenCorrect() { Action.Composite action = (Action.Composite) sequential(nop(), nop(), nop()); assertEquals(3, action.size()); } @Test public void givenSequentialAction$whenDescribe$thenLooksNice() { assertEquals("Sequential (1 actions)", describe(sequential(nop()))); } @Test(timeout = 300000) public void concurrentTest() throws InterruptedException { final List<String> arr = synchronizedList(new ArrayList<String>()); concurrent( simple(new Runnable() { @Override public void run() { arr.add("Hello A"); } }), simple(new Runnable() { @Override public void run() { arr.add("Hello B"); } }) ).accept(new ActionRunner.Impl()); Collections.sort(arr); assertEquals(asList("Hello A", "Hello B"), arr); } @Test(timeout = 300000) public void concurrentTest$checkConcurrency() throws InterruptedException { final List<Map.Entry<Long, Long>> arr = synchronizedList(new ArrayList<Map.Entry<Long, Long>>()); try { concurrent( simple(new Runnable() { @Override public void run() { arr.add(createEntry()); } }), simple(new Runnable() { @Override public void run() { arr.add(createEntry()); } }) ).accept(new ActionRunner.Impl()); } finally { for (Map.Entry<Long, Long> i : arr) { for (Map.Entry<Long, Long> j : arr) { assertTrue(i.getValue() > j.getKey()); } } } } private Map.Entry<Long, Long> createEntry() { long before = currentTimeMillis(); try { TimeUnit.MILLISECONDS.sleep(100); return new AbstractMap.SimpleEntry<>( before, currentTimeMillis() ); } catch (InterruptedException e) { throw propagate(e); } } @Test(timeout = 300000, expected = NullPointerException.class) public void concurrentTest$runtimeExceptionThrown() throws InterruptedException { final List<String> arr = synchronizedList(new ArrayList<String>()); try { concurrent( simple(new Runnable() { @Override public void run() { arr.add("Hello A"); throw new NullPointerException(); } }), simple(new Runnable() { @Override public void run() { arr.add("Hello B"); } }) ).accept(new ActionRunner.Impl()); } finally { Collections.sort(arr); assertEquals(asList("Hello A", "Hello B"), arr); } } @Test(timeout = 300000, expected = Error.class) public void concurrentTest$errorThrown() throws InterruptedException { final List<String> arr = synchronizedList(new ArrayList<String>()); try { concurrent( simple(new Runnable() { @Override public void run() { arr.add("Hello A"); throw new Error(); } }), simple(new Runnable() { @Override public void run() { arr.add("Hello B"); } }) ).accept(new ActionRunner.Impl()); } finally { Collections.sort(arr); assertEquals(asList("Hello A", "Hello B"), arr); } } @Test public void timeoutTest() { final List<String> arr = new ArrayList<>(); timeout(simple(new Runnable() { @Override public void run() { arr.add("Hello"); } }), // 10 msec should be sufficient to finish the action above. 10, MILLISECONDS ).accept(new ActionRunner.Impl()); assertArrayEquals(new Object[] { "Hello" }, arr.toArray()); } @Test public void givenTimeoutAction$whenDescribe$thenLooksNice() { assertEquals("TimeOut (1[milliseconds])", describe(timeout(nop(), 1, MILLISECONDS))); assertEquals("TimeOut (10[seconds])", describe(timeout(nop(), 10000, MILLISECONDS))); assertEquals("TimeOut (1000[days])", describe(timeout(nop(), 1000, DAYS))); } @Test(expected = TimeoutException.class) public void timeoutTest$timeout() throws Throwable { final List<String> arr = new ArrayList<>(); try { timeout( simple(new Runnable() { @Override public void run() { arr.add("Hello"); try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { throw propagate(e); } } }), 1, MICROSECONDS ).accept(new ActionRunner.Impl()); } catch (ActionException e) { throw e.getCause(); } finally { assertArrayEquals(new Object[] { "Hello" }, arr.toArray()); } } @Test(expected = RuntimeException.class, timeout = 300000) public void timeoutTest$throwsRuntimeException() throws Throwable { final List<String> arr = new ArrayList<>(); try { timeout(simple(new Runnable() { @Override public void run() { arr.add("Hello"); throw new RuntimeException(); } }), 1, MILLISECONDS ).accept(new ActionRunner.Impl()); } catch (ActionException e) { throw e.getCause(); } finally { assertArrayEquals(new Object[] { "Hello" }, arr.toArray()); } } @Test(expected = Error.class, timeout = 300000) public void timeoutTest$throwsError() throws Throwable { final List<String> arr = new ArrayList<>(); try { timeout(simple(new Runnable() { @Override public void run() { arr.add("Hello"); throw new Error(); } }), 1, MILLISECONDS ).accept(new ActionRunner.Impl()); } catch (ActionException e) { throw e.getCause(); } finally { assertArrayEquals(new Object[] { "Hello" }, arr.toArray()); } } @Test(timeout = 300000) public void retryTest() { final List<String> arr = new ArrayList<>(); retry(simple(new Runnable() { @Override public void run() { arr.add("Hello"); } }), 0, 1, MILLISECONDS ).accept(new ActionRunner.Impl()); assertArrayEquals(new Object[] { "Hello" }, arr.toArray()); } @Test(timeout = 300000) public void retryTest$failOnce() { final List<String> arr = new ArrayList<>(); try { retry(simple(new Runnable() { int i = 0; @Override public void run() { arr.add("Hello"); if (i < 1) { i++; throw new ActionException("fail"); } } }), 1, 1, MILLISECONDS ).accept(new ActionRunner.Impl()); } finally { assertArrayEquals(new Object[] { "Hello", "Hello" }, arr.toArray()); } } @Test(expected = Abort.class) public void givenRetryAction$whenGiveUpException$thenAborted() { final List<String> arr = new ArrayList<>(); try { retry(simple(new Runnable() { @Override public void run() { throw Abort.abort(); } }), 1, 1, MILLISECONDS ).accept(new ActionRunner.Impl()); } finally { assertEquals(Collections.emptyList(), arr); } } @Test(expected = IOException.class) public void givenRetryAction$whenGiveUpException2$thenAborted() throws Throwable { final List<String> arr = new ArrayList<>(); try { retry(simple(new Runnable() { @Override public void run() { throw Abort.abort(new IOException()); } }), 1, 1, MILLISECONDS ).accept(new ActionRunner.Impl()); } catch (Abort e) { throw e.getCause(); } finally { assertEquals(Collections.emptyList(), arr); } } @Test(expected = ActionException.class, timeout = 300000) public void retryTest$failForever() { final List<String> arr = new ArrayList<>(); try { retry(simple(new Runnable() { @Override public void run() { arr.add("Hello"); throw new ActionException("fail"); } }), 1, 1, MILLISECONDS ).accept(new ActionRunner.Impl()); } finally { assertArrayEquals(new Object[] { "Hello", "Hello" }, arr.toArray()); } } @Test public void givenRetryAction$whenDescribe$thenLooksNice() { assertEquals("Retry(2[seconds]x1times)", describe(retry(nop(), 1, 2, SECONDS))); } @Test(timeout = 300000) public void forEachTest() { final List<String> arr = new ArrayList<>(); forEach( asList("1", "2"), new Sink.Base<String>("print") { @Override public void apply(String input, Object... outer) { arr.add(String.format("Hello %s", input)); } } ).accept(new ActionRunner.Impl()); assertArrayEquals(new Object[] { "Hello 1", "Hello 2" }, arr.toArray()); } @Test public void givenForEachAction$whenDescribe$thenLooksNice() { assertEquals( "ForEach (Concurrent, 2 items) {(noname)}", describe(forEach( asList("hello", "world"), CONCURRENTLY, new Sink.Base<String>() { @Override public void apply(String s, Object... outer) { } } )) ); } @Test public void givenForEachActionViaNonCollection$whenDescribe$thenLooksNice() { assertEquals( "ForEach (Sequential, ? items) {empty!}", describe(forEach( new Iterable<String>() { @Override public Iterator<String> iterator() { return asList("hello", "world").iterator(); } }, SEQUENTIALLY, new Sink.Base<String>("empty!") { @Override public void apply(String s, Object... outer) { } } )) ); } @Test public void givenForEachCreatedWithoutExplicitMode$whenPerform$thenWorksFine() { final List<String> arr = new ArrayList<>(); forEach( asList("1", "2"), sequential( simple(new Runnable() { @Override public void run() { arr.add("Hello!"); } } ), tag(0) ), new Sink.Base<String>("print") { @Override public void apply(String input, Object... outer) { arr.add(String.format("Hello %s", input)); } } ).accept(new ActionRunner.Impl()); assertArrayEquals(new Object[] { "Hello!", "Hello 1", "Hello!", "Hello 2" }, arr.toArray()); } @Test public void givenWithAction$whenPerformed$thenWorksFine() { final List<String> arr = new ArrayList<>(); with("world", new Sink.Base<String>() { @Override public void apply(String input, Object... outer) { arr.add(String.format("Hello, %s.", input)); arr.add(String.format("%s, bye.", input)); } } ).accept(new ActionRunner.Impl()); assertEquals(asList("Hello, world.", "world, bye."), arr); } /** * Even if too many blocks are given, ActionUnit's normal runner doesn't report * an error. It's left to ActionValidator, which is not yet implemented as of * Aug/12/2016. */ @Test public void givenActionWithInsufficientTags$whenPerformed$thenWorksFine() { with("world", sequential(nop()), new Sink.Base<String>() { @Override public void apply(String input, Object... outer) { } } ).accept(new ActionRunner.Impl()); } @Test(expected = IllegalStateException.class) public void givenActionWithTooManyTags$whenPerformed$thenAppropriateErrorReported() { with("world", sequential(tag(0), tag(1)), new Sink.Base<String>() { @Override public void apply(String input, Object... outer) { } } ).accept(new ActionRunner.Impl()); } @Test public void nopTest() { // Just make sure no error happens Actions.nop().accept(new ActionRunner.Impl()); } @Test(timeout = 300000) public void givenWaitForAction$whenPerform$thenExpectedAmountOfTimeSpent() { // To force JVM load classes used by this test, run the action once for warm-up. waitFor(1, TimeUnit.MILLISECONDS).accept(new ActionRunner.Impl()); // Let's do the test. long before = currentTimeMillis(); waitFor(1, TimeUnit.MILLISECONDS).accept(new ActionRunner.Impl()); //noinspection unchecked assertThat( currentTimeMillis() - before, allOf( greaterThanOrEqualTo(1L), // Depending on unpredictable conditions, such as JVM's internal state, // GC, class loading, etc., "waitFor" action may take a longer time // than 1 msec to perform. In this case I'm giving 3 msec including // grace period. lessThan(3L) ) ); } @Test public void givenAttemptAction$whenExceptionCaught$worksFine() { final List<String> out = new LinkedList<>(); attempt(new Runnable() { @Override public void run() { out.add("try"); throw new ActionException("thrown"); } }).recover(/*you can omit exception class parameter you are going to catch ActionException*/ new Sink<ActionException>() { @Override public void apply(ActionException input, Context context) { out.add("catch"); out.add(input.getMessage()); } }).ensure(new Runnable() { @Override public void run() { out.add("finally"); } }).build().accept(new ActionRunner.Impl()); assertEquals(asList("try", "catch", "thrown", "finally"), out); } @Test(expected = RuntimeException.class) public void givenAttemptAction$whenExceptionNotCaught$worksFine() { final List<String> out = new LinkedList<>(); try { attempt(new Runnable() { @Override public void run() { out.add("try"); throw new RuntimeException("thrown"); } }).recover(NullPointerException.class, new Sink<NullPointerException>() { @Override public void apply(NullPointerException input, Context context) { out.add("catch"); out.add(input.getMessage()); } }).ensure(new Runnable() { @Override public void run() { out.add("finally"); } }).build().accept(new ActionRunner.Impl()); } finally { assertEquals(asList("try", "finally"), out); } } @Test public void givenPipeAction$whenPerformed$thenWorksFine() { with("world", pipe( Connectors.<String>context(), new Function<String, Text>() { @Override public Text apply(String s) { return new Text("hello:" + s); } }, new Sink<Text>() { @Override public void apply(Text input, Context context) { assertEquals("hello:world", input.value()); } })).accept(new ActionRunner.Impl()); } @Test public void givenSimplePipeAction$whenPerformed$thenWorksFine() { final List<Text> out = new LinkedList<>(); forEach(asList("world", "WORLD"), pipe( new Function<String, Text>() { @Override public Text apply(String s) { return new Text("hello:" + s); } }, new Sink<Text>() { @Override public void apply(Text input, Context context) { out.add(input); } } )).accept(new ActionRunner.Impl()); assertArrayEquals( asList("hello:world", "hello:WORLD").toArray(new String[2]), toArray(transform(out, new Function<Text, String>() { @Override public String apply(Text input) { return input.value(); } }), String.class) ); } @Test public void givenSimplestPipeAction$whenPerformed$thenWorksFine() { final List<Text> out = new LinkedList<>(); with("world", pipe( new Function<String, Text>() { @Override public Text apply(String s) { out.add(new Text("hello:" + s)); return out.get(0); } } )).accept(new ActionRunner.Impl()); assertEquals("hello:world", out.get(0).value()); } @Test public void givenTestAction$whenBuiltAndPerformed$thenWorksFine() { } @Test public void givenTestActionWithName$whenBuiltAndPerformed$thenWorksFine() { //noinspection unchecked Actions.<String, String>test() .given("Hello") .when(new Function<String, String>() { @Override public String apply(String input) { return "*" + input + "*"; } }) .then( allOf( containsString("Hello"), not(equalTo("Hello")) )) .build() .accept(new ActionRunner.Impl()); } @Test(expected = ComparisonFailure.class) public void givenPipeAction$whenPerformedAndThrowsException$thenPassesThrough () throws Throwable { with("world", pipe( Connectors.<String>context(), new Function<String, Text>() { @Override public Text apply(String s) { return new Text("Hello:" + s); } }, new Sink<Text>() { @Override public void apply(Text input, Context context) { assertEquals("hello:world", input.value()); } })).accept(new ActionRunner.Impl()); } @Test public void givenPipeActionFromFunction$whenPerformed$thenWorksFine() throws Throwable { final List<String> out = new LinkedList<>(); with("world", pipe( Connectors.<String>context(), new Function<String, Text>() { @Override public Text apply(String s) { return new Text("Hello:" + s); } }, new Sink<Text>() { @Override public void apply(Text input, Context context) { out.add(input.value()); } }, new Sink<Text>() { @Override public void apply(Text input, Context context) { out.add(input.value()); } } )).accept(new ActionRunner.Impl()); assertEquals( asList("Hello:world", "Hello:world"), out ); } @Test(expected = UnsupportedOperationException.class) public void unsupportedActionType$simple() { new Action() { @Override public void accept(Visitor visitor) { visitor.visit(this); } }.accept(new ActionRunner.Impl()); } @Test(expected = UnsupportedOperationException.class) public void unsupportedActionType$composite() { new Action.Composite.Base("unsupported", singletonList(nop())) { @Override public void accept(Visitor visitor) { visitor.visit(this); } }.accept(new ActionRunner.Impl()); } }
package com.petukhovsky.jvaluer.units; import com.petukhovsky.jvaluer.JValuer; import com.petukhovsky.jvaluer.JValuerBuilder; import com.petukhovsky.jvaluer.commons.compiler.CloneCompiler; import com.petukhovsky.jvaluer.commons.compiler.RunnableCompiler; import com.petukhovsky.jvaluer.commons.lang.Language; import com.petukhovsky.jvaluer.commons.lang.Languages; import com.petukhovsky.jvaluer.commons.local.OSRelatedValue; import com.petukhovsky.jvaluer.invoker.CustomInvoker; import com.petukhovsky.jvaluer.lang.LanguagesImpl; import org.junit.Before; import org.junit.Test; import java.nio.file.Paths; import static org.junit.Assert.assertEquals; public class JValuerTest { public JValuer loadJValuer() { return new JValuerBuilder() .addLanguage(new Language("GNU C++", new RunnableCompiler("g++", "{defines} -O2 -o {output} {source}")), new String[]{}, new String[]{"c++", "cpp"}) .addLanguage(new Language("GNU C++11", new RunnableCompiler("g++", "{defines} -O2 -o {output} {source}")), new String[]{"cpp"}, new String[]{"c++11", "cpp11"}) .addLanguage(new Language("Python 3", new CloneCompiler(), new CustomInvoker(new OSRelatedValue<String>() .windows("c:/Programs/Python-3/python.exe").orElse("python3"), "{exe} {args}")), new String[]{"py"}, new String[]{"python", "py", "python3"}) .setPath(Paths.get("/tmp/jvaluer/")) .build(); } @Test public void testLanguages() { Languages languages = loadJValuer().getLanguages(); assertEquals(languages.findByExtension("py").name(), "Python 3"); assertEquals(languages.findByName("c++11").name(), "GNU C++11"); } }
package net.sf.jabref.logic.bibtex; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.List; import net.sf.jabref.logic.importer.Importer; import net.sf.jabref.logic.importer.ParserResult; import net.sf.jabref.logic.importer.fileformat.BibtexParser; import net.sf.jabref.model.entry.BibEntry; import net.sf.jabref.preferences.JabRefPreferences; import org.junit.Assert; public class BibEntryAssert { /** * Reads a single entry from the resource using `getResourceAsStream` from the given class. The resource has to * contain a single entry * * @param clazz the class where to call `getResourceAsStream` * @param resourceName the resource to read * @param entry the entry to compare with */ public static void assertEquals(Class<?> clazz, String resourceName, BibEntry entry) throws IOException { Assert.assertNotNull(clazz); Assert.assertNotNull(resourceName); Assert.assertNotNull(entry); try (InputStream shouldBeIs = clazz.getResourceAsStream(resourceName)) { BibEntryAssert.assertEquals(shouldBeIs, entry); } } /** * Reads a single entry from the resource using `getResourceAsStream` from the given class. The resource has to * contain a single entry * * @param clazz the class where to call `getResourceAsStream` * @param resourceName the resource to read * @param asIsEntries a list containing a single entry to compare with */ public static void assertEquals(Class<?> clazz, String resourceName, List<BibEntry> asIsEntries) throws IOException { Assert.assertNotNull(clazz); Assert.assertNotNull(resourceName); Assert.assertNotNull(asIsEntries); try (InputStream shouldBeIs = clazz.getResourceAsStream(resourceName)) { BibEntryAssert.assertEquals(shouldBeIs, asIsEntries); } } private static List<BibEntry> getListFromInputStream(InputStream is) throws IOException { ParserResult result; try (Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) { BibtexParser parser = new BibtexParser(JabRefPreferences.getInstance().getImportFormatPreferences()); result = parser.parse(reader); } Assert.assertNotNull(result); Assert.assertFalse(result.isNullResult()); return result.getDatabase().getEntries(); } /** * Reads a bibtex database from the given InputStream. The list is compared with the given list. * * @param expectedInputStream the inputStream reading the entry from * @param actualEntries a list containing a single entry to compare with */ public static void assertEquals(InputStream expectedInputStream, List<BibEntry> actualEntries) throws IOException { Assert.assertNotNull(expectedInputStream); Assert.assertNotNull(actualEntries); Assert.assertEquals(getListFromInputStream(expectedInputStream), actualEntries); } public static void assertEquals(List<BibEntry> expectedEntries, InputStream actualInputStream) throws IOException { Assert.assertNotNull(actualInputStream); Assert.assertNotNull(expectedEntries); Assert.assertEquals(expectedEntries, getListFromInputStream(actualInputStream)); } /** * Reads a bibtex database from the given InputStream. The result has to contain a single BibEntry. This entry is * compared to the given entry * * @param expected the inputStream reading the entry from * @param actual the entry to compare with */ public static void assertEquals(InputStream expected, BibEntry actual) throws IOException { assertEquals(expected, Collections.singletonList(actual)); } /** * Compares two InputStreams. For each InputStream a list will be created. expectedIs is read directly, actualIs is filtered through importer to convert to a list of BibEntries. * @param expectedIs A BibtexImporter InputStream. * @param fileToImport The path to the file to be imported. * @param importer The fileformat you want to use to read the passed file to get the list of expected BibEntries * @throws IOException */ public static void assertEquals(InputStream expectedIs, Path fileToImport, Importer importer) throws IOException { assertEquals(getListFromInputStream(expectedIs), fileToImport, importer); } public static void assertEquals(InputStream expectedIs, URL fileToImport, Importer importer) throws URISyntaxException, IOException { assertEquals(expectedIs, Paths.get(fileToImport.toURI()), importer); } /** * Compares a list of BibEntries to an InputStream. actualIs is filtered through importerForActualIs to convert to a list of BibEntries. * @param expected A BibtexImporter InputStream. * @param fileToImport The path to the file to be imported. * @param importer The fileformat you want to use to read the passed file to get the list of expected BibEntries * @throws IOException */ public static void assertEquals(List<BibEntry> expected, Path fileToImport, Importer importer) throws IOException { List<BibEntry> actualEntries = importer.importDatabase(fileToImport, StandardCharsets.UTF_8) .getDatabase().getEntries(); Assert.assertEquals(expected, actualEntries); } public static void assertEquals(List<BibEntry> expected, URL fileToImport, Importer importer) throws URISyntaxException, IOException { assertEquals(expected, Paths.get(fileToImport.toURI()), importer); } }
package net.xprova.netlistgraph; import java.util.ArrayList; import java.util.HashMap; import junit.framework.TestCase; import net.xprova.netlist.GateLibrary; import net.xprova.netlist.Netlist; import net.xprova.netlist.PinConnection; import net.xprova.netlist.PinDirection; import net.xprova.verilogparser.VerilogParser; public class VerilogParserTest extends TestCase { public void testMinimal() throws Exception { ClassLoader classLoader = getClass().getClassLoader(); // prepare test GateLibrary String fullPath1 = classLoader.getResource("simple.lib").getPath(); ArrayList<Netlist> libModules = VerilogParser.parseFile(fullPath1, new GateLibrary()); GateLibrary simpleLib = new GateLibrary(libModules); // build Netlist from test resource file minimal.v String fullPath2 = classLoader.getResource("minimal.v").getPath(); ArrayList<Netlist> netListArr = VerilogParser.parseFile(fullPath2, simpleLib); assertEquals(netListArr.size(), 1); Netlist nl = netListArr.get(0); // test ports assertEquals(nl.ports.size(), 4); assertEquals(nl.ports.get("x").direction, PinDirection.IN); assertEquals(nl.ports.get("clk").direction, PinDirection.IN); assertEquals(nl.ports.get("rst").direction, PinDirection.IN); assertEquals(nl.ports.get("y").direction, PinDirection.OUT); // test modules assertEquals(nl.modules.size(), 1); assertEquals(nl.modules.get("inv1").type, "NOT"); assertEquals(nl.modules.get("inv1").id, "inv1"); // test nets assertEquals(nl.nets.size(), 4); assertEquals(nl.nets.get("clk").id, "clk"); assertEquals(nl.nets.get("rst").id, "rst"); assertEquals(nl.nets.get("x").id, "x"); assertEquals(nl.nets.get("y").id, "y"); // test module connections HashMap<String, PinConnection> inv1Cons = nl.modules.get("inv1").connections; assertEquals(inv1Cons.size() , 2); assertEquals(inv1Cons.get("a").dir, PinDirection.IN); assertEquals(inv1Cons.get("y").dir, PinDirection.OUT); assertEquals(inv1Cons.get("a").net, "x"); assertEquals(inv1Cons.get("y").net, "y"); assertEquals(inv1Cons.get("a").bit, 0); assertEquals(inv1Cons.get("y").bit, 0); // test netlist name assertEquals(nl.name, "main"); } public void testMultibit() throws Exception { ClassLoader classLoader = getClass().getClassLoader(); // prepare test GateLibrary String fullPath1 = classLoader.getResource("simple.lib").getPath(); ArrayList<Netlist> libModules = VerilogParser.parseFile(fullPath1, new GateLibrary()); GateLibrary simpleLib = new GateLibrary(libModules); // build Netlist from test resource file minimal.v String fullPath2 = classLoader.getResource("multibit.v").getPath(); ArrayList<Netlist> netListArr = VerilogParser.parseFile(fullPath2, simpleLib); assertEquals(netListArr.size(), 1); Netlist nl = netListArr.get(0); // test multi-bit port assertEquals(nl.nets.size(), 4); assertEquals(nl.nets.get("count").start, 3); assertEquals(nl.nets.get("count").end, 0); assertEquals(nl.nets.get("count").getCount(), 4); assertEquals(nl.nets.get("count").getHigher(), 3); assertEquals(nl.nets.get("count").getLower(), 0); } public void testPortOrder() throws Exception { // library: String LIB_STR = "module NOT (y, a); input a; output y; endmodule"; // should parse correctly: ArrayList<String> LIB_OK = new ArrayList<String>(); LIB_OK.add("module top (a, y); input a; output y; NOT u1 (y, a); endmodule"); LIB_OK.add("module top (a, y); input a; output y; NOT u1 (.y(y), .a(a)); endmodule"); LIB_OK.add("module top (a, y); input a; output y; NOT u1 (.a(a), .y(y)); endmodule"); // should raise a ConnectivityException ArrayList<String> LIB_PROB = new ArrayList<String>(); LIB_PROB.add("module top (a, y); input a; output y; NOT u1 (a, y); endmodule"); LIB_PROB.add("module top (a, y); input a; output y; NOT u1 (.y(a), .a(y)); endmodule"); LIB_PROB.add("module top (a, y); input a; output y; NOT u1 (.a(y), .y(a)); endmodule"); // test code GateLibrary lib = new GateLibrary(VerilogParser.parseString(LIB_STR)); for (String str : LIB_OK) { // this should execute without throwing any exceptions new NetlistGraph(VerilogParser.parseString(str, lib).get(0)); } for (String str : LIB_PROB) { // this should throw a ConnectivityException try { new NetlistGraph(VerilogParser.parseString(str, lib).get(0)); fail("parser did not throw an expected ConnectivityException"); } catch (ConnectivityException e) { // exception caught; test passed } } } public void testEscapedIdentifiers() throws Exception { String str = "module \\top():: (\\a) ); input \\a) ; wire \\hello;; ; NOT u1 (\\hello;; , \\a) ); endmodule "; ClassLoader classLoader = getClass().getClassLoader(); // prepare test GateLibrary String fullPath1 = classLoader.getResource("simple.lib").getPath(); ArrayList<Netlist> libModules = VerilogParser.parseFile(fullPath1, new GateLibrary()); GateLibrary simpleLib = new GateLibrary(libModules); Netlist nl = VerilogParser.parseString(str, simpleLib).get(0); assertEquals(nl.name, "\\top()::"); } }
package nl.pvanassen.ns.handle; import static org.junit.Assert.*; import nl.pvanassen.ns.model.stations.Station; import nl.pvanassen.ns.model.stations.Stations; import nl.pvanassen.ns.model.stations.StationsHandle; import org.junit.Test; public class StationsHandleTest { @Test public void testGetModel() { StationsHandle handle = new StationsHandle(); Stations stations = handle.getModel(getClass().getResourceAsStream("/stations.xml")); assertNotNull(stations); assertNotNull(stations.getStations()); assertNotEquals(0, stations.getStations().size()); Station stationDenBosch = stations.getStations().get(0); assertNotNull(stationDenBosch.getNamen()); assertEquals("H'bosch", stationDenBosch.getNamen().getKort()); assertEquals("'s-Hertogenbosch", stationDenBosch.getNamen().getMiddel()); assertEquals("'s-Hertogenbosch", stationDenBosch.getNamen().getLang()); assertEquals("NL", stationDenBosch.getLand()); assertEquals(8400319, stationDenBosch.getUicCode()); assertEquals(51.69048d, stationDenBosch.getLat(), Double.MIN_VALUE); assertEquals(5.29362d, stationDenBosch.getLon(), Double.MIN_VALUE); assertEquals(2, stationDenBosch.getSynoniemen().size()); assertEquals("Hertogenbosch ('s)", stationDenBosch.getSynoniemen().get(0)); assertEquals("Den Bosch", stationDenBosch.getSynoniemen().get(1)); } }
package org.mariadb.jdbc; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.sun.jna.Platform; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.junit.Assert; import org.junit.Assume; import org.junit.Before; import org.junit.Test; public class Sha256AuthenticationTest extends BaseTest { private String serverPublicKey; private String forceTls = ""; /** * Check requirement. * * @throws SQLException exception exception */ @Before public void checkSsl() throws SQLException { Assume.assumeTrue(!isMariadbServer() && minVersion(5, 7)); serverPublicKey = System.getProperty("serverPublicKey"); Statement stmt = sharedConnection.createStatement(); try { stmt.execute("DROP USER 'sha256User'@'%'"); } catch (SQLException e) { // eat } try { stmt.execute("DROP USER 'cachingSha256User'@'%'"); } catch (SQLException e) { // eat } if (minVersion(8, 0, 0)) { stmt.execute( "CREATE USER 'sha256User'@'%' IDENTIFIED WITH sha256_password BY 'password'"); stmt.execute( "GRANT ALL PRIVILEGES ON *.* TO 'sha256User'@'%'"); } else { stmt.execute("CREATE USER 'sha256User'@'%'"); stmt.execute( "GRANT ALL PRIVILEGES ON *.* TO 'sha256User'@'%' IDENTIFIED WITH " + "sha256_password BY 'password'"); } if (minVersion(8, 0, 0)) { stmt.execute( "CREATE USER 'cachingSha256User'@'%' IDENTIFIED WITH caching_sha2_password BY 'password'"); stmt.execute( "GRANT ALL PRIVILEGES ON *.* TO 'cachingSha256User'@'%'"); } else { forceTls = "&enabledSslProtocolSuites=TLSv1.1"; } } @Test public void sha256PluginTestWithServerRsaKey() throws SQLException { Assume.assumeNotNull(serverPublicKey); Assume.assumeTrue(!Platform.isWindows() && minVersion(8, 0, 0)); try (Connection conn = DriverManager.getConnection( "jdbc:mariadb: + ((hostname == null) ? "localhost" : hostname) + ":" + port + "/" + ((database == null) ? "" : database) + "?user=sha256User&password=password&serverRsaPublicKeyFile=" + serverPublicKey)) { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT '5'"); Assert.assertTrue(rs.next()); Assert.assertEquals("5", rs.getString(1)); } } @Test public void sha256PluginTestWithoutServerRsaKey() throws SQLException { Assume.assumeTrue(!Platform.isWindows() && minVersion(8, 0, 0)); try (Connection conn = DriverManager.getConnection( "jdbc:mariadb: + ((hostname == null) ? "localhost" : hostname) + ":" + port + "/" + ((database == null) ? "" : database) + "?user=sha256User&password=password&allowPublicKeyRetrieval")) { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT '5'"); Assert.assertTrue(rs.next()); Assert.assertEquals("5", rs.getString(1)); } } @Test public void sha256PluginTestException() { try { DriverManager.getConnection( "jdbc:mariadb: + ((hostname == null) ? "localhost" : hostname) + ":" + port + "/" + ((database == null) ? "" : database) + "?user=sha256User&password=password"); fail("must have throw exception"); } catch (SQLException sqle) { assertTrue(sqle.getMessage().contains("RSA public key is not available client side")); } } @Test public void sha256PluginTestSsl() throws SQLException { Assume.assumeTrue(haveSsl(sharedConnection)); try (Connection conn = DriverManager.getConnection( "jdbc:mariadb: + ((hostname == null) ? "localhost" : hostname) + ":" + port + "/" + ((database == null) ? "" : database) + "?user=sha256User&password=password&useSsl&trustServerCertificate" + forceTls)) { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT '5'"); Assert.assertTrue(rs.next()); Assert.assertEquals("5", rs.getString(1)); } } @Test public void cachingSha256PluginTestWithServerRsaKey() throws SQLException { Assume.assumeNotNull(serverPublicKey); Assume.assumeTrue(minVersion(8, 0, 0)); try (Connection conn = DriverManager.getConnection( "jdbc:mariadb: + ((hostname == null) ? "localhost" : hostname) + ":" + port + "/" + ((database == null) ? "" : database) + "?user=cachingSha256User&password=password&serverRsaPublicKeyFile=" + serverPublicKey)) { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT '5'"); Assert.assertTrue(rs.next()); Assert.assertEquals("5", rs.getString(1)); } } @Test public void cachingSha256PluginTestWithoutServerRsaKey() throws SQLException { Assume.assumeTrue(minVersion(8, 0, 0)); try (Connection conn = DriverManager.getConnection( "jdbc:mariadb: + ((hostname == null) ? "localhost" : hostname) + ":" + port + "/" + ((database == null) ? "" : database) + "?user=cachingSha256User&password=password&allowPublicKeyRetrieval")) { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT '5'"); Assert.assertTrue(rs.next()); Assert.assertEquals("5", rs.getString(1)); } } @Test public void cachingSha256PluginTestException() { Assume.assumeTrue(minVersion(8, 0, 0)); try { DriverManager.getConnection( "jdbc:mariadb: + ((hostname == null) ? "localhost" : hostname) + ":" + port + "/" + ((database == null) ? "" : database) + "?user=cachingSha256User&password=password"); fail("must have throw exception"); } catch (SQLException sqle) { assertTrue(sqle.getMessage().contains("RSA public key is not available client side")); } } @Test public void cachingSha256PluginTestSsl() throws SQLException { Assume.assumeTrue(haveSsl(sharedConnection)); Assume.assumeTrue(minVersion(8, 0, 0)); try (Connection conn = DriverManager.getConnection( "jdbc:mariadb: + ((hostname == null) ? "localhost" : hostname) + ":" + port + "/" + ((database == null) ? "" : database) + "?user=cachingSha256User&password=password&useSsl&trustServerCertificate=true")) { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT '5'"); Assert.assertTrue(rs.next()); Assert.assertEquals("5", rs.getString(1)); } } }
package org.wrml.util; import org.junit.Test; import org.mockito.Matchers; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.util.Map; import static org.mockito.Mockito.*; public class DelegatingObservableMapTest { @Test public void shouldFireClearedEvent() { ObservableMap<String, Integer> observableMap = new DelegatingObservableMap<String, Integer>(mock(Map.class)); MapEventListener<String, Integer> listener = mock(MapEventListener.class); observableMap.addEventListener(listener); observableMap.clear(); verify(listener).clearing(Matchers.<MapEvent<String, Integer>>any()); verify(listener).cleared(Matchers.<MapEvent<String, Integer>>any()); verifyNoMoreInteractions(listener); } @Test public void shouldCancelPut() { final Map backingMap = mock(Map.class); ObservableMap<String, Integer> observableMap = new DelegatingObservableMap<String, Integer>(backingMap); MapEventListener<String, Integer> listener = mock(MapEventListener.class); // Cancel the event during a call to listener.updatingEntry(...) doAnswer(new Answer() { public Object answer(InvocationOnMock invocationOnMock) throws Throwable { MapEvent<String, Integer> event = (MapEvent<String, Integer>) invocationOnMock.getArguments()[0]; event.setCancelled(true); return null; } }).when(listener).updatingEntry(Matchers.<MapEvent<String, Integer>>any()); observableMap.addEventListener(listener); observableMap.put("test", 123); verify(listener).updatingEntry(Matchers.<MapEvent<String, Integer>>any()); verifyNoMoreInteractions(listener); verify(backingMap, times(0)).put(any(), any()); } }
package us.kbase.narrativejobservice.subjobs; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.net.SocketException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import us.kbase.common.service.JacksonTupleModule; import us.kbase.common.service.JsonClientException; import us.kbase.common.service.JsonServerMethod; import us.kbase.common.service.JsonServerServlet; import us.kbase.common.service.JsonServerSyslog; import us.kbase.common.service.RpcContext; import us.kbase.common.service.UObject; import us.kbase.common.utils.ModuleMethod; import us.kbase.common.utils.NetUtils; import us.kbase.narrativejobservice.DockerRunner; import us.kbase.narrativejobservice.RunJobParams; import us.kbase.workspace.ProvenanceAction; import us.kbase.workspace.SubAction; public class CallbackServer extends JsonServerServlet { //TODO identical (or close to it) to kb_sdk call back server. // should probably go in java_common or make a common repo for shared // NJSW & KB_SDK code, since they're tightly coupled private static final long serialVersionUID = 1L; private static final int MAX_JOBS = 10; private final File mainJobDir; private final int callbackPort; private final Map<String, String> config; private final DockerRunner.LineLogger logger; private final ProvenanceAction prov = new ProvenanceAction(); private final static DateTimeFormatter DATE_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ").withZoneUTC(); // IMPORTANT: don't access outside synchronized block private final Map<String, ModuleRunVersion> vers = Collections.synchronizedMap( new LinkedHashMap<String, ModuleRunVersion>()); private final ExecutorService executor = Executors.newCachedThreadPool(); private final Map<UUID, FutureTask<Map<String, Object>>> runningJobs = new HashMap<UUID, FutureTask<Map<String, Object>>>(); private final Cache<UUID, FutureTask<Map<String, Object>>> resultsCache = CacheBuilder.newBuilder() .maximumSize(1000) .expireAfterWrite(10, TimeUnit.MINUTES) .build(); public CallbackServer( final File mainJobDir, final int callbackPort, final Map<String, String> config, final DockerRunner.LineLogger logger, final ModuleRunVersion runver, final RunJobParams job) { super("CallbackServer"); this.mainJobDir = mainJobDir; this.callbackPort = callbackPort; this.config = config; this.logger = logger; vers.put(runver.getModuleMethod().getModule(), runver); prov.setTime(DATE_FORMATTER.print(new DateTime())); prov.setService(runver.getModuleMethod().getModule()); prov.setMethod(runver.getModuleMethod().getMethod()); prov.setDescription( "KBase SDK method run via the KBase Execution Engine"); prov.setMethodParams(job.getParams()); prov.setInputWsObjects(job.getSourceWsObjects()); prov.setServiceVer(runver.getVersionAndRelease()); initSilentJettyLogger(); } @JsonServerMethod(rpc = "CallbackServer.get_provenance") public List<ProvenanceAction> getProvenance() throws IOException, JsonClientException { /* Would be more efficient if provenance was updated online although I can't imagine this making a difference compared to serialization / transport */ final List<SubAction> sas = new LinkedList<SubAction>(); for (final ModuleRunVersion mrv: vers.values()) { sas.add(new SubAction() .withCodeUrl(mrv.getGitURL().toExternalForm()) .withCommit(mrv.getGitHash()) .withName(mrv.getModuleMethod().getModuleDotMethod()) .withVer(mrv.getVersionAndRelease())); } return new LinkedList<ProvenanceAction>(Arrays.asList( new ProvenanceAction() .withSubactions(sas) .withTime(prov.getTime()) .withService(prov.getService()) .withMethod(prov.getMethod()) .withDescription(prov.getDescription()) .withMethodParams(prov.getMethodParams()) .withInputWsObjects(prov.getInputWsObjects()) .withServiceVer(prov.getServiceVer()) )); } @JsonServerMethod(rpc = "CallbackServer.status") public UObject status() throws IOException, JsonClientException { Map<String, Object> data = new LinkedHashMap<String, Object>(); data.put("state", "OK"); return new UObject(data); } private static void cbLog(String log) { System.out.println((System.currentTimeMillis() / 1000.0) + " - CallbackServer: " + log); } protected void processRpcCall(RpcCallData rpcCallData, String token, JsonServerSyslog.RpcInfo info, String requestHeaderXForwardedFor, ResponseStatusSetter response, OutputStream output, boolean commandLine) { cbLog("In processRpcCall"); if (rpcCallData.getMethod().startsWith("CallbackServer.")) { super.processRpcCall(rpcCallData, token, info, requestHeaderXForwardedFor, response, output, commandLine); } else { String errorMessage = null; Map<String, Object> jsonRpcResponse = null; try { jsonRpcResponse = handleCall(rpcCallData); } catch (Exception ex) { ex.printStackTrace(); errorMessage = ex.getMessage(); } try { if (jsonRpcResponse == null) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); if (errorMessage == null) errorMessage = "Unknown server error"; Map<String, Object> error = new LinkedHashMap<String, Object>(); error.put("name", "JSONRPCError"); error.put("code", -32601); error.put("message", errorMessage); error.put("error", errorMessage); jsonRpcResponse = new LinkedHashMap<String, Object>(); jsonRpcResponse.put("version", "1.1"); jsonRpcResponse.put("error", error); } else { if (jsonRpcResponse.containsKey("error")) response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } final ObjectMapper mapper = new ObjectMapper().registerModule( new JacksonTupleModule()); mapper.writeValue(new UnclosableOutputStream(output), jsonRpcResponse); } catch (Exception ex) { ex.printStackTrace(); } } } private Map<String, Object> handleCall( final RpcCallData rpcCallData) throws IOException, JsonClientException, InterruptedException { final ModuleMethod modmeth = new ModuleMethod( rpcCallData.getMethod()); final Map<String, Object> jsonRpcResponse; if (modmeth.isCheck()) { jsonRpcResponse = runCheck(rpcCallData); } else { final UUID jobId = UUID.randomUUID(); cbLog(String.format("Subjob method: %s ID: %s", modmeth.getModuleDotMethod(), jobId)); final SubsequentCallRunner runner = getJobRunner( jobId, rpcCallData.getContext(), modmeth); // update method name to get rid of suffixes rpcCallData.setMethod(modmeth.getModuleDotMethod()); if (modmeth.isStandard()) { cbLog(String.format( "Warning: the callback server recieved a " + "request to synchronously run the method " + "%s. The callback server will block until " + "the method is completed.", modmeth.getModuleDotMethod())); // Run method in local docker container jsonRpcResponse = runner.run(rpcCallData); } else { final FutureTask<Map<String, Object>> task = new FutureTask<Map<String, Object>>( new SubsequentCallRunnerRunner( runner, rpcCallData)); synchronized(this) { if (runningJobs.size() >= MAX_JOBS) { throw new IllegalStateException(String.format( "No more than %s concurrent methods " + "are allowed", MAX_JOBS)); } executor.execute(task); runningJobs.put(jobId,task); } jsonRpcResponse = new HashMap<String, Object>(); jsonRpcResponse.put("version", "1.1"); jsonRpcResponse.put("id", rpcCallData.getId()); jsonRpcResponse.put("result", Arrays.asList(jobId)); } } return jsonRpcResponse; } private Map<String, Object> runCheck(final RpcCallData rpcCallData) throws InterruptedException, IOException { if (rpcCallData.getParams().size() != 1) { throw new IllegalArgumentException( "Check methods take exactly one argument"); } final UUID jobId = UUID.fromString(rpcCallData.getParams().get(0) .asClassInstance(String.class)); boolean finished = true; final FutureTask<Map<String, Object>> task; synchronized (this) { if (runningJobs.containsKey(jobId)) { if (runningJobs.get(jobId).isDone()) { task = runningJobs.get(jobId); resultsCache.put(jobId, task); runningJobs.remove(jobId); } else { finished = false; task = null; } } else { task = resultsCache.getIfPresent(jobId); } } final Map<String, Object> resp; if (finished) { if (task == null) { throw new IllegalStateException( "Either there is no job with id " + jobId + "or it has expired from the cache"); } resp = getResults(task); } else { resp = new HashMap<String, Object>(); resp.put("version", "1.1"); resp.put("id", rpcCallData.getId()); } final Map<String, Object> result = new HashMap<String, Object>(); result.put("finished", finished ? 1 : 0); if (resp.containsKey("result")) { // otherwise an error occurred result.put("result", resp.get("result")); } resp.put("result", result); return resp; } private Map<String, Object> getResults( final FutureTask<Map<String, Object>> task) throws InterruptedException, IOException { try { return task.get(); } catch (ExecutionException ee) { final Throwable cause = ee.getCause(); if (cause instanceof InterruptedException) { throw (InterruptedException) cause; } else if (cause instanceof IOException) { throw (IOException) cause; } else if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else { throw (Error) cause; } } } private static class SubsequentCallRunnerRunner implements Callable<Map<String, Object>> { private final SubsequentCallRunner scr; private final RpcCallData rpc; public SubsequentCallRunnerRunner( final SubsequentCallRunner scr, final RpcCallData rpcData) { this.scr = scr; this.rpc = rpcData; } @Override public Map<String, Object> call() throws Exception { return scr.run(rpc); } } private SubsequentCallRunner getJobRunner( final UUID jobId, final RpcContext rpcContext, final ModuleMethod modmeth) throws IOException, JsonClientException { final SubsequentCallRunner runner; synchronized(this) { final String serviceVer; if (vers.containsKey(modmeth.getModule())) { final ModuleRunVersion v = vers.get(modmeth.getModule()); serviceVer = v.getGitHash(); cbLog(String.format( "Warning: Module %s was already used once " + "for this job. Using cached " + "version:\n" + "url: %s\n" + "commit: %s\n" + "version: %s\n" + "release: %s\n", modmeth.getModule(), v.getGitURL(), v.getGitHash(), v.getVersion(), v.getRelease())); } else { serviceVer = rpcContext == null ? null : (String)rpcContext.getAdditionalProperties() .get("service_ver"); } // Request docker image name from Catalog runner = new SubsequentCallRunner( jobId, mainJobDir, modmeth, serviceVer, callbackPort, config, logger); if (!vers.containsKey(modmeth.getModule())) { vers.put(modmeth.getModule(), runner.getModuleRunVersion()); } } return runner; } public static String getCallbackUrl(int callbackPort) throws SocketException { List<String> hostIps = NetUtils.findNetworkAddresses("docker0", "vboxnet0"); String hostIp = null; if (hostIps.isEmpty()) { cbLog("WARNING! No Docker host IP addresses was found. Subsequent local calls are not supported in test mode."); } else { hostIp = hostIps.get(0); if (hostIps.size() > 1) { cbLog("WARNING! Several Docker host IP addresses are detected, first one is used: " + hostIp); } else { cbLog("Docker host IP address is detected: " + hostIp); } } String callbackUrl = hostIp == null ? "" : ("http://" + hostIp + ":" + callbackPort); return callbackUrl; } public static void initSilentJettyLogger() { Log.setLog(new Logger() { @Override public void warn(String arg0, Object arg1, Object arg2) {} @Override public void warn(String arg0, Throwable arg1) {} @Override public void warn(String arg0) {} @Override public void setDebugEnabled(boolean arg0) {} @Override public boolean isDebugEnabled() { return false; } @Override public void info(String arg0, Object arg1, Object arg2) {} @Override public void info(String arg0) {} @Override public String getName() { return null; } @Override public Logger getLogger(String arg0) { return this; } @Override public void debug(String arg0, Object arg1, Object arg2) {} @Override public void debug(String arg0, Throwable arg1) {} @Override public void debug(String arg0) {} }); } private static class UnclosableOutputStream extends OutputStream { OutputStream inner; boolean isClosed = false; public UnclosableOutputStream(OutputStream inner) { this.inner = inner; } @Override public void write(int b) throws IOException { if (isClosed) return; inner.write(b); } @Override public void close() throws IOException { isClosed = true; } @Override public void flush() throws IOException { inner.flush(); } @Override public void write(byte[] b) throws IOException { if (isClosed) return; inner.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { if (isClosed) return; inner.write(b, off, len); } } }
// SlimPlotter.java package loci.apps.slim; import jaolho.data.lma.LMA; import jaolho.data.lma.LMAFunction; import jaolho.data.lma.implementations.JAMAMatrix; import java.awt.*; import java.awt.datatransfer.*; import java.awt.event.*; import java.io.*; import java.rmi.RemoteException; import java.util.*; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.border.TitledBorder; import javax.swing.event.*; import javax.swing.text.Document; import loci.formats.in.SDTInfo; import loci.formats.in.SDTReader; import loci.formats.DataTools; import loci.formats.gui.ExtensionFileFilter; import loci.visbio.util.BreakawayPanel; import loci.visbio.util.ColorUtil; import loci.visbio.util.OutputConsole; import visad.*; import visad.bom.CurveManipulationRendererJ3D; import visad.java3d.*; import visad.util.ColorMapWidget; import visad.util.Util; public class SlimPlotter implements ActionListener, ChangeListener, DisplayListener, DocumentListener, Runnable, WindowListener { // -- Constants -- /** Names for preset color look-up table. */ public static final String[] LUT_NAMES = { "Grayscale", "HSV", "RGB", null, "Red", "Green", "Blue", null, "Cyan", "Magenta", "Yellow", null, "Fire", "Ice" }; /** Preset color look-up tables. */ public static final float[][][] LUTS = { ColorUtil.LUT_GRAY, ColorUtil.LUT_HSV, ColorUtil.LUT_RGB, null, ColorUtil.LUT_RED, ColorUtil.LUT_GREEN, ColorUtil.LUT_BLUE, null, ColorUtil.LUT_CYAN, ColorUtil.LUT_MAGENTA, ColorUtil.LUT_YELLOW, null, ColorUtil.LUT_FIRE, ColorUtil.LUT_ICE }; /** Default orientation for 3D decay curves display. */ private static final double[] MATRIX_3D = { 0.2821, 0.1503, -0.0201, 0.0418, -0.0500, 0.1323, 0.2871, 0.1198, 0.1430, -0.2501, 0.1408, 0.0089, 0.0000, 0.0000, 0.0000, 1.0000 }; /** Default orientation for 2D decay curve display. */ private static final double[] MATRIX_2D = { 0.400, 0.000, 0.000, 0.160, 0.000, 0.400, 0.000, 0.067, 0.000, 0.000, 0.400, 0.000, 0.000, 0.000, 0.000, 1.000 }; private static final char TAU = 'T'; // log base 10, for now private static final float BASE = 10; private static final float BASE_LOG = (float) Math.log(BASE); // -- Fields -- /** Actual data values, dimensioned [channel][row][column][bin]. */ private int[][][][] values; /** Current binned data values, dimensioned [channels * timeBins]. */ private float[] samps; // data parameters private int width, height; private int channels, timeBins; private float timeRange; private int minWave, waveStep, maxWave; private boolean adjustPeaks, computeFWHMs, cutEnd; private boolean[] cVisible; private int maxPeak; private int[] maxIntensity; // ROI parameters private float[][] roiGrid; private boolean[][] roiMask; private UnionSet curveSet; private Irregular2DSet roiSet; private DataReferenceImpl roiRef; private int roiX, roiY; private int roiCount; private double roiPercent; private float maxVal; private float tauMin, tauMax; // fit parameters private float[][] tau; // system clipboard helper private TextTransfer clip = new TextTransfer(); // menu items private JMenuItem menuFileExit; private JMenuItem menuViewSaveProj; private JMenuItem menuViewLoadProj; // GUI components for parameter dialog box private JDialog paramDialog; private JTextField wField, hField, tField, cField, trField, wlField, sField; private JCheckBox peaksBox, fwhmBox, cutBox; // GUI components for intensity pane private JSlider cSlider; private JLabel minLabel, maxLabel; private JSlider minSlider, maxSlider; private JCheckBox cToggle; // GUI components for decay pane private JLabel decayLabel; private ColorMapWidget colorWidget; private JCheckBox cOverride; private JTextField cMinValue, cMaxValue; private JButton lutLoad, lutSave, lutPresets; private JPopupMenu lutsMenu; private JFileChooser lutBox; private JRadioButton linear, log; private JRadioButton perspective, parallel; private JRadioButton dataSurface, dataLines; private JRadioButton fitSurface, fitLines; private JRadioButton resSurface, resLines; private JRadioButton colorHeight, colorTau; private JSpinner numCurves; private JCheckBox showData, showScale; private JCheckBox showBox, showLine; private JCheckBox showFit, showResiduals; private JCheckBox showFWHMs; private JCheckBox zOverride; private JTextField zScaleValue; private JButton exportData; // other GUI components private JFrame masterWindow; private OutputConsole console; // VisAD objects private Unit[] bcUnits; private RealType bType, cType; private RealTupleType bc, bv, bcv; private FunctionType bcvFunc, bcvFuncFit, bcvFuncRes; private ScalarMap zMap, zMapFit, zMapRes, vMap, vMapFit, vMapRes; private DataRenderer decayRend, fitRend, resRend, lineRend, fwhmRend; private DataReferenceImpl decayRef, fwhmRef, fitRef, resRef; private DisplayImpl iPlot, decayPlot; private ScalarMap intensityMap; private AnimationControl ac; // -- Constructor -- public SlimPlotter(String[] args) throws Exception { console = new OutputConsole("Log"); System.setErr(new ConsoleStream(new PrintStream(console))); console.getTextArea().setColumns(54); console.getTextArea().setRows(10); // progress estimate: // * Reading data - 70% // * Creating types - 1% // * Building displays - 7% // * Constructing images - 14% // * Adjusting peaks - 4% // * Creating plots - 4% ProgressMonitor progress = new ProgressMonitor(null, "Launching Slim Plotter", "Initializing", 0, 1000); progress.setMillisToPopup(0); progress.setMillisToDecideToPopup(0); int maxChan = -1; try { // check for required libraries try { Class.forName("javax.vecmath.Point3d"); } catch (Throwable t) { String os = System.getProperty("os.name").toLowerCase(); String url = null; if (os.indexOf("windows") >= 0 || os.indexOf("linux") >= 0 || os.indexOf("solaris") >= 0) { url = "https://java3d.dev.java.net/binary-builds.html"; } else if (os.indexOf("mac os x") >= 0) { url = "http: "java3dandjavaadvancedimagingupdate.html"; } else if (os.indexOf("aix") >= 0) { url = "http://www-128.ibm.com/developerworks/java/jdk/aix/index.html"; } else if (os.indexOf("hp-ux") >= 0) { url = "http: "downloads/index.html"; } else if (os.indexOf("irix") >= 0) { url = "http: } JOptionPane.showMessageDialog(null, "Slim Plotter requires Java3D, but it was not found." + (url == null ? "" : ("\nPlease install it from:\n" + url)), "Slim Plotter", JOptionPane.ERROR_MESSAGE); System.exit(3); } // parse command line arguments String filename = null; File file = null; if (args == null || args.length < 1) { JFileChooser jc = new JFileChooser(System.getProperty("user.dir")); jc.addChoosableFileFilter(new ExtensionFileFilter("sdt", "Becker & Hickl SPC-Image SDT")); int rval = jc.showOpenDialog(null); if (rval != JFileChooser.APPROVE_OPTION) { System.out.println("Please specify an SDT file."); System.exit(1); } file = jc.getSelectedFile(); filename = file.getPath(); } else { filename = args[0]; file = new File(filename); } if (!file.exists()) { System.out.println("File does not exist: " + filename); System.exit(2); } // read SDT file header SDTReader reader = new SDTReader(); reader.setId(file.getPath()); SDTInfo info = reader.getInfo(); reader.close(); int offset = info.dataBlockOffs + 22; width = info.width; height = info.height; timeBins = info.timeBins; channels = info.channels; timeRange = 12.5f; minWave = 400; waveStep = 10; // show dialog confirming data parameters paramDialog = new JDialog((Frame) null, "Slim Plotter", true); JPanel paramPane = new JPanel(); paramPane.setBorder(new EmptyBorder(10, 10, 10, 10)); paramDialog.setContentPane(paramPane); paramPane.setLayout(new GridLayout(12, 3)); wField = addRow(paramPane, "Image width", width, "pixels"); hField = addRow(paramPane, "Image height", height, "pixels"); tField = addRow(paramPane, "Time bins", timeBins, ""); cField = addRow(paramPane, "Channel count", channels, ""); trField = addRow(paramPane, "Time range", timeRange, "nanoseconds"); wlField = addRow(paramPane, "Starting wavelength", minWave, "nanometers"); sField = addRow(paramPane, "Channel width", waveStep, "nanometers"); JButton ok = new JButton("OK"); paramDialog.getRootPane().setDefaultButton(ok); ok.addActionListener(this); // row 8 peaksBox = new JCheckBox("Align peaks", true); peaksBox.setToolTipText("<html>Computes the peak of each spectral " + "channel, and aligns those peaks <br>to match by adjusting the " + "lifetime histograms. This option corrects<br>for skew across " + "channels caused by the multispectral detector's<br>variable system " + "response time between channels. This option must<br>be enabled to " + "perform exponential curve fitting.</html>"); paramPane.add(peaksBox); paramPane.add(new JLabel()); paramPane.add(new JLabel()); // row 9 fwhmBox = new JCheckBox("Compute FWHMs", false); fwhmBox.setToolTipText( "<html>Computes the full width half max at each channel.</html>"); paramPane.add(fwhmBox); paramPane.add(new JLabel()); paramPane.add(new JLabel()); // row 10 cutBox = new JCheckBox("Cut 1.5ns from fit", true); cutBox.setToolTipText("<html>When performing exponential curve " + "fitting, excludes the last 1.5 ns<br>from the computation. This " + "option is useful because the end of the <br>the lifetime histogram " + "sometimes drops off unexpectedly, skewing<br>the fit results.</html>"); paramPane.add(cutBox); paramPane.add(new JLabel()); paramPane.add(new JLabel()); // row 11 paramPane.add(new JLabel()); paramPane.add(new JLabel()); paramPane.add(new JLabel()); // row 12 paramPane.add(new JLabel()); paramPane.add(ok); paramDialog.pack(); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension ps = paramDialog.getSize(); paramDialog.setLocation((screenSize.width - ps.width) / 2, (screenSize.height - ps.height) / 2); paramDialog.setVisible(true); if (cVisible == null) System.exit(0); // dialog canceled (closed with X) maxWave = minWave + (channels - 1) * waveStep; roiCount = width * height; roiPercent = 100; // pop up progress monitor setProgress(progress, 1); // estimate: 0.1% if (progress.isCanceled()) System.exit(0); // read pixel data progress.setNote("Reading data"); DataInputStream fin = new DataInputStream(new FileInputStream(file)); fin.skipBytes(offset); // skip to data byte[] data = new byte[2 * channels * height * width * timeBins]; int blockSize = 65536; for (int off=0; off<data.length; off+=blockSize) { int len = data.length - off; if (len > blockSize) len = blockSize; fin.readFully(data, off, len); setProgress(progress, (int) (700L * (off + blockSize) / data.length)); // estimate: 0% -> 70% if (progress.isCanceled()) System.exit(0); } fin.close(); // create types progress.setNote("Creating types"); RealType xType = RealType.getRealType("element"); RealType yType = RealType.getRealType("line"); ScaledUnit ns = new ScaledUnit(1e-9, SI.second, "ns"); ScaledUnit nm = new ScaledUnit(1e-9, SI.meter, "nm"); bcUnits = new Unit[] {ns, nm}; bType = RealType.getRealType("bin", ns); cType = RealType.getRealType("channel", nm); RealType vType = RealType.getRealType("count"); RealTupleType xy = new RealTupleType(xType, yType); FunctionType xyvFunc = new FunctionType(xy, vType); Integer2DSet xySet = new Integer2DSet(xy, width, height); FunctionType cxyvFunc = new FunctionType(cType, xyvFunc); Linear1DSet cSet = new Linear1DSet(cType, minWave, maxWave, channels, null, new Unit[] {nm}, null); bc = new RealTupleType(bType, cType); bv = new RealTupleType(bType, vType); bcv = new RealTupleType(bType, cType, vType); RealType vType2 = RealType.getRealType("value"); RealTupleType vv = new RealTupleType(vType, vType2); bcvFunc = new FunctionType(bc, vv); RealType vTypeFit = RealType.getRealType("value_fit"); bcvFuncFit = new FunctionType(bc, vTypeFit); RealType vTypeRes = RealType.getRealType("value_res"); bcvFuncRes = new FunctionType(bc, vTypeRes); setProgress(progress, 710); // estimate: 71% if (progress.isCanceled()) System.exit(0); // plot intensity data in 2D display progress.setNote("Building displays"); iPlot = new DisplayImplJ3D("intensity", new TwoDDisplayRendererJ3D()); iPlot.getMouseBehavior().getMouseHelper().setFunctionMap(new int[][][] { {{MouseHelper.DIRECT, MouseHelper.NONE}, // L, shift-L {MouseHelper.NONE, MouseHelper.NONE}}, // ctrl-L, ctrl-shift-L {{MouseHelper.CURSOR_TRANSLATE, MouseHelper.CURSOR_ZOOM}, // M, shift-M {MouseHelper.CURSOR_ROTATE, MouseHelper.NONE}}, // ctrl-M, ctrl-shift-M {{MouseHelper.ROTATE, MouseHelper.ZOOM}, // R, shift-R {MouseHelper.TRANSLATE, MouseHelper.NONE}}, // ctrl-R, ctrl-shift-R }); iPlot.enableEvent(DisplayEvent.MOUSE_DRAGGED); iPlot.addDisplayListener(this); setProgress(progress, 720); // estimate: 72% if (progress.isCanceled()) System.exit(0); iPlot.addMap(new ScalarMap(xType, Display.XAxis)); iPlot.addMap(new ScalarMap(yType, Display.YAxis)); intensityMap = new ScalarMap(vType, Display.RGB); iPlot.addMap(intensityMap); iPlot.addMap(new ScalarMap(cType, Display.Animation)); DataReferenceImpl intensityRef = new DataReferenceImpl("intensity"); iPlot.addReference(intensityRef); setProgress(progress, 730); // estimate: 73% if (progress.isCanceled()) System.exit(0); // set up curve manipulation renderer in 2D display roiGrid = new float[2][width * height]; roiMask = new boolean[height][width]; for (int h=0; h<height; h++) { for (int w=0; w<width; w++) { int ndx = h * width + w; roiGrid[0][ndx] = w; roiGrid[1][ndx] = h; roiMask[h][w] = true; } } final DataReferenceImpl curveRef = new DataReferenceImpl("curve"); UnionSet dummyCurve = new UnionSet(new Gridded2DSet[] { new Gridded2DSet(xy, new float[][] {{0}, {0}}, 1) }); curveRef.setData(dummyCurve); CurveManipulationRendererJ3D curve = new CurveManipulationRendererJ3D(0, 0, true); iPlot.addReferences(curve, curveRef); CellImpl cell = new CellImpl() { public void doAction() throws VisADException, RemoteException { // save latest drawn curve curveSet = (UnionSet) curveRef.getData(); } }; cell.addReference(curveRef); roiRef = new DataReferenceImpl("roi"); roiRef.setData(new Real(0)); // dummy iPlot.addReference(roiRef, new ConstantMap[] { new ConstantMap(0, Display.Blue), new ConstantMap(0.1, Display.Alpha) }); setProgress(progress, 740); // estimate: 74% if (progress.isCanceled()) System.exit(0); ac = (AnimationControl) iPlot.getControl(AnimationControl.class); iPlot.getProjectionControl().setMatrix( iPlot.make_matrix(0, 0, 0, 0.85, 0, 0, 0)); setProgress(progress, 750); // estimate: 75% if (progress.isCanceled()) System.exit(0); // plot decay curves in 3D display decayPlot = channels > 1 ? new DisplayImplJ3D("decay") : new DisplayImplJ3D("decay", new TwoDDisplayRendererJ3D()); ScalarMap xMap = new ScalarMap(bType, Display.XAxis); ScalarMap yMap = new ScalarMap(cType, Display.YAxis); DisplayRealType heightAxis = channels > 1 ? Display.ZAxis : Display.YAxis; zMap = new ScalarMap(vType, heightAxis); zMapFit = new ScalarMap(vTypeFit, heightAxis); zMapRes = new ScalarMap(vTypeRes, heightAxis); vMap = new ScalarMap(vType2, Display.RGB); //vMapFit = new ScalarMap(vTypeFit, Display.RGB); vMapRes = new ScalarMap(vTypeRes, Display.RGB); decayPlot.addMap(xMap); if (channels > 1) decayPlot.addMap(yMap); decayPlot.addMap(zMap); decayPlot.addMap(zMapFit); decayPlot.addMap(zMapRes); decayPlot.addMap(vMap); //decayPlot.addMap(vMapFit); decayPlot.addMap(vMapRes); setProgress(progress, 760); // estimate: 76% if (progress.isCanceled()) System.exit(0); decayRend = new DefaultRendererJ3D(); decayRef = new DataReferenceImpl("decay"); decayPlot.addReferences(decayRend, decayRef); if (computeFWHMs) { // add reference for full width half maxes fwhmRend = new DefaultRendererJ3D(); fwhmRef = new DataReferenceImpl("fwhm"); decayPlot.addReferences(fwhmRend, fwhmRef, new ConstantMap[] { new ConstantMap(0, Display.Red), new ConstantMap(0, Display.Blue), //new ConstantMap(2, Display.LineWidth) }); } if (adjustPeaks) { // add references for curve fitting fitRend = new DefaultRendererJ3D(); fitRef = new DataReferenceImpl("fit"); decayPlot.addReferences(fitRend, fitRef, new ConstantMap[] { new ConstantMap(1, Display.Red), new ConstantMap(1, Display.Green), new ConstantMap(1, Display.Blue) }); fitRend.toggle(false); resRend = new DefaultRendererJ3D(); resRef = new DataReferenceImpl("residuals"); decayPlot.addReferences(resRend, resRef); resRend.toggle(false); } setProgress(progress, 770); // estimate: 77% if (progress.isCanceled()) System.exit(0); xMap.setRange(0, timeRange); yMap.setRange(minWave, maxWave); AxisScale xScale = xMap.getAxisScale(); Font font = Font.decode("serif 24"); xScale.setFont(font); xScale.setTitle("Time (ns)"); xScale.setSnapToBox(true); AxisScale yScale = yMap.getAxisScale(); yScale.setFont(font); yScale.setTitle("Wavelength (nm)"); yScale.setSide(AxisScale.SECONDARY); yScale.setSnapToBox(true); AxisScale zScale = zMap.getAxisScale(); zScale.setFont(font); zScale.setTitle("Count"); zScale.setSnapToBox(true); // workaround for weird axis spacing issue zMapFit.getAxisScale().setVisible(false); zMapRes.getAxisScale().setVisible(false); GraphicsModeControl gmc = decayPlot.getGraphicsModeControl(); gmc.setScaleEnable(true); gmc.setTextureEnable(false); ProjectionControl pc = decayPlot.getProjectionControl(); pc.setMatrix(channels > 1 ? MATRIX_3D : MATRIX_2D); pc.setAspectCartesian( new double[] {2, 1, 1}); setProgress(progress, 780); // estimate: 78% if (progress.isCanceled()) System.exit(0); // convert byte data to unsigned shorts progress.setNote("Constructing images"); values = new int[channels][height][width][timeBins]; float[][][] pix = new float[channels][1][width * height]; FieldImpl field = new FieldImpl(cxyvFunc, cSet); maxIntensity = new int[channels]; for (int c=0; c<channels; c++) { int oc = timeBins * width * height * c; for (int h=0; h<height; h++) { int oh = timeBins * width * h; for (int w=0; w<width; w++) { int ow = timeBins * w; int sum = 0; for (int t=0; t<timeBins; t++) { int ndx = 2 * (oc + oh + ow + t); int val = DataTools.bytesToInt(data, ndx, 2, true); if (val > maxIntensity[c]) maxIntensity[c] = val; values[c][h][w][t] = val; sum += val; } pix[c][0][width * h + w] = sum; } setProgress(progress, 780 + 140 * (height * c + h + 1) / (channels * height)); // estimate: 78% -> 92% if (progress.isCanceled()) System.exit(0); } FlatField ff = new FlatField(xyvFunc, xySet); ff.setSamples(pix[c], false); field.setSample(c, ff); } // compute channel with brightest intensity maxChan = 0; int max = 0; for (int c=0; c<channels; c++) { if (maxIntensity[c] > max) { max = maxIntensity[c]; maxChan = c; } } // adjust peaks if (adjustPeaks) { progress.setNote("Adjusting peaks"); int[] peaks = new int[channels]; for (int c=0; c<channels; c++) { int[] sum = new int[timeBins]; for (int h=0; h<height; h++) { for (int w=0; w<width; w++) { for (int t=0; t<timeBins; t++) sum[t] += values[c][h][w][t]; } } int peak = 0, ndx = 0; for (int t=0; t<timeBins; t++) { if (peak <= sum[t]) { peak = sum[t]; ndx = t; } else if (t > timeBins / 3) break; // HACK - too early to give up } peaks[c] = ndx; setProgress(progress, 920 + 20 * (c + 1) / channels); // estimate: 92% -> 94% if (progress.isCanceled()) System.exit(0); } maxPeak = 0; for (int c=0; c<channels; c++) { if (maxPeak < peaks[c]) maxPeak = peaks[c]; } log("Aligning peaks to tmax = " + maxPeak); for (int c=0; c<channels; c++) { int shift = maxPeak - peaks[c]; if (shift > 0) { for (int h=0; h<height; h++) { for (int w=0; w<width; w++) { for (int t=timeBins-1; t>=shift; t values[c][h][w][t] = values[c][h][w][t - shift]; } for (int t=shift-1; t>=0; t--) values[c][h][w][t] = 0; } } log("\tChannel #" + (c + 1) + ": tmax = " + peaks[c] + " (shifting by " + shift + ")"); } setProgress(progress, 940 + 20 * (c + 1) / channels); // estimate: 94% -> 96% if (progress.isCanceled()) System.exit(0); } // add yellow line to indicate adjusted peak position lineRend = new DefaultRendererJ3D(); DataReferenceImpl peakRef = new DataReferenceImpl("peaks"); float peakTime = (float) (maxPeak * timeRange / (timeBins - 1)); peakRef.setData(new Gridded2DSet(bc, new float[][] {{peakTime, peakTime}, {minWave, maxWave}}, 2)); decayPlot.addReferences(lineRend, peakRef, new ConstantMap[] { new ConstantMap(-1, Display.ZAxis), new ConstantMap(0, Display.Blue), //new ConstantMap(2, Display.LineWidth) }); } // construct 2D pane progress.setNote("Creating plots"); masterWindow = new JFrame("Slim Plotter - " + file.getName()); masterWindow.addWindowListener(this); JPanel masterPane = new JPanel(); masterPane.setLayout(new BorderLayout()); masterWindow.setContentPane(masterPane); JPanel intensityPane = new JPanel(); intensityPane.setLayout(new BoxLayout(intensityPane, BoxLayout.Y_AXIS)); JPanel iPlotPane = new JPanel() { private int height = 380; public Dimension getMinimumSize() { Dimension min = super.getMinimumSize(); return new Dimension(min.width, height); } public Dimension getPreferredSize() { Dimension pref = super.getPreferredSize(); return new Dimension(pref.width, height); } public Dimension getMaximumSize() { Dimension max = super.getMaximumSize(); return new Dimension(max.width, height); } }; iPlotPane.setLayout(new BorderLayout()); iPlotPane.add(iPlot.getComponent(), BorderLayout.CENTER); intensityPane.add(iPlotPane); JMenuBar menubar = new JMenuBar(); masterWindow.setJMenuBar(menubar); JMenu menuFile = new JMenu("File"); menubar.add(menuFile); menuFileExit = new JMenuItem("Exit"); menuFileExit.addActionListener(this); menuFile.add(menuFileExit); JMenu menuView = new JMenu("View"); menubar.add(menuView); menuViewSaveProj = new JMenuItem("Save projection to clipboard"); menuViewSaveProj.addActionListener(this); menuView.add(menuViewSaveProj); menuViewLoadProj = new JMenuItem("Restore projection from clipboard"); menuViewLoadProj.addActionListener(this); menuView.add(menuViewLoadProj); setProgress(progress, 970); // estimate: 97% if (progress.isCanceled()) System.exit(0); JPanel sliderPane = new JPanel(); sliderPane.setLayout(new BoxLayout(sliderPane, BoxLayout.X_AXIS)); intensityPane.add(sliderPane); cSlider = new JSlider(1, channels, 1); cSlider.setToolTipText( "Selects the channel to display in the 2D intensity plot above"); cSlider.setSnapToTicks(true); cSlider.setMajorTickSpacing(channels / 4); cSlider.setMinorTickSpacing(1); cSlider.setPaintTicks(true); cSlider.addChangeListener(this); cSlider.setBorder(new EmptyBorder(8, 5, 8, 5)); cSlider.setEnabled(channels > 1); sliderPane.add(cSlider); cToggle = new JCheckBox("", true); cToggle.setToolTipText( "Toggles the selected channel's visibility in the 3D data plot"); cToggle.addActionListener(this); cToggle.setEnabled(channels > 1); sliderPane.add(cToggle); JPanel minMaxPane = new JPanel(); minMaxPane.setLayout(new BoxLayout(minMaxPane, BoxLayout.X_AXIS)); intensityPane.add(minMaxPane); JPanel minPane = new JPanel(); minPane.setLayout(new BoxLayout(minPane, BoxLayout.Y_AXIS)); minMaxPane.add(minPane); minLabel = new JLabel("min=0"); minLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT); minPane.add(minLabel); minSlider = new JSlider(0, max, 0); minSlider.setToolTipText("<html>" + "Adjusts intensity plot's minimum color value.<br>" + "Anything less than this value appears black.</html>"); minSlider.setMajorTickSpacing(max); int minor = max / 16; if (minor < 1) minor = 1; minSlider.setMinorTickSpacing(minor); minSlider.setPaintTicks(true); minSlider.addChangeListener(this); minSlider.setBorder(new EmptyBorder(0, 5, 8, 5)); minPane.add(minSlider); JPanel maxPane = new JPanel(); maxPane.setLayout(new BoxLayout(maxPane, BoxLayout.Y_AXIS)); minMaxPane.add(maxPane); maxLabel = new JLabel("max=" + max); maxLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT); maxPane.add(maxLabel); maxSlider = new JSlider(0, max, max); maxSlider.setToolTipText("<html>" + "Adjusts intensity plot's maximum color value.<br>" + "Anything greater than this value appears white.</html>"); maxSlider.setMajorTickSpacing(max); maxSlider.setMinorTickSpacing(minor); maxSlider.setPaintTicks(true); maxSlider.addChangeListener(this); maxSlider.setBorder(new EmptyBorder(0, 5, 8, 5)); maxPane.add(maxSlider); intensityRef.setData(field); ColorControl cc = (ColorControl) iPlot.getControl(ColorControl.class); cc.setTable(ColorControl.initTableGreyWedge(new float[3][256])); setProgress(progress, 980); // estimate: 98% if (progress.isCanceled()) System.exit(0); // construct 3D pane JPanel decayPane = new JPanel(); decayPane.setLayout(new BorderLayout()); decayPane.add(decayPlot.getComponent(), BorderLayout.CENTER); decayLabel = new JLabel("Decay curve for all pixels"); decayLabel.setToolTipText( "Displays information about the selected region of interest"); decayPane.add(decayLabel, BorderLayout.NORTH); colorWidget = new ColorMapWidget(vMap); Dimension prefSize = colorWidget.getPreferredSize(); colorWidget.setPreferredSize(new Dimension(prefSize.width, 0)); cOverride = new JCheckBox("", false); cOverride.setToolTipText( "Toggles manual override of color range"); cOverride.addActionListener(this); cMinValue = new JTextField(); Util.adjustTextField(cMinValue); cMinValue.setToolTipText("Overridden color minimum"); cMinValue.setEnabled(false); cMinValue.getDocument().addDocumentListener(this); cMaxValue = new JTextField(); Util.adjustTextField(cMaxValue); cMaxValue.setToolTipText("Overridden color maximum"); cMaxValue.setEnabled(false); cMaxValue.getDocument().addDocumentListener(this); lutLoad = new JButton("Load LUT..."); lutLoad.setToolTipText("Loads a color table from disk"); lutLoad.addActionListener(this); lutSave = new JButton("Save LUT..."); lutSave.setToolTipText("Saves this color table to disk"); lutSave.addActionListener(this); lutsMenu = new JPopupMenu(); for (int i=0; i<LUT_NAMES.length; i++) { if (LUT_NAMES[i] == null) lutsMenu.addSeparator(); else { JMenuItem item = new JMenuItem(LUT_NAMES[i]); item.setActionCommand("lut" + i); item.addActionListener(this); lutsMenu.add(item); } } lutPresets = new JButton("LUTs >"); lutPresets.setToolTipText("Selects a LUT from the list of presets"); lutPresets.addActionListener(this); lutBox = new JFileChooser(System.getProperty("user.dir")); lutBox.addChoosableFileFilter( new ExtensionFileFilter("lut", "Binary color table files")); showData = new JCheckBox("Data", true); showData.setToolTipText("Toggles visibility of raw data"); showData.addActionListener(this); showScale = new JCheckBox("Scale", true); showScale.setToolTipText("Toggles visibility of scale bars"); showScale.addActionListener(this); showBox = new JCheckBox("Box", true); showBox.setToolTipText("Toggles visibility of bounding box"); showBox.addActionListener(this); showLine = new JCheckBox("Line", adjustPeaks); showLine.setToolTipText( "Toggles visibility of aligned peaks indicator line"); showLine.setEnabled(adjustPeaks); showLine.addActionListener(this); showFit = new JCheckBox("Fit", false); showFit.setToolTipText("Toggles visibility of fitted curves"); showFit.setEnabled(adjustPeaks); showFit.addActionListener(this); showResiduals = new JCheckBox("Residuals", false); showResiduals.setToolTipText( "Toggles visibility of fitted curve residuals"); showResiduals.setEnabled(adjustPeaks); showResiduals.addActionListener(this); showFWHMs = new JCheckBox("FWHMs", computeFWHMs); showFWHMs.setToolTipText("Toggles visibility of full width half maxes"); showFWHMs.setEnabled(computeFWHMs); showFWHMs.addActionListener(this); linear = new JRadioButton("Linear", true); linear.setToolTipText("Plots 3D data with a linear scale"); log = new JRadioButton("Log", false); log.setToolTipText("Plots 3D data with a logarithmic scale"); perspective = new JRadioButton("Perspective", true); perspective.setToolTipText( "Displays 3D plot with a perspective projection"); perspective.setEnabled(channels > 1); parallel = new JRadioButton("Parallel", false); parallel.setToolTipText( "Displays 3D plot with a parallel (orthographic) projection"); parallel.setEnabled(channels > 1); dataSurface = new JRadioButton("Surface", channels > 1); dataSurface.setToolTipText("Displays raw data as a 2D surface"); dataSurface.setEnabled(channels > 1); dataLines = new JRadioButton("Lines", channels == 1); dataLines.setToolTipText("Displays raw data as a series of lines"); dataLines.setEnabled(channels > 1); fitSurface = new JRadioButton("Surface", false); fitSurface.setToolTipText("Displays fitted curves as a 2D surface"); fitSurface.setEnabled(adjustPeaks && channels > 1); fitLines = new JRadioButton("Lines", true); fitLines.setToolTipText("Displays fitted curves as a series of lines"); fitLines.setEnabled(adjustPeaks && channels > 1); resSurface = new JRadioButton("Surface", false); resSurface.setToolTipText( "Displays fitted curve residuals as a 2D surface"); resSurface.setEnabled(adjustPeaks && channels > 1); resLines = new JRadioButton("Lines", true); resLines.setToolTipText( "Displays fitted curve residuals as a series of lines"); resLines.setEnabled(adjustPeaks && channels > 1); colorHeight = new JRadioButton("Counts", true); colorHeight.setToolTipText( "Colorizes data according to the height (histogram count)"); colorHeight.setEnabled(adjustPeaks && channels > 1); colorTau = new JRadioButton("Lifetimes", false); colorTau.setToolTipText( "Colorizes data according to aggregate lifetime value"); colorTau.setEnabled(adjustPeaks && channels > 1); zOverride = new JCheckBox("", false); zOverride.setToolTipText( "Toggles manual override of Z axis scale (Count)"); zOverride.addActionListener(this); zScaleValue = new JTextField(9); zScaleValue.setToolTipText("Overridden Z axis scale value"); zScaleValue.setEnabled(false); zScaleValue.getDocument().addDocumentListener(this); exportData = new JButton("Export"); exportData.setToolTipText( "Exports the selected ROI's raw data to a text file"); exportData.addActionListener(this); numCurves = new JSpinner(new SpinnerNumberModel(1, 1, 2, 1)); numCurves.setToolTipText("Number of components in exponential fit"); numCurves.setMaximumSize(numCurves.getPreferredSize()); numCurves.addChangeListener(this); setProgress(progress, 990); // estimate: 99% if (progress.isCanceled()) System.exit(0); JPanel colorPanel = new JPanel(); colorPanel.setBorder(new TitledBorder("Color Mapping")); colorPanel.setLayout(new BoxLayout(colorPanel, BoxLayout.Y_AXIS)); colorPanel.add(colorWidget); JPanel colorRange = new JPanel(); colorRange.setLayout(new BoxLayout(colorRange, BoxLayout.X_AXIS)); colorRange.add(cOverride); colorRange.add(cMinValue); colorRange.add(cMaxValue); colorPanel.add(colorRange); JPanel colorButtons = new JPanel(); colorButtons.setLayout(new BoxLayout(colorButtons, BoxLayout.X_AXIS)); colorButtons.add(lutLoad); colorButtons.add(lutSave); colorButtons.add(lutPresets); colorPanel.add(colorButtons); JPanel showPanel = new JPanel(); showPanel.setBorder(new TitledBorder("Show")); showPanel.setLayout(new BoxLayout(showPanel, BoxLayout.Y_AXIS)); showPanel.add(showData); showPanel.add(showScale); showPanel.add(showBox); showPanel.add(showLine); showPanel.add(showFit); showPanel.add(showResiduals); showPanel.add(showFWHMs); JPanel scalePanel = new JPanel(); scalePanel.setBorder(new TitledBorder("Z Scale Override")); scalePanel.setLayout(new BoxLayout(scalePanel, BoxLayout.X_AXIS)); scalePanel.add(zOverride); scalePanel.add(zScaleValue); JPanel miscRow1 = new JPanel(); miscRow1.setLayout(new BoxLayout(miscRow1, BoxLayout.X_AXIS)); miscRow1.add(makeRadioPanel("Scale", linear, log)); miscRow1.add(makeRadioPanel("Projection", perspective, parallel)); miscRow1.add(makeRadioPanel("Data", dataSurface, dataLines)); JPanel miscRow2 = new JPanel(); miscRow2.setLayout(new BoxLayout(miscRow2, BoxLayout.X_AXIS)); miscRow2.add(makeRadioPanel("Fit", fitSurface, fitLines)); miscRow2.add(makeRadioPanel("Residuals", resSurface, resLines)); miscRow2.add(makeRadioPanel("Colors", colorHeight, colorTau)); JPanel miscRow3 = new JPanel(); miscRow3.setLayout(new BoxLayout(miscRow3, BoxLayout.X_AXIS)); miscRow3.add(scalePanel); miscRow3.add(Box.createHorizontalStrut(5)); // miscRow3.add(numCurves); // miscRow3.add(Box.createHorizontalStrut(5)); miscRow3.add(exportData); JPanel miscPanel = new JPanel(); miscPanel.setLayout(new BoxLayout(miscPanel, BoxLayout.Y_AXIS)); miscPanel.add(miscRow1); miscPanel.add(miscRow2); miscPanel.add(miscRow3); JPanel options = new JPanel(); options.setBorder(new EmptyBorder(8, 5, 8, 5)); options.setLayout(new BoxLayout(options, BoxLayout.X_AXIS)); options.add(colorPanel); options.add(showPanel); options.add(miscPanel); decayPane.add(options, BorderLayout.SOUTH); masterPane.add(decayPane, BorderLayout.CENTER); JPanel rightPanel = new JPanel() { public Dimension getMaximumSize() { Dimension pref = getPreferredSize(); Dimension max = super.getMaximumSize(); return new Dimension(pref.width, max.height); } }; rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS)); rightPanel.add(intensityPane); rightPanel.add(console.getWindow().getContentPane()); BreakawayPanel breakawayPanel = new BreakawayPanel(masterPane, "Intensity Data - " + file.getName(), false); breakawayPanel.setEdge(BorderLayout.EAST); breakawayPanel.setUpEnabled(false); breakawayPanel.setDownEnabled(false); breakawayPanel.setContentPane(rightPanel); setProgress(progress, 999); // estimate: 99.9% if (progress.isCanceled()) System.exit(0); // show window on screen masterWindow.pack(); Dimension size = masterWindow.getSize(); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); masterWindow.setLocation((screen.width - size.width) / 2, (screen.height - size.height) / 2); masterWindow.setVisible(true); } catch (Throwable t) { // display stack trace to the user ByteArrayOutputStream out = new ByteArrayOutputStream(); t.printStackTrace(new PrintStream(out)); String stackTrace = new String(out.toByteArray()); JOptionPane.showMessageDialog(null, "Sorry, Slim Plotter encountered a problem loading your data:\n" + stackTrace, "Slim Plotter", JOptionPane.ERROR_MESSAGE); System.exit(4); } setProgress(progress, 1000); progress.close(); plotData(true, true, true); try { Thread.sleep(200); } catch (InterruptedException exc) { exc.printStackTrace(); } cSlider.setValue(maxChan + 1); } // -- SlimPlotter methods -- private Thread plotThread; private boolean plotCanceled; private boolean doRecalc, doRescale, doRefit; /** Plots the data in a separate thread. */ public void plotData(final boolean recalc, final boolean rescale, final boolean refit) { final SlimPlotter sp = this; new Thread("PlotSpawner") { public void run() { synchronized (sp) { if (plotThread != null) { // wait for old thread to cancel out plotCanceled = true; try { plotThread.join(); } catch (InterruptedException exc) { exc.printStackTrace(); } } sp.doRecalc = recalc; sp.doRescale = rescale; sp.doRefit = refit; plotCanceled = false; plotThread = new Thread(sp, "Plotter"); plotThread.start(); } } }.start(); } /** Handles cursor updates. */ public void doCursor(double[] cursor, boolean rescale, boolean refit) { double[] domain = cursorToDomain(iPlot, cursor); roiX = (int) Math.round(domain[0]); roiY = (int) Math.round(domain[1]); if (roiX < 0) roiX = 0; if (roiX >= width) roiX = width - 1; if (roiY < 0) roiY = 0; if (roiY >= height) roiY = height - 1; roiCount = 1; plotData(true, rescale, refit); } /** Sets the currently selected range component's color widget table. */ public void setWidgetTable(float[][] table) { // float[][] oldTable = colorWidget.getTableView(); // float[] alpha = oldTable.length > 3 ? oldTable[3] : null; // table = ColorUtil.adjustColorTable(table, alpha, true); colorWidget.setTableView(table); } /** Logs the given output to the appropriate location. */ public void log(String msg) { final String message = msg; SwingUtilities.invokeLater(new Runnable() { public void run() { System.err.println(message); } }); } // -- ActionListener methods -- /** Handles checkbox and button presses. */ public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if (src == menuFileExit) System.exit(0); else if (src == menuViewSaveProj) { String save = decayPlot.getProjectionControl().getSaveString(); clip.setClipboardContents(save); } else if (src == menuViewLoadProj) { String save = clip.getClipboardContents(); if (save != null) { try { decayPlot.getProjectionControl().setSaveString(save); } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } } } else if (src == cToggle) { // toggle visibility of this channel int c = cSlider.getValue() - 1; cVisible[c] = !cVisible[c]; plotData(true, true, false); } else if (src == cOverride) { boolean manual = cOverride.isSelected(); cMinValue.setEnabled(manual); cMaxValue.setEnabled(manual); updateColorScale(); } else if (src == lutLoad) { // ask user to specify the file int returnVal = lutBox.showOpenDialog(masterWindow); if (returnVal != JFileChooser.APPROVE_OPTION) return; File file = lutBox.getSelectedFile(); float[][] table = ColorUtil.loadColorTable(file); if (table == null) { JOptionPane.showMessageDialog(masterWindow, "Error reading LUT file.", "Cannot load color table", JOptionPane.ERROR_MESSAGE); } else setWidgetTable(table); } else if (src == lutSave) { // ask user to specify the file int returnVal = lutBox.showSaveDialog(masterWindow); if (returnVal != JFileChooser.APPROVE_OPTION) return; File file = lutBox.getSelectedFile(); String s = file.getAbsolutePath(); if (!s.toLowerCase().endsWith(".lut")) file = new File(s + ".lut"); boolean success = ColorUtil.saveColorTable(colorWidget.getTableView(), file); if (!success) { JOptionPane.showMessageDialog(masterWindow, "Error writing LUT file.", "Cannot save color table", JOptionPane.ERROR_MESSAGE); } } else if (src == lutPresets) { lutsMenu.show(lutPresets, lutPresets.getWidth(), 0); } else if (src == linear || src == log) plotData(true, true, true); else if (src == dataSurface || src == dataLines || src == colorHeight || src == colorTau) { plotData(true, false, false); } else if (src == fitSurface || src == fitLines || src == resSurface || src == resLines) { plotData(true, false, true); } else if (src == perspective || src == parallel) { try { decayPlot.getGraphicsModeControl().setProjectionPolicy( parallel.isSelected() ? DisplayImplJ3D.PARALLEL_PROJECTION : DisplayImplJ3D.PERSPECTIVE_PROJECTION); } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } } else if (src == showData) decayRend.toggle(showData.isSelected()); else if (src == showLine) lineRend.toggle(showLine.isSelected()); else if (src == showBox) { try { decayPlot.getDisplayRenderer().setBoxOn(showBox.isSelected()); } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } } else if (src == showScale) { try { boolean scale = showScale.isSelected(); decayPlot.getGraphicsModeControl().setScaleEnable(scale); } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } } else if (src == showFit) { fitRend.toggle(showFit.isSelected()); } else if (src == showResiduals) { resRend.toggle(showResiduals.isSelected()); } else if (src == showFWHMs) fwhmRend.toggle(showFWHMs.isSelected()); else if (src == zOverride) { boolean manual = zOverride.isSelected(); zScaleValue.setEnabled(manual); if (!manual) plotData(true, true, false); } else if (src == exportData) { // get output file from user JFileChooser jc = new JFileChooser(System.getProperty("user.dir")); jc.addChoosableFileFilter(new ExtensionFileFilter("txt", "Text files")); int rval = jc.showSaveDialog(exportData); if (rval != JFileChooser.APPROVE_OPTION) return; File file = jc.getSelectedFile(); if (file == null) return; // write currently displayed binned data to file try { PrintWriter out = new PrintWriter(new FileWriter(file)); out.println(timeBins + " x " + channels + " (count=" + roiCount + ", percent=" + roiPercent + ", maxVal=" + maxVal + ")"); for (int c=0; c<channels; c++) { for (int t=0; t<timeBins; t++) { if (t > 0) out.print("\t"); float s = samps[timeBins * c + t]; int is = (int) s; if (is == s) out.print(is); else out.print(s); } out.println(); } out.close(); } catch (IOException exc) { JOptionPane.showMessageDialog(exportData, "There was a problem writing the file: " + exc.getMessage(), "Slim Plotter", JOptionPane.ERROR_MESSAGE); } } else { String cmd = e.getActionCommand(); if (cmd != null && cmd.startsWith("lut")) { // apply the chosen LUT preset setWidgetTable(LUTS[Integer.parseInt(cmd.substring(3))]); } else { // OK button width = parse(wField.getText(), width); height = parse(hField.getText(), height); timeBins = parse(tField.getText(), timeBins); channels = parse(cField.getText(), channels); timeRange = parse(trField.getText(), timeRange); minWave = parse(wlField.getText(), minWave); waveStep = parse(sField.getText(), waveStep); adjustPeaks = peaksBox.isSelected(); computeFWHMs = fwhmBox.isSelected(); cutEnd = cutBox.isSelected(); cVisible = new boolean[channels]; Arrays.fill(cVisible, true); paramDialog.setVisible(false); } } } // -- ChangeListener methods -- /** Handles slider changes. */ public void stateChanged(ChangeEvent e) { Object src = e.getSource(); if (src == cSlider) { int c = cSlider.getValue() - 1; try { ac.setCurrent(c); } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } cToggle.removeActionListener(this); cToggle.setSelected(cVisible[c]); cToggle.addActionListener(this); } else if (src == minSlider) { int min = minSlider.getValue(); int max = maxSlider.getMaximum(); maxSlider.setMajorTickSpacing(max - min); int minor = (max - min) / 16; if (minor < 1) minor = 1; maxSlider.setMinorTickSpacing(minor); maxSlider.setMinimum(min); minLabel.setText("min=" + min); rescaleMinMax(); } else if (src == maxSlider) { int max = maxSlider.getValue(); minSlider.setMajorTickSpacing(max); int minor = max / 16; if (minor < 1) minor = 1; minSlider.setMinorTickSpacing(minor); minSlider.setMaximum(max); maxLabel.setText("max=" + max); rescaleMinMax(); } else if (src == numCurves) plotData(true, false, true); } // -- DisplayListener methods -- private boolean drag = false; public void displayChanged(DisplayEvent e) { int id = e.getId(); if (id == DisplayEvent.MOUSE_PRESSED_CENTER) { drag = true; decayPlot.getDisplayRenderer(); doCursor(iPlot.getDisplayRenderer().getCursor(), false, false); } else if (id == DisplayEvent.MOUSE_RELEASED_CENTER) { drag = false; doCursor(iPlot.getDisplayRenderer().getCursor(), true, true); } else if (id == DisplayEvent.MOUSE_RELEASED_LEFT) { // done drawing curve try { roiSet = DelaunayCustom.fillCheck(curveSet, false); if (roiSet == null) { roiRef.setData(new Real(0)); doCursor(pixelToCursor(iPlot, e.getX(), e.getY()), true, true); iPlot.reAutoScale(); } else { roiRef.setData(roiSet); int[] tri = roiSet.valueToTri(roiGrid); roiX = roiY = 0; roiCount = 0; for (int h=0; h<height; h++) { for (int w=0; w<width; w++) { int ndx = h * width + w; roiMask[h][w] = tri[ndx] >= 0; if (roiMask[h][w]) { roiX = w; roiY = h; roiCount++; } } } roiPercent = 100000 * roiCount / (width * height) / 1000.0; plotData(true, true, true); } } catch (VisADException exc) { String msg = exc.getMessage(); if ("path self intersects".equals(msg)) { JOptionPane.showMessageDialog(iPlot.getComponent(), "Please draw a curve that does not intersect itself.", "Slim Plotter", JOptionPane.ERROR_MESSAGE); } else exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } } else if (id == DisplayEvent.MOUSE_DRAGGED) { if (!drag) return; // not a center mouse drag doCursor(iPlot.getDisplayRenderer().getCursor(), false, false); } } // -- DocumentListener methods -- public void changedUpdate(DocumentEvent e) { documentUpdate(e); } public void insertUpdate(DocumentEvent e) { documentUpdate(e); } public void removeUpdate(DocumentEvent e) { documentUpdate(e); } // -- Runnable methods -- public void run() { decayPlot.disableAction(); boolean doLog = log.isSelected(); if (doRecalc) { ProgressMonitor progress = new ProgressMonitor(null, "Plotting data", "Calculating sums", 0, channels * timeBins + (doRefit ? channels : 0) + 1); progress.setMillisToPopup(100); progress.setMillisToDecideToPopup(50); int p = 0; boolean doDataLines = dataLines.isSelected(); boolean doFitLines = fitLines.isSelected(); boolean doResLines = resLines.isSelected(); boolean doTauColors = colorTau.isSelected(); // update scale labels for log scale if (doLog) { AxisScale zScale = zMap.getAxisScale(); Hashtable hash = new Hashtable(); for (int i=1, v=1; v<=maxVal; i++, v*=BASE) { hash.put(new Double(Math.log(v) / BASE_LOG), i > 3 ? "1e" + i : "" + v); } try { zScale.setLabelTable(hash); } catch (VisADException exc) { exc.printStackTrace(); } } // calculate samples int numChanVis = 0; for (int c=0; c<channels; c++) { if (cVisible[c]) numChanVis++; } samps = new float[numChanVis * timeBins]; maxVal = 0; float[] maxVals = new float[numChanVis]; for (int c=0, cc=0; c<channels; c++) { if (!cVisible[c]) continue; for (int t=0; t<timeBins; t++) { int ndx = timeBins * cc + t; int sum = 0; if (roiCount == 1) sum = values[c][roiY][roiX][t]; else { for (int h=0; h<height; h++) { for (int w=0; w<width; w++) { if (roiMask[h][w]) sum += values[c][h][w][t]; } } } samps[ndx] = sum; if (samps[ndx] > maxVal) maxVal = samps[ndx]; if (samps[ndx] > maxVals[cc]) maxVals[cc] = samps[ndx]; setProgress(progress, ++p); if (progress.isCanceled()) plotCanceled = true; if (plotCanceled) break; } if (plotCanceled) break; cc++; } // full width half maxes float[][][] fwhmLines = null; if (computeFWHMs) { log("Calculating full width half maxes"); fwhmLines = new float[channels][3][2]; int grandTotal = 0; for (int c=0, cc=0; c<channels; c++) { if (!cVisible[c]) continue; // sum across all pixels int[] sums = new int[timeBins]; int sumTotal = 0; for (int t=0; t<timeBins; t++) { if (roiCount == 1) sums[t] = values[c][roiY][roiX][t]; else { for (int h=0; h<height; h++) { for (int w=0; w<width; w++) { if (roiMask[h][w]) sums[t] += values[c][h][w][t]; } } } sumTotal += sums[t]; } int maxSum = 0; for (int t=0; t<timeBins; t++) if (sums[t] > maxSum) maxSum = sums[t]; grandTotal += sumTotal; // find full width half max float half = maxSum / 2f; float fwhm1 = Float.NaN, fwhm2 = Float.NaN; boolean up = true; for (int t=0; t<timeBins-1; t++) { if (sums[t] <= half && sums[t + 1] >= half) { // upslope float q = (half - sums[t]) / (sums[t + 1] - sums[t]); fwhm1 = timeRange * (t + q) / (timeBins - 1); // binsToNano } else if (sums[t] >= half && sums[t + 1] <= half) { // downslope float q = (half - sums[t + 1]) / (sums[t] - sums[t + 1]); fwhm2 = timeRange * (t + 1 - q) / (timeBins - 1); // binsToNano } if (fwhm1 == fwhm1 && fwhm2 == fwhm2) break; } fwhmLines[c][0][0] = fwhm1; fwhmLines[c][0][1] = fwhm2; fwhmLines[c][1][0] = fwhmLines[c][1][1] = minWave + c * waveStep; fwhmLines[c][2][0] = fwhmLines[c][2][1] = half; String s = "#" + (c + 1); while (s.length() < 3) s = " " + s; float h1 = 1000 * fwhm1, h2 = 1000 * fwhm2; log("\tChannel " + s + ": fwhm = " + (h2 - h1) + " ps"); log("\t counts = " + sumTotal); log("\t peak = " + sums[maxPeak]); log("\t center = " + ((h1 + h2) / 2) + " ps"); log("\t range = [" + h1 + ", " + h2 + "] ps"); if (plotCanceled) break; cc++; } log("\tTotal counts = " + grandTotal); } // curve fitting double[][] fitResults = null; int numExp = ((Integer) numCurves.getValue()).intValue(); if (adjustPeaks && doRefit) { // perform exponential curve fitting: y(x) = a * e^(-b*t) + c progress.setNote("Fitting curves"); fitResults = new double[channels][]; tau = new float[channels][numExp]; for (int c=0; c<channels; c++) Arrays.fill(tau[c], Float.NaN); ExpFunction func = new ExpFunction(numExp); float[] params = new float[2 * numExp + 1]; if (numExp == 1) { //params[0] = maxVal; params[1] = picoToBins(1000); params[2] = 0; } else if (numExp == 2) { //params[0] = maxVal / 2; params[1] = picoToBins(800); //params[2] = maxVal / 2; params[3] = picoToBins(2000); params[4] = 0; } int num = timeBins - maxPeak; // HACK - cut off last 1500 ps from lifetime histogram, // to improve accuracy of fit. if (cutEnd) { int cutBins = (int) picoToBins(1500); if (num > cutBins + 5) num -= cutBins; } float[] xVals = new float[num]; for (int i=0; i<num; i++) xVals[i] = i; float[] yVals = new float[num]; float[] weights = new float[num]; Arrays.fill(weights, 1); // no weighting StringBuffer equation = new StringBuffer(); equation.append("y(t) = "); for (int i=0; i<numExp; i++) { equation.append("a"); equation.append(i + 1); equation.append(" * e^(-t/"); equation.append(TAU); equation.append(i + 1); equation.append(") + "); } equation.append("c"); log("Computing fit parameters: " + equation.toString()); for (int c=0, cc=0; c<channels; c++) { if (!cVisible[c]) { fitResults[c] = null; continue; } log("\tChannel #" + (c + 1) + ":"); System.arraycopy(samps, timeBins * cc + maxPeak, yVals, 0, num); LMA lma = null; for (int i=0; i<numExp; i++) { int e = 2 * i; params[e] = maxVals[cc] / numExp; } lma = new LMA(func, params, new float[][] {xVals, yVals}, weights, new JAMAMatrix(params.length, params.length)); lma.fit(); log("\t\titerations=" + lma.iterationCount); // normalize chi2 by the channel's peak value if (maxVals[cc] != 0) lma.chi2 /= maxVals[cc]; // scale chi2 by degrees of freedom lma.chi2 /= num - params.length; log("\t\tchi2=" + lma.chi2); for (int i=0; i<numExp; i++) { int e = 2 * i; log("\t\ta" + (i + 1) + "=" + (100 * lma.parameters[e] / maxVals[cc]) + "%"); tau[c][i] = binsToPico((float) (1 / lma.parameters[e + 1])); log("\t\t" + TAU + (i + 1) + "=" + tau[c][i] + " ps"); } log("\t\tc=" + lma.parameters[2 * numExp]); fitResults[c] = lma.parameters; setProgress(progress, ++p); cc++; } } tauMin = tauMax = Float.NaN; if (tau != null) { tauMin = tauMax = tau[0][0]; for (int i=1; i<tau.length; i++) { if (tau[i][0] < tauMin) tauMin = tau[i][0]; if (tau[i][0] > tauMax) tauMax = tau[i][0]; } } StringBuffer sb = new StringBuffer(); sb.append("Decay curve for "); if (roiCount == 1) { sb.append("("); sb.append(roiX); sb.append(", "); sb.append(roiY); sb.append(")"); } else { sb.append(roiCount); sb.append(" pixels ("); sb.append(roiPercent); sb.append("%)"); } if (tauMin == tauMin && tauMax == tauMax) { sb.append("; "); sb.append(TAU); sb.append("="); if (tauMin != tauMax) { sb.append("["); sb.append(tauMin); sb.append(", "); sb.append(tauMax); sb.append("]"); } else sb.append(tauMin); sb.append(" ps"); } decayLabel.setText(sb.toString()); try { // construct domain set for 3D surface plots float[][] bcGrid = new float[2][timeBins * numChanVis]; for (int c=0, cc=0; c<channels; c++) { if (!cVisible[c]) continue; for (int t=0; t<timeBins; t++) { int ndx = timeBins * cc + t; bcGrid[0][ndx] = timeBins > 1 ? t * timeRange / (timeBins - 1) : 0; bcGrid[1][ndx] = channels > 1 ? c * (maxWave - minWave) / (channels - 1) + minWave : 0; } cc++; } Gridded2DSet bcSet = new Gridded2DSet(bc, bcGrid, timeBins, numChanVis, null, bcUnits, null, false); // compile color values for 3D surface plot float[] colors = new float[numChanVis * timeBins]; for (int c=0, cc=0; c<channels; c++) { if (!cVisible[c]) continue; for (int t=0; t<timeBins; t++) { int ndx = timeBins * cc + t; colors[ndx] = doTauColors ? (tau == null ? Float.NaN : tau[c][0]) : samps[ndx]; } cc++; } float[] fitSamps = null, residuals = null; if (fitResults != null) { // compute finite sampling matching fitted exponentials fitSamps = new float[numChanVis * timeBins]; residuals = new float[numChanVis * timeBins]; for (int c=0, cc=0; c<channels; c++) { if (!cVisible[c]) continue; double[] q = fitResults[c]; for (int t=0; t<timeBins; t++) { int ndx = timeBins * cc + t; int et = t - maxPeak; // adjust for peak alignment if (et < 0) fitSamps[ndx] = residuals[ndx] = 0; else { float sum = 0; for (int i=0; i<numExp; i++) { int e = 2 * i; sum += (float) (q[e] * Math.exp(-q[e + 1] * et)); } sum += (float) q[2 * numExp]; fitSamps[ndx] = sum; residuals[ndx] = samps[ndx] - fitSamps[ndx]; } } cc++; } } // construct "Data" plot if (doLog) { // convert samples to log values for plotting // this is done AFTER any computations involving samples (above) for (int i=0; i<samps.length; i++) { samps[i] = linearToLog(samps[i]); } } FlatField ff = new FlatField(bcvFunc, bcSet); ff.setSamples(new float[][] {samps, colors}, false); decayRef.setData(doDataLines ? makeLines(ff) : ff); if (fwhmLines != null) { // construct "FWHMs" plot SampledSet[] fwhmSets = new SampledSet[channels]; for (int c=0; c<channels; c++) { if (doLog) { // convert samples to log values for plotting // this is done AFTER any computations involving samples (above) for (int i=0; i<fwhmLines[c].length; i++) { for (int j=0; j<fwhmLines[c][i].length; i++) { fwhmLines[c][i][j] = linearToLog(fwhmLines[c][i][j]); } } } if (channels > 1) { fwhmSets[c] = new Gridded3DSet(bcv, fwhmLines[c], 2); } else { fwhmSets[c] = new Gridded2DSet(bv, new float[][] {fwhmLines[c][0], fwhmLines[c][2]}, 2); } } fwhmRef.setData(new UnionSet(fwhmSets)); } if (fitSamps != null) { // construct "Fit" plot if (doLog) { // convert samples to log values for plotting // this is done AFTER any computations involving samples (above) for (int i=0; i<fitSamps.length; i++) { fitSamps[i] = linearToLog(fitSamps[i]); } } FlatField fit = new FlatField(bcvFuncFit, bcSet); fit.setSamples(new float[][] {fitSamps}, false); fitRef.setData(doFitLines ? makeLines(fit) : fit); } if (residuals != null) { // construct "Residuals" plot if (doLog) { // convert samples to log values for plotting // this is done AFTER any computations involving samples (above) for (int i=0; i<residuals.length; i++) { residuals[i] = linearToLog(residuals[i]); } } FlatField res = new FlatField(bcvFuncRes, bcSet); res.setSamples(new float[][] {residuals}, false); resRef.setData(doResLines ? makeLines(res) : res); } } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } setProgress(progress, ++p); progress.close(); // update scale labels for linear scale if (!doLog) { AxisScale zScale = zMap.getAxisScale(); zScale.createStandardLabels(maxVal, 0, 0, maxVal); } updateColorScale(); } if (doRescale) { float d = Float.NaN; boolean manual = zOverride.isSelected(); if (manual) { try { d = Float.parseFloat(zScaleValue.getText()); } catch (NumberFormatException exc) { } } else { zScaleValue.getDocument().removeDocumentListener(this); zScaleValue.setText("" + maxVal); zScaleValue.getDocument().addDocumentListener(this); } float minZ = 0; float maxZ = d == d ? d : maxVal; if (doLog) maxZ = linearToLog(maxZ); if (maxZ != maxZ || maxZ == 0) maxZ = 1; try { zMap.setRange(minZ, maxZ); zMapFit.setRange(minZ, maxZ); zMapRes.setRange(minZ, maxZ); decayPlot.reAutoScale(); } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } } decayPlot.enableAction(); plotThread = null; } // -- WindowListener methods -- public void windowActivated(WindowEvent e) { } public void windowClosed(WindowEvent e) { } public void windowClosing(WindowEvent e) { System.exit(0); } public void windowDeactivated(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowOpened(WindowEvent e) { } // -- Helper methods -- /** Converts value in picoseconds to histogram bins. */ private float picoToBins(float pico) { return (timeBins - 1) * pico / timeRange / 1000; } /** Converts value in histogram bins to picoseconds. */ private float binsToPico(float bins) { return 1000 * timeRange * bins / (timeBins - 1); } /** Converts linear value to logarithm value. */ private float linearToLog(float v) { return (float) v >= 1 ? (float) Math.log(v) / BASE_LOG : 0; } private JPanel makeRadioPanel(String title, JRadioButton b1, JRadioButton b2) { JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); p.setBorder(new TitledBorder(title)); p.add(b1); p.add(b2); ButtonGroup group = new ButtonGroup(); group.add(b1); group.add(b2); b1.addActionListener(this); b2.addActionListener(this); return p; } private FieldImpl makeLines(FlatField surface) { try { // HACK - horrible conversion from aligned Gridded2DSet to ProductSet // probably could eliminate this by writing cleaner logic to convert // from 2D surface to 1D lines... Linear1DSet timeSet = new Linear1DSet(bType, 0, timeRange, timeBins, null, new Unit[] {bcUnits[0]}, null); int numChanVis = 0; for (int c=0; c<channels; c++) { if (cVisible[c]) numChanVis++; } float[][] cGrid = new float[1][numChanVis]; for (int c=0, cc=0; c<channels; c++) { if (!cVisible[c]) continue; cGrid[0][cc++] = channels > 1 ? c * (maxWave - minWave) / (channels - 1) + minWave : 0; } Gridded1DSet waveSet = new Gridded1DSet(cType, cGrid, numChanVis, null, new Unit[] {bcUnits[1]}, null, false); ProductSet prodSet = new ProductSet(new SampledSet[] {timeSet, waveSet}); float[][] samples = surface.getFloats(false); FunctionType ffType = (FunctionType) surface.getType(); surface = new FlatField(ffType, prodSet); surface.setSamples(samples, false); return (FieldImpl) surface.domainFactor(cType); } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } return null; } private void documentUpdate(DocumentEvent e) { Document doc = e.getDocument(); if (doc == zScaleValue.getDocument()) updateZAxis(); else updateColorScale(); // cMinValue or cMaxValue } private void updateZAxis() { float f = Float.NaN; try { f = Float.parseFloat(zScaleValue.getText()); } catch (NumberFormatException exc) { } if (f == f) plotData(false, true, false); } private void updateColorScale() { boolean manual = cOverride.isSelected(); float min = Float.NaN, max = Float.NaN; if (manual) { try { min = Float.parseFloat(cMinValue.getText()); } catch (NumberFormatException exc) { } try { max = Float.parseFloat(cMaxValue.getText()); } catch (NumberFormatException exc) { } } else { if (colorHeight.isSelected()) { min = 0; max = maxVal; } else { // colorTau.isSelected() min = tauMin; max = tauMax; } cMinValue.getDocument().removeDocumentListener(this); cMinValue.setText("" + min); cMinValue.getDocument().addDocumentListener(this); cMaxValue.getDocument().removeDocumentListener(this); cMaxValue.setText("" + max); cMaxValue.getDocument().addDocumentListener(this); } if (min == min && max == max && min < max) { try { vMap.setRange(min, max); } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } } } private void rescaleMinMax() { int min = minSlider.getValue(); int max = maxSlider.getValue(); try { intensityMap.setRange(min, max); } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } } // -- Utility methods -- /** Converts the given pixel coordinates to cursor coordinates. */ public static double[] pixelToCursor(DisplayImpl d, int x, int y) { if (d == null) return null; MouseBehavior mb = d.getDisplayRenderer().getMouseBehavior(); VisADRay ray = mb.findRay(x, y); return ray.position; } /** Converts the given cursor coordinates to domain coordinates. */ public static double[] cursorToDomain(DisplayImpl d, double[] cursor) { return cursorToDomain(d, null, cursor); } /** Converts the given cursor coordinates to domain coordinates. */ public static double[] cursorToDomain(DisplayImpl d, RealType[] types, double[] cursor) { if (d == null) return null; // locate x, y and z mappings Vector maps = d.getMapVector(); int numMaps = maps.size(); ScalarMap mapX = null, mapY = null, mapZ = null; for (int i=0; i<numMaps; i++) { if (mapX != null && mapY != null && mapZ != null) break; ScalarMap map = (ScalarMap) maps.elementAt(i); if (types == null) { DisplayRealType drt = map.getDisplayScalar(); if (drt.equals(Display.XAxis)) mapX = map; else if (drt.equals(Display.YAxis)) mapY = map; else if (drt.equals(Display.ZAxis)) mapZ = map; } else { ScalarType st = map.getScalar(); if (st.equals(types[0])) mapX = map; if (st.equals(types[1])) mapY = map; if (st.equals(types[2])) mapZ = map; } } // adjust for scale double[] scaleOffset = new double[2]; double[] dummy = new double[2]; double[] values = new double[3]; if (mapX == null) values[0] = Double.NaN; else { mapX.getScale(scaleOffset, dummy, dummy); values[0] = (cursor[0] - scaleOffset[1]) / scaleOffset[0]; } if (mapY == null) values[1] = Double.NaN; else { mapY.getScale(scaleOffset, dummy, dummy); values[1] = (cursor[1] - scaleOffset[1]) / scaleOffset[0]; } if (mapZ == null) values[2] = Double.NaN; else { mapZ.getScale(scaleOffset, dummy, dummy); values[2] = (cursor[2] - scaleOffset[1]) / scaleOffset[0]; } return values; } public static JTextField addRow(JPanel p, String label, double value, String unit) { p.add(new JLabel(label)); JTextField field = new JTextField(value == (int) value ? ("" + (int) value) : ("" + value), 8); JPanel fieldPane = new JPanel(); fieldPane.setLayout(new BorderLayout()); fieldPane.add(field, BorderLayout.CENTER); fieldPane.setBorder(new EmptyBorder(2, 3, 2, 3)); p.add(fieldPane); p.add(new JLabel(unit)); return field; } public static int parse(String s, int last) { try { return Integer.parseInt(s); } catch (NumberFormatException exc) { return last; } } public static float parse(String s, float last) { try { return Float.parseFloat(s); } catch (NumberFormatException exc) { return last; } } /** Updates progress monitor status; mainly for debugging. */ private static void setProgress(ProgressMonitor progress, int p) { progress.setProgress(p); } // -- Helper classes -- /** * A summed exponential function of the form: * y(t) = a1*e^(-b1*t) + ... + an*e^(-bn*t) + c. */ public class ExpFunction extends LMAFunction { /** Number of exponentials to fit. */ private int numExp = 1; /** Constructs a function with the given number of summed exponentials. */ public ExpFunction(int num) { numExp = num; } public double getY(double x, double[] a) { double sum = 0; for (int i=0; i<numExp; i++) { int e = 2 * i; sum += a[e] * Math.exp(-a[e + 1] * x); } sum += a[2 * numExp]; return sum; } public double getPartialDerivate(double x, double[] a, int parameterIndex) { if (parameterIndex == 2 * numExp) return 1; int e = parameterIndex / 2; int off = parameterIndex % 2; switch (off) { case 0: return Math.exp(-a[e + 1] * x); case 1: return -a[e] * x * Math.exp(-a[e + 1] * x); } throw new RuntimeException("No such parameter index: " + parameterIndex); } } /** * HACK - OutputStream extension for filtering out hardcoded * RuntimeException.printStackTrace() exceptions within LMA library. */ public class ConsoleStream extends PrintStream { private PrintStream ps; private boolean ignore; public ConsoleStream(OutputStream out) { super(out); ps = (PrintStream) out; } public void println(String s) { if (s.equals("java.lang.RuntimeException: Matrix is singular.")) { ignore = true; } else if (ignore && !s.startsWith("\tat ")) ignore = false; if (!ignore) super.println(s); } public void println(Object o) { String s = o.toString(); println(s); } } public final class TextTransfer implements ClipboardOwner { public void setClipboardContents(String value) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); if (clipboard != null) { clipboard.setContents(new StringSelection(value), this); } } public String getClipboardContents() { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); if (clipboard == null) return null; String result = null; Transferable contents = clipboard.getContents(null); boolean hasTransferableText = contents != null && contents.isDataFlavorSupported(DataFlavor.stringFlavor); if (hasTransferableText) { try { result = (String) contents.getTransferData(DataFlavor.stringFlavor); } catch (UnsupportedFlavorException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } return result; } public void lostOwnership(Clipboard clipboard, Transferable contents) { } } // -- Main method -- public static void main(String[] args) throws Exception { new SlimPlotter(args); } }
// SlimPlotter.java // Coded May - August 2006 by Curtis Rueden, for Long Yan and others. package loci.apps.slim; import jaolho.data.lma.LMA; import jaolho.data.lma.LMAFunction; import jaolho.data.lma.implementations.JAMAMatrix; import java.awt.*; import java.awt.event.*; import java.io.*; import java.rmi.RemoteException; import java.util.Arrays; import java.util.Vector; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.border.TitledBorder; import javax.swing.event.*; import loci.formats.DataTools; import loci.formats.ExtensionFileFilter; import loci.visbio.util.OutputConsole; import visad.*; import visad.bom.CurveManipulationRendererJ3D; import visad.java3d.*; public class SlimPlotter implements ActionListener, ChangeListener, DisplayListener, Runnable, WindowListener { // -- Constants -- /** Default orientation for decay curves display. */ private static final double[] MATRIX = { 0.2821, 0.1503, -0.0201, 0.0418, -0.0500, 0.1323, 0.2871, 0.1198, 0.1430, -0.2501, 0.1408, 0.0089, 0.0000, 0.0000, 0.0000, 1.0000 }; private static final char TAU = 'T'; // -- Fields -- /** Actual data values, dimensioned [channel][row][column][bin]. */ private int[][][][] values; // data parameters private int width, height; private int channels, timeBins; private double timeRange; private int minWave, waveStep; private boolean adjustPeaks; private int maxPeak; // ROI parameters private float[][] roiGrid; private boolean[][] roiMask; private UnionSet curveSet; private Irregular2DSet roiSet; private DataReferenceImpl roiRef; private int roiX, roiY; private int roiCount; private double roiPercent; private float maxVal; // GUI components for parameter dialog box private JDialog paramDialog; private JTextField wField, hField, tField, cField, trField, wlField, sField; private JCheckBox peaksBox; // GUI components for decay pane private JLabel decayLabel; private JRadioButton linear, log; private JRadioButton perspective, parallel; private JRadioButton dataSurface, dataLines; private JRadioButton fitSurface, fitLines; private JRadioButton resSurface, resLines; private JCheckBox showData, showLog; private JCheckBox showBox, showScale; private JCheckBox showFit, showResiduals; private JSpinner numCurves; private JSlider cSlider; // other GUI components private OutputConsole console; // VisAD objects private RealType cType; private FunctionType bcvFunc, bcvFuncFit, bcvFuncRes; private Linear2DSet bcSet; private ScalarMap zMap, zMapFit, zMapRes, vMap, vMapFit, vMapRes; private DataRenderer decayRend, fitRend, resRend; private DataReferenceImpl decayRef, fitRef, resRef; private DisplayImpl iPlot, decayPlot; private AnimationControl ac; // -- Constructor -- public SlimPlotter(String[] args) throws Exception { console = new OutputConsole("Log"); System.setErr(new ConsoleStream(new PrintStream(console))); ProgressMonitor progress = new ProgressMonitor(null, "Launching SlimPlotter", "Initializing", 0, 16 + 7); progress.setMillisToPopup(0); progress.setMillisToDecideToPopup(0); int p = 0; // parse command line arguments String filename = null; File file = null; if (args == null || args.length < 1) { JFileChooser jc = new JFileChooser(System.getProperty("user.dir")); jc.addChoosableFileFilter(new ExtensionFileFilter("sdt", "Becker & Hickl SPC-Image SDT")); int rval = jc.showOpenDialog(null); if (rval != JFileChooser.APPROVE_OPTION) { System.out.println("Please specify an SDT file."); System.exit(1); } file = jc.getSelectedFile(); filename = file.getPath(); } else { filename = args[0]; file = new File(filename); } width = height = timeBins = channels = -1; if (args.length >= 3) { width = parse(args[1], -1); height = parse(args[2], -1); } if (args.length >= 4) timeBins = parse(args[3], -1); if (args.length >= 5) channels = parse(args[4], -1); if (!file.exists()) { System.out.println("File does not exist: " + filename); System.exit(2); } // read SDT file header RandomAccessFile raf = new RandomAccessFile(file, "r"); short revision = DataTools.read2SignedBytes(raf, true); int infoOffset = DataTools.read4SignedBytes(raf, true); short infoLength = DataTools.read2SignedBytes(raf, true); int setupOffs = DataTools.read4SignedBytes(raf, true); short setupLength = DataTools.read2SignedBytes(raf, true); int dataBlockOffset = DataTools.read4SignedBytes(raf, true); short noOfDataBlocks = DataTools.read2SignedBytes(raf, true); int dataBlockLength = DataTools.read4SignedBytes(raf, true); int measDescBlockOffset = DataTools.read4SignedBytes(raf, true); short noOfMeasDescBlocks = DataTools.read2SignedBytes(raf, true); short measDescBlockLength = DataTools.read2SignedBytes(raf, true); int headerValid = DataTools.read2UnsignedBytes(raf, true); long reserved1 = DataTools.read4UnsignedBytes(raf, true); int reserved2 = DataTools.read2UnsignedBytes(raf, true); int chksum = DataTools.read2UnsignedBytes(raf, true); int offset = dataBlockOffset + 22; log("File length: " + file.length()); log("Data offset: " + offset); log("Setup offset: " + setupOffs); // read SDT setup block raf.seek(setupOffs); byte[] setupData = new byte[4095]; raf.readFully(setupData); String setup = new String(setupData); raf.close(); int leftToFind = 3; if (width < 0) { String wstr = "[SP_SCAN_X,I,"; int wndx = setup.indexOf(wstr); width = 128; if (wndx >= 0) { int q = setup.indexOf("]", wndx); if (q >= 0) { width = parse(setup.substring(wndx + wstr.length(), q), width); log("Got width from file: " + width); leftToFind } } } if (height < 0) { height = 128; String hstr = "[SP_SCAN_Y,I,"; int hndx = setup.indexOf(hstr); if (hndx >= 0) { int q = setup.indexOf("]", hndx); if (q >= 0) { height = parse(setup.substring(hndx + hstr.length(), q), height); log("Got height from file: " + height); leftToFind } } } if (timeBins < 0) { timeBins = 64; String tstr = "[SP_ADC_RE,I,"; int tndx = setup.indexOf(tstr); if (tndx >= 0) { int q = setup.indexOf("]", tndx); if (q >= 0) { timeBins = parse(setup.substring(tndx + tstr.length(), q), timeBins); log("Got timeBins from file: " + timeBins); leftToFind } } } if (channels < 0) { // autodetect number of channels based on file size channels = (int) ((file.length() - offset) / (2 * timeBins * width * height)); } timeRange = 12.5; minWave = 400; waveStep = 10; // warn user if some numbers were not found if (leftToFind > 0) { JOptionPane.showMessageDialog(null, "Some numbers (image width, image height, and number of time bins)\n" + "were not found within the file. The numbers you are about to see\n" + "are best guesses. Please change them if they are incorrect.", "SlimPlotter", JOptionPane.WARNING_MESSAGE); } // show dialog confirming data parameters paramDialog = new JDialog((Frame) null, "SlimPlotter", true); JPanel paramPane = new JPanel(); paramPane.setBorder(new EmptyBorder(10, 10, 10, 10)); paramDialog.setContentPane(paramPane); paramPane.setLayout(new GridLayout(10, 3)); wField = addRow(paramPane, "Image width", width, "pixels"); hField = addRow(paramPane, "Image height", height, "pixels"); tField = addRow(paramPane, "Time bins", timeBins, ""); cField = addRow(paramPane, "Channel count", channels, ""); trField = addRow(paramPane, "Time range", timeRange, "nanoseconds"); wlField = addRow(paramPane, "Starting wavelength", minWave, "nanometers"); sField = addRow(paramPane, "Channel width", waveStep, "nanometers"); JButton ok = new JButton("OK"); paramDialog.getRootPane().setDefaultButton(ok); ok.addActionListener(this); // row 8 peaksBox = new JCheckBox("Align peaks", true); paramPane.add(peaksBox); paramPane.add(new JLabel()); paramPane.add(new JLabel()); // row 9 paramPane.add(new JLabel()); paramPane.add(new JLabel()); paramPane.add(new JLabel()); // row 10 paramPane.add(new JLabel()); paramPane.add(ok); paramDialog.pack(); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension ps = paramDialog.getSize(); paramDialog.setLocation((screenSize.width - ps.width) / 2, (screenSize.height - ps.height) / 2); paramDialog.setVisible(true); int maxWave = minWave + (channels - 1) * waveStep; roiCount = width * height; roiPercent = 100; // read pixel data progress.setMaximum(adjustPeaks ? (channels * height + 2 * channels + 9) : (channels * height + 7)); progress.setNote("Reading data"); DataInputStream fin = new DataInputStream(new FileInputStream(file)); fin.skipBytes(offset); // skip to data byte[] data = new byte[2 * channels * height * width * timeBins]; fin.readFully(data); fin.close(); progress.setProgress(++p); if (progress.isCanceled()) System.exit(0); // create types progress.setNote("Creating types"); RealType xType = RealType.getRealType("element"); RealType yType = RealType.getRealType("line"); ScaledUnit ns = new ScaledUnit(1e-9, SI.second, "ns"); ScaledUnit nm = new ScaledUnit(1e-9, SI.meter, "nm"); RealType bType = RealType.getRealType("bin", ns); cType = RealType.getRealType("channel", nm); RealType vType = RealType.getRealType("value"); RealTupleType xy = new RealTupleType(xType, yType); FunctionType xyvFunc = new FunctionType(xy, vType); Integer2DSet xySet = new Integer2DSet(xy, width, height); FunctionType cxyvFunc = new FunctionType(cType, xyvFunc); Linear1DSet cSet = new Linear1DSet(cType, minWave, maxWave, channels, null, new Unit[] {nm}, null); RealTupleType bc = new RealTupleType(bType, cType); bcvFunc = new FunctionType(bc, vType); bcSet = new Linear2DSet(bc, 0, timeRange, timeBins, minWave, maxWave, channels, null, new Unit[] {ns, nm}, null); RealType vTypeFit = RealType.getRealType("value_fit"); bcvFuncFit = new FunctionType(bc, vTypeFit); RealType vTypeRes = RealType.getRealType("value_res"); bcvFuncRes = new FunctionType(bc, vTypeRes); progress.setProgress(++p); if (progress.isCanceled()) System.exit(0); // plot intensity data in 2D display progress.setNote("Building displays"); iPlot = new DisplayImplJ3D("intensity", new TwoDDisplayRendererJ3D()); iPlot.getMouseBehavior().getMouseHelper().setFunctionMap(new int[][][] { {{MouseHelper.DIRECT, MouseHelper.NONE}, // L, shift-L {MouseHelper.NONE, MouseHelper.NONE}}, // ctrl-L, ctrl-shift-L {{MouseHelper.CURSOR_TRANSLATE, MouseHelper.CURSOR_ZOOM}, // M, shift-M {MouseHelper.CURSOR_ROTATE, MouseHelper.NONE}}, // ctrl-M, ctrl-shift-M {{MouseHelper.ROTATE, MouseHelper.ZOOM}, // R, shift-R {MouseHelper.TRANSLATE, MouseHelper.NONE}}, // ctrl-R, ctrl-shift-R }); iPlot.enableEvent(DisplayEvent.MOUSE_DRAGGED); iPlot.addDisplayListener(this); iPlot.addMap(new ScalarMap(xType, Display.XAxis)); iPlot.addMap(new ScalarMap(yType, Display.YAxis)); iPlot.addMap(new ScalarMap(vType, Display.RGB)); iPlot.addMap(new ScalarMap(cType, Display.Animation)); DataReferenceImpl intensityRef = new DataReferenceImpl("intensity"); iPlot.addReference(intensityRef); // set up curve manipulation renderer in 2D display roiGrid = new float[2][width * height]; roiMask = new boolean[height][width]; for (int h=0; h<height; h++) { for (int w=0; w<width; w++) { int ndx = h * width + w; roiGrid[0][ndx] = w; roiGrid[1][ndx] = h; roiMask[h][w] = true; } } final DataReferenceImpl curveRef = new DataReferenceImpl("curve"); UnionSet dummyCurve = new UnionSet(xy, new Gridded2DSet[] { new Gridded2DSet(xy, new float[][] {{0}, {0}}, 1) }); curveRef.setData(dummyCurve); CurveManipulationRendererJ3D curve = new CurveManipulationRendererJ3D(0, 0, true); iPlot.addReferences(curve, curveRef); CellImpl cell = new CellImpl() { public void doAction() throws VisADException, RemoteException { // save latest drawn curve curveSet = (UnionSet) curveRef.getData(); } }; cell.addReference(curveRef); roiRef = new DataReferenceImpl("roi"); roiRef.setData(new Real(0)); // dummy iPlot.addReference(roiRef, new ConstantMap[] { new ConstantMap(0, Display.Blue), new ConstantMap(0.1, Display.Alpha) }); ac = (AnimationControl) iPlot.getControl(AnimationControl.class); iPlot.getProjectionControl().setMatrix( iPlot.make_matrix(0, 0, 0, 0.85, 0, 0, 0)); progress.setProgress(++p); if (progress.isCanceled()) System.exit(0); // plot decay curves in 3D display decayPlot = new DisplayImplJ3D("decay"); ScalarMap xMap = new ScalarMap(bType, Display.XAxis); ScalarMap yMap = new ScalarMap(cType, Display.YAxis); zMap = new ScalarMap(vType, Display.ZAxis); zMapFit = new ScalarMap(vTypeFit, Display.ZAxis); zMapRes = new ScalarMap(vTypeRes, Display.ZAxis); vMap = new ScalarMap(vType, Display.RGB); //vMapFit = new ScalarMap(vTypeFit, Display.RGB); vMapRes = new ScalarMap(vTypeRes, Display.RGB); decayPlot.addMap(xMap); decayPlot.addMap(yMap); decayPlot.addMap(zMap); decayPlot.addMap(zMapFit); decayPlot.addMap(zMapRes); decayPlot.addMap(vMap); //decayPlot.addMap(vMapFit); decayPlot.addMap(vMapRes); decayRend = new DefaultRendererJ3D(); decayRef = new DataReferenceImpl("decay"); decayPlot.addReferences(decayRend, decayRef); if (adjustPeaks) { fitRend = new DefaultRendererJ3D(); fitRef = new DataReferenceImpl("fit"); decayPlot.addReferences(fitRend, fitRef, new ConstantMap[] { new ConstantMap(1.0, Display.Red), new ConstantMap(1.0, Display.Green), new ConstantMap(1.0, Display.Blue) }); fitRend.toggle(false); resRend = new DefaultRendererJ3D(); resRef = new DataReferenceImpl("residuals"); decayPlot.addReferences(resRend, resRef); resRend.toggle(false); } xMap.setRange(0, timeRange); yMap.setRange(minWave, maxWave); AxisScale xScale = xMap.getAxisScale(); Font font = Font.decode("serif 24"); xScale.setFont(font); xScale.setTitle("Time (ns)"); xScale.setSnapToBox(true); AxisScale yScale = yMap.getAxisScale(); yScale.setFont(font); yScale.setTitle("Wavelength (nm)"); yScale.setSide(AxisScale.SECONDARY); yScale.setSnapToBox(true); AxisScale zScale = zMap.getAxisScale(); zScale.setFont(font); zScale.setTitle("Count"); zScale.setSnapToBox(true); // workaround for weird axis spacing issue zMapFit.getAxisScale().setVisible(false); zMapRes.getAxisScale().setVisible(false); GraphicsModeControl gmc = decayPlot.getGraphicsModeControl(); gmc.setScaleEnable(true); gmc.setTextureEnable(false); ProjectionControl pc = decayPlot.getProjectionControl(); pc.setMatrix(MATRIX); pc.setAspectCartesian( new double[] {2, 1, 1}); progress.setProgress(++p); if (progress.isCanceled()) System.exit(0); // convert byte data to unsigned shorts progress.setNote("Constructing images "); values = new int[channels][height][width][timeBins]; float[][][] pix = new float[channels][1][width * height]; FieldImpl field = new FieldImpl(cxyvFunc, cSet); int max = 0; int maxChan = 0; for (int c=0; c<channels; c++) { int oc = timeBins * width * height * c; for (int h=0; h<height; h++) { progress.setProgress(++p); if (progress.isCanceled()) System.exit(0); int oh = timeBins * width * h; for (int w=0; w<width; w++) { int ow = timeBins * w; int sum = 0; for (int t=0; t<timeBins; t++) { int ndx = 2 * (oc + oh + ow + t); int val = DataTools.bytesToInt(data, ndx, 2, true); if (val > max) { max = val; maxChan = c; } values[c][h][w][t] = val; sum += val; } pix[c][0][width * h + w] = sum; } } FlatField ff = new FlatField(xyvFunc, xySet); ff.setSamples(pix[c], false); field.setSample(c, ff); } progress.setProgress(++p); if (progress.isCanceled()) System.exit(0); // adjust peaks if (adjustPeaks) { progress.setNote("Adjusting peaks "); int[] peaks = new int[channels]; for (int c=0; c<channels; c++) { progress.setProgress(++p); if (progress.isCanceled()) System.exit(0); int[] sum = new int[timeBins]; for (int h=0; h<height; h++) { for (int w=0; w<width; w++) { for (int t=0; t<timeBins; t++) sum[t] += values[c][h][w][t]; } } int peak = 0, ndx = 0; for (int t=0; t<timeBins; t++) { if (peak <= sum[t]) { peak = sum[t]; ndx = t; } else if (t > 20) break; // HACK - too early to give up } peaks[c] = ndx; } progress.setProgress(++p); if (progress.isCanceled()) System.exit(0); maxPeak = 0; for (int c=1; c<channels; c++) { if (maxPeak < peaks[c]) maxPeak = peaks[c]; } log("Aligning peaks to tmax = " + maxPeak); for (int c=0; c<channels; c++) { progress.setProgress(++p); if (progress.isCanceled()) System.exit(0); int shift = maxPeak - peaks[c]; if (shift > 0) { for (int h=0; h<height; h++) { for (int w=0; w<width; w++) { for (int t=timeBins-1; t>=shift; t values[c][h][w][t] = values[c][h][w][t - shift]; } for (int t=shift-1; t>=0; t--) values[c][h][w][t] = 0; } } log("\tChannel #" + (c + 1) + ": tmax = " + peaks[c] + " (shifting by " + shift + ")"); } } progress.setProgress(++p); if (progress.isCanceled()) System.exit(0); // add yellow line to indicate adjusted peak position DataReferenceImpl peakRef = new DataReferenceImpl("peaks"); float peakTime = (float) (maxPeak * timeRange / timeBins); peakRef.setData(new Gridded2DSet(bc, new float[][] {{peakTime, peakTime}, {minWave, maxWave}}, 2)); decayPlot.addReference(peakRef, new ConstantMap[] { new ConstantMap(-1, Display.ZAxis), new ConstantMap(0, Display.Blue), // new ConstantMap(2, Display.LineWidth) }); } // construct 2D window progress.setNote("Creating plots"); JFrame intensityFrame = new JFrame("Intensity Data - " + file.getName()); intensityFrame.addWindowListener(this); JPanel intensityPane = new JPanel(); intensityPane.setLayout(new BorderLayout()); intensityPane.add(iPlot.getComponent(), BorderLayout.CENTER); cSlider = new JSlider(1, channels, 1); cSlider.setSnapToTicks(true); cSlider.setMajorTickSpacing(channels / 4); cSlider.setMinorTickSpacing(1); cSlider.setPaintTicks(true); cSlider.addChangeListener(this); cSlider.setBorder(new EmptyBorder(8, 5, 8, 5)); intensityPane.add(cSlider, BorderLayout.SOUTH); intensityFrame.setContentPane(intensityPane); intensityRef.setData(field); ColorControl cc = (ColorControl) iPlot.getControl(ColorControl.class); cc.setTable(ColorControl.initTableGreyWedge(new float[3][256])); progress.setProgress(++p); if (progress.isCanceled()) System.exit(0); // construct 3D window JFrame decayFrame = new JFrame("Spectral Lifetime Data - " + file.getName()); decayFrame.addWindowListener(this); JPanel decayPane = new JPanel(); decayPane.setLayout(new BorderLayout()); decayPane.add(decayPlot.getComponent(), BorderLayout.CENTER); decayLabel = new JLabel("Decay curve for all pixels"); decayPane.add(decayLabel, BorderLayout.NORTH); JPanel options = new JPanel(); options.setBorder(new EmptyBorder(8, 5, 8, 5)); options.setLayout(new BoxLayout(options, BoxLayout.X_AXIS)); linear = new JRadioButton("Linear", true); log = new JRadioButton("Log", false); perspective = new JRadioButton("Perspective", true); parallel = new JRadioButton("Parallel", false); dataSurface = new JRadioButton("Surface", true); dataLines = new JRadioButton("Lines", false); fitSurface = new JRadioButton("Surface", false); fitLines = new JRadioButton("Lines", true); resSurface = new JRadioButton("Surface", false); resLines = new JRadioButton("Lines", true); JPanel showPanel = new JPanel(); showPanel.setBorder(new TitledBorder("Show")); showPanel.setLayout(new BoxLayout(showPanel, BoxLayout.X_AXIS)); JPanel showPanel1 = new JPanel(); showPanel1.setLayout(new BoxLayout(showPanel1, BoxLayout.Y_AXIS)); showPanel.add(showPanel1); JPanel showPanel2 = new JPanel(); showPanel2.setLayout(new BoxLayout(showPanel2, BoxLayout.Y_AXIS)); showPanel.add(showPanel2); JPanel showPanel3 = new JPanel(); showPanel3.setLayout(new BoxLayout(showPanel3, BoxLayout.Y_AXIS)); showPanel.add(showPanel3); showData = new JCheckBox("Data", true); showData.addActionListener(this); showPanel1.add(showData); showLog = new JCheckBox("Log", true); showLog.addActionListener(this); showPanel1.add(showLog); showBox = new JCheckBox("Box", true); showBox.addActionListener(this); showPanel2.add(showBox); showScale = new JCheckBox("Scale", true); showScale.addActionListener(this); showPanel2.add(showScale); showFit = new JCheckBox("Fit", false); showFit.setEnabled(adjustPeaks); showFit.addActionListener(this); showPanel3.add(showFit); showResiduals = new JCheckBox("Residuals", false); showResiduals.setEnabled(adjustPeaks); showResiduals.addActionListener(this); showPanel3.add(showResiduals); numCurves = new JSpinner(new SpinnerNumberModel(1, 1, 9, 1)); numCurves.setMaximumSize(numCurves.getPreferredSize()); numCurves.addChangeListener(this); console.getWindow().addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { showLog.setSelected(false); } }); options.add(makeRadioPanel("Scale", linear, log)); options.add(makeRadioPanel("Projection", perspective, parallel)); options.add(makeRadioPanel("Data", dataSurface, dataLines)); options.add(makeRadioPanel("Fit", fitSurface, fitLines)); options.add(makeRadioPanel("Residuals", resSurface, resLines)); options.add(showPanel); // options.add(numCurves); decayPane.add(options, BorderLayout.SOUTH); decayFrame.setContentPane(decayPane); // adjust window sizes intensityFrame.pack(); int intensityWidth = intensityFrame.getSize().width; int intensityHeight = intensityFrame.getSize().height; if (intensityWidth < 400) { // enforce minimum reasonable width intensityHeight = 400 * intensityHeight / intensityWidth; intensityWidth = 400; } int decayHeight = intensityHeight; int decayWidth = 100 * decayHeight / 100; // 100% of width // enlarge 3D window to fill more of the screen int padWidth = 30, padHeight = 70; int pw = padWidth / 2, ph = padHeight / 2; int availWidth = screenSize.width - intensityWidth - padWidth; int availHeight = screenSize.height - padHeight; int growWidth = availWidth - decayWidth; int growHeight = availHeight - decayHeight; int grow = growWidth < growHeight ? growWidth : growHeight; if (grow > 0) { decayWidth += grow; decayHeight += grow; } // widen 2D window to fill any leftover space grow = screenSize.width - intensityWidth - decayWidth - padWidth; intensityWidth += grow; intensityHeight += grow; decayFrame.setBounds(pw + intensityWidth, ph, decayWidth, decayHeight); intensityFrame.setBounds(pw, ph, intensityWidth, intensityHeight); // adjust console window to match console.getWindow().setBounds(pw, ph + intensityHeight, intensityWidth, decayHeight - intensityHeight); // show windows on screen intensityFrame.setVisible(true); decayFrame.setVisible(true); console.setVisible(true); progress.setProgress(++p); progress.close(); plotData(true, true); try { Thread.sleep(200); } catch (InterruptedException exc) { exc.printStackTrace(); } cSlider.setValue(maxChan + 1); } // -- SlimPlotter methods -- private Thread plotThread; private boolean plotCanceled; private boolean rescale, refit; /** Plots the data in a separate thread. */ public void plotData(boolean rescale, boolean refit) { final boolean doRescale = rescale; final boolean doRefit = refit; final SlimPlotter sp = this; new Thread("PlotSpawner") { public void run() { synchronized (sp) { if (plotThread != null) { // wait for old thread to cancel out plotCanceled = true; try { plotThread.join(); } catch (InterruptedException exc) { exc.printStackTrace(); } } sp.rescale = doRescale; sp.refit = doRefit; plotCanceled = false; plotThread = new Thread(sp, "Plotter"); plotThread.start(); } } }.start(); } /** Handles cursor updates. */ public void doCursor(double[] cursor, boolean rescale, boolean refit) { double[] domain = cursorToDomain(iPlot, cursor); roiX = (int) Math.round(domain[0]); roiY = (int) Math.round(domain[1]); if (roiX < 0) roiX = 0; if (roiX >= width) roiX = width - 1; if (roiY < 0) roiY = 0; if (roiY >= height) roiY = height - 1; roiCount = 1; plotData(rescale, refit); } /** Logs the given output to the appropriate location. */ public void log(String msg) { final String message = msg; SwingUtilities.invokeLater(new Runnable() { public void run() { System.err.println(message); } }); } // -- ActionListener methods -- /** Handles checkbox and button presses. */ public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if (src == dataSurface || src == dataLines) plotData(false, false); else if (src == fitSurface || src == fitLines || src == resSurface || src == resLines) { plotData(false, true); } else if (src == linear || src == log) plotData(true, true); else if (src == perspective || src == parallel) { try { decayPlot.getGraphicsModeControl().setProjectionPolicy( parallel.isSelected() ? DisplayImplJ3D.PARALLEL_PROJECTION : DisplayImplJ3D.PERSPECTIVE_PROJECTION); } catch (Exception exc) { exc.printStackTrace(); } } else if (src == showData) { decayRend.toggle(showData.isSelected()); } else if (src == showLog) { console.setVisible(showLog.isSelected()); } else if (src == showBox) { try { decayPlot.getDisplayRenderer().setBoxOn(showBox.isSelected()); } catch (Exception exc) { exc.printStackTrace(); } } else if (src == showScale) { try { boolean scale = showScale.isSelected(); decayPlot.getGraphicsModeControl().setScaleEnable(scale); } catch (Exception exc) { exc.printStackTrace(); } } else if (src == showFit) { fitRend.toggle(showFit.isSelected()); } else if (src == showResiduals) { resRend.toggle(showResiduals.isSelected()); } else { // OK button width = parse(wField.getText(), width); height = parse(hField.getText(), height); timeBins = parse(tField.getText(), timeBins); channels = parse(cField.getText(), channels); timeRange = parse(trField.getText(), timeRange); minWave = parse(wlField.getText(), minWave); waveStep = parse(sField.getText(), waveStep); adjustPeaks = peaksBox.isSelected(); paramDialog.setVisible(false); } } // -- ChangeListener methods -- /** Handles slider changes. */ public void stateChanged(ChangeEvent e) { Object src = e.getSource(); if (src == cSlider) { int c = cSlider.getValue(); try { ac.setCurrent(c - 1); } catch (Exception exc) { exc.printStackTrace(); } } else if (src == numCurves) plotData(false, true); } // -- DisplayListener methods -- private boolean drag = false; public void displayChanged(DisplayEvent e) { int id = e.getId(); if (id == DisplayEvent.MOUSE_PRESSED_CENTER) { drag = true; decayPlot.getDisplayRenderer(); doCursor(iPlot.getDisplayRenderer().getCursor(), false, false); } else if (id == DisplayEvent.MOUSE_RELEASED_CENTER) { drag = false; doCursor(iPlot.getDisplayRenderer().getCursor(), true, true); } else if (id == DisplayEvent.MOUSE_RELEASED_LEFT) { // done drawing curve try { roiSet = DelaunayCustom.fillCheck(curveSet, false); if (roiSet == null) { roiRef.setData(new Real(0)); doCursor(pixelToCursor(iPlot, e.getX(), e.getY()), true, true); iPlot.reAutoScale(); } else { roiRef.setData(roiSet); int[] tri = roiSet.valueToTri(roiGrid); roiX = roiY = 0; roiCount = 0; for (int h=0; h<height; h++) { for (int w=0; w<width; w++) { int ndx = h * width + w; roiMask[h][w] = tri[ndx] >= 0; if (roiMask[h][w]) { roiX = w; roiY = h; roiCount++; } } } roiPercent = 100000 * roiCount / (width * height) / 1000.0; plotData(true, true); } } catch (VisADException exc) { String msg = exc.getMessage(); if ("path self intersects".equals(msg)) { JOptionPane.showMessageDialog(null, "Please draw a curve that does not intersect itself.", "SlimPlotter", JOptionPane.ERROR_MESSAGE); } else exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } } else if (id == DisplayEvent.MOUSE_DRAGGED) { if (!drag) return; // not a center mouse drag doCursor(iPlot.getDisplayRenderer().getCursor(), false, false); } } // -- Runnable methods -- public void run() { ProgressMonitor progress = new ProgressMonitor(null, "Plotting data", "Calculating sums", 0, channels * timeBins + (refit ? channels : 0) + 1); progress.setMillisToPopup(100); progress.setMillisToDecideToPopup(50); int p = 0; if (roiCount == 1) { decayLabel.setText("Decay curve for " + "(" + roiX + ", " + roiY + ")"); } else { decayLabel.setText("Decay curve for " + roiCount + " pixels (" + roiPercent + "%)"); } boolean doDataLines = dataLines.isSelected(); boolean doFitLines = fitLines.isSelected(); boolean doResLines = resLines.isSelected(); boolean doLog = log.isSelected(); // calculate samples float[] samps = new float[channels * timeBins]; maxVal = 0; for (int c=0; c<channels; c++) { for (int t=0; t<timeBins; t++) { int ndx = timeBins * c + t; int sum = 0; if (roiCount == 1) sum = values[c][roiY][roiX][t]; else { for (int h=0; h<height; h++) { for (int w=0; w<width; w++) { if (roiMask[h][w]) sum += values[c][h][w][t]; } } } samps[ndx] = sum; if (doLog) samps[ndx] = (float) Math.log(samps[ndx] + 1); if (samps[ndx] > maxVal) maxVal = samps[ndx]; progress.setProgress(++p); if (progress.isCanceled()) plotCanceled = true; if (plotCanceled) break; } if (plotCanceled) break; } double[][] fitResults = null; int numExp = ((Integer) numCurves.getValue()).intValue(); if (adjustPeaks && refit) { // perform exponential curve fitting: y(x) = a * e^(-b*t) + c progress.setNote("Fitting curves"); fitResults = new double[channels][]; ExpFunction func = new ExpFunction(numExp); float[] params = new float[3 * numExp]; for (int i=0; i<numExp; i++) { // initial guess for (a, b, c) int e = 3 * i; params[e] = (numExp - i) * maxVal / (numExp + 1); params[e + 1] = 1; params[e + 2] = 0; } int num = timeBins - maxPeak; float[] xVals = new float[num]; for (int i=0; i<num; i++) xVals[i] = i; float[] yVals = new float[num]; float[] weights = new float[num]; Arrays.fill(weights, 1); // no weighting log("Computing fit parameters: y(t) = a * e^(-t/" + TAU + ") + c"); for (int c=0; c<channels; c++) { log("\tChannel #" + (c + 1) + ":"); System.arraycopy(samps, timeBins * c + maxPeak, yVals, 0, num); LMA lma = null; lma = new LMA(func, params, new float[][] {xVals, yVals}, weights, new JAMAMatrix(params.length, params.length)); lma.fit(); log("\t\titerations=" + lma.iterationCount); log("\t\tchi2=" + lma.chi2); for (int i=0; i<numExp; i++) { int e = 3 * i; log("\t\ta" + i + "=" + lma.parameters[e]); log("\t\t" + TAU + i + "=" + (1 / lma.parameters[e + 1])); log("\t\tc" + i + "=" + lma.parameters[e + 2]); } fitResults[c] = lma.parameters; progress.setProgress(++p); } } try { // construct "Data" plot FlatField ff = new FlatField(bcvFunc, bcSet); ff.setSamples(new float[][] {samps}, false); decayRef.setData(doDataLines ? ff.domainFactor(cType) : ff); if (fitResults != null) { // compute finite sampling matching fitted exponentials float[] fitSamps = new float[channels * timeBins]; float[] residuals = new float[channels * timeBins]; for (int c=0; c<channels; c++) { double[] q = fitResults[c]; for (int t=0; t<timeBins; t++) { int ndx = timeBins * c + t; int et = t - maxPeak; // adjust for peak alignment if (et < 0) fitSamps[ndx] = residuals[ndx] = 0; else { float sum = 0; for (int i=0; i<numExp; i++) { int e = 3 * i; sum += (float) (q[e] * Math.exp(-q[e + 1] * et) + q[e + 2]); } fitSamps[ndx] = sum; residuals[ndx] = samps[ndx] - fitSamps[ndx]; } } } // construct "Fit" plot FlatField fit = new FlatField(bcvFuncFit, bcSet); fit.setSamples(new float[][] {fitSamps}, false); fitRef.setData(doFitLines ? fit.domainFactor(cType) : fit); // construct "Residuals" plot FlatField res = new FlatField(bcvFuncRes, bcSet); res.setSamples(new float[][] {residuals}, false); resRef.setData(doResLines ? res.domainFactor(cType) : res); } if (rescale) { float max = maxVal == 0 ? 1 : maxVal; zMap.setRange(0, max); zMapFit.setRange(0, max); zMapRes.setRange(0, max); vMap.setRange(0, max); //vMapFit.setRange(0, max); //vMapRes.setRange(0, max); //decayPlot.reAutoScale(); } } catch (Exception exc) { exc.printStackTrace(); } progress.setProgress(++p); progress.close(); plotThread = null; } // -- WindowListener methods -- public void windowActivated(WindowEvent e) { } public void windowClosed(WindowEvent e) { } public void windowClosing(WindowEvent e) { System.exit(0); } public void windowDeactivated(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowOpened(WindowEvent e) { } // -- Helper methods -- private JPanel makeRadioPanel(String title, JRadioButton b1, JRadioButton b2) { JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); p.setBorder(new TitledBorder(title)); p.add(b1); p.add(b2); ButtonGroup group = new ButtonGroup(); group.add(b1); group.add(b2); b1.addActionListener(this); b2.addActionListener(this); return p; } // -- Utility methods -- /** Converts the given pixel coordinates to cursor coordinates. */ public static double[] pixelToCursor(DisplayImpl d, int x, int y) { if (d == null) return null; MouseBehavior mb = d.getDisplayRenderer().getMouseBehavior(); VisADRay ray = mb.findRay(x, y); return ray.position; } /** Converts the given cursor coordinates to domain coordinates. */ public static double[] cursorToDomain(DisplayImpl d, double[] cursor) { return cursorToDomain(d, null, cursor); } /** Converts the given cursor coordinates to domain coordinates. */ public static double[] cursorToDomain(DisplayImpl d, RealType[] types, double[] cursor) { if (d == null) return null; // locate x, y and z mappings Vector maps = d.getMapVector(); int numMaps = maps.size(); ScalarMap mapX = null, mapY = null, mapZ = null; for (int i=0; i<numMaps; i++) { if (mapX != null && mapY != null && mapZ != null) break; ScalarMap map = (ScalarMap) maps.elementAt(i); if (types == null) { DisplayRealType drt = map.getDisplayScalar(); if (drt.equals(Display.XAxis)) mapX = map; else if (drt.equals(Display.YAxis)) mapY = map; else if (drt.equals(Display.ZAxis)) mapZ = map; } else { ScalarType st = map.getScalar(); if (st.equals(types[0])) mapX = map; if (st.equals(types[1])) mapY = map; if (st.equals(types[2])) mapZ = map; } } // adjust for scale double[] scaleOffset = new double[2]; double[] dummy = new double[2]; double[] values = new double[3]; if (mapX == null) values[0] = Double.NaN; else { mapX.getScale(scaleOffset, dummy, dummy); values[0] = (cursor[0] - scaleOffset[1]) / scaleOffset[0]; } if (mapY == null) values[1] = Double.NaN; else { mapY.getScale(scaleOffset, dummy, dummy); values[1] = (cursor[1] - scaleOffset[1]) / scaleOffset[0]; } if (mapZ == null) values[2] = Double.NaN; else { mapZ.getScale(scaleOffset, dummy, dummy); values[2] = (cursor[2] - scaleOffset[1]) / scaleOffset[0]; } return values; } public static JTextField addRow(JPanel p, String label, double value, String unit) { p.add(new JLabel(label)); JTextField field = new JTextField(value == (int) value ? ("" + (int) value) : ("" + value), 8); JPanel fieldPane = new JPanel(); fieldPane.setLayout(new BorderLayout()); fieldPane.add(field, BorderLayout.CENTER); fieldPane.setBorder(new EmptyBorder(2, 3, 2, 3)); p.add(fieldPane); p.add(new JLabel(unit)); return field; } public static int parse(String s, int last) { try { return Integer.parseInt(s); } catch (NumberFormatException exc) { return last; } } public static double parse(String s, double last) { try { return Double.parseDouble(s); } catch (NumberFormatException exc) { return last; } } // -- Helper classes -- public class ExpFunction extends LMAFunction { /** Number of exponentials to fit. */ public int numExp = 1; /** Constructs a function with the given number of summed exponentials. */ public ExpFunction(int num) { numExp = num; } public double getY(double x, double[] a) { double sum = 0; for (int i=0; i<numExp; i++) { int e = 3 * i; sum += a[e] * Math.exp(-a[e + 1] * x) + a[e + 2]; } return sum; } public double getPartialDerivate(double x, double[] a, int parameterIndex) { int e = parameterIndex / 3; int off = parameterIndex % 3; switch (off) { case 0: return Math.exp(-a[e + 1] * x); case 1: return -a[e] * x * Math.exp(-a[e + 1] * x); case 2: return 1; } throw new RuntimeException("No such parameter index: " + parameterIndex); } } /** * HACK - OutputStream extension for filtering out hardcoded * RuntimeException.printStackTrace() exceptions within LMA library. */ public class ConsoleStream extends PrintStream { private PrintStream ps; private boolean ignore; public ConsoleStream(OutputStream out) { super(out); ps = (PrintStream) out; } public void println(String s) { if (s.equals("java.lang.RuntimeException: Matrix is singular.")) { ignore = true; } else if (ignore && !s.startsWith("\tat ")) ignore = false; if (!ignore) super.println(s); } public void println(Object o) { String s = o.toString(); println(s); } } // -- Main method -- public static void main(String[] args) throws Exception { new SlimPlotter(args); } }
package org.ctoolkit.services.task; import com.google.appengine.api.taskqueue.DeferredTask; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.inject.Injector; import com.googlecode.objectify.Key; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.inject.Inject; import java.io.Serializable; import java.util.Objects; import java.util.function.Function; import static com.google.common.base.Preconditions.checkNotNull; import static com.googlecode.objectify.ObjectifyService.ofy; /** * The task, a standalone job definition to be executed asynchronously. Task represents a small, discrete unit of work. * * <b>Vocabulary:</b> * <ul> * <li><b>Entity Key:</b> represents an identification of an entity to work with</li> * <li><b>Task Name:</b> a name of the job, composition of the name prefix and entity Key. * If name prefix is not defined, task name will be auto generated by the App Engine. * Task Name appears in the Google Cloud Console.</li> * <li><b>Make Unique:</b> as task name must be unique at least for 9 days, set this property {@code true} * to append an unique ID to customized task name. By default value is {@code true}</li> * <li><b>Queue name:</b> a queue defined by the execution environment where task will be placed in.</li> * </ul> * * <b>Note:</b> Queue, and task names must be a combination of one or more digits, letters a-z, underscores, and/or dashes, * satisfying the following regular expression: * [0-9a-zA-Z\-\_]+ * * <b>Naming a task</b> * When you create a new task, App Engine assigns the task a unique name by default. However, you can assign your * own name to a task by using the name parameters (Task Name, Entity Key, Make Unique). An advantage of assigning * your own task names is that named tasks are de-duplicated, which means you can use task names to guarantee * that a task is only added once. De-duplication continues for 9 days after the task is completed or deleted. * <p> * Note that de-duplication logic introduces significant performance overhead, resulting in increased latencies and * potentially increased error rates associated with named tasks. These costs can be magnified significantly * if task names are sequential, such as with timestamps. So, if you assign your own names, we recommend * using a well-distributed prefix for task names, such as a hash of the contents. * * @param <T> the type of the entity key and related entity * @author <a href="mailto:aurel.medvegy@ctoolkit.org">Aurel Medvegy</a> * @see TaskExecutor */ @SuppressWarnings( "WeakerAccess" ) public abstract class Task<T> implements DeferredTask { private static final long serialVersionUID = -3959632462820157604L; private static final Logger logger = LoggerFactory.getLogger( Task.class ); @Inject private static Injector injector; @Inject private transient TaskExecutor executor; private Key<T> entityKey; private String namePrefix; private boolean makeUnique; private Task next; private SerializableFunction<Object, Boolean> function; private String queueName; private TaskOptions options; private Integer postponeFor; /** * Creates a task with an auto generated name (by App Engine). Placed to the default queue. */ public Task() { // for null name prefix the task name will be generated by App Engine this( null, true, Queue.DEFAULT_QUEUE ); } /** * Creates task with given name prefix incl. unique ID to be appended. Placed to the default queue. * * @param namePrefix the task name prefix */ public Task( @Nonnull String namePrefix ) { this( namePrefix, true ); } /** * Creates task with given name prefix. Placed to the default queue. * * @param namePrefix the name prefix * @param makeUnique true to append unique ID to the task name prefix */ public Task( @Nonnull String namePrefix, boolean makeUnique ) { this( checkNotNull( namePrefix ), makeUnique, Queue.DEFAULT_QUEUE ); } /** * Creates task with specified name prefix and queue names. * Note, the unique ID will be applied only for non null name prefix. * * @param namePrefix the optional name prefix, {@code null} to be auto generated by App Engine * @param makeUnique true to append unique ID to the task name prefix * @param queueName the queue name where task will be added */ public Task( @Nullable String namePrefix, boolean makeUnique, @Nonnull String queueName ) { this.namePrefix = namePrefix; this.makeUnique = namePrefix != null && makeUnique; this.queueName = checkNotNull( queueName ); } @VisibleForTesting public void setExecutor( TaskExecutor executor ) { this.executor = executor; } /** * Returns the entity key that might be used to retrieve entity to work with. * See {@link #workWith()}. * * @return the entity key */ public final Key<T> getEntityKey() { return entityKey; } /** * Sets the entity key. * * @param entityKey the entity key to be set */ public final void setEntityKey( Key<T> entityKey ) { this.entityKey = entityKey; } /** * Returns the task name prefix. * * @return the task name prefix * @see #getTaskName() */ public final String getNamePrefix() { return namePrefix; } /** * Returns the task name as a composition of the non null name prefix and entity key. * Otherwise returns {@code null}. * <p> * Task Name that appears in the Google Cloud Console. * * @return the task name, or {@code null} to be auto generated */ public final String getTaskName() { if ( namePrefix != null ) { if ( entityKey == null ) { return namePrefix; } else { Object identification; long id = entityKey.getId(); if ( id == 0 ) { // 0 if this key has a name identification = null; } else { identification = id; } return namePrefix + "_" + entityKey.getKind() + ( identification == null ? "" : "_" + identification ); } } return null; } /** * Returns a generic name of the task that is not necessarily unique, however might be useful for logging purpose. * * @return the generic task name */ public String getGenericName() { String taskName = getTaskName(); if ( Strings.isNullOrEmpty( taskName ) ) { taskName = getClass().getSimpleName(); if ( entityKey != null ) { taskName = taskName + "_" + entityKey.getKind() + "_" + entityKey.getId(); } } return taskName; } /** * Returns the boolean indication whether to append an unique ID to the task name. * If task name prefix is {@code null} this will return {@code false}. * * @return true to append an unique ID to the task name */ public final boolean isMakeUnique() { return namePrefix != null && makeUnique; } /** * Sets the boolean indication whether to append an unique ID to the task name. * * @param unique true to append an unique ID to the task name * @return this task to chain configuration */ public final Task makeUnique( boolean unique ) { this.makeUnique = unique; return this; } /** * Returns the queue name where task will be added. * * @return the queue name */ public final String getQueueName() { return queueName; } /** * Schedules the given task as the next one to execute once the this (parent) task has been successfully finished. * The root task is the first one to be executed. * * @param task the task as the next one to execute * @param postponeFor the number of seconds to be added to current time for this, * that's a time when the task will be started. Max 30 days. * @return just added task to chain calls */ private <S> Task<S> setNext( @Nonnull Task<S> task, int postponeFor ) { this.next = checkNotNull( task ); return task.postponeFor( postponeFor ); } /** * Schedules the given task as the next one to execute once the this (parent) task has been successfully finished. * The root task is the first one to be executed. * * @param task the task as the next one to execute * @param options the task configuration * @return just added task to chain calls */ private <S> Task<S> setNext( @Nonnull Task<S> task, @Nullable TaskOptions options ) { this.next = checkNotNull( task ); return task.options( options ); } /** * Returns a task that will be executed once this task has finished successfully. * * @return the next task to execute */ public final Task<?> next() { return next; } /** * Adds task to be scheduled as a last one in the current chain. * The root task is the first one to be executed. * * @param task the task to be scheduled * @param postponeFor the number of seconds to be added to current time for this, * that's a time when the task will be started. Max 30 days. * @return just added task to chain calls */ public final <S> Task<S> addNext( @Nonnull Task<S> task, int postponeFor ) { return leaf().setNext( task, postponeFor ); } /** * Adds task to be scheduled as a last one in the current chain. * The root task is the first one to be executed. * * @param task the task to be scheduled * @return just added task to chain calls */ public final <S> Task<S> addNext( @Nonnull Task<S> task ) { return addNext( task, ( TaskOptions ) null ); } /** * Adds task to be scheduled as a last one in the current chain. * The root task is the first one to be executed. * * @param task the task to be scheduled * @param options the task configuration * @return just added task to chain calls */ public final <S> Task<S> addNext( @Nonnull Task<S> task, @Nullable TaskOptions options ) { return leaf().setNext( task, options ); } /** * Adds task to be scheduled as a last one in the current chain. * The root task is the first one to be executed. * * @param task the task to be scheduled * @param condition the functional interface to evaluate a condition whether to enqueue given task. * If {@code false}, this task will be skipped however a following task (if exist) * will be scheduled. * @return just added task to chain calls */ public final <S> Task<S> addNext( @Nonnull Task<S> task, @Nullable SerializableFunction<S, Boolean> condition ) { // function is being evaluated on its parent task before execution Task<?> leaf = leaf(); //noinspection unchecked leaf.function = ( SerializableFunction<Object, Boolean> ) condition; return leaf.setNext( task, null ); } /** * Adds task to be scheduled as a last one in the current chain. * The root task is the first one to be executed. * * @param task the task to be scheduled * @param condition the functional interface to evaluate a condition whether to enqueue given task. * If {@code false}, this task will be skipped however a following task (if exist) * will be scheduled. * @param options the task configuration * @return just added task to chain calls */ public final <S> Task<S> addNext( @Nonnull Task<S> task, @Nullable TaskOptions options, @Nullable SerializableFunction<S, Boolean> condition ) { // function is being evaluated on its parent task before execution Task<?> leaf = leaf(); //noinspection unchecked leaf.function = ( SerializableFunction<Object, Boolean> ) condition; return leaf.setNext( task, options ); } /** * Returns a boolean indication whether current task has a next task to be scheduled once this will be done. * * @return {@code true} if has next task */ public final boolean hasNext() { return next != null; } /** * Traverses and returns a task to be scheduled as last (leaf) in the chain. * If there is no next task, it will return {@code this}. * * @return the leaf task */ private Task<?> leaf() { Task task = this; while ( task.hasNext() ) { task = task.next(); } return task; } /** * Counts number of tasks to be executed starting from this task (including). * * @return the number of tasks to be executed */ public int countTasks() { int count = 1; Task child = this; while ( child.hasNext() ) { child = child.next(); count++; } return count; } /** * Removes the next task from the actual instance to be queued if defined. * <p> * <strong>Note</strong>: call to this method will not persist this change back to the queue * and will take effect only for this instance. However once task will be successfully finished, * no next task is going to be scheduled as it will be removed as a whole by the task engine from the queue. * * @return {@code true} if there was a planned task but has been cleared */ public final boolean clear() { boolean cleared = this.next != null; this.next = null; this.function = null; return cleared; } /** * Returns the configuration options of this task. * * @return the task options configuration, {@code null} if not set */ public final TaskOptions getOptions() { return options; } /** * Sets the configuration options for this task. * * @param options the configuration options instance * @return this task to chain configuration */ public final Task<T> options( @Nullable TaskOptions options ) { this.options = options; return this; } /** * Returns the countdown of this task in seconds, the value to be used when task will be added to the queue. * If not defined, the task will be executed at some time in near future. * * @return the countdown in seconds, {@code null} if not set */ public final Integer getPostponeFor() { return postponeFor; } /** * Sets the countdown of this task in seconds. * * @param countdown the countdown to be set in seconds * @return this task to chain configuration */ public final Task<T> postponeFor( @Nullable Integer countdown ) { this.postponeFor = countdown; return this; } /** * Returns the task executor service instance. * * @return the task executor */ protected final TaskExecutor executor() { return executor; } /** * Returns the entity resolved by {@link #getEntityKey()}. * <p>Objectify instances are {@link com.googlecode.objectify.Objectify#cache(boolean)} * {@code true} by default.</p> * Override this method if target entity to work with comes from the customized storage (serialized etc). * * @return the entity the task will handle or {@code null} if not found */ public T workWith() { return workWith( true ); } public final T workWith( String errorMessage ) { return workWith( true, errorMessage ); } public final T workWith( boolean cache, String errorMessage ) { T t = workWith( cache ); if ( t == null ) { String key = "; Key: " + getEntityKey(); String message = Strings.isNullOrEmpty( errorMessage ) ? "Entity not found" : errorMessage; throw new IllegalArgumentException( message + key ); } return t; } /** * Returns the entity resolved by {@link #getEntityKey()}. * * @param cache {@code true} to use (or not use) a 2nd-level memcache * @return the entity the task will handle or {@code null} if not found * @see com.googlecode.objectify.annotation.Cache */ public final T workWith( boolean cache ) { Key<T> key = getEntityKey(); checkNotNull( key, "Entity key is null" ); return ofy().cache( cache ).load().key( key ).now(); } @Override public boolean equals( Object o ) { if ( this == o ) return true; if ( !( o instanceof Task ) ) return false; Task task = ( Task ) o; return Objects.equals( entityKey, task.entityKey ) && Objects.equals( namePrefix, task.namePrefix ) && Objects.equals( queueName, task.queueName ); } @Override public int hashCode() { return Objects.hash( entityKey, namePrefix, queueName ); } @Override public String toString() { return "Task{" + "entityKey=" + entityKey + ", namePrefix='" + namePrefix + '\'' + ", makeUnique=" + makeUnique + ", next=" + ( next != null ) + ", queueName='" + queueName + '\'' + ", options=" + ( options != null ) + ", postponeFor=" + postponeFor + '}'; } /** * Evaluates recursively whether there is a next task to be scheduled. * If a next task's non {@code null} {@link Task#function} evaluates to {@code false} that task will be skipped. * * @return the next task to be scheduled for execution, or {@code null} if none */ private <S> Task nextToSchedule( @Nonnull Task<S> task ) { boolean scheduleNext; if ( task.hasNext() && task.function != null ) { Object entity = task.next().workWith(); scheduleNext = entity != null && task.function.apply( entity ); if ( entity == null ) { logger.info( "Entity not found for key: " + task.next().getEntityKey() ); } else { logger.info( task.next().getGenericName() + "'s function has been evaluated with value: " + scheduleNext ); } } else { scheduleNext = true; } Task next; if ( task.hasNext() && !scheduleNext ) { logger.info( "The task with name '" + task.next().getGenericName() + "' is being skipped" ); next = nextToSchedule( task.next() ); } else { next = task.next(); } return next; } @Override public final void run() { logger.info( "Task '" + getGenericName() + "' has been started." ); injector.injectMembers( this ); execute(); Task scheduled = nextToSchedule( this ); if ( scheduled == null ) { return; } else { logger.info( "The task with name '" + scheduled.getGenericName() + "' is being scheduled to be executed as next." ); } // once parent task has been successfully executed, enqueue the next task TaskOptions nextTaskOptions = scheduled.getOptions(); if ( nextTaskOptions == null ) { executor.schedule( scheduled ); } else { executor.schedule( scheduled, nextTaskOptions ); } } /** * The client implementation to be executed asynchronously. */ protected abstract void execute(); /** * Serializable {@link Function}. */ @FunctionalInterface public interface SerializableFunction<T, R> extends Function<T, R>, Serializable { } }
package com.esotericsoftware.kryo.serialize; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import junit.framework.TestCase; import org.junit.Assert; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.NotNull; import com.esotericsoftware.kryo.Serializer; // TODO - Write tests for all serializers. public class SerializerTest extends TestCase { private ByteBuffer buffer = ByteBuffer.allocateDirect(500); private int intValues[] = { 0, 1, 2, 3, -1, -2, -3, 32, -32, 127, 128, 129, -125, -126, -127, -128, 252, 253, 254, 255, 256, -252, -253, -254, -255, -256, 32767, 32768, 32769, -32767, -32768, -32769, 65535, 65536, 65537, Integer.MAX_VALUE, Integer.MIN_VALUE, }; public void testCollection () { Kryo kryo = new Kryo(); CollectionSerializer serializer = new CollectionSerializer(kryo); roundTrip(serializer, 11, new ArrayList(Arrays.asList("1", "2", "3"))); roundTrip(serializer, 13, new ArrayList(Arrays.asList("1", "2", null, 1, 2))); roundTrip(serializer, 15, new ArrayList(Arrays.asList("1", "2", null, 1, 2, 5))); roundTrip(serializer, 11, new ArrayList(Arrays.asList("1", "2", "3"))); roundTrip(serializer, 11, new ArrayList(Arrays.asList("1", "2", "3"))); serializer.setElementClass(String.class); roundTrip(serializer, 11, new ArrayList(Arrays.asList("1", "2", "3"))); serializer.setElementsCanBeNull(false); roundTrip(serializer, 8, new ArrayList(Arrays.asList("1", "2", "3"))); } public void testArray () { Kryo kryo = new Kryo(); ArraySerializer serializer = new ArraySerializer(kryo); roundTrip(serializer, 7, new int[] {1, 2, 3, 4}); roundTrip(serializer, 11, new int[] {1, 2, -100, 4}); roundTrip(serializer, 13, new int[] {1, 2, -100, 40000}); roundTrip(serializer, 10, new int[][] { {1, 2}, {100, 4}}); roundTrip(serializer, 12, new int[][] { {1}, {2}, {100}, {4}}); roundTrip(serializer, 15, new int[][][] { { {1}, {2}}, { {100}, {4}}}); roundTrip(serializer, 19, new String[] {"11", "2222", "3", "4"}); roundTrip(serializer, 17, new String[] {"11", "2222", null, "4"}); serializer.setDimensionCount(1); serializer.setElementsAreSameType(true); roundTrip(serializer, 16, new String[] {"11", "2222", null, "4"}); serializer.setElementsAreSameType(false); roundTrip(serializer, 16, new String[] {"11", "2222", null, "4"}); roundTrip(new ArraySerializer(kryo), 6, new String[] {null, null, null}); roundTrip(new ArraySerializer(kryo), 3, new String[] {}); serializer.setElementsCanBeNull(true); serializer.setElementsAreSameType(true); roundTrip(serializer, 18, new String[] {"11", "2222", "3", "4"}); serializer.setElementsCanBeNull(false); roundTrip(serializer, 14, new String[] {"11", "2222", "3", "4"}); serializer.setLength(4); roundTrip(serializer, 13, new String[] {"11", "2222", "3", "4"}); } public void testMap () { Kryo kryo = new Kryo(); HashMap map = new HashMap(); map.put("123", "456"); map.put("789", "abc"); MapSerializer serializer = new MapSerializer(kryo); roundTrip(serializer, 22, map); serializer.setKeyClass(String.class); serializer.setKeysCanBeNull(false); serializer.setValueClass(String.class); roundTrip(serializer, 20, map); serializer.setValuesCanBeNull(false); roundTrip(serializer, 18, map); } public void testShort () { roundTrip(new ShortSerializer(true), 2, (short)123); roundTrip(new ShortSerializer(false), 2, (short)123); buffer.clear(); ShortSerializer.put(buffer, (short)250, false); buffer.flip(); assertEquals(3, buffer.limit()); assertEquals((short)250, ShortSerializer.get(buffer, false)); buffer.clear(); ShortSerializer.put(buffer, (short)250, true); buffer.flip(); assertEquals(1, buffer.limit()); assertEquals((short)250, ShortSerializer.get(buffer, true)); buffer.clear(); ShortSerializer.put(buffer, (short)123, true); buffer.flip(); assertEquals(1, buffer.limit()); assertEquals((short)123, ShortSerializer.get(buffer, true)); } public void testNumbers () { for (int value : intValues) { roundTrip(value, false); roundTrip(value, true); } } private void roundTrip (int value, boolean optimizePositive) { buffer.clear(); IntSerializer.put(buffer, value, optimizePositive); buffer.flip(); int result = IntSerializer.get(buffer, optimizePositive); System.out.println(value + " int bytes, " + optimizePositive + ": " + buffer.limit()); assertEquals(result, value); short shortValue = (short)value; buffer.clear(); ShortSerializer.put(buffer, shortValue, optimizePositive); buffer.flip(); short shortResult = ShortSerializer.get(buffer, optimizePositive); System.out.println(shortValue + " short bytes, " + optimizePositive + ": " + buffer.limit()); assertEquals(shortResult, shortValue); } private <T> T roundTrip (Serializer serializer, int length, T object1) { buffer.clear(); serializer.writeObject(buffer, object1); buffer.flip(); System.out.println(object1 + " bytes: " + buffer.remaining()); assertEquals("Incorrect length.", length, buffer.remaining()); Object object2 = serializer.readObject(buffer, object1.getClass()); if (object1.getClass().isArray()) { if (object1 instanceof int[]) Assert.assertArrayEquals((int[])object1, (int[])object2); else if (object1 instanceof int[][]) Assert.assertArrayEquals((int[][])object1, (int[][])object2); else if (object1 instanceof int[][][]) Assert.assertArrayEquals((int[][][])object1, (int[][][])object2); else if (object1 instanceof String[]) Assert.assertArrayEquals((String[])object1, (String[])object2); else fail(); } else assertEquals(object1, object2); return (T)object2; } public void testNonNull () { Kryo kryo = new Kryo(); FieldSerializer fieldSerializer = new FieldSerializer(kryo); StringTestClass value = new StringTestClass(); value.text = "moo"; NonNullTestClass nonNullValue = new NonNullTestClass(); nonNullValue.nonNullText = "moo"; buffer.clear(); fieldSerializer.writeObjectData(buffer, value); buffer.flip(); assertEquals("Incorrect length.", 5, buffer.remaining()); buffer.clear(); fieldSerializer.writeObjectData(buffer, nonNullValue); buffer.flip(); assertEquals("Incorrect length.", 4, buffer.remaining()); } public void testFieldSerializer () { TestClass value = new TestClass(); value.child = new TestClass(); Kryo kryo = new Kryo(); FieldSerializer serializer = new FieldSerializer(kryo); serializer.removeField(TestClass.class, "optional"); value.optional = 123; kryo.register(TestClass.class, serializer); TestClass value2 = roundTrip(serializer, 35, value); assertEquals(0, value2.optional); serializer = new FieldSerializer(kryo); value.optional = 123; value2 = roundTrip(serializer, 36, value); assertEquals(123, value2.optional); } public void testNoDefaultConstructor () { NoDefaultConstructor object = new NoDefaultConstructor(2); Kryo kryo = new Kryo(); roundTrip(new SimpleSerializer<NoDefaultConstructor>() { public NoDefaultConstructor read (ByteBuffer buffer) { return new NoDefaultConstructor(IntSerializer.get(buffer, true)); } public void write (ByteBuffer buffer, NoDefaultConstructor object) { IntSerializer.put(buffer, object.constructorValue, true); } }, 2, object); } static public class NoDefaultConstructor { private int constructorValue; public NoDefaultConstructor (int constructorValue) { this.constructorValue = constructorValue; } public int getConstructorValue () { return constructorValue; } public int hashCode () { final int prime = 31; int result = 1; result = prime * result + constructorValue; return result; } public boolean equals (Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NoDefaultConstructor other = (NoDefaultConstructor)obj; if (constructorValue != other.constructorValue) return false; return true; } } static public class NonNullTestClass { @NotNull public String nonNullText; } static public class StringTestClass { public String text = "something"; } static public class TestClass { public String text = "something"; public String nullField; public TestClass child; public float abc = 1.2f; public int optional; public boolean equals (Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TestClass other = (TestClass)obj; if (Float.floatToIntBits(abc) != Float.floatToIntBits(other.abc)) return false; if (child == null) { if (other.child != null) return false; } else if (!child.equals(other.child)) return false; if (nullField == null) { if (other.nullField != null) return false; } else if (!nullField.equals(other.nullField)) return false; if (text == null) { if (other.text != null) return false; } else if (!text.equals(other.text)) return false; return true; } } }
package org.mockitoutil; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Callable; /** * Custom classloader to load classes in hierarchic realm. * * Each class can be reloaded in the realm if the LoadClassPredicate says so. */ public class SimplePerRealmReloadingClassLoader extends URLClassLoader { private final Map<String,Class> classHashMap = new HashMap<String, Class>(); private ReloadClassPredicate reloadClassPredicate; public SimplePerRealmReloadingClassLoader(ReloadClassPredicate reloadClassPredicate) { super(getPossibleClassPathsUrls()); this.reloadClassPredicate = reloadClassPredicate; } public SimplePerRealmReloadingClassLoader(ClassLoader parentClassLoader, ReloadClassPredicate reloadClassPredicate) { super(getPossibleClassPathsUrls(), parentClassLoader); this.reloadClassPredicate = reloadClassPredicate; } private static URL[] getPossibleClassPathsUrls() { return new URL[]{ obtainClassPath(), obtainClassPath("org.mockito.Mockito"), obtainClassPath("org.mockito.cglib.proxy.Enhancer"), }; } private static URL obtainClassPath() { String className = SimplePerRealmReloadingClassLoader.class.getName(); return obtainClassPath(className); } private static URL obtainClassPath(String className) { String path = className.replace('.', '/') + ".class"; String url = SimplePerRealmReloadingClassLoader.class.getClassLoader().getResource(path).toExternalForm(); try { return new URL(url.substring(0, url.length() - path.length())); } catch (MalformedURLException e) { throw new RuntimeException("Classloader couldn't obtain a proper classpath URL", e); } } @Override public Class<?> loadClass(String qualifiedClassName) throws ClassNotFoundException { if(reloadClassPredicate.acceptReloadOf(qualifiedClassName)) { // return customLoadClass(qualifiedClassName); // Class<?> loadedClass = findLoadedClass(qualifiedClassName); if(!classHashMap.containsKey(qualifiedClassName)) { Class<?> foundClass = findClass(qualifiedClassName); saveFoundClass(qualifiedClassName, foundClass); return foundClass; } return classHashMap.get(qualifiedClassName); } return useParentClassLoaderFor(qualifiedClassName); } private void saveFoundClass(String qualifiedClassName, Class<?> foundClass) { classHashMap.put(qualifiedClassName, foundClass); } private Class<?> useParentClassLoaderFor(String qualifiedName) throws ClassNotFoundException { return super.loadClass(qualifiedName); } public Object doInRealm(String callableCalledInClassLoaderRealm) throws Exception { ClassLoader current = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(this); Object instance = this.loadClass(callableCalledInClassLoaderRealm).getConstructor().newInstance(); if (instance instanceof Callable) { Callable<?> callableInRealm = (Callable<?>) instance; return callableInRealm.call(); } } finally { Thread.currentThread().setContextClassLoader(current); } throw new IllegalArgumentException("qualified name '" + callableCalledInClassLoaderRealm + "' should represent a class implementing Callable"); } public Object doInRealm(String callableCalledInClassLoaderRealm, Class[] argTypes, Object[] args) throws Exception { ClassLoader current = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(this); Object instance = this.loadClass(callableCalledInClassLoaderRealm).getConstructor(argTypes).newInstance(args); if (instance instanceof Callable) { Callable<?> callableInRealm = (Callable<?>) instance; return callableInRealm.call(); } } finally { Thread.currentThread().setContextClassLoader(current); } throw new IllegalArgumentException("qualified name '" + callableCalledInClassLoaderRealm + "' should represent a class implementing Callable"); } public static interface ReloadClassPredicate { boolean acceptReloadOf(String qualifiedName); } }
package nl.mvdr.tinustris.gui; import java.util.Arrays; import java.util.List; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.PerspectiveCamera; import javafx.scene.PointLight; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.paint.Color; import javafx.scene.paint.CycleMethod; import javafx.scene.paint.Paint; import javafx.scene.paint.RadialGradient; import javafx.scene.paint.Stop; import javafx.scene.shape.Rectangle; import javafx.scene.shape.StrokeType; import javafx.scene.text.Font; import javafx.stage.Stage; import lombok.extern.slf4j.Slf4j; import nl.mvdr.tinustris.engine.GameEngine; import nl.mvdr.tinustris.engine.GameLoop; import nl.mvdr.tinustris.engine.OnePlayerEngine; import nl.mvdr.tinustris.input.InputController; import nl.mvdr.tinustris.input.JInputController; import nl.mvdr.tinustris.model.OnePlayerGameState; import org.slf4j.bridge.SLF4JBridgeHandler; import com.sun.javafx.runtime.VersionInfo; /** * Main class and entry point for the entire application. * * @author Martijn van de Rijdt */ // When testing the application, don't run this class directly from Eclipse. Use TinustrisTestContext instead. @Slf4j public class Tinustris extends Application { /** Size of the border around the Tetris grid and other UI components. */ private static final int BORDER_SIZE = 10; /** Size of the margin between windows. */ private static final int MARGIN = 10; /** Width of a text window. */ private static final int TEXT_WINDOW_HEIGHT = 50; /** Width of the game over label. */ private static final int GAME_OVER_LABEL_WIDTH = 170; /** Whether 3D graphics are used. */ private static final boolean PERSPECTIVE_3D = true; /** Game loop. */ private GameLoop<OnePlayerGameState> gameLoop; /** * Main method. * * @param args * command-line parameters */ public static void main(String[] args) { // JInput uses java.util.logging; redirect to slf4j. installSlf4jBridge(); // Launch the application! launch(args); } /** Installs a bridge for java.util.logging to slf4j. */ private static void installSlf4jBridge() { // remove existing handlers attached to java.util.logging root logger SLF4JBridgeHandler.removeHandlersForRootLogger(); // add SLF4JBridgeHandler to java.util.logging's root logger SLF4JBridgeHandler.install(); } /** {@inheritDoc} */ @Override public void start(Stage stage) { log.info("Starting application."); logVersionInfo(); Thread.currentThread().setUncaughtExceptionHandler( (thread, throwable) -> log.error("Uncaught runtime exception on JavaFX Thread", throwable)); // TODO configuration screen to select speed curve, level system, button configuration, number of players and 2D/3D BlockCreator blockCreator; if (PERSPECTIVE_3D) { blockCreator = new BoxBlockCreator(); } else { blockCreator = new RectangleBlockCreator(); } // create the game renderers GridRenderer gridGroup = new GridRenderer(blockCreator); NextBlockRenderer nextBlockRenderer = new NextBlockRenderer(blockCreator); LinesRenderer linesRenderer = new LinesRenderer(); LevelRenderer levelRenderer = new LevelRenderer(); GameOverRenderer gameOverRenderer = new GameOverRenderer(); List<GameRenderer<OnePlayerGameState>> renderers = Arrays.<GameRenderer<OnePlayerGameState>> asList(gridGroup, nextBlockRenderer, linesRenderer, levelRenderer, gameOverRenderer); CompositeRenderer<OnePlayerGameState> gameRenderer = new CompositeRenderer<>(renderers); // construct the user interface stage.setTitle("Tinustris"); int widthInBlocks = OnePlayerGameState.DEFAULT_WIDTH; int heightInBlocks = OnePlayerGameState.DEFAULT_HEIGHT - OnePlayerGameState.VANISH_ZONE_HEIGHT; Group gridWindow = createWindow("", gridGroup, MARGIN, MARGIN, widthInBlocks * GridRenderer.BLOCK_SIZE, heightInBlocks * BlockGroupRenderer.BLOCK_SIZE); Group nextBlockWindow = createWindow("NEXT", nextBlockRenderer, 2 * MARGIN + widthInBlocks * BlockGroupRenderer.BLOCK_SIZE + 2 * BORDER_SIZE, MARGIN, 4 * GridRenderer.BLOCK_SIZE, 4 * GridRenderer.BLOCK_SIZE); Group linesWindow = createWindow("LINES", linesRenderer, 2 * MARGIN + widthInBlocks * BlockGroupRenderer.BLOCK_SIZE + 2 * BORDER_SIZE, 2 * MARGIN + 2 * BORDER_SIZE + 4 * GridRenderer.BLOCK_SIZE, 4 * GridRenderer.BLOCK_SIZE, TEXT_WINDOW_HEIGHT); Group levelWindow = createWindow("LEVEL", levelRenderer, 2 * MARGIN + widthInBlocks * BlockGroupRenderer.BLOCK_SIZE + 2 * BORDER_SIZE, 3 * MARGIN + 4 * BORDER_SIZE + 4 * GridRenderer.BLOCK_SIZE + TEXT_WINDOW_HEIGHT, 4 * GridRenderer.BLOCK_SIZE, TEXT_WINDOW_HEIGHT); Group gameOverWindow = createWindow("", gameOverRenderer, (MARGIN + widthInBlocks * BlockGroupRenderer.BLOCK_SIZE) / 2 - GAME_OVER_LABEL_WIDTH / 2, (MARGIN + heightInBlocks * BlockGroupRenderer.BLOCK_SIZE) / 2 - TEXT_WINDOW_HEIGHT / 2, GAME_OVER_LABEL_WIDTH, TEXT_WINDOW_HEIGHT); gameOverWindow.setVisible(false); // TODO also add a background image as the first child: new ImageView("imageurl"); Group parent = new Group(gridWindow, nextBlockWindow, linesWindow, levelWindow, gameOverWindow); Scene scene = new Scene(parent, widthInBlocks * BlockGroupRenderer.BLOCK_SIZE + 4 * BORDER_SIZE + 3 * MARGIN + 4 * GridRenderer.BLOCK_SIZE, heightInBlocks * BlockGroupRenderer.BLOCK_SIZE + 2 * BORDER_SIZE + 2 * MARGIN, Color.GRAY); if (PERSPECTIVE_3D) { // add a camera and lighting scene.setCamera(new PerspectiveCamera()); PointLight light = new PointLight(Color.WHITE); light.setTranslateZ(-300); parent.getChildren().add(light); } stage.setScene(scene); stage.show(); // Default size should also be the minimum size. stage.setMinWidth(stage.getWidth()); stage.setMinHeight(stage.getHeight()); log.info("Stage shown."); // setup necessary components InputController inputController = new JInputController(); GameEngine<OnePlayerGameState> gameEngine = new OnePlayerEngine(); // start the game loop gameLoop = new GameLoop<>(inputController, gameEngine, gameRenderer); gameLoop.start(); log.info("Game loop started."); } /** Logs some version info. */ // default visibility for unit tests void logVersionInfo() { if (log.isInfoEnabled()) { String version = retrieveVersion(); if (version != null) { log.info("Application version: " + version); } else { log.info("pplication version unknown."); } log.info("Classpath: " + System.getProperty("java.class.path")); log.info("Library path: " + System.getProperty("java.library.path")); log.info("Java vendor: " + System.getProperty("java.vendor")); log.info("Java version: " + System.getProperty("java.version")); log.info("OS name: " + System.getProperty("os.name")); log.info("OS version: " + System.getProperty("os.version")); log.info("OS architecture: " + System.getProperty("os.arch")); log.info("JavaFX version: " + VersionInfo.getVersion()); log.info("JavaFX runtime version: " + VersionInfo.getRuntimeVersion()); log.info("JavaFX build timestamp: " + VersionInfo.getBuildTimestamp()); } } /** * Returns the version number from the jar manifest file. * * @return version number, or null if it cannot be determined */ private String retrieveVersion() { String result; Package p = Tinustris.class.getPackage(); if (p != null) { result = p.getImplementationVersion(); } else { result = null; } return result; } /** * Creates a red-bordered window containing the given node. * * @param title * window title * @param contents * contents of the window * @param x * x coordinate * @param y * coordinate * @param contentsWidth * width of the contents * @param contentsHeight * height of the contents * @return group containing the window and the contents */ private Group createWindow(String title, Node contents, double x, double y, double contentsWidth, double contentsHeight) { // bounding red rectangle Rectangle border = new Rectangle(x + BORDER_SIZE, y + BORDER_SIZE, contentsWidth, contentsHeight); border.setFill(null); Paint stroke = new RadialGradient(0, 1, border.getX() + border.getWidth() / 2, border.getY() + border.getHeight() / 2, border.getWidth(), false, CycleMethod.NO_CYCLE, new Stop(0, Color.WHITE), new Stop(1, Color.DARKRED)); border.setStroke(stroke); border.setStrokeWidth(BORDER_SIZE); border.setStrokeType(StrokeType.OUTSIDE); border.setArcWidth(GridRenderer.ARC_SIZE); border.setArcHeight(GridRenderer.ARC_SIZE); // black, seethrough background, to dim whatever is behind the window Rectangle background = new Rectangle(border.getX(), border.getY(), border.getWidth(), border.getHeight()); background.setFill(Color.BLACK); background.setOpacity(.5); background.setArcWidth(GridRenderer.ARC_SIZE); background.setArcHeight(GridRenderer.ARC_SIZE); contents.setTranslateX(x + BORDER_SIZE); contents.setTranslateY(y + BORDER_SIZE); Label label = new Label(title); label.setTextFill(Color.WHITE); label.setFont(new Font(10)); label.setLayoutX(border.getX() + 2); label.setLayoutY(border.getY() - BORDER_SIZE - 2); return new Group(background, border, contents, label); } /** {@inheritDoc} */ @Override public void stop() throws Exception { log.info("Stopping the application."); gameLoop.stop(); super.stop(); log.info("Stopped."); } }
package net.hearthstats.ui; import net.hearthstats.DeckSlotUtils; import net.hearthstats.HearthstoneMatch; import net.hearthstats.Monitor; import net.hearthstats.util.Rank; import net.miginfocom.swing.MigLayout; import org.apache.commons.lang3.StringUtils; import org.json.simple.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; /** * A popup to display at the end of the match that allows the match details to be edited. * * @author gtch */ public class MatchEndPopup extends JPanel { private final static Logger debugLog = LoggerFactory.getLogger(MatchEndPopup.class); private final ResourceBundle bundle = ResourceBundle.getBundle("net.hearthstats.resources.Main"); private final MigLayout layout = new MigLayout( "", "[]10[grow]20[]10[grow]", "" ); private final HearthstoneMatch match; private String infoMessage; private List<String> errorMessages; private JComboBox rankComboBox; private JComboBox gameModeComboBox; private JTextField opponentNameField; private JComboBox opponentClassComboBox; private JComboBox yourClassComboBox; private JComboBox yourDeckComboBox; private JCheckBox coinCheckBox; private JTextArea notesTextArea; private JRadioButton resultVictory; private JRadioButton resultDefeat; private JRadioButton resultDraw; private JPanel rankPanel=new JPanel(); private JPanel deckPanel=new JPanel(); private JLabel rankNotApplicable; private JLabel deckNotApplicable; private MatchEndPopup(HearthstoneMatch match, String infoMessage) { this.match = match; this.infoMessage = infoMessage; this.errorMessages = determineErrors(match); initComponents(); } public static enum Button { SUBMIT, CANCEL } public static Button showPopup(Component parentComponent, HearthstoneMatch match, String infoMessage, String title) { MatchEndPopup popup = new MatchEndPopup(match, infoMessage); int value = JOptionPane.showOptionDialog(parentComponent, popup, title, JOptionPane.INFORMATION_MESSAGE, JOptionPane.YES_NO_OPTION, null, new String[] { "Submit", "Cancel" }, "Submit"); Button result; switch (value) { case 0: result = Button.SUBMIT; break; case 1: result = Button.CANCEL; break; default: result = Button.CANCEL; break; } return result; } private List<String> determineErrors(HearthstoneMatch match) { List<String> result = new ArrayList<>(); if (match.getMode() == null) { result.add(t("match.popup.error.mode")); } if (match.getRankLevel() == null && "Ranked".equals(match.getMode())) { result.add(t("match.popup.error.rank")); } if (match.getUserClass() == null) { result.add(t("match.popup.error.yourclass")); } if (StringUtils.isBlank(match.getOpponentName())) { result.add(t("match.popup.error.opponentname")); } if (match.getOpponentClass() == null) { result.add(t("match.popup.error.opponentclass")); } if (match.getResult() == null) { result.add(t("match.popup.error.result")); } return result; } private void initComponents() { // Increase the site of the panel if there are error messages to display int preferredHeight = 380 + (30 * errorMessages.size()); setLayout(layout); setMinimumSize(new Dimension(660, 380)); setPreferredSize(new Dimension(660, preferredHeight)); setMaximumSize(new Dimension(660, preferredHeight + 200)); //// Row 1 //// JLabel heading = new JLabel(match.getMode() == null ? t("match.popup.heading") : match.getMode() + " " + t("match.popup.heading")); Font headingFont = heading.getFont().deriveFont(20f); heading.setFont(headingFont); add(heading, "span"); //// Row 2 //// if (infoMessage != null) { JLabel infoLabel = new JLabel("<html>" + infoMessage + "</html>"); add(infoLabel, "span, gapy 5px 10px"); } //// Row 3 //// if (errorMessages.size() > 0) { StringBuilder sb = new StringBuilder(); sb.append("<html>"); for (String error : errorMessages) { if (sb.length() > 6) { sb.append("<br>"); } sb.append("- "); sb.append(error); } sb.append("</html>"); JLabel errorLabel = new JLabel(sb.toString()); errorLabel.setForeground(Color.RED.darker()); add(errorLabel, "span, gapy 5px 10px"); } //// Row 3 bis - game mode //// //TODO : localize and use constants String[] gameModes = new String[] {undetectedLabel(), "Arena" , "Casual", "Practice", "Ranked"}; add(new JLabel(t("match.label.game_mode")), "right"); gameModeComboBox = new JComboBox<>(gameModes); setDefaultSize(gameModeComboBox); if (match.getMode() != null) { gameModeComboBox.setSelectedItem(match.getMode()); } else { gameModeComboBox.setSelectedIndex(0); } gameModeComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { match.setMode(gameModeComboBox.getSelectedItem().toString()); updateGameMode(); } }); add(gameModeComboBox, "span"); //// Row 4 //// add(new JLabel(t("match.label.your_rank")), "right"); rankComboBox = new JComboBox<>(Rank.values()); setDefaultSize(rankComboBox); rankComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { match.setRankLevel((Rank) rankComboBox.getSelectedItem()); } }); rankNotApplicable = new JLabel(""); rankNotApplicable.setFont(rankNotApplicable.getFont().deriveFont(Font.ITALIC)); rankNotApplicable.setEnabled(false); setDefaultSize(rankNotApplicable); add(rankPanel, ""); add(new JLabel(t("match.label.opponent_name")), "right"); opponentNameField = new JTextField(); setDefaultSize(opponentNameField); opponentNameField.setText(match.getOpponentName()); opponentNameField.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { match.setOpponentName(opponentNameField.getText().replaceAll("\\s+", "")); } }); add(opponentNameField, "wrap"); //// Row 5 //// String[] localizedClassOptions = new String[Monitor.hsClassOptions.length]; localizedClassOptions[0] = undetectedLabel(); for (int i = 1; i < localizedClassOptions.length; i++) { localizedClassOptions[i] = t(Monitor.hsClassOptions[i]); } add(new JLabel(t("match.label.your_class")), "right"); yourClassComboBox = new JComboBox<>(localizedClassOptions); setDefaultSize(yourClassComboBox); if (match.getUserClass() == null) { yourClassComboBox.setSelectedIndex(0); } else { yourClassComboBox.setSelectedItem(match.getUserClass()); } yourClassComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (yourClassComboBox.getSelectedIndex() == 0) { match.setUserClass(null); } else { match.setUserClass(Monitor.hsClassOptions[yourClassComboBox.getSelectedIndex()]); } } }); add(yourClassComboBox, ""); add(new JLabel(t("match.label.opponents_class")), "right"); opponentClassComboBox = new JComboBox<>(localizedClassOptions); setDefaultSize(opponentClassComboBox); if (match.getOpponentClass() == null) { opponentClassComboBox.setSelectedIndex(0); } else { opponentClassComboBox.setSelectedItem(match.getOpponentClass()); } opponentClassComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (opponentClassComboBox.getSelectedIndex() == 0) { match.setOpponentClass(null); } else { match.setOpponentClass(Monitor.hsClassOptions[opponentClassComboBox.getSelectedIndex()]); } } }); add(opponentClassComboBox, "wrap"); //// Row 6 //// add(new JLabel(t("match.label.your_deck")), "right"); String[] deckSlotList = new String[10]; deckSlotList[0] = undetectedLabel(); for (int i = 1; i <= 9; i++) { JSONObject deck = DeckSlotUtils.getDeckFromSlot(i); StringBuilder sb = new StringBuilder(); sb.append(t("deck_slot.label_" + i)); sb.append(" "); if (deck == null) { sb.append(t("undetected")); } else { sb.append(deck.get("name")); } deckSlotList[i] = sb.toString(); } yourDeckComboBox = new JComboBox<>(deckSlotList); setDefaultSize(yourDeckComboBox); yourDeckComboBox.setSelectedIndex(match.getDeckSlot()); yourDeckComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { match.setDeckSlot(yourDeckComboBox.getSelectedIndex()); } }); deckNotApplicable = new JLabel(""); deckNotApplicable.setFont(deckNotApplicable.getFont().deriveFont(Font.ITALIC)); deckNotApplicable.setEnabled(false); setDefaultSize(deckNotApplicable); add(deckPanel, "wrap"); //// Row 7 //// add(new JLabel(t("match.label.coin")), "right"); coinCheckBox = new JCheckBox(t("match.coin")); coinCheckBox.setSelected(match.hasCoin()); coinCheckBox.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { match.setCoin(coinCheckBox.isSelected()); } }); add(coinCheckBox, "wrap"); //// Row 8 //// add(new JLabel("Result:"), "right, gapy 20px 20px"); JPanel resultPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 1, 1)); resultVictory = new JRadioButton(t("match.label.result_victory")); resultVictory.setMnemonic(KeyEvent.VK_V); resultVictory.setMargin(new Insets(0, 0, 0, 10)); if ("Victory".equals(match.getResult())) { resultVictory.setSelected(true); } resultVictory.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (resultVictory.isSelected()) { match.setResult("Victory"); } } }); resultPanel.add(resultVictory); resultDefeat = new JRadioButton(t("match.label.result_defeat")); resultDefeat.setMnemonic(KeyEvent.VK_D); resultDefeat.setMargin(new Insets(0, 0, 0, 10)); if ("Defeat".equals(match.getResult())) { resultDefeat.setSelected(true); } resultDefeat.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (resultDefeat.isSelected()) { match.setResult("Defeat"); } } }); resultPanel.add(resultDefeat); resultDraw = new JRadioButton(t("match.label.result_draw")); resultDraw.setMnemonic(KeyEvent.VK_R); resultDraw.setMargin(new Insets(0, 0, 0, 10)); if ("Draw".equals(match.getResult())) { resultDraw.setSelected(true); } resultDraw.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (resultDraw.isSelected()) { match.setResult("Draw"); } } }); resultPanel.add(resultDraw); ButtonGroup resultGroup = new ButtonGroup(); resultGroup.add(resultVictory); resultGroup.add(resultDefeat); resultGroup.add(resultDraw); add(resultPanel, "span 3, wrap"); //// Row 9 //// add(new JLabel(t("match.label.notes")), "right"); notesTextArea = new JTextArea(); notesTextArea.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black), BorderFactory.createEmptyBorder(3, 6, 3, 6))); notesTextArea.setMinimumSize(new Dimension(550, 100)); notesTextArea.setPreferredSize(new Dimension(550, 150)); notesTextArea.setMaximumSize(new Dimension(550, 200)); notesTextArea.setBackground(Color.WHITE); notesTextArea.setText(match.getNotes()); notesTextArea.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) { match.setNotes(notesTextArea.getText()); } }); add(notesTextArea, "span 3, wrap"); updateGameMode(); } private void updateGameMode() { boolean isRanked = "Ranked".equals(match.getMode()); rankPanel.removeAll(); if (isRanked) { if (match.getRankLevel() != null) { rankComboBox.setSelectedIndex(25 - match.getRankLevel().number); } rankPanel.add(rankComboBox); } else { String rankMessage; if ("Arena".equals(match.getMode())) { rankMessage = "N/A: Arena Mode"; } else if ("Casual".equals(match.getMode())) { rankMessage = "N/A: Casual Mode"; } else { rankMessage = "N/A"; } rankNotApplicable.setText(rankMessage); rankPanel.add(rankNotApplicable); } deckPanel.removeAll(); if (isRanked || "Casual".equals(match.getMode())) { // TODO shouldn't we add also Practice here ? deckPanel.add(yourDeckComboBox); } else { String deckMessage; if ("Arena".equals(match.getMode())) { deckMessage = "N/A: Arena Mode"; } else { deckMessage = "N/A"; } deckNotApplicable.setText(deckMessage); deckPanel.add(deckNotApplicable); } validate(); repaint(); } private static void setDefaultSize(Component c) { c.setMinimumSize(new Dimension(180, 27)); c.setPreferredSize(new Dimension(200, 28)); } /** * Loads text from the main resource bundle, using the local language when available. * @param key the key for the desired string * @return The requested string */ private String t(String key) { return bundle.getString(key); } private String undetectedLabel() { return "- "+t("undetected")+" -"; } }
package brooklyn.cli; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.io.InputStream; import java.io.OutputStream; import java.util.NoSuchElementException; import java.util.Scanner; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Test the command line interface operation. */ public class CliIntegrationTest { // FIXME this should not be hardcoded; needed to use the local code for Main private static final String BROOKLYN_BIN_PATH = "../dist/target/brooklyn-dist/bin/brooklyn"; private static final String BROOKLYN_CLASSPATH = "./target/test-classes/:./target/classes/"; private ExecutorService executor; @BeforeMethod(alwaysRun = true) public void setup() { executor = Executors.newCachedThreadPool(); } @AfterMethod(alwaysRun = true) public void teardown() { executor.shutdownNow(); } // Helper function used in testing private String convertStreamToString(InputStream is) { try { return new Scanner(is).useDelimiter("\\A").next(); } catch (NoSuchElementException e) { return ""; } } /** * Checks if running {@code brooklyn help} produces the expected output. */ @Test(groups = "Integration") public void testLaunchCliHelp() throws Throwable { // Invoke the brooklyn script with the "help" argument ProcessBuilder pb = new ProcessBuilder(); pb.environment().remove("BROOKLYN_HOME"); pb.environment().put("BROOKLYN_CLASSPATH", BROOKLYN_CLASSPATH); pb.command(BROOKLYN_BIN_PATH, "help"); final Process brooklyn = pb.start(); Callable<Void> cli = new Callable<Void>() { @Override public Void call() throws Exception { // Get the console output of running that command String consoleOutput = convertStreamToString(brooklyn.getInputStream()); String consoleError = convertStreamToString(brooklyn.getErrorStream()); // Check if the output looks as expected for the help command assertTrue(consoleOutput.contains("usage: brooklyn"), "Usage info not present"); assertTrue(consoleOutput.contains("The most commonly used brooklyn commands are:"), "List of common commands not present"); assertTrue(consoleOutput.contains("help Display help for available commands") && consoleOutput.contains("info Display information about brooklyn") && consoleOutput.contains("launch Starts a brooklyn application"), "List of common commands present"); assertTrue(consoleOutput.contains("See 'brooklyn help <command>' for more information on a specific command."), "Implemented commands not listed"); assertTrue(consoleError.isEmpty()); return null; } }; try { Future<Void> future = executor.submit(cli); future.get(10, TimeUnit.SECONDS); // Check error code from process is 0 assertEquals(brooklyn.exitValue(), 0, "Command terminated with error status"); } catch (TimeoutException te) { fail("Timed out waiting for process to complete"); } catch (ExecutionException ee) { throw ee.getCause(); } finally { brooklyn.destroy(); } } /** * Checks if launching an application using {@code brooklyn launch} produces the expected output. */ @Test(groups = "Integration") public void testLaunchCliApp() throws Throwable { // Invoke the brooklyn script with the launch command ProcessBuilder pb = new ProcessBuilder(); pb.environment().remove("BROOKLYN_HOME"); pb.environment().put("BROOKLYN_CLASSPATH", BROOKLYN_CLASSPATH); pb.command(BROOKLYN_BIN_PATH, "--verbose", "launch", "--stopOnKeyPress", "--app", "brooklyn.cli.CliTest$ExampleApp", "--location", "localhost", "--noConsole"); final Process brooklyn = pb.start(); Callable<Void> cli = new Callable<Void>() { @Override public Void call() throws Exception { // Get the console output of running that command String consoleOutput = convertStreamToString(brooklyn.getInputStream()); String consoleError = convertStreamToString(brooklyn.getErrorStream()); // Check if the output looks as expected for the launch command assertTrue(consoleOutput.contains("Launching Brooklyn web console management"), "Launch message not output"); assertFalse(consoleOutput.contains("Initiating Jersey application"), "Web console started"); assertTrue(consoleOutput.contains("Started application ExampleApp"), "ExampleApp not started"); assertTrue(consoleOutput.contains("Server started. Press return to stop."), "Server started message not output"); assertTrue(consoleError.isEmpty()); return null; } }; try { Future<Void> future = executor.submit(cli); // Wait 15s for console output, then send CR to stop Thread.sleep(15000L); OutputStream out = brooklyn.getOutputStream(); out.write('\n'); out.flush(); future.get(10, TimeUnit.SECONDS); // Check error code from process is 0 assertEquals(brooklyn.exitValue(), 0, "Command terminated with error status"); } catch (TimeoutException te) { fail("Timed out waiting for process to complete"); } catch (ExecutionException ee) { throw ee.getCause(); } finally { brooklyn.destroy(); } } /** * Checks if a correct error and help message is given if using incorrect params. */ @Test(groups = "Integration") public void testLaunchCliAppParamError() throws Throwable { // Invoke the brooklyn script with incorrect arguments ProcessBuilder pb = new ProcessBuilder(); pb.environment().remove("BROOKLYN_HOME"); pb.environment().put("BROOKLYN_CLASSPATH", BROOKLYN_CLASSPATH); pb.command(BROOKLYN_BIN_PATH, "launch", "nothing", "--app"); final Process brooklyn = pb.start(); Callable<Void> cli = new Callable<Void>() { @Override public Void call() throws Exception { // Get the console output of running that command String consoleOutput = convertStreamToString(brooklyn.getInputStream()); String consoleError = convertStreamToString(brooklyn.getErrorStream()); // Check if the output looks as expected assertTrue(consoleError.contains("Parse error: Required values for option 'application class or file' not provided"), "Parse error not reported"); assertTrue(consoleError.contains("NAME") && consoleError.contains("SYNOPSIS") && consoleError.contains("OPTIONS") && consoleError.contains("COMMANDS"), "Usage info not printed"); assertTrue(consoleOutput.isEmpty()); return null; } }; try { Future<Void> future = executor.submit(cli); future.get(10, TimeUnit.SECONDS); // Check error code from process assertEquals(brooklyn.exitValue(), 1, "Command returned wrong status"); } catch (TimeoutException te) { fail("Timed out waiting for process to complete"); } catch (ExecutionException ee) { throw ee.getCause(); } finally { brooklyn.destroy(); } } /** * Checks if a correct error and help message is given if using incorrect command. */ @Test(groups = "Integration") public void testLaunchCliAppCommandError() throws Throwable { // Invoke the brooklyn script with incorrect arguments ProcessBuilder pb = new ProcessBuilder(); pb.environment().remove("BROOKLYN_HOME"); pb.environment().put("BROOKLYN_CLASSPATH", BROOKLYN_CLASSPATH); pb.command(BROOKLYN_BIN_PATH, "biscuit"); final Process brooklyn = pb.start(); Callable<Void> cli = new Callable<Void>() { @Override public Void call() throws Exception { // Get the console output of running that command String consoleOutput = convertStreamToString(brooklyn.getInputStream()); String consoleError = convertStreamToString(brooklyn.getErrorStream()); // Check if the output looks as expected assertTrue(consoleError.contains("Parse error: No command specified"), "Parse error not reported"); assertTrue(consoleError.contains("NAME") && consoleError.contains("SYNOPSIS") && consoleError.contains("OPTIONS") && consoleError.contains("COMMANDS"), "Usage info not printed"); assertTrue(consoleOutput.isEmpty()); return null; } }; try { Future<Void> future = executor.submit(cli); future.get(10, TimeUnit.SECONDS); // Check error code from process assertEquals(brooklyn.exitValue(), 1, "Command returned wrong status"); } catch (TimeoutException te) { fail("Timed out waiting for process to complete"); } catch (ExecutionException ee) { throw ee.getCause(); } finally { brooklyn.destroy(); } } /** * Checks if a correct error and help message is given if using incorrect command. */ @Test(groups = "Integration") public void testLaunchCliAppLaunchError() throws Throwable { // Invoke the brooklyn script with incorrect arguments ProcessBuilder pb = new ProcessBuilder(); pb.environment().remove("BROOKLYN_HOME"); pb.environment().put("BROOKLYN_CLASSPATH", BROOKLYN_CLASSPATH); pb.command(BROOKLYN_BIN_PATH, "launch", "--app", "org.eample.DoesNotExist", "--location", "nowhere"); final Process brooklyn = pb.start(); Callable<Void> cli = new Callable<Void>() { @Override public Void call() throws Exception { // Get the console output of running that command String consoleOutput = convertStreamToString(brooklyn.getInputStream()); String consoleError = convertStreamToString(brooklyn.getErrorStream()); // Check if the output looks as expected assertTrue(consoleOutput.contains("ERROR Execution error: brooklyn.util.ResourceUtils.getResourceFromUrl"), "Execution error not logged"); assertTrue(consoleError.contains("Execution error: Error getting resource for LaunchCommand"), "Execution error not reported"); return null; } }; try { Future<Void> future = executor.submit(cli); future.get(10, TimeUnit.SECONDS); // Check error code from process assertEquals(brooklyn.exitValue(), 2, "Command returned wrong status"); } catch (TimeoutException te) { fail("Timed out waiting for process to complete"); } catch (ExecutionException ee) { throw ee.getCause(); } finally { brooklyn.destroy(); } } }
package VASSAL.configure; import java.awt.Component; import java.awt.Font; import java.awt.Frame; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import VASSAL.build.Buildable; import VASSAL.build.Builder; import VASSAL.build.Configurable; import VASSAL.build.GameModule; import VASSAL.build.IllegalBuildException; import VASSAL.build.module.Chatter; import VASSAL.build.module.Plugin; import VASSAL.build.module.documentation.HelpFile; import VASSAL.build.module.documentation.HelpWindow; import VASSAL.build.module.map.boardPicker.board.mapgrid.Zone; import VASSAL.build.module.properties.GlobalProperties; import VASSAL.build.module.properties.GlobalProperty; import VASSAL.build.module.properties.ZoneProperty; import VASSAL.build.widget.CardSlot; import VASSAL.build.widget.PieceSlot; import VASSAL.counters.MassPieceLoader; import VASSAL.i18n.Resources; import VASSAL.i18n.TranslateAction; import VASSAL.launch.EditorWindow; import VASSAL.tools.ErrorDialog; import VASSAL.tools.ReflectionUtils; import VASSAL.tools.menu.MenuManager; import VASSAL.tools.swing.SwingUtils; /** * This is the Configuration Tree that appears in the Configuration window * when editing a VASSAL module. Each node in the tree structure is a * {@link VASSAL.build.Configurable} object, whose child nodes are obtained * via {@link VASSAL.build.Configurable#getConfigureComponents}. */ public class ConfigureTree extends JTree implements PropertyChangeListener, MouseListener, MouseMotionListener, TreeSelectionListener { private static final long serialVersionUID = 1L; protected Map<Configurable, DefaultMutableTreeNode> nodes = new HashMap<>(); protected DefaultMutableTreeNode copyData; protected DefaultMutableTreeNode cutData; protected HelpWindow helpWindow; protected EditorWindow editorWindow; protected Configurable selected; protected int selectedRow; protected String searchCmd; protected String moveCmd; protected String deleteCmd; protected String pasteCmd; protected String copyCmd; protected String cutCmd; protected String helpCmd; protected String propertiesCmd; protected String translateCmd; protected KeyStroke cutKey; protected KeyStroke copyKey; protected KeyStroke pasteKey; protected KeyStroke deleteKey; protected KeyStroke moveKey; protected KeyStroke searchKey; protected KeyStroke helpKey; protected KeyStroke propertiesKey; protected KeyStroke translateKey; protected Action cutAction; protected Action copyAction; protected Action pasteAction; protected Action deleteAction; protected Action moveAction; protected Action searchAction; protected Action propertiesAction; protected Action translateAction; protected Action helpAction; // Search parameters protected String searchString; // Current search string protected boolean matchCase; // True if case-sensitive protected boolean matchNames; // True if match configurable names protected boolean matchTypes; // True if match class names public static Font POPUP_MENU_FONT = new Font("Dialog", 0, 11); protected static List<AdditionalComponent> additionalComponents = new ArrayList<>(); /** Creates new ConfigureTree */ public ConfigureTree(Configurable root, HelpWindow helpWindow) { this(root, helpWindow, null); } public ConfigureTree(Configurable root, HelpWindow helpWindow, EditorWindow editorWindow) { toggleClickCount = 3; this.helpWindow = helpWindow; this.editorWindow = editorWindow; setShowsRootHandles(true); setModel(new DefaultTreeModel(buildTreeNode(root))); setCellRenderer(buildRenderer()); addMouseListener(this); addMouseMotionListener(this); addTreeSelectionListener(this); searchCmd = Resources.getString("Editor.search"); //$NON-NLS-1$ moveCmd = Resources.getString("Editor.move"); //$NON-NLS-1$ deleteCmd = Resources.getString("Editor.delete"); //$NON-NLS-1$ pasteCmd = Resources.getString("Editor.paste"); //$NON-NLS-1$ copyCmd = Resources.getString("Editor.copy"); //$NON-NLS-1$ cutCmd = Resources.getString("Editor.cut"); //$NON-NLS-1$ propertiesCmd = Resources.getString("Editor.ModuleEditor.properties"); //$NON-NLS-1$ translateCmd = Resources.getString("Editor.ModuleEditor.translate"); //$NON-NLS-1$ helpCmd = Resources.getString("Editor.ModuleEditor.component_help"); //$NON-NLS-1$ int mask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx(); cutKey = KeyStroke.getKeyStroke(KeyEvent.VK_X, mask); copyKey = KeyStroke.getKeyStroke(KeyEvent.VK_C, mask); pasteKey = KeyStroke.getKeyStroke(KeyEvent.VK_V, mask); deleteKey = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0); moveKey = KeyStroke.getKeyStroke(KeyEvent.VK_M, mask); searchKey = KeyStroke.getKeyStroke(KeyEvent.VK_F, mask); propertiesKey = KeyStroke.getKeyStroke(KeyEvent.VK_P, mask); translateKey = KeyStroke.getKeyStroke(KeyEvent.VK_T, mask); helpKey = KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0); copyAction = new KeyAction(copyCmd, copyKey); pasteAction = new KeyAction(pasteCmd, pasteKey); cutAction = new KeyAction(cutCmd, cutKey); deleteAction = new KeyAction(deleteCmd, deleteKey); moveAction = new KeyAction(moveCmd, moveKey); searchAction = new KeyAction(searchCmd, searchKey); propertiesAction = new KeyAction(propertiesCmd, propertiesKey); translateAction = new KeyAction(translateCmd, translateKey); helpAction = new KeyAction(helpCmd, helpKey); /* * Cut, Copy and Paste will not work unless I add them to the JTree input and action maps. Why??? All the others * work fine. */ getInputMap().put(cutKey, cutCmd); getInputMap().put(copyKey, copyCmd); getInputMap().put(pasteKey, pasteCmd); getInputMap().put(deleteKey, deleteCmd); getActionMap().put(cutCmd, cutAction); getActionMap().put(copyCmd, copyAction); getActionMap().put(pasteCmd, pasteAction); getActionMap().put(deleteCmd, deleteAction); this.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); //FIXME: remember these search parameters from session to session searchString=""; matchCase = false; matchTypes = true; matchNames = true; } public JFrame getFrame() { return editorWindow; } class KeyAction extends AbstractAction { private static final long serialVersionUID = 1L; protected String actionName; public KeyAction(String name, KeyStroke key) { super(name); actionName = name; putValue(Action.ACCELERATOR_KEY, key); } @Override public void actionPerformed(ActionEvent e) { doKeyAction(actionName); } } protected Renderer buildRenderer() { return new Renderer(); } /** * Tell our enclosing EditorWindow that we are now clean * or dirty. * * @param changed true = state is not dirty */ protected void notifyStateChanged(boolean changed) { if (editorWindow != null) { editorWindow.treeStateChanged(changed); } } private Chatter chatter; private void chat (String text) { if (chatter == null) { chatter = GameModule.getGameModule().getChatter(); } if (chatter != null) { chatter.show("- " + text); } } protected Configurable getTarget(int x, int y) { TreePath path = getPathForLocation(x, y); Configurable target = null; if (path != null) { target = (Configurable) ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); } return target; } protected DefaultMutableTreeNode buildTreeNode(Configurable c) { c.addPropertyChangeListener(this); final DefaultMutableTreeNode node = new DefaultMutableTreeNode(c); final Configurable[] children = c.getConfigureComponents(); for (Configurable child : children) { if (! (child instanceof Plugin)) { // Hide Plug-ins node.add(buildTreeNode(child)); } } nodes.put(c, node); return node; } protected void addAction(JPopupMenu menu, Action a) { if (a != null) { menu.add(a).setFont(POPUP_MENU_FONT); } } private void addActionGroup(JPopupMenu menu, ArrayList<Action> l) { boolean empty = true; for (Action a : l) { if (a != null) { menu.add(a).setFont(POPUP_MENU_FONT); empty = false; } } if (!empty) { menu.addSeparator(); } l.clear(); } protected JPopupMenu buildPopupMenu(final Configurable target) { final JPopupMenu popup = new JPopupMenu(); final ArrayList<Action> l = new ArrayList<>(); l.add(buildEditAction(target)); l.add(buildEditPiecesAction(target)); addActionGroup(popup, l); l.add(buildTranslateAction(target)); addActionGroup(popup, l); l.add(buildHelpAction(target)); addActionGroup(popup, l); l.add(buildSearchAction(target)); addActionGroup(popup, l); l.add(buildDeleteAction(target)); l.add(buildCutAction(target)); l.add(buildCopyAction(target)); l.add(buildPasteAction(target)); l.add(buildMoveAction(target)); addActionGroup(popup, l); for (Action a : buildAddActionsFor(target)) { addAction(popup, a); } if (hasChild(target, PieceSlot.class) || hasChild(target, CardSlot.class)) { addAction(popup, buildMassPieceLoaderAction(target)); } addAction(popup, buildImportAction(target)); return popup; } /** * Enumerates our configure tree in preparation for searching it * @param root - root of our module's tree. * @returns a list of search nodes */ private List<DefaultMutableTreeNode> getSearchNodes(DefaultMutableTreeNode root) { List<DefaultMutableTreeNode> searchNodes = new ArrayList<>(); Enumeration<?> e = root.preorderEnumeration(); while(e.hasMoreElements()) { searchNodes.add((DefaultMutableTreeNode)e.nextElement()); } return searchNodes; } /** * Checks a single string against our search parameters * @param target - string to check * @param searchString - our search string * @return true if this is a match based on our "matchCase" checkbox */ public final boolean checkString(String target, String searchString) { if (matchCase) { return target.contains(searchString); } else { return target.toLowerCase().contains(searchString.toLowerCase()); } } /** * @param node - any node of our module tree * @param searchString - our search string * @return true if the node matches our searchString based on search configuration ("match" checkboxes) */ public final boolean checkNode(DefaultMutableTreeNode node, String searchString) { Configurable c = null; c = (Configurable) node.getUserObject(); if (matchNames) { String objectName = c.getConfigureName(); if (objectName != null && checkString(objectName, searchString)) { return true; } } if (matchTypes) { String className = getConfigureName(c.getClass()); if (className != null && checkString(className, searchString)) { return true; } } return false; } /** * Search through the tree, starting at the currently selected location (and wrapping around if needed) * Compare nodes until we find our search string (or have searched everything we can search) * @return the node we found, or null if none */ public final DefaultMutableTreeNode findNode(String searchString) { List<DefaultMutableTreeNode> searchNodes = getSearchNodes((DefaultMutableTreeNode)getModel().getRoot()); DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)getLastSelectedPathComponent(); DefaultMutableTreeNode foundNode = null; int bookmark = -1; if (currentNode != null) { for (int index = 0; index < searchNodes.size(); index++) { if (searchNodes.get(index) == currentNode) { bookmark = index; break; } } } for (int index = bookmark + 1; index < searchNodes.size(); index++) { if (checkNode(searchNodes.get(index), searchString)) { foundNode = searchNodes.get(index); break; } } if (foundNode == null) { for (int index = 0; index <= bookmark; index++) { if (checkNode(searchNodes.get(index), searchString)) { foundNode = searchNodes.get(index); break; } } } return foundNode; } /** * @return how many total nodes match the search string */ public final int getNumMatches(String searchString) { List<DefaultMutableTreeNode> searchNodes = getSearchNodes((DefaultMutableTreeNode)getModel().getRoot()); int hits = 0; for (int index = 0; index < searchNodes.size(); index++) { if (checkNode(searchNodes.get(index), searchString)) { hits++; } } return hits; } /** * @return Search action - runs search dialog box, then searches */ protected Action buildSearchAction(final Configurable target) { final Action a = new AbstractAction(searchCmd) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { final JDialog d = new JDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, ConfigureTree.this), true); d.setTitle(searchCmd); d.setLayout(new BoxLayout(d.getContentPane(), BoxLayout.Y_AXIS)); Box box = Box.createHorizontalBox(); box.add(new JLabel("String to find: ")); box.add(Box.createHorizontalStrut(10)); final JTextField search = new JTextField(searchString, 32); box.add(search); d.add(box); box = Box.createHorizontalBox(); final JCheckBox sensitive = new JCheckBox(Resources.getString("Editor.search_case"), matchCase); box.add(sensitive); final JCheckBox names = new JCheckBox(Resources.getString("Editor.search_names"), matchNames); box.add(names); final JCheckBox types = new JCheckBox(Resources.getString("Editor.search_types"), matchTypes); box.add(types); d.add(box); box = Box.createHorizontalBox(); JButton find = new JButton(Resources.getString("Editor.search_next")); find.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean anyChanges = (!searchString.equals(search.getText())) || (matchCase != sensitive.isSelected()) || (matchNames != names.isSelected()) || (matchTypes != types.isSelected()); searchString = search.getText(); matchCase = sensitive.isSelected(); matchNames = names.isSelected(); matchTypes = types.isSelected(); if (!matchNames && !matchTypes) { matchNames = true; names.setSelected(true); chat (Resources.getString("Editor.search_all_off")); } if (!searchString.isEmpty()) { if (anyChanges) { int matches = getNumMatches(searchString); chat (matches + " " + Resources.getString("Editor.search_count") + searchString); } DefaultMutableTreeNode node = findNode(searchString); if (node != null) { TreePath path = new TreePath(node.getPath()); setSelectionPath(path); scrollPathToVisible(path); } else { chat (Resources.getString("Editor.search_none_found") + searchString); } } } }); JButton cancel = new JButton(Resources.getString(Resources.CANCEL)); cancel.addActionListener(e1 -> d.dispose()); box.add(find); box.add(cancel); d.add(box); d.getRootPane().setDefaultButton(find); // Enter key activates search // Esc Key cancels KeyStroke k = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); int w = JComponent.WHEN_IN_FOCUSED_WINDOW; d.getRootPane().registerKeyboardAction(ee -> d.dispose(), k, w); d.pack(); d.setLocationRelativeTo(d.getParent()); d.setVisible(true); } }; a.setEnabled(true); return a; } protected Action buildMoveAction(final Configurable target) { Action a = null; if (getTreeNode(target).getParent() != null) { a = new AbstractAction(moveCmd) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { final JDialog d = new JDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, ConfigureTree.this), true); d.setTitle(target.getConfigureName() == null ? moveCmd : moveCmd + " " + target.getConfigureName()); d.setLayout(new BoxLayout(d.getContentPane(), BoxLayout.Y_AXIS)); Box box = Box.createHorizontalBox(); box.add(new JLabel("Move to position")); box.add(Box.createHorizontalStrut(10)); final JComboBox<String> select = new JComboBox<>(); TreeNode parentNode = getTreeNode(target).getParent(); for (int i = 0; i < parentNode.getChildCount(); ++i) { Configurable c = (Configurable) ((DefaultMutableTreeNode) parentNode.getChildAt(i)).getUserObject(); String name = (c.getConfigureName() != null ? c.getConfigureName() : "") + " [" + getConfigureName(c.getClass()) + "]"; select.addItem((i + 1) + ": " + name); } final DefaultMutableTreeNode targetNode = getTreeNode(target); final int currentIndex = targetNode.getParent().getIndex(targetNode); select.setSelectedIndex(currentIndex); box.add(select); JButton ok = new JButton(Resources.getString(Resources.OK)); ok.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int index = select.getSelectedIndex(); if (currentIndex != index) { Configurable parent = getParent(targetNode); if (remove(parent, target)) { insert(parent, target, index); } } d.dispose(); } }); d.add(box); d.add(ok); d.pack(); d.setLocationRelativeTo(d.getParent()); d.setVisible(true); } }; } return a; } protected Action buildCutAction(final Configurable target) { Action a = null; if (getTreeNode(target).getParent() != null) { a = new AbstractAction(cutCmd) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { cutData = getTreeNode(target); copyData = null; updateEditMenu(); } }; } return a; } protected Action buildCopyAction(final Configurable target) { Action a = null; if (getTreeNode(target).getParent() != null) { a = new AbstractAction(copyCmd) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { copyData = getTreeNode(target); cutData = null; updateEditMenu(); } }; } return a; } protected Action buildPasteAction(final Configurable target) { final Action a = new AbstractAction(pasteCmd) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { if (cutData != null) { final DefaultMutableTreeNode targetNode = getTreeNode(target); final Configurable cutObj = (Configurable) cutData.getUserObject(); final Configurable convertedCutObj = convertChild(target, cutObj); if (remove(getParent(cutData), cutObj)) { insert(target, convertedCutObj, targetNode.getChildCount()); } copyData = getTreeNode(convertedCutObj); } else if (copyData != null) { final Configurable copyBase = (Configurable) copyData.getUserObject(); Configurable clone = null; try { clone = convertChild(target, copyBase.getClass().getConstructor().newInstance()); } catch (Throwable t) { ReflectionUtils.handleNewInstanceFailure(t, copyBase.getClass()); } if (clone != null) { clone.build(copyBase.getBuildElement(Builder.createNewDocument())); insert(target, clone, getTreeNode(target).getChildCount()); updateGpIds(clone); } } cutData = null; updateEditMenu(); } }; a.setEnabled(isValidPasteTarget(target)); return a; } protected boolean isValidPasteTarget(Configurable target) { return (cutData != null && isValidParent(target, (Configurable) cutData.getUserObject())) || (copyData != null && isValidParent(target, (Configurable) copyData.getUserObject())); } /** * Some components need to be converted to a new type before insertion. * * Currently this is used to allow cut and paste of CardSlots and PieceSlots * between Decks and GamePiece Palette components. * * @param parent * @param child * @return new Child */ protected Configurable convertChild(Configurable parent, Configurable child) { if (child.getClass() == PieceSlot.class && isAllowedChildClass(parent, CardSlot.class)) { return new CardSlot((PieceSlot) child); } else if (child.getClass() == CardSlot.class && isAllowedChildClass(parent, PieceSlot.class)) { return new PieceSlot((CardSlot) child); } else { return child; } } protected boolean isAllowedChildClass(Configurable parent, Class<?> childClass) { final Class<?>[] allowableClasses = parent.getAllowableConfigureComponents(); for (Class<?> allowableClass : allowableClasses) { if (allowableClass == childClass) { return true; } } return false; } /** * Allocate new PieceSlot Id's to any PieceSlot sub-components * * @param c Configurable to update */ public void updateGpIds(Configurable c) { if (c instanceof PieceSlot) { ((PieceSlot) c).updateGpId(GameModule.getGameModule()); } else { for (Configurable comp : c.getConfigureComponents()) updateGpIds(comp); } } protected Action buildImportAction(final Configurable target) { Action a = new AbstractAction("Add Imported Class") { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent evt) { final Configurable child = importConfigurable(); if (child != null) { try { child.build(null); final Configurable c = target; if (child.getConfigurer() != null) { PropertiesWindow w = new PropertiesWindow((Frame) SwingUtilities.getAncestorOfClass(Frame.class, ConfigureTree.this), false, child, helpWindow) { private static final long serialVersionUID = 1L; @Override public void save() { super.save(); insert(c, child, getTreeNode(c).getChildCount()); } @Override public void cancel() { dispose(); } }; w.setVisible(true); } else { insert(c, child, getTreeNode(c).getChildCount()); } } // FIXME: review error message catch (Exception ex) { JOptionPane.showMessageDialog(getTopLevelAncestor(), "Error adding " + getConfigureName(child) + " to " + getConfigureName(target) + "\n" + ex.getMessage(), "Illegal configuration", JOptionPane.ERROR_MESSAGE); } } } }; return a; } protected Action buildMassPieceLoaderAction(final Configurable target) { Action a = null; final ConfigureTree tree = this; if (getTreeNode(target).getParent() != null) { String desc = "Add Multiple " + (hasChild(target, CardSlot.class) ? "Cards" : "Pieces"); a = new AbstractAction(desc) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { new MassPieceLoader(tree, target).load(); } }; } return a; } protected boolean hasChild(Configurable parent, Class<?> childClass) { for (Class<?> c : parent.getAllowableConfigureComponents()) { if (c.equals(childClass)) { return true; } } return false; } protected List<Action> buildAddActionsFor(final Configurable target) { final ArrayList<Action> l = new ArrayList<>(); for (Class<? extends Buildable> newConfig : target.getAllowableConfigureComponents()) { l.add(buildAddAction(target, newConfig)); } for (AdditionalComponent add : additionalComponents) { if (target.getClass().equals(add.getParent())) { final Class<? extends Buildable> newConfig = add.getChild(); l.add(buildAddAction(target, newConfig)); } } return l; } /** * @deprecated Use {@link #buildAddActionsFor(final Configurable)} instead. */ @Deprecated protected Enumeration<Action> buildAddActions(final Configurable target) { return Collections.enumeration(buildAddActionsFor(target)); } protected Action buildAddAction(final Configurable target, final Class<? extends Buildable> newConfig) { AbstractAction action = new AbstractAction("Add " + getConfigureName(newConfig)) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent evt) { Configurable ch = null; try { ch = (Configurable) newConfig.getConstructor().newInstance(); } catch (Throwable t) { ReflectionUtils.handleNewInstanceFailure(t, newConfig); } if (ch != null) { final Configurable child = ch; child.build(null); if (child instanceof PieceSlot) { ((PieceSlot) child).updateGpId(GameModule.getGameModule()); } final Configurable c = target; if (child.getConfigurer() != null) { if (insert(target, child, getTreeNode(target).getChildCount())) { PropertiesWindow w = new PropertiesWindow((Frame) SwingUtilities.getAncestorOfClass(Frame.class, ConfigureTree.this), false, child, helpWindow) { private static final long serialVersionUID = 1L; @Override public void save() { super.save(); } @Override public void cancel() { ConfigureTree.this.remove(c, child); dispose(); } }; w.setVisible(true); } } else { insert(c, child, getTreeNode(c).getChildCount()); } } } }; return action; } protected Action buildHelpAction(final Configurable target) { Action showHelp; HelpFile helpFile = target.getHelpFile(); if (helpFile == null) { showHelp = new ShowHelpAction(null,null); showHelp.setEnabled(false); } else { showHelp = new ShowHelpAction(helpFile.getContents(), null); } return showHelp; } protected Action buildCloneAction(final Configurable target) { final DefaultMutableTreeNode targetNode = getTreeNode(target); if (targetNode.getParent() != null) { return new AbstractAction("Clone") { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent evt) { Configurable clone = null; try { clone = target.getClass().getConstructor().newInstance(); } catch (Throwable t) { ReflectionUtils.handleNewInstanceFailure(t, target.getClass()); } if (clone != null) { clone.build(target.getBuildElement(Builder.createNewDocument())); insert(getParent(targetNode), clone, targetNode.getParent().getIndex(targetNode) + 1); } } }; } else { return null; } } protected Configurable getParent(final DefaultMutableTreeNode targetNode) { DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) targetNode.getParent(); return parentNode == null ? null : (Configurable) parentNode.getUserObject(); } protected Action buildDeleteAction(final Configurable target) { final DefaultMutableTreeNode targetNode = getTreeNode(target); final Configurable parent = getParent(targetNode); if (targetNode.getParent() != null) { return new AbstractAction(deleteCmd) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent evt) { int row = selectedRow; remove(parent, target); if (row < getRowCount()) { setSelectionRow(row); } else { setSelectionRow(row - 1); } } }; } else { return null; } } protected Action buildEditPiecesAction(final Configurable target) { if (canContainGamePiece(target)) { return new EditContainedPiecesAction(target); } else { return null; } } protected Action buildEditAction(final Configurable target) { return new EditPropertiesAction(target, helpWindow, (Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), this); } protected Action buildTranslateAction(final Configurable target) { Action a = new TranslateAction(target, helpWindow, this); a.setEnabled(target.getI18nData().isTranslatable()); return a; } public boolean canContainGamePiece(final Configurable target) { boolean canContainPiece = false; for (Class<?> c : target.getAllowableConfigureComponents()) { if (VASSAL.build.widget.PieceSlot.class.isAssignableFrom(c)) { canContainPiece = true; break; } } return canContainPiece; } protected boolean remove(Configurable parent, Configurable child) { try { child.removeFrom(parent); parent.remove(child); ((DefaultTreeModel) getModel()).removeNodeFromParent(getTreeNode(child)); notifyStateChanged(true); return true; } // FIXME: review error message catch (IllegalBuildException err) { JOptionPane.showMessageDialog(getTopLevelAncestor(), "Cannot delete " + getConfigureName(child) + " from " + getConfigureName(parent) + "\n" + err.getMessage(), "Illegal configuration", JOptionPane.ERROR_MESSAGE); return false; } } protected boolean insert(Configurable parent, Configurable child, int index) { Configurable theChild = child; // Convert subclasses of GlobalProperty to an actual GlobalProperty before inserting into the GlobalProperties container if (parent.getClass() == GlobalProperties.class && child.getClass() == ZoneProperty.class) { theChild = new GlobalProperty((GlobalProperty) child); } if (parent.getClass() == Zone.class && child.getClass() == GlobalProperty.class) { theChild = new ZoneProperty((GlobalProperty) child); } DefaultMutableTreeNode childNode = buildTreeNode(theChild); DefaultMutableTreeNode parentNode = getTreeNode(parent); Configurable[] oldContents = parent.getConfigureComponents(); boolean succeeded = true; ArrayList<Configurable> moveToBack = new ArrayList<>(); for (int i = index; i < oldContents.length; ++i) { try { oldContents[i].removeFrom(parent); parent.remove(oldContents[i]); } // FIXME: review error message catch (IllegalBuildException err) { JOptionPane.showMessageDialog(getTopLevelAncestor(), "Can't insert " + getConfigureName(theChild) + " before " + getConfigureName(oldContents[i]), "Illegal configuration", JOptionPane.ERROR_MESSAGE); for (int j = index; j < i; ++j) { parent.add(oldContents[j]); oldContents[j].addTo(parent); } return false; } moveToBack.add(oldContents[i]); } try { theChild.addTo(parent); parent.add(theChild); parentNode.insert(childNode, index); int[] childI = new int[1]; childI[0] = index; ((DefaultTreeModel) getModel()).nodesWereInserted(parentNode, childI); } // FIXME: review error message catch (IllegalBuildException err) { JOptionPane.showMessageDialog(getTopLevelAncestor(), "Can't add " + getConfigureName(child) + "\n" + err.getMessage(), "Illegal configuration", JOptionPane.ERROR_MESSAGE); succeeded = false; } for (Configurable c : moveToBack) { parent.add(c); c.addTo(parent); } notifyStateChanged(true); return succeeded; } @Override public void propertyChange(PropertyChangeEvent evt) { DefaultMutableTreeNode newValue = getTreeNode((Configurable) evt.getSource()); ((DefaultTreeModel) getModel()).nodeChanged(newValue); } static class Renderer extends javax.swing.tree.DefaultTreeCellRenderer { private static final long serialVersionUID = 1L; @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { if (value instanceof DefaultMutableTreeNode) { final Configurable c = (Configurable) ((DefaultMutableTreeNode) value).getUserObject(); if (c != null) { leaf = c.getAllowableConfigureComponents().length == 0; value = (c.getConfigureName() != null ? c.getConfigureName() : "") + " [" + getConfigureName(c.getClass()) + "]"; } } return super.getTreeCellRendererComponent( tree, value, sel, expanded, leaf, row, hasFocus ); } } /** * Returns the name of the class for display purposes. Reflection is * used to call <code>getConfigureTypeName()</code>, which should be * a static method if it exists in the given class. (This is necessary * because static methods are not permitted in interfaces.) * * @param the class whose configure name will be returned * @return the configure name of the class */ public static String getConfigureName(Class<?> c) { try { return (String) c.getMethod("getConfigureTypeName").invoke(null); } catch (NoSuchMethodException e) { // Ignore. This is normal, since some classes won't have this method. } catch (IllegalAccessException | ExceptionInInitializerError | NullPointerException | InvocationTargetException | IllegalArgumentException e) { ErrorDialog.bug(e); } return c.getName().substring(c.getName().lastIndexOf(".") + 1); } public static String getConfigureName(Configurable c) { if (c.getConfigureName() != null && c.getConfigureName().length() > 0) { return c.getConfigureName(); } else { return getConfigureName(c.getClass()); } } protected Configurable importConfigurable() { final String className = JOptionPane.showInputDialog( getTopLevelAncestor(), "Enter fully-qualified name of Java class to import"); if (className == null) return null; Object o = null; try { o = GameModule.getGameModule().getDataArchive() .loadClass(className).getConstructor().newInstance(); } catch (Throwable t) { ReflectionUtils.handleImportClassFailure(t, className); } if (o == null) return null; if (o instanceof Configurable) return (Configurable) o; ErrorDialog.show("Error.not_a_configurable", className); return null; } protected void maybePopup(MouseEvent e) { Configurable target = getTarget(e.getX(), e.getY()); if (target == null) { return; } setSelectionRow(getClosestRowForLocation(e.getX(), e.getY())); JPopupMenu popup = buildPopupMenu(target); popup.show(ConfigureTree.this, e.getX(), e.getY()); popup.addPopupMenuListener(new javax.swing.event.PopupMenuListener() { @Override public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) { repaint(); } @Override public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) { repaint(); } @Override public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) { } }); } @Override public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { maybePopup(e); } } // FIXME: should clicked handling be in mouseClicked()? @Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { maybePopup(e); } else if (e.getClickCount() == 2 && SwingUtils.isLeftMouseButton(e)) { Configurable target = getTarget(e.getX(), e.getY()); if (target == null) { return; } if (target.getConfigurer() != null) { Action a = buildEditAction(target); if (a != null) { a.actionPerformed(new ActionEvent(e.getSource(), ActionEvent.ACTION_PERFORMED, "Edit")); } } } } /* * protected void performDrop(Configurable target) { DefaultMutableTreeNode dragNode = getTreeNode(dragging); * DefaultMutableTreeNode targetNode = getTreeNode(target); Configurable parent = null; int index = 0; if * (isValidParent(target, dragging)) { parent = target; index = targetNode.getChildCount(); if (dragNode.getParent() == * targetNode) { index--; } } else if (targetNode.getParent() != null && isValidParent(getParent(targetNode), * dragging)) { parent = (Configurable) ((DefaultMutableTreeNode) targetNode.getParent()).getUserObject(); index = * targetNode.getParent().getIndex(targetNode); } if (parent != null) { remove(getParent(dragNode), dragging); * insert(parent, dragging, index); } dragging = null; } */ public DefaultMutableTreeNode getTreeNode(Configurable target) { return nodes.get(target); } @Override public void mouseDragged(MouseEvent evt) { } protected boolean isValidParent(Configurable parent, Configurable child) { if (parent != null && child != null) { final Class<?>[] c = parent.getAllowableConfigureComponents(); for (Class<?> aClass : c) { if (aClass.isAssignableFrom(child.getClass()) || ((aClass == CardSlot.class) && (child.getClass() == PieceSlot.class)) || // Allow PieceSlots to be pasted to Decks ((aClass == ZoneProperty.class) && (child.getClass() == GlobalProperty.class)) // Allow Global Properties to be saved as Zone Properties ) { return true; } } } return false; } @Override public void mouseClicked(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { } /* * Refresh the display of a node */ public void nodeUpdated(Configurable target) { DefaultMutableTreeNode node = getTreeNode(target); Configurable parent = getParent(node); if (remove(parent, target)) { insert(parent, target, 0); } } /** * Configurers that add or remove their own children directly should implement the Mutable interface so that * ConfigureTree can refresh the changed node. */ public interface Mutable { } /** * Build an AddAction and execute it to request a new component from the user * * @param parent * Target Parent * @param type * Type to add */ public void externalInsert(Configurable parent, Configurable child) { insert(parent, child, getTreeNode(parent).getChildCount()); } public Action getHelpAction() { return helpAction; } public void populateEditMenu(EditorWindow ew) { final MenuManager mm = MenuManager.getInstance(); mm.addAction("Editor.delete", deleteAction); mm.addAction("Editor.cut", cutAction); mm.addAction("Editor.copy", copyAction); mm.addAction("Editor.paste", pasteAction); mm.addAction("Editor.move", moveAction); mm.addAction("Editor.search", searchAction); mm.addAction("Editor.ModuleEditor.properties", propertiesAction); mm.addAction("Editor.ModuleEditor.translate", translateAction); updateEditMenu(); } /** * Handle main Edit menu selections/accelerators * * @param action * Edit command name */ protected void doKeyAction(String action) { DefaultMutableTreeNode targetNode = (DefaultMutableTreeNode) this.getLastSelectedPathComponent(); if (targetNode != null) { Configurable target = (Configurable) targetNode.getUserObject(); Action a = null; if (cutCmd.equals(action)) { a = buildCutAction(target); } else if (copyCmd.equals(action)) { a = buildCopyAction(target); } else if (pasteCmd.equals(action) || action.equals(pasteKey.getKeyChar())) { a = buildPasteAction(target); } else if (deleteCmd.equals(action)) { a = buildDeleteAction(target); } else if (moveCmd.equals(action)) { a = buildMoveAction(target); } else if (searchCmd.equals(action)) { a = buildSearchAction(target); } else if (propertiesCmd.equals(action)) { a = buildEditAction(target); } else if (translateCmd.equals(action)) { a = buildTranslateAction(target); } else if (helpCmd.equals(action)) { a = buildHelpAction(target); } if (a != null) { a.actionPerformed(null); } } } /** * Tree selection changed, record info about the currently selected component */ @Override public void valueChanged(TreeSelectionEvent e) { selected = null; TreePath path = e.getPath(); if (path != null) { selected = (Configurable) ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); selectedRow = getRowForPath(path); updateEditMenu(); } } protected void updateEditMenu() { deleteAction.setEnabled(selected != null); cutAction.setEnabled(selected != null); copyAction.setEnabled(selected != null); pasteAction.setEnabled(selected != null && isValidPasteTarget(selected)); moveAction.setEnabled(selected != null); searchAction.setEnabled(true); propertiesAction.setEnabled(selected != null && selected.getConfigurer() != null); translateAction.setEnabled(selected != null); } /** * Find the parent Configurable of a specified Configurable * * @param target * @return parent */ protected Configurable getParent(Configurable target) { DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) getTreeNode(target).getParent(); return (Configurable) parentNode.getUserObject(); } /** * Record additional available components to add to the popup menu. * * @param parent * @param child */ public static void addAdditionalComponent(Class<? extends Buildable> parent, Class<? extends Buildable> child) { additionalComponents.add(new AdditionalComponent(parent, child)); } protected static class AdditionalComponent { Class<? extends Buildable> parent; Class<? extends Buildable> child; public AdditionalComponent(Class<? extends Buildable> p, Class<? extends Buildable> c) { parent = p; child = c; } public Class<? extends Buildable> getParent() { return parent; } public Class<? extends Buildable> getChild() { return child; } } }
package festival.negocio.model; import java.io.Serializable; import java.sql.Time; import java.util.Date; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name="Noche", schema="DDS") public class Noche implements Serializable { /** * serialVersionUID */ private static final long serialVersionUID = -1251069962856131116L; /** * id interno de la noche */ @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id_noche") private Integer idNoche; /** * festival al que pertenece la noche */ @ManyToOne @JoinColumn(name="id_festival") private Festival festival; /** * numero de noche dentro del festival */ @Column(name="numero") private Integer numero; /** * fecha en la que se realiza el festival */ @Column(name="fecha") private Date fecha; /** * fecha en la que no se puede comprar mas entradas anticipadas */ @Column(name="fecha_fin_anticipada") private Date fechaFinAnticipada; /** * Descuento por comprar entradas de forma anticipada */ @Column(name="descuento") private Integer descuento; /** * Hora de inicio del festival */ @Column(name="hora_inicio") private Time horaInicio; /** * Las bandas que tocan durante la noche */ @ManyToMany(fetch=FetchType.EAGER) @JoinTable(name="Noche_Banda", schema="DDS", joinColumns={ @JoinColumn(name="id_noche", nullable = false, updatable = false) }, inverseJoinColumns={ @JoinColumn(name="id_banda", nullable = false, updatable = false) } ) List<Banda> listaBandas; /** * Las butacas existentes para esa noche */ @OneToMany(cascade=CascadeType.ALL) @JoinColumn(name="id_noche") private List<Butaca> butacas; /** * @return the idNoche */ public Integer getIdNoche() { return idNoche; } /** * @param idNoche the idNoche to set */ public void setIdNoche(Integer idNoche) { this.idNoche = idNoche; } /** * @return the festival */ public Festival getFestival() { return festival; } /** * @param festival the festival to set */ public void setFestival(Festival festival) { this.festival = festival; } /** * @return the numero */ public Integer getNumero() { return numero; } /** * @param numero the numero to set */ public void setNumero(Integer numero) { this.numero = numero; } /** * @return the fecha */ public Date getFecha() { return fecha; } /** * @param fecha the fecha to set */ public void setFecha(Date fecha) { this.fecha = fecha; } /** * @return the fechaFinAnticipada */ public Date getFechaFinAnticipada() { return fechaFinAnticipada; } /** * @param fechaFinAnticipada the fechaFinAnticipada to set */ public void setFechaFinAnticipada(Date fechaFinAnticipada) { this.fechaFinAnticipada = fechaFinAnticipada; } /** * @return the descuento */ public Integer getDescuento() { return descuento; } /** * @param descuento the descuento to set */ public void setDescuento(Integer descuento) { this.descuento = descuento; } /** * @return the horaInicio */ public Time getHoraInicio() { return horaInicio; } /** * @param horaInicio the horaInicio to set */ public void setHoraInicio(Time horaInicio) { this.horaInicio = horaInicio; } /** * @return the listaBandas */ public List<Banda> getListaBandas() { return listaBandas; } /** * @param listaBandas the listaBandas to set */ public void setListaBandas(List<Banda> listaBandas) { this.listaBandas = listaBandas; } /** * @return the butacas */ public List<Butaca> getButacas() { return butacas; } /** * @param butacas the butacas to set */ public void setButacas(List<Butaca> butacas) { this.butacas = butacas; } }
package ro.isdc.wro.http; import static org.mockito.Mockito.when; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Collection; import java.util.Properties; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import junit.framework.Assert; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import ro.isdc.wro.WroRuntimeException; import ro.isdc.wro.cache.CacheEntry; import ro.isdc.wro.cache.CacheStrategy; import ro.isdc.wro.cache.ContentHashEntry; import ro.isdc.wro.config.Context; import ro.isdc.wro.config.factory.FilterConfigWroConfigurationFactory; import ro.isdc.wro.config.factory.PropertyWroConfigurationFactory; import ro.isdc.wro.config.jmx.ConfigConstants; import ro.isdc.wro.config.jmx.WroConfiguration; import ro.isdc.wro.http.handler.ReloadCacheRequestHandler; import ro.isdc.wro.http.handler.ReloadModelRequestHandler; import ro.isdc.wro.http.handler.RequestHandler; import ro.isdc.wro.http.handler.factory.RequestHandlerFactory; import ro.isdc.wro.http.handler.factory.SimpleRequestHandlerFactory; import ro.isdc.wro.http.support.DelegatingServletOutputStream; import ro.isdc.wro.http.support.UnauthorizedRequestException; import ro.isdc.wro.manager.WroManager; import ro.isdc.wro.manager.factory.BaseWroManagerFactory; import ro.isdc.wro.manager.factory.WroManagerFactory; import ro.isdc.wro.model.WroModel; import ro.isdc.wro.model.factory.WroModelFactory; import ro.isdc.wro.model.factory.XmlModelFactory; import ro.isdc.wro.model.group.Group; import ro.isdc.wro.model.group.InvalidGroupNameException; import ro.isdc.wro.model.resource.processor.impl.css.CssUrlRewritingProcessor; import ro.isdc.wro.util.ObjectFactory; public class TestWroFilter { private WroFilter victim; @Mock private FilterConfig mockFilterConfig; @Mock private HttpServletRequest mockRequest; @Mock private HttpServletResponse mockResponse; @Mock private FilterChain mockFilterChain; @Mock private ServletContext mockServletContext; @Mock private WroManagerFactory mockManagerFactory; @Before public void setUp() throws Exception { Context.set(Context.standaloneContext()); MockitoAnnotations.initMocks(this); when(mockRequest.getAttribute(Mockito.anyString())).thenReturn(null); when(mockManagerFactory.create()).thenReturn(new BaseWroManagerFactory().create()); when(mockFilterConfig.getServletContext()).thenReturn(mockServletContext); when(mockResponse.getOutputStream()).thenReturn(new DelegatingServletOutputStream(new ByteArrayOutputStream())); victim = new WroFilter() { @Override protected void onRuntimeException(final RuntimeException e, final HttpServletResponse response, final FilterChain chain) { throw e; } }; victim.setWroManagerFactory(mockManagerFactory); initFilter(victim); } private WroManagerFactory createValidManagerFactory() { return new BaseWroManagerFactory().setModelFactory(createValidModelFactory()); } private WroModelFactory createValidModelFactory() { return new XmlModelFactory() { @Override protected InputStream getModelResourceAsStream() { return TestWroFilter.class.getResourceAsStream("wro.xml"); } }; } private void initChainOnErrorFilter() throws ServletException { victim = new WroFilter(); initFilter(victim); } private void initFilter(final WroFilter filter) throws ServletException { filter.init(mockFilterConfig); } /** * Set filter init params with proper values and check they are the same in {@link WroConfiguration} object. */ @Test(expected = WroRuntimeException.class) public void testFilterInitParamsAreWrong() throws Exception { Mockito.when(mockFilterConfig.getInitParameter(ConfigConstants.cacheUpdatePeriod.name())).thenReturn( "InvalidNumber"); Mockito.when(mockFilterConfig.getInitParameter(ConfigConstants.modelUpdatePeriod.name())).thenReturn("100"); victim.init(mockFilterConfig); } @Test(expected = WroRuntimeException.class) public void cannotAcceptInvalidAppFactoryClassNameIsSet() throws Exception { victim = new WroFilter(); Mockito.when(mockFilterConfig.getInitParameter(ConfigConstants.managerFactoryClassName.name())).thenReturn( "Invalid value"); victim.init(mockFilterConfig); } @Test public void shouldUseInitiallySetManagerEvenIfAnInvalidAppFactoryClassNameIsSet() throws Exception { Mockito.when(mockFilterConfig.getInitParameter(ConfigConstants.managerFactoryClassName.name())).thenReturn( "Invalid value"); victim.doFilter(mockRequest, mockResponse, mockFilterChain); Mockito.verify(mockManagerFactory, Mockito.atLeastOnce()).create(); } /** * Test that in DEPLOYMENT mode if {@link InvalidGroupNameException} is thrown, the response redirect to 404. */ @Test public void testInvalidGroupNameExceptionThrownInDEPLOYMENTMode() throws Exception { testChainContinueWhenSpecificExceptionThrown(new InvalidGroupNameException("")); } /** * Test that in DEPLOYMENT mode if {@link InvalidGroupNameException} is thrown, the response redirect to 404. */ @Test public void testUnauthorizedRequestExceptionThrownInDEPLOYMENTMode() throws Exception { testChainContinueWhenSpecificExceptionThrown(new UnauthorizedRequestException("")); } /** * Test that in DEPLOYMENT mode if specified exception is thrown, the response redirect to 404. */ public void testChainContinueWhenSpecificExceptionThrown(final Throwable e) throws Exception { initChainOnErrorFilter(); Mockito.when(mockManagerFactory.create()).thenThrow(e); victim.doFilter(mockRequest, mockResponse, mockFilterChain); verifyChainIsCalled(mockFilterChain); } @Test public void testValidAppFactoryClassNameIsSet() throws Exception { Mockito.when(mockFilterConfig.getInitParameter(ConfigConstants.managerFactoryClassName.name())).thenReturn( BaseWroManagerFactory.class.getName()); victim.init(mockFilterConfig); } /** * Test that when setting WwroManagerFactory via setter, even if wroConfiguration has a different * {@link WroManagerFactory} configured, the first one instance is used. */ @Test public void shouldUseCorrectWroManagerFactoryWhenOneIsSet() throws Exception { victim.setWroManagerFactory(null); Mockito.when(mockFilterConfig.getInitParameter(ConfigConstants.managerFactoryClassName.name())).thenReturn( TestWroManagerFactory.class.getName()); victim.init(mockFilterConfig); victim.doFilter(mockRequest, mockResponse, mockFilterChain); Mockito.verify(mockManagerFactory, Mockito.atLeastOnce()).create(); } public static class TestWroManagerFactory extends BaseWroManagerFactory { } @Test public void testJmxDisabled() throws Exception { Mockito.when(mockFilterConfig.getInitParameter(ConfigConstants.jmxEnabled.name())).thenReturn("false"); victim.init(mockFilterConfig); } /** * Set filter init params with proper values and check they are the same in {@link WroConfiguration} object. */ @Test public void testFilterInitParamsAreSetProperly() throws Exception { setConfigurationMode(FilterConfigWroConfigurationFactory.PARAM_VALUE_DEPLOYMENT); Mockito.when(mockFilterConfig.getInitParameter(ConfigConstants.gzipResources.name())).thenReturn("false"); Mockito.when(mockFilterConfig.getInitParameter(ConfigConstants.cacheUpdatePeriod.name())).thenReturn("10"); Mockito.when(mockFilterConfig.getInitParameter(ConfigConstants.modelUpdatePeriod.name())).thenReturn("100"); victim.init(mockFilterConfig); final WroConfiguration config = victim.getWroConfiguration(); Assert.assertEquals(false, config.isDebug()); Assert.assertEquals(false, config.isGzipEnabled()); Assert.assertEquals(10, config.getCacheUpdatePeriod()); Assert.assertEquals(100, config.getModelUpdatePeriod()); } @Test public void testValidHeaderParamIsSet() throws Exception { Mockito.when(mockFilterConfig.getInitParameter(ConfigConstants.header.name())).thenReturn("ETag: 998989"); victim.init(mockFilterConfig); } @Test public void testValidHeaderParamsAreSet() throws Exception { Mockito.when(mockFilterConfig.getInitParameter(ConfigConstants.header.name())).thenReturn( "ETag: 998989 | Expires: Thu, 15 Apr 2010 20:00:00 GMT"); victim.init(mockFilterConfig); } @Test(expected = WroRuntimeException.class) public void testInvalidHeaderParamIsSet() throws Exception { Mockito.when(mockFilterConfig.getInitParameter(ConfigConstants.header.name())).thenReturn("ETag 998989 expires 1"); victim.init(mockFilterConfig); } /** * Set filter init params with proper values and check they are the same in {@link WroConfiguration} object. */ @Test public void testConfigurationInitParam() throws Exception { Mockito.when(mockFilterConfig.getInitParameter(FilterConfigWroConfigurationFactory.PARAM_CONFIGURATION)).thenReturn( "anyOtherString"); victim.init(mockFilterConfig); Assert.assertEquals(true, victim.getWroConfiguration().isDebug()); } @Test public void testDisableCacheInitParamInDeploymentMode() throws Exception { Mockito.when(mockFilterConfig.getInitParameter(FilterConfigWroConfigurationFactory.PARAM_CONFIGURATION)).thenReturn( FilterConfigWroConfigurationFactory.PARAM_VALUE_DEPLOYMENT); Mockito.when(mockFilterConfig.getInitParameter(ConfigConstants.disableCache.name())).thenReturn("true"); victim.init(mockFilterConfig); Assert.assertEquals(false, victim.getWroConfiguration().isDebug()); Assert.assertEquals(false, victim.getWroConfiguration().isDisableCache()); } @Test public void testDisableCacheInitParamInDevelopmentMode() throws Exception { Mockito.when(mockFilterConfig.getInitParameter(ConfigConstants.disableCache.name())).thenReturn("true"); victim.init(mockFilterConfig); Assert.assertEquals(true, victim.getWroConfiguration().isDebug()); Assert.assertEquals(true, victim.getWroConfiguration().isDisableCache()); } /** * Check what happens when the request cannot be processed and assure that the we proceed with chain. * * @throws Exception */ public void cannotProcessConfigResourceStream() throws Exception { Mockito.when(mockRequest.getRequestURI()).thenReturn(""); victim.doFilter(mockRequest, mockResponse, mockFilterChain); verifyChainIsCalled(mockFilterChain); } /** * Check if the chain call was performed. */ private void verifyChainIsCalled(final FilterChain chain) throws IOException, ServletException { Mockito.verify(chain, Mockito.atLeastOnce()).doFilter(Mockito.any(HttpServletRequest.class), Mockito.any(HttpServletResponse.class)); } /** * Check if the chain call was performed. */ private void verifyChainIsNotCalled(final FilterChain chain) throws IOException, ServletException { Mockito.verify(chain, Mockito.never()).doFilter(Mockito.any(HttpServletRequest.class), Mockito.any(HttpServletResponse.class)); } @Test public void cannotProcessInvalidUri() throws Exception { initChainOnErrorFilter(); requestGroupByUri("", mockFilterChain); verifyChainIsCalled(mockFilterChain); } @Test public void requestValidGroup() throws Exception { initChainOnErrorFilter(); requestGroupByUri("/folder/g1.css"); } @Test public void requestInvalidGroup() throws Exception { initChainOnErrorFilter(); requestGroupByUri("/folder/INVALID_GROUP.css", mockFilterChain); verifyChainIsCalled(mockFilterChain); } // TODO; fix this test when AuthorizedResourcesHolder is implemented @Test public void cannotAccessUnauthorizedRequest() throws Exception { final String resourcePath = "/g1.css"; final String requestUri = CssUrlRewritingProcessor.PATH_RESOURCES + resourcePath; requestGroupByUri(requestUri, new RequestBuilder(requestUri) { @Override protected HttpServletRequest newRequest() { final HttpServletRequest request = super.newRequest(); Mockito.when(request.getParameter(CssUrlRewritingProcessor.PARAM_RESOURCE_ID)).thenReturn(resourcePath); return request; } }, mockFilterChain); verifyChainIsCalled(mockFilterChain); } // TODO build model before performing the request // @Test public void requestUrlRewrittenResource() throws Exception { final String resourcePath = "classpath:ro/isdc/wro/http/2.css"; final String requestUri = CssUrlRewritingProcessor.PATH_RESOURCES + "?id=" + resourcePath; requestGroupByUri(requestUri, new RequestBuilder(requestUri) { @Override protected HttpServletRequest newRequest() { final HttpServletRequest request = super.newRequest(); Mockito.when(request.getParameter(CssUrlRewritingProcessor.PARAM_RESOURCE_ID)).thenReturn(resourcePath); return request; } }); } private void requestGroupByUri(final String requestUri) throws Exception { requestGroupByUri(requestUri, new RequestBuilder(requestUri), mockFilterChain); } private void requestGroupByUri(final String requestUri, final FilterChain chain) throws Exception { requestGroupByUri(requestUri, new RequestBuilder(requestUri), chain); } @Test public void testDoFilterInDEPLOYMENTMode() throws Exception { Mockito.when(mockRequest.getRequestURI()).thenReturn("/g2.js"); victim.setWroManagerFactory(createValidManagerFactory()); setConfigurationMode(FilterConfigWroConfigurationFactory.PARAM_VALUE_DEPLOYMENT); victim.doFilter(mockRequest, mockResponse, mockFilterChain); } /** * Perform initialization and simulates a call to WroFilter with given requestUri. * * @param requestUri */ private void requestGroupByUri(final String requestUri, final RequestBuilder requestBuilder, final FilterChain chain) throws Exception { final HttpServletRequest request = requestBuilder.newRequest(); final ServletOutputStream sos = Mockito.mock(ServletOutputStream.class); Mockito.when(mockResponse.getOutputStream()).thenReturn(sos); victim.init(mockFilterConfig); victim.doFilter(request, mockResponse, chain); } private void requestGroupByUri(final String requestUri, final RequestBuilder requestBuilder) throws Exception { requestGroupByUri(requestUri, requestBuilder, mockFilterChain); } /** * Tests that in DEPLOYMENT mode the API is not exposed. */ @Test public void testApiCallInDEPLOYMENTMode() throws Exception { initChainOnErrorFilter(); Mockito.when(mockRequest.getRequestURI()).thenReturn(ReloadCacheRequestHandler.PATH_API + "/someMethod"); setConfigurationMode(FilterConfigWroConfigurationFactory.PARAM_VALUE_DEPLOYMENT); victim.doFilter(mockRequest, mockResponse, mockFilterChain); // No api method exposed -> proceed with chain verifyChainIsCalled(mockFilterChain); } /** * Tests that in DEPLOYMENT mode the API is not exposed. */ @Test public void testApiCallInDEVELOPMENTModeAndInvalidApiCall() throws Exception { initChainOnErrorFilter(); Mockito.when(mockRequest.getRequestURI()).thenReturn(ReloadCacheRequestHandler.PATH_API + "/someMethod"); // by default configuration is development victim.doFilter(mockRequest, mockResponse, mockFilterChain); // No api method exposed -> proceed with chain verifyChainIsCalled(mockFilterChain); } /** * Tests that in DEVELOPMENT mode the API is exposed. */ @Test public void testApiCallInDEVELOPMENTModeAndReloadCacheCall() throws Exception { final HttpServletRequest request = Mockito.mock(HttpServletRequest.class, Mockito.RETURNS_DEEP_STUBS); Mockito.when(request.getRequestURI()).thenReturn(ReloadCacheRequestHandler.API_RELOAD_CACHE); Mockito.when(mockResponse.getWriter()).thenReturn(new PrintWriter(System.out)); final FilterChain chain = Mockito.mock(FilterChain.class); final CacheStrategy<CacheEntry, ContentHashEntry> mockCacheStrategy = Mockito.mock(CacheStrategy.class); WroManagerFactory managerFactory = new BaseWroManagerFactory().setCacheStrategy(mockCacheStrategy); victim.setWroManagerFactory(managerFactory); // by default configuration is development victim.init(mockFilterConfig); victim.doFilter(request, mockResponse, chain); // api method exposed -> chain is not called verifyChainIsNotCalled(chain); Mockito.verify(mockCacheStrategy).clear(); } /** * Tests that in DEPLOYMENT mode the API is NOT exposed. */ @Test public void apiCallInDeploymentMode() throws Exception { final Properties props = new Properties(); // init WroConfig properties props.setProperty(ConfigConstants.debug.name(), Boolean.FALSE.toString()); final WroFilter theFilter = new WroFilter() { @Override protected ObjectFactory<WroConfiguration> newWroConfigurationFactory() { final PropertyWroConfigurationFactory factory = new PropertyWroConfigurationFactory(props); return factory; } }; // initFilterWithValidConfig(theFilter); final HttpServletRequest request = Mockito.mock(HttpServletRequest.class, Mockito.RETURNS_DEEP_STUBS); Mockito.when(request.getRequestURI()).thenReturn(ReloadCacheRequestHandler.API_RELOAD_CACHE); final HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.when(response.getWriter()).thenReturn(new PrintWriter(System.out)); // by default configuration is development theFilter.init(mockFilterConfig); theFilter.doFilter(request, response, mockFilterChain); // No api method exposed -> proceed with chain verifyChainIsCalled(mockFilterChain); } /** * Proves that the model reload has effect. */ @Test public void modelShouldBeReloadedWhenReloadIsTriggered() throws Exception { final WroManagerFactory wroManagerFactory = new BaseWroManagerFactory().setModelFactory(new WroModelFactory() { private boolean wasCreated = false; public WroModel create() { if (!wasCreated) { wasCreated = true; // return model with no groups defined return new WroModel(); } // second time when created add one group return new WroModel().addGroup(new Group("g1")); } public void destroy() { } }); Context.set(Context.standaloneContext()); final WroFilter filter = new WroFilter() { @Override protected WroManagerFactory newWroManagerFactory() { return wroManagerFactory; } @Override protected ObjectFactory<WroConfiguration> newWroConfigurationFactory() { return new ObjectFactory<WroConfiguration>() { public WroConfiguration create() { return Context.get().getConfig(); } }; } }; filter.init(mockFilterConfig); final WroModelFactory modelFactory = wroManagerFactory.create().getModelFactory(); Assert.assertTrue(modelFactory.create().getGroups().isEmpty()); // reload model Context.get().getConfig().reloadModel(); // the second time should have one group Assert.assertEquals(1, modelFactory.create().getGroups().size()); } @Test public void testReloadCacheCall() throws Exception { Mockito.when(mockRequest.getRequestURI()).thenReturn(ReloadCacheRequestHandler.API_RELOAD_CACHE); final ThreadLocal<Integer> status = new ThreadLocal<Integer>(); final HttpServletResponse response = new HttpServletResponseWrapper(mockResponse) { @Override public void setStatus(final int sc) { status.set(sc); } }; Context.set(Context.webContext(mockRequest, response, mockFilterConfig)); victim.doFilter(Context.get().getRequest(), Context.get().getResponse(), mockFilterChain); Assert.assertEquals(Integer.valueOf(HttpServletResponse.SC_OK), status.get()); } @Test public void testReloadModelCall() throws Exception { Mockito.when(mockRequest.getRequestURI()).thenReturn(ReloadModelRequestHandler.API_RELOAD_MODEL); final ThreadLocal<Integer> status = new ThreadLocal<Integer>(); final HttpServletResponse response = new HttpServletResponseWrapper(Mockito.mock(HttpServletResponse.class, Mockito.RETURNS_DEEP_STUBS)) { @Override public void setStatus(final int sc) { status.set(sc); } }; Context.set(Context.webContext(mockRequest, response, Mockito.mock(FilterConfig.class))); victim.doFilter(Context.get().getRequest(), Context.get().getResponse(), mockFilterChain); Assert.assertEquals(Integer.valueOf(HttpServletResponse.SC_OK), status.get()); } /** * Mocks the WroFilter.PARAM_CONFIGURATION init param with passed value. */ private void setConfigurationMode(final String value) { Mockito.when(mockFilterConfig.getInitParameter(FilterConfigWroConfigurationFactory.PARAM_CONFIGURATION)).thenReturn( value); } class RequestBuilder { private final String requestUri; public RequestBuilder(final String requestUri) { this.requestUri = requestUri; } protected HttpServletRequest newRequest() { Mockito.when(mockRequest.getRequestURI()).thenReturn(requestUri); return mockRequest; } } /** * Should throw {@link NullPointerException} when provided requestHandler's collection is null. */ @Test(expected = NullPointerException.class) public void shouldNotAcceptNullRequestHandlers() throws Exception { victim.setRequestHandlerFactory(new RequestHandlerFactory() { public Collection<RequestHandler> create() { return null; } }); victim.doFilter(mockRequest, mockResponse, mockFilterChain); } @Test(expected = NullPointerException.class) public void cannotAcceptNullRequestHandlerFactory() { victim.setRequestHandlerFactory(null); } @Test(expected = UnauthorizedRequestException.class) public void testProxyUnauthorizedRequest() throws Exception { processProxyWithResourceId("test"); } private void processProxyWithResourceId(final String resourceId) throws Exception { Mockito.when(mockRequest.getParameter(CssUrlRewritingProcessor.PARAM_RESOURCE_ID)).thenReturn(resourceId); Mockito.when(mockRequest.getRequestURI()).thenReturn( CssUrlRewritingProcessor.PATH_RESOURCES + "?" + CssUrlRewritingProcessor.PARAM_RESOURCE_ID + "=" + resourceId); final WroConfiguration config = new WroConfiguration(); // we don't need caching here, otherwise we'll have clashing during unit tests. config.setDisableCache(true); Context.set( Context.webContext(mockRequest, Mockito.mock(HttpServletResponse.class, Mockito.RETURNS_DEEP_STUBS), Mockito.mock(FilterConfig.class)), newConfigWithUpdatePeriodValue(0)); victim.doFilter(mockRequest, mockResponse, mockFilterChain); } /** * Initialize {@link WroConfiguration} object with cacheUpdatePeriod & modelUpdatePeriod equal with provided argument. */ private WroConfiguration newConfigWithUpdatePeriodValue(final long periodValue) { final WroConfiguration config = new WroConfiguration(); config.setCacheUpdatePeriod(periodValue); config.setModelUpdatePeriod(periodValue); config.setDisableCache(true); return config; } @After public void tearDown() { if (victim != null) { victim.destroy(); } Context.unset(); } }
/* * @author max */ package com.intellij.lang.html; import com.intellij.codeInsight.completion.CompletionUtilCore; import com.intellij.codeInsight.daemon.XmlErrorMessages; import com.intellij.lang.PsiBuilder; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.tree.ICustomParsingType; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.ILazyParseableElementType; import com.intellij.psi.xml.XmlElementType; import com.intellij.psi.xml.XmlTokenType; import com.intellij.util.containers.Stack; import com.intellij.xml.util.HtmlUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class HtmlParsing { @NonNls private static final String TR_TAG = "tr"; @NonNls private static final String TD_TAG = "td"; @NonNls private static final String TH_TAG = "th"; @NonNls private static final String TABLE_TAG = "table"; private final PsiBuilder myBuilder; private final Stack<String> myTagNamesStack = new Stack<>(); private final Stack<String> myOriginalTagNamesStack = new Stack<>(); private final Stack<PsiBuilder.Marker> myTagMarkersStack = new Stack<>(); @NonNls private static final String COMPLETION_NAME = CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED.toLowerCase(); public HtmlParsing(final PsiBuilder builder) { myBuilder = builder; } public void parseDocument() { final PsiBuilder.Marker document = mark(); while (token() == XmlTokenType.XML_COMMENT_START) { parseComment(); } parseProlog(); PsiBuilder.Marker error = null; while (!eof()) { final IElementType tt = token(); if (tt == XmlTokenType.XML_START_TAG_START) { error = flushError(error); parseTag(); myTagMarkersStack.clear(); myTagNamesStack.clear(); } else if (tt == XmlTokenType.XML_COMMENT_START) { error = flushError(error); parseComment(); } else if (tt == XmlTokenType.XML_PI_START) { error = flushError(error); parseProcessingInstruction(); } else if (tt == XmlTokenType.XML_CHAR_ENTITY_REF || tt == XmlTokenType.XML_ENTITY_REF_TOKEN) { parseReference(); } else if (tt == XmlTokenType.XML_REAL_WHITE_SPACE || tt == XmlTokenType.XML_DATA_CHARACTERS) { error = flushError(error); advance(); } else if (tt == XmlTokenType.XML_END_TAG_START) { final PsiBuilder.Marker tagEndError = myBuilder.mark(); advance(); if (token() == XmlTokenType.XML_NAME) { advance(); if (token() == XmlTokenType.XML_TAG_END) { advance(); } } tagEndError.error(XmlErrorMessages.message("xml.parsing.closing.tag.matches.nothing")); } else { if (error == null) error = mark(); advance(); } } if (error != null) { error.error(XmlErrorMessages.message("top.level.element.is.not.completed")); } document.done(XmlElementType.HTML_DOCUMENT); } @Nullable private static PsiBuilder.Marker flushError(PsiBuilder.Marker error) { if (error != null) { error.error(XmlErrorMessages.message("xml.parsing.unexpected.tokens")); error = null; } return error; } private void parseDoctype() { assert token() == XmlTokenType.XML_DOCTYPE_START : "Doctype start expected"; final PsiBuilder.Marker doctype = mark(); advance(); while (token() != XmlTokenType.XML_DOCTYPE_END && !eof()) advance(); if (eof()) { error(XmlErrorMessages.message("xml.parsing.unexpected.end.of.file")); } else { advance(); } doctype.done(XmlElementType.XML_DOCTYPE); } private void parseTag() { assert token() == XmlTokenType.XML_START_TAG_START : "Tag start expected"; String originalTagName; PsiBuilder.Marker xmlText = null; while (!eof()) { final IElementType tt = token(); if (tt == XmlTokenType.XML_START_TAG_START) { xmlText = terminateText(xmlText); final PsiBuilder.Marker tag = mark(); // Start tag header advance(); if (token() != XmlTokenType.XML_NAME) { error(XmlErrorMessages.message("xml.parsing.tag.name.expected")); originalTagName = ""; } else { originalTagName = myBuilder.getTokenText(); advance(); } String tagName = StringUtil.toLowerCase(originalTagName); while (childTerminatesParentInStack(tagName)) { PsiBuilder.Marker top = closeTag(); top.doneBefore(XmlElementType.HTML_TAG, tag); } myTagMarkersStack.push(tag); myTagNamesStack.push(tagName); myOriginalTagNamesStack.push(originalTagName); parseHeader(tagName); if (token() == XmlTokenType.XML_EMPTY_ELEMENT_END) { advance(); doneTag(tag); continue; } if (token() == XmlTokenType.XML_TAG_END) { advance(); } else { error(XmlErrorMessages.message("tag.start.is.not.closed")); doneTag(tag); continue; } if (originalTagName != null && isSingleTag(tagName, originalTagName)) { final PsiBuilder.Marker footer = mark(); while (token() == XmlTokenType.XML_REAL_WHITE_SPACE) { advance(); } if (token() == XmlTokenType.XML_END_TAG_START) { advance(); if (token() == XmlTokenType.XML_NAME) { if (tagName.equalsIgnoreCase(myBuilder.getTokenText())) { advance(); footer.drop(); if (token() == XmlTokenType.XML_TAG_END) { advance(); } doneTag(tag); continue; } } } footer.rollbackTo(); doneTag(tag); } } else if (tt == XmlTokenType.XML_PI_START) { xmlText = terminateText(xmlText); parseProcessingInstruction(); } else if (tt == XmlTokenType.XML_ENTITY_REF_TOKEN || tt == XmlTokenType.XML_CHAR_ENTITY_REF) { xmlText = startText(xmlText); parseReference(); } else if (tt == XmlTokenType.XML_CDATA_START) { xmlText = startText(xmlText); parseCData(); } else if (tt == XmlTokenType.XML_COMMENT_START) { xmlText = startText(xmlText); parseComment(); } else if (tt == XmlTokenType.XML_BAD_CHARACTER) { xmlText = startText(xmlText); final PsiBuilder.Marker error = mark(); advance(); error.error(XmlErrorMessages.message("unescaped.ampersand.or.nonterminated.character.entity.reference")); } else if (tt instanceof ICustomParsingType || tt instanceof ILazyParseableElementType) { xmlText = terminateText(xmlText); advance(); } else if (token() == XmlTokenType.XML_END_TAG_START) { xmlText = terminateText(xmlText); final PsiBuilder.Marker footer = mark(); advance(); if (token() == XmlTokenType.XML_NAME) { String endName = StringUtil.toLowerCase(myBuilder.getTokenText()); final String parentTagName = !myTagNamesStack.isEmpty() ? myTagNamesStack.peek() : ""; if (!parentTagName.equals(endName) && !endName.endsWith(COMPLETION_NAME)) { final boolean isOptionalTagEnd = HtmlUtil.isOptionalEndForHtmlTagL(parentTagName); final boolean hasChancesToMatch = HtmlUtil.isOptionalEndForHtmlTagL(endName) ? childTerminatesParentInStack(endName) : myTagNamesStack.contains(endName); if (hasChancesToMatch) { footer.rollbackTo(); if (!isOptionalTagEnd) { error(XmlErrorMessages.message("named.element.is.not.closed", myOriginalTagNamesStack.peek())); } doneTag(myTagMarkersStack.peek()); } else { advance(); if (token() == XmlTokenType.XML_TAG_END) advance(); footer.error(XmlErrorMessages.message("xml.parsing.closing.tag.matches.nothing")); } continue; } advance(); while (token() != XmlTokenType.XML_TAG_END && token() != XmlTokenType.XML_START_TAG_START && token() != XmlTokenType.XML_END_TAG_START && !eof()) { error(XmlErrorMessages.message("xml.parsing.unexpected.token")); advance(); } } else { error(XmlErrorMessages.message("xml.parsing.closing.tag.name.missing")); } footer.drop(); if (token() == XmlTokenType.XML_TAG_END) { advance(); } else { error(XmlErrorMessages.message("xml.parsing.closing.tag.is.not.done")); } if (hasTags()) doneTag(myTagMarkersStack.peek()); } else if ((token() == XmlTokenType.XML_REAL_WHITE_SPACE || token() == XmlTokenType.XML_DATA_CHARACTERS) && !hasTags()) { xmlText = terminateText(xmlText); advance(); } else { xmlText = startText(xmlText); advance(); } } terminateText(xmlText); while (hasTags()) { final String tagName = myTagNamesStack.peek(); if (!HtmlUtil.isOptionalEndForHtmlTagL(tagName) && !"html".equals(tagName) && !"body".equals(tagName)) { error(XmlErrorMessages.message("named.element.is.not.closed", myOriginalTagNamesStack.peek())); } doneTag(myTagMarkersStack.peek()); } } protected boolean isSingleTag(@NotNull String tagName, @NotNull String originalTagName) { return HtmlUtil.isSingleHtmlTagL(tagName); } private boolean hasTags() { return !myTagNamesStack.isEmpty(); } private PsiBuilder.Marker closeTag() { myTagNamesStack.pop(); myOriginalTagNamesStack.pop(); return myTagMarkersStack.pop(); } private void doneTag(PsiBuilder.Marker tag) { tag.done(XmlElementType.HTML_TAG); final String tagName = myTagNamesStack.peek(); closeTag(); final String parentTagName = hasTags() ? myTagNamesStack.peek() : ""; boolean isInlineTagContainer = HtmlUtil.isInlineTagContainerL(parentTagName); boolean isOptionalTagEnd = HtmlUtil.isOptionalEndForHtmlTagL(parentTagName); if (isInlineTagContainer && HtmlUtil.isHtmlBlockTagL(tagName) && isOptionalTagEnd && !HtmlUtil.isPossiblyInlineTag(tagName)) { PsiBuilder.Marker top = closeTag(); top.doneBefore(XmlElementType.HTML_TAG, tag); } } private void parseHeader(String tagName) { boolean freeMakerTag = !tagName.isEmpty() && '#' == tagName.charAt(0); do { final IElementType tt = token(); if (freeMakerTag) { if (tt == XmlTokenType.XML_EMPTY_ELEMENT_END || tt == XmlTokenType.XML_TAG_END || tt == XmlTokenType.XML_END_TAG_START || tt == XmlTokenType.XML_START_TAG_START) break; advance(); } else { if (tt == XmlTokenType.XML_NAME) { parseAttribute(); } else if (tt == XmlTokenType.XML_CHAR_ENTITY_REF || tt == XmlTokenType.XML_ENTITY_REF_TOKEN) { parseReference(); } else { break; } } } while (!eof()); } private boolean childTerminatesParentInStack(final String childName) { boolean isCell = TD_TAG.equals(childName) || TH_TAG.equals(childName); boolean isRow = TR_TAG.equals(childName); boolean isStructure = isStructure(childName); for (int i = myTagNamesStack.size() - 1; i >= 0; i String parentName = myTagNamesStack.get(i); final boolean isParentTable = TABLE_TAG.equals(parentName); final boolean isParentStructure = isStructure(parentName); if (isCell && (TR_TAG.equals(parentName) || isParentStructure || isParentTable) || isRow && (isParentStructure || isParentTable) || isStructure && isParentTable) { return false; } if ("li".equals(childName) && ("ul".equals(parentName) || "ol".equals(parentName))) { return false; } if ("dl".equals(parentName) && ("dd".equals(childName) || "dt".equals(childName))) { return false; } if (HtmlUtil.canTerminate(childName, parentName)) { return true; } } return false; } private static boolean isStructure(String childName) { return "thead".equals(childName) || "tbody".equals(childName) || "tfoot".equals(childName); } @NotNull private PsiBuilder.Marker startText(@Nullable PsiBuilder.Marker xmlText) { if (xmlText == null) { xmlText = mark(); assert xmlText != null; } return xmlText; } protected final PsiBuilder.Marker mark() { return myBuilder.mark(); } @Nullable private static PsiBuilder.Marker terminateText(@Nullable PsiBuilder.Marker xmlText) { if (xmlText != null) { xmlText.done(XmlElementType.XML_TEXT); xmlText = null; } return xmlText; } private void parseCData() { assert token() == XmlTokenType.XML_CDATA_START; final PsiBuilder.Marker cdata = mark(); while (token() != XmlTokenType.XML_CDATA_END && !eof()) { advance(); } if (!eof()) { advance(); } cdata.done(XmlElementType.XML_CDATA); } protected void parseComment() { final PsiBuilder.Marker comment = mark(); advance(); while (true) { final IElementType tt = token(); if (tt == XmlTokenType.XML_COMMENT_CHARACTERS || tt == XmlTokenType.XML_CONDITIONAL_COMMENT_START || tt == XmlTokenType.XML_CONDITIONAL_COMMENT_START_END || tt == XmlTokenType.XML_CONDITIONAL_COMMENT_END_START || tt == XmlTokenType.XML_CONDITIONAL_COMMENT_END) { advance(); continue; } if (tt == XmlTokenType.XML_ENTITY_REF_TOKEN || tt == XmlTokenType.XML_CHAR_ENTITY_REF) { parseReference(); continue; } if (tt == XmlTokenType.XML_BAD_CHARACTER) { final PsiBuilder.Marker error = mark(); advance(); error.error(XmlErrorMessages.message("xml.parsing.bad.character")); continue; } if (tt == XmlTokenType.XML_COMMENT_END) { advance(); } break; } comment.done(XmlElementType.XML_COMMENT); } private void parseReference() { if (token() == XmlTokenType.XML_CHAR_ENTITY_REF) { advance(); } else if (token() == XmlTokenType.XML_ENTITY_REF_TOKEN) { final PsiBuilder.Marker ref = mark(); advance(); ref.done(XmlElementType.XML_ENTITY_REF); } else { assert false : "Unexpected token"; } } private void parseAttribute() { assert token() == XmlTokenType.XML_NAME; final PsiBuilder.Marker att = mark(); advance(); if (token() == XmlTokenType.XML_EQ) { advance(); parseAttributeValue(); att.done(XmlElementType.XML_ATTRIBUTE); } else { att.done(XmlElementType.XML_ATTRIBUTE); } } private void parseAttributeValue() { final PsiBuilder.Marker attValue = mark(); if (token() == XmlTokenType.XML_ATTRIBUTE_VALUE_START_DELIMITER) { while (true) { final IElementType tt = token(); if (tt == null || tt == XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER || tt == XmlTokenType.XML_END_TAG_START || tt == XmlTokenType .XML_EMPTY_ELEMENT_END || tt == XmlTokenType.XML_START_TAG_START) { break; } if (tt == XmlTokenType.XML_BAD_CHARACTER) { final PsiBuilder.Marker error = mark(); advance(); error.error(XmlErrorMessages.message("unescaped.ampersand.or.nonterminated.character.entity.reference")); } else if (tt == XmlTokenType.XML_ENTITY_REF_TOKEN) { parseReference(); } else { advance(); } } if (token() == XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER) { advance(); } else { error(XmlErrorMessages.message("xml.parsing.unclosed.attribute.value")); } } else { if (token() != XmlTokenType.XML_TAG_END && token() != XmlTokenType.XML_EMPTY_ELEMENT_END) { advance(); // Single token att value } } attValue.done(XmlElementType.XML_ATTRIBUTE_VALUE); } private void parseProlog() { while (true) { final IElementType tt = token(); if (tt == XmlTokenType.XML_COMMENT_START) { parseComment(); } else if (tt == XmlTokenType.XML_REAL_WHITE_SPACE) { advance(); } else { break; } } final PsiBuilder.Marker prolog = mark(); while (true) { final IElementType tt = token(); if (tt == XmlTokenType.XML_PI_START) { parseProcessingInstruction(); } else if (tt == XmlTokenType.XML_DOCTYPE_START) { parseDoctype(); } else if (tt == XmlTokenType.XML_COMMENT_START) { parseComment(); } else if (tt == XmlTokenType.XML_REAL_WHITE_SPACE) { advance(); } else { break; } } prolog.done(XmlElementType.XML_PROLOG); } private void parseProcessingInstruction() { assert token() == XmlTokenType.XML_PI_START; final PsiBuilder.Marker pi = mark(); advance(); if (token() == XmlTokenType.XML_NAME || token() == XmlTokenType.XML_PI_TARGET) { advance(); } while (token() == XmlTokenType.XML_NAME) { advance(); if (token() == XmlTokenType.XML_EQ) { advance(); } else { error(XmlErrorMessages.message("expected.attribute.eq.sign")); } parseAttributeValue(); } if (token() == XmlTokenType.XML_PI_END) { advance(); } else { error(XmlErrorMessages.message("xml.parsing.unterminated.processing.instruction")); } pi.done(XmlElementType.XML_PROCESSING_INSTRUCTION); } protected final IElementType token() { return myBuilder.getTokenType(); } protected final boolean eof() { return myBuilder.eof(); } protected final void advance() { myBuilder.advanceLexer(); } private void error(final String message) { myBuilder.error(message); } }
package org.zanata.dao; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import java.util.List; import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.dbunit.operation.DatabaseOperation; import org.hamcrest.Matchers; import org.hibernate.Query; import org.hibernate.Session; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.zanata.ZanataDbunitJpaTest; import org.zanata.model.HLocale; import org.zanata.model.HTextFlow; import org.zanata.model.HTextFlowTarget; import org.zanata.search.FilterConstraints; import org.zanata.webtrans.shared.model.DocumentId; @Test(groups = { "jpa-tests" }) @Slf4j public class TextFlowDAOTest extends ZanataDbunitJpaTest { private TextFlowDAO dao; @Override protected void prepareDBUnitOperations() { beforeTestOperations.add(new DataSetOperation("org/zanata/test/model/ProjectsData.dbunit.xml", DatabaseOperation.CLEAN_INSERT)); beforeTestOperations.add(new DataSetOperation("org/zanata/test/model/TextFlowTestData.dbunit.xml", DatabaseOperation.CLEAN_INSERT)); beforeTestOperations.add(new DataSetOperation("org/zanata/test/model/LocalesData.dbunit.xml", DatabaseOperation.CLEAN_INSERT)); beforeTestOperations.add(new DataSetOperation("org/zanata/test/model/AccountData.dbunit.xml", DatabaseOperation.CLEAN_INSERT)); } @BeforeMethod(firstTimeOnly = true) public void setup() { dao = new TextFlowDAO((Session) getEm().getDelegate()); // printTestData(); } private void printTestData() { //single text flow with 4 targets HTextFlow textFlow = dao.findById(1L, false); log.info("text flow: {}", textFlow); for (Map.Entry<Long, HTextFlowTarget> entry : textFlow.getTargets().entrySet()) { log.debug("locale id: {} - target state: {}", entry.getKey(), entry.getValue().getState()); } //3 text flows with single en-US fuzzy target List<HTextFlow> doc2TextFlows = dao.getTextFlowsByDocumentId(new DocumentId(2L, ""), 0, 9999); for (HTextFlow doc2tf : doc2TextFlows) { log.debug("text flow id {} - targets {}", doc2tf.getId(), doc2tf.getTargets()); } //single text flow no target HTextFlow textFlow6 = dao.findById(6L, false); log.debug("text flow {} target: {}", textFlow6.getId(), textFlow6.getTargets()); } // FIXME looks like this test does not take more recently added states into account // should ensure all states are in test data and check test logic @Test public void canGetAllUntranslatedTextFlowForADocument() { HLocale deLocale = getEm().find(HLocale.class, 3L); log.info("locale: {}", deLocale); FilterConstraints untranslated = FilterConstraints.builder().keepAll().excludeFuzzy().excludeTranslated().build(); List<HTextFlow> result = dao.getTextFlowByDocumentIdWithConstraints(new DocumentId(1L, ""), deLocale, untranslated, 0, 10); assertThat(result.size(), is(0)); HLocale frLocale = getEm().find(HLocale.class, 6L); result = dao.getTextFlowByDocumentIdWithConstraints(new DocumentId(1L, ""), frLocale, untranslated, 0, 10); assertThat(result.size(), is(1)); } @Test public void canGetTextFlowWithNullTarget() { HLocale deLocale = getEm().find(HLocale.class, 3L); FilterConstraints untranslated = FilterConstraints.builder().keepAll().excludeFuzzy().excludeTranslated().build(); List<HTextFlow> result = dao.getTextFlowByDocumentIdWithConstraints(new DocumentId(4L, ""), deLocale, untranslated, 0, 10); assertThat(result, Matchers.hasSize(1)); } @Test public void canGetTextFlowsByStatus() { HLocale esLocale = getEm().find(HLocale.class, 5L); HLocale frLocale = getEm().find(HLocale.class, 6L); HLocale deLocale = getEm().find(HLocale.class, 3L); DocumentId documentId1 = new DocumentId(1L, ""); // esLocale fuzzy, // frLocale new, deLocale // approved List<HTextFlow> result = dao.getTextFlowByDocumentIdWithConstraints(documentId1, esLocale, FilterConstraints.builder().keepAll().excludeTranslated().excludeNew().build(), 0, 10); assertThat(result, Matchers.hasSize(1)); result = dao.getTextFlowByDocumentIdWithConstraints(documentId1, frLocale, FilterConstraints.builder().keepAll().excludeFuzzy().build(), 0, 10); assertThat(result, Matchers.hasSize(1)); result = dao.getTextFlowByDocumentIdWithConstraints(documentId1, deLocale, FilterConstraints.builder().keepAll().excludeFuzzy().excludeNew().build(), 0, 10); assertThat(result, Matchers.hasSize(1)); HLocale enUSLocale = getEm().find(HLocale.class, 4L); DocumentId documentId2 = new DocumentId(2L, ""); // all 3 text flows has // en-US fuzzy target result = dao.getTextFlowByDocumentIdWithConstraints(documentId2, enUSLocale, FilterConstraints.builder().keepAll().excludeTranslated().excludeFuzzy().build(), 0, 10); assertThat(result, Matchers.<HTextFlow>empty()); result = dao.getTextFlowByDocumentIdWithConstraints(documentId2, enUSLocale, FilterConstraints.builder().keepAll().excludeNew().build(), 0, 10); assertThat(result, Matchers.hasSize(3)); } @Test public void canBuildAcceptAllQuery() { String contentStateCondition = TextFlowDAO.buildContentStateCondition( FilterConstraints.builder().keepAll().build(), "tft"); assertThat("Conditional that accepts all should be '1'", contentStateCondition, is("1")); } @Test public void canBuildAcceptAllQueryWhenNoStatesSelected() { String contentStateCondition = TextFlowDAO.buildContentStateCondition( FilterConstraints.builder().keepNone().build(), "tft"); assertThat("Conditional that accepts all should be '1'", contentStateCondition, is("1")); } @Test public void canBuildNewOnlyConditional() { FilterConstraints constraints = FilterConstraints.builder() .keepNone().includeNew().build(); String contentStateCondition = TextFlowDAO.buildContentStateCondition(constraints, "tft"); assertThat(contentStateCondition, is("(tft.state=0 or tft.state is null)")); } @Test public void canBuildFuzzyOnlyConditional() { FilterConstraints constraints = FilterConstraints.builder() .keepNone().includeFuzzy().build(); String contentStateCondition = TextFlowDAO.buildContentStateCondition(constraints, "tft"); assertThat(contentStateCondition, is("(tft.state=1 or tft.state=4)")); } @Test public void canBuildTranslatedOnlyConditional() { FilterConstraints constraints = FilterConstraints.builder() .keepNone().includeTranslated().build(); String contentStateCondition = TextFlowDAO.buildContentStateCondition(constraints, "tft"); assertThat(contentStateCondition, is("(tft.state=2 or tft.state=3)")); } @Test public void canBuildContentStateQuery() { FilterConstraints constraints = FilterConstraints.builder() .keepNone().includeNew().includeFuzzy().build(); String contentStateCondition = TextFlowDAO.buildContentStateCondition(constraints, "tft"); assertThat(contentStateCondition, is("(tft.state=1 or tft.state=4 or tft.state=0 or tft.state is null)")); } @Test public void canBuildNewAndTranslatedConditional() { FilterConstraints constraints = FilterConstraints.builder() .keepNone().includeNew().includeTranslated().build(); String contentStateCondition = TextFlowDAO.buildContentStateCondition(constraints, "tft"); assertThat(contentStateCondition, is("(tft.state=2 or tft.state=3 or tft.state=0 or tft.state is null)")); } @Test public void canBuildFuzzyAndTranslatedConditional() { FilterConstraints constraints = FilterConstraints.builder() .keepNone().includeFuzzy().includeTranslated().build(); String contentStateCondition = TextFlowDAO.buildContentStateCondition(constraints, "tft"); assertThat(contentStateCondition, is("(tft.state=2 or tft.state=3 or tft.state=1 or tft.state=4)")); } @Test public void canBuildSearchQuery() { // no search term assertThat(TextFlowDAO.buildSearchCondition(null, "tft"), Matchers.equalTo("1")); assertThat(TextFlowDAO.buildSearchCondition("", "tft"), Matchers.equalTo("1")); // with search term assertThat(TextFlowDAO.buildSearchCondition("a", "tft"), Matchers.equalTo("(lower(tft.content0) LIKE :searchstringlowercase or lower(tft.content1) LIKE :searchstringlowercase or lower(tft.content2) LIKE :searchstringlowercase or lower(tft.content3) LIKE :searchstringlowercase or lower(tft.content4) LIKE :searchstringlowercase or lower(tft.content5) LIKE :searchstringlowercase)")); assertThat(TextFlowDAO.buildSearchCondition("A", "tft"), Matchers.equalTo("(lower(tft.content0) LIKE :searchstringlowercase or lower(tft.content1) LIKE :searchstringlowercase or lower(tft.content2) LIKE :searchstringlowercase or lower(tft.content3) LIKE :searchstringlowercase or lower(tft.content4) LIKE :searchstringlowercase or lower(tft.content5) LIKE :searchstringlowercase)")); } @Test public void testGetTextFlowByDocumentIdWithConstraint() { HLocale deLocale = getEm().find(HLocale.class, 3L); List<HTextFlow> result = dao.getTextFlowByDocumentIdWithConstraints( new DocumentId(new Long(4), ""), deLocale, FilterConstraints.builder().filterBy("mssg").excludeTranslated().excludeFuzzy().build(), 0, 10); assertThat(result, Matchers.hasSize(1)); } @Test public void queryTest1() { String queryString = "from HTextFlow tf left join tf.targets tft with (index(tft) = 3) " + "where (exists (from HTextFlowTarget where textFlow = tf and content0 like '%mssg%'))"; Query query = getSession().createQuery(queryString); List result = query.list(); } }
package org.capcaval.c3.component; public interface ComponentEventSubscribe<T extends ComponentEvent> { public <S extends ComponentEvent> void subscribe(S observer); public void unsubscribe(T observer); }
package jolie.lang.parse.module; import java.util.List; import jolie.lang.Constants; import jolie.lang.CodeCheckException; import jolie.lang.CodeCheckMessage; public class ModuleException extends CodeCheckException { private static final long serialVersionUID = Constants.serialVersionUID(); public ModuleException( CodeCheckMessage message ) { super( List.of( message ) ); } public ModuleException( List< CodeCheckMessage > errors ) { super( errors ); } }
package com.ae.apps.common.utils; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; /** * Utility class to show dialogs * * @author Midhun * */ public class DialogUtils { /** * Displays a basic dialog with a button * * @param context * @param titleResourceId * @param messageResourceId */ public static void showWithMessageAndOkButton(final Context context, int titleResourceId, int messageResourceId, int buttonResourceId) { AlertDialog.Builder builder = new AlertDialog.Builder(context) .setCancelable(true) .setTitle(titleResourceId) .setMessage(messageResourceId) .setPositiveButton(buttonResourceId, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // We shall dismiss the dialog when the ok is clicked dialog.dismiss(); } }); builder.show(); } /** * To display a Material Dialog box, with title, content and a button * * @param context * @param titleResourceId * @param messageResourceId * @param positiveButtonResourceId */ public static void showMaterialDialog(final Context context, int titleResourceId, int messageResourceId, int positiveButtonResourceId){ } }
package jade.imtp.leap; import jade.core.CaseInsensitiveString; import jade.core.IMTPException; import jade.core.UnreachableException; import jade.core.Profile; import jade.core.ServiceManager; import jade.mtp.TransportAddress; import jade.util.leap.ArrayList; import jade.util.leap.Iterator; import jade.util.leap.List; import java.util.Enumeration; import java.util.Hashtable; /** * This class provides a full implementation of a command dispatcher. The * command dispatcher provides support for multiple remote objects, * multiple ICPs and command routing. * * <p>The command dispatcher is based on an implementation written by * Michael Watzke and Giovanni Caire (TILAB), 09/11/2000.</p> * * @author Tobias Schaefer * @version 1.0 */ class FullCommandDispatcher extends CommandDispatcher { /** * This hashtable maps the IDs of the objects remotized by this * command dispatcher to the skeletons for these objects. It is used * when a command is received from a remote JVM. */ protected Hashtable skeletons = new Hashtable(); /** * This hashtable maps the objects remotized by this command * dispatcher to their IDs. It is used when a stub of a remotized * object must be built to be sent to a remote JVM. */ protected Hashtable ids = new Hashtable(); /** * A counter that is used for determining IDs for remotized objects. * Everytime a new object is registered by the command dispatcher it * gets the value of this field as ID and the field is increased. */ protected int nextID; /** * The pool of ICP objects used by this command dispatcher to * actually send/receive data over the network. It is a table that * associates a <tt>String</tt> representing a protocol (e.g. "http") * to a list of ICPs supporting that protocol. */ protected Hashtable icps = new Hashtable(); /** * The transport addresses the ICPs managed by this command * dispatcher are listening for commands on. */ protected List addresses = new ArrayList(); /** * The URLs corresponding to the local transport addresses. */ protected List urls = new ArrayList(); /** * A sole constructor. To get a command dispatcher the constructor * should not be called directly but the static <tt>create</tt> and * <tt>getDispatcher</tt> methods should be used. Thereby the * existence of a singleton instance of the command dispatcher will * be guaranteed. */ public FullCommandDispatcher() { // Set a temporary name. Will be substituted as soon as the first // container attached to this CommandDispatcher will receive a // unique name from the main. name = DEFAULT_NAME; nextID = 1; // DEBUG // System.out.println("full command dispatcher initialized"); } /** * Adds (and activates) an ICP to this command dispatcher. * * @param peer the ICP to add. * @param args the arguments required by the ICP for the activation. * These arguments are ICP specific. */ public void addICP(ICP peer, String peerID, Profile p) { try { // Activate the peer. TransportAddress ta = peer.activate(this, peerID, p); // Add the listening address to the list of local addresses. TransportProtocol tp = peer.getProtocol(); String url = tp.addrToString(ta); addresses.add(ta); urls.add(url); // Put the peer in the table of local ICPs. String proto = tp.getName().toLowerCase(); List list = (List) icps.get(proto); if (list == null) { icps.put(proto, (list = new ArrayList())); } list.add(peer); } catch (ICPException icpe) { // Print a warning. System.out.println("Error adding ICP "+peer+"["+icpe.getMessage()+"]."); } } /** * Returns the ID of the specified remotized object. * * @param remoteObject the object whose ID should be returned. * @return the ID of the reomte object. * @throws RuntimeException if the specified object is not * remotized by this command dispatcher. */ public int getID(Object remoteObject) throws IMTPException { Integer id = (Integer) ids.get(remoteObject); if (id != null) { return id.intValue(); } throw new IMTPException("specified object is not remotized by this command dispatcher."); } /** * Returns the list of local addresses. * * @return the list of local addresses. */ public List getLocalTAs() { return addresses; } /** * Returns the list of URLs corresponding to the local addresses. * * @return the list of URLs corresponding to the local addresses. */ public List getLocalURLs() { return urls; } /** * Converts an URL into a transport address using the transport * protocol supported by the ICPs currently installed in the command * dispatcher. If there is no ICP installed to the command dispatcher * or their transport protocols are not able to convert the specified * URL a <tt>DispatcherException</tt> is thrown. * * @param url a <tt>String</tt> object specifying the URL to convert. * @return the converted URL. * @throws DispatcherException if there is no ICP installed to the * command dispatcher or the transport protocols of the ICPs * are not able to convert the specified URL. */ protected TransportAddress stringToAddr(String url) throws DispatcherException { Enumeration peers = icps.elements(); while (peers.hasMoreElements()) { // Try to convert the url using the TransportProtocol // supported by this ICP. try { // There can be more than one peer supporting the same // protocol. Use the first one. return ((ICP) ((List) peers.nextElement()).get(0)).getProtocol().stringToAddr(url); } catch (Throwable t) { // Do nothing and try the next one. } } // If we reach this point the url can't be converted. throw new DispatcherException("can't convert URL "+url+"."); } /** * Registers the specified skeleton to the command dispatcher. * * @param skeleton a skeleton to be managed by the command * dispatcher. * @param remoteObject the remote object related to the specified * skeleton. */ public void registerSkeleton(Skeleton skeleton, Object remoteObject) { Integer id = null; if (remoteObject instanceof ServiceManager) { id = new Integer(0); name = "Service-Manager"; } else { id = new Integer(nextID++); } skeletons.put(id, skeleton); ids.put(remoteObject, id); } /** * Deregisters the specified remote object from the command dispatcher. * * @param remoteObject the remote object related to the specified * skeleton. */ public void deregisterSkeleton(Object remoteObject) { try { skeletons.remove(ids.remove(remoteObject)); } catch (NullPointerException npe) { } if (ids.isEmpty()) { //System.out.println("CommandDispatcher shutting down"); shutDown(); } } public Stub buildLocalStub(Object remoteObject) throws IMTPException { Stub stub = null; if(remoteObject instanceof NodeAdapter) { NodeAdapter na = (NodeAdapter)remoteObject; NodeLEAP nl = na.getAdaptee(); if(nl instanceof NodeStub) { stub = (NodeStub)nl; } else { stub = new NodeStub(getID(remoteObject)); // Add the local addresses. Iterator it = addresses.iterator(); while (it.hasNext()) { stub.addTA((TransportAddress) it.next()); } } } else { throw new IMTPException("can't create a stub for object "+remoteObject+"."); } return stub; } /** * Selects a suitable peer and sends the specified serialized command * to the specified transport address. * * @param ta the transport addresses where the command should be * sent. * @param commandPayload the serialized command that is to be * sent. * @return a serialized response command from the receiving * container. * @throws UnreachableException if the destination address is not * reachable. */ protected byte[] send(TransportAddress ta, byte[] commandPayload) throws UnreachableException { // Get the ICPs suitable for the given TransportAddress. List list = (List) icps.get(ta.getProto().toLowerCase()); if (list == null) { throw new UnreachableException("no ICP suitable for protocol "+ta.getProto()+"."); } for (int i = 0; i < list.size(); i++) { try { return ((ICP) list.get(i)).deliverCommand(ta, commandPayload); } catch (ICPException icpe) { // Print a warning and try next address System.out.println("Warning: can't deliver command to "+ta+". "+icpe.getMessage()); } } throw new UnreachableException("ICPException delivering command to address "+ta+"."); } /** * Shuts the command dipatcher down and deactivates the local ICPs. */ public void shutDown() { Enumeration peersKeys = icps.keys(); while (peersKeys.hasMoreElements()) { List list = (List) icps.remove(peersKeys.nextElement()); for (int i = 0; i < list.size(); i++) { try { // This call interrupts the listening thread of this peer // and waits for its completion. ((ICP) list.get(i)).deactivate(); // DEBUG // System.out.println("ICP deactivated."); } catch (ICPException icpe) { // Do nothing as this means that this peer had never been // activated. } } } } // ICP.Listener INTERFACE /** * Handles a received (still serialized) command object, i.e. * deserialize it and launch processing of the command. * * @param commandPayload the command to be deserialized and * processed. * @return a <tt>byte</tt> array containing the serialized response * command. * @throws LEAPSerializationException if the command cannot be * (de-)serialized. */ public byte[] handleCommand(byte[] commandPayload) throws LEAPSerializationException { try { // Deserialize the incoming command. Command command = deserializeCommand(commandPayload); Command response = null; // DEBUG // System.out.println("Received command of type " + command.getCode()); if (command.getCode() == Command.FORWARD) { // DEBUG // System.out.println("Routing command"); // If this is a FORWARD command then handle it directly. byte[] originalPayload = (byte[]) command.getParamAt(0); List destTAs = (List) command.getParamAt(1); String origin = (String) command.getParamAt(2); if (origin.equals(name)) { // The forwarding mechanism is looping. response = buildExceptionResponse(new UnreachableException("destination unreachable (and forward loop).")); } else { try { response = dispatchSerializedCommand(destTAs, originalPayload, origin); } catch (UnreachableException ue) { // rsp = buildExceptionResponse("jade.core.UnreachableException", ue.getMessage()); response = buildExceptionResponse(ue); } } } else { // If this is a normal Command, let the proper Skeleton // process it. Integer id = new Integer(command.getObjectID()); Skeleton s = (Skeleton) skeletons.get(id); if (s == null) { throw new DispatcherException("No skeleton for object-id "+id); } response = s.processCommand(command); } return serializeCommand(response); } catch (Exception e) { e.printStackTrace(); // FIXME. If this throws an exception this is not handled by // the CommandDispatcher. return serializeCommand(buildExceptionResponse(new DispatcherException(e.getMessage()))); } } }
package com.macro.mall.common.api; public enum ResultCode implements IErrorCode { SUCCESS(200, ""), FAILED(500, ""), VALIDATE_FAILED(404, ""), UNAUTHORIZED(401, "token"), FORBIDDEN(403, ""); private long code; private String message; private ResultCode(long code, String message) { this.code = code; this.message = message; } public long getCode() { return code; } public String getMessage() { return message; } }
// ImageUtil.java package ed.util; import java.io.*; import java.util.*; import java.awt.*; import java.awt.image.*; import javax.imageio.*; import javax.imageio.stream.*; import javax.imageio.plugins.jpeg.*; import ed.js.*; import ed.appserver.*; /** @expose */ public class ImageUtil { public static JSFile imgToJpg( BufferedImage img , double compressionQuality , String filename ) throws IOException { String ext = "jpg"; if ( filename != null && filename.indexOf( "." ) >= 0 ){ String test = MimeTypes.getExtension( filename ); String mime = MimeTypes.get( test ); if ( mime != null && mime.startsWith( "image/" ) ) ext = test; } String mime = MimeTypes.get( ext ); ByteArrayOutputStream out = convertImage(img, compressionQuality, ext); return new JSInputFile( filename , mime , out.toByteArray() ); } /** * Convert a BufferedImage to a String representation of that image, * in the format appropriate for the file extension ext. * * @param img image to be converted. must be non-null. * @param compressionQuality the quality paramater to be used for lossy encodings [0.0, 1.0]. * @param ext the extension of the desired image type. defaults to "jpg", * which results in a jpeg image. * @param enc the encoding to use for the resulting String. * @return the representation of the BufferedImage as a string. */ public static String imgToString(BufferedImage img, double compressionQuality, String ext, String enc) throws IOException { if (img == null) { throw new IllegalArgumentException("img must not be null"); } if (ext == null) { ext = "jpg"; } if (enc == null) { throw new IllegalArgumentException("enc must not be null"); } return convertImage(img, compressionQuality, ext).toString(enc); } private static ByteArrayOutputStream convertImage(BufferedImage img, double compressionQuality, String ext) throws IOException { Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName( ext ); if ( ! writers.hasNext() ) throw new RuntimeException( "no writer for : " + ext ); ImageWriter writer = writers.next(); ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageOutputStream ios = ImageIO.createImageOutputStream( out ); writer.setOutput(ios); ImageWriteParam iwparam = new MyImageWriteParam(); iwparam.setCompressionMode( ImageWriteParam.MODE_EXPLICIT ); iwparam.setCompressionQuality( (float)compressionQuality ); writer.write(null, new IIOImage( img, null, null), iwparam); ios.flush(); writer.dispose(); ios.close(); return out; } public static class MyImageWriteParam extends JPEGImageWriteParam { public MyImageWriteParam() { super(Locale.getDefault()); } public void setCompressionQuality(float quality) { if (quality < 0.0F || quality > 1.0F) { throw new IllegalArgumentException("Quality out-of-bounds!"); } this.compressionQuality = 256 - (quality * 256); } } public static BufferedImage getScaledInstance(BufferedImage img , double targetWidth , double targetHeight ){ return getScaledInstance( img , (int)targetWidth , (int)targetHeight , true ); } public static BufferedImage getScaledInstance(BufferedImage img, int targetWidth, int targetHeight, boolean higherQuality){ int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB; BufferedImage ret = (BufferedImage)img; int w, h; if (higherQuality && targetWidth < img.getWidth() && targetHeight < img.getHeight()) { // Use multi-step technique: start with original size, then // scale down in multiple passes with drawImage() // until the target size is reached w = img.getWidth(); h = img.getHeight(); } else { // Use one-step technique: scale directly from original // size to target size with a single drawImage() call w = targetWidth; h = targetHeight; } do { if (higherQuality && w > targetWidth) { w /= 2; if (w < targetWidth) { w = targetWidth; } } if (higherQuality && h > targetHeight) { h /= 2; if (h < targetHeight) { h = targetHeight; } } BufferedImage tmp = new BufferedImage(w, h, type); Graphics2D g2 = tmp.createGraphics(); g2.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC ); g2.drawImage(ret, 0, 0, w, h, null); g2.dispose(); ret = tmp; } while (w != targetWidth || h != targetHeight); return ret; } /** * Rotates an image by the specified number of degrees. Only handles rotations through * multiples of 90 degrees. * * @param img image to be rotated. must be non-null * @param degrees angle through which the image is rotated. must be a multiple of 90. * @return a new BufferedImage, the result of applying the rotation to img */ public static BufferedImage getRotatedInstance(final BufferedImage img, final int degrees) { if (img == null) { throw new IllegalArgumentException("img must not be null"); } if (degrees % 90 != 0) { throw new IllegalArgumentException("can only rotate images in multiples of 90 degrees"); } int turns = (degrees / 90) % 4; if (turns < 0) { turns = turns + 4; } // TODO maybe we should short-circuit here if turns is 0 => just return a copy of img. int result_width = (turns % 2 == 0) ? img.getWidth() : img.getHeight(); int result_height = (turns % 2 == 0) ? img.getHeight() : img.getWidth(); BufferedImage result = new BufferedImage(result_width, result_height, img.getType()); for (int i = 0; i < result_width; i++) { for (int j = 0; j < result_height; j++) { int target_x; int target_y; switch (turns) { case 0: target_x = i; target_y = j; break; case 1: target_x = j; target_y = result_width - i - 1; break; case 2: target_x = result_width - i - 1; target_y = result_height - j - 1; break; case 3: target_x = result_height - j - 1; target_y = i; break; default: throw new RuntimeException("this should never happen"); } result.setRGB(i, j, img.getRGB(target_x, target_y)); } } return result; } /** * Flips an image horizontally. The edge that was the left becomes the right, and vice versa. * * @param img image to be flipped. must be non-null * @return a new BufferedImage, the result of flipping img */ public static BufferedImage getHorizontallyFlippedInstance(final BufferedImage img) { if (img == null) { throw new IllegalArgumentException("img must not be null"); } BufferedImage result = new BufferedImage(img.getWidth(), img.getHeight(), img.getType()); for (int i = 0; i < img.getWidth(); i++) { for (int j = 0; j < img.getHeight(); j++) { result.setRGB(img.getWidth() - i - 1, j, img.getRGB(i, j)); } } return result; } /** * Flips an image vertically. The edge that was the top becomes the bottom, and vice versa. * * @param img image to be flipped. must be non-null * @return a new BufferedImage, the result of flipping img */ public static BufferedImage getVerticallyFlippedInstance(final BufferedImage img) { if (img == null) { throw new IllegalArgumentException("img must not be null"); } BufferedImage result = new BufferedImage(img.getWidth(), img.getHeight(), img.getType()); for (int i = 0; i < img.getWidth(); i++) { for (int j = 0; j < img.getHeight(); j++) { result.setRGB(i, img.getHeight() - j - 1, img.getRGB(i, j)); } } return result; } /** * Crops an image. The bounding box to crop to is given by left_x * width, top_y * height * right_x * width, and bottom_y * height. * * @param img image to be cropped. must be non-null * @param left_x the left border of the bounding box, proportional to the image width. * specified as a float value from 0.0 to 1.0 inclusive. * @param top_y the top border of the bounding box, proportional to the image height. * specified as a float value from 0.0 to 1.0 inclusive. * @param right_x the right border of the bounding box, proportional to the image width. * specified as a float value from 0.0 to 1.0 inclusive. * @param bottom_y the bottom border of the bounding box, proportional to the image height. * specified as a float value from 0.0 to 1.0 inclusive. * @return a new BufferedImage, cropped to the bounding box specified. */ public static BufferedImage getCroppedInstance(final BufferedImage img, final float left_x, final float top_y, final float right_x, final float bottom_y) { if (img == null) { throw new IllegalArgumentException("img must not be null"); } int left = (int)(left_x * img.getWidth()); int width = (int)(right_x * img.getWidth()) - left; int top = (int)(top_y * img.getHeight()); int height = (int)(bottom_y * img.getHeight()) - top; BufferedImage result = new BufferedImage(width, height, img.getType()); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { result.setRGB(i, j, img.getRGB(left + i, top + j)); } } return result; } }
package se.soy.gpg; public class GPGException extends RuntimeException { public GPGException() { } public GPGException(String msg) { super(msg); } }
import java.awt.*; import java.awt.event.WindowListener; import java.lang.reflect.Field; import java.util.Collection; public class HuskyRoncace extends Critter { private static CritterModel model = null; private static Field critterList = null; private final String donger; private boolean hasEaten = false; private int iteration = 5; private Direction dir = Direction.CENTER; private boolean avoidStalemate = false; private static final Attack fallbackAttack = Attack.values()[(int)(Math.random() * Attack.values().length)]; private static boolean isSpeciescideComplete = false; private static final String[] dongers = { "( _)", "(°°)", "( )", "(´∀ `)", " ", "ლ(Дლ)" // >tfw no lenny // >tfw no raise your dongers }; public HuskyRoncace() { donger = dongers[(int)(Math.random() * dongers.length)]; } @Override public String toString() { StackTraceElement[] trace = Thread.currentThread().getStackTrace(); if (trace.length > 2 && trace[2].getMethodName().equals("fight")) { return "%"; // disguise as an ant to promote predictable behavior } return donger; } private static void cheat() { try { outer: for (Window f : Window.getWindows()) { for (WindowListener l : f.getWindowListeners()) { if (l instanceof CritterGui) { CritterGui gui = (CritterGui)l; Field modelField = gui.getClass().getDeclaredField("model"); modelField.setAccessible(true); model = (CritterModel)modelField.get(gui); critterList = model.getClass().getDeclaredField("critterList"); critterList.setAccessible(true); break outer; } } } } catch (IllegalAccessException | NoSuchFieldException ex) { throw new AssertionError(); } } @Override public boolean eat() { // I was considering always returning true and modifying the // CritterState to remove the penalty, but apparently that would violate // the assignment's rules return isSpeciescideComplete || (!hasEaten && (hasEaten = true)); } @Override @SuppressWarnings("unchecked") public Attack fight(String opponent) { StackTraceElement[] trace = Thread.currentThread().getStackTrace(); if (trace.length > 2 && trace[2].getMethodName().equals("fight") && trace[2].getClassName().startsWith("Husky") && !trace[2].getClassName().equals("HuskyRoncace")) { avoidStalemate = true; return Attack.POUNCE; } else if (avoidStalemate) { return Attack.SCRATCH; } Attack counter = null; try { if (critterList == null) { cheat(); } Collection<Critter> critters = (Collection<Critter>)critterList.get(model); boolean others = false; for (Critter c : critters) { if (c != this && this.getX() == c.getX() && this.getY() == c.getY() && c.toString().equals(opponent)) { Attack attack = c.fight(this.toString()); switch (attack) { case POUNCE: counter = Attack.SCRATCH; break; case SCRATCH: counter = Attack.ROAR; break; case ROAR: counter = Attack.POUNCE; break; } } else if (!(c instanceof HuskyRoncace)) { others = true; } if (others && counter != null) { break; } } if (!others) { isSpeciescideComplete = true; } } catch (IllegalAccessException ex) { ex.printStackTrace(); } if (counter == null) { counter = fallbackAttack; } return counter; } @Override public Direction getMove() { // I mean, hey, it works for the hippos if (iteration == 5) { iteration = 0; int r = (int)(Math.random() * 4); switch (r) { case 0: dir = Direction.NORTH; break; case 1: dir = Direction.SOUTH; break; case 2: dir = Direction.EAST; break; case 3: dir = Direction.WEST; break; } } ++iteration; return dir; } @Override public Color getColor() { return Color.MAGENTA; } }
package main.java.engine; import java.awt.geom.Point2D; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import jgame.platform.JGEngine; import main.java.author.view.tabs.enemy.EnemyViewDefaults; import main.java.data.DataHandler; import main.java.engine.factory.TDObjectFactory; import main.java.engine.map.TDMap; import main.java.engine.objects.CollisionManager; import main.java.engine.objects.Exit; import main.java.engine.objects.item.TDItem; import main.java.engine.objects.monster.Monster; import main.java.engine.objects.tower.ITower; import main.java.engine.objects.tower.TowerBehaviors; import main.java.exceptions.engine.InvalidSavedGameException; import main.java.exceptions.engine.MonsterCreationFailureException; import main.java.exceptions.engine.TowerCreationFailureException; import main.java.schema.GameBlueprint; import main.java.schema.GameSchema; import main.java.schema.MonsterSpawnSchema; import main.java.schema.WaveSpawnSchema; import main.java.schema.map.GameMapSchema; import main.java.schema.tdobjects.ItemSchema; import main.java.schema.tdobjects.MonsterSchema; import main.java.schema.tdobjects.TDObjectSchema; import main.java.schema.tdobjects.TowerSchema; import main.java.schema.tdobjects.items.AnnihilatorItemSchema; import main.java.schema.tdobjects.items.AreaBombItemSchema; import main.java.schema.tdobjects.items.InstantFreezeItemSchema; import main.java.schema.tdobjects.items.LifeSaverItemSchema; import main.java.schema.tdobjects.items.RowBombItemSchema; import main.java.schema.tdobjects.monsters.SimpleMonsterSchema; public class Model implements IModel{ private static final double DEFAULT_MONEY_MULTIPLIER = 0.5; public static final String RESOURCE_PATH = "/main/resources/"; private JGEngine engine; private TDObjectFactory factory; private Player player; private double gameClock; private ITower[][] towers; private List<Monster> monsters; private CollisionManager collisionManager; private GameState gameState; private DataHandler dataHandler; private LevelManager levelManager; private EnvironmentKnowledge environ; private List<TDItem> items; public Model (JGEngine engine, String pathToBlueprint) { this.engine = engine; dataHandler = new DataHandler(); defineAllStaticImages(); this.factory = new TDObjectFactory(engine); collisionManager = new CollisionManager(engine); levelManager = new LevelManager(factory); // TODO: Code entrance/exit logic into wave or monster spawn schema levelManager.setEntrance(0, engine.pfHeight() / 2); //levelManager.setExit(engine.pfWidth() / 2, engine.pfHeight() / 2); levelManager.setExit(12 * engine.tileWidth(), 9 * engine.tileHeight()); this.gameClock = 0; monsters = new ArrayList<Monster>(); towers = new ITower[engine.viewTilesX()][engine.viewTilesY()]; gameState = new GameState(); items = new ArrayList<TDItem>(); try { loadGameBlueprint(pathToBlueprint);// TODO: REPLACE } catch (Exception e) { e.printStackTrace(); } addNewPlayer(); } private void defineAllStaticImages () { // TODO: remove this method, make exit a part of wavespawnschemas //and define its image dynamically engine.defineImage(Exit.NAME, "-", 1, RESOURCE_PATH + Exit.IMAGE_NAME, "-"); } /** * Add a new player to the engine */ public void addNewPlayer () { this.player = new Player(); levelManager.registerPlayer(player); environ = new EnvironmentKnowledge(monsters, player, towers, levelManager.getExit()); } /** * Add a tower at the specified location. If tower already exists in that cell, do nothing. * * @param x x coordinate of the tower * @param y y coordinate of the tower * @param towerName Type tower to be placed */ public boolean placeTower (double x, double y, String towerName) { try { Point2D location = new Point2D.Double(x, y); int[] currentTile = getTileCoordinates(location); // if tower already exists in the tile clicked, do nothing if (isTowerPresent(currentTile)) { return false; } ITower newTower = factory.placeTower(location, towerName); if (player.getMoney() >= newTower.getCost()) { // FIXME: Decrease money? player.changeMoney(-newTower.getCost()); towers[currentTile[0]][currentTile[1]] = newTower; return true; } else { newTower.remove(); return false; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } /** * Return a two element int array with the tile coordinates that a given point is on, for use * with Tower[][] * * @param location * @return the row, col of the tile on which the location is situated */ private int[] getTileCoordinates (Point2D location) { int curXTilePos = (int) (location.getX() / engine.tileWidth()); int curYTilePos = (int) (location.getY() / engine.tileHeight()); return new int[] { curXTilePos, curYTilePos }; } /** * Check if there's a tower present at the specified coordinates * * @param coordinates * @return true if there is a tower */ private boolean isTowerPresent (int[] coordinates) { return towers[coordinates[0]][coordinates[1]] != null; } /** * Check if there's a tower present at the specified coordinates * This is mainly for the view to do a quick check * * @param x * @param y * @return true if there is a tower */ public boolean isTowerPresent (double x, double y) { return isTowerPresent(getTileCoordinates(new Point2D.Double(x, y))); } /** * Get the information of the TDObject, if any, * at the specified coordinates * * @param x * @param y * @return The information that we want to display to the player */ public List<String> getUnitInfo(double x, double y) { List<String> info = new ArrayList<String>(); if (isTowerPresent(x, y)) { int[] currentTile = getTileCoordinates(new Point2D.Double(x, y)); ITower currTower = towers[currentTile[0]][currentTile[1]]; info.addAll(currTower.getInfo()); } Monster m; if ((m=monsterPresent(x, y)) != null) { info.addAll(m.getInfo()); } return info; } /** * Return the monster at the specified coordinates. * If there's no monster at that location, null will be returned. * * @param x * @param y * @return the monster present */ private Monster monsterPresent(double x, double y) { Monster monster = null; for (Monster m : monsters) { double xUpper = m.x + m.getImageBBoxConst().width; double yUpper = m.y + m.getImageBBoxConst().height; if (m.x <= x && x <= xUpper && m.y <= y && y <= yUpper) { monster = m; } } return monster; } /** * Check if the current location contains any tower. If yes, remove it. If no, do nothing * * @param x * @param y */ public void checkAndRemoveTower (double x, double y) { int[] coordinates = getTileCoordinates(new Point2D.Double(x, y)); if (isTowerPresent(coordinates)) { int xtile = coordinates[0]; int ytile = coordinates[1]; player.changeMoney(DEFAULT_MONEY_MULTIPLIER * towers[xtile][ytile].getCost()); towers[xtile][ytile].remove(); towers[xtile][ytile] = null; } } // TODO: use this instead of other one, will change -jordan public void loadMapTest (String fileName) { try { FileInputStream fis = new FileInputStream(fileName); ObjectInputStream is = new ObjectInputStream(fis); GameMapSchema mapToLoad = (GameMapSchema) is.readObject(); is.close(); TDMap tdMap = new TDMap(engine, mapToLoad); } catch (Exception e) { e.printStackTrace(); } } /** * Deserialize and load into the engine the GameBlueprint obtained from the file path * * @param filePath File path of the blueprint to be loaded * @throws IOException * @throws ClassNotFoundException */ public void loadGameBlueprint (String filePath) throws ClassNotFoundException, IOException { GameBlueprint blueprint = null; if (filePath == null) { blueprint = createTestBlueprint(); } else { try { blueprint = dataHandler.loadBlueprint(filePath, true); } catch (Exception e) { e.printStackTrace(); return; } } // Initialize from game settings from game schema GameSchema gameSchema = blueprint.getMyGameScenario(); Map<String, Serializable> gameSchemaAttributeMap = gameSchema.getAttributesMap(); this.player = new Player((Integer) gameSchemaAttributeMap.get(GameSchema.MONEY), (Integer) gameSchemaAttributeMap.get(GameSchema.LIVES)); // Initialize factory objects if (blueprint.getMyTowerSchemas() != null) { factory.loadTowerSchemas(blueprint.getMyTowerSchemas()); } if (blueprint.getMyMonsterSchemas() != null) { factory.loadMonsterSchemas(blueprint.getMyMonsterSchemas()); } if (blueprint.getMyItemSchemas() != null) { factory.loadItemSchemas(blueprint.getMyItemSchemas()); } // Initialize waves if (blueprint.getMyWaveSchemas() != null) { levelManager.cleanLoadWaveSchemas(blueprint.getMyWaveSchemas(), 0); } // Initialize map if necessary if (blueprint.getMyGameMapSchemas() != null) { TDMap map = new TDMap(engine, blueprint.getMyGameMapSchemas().get(0)); // TODO: load // each map } } /** * Reset the game clock */ public void resetGameClock () { this.gameClock = 0; } public void addScore (double score) { player.addScore(score); } /** * Get the score of the player * * @return player's current score */ public double getScore () { return player.getScore(); } /** * Check whether the game is lost * * @return true if game is lost */ public boolean isGameLost () { return getPlayerLives() <= 0; } private void updateGameClockByFrame () { this.gameClock++; } /** * Get the game clock * * @return current game clock */ public double getGameClock () { return this.gameClock; } /** * Get the number of remaining lives of the player * * @return number of lives left */ public int getPlayerLives () { return player.getLivesRemaining(); } /** * Get the amount of money obtained by the player * * @return current amount of money */ public int getMoney () { return player.getMoney(); } /** * Returns whether or not the player has complete all waves and thus has won * the game. This will always return false on survival mode. * * @return boolean of whether game is won (all waves completed) */ public boolean isGameWon() { return levelManager.isGameWon(); } /** * Set whether or not the game is played on survival mode. * @param survivalMode * @return */ public void setSurvivalMode(boolean survivalMode){ levelManager.setSurvivalMode(survivalMode); } /** * Spawns a new wave * * @throws MonsterCreationFailureException */ public void doSpawnActivity () throws MonsterCreationFailureException { // at determined intervals: // if (gameClock % 100 == 0) // or if previous wave defeated: if (monsters.isEmpty()) monsters.addAll(levelManager.spawnNextWave()); } /** * The model's "doFrame()" method that updates all state, spawn monsters, * etc. * * @throws MonsterCreationFailureException */ public void updateGame () throws MonsterCreationFailureException { updateGameClockByFrame(); doSpawnActivity(); doTowerBehaviors(); doItemActions(); removeDeadMonsters(); } private void doItemActions () { Iterator<TDItem> itemIter = items.iterator(); while (itemIter.hasNext()) { TDItem currentItem = itemIter.next(); if (currentItem.isDead()) { itemIter.remove(); currentItem.remove(); return; } currentItem.doAction(environ); } } /** * Place an item at the specified location. * If it costs more than the player has, do nothing. * * @param name * @param x * @param y */ public boolean placeItem (String name, double x, double y) { try { TDItem newItem = factory.placeItem(new Point2D.Double(x, y), name); if (newItem.getCost() <= player.getMoney()) { items.add(newItem); player.changeMoney(-newItem.getCost()); return true; } else { newItem.setImage(null); newItem.remove(); return false; } } catch (Exception e) { e.printStackTrace(); return false; } } /** * Clean up dead monsters from monsters list and JGEngine display. */ private void removeDeadMonsters () { Iterator<Monster> monsterIter = monsters.iterator(); List<Monster> newlyAdded = new ArrayList<Monster>(); while (monsterIter.hasNext()) { Monster currentMonster = monsterIter.next(); if (currentMonster.isDead()) { MonsterSpawnSchema resurrectSchema = currentMonster.getResurrrectMonsterSpawnSchema(); if (resurrectSchema != null) { try { newlyAdded = levelManager.spawnMonsterSpawnSchema(resurrectSchema, currentMonster .getCurrentCoor()); } catch (MonsterCreationFailureException e) { // resurrection schema could not be spawned, so ignore it. e.printStackTrace(); } } monsterIter.remove(); addMoney(currentMonster.getMoneyValue()); currentMonster.remove(); } } monsters.addAll(newlyAdded); } private void addMoney (double moneyValue) { player.changeMoney(moneyValue); } /** * Call this to do the individual behavior of each Tower */ private void doTowerBehaviors () { for (ITower[] towerRow : towers) { for (ITower t : towerRow) { if (t != null) { t.callTowerActions(environ); } } } } /** * Check all collisions specified by the CollisionManager */ public void checkCollisions () { collisionManager.checkAllCollisions(); } /** * Upgrade the tower at the specified coordinates and return true if upgraded successfully. * If not possible, does nothing, and this method returns false. * * @param x x-coordinate of tower to be upgraded * @param y y-coordinate of tower to be upgraded * @return boolean whether or not the tower was successfully upgraded * @throws TowerCreationFailureException */ public boolean upgradeTower (double x, double y) throws TowerCreationFailureException { int[] coordinates = getTileCoordinates(new Point2D.Double(x, y)); if (!isTowerPresent(coordinates)) { return false; } int xtile = coordinates[0]; int ytile = coordinates[1]; ITower existingTower = towers[xtile][ytile]; String newTowerName = existingTower.getUpgradeTowerName(); if (!isValidUpgradeTower(newTowerName)) { return false; } ITower newTower = factory.placeTower(new Point2D.Double(x, y), newTowerName); player.changeMoney(-newTower.getCost()); // TODO: Specify cost of upgrade, calculate difference between old and new tower, or give // some discount? existingTower.remove(); towers[xtile][ytile] = newTower; return true; } /** * Checks if a string is a valid tower name, i.e. non-empty and in the list of possible towers * defined by loaded schemas * * @param newTowerName * @return boolean */ private boolean isValidUpgradeTower (String newTowerName) { return (!newTowerName.equals("") && getPossibleTowers().contains(newTowerName)); } /** * Decrease player's lives by one. */ public void decrementLives () { player.decrementLives(); } /** * TEST METHOD - Create a test blueprint for testing purposes * TODO: remove when we no longer need this * * @return test blueprint */ private GameBlueprint createTestBlueprint () { GameBlueprint testBlueprint = new GameBlueprint(); // Populate TDObjects List<TowerSchema> testTowerSchema = new ArrayList<>(); List<MonsterSchema> testMonsterSchema = new ArrayList<>(); List<ItemSchema> testItemSchema = new ArrayList<>(); // Create test items AnnihilatorItemSchema testAnnihilatorItem = new AnnihilatorItemSchema(); testAnnihilatorItem.addAttribute(ItemSchema.NAME, "Annihilator"); testAnnihilatorItem.addAttribute(ItemSchema.IMAGE_NAME, "fire.png"); testAnnihilatorItem.addAttribute(ItemSchema.COST, (double) 1); testAnnihilatorItem.addAttribute(ItemSchema.DAMAGE, (double) 999); testItemSchema.add(testAnnihilatorItem); AreaBombItemSchema testAreaBombItem = new AreaBombItemSchema(); testAreaBombItem.addAttribute(ItemSchema.NAME, "AreaBomb"); testAreaBombItem.addAttribute(ItemSchema.IMAGE_NAME, "fire.png"); testAreaBombItem.addAttribute(AreaBombItemSchema.RANGE, (double) 100); testItemSchema.add(testAreaBombItem); RowBombItemSchema testRowBombItem = new RowBombItemSchema(); testRowBombItem.addAttribute(ItemSchema.NAME, "RowBomb"); testRowBombItem.addAttribute(ItemSchema.IMAGE_NAME, "fire.png"); testRowBombItem.addAttribute(ItemSchema.COST, (double) 1); testItemSchema.add(testRowBombItem); InstantFreezeItemSchema testInstantFreezeItem = new InstantFreezeItemSchema(); testInstantFreezeItem.addAttribute(ItemSchema.NAME, "InstantFreeze"); testInstantFreezeItem.addAttribute(ItemSchema.IMAGE_NAME, "fire.png"); testInstantFreezeItem.addAttribute(InstantFreezeItemSchema.FREEZE_DURATION, Double.MAX_VALUE); testItemSchema.add(testInstantFreezeItem); LifeSaverItemSchema testLifeSaverItem = new LifeSaverItemSchema(); testLifeSaverItem.addAttribute(ItemSchema.NAME, "LifeSaver"); testLifeSaverItem.addAttribute(ItemSchema.IMAGE_NAME, "fire.png"); testItemSchema.add(testLifeSaverItem); // Create test towers TowerSchema testTowerOne = new TowerSchema(); testTowerOne.addAttribute(TowerSchema.NAME, "MoneyTower"); testTowerOne.addAttribute(TowerSchema.IMAGE_NAME, "tower.gif"); testTowerOne.addAttribute(TowerSchema.BULLET_IMAGE_NAME, "red_bullet.png"); testTowerOne.addAttribute(TowerSchema.SHRAPNEL_IMAGE_NAME, "red_bullet.png"); Collection<TowerBehaviors> towerBehaviors = new ArrayList<TowerBehaviors>(); towerBehaviors.add(TowerBehaviors.MONEY_FARMING); testTowerOne.addAttribute(TowerSchema.UPGRADE_PATH, "BombingTower"); testTowerOne.addAttribute(TowerSchema.TOWER_BEHAVIORS, (Serializable) towerBehaviors); testTowerOne.addAttribute(TowerSchema.COST, (double) 10); testTowerSchema.add(testTowerOne); TowerSchema testTowerTwo = new TowerSchema(); testTowerTwo.addAttribute(TowerSchema.NAME, "ShootingTower"); testTowerTwo.addAttribute(TowerSchema.IMAGE_NAME, "tower.gif"); testTowerTwo.addAttribute(TowerSchema.BULLET_IMAGE_NAME, "red_bullet.png"); testTowerTwo.addAttribute(TowerSchema.SHRAPNEL_IMAGE_NAME, "red_bullet.png"); Collection<TowerBehaviors> towerBehaviors2 = new ArrayList<TowerBehaviors>(); towerBehaviors2.add(TowerBehaviors.SHOOTING); testTowerTwo.addAttribute(TowerSchema.TOWER_BEHAVIORS, (Serializable) towerBehaviors2); testTowerTwo.addAttribute(TowerSchema.COST, (double) 10); testTowerSchema.add(testTowerTwo); TowerSchema testTowerThree = new TowerSchema(); testTowerThree.addAttribute(TowerSchema.NAME, "BombingTower"); testTowerThree.addAttribute(TowerSchema.IMAGE_NAME, "tower.gif"); testTowerThree.addAttribute(TowerSchema.BULLET_IMAGE_NAME, "blue_bullet.png"); testTowerThree.addAttribute(TowerSchema.SHRAPNEL_IMAGE_NAME, "red_bullet.png"); Collection<TowerBehaviors> towerBehaviors3 = new ArrayList<TowerBehaviors>(); towerBehaviors3.add(TowerBehaviors.BOMBING); testTowerThree.addAttribute(TowerSchema.TOWER_BEHAVIORS, (Serializable) towerBehaviors3); testTowerThree.addAttribute(TowerSchema.COST, (double) 10); testTowerSchema.add(testTowerThree); TowerSchema testTowerFour = new TowerSchema(); testTowerFour.addAttribute(TowerSchema.NAME, "FreezingTower"); testTowerFour.addAttribute(TowerSchema.IMAGE_NAME, "tower.gif"); testTowerFour.addAttribute(TowerSchema.BULLET_IMAGE_NAME, "red_bullet.png"); testTowerFour.addAttribute(TowerSchema.SHRAPNEL_IMAGE_NAME, "red_bullet.png"); testTowerFour.addAttribute(TowerSchema.FREEZE_SLOWDOWN_PROPORTION, (double) 0.8); Collection<TowerBehaviors> towerBehaviors4 = new ArrayList<TowerBehaviors>(); towerBehaviors4.add(TowerBehaviors.FREEZING); testTowerFour.addAttribute(TowerSchema.TOWER_BEHAVIORS, (Serializable) towerBehaviors4); testTowerFour.addAttribute(TowerSchema.COST, (double) 10); testTowerSchema.add(testTowerFour); TowerSchema testTowerFive = new TowerSchema(); testTowerFive.addAttribute(TowerSchema.NAME, "SplashingTower"); testTowerFive.addAttribute(TowerSchema.IMAGE_NAME, "tower.gif"); testTowerFive.addAttribute(TowerSchema.BULLET_IMAGE_NAME, "red_bullet.png"); testTowerFive.addAttribute(TowerSchema.SHRAPNEL_IMAGE_NAME, "red_bullet.png"); Collection<TowerBehaviors> towerBehaviors5 = new ArrayList<TowerBehaviors>(); towerBehaviors5.add(TowerBehaviors.SPLASHING); testTowerFive.addAttribute(TowerSchema.TOWER_BEHAVIORS, (Serializable) towerBehaviors5); testTowerFive.addAttribute(TowerSchema.COST, (double) 10); testTowerSchema.add(testTowerFive); //test defaults: /* SimpleMonsterSchema testMonsterOneX = new SimpleMonsterSchema(); testMonsterOneX.addAttribute(MonsterSchema.NAME, ""); testMonsterOneX.addAttribute(MonsterSchema.HEALTH, EnemyViewDefaults.HEALTH_DEFAULT); testMonsterOneX.addAttribute(MonsterSchema.SPEED, EnemyViewDefaults.SPEED_DEFAULT); testMonsterOneX.addAttribute(MonsterSchema.DAMAGE, EnemyViewDefaults.DAMAGE_DEFAULT); testMonsterOneX.addAttribute(MonsterSchema.REWARD, EnemyViewDefaults.REWARD_DEFAULT); testMonsterOneX.addAttribute(MonsterSchema.FLYING_OR_GROUND, MonsterSchema.GROUND); testMonsterOneX.addAttribute(MonsterSchema.TILE_SIZE, MonsterSchema.TILE_SIZE_SMALL); testMonsterOneX.addAttribute(TDObjectSchema.IMAGE_NAME, EnemyViewDefaults.ENEMY_DEFAULT_IMAGE); testMonsterSchema.add(testMonsterOneX);*/ // Create test monsters SimpleMonsterSchema testMonsterOne = new SimpleMonsterSchema(); testMonsterOne.addAttribute(MonsterSchema.NAME, "test-monster-1"); testMonsterOne.addAttribute(TDObjectSchema.IMAGE_NAME, "monster.png"); testMonsterOne.addAttribute(MonsterSchema.SPEED, (double) 1); testMonsterOne.addAttribute(MonsterSchema.REWARD, (double) 200); testMonsterSchema.add(testMonsterOne); SimpleMonsterSchema testMonsterResurrects = new SimpleMonsterSchema(); testMonsterResurrects.addAttribute(MonsterSchema.NAME, "test-monster-2"); testMonsterResurrects.addAttribute(TDObjectSchema.IMAGE_NAME, "monster.png"); // resurrect spawn schema is 2 testMonsterOnes MonsterSpawnSchema resurrect = new MonsterSpawnSchema(testMonsterOne, 2); testMonsterResurrects.addAttribute(MonsterSchema.RESURRECT_MONSTERSPAWNSCHEMA, resurrect); testMonsterResurrects.addAttribute(MonsterSchema.SPEED, (double) 1); testMonsterResurrects.addAttribute(MonsterSchema.REWARD, (double) 200); testMonsterSchema.add(testMonsterResurrects); testBlueprint.setMyTowerSchemas(testTowerSchema); testBlueprint.setMyMonsterSchemas(testMonsterSchema); testBlueprint.setMyItemSchemas(testItemSchema); // Create test game schemas GameSchema testGameSchema = new GameSchema(); testGameSchema.addAttribute(GameSchema.LIVES, 3); testGameSchema.addAttribute(GameSchema.MONEY, 500); testBlueprint.setMyGameScenario(testGameSchema); // Create wave schemas List<WaveSpawnSchema> testWaves = new ArrayList<WaveSpawnSchema>(); MonsterSpawnSchema testMonsterSpawnSchemaOne = new MonsterSpawnSchema(testMonsterResurrects, 1); WaveSpawnSchema testWaveSpawnSchemaOne = new WaveSpawnSchema(); testWaveSpawnSchemaOne.addMonsterSchema(testMonsterSpawnSchemaOne); testWaves.add(testWaveSpawnSchemaOne); MonsterSpawnSchema testMonsterSpawnSchemaTwo = new MonsterSpawnSchema(testMonsterOne, 3); WaveSpawnSchema testWaveSpawnSchemaTwo = new WaveSpawnSchema(); testWaveSpawnSchemaTwo.addMonsterSchema(testMonsterSpawnSchemaTwo); testWaves.add(testWaveSpawnSchemaTwo); MonsterSpawnSchema testMonsterSpawnSchemaThree = new MonsterSpawnSchema(testMonsterOne, 10); WaveSpawnSchema testWaveSpawnSchemaThree = new WaveSpawnSchema(); testWaveSpawnSchemaThree.addMonsterSchema(testMonsterSpawnSchemaThree); testWaves.add(testWaveSpawnSchemaThree); testBlueprint.setMyWaveSchemas(testWaves); return testBlueprint; } /** * A list of names of possible towers to create * * @return */ public List<String> getPossibleTowers () { return Collections.unmodifiableList(factory.getPossibleTowersNames()); } /** * A list of names of possible items to create * * @return */ public List<String> getPossibleItems () { return Collections.unmodifiableList(factory.getPossibleItemNames()); } /** * Save the present game state to a loadable file. * Note: all saved game files saved to under resources folder. * * @param gameName the file name to save the current game under. * @throws InvalidSavedGameException Problem saving the game */ public void saveGame (String gameName) throws InvalidSavedGameException { GameState currentGame = new GameState(); currentGame.updateGameStates(towers, levelManager.getCurrentWave(), levelManager.getAllWaves(), gameClock, player); try { //Michael- i removed the resource_path because it was giving me an error since the method should take the straight file name not the resource path dataHandler.saveState(currentGame, gameName); } catch (IOException ioe) { throw new InvalidSavedGameException(ioe); } } /** * Clears current game and restarts a new game based on loaded saved game. * Only valid saved game files in the resources folder can be loaded. * Pass in the file's name only (e.g. which can be chosen through JFileChooser) * * @param filename The full filename only. * @throws InvalidSavedGameException issue loading the game, * (please pause and notify the player, then continue the present game). */ public void loadSavedGame (String filename) throws InvalidSavedGameException { try { // TODO: check for proper game blueprint loaded prior? //removed the RESOURCE_PATH variable as i think thats causing issues with actually saving GameState newGameState = dataHandler.loadState(filename); // replace towers, player, clock with new state clearAllTowers(); towers = newGameState.getTowers(); player = newGameState.getPlayer(); gameClock = newGameState.getGameClock(); // cleanly reload waves in the level manager, and reset wave # to start at. levelManager.cleanLoadWaveSchemas(newGameState.getAllWaveSchemas(), newGameState.getCurrentWaveNumber()); } catch (ClassNotFoundException | IOException e) { throw new InvalidSavedGameException(e); } } /** * Clear all of the current towers. * Used internally to replace current tower state with with a new loaded saved game state. */ private void clearAllTowers () { for (ITower[] row : towers) { for (ITower t : row) { if (t != null) { t.remove(); } } // null out tower matrix row by row after jgobject removal called. Arrays.fill(row, null); } } }
package jodd.util; import jodd.typeconverter.TypeConverter; import jodd.typeconverter.TypeConverterManager; import jodd.typeconverter.TypeConversionException; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Various java.lang.reflect utilities. */ public class ReflectUtil { /** an empty class array */ public static final Class[] NO_PARAMETERS = new Class[0]; /** an empty object array */ public static final Object[] NO_ARGUMENTS = new Object[0]; /** an empty object array */ public static final Type[] NO_TYPES = new Type[0]; public static final String METHOD_GET_PREFIX = "get"; public static final String METHOD_IS_PREFIX = "is"; public static final String METHOD_SET_PREFIX = "set"; private static Method _getMethod0; static { try { _getMethod0 = Class.class.getDeclaredMethod("getMethod0", String.class, Class[].class); _getMethod0.setAccessible(true); } catch (Exception e) { try { _getMethod0 = Class.class.getMethod("getMethod", String.class, Class[].class); } catch (Exception ex) { _getMethod0 = null; } } } /** * Invokes private <code>Class.getMethod0()</code> without throwing NoSuchMethodException. * Returns only public methods or <code>null</code> if method not found. * * @param c class to inspect * @param name name of method to find * @param parameterTypes parameter types * @return founded method, or null */ public static Method getMethod0(Class c, String name, Class... parameterTypes) { try { return (Method) _getMethod0.invoke(c, name, parameterTypes); } catch (Exception ex) { return null; } } /** * Invokes private <code>Class.getMethod0()</code> without throwing NoSuchMethod exception. * Returns only accessible methods. * * @param o object to inspect * @param name name of method to find * @param parameterTypes parameter types * @return founded method, or null */ public static Method getMethod0(Object o, String name, Class... parameterTypes) { try { return (Method) _getMethod0.invoke(o.getClass(), name, parameterTypes); } catch (Exception ex) { return null; } } /** * Returns method from an object, matched by name. This may be considered as * a slow operation, since methods are matched one by one. * Returns only accessible methods. * Only first method is matched. * * @param c class to examine * @param methodName Full name of the method. * @return null if method not found */ public static Method findMethod(Class c, String methodName) { return findDeclaredMethod(c, methodName, true); } public static Method findDeclaredMethod(Class c, String methodName) { return findDeclaredMethod(c, methodName, false); } private static Method findDeclaredMethod(Class c, String methodName, boolean publicOnly) { if ((methodName == null) || (c == null)) { return null; } Method[] ms = publicOnly ? c.getMethods() : c.getDeclaredMethods(); for (Method m : ms) { if (m.getName().equals(methodName)) { return m; } } return null; } /** * Returns classes from array of specified objects. */ public static Class[] getClasses(Object... objects) { if (objects == null) { return null; } Class[] result = new Class[objects.length]; for (int i = 0; i < objects.length; i++) { if (objects[i] != null) { result[i] = objects[i].getClass(); } } return result; } /** * Invokes accessible method of an object. * * @param c class that contains method * @param obj object to execute * @param method method to invoke * @param paramClasses classes of parameters * @param params parameters */ public static Object invoke(Class c, Object obj, String method, Class[] paramClasses, Object[] params) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { Method m = c.getMethod(method, paramClasses); return m.invoke(obj, params); } /** * Invokes accessible method of an object. * * @param obj object * @param method name of the objects method * @param params method parameters * @param paramClasses method parameter types */ public static Object invoke(Object obj, String method, Class[] paramClasses, Object[] params) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { Method m = obj.getClass().getMethod(method, paramClasses); return m.invoke(obj, params); } /** * Invokes accessible method of an object without specifying parameter types. * @param obj object * @param method method of an object * @param params method parameters */ public static Object invoke(Object obj, String method, Object[] params) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { Class[] paramClass = getClasses(params); return invoke(obj, method, paramClass, params); } public static Object invoke(Class c, Object obj, String method, Object[] params) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { Class[] paramClass = getClasses(params); return invoke(c, obj, method, paramClass, params); } /** * Invokes any method of a class, even private ones. * * @param c class to examine * @param obj object to inspect * @param method method to invoke * @param paramClasses parameter types * @param params parameters */ public static Object invokeDeclared(Class c, Object obj, String method, Class[] paramClasses, Object[] params) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { Method m = c.getDeclaredMethod(method, paramClasses); m.setAccessible(true); return m.invoke(obj, params); } /** * Invokes any method of a class suppressing java access checking. * * @param obj object to inspect * @param method method to invoke * @param paramClasses parameter types * @param params parameters */ public static Object invokeDeclared(Object obj, String method, Class[] paramClasses, Object[] params) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { Method m = obj.getClass().getDeclaredMethod(method, paramClasses); m.setAccessible(true); return m.invoke(obj, params); } public static Object invokeDeclared(Object obj, String method, Object[] params) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { Class[] paramClass = getClasses(params); return invokeDeclared(obj, method, paramClass, params); } public static Object invokeDeclared(Class c, Object obj, String method, Object[] params) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { Class[] paramClass = getClasses(params); return invokeDeclared(c, obj, method, paramClass, params); } /** * Determines if first class match the destination and simulates kind * of <code>instanceof</code>. All subclasses and interface of first class * are examined against second class. Method is not symmetric. */ public static boolean isSubclass(Class thisClass, Class target) { if (target.isInterface() != false) { return isInterfaceImpl(thisClass, target); } for (Class x = thisClass; x != null; x = x.getSuperclass()) { if (x == target) { return true; } } return false; } /** * Returns <code>true</code> if provided class is interface implementation. */ public static boolean isInterfaceImpl(Class thisClass, Class targetInterface) { for (Class x = thisClass; x != null; x = x.getSuperclass()) { Class[] interfaces = x.getInterfaces(); for (Class i : interfaces) { if (i == targetInterface) { return true; } if (isInterfaceImpl(i, targetInterface)) { return true; } } } return false; } /** * Dynamic version of <code>instanceof</code>. * Much faster then Class.isInstance(). * * @param o object to match * @param target target class * @return <code>true</code> if object is an instance of target class */ public static boolean isInstanceOf(Object o, Class target) { return isSubclass(o.getClass(), target); } /** * Casts an object to destination type using {@link TypeConverterManager type conversion}. */ @SuppressWarnings({"unchecked"}) public static <T> T castType(Object value, Class<T> destinationType) { if (value == null) { return null; } if (destinationType.isEnum()) { Object[] enums = destinationType.getEnumConstants(); String valStr = value.toString(); for (Object e : enums) { if (e.toString().equals(valStr)) { return (T) e; } } throw new ClassCastException("Unable to cast enumeration: '" + destinationType.getName() + "'."); } TypeConverter converter = TypeConverterManager.lookup(destinationType); if (converter == null) { if (isInstanceOf(value, destinationType) == true) { return (T) value; } throw new ClassCastException("Unable to cast value to type: '" + destinationType.getName() + "'."); } try { return (T) converter.convert(value); } catch (TypeConversionException tcex) { throw new ClassCastException("Unable to convert value to type: '" + destinationType.getName() + "'.:" + tcex.toString()); } } /** * Returns array of all methods that are accessible from given class. * @see #getAccessibleMethods(Class, Class) */ public static Method[] getAccessibleMethods(Class clazz) { return getAccessibleMethods(clazz, Object.class); } /** * Returns array of all methods that are accessible from given class, upto limit * (usually <code>Object.class</code>). Abstract methods are ignored. */ public static Method[] getAccessibleMethods(Class clazz, Class limit) { Package topPackage = clazz.getPackage(); List<Method> methodList = new ArrayList<Method>(); int topPackageHash = topPackage == null ? 0 : topPackage.hashCode(); boolean top = true; do { if (clazz == null) { break; } Method[] declaredMethods = clazz.getDeclaredMethods(); for (Method method : declaredMethods) { if (Modifier.isVolatile(method.getModifiers())) { continue; } // if (Modifier.isAbstract(method.getModifiers())) { // continue; if (top == true) { // add all top declared methods methodList.add(method); continue; } int modifier = method.getModifiers(); if (Modifier.isPrivate(modifier) == true) { continue; // ignore super private methods } if (Modifier.isAbstract(modifier) == true) { // ignore super abstract methods continue; } if (Modifier.isPublic(modifier) == true) { addMethodIfNotExist(methodList, method); // add super public methods continue; } if (Modifier.isProtected(modifier) == true) { addMethodIfNotExist(methodList, method); // add super protected methods continue; } // add super default methods from the same package Package pckg = method.getDeclaringClass().getPackage(); int pckgHash = pckg == null ? 0 : pckg.hashCode(); if (pckgHash == topPackageHash) { addMethodIfNotExist(methodList, method); } } top = false; } while ((clazz = clazz.getSuperclass()) != limit); Method[] methods = new Method[methodList.size()]; for (int i = 0; i < methods.length; i++) { methods[i] = methodList.get(i); } return methods; } private static void addMethodIfNotExist(List<Method> allMethods, Method newMethod) { for (Method m : allMethods) { if (compareSignatures(m, newMethod) == true) { return; } } allMethods.add(newMethod); } public static Field[] getAccessibleFields(Class clazz) { return getAccessibleFields(clazz, Object.class); } public static Field[] getAccessibleFields(Class clazz, Class limit) { Package topPackage = clazz.getPackage(); List<Field> fieldList = new ArrayList<Field>(); int topPackageHash = topPackage == null ? 0 : topPackage.hashCode(); boolean top = true; do { if (clazz == null) { break; } Field[] declaredFields = clazz.getDeclaredFields(); for (Field field : declaredFields) { if (top == true) { // add all top declared fields fieldList.add(field); continue; } int modifier = field.getModifiers(); if (Modifier.isPrivate(modifier) == true) { continue; // ignore super private fields } if (Modifier.isPublic(modifier) == true) { addFieldIfNotExist(fieldList, field); // add super public methods continue; } if (Modifier.isProtected(modifier) == true) { addFieldIfNotExist(fieldList, field); // add super protected methods continue; } // add super default methods from the same package Package pckg = field.getDeclaringClass().getPackage(); int pckgHash = pckg == null ? 0 : pckg.hashCode(); if (pckgHash == topPackageHash) { addFieldIfNotExist(fieldList, field); } } top = false; } while ((clazz = clazz.getSuperclass()) != limit); Field[] fields = new Field[fieldList.size()]; for (int i = 0; i < fields.length; i++) { fields[i] = fieldList.get(i); } return fields; } private static void addFieldIfNotExist(List<Field> allFields, Field newField) { for (Field f : allFields) { if (compareSignatures(f, newField) == true) { return; } } allFields.add(newField); } public static Method[] getSupportedMethods(Class clazz) { return getSupportedMethods(clazz, Object.class); } /** * Returns a <code>Method</code> array of the methods to which instances of the specified * respond except for those methods defined in the class specified by limit * or any of its superclasses. Note that limit is usually used to eliminate * them methods defined by <code>java.lang.Object</code>. If limit is <code>null</code> then all * methods are returned. */ public static Method[] getSupportedMethods(Class clazz, Class limit) { ArrayList<Method> supportedMethods = new ArrayList<Method>(); for (Class c = clazz; c != limit; c = c.getSuperclass()) { Method[] methods = c.getDeclaredMethods(); for (Method method : methods) { boolean found = false; for (Method supportedMethod : supportedMethods) { if (compareSignatures(method, supportedMethod)) { found = true; break; } } if (found == false) { supportedMethods.add(method); } } } return supportedMethods.toArray(new Method[supportedMethods.size()]); } public static Field[] getSupportedFields(Class clazz) { return getSupportedFields(clazz, Object.class); } public static Field[] getSupportedFields(Class clazz, Class limit) { ArrayList<Field> supportedFields = new ArrayList<Field>(); for (Class c = clazz; c != limit; c = c.getSuperclass()) { Field[] fields = c.getDeclaredFields(); for (Field field : fields) { boolean found = false; for (Field supportedField : supportedFields) { if (compareSignatures(field, supportedField)) { found = true; break; } } if (found == false) { supportedFields.add(field); } } } return supportedFields.toArray(new Field[supportedFields.size()]); } /** * Compares method declarations: signature and return types. */ public static boolean compareDeclarations(Method first, Method second) { if (first.getReturnType() != second.getReturnType()) { return false; } return compareSignatures(first, second); } /** * Compares method signatures: names and parameters */ public static boolean compareSignatures(Method first, Method second) { if (first.getName().equals(second.getName()) == false) { return false; } return compareParameteres(first.getParameterTypes(), second.getParameterTypes()); } /** * Compares constructor signatures: names and parameters */ public static boolean compareSignatures(Constructor first, Constructor second) { if (first.getName().equals(second.getName()) == false) { return false; } return compareParameteres(first.getParameterTypes(), second.getParameterTypes()); } public static boolean compareSignatures(Field first, Field second) { return first.getName().equals(second.getName()); } /** * Compares method or ctor parameters. */ public static boolean compareParameteres(Class[] first, Class[] second) { if (first.length != second.length) { return false; } for (int i = 0; i < first.length; i++) { if (first[i] != second[i]) { return false; } } return true; } /** * Suppress access check against a reflection object. SecurityException is silently ignored. * Checks first if the object is already accessible. */ public static void forceAccess(AccessibleObject accObject){ if (accObject.isAccessible() == true) { return; } try { accObject.setAccessible(true); } catch (SecurityException sex) { // ignore } } /** * Returns <code>true</code> if class member is public. */ public static boolean isPublic(Member member) { return Modifier.isPublic(member.getModifiers()); } /** * Returns <code>true</code> if class member is public and if its declaring class is also public. */ public static boolean isPublicPublic(Member member) { if (Modifier.isPublic(member.getModifiers()) == true) { if (Modifier.isPublic(member.getDeclaringClass().getModifiers())) { return true; } } return false; } /** * Returns <code>true</code> if class is public. */ public static boolean isPublic(Class c) { return Modifier.isPublic(c.getModifiers()); } /** * Creates new intances including for common mutable classes that do not have a default constructor. * more user-friendly. It examines if class is a map, list, * String, Character, Boolean or a Number. Immutable instances are cached and not created again. * Arrays are also created with no elements. Note that this bunch of ifs is faster then a hashmap. */ public static Object newInstance(Class type) throws IllegalAccessException, InstantiationException { if (type.isPrimitive()) { if (type == int.class) { return Integer.valueOf(0); } if (type == long.class) { return Long.valueOf(0); } if (type == boolean.class) { return Boolean.FALSE; } if (type == float.class) { return Float.valueOf(0); } if (type == double.class) { return Double.valueOf(0); } if (type == byte.class) { return Byte.valueOf((byte) 0); } if (type == short.class) { return Short.valueOf((short) 0); } if (type == char.class) { return Character.valueOf((char) 0); } throw new IllegalArgumentException("Invalid primitive type: " + type); } if (type == Integer.class) { return Integer.valueOf(0); } if (type == String.class) { return StringPool.EMPTY; } if (type == Long.class) { return Long.valueOf(0); } if (type == Boolean.class) { return Boolean.FALSE; } if (type == Float.class) { Float.valueOf(0); } if (type == Double.class) { Double.valueOf(0); } if (type == Map.class) { return new HashMap(); } if (type == List.class) { return new ArrayList(); } if (type == Set.class) { return new LinkedHashSet(); } if (type == Collection.class) { return new ArrayList(); } if (type == Byte.class) { return Byte.valueOf((byte) 0); } if (type == Short.class) { return Short.valueOf((short) 0); } if (type == Character.class) { return Character.valueOf((char) 0); } if (type.isEnum() == true) { return type.getEnumConstants()[0]; } if (type.isArray() == true) { return Array.newInstance(type.getComponentType(), 0); } return type.newInstance(); } /** * Returns <code>true</code> if the first member is accessable from second one. */ public static boolean isAssignableFrom(Member member1, Member member2) { return member1.getDeclaringClass().isAssignableFrom(member2.getDeclaringClass()); } /** * Returns all superclasses. */ public static Class[] getSuperclasses(Class type) { int i = 0; for (Class x = type.getSuperclass(); x != null; x = x.getSuperclass()) { i++; } Class[] result = new Class[i]; i = 0; for (Class x = type.getSuperclass(); x != null; x = x.getSuperclass()) { result[i] = x; i++; } return result; } /** * Returns <code>true</code> if method is user defined and not defined in <code>Object</code> class. */ public static boolean isUserDefinedMethod(final Method method) { return method.getDeclaringClass() != Object.class; } /** * Returns <code>true</code> if method defined in <code>Object</code> class. */ public static boolean isObjectMethod(final Method method) { return method.getDeclaringClass() == Object.class; } /** * Returns <code>true</code> if method is a bean property. */ public static boolean isBeanProperty(Method method) { if (isObjectMethod(method)) { return false; } String methodName = method.getName(); Class returnType = method.getReturnType(); Class[] paramTypes = method.getParameterTypes(); if (methodName.startsWith(METHOD_GET_PREFIX)) { // getter method must starts with 'get' and it is not getClass() if ((returnType != null) && (paramTypes.length == 0)) { // getter must have a return type and no arguments return true; } } else if (methodName.startsWith(METHOD_IS_PREFIX)) { // ister must starts with 'is' if ((returnType != null) && (paramTypes.length == 0)) { // ister must have return type and no arguments return true; } } else if (methodName.startsWith(METHOD_SET_PREFIX)) { // setter must start with a 'set' if (paramTypes.length == 1) { // setter must have just one argument return true; } } return false; } /** * Returns <code>true</code> if method is bean getter. */ public static boolean isBeanPropertyGetter(Method method) { if (isObjectMethod(method)) { return false; } String methodName = method.getName(); Class returnType = method.getReturnType(); Class[] paramTypes = method.getParameterTypes(); if (methodName.startsWith(METHOD_GET_PREFIX)) { // getter method must starts with 'get' and it is not getClass() if ((returnType != null) && (paramTypes.length == 0)) { // getter must have a return type and no arguments return true; } } else if (methodName.startsWith(METHOD_IS_PREFIX)) { // ister must starts with 'is' if ((returnType != null) && (paramTypes.length == 0)) { // ister must have return type and no arguments return true; } } return false; } /** * Returns beans property getter name or <code>null</code> if method is not a real getter. */ public static String getBeanPropertyGetterName(Method method) { if (isObjectMethod(method)) { return null; } String methodName = method.getName(); Class returnType = method.getReturnType(); Class[] paramTypes = method.getParameterTypes(); if (methodName.startsWith(METHOD_GET_PREFIX)) { // getter method must starts with 'get' and it is not getClass() if ((returnType != null) && (paramTypes.length == 0)) { // getter must have a return type and no arguments return CharUtil.toLowerAscii(methodName.charAt(3)) + methodName.substring(4); } } else if (methodName.startsWith(METHOD_IS_PREFIX)) { // ister must starts with 'is' if ((returnType != null) && (paramTypes.length == 0)) { // ister must have return type and no arguments return CharUtil.toLowerAscii(methodName.charAt(2)) + methodName.substring(3); } } return null; } /** * Returns <code>true</code> if method is bean setter. */ public static boolean isBeanPropertySetter(Method method) { if (isObjectMethod(method)) { return false; } String methodName = method.getName(); Class[] paramTypes = method.getParameterTypes(); if (methodName.startsWith(METHOD_SET_PREFIX)) { // setter must start with a 'set' if (paramTypes.length == 1) { // setter must have just one argument return true; } } return false; } /** * Returns beans property setter name or <code>null</code> if method is not a real setter. */ public static String getBeanPropertySetterName(Method method) { if (isObjectMethod(method)) { return null; } String methodName = method.getName(); Class[] paramTypes = method.getParameterTypes(); if (methodName.startsWith(METHOD_SET_PREFIX)) { // setter must start with a 'set' if (paramTypes.length == 1) { // setter must have just one argument return CharUtil.toLowerAscii(methodName.charAt(3)) + methodName.substring(4); } } return null; } /** * Returns component type of the given <code>type</code>. * For <code>ParameterizedType</code> it returns the last type in array. */ public static Class getComponentType(Type type) { return getComponentType(type, -1); } /** * Returns the component type of the given <code>type</code>.<br> * For example the following types all have the component-type MyClass: * <ul> * <li>MyClass[]</li> * <li>List&lt;MyClass&gt;</li> * <li>Foo&lt;? extends MyClass&gt;</li> * <li>Bar&lt;? super MyClass&gt;</li> * <li>&lt;T extends MyClass&gt; T[]</li> * </ul> * * @param type is the type where to get the component type from. * @return the component type of the given <code>type</code> or * <code>null</code> if the given <code>type</code> does NOT have * a single (component) type. */ public static Class getComponentType(Type type, int index) { if (type instanceof Class) { Class clazz = (Class) type; if (clazz.isArray()) { return clazz.getComponentType(); } } else if (type instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) type; Type[] generics = pt.getActualTypeArguments(); if (index < 0) { index = generics.length + index; } if (index < generics.length) { return toClass(generics[index]); } } else if (type instanceof GenericArrayType) { GenericArrayType gat = (GenericArrayType) type; return toClass(gat.getGenericComponentType()); } return null; } public static Class getGenericSupertype(Class type, int index) { return getComponentType(type.getGenericSuperclass(), index); } public static Class getGenericSupertype(Class type) { return getComponentType(type.getGenericSuperclass()); } /** * Returns {@link Class} for the given <code>type</code>.<br> * Examples: <br> * <table border="1"> * <tr> * <th><code>type</code></th> * <th><code>getSimpleType(type)</code></th> * </tr> * <tr> * <td><code>String</code></td> * <td><code>String</code></td> * </td> * <tr> * <td><code>List&lt;String&gt;</code></td> * <td><code>List</code></td> * </td> * <tr> * <td><code>&lt;T extends MyClass&gt; T[]</code></td> * <td><code>MyClass[]</code></td> * </td> * </table> * * @param type is the type to convert. * @return the closest class representing the given <code>type</code>. */ public static Class toClass(Type type) { if (type instanceof Class) { return (Class) type; } else if (type instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) type; return toClass(pt.getRawType()); } else if (type instanceof WildcardType) { WildcardType wt = (WildcardType) type; Type[] lower = wt.getLowerBounds(); if (lower.length == 1) { return toClass(lower[0]); } Type[] upper = wt.getUpperBounds(); if (upper.length == 1) { return toClass(upper[0]); } } else if (type instanceof GenericArrayType) { GenericArrayType gat = (GenericArrayType) type; Class componentType = toClass(gat.getGenericComponentType()); // this is sort of stupid but there seems no other way... return Array.newInstance(componentType, 0).getClass(); } else if (type instanceof TypeVariable) { TypeVariable tv = (TypeVariable) type; Type[] bounds = tv.getBounds(); if (bounds.length == 1) { return toClass(bounds[0]); } } return null; } /** * Read annotation value. Returns <code>null</code> on error. */ public static Object readAnnotationValue(Annotation annotation, String name) { try { Method method = annotation.annotationType().getDeclaredMethod(name); return method.invoke(annotation); } catch (Exception ignore) { return null; } } }
package hex.glm; import com.google.gson.JsonObject; import hex.FrameTask.DataInfo; import hex.GridSearch.GridSearchProgress; import hex.glm.GLMModel.GLMXValidationTask; import hex.glm.GLMParams.Family; import hex.glm.GLMParams.Link; import hex.glm.GLMTask.GLMIterationTask; import hex.glm.GLMTask.LMAXTask; import hex.glm.GLMTask.YMUTask; import hex.glm.LSMSolver.ADMMSolver; import jsr166y.CountedCompleter; import water.*; import water.H2O.H2OCallback; import water.H2O.H2OCountedCompleter; import water.api.DocGen; import water.api.ParamImportance; import water.fvec.Frame; import water.util.Log; import water.util.RString; import water.util.Utils; import java.text.DecimalFormat; import java.util.Arrays; import java.util.Properties; import java.util.concurrent.atomic.AtomicInteger; public class GLM2 extends Job.ModelJobWithoutClassificationField { static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields public static DocGen.FieldDoc[] DOC_FIELDS; public static final String DOC_GET = "GLM2"; public final String _jobName; @API(help = "max-iterations", filter = Default.class, lmin=1, lmax=1000000, json=true, importance = ParamImportance.CRITICAL) int max_iter = 100; @API(help = "Standardize numeric columns to have zero mean and unit variance.", filter = Default.class, json=true, importance = ParamImportance.CRITICAL) boolean standardize = true; @API(help = "validation folds", filter = Default.class, lmin=0, lmax=100, json=true, importance = ParamImportance.CRITICAL) int n_folds; @API(help = "Family.", filter = Default.class, json=true, importance = ParamImportance.CRITICAL) Family family = Family.gaussian; @API(help = "Tweedie variance power", filter = Default.class, json=true, importance = ParamImportance.SECONDARY) double tweedie_variance_power; @API(help = "distribution of regularization between L1 and L2.", filter = Default.class, json=true, importance = ParamImportance.SECONDARY) double [] alpha = new double[]{0.5}; @API(help = "regularization strength", filter = Default.class, json=true, importance = ParamImportance.SECONDARY) public double [] lambda = new double[]{1e-5}; @API(help = "beta_eps", filter = Default.class, json=true, importance = ParamImportance.SECONDARY) double beta_epsilon = DEFAULT_BETA_EPS; @API(help="use line search (slower speed, to be used if glm does not converge otherwise)",filter=Default.class) boolean higher_accuracy; @API(help="By default, first factor level is skipped from the possible set of predictors. Set this flag if you want use all of the levels. Needs sufficient regularization to solve!",filter=Default.class) boolean use_all_factor_levels; @API(help="use lambda search starting at lambda max, given lambda is then interpreted as lambda min",filter=Default.class) boolean lambda_search; @API(help="use strong rules to filter out inactive columns",filter=Default.class) boolean strong_rules_enabled = true; // intentionally not declared as API now int sparseCoefThreshold = 1000; // if more than this number of predictors, result vector of coefficients will be stored sparse @API(help="number of lambdas to be used in a search",filter=Default.class) int nlambdas = 100; @API(help="min lambda used in lambda search, specified as a ratio of lambda_max",filter=Default.class) double lambda_min_ratio = 0.0001; @API(help="prior probability for y==1. To be used only for logistic regression iff the data has been sampled and the mean of response does not reflect reality.",filter=Default.class) double prior = -1; // -1 is magic value for default value which is mean(y) computed on the current dataset private transient double _iceptAdjust; // adjustment due to the prior @API(help = "", json=true, importance = ParamImportance.SECONDARY) private double [] _wgiven; @API(help = "", json=true, importance = ParamImportance.SECONDARY) private double _proximalPenalty; @API(help = "", json=true, importance = ParamImportance.SECONDARY) private double [] _beta; @API(help = "", json=true, importance = ParamImportance.SECONDARY) private boolean _runAllLambdas = true; @API(help = "", json=true, importance = ParamImportance.SECONDARY) Link link = Link.identity; @API(help = "Tweedie link power", json=true, importance = ParamImportance.SECONDARY) double tweedie_link_power; @API(help = "lambda max", json=true, importance = ParamImportance.SECONDARY) double lambda_max = Double.NaN; public static int MAX_PREDICTORS = 10000; private static double GLM_GRAD_EPS = 1e-5; // done (converged) if subgrad < this value. private boolean highAccuracy(){return higher_accuracy;} private void setHighAccuracy(){ higher_accuracy = true; } private DataInfo _dinfo; private transient int [] _activeCols; private DataInfo _activeData; public GLMParams _glm; private boolean _grid; private double ADMM_GRAD_EPS = 1e-4; // default addm gradietn eps private static final double MIN_ADMM_GRAD_EPS = 1e-5; // min admm gradient eps int _lambdaIdx = 0; private transient double _addedL2; public static final double DEFAULT_BETA_EPS = 1e-4; private transient double _ymu; private transient double _reg; private transient int _iter; private transient GLMModel _model; private double objval(GLMIterationTask glmt){ return glmt._val.residual_deviance/ glmt._nobs + 0.5*l2pen()*l2norm(glmt._beta) + l1pen()*l1norm(glmt._beta); } private static class IterationInfo { final int _iter; double [] _fullGrad; private final GLMIterationTask _glmt; final int [] _activeCols; public IterationInfo(int i, GLMIterationTask glmt, final int [] activeCols){ _iter = i; _glmt = glmt.clone(); _activeCols = activeCols; assert _glmt._beta != null && _glmt._val != null; } } private transient IterationInfo _lastResult; @Override public JsonObject toJSON() { JsonObject jo = super.toJSON(); if (lambda == null) jo.addProperty("lambda", "automatic"); //better than not printing anything if lambda=null return jo; } @Override public Key defaultDestKey(){ return null; } @Override public Key defaultJobKey() {return null;} public GLM2() {_jobName = "";} public GLM2(String desc, Key jobKey, Key dest, DataInfo dinfo, GLMParams glm, double [] lambda){ this(desc,jobKey,dest,dinfo,glm,lambda,0.5,0); } public GLM2(String desc, Key jobKey, Key dest, DataInfo dinfo, GLMParams glm, double [] lambda, double alpha){ this(desc,jobKey,dest,dinfo,glm,lambda,alpha,0); } public GLM2(String desc, Key jobKey, Key dest, DataInfo dinfo, GLMParams glm, double [] lambda, double alpha, int nfolds){ this(desc,jobKey,dest,dinfo,glm,lambda,0.5,nfolds,DEFAULT_BETA_EPS); } public GLM2(String desc, Key jobKey, Key dest, DataInfo dinfo, GLMParams glm, double [] lambda, double alpha,int nfolds, double betaEpsilon){ this(desc,jobKey,dest,dinfo,glm,lambda,alpha,nfolds,betaEpsilon,null); } public GLM2(String desc, Key jobKey, Key dest, DataInfo dinfo, GLMParams glm, double [] lambda, double alpha, int nfolds, double betaEpsilon, Key parentJob){ this(desc,jobKey,dest,dinfo,glm,lambda,alpha,nfolds,betaEpsilon,parentJob, null,false,-1,0); } public GLM2(String desc, Key jobKey, Key dest, DataInfo dinfo, GLMParams glm, double [] lambda, double alpha, int nfolds, double betaEpsilon, Key parentJob, double [] beta, boolean highAccuracy, double prior, double proximalPenalty) { assert beta == null || beta.length == (dinfo.fullN()+1):"unexpected size of beta, got length " + beta.length + ", expected " + dinfo.fullN(); job_key = jobKey; description = desc; destination_key = dest; beta_epsilon = betaEpsilon; _beta = beta; _dinfo = dinfo; _glm = glm; this.lambda = lambda; _beta = beta; if((_proximalPenalty = proximalPenalty) != 0) _wgiven = beta; this.alpha= new double[]{alpha}; n_folds = nfolds; source = dinfo._adaptedFrame; response = dinfo._adaptedFrame.lastVec(); _jobName = dest.toString() + ((nfolds > 1)?("[" + dinfo._foldId + "]"):""); higher_accuracy = highAccuracy; this.prior = prior; } static String arrayToString (double[] arr) { if (arr == null) { return "(null)"; } StringBuffer sb = new StringBuffer(); for (int i = 0; i < arr.length; i++) { if (i > 0) { sb.append(", "); } sb.append(arr[i]); } return sb.toString(); } /** Return the query link to this page */ public static String link(Key k, String content) { RString rs = new RString("<a href='GLM2.query?source=%$key'>%content</a>"); rs.replace("key", k.toString()); rs.replace("content", content); return rs.toString(); } public static Job gridSearch(Key jobKey, Key destinationKey, DataInfo dinfo, GLMParams glm, double [] lambda, boolean lambda_search, double [] alpha, boolean higher_accuracy, int nfolds){ return gridSearch(jobKey, destinationKey, dinfo, glm, lambda, lambda_search, alpha, higher_accuracy, nfolds, DEFAULT_BETA_EPS); } public static Job gridSearch(Key jobKey, Key destinationKey, DataInfo dinfo, GLMParams glm, double [] lambda, boolean lambda_search, double [] alpha, boolean high_accuracy, int nfolds, double betaEpsilon){ return new GLMGridSearch(4, jobKey, destinationKey,dinfo,glm,lambda, lambda_search, alpha, high_accuracy, nfolds,betaEpsilon).fork(); } protected void complete(){ if(_addedL2 > 0){ String warn = "Added L2 penalty (rho = " + _addedL2 + ") due to non-spd matrix. "; if(_model.warnings == null || _model.warnings.length == 0) _model.warnings = new String[]{warn}; else { _model.warnings = Arrays.copyOf(_model.warnings,_model.warnings.length+1); _model.warnings[_model.warnings.length-1] = warn; } _model.update(self()); } _model.unlock(self()); if( _dinfo._nfolds == 0 && !_grid)remove(); // Remove/complete job only for top-level, not xval GLM2s state = JobState.DONE; if(_fjtask != null)_fjtask.tryComplete(); } @Override public void cancel(Throwable ex){ if(isCancelledOrCrashed())return; if( _model != null ) _model.unlock(self()); if(ex instanceof JobCancelledException){ if(!isCancelledOrCrashed())cancel(); } else super.cancel(ex); } @Override public void init(){ super.init(); if(lambda_search && lambda.length > 1) throw new IllegalArgumentException("Can not supply both lambda_search and multiple lambdas. If lambda_search is on, GLM expects only one value of lambda, representing the lambda min (smallest lambda in the lambda search)."); // check the response if( response.isEnum() && family != Family.binomial)throw new IllegalArgumentException("Invalid response variable, trying to run regression with categorical response!"); switch( family ) { case poisson: case tweedie: if( response.min() < 0 ) throw new IllegalArgumentException("Illegal response column for family='" + family + "', response must be >= 0."); break; case gamma: if( response.min() <= 0 ) throw new IllegalArgumentException("Invalid response for family='Gamma', response must be > 0!"); break; case binomial: if(response.min() < 0 || response.max() > 1) throw new IllegalArgumentException("Illegal response column for family='Binomial', response must in <0,1> range!"); break; default: //pass } Frame fr = DataInfo.prepareFrame(source, response, ignored_cols, family==Family.binomial, true,true); _dinfo = new DataInfo(fr, 1, use_all_factor_levels || lambda_search, standardize,false); if(higher_accuracy)setHighAccuracy(); } @Override protected boolean filterNaCols(){return true;} @Override protected Response serve() { init(); link = family.defaultLink;// TODO tweedie_link_power = 1 - tweedie_variance_power;// TODO _glm = new GLMParams(family, tweedie_variance_power, link, tweedie_link_power); if(alpha.length > 1) { // grid search if(destination_key == null)destination_key = Key.make("GLMGridResults_"+Key.make()); if(job_key == null)job_key = Key.make((byte) 0, Key.JOB, H2O.SELF);; Job j = gridSearch(self(),destination_key, _dinfo, _glm, lambda, lambda_search, alpha, higher_accuracy, n_folds); return GLMGridView.redirect(this,j.dest()); } else { if(destination_key == null)destination_key = Key.make("GLMModel_"+Key.make()); if(job_key == null)job_key = Key.make("GLM2Job_"+Key.make()); fork(); return GLMProgress.redirect(this,job_key, dest()); } } private static double beta_diff(double[] b1, double[] b2) { if(b1 == null)return Double.MAX_VALUE; double res = Math.abs(b1[0] - b2[0]); for( int i = 1; i < b1.length; ++i ) res = Math.max(res, Math.abs(b1[i] - b2[i])); return res; } @Override public float progress(){ return (float)_iter/max_iter;} protected double l2norm(double[] beta){ double l2 = 0; for(int i = 0; i < beta.length; ++i) l2 += beta[i]*beta[i]; return l2; } protected double l1norm(double[] beta){ double l2 = 0; for(int i = 0; i < beta.length; ++i) l2 += Math.abs(beta[i]); return l2; } private final double [] expandVec(double [] beta, final int [] activeCols){ if(activeCols == null)return beta; double [] res = MemoryManager.malloc8d(_dinfo.fullN()+1); int i = 0; for(int c:activeCols) res[c] = beta[i++]; res[res.length-1] = beta[beta.length-1]; return res; } private final double [] contractVec(double [] beta, final int [] activeCols){ if(activeCols == null)return beta.clone(); double [] res = MemoryManager.malloc8d(activeCols.length+1); int i = 0; for(int c:activeCols) res[i++] = beta[c]; res[res.length-1] = beta[beta.length-1]; return res; } private final double [] resizeVec(double[] beta, final int[] activeCols, final int[] oldActiveCols){ if(Arrays.equals(activeCols,oldActiveCols))return beta; double [] full = expandVec(beta,oldActiveCols); if(activeCols == null)return full; return contractVec(full,activeCols); } protected boolean needLineSearch(final double [] beta,double objval, double step){ if(Double.isNaN(objval))return true; // needed for gamma (and possibly others...) final double [] grad = _activeCols == _lastResult._activeCols ?_lastResult._glmt.gradient(l2pen()) :contractVec(_lastResult._fullGrad,_activeCols); // line search double f_hat = 0; ADMMSolver.subgrad(alpha[0],lambda[_lambdaIdx],beta,grad); final double [] oldBeta = resizeVec(_lastResult._glmt._beta, _activeCols,_lastResult._activeCols); for(int i = 0; i < beta.length; ++i){ double diff = beta[i] - oldBeta[i]; f_hat += grad[i]*diff; } f_hat = objval(_lastResult._glmt) + 0.25*step*f_hat; return objval > f_hat; } private class LineSearchIteration extends H2OCallback<GLMTask.GLMLineSearchTask> { @Override public void callback(final GLMTask.GLMLineSearchTask glmt) { double step = 0.5; for(int i = 0; i < glmt._objvals.length; ++i){ if(!needLineSearch(glmt._betas[i],glmt._objvals[i],step)){ Log.info("GLM2 (iteration=" + _iter + ") line search: found admissible step=" + step); _lastResult = null; // set last result to null so that the Iteration will not attempt to verify whether or not it should do the line search. new GLMIterationTask(GLM2.this,_activeData,_glm,true,true,true,glmt._betas[i],_ymu,_reg,new Iteration()).asyncExec(_activeData._adaptedFrame); return; } step *= 0.5; } // no line step worked, forcibly converge Log.info("GLM2 (iteration=" + _iter + ") line search failed to find feasible step. Forcibly converged."); nextLambda(_lastResult._glmt.clone(),resizeVec(_lastResult._glmt._beta,_activeCols,_lastResult._activeCols)); } @Override public boolean onExceptionalCompletion(Throwable ex, CountedCompleter caller){ GLM2.this.cancel(ex); return true; } } protected double checkGradient(final double [] newBeta, final double [] grad){ // check the gradient ADMMSolver.subgrad(alpha[0], lambda[_lambdaIdx], newBeta, grad); double err = 0; for(double d:grad) if(d > err) err = d; else if(d < -err) err = -d; Log.info("GLM converged with max |subgradient| = " + err); return err; } protected void nextLambda(final GLMIterationTask glmt, GLMValidation val){ currentLambdaIter = 0; boolean improved = _model.setAndTestValidation(_lambdaIdx,val); _model.clone().update(self()); boolean done = false; // _iter < max_iter && (improved || _runAllLambdas) && _lambdaIdx < (lambda.length-1); if(_iter == max_iter){ Log.info("GLM2 reached max #iterations."); done = true; } else if(!improved && !_runAllLambdas){ Log.info("GLM2 converged as solution stopped improving with decreasing lambda."); done = true; } else if(_lambdaIdx == lambda.length-1){ Log.info("GLM2 done with all given lambdas."); done = true; } else if(_activeCols != null && _activeCols.length + 1 >= MAX_PREDICTORS){ Log.info("GLM2 reached maximum allowed number of predictors at lambda = " + lambda[_lambdaIdx]); done = true; } if(!done){ // continue with next lambda value? ++_lambdaIdx; glmt._val = null; if(glmt._gram == null){ // assume we had lambda search with strong rules // we use strong rules so we can't really used this gram for the next lambda computation (different sets of coefficients) // I expect that: // 1) beta has been expanded to match current set of active cols // 2) it is new GLMIteration ready to be launched // caller (nextLambda(glmt,beta)) is expected to ensure this... assert _activeCols == null || (glmt._beta.length == _activeCols.length+1); assert !glmt.isDone(); glmt.asyncExec(_activeData._adaptedFrame); } else // we have the right gram, just solve with with next lambda new Iteration().callback(glmt); } else // nope, we're done GLM2.this.complete(); // signal we're done to anyone waiting for the job } private void nextLambda(final GLMIterationTask glmt, final double [] newBeta){ final double [] fullBeta = setNewBeta(newBeta); // now we need full gradient (on all columns) using this beta new GLMIterationTask(GLM2.this,_dinfo,_glm,false,true,true,fullBeta,_ymu,_reg,new H2OCallback<GLMIterationTask>(GLM2.this){ @Override public void callback(final GLMIterationTask glmt2){ final double [] grad = glmt2.gradient(l2pen()); if(_lastResult != null && _lambdaIdx < (lambda.length-1)) _lastResult._fullGrad = glmt2.gradient(l2pen(_lambdaIdx+1)); // check the KKT conditions and filter data for next lambda // check the gradient ADMMSolver.subgrad(alpha[0], lambda[_lambdaIdx], fullBeta, grad); double err = 0; if(_activeCols != null){ for(int c:_activeCols) if(grad[c] > err) err = grad[c]; else if(grad[c] < -err) err = -grad[c]; int [] failedCols = new int[64]; int fcnt = 0; for(int i = 0; i < grad.length-1; ++i){ if(Arrays.binarySearch(_activeCols,i) >= 0)continue; if(grad[i] > GLM_GRAD_EPS || -grad[i] < -GLM_GRAD_EPS){ if(fcnt == failedCols.length) failedCols = Arrays.copyOf(failedCols,failedCols.length << 1); failedCols[fcnt++] = i; } } if(fcnt > 0){ Log.info("GLM2: " + fcnt + " variables failed KKT conditions check! Adding them to the model and continuing computation..."); final int n = _activeCols.length; final int [] oldActiveCols = _activeCols; _activeCols = Arrays.copyOf(_activeCols,_activeCols.length+fcnt); for(int i = 0; i < fcnt; ++i) _activeCols[n+i] = failedCols[i]; Arrays.sort(_activeCols); _activeData = _dinfo.filterExpandedColumns(_activeCols); new GLMIterationTask(GLM2.this, _activeData,_glm,true,false,false, resizeVec(newBeta,_activeCols,oldActiveCols),glmt._ymu,glmt._reg,new Iteration()).asyncExec(_activeData._adaptedFrame); return; } } else { for(double d:grad) if(d > err) err = d; else if(d < -err) err = -d; } final GLMIterationTask glmt3; // now filter out the cols for the next lambda... if(lambda.length > 1 && _lambdaIdx < lambda.length-1 && _activeCols != null){ final int [] oldCols = _activeCols; activeCols(lambda[_lambdaIdx+1],lambda[_lambdaIdx],glmt2.gradient(l2pen())); // epxand the beta final double [] fullBeta = glmt2._beta; final double [] newBeta; if(_activeCols != null){ newBeta = MemoryManager.malloc8d(_activeCols.length+1); newBeta[newBeta.length-1] = fullBeta[fullBeta.length-1]; int j = 0; for(int c:_activeCols) newBeta[j++] = fullBeta[c]; assert j == newBeta.length-1; } else newBeta = fullBeta; if(Arrays.equals(oldCols,_activeCols) && (glmt._gram.fullN() == _activeCols.length+1)) // set of coefficients did not change glmt3 = glmt; else glmt3 = new GLMIterationTask(GLM2.this,_activeData,glmt._glm,true,false,false,newBeta,glmt._ymu,glmt._reg,new Iteration()); } else glmt3 = glmt; if(n_folds > 1) xvalidate(_model,_lambdaIdx,new H2OCallback<GLMModel.GLMValidationTask>(GLM2.this) { @Override public void callback(GLMModel.GLMValidationTask v){ nextLambda(glmt3,v._res);} }); else nextLambda(glmt3,glmt2._val); } }).asyncExec(_dinfo._adaptedFrame); } private double [] setNewBeta(final double [] newBeta){ final double [] fullBeta = (_activeCols == null)?newBeta:expandVec(newBeta,_activeCols); final double [] newBetaDeNorm; if(_dinfo._standardize) { newBetaDeNorm = fullBeta.clone(); double norm = 0.0; // Reverse any normalization on the intercept // denormalize only the numeric coefs (categoricals are not normalized) final int numoff = _dinfo.numStart(); for( int i=numoff; i< fullBeta.length-1; i++ ) { double b = newBetaDeNorm[i]*_dinfo._normMul[i-numoff]; norm += b*_dinfo._normSub[i-numoff]; // Also accumulate the intercept adjustment newBetaDeNorm[i] = b; } newBetaDeNorm[newBetaDeNorm.length-1] -= norm; } else newBetaDeNorm = null; _model.setLambdaSubmodel(_lambdaIdx, newBetaDeNorm == null ? fullBeta : newBetaDeNorm, newBetaDeNorm == null ? null : fullBeta, (_iter + 1),_dinfo.fullN() >= sparseCoefThreshold); _model.clone().update(self()); return fullBeta; } private class Iteration extends H2OCallback<GLMIterationTask> { public final long _iterationStartTime; public Iteration(){super(GLM2.this); _iterationStartTime = System.currentTimeMillis(); _model.start_training(null);} @Override public void callback(final GLMIterationTask glmt){ _model.stop_training(); Log.info("GLM2 iteration(" + _iter + ") done in " + (System.currentTimeMillis() - _iterationStartTime) + "ms"); if( !isRunning(self()) ) throw new JobCancelledException(); currentLambdaIter++; if(glmt._val != null){ if(!(glmt._val.residual_deviance < glmt._val.null_deviance)){ // complete fail, look if we can restart with higher_accuracy on if(!highAccuracy()){ Log.info("GLM2 reached negative explained deviance without line-search, rerunning with high accuracy settings."); setHighAccuracy(); if(_lastResult != null) new GLMIterationTask(GLM2.this,_activeData,glmt._glm, true, true, true, _lastResult._glmt._beta,_ymu,_reg,new Iteration()).asyncExec(_activeData._adaptedFrame); else if(_lambdaIdx > 2) // > 2 because 0 is null model, we don't wan to run with that new GLMIterationTask(GLM2.this,_activeData,glmt._glm, true, true, true, _model.submodels[_lambdaIdx-1].norm_beta,_ymu,_reg,new Iteration()).asyncExec(_activeData._adaptedFrame); else // no sane solution to go back to, start from scratch! new GLMIterationTask(GLM2.this,_activeData,glmt._glm, true, false, false, null,_ymu,_reg,new Iteration()).asyncExec(_activeData._adaptedFrame); _lastResult = null; return; } } _model.setAndTestValidation(_lambdaIdx,glmt._val); _model.clone().update(self()); } if(glmt._val != null && glmt._computeGradient){ // check gradient final double [] grad = glmt.gradient(l2pen()); ADMMSolver.subgrad(alpha[0], lambda[_lambdaIdx], glmt._beta, grad); double err = 0; for(double d:grad) if(d > err) err = d; else if(d < -err) err = -d; Log.info("GLM2 gradient after " + _iter + " iterations = " + err); if(err <= GLM_GRAD_EPS){ Log.info("GLM2 converged by reaching small enough gradient, with max |subgradient| = " + err); setNewBeta(glmt._beta); nextLambda(glmt, glmt._beta); return; } } if(glmt._beta != null && glmt._val!=null && glmt._computeGradient && _glm.family != Family.tweedie){ if(_lastResult != null && needLineSearch(glmt._beta,objval(glmt),1)){ if(!highAccuracy()){ setHighAccuracy(); if(_lastResult._iter < (_iter-2)){ // there is a gap form last result...return to it and start again final double [] prevBeta = _lastResult._activeCols != _activeCols? resizeVec(_lastResult._glmt._beta, _activeCols, _lastResult._activeCols):_lastResult._glmt._beta; new GLMIterationTask(GLM2.this,_activeData,glmt._glm, true, true, true, prevBeta, _ymu,_reg,new Iteration()).asyncExec(_activeData._adaptedFrame); return; } } final double [] b = resizeVec(_lastResult._glmt._beta, _activeCols, _lastResult._activeCols); assert (b.length == glmt._beta.length):b.length + " != " + glmt._beta.length + ", activeCols = " + _activeCols.length; new GLMTask.GLMLineSearchTask(GLM2.this,_activeData,_glm, resizeVec(_lastResult._glmt._beta, _activeCols, _lastResult._activeCols),glmt._beta,1e-4,glmt._nobs,alpha[0],lambda[_lambdaIdx], new LineSearchIteration()).asyncExec(_activeData._adaptedFrame); return; } _lastResult = new IterationInfo(GLM2.this._iter-1, glmt,_activeCols); } final double [] newBeta = MemoryManager.malloc8d(glmt._xy.length); ADMMSolver slvr = new ADMMSolver(lambda[_lambdaIdx],alpha[0], ADMM_GRAD_EPS, _addedL2); slvr.solve(glmt._gram,glmt._xy,glmt._yy,newBeta); _addedL2 = slvr._addedL2; if(Utils.hasNaNsOrInfs(newBeta)){ Log.info("GLM2 forcibly converged by getting NaNs and/or Infs in beta"); nextLambda(glmt,glmt._beta); } else { setNewBeta(newBeta); final double bdiff = beta_diff(glmt._beta,newBeta); if(_glm.family == Family.gaussian || bdiff < beta_epsilon || _iter == max_iter){ // Gaussian is non-iterative and gradient is ADMMSolver's gradient => just validate and move on to the next lambda int diff = (int)Math.log10(bdiff); int nzs = 0; for(int i = 0; i < newBeta.length; ++i) if(newBeta[i] != 0) ++nzs; if(newBeta.length < 20)System.out.println("beta = " + Arrays.toString(newBeta)); Log.info("GLM2 (lambda_" + _lambdaIdx + "=" + lambda[_lambdaIdx] + ") converged (reached a fixed point with ~ 1e" + diff + " precision) after " + _iter + "iterations, got " + nzs + " nzs"); nextLambda(glmt,newBeta); } else { // not done yet, launch next iteration final boolean validate = higher_accuracy || (currentLambdaIter % 5) == 0; ++_iter; System.out.println("Iter = " + _iter); new GLMIterationTask(GLM2.this,_activeData,glmt._glm, true, validate, validate, newBeta,_ymu,_reg,new Iteration()).asyncExec(_activeData._adaptedFrame); } } } } private int currentLambdaIter = 0; @Override public GLM2 fork(){ start(new H2O.H2OEmptyCompleter()); run(true); return this; } // start inside of a parent job public void run(final H2OCountedCompleter fjt){ assert GLM2.this._fjtask == null; GLM2.this._fjtask = fjt; run(); } public long start = 0; public void run(){run(false);} public void run(final boolean doLog){ if(doLog)logStart(); System.out.println("running with " + _dinfo.fullN() + " predictors"); _activeData = _dinfo; assert alpha.length == 1; start = System.currentTimeMillis(); if(highAccuracy() || lambda_search) // shortcut for fast & simple mode new YMUTask(GLM2.this,_dinfo,new H2OCallback<YMUTask>(GLM2.this) { @Override public void callback(final YMUTask ymut){ run(ymut.ymu(),ymut.nobs()); } }).asyncExec(_dinfo._adaptedFrame); else { double ymu = _dinfo._adaptedFrame.lastVec().mean(); run(ymu, _dinfo._adaptedFrame.numRows()); // shortcut for quick & simple } } private void run(final double ymu, final long nobs){ if(_glm.family == Family.binomial && prior != -1 && prior != ymu && !Double.isNaN(prior)){ double ratio = prior/ymu; double pi0 = 1,pi1 = 1; if(ratio > 1){ pi1 = 1.0/ratio; } else if(ratio < 1) { pi0 = ratio; } _iceptAdjust = Math.log(pi0/pi1); } else prior = ymu; if(highAccuracy() || lambda_search){ new LMAXTask(GLM2.this, _dinfo, _glm, ymu,nobs,alpha[0],new H2OCallback<LMAXTask>(GLM2.this){ @Override public void callback(LMAXTask t){ run(ymu,nobs,t);} }).asyncExec(_dinfo._adaptedFrame); } else run(ymu, nobs, null); // shortcut for quick & simple } private void run(final double ymu, final long nobs, LMAXTask lmaxt){ String [] warns = null; if((!lambda_search || !strong_rules_enabled) && (_dinfo.fullN() > MAX_PREDICTORS)) throw new IllegalArgumentException("Too many predictors! GLM can only handle " + MAX_PREDICTORS + " predictors, got " + _dinfo.fullN() + ", try to run with strong_rules enabled."); if(lambda_search){ max_iter = Math.max(300,max_iter); assert lmaxt != null:"running lambda search, but don't know what is the lambda max!"; final double lmax = lmaxt.lmax(); final double d = Math.pow(lambda_min_ratio,1.0/nlambdas); lambda = new double [nlambdas]; lambda[0] = lmax; for(int i = 1; i < lambda.length; ++i) lambda[i] = lambda[i-1]*d; _runAllLambdas = false; } else if(alpha[0] > 0 && lmaxt != null) { // make sure we start with lambda max (and discard all lambda > lambda max) final double lmax = lmaxt.lmax(); int i = 0; while(i < lambda.length && lambda[i] > lmax)++i; if(i != 0) { Log.info("GLM: removing " + i + " lambdas > lambda_max: " + Arrays.toString(Arrays.copyOf(lambda,i))); warns = i == lambda.length?new String[] {"Removed " + i + " lambdas > lambda_max","No lambdas < lambda_max, returning null model."}:new String[] {"Removed " + i + " lambdas > lambda_max"}; } lambda = i == lambda.length?new double [] {lambda_max}:Arrays.copyOfRange(lambda, i, lambda.length); } _model = new GLMModel(GLM2.this,dest(),_dinfo, _glm,beta_epsilon,alpha[0],lambda_max,lambda,ymu,prior); _model.warnings = warns; _model.clone().delete_and_lock(self()); if(lambda[0] == lambda_max && alpha[0] > 0){ // fill-in trivial solution for lambda max _beta = MemoryManager.malloc8d(_dinfo.fullN()+1); _beta[_beta.length-1] = _glm.link(ymu) + _iceptAdjust; _model.setLambdaSubmodel(0,_beta,_beta,0,_dinfo.fullN() >= sparseCoefThreshold); if(lmaxt != null) _model.setAndTestValidation(0,lmaxt._val); _lambdaIdx = 1; } if(_lambdaIdx == lambda.length) // ran only with one lambda > lambda_max => return null model GLM2.this.complete(); // signal we're done to anyone waiting for the job else { ++_iter; if(lmaxt != null && strong_rules_enabled) activeCols(lambda[_lambdaIdx],lmaxt.lmax(),lmaxt.gradient(l2pen())); Log.info("GLM2 staring GLM after " + (System.currentTimeMillis()-start) + "ms of preprocessing (mean/lmax/strong rules computation)"); new GLMIterationTask(GLM2.this, _activeData,_glm,true,false,false,null,_ymu = ymu,_reg = 1.0/nobs, new Iteration()).asyncExec(_activeData._adaptedFrame); } } private final double l2pen(){return l2pen(_lambdaIdx);} private final double l2pen(int lambdaIdx){return lambda[lambdaIdx]*(1-alpha[0]);} private final double l1pen(){return lambda[_lambdaIdx]*alpha[0];} // filter the current active columns using the strong rules // note: strong rules are update so tha they keep all previous coefficients in, to prevent issues with line-search private int [] activeCols(final double l1, final double l2, final double [] grad){ final double rhs = alpha[0]*(2*l1-l2); int [] cols = MemoryManager.malloc4(_dinfo.fullN()); int selected = 0; int j = 0; if(_activeCols == null)_activeCols = new int[]{-1}; for(int i = 0; i < _dinfo.fullN(); ++i) if((j < _activeCols.length && i == _activeCols[j]) || grad[i] > rhs || grad[i] < -rhs){ cols[selected++] = i; if(j < _activeCols.length && i == _activeCols[j])++j; } if(!strong_rules_enabled || selected == _dinfo.fullN()){ _activeCols = null; _activeData._adaptedFrame = _dinfo._adaptedFrame; _activeData = _dinfo; } else { _activeCols = Arrays.copyOf(cols,selected); _activeData = _dinfo.filterExpandedColumns(_activeCols); } Log.info("GLM2 strong rule at lambda=" + l1 + ", got " + selected + " active cols out of " + _dinfo.fullN() + " total."); return _activeCols; } private void xvalidate(final GLMModel model, int lambdaIxd,final H2OCountedCompleter cmp){ final Key [] keys = new Key[n_folds]; GLM2 [] glms = new GLM2[n_folds]; for(int i = 0; i < n_folds; ++i) glms[i] = new GLM2(this.description + "xval " + i, self(), keys[i] = Key.make(destination_key + "_" + _lambdaIdx + "_xval" + i), _dinfo.getFold(i, n_folds),_glm,new double[]{lambda[_lambdaIdx]},model.alpha,0, model.beta_eps,self(),model.norm_beta(_lambdaIdx),higher_accuracy,prior,0); H2O.submitTask(new ParallelGLMs(GLM2.this,glms,H2O.CLOUD.size(),new H2OCallback(GLM2.this) { @Override public void callback(H2OCountedCompleter t) { GLMModel [] models = new GLMModel[keys.length]; // we got the xval models, now compute their validations... for(int i = 0; i < models.length; ++i)models[i] = DKV.get(keys[i]).get(); new GLMXValidationTask(model,_lambdaIdx,models, cmp).asyncExec(_dinfo._adaptedFrame); } })); } // Expand grid search related argument sets @Override protected NanoHTTPD.Response serveGrid(NanoHTTPD server, Properties parms, RequestType type) { return superServeGrid(server, parms, type); } public static final DecimalFormat AUC_DFORMAT = new DecimalFormat(" public static final String aucStr(double auc){ return AUC_DFORMAT.format(Math.round(1000 * auc) * 0.001); } public static final DecimalFormat AIC_DFORMAT = new DecimalFormat(" public static final String aicStr(double aic){ return AUC_DFORMAT.format(Math.round(1000*aic)*0.001); } public static final DecimalFormat DEV_EXPLAINED_DFORMAT = new DecimalFormat(" public static final String devExplainedStr(double dev){ return AUC_DFORMAT.format(Math.round(1000*dev)*0.001); } public static class GLMGrid extends Iced { static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields static public DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code. final Key _jobKey; final long _startTime; @API(help="mean of response in the training dataset") final Key [] destination_keys; final double [] _alphas; public GLMGrid (Key jobKey, GLM2 [] jobs){ _jobKey = jobKey; _alphas = new double [jobs.length]; destination_keys = new Key[jobs.length]; for(int i = 0; i < jobs.length; ++i){ destination_keys[i] = jobs[i].destination_key; _alphas[i] = jobs[i].alpha[0]; } _startTime = System.currentTimeMillis(); } } public static class GLMGridSearch extends Job { public final int _maxParallelism; transient private AtomicInteger _idx; public final GLM2 [] _jobs; public GLMGridSearch(int maxP, Key jobKey, Key dstKey, DataInfo dinfo, GLMParams glm, double [] lambdas, boolean lambda_search, double [] alphas, boolean high_accuracy, int nfolds, double betaEpsilon){ super(jobKey, dstKey); description = "GLM Grid with params " + glm.toString() + "on data " + dinfo.toString() ; _maxParallelism = maxP; _jobs = new GLM2[alphas.length]; _idx = new AtomicInteger(_maxParallelism); for(int i = 0; i < _jobs.length; ++i) { _jobs[i] = new GLM2("GLM grid(" + i + ")",self(),Key.make(dstKey.toString() + "_" + i),dinfo,glm,lambdas,alphas[i], nfolds, betaEpsilon,self()); _jobs[i]._grid = true; _jobs[i].lambda_search = lambda_search; _jobs[i].higher_accuracy = high_accuracy; } } @Override public float progress(){ float sum = 0f; for(GLM2 g:_jobs)sum += g.progress(); return sum/_jobs.length; } @Override public Job fork(){ DKV.put(destination_key, new GLMGrid(self(),_jobs)); assert _maxParallelism >= 1; final H2OCountedCompleter fjt = new H2OCallback<ParallelGLMs>() { @Override public void callback(ParallelGLMs pgs){ remove(); } }; start(fjt); H2O.submitTask(new ParallelGLMs(this,_jobs,H2O.CLOUD.size(),fjt)); return this; } @Override public Response redirect() { String n = GridSearchProgress.class.getSimpleName(); return Response.redirect( this, n, "job_key", job_key, "destination_key", destination_key); } } // class to execute multiple GLM runs in parallel // (with user-given limit on how many to run in in parallel) public static class ParallelGLMs extends DTask { transient final private GLM2 [] _glms; transient final Job _job; transient final public int _maxP; transient private AtomicInteger _remCnt; transient private AtomicInteger _doneCnt; public ParallelGLMs(Job j, GLM2 [] glms){this(j,glms,H2O.CLOUD.size());} public ParallelGLMs(Job j, GLM2 [] glms, int maxP){_job = j; _glms = glms; _maxP = maxP;} public ParallelGLMs(Job j, GLM2 [] glms, int maxP, H2OCountedCompleter cmp){super(cmp); _job = j; _glms = glms; _maxP = maxP;} private void forkDTask(int i){ int nodeId = i%H2O.CLOUD.size(); final GLM2 glm = _glms[i]; new RPC(H2O.CLOUD._memary[nodeId],new DTask() { @Override public void compute2() { glm.run(this); } }).addCompleter(new Callback()).call(); } class Callback extends H2OCallback<H2OCountedCompleter> { public Callback(){super(_job);} @Override public void callback(H2OCountedCompleter cc){ int i; if((i = _remCnt.getAndDecrement()) > 0) // not done yet forkDTask(_glms.length - i); else if(_doneCnt.getAndDecrement() == 0) // am I the last guy to finish? if so complete parent. ParallelGLMs.this.tryComplete(); // else just done myself (no more work) but others still in progress -> just return } @Override public boolean onExceptionalCompletion(Throwable ex, CountedCompleter caller){ _job.cancel(ex); return true; } } @Override public void compute2(){ final int n = Math.min(_maxP, _glms.length); _remCnt = new AtomicInteger(_glms.length-n); _doneCnt = new AtomicInteger(n-1); for(int i = 0; i < n; ++i) forkDTask(i); } } }
package com.redhat.ceylon.compiler.java; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import ceylon.language.ArraySequence; import ceylon.language.AssertionException; import ceylon.language.Callable; import ceylon.language.Integer; import ceylon.language.Iterable; import ceylon.language.Iterator; import ceylon.language.Ranged; import ceylon.language.Sequential; import ceylon.language.empty_; import ceylon.language.finished_; import com.redhat.ceylon.cmr.api.ArtifactResult; import com.redhat.ceylon.compiler.java.metadata.Ceylon; import com.redhat.ceylon.compiler.java.metadata.Class; import com.redhat.ceylon.compiler.java.metadata.SatisfiedTypes; import com.redhat.ceylon.compiler.java.runtime.metamodel.Metamodel; import com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor; public class Util { static { // Make sure the rethrow class is loaded if ever we need to rethrow // errors such as StackOverflowError, otherwise if we have to rethrow it // we will not be able to load that class since we've ran out of stack ceylon.language.impl.rethrow_.class.toString(); } public static String declClassName(String name) { return name.replace("::", "."); } public static void loadModule(String name, String version, ArtifactResult result, ClassLoader classLoader){ Metamodel.loadModule(name, version, result, classLoader); } public static boolean isReified(java.lang.Object o, TypeDescriptor type){ return Metamodel.isReified(o, type); } /** * Returns true if the given object satisfies ceylon.language.Identifiable */ public static boolean isIdentifiable(java.lang.Object o){ return satisfiesInterface(o, "ceylon.language.Identifiable"); } /** * Returns true if the given object extends ceylon.language.Basic */ public static boolean isBasic(java.lang.Object o){ return extendsClass(o, "ceylon.language.Basic"); } /** * Returns true if the given object extends the given class */ public static boolean extendsClass(java.lang.Object o, String className) { if(o == null) return false; if(className == null) throw new AssertionException("Type name cannot be null"); return classExtendsClass(o.getClass(), className); } private static boolean classExtendsClass(java.lang.Class<?> klass, String className) { if(klass == null) return false; if (klass.getName().equals(className)) return true; if ((className.equals("ceylon.language.Basic")) && klass!=java.lang.Object.class //&& klass!=java.lang.String.class && !klass.isAnnotationPresent(Class.class) && (!klass.isInterface() || !klass.isAnnotationPresent(Ceylon.class))) { //TODO: this is broken for a Java class that // extends a Ceylon class return true; } return classExtendsClass(getCeylonSuperClass(klass), className); } private static java.lang.Class<?> getCeylonSuperClass(java.lang.Class<?> klass) { Class classAnnotation = klass.getAnnotation(Class.class); // only consider Class.extendsType() if non-empty if (classAnnotation != null && !classAnnotation.extendsType().isEmpty()) { String superclassName = declClassName(classAnnotation.extendsType()); int i = superclassName.indexOf('<'); if (i>0) { superclassName = superclassName.substring(0, i); } if (superclassName.isEmpty()) { throw new RuntimeException("Malformed @Class.extendsType() annotation value: "+classAnnotation.extendsType()); } try { return java.lang.Class.forName(superclassName, true, klass.getClassLoader()); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } // we consider that subclasses of Object that do not have any @Ceylon.extendsType() are in fact subclasses of Basic if(klass.getSuperclass() != java.lang.Object.class) return klass.getSuperclass(); // Anything has no super class if(klass == ceylon.language.Anything.class) return null; // The default super class is Basic return ceylon.language.Basic.class; } /** * Returns true if the given object satisfies the given interface */ public static boolean satisfiesInterface(java.lang.Object o, String className){ if(o == null) return false; if(className == null) throw new AssertionException("Type name cannot be null"); // we use a hash set to speed things up for interfaces, to avoid looking at them twice Set<java.lang.Class<?>> alreadyVisited = new HashSet<java.lang.Class<?>>(); return classSatisfiesInterface(o.getClass(), className, alreadyVisited); } private static boolean classSatisfiesInterface(java.lang.Class<?> klass, String className, Set<java.lang.Class<?>> alreadyVisited) { if(klass == null || klass == ceylon.language.Anything.class) return false; if ((className.equals("ceylon.language.Identifiable")) && klass!=java.lang.Object.class //&& klass!=java.lang.String.class && !klass.isAnnotationPresent(Ceylon.class)) { //TODO: this is broken for a Java class that // extends a Ceylon class return true; } // try the interfaces if(lookForInterface(klass, className, alreadyVisited)) return true; // try its superclass return classSatisfiesInterface(getCeylonSuperClass(klass), className, alreadyVisited); } private static boolean lookForInterface(java.lang.Class<?> klass, String className, Set<java.lang.Class<?>> alreadyVisited){ if (klass.getName().equals(className)) return true; // did we already visit this type? if(!alreadyVisited.add(klass)) return false; // first see if it satisfies it directly SatisfiedTypes satisfiesAnnotation = klass.getAnnotation(SatisfiedTypes.class); if (satisfiesAnnotation!=null){ for (String satisfiedType : satisfiesAnnotation.value()){ satisfiedType = declClassName(satisfiedType); int i = satisfiedType.indexOf('<'); if (i>0) { satisfiedType = satisfiedType.substring(0, i); } try { if (lookForInterface( java.lang.Class.forName(satisfiedType, true, klass.getClassLoader()), className, alreadyVisited)) { return true; } } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } }else{ // otherwise look at this class's interfaces for (java.lang.Class<?> intrface : klass.getInterfaces()){ if (lookForInterface(intrface, className, alreadyVisited)) return true; } } // no luck return false; } // Java variadic conversions @SuppressWarnings("unchecked") public static <T> List<T> collectIterable(Iterable<? extends T, ?> sequence) { List<T> list = new LinkedList<T>(); if (sequence != null) { Iterator<? extends T> iterator = sequence.iterator(); Object o; while((o = iterator.next()) != finished_.get_()){ list.add((T)o); } } return list; } @SuppressWarnings("unchecked") public static boolean[] toBooleanArray(ceylon.language.Iterable<? extends ceylon.language.Boolean, ?> sequence, boolean... initialElements){ if(sequence instanceof ceylon.language.List) return toBooleanArray((ceylon.language.List<? extends ceylon.language.Boolean>)sequence, initialElements); List<ceylon.language.Boolean> list = collectIterable(sequence); boolean[] ret = new boolean[list.size() + initialElements.length]; int i=0; for(;i<initialElements.length;i++){ ret[i] = initialElements[i]; } for(ceylon.language.Boolean e : list){ ret[i++] = e.booleanValue(); } return ret; } public static boolean[] toBooleanArray(ceylon.language.List<? extends ceylon.language.Boolean> sequence, boolean... initialElements){ boolean[] ret = new boolean[(int) sequence.getSize() + initialElements.length]; int i=0; for(;i<initialElements.length;i++){ ret[i] = initialElements[i]; } while(!sequence.getEmpty()){ ret[i++] = sequence.getFirst().booleanValue(); sequence = (ceylon.language.List<? extends ceylon.language.Boolean>)sequence.getRest(); } return ret; } @SuppressWarnings("unchecked") public static byte[] toByteArray(ceylon.language.Iterable<? extends ceylon.language.Integer, ?> sequence, long... initialElements){ if(sequence instanceof ceylon.language.List) return toByteArray((ceylon.language.List<? extends ceylon.language.Integer>)sequence, initialElements); List<ceylon.language.Integer> list = collectIterable(sequence); byte[] ret = new byte[initialElements.length + list.size()]; int i=0; for(;i<initialElements.length;i++){ ret[i] = (byte) initialElements[i]; } for(ceylon.language.Integer e : list){ ret[i++] = (byte)e.longValue(); } return ret; } public static byte[] toByteArray(ceylon.language.List<? extends ceylon.language.Integer> sequence, long... initialElements){ byte[] ret = new byte[initialElements.length + (int) sequence.getSize()]; int i=0; for(;i<initialElements.length;i++){ ret[i] = (byte) initialElements[i]; } while(!sequence.getEmpty()){ ret[i++] = (byte) sequence.getFirst().longValue(); sequence = (ceylon.language.List<? extends ceylon.language.Integer>)sequence.getRest(); } return ret; } @SuppressWarnings("unchecked") public static short[] toShortArray(ceylon.language.Iterable<? extends ceylon.language.Integer, ?> sequence, long... initialElements){ if(sequence instanceof ceylon.language.List) return toShortArray((ceylon.language.List<? extends ceylon.language.Integer>)sequence, initialElements); List<ceylon.language.Integer> list = collectIterable(sequence); short[] ret = new short[list.size() + initialElements.length]; int i=0; for(;i<initialElements.length;i++){ ret[i] = (short) initialElements[i]; } for(ceylon.language.Integer e : list){ ret[i++] = (short)e.longValue(); } return ret; } public static short[] toShortArray(ceylon.language.List<? extends ceylon.language.Integer> sequence, long... initialElements){ short[] ret = new short[(int) sequence.getSize() + initialElements.length]; int i=0; for(;i<initialElements.length;i++){ ret[i] = (short) initialElements[i]; } while(!sequence.getEmpty()){ ret[i++] = (short) sequence.getFirst().longValue(); sequence = (ceylon.language.List<? extends ceylon.language.Integer>)sequence.getRest(); } return ret; } @SuppressWarnings("unchecked") public static int[] toIntArray(ceylon.language.Iterable<? extends ceylon.language.Integer, ?> sequence, long... initialElements){ if(sequence instanceof ceylon.language.List) return toIntArray((ceylon.language.List<? extends ceylon.language.Integer>)sequence, initialElements); List<ceylon.language.Integer> list = collectIterable(sequence); int[] ret = new int[list.size() + initialElements.length]; int i=0; for(;i<initialElements.length;i++){ ret[i] = (int) initialElements[i]; } for(ceylon.language.Integer e : list){ ret[i++] = (int)e.longValue(); } return ret; } public static int[] toIntArray(ceylon.language.List<? extends ceylon.language.Integer> sequence, long... initialElements){ int[] ret = new int[(int) sequence.getSize() + initialElements.length]; int i=0; for(;i<initialElements.length;i++){ ret[i] = (int) initialElements[i]; } while(!sequence.getEmpty()){ ret[i++] = (int) sequence.getFirst().longValue(); sequence = (ceylon.language.List<? extends ceylon.language.Integer>)sequence.getRest(); } return ret; } @SuppressWarnings("unchecked") public static long[] toLongArray(ceylon.language.Iterable<? extends ceylon.language.Integer, ?> sequence, long... initialElements){ if(sequence instanceof ceylon.language.List) return toLongArray((ceylon.language.List<? extends ceylon.language.Integer>)sequence, initialElements); List<ceylon.language.Integer> list = collectIterable(sequence); long[] ret = new long[list.size() + initialElements.length]; int i=0; for(;i<initialElements.length;i++){ ret[i] = initialElements[i]; } for(ceylon.language.Integer e : list){ ret[i++] = e.longValue(); } return ret; } public static long[] toLongArray(ceylon.language.List<? extends ceylon.language.Integer> sequence, long... initialElements){ long[] ret = new long[(int) sequence.getSize() + initialElements.length]; int i=0; for(;i<initialElements.length;i++){ ret[i] = initialElements[i]; } while(!sequence.getEmpty()){ ret[i++] = sequence.getFirst().longValue(); sequence = (ceylon.language.List<? extends ceylon.language.Integer>)sequence.getRest(); } return ret; } @SuppressWarnings("unchecked") public static float[] toFloatArray(ceylon.language.Iterable<? extends ceylon.language.Float, ?> sequence, double... initialElements){ if(sequence instanceof ceylon.language.List) return toFloatArray((ceylon.language.List<? extends ceylon.language.Float>)sequence, initialElements); List<ceylon.language.Float> list = collectIterable(sequence); float[] ret = new float[initialElements.length + list.size()]; int i=0; for(;i<initialElements.length;i++){ ret[i] = (float) initialElements[i]; } for(ceylon.language.Float e : list){ ret[i++] = (float)e.doubleValue(); } return ret; } public static float[] toFloatArray(ceylon.language.List<? extends ceylon.language.Float> sequence, double... initialElements){ float[] ret = new float[initialElements.length + (int) sequence.getSize()]; int i = 0; for(;i<initialElements.length;i++){ ret[i] = (float) initialElements[i]; } while(!sequence.getEmpty()){ ret[i++] = (float) sequence.getFirst().doubleValue(); sequence = (ceylon.language.List<? extends ceylon.language.Float>)sequence.getRest(); } return ret; } @SuppressWarnings("unchecked") public static double[] toDoubleArray(ceylon.language.Iterable<? extends ceylon.language.Float, ?> sequence, double... initialElements){ if(sequence instanceof ceylon.language.List) return toDoubleArray((ceylon.language.List<? extends ceylon.language.Float>)sequence, initialElements); List<ceylon.language.Float> list = collectIterable(sequence); double[] ret = new double[list.size() + initialElements.length]; int i=0; for(;i<initialElements.length;i++){ ret[i] = initialElements[i]; } for(ceylon.language.Float e : list){ ret[i++] = e.doubleValue(); } return ret; } public static double[] toDoubleArray(ceylon.language.List<? extends ceylon.language.Float> sequence, double... initialElements){ double[] ret = new double[(int) sequence.getSize() + initialElements.length]; int i=0; for(;i<initialElements.length;i++){ ret[i] = initialElements[i]; } while(!sequence.getEmpty()){ ret[i++] = sequence.getFirst().doubleValue(); sequence = (ceylon.language.List<? extends ceylon.language.Float>)sequence.getRest(); } return ret; } @SuppressWarnings("unchecked") public static char[] toCharArray(ceylon.language.Iterable<? extends ceylon.language.Character, ?> sequence, int... initialElements){ if(sequence instanceof ceylon.language.List) return toCharArray((ceylon.language.List<? extends ceylon.language.Character>)sequence, initialElements); List<ceylon.language.Character> list = collectIterable(sequence); char[] ret = new char[list.size() + initialElements.length]; int i=0; // FIXME: this is invalid and should yield a larger array by splitting chars > 16 bits in two for(;i<initialElements.length;i++){ ret[i] = (char) initialElements[i]; } for(ceylon.language.Character e : list){ ret[i++] = (char)e.intValue(); } return ret; } public static char[] toCharArray(ceylon.language.List<? extends ceylon.language.Character> sequence, int... initialElements){ char[] ret = new char[(int) sequence.getSize() + initialElements.length]; int i=0; // FIXME: this is invalid and should yield a larger array by splitting chars > 16 bits in two for(;i<initialElements.length;i++){ ret[i] = (char) initialElements[i]; } while(!sequence.getEmpty()){ ret[i++] = (char) sequence.getFirst().intValue(); sequence = (ceylon.language.List<? extends ceylon.language.Character>)sequence.getRest(); } return ret; } @SuppressWarnings("unchecked") public static int[] toCodepointArray(ceylon.language.Iterable<? extends ceylon.language.Character, ?> sequence, int... initialElements){ if(sequence instanceof ceylon.language.List) return toCodepointArray((ceylon.language.List<? extends ceylon.language.Character>)sequence, initialElements); List<ceylon.language.Character> list = collectIterable(sequence); int[] ret = new int[list.size() + initialElements.length]; int i=0; for(;i<initialElements.length;i++){ ret[i] = initialElements[i]; } for(ceylon.language.Character e : list){ ret[i++] = e.intValue(); } return ret; } public static int[] toCodepointArray(ceylon.language.List<? extends ceylon.language.Character> sequence, int... initialElements){ int[] ret = new int[(int) sequence.getSize() + initialElements.length]; int i=0; for(;i<initialElements.length;i++){ ret[i] = initialElements[i]; } while(!sequence.getEmpty()){ ret[i++] = sequence.getFirst().intValue(); sequence = (ceylon.language.List<? extends ceylon.language.Character>)sequence.getRest(); } return ret; } @SuppressWarnings("unchecked") public static java.lang.String[] toJavaStringArray(ceylon.language.Iterable<? extends ceylon.language.String, ?> sequence, java.lang.String... initialElements){ if(sequence instanceof ceylon.language.List) return toJavaStringArray((ceylon.language.List<? extends ceylon.language.String>)sequence, initialElements); List<ceylon.language.String> list = collectIterable(sequence); java.lang.String[] ret = new java.lang.String[list.size() + initialElements.length]; int i=0; for(;i<initialElements.length;i++){ ret[i] = initialElements[i]; } for(ceylon.language.String e : list){ ret[i++] = e.toString(); } return ret; } public static java.lang.String[] toJavaStringArray(ceylon.language.List<? extends ceylon.language.String> sequence, java.lang.String... initialElements){ java.lang.String[] ret = new java.lang.String[(int) sequence.getSize() + initialElements.length]; int i=0; for(;i<initialElements.length;i++){ ret[i] = initialElements[i]; } while(!sequence.getEmpty()){ ret[i++] = sequence.getFirst().toString(); sequence = (ceylon.language.List<? extends ceylon.language.String>)sequence.getRest(); } return ret; } @SuppressWarnings("unchecked") public static <T> T[] toArray(ceylon.language.List<? extends T> sequence, T[] ret, T... initialElements){ System.arraycopy(initialElements, 0, ret, 0, initialElements.length); int i=initialElements.length; while(!sequence.getEmpty()){ ret[i++] = sequence.getFirst(); sequence = (ceylon.language.List<? extends T>)sequence.getRest(); } return ret; } @SuppressWarnings("unchecked") public static <T> T[] toArray(ceylon.language.List<? extends T> sequence, java.lang.Class<T> klass, T... initialElements){ T[] ret = (T[]) java.lang.reflect.Array.newInstance(klass, (int)sequence.getSize() + initialElements.length); System.arraycopy(initialElements, 0, ret, 0, initialElements.length); int i=initialElements.length; while(!sequence.getEmpty()){ ret[i++] = sequence.getFirst(); sequence = (ceylon.language.List<? extends T>)sequence.getRest(); } return ret; } @SuppressWarnings("unchecked") public static <T> T[] toArray(ceylon.language.Iterable<? extends T, ?> iterable, java.lang.Class<T> klass, T... initialElements){ List<T> list = collectIterable(iterable); T[] ret = (T[]) java.lang.reflect.Array.newInstance(klass, list.size() + initialElements.length); // fast path if(initialElements.length == 0){ // fast copy of list list.toArray(ret); }else{ // fast copy of initialElements System.arraycopy(initialElements, 0, ret, 0, initialElements.length); // slow iteration for list :( int i = initialElements.length; for(T o : list) ret[i++] = o; } return ret; } public static <T> T checkNull(T t) { if(t == null) throw new AssertionException("null value returned from native call not assignable to Object"); return t; } /** * Return {@link empty_#getEmpty$ empty} or an {@link ArraySequence} * wrapping the given elements, depending on whether the given array is * empty * @param elements The elements * @return A Sequential */ @SuppressWarnings({"unchecked","rawtypes"}) public static <T> Sequential<T> sequentialInstance(TypeDescriptor $reifiedT, T[] elements) { if (elements.length == 0) { return (Sequential)empty_.get_(); } // Annoyingly this implies an extra copy return ArraySequence.<T>instance($reifiedT, elements); } @SuppressWarnings({"unchecked","rawtypes"}) public static Sequential<? extends ceylon.language.String> sequentialInstanceBoxed(java.lang.String[] elements) { if (elements.length == 0){ return (Sequential)empty_.get_(); } int total = elements.length; java.lang.Object[] newArray = new java.lang.Object[total]; int i = 0; for(java.lang.String element : elements){ newArray[i++] = ceylon.language.String.instance(element); } // TODO Annoyingly this results in an extra copy return ArraySequence.instance(ceylon.language.String.$TypeDescriptor$, newArray); } @SuppressWarnings({"unchecked","rawtypes"}) public static Sequential<? extends ceylon.language.Integer> sequentialInstanceBoxed(long[] elements) { if (elements.length == 0){ return (Sequential)empty_.get_(); } int total = elements.length; java.lang.Object[] newArray = new java.lang.Object[total]; int i = 0; for(long element : elements){ newArray[i++] = ceylon.language.Integer.instance(element); } // TODO Annoyingly this results in an extra copy return ArraySequence.instance(ceylon.language.Integer.$TypeDescriptor$, newArray); } @SuppressWarnings({"unchecked","rawtypes"}) public static Sequential<? extends ceylon.language.Character> sequentialInstanceBoxed(int[] elements) { if (elements.length == 0){ return (Sequential)empty_.get_(); } int total = elements.length; java.lang.Object[] newArray = new java.lang.Object[total]; int i = 0; for(int element : elements){ newArray[i++] = ceylon.language.Character.instance(element); } // TODO Annoyingly this results in an extra copy return ArraySequence.instance(ceylon.language.Character.$TypeDescriptor$, newArray); } @SuppressWarnings({"unchecked","rawtypes"}) public static Sequential<? extends ceylon.language.Boolean> sequentialInstanceBoxed(boolean[] elements) { if (elements.length == 0){ return (Sequential)empty_.get_(); } int total = elements.length; java.lang.Object[] newArray = new java.lang.Object[total]; int i = 0; for(boolean element : elements){ newArray[i++] = ceylon.language.Boolean.instance(element); } // TODO Annoyingly this results in an extra copy return ArraySequence.instance(ceylon.language.Boolean.$TypeDescriptor$, newArray); } @SuppressWarnings({"unchecked","rawtypes"}) public static Sequential<? extends ceylon.language.Float> sequentialInstanceBoxed(double[] elements) { if (elements.length == 0){ return (Sequential)empty_.get_(); } int total = elements.length; java.lang.Object[] newArray = new java.lang.Object[total]; int i = 0; for(double element : elements){ newArray[i++] = ceylon.language.Float.instance(element); } // TODO Annoyingly this results in an extra copy return ArraySequence.instance(ceylon.language.Float.$TypeDescriptor$, newArray); } /** * Return {@link empty_#getEmpty$ empty} or an {@link ArraySequence} * wrapping the given elements, depending on whether the given array * and varargs are empty * @param rest The elements at the end of the sequence * @param elements the elements at the start of the sequence * @return A Sequential */ @SuppressWarnings({"unchecked"}) public static <T> Sequential<? extends T> sequentialInstance(TypeDescriptor $reifiedT, Sequential<? extends T> rest, T... elements) { return sequentialInstance($reifiedT, 0, elements.length, elements, true, rest); } /** * Returns a Sequential made by concatenating the {@code length} elements * of {@code elements} starting from {@code state} with the elements of * {@code rest}: <code> {*elements[start:length], *rest}</code>. * * <strong>This method does not copy {@code elements} unless it has to</strong> */ @SuppressWarnings("unchecked") public static <T> Sequential<? extends T> sequentialInstance( TypeDescriptor $reifiedT, int start, int length, T[] elements, boolean copy, Sequential<? extends T> rest) { if (length == 0){ if(rest.getEmpty()) { return (Sequential<T>)empty_.get_(); } return rest; } // elements is not empty if(rest.getEmpty()) { return new ArraySequence<T>($reifiedT, elements, start, length, copy); } // we have both, let's find the total size int total = (int) (rest.getSize() + length); java.lang.Object[] newArray = new java.lang.Object[total]; System.arraycopy(elements, start, newArray, 0, length); Iterator<? extends T> iterator = rest.iterator(); int i = length; for(Object elem; (elem = iterator.next()) != finished_.get_(); i++){ newArray[i] = elem; } return ArraySequence.<T>instance($reifiedT, newArray); } /** * Method for instantiating a Range (or Empty) from a Tree.SpreadOp, * {@code start:length}. * @param start The start * @param length The size of the Range to create * @return A range */ @SuppressWarnings({"unchecked","rawtypes"}) public static <T extends ceylon.language.Ordinal<? extends T>> Sequential<T> spreadOp(TypeDescriptor $reifiedT, T start, long length) { if (length <= 0) { return (Sequential)empty_.get_(); } if (start instanceof ceylon.language.Integer) { ceylon.language.Integer startInt = (ceylon.language.Integer)start; return new ceylon.language.Range($reifiedT, startInt, ceylon.language.Integer.instance(startInt.longValue() + (length - 1))); } else if (start instanceof ceylon.language.Character) { ceylon.language.Character startChar = (ceylon.language.Character)start; return new ceylon.language.Range($reifiedT, startChar, ceylon.language.Character.instance((int)(startChar.intValue() + length - 1))); } else { T end = start; long ii = 0L; while (++ii < length) { end = end.getSuccessor(); } return new ceylon.language.Range($reifiedT, start, end); } } /** * Returns a runtime exception. To be used by implementors * of mixin methods used to access super-interfaces $impl fields * for final classes that don't and will never need them */ public static RuntimeException makeUnimplementedMixinAccessException() { return new RuntimeException("Internal error: should never be called"); } /** * Specialised version of Tuple.spanFrom for when the * typechecker determines that it can do better than the * generic one that returns a Sequential. Here we return * a Tuple, although our type signature hides this. */ public static Sequential<?> tuple_spanFrom(Ranged tuple, ceylon.language.Integer index){ Sequential<?> seq = (Sequential<?>)tuple; long i = index.longValue(); while(i seq = seq.getRest(); } return seq; } public static boolean[] fillArray(boolean[] array, boolean val){ Arrays.fill(array, val); return array; } public static byte[] fillArray(byte[] array, byte val){ Arrays.fill(array, val); return array; } public static short[] fillArray(short[] array, short val){ Arrays.fill(array, val); return array; } public static int[] fillArray(int[] array, int val){ Arrays.fill(array, val); return array; } public static long[] fillArray(long[] array, long val){ Arrays.fill(array, val); return array; } public static float[] fillArray(float[] array, float val){ Arrays.fill(array, val); return array; } public static double[] fillArray(double[] array, double val){ Arrays.fill(array, val); return array; } public static char[] fillArray(char[] array, char val){ Arrays.fill(array, val); return array; } public static <T> T[] fillArray(T[] array, T val){ Arrays.fill(array, val); return array; } @SuppressWarnings("unchecked") public static <T> T[] makeArray(TypeDescriptor $reifiedElement, int size){ return (T[]) java.lang.reflect.Array.newInstance($reifiedElement.getArrayElementClass(), size); } @SuppressWarnings("unchecked") public static <T> T[] makeArray(TypeDescriptor $reifiedElement, int... dimensions){ return (T[]) java.lang.reflect.Array.newInstance($reifiedElement.getArrayElementClass(), dimensions); } /** * Returns a runtime exception. To be used by implementors * of Java array methods used to make sure they are never * called */ public static RuntimeException makeJavaArrayWrapperException() { return new RuntimeException("Internal error: should never be called"); } /** * Throws an exception without having to declare it. This * uses a Ceylon helper that does this because Ceylon does * not have checked exceptions. This is merely to avoid a * javac check wrt. checked exceptions. * Stef tried using Unsafe.throwException() but * Unsafe.getUnsafe() throws if we have a ClassLoader, and * the only other way is using reflection to get to it, * which starts to smell real bad when we can just use a * Ceylon helper. */ public static void rethrow(final Throwable t){ ceylon.language.impl.rethrow_.rethrow(t); } /** * Null-safe equals. */ public static boolean eq(Object a, Object b) { if(a == null) return b == null; if(b == null) return false; return a.equals(b); } /** * Applies the given function to the given arguments. The * argument types are assumed to be correct and will not * be checked. This method will properly deal with variadic * functions. The arguments are expected to be spread in the * given sequential, even in the case of variadic functions, * which means that there will be no spreading of any * Sequential instance in the given arguments. On the * contrary, a portion of the given arguments may be packaged * into a Sequential if the given function is variadic. * * @param function the function to apply * @param arguments the argument values to pass to the function * @return the function's return value */ public static <Return> Return apply(Callable<? extends Return> function, Sequential<? extends Object> arguments){ int variadicParameterIndex = function.$getVariadicParameterIndex$(); switch ((int) arguments.getSize()) { case 0: // even if the function is variadic it will overload $call so we're good return function.$call$(); case 1: // if the first param is variadic, just pass the sequence along if(variadicParameterIndex == 0) return function.$callvariadic$(arguments); return function.$call$(arguments.get(Integer.instance(0))); case 2: switch(variadicParameterIndex){ // pass the sequence along case 0: return function.$callvariadic$(arguments); // extract the first, pass the rest case 1: return function.$callvariadic$(arguments.get(Integer.instance(0)), (Sequential<?>)arguments.spanFrom(Integer.instance(1))); // no variadic param, or after we run out of elements to pass default: return function.$call$(arguments.get(Integer.instance(0)), arguments.get(Integer.instance(1))); } case 3: switch(variadicParameterIndex){ // pass the sequence along case 0: return function.$callvariadic$(arguments); // extract the first, pass the rest case 1: return function.$callvariadic$(arguments.get(Integer.instance(0)), (Sequential<?>)arguments.spanFrom(Integer.instance(1))); // extract the first and second, pass the rest case 2: return function.$callvariadic$(arguments.get(Integer.instance(0)), arguments.get(Integer.instance(1)), (Sequential<?>)arguments.spanFrom(Integer.instance(2))); // no variadic param, or after we run out of elements to pass default: return function.$call$(arguments.get(Integer.instance(0)), arguments.get(Integer.instance(1)), arguments.get(Integer.instance(2))); } default: switch(variadicParameterIndex){ // pass the sequence along case 0: return function.$callvariadic$(arguments); // extract the first, pass the rest case 1: return function.$callvariadic$(arguments.get(Integer.instance(0)), (Sequential<?>)arguments.spanFrom(Integer.instance(1))); // extract the first and second, pass the rest case 2: return function.$callvariadic$(arguments.get(Integer.instance(0)), arguments.get(Integer.instance(1)), (Sequential<?>)arguments.spanFrom(Integer.instance(2))); case 3: return function.$callvariadic$(arguments.get(Integer.instance(0)), arguments.get(Integer.instance(1)), arguments.get(Integer.instance(2)), (Sequential<?>)arguments.spanFrom(Integer.instance(3))); // no variadic param case -1: java.lang.Object[] args = Util.toArray(arguments, new java.lang.Object[(int) arguments.getSize()]); return function.$call$(args); // we have a variadic param in there bothering us default: // we stuff everything before the variadic into an array int beforeVariadic = (int)Math.min(arguments.getSize(), variadicParameterIndex); boolean needsVariadic = beforeVariadic < arguments.getSize(); args = new java.lang.Object[beforeVariadic + (needsVariadic ? 1 : 0)]; Iterator<?> iterator = arguments.iterator(); java.lang.Object it; int i=0; while(i < beforeVariadic && (it = iterator.next()) != finished_.get_()){ args[i++] = it; } // add the remainder as a variadic arg if required if(needsVariadic){ args[i] = arguments.spanFrom(Integer.instance(beforeVariadic)); return function.$callvariadic$(args); } return function.$call$(args); } } } @SuppressWarnings("unchecked") public static <T> java.lang.Class<T> getJavaClassForDescriptor(TypeDescriptor descriptor) { if(descriptor == TypeDescriptor.NothingType || descriptor == ceylon.language.Object.$TypeDescriptor$ || descriptor == ceylon.language.Anything.$TypeDescriptor$ || descriptor == ceylon.language.Basic.$TypeDescriptor$ || descriptor == ceylon.language.Null.$TypeDescriptor$ || descriptor == ceylon.language.Identifiable.$TypeDescriptor$) return (java.lang.Class<T>) Object.class; if(descriptor instanceof TypeDescriptor.Class) return (java.lang.Class<T>) ((TypeDescriptor.Class) descriptor).getKlass(); if(descriptor instanceof TypeDescriptor.Member) return getJavaClassForDescriptor(((TypeDescriptor.Member) descriptor).getMember()); if(descriptor instanceof TypeDescriptor.Intersection) return (java.lang.Class<T>) Object.class; if(descriptor instanceof TypeDescriptor.Union){ TypeDescriptor.Union union = (TypeDescriptor.Union) descriptor; TypeDescriptor[] members = union.getMembers(); // special case for optional types if(members.length == 2){ if(members[0] == ceylon.language.Null.$TypeDescriptor$) return getJavaClassForDescriptor(members[1]); if(members[1] == ceylon.language.Null.$TypeDescriptor$) return getJavaClassForDescriptor(members[0]); } return (java.lang.Class<T>) Object.class; } return (java.lang.Class<T>) Object.class; } public static int arrayLength(Object o) { if (o instanceof Object[]) return ((Object[])o).length; else if (o instanceof boolean[]) return ((boolean[])o).length; else if (o instanceof float[]) return ((float[])o).length; else if (o instanceof double[]) return ((double[])o).length; else if (o instanceof char[]) return ((char[])o).length; else if (o instanceof byte[]) return ((byte[])o).length; else if (o instanceof short[]) return ((short[])o).length; else if (o instanceof int[]) return ((int[])o).length; else if (o instanceof long[]) return ((long[])o).length; throw new ClassCastException(notArrayType(o)); } /** * Used by the JVM backend to get unboxed items from an Array&lt;Integer> backing array */ public static long getIntegerArray(Object o, int index) { if (o instanceof byte[]) return ((byte[])o)[index]; else if (o instanceof short[]) return ((short[])o)[index]; else if (o instanceof int[]) return ((int[])o)[index]; else if (o instanceof long[]) return ((long[])o)[index]; throw new ClassCastException(notArrayType(o)); } /** * Used by the JVM backend to get unboxed items from an Array&lt;Float> backing array */ public static double getFloatArray(Object o, int index) { if (o instanceof float[]) return ((float[])o)[index]; else if (o instanceof double[]) return ((double[])o)[index]; throw new ClassCastException(notArrayType(o)); } /** * Used by the JVM backend to get unboxed items from an Array&lt;Character> backing array */ public static int getCharacterArray(Object o, int index) { if (o instanceof int[]) return ((int[])o)[index]; throw new ClassCastException(notArrayType(o)); } /** * Used by the JVM backend to get unboxed items from an Array&lt;Boolean> backing array */ public static boolean getBooleanArray(Object o, int index) { if (o instanceof boolean[]) return ((boolean[])o)[index]; throw new ClassCastException(notArrayType(o)); } /** * Used by the JVM backend to get items from an ArraySequence object. Beware: do not use that * for Array&lt;Object> as there's too much magic in there. */ public static Object getObjectArray(Object o, int index) { if (o instanceof Object[]) return ((Object[])o)[index]; else if (o instanceof boolean[]) return ceylon.language.Boolean.instance(((boolean[])o)[index]); else if (o instanceof float[]) return ceylon.language.Float.instance(((float[])o)[index]); else if (o instanceof double[]) return ceylon.language.Float.instance(((double[])o)[index]); else if (o instanceof char[]) return ceylon.language.Character.instance(((char[])o)[index]); else if (o instanceof byte[]) return ceylon.language.Integer.instance(((byte[])o)[index]); else if (o instanceof short[]) return ceylon.language.Integer.instance(((short[])o)[index]); else if (o instanceof int[]) return ceylon.language.Integer.instance(((int[])o)[index]); else if (o instanceof long[]) return ceylon.language.Integer.instance(((long[])o)[index]); throw new ClassCastException(notArrayType(o)); } private static String notArrayType(Object o) { return (o == null ? "null" : o.getClass().getName()) + " is not an array type"; } }
package ninja; import sirius.kernel.cache.Cache; import sirius.kernel.cache.CacheManager; import sirius.kernel.commons.Limit; import sirius.kernel.commons.Strings; import sirius.kernel.health.Exceptions; import sirius.kernel.xml.Attribute; import sirius.kernel.xml.XMLStructuredOutput; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Represents a bucket. * <p> * Internally a bucket is just a directory within the base directory. */ public class Bucket { private static final Pattern BUCKET_NAME_PATTERN = Pattern.compile("^[a-z\\d][a-z\\d\\-.]{1,61}[a-z\\d]$"); /** * Matches IPv4 addresses roughly. */ private static final Pattern IP_ADDRESS_PATTERN = Pattern.compile("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$"); private static final int MOST_RECENT_VERSION = 2; private final File folder; private final File versionMarker; private final File publicMarker; private static final Cache<String, Boolean> publicAccessCache = CacheManager.createLocalCache("public-bucket-access"); /** * Creates a new bucket based on the given directory. * * @param folder the directory which stores the contents of the bucket. */ public Bucket(File folder) { this.folder = folder; // set the public marker file this.publicMarker = new File(folder, "$public"); // as last step, check the version, and migrate the bucket if necessary this.versionMarker = new File(folder, "$version"); int version = getVersion(); if (version < MOST_RECENT_VERSION) { migrateBucket(version); } } /** * Returns the name of the bucket. * * @return the name of the bucket */ public String getName() { return folder.getName(); } /** * Returns the encoded name of the bucket. * * @return the encoded name of the bucket */ public String getEncodedName() { return Strings.urlEncode(getName()); } /** * Returns the underlying directory as {@link File}. * * @return a {@link File} representing the underlying directory */ public File getFolder() { return folder; } /** * Determines if the bucket exists. * * @return <b>true</b> if the bucket exists, <b>false</b> else */ public boolean exists() { return folder.exists(); } /** * Creates the bucket. * <p> * If the underlying directory already exists, nothing happens. * * @return <b>true</b> if the folder for the bucket was created successfully and if it was missing before */ public boolean create() { if (folder.exists() || !folder.mkdirs()) { return false; } // having successfully created the folder, write the version marker setVersion(MOST_RECENT_VERSION); return true; } /** * Deletes the bucket and all of its contents. * * @return true if all files of the bucket and the bucket itself was deleted successfully, false otherwise. */ public boolean delete() { if (!folder.exists()) { return true; } boolean deleted = false; for (File child : Objects.requireNonNull(folder.listFiles())) { deleted = child.delete() || deleted; } deleted = folder.delete() || deleted; return deleted; } /** * Returns a list of at most the provided number of stored objects * * @param output the xml structured output the list of objects should be written to * @param limit controls the maximum number of objects returned * @param marker the key to start with when listing objects in a bucket * @param prefix limits the response to keys that begin with the specified prefix */ public void outputObjects(XMLStructuredOutput output, int limit, @Nullable String marker, @Nullable String prefix) { ListFileTreeVisitor visitor = new ListFileTreeVisitor(output, limit, marker, prefix); output.beginOutput("ListBucketResult", Attribute.set("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/")); output.property("Name", getName()); output.property("MaxKeys", limit); output.property("Marker", marker); output.property("Prefix", prefix); try { walkFileTreeOurWay(folder.toPath(), visitor); } catch (IOException e) { Exceptions.handle(e); } output.property("IsTruncated", limit > 0 && visitor.getCount() > limit); output.endOutput(); } /** * Very simplified stand-in for {@link Files#walkFileTree(Path, FileVisitor)} where we control the traversal order. * * @param path the start path. * @param visitor the visitor processing the files. * @throws IOException forwarded from nested I/O operations. */ private static void walkFileTreeOurWay(Path path, FileVisitor<? super Path> visitor) throws IOException { if (!path.toFile().isDirectory()) { throw new IOException("Directory expected."); } try (Stream<Path> children = Files.list(path)) { children.sorted(Bucket::compareUtf8Binary) .filter(p -> p.toFile().isFile()) .forEach(p -> { try { BasicFileAttributes attrs = Files.readAttributes(p, BasicFileAttributes.class); visitor.visitFile(p, attrs); } catch (IOException e) { Exceptions.handle(e); } }); } } private static int compareUtf8Binary(Path p1, Path p2) { String s1 = p1.getFileName().toString(); String s2 = p2.getFileName().toString(); byte[] b1 = s1.getBytes(StandardCharsets.UTF_8); byte[] b2 = s2.getBytes(StandardCharsets.UTF_8); // unless we upgrade to java 9+ offering Arrays.compare(...), we need to compare the arrays manually :( int length = Math.min(b1.length, b2.length); for (int i = 0; i < length; ++i) { if (b1[i] != b2[i]) { return Byte.compare(b1[i], b2[i]); } } return b1.length - b2.length; } /** * Determines if the bucket is only privately accessible, i.e. non-public. * * @return <b>true</b> if the bucket is only privately accessible, <b>false</b> else */ public boolean isPrivate() { return !Boolean.TRUE.equals(publicAccessCache.get(getName(), key -> publicMarker.exists())); } /** * Marks the bucket as only privately accessible, i.e. non-public. */ public void makePrivate() { if (publicMarker.exists()) { if (publicMarker.delete()) { publicAccessCache.put(getName(), false); } else { Storage.LOG.WARN("Failed to delete public marker for bucket %s - it remains public!", getName()); } } } /** * Marks the bucket as publicly accessible. */ public void makePublic() { if (!publicMarker.exists()) { try { new FileOutputStream(publicMarker).close(); } catch (IOException e) { throw Exceptions.handle(Storage.LOG, e); } } publicAccessCache.put(getName(), true); } /** * Returns the object with the given key. * <p> * The method never returns <b>null</b>, but {@link StoredObject#exists()} may return <b>false</b>. * <p> * Make sure that the key passes {@link StoredObject#isValidKey(String)} by meeting the naming restrictions * documented there. * * @param key the key of the requested object * @return the object with the given key */ @Nonnull public StoredObject getObject(String key) { if (!StoredObject.isValidKey(key)) { throw Exceptions.createHandled() .withSystemErrorMessage( "Object key \"%s\" does not adhere to the rules. [https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html]", key) .handle(); } return new StoredObject(new File(folder, key)); } /** * Returns a number of files meeting the given query, within the given indexing limits. Leave the query empty to * get all files. * * @param query the query to filter for * @param limit the limit to apply * @return all files meeting the query, restricted by the limit */ public List<StoredObject> getObjects(@Nullable String query, Limit limit) { try (Stream<Path> stream = Files.list(folder.toPath())) { return stream.sorted(Bucket::compareUtf8Binary) .map(Path::toFile) .filter(currentFile -> isMatchingObject(query, currentFile)) .filter(limit.asPredicate()) .map(StoredObject::new) .collect(Collectors.toList()); } catch (IOException e) { throw Exceptions.handle(e); } } /** * Count the files containing the query. Leave the query empty to count all files. * * @param query the query to filter for * @return the number of files in the bucket matching the query */ public int countObjects(@Nullable String query) { try (Stream<Path> stream = Files.list(folder.toPath())) { return Math.toIntExact(stream.map(Path::toFile) .filter(currentFile -> isMatchingObject(query, currentFile)) .count()); } catch (IOException e) { throw Exceptions.handle(e); } } private boolean isMatchingObject(@Nullable String query, File currentFile) { return (Strings.isEmpty(query) || currentFile.getName().contains(query)) && currentFile.isFile() && !currentFile .getName() .startsWith("$"); } private int getVersion() { // non-existent buckets always have the most recent version if (!exists()) { return MOST_RECENT_VERSION; } // return the minimal version if the bucket exists, but without a version marker if (!versionMarker.exists()) { return 1; } try { // parse the version from the version marker file return Integer.parseInt(Strings.join(Files.readAllLines(versionMarker.toPath()), "\n").trim()); } catch (IOException e) { throw Exceptions.handle(Storage.LOG, e); } } private void setVersion(int version) { // non-existent buckets always have the most recent version if (!exists()) { return; } try { // write the version into the version marker file Files.write(versionMarker.toPath(), Collections.singletonList(String.valueOf(version))); } catch (IOException e) { throw Exceptions.handle(Storage.LOG, e); } } /** * Migrates a bucket folder to the most recent version. * * @param fromVersion the version to migrate from. */ private void migrateBucket(int fromVersion) { if (fromVersion <= 1) { migratePublicMarkerVersion1To2(); for (File object : Objects.requireNonNull(folder.listFiles(this::filterObjects))) { migrateObjectVersion1To2(object); } } // further incremental updates go here one day // write the most recent version marker setVersion(MOST_RECENT_VERSION); } private boolean filterObjects(File file) { // ignore directories if (file.isDirectory()) { return false; } // ignore legacy system files if (file.getName().startsWith("__ninja_")) { return false; } // ignore marker files if (file.equals(publicMarker) || file.equals(versionMarker)) { return false; } // ignore properties files return !(file.getName().startsWith("$") && file.getName().endsWith(".properties")); } /** * Migrates a version 1 public marker file to version 2. */ private void migratePublicMarkerVersion1To2() { try { File legacyPublicMarker = new File(folder, "__ninja_public"); if (legacyPublicMarker.exists() && !publicMarker.exists()) { Files.move(legacyPublicMarker.toPath(), publicMarker.toPath()); } else if (legacyPublicMarker.exists()) { Files.delete(legacyPublicMarker.toPath()); } } catch (IOException e) { throw Exceptions.handle(Storage.LOG, e); } } private void migrateObjectVersion1To2(File legacyChild) { File legacyProperties = new File(folder, "__ninja_" + legacyChild.getName() + ".properties"); try { File child = new File(folder, StoredObject.encodeKey(legacyChild.getName())); File properties = new File(folder, "$" + child.getName() + ".properties"); if (!child.exists()) { Files.move(legacyChild.toPath(), child.toPath()); } else if (!child.equals(legacyChild)) { Files.delete(legacyChild.toPath()); } if (legacyProperties.exists()) { if (!properties.exists()) { Files.move(legacyProperties.toPath(), properties.toPath()); } else if (!properties.equals(legacyProperties)) { Files.delete(legacyProperties.toPath()); } } } catch (Exception e) { throw Exceptions.handle(Storage.LOG, e); } } public static boolean isValidName(@Nullable String name) { if (name == null || Strings.isEmpty(name.trim())) { return false; } // test the majority of simple requirements via a regex if (!BUCKET_NAME_PATTERN.matcher(name).matches()) { return false; } // make sure that it does not start with "xn--" if (name.startsWith("xn return false; } try { // make sure that the name is no valid IP address (the null check is pointless, it is just there to trigger // actual conversion after the regex has matched; if the parsing fails, we end up in the catch clause) if (IP_ADDRESS_PATTERN.matcher(name).matches() && InetAddress.getByName(name) != null) { return false; } } catch (Exception e) { // ignore this, we want the conversion to fail and thus to end up here } // reaching this point, the name is valid return true; } }
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.sitenv.contentvalidator.service.ContentValidatorService; import org.sitenv.referenceccda.dto.ValidationResultsDto; import org.sitenv.referenceccda.dto.ValidationResultsMetaData; import org.sitenv.referenceccda.services.ReferenceCCDAValidationService; import org.sitenv.referenceccda.validators.RefCCDAValidationResult; import org.sitenv.referenceccda.validators.content.ReferenceContentValidator; import org.sitenv.referenceccda.validators.enums.UsrhSubType; import org.sitenv.referenceccda.validators.enums.ValidationResultType; import org.sitenv.referenceccda.validators.schema.CCDATypes; import org.sitenv.referenceccda.validators.schema.ReferenceCCDAValidator; import org.sitenv.referenceccda.validators.schema.ValidationObjectives; import org.sitenv.referenceccda.validators.vocabulary.VocabularyCCDAValidator; import org.sitenv.vocabularies.validation.services.VocabularyValidationService; import org.springframework.mock.web.MockMultipartFile; import org.springframework.web.multipart.MultipartFile; import org.xml.sax.SAXException; public class RefCCDATest { private static final boolean LOG_RESULTS_TO_CONSOLE = false; private static final boolean SHOW_ERRORS_ONLY = false; private static final int HAS_SCHEMA_ERROR_INDEX = 1, LAST_SCHEMA_TEST_AND_NO_SCHEMA_ERROR_INDEX = 2, INVALID_SNIPPET_ONLY_INDEX = 3, NON_CCDA_XML_HTML_FILE_WITH_XML_EXTENSION_INDEX = 4, BLANK_EMPTY_DOCUMENT_INDEX = 5, HAS_4_POSSIBLE_CONSOL_AND_1_POSSIBLE_MU2_ERROR = 6, DS4P_FROM_MDHT = 7, DS4P_AMB_1 = 8, DS4P_INP_1 = 9, CCD_R21 = 10, DS4P_WITH_NO_DS4P_DATA = 11; // feel free to add docs to the end but don't alter existing data // - the same sample is referenced twice due to a loop test private static URI[] CCDA_FILES = new URI[0]; static { try { CCDA_FILES = new URI[] { RefCCDATest.class.getResource("/Sample.xml").toURI(), RefCCDATest.class.getResource("/Sample_addSchemaErrors.xml").toURI(), RefCCDATest.class.getResource("/Sample.xml").toURI(), RefCCDATest.class.getResource("/Sample_invalid-SnippetOnly.xml").toURI(), RefCCDATest.class.getResource("/Sample_basicHTML.xml").toURI(), RefCCDATest.class.getResource("/Sample_blank_Empty_Document.xml").toURI(), RefCCDATest.class.getResource("/Sample_CCDA_CCD_b1_Ambulatory_v2.xml").toURI(), RefCCDATest.class.getResource("/Sample_DS4P_MDHTGen.xml").toURI(), RefCCDATest.class.getResource("/170.315_b8_ds4p_amb_sample1_v4.xml").toURI(), RefCCDATest.class.getResource("/170.315_b8_ds4p_inp_sample1_v4.xml").toURI(), RefCCDATest.class.getResource("/170.315_b1_toc_amb_ccd_r21_sample1_v8.xml").toURI(), RefCCDATest.class.getResource("/170.315_b8_ds4p_amb_sample2_v2.xml").toURI() }; } catch (URISyntaxException e) { if(LOG_RESULTS_TO_CONSOLE) e.printStackTrace(); } } @Test public void stringConversionAndResultsSizeTest() { String ccdaFileAsString = convertCCDAFileToString(CCDA_FILES[LAST_SCHEMA_TEST_AND_NO_SCHEMA_ERROR_INDEX]); println("ccdaFileAsString: " + ccdaFileAsString); assertFalse( "The C-CDA file String conversion failed as no data was captured", ccdaFileAsString.isEmpty()); ArrayList<RefCCDAValidationResult> results = validateDocumentAndReturnResults(ccdaFileAsString); ; println("No of Entries = " + results.size()); assertFalse("No results were returned", results.isEmpty()); println("***************** No Exceptions were thrown during the test******************" + System.lineSeparator() + System.lineSeparator()); } @Test public void hasSchemaErrorsAndDatatypeSchemaErrorTest() { ArrayList<RefCCDAValidationResult> results = validateDocumentAndReturnResults(convertCCDAFileToString(CCDA_FILES[HAS_SCHEMA_ERROR_INDEX])); println("global result"); assertTrue( "The document has a schema error yet the flag is set to false", mdhtResultsHaveSchemaError(results)); println("and for sanity, check the single results as well"); printResults(getMDHTErrorsFromResults(results)); boolean schemaErrorInSingleResultFound = false, expectedDataTypeSchemaErrorInResultsFound = false; String expectedDatatypeSchemaErrorPrefix = "The feature 'author' of"; for (RefCCDAValidationResult result : results) { if (result.isSchemaError()) { schemaErrorInSingleResultFound = true; final String msgPrefix = "A schema error cannot also be an "; assertFalse(msgPrefix + "IG Issue", result.isIGIssue()); assertFalse(msgPrefix + "MU2 Issue", result.isMUIssue()); } if(result.getDescription().contains( expectedDatatypeSchemaErrorPrefix)) { expectedDataTypeSchemaErrorInResultsFound = true; } } assertTrue("The document has at least one schema error but no single result flagged it as such", schemaErrorInSingleResultFound); assertTrue("The document is expected to return has the following specific data type schema error (prefix) :" + expectedDatatypeSchemaErrorPrefix, expectedDataTypeSchemaErrorInResultsFound); } @Test public void doesNotHaveSchemaErrorTest() { ArrayList<RefCCDAValidationResult> results = validateDocumentAndReturnResults(convertCCDAFileToString(CCDA_FILES[LAST_SCHEMA_TEST_AND_NO_SCHEMA_ERROR_INDEX])); println("global result"); assertFalse( "The document does not have schema error yet the flag is set to true", mdhtResultsHaveSchemaError(results)); println("and for sanity, check the single results as well"); boolean schemaErrorInSingleResultFound = false; printResults(getMDHTErrorsFromResults(results)); for (RefCCDAValidationResult result : results) if (result.isSchemaError()) schemaErrorInSingleResultFound = true; assertFalse( "The document has no single schema error yet a single result flagged it as true", schemaErrorInSingleResultFound); } @Test public void multipleDocumentsWithAndWithoutSchemaErrorTest() { for (int curCCDAFileIndex = 0; curCCDAFileIndex < LAST_SCHEMA_TEST_AND_NO_SCHEMA_ERROR_INDEX + 1; curCCDAFileIndex++) { println("***************** Running multipleDocumentsWithAndWithoutSchemaErrorTest test + (curCCDAFileIndex + 1) + " ******************" + System.lineSeparator()); ArrayList<RefCCDAValidationResult> results = validateDocumentAndReturnResults(convertCCDAFileToString(CCDA_FILES[curCCDAFileIndex])); println(System.lineSeparator() + "CCDAIssueStates.hasSchemaError(): " + mdhtResultsHaveSchemaError(results) + System.lineSeparator()); if (curCCDAFileIndex == 0 || curCCDAFileIndex == LAST_SCHEMA_TEST_AND_NO_SCHEMA_ERROR_INDEX) { assertFalse( "The document does not have schema error yet the flag is set to true", mdhtResultsHaveSchemaError(results)); } else { assertTrue( "The document has a schema error yet the flag is set to false", mdhtResultsHaveSchemaError(results)); } for (RefCCDAValidationResult result : results) { if (SHOW_ERRORS_ONLY) { if (result.getType() == ValidationResultType.CCDA_MDHT_CONFORMANCE_ERROR) { printResults(result); } } else { printResults(result); } } println("***************** End results for test + (curCCDAFileIndex + 1) + " ******************" + System.lineSeparator() + System.lineSeparator()); } } @Test public void igOrMu2SchemaErrorsFileTest() { runIgOrMu2OrDS4PAndNotSchemaTests(HAS_SCHEMA_ERROR_INDEX, CCDATypes.CLINICAL_OFFICE_VISIT_SUMMARY, true); } @Test public void igOrMu2NoSchemaErrorsHasMU2ErrorsFileTest() { runIgOrMu2OrDS4PAndNotSchemaTests(HAS_4_POSSIBLE_CONSOL_AND_1_POSSIBLE_MU2_ERROR, CCDATypes.TRANSITIONS_OF_CARE_AMBULATORY_SUMMARY, false); } @Test public void ds4pGeneralTestAndHasErrors() { List<RefCCDAValidationResult> mdhtErrors = getMDHTErrorsFromResults( runIgOrMu2OrDS4PAndNotSchemaTests(DS4P_FROM_MDHT, CCDATypes.NON_SPECIFIC_DS4P, false)); assertTrue("The DS4P file does not contain errors as it should", mdhtErrors.size() > 0); } @Test public void ds4pOfficialAmbulatory() { ArrayList<RefCCDAValidationResult> results = validateDocumentAndReturnResults(convertCCDAFileToString(CCDA_FILES[DS4P_AMB_1]), ValidationObjectives.Sender.B7_DS4P_AMB_170_315); List<RefCCDAValidationResult> mdhtErrors = getMDHTErrorsFromResults(results); assertTrue("The Ambulatory DS4P file has errors but it should not have any errors", mdhtErrors.isEmpty()); printResultsBasedOnFlags(results); } @Test public void ds4pOfficialInpatient() { ArrayList<RefCCDAValidationResult> results = validateDocumentAndReturnResults(convertCCDAFileToString(CCDA_FILES[DS4P_INP_1]), ValidationObjectives.Sender.B7_DS4P_INP_170_315); List<RefCCDAValidationResult> mdhtErrors = getMDHTErrorsFromResults(results); assertTrue("The Inpatient DS4P file has errors but it should not have any errors", mdhtErrors.isEmpty()); printResultsBasedOnFlags(results); } private static ArrayList<RefCCDAValidationResult> runIgOrMu2OrDS4PAndNotSchemaTests(final int ccdaFileIndex, String ccdaTypesObjective, boolean shouldHaveSchemaErrors) { ArrayList<RefCCDAValidationResult> results = validateDocumentAndReturnResults(convertCCDAFileToString(CCDA_FILES[ccdaFileIndex]), ccdaTypesObjective); printResultsBasedOnFlags(results); boolean hasSchemaError = false; for (RefCCDAValidationResult result : getMDHTErrorsFromResults(results)) { if (result.isSchemaError()) { hasSchemaError = true; } } if(shouldHaveSchemaErrors) { assertTrue("The document IS supposed to have a schema error but one was NOT flagged", hasSchemaError); } else { assertFalse("The document is NOT supposed to have a schema error but one WAS flagged", hasSchemaError); } final String msgSuffix = " Issue cannot also be a schema error of type: "; final String msgSuffixSchemaError = msgSuffix + "isSchemaError"; final String msgSuffixDatatypeSchemaError = msgSuffix + "isDatatypeError"; for (RefCCDAValidationResult result : results) { if(result.getDescription().startsWith("Consol")) { assertTrue("The issue (" + result.getDescription() + ") is an IG Issue but was not flagged as such", result.isIGIssue()); assertFalse("The issue (" + result.getDescription() + ") is an IG Issue but was flagged as an MU Issue", result.isMUIssue()); assertFalse("The issue (" + result.getDescription() + ") is an IG Issue but was flagged as a DS4P Issue", result.isDS4PIssue()); assertFalse("An IG" + msgSuffixSchemaError + " (" + result.getDescription() + ")", result.isSchemaError()); assertFalse("An IG" + msgSuffixDatatypeSchemaError + " (" + result.getDescription() + ")", result.isDataTypeSchemaError()); } else if(result.getDescription().startsWith("Mu2consol")) { assertTrue("The issue (" + result.getDescription() + ") is an MU Issue but was not flagged as such", result.isMUIssue()); assertFalse("The issue (" + result.getDescription() + ") is an MU Issue but was flagged as an IG Issue", result.isIGIssue()); assertFalse("The issue (" + result.getDescription() + ") is an MU Issue but was flagged as a DS4P Issue", result.isDS4PIssue()); assertFalse("An Mu2" + msgSuffixSchemaError + " (" + result.getDescription() + ")", result.isSchemaError()); assertFalse("An Mu2" + msgSuffixDatatypeSchemaError + " (" + result.getDescription() + ")", result.isDataTypeSchemaError()); } else if(result.getDescription().startsWith("CONTENTPROFILE")) { assertTrue("The issue (" + result.getDescription() + ") is a DS4P Issue but was not flagged as such", result.isDS4PIssue()); assertFalse("The issue (" + result.getDescription() + ") is a DS4P Issue but was flagged as an IG Issue", result.isIGIssue()); assertFalse("The issue (" + result.getDescription() + ") is an DS4P Issue but was flagged as an MU Issue", result.isMUIssue()); assertFalse("A DS4P" + msgSuffixSchemaError + " (" + result.getDescription() + ")", result.isSchemaError()); assertFalse("A DS4P" + msgSuffixDatatypeSchemaError + " (" + result.getDescription() + ")", result.isDataTypeSchemaError()); } } return results; } @Test public void invalidSnippetOnlyValidationResultsTest() { ArrayList<RefCCDAValidationResult> results = validateDocumentAndReturnResults(convertCCDAFileToString(CCDA_FILES[INVALID_SNIPPET_ONLY_INDEX])); assertTrue( "The results should be null because a SAXParseException should have been thrown", results == null); println("Note: As indicated by a pass, the SAXParseException is expected for the document tested."); } @Test public void invalidSnippetOnlyServiceErrorTest() { ValidationResultsDto results = runReferenceCCDAValidationServiceAndReturnResults( CCDATypes.NON_SPECIFIC_CCDAR2, INVALID_SNIPPET_ONLY_INDEX); handleServiceErrorTest(results); } @Test public void classCastMDHTExceptionThrownServiceErrorTest() { ValidationResultsDto results = runReferenceCCDAValidationServiceAndReturnResults( CCDATypes.NON_SPECIFIC_CCDAR2, NON_CCDA_XML_HTML_FILE_WITH_XML_EXTENSION_INDEX); handleServiceErrorTest(results); } @Test public void altSaxParseMDHTExceptionThrownServiceErrorTest() { ValidationResultsDto results = runReferenceCCDAValidationServiceAndReturnResults( CCDATypes.NON_SPECIFIC_CCDAR2, BLANK_EMPTY_DOCUMENT_INDEX); handleServiceErrorTest(results); } private String handleServiceErrorTest(ValidationResultsDto results) { return handleServiceErrorTest(results, true); } private static String handleServiceErrorTest(ValidationResultsDto results, boolean expectException) { boolean isServiceError = results.getResultsMetaData().isServiceError() && (results.getResultsMetaData().getServiceErrorMessage() != null && !results .getResultsMetaData().getServiceErrorMessage() .isEmpty()); if (isServiceError) { println("Service Error Message: " + results.getResultsMetaData().getServiceErrorMessage()); } if (expectException) { assertTrue( "The results are supposed to contain a service error since the snippet sent is invalid", isServiceError); } else { assertFalse( "The results are NOT supposed to contain a service error the XML file sent is valid", isServiceError); } return results.getResultsMetaData().getServiceErrorMessage(); } @Test public void consolOnlyResultsRemainAfterSwitchAndBackTest() { handlePackageSwitchAndBackTestChoice( CCDATypes.NON_SPECIFIC_CCDAR2, convertCCDAFileToString(CCDA_FILES[HAS_4_POSSIBLE_CONSOL_AND_1_POSSIBLE_MU2_ERROR])); } @Test public void mu2ResultsAreRemovedAfterSwitchAndBackTest() { handlePackageSwitchAndBackTestChoice( CCDATypes.TRANSITIONS_OF_CARE_AMBULATORY_SUMMARY, convertCCDAFileToString(CCDA_FILES[HAS_4_POSSIBLE_CONSOL_AND_1_POSSIBLE_MU2_ERROR])); } @Test public void ds4pResultsAreRemovedAfterSwitchAndBackTest() { handlePackageSwitchAndBackTestChoice( CCDATypes.NON_SPECIFIC_DS4P, convertCCDAFileToString(CCDA_FILES[DS4P_FROM_MDHT])); } private static void handlePackageSwitchAndBackTestChoice(String firstTestCCDATypesType, String ccdaFileAsString) { List<RefCCDAValidationResult> results = validateDocumentAndReturnResults(ccdaFileAsString, firstTestCCDATypesType); assertTrue("MDHT Errors must be returned", hasMDHTValidationErrors(results)); if (firstTestCCDATypesType.equals(CCDATypes.NON_SPECIFIC_CCDAR2) || firstTestCCDATypesType.equals(CCDATypes.NON_SPECIFIC_CCDA)) { println("check original results to ensure there are NO MU2 results (or that there ARE MU2 Results if MU2 type"); List<RefCCDAValidationResult> mdhtErrors = getMDHTErrorsFromResults(results); printResults(mdhtErrors, false, false, false); assertFalse("Since this was not an MU2 validation, Mu2consolPackage results should NOT have been returned", mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.CCDAR11_MU2)); println("run a new validation against MU2 and ensure there ARE MU2 results"); mdhtErrors = getMDHTErrorsFromResults(validateDocumentAndReturnResults( ccdaFileAsString, CCDATypes.TRANSITIONS_OF_CARE_AMBULATORY_SUMMARY)); printResults(mdhtErrors, false, false, false); assertTrue("Since this WAS an MU2 validation, Mu2consolPackage results SHOULD have been returned", mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.CCDAR11_MU2)); println("run a final validation against Consol and ensure there are NO MU2 results and that there ARE Consol Results"); mdhtErrors = getMDHTErrorsFromResults(validateDocumentAndReturnResults( ccdaFileAsString, CCDATypes.NON_SPECIFIC_CCDA)); printResults(mdhtErrors, false, false, false); assertFalse("Since this was a Consol validation (reverted from MU2), Mu2consolPackage results should NOT have been returned", mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.CCDAR11_MU2)); assertTrue("ConsolPackage results SHOULD have been returned since the document was tested against Consol and contains errors", mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.CCDAR21_OR_CCDAR11)); } else if(firstTestCCDATypesType.equals(CCDATypes.TRANSITIONS_OF_CARE_AMBULATORY_SUMMARY)) { println("check original results to ensure there ARE MU2 results"); List<RefCCDAValidationResult> mdhtErrors = getMDHTErrorsFromResults(results); printResults(mdhtErrors, false, false, false); assertTrue("Since this is an MU2 validation, Mu2consolPackage results SHOULD have been returned", mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.CCDAR11_MU2)); println("run a new validation against Consol and ensure there are NO MU2 results)"); mdhtErrors = getMDHTErrorsFromResults(validateDocumentAndReturnResults( ccdaFileAsString, CCDATypes.NON_SPECIFIC_CCDAR2)); printResults(mdhtErrors, false, false, false); assertFalse("Since this was NOT an MU2 validation, Mu2consolPackage results should NOT have been returned", mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.CCDAR11_MU2)); println("run a final validation against MU2 and ensure the MU2 results HAVE RETURNED"); mdhtErrors = getMDHTErrorsFromResults(validateDocumentAndReturnResults( ccdaFileAsString, CCDATypes.TRANSITIONS_OF_CARE_INPATIENT_SUMMARY)); printResults(mdhtErrors, false, false, false); assertTrue("Since this was an MU2 validation (reverted from Consol), Mu2consolPackage results SHOULD have been returned", mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.CCDAR11_MU2)); assertTrue("ConsolPackage results SHOULD have been returned as well since MU2 inherits from consol " + "and the doc tested has base level errors", mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.CCDAR21_OR_CCDAR11)); } else if(firstTestCCDATypesType.equals(ValidationObjectives.Receiver.B8_DS4P_AMB_170_315)) { println("check original results to ensure there ARE DS4P results"); List<RefCCDAValidationResult> mdhtErrors = getMDHTErrorsFromResults(results); printResults(mdhtErrors, false, false, false); assertTrue("Since this is a DS4P validation, CONTENTPROFILEPackage results SHOULD have been returned", mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.DS4P)); println("run a new validation against Consol and ensure there are NO DS4P results)"); mdhtErrors = getMDHTErrorsFromResults(validateDocumentAndReturnResults( ccdaFileAsString, CCDATypes.NON_SPECIFIC_CCDAR2)); printResults(mdhtErrors, false, false, false); assertFalse("Since this was NOT a DS4P validation, CONTENTPROFILEPackage results should NOT have been returned", mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.DS4P)); println("run a final validation against DS4P and ensure the DS4P results HAVE RETURNED"); mdhtErrors = getMDHTErrorsFromResults(validateDocumentAndReturnResults( ccdaFileAsString, ValidationObjectives.Receiver.B8_DS4P_INP_170_315)); printResults(mdhtErrors, false, false, false); assertTrue("Since this was a DS4P validation (reverted from Consol), CONTENTPROFILEPackage results SHOULD have been returned", mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.DS4P)); assertFalse("ConsolPackage results should NOT have been returned as well since DS4P does not inherit from consol " + "but instead from CDA", mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.CCDAR21_OR_CCDAR11)); } } //Ignoring test due to temporary allowance of invalid objectives @Ignore @Test public void invalidValidationObjectiveSentTest() { ValidationResultsDto results = runReferenceCCDAValidationServiceAndReturnResults( "INVALID VALIDATION OBJECTIVE", HAS_4_POSSIBLE_CONSOL_AND_1_POSSIBLE_MU2_ERROR); final String msg = handleServiceErrorTest(results); final String match = "invalid"; assertTrue("The service error returned did not contain: " + match, msg.contains(match)); } //Temporary test introduced due to temporary allowance of invalid objectives @Test public void invalidValidationObjectiveSentConvertToDefaultTest() { List<RefCCDAValidationResult> results = getMDHTErrorsFromResults(validateDocumentAndReturnResults( convertCCDAFileToString(CCDA_FILES[HAS_4_POSSIBLE_CONSOL_AND_1_POSSIBLE_MU2_ERROR]), "INVALID VALIDATION OBJECTIVE")); printResults(results, false, false, false); assertTrue(results != null && !results.isEmpty()); } @Test public void emptyStringValidationObjectiveSentTest() { ValidationResultsDto results = runReferenceCCDAValidationServiceAndReturnResults( "", HAS_4_POSSIBLE_CONSOL_AND_1_POSSIBLE_MU2_ERROR); final String msg = handleServiceErrorTest(results); final String match = "empty"; assertTrue("The service error returned did not contain: " + match, msg.contains(match)); } @Test public void allPossibleValidValidationObjectivesExceptDS4PSentTest() { for (String objective : ValidationObjectives.ALL_UNIQUE_EXCEPT_DS4P) { List<RefCCDAValidationResult> results = getMDHTErrorsFromResults(validateDocumentAndReturnResults( convertCCDAFileToString(CCDA_FILES[HAS_4_POSSIBLE_CONSOL_AND_1_POSSIBLE_MU2_ERROR]), objective)); printResults(results, false, false, false); assertTrue(results != null && !results.isEmpty()); } } @Test public void allPossibleValidCcdaTypesSentTest() { List<String> legacyAndMu2Types = new ArrayList<String>(); legacyAndMu2Types.addAll(CCDATypes.NON_SPECIFIC_CCDA_TYPES); legacyAndMu2Types.addAll(CCDATypes.MU2_TYPES); for (String type : legacyAndMu2Types) { List<RefCCDAValidationResult> results = getMDHTErrorsFromResults(validateDocumentAndReturnResults( convertCCDAFileToString(CCDA_FILES[HAS_4_POSSIBLE_CONSOL_AND_1_POSSIBLE_MU2_ERROR]), type)); printResults(results, false, false, false); assertTrue(results != null && !results.isEmpty()); } } @Ignore @Test public void basicNoExceptionServiceTest() { ValidationResultsDto results = runReferenceCCDAValidationServiceAndReturnResults( ValidationObjectives.Sender.B1_TOC_AMB_170_315, HAS_4_POSSIBLE_CONSOL_AND_1_POSSIBLE_MU2_ERROR); handleServiceErrorTest(results, false); } @Test public void testDocumentTypeIdentificationCCDAndObjectiveSentMetaDataUsingServiceNonVocab() { ValidationResultsDto results = runReferenceCCDAValidationServiceAndReturnResults( CCDATypes.NON_SPECIFIC_CCDA, HAS_4_POSSIBLE_CONSOL_AND_1_POSSIBLE_MU2_ERROR); final String docTypeExpected = UsrhSubType.CONTINUITY_OF_CARE_DOCUMENT.getName(); final String docTypeSet = results.getResultsMetaData().getCcdaDocumentType(); final String objectiveExpected = CCDATypes.NON_SPECIFIC_CCDA; final String objectiveSet = results.getResultsMetaData().getObjectiveProvided(); testDocumentTypeIdentificationAndObjectiveSentMetaDataUsingServiceNonVocab(results.getResultsMetaData(), docTypeExpected, docTypeSet, objectiveExpected, objectiveSet); } @Test public void testDocumentTypeIdentificationCCDR2AndObjectiveSentMetaDataUsingServiceNonVocab() { ValidationResultsDto results = runReferenceCCDAValidationServiceAndReturnResults( CCDATypes.NON_SPECIFIC_CCDA, CCD_R21); final String docTypeExpected = UsrhSubType.CONTINUITY_OF_CARE_DOCUMENT.getName(); final String docTypeSet = results.getResultsMetaData().getCcdaDocumentType(); final String objectiveExpected = CCDATypes.NON_SPECIFIC_CCDA; final String objectiveSet = results.getResultsMetaData().getObjectiveProvided(); testDocumentTypeIdentificationAndObjectiveSentMetaDataUsingServiceNonVocab(results.getResultsMetaData(), docTypeExpected, docTypeSet, objectiveExpected, objectiveSet); } private static void testDocumentTypeIdentificationAndObjectiveSentMetaDataUsingServiceNonVocab(ValidationResultsMetaData resultsMetaData, final String docTypeExpected, final String docTypeSet, final String objectiveExpected, final String objectiveSet) { assertTrue("The document type should be '" + docTypeExpected + "' but it is '" + docTypeSet + "' instead", docTypeSet.equals(docTypeExpected)); System.out.println("docTypeExpected");System.out.println(docTypeExpected); System.out.println("docTypeSet");System.out.println(docTypeSet); assertTrue("The given validation objective should be '" + objectiveExpected + "' but it is '" + objectiveSet + "' instead", objectiveSet.equals(objectiveExpected)); } private static boolean hasMDHTValidationErrors(List<RefCCDAValidationResult> results) { return !getMDHTErrorsFromResults(results).isEmpty(); } private static List<RefCCDAValidationResult> getMDHTErrorsFromResults(List<RefCCDAValidationResult> results) { List<RefCCDAValidationResult> mdhtErrors = new ArrayList<RefCCDAValidationResult>(); for (RefCCDAValidationResult result : results) { if (result.getType() == ValidationResultType.CCDA_MDHT_CONFORMANCE_ERROR) { mdhtErrors.add(result); } } return mdhtErrors; } private static boolean mdhtErrorsHaveProvidedPackageResult(List<RefCCDAValidationResult> mdhtErrors, String ccdaTypeToCheckFor) { boolean hasMu2 = false, hasConsol = false, hasDs4p = false; for(RefCCDAValidationResult mdhtError : mdhtErrors) { if(mdhtError.getDescription().contains("Mu2consol")) { hasMu2 = true; } if(mdhtError.getDescription().contains("Consol")) { hasConsol = true; } if(mdhtError.getDescription().contains("CONTENTPROFILE")) { hasDs4p = true; } } if(ccdaTypeToCheckFor.equals(CCDATypes.CCDAR11_MU2)) { return hasMu2; } else if(ccdaTypeToCheckFor.equals(CCDATypes.CCDAR21_OR_CCDAR11)) { return hasConsol; } else if(ccdaTypeToCheckFor.equals(CCDATypes.DS4P)) { return hasDs4p; } return false; } private static String convertCCDAFileToString(URI ccdaFileURL) { StringBuilder sb = new StringBuilder(); BufferedReader br = null; try { br = new BufferedReader(new FileReader(ccdaFileURL.getPath())); String sCurrentLine = ""; while ((sCurrentLine = br.readLine()) != null) { sb.append(sCurrentLine); } } catch (Exception e) { println(e.toString()); } finally { try { br.close(); } catch (IOException e) { if(LOG_RESULTS_TO_CONSOLE) e.printStackTrace(); } } return sb.toString(); } private static ValidationResultsDto runReferenceCCDAValidationServiceAndReturnResults( String validationObjective, final int XML_FILE_INDEX) { // MultipartFile mockSample = new MockMultipartFile("ccdaFileActualName", "ccdaFileOriginalName", // "text/xml", convertCCDAFileToString(CCDA_FILES[XML_FILE_INDEX]).getBytes()); File file = new File(CCDA_FILES[XML_FILE_INDEX]); ReferenceCCDAValidationService referenceCcdaValidationService = null; MultipartFile mockSample = null; try(FileInputStream is = new FileInputStream(file)) { mockSample = new MockMultipartFile("ccdaFileActualName", "ccdaFileOriginalName", "text/xml", is); referenceCcdaValidationService = new ReferenceCCDAValidationService( new ReferenceCCDAValidator(), new VocabularyCCDAValidator( new VocabularyValidationService()), new ReferenceContentValidator(new ContentValidatorService())); } catch (IOException e) { e.printStackTrace(); } if(referenceCcdaValidationService == null || mockSample == null) { Assert.fail("referenceCcdaValidationService == null || mockSample == null"); throw new NullPointerException("referenceCcdaValidationService is " + (referenceCcdaValidationService == null ? "null" : "not null") + ("mockSample is " + mockSample == null ? "null" : "not null")); } return referenceCcdaValidationService.validateCCDA(validationObjective, "", mockSample); } private static ArrayList<RefCCDAValidationResult> validateDocumentAndReturnResults(String ccdaFileAsString) { return validateDocumentAndReturnResults(ccdaFileAsString, CCDATypes.NON_SPECIFIC_CCDAR2); } private static ArrayList<RefCCDAValidationResult> validateDocumentAndReturnResults(String ccdaFileAsString, String validationObjective) { ReferenceCCDAValidator referenceCCDAValidator = new ReferenceCCDAValidator(); ArrayList<RefCCDAValidationResult> results = null; try { results = referenceCCDAValidator.validateFile(validationObjective, "Test", ccdaFileAsString); } catch (SAXException e) { if(LOG_RESULTS_TO_CONSOLE) e.printStackTrace(); } catch (Exception e) { if(LOG_RESULTS_TO_CONSOLE) e.printStackTrace(); } return results; } private static void printResultsBasedOnFlags(List<RefCCDAValidationResult> results) { if(SHOW_ERRORS_ONLY) { printResults(getMDHTErrorsFromResults(results)); } else { printResults(results); } } private static void printResults(List<RefCCDAValidationResult> results) { printResults(results, true, true, true); } private static void printResults(List<RefCCDAValidationResult> results, boolean showSchema, boolean showType, boolean showIgOrMuType) { if (LOG_RESULTS_TO_CONSOLE) { if (!results.isEmpty()) { for (RefCCDAValidationResult result : results) { printResults(result, showSchema, showType, showIgOrMuType); } println(); } else { println("There are no results to print as the list is empty."); } } } private static void printResults(RefCCDAValidationResult result) { printResults(result, true, true, true); } private static void printResults(RefCCDAValidationResult result, boolean showSchema, boolean showType, boolean showIgOrMuOrDS4PType) { if (LOG_RESULTS_TO_CONSOLE) { println("Description : " + result.getDescription()); if(showType) { println("Type : " + result.getType()); } if(showSchema) { println("result.isSchemaError() : " + result.isSchemaError()); println("result.isDataTypeSchemaError() : " + result.isDataTypeSchemaError()); } if(showIgOrMuOrDS4PType) { println("result.isIGIssue() : " + result.isIGIssue()); println("result.isMUIssue() : " + result.isMUIssue()); println("result.isDS4PIssue() : " + result.isDS4PIssue()); } } } private static void println() { if (LOG_RESULTS_TO_CONSOLE) System.out.println(); } private static void println(String message) { print(message); println(); } private static void print(String message) { if (LOG_RESULTS_TO_CONSOLE) System.out.print(message); } private boolean mdhtResultsHaveSchemaError( List<RefCCDAValidationResult> mdhtResults) { for (RefCCDAValidationResult result : mdhtResults) { if (result.isSchemaError()) { return true; } } return false; } }
package view; import controller.CellSocietyController; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.input.KeyEvent; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; public class SimulationScreen { private CellSocietyController myController; private int myWidth; private int myHeight; private HBox myTop; /** * This function begins setting up the general simulation scene. This includes things like adding the four buttons * at the top that load, step through, speed up, and stop/start the simulation. * @returns a scene */ public Scene initSimScreen(int width, int height){ BorderPane root = new BorderPane(); myWidth = width; myHeight = height; myController = new CellSocietyController(width, height); root.getChildren().add(addButtons()); return new Scene(root, width, height, Color.WHITE); } private HBox addButtons() { HBox myTop = new HBox(); myTop.getChildren().add(addLoadButton()); myTop.getChildren().add(addStepButton()); myTop.getChildren().add(addSpeedUpButton()); myTop.getChildren().add(addStopStartButton(); return myTop; } /** * This function adds the load button to the scene and creates the eventListener. * @return Button that loads new file */ private Button addLoadButton(){ Button loadButton = new Button("Load"); myTop.getChildren().add(loadButton); loadButton.setOnAction(e -> { myController.transitionToFileLoaderScreen(); }); return loadButton; } /** * This function adds the step button to the scene and creates the eventListener. */ private Button addStepButton(){ Button stepButton = new Button ("Step"); myTop.getChildren().add(stepButton); stepButton.setOnAction(e-> { myController.stepThroughSimulation(); }); return stepButton; } /** * Adds speed up button */ private Button addSpeedUpButton(){ Button speedUpButton = new Button("Speed Up"); myTop.getChildren().add(speedUpButton); speedUpButton.setOnAction(e -> { myController.speedUpSimulation(); }); } /** * adds stop.start button * @return */ private Button addStopStartButton(){ Button stopStartButton = new Button("Stop/Start"); myTop.getChildren().add(stopStartButton); stopStartButton.setOnAction(e -> { myController.stopOrStart(); }); } }
import java.util.*; public class Robot { public static final char UP = '^'; public static final char DOWN = 'v'; public static final char LEFT = '<'; public static final char RIGHT = '>'; public static final int LEFT_TURN_90 = 0; public static final int RUGHT_TURN_90 = 1; public static final int DEFAULT_START_X = 0; public static final int DEFAULT_START_Y = 0; public static final int NUMBER_OF_PANELS_TO_MOVE = 1; public static final String WHITE = " "; public static final String BLACK = "x"; public Robot (Vector<String> instructions, boolean debug) { this(instructions, DEFAULT_START_X, DEFAULT_START_Y, debug); } public Robot (Vector<String> instructions, int x, int y, boolean debug) { // any input instructions at this point should be provided 0 _theComputer = new Intcode(instructions, 0, debug); _debug = debug; _currentDirection = UP; // The robot starts facing up. _currentPanel = new Panel(x, y); _panelsPainted = new Vector<Panel>(); _maxX = 0; _minX = 0; _maxY = 0; _minY = 0; _panelsPainted.add(_currentPanel); } public int paint () { String output = null; boolean paintInstruction = true; while (!_theComputer.hasHalted()) { output = _theComputer.executeProgram(); System.out.println("got back "+output+" instructions"); /* * Should return two outputs: * * First, it will output a value indicating the color to paint the panel the * robot is over: 0 means to paint the panel black, and 1 means to paint the panel white. * * Second, it will output a value indicating the direction the robot should turn: 0 means * it should turn left 90 degrees, and 1 means it should turn right 90 degrees. * * After the robot turns, it should always move forward exactly one panel. The robot * starts facing up. */ if (paintInstruction) // which output is this? { paintPanel(output); paintInstruction = false; } else { moveRobot(output); paintInstruction = true; } printPath(); } return _panelsPainted.size(); } public final char currentDirection () { return _currentDirection; } @Override public String toString () { return "Robert current direction: "+_currentDirection+" and current panel: "+_currentPanel; } public void printPath () { for (int x = _minX; x <= _maxX; x++) { for (int y = _minY; y < _maxY; y++) { Panel p = new Panel(x, y); if (_panelsPainted.contains(p)) System.out.print(WHITE); else System.out.println(BLACK); } System.out.println(); } } private void paintPanel (String colour) { int theColour = Integer.parseInt(colour); if (_debug) System.out.println("Got instruction to paint panel "+ ((theColour == Panel.BLACK) ? "black" : "white")); if (theColour == Panel.BLACK) _currentPanel.paint(Panel.BLACK); else _currentPanel.paint(Panel.WHITE); } private void moveRobot (String direction) { int newDirection = Integer.parseInt(direction); Coordinate currentPosition = _currentPanel.getPosition(); int xCoord = currentPosition.getX(); int yCoord = currentPosition.getY(); if (_debug) System.out.println("Got instruction to move "+newDirection); // figure out which direction we're supposed to point in next switch (_currentDirection) { case UP: { if (newDirection == LEFT_TURN_90) { _currentDirection = LEFT; xCoord } else { _currentDirection = RIGHT; xCoord ++; } } break; case DOWN: { if (newDirection == LEFT_TURN_90) { _currentDirection = RIGHT; xCoord++; } else { _currentDirection = LEFT; xCoord } } break; case LEFT: { if (newDirection == LEFT_TURN_90) { _currentDirection = DOWN; yCoord } else { _currentDirection = UP; yCoord++; } } break; case RIGHT: { if (newDirection == LEFT_TURN_90) { _currentDirection = UP; yCoord++; } else { _currentDirection = DOWN; yCoord++; } } break; default: System.out.println("Unknown current direction: "+_currentDirection); break; } if (xCoord > _maxX) _maxX = xCoord; else { if (xCoord < _minX) _minX = xCoord; } if (yCoord > _maxY) _maxY = yCoord; else { if (yCoord < _minY) _minY = yCoord; } Coordinate nextCoord = new Coordinate(xCoord, yCoord); // Have we passed over this panel before? Enumeration<Panel> iter = _panelsPainted.elements(); Panel nextPanel = null; while (iter.hasMoreElements() && (nextPanel == null)) { nextPanel = iter.nextElement(); System.out.println("**comparing "+nextCoord+" and "+nextPanel.getPosition()); if (nextCoord.equals(nextPanel.getPosition())) break; else nextPanel = null; } System.out.println("nextPanel "+nextPanel); if (nextPanel == null) { nextPanel = new Panel(nextCoord); _panelsPainted.add(nextPanel); } _currentPanel = nextPanel; } private Intcode _theComputer; private boolean _debug; private char _currentDirection; private Panel _currentPanel; private Vector<Panel> _panelsPainted; private int _maxX; private int _minX; private int _maxY; private int _minY; }
package bytelang.compiler; import java.util.ArrayList; import java.util.Hashtable; import bytelang.classes.constantpool.CPItem; import bytelang.classes.constantpool.CPItemClass; import bytelang.classes.constantpool.CPItemNameAndType; import bytelang.classes.constantpool.CPItemType; import bytelang.classes.constantpool.CPItemUtf8; import bytelang.compiler.annotations.constantpool.CPItemAnnotation; import bytelang.compiler.annotations.general.AnnotationType; import bytelang.parser.container.values.Value; import bytelang.parser.container.values.ValueInteger; import bytelang.parser.container.values.ValueReference; import bytelang.parser.container.values.ValueType; public class ConstantPoolBuilder { private boolean locked = false; private ArrayList<CPItem> constantPoolItems = new ArrayList<>(); public void setLocked(boolean locked) { this.locked = locked; } public void fromAnotations(ArrayList<CPItemAnnotation> annotations) { replaceReferences(annotations); for (int i = 0; i < annotations.size(); i++) { if (annotations.get(i).isIndependent()) { constantPoolItems.add(annotations.get(i).toCPItem(null)); } else { constantPoolItems.add(null); } } for (int i = 0; i < annotations.size(); i++) { if (constantPoolItems.get(i) == null) { constantPoolItems.set(i, annotations.get(i).toCPItem(this)); } } } public int addItemUtf8(String string) { for (int i = 0; i < constantPoolItems.size(); i++) { if (constantPoolItems.get(i) != null && constantPoolItems.get(i).getType() == CPItemType.UTF8) { short[] containedStringBytes = ((CPItemUtf8) constantPoolItems.get(i)).bytes; char[] containedStringChars = new char[containedStringBytes.length]; for (int j = 0; j < containedStringBytes.length; j++) { containedStringChars[j] = (char) containedStringBytes[j]; } String containedString = String.valueOf(containedStringChars); if (containedString.equals(string)) { return getConstantPoolIndex(i); } } } if (!locked) { byte[] newStringBytes = string.getBytes(); short[] newStringShorts = new short[newStringBytes.length]; for (int i = 0; i < newStringBytes.length; i++) { newStringShorts[i] = newStringBytes[i]; } this.constantPoolItems.add(new CPItemUtf8(null, newStringShorts.length, newStringShorts)); return getConstantPoolIndex(constantPoolItems.size() - 1); } else { throw new RuntimeException("Annotation @lock has been applied, but there are constant-pool items to be generated."); } } public int addItemClass(String className) { for (int i = 0; i < constantPoolItems.size(); i++) { if (constantPoolItems.get(i) != null && constantPoolItems.get(i).getType() == CPItemType.CLASS) { CPItemClass itemClass = (CPItemClass) constantPoolItems.get(i); int nameIndex = itemClass.nameIndex; int itemIndex = getItemIndex(nameIndex); if (itemIndex != -1) { CPItem item = constantPoolItems.get(itemIndex); if (item.getType() == CPItemType.UTF8) { CPItemUtf8 utf8 = (CPItemUtf8) item; String value = utf8.getBytesAsString(); if (value != null && value.equals(className)) { return getConstantPoolIndex(i); } } } } } int stringNameCPIndex = addItemUtf8(className); CPItemClass itemClass = new CPItemClass(null, stringNameCPIndex); constantPoolItems.add(itemClass); return getConstantPoolIndex(constantPoolItems.size() - 1); } public int addItemNameAndType(int nameIndex, int descriptorIndex) { for (int i = 0; i < constantPoolItems.size(); i++) { if (constantPoolItems.get(i) != null && constantPoolItems.get(i).getType() == CPItemType.NAME_AND_TYPE) { CPItemNameAndType itemNameAndType = (CPItemNameAndType) constantPoolItems.get(i); int existingNameIndex = getItemIndex(itemNameAndType.nameIndex); int existingDescriptorIndex = getItemIndex(itemNameAndType.descriptorIndex); if (existingNameIndex == nameIndex && existingDescriptorIndex == descriptorIndex) { return getConstantPoolIndex(i); } } } CPItemNameAndType cpItemNameAndType = new CPItemNameAndType(null, nameIndex, descriptorIndex); constantPoolItems.add(cpItemNameAndType); return getConstantPoolIndex(constantPoolItems.size() - 1); } public int getItemIndex(int constantPoolIndex) { for (int i = 0; i < constantPoolItems.size(); i++) { if (getConstantPoolIndex(i) == constantPoolIndex) { return i; } } return -1; } public int getConstantPoolIndex(int itemIndex) { int constantPoolIndex = 1; for (int i = 0; i < itemIndex; i++) { if (constantPoolItems.get(i) != null) { switch (constantPoolItems.get(i).getType()) { case LONG: case DOUBLE: constantPoolIndex += 2; continue; default: break; } } constantPoolIndex++; } return constantPoolIndex; } private void replaceReferences(ArrayList<CPItemAnnotation> annotations) { Hashtable<String, Integer> referencesTable = buildReferencesTable(annotations); for (CPItemAnnotation annotation : annotations) { annotation.replaceReferences(referencesTable); } } private Hashtable<String, Integer> buildReferencesTable(ArrayList<CPItemAnnotation> annotations) { Hashtable<String, Integer> result = new Hashtable<>(); int currentIndex = 1; for (CPItemAnnotation cpItemAnnotation : annotations) { if (cpItemAnnotation.hasId()) { if (result.get(cpItemAnnotation.getId()) == null) { result.put(cpItemAnnotation.getId(), currentIndex); } else { throw new RuntimeException("Multiple same identifiers found."); } } if (cpItemAnnotation.getType() == AnnotationType.DOUBLE || cpItemAnnotation.getType() == AnnotationType.LONG) { currentIndex += 2; } else { currentIndex++; } } return result; } public static Value replaceReference(Hashtable<String, Integer> referencesTable, Value value) { if (value.getType() == ValueType.REFERENCE) { String referenceName = ((ValueReference) value).getValue(); Integer referenceNumber = referencesTable.get(referenceName); if (referenceNumber == null) { throw new RuntimeException("Identifier " + referenceName + " doesn't exist."); } else { return new ValueInteger(referenceNumber); } } else { return value; } } public CPItem[] toArray() { CPItem[] result = new CPItem[constantPoolItems.size()]; for (int i = 0 ; i < constantPoolItems.size(); i++) { result[i] = constantPoolItems.get(i); } return result; } public int getCPItemIndexById(String id) { for (int i = 0; i < constantPoolItems.size(); i++) { CPItem currentItem = constantPoolItems.get(i); if (currentItem.identifier != null && currentItem.identifier.equals(id)) { return getConstantPoolIndex(i); } } throw new RuntimeException( "Item with identifier \"" + id + "\" is undefined." ); } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.text.NumberFormat; import java.util.Objects; import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableModel; import javax.swing.text.AbstractDocument; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultFormatterFactory; import javax.swing.text.Document; import javax.swing.text.DocumentFilter; import javax.swing.text.JTextComponent; import javax.swing.text.NumberFormatter; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); JTextField textField1 = new JTextField(); initBorderAndAlignment(textField1); ((AbstractDocument) textField1.getDocument()).setDocumentFilter(new IntegerDocumentFilter()); JTextField textField2 = new JTextField(); initBorderAndAlignment(textField2); textField2.setInputVerifier(new IntegerInputVerifier()); JFormattedTextField textField3 = new JFormattedTextField(); initBorderAndAlignment(textField3); textField3.setFormatterFactory(new NumberFormatterFactory()); String[] columnNames = {"Default", "DocumentFilter", "InputVerifier", "JFormattedTextField"}; TableModel model = new DefaultTableModel(columnNames, 10) { @Override public Class<?> getColumnClass(int column) { return Integer.class; } }; JTable table = new JTable(model) { @Override public Component prepareEditor(TableCellEditor editor, int row, int column) { Component c = super.prepareEditor(editor, row, column); ((JComponent) c).setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); return c; } }; table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(textField1)); table.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor(textField2) { @Override public boolean stopCellEditing() { JComponent editor = (JComponent) getComponent(); boolean isEditValid = editor.getInputVerifier().verify(editor); editor.setBorder(isEditValid ? BorderFactory.createEmptyBorder(1, 1, 1, 1) : BorderFactory.createLineBorder(Color.RED)); return isEditValid && super.stopCellEditing(); } }); table.getColumnModel().getColumn(3).setCellEditor(new DefaultCellEditor(textField3) { @Override public boolean stopCellEditing() { JFormattedTextField editor = (JFormattedTextField) getComponent(); boolean isEditValid = editor.isEditValid(); editor.setBorder(isEditValid ? BorderFactory.createEmptyBorder(1, 1, 1, 1) : BorderFactory.createLineBorder(Color.RED)); return isEditValid && super.stopCellEditing(); } }); add(new JScrollPane(table)); setPreferredSize(new Dimension(320, 240)); } private static void initBorderAndAlignment(JTextField textField) { textField.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); textField.setHorizontalAlignment(SwingConstants.RIGHT); } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } // Validating Text and Filtering Documents and Accessibility and the Java Access Bridge Tech Tips // Validating with Input Verifiers class IntegerInputVerifier extends InputVerifier { @Override public boolean verify(JComponent c) { boolean verified = false; if (c instanceof JTextComponent) { String txt = ((JTextComponent) c).getText(); if (txt.isEmpty()) { return true; } try { int iv = Integer.parseInt(txt); verified = iv >= 0; } catch (NumberFormatException ex) { UIManager.getLookAndFeel().provideErrorFeedback(c); } } return verified; } } // Validating Text and Filtering Documents and Accessibility and the Java Access Bridge Tech Tips // Validating with a Document Filter class IntegerDocumentFilter extends DocumentFilter { @Override public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException { if (Objects.nonNull(text)) { replace(fb, offset, 0, text, attr); } } @Override public void remove(DocumentFilter.FilterBypass fb, int offset, int length) throws BadLocationException { replace(fb, offset, length, "", null); } @Override public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { Document doc = fb.getDocument(); int currentLength = doc.getLength(); String currentContent = doc.getText(0, currentLength); String before = currentContent.substring(0, offset); String after = currentContent.substring(length + offset, currentLength); String newValue = before + Objects.toString(text, "") + after; checkInput(newValue, offset); fb.replace(offset, length, text, attrs); } private static void checkInput(String proposedValue, int offset) throws BadLocationException { if (!proposedValue.isEmpty()) { try { Integer.parseInt(proposedValue); } catch (NumberFormatException ex) { throw (BadLocationException) new BadLocationException(proposedValue, offset).initCause(ex); } } } } class NumberFormatterFactory extends DefaultFormatterFactory { private static final NumberFormatter FORMATTER = new NumberFormatter(); static { FORMATTER.setValueClass(Integer.class); ((NumberFormat) FORMATTER.getFormat()).setGroupingUsed(false); } protected NumberFormatterFactory() { super(FORMATTER, FORMATTER, FORMATTER); } }
package com.tamic.excemple; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.tamic.excemple.model.MovieModel; import com.tamic.excemple.model.ResultModel; import com.tamic.excemple.model.SouguBean; import com.tamic.novate.NovateResponse; import com.tamic.novate.BaseSubscriber; import com.tamic.novate.Novate; import com.tamic.novate.RxApiManager; import com.tamic.novate.Throwable; import com.tamic.novate.callback.RxStringCallback; import com.tamic.novate.download.DownLoadCallBack; import com.tamic.novate.download.UpLoadCallback; import com.tamic.novate.request.NovateRequestBody; import com.tamic.novate.util.FileUtil; import com.tamic.novate.util.LogWraper; import com.tamic.novate.util.Utils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import okhttp3.ResponseBody; import rx.Subscription; public class ExempleActivity extends AppCompatActivity { String baseUrl = "http://ip.taobao.com/"; private Novate novate; private Map<String, Object> parameters = new HashMap<String, Object>(); private Map<String, String> headers = new HashMap<>(); private Button btn, btn_test, btn_get, btn_post, btn_download, btn_download_Min, btn_upload, btn_uploadfile, btn_myApi, btn_more; private ProgressDialog mProgressDialog; String uploadPath = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_exemple); // UI referen btn = (Button) findViewById(R.id.bt_simple); btn_test = (Button) findViewById(R.id.bt_test); btn_get = (Button) findViewById(R.id.bt_get); btn_post = (Button) findViewById(R.id.bt_post); btn_download = (Button) findViewById(R.id.bt_download); btn_upload = (Button) findViewById(R.id.bt_upload); btn_download_Min = (Button) findViewById(R.id.bt_download_min); btn_uploadfile = (Button) findViewById(R.id.bt_uploadflie); btn_myApi = (Button) findViewById(R.id.bt_my_api); btn_more = (Button) findViewById(R.id.bt_more); initProgress(this); parameters.put("ip", "21.22.11.33"); headers.put("Accept", "application/json"); novate = new Novate.Builder(this) //.addParameters(parameters) .connectTimeout(20) .writeTimeout(15) .baseUrl(baseUrl) .addHeader(headers) .addCache(true) .addLog(true) .build(); btn_test.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { performTest(); } }); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { perform(); } }); btn_get.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { performGet(); } }); btn_post.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { performPost(); } }); btn_myApi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { perform_Api(); } }); btn_download.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { performDown(); } }); btn_download_Min.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { performDownMin(); } }); btn_upload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { performUpLoadImage(); } }); btn_uploadfile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { performUpLoadFlie(); } }); btn_more.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //startActivity(new Intent(ExempleActivity.this, RequstActivity.class)); } }); } private void initProgress(Context aContext) { if (mProgressDialog == null) { mProgressDialog = new ProgressDialog(aContext); } mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setTitle(""); mProgressDialog.setMax(100); mProgressDialog.setMessage("..."); mProgressDialog.setCancelable(true); } private void showPressDialog() { if (mProgressDialog == null || this.isFinishing()) { return; } mProgressDialog.show(); } private void dismissProgressDialog() { if (mProgressDialog != null && mProgressDialog.isShowing()) { mProgressDialog.dismiss(); } } private void updateProgressDialog(int progress) { if (mProgressDialog != null) { if (!mProgressDialog.isShowing()) { showPressDialog(); } mProgressDialog.setProgress(progress); } } /** * test */ private void performTest() { Map<String, String> headers = new HashMap<>(); headers.put("apikey", "27b6fb21f2b42e9d70cd722b2ed038a9"); headers.put("Accept", "application/json"); novate = new Novate.Builder(this) .addHeader(headers) .addParameters(parameters) .connectTimeout(5) .baseUrl("https://apis.baidu.com/") .addHeader(headers) .addLog(true) .build(); Subscription subscription = novate.test("https://apis.baidu.com/apistore/weatherservice/cityname?cityname=", null, new MyBaseSubscriber<ResponseBody>(ExempleActivity.this) { @Override public void onError(Throwable e) { Log.e("OkHttp", e.getMessage()); Toast.makeText(ExempleActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } @Override public void onNext(ResponseBody responseBody) { try { Toast.makeText(ExempleActivity.this, new String(responseBody.bytes()), Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } } }); RxApiManager.get().add("test", subscription); //cancel RxApiManager.get().cancel("my"); } @Override protected void onPause() { super.onPause(); //RxApiManager.get().cancel("my"); } private void perform() { parameters = new HashMap<>(); /*start=0&count=5*/ parameters.put("start", "0"); parameters.put("count", "1"); Map<String, Object> parameters = new HashMap<>(); parameters.put("mobileNumber", "18826412577"); parameters.put("loginPassword", "123456"); novate = new Novate.Builder(this) .addParameters(parameters) .connectTimeout(10) .baseUrl("http://api.douban.com/") //.addApiManager(ApiManager.class) .addLog(true) .build(); novate.get("v2/movie/top250", parameters, new BaseSubscriber<ResponseBody>() { @Override public void onError(Throwable e) { Toast.makeText(ExempleActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } @Override public void onNext(ResponseBody responseBody) { try { String jstr = new String(responseBody.bytes()); Type type = new TypeToken<MovieModel>() { }.getType(); MovieModel response = new Gson().fromJson(jstr, type); Toast.makeText(ExempleActivity.this, response.toString(), Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } } }); } /** * performGet * */ private void performGet() { /** * novate.Get() * performPost() */ novate.executeGet("service/getIpInfo.php", parameters, new Novate.ResponseCallBack<ResultModel>() { @Override public void onStart() { // todo onStart } @Override public void onCompleted() { } @Override public void onError(Throwable e) { Toast.makeText(ExempleActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } @Override public void onSuccee(NovateResponse<ResultModel> response) { } @Override public void onsuccess(int code, String msg, ResultModel response, String originalResponse) { Toast.makeText(ExempleActivity.this, response.toString(), Toast.LENGTH_SHORT).show(); } }); } /** * performPost */ private void performPost() { Map<String, Object> parameters = new HashMap<>(); parameters.put("ip", "21.22.11.33"); novate = new Novate.Builder(this) .connectTimeout(8) .baseUrl(baseUrl) //.addApiManager(ApiManager.class) .addLog(true) .build(); /** * * * post * * novate.executeGet() * performGet() */ novate.post("service/getIpInfo.php", parameters, new MyBaseSubscriber<ResponseBody>(ExempleActivity.this) { @Override public void onError(Throwable e) { if (!TextUtils.isEmpty(e.getMessage())) { Log.e("OkHttp", e.getMessage()); Toast.makeText(ExempleActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } } @Override public void onNext(ResponseBody responseBody) { try { String jstr = new String(responseBody.bytes()); if (jstr.trim().isEmpty()) { return; } Type type = new TypeToken<NovateResponse<ResultModel>>() { }.getType(); NovateResponse<ResultModel> response = new Gson().fromJson(jstr, type); if (response.getData() != null) { Toast.makeText(ExempleActivity.this, response.getData().toString(), Toast.LENGTH_SHORT).show(); } Toast.makeText(ExempleActivity.this, jstr , Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } } }); } private void perform_Api() { parameters.clear(); parameters.put("m", "souguapp"); parameters.put("c", "appusers"); parameters.put("a", "network"); novate = new Novate.Builder(this) .addHeader(headers) .addParameters(parameters) .baseUrl("http://lbs.sougu.net.cn/") .addLog(true) .build(); MyAPI myAPI = novate.create(MyAPI.class); novate.call(myAPI.getSougu(parameters), new MyBaseSubscriber<SouguBean>(ExempleActivity.this) { @Override public void onError(Throwable e) { Toast.makeText(ExempleActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } @Override public void onNext(SouguBean souguBean) { Toast.makeText(ExempleActivity.this, souguBean.toString(), Toast.LENGTH_SHORT).show(); } }); } /** * upload */ private void performUpLoadImage() { String mPath = uploadPath; //"you File path "; String url = ""; RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpg"), new File(mPath)); final NovateRequestBody requestBody = Utils.createNovateRequestBody(requestFile, new UpLoadCallback() { @Override public void onProgress(Object tag, int progress, long speed, boolean done) { LogWraper.d("uplaod", "tag:" + tag.toString() + "progress:"+ progress); updateProgressDialog(progress); } }); novate.RxUploadWithBody(url, requestBody, new RxStringCallback() { @Override public void onStart(Object tag) { super.onStart(tag); showPressDialog(); } @Override public void onNext(Object tag, String response) { LogWraper.d("novate", response); Toast.makeText(ExempleActivity.this, "", Toast.LENGTH_SHORT).show(); } @Override public void onError(Object tag, Throwable e) { Toast.makeText(ExempleActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); dismissProgressDialog(); } @Override public void onCancel(Object tag, Throwable e) { } @Override public void onCompleted(Object tag) { super.onCompleted(tag); dismissProgressDialog(); } }); } /** * upload */ private void performUpLoadFlie() { String mPath = uploadPath; //"you File path "; String url = ""; File file = new File(mPath); RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data; charset=utf-8"), file); final NovateRequestBody requestBody = Utils.createNovateRequestBody(requestFile, new UpLoadCallback() { @Override public void onProgress(Object tag, int progress, long speed, boolean done) { LogWraper.d("uplaod", "tag:" + tag.toString() + "progress:"+ progress); updateProgressDialog(progress); } }); MultipartBody.Part body2 = MultipartBody.Part.createFormData("image", file.getName(), requestBody); novate.RxUploadWithPart(url, body2, new RxStringCallback() { @Override public void onStart(Object tag) { super.onStart(tag); showPressDialog(); } @Override public void onError(Object tag, Throwable e) { Toast.makeText(ExempleActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); dismissProgressDialog(); } @Override public void onCancel(Object tag, Throwable e) { } @Override public void onNext(Object tag, String response) { LogWraper.d(response); Toast.makeText(ExempleActivity.this, "", Toast.LENGTH_SHORT).show(); dismissProgressDialog(); } }); } /** * upload */ private void performUpLoadFlies(){ String path = uploadPath;//"you File path "; String url = "http://workflow.tjcclz.com/GWWorkPlatform/NoticeServlet?GWType=wifiUploadFile"; File file = new File(path); // RequestBody RequestBody RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file); final NovateRequestBody requestBody = Utils.createNovateRequestBody(requestFile, new UpLoadCallback() { @Override public void onProgress(Object tag, int progress, long speed, boolean done) { LogWraper.d("uplaod", "tag:" + tag.toString() + "progress:"+ progress); updateProgressDialog(progress); } }); MultipartBody.Part part = MultipartBody.Part.createFormData("image", file.getName(), requestBody); Map<String, MultipartBody.Part> maps = new HashMap<>(); maps.put("image", part); novate.RxUploadWithPartMap(url, maps, new RxStringCallback() { @Override public void onStart(Object tag) { super.onStart(tag); showPressDialog(); } @Override public void onNext(Object tag, String response) { LogWraper.d("novate", response); Toast.makeText(ExempleActivity.this, "", Toast.LENGTH_SHORT).show(); } @Override public void onError(Object tag, Throwable e) { Toast.makeText(ExempleActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); dismissProgressDialog(); } @Override public void onCancel(Object tag, Throwable e) { } }); } /** * performDown file * ex: apk , video... */ private void performDown() { String downUrl = "http://wifiapi02.51y5.net/wifiapi/rd.do?f=wk00003&b=gwanz02&rurl=http%3A%2F%2Fdl.lianwifi.com%2Fdownload%2Fandroid%2FWifiKey-3091-guanwang.apk"; novate.download(downUrl, "test.mei", new DownLoadCallBack() { @Override public void onStart(String s) { super.onStart(s); btn_download.setText("DownLoad cancel"); showPressDialog(); } @Override public void onError(Throwable e) { Toast.makeText(ExempleActivity.this, "onError:" + e.getMessage(), Toast.LENGTH_SHORT).show(); } @Override public void onProgress(String key, int progress, long fileSizeDownloaded, long totalSize) { super.onProgress(key, progress, fileSizeDownloaded, totalSize); Log.v("test", fileSizeDownloaded+""); //Toast.makeText(ExempleActivity.this, "progress: " + progress + " download: " + fileSizeDownloaded, Toast.LENGTH_SHORT).show(); updateProgressDialog(progress); } @Override public void onSucess(String key, String path, String name, long fileSize) { Toast.makeText(ExempleActivity.this, "download onSucess", Toast.LENGTH_SHORT).show(); btn_download.setText("DownLoad start"); dismissProgressDialog(); } @Override public void onCancel() { super.onCancel(); btn_download.setText("DownLoad start"); dismissProgressDialog(); } }); } /** * performDown small file * ex: image txt */ private void performDownMin() { String downUrl = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png"; novate.downloadMin("tag", downUrl, "my.jpg",new DownLoadCallBack() { @Override public void onStart(String s) { super.onStart(s); btn_download.setText("DownLoadMin cancel"); showPressDialog(); } @Override public void onError(Throwable e) { Toast.makeText(ExempleActivity.this, "onError:" + e.getMessage(), Toast.LENGTH_SHORT).show(); } @Override public void onSucess(String key, String path, String name, long fileSize) { btn_download.setText("DownLoad start"); uploadPath = path + name; dismissProgressDialog(); } @Override public void onProgress(String key, int progress, long fileSizeDownloaded, long totalSize) { super.onProgress(key, progress, fileSizeDownloaded, totalSize); updateProgressDialog(progress); Toast.makeText(ExempleActivity.this, "progress: " + progress + " download: " + fileSizeDownloaded, Toast.LENGTH_SHORT).show(); } @Override public void onCancel() { super.onCancel(); btn_download.setText("DownLoadMin start"); } }); } }
package de.osramos.ss13.proj1.services; import java.util.HashSet; import java.util.Set; import de.osramos.ss13.proj1.model.Taskdb; import de.osramos.ss13.proj1.model.Userdb; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.ContextStartedEvent; public class FirstRun implements ApplicationListener<ContextRefreshedEvent>{ static boolean first = true; public synchronized void onApplicationEvent(ContextRefreshedEvent context ) { if(first) { first= false; PopulateDatabase(); } } public void PopulateDatabase() { // populate with default usernames and passwords CreateUsers(); // create example tasks createTasks(); } private void CreateUsers() { Userdb user = null; try { user = null; user = Userdb.findUserdbsByUsernameEquals("admin") .getSingleResult(); } catch (Exception e) { } finally { try { if (null == user) { user = new Userdb(); user.setFirstname("admin"); user.setLastname("ADMIN"); user.setUsername("admin"); user.setUserrole("admin"); user.setPassword("admin"); user.persist(); } } catch (Exception e) { } } try { user = null; user = Userdb.findUserdbsByUsernameEquals("senior") .getSingleResult(); } catch (Exception e) { } finally { try { if (null == user) { user = new Userdb(); user.setFirstname("senior"); user.setLastname("SENIOR"); user.setUsername("senior"); user.setUserrole("senior"); user.setPassword("senior"); user.persist(); } } catch (Exception e) { } } try { user = null; user = Userdb.findUserdbsByUsernameEquals("trainee") .getSingleResult(); } catch (Exception e) { } finally { try { if (null == user) { user = null; user = new Userdb(); user.setFirstname("trainee"); user.setLastname("TRAINEE"); user.setUsername("trainee"); user.setUserrole("trainee"); user.setPassword("trainee"); user.persist(); } } catch (Exception e) { } } } private void createTasks() { Userdb trainee = Userdb.findUserdbsByUsernameEquals("trainee").getSingleResult(); Taskdb t = null; t = new Taskdb(); t.setDescription("description A"); t.setPerson("Mr. Bond"); t.setBuilding("Building ??"); t.setPersonfunction("Function 007"); t.setRoomno("007"); t.setTaskname("Your first mission"); t.setTrainee(trainee); t.setGps_Start("51.522416,-0.069551"); t.setGps_End("51.500194,-0.057192"); t.persist(); t = new Taskdb(); t.setDescription("description B"); t.setPerson("Mr. Powers"); t.setBuilding("Club X"); t.setPersonfunction("Function uncertain"); t.setRoomno("no number"); t.setTaskname("Your punishment"); t.setTrainee(trainee); t.setGps_Start("55.841205,-4.232883"); t.setGps_End("55.815365,-4.242496"); t.persist(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package snowballmadness; import org.bukkit.entity.Entity; import org.bukkit.entity.Snowball; import org.bukkit.util.Vector; /** * This is a snowball that flies faster than nomrla, and can apply a second * logic that will be amplified too. * * @author DanJ */ public class AmplifiedSnowballLogic extends ChainableSnowballLogic { private final double amplification; public AmplifiedSnowballLogic(double amplification, InventorySlice nextSlice) { super(nextSlice); this.amplification = amplification; } @Override public void launch(Snowball snowball, SnowballInfo info) { Vector v = snowball.getVelocity().clone(); v.multiply(amplification * info.amplification); snowball.setVelocity(v); super.launch(snowball, info); } @Override public double damage(Snowball snowball, SnowballInfo info, Entity target, double proposedDamage) { double damage = super.damage(snowball, info, target, proposedDamage); if (amplification > 1.0 && damage == 0.0) { damage = 1.0; } return damage * amplification; } @Override protected SnowballInfo adjustInfo(Snowball snowball, SnowballInfo info) { return info.getAmplified(amplification); } @Override public String toString() { return String.format("%s -> (x%f) %s", getClass().getSimpleName(), amplification, nextLogic); } }
package com.timeanddate.services.common; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * * @author Cato Auestad <cato@timeanddate.com> * */ public class WebClient { public String downloadString(URL url) { HttpURLConnection connection = null; try { // Create connection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(url.getQuery().getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setRequestProperty("User-Agent", "libtad-jvm-1.0.0"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); // Send request DataOutputStream wr = new DataOutputStream( connection.getOutputStream()); wr.writeBytes(url.getQuery()); wr.flush(); wr.close(); // Get Response InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); return response.toString(); } catch (Exception e) { e.printStackTrace(); return null; } finally { if (connection != null) { connection.disconnect(); } } } }
package edu.wustl.catissuecore.actionForm; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; import edu.wustl.catissuecore.domain.ExternalIdentifier; import edu.wustl.catissuecore.domain.Specimen; import edu.wustl.catissuecore.domain.SpecimenCharacteristics; import edu.wustl.catissuecore.domain.StorageContainer; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.catissuecore.util.global.Utility; import edu.wustl.common.actionForm.AbstractActionForm; import edu.wustl.common.domain.AbstractDomainObject; import edu.wustl.common.util.global.ApplicationProperties; import edu.wustl.common.util.global.Validator; import edu.wustl.common.util.logger.Logger; /** * SpecimenForm Class is used to encapsulate all the request parameters passed * from New/Create Specimen webpage. * @author aniruddha_phadnis */ public class SpecimenForm extends AbstractActionForm { /** * Type of specimen. e.g. Tissue, Molecular, Cell, Fluid */ protected String className = ""; /** * Sub Type of specimen. e.g. Serum, Plasma, Blood, Fresh Tissue etc. */ protected String type; /** * Concentration of specimen. */ protected String concentration; /** * Amount of Specimen. */ protected String quantity; /** * Available Amount of Specimen. */ protected String availableQuantity; /** * Is quantity available? */ protected boolean available; /** * Unit of specimen. */ protected String unit; /** * A physically discreet container that is used to store a specimen. * e.g. Box, Freezer etc */ protected String storageContainer = ""; /** * Reference to dimensional position one of the specimen in Storage Container. */ protected String positionDimensionOne; /** * Reference to dimensional position two of the specimen in Storage Container. */ protected String positionDimensionTwo; /** * Barcode assigned to the specimen. */ protected String barcode; /** * Comments on specimen. */ protected String comments = ""; /** * Number of external identifier rows. */ protected int exIdCounter = 1; /** * Parent Container Identifier. */ private String parentContainerId; protected String positionInStorageContainer; /** * Map to handle all the data of external identifiers. */ protected Map externalIdentifier = new HashMap(); /** * Returns the concentration. * @return String the concentration. * @see #setConcentration(String) */ public String getConcentration() { return concentration; } /** * Sets the concentration. * @param concentration The concentration. * @see #getConcentration() */ public void setConcentration(String concentration) { this.concentration = concentration; } /** * Associates the specified object with the specified key in the map. * @param key the key to which the object is mapped. * @param value the object which is mapped. */ public void setExternalIdentifierValue(String key, Object value) { if (isMutable()) externalIdentifier.put(key, value); } /** * Returns the object to which this map maps the specified key. * @param key the required key. * @return the object to which this map maps the specified key. */ public Object getExternalIdentifierValue(String key) { return externalIdentifier.get(key); } /** * Returns all the values in the map. * @return Collection all the values in the map. */ public Collection getAllExternalIdentifiers() { return externalIdentifier.values(); } /** * Sets the map. * @param externalIdentifier the map to be set. * @see #getExternalIdentifier() */ public void setExternalIdentifier(Map externalIdentifier) { this.externalIdentifier = externalIdentifier; } /** * Returns the map of external identifiers. * @return Map the map of external identifiers. * @see #setExternalIdentifier(Map) */ public Map getExternalIdentifier() { return this.externalIdentifier; } /** * Returns the comments. * @return String the comments. * @see #setComments(String) */ public String getComments() { return comments; } /** * Sets the comments. * @param comments The comments. * @see #getComments() */ public void setComments(String comments) { this.comments = comments; } /** * Returns the position dimension one. * @return String the position dimension one. * @see #setPositionDimensionOne(String) */ public String getPositionDimensionOne() { return positionDimensionOne; } /** * Sets the position dimension one. * @param positionDimensionOne The position dimension one. * @see #getPositionDimensionOne() */ public void setPositionDimensionOne(String positionDimensionOne) { this.positionDimensionOne = positionDimensionOne; } /** * Returns the position dimension two. * @return String the position dimension two. * @see #setPositionDimensionTwo(String) */ public String getPositionDimensionTwo() { return positionDimensionTwo; } /** * Sets the position dimension two. * @param positionDimensionTwo The position dimension two. * @see #getPositionDimensionTwo() */ public void setPositionDimensionTwo(String positionDimensionTwo) { this.positionDimensionTwo = positionDimensionTwo; } /** * Returns the barcode of this specimen. * @return String the barcode of this specimen. * @see #setBarcode(String) */ public String getBarcode() { return barcode; } /** * Sets the barcode of this specimen. * @param barcode The barcode of this specimen. * @see #getBarcode() */ public void setBarcode(String barcode) { this.barcode = barcode; } /** * Returns the quantity. * @return String the quantity. * @see #setQuantity(String) */ public String getQuantity() { return quantity; } /** * Sets the quantity. * @param quantity The quantity. * @see #getQuantity() */ public void setQuantity(String quantity) { this.quantity = quantity; } /** * Returns the available quantity. * @return String the available quantity. * @see #setAvailableQuantity(String) */ public String getAvailableQuantity() { return availableQuantity; } /** * Sets the available quantity. * @param availableQuantity The available quantity. * @see #getAvailableQuantity() */ public void setAvailableQuantity(String availableQuantity) { if (isMutable()) { this.availableQuantity = availableQuantity; } } /** * Returns the unit of this specimen. * @return String the unit of this specimen. * @see #setUnit(String) */ public String getUnit() { return unit; } /** * Sets the unit of this specimen. * @param unit The unit of this specimen. * @see #getUnit() */ public void setUnit(String unit) { this.unit = unit; } /** * Returns the storage container of this specimen. * @return String the storage container of this specimen. * @see #setStorageContainer(String) */ public String getStorageContainer() { return storageContainer; } /** * Sets the storage container of this specimen. * @param storageContainer The storage container of this specimen. * @see #getStorageContainer() */ public void setStorageContainer(String storageContainer) { this.storageContainer = storageContainer; } /** * Returns the subtype of this specimen. * @return String the subtype of this specimen. * @see #setType(String) */ public String getType() { return type; } /** * Sets the subtype of this specimen. * @param subType The subtype of this specimen. * @see #getType() */ public void setType(String subType) { this.type = subType; } /** * Returns the className of this specimen. * @return String the className of this specimen. * @see #setClassName(String) */ public String getClassName() { return className; } /** * Sets the className of this specimen. * @param className The className of this specimen. * @see #getClassName() */ public void setClassName(String className) { this.className = className; } protected void reset() { this.className = null; this.type = null; this.storageContainer = null; this.comments = null; this.externalIdentifier = new HashMap(); } /** * Returns the id assigned to form bean. */ public int getFormId() { return -1; } /** * This function Copies the data from an Specimen object to a SpecimenForm object. * @param site An object containing the information about site. */ public void setAllValues(AbstractDomainObject abstractDomain) { Specimen specimen = (Specimen) abstractDomain; this.systemIdentifier = specimen.getId().longValue(); this.type = specimen.getType(); this.concentration = ""; this.comments = specimen.getComments(); this.activityStatus = specimen.getActivityStatus(); if(specimen.getAvailable()!=null) this.available = specimen.getAvailable().booleanValue(); StorageContainer container = specimen.getStorageContainer(); if (container != null) { this.storageContainer = String.valueOf(container .getSystemIdentifier()); this.positionDimensionOne = String.valueOf(specimen .getPositionDimensionOne()); this.positionDimensionTwo = String.valueOf(specimen .getPositionDimensionTwo()); this.positionInStorageContainer = container.getStorageType().getName() + " : " + container.getSystemIdentifier() + " Pos(" + this.positionDimensionOne + "," + this.positionDimensionTwo + ")"; } this.barcode = specimen.getBarcode(); //TODO : Aniruddha // if (specimen instanceof CellSpecimen) // this.className = "Cell"; // this.quantity = String.valueOf(((CellSpecimen) specimen) // .getQuantityInCellCount()); // this.availableQuantity = String.valueOf(((CellSpecimen) specimen).getAvailableQuantityInCellCount()); // else if (specimen instanceof FluidSpecimen) // this.className = "Fluid"; // this.quantity = String.valueOf(((FluidSpecimen) specimen) // .getQuantityInMilliliter()); // this.availableQuantity = String.valueOf(((FluidSpecimen) specimen).getAvailableQuantityInMilliliter()); // else if (specimen instanceof MolecularSpecimen) // this.className = "Molecular"; // this.quantity = String.valueOf(((MolecularSpecimen) specimen) // .getQuantityInMicrogram()); // this.availableQuantity = String.valueOf(((MolecularSpecimen) specimen).getAvailableQuantityInMicrogram()); // if (((MolecularSpecimen) specimen) // .getConcentrationInMicrogramPerMicroliter() != null) // this.concentration = String // .valueOf(((MolecularSpecimen) specimen) // .getConcentrationInMicrogramPerMicroliter()); // else if (specimen instanceof TissueSpecimen) // this.className = "Tissue"; // this.quantity = String.valueOf(((TissueSpecimen) specimen) // .getQuantityInGram()); // this.availableQuantity = String.valueOf(((TissueSpecimen) specimen).getAvailableQuantityInGram()); SpecimenCharacteristics characteristic = specimen .getSpecimenCharacteristics(); Collection externalIdentifierCollection = specimen .getExternalIdentifierCollection(); exIdCounter = 1; if (externalIdentifierCollection != null && externalIdentifierCollection.size() != 0) { externalIdentifier = new HashMap(); int i = 1; Iterator it = externalIdentifierCollection.iterator(); while (it.hasNext()) { String key1 = "ExternalIdentifier:" + i + "_name"; String key2 = "ExternalIdentifier:" + i + "_value"; String key3 = "ExternalIdentifier:" + i + "_systemIdentifier"; ExternalIdentifier externalId = (ExternalIdentifier) it .next(); externalIdentifier.put(key1, externalId.getName()); externalIdentifier.put(key2, externalId.getValue()); externalIdentifier.put(key3, String.valueOf(externalId .getId())); i++; } exIdCounter = externalIdentifierCollection.size(); } } public void setAllVal(Object obj) { edu.wustl.catissuecore.domainobject.Specimen specimen = (edu.wustl.catissuecore.domainobject.Specimen) obj; this.systemIdentifier = specimen.getId().longValue(); this.type = specimen.getType(); this.concentration = ""; this.comments = specimen.getComments(); this.activityStatus = specimen.getActivityStatus(); if(specimen.getAvailable()!=null) this.available = specimen.getAvailable().booleanValue(); edu.wustl.catissuecore.domainobject.StorageContainer container = specimen.getStorageContainer(); if (container != null) { this.storageContainer = String.valueOf(container .getId()); this.positionDimensionOne = String.valueOf(specimen .getPositionDimensionOne()); this.positionDimensionTwo = String.valueOf(specimen .getPositionDimensionTwo()); this.positionInStorageContainer = container.getStorageType().getType() + " : " + container.getId() + " Pos(" + this.positionDimensionOne + "," + this.positionDimensionTwo + ")"; } this.barcode = specimen.getBarcode(); if (specimen instanceof edu.wustl.catissuecore.domainobject.CellSpecimen) { this.className = "Cell"; this.quantity = String.valueOf(((edu.wustl.catissuecore.domainobject.CellSpecimen) specimen) .getQuantityInCellCount()); this.availableQuantity = String.valueOf(((edu.wustl.catissuecore.domainobject.CellSpecimen) specimen).getAvailableQuantityInCellCount()); } else if (specimen instanceof edu.wustl.catissuecore.domainobject.FluidSpecimen) { this.className = "Fluid"; this.quantity = String.valueOf(((edu.wustl.catissuecore.domainobject.FluidSpecimen) specimen) .getQuantityInMilliliter()); this.availableQuantity = String.valueOf(((edu.wustl.catissuecore.domainobject.FluidSpecimen) specimen).getAvailableQuantityInMilliliter()); } else if (specimen instanceof edu.wustl.catissuecore.domainobject.MolecularSpecimen) { this.className = "Molecular"; this.quantity = String.valueOf(((edu.wustl.catissuecore.domainobject.MolecularSpecimen) specimen) .getQuantityInMicrogram()); this.availableQuantity = String.valueOf(((edu.wustl.catissuecore.domainobject.MolecularSpecimen) specimen).getAvailableQuantityInMicrogram()); if (((edu.wustl.catissuecore.domainobject.MolecularSpecimen) specimen) .getConcentrationInMicrogramPerMicroliter() != null) this.concentration = String .valueOf(((edu.wustl.catissuecore.domainobject.MolecularSpecimen) specimen) .getConcentrationInMicrogramPerMicroliter()); } else if (specimen instanceof edu.wustl.catissuecore.domainobject.TissueSpecimen) { this.className = "Tissue"; this.quantity = String.valueOf(((edu.wustl.catissuecore.domainobject.TissueSpecimen) specimen) .getQuantityInGram()); this.availableQuantity = String.valueOf(((edu.wustl.catissuecore.domainobject.TissueSpecimen) specimen).getAvailableQuantityInGram()); } edu.wustl.catissuecore.domainobject.SpecimenCharacteristics characteristic = specimen .getSpecimenCharacteristics(); Collection externalIdentifierCollection = specimen .getExternalIdentifierCollection(); exIdCounter = 1; if (externalIdentifierCollection != null && externalIdentifierCollection.size() != 0) { externalIdentifier = new HashMap(); int i = 1; Iterator it = externalIdentifierCollection.iterator(); while (it.hasNext()) { String key1 = "ExternalIdentifier:" + i + "_name"; String key2 = "ExternalIdentifier:" + i + "_value"; String key3 = "ExternalIdentifier:" + i + "_systemIdentifier"; edu.wustl.catissuecore.domainobject.ExternalIdentifier externalId = (edu.wustl.catissuecore.domainobject.ExternalIdentifier) it.next(); if(externalId != null) { externalIdentifier.put(key1, Utility.toString(externalId.getName())); externalIdentifier.put(key2, Utility.toString(externalId.getValue())); externalIdentifier.put(key3, Utility.toString(externalId.getId())); } i++; } exIdCounter = externalIdentifierCollection.size(); } } /** * Overrides the validate method of ActionForm. * */ public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); Validator validator = new Validator(); try { if (operation.equals(Constants.ADD) || operation.equals(Constants.EDIT)) { if (!validator.isValidOption(className)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("specimen.type"))); } if (!className.equals("Cell") && !validator.isValidOption(type)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("specimen.subType"))); } if (validator.isEmpty(quantity)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("specimen.quantity"))); } else if (!validator.isDouble(quantity)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.format", ApplicationProperties .getValue("specimen.quantity"))); } if(validator.isEmpty(positionDimensionOne) || validator.isEmpty(positionDimensionTwo) || validator.isEmpty(storageContainer )) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("specimen.positionInStorageContainer"))); } else { if(!validator.isNumeric(positionDimensionOne,1) || !validator.isNumeric(positionDimensionTwo,1) || !validator.isNumeric(storageContainer,1)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.format", ApplicationProperties .getValue("specimen.positionInStorageContainer"))); } } //Validations for External Identifier Add-More Block String className = "ExternalIdentifier:"; String key1 = "_name"; String key2 = "_value"; String key3 = "_" + Constants.SYSTEM_IDENTIFIER; int index = 1; while (true) { String keyOne = className + index + key1; String keyTwo = className + index + key2; String keyThree = className + index + key3; String value1 = (String) externalIdentifier.get(keyOne); String value2 = (String) externalIdentifier.get(keyTwo); if (value1 == null || value2 == null) { break; } else if (value1.trim().equals("") && value2.trim().equals("")) { externalIdentifier.remove(keyOne); externalIdentifier.remove(keyTwo); externalIdentifier.remove(keyThree); } else if ((!value1.trim().equals("") && value2.trim().equals("")) || (value1.trim().equals("") && !value2.trim().equals(""))) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.specimen.externalIdentifier.missing", ApplicationProperties.getValue("specimen.msg"))); break; } index++; } } } catch (Exception excp) { Logger.out.error(excp.getMessage()); } return errors; } /** * Returns the counter that holds no. of external identifier rows. * @return The counter that holds no. of external identifier rows. * @see #setExIdCounter(int) */ public int getExIdCounter() { return exIdCounter; } /** * Sets the counter that holds no. of external identifier rows. * @param exIdCounter The counter that holds no. of external identifier rows. * @see #getExIdCounter() */ public void setExIdCounter(int exIdCounter) { this.exIdCounter = exIdCounter; } /** * Returns the position in storage container. * @return The position in storage container. * @see #setPositionInStorageContainer(String) */ public String getPositionInStorageContainer() { return positionInStorageContainer; } /** * Sets the position in storage container. * @param positionInStorageContainer The position in storage container. * @see #getPositionInStorageContainer() */ public void setPositionInStorageContainer(String positionInStorageContainer) { this.positionInStorageContainer = positionInStorageContainer; } /** * Returns True/False, whether the quatity is available or not. * @return True/False, whether the quatity is available or not. * @see #setAvailable(boolean) */ public boolean isAvailable() { return available; } /** * Sets True/False depending upon the availability of the quantity. * @param available True/False depending upon the availability of the quantity. * @see #getAvailable() */ public void setAvailable(boolean available) { this.available = available; } /** * Returns the parent container id. * @return The parent container id. * @see #setParentContainerId(String) */ public String getParentContainerId() { return parentContainerId; } /** * Sets the parent container id. * @param parentContainerId The parent container id. * @see #getParentContainerId() */ public void setParentContainerId(String parentContainerId) { this.parentContainerId = parentContainerId; } }
package edu.wustl.catissuecore.domain; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import edu.wustl.catissuecore.actionForm.SpecimenProtocolForm; import edu.wustl.catissuecore.util.global.Utility; import edu.wustl.common.actionForm.AbstractActionForm; import edu.wustl.common.domain.AbstractDomainObject; import edu.wustl.common.util.logger.Logger; /** * A set of procedures that govern the collection and/or distribution of biospecimens. * @author mandar_deshmukh * @hibernate.class table="CATISSUE_SPECIMEN_PROTOCOL" */ public abstract class SpecimenProtocol extends AbstractDomainObject implements java.io.Serializable { private static final long serialVersionUID = 1234567890L; /** * System generated unique systemIdentifier. */ protected Long systemIdentifier = null; /** * The current principal investigator of the protocol. */ protected User principalInvestigator = new User(); /** * Full title assigned to the protocol. */ protected String title; /** * Abbreviated title assigned to the protocol. */ protected String shortTitle; /** * IRB approval number. */ protected String irbIdentifier; /** * Date on which the protocol is activated. */ protected Date startDate; /** * Date on which the protocol is marked as closed. */ protected Date endDate; /** * Number of anticipated cases need for the protocol. */ protected Integer enrollment; /** * URL to the document that describes detailed information for the biospecimen protocol. */ protected String descriptionURL; /** * Defines whether this SpecimenProtocol record can be queried (Active) or not queried (Inactive) by any actor. */ protected String activityStatus; /** * NOTE: Do not delete this constructor. Hibernet uses this by reflection API. * */ public SpecimenProtocol() { super(); } /** * Returns the systemidentifier of the protocol. * @hibernate.id name="systemIdentifier" column="IDENTIFIER" type="long" length="30" * unsaved-value="null" generator-class="native" * @hibernate.generator-param name="sequence" value="CATISSUE_SPECIMEN_PROTOCOL_SEQ" * @return Returns the systemIdentifier. */ public Long getSystemIdentifier() { return systemIdentifier; } /** * @param systemIdentifier The systemIdentifier to set. */ public void setSystemIdentifier(Long systemIdentifier) { this.systemIdentifier = systemIdentifier; } /** * Returns the principal investigator of the protocol. * @hibernate.many-to-one column="PRINCIPAL_INVESTIGATOR_ID" class="edu.wustl.catissuecore.domain.User" * constrained="true" * @return the principal investigator of the protocol. * @see #setPrincipalInvestigator(User) */ public User getPrincipalInvestigator() { return principalInvestigator; } /** * @param principalInvestigator The principalInvestigator to set. */ public void setPrincipalInvestigator(User principalInvestigator) { this.principalInvestigator = principalInvestigator; } /** * Returns the title of the protocol. * @hibernate.property name="title" type="string" column="TITLE" length="50" not-null="true" unique="true" * @return Returns the title. */ public String getTitle() { return title; } /** * @param title The title to set. */ public void setTitle(String title) { this.title = title; } /** * Returns the short title of the protocol. * @hibernate.property name="shortTitle" type="string" column="SHORT_TITLE" * length="50" * @return Returns the shortTitle. */ public String getShortTitle() { return shortTitle; } /** * @param shortTitle The shortTitle to set. */ public void setShortTitle(String shortTitle) { this.shortTitle = shortTitle; } /** * Returns the irb systemIdentifier of the protocol. * @hibernate.property name="irbIdentifier" type="string" column="IRB_IDENTIFIER" length="50" * @return Returns the irbIdentifier. */ public String getIrbIdentifier() { return irbIdentifier; } /** * @param irbIdentifier The irbIdentifier to set. */ public void setIrbIdentifier(String irbIdentifier) { this.irbIdentifier = irbIdentifier; } /** * Returns the startdate of the protocol. * @hibernate.property name="startDate" type="date" column="START_DATE" length="50" * @return Returns the startDate. */ public Date getStartDate() { return startDate; } /** * @param startDate The startDate to set. */ public void setStartDate(Date startDate) { this.startDate = startDate; } /** * Returns the enddate of the protocol. * @hibernate.property name="endDate" type="date" column="END_DATE" length="50" * @return Returns the endDate. */ public Date getEndDate() { return endDate; } /** * @param endDate The endDate to set. */ public void setEndDate(Date endDate) { this.endDate = endDate; } /** * Returns the enrollment. * @hibernate.property name="enrollment" type="int" column="ENROLLMENT" length="50" * @return Returns the enrollment. */ public Integer getEnrollment() { return enrollment; } /** * @param enrollment The enrollment to set. */ public void setEnrollment(Integer enrollment) { this.enrollment = enrollment; } /** * Returns the descriptionURL. * @hibernate.property name="descriptionURL" type="string" column="DESCRIPTION_URL" length="200" * @return Returns the descriptionURL. */ public String getDescriptionURL() { return descriptionURL; } /** * @param descriptionURL The descriptionURL to set. */ public void setDescriptionURL(String descriptionURL) { this.descriptionURL = descriptionURL; } /** * Returns the activityStatus. * @hibernate.property name="activityStatus" type="string" column="ACTIVITY_STATUS" length="50" * @return Returns the activityStatus. */ public String getActivityStatus() { return activityStatus; } /** * @param activityStatus The activityStatus to set. */ public void setActivityStatus(String activityStatus) { this.activityStatus = activityStatus; } public void setAllValues(AbstractActionForm abstractForm) { Logger.out.debug("SpecimenProtocol: setAllValues "); try { SpecimenProtocolForm spForm = (SpecimenProtocolForm) abstractForm; this.title = spForm.getTitle(); this.shortTitle = spForm.getShortTitle(); this.irbIdentifier = spForm.getIrbID(); this.startDate = Utility.parseDate(spForm.getStartDate() ,Utility.datePattern(spForm.getStartDate())); this.endDate = Utility.parseDate(spForm.getEndDate(),Utility.datePattern(spForm.getEndDate())); if(spForm.getEnrollment() != null && spForm.getEnrollment().trim().length()>0 ) this.enrollment = new Integer(spForm.getEnrollment()); this.descriptionURL = spForm.getDescriptionURL(); this.activityStatus = spForm.getActivityStatus(); principalInvestigator = new User(); this.principalInvestigator.setSystemIdentifier(new Long(spForm.getPrincipalInvestigatorId())); } catch (Exception excp) { // use of logger as per bug 79 Logger.out.error(excp.getMessage(),excp); } } //SpecimenRequirement#FluidSpecimenRequirement:1.specimenType", "Blood"); protected Map fixMap(Map orgMap) { Map replaceMap = new HashMap(); Map unitMap = new HashMap(); unitMap.put("Cell","CellCount"); unitMap.put("Fluid","Milliliter"); unitMap.put("Tissue","Gram"); unitMap.put("Molecular","Microgram"); Iterator it = orgMap.keySet().iterator(); while(it.hasNext()) { String key = (String)it.next(); Logger.out.debug("Key************************"+key); if(key.indexOf("specimenClass")!=-1) { String value = (String)orgMap.get(key); Logger.out.debug("Value..........................."+value); String replaceWith = "SpecimenRequirement"+"#"+value+"SpecimenRequirement"; key = key.substring(0,key.lastIndexOf("_")); Logger.out.debug("Second Key***********************"+key); String newKey = key.replaceFirst("SpecimenRequirement",replaceWith); Logger.out.debug("New Key................"+newKey); replaceMap.put(key,newKey); } } Map newMap = new HashMap(); it = orgMap.keySet().iterator(); while(it.hasNext()) { String key = (String)it.next(); String value = (String)orgMap.get(key); Logger.out.debug("key "+key); if(key.indexOf("SpecimenRequirement")==-1) { newMap.put(key,value); } else { if(key.indexOf("specimenClass")==-1 && key.indexOf("unitspan")==-1) { String keyPart, newKeyPart; if(key.indexOf("quantityIn")!=-1) { keyPart = "quantityIn"; String searchKey = key.substring(0,key.lastIndexOf("_"))+"_specimenClass"; String specimenClass = (String)orgMap.get(searchKey); String unit = (String)unitMap.get(specimenClass); newKeyPart = keyPart + unit; key = key.replaceFirst(keyPart,newKeyPart); } //Replace # and class name and FIX for abstract class keyPart = key.substring(0,key.lastIndexOf("_")); newKeyPart = (String)replaceMap.get(keyPart); key = key.replaceFirst(keyPart,newKeyPart); newMap.put(key,value); } } } return newMap; } }
// WebSocketIO.java // Open XAL package xal.extension.service; import java.net.Socket; import java.io.*; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.security.*; import java.util.*; import javax.xml.bind.DatatypeConverter; /** Utility for processing messages passed through sockets on top of the WebSocket protocol */ class WebSocketIO { /** key with which to encode the web socket header key for completing the handshake */ static final private String HANDSHAKE_ENCODE_KEY = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; /** Send the handshake (from the client) generating a random security value and process the response. Returns true upon success. */ static boolean performHandshake( final Socket socket ) throws java.net.SocketException, java.io.IOException, SocketPrematurelyClosedException { sendHandshakeRequest( socket ); return processResponseHandshake( socket ); } /** Send the handshake (from the client) generating a random security value. Use this method when you don't need to valide the header response. */ static void sendHandshakeRequest( final Socket socket ) throws java.net.SocketException, java.io.IOException { sendHandshakeRequest( socket, new Random().nextLong() ); } /** Initiate the handshake (from the client) passing a random value for the security key. Use this method when you want to validate the header response. */ static void sendHandshakeRequest( final Socket socket, final long randomSecurityValue ) throws java.net.SocketException, java.io.IOException { final String randomKey = String.valueOf( randomSecurityValue ); final String encodedRandomKey = toBase64( randomKey ); // base64 encoded random key final Writer writer = new OutputStreamWriter( socket.getOutputStream() ); writer.write( "GET /stuff HTTP/1.1\r\n" ); writer.write( "Upgrade: websocket\r\n" ); writer.write( "Host: " + socket.getInetAddress().getHostName() + ":" + socket.getPort() + "\r\n" ); writer.write( "Origin: file: writer.write( "Sec-WebSocket-Key: " + encodedRandomKey + "\r\n" ); writer.write( "Sec-WebSocket-Version: 13\r\n" ); writer.write( "Origin: file: writer.write( "\r\n" ); writer.flush(); } /** process the handshake (on the server) */ static private boolean sendHandshakeResponse( final Socket socket, final String requestHeader ) throws java.net.SocketException, java.io.IOException { final Map<String,String> headerMap = new HashMap<>(); final BufferedReader reader = new BufferedReader( new StringReader( requestHeader ) ); while( true ) { final String line = reader.readLine(); if ( line != null ) { final String[] pair = line.split( ":" ); // key/value pair if ( pair.length == 2 ) { headerMap.put( pair[0].trim(), pair[1].trim() ); } } else { break; } } try { final String secWebSocketKey = headerMap.get( "Sec-WebSocket-Key" ); final String input_plus = secWebSocketKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; final MessageDigest messageDigest = MessageDigest.getInstance( "SHA-1" ); messageDigest.update( input_plus.getBytes( Charset.forName( "UTF-8" ) ) ); final String secWebSocketAccept = DatatypeConverter.printBase64Binary( messageDigest.digest() ); final Writer writer = new OutputStreamWriter( socket.getOutputStream() ); writer.write( "HTTP/1.1 101 Switching Protocols\r\n" ); writer.write( "Upgrade: websocket\r\n" ); writer.write( "Connection: Upgrade\r\n" ); writer.write( "Sec-WebSocket-Accept: " + secWebSocketAccept + "\r\n" ); writer.write( "Access-Control-Allow-Headers: content-type\r\n" ); writer.write( "\r\n" ); writer.flush(); return true; } catch ( NoSuchAlgorithmException exception ) { throw new RuntimeException( "Exception encoding websocket server handshake.", exception ); } } /** process the handshake with the socket */ static boolean processRequestHandshake( final Socket socket ) throws java.net.SocketException, java.io.IOException { final int BUFFER_SIZE = socket.getReceiveBufferSize(); final char[] streamBuffer = new char[BUFFER_SIZE]; final InputStream readStream = socket.getInputStream(); final BufferedReader reader = new BufferedReader( new InputStreamReader( readStream ) ); final StringBuilder inputBuffer = new StringBuilder(); do { final int readCount = reader.read( streamBuffer, 0, BUFFER_SIZE ); if ( readCount == -1 ) { // the session has been closed throw new RuntimeException( "The remote socket has closed while reading the remote response..." ); } else if ( readCount > 0 ) { inputBuffer.append( streamBuffer, 0, readCount ); } } while ( reader.ready() || readStream.available() > 0 ); return sendHandshakeResponse( socket, inputBuffer.toString() ); } /** process the handshake response for the socket without any validation */ static boolean processResponseHandshake( final Socket socket ) throws java.net.SocketException, java.io.IOException, WebSocketIO.SocketPrematurelyClosedException { final int BUFFER_SIZE = socket.getReceiveBufferSize(); final char[] streamBuffer = new char[BUFFER_SIZE]; final InputStream readStream = socket.getInputStream(); final BufferedReader reader = new BufferedReader( new InputStreamReader( readStream ) ); final StringBuilder inputBuffer = new StringBuilder(); // empty out the buffer and store the header info do { final int readCount = reader.read( streamBuffer, 0, BUFFER_SIZE ); if ( readCount == -1 ) { // the session has been closed throw new SocketPrematurelyClosedException( "The remote socket has closed while reading the remote response..." ); } else if ( readCount > 0 ) { inputBuffer.append( streamBuffer, 0, readCount ); } } while ( reader.ready() || readStream.available() > 0 ); // TODO: might want to validate the response handshake return true; } /** send the message */ static void sendMessage( final Socket socket, final String message ) throws java.net.SocketException, java.io.IOException { //System.out.println( "Sending message of length: " + message.length() ); final OutputStream output = socket.getOutputStream(); final byte opcode = 1; // response is text final int byte1 = opcode | 0b10000000; output.write( byte1 ); final int messageLength = message.length(); if ( messageLength < 126 ) { output.write( messageLength ); } else if ( messageLength < 65536 ) { output.write( 126 ); // write the length as two bytes try { short shortLen = (short)messageLength; final byte[] lenBytes = new byte[2]; final ByteBuffer lenByteBuffer = ByteBuffer.wrap( lenBytes ); lenByteBuffer.putShort( 0, shortLen ); output.write( lenBytes, 0, 2 ); } catch( RuntimeException exception ) { System.err.println( "Exception writing short message length: " + exception ); exception.printStackTrace(); throw exception; } } else { output.write( 127 ); // write the length as 8 bytes try { long longLen = (long)messageLength; final byte[] lenBytes = new byte[8]; final ByteBuffer lenByteBuffer = ByteBuffer.wrap( lenBytes ); lenByteBuffer.putLong( 0, longLen ); output.write( lenBytes, 0, 8 ); } catch( RuntimeException exception ) { System.err.println( "Exception writing long message length: " + exception ); exception.printStackTrace(); throw exception; } } // write the raw message final byte[] messageBytes = message.getBytes( Charset.forName( "UTF-8" ) ); output.write( messageBytes, 0, messageBytes.length ); output.flush(); } /** Read the message from the socket and return it */ static String readMessage( final Socket socket ) throws java.net.SocketException, java.io.IOException, WebSocketIO.SocketPrematurelyClosedException { //System.out.println( "Reading message..." ); final int BUFFER_SIZE = socket.getReceiveBufferSize(); final InputStream readStream = socket.getInputStream(); final StreamByteReader byteReader = new StreamByteReader( readStream, BUFFER_SIZE ); try { final byte head1 = byteReader.nextByte(); final byte head2 = byteReader.nextByte(); final boolean fin = ( head1 & 0b10000000 ) == 0b10000000; final byte opcode = (byte)( head1 & 0b00001111 ); final boolean masked = ( head2 & 0b10000000 ) == 0b10000000; final byte lengthCode = (byte)( head2 & 0b01111111 ); //System.out.println( "fin: " + fin + ", opcode: " + opcode + ", masked: " + masked + ", length code: " + lengthCode ); int dataLength = 0; switch ( lengthCode ) { case 126: // payload length defined by next 2 bytes try { final byte[] lenBytes = byteReader.nextBytes( 2 ); final ByteBuffer lenByteBuffer = ByteBuffer.wrap( lenBytes ); dataLength = lenByteBuffer.getShort(); } catch( RuntimeException exception ) { System.err.println( "Exception getting short message length: " + exception ); exception.printStackTrace(); throw exception; } break; case 127: // payload length defined by next 8 bytes // TODO: Need to handle true 8 byte lengths. Java only accepts 4 byte lengths (i.e. int) for arrays, so the following code really only supports processing 4 byte lengths even though it reads the 8 byte length. try { final byte[] lenBytes = byteReader.nextBytes( 8 ); final ByteBuffer lenByteBuffer = ByteBuffer.wrap( lenBytes ); dataLength = (int)lenByteBuffer.getLong(); // cast the long to int since arrays only allow 32 bit lengths } catch( RuntimeException exception ) { System.err.println( "Exception getting long message length: " + exception ); exception.printStackTrace(); throw exception; } break; default: // payload length is simply the lengthCode itself dataLength = lengthCode; break; } // TODO: need to check the fin bit to see whether more data is coming // TODO: need to check the opcode to see what kind of data has arrived (e.g. continuation, text, data, ping or pong) final StringBuilder resultBuilder = new StringBuilder(); PayloadReader payloadReader = PayloadReader.getInstance(); if ( masked ) { final byte[] mask = byteReader.nextBytes( 4 ); payloadReader = new MaskPayloadReader( mask ); } try { final byte[] dataBytes = byteReader.nextBytes( dataLength ); for ( int index = 0 ; index < dataBytes.length ; index++ ) { int charCode = payloadReader.readCharCode( dataBytes, index ); final char[] chars = Character.toChars( charCode ); resultBuilder.append( chars ); } } catch( Exception exception ) { System.err.println( "Exception reading characters: " + exception ); exception.printStackTrace(); } return resultBuilder.toString(); } catch( StreamByteReader.StreamPrematurelyClosedException exception ) { throw new SocketPrematurelyClosedException( "The remote socket has closed while reading the message..." ); } } /** Encode the the specified input string as Base64 */ static private String toBase64( final String input ) { final byte[] rawInputBytes = input.getBytes( Charset.forName( "UTF-8" ) ); return DatatypeConverter.printBase64Binary( rawInputBytes ); } /** Exception indicating that the socket closed prematurely */ static public class SocketPrematurelyClosedException extends Exception { /** required serial version ID */ static final long serialVersionUID = 0L; /** Constructor */ public SocketPrematurelyClosedException( final String message ) { super( message ); } } } /** Reads the payload directly without masking */ class PayloadReader { /** direct reader singleton */ final private static PayloadReader DEFAULT_READER = new PayloadReader(); /** get the default instance */ static public PayloadReader getInstance() { return DEFAULT_READER; } /** read the specified character directly */ public int readCharCode( final byte[] inputBuffer, final int index ) { return inputBuffer[index]; } } /** Reads the payload when there is a mask */ class MaskPayloadReader extends PayloadReader { /** mask to use */ final private byte[] MASK; /** Constructor */ public MaskPayloadReader( final byte[] mask ) { MASK = mask; } /** read the specified character and mask it */ public int readCharCode( final byte[] inputBuffer, final int index ) { return MASK[index%4] ^ inputBuffer[index]; } } /** read bytes from a stream as requested */ class StreamByteReader { /** stream of data from which to read */ final private InputStream SOURCE_STREAM; /** buffer size for reading from the stream */ final private int BUFFER_SIZE; /** current position */ private int _position; /** stack of bytes */ private byte[] _byteStack; /** Constructor */ public StreamByteReader( final InputStream inputStream, final int bufferSize ) { SOURCE_STREAM = inputStream; BUFFER_SIZE = bufferSize; _position = 0; _byteStack = new byte[0]; } /** read the next byte waiting for data from the stream if necessary */ public byte nextByte() throws java.io.IOException, StreamPrematurelyClosedException { final int position = _position; if ( position < _byteStack.length ) { final byte nextByte = _byteStack[position]; _position += 1; return nextByte; } else { final byte[] streamBuffer = new byte[BUFFER_SIZE]; final InputStream readStream = SOURCE_STREAM; final BufferedInputStream reader = new BufferedInputStream( readStream ); final ByteArrayOutputStream rawByteBuffer = new ByteArrayOutputStream(); do { final int readCount = reader.read( streamBuffer, 0, BUFFER_SIZE ); if ( readCount == -1 ) { // the session has been closed throw new StreamPrematurelyClosedException( "The stream has closed while reading the remote response..." ); } else if ( readCount > 0 ) { rawByteBuffer.write( streamBuffer, 0, readCount ); } } while ( readStream.available() > 0 ); _byteStack = rawByteBuffer.toByteArray(); _position = 0; return nextByte(); } } /** read and return the next specified count of bytes */ public byte[] nextBytes( final int count ) throws java.io.IOException, StreamPrematurelyClosedException { final byte[] result = new byte[count]; nextBytes( result ); return result; } /** read the next bytes into the specified destination */ public void nextBytes( final byte[] destination ) throws java.io.IOException, StreamPrematurelyClosedException { nextBytes( destination, 0, destination.length ); } /** read the next bytes into the specified destination */ public void nextBytes( final byte[] destination, final int offset, final int count ) throws java.io.IOException, StreamPrematurelyClosedException { int position = offset; for ( int index = 0 ; index < count ; index++ ) { destination[position++] = nextByte(); } } /** Exception indicating that the socket closed prematurely */ static public class StreamPrematurelyClosedException extends Exception { /** required serial version ID */ static final long serialVersionUID = 0L; /** Constructor */ public StreamPrematurelyClosedException( final String message ) { super( message ); } } }
package edu.umd.cs.findbugs.detect; import java.util.HashSet; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.CodeException; import org.apache.bcel.classfile.Constant; import org.apache.bcel.classfile.ConstantClass; import org.apache.bcel.classfile.ConstantPool; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.ObjectType; import org.apache.bcel.generic.ReferenceType; import org.apache.bcel.generic.Type; import edu.umd.cs.findbugs.BugAccumulator; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.BytecodeScanningDetector; import edu.umd.cs.findbugs.JavaVersion; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.CFGBuilderException; import edu.umd.cs.findbugs.ba.DataflowAnalysisException; import edu.umd.cs.findbugs.ba.Hierarchy; import edu.umd.cs.findbugs.ba.ObjectTypeFactory; import edu.umd.cs.findbugs.ba.type.TypeDataflow; public class DumbMethods extends BytecodeScanningDetector { private static final ObjectType CONDITION_TYPE = ObjectTypeFactory.getInstance("java.util.concurrent.locks.Condition"); private HashSet<String> alreadyReported = new HashSet<String>(); private BugReporter bugReporter; private boolean sawCurrentTimeMillis; private BugInstance gcInvocationBugReport; private int gcInvocationPC; private CodeException[] exceptionTable; /* private boolean sawLDCEmptyString; */ private String primitiveObjCtorSeen; private boolean ctorSeen; private boolean prevOpcodeWasReadLine; private int prevOpcode; private boolean isPublicStaticVoidMain; private boolean isEqualsObject; private boolean sawInstanceofCheck; private boolean reportedBadCastInEquals; private int randomNextIntState; private boolean checkForBitIorofSignedByte; private boolean jdk15ChecksEnabled; private BugAccumulator accumulator; public DumbMethods(BugReporter bugReporter) { this.bugReporter = bugReporter; accumulator = new BugAccumulator(bugReporter); jdk15ChecksEnabled = JavaVersion.getRuntimeVersion().isSameOrNewerThan(JavaVersion.JAVA_1_5); } OpcodeStack stack = new OpcodeStack(); @Override public void visitAfter(JavaClass obj) { accumulator.reportAccumulatedBugs(); } @Override public void visit(Method method) { String cName = getDottedClassName(); stack.resetForMethodEntry(this); isPublicStaticVoidMain = method.isPublic() && method.isStatic() && getMethodName().equals("main") || cName.toLowerCase().indexOf("benchmark") >= 0; prevOpcodeWasReadLine = false; pendingRemOfRandomIntBug = null; Code code = method.getCode(); if (code != null) this.exceptionTable = code.getExceptionTable(); if (this.exceptionTable == null) this.exceptionTable = new CodeException[0]; primitiveObjCtorSeen = null; ctorSeen = false; randomNextIntState = 0; checkForBitIorofSignedByte = false; isEqualsObject = getMethodName().equals("equals") && getMethodSig().equals("(Ljava/lang/Object;)Z") && !method.isStatic(); sawInstanceofCheck = false; reportedBadCastInEquals = false; } BugInstance pendingRemOfRandomIntBug; @Override public void sawOpcode(int seen) { stack.mergeJumps(this); if (isEqualsObject && !reportedBadCastInEquals) { if (seen == INSTANCEOF || seen == INVOKEVIRTUAL && getNameConstantOperand().equals("getClass") && getSigConstantOperand().equals("()Ljava/lang/Class;") ) { OpcodeStack.Item item = stack.getStackItem(0); if (item.getRegisterNumber() == 1) sawInstanceofCheck = true; } else if (seen == INVOKESPECIAL && getNameConstantOperand().equals("equals") && getSigConstantOperand().equals("(Ljava/lang/Object;)Z")) { OpcodeStack.Item item0 = stack.getStackItem(0); OpcodeStack.Item item1 = stack.getStackItem(1); if (item1.getRegisterNumber() + item0.getRegisterNumber() == 1) sawInstanceofCheck = true; } else if (seen == CHECKCAST && !sawInstanceofCheck) { OpcodeStack.Item item = stack.getStackItem(0); if (item.getRegisterNumber() == 1) { if (getSizeOfSurroundingTryBlock(getPC()) == Integer.MAX_VALUE) bugReporter.reportBug(new BugInstance(this, "BC_EQUALS_METHOD_SHOULD_WORK_FOR_ALL_OBJECTS", NORMAL_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); reportedBadCastInEquals = true; } } } { boolean foundVacuousComparison = false; if (seen == IF_ICMPGT || seen == IF_ICMPLE) { OpcodeStack.Item rhs = stack.getStackItem(0); Object rhsConstant = rhs.getConstant(); if (rhsConstant instanceof Integer && ((Integer)rhsConstant).intValue() == Integer.MAX_VALUE) foundVacuousComparison = true; OpcodeStack.Item lhs = stack.getStackItem(1); Object lhsConstant = lhs.getConstant(); if (lhsConstant instanceof Integer && ((Integer)lhsConstant).intValue() == Integer.MIN_VALUE) foundVacuousComparison = true; } if (seen == IF_ICMPLT || seen == IF_ICMPGE) { OpcodeStack.Item rhs = stack.getStackItem(0); Object rhsConstant = rhs.getConstant(); if (rhsConstant instanceof Integer && ((Integer)rhsConstant).intValue() == Integer.MIN_VALUE) foundVacuousComparison = true; OpcodeStack.Item lhs = stack.getStackItem(1); Object lhsConstant = lhs.getConstant(); if (lhsConstant instanceof Integer && ((Integer)lhsConstant).intValue() == Integer.MAX_VALUE) foundVacuousComparison = true; } if (foundVacuousComparison) bugReporter.reportBug(new BugInstance(this, "INT_VACUOUS_COMPARISON", getBranchOffset() < 0 ? HIGH_PRIORITY : NORMAL_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); } if (pendingRemOfRandomIntBug != null && !(seen == INVOKESTATIC && getClassConstantOperand().equals("java/lang/Math") && getNameConstantOperand().equals("abs"))) bugReporter.reportBug(pendingRemOfRandomIntBug); if (seen == INVOKESTATIC && ( getClassConstantOperand().equals("java/lang/Math") || getClassConstantOperand().equals("java/lang/StrictMath")) && getNameConstantOperand().equals("abs") && getSigConstantOperand().equals("(I)I")) { OpcodeStack.Item item0 = stack.getStackItem(0); int special = item0.getSpecialKind(); if (special == OpcodeStack.Item.RANDOM_INT) bugReporter.reportBug(new BugInstance(this, "RV_ABSOLUTE_VALUE_OF_RANDOM_INT", HIGH_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); else if (special == OpcodeStack.Item.HASHCODE_INT) bugReporter.reportBug(new BugInstance(this, "RV_ABSOLUTE_VALUE_OF_HASHCODE", HIGH_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); } try { if (seen == IREM) { OpcodeStack.Item item0 = stack.getStackItem(0); Object constant0 = item0.getConstant(); OpcodeStack.Item item1 = stack.getStackItem(1); int special = item1.getSpecialKind(); if (special == OpcodeStack.Item.RANDOM_INT) { pendingRemOfRandomIntBug = new BugInstance(this, "RV_REM_OF_RANDOM_INT", HIGH_PRIORITY) .addClassAndMethod(this) .addSourceLine(this); } else if (special == OpcodeStack.Item.HASHCODE_INT) { pendingRemOfRandomIntBug = new BugInstance(this, "RV_REM_OF_HASHCODE", HIGH_PRIORITY) .addClassAndMethod(this) .addSourceLine(this); } else if (constant0 instanceof Integer && ((Integer)constant0).intValue() == 1) bugReporter.reportBug(new BugInstance(this, "INT_BAD_REM_BY_1", HIGH_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); } if (stack.getStackDepth() >= 1 && (seen == LOOKUPSWITCH || seen == TABLESWITCH)) { OpcodeStack.Item item0 = stack.getStackItem(0); if (item0.getSpecialKind() == OpcodeStack.Item.SIGNED_BYTE) { int[] switchLabels = getSwitchLabels(); int [] switchOffsets = getSwitchOffsets(); for(int i = 0; i < switchLabels.length; i++) { int v = switchLabels[i]; if (v <= -129 || v >= 128) bugReporter.reportBug(new BugInstance(this, "INT_BAD_COMPARISON_WITH_SIGNED_BYTE", HIGH_PRIORITY) .addClassAndMethod(this) .addInt(v) .addSourceLine(this, getPC() + switchOffsets[i])); } } } // check for use of signed byte where is it assumed it can be out of the -128...127 range if (stack.getStackDepth() >= 2) switch (seen) { case IF_ICMPEQ: case IF_ICMPNE: case IF_ICMPLT: case IF_ICMPLE: case IF_ICMPGE: case IF_ICMPGT: OpcodeStack.Item item0 = stack.getStackItem(0); OpcodeStack.Item item1 = stack.getStackItem(1); int seen2 = seen; if (item1.getSpecialKind() == OpcodeStack.Item.SIGNED_BYTE) { OpcodeStack.Item tmp = item0; item0 = item1; item1 = tmp; if (seen >= IF_ICMPLT && seen <= IF_ICMPGE) seen2 += 2; else if (seen >= IF_ICMPGT && seen <= IF_ICMPLE) seen2 -= 2; } Object constant1 = item1.getConstant(); if (item0.getSpecialKind() == OpcodeStack.Item.SIGNED_BYTE && constant1 instanceof Number) { int v1 = ((Number)constant1).intValue(); if (v1 <= -129 || v1 >= 128 || v1 == 127 && !(seen2 == IF_ICMPEQ || seen2 == IF_ICMPNE )) { int priority = HIGH_PRIORITY; if (v1 == 127 && seen2 == IF_ICMPLE ) priority = NORMAL_PRIORITY; if (v1 == 128 && seen2 == IF_ICMPLE) priority = NORMAL_PRIORITY; if (v1 <= -129) priority = NORMAL_PRIORITY; bugReporter.reportBug(new BugInstance(this, "INT_BAD_COMPARISON_WITH_SIGNED_BYTE", priority) .addClassAndMethod(this) .addInt(v1) .addSourceLine(this)); } } } if (checkForBitIorofSignedByte && seen != I2B) { bugReporter.reportBug(new BugInstance(this, "BIT_IOR_OF_SIGNED_BYTE", prevOpcode == LOR ? HIGH_PRIORITY : NORMAL_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); checkForBitIorofSignedByte = false; } else if ((seen == IOR || seen == LOR) && stack.getStackDepth() >= 2) { OpcodeStack.Item item0 = stack.getStackItem(0); OpcodeStack.Item item1 = stack.getStackItem(1); int special0 = item0.getSpecialKind(); int special1 = item1.getSpecialKind(); if (special0 == OpcodeStack.Item.SIGNED_BYTE && special1 == OpcodeStack.Item.LOW_8_BITS_CLEAR || special0 == OpcodeStack.Item.LOW_8_BITS_CLEAR && special1 == OpcodeStack.Item.SIGNED_BYTE ) checkForBitIorofSignedByte = true; else checkForBitIorofSignedByte = false; } else checkForBitIorofSignedByte = false; if (prevOpcodeWasReadLine && seen == INVOKEVIRTUAL && getClassConstantOperand().equals("java/lang/String")) { bugReporter.reportBug(new BugInstance(this, "NP_IMMEDIATE_DEREFERENCE_OF_READLINE", NORMAL_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); } prevOpcodeWasReadLine = (seen == INVOKEVIRTUAL||seen == INVOKEINTERFACE) && getNameConstantOperand().equals("readLine") && getSigConstantOperand().equals("()Ljava/lang/String;"); // System.out.println(randomNextIntState + " " + OPCODE_NAMES[seen] + " " + getMethodName()); switch(randomNextIntState) { case 0: if (seen == INVOKEVIRTUAL && getClassConstantOperand().equals("java/util/Random") && getNameConstantOperand().equals("nextDouble") || seen == INVOKESTATIC && getClassConstantOperand().equals("java/lang/Math") && getNameConstantOperand().equals("random")) randomNextIntState = 1; break; case 1: if (seen == D2I) { bugReporter.reportBug(new BugInstance(this, "RV_01_TO_INT", HIGH_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); randomNextIntState = 0; } else if (seen == DMUL) randomNextIntState = 4; else randomNextIntState = 2; break; case 2: if (seen == I2D) randomNextIntState = 3; else if (seen == DMUL) randomNextIntState = 4; else randomNextIntState = 0; break; case 3: if (seen == DMUL) randomNextIntState = 4; else randomNextIntState = 0; break; case 4: if (seen == D2I) bugReporter.reportBug(new BugInstance(this, "DM_NEXTINT_VIA_NEXTDOUBLE", NORMAL_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); randomNextIntState = 0; break; default: throw new IllegalStateException(); } if (isPublicStaticVoidMain && seen == INVOKEVIRTUAL && getClassConstantOperand().startsWith("javax/swing/") && (getNameConstantOperand().equals("show") && getSigConstantOperand().equals("()V") || getNameConstantOperand().equals("pack") && getSigConstantOperand().equals("()V") || getNameConstantOperand().equals("setVisible") && getSigConstantOperand().equals("(Z)V"))) bugReporter.reportBug(new BugInstance(this, "SW_SWING_METHODS_INVOKED_IN_SWING_THREAD", LOW_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); // if ((seen == INVOKEVIRTUAL) // && getClassConstantOperand().equals("java/lang/String") // && getNameConstantOperand().equals("substring") // && getSigConstantOperand().equals("(I)Ljava/lang/String;") // && stack.getStackDepth() > 1) { // OpcodeStack.Item item = stack.getStackItem(0); // Object o = item.getConstant(); // if (o != null && o instanceof Integer) { // int v = ((Integer) o).intValue(); // if (v == 0) // bugReporter.reportBug(new BugInstance(this, "DMI_USELESS_SUBSTRING", NORMAL_PRIORITY) // .addClassAndMethod(this) // .addSourceLine(this)); if ((seen == INVOKEVIRTUAL) && getNameConstantOperand().equals("isAnnotationPresent") && getSigConstantOperand().equals("(Ljava/lang/Class;)Z") && stack.getStackDepth() > 0) { OpcodeStack.Item item = stack.getStackItem(0); Object value = item.getConstant(); if (value instanceof String) { String annotationClassName = (String) value; boolean lacksClassfileRetention = AnalysisContext.currentAnalysisContext().getAnnotationRetentionDatabase().lacksClassfileRetention( annotationClassName.replace('/','.')); if (lacksClassfileRetention) bugReporter.reportBug(new BugInstance(this, "DMI_ANNOTATION_IS_NOT_VISIBLE_TO_REFLECTION", HIGH_PRIORITY) .addClassAndMethod(this) .addSourceLine(this) .addCalledMethod(this)); } } if ((seen == INVOKEVIRTUAL) && getNameConstantOperand().equals("next") && getSigConstantOperand().equals("()Ljava/lang/Object;") && getMethodName().equals("hasNext") && getMethodSig().equals("()Z") && stack.getStackDepth() > 0) { OpcodeStack.Item item = stack.getStackItem(0); bugReporter.reportBug(new BugInstance(this, "DMI_CALLING_NEXT_FROM_HASNEXT", item.isInitialParameter() && item.getRegisterNumber() == 0 ? NORMAL_PRIORITY : LOW_PRIORITY) .addClassAndMethod(this) .addSourceLine(this) .addCalledMethod(this)); } if ((seen == INVOKESPECIAL) && getClassConstantOperand().equals("java/lang/String") && getNameConstantOperand().equals("<init>") && getSigConstantOperand().equals("(Ljava/lang/String;)V")) if (alreadyReported.add(getRefConstantOperand())) bugReporter.reportBug(new BugInstance(this, "DM_STRING_CTOR", NORMAL_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); if (seen == INVOKESTATIC && getClassConstantOperand().equals("java/lang/System") && getNameConstantOperand().equals("runFinalizersOnExit") || seen == INVOKEVIRTUAL && getClassConstantOperand().equals("java/lang/Runtime") && getNameConstantOperand().equals("runFinalizersOnExit")) bugReporter.reportBug(new BugInstance(this, "DM_RUN_FINALIZERS_ON_EXIT", HIGH_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); if ((seen == INVOKESPECIAL) && getClassConstantOperand().equals("java/lang/String") && getNameConstantOperand().equals("<init>") && getSigConstantOperand().equals("()V")) if (alreadyReported.add(getRefConstantOperand())) bugReporter.reportBug(new BugInstance(this, "DM_STRING_VOID_CTOR", NORMAL_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); if (!isPublicStaticVoidMain && seen == INVOKESTATIC && getClassConstantOperand().equals("java/lang/System") && getNameConstantOperand().equals("exit") && !getMethodName().equals("processWindowEvent") && !getMethodName().startsWith("windowClos") && getMethodName().indexOf("exit") == -1 && getMethodName().indexOf("Exit") == -1 && getMethodName().indexOf("crash") == -1 && getMethodName().indexOf("Crash") == -1 && getMethodName().indexOf("die") == -1 && getMethodName().indexOf("Die") == -1 && getMethodName().indexOf("main") == -1) accumulator.accumulateBug(new BugInstance(this, "DM_EXIT", getMethod().isStatic() ? LOW_PRIORITY : NORMAL_PRIORITY) .addClassAndMethod(this), SourceLineAnnotation.fromVisitedInstruction(this)); if (((seen == INVOKESTATIC && getClassConstantOperand().equals("java/lang/System")) || (seen == INVOKEVIRTUAL && getClassConstantOperand().equals("java/lang/Runtime"))) && getNameConstantOperand().equals("gc") && getSigConstantOperand().equals("()V") && !getDottedClassName().startsWith("java.lang") && !getMethodName().startsWith("gc") && !getMethodName().endsWith("gc")) if (alreadyReported.add(getRefConstantOperand())) { // System.out.println("Saw call to GC"); if (isPublicStaticVoidMain) { // System.out.println("Skipping GC complaint in main method"); return; } // Just save this report in a field; it will be flushed // IFF there were no calls to System.currentTimeMillis(); // in the method. gcInvocationBugReport = new BugInstance(this, "DM_GC", HIGH_PRIORITY) .addClassAndMethod(this) .addSourceLine(this); gcInvocationPC = getPC(); //System.out.println("GC invocation at pc " + PC); } if ((seen == INVOKESPECIAL) && getClassConstantOperand().equals("java/lang/Boolean") && getNameConstantOperand().equals("<init>") && !getClassName().equals("java/lang/Boolean") ) if (alreadyReported.add(getRefConstantOperand())) bugReporter.reportBug(new BugInstance(this, "DM_BOOLEAN_CTOR", NORMAL_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); if ((seen == INVOKESTATIC) && getClassConstantOperand().equals("java/lang/System") && (getNameConstantOperand().equals("currentTimeMillis") || getNameConstantOperand().equals("nanoTime"))) sawCurrentTimeMillis = true; if ((seen == INVOKEVIRTUAL) && getClassConstantOperand().equals("java/lang/String") && getNameConstantOperand().equals("toString") && getSigConstantOperand().equals("()Ljava/lang/String;")) if (alreadyReported.add(getRefConstantOperand())) bugReporter.reportBug(new BugInstance(this, "DM_STRING_TOSTRING", NORMAL_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); if ((seen == INVOKEVIRTUAL) && getClassConstantOperand().equals("java/lang/String") && (getNameConstantOperand().equals("toUpperCase") || getNameConstantOperand().equals("toLowerCase")) && getSigConstantOperand().equals("()Ljava/lang/String;")) if (alreadyReported.add(getRefConstantOperand())) bugReporter.reportBug(new BugInstance(this, "DM_CONVERT_CASE", LOW_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); if ((seen == INVOKESPECIAL) && getNameConstantOperand().equals("<init>")) { String cls = getClassConstantOperand(); String sig = getSigConstantOperand(); if ((cls.equals("java/lang/Integer") && sig.equals("(I)V")) || (cls.equals("java/lang/Float") && sig.equals("(F)V")) || (cls.equals("java/lang/Double") && sig.equals("(D)V")) || (cls.equals("java/lang/Long") && sig.equals("(J)V")) || (cls.equals("java/lang/Byte") && sig.equals("(B)V")) || (cls.equals("java/lang/Character") && sig.equals("(C)V")) || (cls.equals("java/lang/Short") && sig.equals("(S)V")) || (cls.equals("java/lang/Boolean") && sig.equals("(Z)V"))) { primitiveObjCtorSeen = cls; } else { primitiveObjCtorSeen = null; } } else if ((primitiveObjCtorSeen != null) && (seen == INVOKEVIRTUAL) && getNameConstantOperand().equals("toString") && getClassConstantOperand().equals(primitiveObjCtorSeen) && getSigConstantOperand().equals("()Ljava/lang/String;")) { bugReporter.reportBug(new BugInstance(this, "DM_BOXED_PRIMITIVE_TOSTRING", LOW_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); primitiveObjCtorSeen = null; } else primitiveObjCtorSeen = null; if ((seen == INVOKESPECIAL) && getNameConstantOperand().equals("<init>")) { ctorSeen = true; } else if (ctorSeen && (seen == INVOKEVIRTUAL) && getClassConstantOperand().equals("java/lang/Object") && getNameConstantOperand().equals("getClass") && getSigConstantOperand().equals("()Ljava/lang/Class;")) { accumulator.accumulateBug(new BugInstance(this, "DM_NEW_FOR_GETCLASS", LOW_PRIORITY) .addClassAndMethod(this), this); ctorSeen = false; } else { ctorSeen = false; } if (jdk15ChecksEnabled && (seen == INVOKEVIRTUAL) && isMonitorWait(getNameConstantOperand(), getSigConstantOperand())) { checkMonitorWait(); } if ((seen == INVOKESPECIAL) && getNameConstantOperand().equals("<init>") && getClassConstantOperand().equals("java/lang/Thread")) { String sig = getSigConstantOperand(); if (sig.equals("()V") || sig.equals("(Ljava/lang/String;)V") || sig.equals("(Ljava/lang/ThreadGroup;Ljava/lang/String;)V")) if (!getMethodName().equals("<init>") || (getPC() > 20)) { bugReporter.reportBug(new BugInstance(this, "DM_USELESS_THREAD", LOW_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); } } /* // // TODO: put this back in when we have a standard way // of enabling and disabling warnings on a per-bug-pattern // basis. // if ((seen == INVOKEVIRTUAL) && sawLDCEmptyString && getNameConstantOperand().equals("equals")) bugReporter.reportBug(new BugInstance("DM_STRING_EMPTY_EQUALS", LOW_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); if ((seen == LDC) && (getConstantRefOperand() instanceof ConstantString) && (getStringConstantOperand().length() == 0)) sawLDCEmptyString = true; else sawLDCEmptyString = false; */ } finally { stack.sawOpcode(this,seen); prevOpcode = seen; } } private void checkMonitorWait() { try { TypeDataflow typeDataflow = getClassContext().getTypeDataflow(getMethod()); TypeDataflow.LocationAndFactPair pair = typeDataflow.getLocationAndFactForInstruction(getPC()); if (pair == null) return; Type receiver = pair.frame.getInstance( pair.location.getHandle().getInstruction(), getClassContext().getConstantPoolGen() ); if (!(receiver instanceof ReferenceType)) return; if (Hierarchy.isSubtype((ReferenceType) receiver, CONDITION_TYPE)) { bugReporter.reportBug(new BugInstance("DM_MONITOR_WAIT_ON_CONDITION", HIGH_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); } } catch (ClassNotFoundException e) { bugReporter.reportMissingClass(e); } catch (DataflowAnalysisException e) { bugReporter.logError("Exception caught by DumbMethods", e); } catch (CFGBuilderException e) { bugReporter.logError("Exception caught by DumbMethods", e); } } private boolean isMonitorWait(String name, String sig) { // System.out.println("Check call " + name + "," + sig); return name.equals("wait") && (sig.equals("()V") || sig.equals("(J)V") || sig.equals("(JI)V")); } @Override public void visit(Code obj) { super.visit(obj); flush(); } /** * A heuristic - how long a catch block for OutOfMemoryError might be. */ private static final int OOM_CATCH_LEN = 20; /** * Flush out cached state at the end of a method. */ private void flush() { if (gcInvocationBugReport != null && !sawCurrentTimeMillis) { // Make sure the GC invocation is not in an exception handler // for OutOfMemoryError. boolean outOfMemoryHandler = false; for (CodeException handler : exceptionTable) { if (gcInvocationPC < handler.getHandlerPC() || gcInvocationPC > handler.getHandlerPC() + OOM_CATCH_LEN) continue; int catchTypeIndex = handler.getCatchType(); if (catchTypeIndex > 0) { ConstantPool cp = getThisClass().getConstantPool(); Constant constant = cp.getConstant(catchTypeIndex); if (constant instanceof ConstantClass) { String exClassName = (String) ((ConstantClass) constant).getConstantValue(cp); if (exClassName.equals("java/lang/OutOfMemoryError")) { outOfMemoryHandler = true; break; } } } } if (!outOfMemoryHandler) bugReporter.reportBug(gcInvocationBugReport); } sawCurrentTimeMillis = false; gcInvocationBugReport = null; alreadyReported.clear(); exceptionTable = null; } }
package com.yahoo.vespa.flags; import com.yahoo.vespa.flags.custom.ClusterCapacity; import com.yahoo.vespa.flags.custom.SharedHost; import java.time.Instant; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.CLUSTER_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.CLUSTER_TYPE; import static com.yahoo.vespa.flags.FetchVector.Dimension.CONSOLE_USER_EMAIL; import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME; import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE; import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID; /** * Definition for permanent feature flags * * @author bjorncs */ public class PermanentFlags { static final List<String> OWNERS = List.of(); static final Instant CREATED_AT = Instant.EPOCH; static final Instant EXPIRES_AT = ZonedDateTime.of(2100, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC).toInstant(); public static final UnboundBooleanFlag USE_ALTERNATIVE_ENDPOINT_CERTIFICATE_PROVIDER = defineFeatureFlag( "use-alternative-endpoint-certificate-provider", false, "Whether to use an alternative CA when provisioning new certificates", "Takes effect only on initial application deployment - not on later certificate refreshes!"); public static final UnboundStringFlag JVM_GC_OPTIONS = defineStringFlag( "jvm-gc-options", "", "Sets default jvm gc options", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag FLEET_CANARY = defineFeatureFlag( "fleet-canary", false, "Whether the host is a fleet canary.", "Takes effect on next host admin tick.", HOSTNAME); public static final UnboundListFlag<ClusterCapacity> PREPROVISION_CAPACITY = defineListFlag( "preprovision-capacity", List.of(), ClusterCapacity.class, "Specifies the resources that ought to be immediately available for additional cluster " + "allocations. If the resources are not available, additional hosts will be provisioned. " + "Only applies to dynamically provisioned zones.", "Takes effect on next iteration of DynamicProvisioningMaintainer."); public static final UnboundIntFlag REBOOT_INTERVAL_IN_DAYS = defineIntFlag( "reboot-interval-in-days", 15, "No reboots are scheduled 0x-1x reboot intervals after the previous reboot, while reboot is " + "scheduled evenly distributed in the 1x-2x range (and naturally guaranteed at the 2x boundary).", "Takes effect on next run of NodeRebooter"); public static final UnboundJacksonFlag<SharedHost> SHARED_HOST = defineJacksonFlag( "shared-host", SharedHost.createDisabled(), SharedHost.class, "Specifies whether shared hosts can be provisioned, and if so, the advertised " + "node resources of the host, the maximum number of containers, etc.", "Takes effect on next iteration of DynamicProvisioningMaintainer."); public static final UnboundBooleanFlag SKIP_MAINTENANCE_DEPLOYMENT = defineFeatureFlag( "node-repository-skip-maintenance-deployment", false, "Whether PeriodicApplicationMaintainer should skip deployment for an application", "Takes effect at next run of maintainer", APPLICATION_ID); public static final UnboundListFlag<String> INACTIVE_MAINTENANCE_JOBS = defineListFlag( "inactive-maintenance-jobs", List.of(), String.class, "The list of maintenance jobs that are inactive.", "Takes effect immediately, but any currently running jobs will run until completion."); public static final UnboundListFlag<String> OUTBOUND_BLOCKED_IPV4 = defineListFlag( "container-outbound-blocked-ipv4", List.of(), String.class, "List of IPs or CIDRs that are blocked for outbound connections", "Takes effect on next tick"); public static final UnboundListFlag<String> OUTBOUND_BLOCKED_IPV6 = defineListFlag( "container-outbound-blocked-ipv6", List.of(), String.class, "List of IPs or CIDRs that are blocked for outbound connections", "Takes effect on next tick"); public static final UnboundIntFlag TENANT_BUDGET_QUOTA = defineIntFlag( "tenant-budget-quota", -1, "The budget in cents/hr a tenant is allowed spend per instance, as calculated by NodeResources", "Only takes effect on next deployment, if set to a value other than the default for flag!", TENANT_ID); public static final UnboundDoubleFlag CONTAINER_CPU_CAP = defineDoubleFlag( "container-cpu-cap", 0, "Hard limit on how many CPUs a container may use. This value is multiplied by CPU allocated to node, so " + "to cap CPU at 200%, set this to 2, etc. 0 disables the cap to allow unlimited CPU.", "Takes effect on next node agent tick. Change is orchestrated, but does NOT require container restart", HOSTNAME, APPLICATION_ID, CLUSTER_ID, CLUSTER_TYPE); public static final UnboundListFlag<String> DISABLED_HOST_ADMIN_TASKS = defineListFlag( "disabled-host-admin-tasks", List.of(), String.class, "List of host-admin task names (as they appear in the log, e.g. root>main>UpgradeTask), or some node-agent " + "functionality (see NodeAgentTask), that should be skipped", "Takes effect on next host admin tick", HOSTNAME, NODE_TYPE); public static final UnboundStringFlag DOCKER_IMAGE_REPO = defineStringFlag( "docker-image-repo", "", "Override default docker image repo. Docker image version will be Vespa version.", "Takes effect on next deployment from controller", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag ZOOKEEPER_SERVER_VERSION = defineStringFlag( "zookeeper-server-version", "3.6.3", "ZooKeeper server version, a jar file zookeeper-server-<ZOOKEEPER_SERVER_VERSION>-jar-with-dependencies.jar must exist", "Takes effect on restart of Docker container", NODE_TYPE, APPLICATION_ID, HOSTNAME); public static final UnboundBooleanFlag ENABLE_PUBLIC_SIGNUP_FLOW = defineFeatureFlag( "enable-public-signup-flow", false, "Show the public signup flow for a user in the console", "takes effect on browser reload of api/user/v1/user", CONSOLE_USER_EMAIL); public static final UnboundLongFlag INVALIDATE_CONSOLE_SESSIONS = defineLongFlag( "invalidate-console-sessions", 0, "Invalidate console sessions (cookies) issued before this unix timestamp", "Takes effect on next api request" ); public static final UnboundBooleanFlag JVM_OMIT_STACK_TRACE_IN_FAST_THROW = defineFeatureFlag( "jvm-omit-stack-trace-in-fast-throw", true, "Controls JVM option OmitStackTraceInFastThrow (default feature flag value is true, which is the default JVM option value as well)", "takes effect on JVM restart", CLUSTER_TYPE, APPLICATION_ID); public static final UnboundIntFlag MAX_TRIAL_TENANTS = defineIntFlag( "max-trial-tenants", -1, "The maximum nr. of tenants with trial plan, -1 is unlimited", "Takes effect immediately" ); public static final UnboundBooleanFlag ALLOW_DISABLE_MTLS = defineFeatureFlag( "allow-disable-mtls", true, "Allow application to disable client authentication", "Takes effect on redeployment", APPLICATION_ID); public static final UnboundIntFlag MAX_REBUILDS = defineIntFlag( "max-host-rebuilds", 10, "The maximum number of hosts allowed to rebuild at a time", "Takes effect immediately, but any current excess rebuilds will not be cancelled" ); public static final UnboundListFlag<String> EXTENDED_TRIAL_TENANTS = defineListFlag( "extended-trial-tenants", List.of(), String.class, "Tenants that will not be expired from their trial plan", "Takes effect immediately, used by the CloudTrialExpirer maintainer", TENANT_ID ); public static final UnboundListFlag<String> TLS_CIPHERS_OVERRIDE = defineListFlag( "tls-ciphers-override", List.of(), String.class, "Override TLS ciphers enabled for port 4443 on hosted application containers", "Takes effect on redeployment", APPLICATION_ID ); public static final UnboundDoubleFlag RESOURCE_LIMIT_DISK = defineDoubleFlag( "resource-limit-disk", 0.8, "Resource limit (between 0.0 and 1.0) for disk used by cluster controller for when to block feed", "Takes effect on next deployment", APPLICATION_ID ); public static final UnboundDoubleFlag RESOURCE_LIMIT_MEMORY = defineDoubleFlag( "resource-limit-memory", 0.8, "Resource limit (between 0.0 and 1.0) for memory used by cluster controller for when to block feed", "Takes effect on next deployment", APPLICATION_ID ); public static final UnboundListFlag<String> LOGCTL_OVERRIDE = defineListFlag( "logctl-override", List.of(), String.class, "Run vespa-logctl statements on container startup. Should be on the form <service>:<component> <level>=on", "Takes effect on container restart", APPLICATION_ID, HOSTNAME ); public static final UnboundStringFlag CONFIG_PROXY_JVM_ARGS = defineStringFlag( "config-proxy-jvm-args", "", "Sets jvm args for config proxy (added at the end of startup command, will override existing ones)", "Takes effect on restart of Docker container", ZONE_ID, APPLICATION_ID); private PermanentFlags() {} private static UnboundBooleanFlag defineFeatureFlag( String flagId, boolean defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return Flags.defineFeatureFlag(flagId, defaultValue, OWNERS, toString(CREATED_AT), toString(EXPIRES_AT), description, modificationEffect, dimensions); } private static UnboundStringFlag defineStringFlag( String flagId, String defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return Flags.defineStringFlag(flagId, defaultValue, OWNERS, toString(CREATED_AT), toString(EXPIRES_AT), description, modificationEffect, dimensions); } private static UnboundIntFlag defineIntFlag( String flagId, int defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return Flags.defineIntFlag(flagId, defaultValue, OWNERS, toString(CREATED_AT), toString(EXPIRES_AT), description, modificationEffect, dimensions); } private static UnboundLongFlag defineLongFlag( String flagId, long defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return Flags.defineLongFlag(flagId, defaultValue, OWNERS, toString(CREATED_AT), toString(EXPIRES_AT), description, modificationEffect, dimensions); } private static UnboundDoubleFlag defineDoubleFlag( String flagId, double defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return Flags.defineDoubleFlag(flagId, defaultValue, OWNERS, toString(CREATED_AT), toString(EXPIRES_AT), description, modificationEffect, dimensions); } private static <T> UnboundJacksonFlag<T> defineJacksonFlag( String flagId, T defaultValue, Class<T> jacksonClass, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return Flags.defineJacksonFlag(flagId, defaultValue, jacksonClass, OWNERS, toString(CREATED_AT), toString(EXPIRES_AT), description, modificationEffect, dimensions); } private static <T> UnboundListFlag<T> defineListFlag( String flagId, List<T> defaultValue, Class<T> elementClass, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return Flags.defineListFlag(flagId, defaultValue, elementClass, OWNERS, toString(CREATED_AT), toString(EXPIRES_AT), description, modificationEffect, dimensions); } private static String toString(Instant instant) { return DateTimeFormatter.ISO_DATE.withZone(ZoneOffset.UTC).format(instant); } }
package com.flash3388.flashlib.time; import com.flash3388.flashlib.util.CompareResult; import java.util.Objects; import java.util.concurrent.TimeUnit; public class Time implements Comparable<Time> { public static final long INVALID_VALUE = -1L; public static final Time INVALID = new Time(INVALID_VALUE, TimeUnit.MILLISECONDS); private final long mValue; private final TimeUnit mUnit; public Time(long value, TimeUnit unit) { mValue = value; mUnit = Objects.requireNonNull(unit, "time unit"); } public static Time of(long value, TimeUnit unit) { return new Time(value, unit); } public static Time milliseconds(long timeMs) { return new Time(timeMs, TimeUnit.MILLISECONDS); } public static Time seconds(long timeSeconds) { return new Time(timeSeconds, TimeUnit.SECONDS); } public static Time seconds(double timeSeconds) { return milliseconds((long) (timeSeconds * 1000)); } public static Time minutes(long timeMinutes) { return new Time(timeMinutes, TimeUnit.MINUTES); } public static Time minutes(double timeMinutes) { return seconds(timeMinutes * 60); } public long value() { return mValue; } public TimeUnit unit() { return mUnit; } public Time toUnit(TimeUnit newTimeUnit) { if (!isValid()) { return new Time(INVALID_VALUE, newTimeUnit); } if (mUnit == newTimeUnit) { return this; } long valueInWantedUnits = newTimeUnit.convert(mValue, mUnit); return new Time(valueInWantedUnits, newTimeUnit); } public long valueAsMillis() { return toUnit(TimeUnit.MILLISECONDS).value(); } public boolean isValid() { return mValue >= 0; } public Time add(Time other) { checkValidForOperation(other); TimeUnit smallerUnit = UnitComparing.smallerUnit(mUnit, other.unit()); long newValue = smallerUnit.convert(mValue, mUnit) + other.toUnit(smallerUnit).value(); return new Time(newValue, smallerUnit); } public Time sub(Time other) { checkValidForOperation(other); TimeUnit smallerUnit = UnitComparing.smallerUnit(mUnit, other.unit()); long newValue = smallerUnit.convert(mValue, mUnit) - other.toUnit(smallerUnit).value(); return new Time(newValue, smallerUnit); } public boolean before(Time other) { return lessThan(other); } public boolean lessThan(Time other) { return CompareResult.SMALLER_THAN.is(compareTo(other)); } public boolean lessThanOrEquals(Time other) { int compareResult = compareTo(other); return CompareResult.in(compareResult, CompareResult.SMALLER_THAN, CompareResult.EQUAL_TO); } public boolean after(Time other) { return largerThan(other); } public boolean largerThan(Time other) { return CompareResult.GREATER_THAN.is(compareTo(other)); } public boolean largerThanOrEquals(Time other) { int compareResult = compareTo(other); return CompareResult.in(compareResult, CompareResult.GREATER_THAN, CompareResult.EQUAL_TO); } public boolean equals(Time other) { return CompareResult.EQUAL_TO.is(compareTo(other)); } @Override public int compareTo(Time other) { if (!isValid() && !other.isValid()) { return CompareResult.EQUAL_TO.value(); } if (!other.isValid()) { return CompareResult.GREATER_THAN.value(); } if (!isValid()) { return CompareResult.SMALLER_THAN.value(); } long otherValue = other.toUnit(mUnit).value(); if (mValue > otherValue) { return CompareResult.GREATER_THAN.value(); } if (mValue < otherValue) { return CompareResult.SMALLER_THAN.value(); } return CompareResult.EQUAL_TO.value(); } @Override public boolean equals(Object obj) { return obj instanceof Time && equals((Time) obj); } @Override public int hashCode() { return Objects.hash(mValue, mUnit); } @Override public String toString() { if (!isValid()) { return "Invalid Time"; } return String.format("%d [%s]", mValue, mUnit.name()); } private void checkValidForOperation(Time other) { if (!isValid()) { throw new IllegalStateException(getNotValidExceptionMessage(this)); } if (!other.isValid()) { throw new IllegalArgumentException(getNotValidExceptionMessage(other)); } } private String getNotValidExceptionMessage(Time time) { return String.format("time not valid: %s", time.toString()); } }
package org.flymine.web.widget; import java.util.Arrays; import org.intermine.api.profile.InterMineBag; import org.intermine.objectstore.ObjectStore; import org.intermine.pathquery.Constraints; import org.intermine.pathquery.PathQuery; import org.intermine.web.logic.widget.WidgetURLQuery; /** * Builds a query to get all the genes (in bag) associated with specified go term. * @author Julie Sullivan */ public class TiffinURLQuery implements WidgetURLQuery { private InterMineBag bag; private String key; private ObjectStore os; private static final String DATASET = "Tiffin"; /** * @param key which bar the user clicked on * @param bag bag * @param os object store */ public TiffinURLQuery(ObjectStore os, InterMineBag bag, String key) { this.bag = bag; this.key = key; this.os = os; } /** * {@inheritDoc} */ public PathQuery generatePathQuery(boolean showAll) { PathQuery q = new PathQuery(os.getModel()); String motifPath = "Gene.upstreamIntergenicRegion.overlappingFeatures.motif.primaryIdentifier"; q.addViews("Gene.secondaryIdentifier", motifPath); q.addConstraints(Constraints.type("Gene.upstreamIntergenicRegion.overlappingFeatures", "TFBindingSite")); q.addConstraint(Constraints.eq("TFBindingSite.dataSets.name", DATASET)); q.addConstraint(Constraints.in(bag.getType(), bag.getName())); if (!showAll) { String[] keys = key.split(","); q.addConstraint(Constraints.oneOfValues(motifPath, Arrays.asList(keys))); } return q; } }
package org.loader.superglin; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import android.util.Log; import org.loader.glin.Callback; import org.loader.glin.NetResult; import org.loader.glin.Params; import org.loader.glin.Result; import org.loader.glin.cache.DefaultCacheProvider; import org.loader.glin.cache.ICacheProvider; import org.loader.glin.client.IClient; import org.loader.glin.factory.ParserFactory; import org.loader.glin.helper.Helper; import org.loader.glin.helper.SerializeHelper; import org.loader.glin.interceptor.IResultInterceptor; import org.loader.glin.parser.Parser; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Queue; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import okhttp3.Call; import okhttp3.Headers; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class OkClient implements IClient { public static final String MSG_ERROR_HTTP = "msg_error_http:okhttp"; private static final long DEFAULT_TIME_OUT = 5000; private OkHttpClient mClient; private Handler mHandler; private ParserFactory mParserFactory; private IResultInterceptor mResultInterceptor; private ICacheProvider mCacheProvider; private long mTimeOut = DEFAULT_TIME_OUT; private boolean isDebug; public OkClient() { mClient = buildClient(); } private OkHttpClient buildClient() { OkHttpClient.Builder builder = new OkHttpClient.Builder(); try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[]{new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { X509Certificate[] x509Certificates = new X509Certificate[0]; return x509Certificates; } }}, new SecureRandom()); builder.sslSocketFactory(sc.getSocketFactory()); builder.hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } catch (Exception e) { e.printStackTrace(); } return builder.build(); } @Override public <T> void get(String url, final LinkedHashMap<String, String> header, Object tag, boolean shouldCache, Callback<T> callback) { final Request request = new Request.Builder().url(url).build(); call(request, header, null, callback, tag, shouldCache, new StringBuilder()); } @Override public <T> void post(String url, final LinkedHashMap<String, String> header, Params params, Object tag, boolean shouldCache, Callback<T> callback) { StringBuilder debugInfo = new StringBuilder(); MultipartBody builder = createRequestBody(params, debugInfo); Request request = new Request.Builder().url(url).post(builder).build(); call(request, header, params.encode(), callback, tag, shouldCache, debugInfo); } @Override public <T> void post(String url, final LinkedHashMap<String, String> header, String json, Object tag, boolean shouldCache, final Callback<T> callback) { StringBuilder debugInfo = new StringBuilder(); Request request = new Request.Builder().url(url).post(createJsonBody(json, debugInfo)).build(); call(request, header, json, callback, tag, shouldCache, debugInfo); } @Override public <T> void put(String url, final LinkedHashMap<String, String> header, Params params, Object tag, boolean shouldCache, Callback<T> callback) { StringBuilder debugInfo = new StringBuilder(); MultipartBody builder = createRequestBody(params, debugInfo); Request request = new Request.Builder().url(url).put(builder).build(); call(request, header, params.encode(), callback, tag, shouldCache, debugInfo); } @Override public <T> void put(String url, final LinkedHashMap<String, String> header, String json, Object tag, boolean shouldCache, Callback<T> callback) { StringBuilder debugInfo = new StringBuilder(); Request request = new Request.Builder().url(url).put(createJsonBody(json, debugInfo)).build(); call(request, header, json, callback, tag, shouldCache, debugInfo); } @Override public <T> void delete(String url, final LinkedHashMap<String, String> header, Object tag, boolean shouldCache, Callback<T> callback) { StringBuilder debugInfo = new StringBuilder(); final Request request = new Request.Builder().url(url).delete().build(); call(request, header, null, callback, tag, shouldCache, debugInfo); } @Override public void cancel(Object tag) { for (Call call : mClient.dispatcher().queuedCalls()) { if (tag.equals(call.request().tag())) { call.cancel(); } } for (Call call : mClient.dispatcher().runningCalls()) { if (tag.equals(call.request().tag())) { call.cancel(); } } } @Override public LinkedHashMap<String, String> headers() { return null; } @Override public void parserFactory(ParserFactory factory) { mParserFactory = factory; } @Override public void timeout(long ms) { mTimeOut = ms; } @Override public void debugMode(boolean debug) { isDebug = debug; } @Override public void cacheProvider(ICacheProvider provider) { mCacheProvider = provider; } private OkHttpClient cloneClient() { return mClient.newBuilder() .connectTimeout(mTimeOut, TimeUnit.MILLISECONDS) // .readTimeout(mTimeOut, TimeUnit.MILLISECONDS) // .writeTimeout(mTimeOut, TimeUnit.MILLISECONDS) .build(); } @SuppressWarnings("unchecked") private <T> void call(Request request, final LinkedHashMap<String, String> header, final String params, final Callback<T> callback, final Object tag, final boolean shouldCache, StringBuilder debugInfo) { final String cacheKey = mCacheProvider == null ? null : mCacheProvider.getKey(request.url().toString(), params); if (shouldCache && mCacheProvider != null) { T cacheResult = mCacheProvider.get(cacheKey); if (cacheResult != null) { prntInfo("ReadCache->" + cacheKey); Result<T> res = new Result<>(); res.setOk(true); res.setMessage(""); res.setResult(cacheResult); res.setObj(200); res.setCache(true); callback.onResponse(res); } } String info = debugInfo.toString(); debugInfo.delete(0, debugInfo.length()); debugInfo.append("URL->").append(request.url().toString()).append("\n"); debugInfo.append("Method->").append(request.method()).append("\n"); LinkedHashMap<String, String> map = (header != null && !header.isEmpty()) ? header : headers(); Request.Builder builder = request.newBuilder(); builder.tag(tag); if (map != null && !map.isEmpty()) { for (Iterator<String> iterator = map.keySet().iterator(); iterator.hasNext();) { String key = iterator.next(); String value = map.get(key); if(value == null) continue; builder.addHeader(key, value); } } request = builder.build(); final Call call = cloneClient().newCall(request); call.enqueue(new okhttp3.Callback() { @Override public void onFailure(Call call, IOException e) { prntInfo("Error->" + e.getMessage()); Result<T> result = new Result<>(); result.ok(false); result.setObj(0); result.setMessage(MSG_ERROR_HTTP); callback(call, callback, result); } @Override public void onResponse(final Call call, Response response) throws IOException { if (!response.isSuccessful()) { prntInfo("Response->" + response.code() + ":" + response.message()); Result<T> res = new Result<>(); res.ok(false); res.setObj(response.code()); res.setMessage(MSG_ERROR_HTTP); callback(call, callback, res); return; } String resp = response.body().string(); prntInfo("Response->" + replaceBlank(resp)); NetResult netResult = new NetResult(response.code(), response.message(), resp); Result<T> res = (Result<T>) getParser(callback.getClass()).parse(callback.getClass(), netResult); callback(call, callback, res); if (shouldCache && mCacheProvider != null && res.getResult() != null) { prntInfo("CacheResult->" + cacheKey); mCacheProvider.put(cacheKey, netResult, res); } } }); String debugHeader = request.headers().toString(); if(!TextUtils.isEmpty(debugHeader)) { debugInfo.append("Header->").append(debugHeader).append("\n"); } debugInfo.append("\n"); debugInfo.append(info); prntInfo(debugInfo.toString()); } private <T> Parser getParser(Class<T> klass) { Class<?> type = Helper.getType(klass); if (List.class.isAssignableFrom(type)) { return mParserFactory.getListParser(); } return mParserFactory.getParser(); } private static String replaceBlank(String str) { String dest = str; if (dest != null) { Pattern p = Pattern.compile("\\s*|\t|\r|\n"); Matcher m = p.matcher(str); dest = m.replaceAll(""); } return dest; } private void prntInfo(String info) { if (!isDebug) { return;} Log.d("Glin", "*******************--BEGIN Log.d("Glin", info); Log.d("Glin", "********************--END } private <T> void callback(final Call call, final Callback<T> callback, final Result<T> result) { if(Looper.myLooper() == Looper.getMainLooper()) { realCallback(call, callback, result); }else { getHandler().post(new Runnable() { @Override public void run() { realCallback(call, callback, result); } }); } } private <T> void realCallback(Call call, Callback<T> callback, Result<T> result) { // if (isDebug) { Log.d("Glin", "call is canceled ? " + call.isCanceled());} if (call.isCanceled()) { return;} if (!intercept(result)) { callback.onResponse(result);} } private <T> boolean intercept(final Result<T> result) { if (mResultInterceptor != null && mResultInterceptor.intercept(result)) { return true; } return false; } private MultipartBody createRequestBody(Params params, StringBuilder debugInfo) { debugInfo.append("Params->"); MultipartBody.Builder builder = new MultipartBody.Builder() .setType(MultipartBody.FORM); LinkedHashMap<String, String> map = params.get(); for(Iterator<String> iterator=map.keySet().iterator();iterator.hasNext();) { String key = iterator.next(); String value = map.get(key); if(value == null) continue; debugInfo.append(key).append(":").append(value).append(";"); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\""+ key +"\""), RequestBody.create(null, value)); } debugInfo.append("\nFiles->"); LinkedHashMap<String, File> files = params.files(); for(Iterator<String> iterator=files.keySet().iterator();iterator.hasNext();) { String key = iterator.next(); File file = files.get(key); if(file == null) continue; debugInfo.append(key).append(":").append(file.getName()); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\";filename=\""+ file.getName() +"\""), RequestBody.create(MediaType.parse("application/octet-stream"), file)); } debugInfo.append("\n"); return builder.build(); } private RequestBody createJsonBody(String json, StringBuilder debugInfo) { debugInfo.append("RequestJson->").append(json); RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), json); return body; } private Handler getHandler() { if(mHandler == null) { mHandler = new Handler(Looper.getMainLooper());} return mHandler; } @Override public void resultInterceptor(IResultInterceptor interceptor) { mResultInterceptor = interceptor; } }
// Main.java package imagej; import imagej.ImageJ; import imagej.ui.UIManager; /** * Launches ImageJ. * * @author Curtis Rueden */ public final class Main { private Main() { // prevent instantiation of utility class } public static void main(String[] args) { manageSettings(); ImageJ.get(UIManager.class).processArgs(args); } private static void manageSettings() { // TODO // if (settings don't exist on disk) { // someone.initSettingsToDefault(); // who should own this code? // maybe write to disk or let persistence mechanism auto save on exit } }
/* * $Log: JobDef.java,v $ * Revision 1.21 2011-12-08 11:15:50 europe\m168309 * fixed javadoc * * Revision 1.20 2011/11/30 13:51:42 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org> * adjusted/reversed "Upgraded from WebSphere v5.1 to WebSphere v6.1" * * Revision 1.1 2011/10/19 14:49:53 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org> * Upgraded from WebSphere v5.1 to WebSphere v6.1 * * Revision 1.18 2010/02/03 14:57:00 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * check for expiration of timeouts * * Revision 1.17 2009/12/29 14:37:28 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * modified imports to reflect move of statistics classes to separate package * * Revision 1.16 2009/10/26 13:53:52 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org> * added MessageLog facility to receivers * * Revision 1.15 2009/06/05 07:28:48 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added function dumpStatisticsFull; function dumpStatistics now only dumps adapter level statistics * * Revision 1.14 2009/03/17 10:33:38 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org> * added numThreads and messageKeeperSize attribute * * Revision 1.13 2009/03/13 14:47:27 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org> * - added attributes transactionAttribute and transactionTimeout * - added function "cleanupDatabase" for generic cleaning up the MessageLog and Locker * * Revision 1.12 2009/02/24 09:45:42 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org> * added configureScheduledJob method * * Revision 1.11 2009/02/10 10:46:19 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org> * Replaced deprecated class * * Revision 1.10 2008/09/04 13:27:27 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * restructured job scheduling * * Revision 1.9 2008/08/27 16:21:48 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added configure() * * Revision 1.8 2007/12/12 09:09:56 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * allow for query-type jobs * * Revision 1.7 2007/05/16 11:48:07 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved javadoc * * Revision 1.6 2007/02/21 16:04:24 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * updated javadoc * */ package nl.nn.adapterframework.scheduler; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import nl.nn.adapterframework.configuration.Configuration; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.configuration.IbisManager; import nl.nn.adapterframework.core.Adapter; import nl.nn.adapterframework.core.IPipe; import nl.nn.adapterframework.core.ITransactionalStorage; import nl.nn.adapterframework.core.IbisTransaction; import nl.nn.adapterframework.core.PipeLine; import nl.nn.adapterframework.core.SenderException; import nl.nn.adapterframework.jdbc.DirectQuerySender; import nl.nn.adapterframework.jdbc.JdbcTransactionalStorage; import nl.nn.adapterframework.pipes.MessageSendingPipe; import nl.nn.adapterframework.senders.IbisLocalSender; import nl.nn.adapterframework.statistics.HasStatistics; import nl.nn.adapterframework.task.TimeoutGuard; import nl.nn.adapterframework.util.AppConstants; import nl.nn.adapterframework.util.JtaUtil; import nl.nn.adapterframework.util.LogUtil; import nl.nn.adapterframework.util.MessageKeeper; import nl.nn.adapterframework.util.SpringTxManagerProxy; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.log4j.Logger; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; public class JobDef { protected Logger log=LogUtil.getLogger(this); public static final String JOB_FUNCTION_STOP_ADAPTER="StopAdapter"; public static final String JOB_FUNCTION_START_ADAPTER="StartAdapter"; public static final String JOB_FUNCTION_STOP_RECEIVER="StopReceiver"; public static final String JOB_FUNCTION_START_RECEIVER="StartReceiver"; public static final String JOB_FUNCTION_SEND_MESSAGE="SendMessage"; public static final String JOB_FUNCTION_QUERY="ExecuteQuery"; public static final String JOB_FUNCTION_DUMPSTATS="dumpStatistics"; public static final String JOB_FUNCTION_DUMPSTATSFULL="dumpStatisticsFull"; public static final String JOB_FUNCTION_CLEANUPDB="cleanupDatabase"; private String name; private String cronExpression; private String function; private String adapterName; private String description; private String receiverName; private String query; private String jmsRealm; private Locker locker=null; private int numThreads = 1; private int countThreads = 0; private MessageKeeper messageKeeper; //instantiated in configure() private int messageKeeperSize = 10; //default length private int transactionAttribute=TransactionDefinition.PROPAGATION_SUPPORTS; private int transactionTimeout=0; private TransactionDefinition txDef=null; private PlatformTransactionManager txManager; private String jobGroup=AppConstants.getInstance().getString("scheduler.defaultJobGroup", "DEFAULT"); private class MessageLogObject { private String jmsRealmName; private String tableName; private String expiryDateField; public MessageLogObject(String jmsRealmName, String tableName, String expiryDateField) { this.jmsRealmName = jmsRealmName; this.tableName = tableName; this.expiryDateField = expiryDateField; } public boolean equals(Object o) { MessageLogObject mlo = (MessageLogObject) o; if (mlo.getJmsRealmName().equals(jmsRealmName) && mlo.getTableName().equals(tableName) && mlo.expiryDateField.equals(expiryDateField)) { return true; } else { return false; } } public String getJmsRealmName() { return jmsRealmName; } public String getTableName() { return tableName; } public String getExpiryDateField() { return expiryDateField; } } public String toString() { return ToStringBuilder.reflectionToString(this); } public void configure(Configuration config) throws ConfigurationException { MessageKeeper messageKeeper = getMessageKeeper(); if (StringUtils.isEmpty(getFunction())) { throw new ConfigurationException("jobdef ["+getName()+"] function must be specified"); } if (!(getFunction().equalsIgnoreCase(JOB_FUNCTION_STOP_ADAPTER)|| getFunction().equalsIgnoreCase(JOB_FUNCTION_START_ADAPTER)|| getFunction().equalsIgnoreCase(JOB_FUNCTION_STOP_RECEIVER)|| getFunction().equalsIgnoreCase(JOB_FUNCTION_START_RECEIVER)|| getFunction().equalsIgnoreCase(JOB_FUNCTION_SEND_MESSAGE)|| getFunction().equalsIgnoreCase(JOB_FUNCTION_QUERY)|| getFunction().equalsIgnoreCase(JOB_FUNCTION_DUMPSTATS) || getFunction().equalsIgnoreCase(JOB_FUNCTION_DUMPSTATSFULL) || getFunction().equalsIgnoreCase(JOB_FUNCTION_CLEANUPDB) )) { throw new ConfigurationException("jobdef ["+getName()+"] function ["+getFunction()+"] must be one of ["+ JOB_FUNCTION_STOP_ADAPTER+","+ JOB_FUNCTION_START_ADAPTER+","+ JOB_FUNCTION_STOP_RECEIVER+","+ JOB_FUNCTION_START_RECEIVER+","+ JOB_FUNCTION_SEND_MESSAGE+","+ JOB_FUNCTION_QUERY+","+ JOB_FUNCTION_DUMPSTATS+","+ JOB_FUNCTION_DUMPSTATSFULL+","+ JOB_FUNCTION_CLEANUPDB+ "]"); } if (getFunction().equalsIgnoreCase(JOB_FUNCTION_DUMPSTATS)) { // nothing special for now } else if (getFunction().equalsIgnoreCase(JOB_FUNCTION_DUMPSTATSFULL)) { // nothing special for now } else if (getFunction().equalsIgnoreCase(JOB_FUNCTION_CLEANUPDB)) { // nothing special for now } else if (getFunction().equalsIgnoreCase(JOB_FUNCTION_QUERY)) { if (StringUtils.isEmpty(getJmsRealm())) { throw new ConfigurationException("jobdef ["+getName()+"] for function ["+getFunction()+"] a jmsRealm must be specified"); } } else { if (StringUtils.isEmpty(getAdapterName())) { throw new ConfigurationException("jobdef ["+getName()+"] for function ["+getFunction()+"] a adapterName must be specified"); } if (config.getRegisteredAdapter(getAdapterName()) == null) { String msg="Jobdef [" + getName() + "] got error: adapter [" + getAdapterName() + "] not registered."; throw new ConfigurationException(msg); } if (getFunction().equalsIgnoreCase(JOB_FUNCTION_STOP_RECEIVER) || getFunction().equalsIgnoreCase(JOB_FUNCTION_START_RECEIVER)) { if (StringUtils.isEmpty(getReceiverName())) { throw new ConfigurationException("jobdef ["+getName()+"] for function ["+getFunction()+"] a receiverName must be specified"); } if (StringUtils.isNotEmpty(getReceiverName())){ if (! config.isRegisteredReceiver(getAdapterName(), getReceiverName())) { String msg="Jobdef [" + getName() + "] got error: adapter [" + getAdapterName() + "] receiver ["+getReceiverName()+"] not registered."; throw new ConfigurationException(msg); } } } } if (getLocker()!=null) { getLocker().configure(); } txDef = SpringTxManagerProxy.getTransactionDefinition(getTransactionAttributeNum(),getTransactionTimeout()); messageKeeper.add("job successfully configured"); } public JobDetail getJobDetail(IbisManager ibisManager) { JobDetail jobDetail = new JobDetail(getName(), Scheduler.DEFAULT_GROUP, ConfiguredJob.class);; jobDetail.getJobDataMap().put("manager", ibisManager); // reference to manager. jobDetail.getJobDataMap().put("jobdef", this); if (StringUtils.isNotEmpty(getDescription())) { jobDetail.setDescription(getDescription()); } return jobDetail; } protected void executeJob(IbisManager ibisManager) { if (incrementCountThreads()) { try { IbisTransaction itx = null; TransactionStatus txStatus = null; if (getTxManager()!=null) { //txStatus = getTxManager().getTransaction(txDef); itx = new IbisTransaction(getTxManager(), txDef, "scheduled job ["+getName()+"]"); txStatus = itx.getStatus(); } try { if (getLocker()!=null) { String objectId = null; try { try { objectId = getLocker().lock(); } catch (Exception e) { String msg = "error while setting lock: " + e.getMessage(); getMessageKeeper().add(msg); log.error(getLogPrefix()+msg); } if (objectId!=null) { TimeoutGuard tg = new TimeoutGuard("Job "+getName()); try { tg.activateGuard(getTransactionTimeout()); runJob(ibisManager); } finally { if (tg.cancel()) { log.error(getLogPrefix()+"thread has been interrupted"); } } } } finally { if (objectId!=null) { try { getLocker().unlock(objectId); } catch (Exception e) { String msg = "error while removing lock: " + e.getMessage(); getMessageKeeper().add(msg); log.error(getLogPrefix()+msg); } } } } else { runJob(ibisManager); } } finally { if (txStatus!=null) { //getTxManager().commit(txStatus); itx.commit(); } } } finally { decrementCountThreads(); } } else { String msg = "maximum number of threads that may execute concurrently [" + getNumThreads() + "] is exceeded, the processing of this thread will be interrupted"; getMessageKeeper().add(msg); log.error(getLogPrefix()+msg); } } public synchronized boolean incrementCountThreads() { if (countThreads < getNumThreads()) { countThreads++; return true; } else { return false; } } public synchronized void decrementCountThreads() { countThreads } protected void runJob(IbisManager ibisManager) { String function = getFunction(); if (function.equalsIgnoreCase(JOB_FUNCTION_DUMPSTATS)) { ibisManager.getConfiguration().dumpStatistics(HasStatistics.STATISTICS_ACTION_MARK_MAIN); } else if (function.equalsIgnoreCase(JOB_FUNCTION_DUMPSTATSFULL)) { ibisManager.getConfiguration().dumpStatistics(HasStatistics.STATISTICS_ACTION_MARK_FULL); } else if (function.equalsIgnoreCase(JOB_FUNCTION_CLEANUPDB)) { cleanupDatabase(ibisManager); } else if (function.equalsIgnoreCase(JOB_FUNCTION_QUERY)) { executeQueryJob(); } else if (function.equalsIgnoreCase(JOB_FUNCTION_SEND_MESSAGE)) { executeSendMessageJob(); } else{ ibisManager.handleAdapter(getFunction(), getAdapterName(), getReceiverName(), "scheduled job ["+getName()+"]"); } } private void cleanupDatabase(IbisManager ibisManager) { Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formattedDate = formatter.format(date); Configuration config = ibisManager.getConfiguration(); List lockers = new ArrayList(); List scheduledJobs = config.getScheduledJobs(); for (Iterator iter = scheduledJobs.iterator(); iter.hasNext();) { JobDef jobdef = (JobDef) iter.next(); if (jobdef.getLocker()!=null) { String jmsRealmName = jobdef.getLocker().getJmsRealName(); if (!lockers.contains(jmsRealmName)) { lockers.add(jmsRealmName); } } } for (Iterator iter = lockers.iterator(); iter.hasNext();) { String jmsRealmName = (String) iter.next(); setJmsRealm(jmsRealmName); String deleteQuery = "DELETE FROM IBISLOCK WHERE EXPIRYDATE < TO_TIMESTAMP('" + formattedDate + "', 'YYYY-MM-DD HH24:MI:SS')"; setQuery(deleteQuery); executeQueryJob(); } List messageLogs = new ArrayList(); for(int j=0; j<config.getRegisteredAdapters().size(); j++) { Adapter adapter = (Adapter)config.getRegisteredAdapter(j); PipeLine pipeline = adapter.getPipeLine(); for (int i=0; i<pipeline.getPipes().size(); i++) { IPipe pipe = pipeline.getPipe(i); if (pipe instanceof MessageSendingPipe) { MessageSendingPipe msp=(MessageSendingPipe)pipe; if (msp.getMessageLog()!=null) { ITransactionalStorage transactionStorage = msp.getMessageLog(); if (transactionStorage instanceof JdbcTransactionalStorage) { JdbcTransactionalStorage messageLog = (JdbcTransactionalStorage)transactionStorage; String jmsRealmName = messageLog.getJmsRealName(); String expiryDateField = messageLog.getExpiryDateField(); String tableName = messageLog.getTableName(); MessageLogObject mlo = new MessageLogObject(jmsRealmName, tableName, expiryDateField); if (!messageLogs.contains(mlo)) { messageLogs.add(mlo); } } } } } } for (Iterator iter = messageLogs.iterator(); iter.hasNext();) { MessageLogObject mlo = (MessageLogObject) iter.next(); setJmsRealm(mlo.getJmsRealmName()); String deleteQuery = "DELETE FROM " + mlo.getTableName() + " WHERE TYPE IN ('" + JdbcTransactionalStorage.TYPE_MESSAGELOG_PIPE + "','" + JdbcTransactionalStorage.TYPE_MESSAGELOG_RECEIVER + "') AND " + mlo.getExpiryDateField() + " < TO_TIMESTAMP('" + formattedDate + "', 'YYYY-MM-DD HH24:MI:SS')"; setQuery(deleteQuery); executeQueryJob(); } } private void executeQueryJob() { DirectQuerySender qs = new DirectQuerySender(); try { qs.setName("QuerySender"); qs.setJmsRealm(getJmsRealm()); qs.setQueryType("other"); qs.configure(); qs.open(); String result = qs.sendMessage("dummy", getQuery()); log.info("result [" + result + "]"); } catch (Exception e) { String msg = "error while executing query ["+getQuery()+"] (as part of scheduled job execution): " + e.getMessage(); getMessageKeeper().add(msg); log.error(getLogPrefix()+msg); } finally { try { qs.close(); } catch (SenderException e1) { String msg = "Could not close query sender" + e1.getMessage(); getMessageKeeper().add(msg); log.warn(msg); } } } private void executeSendMessageJob() { try { // send job IbisLocalSender localSender = new IbisLocalSender(); localSender.setJavaListener(receiverName); localSender.setIsolated(false); localSender.setName("AdapterJob"); localSender.configure(); localSender.open(); try { localSender.sendMessage(null, ""); } finally { localSender.close(); } } catch(Exception e) { String msg = "Error while sending message (as part of scheduled job execution): " + e.getMessage(); getMessageKeeper().add(msg); log.error(getLogPrefix()+msg); } } public String getLogPrefix() { return "Job ["+getName()+"] "; } /** * Defaults to the value under key <code>scheduler.defaultJobGroup</code> in the {@link AppConstants}. * If the value is not specified, it assumes <code>DEFAULT</code> * @param jobGroup */ public void setJobGroup(String jobGroup) { this.jobGroup = jobGroup; } public String getJobGroup() { return jobGroup; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setDescription(String description) { this.description = description; } public String getDescription() { return description; } public void setCronExpression(String cronExpression) { this.cronExpression = cronExpression; } public String getCronExpression() { return cronExpression; } public void setFunction(String function) { this.function = function; } public String getFunction() { return function; } public void setAdapterName(String adapterName) { this.adapterName = adapterName; } public String getAdapterName() { return adapterName; } public void setReceiverName(String receiverName) { this.receiverName = receiverName; } public String getReceiverName() { return receiverName; } public void setQuery(String query) { this.query = query; } public String getQuery() { return query; } public void setJmsRealm(String jmsRealm) { this.jmsRealm = jmsRealm; } public String getJmsRealm() { return jmsRealm; } public void setLocker(Locker locker) { this.locker = locker; locker.setName("Locker of job ["+getName()+"]"); } public Locker getLocker() { return locker; } public void setTransactionAttribute(String attribute) throws ConfigurationException { transactionAttribute = JtaUtil.getTransactionAttributeNum(attribute); if (transactionAttribute<0) { String msg="illegal value for transactionAttribute ["+attribute+"]"; messageKeeper.add(msg); throw new ConfigurationException(msg); } } public String getTransactionAttribute() { return JtaUtil.getTransactionAttributeString(transactionAttribute); } public void setTransactionAttributeNum(int i) { transactionAttribute = i; } public int getTransactionAttributeNum() { return transactionAttribute; } public void setTransactionTimeout(int i) { transactionTimeout = i; } public int getTransactionTimeout() { return transactionTimeout; } public void setTxManager(PlatformTransactionManager manager) { txManager = manager; } public PlatformTransactionManager getTxManager() { return txManager; } public void setNumThreads(int newNumThreads) { numThreads = newNumThreads; } public int getNumThreads() { return numThreads; } public synchronized MessageKeeper getMessageKeeper() { if (messageKeeper == null) messageKeeper = new MessageKeeper(messageKeeperSize < 1 ? 1 : messageKeeperSize); return messageKeeper; } public void setMessageKeeperSize(int size) { this.messageKeeperSize = size; } }
package frontend; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Locale; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.RowFilter; import javax.swing.border.MatteBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import backend.ActionHandler; import backend.language.LanguageController; import backend.libraries.AboutWindow; import backend.libraries.FileTreeWindow; public class ConceptJFrameGUI { /** * All the management of the music video list and more methods for * interaction with everything */ private ActionHandler actionManager; /** * The global JFrame window */ private JFrame guiMainFrame; /** * The global main JTable table */ private JTable table; /** * The DefaultTableModel of the global main JTable table */ private DefaultTableModel tableModel; /** * The TableRowSorter of the global main JTable table */ private TableRowSorter<TableModel> tableRowSorter; /** * Global JTextField text input field */ private JTextField textInputField; /** * The about JFrame window */ private AboutWindow newAboutWindow; /** * The path editor JFrame window */ private FileTreeWindow fileTreeWindow; /** * The program version */ private String version; /** * The program release date */ private String releaseDate; /** * Constructor: When an object of ConceptJFrameGUI gets produced this * automatically will happen: */ public ConceptJFrameGUI() { // set version and release date version = "0.8.3 (beta)"; releaseDate = LanguageController.getTranslation("June") + " 2017"; // set the column names and configuration file name String[] columnNames = new String[] { "#", LanguageController.getTranslation("Artist"), LanguageController.getTranslation("Title") }; String[] fileNameConfiguration = new String[] { "karaokeConfig", "cfg" }; // start a ActionHandler for all the under the surface commands actionManager = new ActionHandler(columnNames, fileNameConfiguration); } /** * At startup this method checks if a configuration file exist and loads it * if it finds one. So a fast start for already set up party's/etc. is * possible. */ private void startupConfig() { // check if a configuration file exists if (ActionHandler.fileExists(actionManager.getConfigurationFile())) { // read it actionManager.configFileReaderOnStart(); // update column heads and version date if language change actionManager.setColumnNames(new String[] { "#", LanguageController.getTranslation("Artist"), LanguageController.getTranslation("Title") }); releaseDate = "7. " + LanguageController.getTranslation("June") + " 2017"; } // start in the background the path editor fileTreeWindow = new FileTreeWindow(actionManager, this); } /** * This method manages the main graphic user interface. Here you can find * all features. */ private void createWindow() { guiMainFrame = new JFrame(); // start the global window/JFrame guiMainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // make sure the program exits when the frame closes guiMainFrame.setTitle(LanguageController.getTranslation("Karaoke Desktop Client [Beta]")); // title of the window guiMainFrame.setSize(500, 620); // size of the window at the start guiMainFrame.setLocationRelativeTo(null); // let it pop up in the middle of the screen guiMainFrame.setMinimumSize(new Dimension(400, 270)); // set a minimum size ActionHandler.setProgramWindowIcon(guiMainFrame); // set the default icon of the program as window icon JPanel mainPanel = new JPanel(new BorderLayout()); // create a panel in which we fit all our components String textSource = LanguageController.getTranslation("Source folders"); String tooltipSource = LanguageController.getTranslation("Edit the source folders of your music videos"); ImageIcon iconAdd = ActionHandler.loadImageIconFromClass("/icons/add_20x20.png"); String textAdd = LanguageController.getTranslation("Add"); String tooltipAdd = LanguageController.getTranslation("Add a new folder with new music videos to your list"); tooltipAdd += " ([control] + [a])"; ImageIcon iconRemove = ActionHandler.loadImageIconFromClass("/icons/remove_20x20.png"); String textRemove = LanguageController.getTranslation("Remove and more"); String tooltipRemove = LanguageController.getTranslation("Remove a folder with music videos from your list"); tooltipRemove += " ([control] + [e])"; String textExport = LanguageController.getTranslation("Export"); String tooltipExport = LanguageController.getTranslation("Export to the following formats") + ": CSV, HTML"; ImageIcon iconExportCsv = ActionHandler.loadImageIconFromClass("/icons/csv_20x20.png"); String textExportCsv = LanguageController.getTranslation("Export to") + " CSV"; String tooltipExportCsv = LanguageController.getTranslation("Export your data to") + " CSV (" + LanguageController.getTranslation("spreadsheet") + ")"; tooltipExportCsv += " ([control] + [t])"; ImageIcon iconExportHtml = ActionHandler.loadImageIconFromClass("/icons/html_20x20.png"); String textExportHtml = LanguageController.getTranslation("Export to") + " HTML"; String tooltipExportHtml = LanguageController.getTranslation("Export your data to") + " HTML (" + LanguageController.getTranslation("web browser") + ")"; tooltipExportHtml += " ([control] + [h])"; ImageIcon iconExportHtmlSearch = ActionHandler.loadImageIconFromClass("/icons/htmlSearch_20x20.png"); String textExportHtmlSearch = LanguageController.getTranslation("Export to") + " HTML " + LanguageController.getTranslation("with a search"); String tooltipExportHtmlSearch = LanguageController.getTranslation("Export your data to") + " HTML (" + LanguageController.getTranslation("web browser") + ")"; tooltipExportHtmlSearch += " ([control] + [s])"; String textLanguage = LanguageController.getTranslation("Language"); String tooltipLanguage = LanguageController.getTranslation("Change the language of the program") + ": GER, ENG"; ImageIcon iconLanguageEng = ActionHandler.loadImageIconFromClass("/icons/eng_30x20.png"); String textLanguageEng = LanguageController.getTranslation("English"); String tooltipLanguageEng = LanguageController.getTranslation("Change the language of the program to") + " " + LanguageController.getTranslation("English"); ImageIcon iconLanguageGer = ActionHandler.loadImageIconFromClass("/icons/de_30x20.png"); String textLanguageGer = LanguageController.getTranslation("German"); String tooltipLanguageGer = LanguageController.getTranslation("Change the language of the program to") + " " + LanguageController.getTranslation("German"); String textMore = LanguageController.getTranslation("More"); String tooltipMore = LanguageController.getTranslation("Save configuration, about and more"); ImageIcon iconSaveConfiguration = ActionHandler.loadImageIconFromClass("/icons/save_20x20.png"); String textSaveConfiguration = LanguageController.getTranslation("Save configuration"); String tooltipSaveConfiguration = LanguageController .getTranslation("Saves configuration in a configuration file"); ImageIcon iconLoadConfiguration = ActionHandler.loadImageIconFromClass("/icons/load_20x20.png"); String textLoadConfiguration = LanguageController.getTranslation("Load configuration"); String tooltipLoadConfiguration = LanguageController .getTranslation("Load configuration from a configuration file"); ImageIcon iconAbout = ActionHandler.loadImageIconFromClass("/icons/info_20x20.png"); String textAbout = LanguageController.getTranslation("About"); String tooltipAbout = LanguageController.getTranslation("About this program"); // add a menu bar to the window JMenuBar menuBar = new JMenuBar(); // >> with the sub menu "Source folders" JMenu subMenuSource = new JMenu(textSource); subMenuSource.setToolTipText(tooltipSource); // >> >> and the sub sub menu "Add" JMenuItem subSubMenuAddSourceFolder = new JMenuItem(textAdd, iconAdd); subSubMenuAddSourceFolder.setToolTipText(tooltipAdd); subSubMenuAddSourceFolder.addActionListener((ActionEvent event) -> { if (actionManager.addToPathList(actionManager.getPathOfDirectories())) updateTable(); // update table if new paths are here }); // >> >> and the sub sub menu "Remove and more" >> JMenuItem subSubMenuRemoveSourceFolder = new JMenuItem(textRemove, iconRemove); subSubMenuRemoveSourceFolder.setToolTipText(tooltipRemove); subSubMenuRemoveSourceFolder.addActionListener((ActionEvent event) -> { guiMainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); fileTreeWindow.closeIt(); // if there is an open window close it fileTreeWindow.createAndShowGUI(); // and open a new one // color the table special - needs somehow to be here ActionHandler.colorTableWithTwoColors(); guiMainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); }); // >> with the sub menu "Export" JMenu subMenuExport = new JMenu(textExport); subMenuExport.setToolTipText(tooltipExport); // >> >> and the sub sub menu "Export to CSV" JMenuItem subSubMenuExportCsv = new JMenuItem(textExportCsv, iconExportCsv); subSubMenuExportCsv.setToolTipText(tooltipExportCsv); subSubMenuExportCsv.addActionListener((ActionEvent event) -> { actionManager.exportCsvFile("musicvideolist.csv"); }); // >> >> and the sub sub menu "Export to HTML" JMenuItem subSubMenuExportHtml = new JMenuItem(textExportHtml, iconExportHtml); subSubMenuExportHtml.setToolTipText(tooltipExportHtml); subSubMenuExportHtml.addActionListener((ActionEvent event) -> { actionManager.exportHtmlFile("table.html"); }); // >> >> and the sub sub menu "Export to HTML with a search" JMenuItem subSubMenuExportHtmlWithSearch = new JMenuItem(textExportHtmlSearch, iconExportHtmlSearch); subSubMenuExportHtmlWithSearch.setToolTipText(tooltipExportHtmlSearch); subSubMenuExportHtmlWithSearch.addActionListener((ActionEvent event) -> { actionManager.exportHtmlFileWithSearch("tableWithSearch.html"); }); // >> with the sub menu "Export" JMenu subMenuLanguage = new JMenu(textLanguage); subMenuLanguage.setToolTipText(tooltipLanguage); // >> >> and the sub sub menu "Export to HTML with a search" JMenuItem subSubMenuEnglish = new JMenuItem(textLanguageEng, iconLanguageEng); subSubMenuEnglish.setToolTipText(tooltipLanguageEng); subSubMenuEnglish.addActionListener((ActionEvent event) -> { if (LanguageController.changeLanguageRestart(Locale.ENGLISH)) actionManager.fileOverWriterConfig(); }); // >> >> and the sub sub menu "Export to HTML with a search" JMenuItem subSubMenuGerman = new JMenuItem(textLanguageGer, iconLanguageGer); subSubMenuGerman.setToolTipText(tooltipLanguageGer); subSubMenuGerman.addActionListener((ActionEvent event) -> { if (LanguageController.changeLanguageRestart(Locale.GERMAN)) actionManager.fileOverWriterConfig(); }); // >> with the sub menu "More" JMenu subMenuMore = new JMenu(textMore); subMenuMore.setToolTipText(tooltipMore); // >> >> and the sub sub menu "Save configuration" JMenuItem subSubMenuConfigurationSave = new JMenuItem(textSaveConfiguration, iconSaveConfiguration); subSubMenuConfigurationSave.setToolTipText(tooltipSaveConfiguration); subSubMenuConfigurationSave.addActionListener((ActionEvent event) -> { actionManager.fileOverWriterConfig(); }); // >> >> and the sub sub menu "Load configuration" JMenuItem subSubMenuConfigurationLoad = new JMenuItem(textLoadConfiguration, iconLoadConfiguration); subSubMenuConfigurationLoad.setToolTipText(tooltipLoadConfiguration); subSubMenuConfigurationLoad.addActionListener((ActionEvent event) -> { if (actionManager.configFileLoaderDialog()) // if a new updateTable(); // configuration was loaded update the table }); // >> >> and last but not least the sub sub menu "About" JMenuItem subSubMenuAbout = new JMenuItem(textAbout, iconAbout); subSubMenuAbout.setToolTipText(tooltipAbout); subSubMenuAbout.addActionListener((ActionEvent event) -> { if (newAboutWindow != null) newAboutWindow.closeIt(); newAboutWindow = new AboutWindow(version, releaseDate); // color the table special - needs somehow to be here ActionHandler.colorTableWithTwoColors(); }); // add the menu buttons to the menu bar to the JFrame subMenuSource.add(subSubMenuAddSourceFolder); subMenuSource.addSeparator(); subMenuSource.add(subSubMenuRemoveSourceFolder); menuBar.add(subMenuSource); subMenuExport.add(subSubMenuExportCsv); subMenuExport.addSeparator(); subMenuExport.add(subSubMenuExportHtml); subMenuExport.addSeparator(); subMenuExport.add(subSubMenuExportHtmlWithSearch); menuBar.add(subMenuExport); subMenuLanguage.add(subSubMenuEnglish); subMenuLanguage.add(subSubMenuGerman); menuBar.add(subMenuLanguage); subMenuMore.add(subSubMenuConfigurationSave); subMenuMore.addSeparator(); subMenuMore.add(subSubMenuConfigurationLoad); subMenuMore.addSeparator(); subMenuMore.add(subSubMenuAbout); menuBar.add(subMenuMore); guiMainFrame.setJMenuBar(menuBar); // add to all the buttons a mouse click effect (MouseListener) Object[] menus = { subMenuSource, subMenuExport, subMenuLanguage, subMenuMore, subSubMenuAddSourceFolder, subSubMenuRemoveSourceFolder, subSubMenuExportCsv, subSubMenuExportHtml, subSubMenuExportHtmlWithSearch, subSubMenuGerman, subSubMenuEnglish, subSubMenuConfigurationSave, subSubMenuConfigurationLoad, subSubMenuAbout }; for (Object a : menus) { try { JMenu b = (JMenu) a; b.addMouseListener(ActionHandler.mouseChangeListener(guiMainFrame)); } catch (ClassCastException e) { JMenuItem b = (JMenuItem) a; b.addMouseListener(ActionHandler.mouseChangeListener(guiMainFrame)); } } tableModel = new DefaultTableModel(actionManager.musicVideoListToTable(" "), actionManager.getColumnNames()); table = new JTable(tableModel); // for Linux? table background table.getTableHeader().setBackground(new Color(240, 240, 240)); // set the color of the border MatteBorder border = new MatteBorder(0, 0, 0, 0, Color.BLACK); table.setBorder(border); // if you select a cell the whole row will be selected table.setRowSelectionAllowed(true); // only one row can be selected table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // set the specific width of the columns TableColumnModel columnModel = table.getColumnModel(); columnModel.getColumn(0).setPreferredWidth(40); columnModel.getColumn(1).setPreferredWidth(150); columnModel.getColumn(2).setPreferredWidth(300); columnModel.getColumn(0).setMinWidth(40); // center text in the first column DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer(); centerRenderer.setHorizontalAlignment(JLabel.CENTER); table.getColumnModel().getColumn(0).setCellRenderer(centerRenderer); // automatic row sorter table.setAutoCreateRowSorter(true); // color the table special ActionHandler.colorTableWithTwoColors(); JTableHeader header = table.getTableHeader(); DefaultTableCellRenderer headRenderer = new DefaultTableCellRenderer(); headRenderer.setHorizontalAlignment(JLabel.CENTER); // does not work but still... headRenderer.setFont(new Font("Dialog", Font.BOLD, 18)); headRenderer.setBorder(new MatteBorder(1, 1, 1, 1, Color.BLACK)); header.setDefaultRenderer(headRenderer); // place the JTable object in a JScrollPane for a scrolling table JScrollPane tableScrollPane = new JScrollPane(table); mainPanel.add(tableScrollPane, BorderLayout.CENTER); // add table mouse listener table.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mouseClicked(java.awt.event.MouseEvent evt) { actionManager.openMusicVideo((int) table.getValueAt(table.getSelectedRow(), 0) - 1); } public void mouseEntered(MouseEvent e) { guiMainFrame.setCursor(new Cursor(Cursor.HAND_CURSOR)); } public void mouseExited(MouseEvent e) { guiMainFrame.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } }); // create a panel in which we fit all our components JPanel topNorthPanel = new JPanel(new BorderLayout()); // add the search label ImageIcon iconSearch = ActionHandler.loadImageIconFromClass("/icons/search.png"); String textSearch = LanguageController.getTranslation("Search for a music video") + ": "; String tooltipSearch = LanguageController .getTranslation("Type in the field to instantly find your music video"); JLabel searchLabel = new JLabel(" " + textSearch); searchLabel.setIcon(iconSearch); searchLabel.setToolTipText(tooltipSearch); // create our JTextField as a text input field textInputField = new JTextField(); // add the search on YouTube button ImageIcon iconYoutubeButton = ActionHandler.loadImageIconFromClass("/icons/youtube.png"); String tooltipYoutubeButton = LanguageController.getTranslation("Start a video search on YouTube"); JButton youTubeButtonIcon = new JButton(iconYoutubeButton); youTubeButtonIcon.setToolTipText(tooltipYoutubeButton); // make the whole area this icon red color youTubeButtonIcon.setBackground(new Color(224, 47, 47)); youTubeButtonIcon.setContentAreaFilled(false); youTubeButtonIcon.setOpaque(true); // and add a MouseListener for the cursor icon youTubeButtonIcon.addMouseListener(ActionHandler.mouseChangeListener(guiMainFrame)); // add a MouseListener for the case if the button gets clicked youTubeButtonIcon.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { // URL we want to open String urlToOpen = "https: // get text of JTextField String currentInputFieldText = textInputField.getText(); // if text field has text try to add it to the urlToOpen try { if (currentInputFieldText != null && currentInputFieldText.length() > 0) { String textToSearchQuery = URLEncoder.encode(currentInputFieldText, "UTF-8"); urlToOpen += "/results?search_query=" + textToSearchQuery; } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // open URL in default web browser of the system ActionHandler.openUrlInDefaultBrowser(urlToOpen); } }); // add all components to our top panel topNorthPanel.add(searchLabel, BorderLayout.WEST); topNorthPanel.add(youTubeButtonIcon, BorderLayout.EAST); topNorthPanel.add(textInputField, BorderLayout.CENTER); // create a transparent border for better usability topNorthPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20)); // add the top panel at the top of our main panel mainPanel.add(topNorthPanel, BorderLayout.NORTH); // only allow valid input textInputField.addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent e) { char c = e.getKeyChar(); for (String a : new String[] { "(", ")", "[", "]", "\\", "*", "?" }) { String b = "" + c; if (b.equalsIgnoreCase(a)) e.consume(); // ignore input } } }); // if enter was pressed do this Action action = new AbstractAction() { private static final long serialVersionUID = 2735007834058697821L; public void actionPerformed(ActionEvent e) { // because we always want to open the top result on enter: if (table.getRowCount() > 0) { // we open the top music video if there are any music videos if (ActionHandler.isNumeric(textInputField.getText())) { // special case because number first actionManager.openMusicVideo(Integer.parseInt(textInputField.getText()) - 1); } else { actionManager.openMusicVideo((int) table.getValueAt(0, 0) - 1); } } else if (table.getRowCount() == 0) { // open YouTube with text field text as search query if // there are no elements in the table ActionHandler.openYouTubeWithSearchQuery(textInputField.getText()); } } }; textInputField.addActionListener(action); // also look up if the text in the input field changes textInputField.getDocument().addDocumentListener(new DocumentListener() { // update filter if something in text field gets added public void insertUpdate(DocumentEvent e) { updateFilter(textInputField.getText()); selectTopRowOfTable(); } // update filter if something in text field gets removed public void removeUpdate(DocumentEvent e) { updateFilter(textInputField.getText()); selectTopRowOfTable(); } public void changedUpdate(DocumentEvent arg0) { } }); // key shortcuts [control] + [key] textInputField.addKeyListener(new KeyListener() { public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { // control is pressed if ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0) { if (e.getKeyCode() == KeyEvent.VK_A) { // add folder if (actionManager.addToPathList(actionManager.getPathOfDirectories())) updateTable(); } else if (e.getKeyCode() == KeyEvent.VK_B) { // bad formatted video files guiMainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); actionManager.getWrongFormattedMusicVideos(); // color the table special - needs somehow to be here ActionHandler.colorTableWithTwoColors(); guiMainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } else if (e.getKeyCode() == KeyEvent.VK_T) { actionManager.exportCsvFile("musicvideolist.csv"); } else if (e.getKeyCode() == KeyEvent.VK_H) { actionManager.exportHtmlFile("table.html"); } else if (e.getKeyCode() == KeyEvent.VK_R) { openRandomVideoDialog(); // random video } else if (e.getKeyCode() == KeyEvent.VK_S) { actionManager.exportHtmlFileWithSearch("tableWithSearch.html"); } else if (e.getKeyCode() == KeyEvent.VK_E) { // editor guiMainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); fileTreeWindow.closeIt(); fileTreeWindow.createAndShowGUI(); ActionHandler.colorTableWithTwoColors(); guiMainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } } public void keyReleased(KeyEvent e) { } }); // create a row sorter (especially important for our search) tableRowSorter = new TableRowSorter<>(table.getModel()); // add row sorter to the table table.setRowSorter(tableRowSorter); // set every column able to sort for (int i = 0; i < actionManager.getColumnNames().length; i++) { tableRowSorter.setSortable(i, true); } // set a special number comparator to the number column tableRowSorter.setComparator(0, actionManager.new NumberComparator()); // play a random music video button ImageIcon iconRandomButton = ActionHandler.loadImageIconFromClass("/icons/random.png"); String textRandomButton = LanguageController.getTranslation("Play a random music video"); String tooltipRandomButton = " ([control] + [r])"; JButton randomMusicvideoButton = new JButton(textRandomButton, iconRandomButton); randomMusicvideoButton.setToolTipText(tooltipRandomButton); // make it change the cursor symbol randomMusicvideoButton.addMouseListener(ActionHandler.mouseChangeListener(guiMainFrame)); // add special click event randomMusicvideoButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { openRandomVideoDialog(); } }); mainPanel.add(randomMusicvideoButton, BorderLayout.SOUTH); // add the panel with everything to the JFrame window guiMainFrame.add(mainPanel); // make the frame visible for the user // (you can do this only if every graphical component was added - // otherwise some components will not be displayed) guiMainFrame.setVisible(true); // when the user wants to close the window (we want to do something) guiMainFrame.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent windowEvent) { /* * check if there already exist a saved configuration that is * different from the actual configuration or if there exist no * configuration at all */ boolean fileExistButPathListIsNotTheSame = ActionHandler .fileExists(actionManager.getConfigurationFile()) && (!actionManager.configFilePathExtracter().equals(actionManager.getPathList())); boolean fileDoesExist = ActionHandler.fileExists(actionManager.getConfigurationFile()); boolean noPathsExist = actionManager.getPathList().isEmpty(); if (!noPathsExist && (fileExistButPathListIsNotTheSame || !fileDoesExist)) { // then ask the user if he wants to close without saving if (JOptionPane.showConfirmDialog(guiMainFrame, LanguageController.getTranslation( "Are you sure to close the program without saving your music video folder paths to a configuration file?"), LanguageController.getTranslation("Really Closing") + "?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.NO_OPTION) { actionManager.fileOverWriterConfig(); } } } }); } /** * This method updates our TableRowSorter after our filter. * * @param searchString * (String | search command from text field) */ public void updateFilter(String searchString) { if (searchString.trim().length() == 0) { tableRowSorter.setRowFilter(null); } else { tableRowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + searchString)); } } /** * Selects automatically the top row of the table */ private void selectTopRowOfTable() { if (table.getSelectedRow() != 0) { table.changeSelection(0, 0, true, false); } } /** * This method removes all rows of our table and updates them with new rows * created of a new read of an up to date music video list. */ public void updateTable() { guiMainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); // delete all actual rows if there are even any rows! while (tableModel.getRowCount() > 0) { tableModel.removeRow(0); } // update the whole music video list (rescan all paths) actionManager.updateMusicVideoList(); // now add for each entry of the updated music video list a row to // the empty table for (Object[] a : actionManager.musicVideoListToTable(" ")) { tableModel.addRow(a); } // color the table special ActionHandler.colorTableWithTwoColors(); guiMainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } public void openRandomVideoDialog() { if (actionManager.getMusicVideosList().size() > 0) { int randomNum = ActionHandler.getRandomNumber(0, actionManager.getMusicVideosList().size()); String randomSong = actionManager.getMusicVideosList().get(randomNum).getTitle() + " " + LanguageController.getTranslation("by") + " " + actionManager.getMusicVideosList().get(randomNum).getArtist() + "?"; System.out.println("Random music video: ...Playing " + randomSong); if (JOptionPane.showConfirmDialog(null, LanguageController.getTranslation("Would you like to play") + " " + randomSong, "Info", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { actionManager.openMusicVideo(randomNum); } else { System.out.println("\tPlaying was denied by the user."); } } else { JOptionPane.showMessageDialog(null, LanguageController.getTranslation("You first need to add music videos to use this feature") + "!"); } } /** * This happens when the program gets executed: We create a new * ConceptJFrameGUI and the constructor does the rest :) */ public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { // Get the Windows look on Windows computers ActionHandler.windowsLookActivator(); // create a new Object of our class ConceptJFrameGUI mainFrame = new ConceptJFrameGUI(); // look after configuration file before starting mainFrame.startupConfig(); // open/show the window mainFrame.createWindow(); } }); } }
package org.smbarbour.mcu; import javax.swing.JFrame; import javax.swing.JPanel; import org.smbarbour.mcu.util.ConfigFile; import org.smbarbour.mcu.util.MCUpdater; import org.smbarbour.mcu.util.Module; import org.smbarbour.mcu.util.ServerList; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import javax.swing.JMenuBar; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.GridBagLayout; import javax.swing.JLabel; import java.awt.GridBagConstraints; import javax.swing.JTextField; import java.awt.Insets; import java.awt.Component; import javax.swing.Box; import java.awt.Dimension; import javax.swing.border.EtchedBorder; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.border.TitledBorder; import javax.swing.ComboBoxModel; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.ListSelectionModel; import javax.swing.AbstractListModel; import javax.swing.JScrollPane; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.SwingConstants; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.ListSelectionListener; import javax.swing.event.ListSelectionEvent; import javax.swing.filechooser.FileFilter; import javax.swing.event.ChangeListener; import javax.swing.event.ChangeEvent; public class ServerForm extends MCUApp { private static ServerForm window; private JFrame frmMain; final MCUpdater mcu = MCUpdater.getInstance(); private JTextField txtServerName; private JTextField txtServerNewsUrl; private JTextField txtServerAddress; private JTextField txtModName; private JTextField txtModUrl; private JTextField txtConfigUrl; private JTextField txtConfigPath; private JTextField txtServerMCVersion; private JTextField txtServerIconUrl; private JTextField txtServerRevision; private JTextField txtServerID; private JTextField txtModMD5; private JTextField txtModId; private JTextField txtConfigMD5; private JComboBox<String> lstConfigParentId; private JList<ConfigFileWrapper> lstConfigFiles; private JList<Module> lstModules; private ServerListModel modelServer; private ModuleListModel modelModule; private ConfigFileListModel modelConfig; private ModIdListModel modelParentId; private JTextField txtModDepends; private JCheckBox chkModInRoot; private JCheckBox chkModExtract; private JCheckBox chkModIsDefault; private JCheckBox chkModCoreMod; private JCheckBox chkModInJar; private JCheckBox chkModRequired; private JButton btnModMoveUp; private JButton btnModMoveDown; private JMenuItem mnuSave; private JList<ServerDefinition> lstServers; private boolean serverDirty = false; private boolean moduleDirty = false; private boolean configDirty = false; private int serverCurrentSelection; private int moduleCurrentSelection; private int configCurrentSelection; protected Path currentFile; protected FileFilter xmlFilter = new FileFilter() { @Override public boolean accept(File f) { if (f.isDirectory()) { return true; } String extension = getExtension(f); if (extension != null && extension.equalsIgnoreCase("xml")) { return true; } else { return false; } } @Override public String getDescription() { return "XML Files"; } private String getExtension(File f) { String ext = null; String s = f.getName(); int i = s.lastIndexOf('.'); if (i > 0 && i < s.length() - 1) { ext = s.substring(i+1).toLowerCase(); } return ext; } }; private JCheckBox chkServerGenerateList; private JButton btnModSort; public ServerForm() { initialize(); window = this; window.frmMain.setVisible(true); mcu.setParent(window); } private void initialize() { frmMain = new JFrame(); frmMain.setTitle("MCUpdater - ServerPack Utility build " + Version.BUILD_VERSION + " (Implementing MCU-API " + Version.API_VERSION + ")"); frmMain.setBounds(100,100,900,700); frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JMenuBar menuBar = new JMenuBar(); frmMain.setJMenuBar(menuBar); JMenu mnuFile = new JMenu("File"); mnuFile.setMnemonic('F'); menuBar.add(mnuFile); // JMenuItem mnuNew = new JMenuItem("New"); // mnuNew.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // modelModule.clear(); // modelConfig.clear(); // modelParentId.clear(); // mnuFile.add(mnuNew); JMenuItem mnuOpen = new JMenuItem("Open..."); mnuOpen.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { modelModule.clear(); modelConfig.clear(); modelParentId.clear(); modelParentId.add(""); JFileChooser jfc = new JFileChooser(); jfc.setFileFilter(xmlFilter); jfc.showOpenDialog(frmMain); currentFile = jfc.getSelectedFile().toPath(); mnuSave.setEnabled(true); try { Element docEle = null; Document serverHeader = MCUpdater.readXmlFromFile(currentFile.toFile()); if (!(serverHeader == null)) { Element parent = serverHeader.getDocumentElement(); if (parent.getNodeName().equals("ServerPack")){ NodeList servers = parent.getElementsByTagName("Server"); for (int i = 0; i < servers.getLength(); i++){ docEle = (Element)servers.item(i); ServerList sl = new ServerList(docEle.getAttribute("id"), docEle.getAttribute("name"), "", docEle.getAttribute("newsUrl"), docEle.getAttribute("iconUrl"), docEle.getAttribute("version"), docEle.getAttribute("serverAddress"), MCUpdater.parseBoolean(docEle.getAttribute("generateList")), docEle.getAttribute("revision")); List<Module> modules = new ArrayList<Module>(MCUpdater.getInstance().loadFromFile(currentFile.toFile(), docEle.getAttribute("id"))); List<ConfigFileWrapper> configs = new ArrayList<ConfigFileWrapper>(); for (Module modEntry : modules) { if (modEntry.getId().equals("")){ modEntry.setId(modEntry.getName().replace(" ", "")); } for (ConfigFile cfEntry : modEntry.getConfigs()) { configs.add(new ConfigFileWrapper(modEntry.getId(), cfEntry)); } } modelServer.add(new ServerDefinition(sl, modules, configs)); } } else { docEle = parent; ServerList sl = new ServerList(parent.getAttribute("id"), parent.getAttribute("name"), "", parent.getAttribute("newsUrl"), parent.getAttribute("iconUrl"), parent.getAttribute("version"), parent.getAttribute("serverAddress"), MCUpdater.parseBoolean(parent.getAttribute("generateList")), parent.getAttribute("revision")); List<Module> modules = new ArrayList<Module>(MCUpdater.getInstance().loadFromFile(currentFile.toFile(), docEle.getAttribute("id"))); List<ConfigFileWrapper> configs = new ArrayList<ConfigFileWrapper>(); for (Module modEntry : modules) { if (modEntry.getId().equals("")){ modEntry.setId(modEntry.getName().replace(" ", "")); } for (ConfigFile cfEntry : modEntry.getConfigs()) { configs.add(new ConfigFileWrapper(modEntry.getId(), cfEntry)); } } modelServer.add(new ServerDefinition(sl, modules, configs)); } } else { log("Unable to get server information from " + currentFile.toString()); } } catch (Exception exception) { exception.printStackTrace(); } } }); //mnuOpen.setEnabled(false); mnuFile.add(mnuOpen); JMenuItem mntmScanFolder = new JMenuItem("Scan Folder..."); mntmScanFolder.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int confirm = JOptionPane.showConfirmDialog(frmMain, "This will clear all existing modules and configurations.\n\nDo you wish to continue?", "MCU-ServerUtility", JOptionPane.YES_NO_OPTION); if (!(confirm == JOptionPane.YES_OPTION)) return; modelModule.clear(); modelConfig.clear(); modelParentId.clear(); modelParentId.add(""); JFileChooser jfc = new JFileChooser(); jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); jfc.showOpenDialog(frmMain); String urlBase = new String(); urlBase = JOptionPane.showInputDialog("Enter base URL for downloads"); Path rootPath = jfc.getSelectedFile().toPath(); PathWalker pathWalk = new PathWalker(window, rootPath, urlBase); try { Files.walkFileTree(rootPath, pathWalk); } catch (IOException e1) { e1.printStackTrace(); } modelParentId.sort(); } }); mnuFile.add(mntmScanFolder); mnuSave = new JMenuItem("Save"); mnuSave.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doSave(currentFile); } }); mnuSave.setEnabled(false); mnuFile.add(mnuSave); JMenuItem mnuSaveAs = new JMenuItem("Save As..."); mnuSaveAs.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser saveDialog = new JFileChooser(); saveDialog.setFileFilter(xmlFilter ); saveDialog.showSaveDialog(frmMain); Path outputFile = saveDialog.getSelectedFile().toPath(); currentFile = outputFile; mnuSave.setEnabled(true); doSave(currentFile); } }); mnuFile.add(mnuSaveAs); mnuFile.addSeparator(); JMenuItem mnuExit = new JMenuItem("Exit"); mnuExit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); mnuFile.add(mnuExit); frmMain.getContentPane().setLayout(new BorderLayout(0, 0)); JPanel serverListPanel = new JPanel(); serverListPanel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null)); frmMain.getContentPane().add(serverListPanel, BorderLayout.WEST); /* GridBagLayout gbl_serverListPanel = new GridBagLayout(); gbl_serverListPanel.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0}; gbl_serverListPanel.rowHeights = new int[]{0, 0, 0, 0, 0}; gbl_serverListPanel.columnWeights = new double[]{0.0, 0.0, 1.0, 0.0, 1.0, 0.0, Double.MIN_VALUE}; gbl_serverListPanel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE}; */ serverListPanel.setLayout(new BorderLayout(0,0)); { lstServers = new JList<ServerDefinition>(); lstServers.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting() == false) { if (serverDirty || moduleDirty || configDirty) { int confirm = JOptionPane.showConfirmDialog(frmMain, "Changes to the current selection(s) have been made. Do you wish to save these changes?", "MCU-ServerUtility", JOptionPane.YES_NO_OPTION); if (confirm == JOptionPane.YES_OPTION) { if (configDirty) updateConfigEntry(); if (moduleDirty) updateModuleEntry(); updateServerEntry(); } } if (lstServers.getSelectedIndex() > -1) { ServerDefinition changeTo = lstServers.getSelectedValue(); txtServerName.setText(changeTo.getServer().getName()); txtServerID.setText(changeTo.getServer().getServerId()); txtServerAddress.setText(changeTo.getServer().getAddress()); txtServerNewsUrl.setText(changeTo.getServer().getNewsUrl()); txtServerIconUrl.setText(changeTo.getServer().getIconUrl()); txtServerRevision.setText(changeTo.getServer().getRevision()); txtServerMCVersion.setText(changeTo.getServer().getVersion()); chkServerGenerateList.setSelected(changeTo.getServer().isGenerateList()); modelModule.clear(); modelParentId.clear(); for (Module entry : changeTo.getModules()) { modelModule.add(entry); modelParentId.add(entry.getId()); } modelParentId.sort(); modelConfig.clear(); for (ConfigFileWrapper entry : changeTo.getConfigs()) { modelConfig.add(entry); } serverCurrentSelection = lstServers.getSelectedIndex(); } serverDirty=false; moduleDirty=false; configDirty=false; } } }); modelServer = new ServerListModel(); lstServers.setModel(modelServer); serverListPanel.add(lstServers, BorderLayout.CENTER); JPanel pnlSLCommands = new JPanel(); GridBagLayout gbl_pnlSLCommands = new GridBagLayout(); pnlSLCommands.setLayout(gbl_pnlSLCommands); serverListPanel.add(pnlSLCommands, BorderLayout.SOUTH); { Component SLCTopLeft = Box.createRigidArea(new Dimension(3,3)); GridBagConstraints gbc_SLCTopLeft = new GridBagConstraints(); gbc_SLCTopLeft.insets=new Insets(0, 0, 5, 5); gbc_SLCTopLeft.gridx=0; gbc_SLCTopLeft.gridy=0; pnlSLCommands.add(SLCTopLeft, gbc_SLCTopLeft); JButton btnServerNew = new JButton("New"); btnServerNew.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { modelServer.add(new ServerDefinition(new ServerList("newServer","New Server","","","","","",true,"1"), new ArrayList<Module>(), new ArrayList<ConfigFileWrapper>())); } }); GridBagConstraints gbc_btnServerNew = new GridBagConstraints(); gbc_btnServerNew.insets=new Insets(0, 0, 5, 5); gbc_btnServerNew.gridx=1; gbc_btnServerNew.gridy=1; pnlSLCommands.add(btnServerNew, gbc_btnServerNew); JButton btnServerRemove = new JButton("Remove"); btnServerRemove.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { modelServer.remove(serverCurrentSelection); lstServers.clearSelection(); lstModules.clearSelection(); lstConfigFiles.clearSelection(); lstConfigParentId.setSelectedIndex(-1); modelModule.clear(); modelConfig.clear(); modelParentId.clear(); clearServerDetailPane(); clearModuleDetailPane(); clearConfigDetailPane(); } }); GridBagConstraints gbc_btnServerRemove = new GridBagConstraints(); gbc_btnServerRemove.insets=new Insets(0, 0, 5, 5); gbc_btnServerRemove.gridx=2; gbc_btnServerRemove.gridy=1; pnlSLCommands.add(btnServerRemove, gbc_btnServerRemove); JButton btnServerUpdate = new JButton("Update"); btnServerUpdate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateServerEntry(); } }); GridBagConstraints gbc_btnServerUpdate = new GridBagConstraints(); gbc_btnServerUpdate.insets=new Insets(0, 0, 5, 5); gbc_btnServerUpdate.gridx=3; gbc_btnServerUpdate.gridy=1; pnlSLCommands.add(btnServerUpdate, gbc_btnServerUpdate); Component SLCBottomRight = Box.createRigidArea(new Dimension(3,3)); GridBagConstraints gbc_SLCBottomRight = new GridBagConstraints(); gbc_SLCBottomRight.insets=new Insets(0, 0, 5, 5); gbc_SLCBottomRight.gridx=4; gbc_SLCBottomRight.gridy=2; pnlSLCommands.add(SLCBottomRight, gbc_SLCBottomRight); } } JPanel serverDetailPanel = new JPanel(); serverDetailPanel.setLayout(new BorderLayout(0,0)); frmMain.getContentPane().add(serverDetailPanel, BorderLayout.CENTER); JPanel serverPanel = new JPanel(); serverPanel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null)); serverDetailPanel.add(serverPanel, BorderLayout.NORTH); GridBagLayout gbl_serverPanel = new GridBagLayout(); gbl_serverPanel.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0}; gbl_serverPanel.rowHeights = new int[]{0, 0, 0, 0, 0}; gbl_serverPanel.columnWeights = new double[]{0.0, 0.0, 1.0, 0.0, 1.0, 0.0, Double.MIN_VALUE}; gbl_serverPanel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE}; serverPanel.setLayout(gbl_serverPanel); { // serverPanel DocumentListener serverDocumentListener = new DocumentListener(){ @Override public void insertUpdate(DocumentEvent e) { serverDirty = true; } @Override public void removeUpdate(DocumentEvent e) { serverDirty = true; } @Override public void changedUpdate(DocumentEvent e) { serverDirty = true; } }; int row = 0; Component rigidArea = Box.createRigidArea(new Dimension(3, 3)); GridBagConstraints gbc_rigidArea = new GridBagConstraints(); gbc_rigidArea.insets = new Insets(0, 0, 5, 5); gbc_rigidArea.gridx = 0; gbc_rigidArea.gridy = row; serverPanel.add(rigidArea, gbc_rigidArea); row++; JLabel lblServerName = new JLabel("Server Name:"); GridBagConstraints gbc_lblServerName = new GridBagConstraints(); gbc_lblServerName.insets = new Insets(0, 0, 5, 5); gbc_lblServerName.anchor = GridBagConstraints.EAST; gbc_lblServerName.gridx = 1; gbc_lblServerName.gridy = row; serverPanel.add(lblServerName, gbc_lblServerName); txtServerName = new JTextField(); txtServerName.getDocument().addDocumentListener(serverDocumentListener); GridBagConstraints gbc_txtServerName = new GridBagConstraints(); gbc_txtServerName.insets = new Insets(0, 0, 5, 5); gbc_txtServerName.fill = GridBagConstraints.HORIZONTAL; gbc_txtServerName.gridx = 2; gbc_txtServerName.gridy = row; serverPanel.add(txtServerName, gbc_txtServerName); txtServerName.setColumns(10); JLabel lblServerID = new JLabel("Server ID:"); GridBagConstraints gbc_lblServerID = new GridBagConstraints(); gbc_lblServerID.anchor = GridBagConstraints.EAST; gbc_lblServerID.insets = new Insets(0, 0, 5, 5); gbc_lblServerID.gridx = 3; gbc_lblServerID.gridy = row; serverPanel.add(lblServerID, gbc_lblServerID); txtServerID = new JTextField(); txtServerID.getDocument().addDocumentListener(serverDocumentListener); GridBagConstraints gbc_txtServerID = new GridBagConstraints(); gbc_txtServerID.insets = new Insets(0, 0, 5, 5); gbc_txtServerID.fill = GridBagConstraints.HORIZONTAL; gbc_txtServerID.gridx = 4; gbc_txtServerID.gridy = row; serverPanel.add(txtServerID, gbc_txtServerID); txtServerID.setColumns(10); row++; JLabel lblServerAddress = new JLabel("Server Address:"); GridBagConstraints gbc_lblServerAddress = new GridBagConstraints(); gbc_lblServerAddress.anchor = GridBagConstraints.EAST; gbc_lblServerAddress.insets = new Insets(0, 0, 5, 5); gbc_lblServerAddress.gridx = 1; gbc_lblServerAddress.gridy = row; serverPanel.add(lblServerAddress, gbc_lblServerAddress); txtServerAddress = new JTextField(); txtServerAddress.getDocument().addDocumentListener(serverDocumentListener); GridBagConstraints gbc_txtServerAddress = new GridBagConstraints(); gbc_txtServerAddress.insets = new Insets(0, 0, 5, 5); gbc_txtServerAddress.fill = GridBagConstraints.HORIZONTAL; gbc_txtServerAddress.gridx = 2; gbc_txtServerAddress.gridy = row; serverPanel.add(txtServerAddress, gbc_txtServerAddress); txtServerAddress.setColumns(10); JLabel lblNewsUrl = new JLabel("News URL:"); GridBagConstraints gbc_lblNewsUrl = new GridBagConstraints(); gbc_lblNewsUrl.anchor = GridBagConstraints.EAST; gbc_lblNewsUrl.insets = new Insets(0, 0, 5, 5); gbc_lblNewsUrl.gridx = 3; gbc_lblNewsUrl.gridy = row; serverPanel.add(lblNewsUrl, gbc_lblNewsUrl); txtServerNewsUrl = new JTextField(); txtServerNewsUrl.getDocument().addDocumentListener(serverDocumentListener); GridBagConstraints gbc_txtNewsUrl = new GridBagConstraints(); gbc_txtNewsUrl.insets = new Insets(0, 0, 5, 5); gbc_txtNewsUrl.fill = GridBagConstraints.HORIZONTAL; gbc_txtNewsUrl.gridx = 4; gbc_txtNewsUrl.gridy = row; serverPanel.add(txtServerNewsUrl, gbc_txtNewsUrl); txtServerNewsUrl.setColumns(10); row++; JLabel lblIconURL = new JLabel("Icon URL:"); GridBagConstraints gbc_lblIconURL = new GridBagConstraints(); gbc_lblIconURL.anchor = GridBagConstraints.EAST; gbc_lblIconURL.insets = new Insets(0, 0, 5, 5); gbc_lblIconURL.gridx = 1; gbc_lblIconURL.gridy = row; serverPanel.add(lblIconURL, gbc_lblIconURL); txtServerIconUrl = new JTextField(); txtServerIconUrl.getDocument().addDocumentListener(serverDocumentListener); GridBagConstraints gbc_txtIconURL = new GridBagConstraints(); gbc_txtIconURL.insets = new Insets(0, 0, 5, 5); gbc_txtIconURL.fill = GridBagConstraints.HORIZONTAL; gbc_txtIconURL.gridx = 2; gbc_txtIconURL.gridy = row; serverPanel.add(txtServerIconUrl, gbc_txtIconURL); txtServerIconUrl.setColumns(10); JLabel lblVersion = new JLabel("Minecraft Version:"); GridBagConstraints gbc_lblVersion = new GridBagConstraints(); gbc_lblVersion.anchor = GridBagConstraints.EAST; gbc_lblVersion.insets = new Insets(0, 0, 5, 5); gbc_lblVersion.gridx = 3; gbc_lblVersion.gridy = row; serverPanel.add(lblVersion, gbc_lblVersion); txtServerMCVersion = new JTextField(); txtServerMCVersion.getDocument().addDocumentListener(serverDocumentListener); GridBagConstraints gbc_txtVersion = new GridBagConstraints(); gbc_txtVersion.insets = new Insets(0, 0, 5, 5); gbc_txtVersion.fill = GridBagConstraints.HORIZONTAL; gbc_txtVersion.gridx = 4; gbc_txtVersion.gridy = row; serverPanel.add(txtServerMCVersion, gbc_txtVersion); txtServerMCVersion.setColumns(10); row++; JLabel lblRevision = new JLabel("ServerPack Revision:"); GridBagConstraints gbc_lblRevision = new GridBagConstraints(); gbc_lblRevision.anchor = GridBagConstraints.EAST; gbc_lblRevision.insets = new Insets(0, 0, 5, 5); gbc_lblRevision.gridx = 1; gbc_lblRevision.gridy = row; serverPanel.add(lblRevision, gbc_lblRevision); txtServerRevision = new JTextField(); txtServerRevision.getDocument().addDocumentListener(serverDocumentListener); GridBagConstraints gbc_txtRevision = new GridBagConstraints(); gbc_txtRevision.insets = new Insets(0, 0, 5, 5); gbc_txtRevision.fill = GridBagConstraints.HORIZONTAL; gbc_txtRevision.gridx = 2; gbc_txtRevision.gridy = row; serverPanel.add(txtServerRevision, gbc_txtRevision); txtServerRevision.setColumns(10); JLabel lblGenerateList = new JLabel("Generate List:"); lblGenerateList.setHorizontalAlignment(SwingConstants.TRAILING); GridBagConstraints gbc_lblGenerateList = new GridBagConstraints(); gbc_lblGenerateList.fill = GridBagConstraints.HORIZONTAL; gbc_lblGenerateList.insets = new Insets(0, 0, 5, 5); gbc_lblGenerateList.gridx = 3; gbc_lblGenerateList.gridy = row; serverPanel.add(lblGenerateList, gbc_lblGenerateList); chkServerGenerateList = new JCheckBox(""); chkServerGenerateList.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { serverDirty = true; } }); GridBagConstraints gbc_chkGenerateList = new GridBagConstraints(); gbc_chkGenerateList.insets = new Insets(0, 0, 5, 5); gbc_chkGenerateList.anchor = GridBagConstraints.WEST; gbc_chkGenerateList.gridx = 4; gbc_chkGenerateList.gridy = row; serverPanel.add(chkServerGenerateList, gbc_chkGenerateList); row++; Component rigidArea_1 = Box.createRigidArea(new Dimension(3, 3)); GridBagConstraints gbc_rigidArea_1 = new GridBagConstraints(); gbc_rigidArea_1.gridx = 5; gbc_rigidArea_1.gridy = row; serverPanel.add(rigidArea_1, gbc_rigidArea_1); } serverPanel.setSize(serverPanel.getWidth(), (int)serverPanel.getMinimumSize().getHeight()); JPanel detailPanel = new JPanel(); serverDetailPanel.add(detailPanel, BorderLayout.CENTER); detailPanel.setLayout(new GridLayout(1, 0, 0, 0)); JPanel modulePanel = new JPanel(); modulePanel.setBorder(new TitledBorder(null, "Modules", TitledBorder.LEADING, TitledBorder.TOP, null, null)); detailPanel.add(modulePanel); GridBagLayout gbl_modulePanel = new GridBagLayout(); gbl_modulePanel.columnWidths = new int[]{0, 0}; gbl_modulePanel.rowHeights = new int[]{0, 0, 0}; gbl_modulePanel.columnWeights = new double[]{1.0, Double.MIN_VALUE}; gbl_modulePanel.rowWeights = new double[]{1.0, 0.0, Double.MIN_VALUE}; modulePanel.setLayout(gbl_modulePanel); JPanel modListPanel = new JPanel(); GridBagConstraints gbc_modListPanel = new GridBagConstraints(); gbc_modListPanel.insets = new Insets(0, 0, 5, 0); gbc_modListPanel.fill = GridBagConstraints.BOTH; gbc_modListPanel.gridx = 0; gbc_modListPanel.gridy = 0; modulePanel.add(modListPanel, gbc_modListPanel); modListPanel.setLayout(new BorderLayout(0, 0)); JScrollPane modListScroll = new JScrollPane(); modListPanel.add(modListScroll, BorderLayout.CENTER); lstModules = new JList<Module>(); lstModules.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting() == false) { if (lstModules.getSelectedIndex() > -1) { Module selected = lstModules.getSelectedValue(); txtModName.setText(selected.getName()); txtModId.setText(selected.getId()); txtModMD5.setText(selected.getMD5()); txtModDepends.setText(selected.getDepends()); txtModUrl.setText(selected.getUrl()); chkModRequired.setSelected(selected.getRequired()); chkModInJar.setSelected(selected.getInJar()); chkModCoreMod.setSelected(selected.getCoreMod()); chkModIsDefault.setSelected(selected.getIsDefault()); chkModExtract.setSelected(selected.getExtract()); chkModInRoot.setSelected(selected.getInRoot()); btnModMoveUp.setEnabled(moduleCurrentSelection == 0 ? false : true); btnModMoveDown.setEnabled(moduleCurrentSelection == modelModule.getSize()-1 ? false : true); moduleDirty=false; moduleCurrentSelection = lstModules.getSelectedIndex(); } } } }); modelModule = new ModuleListModel(new ArrayList<Module>()); lstModules.setModel(modelModule); lstModules.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); modListScroll.setViewportView(lstModules); JPanel modDetailPanel = new JPanel(); modDetailPanel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null)); GridBagConstraints gbc_modDetailPanel = new GridBagConstraints(); gbc_modDetailPanel.fill = GridBagConstraints.BOTH; gbc_modDetailPanel.gridx = 0; gbc_modDetailPanel.gridy = 1; modulePanel.add(modDetailPanel, gbc_modDetailPanel); GridBagLayout gbl_modDetailPanel = new GridBagLayout(); gbl_modDetailPanel.columnWidths = new int[]{0, 60, 86, 0, 0, 0}; gbl_modDetailPanel.rowHeights = new int[]{0, 20, 0, 0, 0, 0, 0, 0}; gbl_modDetailPanel.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE}; gbl_modDetailPanel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE}; modDetailPanel.setLayout(gbl_modDetailPanel); { // modDetailPanel DocumentListener moduleDocumentListener = new DocumentListener(){ @Override public void insertUpdate(DocumentEvent e) {moduleDirty = true;} @Override public void removeUpdate(DocumentEvent e) {moduleDirty = true;} @Override public void changedUpdate(DocumentEvent e) {moduleDirty = true;} }; ChangeListener moduleChangeListener = new ChangeListener() { public void stateChanged(ChangeEvent e) { moduleDirty = true; } }; int row = 0; { Component rigidArea_6 = Box.createRigidArea(new Dimension(3, 3)); GridBagConstraints gbc_rigidArea_6 = new GridBagConstraints(); gbc_rigidArea_6.anchor = GridBagConstraints.WEST; gbc_rigidArea_6.insets = new Insets(0, 0, 5, 5); gbc_rigidArea_6.gridx = 0; gbc_rigidArea_6.gridy = row; modDetailPanel.add(rigidArea_6, gbc_rigidArea_6); row++; } { JLabel lblModName = new JLabel("Name:"); lblModName.setHorizontalAlignment(SwingConstants.TRAILING); GridBagConstraints gbc_lblModName = new GridBagConstraints(); gbc_lblModName.fill = GridBagConstraints.HORIZONTAL; gbc_lblModName.insets = new Insets(0, 0, 5, 5); gbc_lblModName.gridx = 1; gbc_lblModName.gridy = row; modDetailPanel.add(lblModName, gbc_lblModName); txtModName = new JTextField(); txtModName.getDocument().addDocumentListener(moduleDocumentListener); GridBagConstraints gbc_txtModName = new GridBagConstraints(); gbc_txtModName.gridwidth = 3; gbc_txtModName.insets = new Insets(0, 0, 5, 5); gbc_txtModName.fill = GridBagConstraints.HORIZONTAL; gbc_txtModName.anchor = GridBagConstraints.NORTH; gbc_txtModName.gridx = 2; gbc_txtModName.gridy = row; modDetailPanel.add(txtModName, gbc_txtModName); txtModName.setColumns(10); row++; } { JLabel lblModId = new JLabel("ID:"); lblModId.setHorizontalAlignment(SwingConstants.TRAILING); GridBagConstraints gbc_lblModId = new GridBagConstraints(); gbc_lblModId.fill = GridBagConstraints.HORIZONTAL; gbc_lblModId.insets = new Insets(0, 0, 5, 5); gbc_lblModId.gridx = 1; gbc_lblModId.gridy = row; modDetailPanel.add(lblModId, gbc_lblModId); txtModId = new JTextField(); txtModId.getDocument().addDocumentListener(moduleDocumentListener); GridBagConstraints gbc_txtModId = new GridBagConstraints(); gbc_txtModId.gridwidth = 3; gbc_txtModId.insets = new Insets(0, 0, 5, 5); gbc_txtModId.fill = GridBagConstraints.HORIZONTAL; gbc_txtModId.anchor = GridBagConstraints.NORTH; gbc_txtModId.gridx = 2; gbc_txtModId.gridy = row; modDetailPanel.add(txtModId, gbc_txtModId); txtModId.setColumns(10); row++; } { JLabel lblModDepends = new JLabel("Depends:"); lblModDepends.setHorizontalAlignment(SwingConstants.TRAILING); GridBagConstraints gbc_lblModDepends = new GridBagConstraints(); gbc_lblModDepends.fill = GridBagConstraints.HORIZONTAL; gbc_lblModDepends.insets = new Insets(0, 0, 5, 5); gbc_lblModDepends.gridx = 1; gbc_lblModDepends.gridy = row; modDetailPanel.add(lblModDepends, gbc_lblModDepends); txtModDepends = new JTextField(); txtModDepends.getDocument().addDocumentListener(moduleDocumentListener); GridBagConstraints gbc_txtModDepends = new GridBagConstraints(); gbc_txtModDepends.gridwidth = 3; gbc_txtModDepends.insets = new Insets(0, 0, 5, 5); gbc_txtModDepends.fill = GridBagConstraints.HORIZONTAL; gbc_txtModDepends.anchor = GridBagConstraints.NORTH; gbc_txtModDepends.gridx = 2; gbc_txtModDepends.gridy = row; modDetailPanel.add(txtModDepends, gbc_txtModDepends); txtModDepends.setColumns(10); row++; } { JLabel lblModUrl = new JLabel("URL:"); lblModUrl.setHorizontalAlignment(SwingConstants.TRAILING); GridBagConstraints gbc_lblModUrl = new GridBagConstraints(); gbc_lblModUrl.fill = GridBagConstraints.HORIZONTAL; gbc_lblModUrl.insets = new Insets(0, 0, 5, 5); gbc_lblModUrl.gridx = 1; gbc_lblModUrl.gridy = row; modDetailPanel.add(lblModUrl, gbc_lblModUrl); txtModUrl = new JTextField(); txtModUrl.getDocument().addDocumentListener(moduleDocumentListener); GridBagConstraints gbc_txtModUrl = new GridBagConstraints(); gbc_txtModUrl.gridwidth = 3; gbc_txtModUrl.insets = new Insets(0, 0, 5, 5); gbc_txtModUrl.fill = GridBagConstraints.HORIZONTAL; gbc_txtModUrl.gridx = 2; gbc_txtModUrl.gridy = row; modDetailPanel.add(txtModUrl, gbc_txtModUrl); txtModUrl.setColumns(10); row++; } { JLabel lblMD5 = new JLabel("MD5 Checksum:"); lblMD5.setHorizontalAlignment(SwingConstants.TRAILING); GridBagConstraints gbc_lblMD5 = new GridBagConstraints(); gbc_lblMD5.fill = GridBagConstraints.HORIZONTAL; gbc_lblMD5.insets = new Insets(0, 0, 5, 5); gbc_lblMD5.gridx = 1; gbc_lblMD5.gridy = row; modDetailPanel.add(lblMD5, gbc_lblMD5); txtModMD5 = new JTextField(); txtModMD5.getDocument().addDocumentListener(moduleDocumentListener); GridBagConstraints gbc_txtMD5 = new GridBagConstraints(); gbc_txtMD5.gridwidth = 3; gbc_txtMD5.insets = new Insets(0, 0, 5, 5); gbc_txtMD5.fill = GridBagConstraints.HORIZONTAL; gbc_txtMD5.gridx = 2; gbc_txtMD5.gridy = row; modDetailPanel.add(txtModMD5, gbc_txtMD5); txtModMD5.setColumns(10); row++; } { JLabel lblRequired = new JLabel("Required:"); lblRequired.setHorizontalAlignment(SwingConstants.TRAILING); GridBagConstraints gbc_lblRequired = new GridBagConstraints(); gbc_lblRequired.fill = GridBagConstraints.HORIZONTAL; gbc_lblRequired.insets = new Insets(0, 0, 5, 5); gbc_lblRequired.gridx = 1; gbc_lblRequired.gridy = row; modDetailPanel.add(lblRequired, gbc_lblRequired); chkModRequired = new JCheckBox(""); chkModRequired.addChangeListener(moduleChangeListener); GridBagConstraints gbc_chkRequired = new GridBagConstraints(); gbc_chkRequired.insets = new Insets(0, 0, 5, 5); gbc_chkRequired.anchor = GridBagConstraints.WEST; gbc_chkRequired.gridx = 2; gbc_chkRequired.gridy = row; modDetailPanel.add(chkModRequired, gbc_chkRequired); JLabel lblInJar = new JLabel("In JAR:"); lblInJar.setHorizontalAlignment(SwingConstants.TRAILING); GridBagConstraints gbc_lblInJar = new GridBagConstraints(); gbc_lblInJar.fill = GridBagConstraints.HORIZONTAL; gbc_lblInJar.insets = new Insets(0, 0, 5, 5); gbc_lblInJar.gridx = 3; gbc_lblInJar.gridy = row; modDetailPanel.add(lblInJar, gbc_lblInJar); chkModInJar = new JCheckBox(""); chkModInJar.addChangeListener(moduleChangeListener); GridBagConstraints gbc_chkInJar = new GridBagConstraints(); gbc_chkInJar.insets = new Insets(0, 0, 5, 5); gbc_chkInJar.anchor = GridBagConstraints.WEST; gbc_chkInJar.gridx = 4; gbc_chkInJar.gridy = row; modDetailPanel.add(chkModInJar, gbc_chkInJar); row++; } { JLabel lblCoreMod = new JLabel("Core Mod:"); lblCoreMod.setHorizontalAlignment(SwingConstants.TRAILING); GridBagConstraints gbc_lblCoreMod = new GridBagConstraints(); gbc_lblCoreMod.fill = GridBagConstraints.HORIZONTAL; gbc_lblCoreMod.insets = new Insets(0, 0, 5, 5); gbc_lblCoreMod.gridx = 1; gbc_lblCoreMod.gridy = row; modDetailPanel.add(lblCoreMod, gbc_lblCoreMod); chkModCoreMod = new JCheckBox(""); chkModCoreMod.addChangeListener(moduleChangeListener); GridBagConstraints gbc_chkCoreMod = new GridBagConstraints(); gbc_chkCoreMod.insets = new Insets(0, 0, 5, 5); gbc_chkCoreMod.anchor = GridBagConstraints.WEST; gbc_chkCoreMod.gridx = 2; gbc_chkCoreMod.gridy = row; modDetailPanel.add(chkModCoreMod, gbc_chkCoreMod); JLabel lblIsDefault = new JLabel("Is Default:"); lblIsDefault.setHorizontalAlignment(SwingConstants.TRAILING); GridBagConstraints gbc_lblIsDefault = new GridBagConstraints(); gbc_lblIsDefault.fill = GridBagConstraints.HORIZONTAL; gbc_lblIsDefault.insets = new Insets(0, 0, 5, 5); gbc_lblIsDefault.gridx = 3; gbc_lblIsDefault.gridy = row; modDetailPanel.add(lblIsDefault, gbc_lblIsDefault); chkModIsDefault = new JCheckBox(""); chkModIsDefault.addChangeListener(moduleChangeListener); GridBagConstraints gbc_chkIsDefault = new GridBagConstraints(); gbc_chkIsDefault.insets = new Insets(0, 0, 5, 5); gbc_chkIsDefault.anchor = GridBagConstraints.WEST; gbc_chkIsDefault.gridx = 4; gbc_chkIsDefault.gridy = row; modDetailPanel.add(chkModIsDefault, gbc_chkIsDefault); row++; } { JLabel lblExtract = new JLabel("Extract:"); lblExtract.setHorizontalAlignment(SwingConstants.TRAILING); GridBagConstraints gbc_lblExtract = new GridBagConstraints(); gbc_lblExtract.fill = GridBagConstraints.HORIZONTAL; gbc_lblExtract.insets = new Insets(0, 0, 5, 5); gbc_lblExtract.gridx = 1; gbc_lblExtract.gridy = row; modDetailPanel.add(lblExtract, gbc_lblExtract); chkModExtract = new JCheckBox(""); chkModExtract.addChangeListener(moduleChangeListener); GridBagConstraints gbc_chkExtract = new GridBagConstraints(); gbc_chkExtract.insets = new Insets(0, 0, 5, 5); gbc_chkExtract.anchor = GridBagConstraints.WEST; gbc_chkExtract.gridx = 2; gbc_chkExtract.gridy = row; modDetailPanel.add(chkModExtract, gbc_chkExtract); JLabel lblInRoot = new JLabel("In Root:"); lblInRoot.setHorizontalAlignment(SwingConstants.TRAILING); GridBagConstraints gbc_lblInRoot = new GridBagConstraints(); gbc_lblInRoot.fill = GridBagConstraints.HORIZONTAL; gbc_lblInRoot.insets = new Insets(0, 0, 5, 5); gbc_lblInRoot.gridx = 3; gbc_lblInRoot.gridy = row; modDetailPanel.add(lblInRoot, gbc_lblInRoot); chkModInRoot = new JCheckBox(""); chkModInRoot.addChangeListener(moduleChangeListener); GridBagConstraints gbc_chkInRoot = new GridBagConstraints(); gbc_chkInRoot.insets = new Insets(0, 0, 5, 5); gbc_chkInRoot.anchor = GridBagConstraints.WEST; gbc_chkInRoot.gridx = 4; gbc_chkInRoot.gridy = row; modDetailPanel.add(chkModInRoot, gbc_chkInRoot); row++; } { JButton btnModAdd = new JButton("Add"); btnModAdd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Module newMod = new Module(txtModName.getText(), txtModId.getText(), txtModUrl.getText(), txtModDepends.getText(), chkModRequired.isSelected(), chkModInJar.isSelected(), chkModExtract.isSelected(), chkModInRoot.isSelected(), chkModIsDefault.isSelected(), chkModCoreMod.isSelected(), txtModMD5.getText(), null); modelModule.add(newMod); modelParentId.add(newMod.getId()); modelParentId.sort(); } }); GridBagConstraints gbc_btnModAdd = new GridBagConstraints(); gbc_btnModAdd.fill = GridBagConstraints.HORIZONTAL; gbc_btnModAdd.insets = new Insets(0, 0, 5, 5); gbc_btnModAdd.gridx = 1; gbc_btnModAdd.gridy = row; modDetailPanel.add(btnModAdd, gbc_btnModAdd); JButton btnModRemove = new JButton("Remove"); btnModRemove.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { modelParentId.remove(modelParentId.find(lstModules.getSelectedValue().getId())); modelModule.remove(moduleCurrentSelection); clearModuleDetailPane(); lstModules.clearSelection(); } }); GridBagConstraints gbc_btnModRemove = new GridBagConstraints(); gbc_btnModRemove.fill = GridBagConstraints.HORIZONTAL; gbc_btnModRemove.insets = new Insets(0, 0, 5, 5); gbc_btnModRemove.gridx = 2; gbc_btnModRemove.gridy = row; modDetailPanel.add(btnModRemove, gbc_btnModRemove); JButton btnModUpdate = new JButton("Update"); btnModUpdate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateModuleEntry(); } }); GridBagConstraints gbc_btnModUpdate = new GridBagConstraints(); gbc_btnModUpdate.fill = GridBagConstraints.HORIZONTAL; gbc_btnModUpdate.insets = new Insets(0, 0, 5, 5); gbc_btnModUpdate.gridx = 3; gbc_btnModUpdate.gridy = row; modDetailPanel.add(btnModUpdate, gbc_btnModUpdate); row++; } { btnModMoveUp = new JButton("Move Up"); btnModMoveUp.setEnabled(false); btnModMoveUp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int current = moduleCurrentSelection; modelModule.moveUp(current); lstModules.setSelectedIndex(current-1); } }); GridBagConstraints gbc_btnModMoveUp = new GridBagConstraints(); gbc_btnModMoveUp.fill = GridBagConstraints.HORIZONTAL; gbc_btnModMoveUp.insets = new Insets(0, 0, 5, 5); gbc_btnModMoveUp.gridx = 1; gbc_btnModMoveUp.gridy = row; modDetailPanel.add(btnModMoveUp, gbc_btnModMoveUp); btnModMoveDown = new JButton("Move Down"); btnModMoveDown.setEnabled(false); btnModMoveDown.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int current = moduleCurrentSelection; modelModule.moveDown(current); lstModules.setSelectedIndex(current+1); } }); GridBagConstraints gbc_btnModMoveDown = new GridBagConstraints(); gbc_btnModMoveDown.fill = GridBagConstraints.HORIZONTAL; gbc_btnModMoveDown.insets = new Insets(0, 0, 5, 5); gbc_btnModMoveDown.gridx = 2; gbc_btnModMoveDown.gridy = row; modDetailPanel.add(btnModMoveDown, gbc_btnModMoveDown); btnModSort = new JButton("IntelliSort"); btnModSort.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { modelModule.sort(); } }); GridBagConstraints gbc_btnModSort = new GridBagConstraints(); gbc_btnModSort.fill = GridBagConstraints.HORIZONTAL; gbc_btnModSort.insets = new Insets(0, 0, 5, 5); gbc_btnModSort.gridx = 3; gbc_btnModSort.gridy = row; modDetailPanel.add(btnModSort, gbc_btnModSort); row++; } { Component rigidArea_7 = Box.createRigidArea(new Dimension(3, 3)); GridBagConstraints gbc_rigidArea_7 = new GridBagConstraints(); gbc_rigidArea_7.gridx = 5; gbc_rigidArea_7.gridy = row; modDetailPanel.add(rigidArea_7, gbc_rigidArea_7); } } JPanel configFilePanel = new JPanel(); configFilePanel.setBorder(new TitledBorder(null, "Config Files", TitledBorder.LEADING, TitledBorder.TOP, null, null)); detailPanel.add(configFilePanel); GridBagLayout gbl_configFilePanel = new GridBagLayout(); gbl_configFilePanel.columnWidths = new int[]{0, 0}; gbl_configFilePanel.rowHeights = new int[]{0, 0, 0}; gbl_configFilePanel.columnWeights = new double[]{1.0, Double.MIN_VALUE}; gbl_configFilePanel.rowWeights = new double[]{1.0, 0.0, Double.MIN_VALUE}; configFilePanel.setLayout(gbl_configFilePanel); JPanel configListPanel = new JPanel(); GridBagConstraints gbc_configListPanel = new GridBagConstraints(); gbc_configListPanel.insets = new Insets(0, 0, 5, 0); gbc_configListPanel.fill = GridBagConstraints.BOTH; gbc_configListPanel.gridx = 0; gbc_configListPanel.gridy = 0; configFilePanel.add(configListPanel, gbc_configListPanel); configListPanel.setLayout(new BorderLayout(0, 0)); JScrollPane configListScroll = new JScrollPane(); configListPanel.add(configListScroll, BorderLayout.CENTER); lstConfigFiles = new JList<ConfigFileWrapper>(); modelConfig = new ConfigFileListModel(new ArrayList<ConfigFileWrapper>()); lstConfigFiles.setModel(modelConfig); lstConfigFiles.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); lstConfigFiles.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting() == false) { if (lstConfigFiles.getSelectedIndex() > -1) { ConfigFileWrapper selected = lstConfigFiles.getSelectedValue(); lstConfigParentId.setSelectedIndex(modelParentId.find(selected.getParentId())); lstConfigParentId.repaint(); txtConfigMD5.setText(selected.getConfigFile().getMD5()); txtConfigUrl.setText(selected.getConfigFile().getUrl()); txtConfigPath.setText(selected.getConfigFile().getPath()); configDirty=false; configCurrentSelection = lstConfigFiles.getSelectedIndex(); } } } }); configListScroll.setViewportView(lstConfigFiles); JPanel configDetailPanel = new JPanel(); configDetailPanel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null)); GridBagConstraints gbc_configDetailPanel = new GridBagConstraints(); gbc_configDetailPanel.fill = GridBagConstraints.BOTH; gbc_configDetailPanel.gridx = 0; gbc_configDetailPanel.gridy = 1; configFilePanel.add(configDetailPanel, gbc_configDetailPanel); GridBagLayout gbl_configDetailPanel = new GridBagLayout(); gbl_configDetailPanel.columnWidths = new int[]{0, 0, 23, 0, 0}; gbl_configDetailPanel.rowHeights = new int[]{0, 14, 0, 0, 0, 0, 0}; gbl_configDetailPanel.columnWeights = new double[]{0.0, 0.0, 1.0, 1.0, 0.0}; gbl_configDetailPanel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE}; configDetailPanel.setLayout(gbl_configDetailPanel); { // configDetailPanel DocumentListener configDocumentListener = new DocumentListener(){ @Override public void insertUpdate(DocumentEvent e) {configDirty = true;} @Override public void removeUpdate(DocumentEvent e) {configDirty = true;} @Override public void changedUpdate(DocumentEvent e) {configDirty = true;} }; int row = 0; Component rigidArea_2 = Box.createRigidArea(new Dimension(3, 3)); GridBagConstraints gbc_rigidArea_2 = new GridBagConstraints(); gbc_rigidArea_2.insets = new Insets(0, 0, 5, 5); gbc_rigidArea_2.gridx = 0; gbc_rigidArea_2.gridy = row; configDetailPanel.add(rigidArea_2, gbc_rigidArea_2); row++; JLabel lblParentId = new JLabel("Parent Mod:"); lblParentId.setHorizontalAlignment(SwingConstants.TRAILING); GridBagConstraints gbc_lblParentId = new GridBagConstraints(); gbc_lblParentId.fill = GridBagConstraints.HORIZONTAL; gbc_lblParentId.insets = new Insets(0, 0, 5, 5); gbc_lblParentId.anchor = GridBagConstraints.NORTH; gbc_lblParentId.gridx = 1; gbc_lblParentId.gridy = row; configDetailPanel.add(lblParentId, gbc_lblParentId); modelParentId = new ModIdListModel(); lstConfigParentId = new JComboBox<String>(modelParentId); lstConfigParentId.addItemListener(new ItemListener(){ @Override public void itemStateChanged(ItemEvent e) { configDirty=true; } }); GridBagConstraints gbc_lstParentId = new GridBagConstraints(); gbc_lstParentId.gridwidth = 3; gbc_lstParentId.insets = new Insets(0, 0, 5, 5); gbc_lstParentId.fill = GridBagConstraints.HORIZONTAL; gbc_lstParentId.gridx = 2; gbc_lstParentId.gridy = row; configDetailPanel.add(lstConfigParentId, gbc_lstParentId); row++; JLabel lblConfigURL = new JLabel("URL:"); lblConfigURL.setHorizontalAlignment(SwingConstants.TRAILING); GridBagConstraints gbc_lblConfigURL = new GridBagConstraints(); gbc_lblConfigURL.fill = GridBagConstraints.HORIZONTAL; gbc_lblConfigURL.insets = new Insets(0, 0, 5, 5); gbc_lblConfigURL.anchor = GridBagConstraints.NORTH; gbc_lblConfigURL.gridx = 1; gbc_lblConfigURL.gridy = row; configDetailPanel.add(lblConfigURL, gbc_lblConfigURL); txtConfigUrl = new JTextField(); txtConfigUrl.getDocument().addDocumentListener(configDocumentListener); GridBagConstraints gbc_txtConfigURL = new GridBagConstraints(); gbc_txtConfigURL.gridwidth = 3; gbc_txtConfigURL.insets = new Insets(0, 0, 5, 5); gbc_txtConfigURL.fill = GridBagConstraints.HORIZONTAL; gbc_txtConfigURL.gridx = 2; gbc_txtConfigURL.gridy = row; configDetailPanel.add(txtConfigUrl, gbc_txtConfigURL); txtConfigUrl.setColumns(10); row++; JLabel lblConfigPath = new JLabel("Path:"); lblConfigPath.setHorizontalAlignment(SwingConstants.TRAILING); GridBagConstraints gbc_lblConfigPath = new GridBagConstraints(); gbc_lblConfigPath.fill = GridBagConstraints.HORIZONTAL; gbc_lblConfigPath.insets = new Insets(0, 0, 5, 5); gbc_lblConfigPath.gridx = 1; gbc_lblConfigPath.gridy = row; configDetailPanel.add(lblConfigPath, gbc_lblConfigPath); txtConfigPath = new JTextField(); txtConfigPath.getDocument().addDocumentListener(configDocumentListener); GridBagConstraints gbc_txtConfigPath = new GridBagConstraints(); gbc_txtConfigPath.gridwidth = 3; gbc_txtConfigPath.insets = new Insets(0, 0, 5, 5); gbc_txtConfigPath.fill = GridBagConstraints.HORIZONTAL; gbc_txtConfigPath.gridx = 2; gbc_txtConfigPath.gridy = row; configDetailPanel.add(txtConfigPath, gbc_txtConfigPath); txtConfigPath.setColumns(10); row++; JLabel lblConfigMD5 = new JLabel("MD5 Checksum:"); lblConfigMD5.setHorizontalAlignment(SwingConstants.TRAILING); GridBagConstraints gbc_lblConfigMD5 = new GridBagConstraints(); gbc_lblConfigMD5.fill = GridBagConstraints.HORIZONTAL; gbc_lblConfigMD5.insets = new Insets(0, 0, 5, 5); gbc_lblConfigMD5.gridx = 1; gbc_lblConfigMD5.gridy = row; configDetailPanel.add(lblConfigMD5, gbc_lblConfigMD5); txtConfigMD5 = new JTextField(); txtConfigMD5.getDocument().addDocumentListener(configDocumentListener); GridBagConstraints gbc_txtConfigMD5 = new GridBagConstraints(); gbc_txtConfigMD5.gridwidth = 3; gbc_txtConfigMD5.insets = new Insets(0, 0, 5, 5); gbc_txtConfigMD5.fill = GridBagConstraints.HORIZONTAL; gbc_txtConfigMD5.gridx = 2; gbc_txtConfigMD5.gridy = row; configDetailPanel.add(txtConfigMD5, gbc_txtConfigMD5); txtConfigMD5.setColumns(10); row++; JButton btnConfigAdd = new JButton("Add"); btnConfigAdd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ConfigFileWrapper newConfig = new ConfigFileWrapper(lstConfigParentId.getSelectedItem().toString(), new ConfigFile(txtConfigUrl.getText(), txtConfigPath.getText(), txtConfigMD5.getText())); modelConfig.add(newConfig); } }); GridBagConstraints gbc_btnConfigAdd = new GridBagConstraints(); gbc_btnConfigAdd.fill = GridBagConstraints.HORIZONTAL; gbc_btnConfigAdd.insets = new Insets(0, 0, 5, 5); gbc_btnConfigAdd.gridx = 1; gbc_btnConfigAdd.gridy = row; configDetailPanel.add(btnConfigAdd, gbc_btnConfigAdd); JButton btnConfigRemove = new JButton("Remove"); btnConfigRemove.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { modelConfig.remove(configCurrentSelection); clearConfigDetailPane(); lstConfigParentId.setSelectedIndex(-1); lstConfigFiles.clearSelection(); } }); GridBagConstraints gbc_btnConfigRemove = new GridBagConstraints(); gbc_btnConfigRemove.fill = GridBagConstraints.HORIZONTAL; gbc_btnConfigRemove.insets = new Insets(0, 0, 5, 5); gbc_btnConfigRemove.gridx = 2; gbc_btnConfigRemove.gridy = row; configDetailPanel.add(btnConfigRemove, gbc_btnConfigRemove); JButton btnConfigUpdate = new JButton("Update"); btnConfigUpdate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateConfigEntry(); } }); GridBagConstraints gbc_btnConfigUpdate = new GridBagConstraints(); gbc_btnConfigUpdate.fill = GridBagConstraints.HORIZONTAL; gbc_btnConfigUpdate.insets = new Insets(0, 0, 5, 5); gbc_btnConfigUpdate.gridx = 3; gbc_btnConfigUpdate.gridy = row; configDetailPanel.add(btnConfigUpdate, gbc_btnConfigUpdate); row++; Component rigidArea_3 = Box.createRigidArea(new Dimension(3, 3)); GridBagConstraints gbc_rigidArea_3 = new GridBagConstraints(); gbc_rigidArea_3.gridx = 5; gbc_rigidArea_3.gridy = row; configDetailPanel.add(rigidArea_3, gbc_rigidArea_3); } } protected void clearConfigDetailPane() { lstConfigParentId.setSelectedIndex(-1); txtConfigPath.setText(""); txtConfigUrl.setText(""); txtConfigMD5.setText(""); configDirty = false; } protected void clearModuleDetailPane() { txtModName.setText(""); txtModId.setText(""); txtModDepends.setText(""); txtModMD5.setText(""); txtModUrl.setText(""); chkModCoreMod.setSelected(false); chkModExtract.setSelected(false); chkModInJar.setSelected(false); chkModInRoot.setSelected(false); chkModIsDefault.setSelected(false); chkModRequired.setSelected(false); moduleDirty = false; } protected void clearServerDetailPane() { txtServerAddress.setText(""); txtServerID.setText(""); txtServerName.setText(""); txtServerNewsUrl.setText(""); txtServerIconUrl.setText(""); txtServerMCVersion.setText(""); txtServerRevision.setText(""); chkServerGenerateList.setSelected(false); serverDirty = false; } protected void doSave(Path outputFile) { try { BufferedWriter fileWriter = Files.newBufferedWriter(outputFile, StandardCharsets.UTF_8, StandardOpenOption.CREATE); fileWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); fileWriter.newLine(); fileWriter.write("<ServerPack version=\"" + Version.API_VERSION + "\" xmlns:xsi='http: fileWriter.newLine(); for (ServerDefinition server : modelServer.getContents()) { fileWriter.write("\t<Server id=\"" + server.getServer().getServerId() + "\" name=\"" + server.getServer().getName() + "\" newsUrl=\"" + server.getServer().getNewsUrl() + "\" iconUrl=\"" + server.getServer().getIconUrl() + "\" version=\"" + server.getServer().getVersion() + "\" serverAddress=\"" + server.getServer().getAddress() + "\" revision=\"" + server.getServer().getRevision() + "\" generateList=\"" + server.getServer().isGenerateList() + "\">"); fileWriter.newLine(); for (Module entry : server.getModules()) { fileWriter.write("\t\t<Module name=\"" + entry.getName() + "\" id=\"" + entry.getId() + "\" depends=\"" + entry.getDepends() + "\">"); fileWriter.newLine(); fileWriter.write("\t\t\t<URL>" + entry.getUrl() + "</URL>"); fileWriter.newLine(); fileWriter.write("\t\t\t<Required>" + (entry.getRequired() == true ? "true" : "false") + "</Required>"); fileWriter.newLine(); fileWriter.write("\t\t\t<InJar>" + (entry.getInJar() == true ? "true" : "false") + "</InJar>"); fileWriter.newLine(); fileWriter.write("\t\t\t<IsDefault>" + (entry.getIsDefault() == true ? "true" : "false") + "</IsDefault>"); fileWriter.newLine(); fileWriter.write("\t\t\t<Extract>" + (entry.getExtract() == true ? "true" : "false") + "</Extract>"); fileWriter.newLine(); fileWriter.write("\t\t\t<InRoot>" + (entry.getInRoot() == true ? "true" : "false") + "</InRoot>"); fileWriter.newLine(); fileWriter.write("\t\t\t<CoreMod>" + (entry.getCoreMod() == true ? "true" : "false") + "</CoreMod>"); fileWriter.newLine(); fileWriter.write("\t\t\t<MD5>" + entry.getMD5() + "</MD5>"); fileWriter.newLine(); for (ConfigFileWrapper cfw : server.getConfigs()) { if (cfw.getParentId().equals(entry.getId())) { fileWriter.write("\t\t\t\t<ConfigFile>"); fileWriter.newLine(); fileWriter.write("\t\t\t\t\t<URL>" + cfw.getConfigFile().getUrl() + "</URL>"); fileWriter.newLine(); fileWriter.write("\t\t\t\t\t<Path>" + cfw.getConfigFile().getPath() + "</Path>"); fileWriter.newLine(); fileWriter.write("\t\t\t\t\t<MD5>" + cfw.getConfigFile().getMD5() + "</MD5>"); fileWriter.newLine(); fileWriter.write("\t\t\t\t</ConfigFile>"); fileWriter.newLine(); } } fileWriter.write("\t\t</Module>"); fileWriter.newLine(); } fileWriter.write("\t</Server>"); fileWriter.newLine(); } fileWriter.write("</ServerPack>"); fileWriter.newLine(); fileWriter.close(); } catch (IOException e1) { e1.printStackTrace(); } } public void AddModule(Module newMod) { modelModule.add(newMod); modelParentId.add(newMod.getId()); } public void AddConfig(ConfigFileWrapper newConfig) { modelConfig.add(newConfig); } @Override public void setLblStatus(String string) { } @Override public void setProgressBar(int i) { } @Override public void log(String msg) { } @Override public boolean requestLogin() { return false; } private void updateServerEntry() { ServerList entry = new ServerList(txtServerID.getText(),txtServerName.getText(),"",txtServerNewsUrl.getText(),txtServerIconUrl.getText(),txtServerMCVersion.getText(),txtServerAddress.getText(),chkServerGenerateList.isSelected(),txtServerRevision.getText()); List<Module> newModules = new ArrayList<Module>(); newModules.addAll(modelModule.getContents()); List<ConfigFileWrapper> newConfigs = new ArrayList<ConfigFileWrapper>(); newConfigs.addAll(modelConfig.getContents()); modelServer.replace(serverCurrentSelection, new ServerDefinition(entry, newModules, newConfigs)); serverDirty = false; } private void updateModuleEntry() { modelParentId.replaceEntry(lstModules.getSelectedValue().getId(), txtModId.getText()); Module newMod = new Module(txtModName.getText(), txtModId.getText(), txtModUrl.getText(), txtModDepends.getText(), chkModRequired.isSelected(), chkModInJar.isSelected(), chkModExtract.isSelected(), chkModInRoot.isSelected(), chkModIsDefault.isSelected(), chkModCoreMod.isSelected(), txtModMD5.getText(), null); modelModule.replace(moduleCurrentSelection, newMod); moduleDirty = false; serverDirty = true; } private void updateConfigEntry() { String modId = ""; try { modId = lstConfigParentId.getSelectedItem().toString(); } catch (Exception e) { /* no op */ } ConfigFileWrapper newConfig = new ConfigFileWrapper(modId, new ConfigFile(txtConfigUrl.getText(), txtConfigPath.getText(), txtConfigMD5.getText())); modelConfig.replace(configCurrentSelection, newConfig); configDirty = false; serverDirty = true; } } class ModuleListModel extends AbstractListModel<Module> { private static final long serialVersionUID = 8669589670935830304L; private List<Module> modules = new ArrayList<Module>(); public ModuleListModel(List<Module> modList) { this.modules = modList; } public void moveUp(int current) { Collections.swap(modules, current, current-1); this.fireContentsChanged(this, current-1, current); } public void moveDown(int current) { Collections.swap(modules, current, current+1); this.fireContentsChanged(this, current, current+1); } public void sort() { Collections.sort(this.modules, new SortModules()); this.fireContentsChanged(this, 0, this.modules.size()); } public void clear() { int current = modules.size() - 1; modules.clear(); this.fireContentsChanged(this, 0, current); } public void replace(int index, Module newModule) { this.modules.set(index, newModule); this.fireContentsChanged(this, index, index); } public void add(Module newModule) { this.modules.add(newModule); this.fireContentsChanged(this, 0, modules.size()); } public void remove(int index) { this.modules.remove(index); this.fireContentsChanged(this, 0, modules.size()); } public List<Module> getContents() { return this.modules; } @Override public int getSize() { return this.modules.size(); } @Override public Module getElementAt(int index) { return this.modules.get(index); } } class ConfigFileListModel extends AbstractListModel<ConfigFileWrapper> { private static final long serialVersionUID = 4310927230482995630L; private List<ConfigFileWrapper> configs = new ArrayList<ConfigFileWrapper>(); public ConfigFileListModel(List<ConfigFileWrapper> configList) { this.configs = configList; } public void clear() { int current = configs.size() - 1; this.configs.clear(); this.fireContentsChanged(this, 0, current); } public void add(ConfigFileWrapper newConfig) { this.configs.add(newConfig); this.fireContentsChanged(this, 0, configs.size()); } public void replace(int index, ConfigFileWrapper newConfig) { this.configs.set(index, newConfig); this.fireContentsChanged(this, 0, configs.size()); } public void remove(int index) { this.configs.remove(index); this.fireContentsChanged(this, 0, configs.size()); } public List<ConfigFileWrapper> getContents() { return this.configs; } @Override public int getSize() { return this.configs.size(); } @Override public ConfigFileWrapper getElementAt(int index) { return this.configs.get(index); } } class ModIdListModel extends AbstractListModel<String> implements ComboBoxModel<String> { private static final long serialVersionUID = -1133359312481243116L; private List<String> list = new ArrayList<String>(); private String selected; public void clear() { int current = list.size() - 1; this.list.clear(); this.fireContentsChanged(this, 0, current); } public int find(String parentId) { return this.list.indexOf(parentId); } public void add(String entry) { this.list.add(entry); sort(); } public void remove(int index) { this.list.remove(index); sort(); } public void replaceEntry(String oldEntry, String newEntry) { this.list.remove(oldEntry); this.list.add(newEntry); sort(); } public void sort() { Collections.sort(this.list, new SortIgnoreCase()); this.fireContentsChanged(this, 0, this.list.size()-1); } @Override public int getSize() { return this.list.size(); } @Override public String getElementAt(int index) { return this.list.get(index); } @Override public void setSelectedItem(Object anItem) { int newIndex = this.list.indexOf(anItem); if (newIndex >= 0) { this.selected = this.list.get(newIndex); } else { this.selected = ""; } } @Override public Object getSelectedItem() { return this.selected; } } class ServerListModel extends AbstractListModel<ServerDefinition> { private static final long serialVersionUID = 1724821606072665288L; private List<ServerDefinition> servers = new ArrayList<ServerDefinition>(); @Override public int getSize() { return this.servers.size(); } public void clear() { int current = servers.size() - 1; this.servers.clear(); this.fireContentsChanged(this, 0, current); } public void add(ServerDefinition newServer) { this.servers.add(newServer); this.fireContentsChanged(this, 0, servers.size()); } public void replace(int index, ServerDefinition newServer) { this.servers.set(index, newServer); this.fireContentsChanged(this, 0, servers.size()); } public void remove(int index) { this.servers.remove(index); this.fireContentsChanged(this, 0, servers.size()); } @Override public ServerDefinition getElementAt(int index) { return this.servers.get(index); } public List<ServerDefinition> getContents() { return this.servers; } } class SortIgnoreCase implements Comparator<String> { @Override public int compare(String arg0, String arg1) { return arg0.compareToIgnoreCase(arg1.toLowerCase()); } } class SortModules implements Comparator<Module> { @Override public int compare(Module o1, Module o2) { Integer o1weight = (o1.getInJar() ? 0 : (o1.getCoreMod() ? 1 : 2)); Integer o2weight = (o2.getInJar() ? 0 : (o2.getCoreMod() ? 1 : 2)); if (o1weight == o2weight) { return o1.getName().compareToIgnoreCase(o2.getName()); } else { return o1weight.compareTo(o2weight); } } }
package com.namelessdev.mpdroid; import java.util.ArrayList; import java.util.Collections; import org.a0z.mpd.Album; import org.a0z.mpd.Artist; import org.a0z.mpd.Music; import org.a0z.mpd.exception.MPDServerException; import android.app.ActionBar; import android.app.ActionBar.Tab; import android.app.ActionBar.TabListener; import android.app.FragmentTransaction; import android.app.SearchManager; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; import com.namelessdev.mpdroid.MPDroidActivities.MPDroidActivity; import com.namelessdev.mpdroid.adapters.SeparatedListAdapter; import com.namelessdev.mpdroid.helpers.MPDAsyncHelper.AsyncExecListener; import com.namelessdev.mpdroid.library.SimpleLibraryActivity; import com.namelessdev.mpdroid.tools.Tools; import com.namelessdev.mpdroid.views.SearchResultDataBinder; public class SearchActivity extends MPDroidActivity implements OnMenuItemClickListener, AsyncExecListener, OnItemClickListener, TabListener { public static final int MAIN = 0; public static final int PLAYLIST = 3; public static final int ADD = 0; public static final int ADDNREPLACE = 1; public static final int ADDNREPLACEPLAY = 3; public static final int ADDNPLAY = 2; private MPDApplication app; private ArrayList<Artist> arrayArtistsResults; private ArrayList<Album> arrayAlbumsResults; private ArrayList<Music> arraySongsResults; protected int iJobID = -1; private ListView listArtists = null; private ListView listAlbums = null; private ListView listSongs = null; protected View loadingView; protected TextView loadingTextView; protected View noResultArtistsView; protected View noResultAlbumsView; protected View noResultSongsView; protected ViewPager pager; private Tab tabArtists; private Tab tabAlbums; private Tab tabSongs; private int addString, addedString; private String searchKeywords = ""; public SearchActivity() { addString = R.string.addSong; addedString = R.string.songAdded; arrayArtistsResults = new ArrayList<Artist>(); arrayAlbumsResults = new ArrayList<Album>(); arraySongsResults = new ArrayList<Music>(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); app = (MPDApplication) getApplication(); setContentView(R.layout.search_results); SearchResultsPagerAdapter adapter = new SearchResultsPagerAdapter(); pager = (ViewPager) findViewById(R.id.pager); pager.setAdapter(adapter); pager.setOnPageChangeListener( new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { // When swiping between pages, select the // corresponding tab. getActionBar().setSelectedNavigationItem(position); } }); final ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); tabArtists = actionBar.newTab() .setText(R.string.artists) .setTabListener(this); actionBar.addTab(tabArtists); tabAlbums = actionBar.newTab() .setText(R.string.albums) .setTabListener(this); actionBar.addTab(tabAlbums); tabSongs = actionBar.newTab() .setText(R.string.songs) .setTabListener(this); actionBar.addTab(tabSongs); listArtists = (ListView) findViewById(R.id.list_artists); listArtists.setOnItemClickListener(this); listAlbums = (ListView) findViewById(R.id.list_albums); listAlbums.setOnItemClickListener(this); listSongs = (ListView) findViewById(R.id.list_songs); listSongs.setOnItemClickListener(this); loadingView = findViewById(R.id.loadingLayout); loadingTextView = (TextView) findViewById(R.id.loadingText); noResultArtistsView = findViewById(R.id.noResultArtistsLayout); noResultAlbumsView = findViewById(R.id.noResultAlbumsLayout); noResultSongsView = findViewById(R.id.noResultSongsLayout); loadingView.setVisibility(View.VISIBLE); loadingTextView.setText(R.string.loading); final Intent queryIntent = getIntent(); final String queryAction = queryIntent.getAction(); if (Intent.ACTION_SEARCH.equals(queryAction)) { searchKeywords = queryIntent.getStringExtra(SearchManager.QUERY).trim(); } else { return; // Bye ! } setTitle(getTitle() + " : " + searchKeywords); registerForContextMenu(listArtists); registerForContextMenu(listAlbums); registerForContextMenu(listSongs); updateList(); getActionBar().setDisplayHomeAsUpEnabled(true); } @Override public void onStart() { super.onStart(); MPDApplication app = (MPDApplication) getApplicationContext(); app.setActivity(this); } @Override public void onStop() { super.onStop(); MPDApplication app = (MPDApplication) getApplicationContext(); app.unsetActivity(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.mpd_searchmenu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_search: this.onSearchRequested(); return true; case android.R.id.home: final Intent i = new Intent(this, MainMenuActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); return true; } return false; } private String getItemName(Object o) { if (o instanceof Music) { return ((Music) o).getTitle(); } else if (o instanceof Artist) { return ((Artist) o).getName(); } else if (o instanceof Album) { return ((Album) o).getName(); } return ""; } private void setContextForObject(Object object) { if (object instanceof Music) { addString = R.string.addSong; addedString = R.string.songAdded; } else if (object instanceof Artist) { addString = R.string.addArtist; addedString = R.string.artistAdded; } else if (object instanceof Album) { addString = R.string.addAlbum; addedString = R.string.albumAdded; } } public void onItemClick(AdapterView<?> adapterView, View v, int position, long id) { Object selectedItem = adapterView.getAdapter().getItem(position); if (selectedItem instanceof Music) { add((Music) selectedItem, false, false); } else if (selectedItem instanceof Artist) { Intent intent = new Intent(this, SimpleLibraryActivity.class); intent.putExtra("artist", ((Artist) selectedItem)); startActivityForResult(intent, -1); } else if (selectedItem instanceof Album) { Intent intent = new Intent(this, SimpleLibraryActivity.class); intent.putExtra("album", ((Album) selectedItem)); startActivityForResult(intent, -1); } } protected void add(Object object, boolean replace, boolean play) { setContextForObject(object); if (object instanceof Music) { add((Music) object, replace, play); } else if (object instanceof Artist) { add(((Artist) object), null, replace, play); } else if (object instanceof Album) { Album album = (Album) object; add(album.getArtist(), album, replace, play); } } protected void add(Artist artist, Album album, boolean replace, boolean play) { try { app.oMPDAsyncHelper.oMPD.add(artist, album, replace, play); Tools.notifyUser(String.format(getResources().getString(addedString), null == album ? artist.getName() : (null == artist ? album.getName() : artist.getName() + " - " + album.getName())), this); } catch (MPDServerException e) { e.printStackTrace(); } } protected void add(Music music, boolean replace, boolean play) { try { app.oMPDAsyncHelper.oMPD.add(music, replace, play); Tools.notifyUser(String.format(getResources().getString(R.string.songAdded, music.getTitle()), music.getName()), this); } catch (MPDServerException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void updateList() { app.oMPDAsyncHelper.addAsyncExecListener(this); iJobID = app.oMPDAsyncHelper.execAsync(new Runnable() { @Override public void run() { asyncUpdate(); } }); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; ArrayList<? extends Object> targetArray; switch (pager.getCurrentItem()) { default: case 0: targetArray = arrayArtistsResults; break; case 1: targetArray = arrayAlbumsResults; break; case 2: targetArray = arraySongsResults; break; } final Object item = targetArray.get((int) info.id); menu.setHeaderTitle(getItemName(item)); setContextForObject(item); android.view.MenuItem addItem = menu.add(ContextMenu.NONE, ADD, 0, getResources().getString(addString)); addItem.setOnMenuItemClickListener(this); android.view.MenuItem addAndReplaceItem = menu.add(ContextMenu.NONE, ADDNREPLACE, 0, R.string.addAndReplace); addAndReplaceItem.setOnMenuItemClickListener(this); android.view.MenuItem addAndReplacePlayItem = menu.add(ContextMenu.NONE, ADDNREPLACEPLAY, 0, R.string.addAndReplacePlay); addAndReplacePlayItem.setOnMenuItemClickListener(this); android.view.MenuItem addAndPlayItem = menu.add(ContextMenu.NONE, ADDNPLAY, 0, R.string.addAndPlay); addAndPlayItem.setOnMenuItemClickListener(this); } @Override public boolean onMenuItemClick(final android.view.MenuItem item) { final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); final MPDApplication app = (MPDApplication) getApplication(); ArrayList<? extends Object> targetArray; switch (pager.getCurrentItem()) { default: case 0: targetArray = arrayArtistsResults; break; case 1: targetArray = arrayAlbumsResults; break; case 2: targetArray = arraySongsResults; break; } final Object selectedItem = targetArray.get((int) info.id); app.oMPDAsyncHelper.execAsync(new Runnable() { @Override public void run() { boolean replace = false; boolean play = false; switch (item.getItemId()) { case ADDNREPLACEPLAY: replace = true; play = true; break; case ADDNREPLACE: replace = true; break; case ADDNPLAY: play = true; break; } add(selectedItem, replace, play); } }); return false; } protected void asyncUpdate() { final String finalsearch = this.searchKeywords.toLowerCase(); ArrayList<Music> arrayMusic = null; try { arrayMusic = (ArrayList<Music>) app.oMPDAsyncHelper.oMPD.search("any", finalsearch); } catch (MPDServerException e) { } arrayArtistsResults.clear(); arrayAlbumsResults.clear(); arraySongsResults.clear(); String tmpValue; boolean valueFound; for (Music music : arrayMusic) { if (music.getTitle() != null && music.getTitle().toLowerCase().contains(finalsearch)) { arraySongsResults.add(music); } valueFound = false; tmpValue = music.getArtist(); if (tmpValue != null && tmpValue.toLowerCase().contains(finalsearch)) { for (Artist artistItem : arrayArtistsResults) { if (artistItem.getName().equalsIgnoreCase(tmpValue)) valueFound = true; } if (!valueFound) arrayArtistsResults.add(new Artist(tmpValue, 0)); } valueFound = false; tmpValue = music.getAlbum(); if (tmpValue != null && tmpValue.toLowerCase().contains(finalsearch)) { for (Album albumItem : arrayAlbumsResults) { if (albumItem.getName().equalsIgnoreCase(tmpValue)) valueFound = true; } if (!valueFound) arrayAlbumsResults.add(new Album(tmpValue, new Artist(music.getArtist()))); } } Collections.sort(arrayArtistsResults); Collections.sort(arrayAlbumsResults); Collections.sort(arraySongsResults); runOnUiThread(new Runnable() { @Override public void run() { tabArtists.setText(getString(R.string.artists) + " (" + arrayArtistsResults.size() + ")"); tabAlbums.setText(getString(R.string.albums) + " (" + arrayAlbumsResults.size() + ")"); tabSongs.setText(getString(R.string.songs) + " (" + arraySongsResults.size() + ")"); } }); } /** * Update the view from the items list if items is set. */ public void updateFromItems() { if (arrayArtistsResults != null) { listArtists.setAdapter(new SeparatedListAdapter(this, R.layout.search_list_item, new SearchResultDataBinder(), arrayArtistsResults)); try { listArtists.setEmptyView(noResultArtistsView); loadingView.setVisibility(View.GONE); } catch (Exception e) { } } if (arrayAlbumsResults != null) { listAlbums.setAdapter(new SeparatedListAdapter(this, R.layout.search_list_item, new SearchResultDataBinder(), arrayAlbumsResults)); try { listAlbums.setEmptyView(noResultAlbumsView); loadingView.setVisibility(View.GONE); } catch (Exception e) { } } if (arraySongsResults != null) { listSongs.setAdapter(new SeparatedListAdapter(this, R.layout.search_list_item, new SearchResultDataBinder(), arraySongsResults)); try { listSongs.setEmptyView(noResultSongsView); loadingView.setVisibility(View.GONE); } catch (Exception e) { } } } @Override public void asyncExecSucceeded(int jobID) { if (iJobID == jobID) { updateFromItems(); } } class SearchResultsPagerAdapter extends PagerAdapter { public Object instantiateItem(View collection, int position) { int resId = 0; switch (position) { case 0: resId = R.id.list_artists; break; case 1: resId = R.id.list_albums; break; case 2: resId = R.id.list_songs; break; } return findViewById(resId); } @Override public int getCount() { return 3; } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == ((View) arg1); } @Override public void destroyItem(ViewGroup container, int position, Object object) { return; } } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { return; } @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { pager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { return; } }
package au.gov.amsa.ais.router; import au.gov.amsa.ais.router.model.Connection; import au.gov.amsa.ais.router.model.Group; import au.gov.amsa.ais.router.model.Port; public class RouterMain { public static void main(String[] args) throws InterruptedException { // setup connections Connection terrestrial = Connection.builder().id("terrestrial").host("mariweb.amsa.gov.au") .port(9010).readTimeoutSeconds(10).retryIntervalSeconds(1).build(); Connection satellite = Connection.builder().id("satellite").host("mariweb.amsa.gov.au") .port(9100).readTimeoutSeconds(10).retryIntervalSeconds(5).build(); // set up groups Group groupAll = Group.builder().id("all").member(terrestrial).member(satellite).build(); Group kembla = Group.builder().id("Port Kembla").member(terrestrial).filterPattern("Kembla") .build(); // set up ports Port portAll = Port.builder().group(groupAll).port(9000).build(); Port portTerrestrial = Port.builder().group(terrestrial).port(9001).build(); Port portKembla = Port.builder().group(kembla).port(9002).build(); // start Router.start(portAll, portTerrestrial, portKembla); Thread.sleep(Long.MAX_VALUE); } }
apackage com.allaboutolaf; import android.app.Application; import android.net.http.HttpResponseCache; import android.os.Bundle; import android.util.Log; // keep these sorted alphabetically import com.avishayil.rnrestart.ReactNativeRestartPackage; import com.bugsnag.BugsnagReactNative; import com.BV.LinearGradient.LinearGradientPackage; import com.calendarevents.CalendarEventsPackage; import com.facebook.react.ReactApplication; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.facebook.soloader.SoLoader; import com.github.droibit.android.reactnative.customtabs.CustomTabsPackage; import com.idehub.GoogleAnalyticsBridge.GoogleAnalyticsBridgePackage; import com.learnium.RNDeviceInfo.RNDeviceInfo; import com.mapbox.rctmgl.RCTMGLPackage; import com.oblador.keychain.KeychainPackage; import com.oblador.vectoricons.VectorIconsPackage; import com.pusherman.networkinfo.RNNetworkInfoPackage; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), // please keep these sorted alphabetically BugsnagReactNative.getPackage(), new CalendarEventsPackage(), new CustomTabsPackage(), new GoogleAnalyticsBridgePackage(), new KeychainPackage(), new LinearGradientPackage(), new RCTMGLPackage(), new ReactNativeRestartPackage(), new RNDeviceInfo(), new RNNetworkInfoPackage(), new VectorIconsPackage() ); } @Override protected String getJSMainModuleName() { return "index"; } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); // set up network cache try { File httpCacheDir = new File(getApplicationContext().getCacheDir(), "http"); long httpCacheSize = 20 * 1024 * 1024; // 20 MiB HttpResponseCache.install(httpCacheDir, httpCacheSize); } catch (IOException e) { Log.i("allaboutolaf", "HTTP response cache installation failed:", e); // Log.i(TAG, "HTTP response cache installation failed:", e); } } public void onStop() { HttpResponseCache cache = HttpResponseCache.getInstalled(); if (cache != null) { cache.flush(); } } }
package com.artirigo.kontaktio; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableMap; import com.kontakt.sdk.android.ble.connection.OnServiceReadyListener; import com.kontakt.sdk.android.ble.device.BeaconRegion; import com.kontakt.sdk.android.ble.manager.ProximityManager; import com.kontakt.sdk.android.common.KontaktSDK; import java.util.HashMap; import java.util.Map; import java.util.UUID; import android.util.Log; import static com.artirigo.kontaktio.ReactUtils.sendEvent; public class KontaktModule extends ReactContextBaseJavaModule { private static final String TAG = "KontaktModule"; private static ReactApplicationContext reactAppContext; private static final String DEFAULT_KONTAKT_BEACON_PROXIMITY_UUID = "DEFAULT_KONTAKT_BEACON_PROXIMITY_UUID"; private static final String DEFAULT_KONTAKT_NAMESPACE_ID = "DEFAULT_KONTAKT_NAMESPACE_ID"; private static final String BEACON_REGION_ANY_MAJOR = "ANY_MAJOR"; private static final String BEACON_REGION_ANY_MINOR = "ANY_MINOR"; private static final String PROXIMITY_IMMEDIATE = "PROXIMITY_IMMEDIATE"; private static final String PROXIMITY_NEAR = "PROXIMITY_NEAR"; private static final String PROXIMITY_FAR = "PROXIMITY_FAR"; private static final String PROXIMITY_UNKNOWN = "PROXIMITY_UNKNOWN"; private static final String SORT_ASC = "SORT_ASC"; private static final String SORT_DESC = "SORT_DESC"; private static final String SORT_DISABLED = "SORT_DISABLED"; private ProximityManager proximityManager; // Local BeaconProximityManager class initializes the beacon scanner private BeaconProximityManager beaconProximityManager; private Configuration configuration; private BeaconListeners beaconListeners; private ScanManager scanManager; private RegionManager regionManager; // Promise used to connect to beacons private Promise connectPromise; private WritableMap connectMap; public KontaktModule(ReactApplicationContext reactAppContext) { super(reactAppContext); this.reactAppContext = reactAppContext; this.connectMap = Arguments.createMap(); } @Override public String getName() { return "KontaktBeacons"; } @Override public Map<String, Object> getConstants() { final Map<String, Object> constants = new HashMap<>(); constants.put(DEFAULT_KONTAKT_BEACON_PROXIMITY_UUID, String.valueOf(KontaktSDK.DEFAULT_KONTAKT_BEACON_PROXIMITY_UUID)); constants.put(DEFAULT_KONTAKT_NAMESPACE_ID, String.valueOf(KontaktSDK.DEFAULT_KONTAKT_NAMESPACE_ID)); constants.put(BEACON_REGION_ANY_MAJOR, BeaconRegion.ANY_MAJOR); constants.put(BEACON_REGION_ANY_MINOR, BeaconRegion.ANY_MINOR); // constants.put(PROXIMITY_IMMEDIATE, String.valueOf(Proximity.IMMEDIATE)); // constants.put(PROXIMITY_NEAR, String.valueOf(Proximity.NEAR)); // constants.put(PROXIMITY_FAR, String.valueOf(Proximity.FAR)); // constants.put(PROXIMITY_UNKNOWN, String.valueOf(Proximity.UNKNOWN)); // constants.put(SORT_ASC, String.valueOf(DistanceSort.ASC)); // constants.put(SORT_DESC, String.valueOf(DistanceSort.DESC)); // constants.put(SORT_DISABLED, String.valueOf(DistanceSort.DISABLED)); return constants; } // Methods exposed to React Native @ReactMethod public void connect(String apiKey, ReadableArray beaconTypes, Promise promise) { try { connectPromise = promise; beaconProximityManager = new BeaconProximityManager(reactAppContext, apiKey); proximityManager = beaconProximityManager.init(beaconTypes); // proximityManager = beaconProximityManager.getProximityManager(); configuration = beaconProximityManager.getConfiguration(); beaconListeners = beaconProximityManager.getBeaconListeners(); scanManager = beaconProximityManager.getScanManager(); regionManager = beaconProximityManager.getRegionManager(); // connect to beaconManager proximityManager.connect(serviceReadyListener); } catch (Exception e) { connectPromise.reject(Constants.EXCEPTION, e); } } OnServiceReadyListener serviceReadyListener = new OnServiceReadyListener() { @Override public void onServiceReady() { connectMap = Arguments.createMap(); try { // Send event connectMap.putBoolean("isReady", true); sendEvent(reactAppContext, "beaconInitStatus", connectMap); // Resolve promise connectPromise.resolve(null); } catch (Exception e) { // from native module // Send event connectMap.putBoolean("isReady", false); sendEvent(reactAppContext, "beaconInitStatus", connectMap); // Reject promise connectPromise.reject(Constants.EXCEPTION, e); } } }; // From BeaconProximityManager @ReactMethod public void disconnect(Promise promise) { if (beaconProximityManager != null) { beaconProximityManager.disconnect(promise); } else { promise.reject( "Did you forget to call connect() or did the connect() call fail? The beaconProximityManager object is not defined."); } } @ReactMethod public void isConnected(Promise promise) { if (beaconProximityManager != null || proximityManager != null) { beaconProximityManager.isConnected(promise); } else { Log.w(Constants.TAG, "Did you forget to call connect() or did the connect() call fail? The beaconProximityManager object is not defined."); promise.resolve(false); } } // From ScanManager @ReactMethod public void startScanning(Promise promise) { if (scanManager != null) { scanManager.startScanning(promise); } else { promise.reject( "Did you forget to call connect() or did the connect() call fail? The scanManager object is not defined."); } } @ReactMethod public void stopScanning(Promise promise) { if (scanManager != null) { scanManager.stopScanning(promise); } else { promise.reject( "Did you forget to call connect() or did the connect() call fail? The scanManager object is not defined."); } } @ReactMethod public void restartScanning(Promise promise) { if (scanManager != null) { scanManager.restartScanning(promise); } else { promise.reject( "Did you forget to call connect() or did the connect() call fail? The scanManager object is not defined."); } } @ReactMethod public void isScanning(Promise promise) { if (scanManager != null || proximityManager != null) { scanManager.isScanning(promise); } else { Log.w(Constants.TAG, "Did you forget to call connect() or did the connect() call fail? The scanManager object is not defined."); promise.resolve(false); } } // From Configuration @ReactMethod public void configure(ReadableMap params, Promise promise) { if (configuration != null) { configuration.configureProximityManager(params, promise); } else { promise.reject( "Did you forget to call connect() or did the connect() call fail? The configuration object is not defined."); } } // From RegionManager /** * Replaces the currently observed region(s) with the given region If region is * null or empty, the default region EVERYWHERE is used. * * Restart has to be triggered so that region changes take effect when changing * regions after scan started. * * @param region Object with IBeacon region data * @param promise */ @ReactMethod public void setBeaconRegion(ReadableMap regionParams, Promise promise) { if (regionManager != null) { regionManager.setBeaconRegion(regionParams, promise); } else { promise.reject( "Did you forget to call connect() or did the connect() call fail? The regionManager object is not defined."); } } @ReactMethod public void setBeaconRegions(ReadableArray regionsParams, Promise promise) { if (regionManager != null) { regionManager.setBeaconRegions(regionsParams, promise); } else { promise.reject( "Did you forget to call connect() or did the connect() call fail? The regionManager object is not defined."); } } @ReactMethod public void getBeaconRegions(Promise promise) { if (regionManager != null) { regionManager.getBeaconRegions(promise); } else { promise.reject( "Did you forget to call connect() or did the connect() call fail? The regionManager object is not defined."); } } @ReactMethod public void setEddystoneNamespace(ReadableMap namespaceParams, Promise promise) { if (regionManager != null) { regionManager.setEddystoneNamespace(namespaceParams, promise); } else { promise.reject( "Did you forget to call connect() or did the connect() call fail? The regionManager object is not defined."); } } }
package im.shimo.react.keyboard; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.support.annotation.Nullable; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.WindowManager; import android.view.accessibility.AccessibilityEvent; import android.webkit.WebView; import android.widget.EditText; import android.widget.PopupWindow; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.DisplayMetricsHolder; import com.facebook.react.uimanager.ReactShadowNode; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.events.RCTEventEmitter; import com.facebook.yoga.YogaEdge; import com.facebook.yoga.YogaPositionType; import java.util.ArrayList; public class KeyboardView extends ReactRootAwareViewGroup implements LifecycleEventListener, AdjustResizeWithFullScreen.OnKeyboardStatusListener { private final static String TAG = "KeyboardView"; private final ThemedReactContext mThemedContext; private final UIManagerModule mNativeModule; private @Nullable volatile KeyboardCoverView mCoverView; private @Nullable volatile KeyboardContentView mContentView; private int navigationBarHeight; private int statusBarHeight; private RCTEventEmitter mEventEmitter; private int mKeyboardPlaceholderHeight; private float mScale = DisplayMetricsHolder.getScreenDisplayMetrics().density; private boolean mContentVisible = true; private boolean mHideWhenKeyboardIsDismissed = true; private volatile int mChildCount; private View mEditFocusView; private volatile boolean initWhenAttached; private PopupWindow mContentViewPopupWindow; private int mMinContentViewHeight = 256; private boolean mKeyboardShownStatus; private int mUseBottom; private int mUseRight; private ValueAnimator translationSlide; // whether keyboard is shown private boolean mKeyboardShown = false; private volatile int mVisibility = -1; private int mOrientation = -1; private boolean isOrientationChange; public enum Events { EVENT_SHOW("onKeyboardShow"), EVENT_HIDE("onKeyboardHide"); private final String mName; Events(final String name) { mName = name; } @Override public String toString() { return mName; } } public KeyboardView(final ThemedReactContext context, int navigationBarHeight, int statusBarHeight) { super(context); this.mThemedContext = context; this.mNativeModule = mThemedContext.getNativeModule(UIManagerModule.class); this.navigationBarHeight = navigationBarHeight; this.statusBarHeight = statusBarHeight; mEventEmitter = context.getJSModule(RCTEventEmitter.class); context.addLifecycleEventListener(this); mContentViewPopupWindow = new PopupWindow(); mContentViewPopupWindow.setAnimationStyle(R.style.DialogAnimationSlide); mContentViewPopupWindow.setClippingEnabled(false); mContentViewPopupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT); mContentViewPopupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); mContentViewPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { mContentViewPopupWindow.setAttachedInDecor(true); } if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) { //PopupWindowPopupWindow mContentViewPopupWindow.setBackgroundDrawable(null); } else { mContentViewPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); } } @Override public void addView(View child, int index) { final ViewGroup view = getReactRootView(); if (view == null) { if (child instanceof KeyboardCoverView) { mCoverView = (KeyboardCoverView) child; } else if (child instanceof KeyboardContentView) { mContentView = (KeyboardContentView) child; } initWhenAttached = true; } else { if (child instanceof KeyboardCoverView) { if (mCoverView != null) { removeView(mCoverView); } mCoverView = (KeyboardCoverView) child; view.addView(mCoverView); mChildCount++; } else if (child instanceof KeyboardContentView) { if (mContentView != null) { removeView(mContentView); } mContentView = (KeyboardContentView) child; mContentViewPopupWindow.setContentView(mContentView); mContentViewPopupWindow.setWidth(AdjustResizeWithFullScreen.getUseRight()); } } if (KeyboardViewManager.DEBUG) { Log.e(TAG, "child = [" + child + "], index = [" + index + "]" + ",mHideWhenKeyboardIsDismissed=" + mHideWhenKeyboardIsDismissed + ",mContentVisible=" + mContentVisible + ",mKeyboardPlaceholderHeight=" + mKeyboardPlaceholderHeight ); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (KeyboardViewManager.DEBUG) { Log.e(TAG, "onAttachedToWindow,mOrientation=" + mOrientation); } if (mOrientation == -1) { mOrientation = getResources().getConfiguration().orientation; } AdjustResizeWithFullScreen.assistRegisterActivity(mThemedContext.getCurrentActivity(), statusBarHeight, navigationBarHeight, this); if (initWhenAttached) { initWhenAttached = false; final ViewGroup view = getReactRootView(); if (mCoverView != null) { if (mHideWhenKeyboardIsDismissed || (mContentView != null && mContentView.isShown())) { mCoverView.setVisibility(GONE); } else { keepCoverViewOnScreenFrom(AdjustResizeWithFullScreen.getUseBottom(), 0); mCoverView.setVisibility(VISIBLE); } view.addView(mCoverView); mChildCount++; } if (mContentView != null) { mContentViewPopupWindow.setContentView(mContentView); mContentViewPopupWindow.setWidth(AdjustResizeWithFullScreen.getUseRight()); } } } public void setHideWhenKeyboardIsDismissed(boolean hideWhenKeyboardIsDismissed) { mHideWhenKeyboardIsDismissed = hideWhenKeyboardIsDismissed; } public void setKeyboardPlaceholderHeight(int keyboardPlaceholderHeight) { if (AdjustResizeWithFullScreen.getKeyboardHeight() == 0) { mKeyboardPlaceholderHeight = (int) (keyboardPlaceholderHeight * mScale); } if (mContentView != null && mCoverView != null) { if (keyboardPlaceholderHeight > 0 && !mKeyboardShown) { final int height = AdjustResizeWithFullScreen.getKeyboardHeight(); final int useBottom = mCoverView.getBottom(); if (height != 0) { keepCoverViewOnScreenFrom(useBottom - height, height); } else { keepCoverViewOnScreenFrom(useBottom - mKeyboardPlaceholderHeight, mKeyboardPlaceholderHeight); } receiveEvent(Events.EVENT_SHOW); } } else if (mCoverView != null && !mContentVisible && !mHideWhenKeyboardIsDismissed && keyboardPlaceholderHeight == 0) { View viewGroup = mCoverView.getChildAt(0); while (!(viewGroup instanceof EditText) && ((ViewGroup) viewGroup).getChildCount() > 0) { viewGroup = ((ViewGroup) viewGroup).getChildAt(0); } if (viewGroup != null && viewGroup instanceof EditText) { if (!viewGroup.isFocused()) { keepCoverViewOnScreenFrom(AdjustResizeWithFullScreen.getUseBottom(), 0); mCoverView.setVisibility(VISIBLE); } else { //bug KeyboardUtil.showKeyboardOnTouch(viewGroup); } } } } public void setContentVisible(boolean contentVisible) { mContentVisible = contentVisible; if (contentVisible) { if (mCoverView == null) return; mCoverView.setVisibility(VISIBLE); keepCoverViewOnScreenFrom(mPreCoverHeight, mPreCoverBottom); } else { if (mEditFocusView != null) { if (mEditFocusView.isFocused()) { if (!mKeyboardShown) { if (mCoverView != null) { mCoverView.setVisibility(GONE); keepCoverViewOnScreenFrom(mPreCoverHeight, AdjustResizeWithFullScreen.getUseBottom()); if (mContentView != null) { removeContentView(); } } } } else { mKeyboardShown = true; onKeyboardClosed(); } } } } @Override public void onKeyboardOpened() { if (KeyboardViewManager.DEBUG) { Log.e(TAG, "onKeyboardOpened" + ",mHideWhenKeyboardIsDismissed=" + mHideWhenKeyboardIsDismissed + ",mContentVisible=" + mContentVisible + ",mKeyboardShown=" + mKeyboardShown + ",mKeyboardPlaceholderHeight=" + mKeyboardPlaceholderHeight ); } if (mKeyboardShown) return; mKeyboardShown = true; if (mEditFocusView == null) { View view = mThemedContext.getCurrentActivity().getWindow().getDecorView().findFocus(); if (view instanceof EditText || view instanceof WebView) { mEditFocusView = view; } } if (mContentView != null && mContentView.isShown()) { receiveEvent(Events.EVENT_HIDE); } if (mCoverView != null) { mCoverView.setVisibility(VISIBLE); receiveEvent(Events.EVENT_SHOW); } } @Override public void onKeyboardClosed() { if (KeyboardViewManager.DEBUG) { Log.e(TAG, "onKeyboardClosed" + ",mHideWhenKeyboardIsDismissed=" + mHideWhenKeyboardIsDismissed + ",mContentVisible=" + mContentVisible + ",mKeyboardShown=" + mKeyboardShown + ",mKeyboardPlaceholderHeight=" + mKeyboardPlaceholderHeight ); } if (!mKeyboardShown) return; mKeyboardShown = false; if (mContentView != null) { if (mContentVisible) { } else { if (mKeyboardPlaceholderHeight == 0) { receiveEvent(Events.EVENT_HIDE); } } } else { receiveEvent(Events.EVENT_HIDE); } if (mCoverView != null) { if (mEditFocusView != null && mEditFocusView.isFocused()) { if (mHideWhenKeyboardIsDismissed) { mCoverView.setVisibility(GONE); mContentViewPopupWindow.dismiss(); } else { if (mContentView == null) { if (mHideWhenKeyboardIsDismissed) { mCoverView.setVisibility(GONE); } else { mCoverView.setVisibility(VISIBLE); } } else { mCoverView.setVisibility(VISIBLE); } } } else { if (!mHideWhenKeyboardIsDismissed) { mCoverView.setVisibility(VISIBLE); } else { mCoverView.setVisibility(GONE); } } } } @Override public boolean onKeyboardResize(int heightOfLayout, int bottom) { if (KeyboardViewManager.DEBUG) { Log.e(TAG, "onKeyboardResize,heightOfLayout=" + heightOfLayout); Log.e(TAG, "onKeyboardResize,mCoverView.isShown()=" + mCoverView.isShown()); } if (mCoverView != null && AdjustResizeWithFullScreen.isInit()) { if (mCoverView.isShown()) { int diff = AdjustResizeWithFullScreen.getWindowBottom() - heightOfLayout; if (mContentVisible && diff <= navigationBarHeight + statusBarHeight) { int coverViewBottom = mCoverView.getBottom(); if (!AdjustResizeWithFullScreen.isFullscreen() && coverViewBottom + AdjustResizeWithFullScreen.getKeyboardHeight() == AdjustResizeWithFullScreen.getWindowBottom()) { coverViewBottom -= diff; } keepCoverViewOnScreenFrom(coverViewBottom, bottom); return true; } else { keepCoverViewOnScreenFrom(heightOfLayout, bottom); return true; } } if (mKeyboardShown) { keepCoverViewOnScreenFrom(heightOfLayout, bottom); } } return true; } @Override public void addChildrenForAccessibility(ArrayList<View> outChildren) { // Explicitly override this to prevent accessibility events being passed down to children // Those will be handled by the mHostView which lives in the PopupWindow } @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { // Explicitly override this to prevent accessibility events being passed down to children // Those will be handled by the mHostView which lives in the PopupWindow return false; } @Override public void onHostResume() { } @Override public void onHostPause() { } @Override protected void onWindowVisibilityChanged(int visibility) { super.onWindowVisibilityChanged(visibility); if (mVisibility != visibility) { if (KeyboardViewManager.DEBUG) { Log.e(TAG, "onWindowVisibilityChanged,mVisibility=" + mVisibility + ",visibility=" + visibility + ",mUseBottom=" + mUseBottom + ",mKeyboardShownStatus=" + mKeyboardShownStatus); } if (visibility == VISIBLE) { if (mUseBottom == 0 && !mKeyboardShownStatus) { return; } int orientation = getResources().getConfiguration().orientation; final boolean isOchanged = isOrientationChange = mOrientation != orientation; if (isOchanged) { mOrientation = orientation; mKeyboardShownStatus = false; mVisibility = visibility; return; } if (mKeyboardShownStatus) { mKeyboardShownStatus = false; if (mEditFocusView != null) { mEditFocusView.setFocusable(true); mEditFocusView.requestFocus(); } } else { if (mCoverView == null || !mCoverView.isShown() || mPreCoverHeight == 0) { mVisibility = visibility; return; } int diff = mUseBottom - AdjustResizeWithFullScreen.getUseBottom(); int diffR = mUseRight - getRootView().getWidth();//AdjustResizeWithFullScreen.getUseRight(); boolean isChanged = diff != 0 || diffR != 0 || isOchanged; if (isChanged) { keepCoverViewOnScreenFrom(mPreCoverHeight - diff, 0); } else { keepCoverViewOnScreenFrom(mPreCoverHeight, 0); } } mVisibility = visibility; } else if (visibility == GONE) { if (mEditFocusView != null && (KeyboardUtil.isKeyboardActive(mEditFocusView)) || mKeyboardShown) { mKeyboardShownStatus = true; } else { if (mCoverView != null) { mUseBottom = AdjustResizeWithFullScreen.getUseBottom(); mUseRight = getRootView().getWidth();//AdjustResizeWithFullScreen.getUseRight(); } } mVisibility = visibility; } } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); receiveEvent(Events.EVENT_HIDE); onDropInstance(); } @Override public void onHostDestroy() { ((ReactContext) getContext()).removeLifecycleEventListener(this); onDropInstance(); } public void onDropInstance() { if (mCoverView != null) { removeView(mCoverView); } if (mContentView != null) { removeView(mContentView); } AdjustResizeWithFullScreen.assistUnRegister(mThemedContext.getCurrentActivity()); // mContentView = null; // mCoverView = null; mEditFocusView = null; // mContentViewPopupWindow.dismiss(); mContentViewPopupWindow.setContentView(null); mVisibility = -1; mKeyboardShown = mKeyboardShownStatus = false; mOrientation = -1; mContentVisible = false; mKeyboardPlaceholderHeight = 0; if (translationSlide != null) { translationSlide = null; } } @Override public void removeView(final View child) { if (child == null) return; ViewParent viewParent = child.getParent(); if (viewParent != null) { if (KeyboardViewManager.DEBUG) { Log.e(TAG, "removeView,child=" + child); } if (child.equals(mCoverView)) { removeCoverView(child, (ViewGroup) viewParent); } else { removeContentView(); } child.setVisibility(GONE); } } private void removeCoverView(View child, ViewGroup viewParent) { mCoverView = null; viewParent.removeView(child); mChildCount if (!mContentVisible) { receiveEvent(Events.EVENT_HIDE); } mPreCoverBottom = mPreCoverHeight = mPreCoverWidth = 0; } private void removeContentView() { mContentViewPopupWindow.dismiss(); ViewGroup parent = (ViewGroup) mContentView.getParent(); if (parent != null) { parent.removeView(mContentView); } mContentView = null; receiveEvent(Events.EVENT_HIDE); mPreContentWidth = mPreContentHeight = mPreContentTop = 0; } @Override public void removeViewAt(int index) { if (index == 0 && mContentView != null) { removeView(mContentView); } else { removeView(mCoverView); } } @Override public int getChildCount() { return mChildCount; } @Override public View getChildAt(int index) { if (index == 0 && mContentView != null) { return mContentView; } else { return mCoverView; } } private void receiveEvent(Events event) { WritableMap map = Arguments.createMap(); map.putBoolean("keyboardShown", mKeyboardShown); mEventEmitter.receiveEvent(getId(), event.toString(), map); } private int mPreCoverHeight = 0; private int mPreCoverBottom = 0; private int mPreCoverWidth = 0; /** * CoverViewcoverViewcontentView */ private void keepCoverViewOnScreenFrom(final int height, final int bottom) { if (mCoverView != null) { ((ReactContext) getContext()).runOnNativeModulesQueueThread( new Runnable() { @Override public void run() { final int useRight = getReactRootView().getWidth();//AdjustResizeWithFullScreen.getUseRight(); //maybe its null in this thread if (!isOrientationChange && mPreCoverBottom == bottom && mPreCoverHeight == height && mPreCoverWidth == useRight || mCoverView == null) { postContentView(); return; } if (KeyboardViewManager.DEBUG) { Log.e(TAG, "keepCoverViewOnScreenFrom,height" + height + ",bottom=" + bottom + ",useRight=" + useRight); } mPreCoverBottom = bottom; mPreCoverHeight = height; mPreCoverWidth = useRight; try { ReactShadowNode coverShadowNode = mNativeModule.getUIImplementation().resolveShadowNode(mCoverView.getId()); if (bottom >= 0) { coverShadowNode.setPosition(YogaEdge.BOTTOM.intValue(), bottom); } coverShadowNode.setPosition(YogaEdge.TOP.intValue(), 0); coverShadowNode.setPositionType(YogaPositionType.ABSOLUTE); if (height > -1) { coverShadowNode.setStyleHeight(height); mNativeModule.updateNodeSize(mCoverView.getId(), useRight, height); } mNativeModule.getUIImplementation().dispatchViewUpdates(-1); postContentView(); } catch (Exception e) { e.printStackTrace(); } } private void postContentView() { post(new Runnable() { @Override public void run() { if (mContentVisible) { if (height > -1) { keepContentViewOnScreenFrom(height); } else { try { final int coverBottom = mCoverView == null ? -99 : mCoverView.getBottom(); if (coverBottom == -99) return; keepContentViewOnScreenFrom(coverBottom); } catch (Exception e) { //maybe its null in this thread e.printStackTrace(); } } } } }); } }); if (mPreCoverBottom == bottom && mPreCoverHeight == height) { return; } if (translationSlide != null) { if (translationSlide.isRunning() || translationSlide.isStarted()) { translationSlide.cancel(); } } translationSlide = ObjectAnimator.ofFloat(mCoverView, "alpha", 0, 1); translationSlide.start(); } } private int mPreContentHeight = 0; private int mPreContentTop = 0; private int mPreContentWidth = 0; /** * mCoverViewbottom * * @param top */ private void keepContentViewOnScreenFrom(int top) { if (mContentView != null) { if (mContentViewPopupWindow.getContentView() == null) { mContentViewPopupWindow.setContentView(mContentView); mContentViewPopupWindow.setWidth(AdjustResizeWithFullScreen.getUseRight()); } if (mKeyboardShown) { if (top != AdjustResizeWithFullScreen.getUseBottom()) { top = AdjustResizeWithFullScreen.getUseBottom(); } } final int tempHeight = getContentViewHeight(top); final int useRight = getReactRootView().getWidth();//AdjustResizeWithFullScreen.getUseRight(); if (KeyboardViewManager.DEBUG) { Log.e(TAG, "keepContentViewOnScreenFrom,height" + tempHeight + ",top=" + top + ",useRight=" + useRight); } ((ReactContext) getContext()).runOnNativeModulesQueueThread( new Runnable() { @Override public void run() { if (mContentView != null) { //maybe its null in this thread mNativeModule.updateNodeSize(mContentView.getId(), useRight, tempHeight); } } }); if (mContentViewPopupWindow.isShowing()) { boolean isOrientChanged = isOrientationChange; if (!isOrientChanged) { isOrientChanged = mOrientation == getResources().getConfiguration().orientation; } if (!isOrientChanged && mPreContentHeight == tempHeight && mPreContentTop == top && mPreContentWidth == useRight) { return; } if (isOrientChanged) { isOrientationChange = false; mOrientation = getResources().getConfiguration().orientation; } mContentViewPopupWindow.update(AdjustResizeWithFullScreen.getUseLeft(), top, useRight, tempHeight); } else { if (mContentViewPopupWindow.getHeight() != tempHeight) { mContentViewPopupWindow.setHeight(tempHeight); } if (mContentViewPopupWindow.getWidth() != useRight) { mContentViewPopupWindow.setWidth(useRight); } mContentViewPopupWindow.showAtLocation(AdjustResizeWithFullScreen.getDecorView(), Gravity.NO_GRAVITY, AdjustResizeWithFullScreen.getUseLeft(), top); } mPreContentHeight = tempHeight; mPreContentTop = top; mPreContentWidth = useRight; } } private int getContentViewHeight(int top) { int realKeyboardHeight = AdjustResizeWithFullScreen.getRemainingHeight(top); int keyboardHeight = AdjustResizeWithFullScreen.getKeyboardHeight(); if (realKeyboardHeight == 0 || realKeyboardHeight < keyboardHeight) { realKeyboardHeight = keyboardHeight; if (realKeyboardHeight == 0) { if (mKeyboardPlaceholderHeight != 0) { realKeyboardHeight = mKeyboardPlaceholderHeight; } else { realKeyboardHeight = mMinContentViewHeight; } } } return realKeyboardHeight; } }
package at.irian.ankor.delay; import at.irian.ankor.event.dispatch.EventDispatcher; import at.irian.ankor.ref.Ref; import at.irian.ankor.ref.RefContext; import java.util.concurrent.atomic.AtomicReference; /** * @author Manfred Geiler */ public class FloodControl { //private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(DelaySupport.class); private final Scheduler scheduler; private final EventDispatcher eventDispatcher; private final long delay; private final AtomicReference<Cancellable> lastDelayedRef = new AtomicReference<Cancellable>(); public FloodControl(Ref ref, long delay) { this(ref.context(), delay); } public FloodControl(RefContext refContext, long delay) { this(refContext.scheduler(), refContext.modelContext().getEventDispatcher(), delay); } public FloodControl(Scheduler scheduler, EventDispatcher eventDispatcher, long delay) { this.scheduler = scheduler; this.eventDispatcher = eventDispatcher; this.delay = delay; } public void control(final Runnable task) { Cancellable oldLastDelayed = lastDelayedRef.getAndSet( scheduler.schedule(delay, new Runnable() { @Override public void run() { eventDispatcher.dispatch(new TaskRequestEvent(FloodControl.this, task)); } }) ); if (oldLastDelayed != null) { oldLastDelayed.cancel(); } } }
package br.com.projeto.view; import br.com.projeto.model.Jogo; import java.awt.Color; import java.awt.Font; import javax.swing.JFrame; import javax.swing.SwingConstants; public class TelaInfoJogo extends javax.swing.JFrame { /** * Creates new form TelaInfoJogo * Commit */ public TelaInfoJogo() { initComponents(); } public TelaInfoJogo(Jogo jogo){ this(); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.getContentPane().setBackground(Color.WHITE); this.painel1.setBackground(Color.WHITE); Font f = InicioProjeto.getFonte(36); painel1.setFont(f); lbTime1.setIcon(jogo.getTime1().getEscudo()); lbTime1.setFont(f); lbTime1.setHorizontalAlignment(SwingConstants.CENTER); lbTime1.setVerticalAlignment(SwingConstants.CENTER); lbTime2.setIcon(jogo.getTime2().getEscudo()); lbTime2.setFont(f); lbTime2.setHorizontalAlignment(SwingConstants.CENTER); lbTime2.setVerticalAlignment(SwingConstants.CENTER); lbGolsTime1.setText(String.valueOf(jogo.getGolTime1())); lbGolsTime1.setFont(f); lbGolsTime1.setHorizontalAlignment(SwingConstants.CENTER); lbGolsTime1.setVerticalAlignment(SwingConstants.CENTER); lbGolsTime2.setText(String.valueOf(jogo.getGolTime2())); lbGolsTime2.setFont(f); lbGolsTime2.setHorizontalAlignment(SwingConstants.CENTER); lbGolsTime2.setVerticalAlignment(SwingConstants.CENTER); lbFinalizacoesTime1.setText(String.valueOf(jogo.getFinalizacaoTime1())); lbFinalizacoesTime1.setFont(f); lbFinalizacoesTime1.setHorizontalAlignment(SwingConstants.CENTER); lbFinalizacoesTime1.setVerticalAlignment(SwingConstants.CENTER); lbFinalizacoesTime2.setText(String.valueOf(jogo.getFinalizacaoTime2())); lbFinalizacoesTime2.setFont(f); lbFinalizacoesTime2.setHorizontalAlignment(SwingConstants.CENTER); lbFinalizacoesTime2.setVerticalAlignment(SwingConstants.CENTER); lbPosseTime1.setText(String.valueOf((int)jogo.getPosseDeBolaTime1()) + "%"); lbPosseTime1.setFont(f); lbPosseTime1.setHorizontalAlignment(SwingConstants.CENTER); lbPosseTime1.setVerticalAlignment(SwingConstants.CENTER); lbPosseTime2.setText(String.valueOf((int)jogo.getPosseDeBolaTime2()) + "%"); lbPosseTime2.setFont(f); lbPosseTime2.setHorizontalAlignment(SwingConstants.CENTER); lbPosseTime2.setVerticalAlignment(SwingConstants.CENTER); lbTextoGols.setFont(f); lbTextoFinalizacoes.setFont(f); lbTextoPosse.setFont(f); this.setResizable(false); this.setVisible(true); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { painel1 = new javax.swing.JPanel(); lbTextoGols = new javax.swing.JLabel(); lbTextoFinalizacoes = new javax.swing.JLabel(); lbTextoPosse = new javax.swing.JLabel(); lbTime1 = new javax.swing.JLabel(); lbTime2 = new javax.swing.JLabel(); lbGolsTime1 = new javax.swing.JLabel(); jLabel31 = new javax.swing.JLabel(); lbGolsTime2 = new javax.swing.JLabel(); lbFinalizacoesTime1 = new javax.swing.JLabel(); lbFinalizacoesTime2 = new javax.swing.JLabel(); lbPosseTime1 = new javax.swing.JLabel(); lbPosseTime2 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); painel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Informações")); lbTextoGols.setFont(new java.awt.Font("FIFA Welcome", 0, 36)); // NOI18N lbTextoGols.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lbTextoGols.setText("Gols"); lbTextoFinalizacoes.setFont(new java.awt.Font("FIFA Welcome", 0, 36)); // NOI18N lbTextoFinalizacoes.setText("Finalizacoes"); lbTextoPosse.setFont(new java.awt.Font("FIFA Welcome", 0, 36)); // NOI18N lbTextoPosse.setText("Posse de Bola"); lbTime1.setForeground(new java.awt.Color(255, 255, 255)); lbTime1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lbTime2.setForeground(new java.awt.Color(255, 255, 255)); lbTime2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lbGolsTime1.setFont(new java.awt.Font("FIFA Welcome", 0, 36)); // NOI18N lbGolsTime1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lbGolsTime1.setText("_"); jLabel31.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N jLabel31.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel31.setText("X"); lbGolsTime2.setFont(new java.awt.Font("FIFA Welcome", 0, 36)); // NOI18N lbGolsTime2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lbGolsTime2.setText("_"); lbFinalizacoesTime1.setFont(new java.awt.Font("FIFA Welcome", 0, 36)); // NOI18N lbFinalizacoesTime1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lbFinalizacoesTime1.setText("_"); lbFinalizacoesTime2.setFont(new java.awt.Font("FIFA Welcome", 0, 36)); // NOI18N lbFinalizacoesTime2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lbFinalizacoesTime2.setText("_"); lbPosseTime1.setFont(new java.awt.Font("FIFA Welcome", 0, 36)); // NOI18N lbPosseTime1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lbPosseTime1.setText("_"); lbPosseTime2.setFont(new java.awt.Font("FIFA Welcome", 0, 36)); // NOI18N lbPosseTime2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lbPosseTime2.setText("_"); javax.swing.GroupLayout painel1Layout = new javax.swing.GroupLayout(painel1); painel1.setLayout(painel1Layout); painel1Layout.setHorizontalGroup( painel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(painel1Layout.createSequentialGroup() .addGroup(painel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(painel1Layout.createSequentialGroup() .addGap(11, 11, 11) .addGroup(painel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(lbFinalizacoesTime1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 80, Short.MAX_VALUE) .addComponent(lbGolsTime1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lbTime1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(painel1Layout.createSequentialGroup() .addContainerGap() .addComponent(lbPosseTime1, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(painel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(painel1Layout.createSequentialGroup() .addGap(132, 132, 132) .addComponent(jLabel31, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, painel1Layout.createSequentialGroup() .addGroup(painel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(painel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lbTextoGols, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(painel1Layout.createSequentialGroup() .addGap(45, 45, 45) .addGroup(painel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lbTextoPosse, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(painel1Layout.createSequentialGroup() .addComponent(lbTextoFinalizacoes, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))))) .addGap(45, 45, 45))) .addGroup(painel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(lbPosseTime2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 80, Short.MAX_VALUE) .addComponent(lbFinalizacoesTime2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lbGolsTime2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lbTime2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); painel1Layout.setVerticalGroup( painel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(painel1Layout.createSequentialGroup() .addContainerGap() .addGroup(painel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(painel1Layout.createSequentialGroup() .addComponent(jLabel31, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(209, 209, 209)) .addGroup(painel1Layout.createSequentialGroup() .addGroup(painel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(lbTime1, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbTime2, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(29, 29, 29) .addGroup(painel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lbGolsTime1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbTextoGols, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbGolsTime2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(painel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lbFinalizacoesTime1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbFinalizacoesTime2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbTextoFinalizacoes, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(painel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lbPosseTime1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbPosseTime2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbTextoPosse, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(painel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(painel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(TelaInfoJogo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TelaInfoJogo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TelaInfoJogo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TelaInfoJogo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TelaInfoJogo().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel31; private javax.swing.JLabel lbFinalizacoesTime1; private javax.swing.JLabel lbFinalizacoesTime2; private javax.swing.JLabel lbGolsTime1; private javax.swing.JLabel lbGolsTime2; private javax.swing.JLabel lbPosseTime1; private javax.swing.JLabel lbPosseTime2; private javax.swing.JLabel lbTextoFinalizacoes; private javax.swing.JLabel lbTextoGols; private javax.swing.JLabel lbTextoPosse; private javax.swing.JLabel lbTime1; private javax.swing.JLabel lbTime2; private javax.swing.JPanel painel1; // End of variables declaration//GEN-END:variables }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.util.Comparator; import javax.swing.*; import javax.swing.event.TableColumnModelEvent; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); JTable table = new JTable(new DefaultTableModel(8, 6)) { @Override protected TableColumnModel createDefaultColumnModel() { return new SortableTableColumnModel(); } }; table.setAutoCreateRowSorter(true); JButton b = new JButton("restore TableColumn order"); b.addActionListener(e -> { TableColumnModel m = table.getColumnModel(); // TEST: sortTableColumn(m); if (m instanceof SortableTableColumnModel) { ((SortableTableColumnModel) m).restoreColumnOrder(); } }); add(new JScrollPane(table)); add(b, BorderLayout.SOUTH); setPreferredSize(new Dimension(320, 240)); } // // TEST: selection sort // public static void sortTableColumn(TableColumnModel model) { // int n = model.getColumnCount(); // for (int i = 0; i < n - 1; i++) { // TableColumn c = (TableColumn) model.getColumn(i); // for (int j = i + 1; j < n; j++) { // TableColumn p = (TableColumn) model.getColumn(j); // if (c.getModelIndex() - p.getModelIndex() > 0) { // model.moveColumn(j, i); // i -= 1; // break; public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class SortableTableColumnModel extends DefaultTableColumnModel { // TEST: private static Comparator<TableColumn> tcc = (o1, o2) -> o1.getModelIndex() - o2.getModelIndex(); public void restoreColumnOrder() { tableColumns.sort(Comparator.comparingInt(TableColumn::getModelIndex)); fireColumnMoved(new TableColumnModelEvent(this, 0, tableColumns.size())); } }
package com.josenaves.sunshine.app; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.location.Location; import android.test.AndroidTestCase; import android.util.Log; import com.josenaves.sunshine.app.data.WeatherContract; import com.josenaves.sunshine.app.data.WeatherContract.LocationEntry; import com.josenaves.sunshine.app.data.WeatherContract.WeatherEntry; import com.josenaves.sunshine.app.data.WeatherDbHelper; import junit.framework.Test; import java.util.Map; import java.util.Set; public class TestDb extends AndroidTestCase { private String LOG_TAG = TestDb.class.getSimpleName(); private static final String TEST_CITY_NAME = "North Pole"; public void testCreateDb() throws Throwable { mContext.deleteDatabase(WeatherDbHelper.DATABASE_NAME); SQLiteDatabase db = new WeatherDbHelper(mContext).getWritableDatabase(); assertEquals(true, db.isOpen()); db.close(); } public void testInsertReadDb() { WeatherDbHelper dbHelper = new WeatherDbHelper(mContext); SQLiteDatabase db = dbHelper.getWritableDatabase(); // create a new map of values where column names are the keys ContentValues values = getLocationContentValues(); long locationRowId; locationRowId = db.insert(LocationEntry.TABLE_NAME, null, values); // verify we got a row back assertTrue(locationRowId != -1); Log.d(LOG_TAG, "New row id: " + locationRowId); // a cursor is your primary interface to query results Cursor cursor = db.query( LocationEntry.TABLE_NAME, null, // columns projection (all) null, // columns for the "where" clause null, // values for the "where" clause null, // columns to group by null, // columns to filter by row groups null // sort order ); if (cursor.moveToFirst()) { ContentValues weatherValues = getWeatherContentValues(locationRowId); long weatherRowId = db.insert(WeatherEntry.TABLE_NAME, null, weatherValues); // verify we got a row back assertTrue(weatherRowId != -1); Log.d(LOG_TAG, "New row id: " + weatherRowId); // a cursor is your primary interface to query results Cursor weatherCursor = db.query( WeatherEntry.TABLE_NAME, null, // leaving columns null just return all the columns null, // columns for the "where" clause null, // values for the "where" clause null, // columns to group by null, // columns to filter by row groups null // sort order ); if (weatherCursor.moveToFirst()) { validateCursor(weatherValues, weatherCursor); } else { // That's weirds, it works on MY machine :) fail("No weather data returned :("); } weatherCursor.close(); } else { // That's weirds, it works on MY machine :) fail("No values returned :("); } cursor.close(); } public static void validateCursor(ContentValues expectedValues, Cursor valueCursor) { Set<Map.Entry<String, Object>> valueSet = expectedValues.valueSet(); for (Map.Entry<String,Object> entry : valueSet) { String columnName = entry.getKey(); int idx = valueCursor.getColumnIndex(columnName); assertFalse(-1 == idx); String expectedValue = entry.getValue().toString(); assertEquals(expectedValue, valueCursor.getString(idx)); } } private ContentValues getLocationContentValues() { // test data we're going to insert into the DB String testLocationSetting = "99705"; double testLatitude = 64.7488; double testLongitude = -147.353; ContentValues values = new ContentValues(); values.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, TEST_CITY_NAME); values.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, testLocationSetting); values.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, testLatitude); values.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, testLongitude); return values; } public static ContentValues getWeatherContentValues(long locationRowId) { ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationRowId); weatherValues.put(WeatherEntry.COLUMN_DATETEXT, "20141205"); weatherValues.put(WeatherEntry.COLUMN_DEGREES, 1.1); weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, 1.2); weatherValues.put(WeatherEntry.COLUMN_PRESSURE, 1.3); weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, 75); weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, 65); weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, "Asteroids"); weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, 5.5); weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, 321); return weatherValues; } }