answer
stringlengths
17
10.2M
package com.hjh.files.sync.client; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.http.util.Asserts; import com.hjh.files.sync.common.HLogFactory; import com.hjh.files.sync.common.ILog; import com.hjh.files.sync.common.RemoteFile; import com.hjh.files.sync.common.RemoteFileFactory; import com.hjh.files.sync.common.RemoteFileManage; import com.hjh.files.sync.common.RemoteSyncConfig; import com.hjh.files.sync.common.StopAble; import com.hjh.files.sync.common.util.MD5; public class ClientFolder { private static ILog logger = HLogFactory.create(ClientFolder.class); private RemoteFileManage fromManage; private String store_folder; private String name; private String url; private FileCopy fileCopy; private FileInfoRecorder infoRecorder; public ClientFolder(String name, String store_folder, String url, int block_size) { this.name = name; this.store_folder = store_folder; this.url = url; if ("cache".equals(RemoteSyncConfig.getCopyType())) { this.fileCopy = new FileCopyByCache(this, block_size); } else if ("simple".equals(RemoteSyncConfig.getCopyType())) { this.fileCopy = new FileCopyBySimple(this, block_size); } else { throw new RuntimeException("error client.copy.type :" + RemoteSyncConfig.getCopyType()); } this.infoRecorder = new FileInfoRecorder(this); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getStore_folder() { return store_folder; } public void setStore_folder(String store_folder) { this.store_folder = store_folder; } public void sync(StopAble stop) throws IOException { String store_path = new File(new File(store_folder), name).getCanonicalPath(); if (null == fromManage) { fromManage = RemoteFileFactory.queryManage(url); } logger.stdout(String.format("sync[%s] %s => %s", name, url, store_path)); File root = new File(store_path); if (!root.exists()) { root.mkdir(); } Asserts.check(root.isDirectory(), "must be a directory :" + store_path); long time = System.currentTimeMillis(); try { if (stop.isStop()) { return; } doSync(stop, null, root); } finally { long end = System.currentTimeMillis(); logger.stdout(String.format("sync finish[%s](cost: %s) %s => %s", name, (end - time) / 1000 + "s", url, store_path)); } } private void doSync(StopAble stop, RemoteFile from, File target) throws IOException { if (null == from || from.isFolder()) { String path = null == from ? null : from.path(); if (stop.isStop()) { return; } RemoteFile[] remotes = fromManage.list(path); if (stop.isStop()) { return; } if (target.isFile()) { logger.stdout("remove file:" + target.getAbsolutePath()); Asserts.check(target.delete(), "delete file fail : " + target.getAbsolutePath()); } if (!target.exists()) { logger.stdout(String.format("sync folder[%s] %s => %s", name, path, target.getAbsolutePath())); Asserts.check(target.mkdir(), "create folder fail : " + target.getAbsolutePath()); } String[] exists = target.list(); for (RemoteFile item : remotes) { doSync(stop, item, new File(target, item.name())); if (null != exists) { for (int i = 0; i < exists.length; i++) { if (exists[i] != null && exists[i].equals(item.name())) { exists[i] = null; break; } } } } if (null != exists) { for (int i = 0; i < exists.length; i++) { if (exists[i] != null) { File cur_exist = new File(target, exists[i]); if (cur_exist.isDirectory()) { logger.stdout("remove directory:" + cur_exist.getAbsolutePath()); FileUtils.deleteDirectory(cur_exist); } else { logger.stdout("remove file:" + cur_exist.getAbsolutePath()); Asserts.check(cur_exist.delete(), "can not delete file :" + cur_exist.getAbsolutePath()); } } } } } else { if (!isSame(from, target)) { logger.stdout(String.format("sync file[%s] %s => %s", name, from.path(), target.getAbsolutePath())); if (stop.isStop()) { return; } String md5 = fromManage.md5(from.path()); if (stop.isStop()) { return; } if (target.isDirectory()) { logger.stdout("remove directory:" + target.getAbsolutePath()); FileUtils.deleteDirectory(target); } String local_md5 = target.isFile() ? MD5.md5(target) : null; if (!md5.equals(local_md5)) { if (target.isFile()) { logger.stdout("remove unmatch file:" + target.getAbsolutePath()); Asserts.check(target.delete(), String.format("can not delete file : %s", target.getAbsolutePath())); } fileCopy.copy(stop, from, target, md5); } } } if (null != from) { if (RemoteSyncConfig.isCopyTime() && !isSameTime(from, target)) { target.setLastModified(from.lastModify()); } if (!infoRecorder.isSame(from)) { infoRecorder.record(from); } } } private boolean isSameTime(RemoteFile from, File to) { if (from.lastModify() != to.lastModified()) { if (Math.abs(from.lastModify() - to.lastModified()) > RemoteSyncConfig.getMinDiffTime()) { logger.debug(String.format("[%s] %d <> %d", from.path(), from.lastModify(), to.lastModified())); return false; } } return true; } private boolean isSame(RemoteFile from, File to) throws IOException { if (!to.exists()) { return false; } if (from.isFolder()) { if (!to.isDirectory()) { return false; } } else { if (to.isDirectory()) { return false; } } if (!from.name().equals(to.getName())) { return false; } if (from.length() != to.length()) { return false; } if (infoRecorder.isSame(from)) { return true; } if (RemoteSyncConfig.isCopyTime() && isSameTime(from, to)) { return true; } return false; } public void validate() throws IOException { String store_path = new File(new File(store_folder), name).getCanonicalPath(); if (null == fromManage) { fromManage = RemoteFileFactory.queryManage(url); } logger.stdout(String.format("validate [%s] %s => %s", name, url, store_path)); File root = new File(store_path); if (!root.exists()) { logger.info("not any files in local"); return; } long time = System.currentTimeMillis(); try { doValidate(null, root); } finally { long end = System.currentTimeMillis(); logger.stdout(String.format("validate finish[%s](cost: %s) %s => %s", name, (end - time) / 1000 + "s", url, store_path)); } } private void doValidate(RemoteFile from, File target) throws IOException { if (null == from || from.isFolder()) { String path = null == from ? null : from.path(); RemoteFile[] remotes = fromManage.list(path); if (target.isFile()) { logger.stdout("file type error (must be a folder) :" + target.getAbsolutePath()); } else if (!target.exists()) { logger.stdout("can not found folder:" + target.getAbsolutePath()); } else { String[] exists = target.list(); for (RemoteFile item : remotes) { doValidate(item, new File(target, item.name())); if (null != exists) { for (int i = 0; i < exists.length; i++) { if (exists[i] != null && exists[i].equals(item.name())) { exists[i] = null; break; } } } } if (null != exists) { for (int i = 0; i < exists.length; i++) { if (exists[i] != null) { File cur_exist = new File(target, exists[i]); logger.stdout("must remove:" + cur_exist.getAbsolutePath()); } } } } } else { if (!target.exists()) { logger.stdout("can not found file:" + target.getAbsolutePath()); } else if (target.isDirectory()) { logger.stdout("file type error (must be a file) :" + target.getAbsolutePath()); } else { if (!isSame(from, target)) { logger.stdout("file info not match : " + target.getAbsolutePath()); } String md5_from = fromManage.md5(from.path()); String md5_target = MD5.md5(target); if (!md5_from.equals(md5_target)) { logger.stdout("file md5 not match : " + target.getAbsolutePath()); } } } } public RemoteFileManage getFromManage() { return this.fromManage; } }
package com.lowtuna.dropwizard.grpc; import io.dropwizard.lifecycle.Managed; import io.dropwizard.setup.Environment; import io.grpc.Server; import io.grpc.ServerBuilder; import lombok.Data; import lombok.extern.slf4j.Slf4j; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; @Slf4j @Data class GrpcServer implements Managed { private final AtomicReference<Optional<Server>> server = new AtomicReference<>(Optional.empty()); private final GrpcEnvironment grpcEnvironment; private final Environment environment; private final GrpcConnectorConfiguration connectorConfiguration; @Override public void start() throws Exception { int port = connectorConfiguration.getPort(); ServerBuilder<?> serverBuilder = ServerBuilder.forPort(port); serverBuilder.executor(environment.lifecycle().executorService("gRPC").build()); log.debug("Adding {} ServerServiceDefinitions...", grpcEnvironment.getServerServiceDefinitions().size()); grpcEnvironment.getServerServiceDefinitions().forEach(serverBuilder::addService); log.debug("Adding {} BindableServices...", grpcEnvironment.getBindableServices().size()); grpcEnvironment.getBindableServices().forEach(serverBuilder::addService); log.info("Starting gRPC server listening on port {}", port); grpcEnvironment.getLifecycleEvents().parallelStream().forEach(lifecycleListener -> { try { lifecycleListener.preServerStart(); } catch (Exception preStartException) { log.warn("Caught exception while trying to call preServerStart on {}", lifecycleListener.getClass().getCanonicalName(), preStartException); } }); boolean serverStarted = startServer(port, serverBuilder); if (serverStarted) { log.info("Started gRPC server listening on port {}", port); grpcEnvironment.getLifecycleEvents().parallelStream().forEach(lifecycleListener -> { try { lifecycleListener.postServerStart(); } catch (Exception postStartException) { log.warn("Caught exception while trying to call postServerStart on {}", lifecycleListener.getClass().getCanonicalName(), postStartException); } }); } else { log.warn("Unable to start gRPC on port {}", port); throw new IllegalStateException("Unable to start gRPC server on port " + port); } } @Override public void stop() throws Exception { if (server.get().isPresent()) { grpcEnvironment.getLifecycleEvents().parallelStream().forEach(lifecycleListener -> { try { lifecycleListener.preServerStop(); } catch (Exception preStopException) { log.warn("Caught exception while trying to call preServerStop on {}", lifecycleListener.getClass().getCanonicalName(), preStopException); } }); stopServer(); grpcEnvironment.getLifecycleEvents().parallelStream().forEach(lifecycleListener -> { try { lifecycleListener.postServerStop(); } catch (Exception postStopException) { log.warn("Caught exception while trying to call postServerStop on {}", lifecycleListener.getClass().getCanonicalName(), postStopException); } }); } } private boolean startServer(int port, ServerBuilder<?> serverBuilder) { try { Server grpcServer = serverBuilder.build().start(); if (server.compareAndSet(Optional.empty(), Optional.of(grpcServer))) { return true; } else { log.warn("gRPC server already running on port {}", this.server.get().get().getPort()); grpcServer.shutdownNow(); } } catch (Exception exception) { log.warn("IOException while trying to start gRPC server on port {}", port, exception); } return false; } private boolean stopServer() { int port = connectorConfiguration.getPort(); Server gRpcServer = server.get().get(); try { log.info("Stopping gRPC server on port {}", port); gRpcServer.shutdown(); log.info("Stopped gRPC server on port {}", port); return true; } catch (Exception shutDownException) { log.warn("Caught Exception when trying to stop gRPC server on port {}", shutDownException, port); } return false; } }
package com.minesnap.restarter; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import java.util.Calendar; import org.bukkit.command.PluginCommand; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.ChatColor; /** * Restarter plugin for Bukkit * * @author AgentME */ public class RestarterPlugin extends JavaPlugin { BukkitScheduler scheduler; private int minutesToRestart; private int variance; private Timer timer; private Calendar warnTime; private Calendar restartTime; private static final int TICS_PER_SECOND = 20; private String warnMessage; private String kickMessage; private final RestarterPlugin plugin = this; public void onDisable() { timer.cancel(); timer = null; } public void onEnable() { // Register our commands getCommand("rsquery").setExecutor(new RSQueryCommand(this)); getCommand("rsset").setExecutor(new RSSetCommand(this)); scheduler = getServer().getScheduler(); // Config stuff getConfig().options().copyDefaults(true); saveConfig(); minutesToRestart = getConfig().getInt("minutesToRestart"); variance = getConfig().getInt("variance"); warnMessage = getConfig().getString("warnMessage"); kickMessage = getConfig().getString("kickMessage"); if(minutesToRestart <= 1) { minutesToRestart = 80; getLogger().severe("minutesToRestart value too low! Using default."); } if(variance < 0 || minutesToRestart - variance <= 1) { variance = 0; getLogger().severe("variance value is bad! Using default."); } // Apply variance. The new value of minutesToRestart will be Random rand = new Random(); minutesToRestart = minutesToRestart-variance + rand.nextInt(2*variance+1); scheduleRestart(minutesToRestart); } public void scheduleRestart(int minutes) { if(timer != null) { timer.cancel(); } timer = new Timer(true); if(minutes >= 1) { warnTime = Calendar.getInstance(); warnTime.add(Calendar.MINUTE, minutes-1); timer.schedule(new RestartWarner(), warnTime.getTime()); restartTime = (Calendar)warnTime.clone(); restartTime.add(Calendar.MINUTE, 1); } else { warnTime = null; restartTime = Calendar.getInstance(); restartTime.add(Calendar.MINUTE, minutes); } timer.schedule(new Restarter(), restartTime.getTime()); getLogger().info("Restart scheduled in "+minutes+" minutes."); } private class RestartWarner extends TimerTask { public void run() { scheduler.scheduleSyncDelayedTask(plugin, new Runnable() { public void run() { getLogger().info("Server restart in one minute."); getServer().broadcastMessage(ChatColor.RED+warnMessage); } }); } } private class Restarter extends TimerTask { public void run() { scheduler.scheduleSyncDelayedTask(plugin, new Runnable() { public void run() { stopServer(); } }); } } public boolean stopServer() { // log it and empty out the server first getLogger().info("Restarting..."); clearServer(kickMessage); getServer().shutdown(); return true; } public void clearServer(String message) { getServer().broadcastMessage(ChatColor.RED+message); for (Player player : getServer().getOnlinePlayers()) { player.kickPlayer(message); } } /* Returns the minutesToRestart value that was read from config, * regardless of whether it's been changed in-game */ public int getMinutesToRestartConfig() { return minutesToRestart; } /* Returns the number of minutes until the next restart from * now. */ public int getMinutesToRestartLeft() { Calendar now = Calendar.getInstance(); long milliDiff = restartTime.getTime().getTime()-now.getTime().getTime(); return (int)(milliDiff / (1000*60)); } }
package com.modym.client.objects; import java.io.Serializable; import java.math.BigDecimal; import org.joda.time.LocalDate; import lombok.Getter; import lombok.Setter; /** * @author bashar * */ @Getter @Setter public class ModymCustomer extends UDFType implements Serializable { private static final long serialVersionUID = 1L; private long customerId; private String referenceId; private String title; private String firstName; private String lastName; private String email; private String phoneMobile; private String phoneOther; private ModymGender gender; private ModymMaritalStatus maritalStatus; private LocalDate dateOfBirth; private Integer age; private String address1; private String address2; private String postcode; private String cityName; private String countryIso2; private String company; private String position; private String language; private LocalDate registered; private BigDecimal lifetimeRevenue = null; private String lifetimeRevenueCurrency = null; private Integer activityCount = null; private Integer purchaseCount = null; private LocalDate lastActivity = null; private LocalDate lastPurchase = null; private Long accountId; private Long levelId; private String levelName; private BigDecimal totalPoints; private BigDecimal availablePoints; private BigDecimal totalLifetimePoints; private BigDecimal totalLifetimeConsumedPoints; private LocalDate loyaltyJoinDate; private boolean enabled; public enum ModymGender { MALE, FEMALE, UNSPECIFIED; } public enum ModymMaritalStatus { SINGLE, MARRIED, WIDOWED, DIVORCED, UNSPECIFIED; } }
package com.ne0nx3r0.quantum.circuits; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.material.MaterialData; public class Receiver { private Location location; private int type; private int delay = 0; public Receiver(Location location, int type, int delay) { this.location = location; this.type = type; this.delay = delay; } public Receiver(Location location, int type) { this.location = location; this.type = type; } public void setActive(boolean powerOn) { Block block = location.getBlock(); Material material = block.getType(); BlockState state = block.getState(); MaterialData data = state.getData(); } public Location getLocation() { return location; } public int getType() { return type; } public int getDelay() { return delay; } public int getBlockMaterial() { return location.getBlock().getTypeId(); } public byte getBlockData() { return location.getBlock().getData(); } }
package com.nirima.docker.api; import com.nirima.docker.client.model.*; import javax.annotation.Nullable; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.io.InputStream; import java.util.List; @Path("/containers") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public interface ContainersClient { /** * List containers * * @param all 1/True/true or 0/False/false, Show all containers. Only running containers are shown by default * @param limit Show limit last created containers, include non-running ones. * @param since Show only containers created since Id, include non-running ones. * @param before Show only containers created before Id, include non-running ones. * @param size 1/True/true or 0/False/false, Show the containers sizes * @return */ @GET @Path("/json") List<Container> listContainers(@QueryParam("all")boolean all, @QueryParam("limit")int limit, @DefaultValue("") @QueryParam("since")String since, @DefaultValue("") @QueryParam("before")String before, @QueryParam("size")boolean size); @POST @Consumes(MediaType.APPLICATION_JSON) @Path("/create") ContainerCreateResponse createContainer(ContainerConfig config); /** * Inspect a container * * @param id - id of the container * @return */ @GET @Path("/{id}/json") ContainerInspectResponse inspectContainer(@PathParam("id")String id); @GET @Path("/{id}/top") TopResponse top(@PathParam("id")String containerId); @GET @Path("/{id}/changes") List<FileChanges> getFilesystemChanges(@PathParam("id")String containerId); @GET @Path("/{id}/export") Object exportContainer(@PathParam("id")String containerId); @POST @Path("/{id}/start") @Produces(MediaType.TEXT_PLAIN) String startContainer(@PathParam("id") String id, HostConfig hostConfig); @POST @Path("/{id}/stop") @Produces(MediaType.TEXT_PLAIN) String stopContainer(@PathParam("id")String id, @QueryParam("t")Long secondsToWait); @POST @Path("/{id}/restart") @Produces(MediaType.TEXT_PLAIN) String restartContainer(@PathParam("id")String id, @QueryParam("t")Long secondsToWait); /** * Kill a container * @param id * @return an empty string (may change to void) */ @POST @Path("/{id}/kill") @Produces(MediaType.TEXT_PLAIN) String killContainer(@PathParam("id")String id); @POST @Path("/{id}/attach") @Produces(MediaType.APPLICATION_OCTET_STREAM) InputStream attachToContainer(@PathParam("id")String id, @QueryParam("logs")boolean returnLogs, @QueryParam("stream")boolean returnStream, @QueryParam("stdin")boolean attachStdin, @QueryParam("stdout")boolean attachStdout, @QueryParam("stderr")boolean attachStderr ); @POST @Path("/{id}/wait") StatusCodeResponse waitForContainer(@PathParam("id")String id); @DELETE @Path("/{id}") @Produces(MediaType.TEXT_PLAIN) String removeContainer(@PathParam("id")String id); @DELETE @Path("/{id}") @Produces(MediaType.TEXT_PLAIN) String removeContainer(@PathParam("id")String id, @QueryParam("v")boolean removeVolumes); @POST @Path("/{id}/copy") void copy(@PathParam("id")String id); }
package com.nitorcreations.dopeplugin; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; 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.regex.Matcher; import java.util.regex.Pattern; import javax.imageio.ImageIO; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.WordUtils; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.apache.pdfbox.exceptions.COSVisitorException; import org.apache.pdfbox.util.PDFMergerUtility; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.imgscalr.Scalr; import org.pegdown.Extensions; import org.pegdown.LinkRenderer; import org.pegdown.PegDownProcessor; import org.pegdown.ToHtmlSerializer; import org.pegdown.ast.RootNode; import org.pegdown.ast.VerbatimNode; import org.python.util.PythonInterpreter; import com.github.jarlakxen.embedphantomjs.ExecutionTimeout; import com.github.jarlakxen.embedphantomjs.PhantomJSReference; import com.github.jarlakxen.embedphantomjs.executor.PhantomJSFileExecutor; @Mojo( name = "render", defaultPhase = LifecyclePhase.COMPILE ) public class DopeMojo extends AbstractMojo { @Parameter( defaultValue = "${project.build.directory}/classes/markdown", property = "markdownDir", required = true ) private File markdownDirectory; @Parameter( defaultValue = "${project.build.directory}/classes/html", property = "htmlDir", required = true ) private File htmlDirectory; private File htmlTemplate; private File titleTemplate; @Parameter( defaultValue = "${project.build.directory}/classes/slides", property = "buildDir", required = true ) private File slidesDirectory; @Parameter( defaultValue = "${project.build.directory}/classes/slides-small", property = "buildDir", required = true ) private File smallSlidesDirectory; @Parameter( defaultValue = "${project.build.directory}", property = "buildDir", required = true ) private File buildDirectory; @Parameter( defaultValue = "${project.groupId}.css", property = "css", required = true ) private String css; @Parameter( defaultValue = "${project.name}", property = "name", required = true ) private String name; @Parameter( defaultValue = "${project}", required = true ) private MavenProject project; @Parameter( defaultValue = "", property = "pngoptimizer" ) private String pngoptimizer; @Parameter( defaultValue = "UTF-8", property = "charset" ) private String charset; private static File renderScript; private static File videoPositionScript; ExecutorService service = Executors.newCachedThreadPool(); static { try { renderScript = extractFile("render.js", ".js"); videoPositionScript = extractFile("videoposition.js", ".js"); } catch (IOException e) { throw new RuntimeException("Failed to create temporary resource", e); } } public final class RenderHtmlTask implements Callable<Throwable> { private final File out; private final Map<String, String> htmls; private final Map<String, String> notes; private final String markdown; private final boolean isSlide; private final String slideName; private final long lastModified; public final List<Future<Throwable>> children; private RenderHtmlTask(File nextSource, Map<String, String> htmls, Map<String, String> notes, List<Future<Throwable>> children) throws IOException { this(new String(Files.readAllBytes(Paths.get(nextSource.toURI())), Charset.defaultCharset()), htmls, notes, children, nextSource.getName().endsWith(".md"), nextSource.getName().replaceAll("\\.md(\\.notes)?$", ""), nextSource.lastModified()); } private RenderHtmlTask(String markdown, Map<String, String> htmls, Map<String, String> notes, List<Future<Throwable>> children, boolean isSlide, String slideName, long lastModified) { this.out = htmlDirectory; this.markdown = markdown; this.htmls = htmls; this.notes = notes; this.children = children; this.isSlide = isSlide; this.slideName = slideName; this.lastModified = lastModified; } public Throwable call() { try { PegDownProcessor processor = new PegDownProcessor(Extensions.AUTOLINKS + Extensions.TABLES + Extensions.FENCED_CODE_BLOCKS); if (isSlide) { File htmlFinal = new File(out, slideName + ".html"); RootNode astRoot = processor.parseMarkdown(markdown.toCharArray()); String nextHtml = new PygmentsToHtmlSerializer().toHtml(astRoot); htmls.put(slideName, nextHtml); if (htmlFinal.exists() && (htmlFinal.lastModified() >= lastModified)) { return null; } MergeHtml m = new MergeHtml(nextHtml, slideName, htmlFinal); m.merge(); children.add(service.submit(new RenderPngPdfTask(htmlFinal, "png"))); children.add(service.submit(new RenderPngPdfTask(htmlFinal, "pdf"))); children.add(service.submit(new VideoPositionTask(htmlFinal))); } else { RootNode astRoot = processor.parseMarkdown(markdown.toCharArray()); String nextHtml = new PygmentsToHtmlSerializer().toHtml(astRoot); notes.put(slideName, nextHtml); } } catch (IOException e) { return e; } return null; } } public final class MergeHtml { private final String html; private final String slideName; private final String css; private final File out; private final File template; private final File htmlFinal; public MergeHtml(String html, String slideName, File htmlFinal) { this.html = html; this.slideName = slideName; this.css = DopeMojo.this.css; this.out = htmlDirectory; this.template = htmlTemplate; this.htmlFinal = htmlFinal; } public void merge() throws IOException { VelocityEngine ve = new VelocityEngine(); ve.setProperty("resource.loader", "file"); ve.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader"); ve.setProperty("file.resource.loader.path", ""); ve.init(); Template t = ve.getTemplate(template.getAbsolutePath()); VelocityContext context = new VelocityContext(); context.put("name", name); context.put("slideName", slideName); context.put("css", css); context.put("html", html); context.put("project", project); File nextOut = new File(out, slideName + ".html.tmp"); FileWriter w = new FileWriter(nextOut); t.merge( context, w); w.flush(); nextOut.renameTo(htmlFinal); } } public final class RenderPngPdfTask implements Callable<Throwable> { private final File slides; private final File smallSlides; private final File nextSource; private final String format; private RenderPngPdfTask(File nextSource, String format) { this.slides = slidesDirectory; this.smallSlides = smallSlidesDirectory; this.nextSource = nextSource; this.format = format; } @Override public Throwable call() { String slideName = nextSource.getName().substring(0, nextSource.getName().length() - 5); File outFolder; if ("png".equals(format)) { outFolder = slides; } else { outFolder = buildDirectory; } File nextPngPdf = new File(outFolder, slideName + ".tmp." + format); File finalPngPdf = new File(outFolder, slideName + "." + format); if (finalPngPdf.exists() && (finalPngPdf.lastModified() >= nextSource.lastModified())) { return null; } PhantomJSFileExecutor ex = new PhantomJSFileExecutor(PhantomJSReference.create().build(), new ExecutionTimeout(10, TimeUnit.SECONDS)); String output; try { output = ex.execute(renderScript, nextSource.getAbsolutePath(), nextPngPdf.getAbsolutePath()).get(); } catch (InterruptedException | ExecutionException e) { return e; } if (output.length() == 0) { nextPngPdf.renameTo(finalPngPdf); if ("png".equals(format)) { try { Future<Throwable> ob = service.submit(new OptimizePngTask(finalPngPdf)); BufferedImage image = ImageIO.read(finalPngPdf); BufferedImage smallImage = Scalr.resize(image, Scalr.Method.QUALITY, Scalr.Mode.FIT_TO_WIDTH, 960, 0, Scalr.OP_ANTIALIAS); File nextSmallPng = new File(smallSlides, finalPngPdf.getName() + ".tmp"); File finalSmallPng = new File(smallSlides, finalPngPdf.getName()); ImageIO.write(smallImage, "png", nextSmallPng); nextSmallPng.renameTo(finalSmallPng); Future<Throwable> os = service.submit(new OptimizePngTask(finalSmallPng)); Throwable bt = ob.get(); Throwable st = os.get(); if (bt != null) { return bt; } else { return st; } } catch (IOException | InterruptedException | ExecutionException e) { return e; } } } else { return new Throwable(String.format("Failed to render %s '%s'.%s: %s", format, slideName, format, output)); } return null; } } public final class VideoPositionTask implements Callable<Throwable> { private final File slides; private final File smallSlides; private final File nextSource; private VideoPositionTask(File nextSource) { this.slides = slidesDirectory; this.smallSlides = smallSlidesDirectory; this.nextSource = nextSource; } @Override public Throwable call() { String slideName = nextSource.getName().substring(0, nextSource.getName().length() - 5); File nextVideo = new File(slides, slideName + ".tmp.video"); File finalVideo = new File(slides, slideName + ".video"); File nextSmallVideo = new File(smallSlides, slideName + ".tmp.video"); File finalSmallVideo = new File(smallSlides, slideName + ".video"); if (finalVideo.exists() && (finalVideo.lastModified() >= nextSource.lastModified())) { return null; } PhantomJSFileExecutor ex = new PhantomJSFileExecutor(PhantomJSReference.create().build(), new ExecutionTimeout(10, TimeUnit.SECONDS)); String output; try { output = ex.execute(videoPositionScript, nextSource.getAbsolutePath()).get(); } catch (InterruptedException | ExecutionException e) { return e; } if (output.length() > 0) { try (FileOutputStream out = new FileOutputStream(nextVideo); FileOutputStream smallOut = new FileOutputStream(nextSmallVideo); ) { out.write(output.getBytes(Charset.defaultCharset())); out.flush(); smallOut.write(output.getBytes(Charset.defaultCharset())); smallOut.flush(); } catch (IOException e) { return e; } nextVideo.renameTo(finalVideo); nextSmallVideo.renameTo(finalSmallVideo); } return null; } } public final class OptimizePngTask implements Callable<Throwable> { private final File png; public OptimizePngTask(File png) { this.png = png; } @Override public Throwable call() { if (pngoptimizer == null || pngoptimizer.length() == 0) { return null; } VelocityEngine ve = new VelocityEngine(); ve.init(); VelocityContext context = new VelocityContext(); context.put("png", png.getAbsolutePath()); context.put("project", project); StringWriter out = new StringWriter(); if (!ve.evaluate(context, out, "png", pngoptimizer)) { return new RuntimeException("Failed to merge optimizer template"); } try { List<String> list = new ArrayList<String>(); Matcher m = Pattern.compile("([^\"]\\S*|\".+?\")\\s*").matcher(out.toString().trim()); while (m.find()) { list.add(m.group(1).replace("\"", "")); } Process optimize = new ProcessBuilder(list).redirectErrorStream(true).start(); final InputStream is = optimize.getInputStream(); Thread pump = new Thread() { public void start() { InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; try { while ((line = br.readLine()) != null) { getLog().debug(line); } } catch (IOException e) { } } }; pump.start(); if (optimize.waitFor() != 0) { return new RuntimeException("Failed to run optimizer - check debug output for why"); } pump.interrupt(); } catch (IOException | InterruptedException | IllegalThreadStateException e) { return e; } return null; } } public class IndexTemplateTask implements Callable<Throwable> { private final File nextIndex; private final Map<String, String> htmls; private final Map<String, String> notes; private final List<String> slideNames; private final MavenProject project; private IndexTemplateTask(File nextIndex, Map<String, String> htmls, Map<String, String> notes, List<String> slideNames) { this.nextIndex = nextIndex; this.htmls = htmls; this.notes = notes; this.slideNames = slideNames; this.project = DopeMojo.this.project; } @Override public Throwable call() { VelocityEngine ve = new VelocityEngine(); ve.setProperty("resource.loader", "file"); ve.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader"); ve.setProperty("file.resource.loader.path", ""); ve.init(); Template t = ve.getTemplate(nextIndex.getAbsolutePath()); File nextOut = new File(nextIndex.getParent(), nextIndex.getName() + ".tmp"); VelocityContext context = createContext(); try (FileWriter w = new FileWriter(nextOut)){ t.merge( context, w); w.flush(); nextOut.renameTo(nextIndex); } catch (IOException e) { return e; } return null; } protected VelocityContext createContext() { VelocityContext context = new VelocityContext(); context.put("name", name); context.put("htmls", htmls); context.put("notes", notes); context.put("slidenames", slideNames); context.put("project", project); context.put("css", css); return context; } } public class DefaultIndexTemplateTask extends IndexTemplateTask { private final Map<String, String> renderedIndexes; private DefaultIndexTemplateTask(File nextIndex, Map<String, String> htmls, Map<String, String> notes, List<String> slideNames, Map<String, String> renderedIndexes) { super(nextIndex,htmls, notes, slideNames); this.renderedIndexes = renderedIndexes; } @Override protected VelocityContext createContext() { VelocityContext context = super.createContext(); context.put("indexes", renderedIndexes); return context; } } public final class TitleTemplateTask extends IndexTemplateTask { private final List<Future<Throwable>> children; public TitleTemplateTask(List<Future<Throwable>> children) { super(titleTemplate, null, null, null); this.children = children; } @Override public Throwable call() { Throwable superRes = super.call(); if (superRes == null) { children.add(service.submit(new RenderPngPdfTask(titleTemplate, "png"))); children.add(service.submit(new RenderPngPdfTask(titleTemplate, "pdf"))); children.add(service.submit(new VideoPositionTask(titleTemplate))); return null; } else { return superRes; } } } private static File extractFile(String name, String suffix) throws IOException { File target = File.createTempFile(name.substring(0, name.length() - suffix.length()), suffix); target.deleteOnExit(); try (FileOutputStream outStream = new FileOutputStream(target); InputStream inStream = DopeMojo.class.getClassLoader().getResourceAsStream(name)) { IOUtils.copy(inStream, outStream); return target; } } public void execute() throws MojoExecutionException { File f = markdownDirectory; htmlTemplate = new File(htmlDirectory, "slidetemplate.html"); titleTemplate = new File(htmlDirectory, "title.html"); getLog().debug(String.format("Markdown from %s", f.getAbsolutePath())); if ( !f.exists() ) { return; } getLog().debug(String.format("HTML to %s", htmlDirectory.getAbsolutePath())); ensureDir(htmlDirectory); getLog().debug(String.format("Slides to %s", slidesDirectory.getAbsolutePath())); ensureDir(slidesDirectory); getLog().debug(String.format("Small slides to %s", smallSlidesDirectory.getAbsolutePath())); ensureDir(smallSlidesDirectory); final File[] sources = f.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".md") || name.endsWith(".md.notes"); } }); getLog().info(String.format("Processing %d markdown files", sources.length)); final Map<String, String> notes = new ConcurrentHashMap<>(); final Map<String, String> htmls = new ConcurrentHashMap<>(); final List<Future<Throwable>> execs = new ArrayList<>(); final List<Future<Throwable>> children = new CopyOnWriteArrayList<>(); final ArrayList<String> slideNames = new ArrayList<>(); for (int i=0; i<sources.length;i++) { final File nextSource = sources[i]; String fileName = nextSource.getName(); String slideName; boolean isSlide = true; if (fileName.endsWith(".md")) { slideName = fileName.substring(0, fileName.length() - 3); } else { slideName = fileName.substring(0, fileName.length() - 9); isSlide = false; } getLog().debug(String.format("Starting to process %s", nextSource.getAbsolutePath())); try { String nextMarkdown = new String(Files.readAllBytes(Paths.get(nextSource.toURI())), Charset.forName(charset)); int slideStart = 0; int nextStart = nextMarkdown.indexOf("<!--break", slideStart); boolean nextIsSlide = isSlide; int index=0; while (nextStart > -1) { String slideId = slideName + "$" + index; if (nextIsSlide) { slideNames.add(slideId); index++; } else { slideId = slideName + "$" + (index-1); } execs.add(service.submit(new RenderHtmlTask(nextMarkdown.substring(slideStart, nextStart), htmls, notes, children, nextIsSlide, slideId, nextSource.lastModified()))); nextIsSlide = !nextMarkdown.regionMatches(nextStart, "<!--break:notes", 0, "<!--break:notes".length()); slideStart = nextStart; nextStart = nextMarkdown.indexOf("<!--break", slideStart + 1); } String slideId = slideName + "$" + index; if (nextIsSlide) { slideNames.add(slideId); } else { slideId = slideName + "$" + (index-1); } execs.add(service.submit(new RenderHtmlTask(nextMarkdown.substring(slideStart), htmls, notes, children, nextIsSlide, slideId, nextSource.lastModified()))); } catch (IOException e) { getLog().error(e); } } if (titleTemplate != null && titleTemplate.exists()) { execs.add(service.submit(new TitleTemplateTask(children))); } for (Future<Throwable> next : execs) { Throwable nextT; try { nextT = next.get(); if (nextT != null) { getLog().error(nextT); } } catch (InterruptedException | ExecutionException e) { getLog().error(e); } } Collections.sort(slideNames); if (titleTemplate.exists()) { slideNames.add(0, "title"); } LinkedHashMap<String, String> renderedIndexes = new LinkedHashMap<>(); LinkedHashMap<String, String> index = new LinkedHashMap<String, String>(); index.put("run", "Run presentation"); index.put("follow", "Follow presentation"); index.put("reveal", "Web version of the presentation"); for (String nextIndex : index.keySet()) { File nextIndexFile = new File(htmlDirectory, "index-" + nextIndex + ".html"); if (nextIndexFile.exists()) { children.add(service.submit(new IndexTemplateTask(nextIndexFile, htmls, notes, slideNames))); renderedIndexes.put(nextIndex, index.get(nextIndex)); } } children.add(service.submit((new DefaultIndexTemplateTask(new File(htmlDirectory, "index-default.html"), htmls, notes, slideNames, renderedIndexes)))); for (Future<Throwable> next : children) { Throwable nextT; try { nextT = next.get(); if (nextT != null) { getLog().error(nextT); } } catch (InterruptedException | ExecutionException e) { getLog().error(e); } } getLog().debug("Merging pdfs"); PDFMergerUtility merger = new PDFMergerUtility(); for( String sourceFileName : slideNames ) { File source = new File(buildDirectory, sourceFileName + ".pdf"); getLog().debug("Merging pdf: " + source.getAbsolutePath()); merger.addSource(source.getAbsolutePath()); } String destinationFileName = new File(htmlDirectory, "presentation.pdf").getAbsolutePath(); merger.setDestinationFileName(destinationFileName); try { merger.mergeDocuments(); } catch (COSVisitorException | IOException e) { throw new MojoExecutionException("Failed to merge pdf", e); } } private static void ensureDir(File dir) throws MojoExecutionException { if (dir.exists() && !dir.isDirectory()) { throw new MojoExecutionException(String.format("%s exists and is not a directory", dir.getAbsolutePath())); } if (!dir.exists() && !dir.mkdirs()) { throw new MojoExecutionException(String.format("Failed to create directory %s", dir.getAbsolutePath())); } } private class PygmentsToHtmlSerializer extends ToHtmlSerializer { public PygmentsToHtmlSerializer() { this(new LinkRenderer()); } public PygmentsToHtmlSerializer(LinkRenderer linkRenderer) { super(linkRenderer); } @Override public void visit(VerbatimNode node) { try { if (!node.getType().isEmpty()) { synchronized (this.getClass()) { PythonInterpreter interpreter = new PythonInterpreter(); String lang = WordUtils.capitalize(node.getType()); interpreter.set("code", node.getText()); interpreter.exec("from pygments import highlight\n" + "from pygments.lexers import " + lang + "Lexer\n" + "from pygments.formatters import HtmlFormatter\n" + "\nresult = highlight(code, " + lang + "Lexer(), HtmlFormatter())"); String ret = interpreter.get("result", String.class); if (ret != null) { printer.print(ret); } else { super.visit(node); } } } else { super.visit(node); } } catch (Exception e) { e.printStackTrace(); super.visit(node); } } } }
package com.ociweb.gl.impl.mqtt; import com.ociweb.gl.api.*; import com.ociweb.gl.impl.BridgeConfigImpl; import com.ociweb.gl.impl.BridgeConfigStage; import com.ociweb.gl.impl.BuilderImpl; import com.ociweb.gl.impl.schema.IngressMessages; import com.ociweb.gl.impl.stage.EgressConverter; import com.ociweb.gl.impl.stage.EgressMQTTStage; import com.ociweb.gl.impl.stage.IngressConverter; import com.ociweb.gl.impl.stage.IngressMQTTStage; import com.ociweb.pronghorn.network.TLSCertificates; import com.ociweb.pronghorn.network.mqtt.MQTTClientGraphBuilder; import com.ociweb.pronghorn.network.mqtt.MQTTEncoder; import com.ociweb.pronghorn.network.schema.MQTTClientRequestSchema; import com.ociweb.pronghorn.network.schema.MQTTClientResponseSchema; import com.ociweb.pronghorn.pipe.DataOutputBlobWriter; import com.ociweb.pronghorn.pipe.Pipe; import com.ociweb.pronghorn.pipe.PipeConfig; import com.ociweb.pronghorn.pipe.PipeWriter; import com.ociweb.pronghorn.stage.scheduling.GraphManager; import com.ociweb.pronghorn.stage.test.PipeCleanerStage; import com.ociweb.pronghorn.stage.test.PipeNoOp; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MQTTConfigImpl extends BridgeConfigImpl<MQTTConfigTransmission,MQTTConfigSubscription> implements MQTTBridge { private final static Logger logger = LoggerFactory.getLogger(MQTTConfigImpl.class); // MQTT public static final int DEFAULT_MAX_MQTT_IN_FLIGHT = 10; public static final int DEFAULT_MAX__MQTT_MESSAGE = 1<<12; private final CharSequence host; private final int port; private final CharSequence clientId; private int keepAliveSeconds = 10; //default private CharSequence user = null; private CharSequence pass = null; private CharSequence lastWillTopic = null; private CharSequence connectionFeedbackTopic; private Writable lastWillPayload = null; private int flags; private TLSCertificates certificates; private final short maxInFlight; private int maximumLenghOfVariableLengthFields; private final BuilderImpl builder; private BridgeConfigStage configStage = BridgeConfigStage.Construction; private Pipe<MQTTClientRequestSchema> clientRequest; private Pipe<MQTTClientResponseSchema> clientResponse; private final long rate; private int subscriptionQoS = 0; private int transmissionFieldQOS = 0; private int transmissionFieldRetain = 0; public MQTTConfigImpl(CharSequence host, int port, CharSequence clientId, BuilderImpl builder, long rate, short maxInFlight, int maxMessageLength) { this.host = host; this.port = port; this.clientId = clientId; this.builder = builder; this.rate = rate; this.maxInFlight = maxInFlight; this.maximumLenghOfVariableLengthFields = maxMessageLength; } public void beginDeclarations() { configStage = BridgeConfigStage.DeclareConnections; } private static Pipe<MQTTClientRequestSchema> newClientRequestPipe(PipeConfig<MQTTClientRequestSchema> config) { return new Pipe<MQTTClientRequestSchema>(config) { @SuppressWarnings("unchecked") @Override protected DataOutputBlobWriter<MQTTClientRequestSchema> createNewBlobWriter() { return new MQTTWriter(this); } }; } //send on construction, do not save private void publishBrokerConfig(Pipe<MQTTClientRequestSchema> output) { PipeWriter.presumeWriteFragment(output, MQTTClientRequestSchema.MSG_BROKERCONFIG_100); PipeWriter.writeUTF8(output,MQTTClientRequestSchema.MSG_BROKERCONFIG_100_FIELD_HOST_26, (CharSequence) host); PipeWriter.writeInt(output,MQTTClientRequestSchema.MSG_BROKERCONFIG_100_FIELD_PORT_27, port); PipeWriter.publishWrites(output); } //send upon complete construction private void publishConnect(Pipe<MQTTClientRequestSchema> output) { PipeWriter.presumeWriteFragment(output, MQTTClientRequestSchema.MSG_CONNECT_1); PipeWriter.writeInt(output,MQTTClientRequestSchema.MSG_CONNECT_1_FIELD_KEEPALIVESEC_28, keepAliveSeconds); PipeWriter.writeInt(output,MQTTClientRequestSchema.MSG_CONNECT_1_FIELD_FLAGS_29, flags); PipeWriter.writeUTF8(output,MQTTClientRequestSchema.MSG_CONNECT_1_FIELD_CLIENTID_30, (CharSequence) clientId); PipeWriter.writeUTF8(output,MQTTClientRequestSchema.MSG_CONNECT_1_FIELD_WILLTOPIC_31, (CharSequence) lastWillTopic); DataOutputBlobWriter<MQTTClientRequestSchema> writer = PipeWriter.outputStream(output); DataOutputBlobWriter.openField(writer); if(null!= lastWillPayload) { lastWillPayload.write((MQTTWriter)writer); } DataOutputBlobWriter.closeHighLevelField(writer, MQTTClientRequestSchema.MSG_CONNECT_1_FIELD_WILLPAYLOAD_32); PipeWriter.writeUTF8(output,MQTTClientRequestSchema.MSG_CONNECT_1_FIELD_USER_33, (CharSequence) user); PipeWriter.writeUTF8(output,MQTTClientRequestSchema.MSG_CONNECT_1_FIELD_PASS_34, (CharSequence) pass); PipeWriter.publishWrites(output); } public MQTTBridge keepAliveSeconds(int seconds) { configStage.throwIfNot(BridgeConfigStage.DeclareConnections); keepAliveSeconds = seconds; return this; } /** * Clean session ensures the server will not remember state from * previous connections from this client. In order to ensure QOS * across restarts of the client this should be set to true. * * By default this is false. * * @param clean */ public MQTTBridge cleanSession(boolean clean) { configStage.throwIfNot(BridgeConfigStage.DeclareConnections); flags = setBitByBoolean(flags, clean, MQTTEncoder.CONNECT_FLAG_CLEAN_SESSION_1); return this; } private int setBitByBoolean(int target, boolean clean, int bit) { if (clean) { target = target|bit; } else { target = (~target)&bit; } return target; } public MQTTBridge useTLS() { return useTLS(TLSCertificates.defaultCerts); } public MQTTBridge useTLS(TLSCertificates certificates) { configStage.throwIfNot(BridgeConfigStage.DeclareConnections); assert(null != certificates); this.certificates = certificates; this.maximumLenghOfVariableLengthFields = Math.max(this.maximumLenghOfVariableLengthFields, 1<<15); return this; } public MQTTBridge authentication(CharSequence user, CharSequence pass) { return this.authentication(user, pass, TLSCertificates.defaultCerts); } public MQTTBridge authentication(CharSequence user, CharSequence pass, TLSCertificates certificates) { configStage.throwIfNot(BridgeConfigStage.DeclareConnections); flags |= MQTTEncoder.CONNECT_FLAG_USERNAME_7; flags |= MQTTEncoder.CONNECT_FLAG_PASSWORD_6; this.user = user; this.pass = pass; assert(null != user); assert(null != pass); assert(null != certificates); return this; } @Override public MQTTBridge subscriptionQoS(MQTTQoS qos) { subscriptionQoS = qos.getSpecification(); return this; } @Override public MQTTBridge transmissionOoS(MQTTQoS qos) { transmissionFieldQOS = qos.getSpecification(); return this; } @Override public MQTTBridge transmissionRetain(boolean value) { transmissionFieldRetain = setBitByBoolean(transmissionFieldRetain, value, MQTTEncoder.CONNECT_FLAG_WILL_RETAIN_5 ); return this; } @Override public MQTTBridge lastWill(CharSequence topic, boolean retain, MQTTQoS qos, Writable payload) { configStage.throwIfNot(BridgeConfigStage.DeclareConnections); assert(null!=topic); flags |= MQTTEncoder.CONNECT_FLAG_WILL_FLAG_2; if (retain) { flags |= MQTTEncoder.CONNECT_FLAG_WILL_RETAIN_5; } byte qosFlag = (byte) (qos.getSpecification() << 3); flags |= qosFlag; this.lastWillTopic = topic; this.lastWillPayload = payload; return this; } public MQTTBridge connectionFeedbackTopic(CharSequence connectFeedbackTopic) { this.connectionFeedbackTopic = connectFeedbackTopic; return this; } private void ensureConnected() { if (configStage == BridgeConfigStage.DeclareBehavior) { return; } else { //No need for this pipe to be large since we can only get one at a time from the MessagePubSub feeding EngressMQTTStage int egressPipeLength = 32; PipeConfig<MQTTClientRequestSchema> newPipeConfig = MQTTClientRequestSchema.instance.newPipeConfig(egressPipeLength, maximumLenghOfVariableLengthFields); clientRequest = newClientRequestPipe(newPipeConfig); clientRequest.initBuffers(); PipeConfig<MQTTClientResponseSchema> newPipeConfig2 = MQTTClientResponseSchema.instance.newPipeConfig((int) maxInFlight, maximumLenghOfVariableLengthFields); clientResponse = new Pipe<MQTTClientResponseSchema>(newPipeConfig2); final byte totalConnectionsInBits = 2; //only 4 brokers final short maxPartialResponses = 1; MQTTClientGraphBuilder.buildMQTTClientGraph(builder.gm, certificates, maxInFlight, maximumLenghOfVariableLengthFields, clientRequest, clientResponse, rate, totalConnectionsInBits, maxPartialResponses, user,pass); //send the broker details publishBrokerConfig(clientRequest); //send the connect msg publishConnect(clientRequest); configStage = BridgeConfigStage.DeclareBehavior; } } private final int code = System.identityHashCode(this); private CharSequence[] internalTopicsXmit = new CharSequence[0]; private CharSequence[] externalTopicsXmit = new CharSequence[0]; private EgressConverter[] convertersXmit = new EgressConverter[0]; private int[] qosXmit = new int[0]; private int[] retainXmit = new int[0]; private CharSequence[] internalTopicsSub = new CharSequence[0]; private CharSequence[] externalTopicsSub = new CharSequence[0]; private IngressConverter[] convertersSub = new IngressConverter[0]; private int[] qosSub = new int[0]; @Override public long addSubscription(CharSequence internalTopic, CharSequence externalTopic) { ensureConnected(); internalTopicsSub = grow(internalTopicsSub, internalTopic); externalTopicsSub = grow(externalTopicsSub, externalTopic); convertersSub = grow(convertersSub,IngressMQTTStage.copyConverter); qosSub = grow(qosSub, subscriptionQoS); assert(internalTopicsSub.length == externalTopicsSub.length); assert(internalTopicsSub.length == convertersSub.length); assert(internalTopicsSub.length == qosSub.length); return internalTopicsSub.length-1; } @Override public long addSubscription(CharSequence internalTopic, CharSequence externalTopic, IngressConverter converter) { ensureConnected(); internalTopicsSub = grow(internalTopicsSub, internalTopic); externalTopicsSub = grow(externalTopicsSub, externalTopic); convertersSub = grow(convertersSub,converter); qosSub = grow(qosSub, subscriptionQoS); assert(internalTopicsSub.length == externalTopicsSub.length); assert(internalTopicsSub.length == convertersSub.length); assert(internalTopicsSub.length == qosSub.length); return internalTopicsSub.length-1; } @Override public long addTransmission(MsgRuntime<?,?> msgRuntime, CharSequence internalTopic, CharSequence externalTopic) { ensureConnected(); //logger.trace("added subscription to {} in order to transmit out to ",internalTopic, externalTopic); builder.addStartupSubscription(internalTopic, code); internalTopicsXmit = grow(internalTopicsXmit, internalTopic); externalTopicsXmit = grow(externalTopicsXmit, externalTopic); convertersXmit = grow(convertersXmit,EgressMQTTStage.copyConverter); qosXmit = grow(qosXmit, transmissionFieldQOS); retainXmit = grow(retainXmit, transmissionFieldRetain); assert(internalTopicsXmit.length == externalTopicsXmit.length); assert(internalTopicsXmit.length == convertersXmit.length); assert(internalTopicsXmit.length == qosXmit.length); return internalTopicsXmit.length-1; } @Override public long addTransmission(MsgRuntime<?,?> msgRuntime, CharSequence internalTopic, CharSequence externalTopic, EgressConverter converter) { ensureConnected(); builder.addStartupSubscription(internalTopic, code); internalTopicsXmit = grow(internalTopicsXmit, internalTopic); externalTopicsXmit = grow(externalTopicsXmit, externalTopic); convertersXmit = grow(convertersXmit,converter); qosXmit = grow(qosXmit, transmissionFieldQOS); assert(internalTopicsXmit.length == externalTopicsXmit.length); assert(internalTopicsXmit.length == convertersXmit.length); assert(internalTopicsXmit.length == qosXmit.length); return internalTopicsXmit.length-1; } private EgressConverter[] grow(EgressConverter[] converters, EgressConverter converter) { int i = converters.length; EgressConverter[] newArray = new EgressConverter[i+1]; System.arraycopy(converters, 0, newArray, 0, i); newArray[i] = converter; return newArray; } private int[] grow(int[] array, int newItem) { int i = array.length; int[] newArray = new int[i+1]; System.arraycopy(array, 0, newArray, 0, i); newArray[i] = newItem; return newArray; } private IngressConverter[] grow(IngressConverter[] converters, IngressConverter converter) { int i = converters.length; IngressConverter[] newArray = new IngressConverter[i+1]; System.arraycopy(converters, 0, newArray, 0, i); newArray[i] = converter; return newArray; } private CharSequence[] grow(CharSequence[] topics, CharSequence topic) { int i = topics.length; CharSequence[] newArray = new CharSequence[i+1]; System.arraycopy(topics, 0, newArray, 0, i); newArray[i] = topic; return newArray; } public void finalizeDeclareConnections(MsgRuntime<?,?> msgRuntime) { configStage = BridgeConfigStage.Finalized; assert(internalTopicsXmit.length == externalTopicsXmit.length); assert(internalTopicsXmit.length == convertersXmit.length); assert(internalTopicsSub.length == externalTopicsSub.length); assert(internalTopicsSub.length == convertersSub.length); if (internalTopicsSub.length>0) { //now publish all our subscription requests int i = externalTopicsSub.length; while (--i>=0) { PipeWriter.presumeWriteFragment(clientRequest, MQTTClientRequestSchema.MSG_SUBSCRIBE_8); PipeWriter.writeInt(clientRequest,MQTTClientRequestSchema.MSG_SUBSCRIBE_8_FIELD_QOS_21, qosSub[i]); PipeWriter.writeUTF8(clientRequest,MQTTClientRequestSchema.MSG_SUBSCRIBE_8_FIELD_TOPIC_23, externalTopicsSub[i]); PipeWriter.publishWrites(clientRequest); } IngressMQTTStage stage = new IngressMQTTStage(builder.gm, clientResponse, new Pipe<IngressMessages>(builder.pcm.getConfig(IngressMessages.class)), externalTopicsSub, internalTopicsSub, convertersSub, connectionFeedbackTopic); GraphManager.addNota(builder.gm, GraphManager.DOT_BACKGROUND, MQTTClientGraphBuilder.BACKGROUND_COLOR, stage); } else { PipeCleanerStage.newInstance(builder.gm, clientResponse); } if (internalTopicsXmit.length>0) { EgressMQTTStage stage = new EgressMQTTStage(builder.gm, msgRuntime.buildPublishPipe(code), clientRequest, internalTopicsXmit, externalTopicsXmit, convertersXmit, qosXmit, retainXmit); GraphManager.addNota(builder.gm, GraphManager.DOT_BACKGROUND, MQTTClientGraphBuilder.BACKGROUND_COLOR, stage); } else { PipeNoOp.newInstance(builder.gm, clientRequest); } } private int activeRow = -1; private final MQTTConfigTransmission transConf = new MQTTConfigTransmission() { @Override public MQTTConfigTransmission setQoS(MQTTQoS qos) { qosXmit[activeRow] = qos.getSpecification(); return transConf; } @Override public MQTTConfigTransmission setRetain(boolean retain) { retainXmit[activeRow] = retain?1:0; return transConf; } }; private final MQTTConfigSubscription subsConf = new MQTTConfigSubscription() { @Override public void setQoS(MQTTQoS qos) { qosSub[activeRow] = qos.getSpecification(); } }; @Override public MQTTConfigTransmission transmissionConfigurator(long id) { activeRow = (int)id; return transConf; } @Override public MQTTConfigSubscription subscriptionConfigurator(long id) { activeRow = (int)id; return subsConf; } }
package com.ociweb.iot.grove; import com.ociweb.iot.hardware.I2CConnection; import com.ociweb.iot.hardware.IODevice; import com.ociweb.iot.maker.FogCommandChannel; import com.ociweb.pronghorn.iot.schema.I2CCommandSchema; import com.ociweb.pronghorn.pipe.DataOutputBlobWriter; import static com.ociweb.iot.grove.Grove_OLED_128x64_Constants.*; import static com.ociweb.iot.grove.Grove_OLED_128x64_Constants.Direction.*; import com.ociweb.iot.grove.display.OLED_128x64; /** * Singleton utility class that communicates with the i2c Grove OLED 128x64 display, includes basic functionality such as printing * bitmap or CharSequence. * @author Ray Lo, Nathan Tippy * */ public class Grove_OLED_128x64 implements IODevice{ private static Grove_OLED_128x64 instance = null; /** * Private constructor for singleton design pattern. */ private Grove_OLED_128x64(){ } /** * Returns the singleton instance of Grove_OLED_128x64, lazily initializes the instance if it's still. * @return singleton instance */ public static Grove_OLED_128x64 getInstace(){ if (instance == null){ instance = new Grove_OLED_128x64(); } return instance; } /** * Dynamically allocates an instance of {@link OLED_128x64} * @param ch {@link FogCommandChannel} reference to be held onto by the new {@link OLED_128x64} * @return the new instance of {@link OLED_128x64} created. */ public static OLED_128x64 newObj(FogCommandChannel ch){ return new OLED_128x64(ch); } public static boolean isStarted = false; /** * Flashes the display screen off and then on and ensures that the inverse_display and scrolling functions * are turned off. The display is left in the Horizontal mode afterwards. * @param target is the {@link com.ociweb.iot.maker.FogCommandChannel} in charge of the i2c connection. * @return true if the commands were sent, returns false if any single command was not sent. */ public static boolean init(FogCommandChannel target, int[] output){ output[0] = PUT_DISPLAY_TO_SLEEP; output[1] = WAKE_DISPLAY; output[2] = TURN_OFF_INVERSE_DISPLAY; output[3] = DEACTIVATE_SCROLL; output[4] = SET_MEMORY; output[5] = 0x00; output[6] = SET_DISPLAY_OFFSET; output[7] = 0x00; return sendCommands(target, output, 0, 8); } /** * Send an array of data * Implemented by calling {@link #sendData(FogCommandChannel, int[], int, int, int)}, which recursively calls itself * exactly 'm' times, where 'm' is the number of batches requires to send the data array specified by the start and length. * @param ch * @param data * @param start * @param length * @return true if the i2c bus is ready, false otherwise. */ private static boolean sendData(FogCommandChannel ch, int[] data, int start, int length){ if (!ch.i2cIsReady()){ return false; } //call the helper method to recursively send batches return sendData(ch,data,start,BATCH_SIZE, start+length); } private static boolean sendData(FogCommandChannel ch, int[] data, int start, int length, int finalTargetIndex){ DataOutputBlobWriter<I2CCommandSchema> i2cPayloadWriter = ch.i2cCommandOpen(OLEDADDRESS); i2cPayloadWriter.write(DATA_MODE); int i; for (i = start; i < Math.min(start + length, finalTargetIndex); i++){ i2cPayloadWriter.write(data[i]); } ch.i2cCommandClose(); ch.i2cFlushBatch(); if (i == finalTargetIndex){ return true; } return sendData(ch, data, i + 1, BATCH_SIZE, finalTargetIndex); //calls itself recursively until we reach finalTargetIndex } /* private static boolean iterativeSendData(FogCommandChannel ch, int[] data, int start, int length){ * DataOutputBlobWriter<I2CCommandSchema> i2cPayloadWriter = ch.i2cCommandOpen(OLEDADDRESS); int counter = 1; i2cPayloadWriter.write(DATA_MODE); //TODO: Fix for loop to not check batch size every iteration for (int i = start; i < start+length; i ++){ if (counter < BATCH_SIZE){ i2cPayloadWriter.write(data[i]); counter = counter + 1; } else { ch.i2cCommandClose(); ch.i2cFlushBatch(); i2cPayloadWriter = ch.i2cCommandOpen(OLEDADDRESS); i2cPayloadWriter.write(DATA_MODE); i2cPayloadWriter.write(data[i]); counter = 2; } } if (counter > 0){ ch.i2cCommandClose(); ch.i2cFlushBatch(); } */ /* final int num_batches = length / BATCH_SIZE; DataOutputBlobWriter<I2CCommandSchema> i2cPayloadWriter = ch.i2cCommandOpen(OLEDADDRESS); i2cPayloadWriter.write(DATA_MODE); //iterate through all the batches we need to send for (int i = 0; i < num_batches; i++){ //iterate through all the indiviusal bytes in each batch for (int j = start + (i * BATCH_SIZE); j < start + ( (i + 1) * BATCH_SIZE); j++){ i2cPayloadWriter.write(data[j]); } //flush the batch once a batch is full ch.i2cCommandClose(); ch.i2cFlushBatch(); i2cPayloadWriter = ch.i2cCommandOpen(OLEDADDRESS); i2cPayloadWriter.write(DATA_MODE); } //send the last fraction of batch worth of remaining bytes. int start_last_batch = start + (num_batches * BATCH_SIZE); for (int j = start_last_batch; j < start + length; j++){ i2cPayloadWriter.write(data[j]); } ch.i2cCommandClose(); ch.i2cFlushBatch(); return true; } */ /** * Sends a "data" identifier byte followed by the user-supplied byte over the i2c. * @param ch is the {@link com.ociweb.iot.maker.FogCommandChannel} in charge of the i2c connection to this OLED. * @param data is the array of data to be sent in the form of an integer array (the L.S. 8 bits of each int are used.) * @return true if the command byte and the supplied byte were succesfully sent, false otherwise. */ public static boolean sendData(FogCommandChannel ch, int[] data ){ return sendData(ch, data,0, data.length); } /** * Sets the contrast (olso refered to as brightness) of the display. * @param ch is the {@link com.ociweb.iot.maker.FogCommandChannel} in charge of the i2c connection to this OLED. * @param contrast is a value ranging from 0 to 255. A bit-mask is enforced so that only the lowest 8 bits of the supplied integer will matter. * @return true if the command byte and the contrast byte were sent, false otherwise. */ public static boolean setContrast(FogCommandChannel ch, int contrast, int[] output){ output[0] = SET_CONTRAST_CONTROL; output[1] = contrast & 0xFF; return sendCommands(ch, output, 0, 2); } public static boolean setPageMode(FogCommandChannel ch, int[] output){ output[0] = SET_MEMORY; output[1] = 0x02; return sendCommands(ch, output, 0, 2); } public static boolean setHorizontalMode(FogCommandChannel ch, int[] output){ output[0] = SET_MEMORY; output[1] = 0x00; return sendCommands(ch, output, 0, 2); } public static boolean setVerticalMode(FogCommandChannel ch, int[] output){ output[0] = SET_MEMORY; output[1] = 0x01; return sendCommands(ch, output, 0, 2); } /** * Turns on the inverse feature which switches all black pixels with white pixels and vice versa. * @param ch is the ch is the {@link com.ociweb.iot.maker.FogCommandChannel} in charge of the i2c connection of this OLED. * @return true if all two necessary bytes were sent, false otherwise. */ public static boolean turnOnInverseDisplay(FogCommandChannel ch){ return sendCommand(ch, TURN_ON_INVERSE_DISPLAY); } /** * Turns off the inverse feature which switches all black pixels with white pixels and vice versa. * @param ch is the ch is the {@link com.ociweb.iot.maker.FogCommandChannel} in charge of the i2c connection of this OLED. * @return true if all two necessary bytes were sent, false otherwise. */ public static boolean turnOffInverseDisplay(FogCommandChannel ch){ return sendCommand(ch, TURN_OFF_INVERSE_DISPLAY); } public static boolean activateScroll(FogCommandChannel ch){ return sendCommand(ch, ACTIVATE_SCROLL); } public static boolean deactivateScroll(FogCommandChannel ch){ return sendCommand(ch, DEACTIVATE_SCROLL); } public static boolean setMultiplexRatio(FogCommandChannel ch, int mux_ratio, int[] output){ output[0] = SET_MUX_RATIO; output[1] = mux_ratio & 0x3F; return sendCommands(ch, output, 0,2); } public static boolean setClockDivRatioAndOscFreq(FogCommandChannel ch, int clock_div_ratio, int osc_freq, int [] output){ output[0] = SET_CLOCK_DIV_RATIO; output[1] = (clock_div_ratio & 0x0F) | (osc_freq << 4 & 0xF0); return sendCommands(ch, output, 0,2); } public static boolean setVerticalOffset(FogCommandChannel ch, int offset, int[] output){ output[0] = SET_DISPLAY_OFFSET; output[1] = offset & 0x3F; return sendCommands(ch, output, 0,2); } public static boolean setUpRightContinuousHorizontalScroll(FogCommandChannel ch, ScrollSpeed speed, int startPage, int endPage, int[] output){ return setUpContinuousHorizontalScroll(ch, speed, startPage, endPage, Right, output); } public static boolean setUpLeftContinuousHorizontalScroll(FogCommandChannel ch, ScrollSpeed speed, int startPage, int endPage, int[] output){ return setUpContinuousHorizontalScroll(ch, speed, startPage, endPage, Left, output); } public static boolean setUpRightContinuousVerticalHorizontalScroll(FogCommandChannel ch, ScrollSpeed speed, int startPage, int endPage, int offset, int[] output){ return setUpContinuousVerticalHorizontalScroll(ch, speed, startPage, endPage, offset, Vertical_Right, output); } public static boolean setUpLeftContinuousVerticalHorizontalScroll(FogCommandChannel ch, ScrollSpeed speed, int startPage, int endPage, int offset, int[] output){ return setUpContinuousVerticalHorizontalScroll(ch, speed, startPage, endPage, offset, Vertical_Left, output); } private static boolean setUpContinuousHorizontalScroll(FogCommandChannel ch, ScrollSpeed speed, int startPage, int endPage, Direction orientation, int[] output){ int dir_command = 0; switch (orientation){ case Right: dir_command = SET_RIGHT_HOR_SCROLL; break; case Left: dir_command = SET_LEFT_HOR_SCROLL; break; } output[0] = dir_command; output[1] = 0x00; //dummy byte as required output[2] = startPage & 0x07; output[3] =speed.command; output[4] =endPage & 0x07; output[5] = 0xFF; // dummy byte as required output[6] = 0x00; // dummy byte as required return sendCommands(ch, output, 0,7); } private static boolean setUpContinuousVerticalHorizontalScroll(FogCommandChannel ch, ScrollSpeed speed, int startPage, int endPage, int offset, Direction orientation, int[] output){ int dir_command = 0; switch (orientation){ case Vertical_Left: dir_command = SET_VER_AND_RIGHT_HOR_SCROLL; break; case Vertical_Right: dir_command = SET_VER_AND_LEFT_HOR_SCROLL; break; } output[0] = dir_command; output[1] = 0x00; //dummy byte as required output[2] = startPage & 0x07; output[3] =speed.command; output[4] =endPage & 0x07; output[5] = offset & 0x1F; return sendCommands(ch,output,0,6); } /** * NOTE: this method leaves the display in horizontal mode * @param ch * @param map * @return true if the i2c commands were succesfully sent, false otherwise */ public static boolean drawBitmapInHorizontalMode(FogCommandChannel ch, int[] map, int[] data_output){ if (!setHorizontalMode(ch,data_output)){ return false; } return sendData(ch,map); } public static boolean drawBitmap(FogCommandChannel ch, int[] map, int[] cmd_output){ return drawBitmapInPageMode(ch, map, cmd_output); } /** * NOTE: drawing in page mode instead of horizontal mode sends 16 extra bytes per reflash compared to drawing * in horizontal mode as we need to reset textRowCol everytime we reach a new page. It may be preferable to use * drawing in page mode however, as it eliminates the need to switch between page mode and horizontal mode when doing * both drawing and CharSequence printing. * @param ch * @param map * @return true */ public static boolean drawBitmapInPageMode(FogCommandChannel ch, int[] map, int[] cmd_output){ for (int page = 0; page <8; page++){ if (! setTextRowCol(ch,page,0, cmd_output)){ return false; } int startingPoint = page*128; if (!sendData(ch, map, startingPoint, 128)){ return false; } } return true; } public static boolean encodeChar(char c, int[] output){ return encodeChar(c, output, 0); } public static boolean encodeChar(char c, int[] output, int start){ if (c > 127 || c < 32){ //'c' has no defined font for Grove_OLED_128x64"); return false; } int counter = 0; for (int i = start; i < start + 8; i++){ output[i] = BASIC_FONT[c-32][counter]; counter ++; } return true; } public static boolean encodeCharSequence(CharSequence s, int[] output){ return encodeCharSequence(s, output, 0, s.length()); } public static boolean encodeCharSequence(CharSequence s, int[] output, int start, int CharSequence_length){ for (int i = start; i < start + CharSequence_length; i++){ if (encodeChar(s.charAt(i), output, i*8)){ } else { return false; } } return true; } public static boolean printCharSequenceAt(FogCommandChannel ch, CharSequence s, int[] data_output, int row, int col, int[] cmd_output){ return setTextRowCol(ch,row,col, cmd_output) && printCharSequence(ch,s,data_output); } public static boolean printCharSequence(FogCommandChannel ch, CharSequence s, int[] output){ encodeCharSequence(s, output); return sendData(ch, output, 0, s.length()*8); } public static boolean setTextRowCol(FogCommandChannel ch, int row, int col, int[] output){ //only works in Page Mode //bit-mask because x and y can only be within a certain range (0-7) output[0] = ROW_START_ADDRESS_PAGE_MODE + (row & 0x07); output[1] = LOWER_COL_START_ADDRESS_PAGE_MODE + (8*col & 0x0F); output[2] = HIGHER_COL_START_ADDRESS_PAGE_MODE + ((8*col >> 4) & 0x0F); //TODO: avoid three seperate if-statements by ANDing them in the condtional, is there a better way? return sendCommands(ch, output, 0, 3); } public static boolean setPageModeAndTextRowCol(FogCommandChannel ch, int row, int col, int[] output){ return setPageMode(ch, output) && setTextRowCol(ch,row,col, output); } public static boolean setDisplayStartLine(FogCommandChannel ch, int startLine,int[] output){ output[0] = DISPLAY_START_LINE; output[1] = startLine & 0x3F; return sendCommands(ch, output,0,2); } public static boolean remapSegment(FogCommandChannel ch, boolean isRemapped){ int remap_cmd = MAP_ADDRESS_0_TO_SEG0; if (isRemapped){ remap_cmd = MAP_ADDRESS_127_TO_SEG0; } return sendCommand(ch, remap_cmd); } /** * Note: leaves the display in page mode * @param ch * @return true */ public static boolean clear(FogCommandChannel ch, int[] output){ if (setPageMode(ch, output)){ } else { return false; } for (int row = 0; row < 8; row++){ setTextRowCol(ch, row, 0, output); if (sendData(ch, EMPTY_ROW)){ } else { return false; } } return true; } public static boolean cleanClear(FogCommandChannel ch, int[] output){ if (sendCommand(ch, PUT_DISPLAY_TO_SLEEP) && clear(ch, output) && sendCommand(ch, WAKE_DISPLAY)) { ch.i2cFlushBatch(); return true; } ch.i2cFlushBatch(); return false; } private static boolean sendCommand(FogCommandChannel ch, int b){ if (!ch.i2cIsReady()){ return false; } DataOutputBlobWriter<I2CCommandSchema> i2cPayloadWriter = ch.i2cCommandOpen(OLEDADDRESS); i2cPayloadWriter.write(Grove_OLED_128x64_Constants.COMMAND_MODE); i2cPayloadWriter.write(b); ch.i2cCommandClose(); return true; } /** * Unliked send data, sendCommands makes the assumption that the call is not sending more than one batch worth of commands *Each command involves two bytes. So if the caller is trying to send a command array of size 5, they are really sending *10 bytes. * @param ch * @param commands * @param start * @param length * @return */ private static boolean sendCommands(FogCommandChannel ch, int[] commands, int start, int length){ if (!ch.i2cIsReady()){ return false; } DataOutputBlobWriter<I2CCommandSchema> i2cPayloadWriter = ch.i2cCommandOpen(OLEDADDRESS); assert(length*2 <= BATCH_SIZE); for (int i = start; i < start + length; i++){ i2cPayloadWriter.write(COMMAND_MODE); i2cPayloadWriter.write(commands[i]); } ch.i2cCommandClose(); ch.i2cFlushBatch(); return true; } @Deprecated private static boolean writeByteSequence(FogCommandChannel ch, byte[] seq){ if(!ch.i2cIsReady()){ return false; } DataOutputBlobWriter<I2CCommandSchema> i2cPayloadWriter = ch.i2cCommandOpen(OLEDADDRESS); i2cPayloadWriter.write(seq); ch.i2cCommandClose(); return true; } //Overloading the function to automatically mask ints and use their least significant 8-bits as our bytes to send //Ideally, for best performance, we should send byte array and not int array to avoid this extra function call @Deprecated private static boolean writeByteSequence(FogCommandChannel ch, int[] seq){ byte[] byteSeq = new byte[seq.length]; int counter = 0; for (int i: seq){ byteSeq[counter] = (byte)(i & 0xFF); //this mask turns anything but the smallest 8 bits to 0 counter++; } return writeByteSequence(ch, byteSeq); } @Override public int response() { return 20; } @Override public int scanDelay() { return 0; } @Override public boolean isInput() { return false; } @Override public boolean isOutput() { return true; } @Override public boolean isPWM() { return false; } @Override public int range() { return 0; } @Override public I2CConnection getI2CConnection() { byte[] LED_READCMD = {}; byte[] LED_SETUP = {}; byte LED_ADDR = 0x04; byte LED_BYTESTOREAD = 0; byte LED_REGISTER = 0; return new I2CConnection(this, LED_ADDR, LED_READCMD, LED_BYTESTOREAD, LED_REGISTER, LED_SETUP); } @Override public boolean isValid(byte[] backing, int position, int length, int mask) { return true; } @Override public int pinsUsed() { return 1; } }
package com.randomcoder.saml; import java.io.Serializable; import java.util.Locale; public class SamlAttributeSpec implements Serializable { private static final long serialVersionUID = -536785258783107725L; private String namespace; private String local; public SamlAttributeSpec(String namespace, String local) throws IllegalArgumentException { if (namespace == null) throw new IllegalArgumentException("namespace is required"); if (local == null) throw new IllegalArgumentException("local is required"); this.namespace = namespace; this.local = local.toLowerCase(Locale.US); } /** * Gets the namespace of this attribute. * @return namespace */ public String getNamespace() { return namespace; } /** * Gets the localname of this attribute. * @return namespace */ public String getLocal() { return local; } /** * Determines if this <code>SamlAttributeSpec</code> is equal * to another instance of this class. * * <p> * This method will return true if and only if the namespace and local * fields in the two classes are equal. * </p> * @param obj object to compare * @return true if equal, false otherwise */ @Override public boolean equals(Object obj) { if (!(obj instanceof SamlAttributeSpec)) return false; SamlAttributeSpec other = (SamlAttributeSpec) obj; if (!namespace.equals(other.namespace)) return false; return local.equals(other.local); } /** * Calculates a hash code. * @return hash code */ @Override public int hashCode() { return toString().hashCode(); } /** * Generates a string representation of this class. * <p> * The format of the returned string is {namespace}:{local}. * </p> * @return string version */ @Override public String toString() { return new StringBuilder(namespace).append(":").append(local).toString(); } }
package com.sandwell.JavaSimulation; import java.io.File; import javax.swing.JFrame; import com.jaamsim.basicsim.Entity; import com.jaamsim.basicsim.InitModelTarget; import com.jaamsim.events.EventManager; import com.jaamsim.input.BooleanInput; import com.jaamsim.input.Input; import com.jaamsim.input.InputAgent; import com.jaamsim.input.InputErrorException; import com.jaamsim.input.IntegerInput; import com.jaamsim.input.Keyword; import com.jaamsim.input.Output; import com.jaamsim.input.StringInput; import com.jaamsim.input.ValueInput; import com.jaamsim.ui.EditBox; import com.jaamsim.ui.EntityPallet; import com.jaamsim.ui.FrameBox; import com.jaamsim.ui.LogBox; import com.jaamsim.ui.ObjectSelector; import com.jaamsim.ui.OutputBox; import com.jaamsim.ui.PropertyBox; import com.jaamsim.units.DimensionlessUnit; import com.jaamsim.units.TimeUnit; import com.sandwell.JavaSimulation3D.Clock; import com.sandwell.JavaSimulation3D.GUIFrame; /** * Class Simulation - Sandwell Discrete Event Simulation * <p> * Class structure defining essential simulation objects. Eventmanager is * instantiated to manage events generated in the simulation. Function prototypes * are defined which any simulation must define in order to run. */ public class Simulation extends Entity { @Keyword(description = "The initialization period for the simulation run. The model will " + "run for the initialization period and then clear the statistics " + "and execute for the specified run duration. The total length of the " + "simulation run will be the sum of Initialization and Duration.", example = "Simulation Initialization { 720 h }") private static final ValueInput initializationTime; @Keyword(description = "Date at which the simulation run is started (yyyy-mm-dd). This " + "input has no effect on the simulation results unless the seasonality " + "factors vary from month to month.", example = "Simulation StartDate { 2011-01-01 }") private static final StringInput startDate; @Keyword(description = "Time at which the simulation run is started (hh:mm).", example = "Simulation StartTime { 2160 h }") private static final ValueInput startTimeInput; @Keyword(description = "The duration of the simulation run in which all statistics will be recorded.", example = "Simulation Duration { 8760 h }") private static final ValueInput runDuration; @Keyword(description = "The time at which the simulation will be paused.", example = "Simulation PauseTime { 200 h }") private static final ValueInput pauseTime; @Keyword(description = "The number of discrete time units in one hour.", example = "Simulation SimulationTimeScale { 4500 }") private static final ValueInput simTimeScaleInput; @Keyword(description = "If the value is TRUE, then the input report file will be printed after loading the " + "configuration file. The input report can always be generated when needed by selecting " + "\"Print Input Report\" under the File menu.", example = "Simulation PrintInputReport { TRUE }") private static final BooleanInput printInputReport; @Keyword(description = "This is placeholder description text", example = "This is placeholder example text") private static final BooleanInput traceEventsInput; @Keyword(description = "This is placeholder description text", example = "This is placeholder example text") private static final BooleanInput verifyEventsInput; @Keyword(description = "The real time speed up factor", example = "Simulation RealTimeFactor { 1200 }") private static final IntegerInput realTimeFactor; public static final int DEFAULT_REAL_TIME_FACTOR = 10000; public static final int MIN_REAL_TIME_FACTOR = 1; public static final int MAX_REAL_TIME_FACTOR= 1000000; @Keyword(description = "A Boolean to turn on or off real time in the simulation run", example = "Simulation RealTime { TRUE }") private static final BooleanInput realTime; @Keyword(description = "Indicates whether to close the program on completion of the simulation run.", example = "Simulation ExitAtStop { TRUE }") private static final BooleanInput exitAtStop; @Keyword(description = "Indicates whether the Model Builder tool should be shown on startup.", example = "Simulation ShowModelBuilder { TRUE }") private static final BooleanInput showModelBuilder; @Keyword(description = "Indicates whether the Object Selector tool should be shown on startup.", example = "Simulation ShowObjectSelector { TRUE }") private static final BooleanInput showObjectSelector; @Keyword(description = "Indicates whether the Input Editor tool should be shown on startup.", example = "Simulation ShowInputEditor { TRUE }") private static final BooleanInput showInputEditor; @Keyword(description = "Indicates whether the Output Viewer tool should be shown on startup.", example = "Simulation ShowOutputViewer { TRUE }") private static final BooleanInput showOutputViewer; @Keyword(description = "Indicates whether the Output Viewer tool should be shown on startup.", example = "Simulation ShowPropertyViewer { TRUE }") private static final BooleanInput showPropertyViewer; @Keyword(description = "Indicates whether the Log Viewer tool should be shown on startup.", example = "Simulation ShowLogViewer { TRUE }") private static final BooleanInput showLogViewer; private static double timeScale; // the scale from discrete to continuous time private static double startTime; private static double endTime; private static Simulation myInstance; private static String modelName = "JaamSim"; static { initializationTime = new ValueInput("InitializationDuration", "Key Inputs", 0.0); initializationTime.setUnitType(TimeUnit.class); initializationTime.setValidRange(0.0d, Double.POSITIVE_INFINITY); runDuration = new ValueInput("RunDuration", "Key Inputs", 31536000.0d); runDuration.setUnitType(TimeUnit.class); runDuration.setValidRange(1e-15d, Double.POSITIVE_INFINITY); pauseTime = new ValueInput("PauseTime", "Key Inputs", Double.POSITIVE_INFINITY); pauseTime.setUnitType(TimeUnit.class); pauseTime.setValidRange(0.0d, Double.POSITIVE_INFINITY); startDate = new StringInput("StartDate", "Key Inputs", null); startTimeInput = new ValueInput("StartTime", "Key Inputs", 0.0d); startTimeInput.setUnitType(TimeUnit.class); startTimeInput.setValidRange(0.0d, Double.POSITIVE_INFINITY); simTimeScaleInput = new ValueInput("SimulationTimeScale", "Key Inputs", 4000.0d); simTimeScaleInput.setUnitType(DimensionlessUnit.class); simTimeScaleInput.setValidRange(1e-15d, Double.POSITIVE_INFINITY); traceEventsInput = new BooleanInput("TraceEvents", "Key Inputs", false); verifyEventsInput = new BooleanInput("VerifyEvents", "Key Inputs", false); printInputReport = new BooleanInput("PrintInputReport", "Key Inputs", false); realTimeFactor = new IntegerInput("RealTimeFactor", "Key Inputs", DEFAULT_REAL_TIME_FACTOR); realTimeFactor.setValidRange(MIN_REAL_TIME_FACTOR, MAX_REAL_TIME_FACTOR); realTime = new BooleanInput("RealTime", "Key Inputs", false); exitAtStop = new BooleanInput("ExitAtStop", "Key Inputs", false); showModelBuilder = new BooleanInput("ShowModelBuilder", "Key Inputs", false); showObjectSelector = new BooleanInput("ShowObjectSelector", "Key Inputs", false); showInputEditor = new BooleanInput("ShowInputEditor", "Key Inputs", false); showOutputViewer = new BooleanInput("ShowOutputViewer", "Key Inputs", false); showPropertyViewer = new BooleanInput("ShowPropertyViewer", "Key Inputs", false); showLogViewer = new BooleanInput("ShowLogViewer", "Key Inputs", false); // Create clock Clock.setStartDate(2000, 1, 1); // Initialize basic model information startTime = 0.0; endTime = 8760.0; } { this.addInput(runDuration); this.addInput(initializationTime); this.addInput(pauseTime); this.addInput(startDate); this.addInput(startTimeInput); this.addInput(simTimeScaleInput); this.addInput(traceEventsInput); this.addInput(verifyEventsInput); this.addInput(printInputReport); this.addInput(realTimeFactor); this.addInput(realTime); this.addInput(exitAtStop); this.addInput(showModelBuilder); this.addInput(showObjectSelector); this.addInput(showInputEditor); this.addInput(showOutputViewer); this.addInput(showPropertyViewer); this.addInput(showLogViewer); attributeDefinitionList.setHidden(true); startDate.setHidden(true); startTimeInput.setHidden(true); traceEventsInput.setHidden(true); verifyEventsInput.setHidden(true); printInputReport.setHidden(true); } public Simulation() {} public static Simulation getInstance() { if (myInstance == null) { for (Entity ent : Entity.getAll()) { if (ent instanceof Simulation ) { myInstance = (Simulation) ent; break; } } } return myInstance; } @Override public void validate() { super.validate(); if( startDate.getValue() != null && !Tester.isDate( startDate.getValue() ) ) { throw new InputErrorException("The value for Start Date must be a valid date."); } } @Override public void updateForInput( Input<?> in ) { super.updateForInput( in ); if(in == realTimeFactor || in == realTime) { updateRealTime(); return; } if (in == pauseTime) { updatePauseTime(); return; } if (in == showModelBuilder) { setWindowVisible(EntityPallet.getInstance(), showModelBuilder.getValue()); return; } if (in == showObjectSelector) { setWindowVisible(ObjectSelector.getInstance(), showObjectSelector.getValue()); return; } if (in == showInputEditor) { setWindowVisible(EditBox.getInstance(), showInputEditor.getValue()); FrameBox.reSelectEntity(); return; } if (in == showOutputViewer) { setWindowVisible(OutputBox.getInstance(), showOutputViewer.getValue()); FrameBox.reSelectEntity(); return; } if (in == showPropertyViewer) { setWindowVisible(PropertyBox.getInstance(), showPropertyViewer.getValue()); FrameBox.reSelectEntity(); return; } if (in == showLogViewer) { setWindowVisible(LogBox.getInstance(), showLogViewer.getValue()); FrameBox.reSelectEntity(); return; } } public static void clear() { initializationTime.reset(); runDuration.reset(); pauseTime.reset(); simTimeScaleInput.reset(); traceEventsInput.reset(); verifyEventsInput.reset(); printInputReport.reset(); realTimeFactor.reset(); realTime.reset(); updateRealTime(); exitAtStop.reset(); startDate.reset(); startTimeInput.reset(); showModelBuilder.reset(); showObjectSelector.reset(); showInputEditor.reset(); showOutputViewer.reset(); showPropertyViewer.reset(); showLogViewer.reset(); // Create clock Clock.setStartDate(2000, 1, 1); // Initialize basic model information startTime = 0.0; endTime = 8760.0; // close warning/error trace file InputAgent.closeLogFile(); // Kill all entities except simulation while(Entity.getAll().size() > 0) { Entity ent = Entity.getAll().get(Entity.getAll().size()-1); ent.kill(); } } /** * Initializes and starts the model * 1) Initializes EventManager to accept events. * 2) calls startModel() to allow the model to add its starting events to EventManager * 3) start EventManager processing events */ public static void start(EventManager evt) { // Validate each entity based on inputs only for (int i = 0; i < Entity.getAll().size(); i++) { try { Entity.getAll().get(i).validate(); } catch (Throwable e) { LogBox.format("%s: Validation error- %s", Entity.getAll().get(i).getName(), e.getMessage()); GUIFrame.showErrorDialog("Input Error Detected During Validation", "%s: %-70s", Entity.getAll().get(i).getName(), e.getMessage()); return; } } InputAgent.prepareReportDirectory(); evt.clear(); evt.setTraceListener(null); if( Simulation.traceEvents() ) { String evtName = InputAgent.getConfigFile().getParentFile() + File.separator + InputAgent.getRunName() + ".evt"; EventRecorder rec = new EventRecorder(evtName); evt.setTraceListener(rec); } else if( Simulation.verifyEvents() ) { String evtName = InputAgent.getConfigFile().getParentFile() + File.separator + InputAgent.getRunName() + ".evt"; EventTracer trc = new EventTracer(evtName); evt.setTraceListener(trc); } evt.setSimTimeScale(simTimeScaleInput.getValue()); setSimTimeScale(simTimeScaleInput.getValue()); FrameBox.setSecondsPerTick(3600.0d / simTimeScaleInput.getValue()); if( startDate.getValue() != null ) { Clock.getStartingDateFromString( startDate.getValue() ); } double startTimeHours = startTimeInput.getValue() / 3600.0d; startTime = Clock.calcTimeForYear_Month_Day_Hour(1, Clock.getStartingMonth(), Clock.getStartingDay(), startTimeHours); endTime = startTime + Simulation.getInitializationHours() + Simulation.getRunDurationHours(); evt.scheduleProcessExternal(0, Entity.PRIO_DEFAULT, false, new InitModelTarget(), null); } public static boolean traceEvents() { return traceEventsInput.getValue(); } public static boolean verifyEvents() { return verifyEventsInput.getValue(); } static void setSimTimeScale(double scale) { timeScale = scale; } public static double getSimTimeFactor() { return timeScale; } public static double getEventTolerance() { return (1.0d / getSimTimeFactor()); } public static double getPauseTime() { return pauseTime.getValue(); } /** * Returns the end time of the run. * @return double - the time the current run will stop */ public static double getEndHours() { return endTime; } /** * Return the run duration for the run (not including intialization) */ public static double getRunDurationHours() { return Simulation.getRunDuration() / 3600.0d; } /** * Returns the start time of the run. */ public static double getStartHours() { return startTime; } /** * Return the initialization duration in hours */ public static double getInitializationHours() { return Simulation.getInitializationTime() / 3600.0d; } /** * Returns the duration of the run (not including intialization) */ public static double getRunDuration() { return runDuration.getValue(); } /** * Returns the duration of the initialization period */ public static double getInitializationTime() { return initializationTime.getValue(); } static void updateRealTime() { GUIFrame.instance().updateForRealTime(realTime.getValue(), realTimeFactor.getValue()); } static void updatePauseTime() { GUIFrame.instance().updateForPauseTime(pauseTime.getValueString()); } public static void setModelName(String newModelName) { modelName = newModelName; } public static String getModelName() { return modelName; } public static boolean getExitAtStop() { return exitAtStop.getValue(); } public static boolean getPrintInputReport() { return printInputReport.getValue(); } private static void setWindowVisible(JFrame f, boolean visible) { f.setVisible(visible); if (visible) f.toFront(); } /** * Re-open any Tools windows that have been closed temporarily. */ public static void showActiveTools() { setWindowVisible(EntityPallet.getInstance(), showModelBuilder.getValue()); setWindowVisible(ObjectSelector.getInstance(), showObjectSelector.getValue()); setWindowVisible(EditBox.getInstance(), showInputEditor.getValue()); setWindowVisible(OutputBox.getInstance(), showOutputViewer.getValue()); setWindowVisible(PropertyBox.getInstance(), showPropertyViewer.getValue()); setWindowVisible(LogBox.getInstance(), showLogViewer.getValue()); } /** * Closes all the Tools windows temporarily. */ public static void closeAllTools() { setWindowVisible(EntityPallet.getInstance(), false); setWindowVisible(ObjectSelector.getInstance(), false); setWindowVisible(EditBox.getInstance(), false); setWindowVisible(OutputBox.getInstance(), false); setWindowVisible(PropertyBox.getInstance(), false); setWindowVisible(LogBox.getInstance(), false); } @Output(name = "Configuration File", description = "The present configuration file.") public String getConfigFileName(double simTime) { return InputAgent.getConfigFile().getPath(); } }
package com.winterbe.java8.explorer; import org.apache.commons.lang3.StringUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Optional; /** * @author Benjamin Winterberg */ public class FileParser { private static final String JAVA_VERSION = "1.8"; public Optional<TypeInfo> parse(File file, String path, Statistics statistics) throws IOException { if (!file.exists()) { throw new FileNotFoundException("file does not exist: " + file.getAbsolutePath()); } Document document = Jsoup.parse(file, "UTF-8", "http://download.java.net/jdk8/docs/api/"); try { return getTypeInfo(document, path, statistics); } catch (Exception e) { statistics.failures++; System.err.println("failed to parse file " + file.getAbsolutePath() + ": " + e.getMessage()); return Optional.empty(); } } private Optional<TypeInfo> getTypeInfo(Document document, String path, Statistics statistics) { String title = document.title(); String typeName = StringUtils.substringBefore(title, " "); Element body = document.body(); if (!body.html().contains(JAVA_VERSION)) { return Optional.empty(); } String fullType = body .select(".header h2") .first() .text(); String packageName = body .select(".header > .subTitle") .last() .text(); String declaration = body .select(".description > ul > li > pre") .first() .html(); boolean newType = false; Elements elements1 = body.select(".contentContainer .description dd"); for (Element dd : elements1) { if (dd.text().equals(JAVA_VERSION)) { newType = true; break; } } TypeInfo typeInfo = new TypeInfo(); typeInfo.setName(typeName); typeInfo.setFullType(fullType); FileType fileType = FileType.ofFullType(fullType); typeInfo.setFileType(fileType); typeInfo.setPackageName(packageName); typeInfo.setPath(path); typeInfo.setNewType(newType); typeInfo.setDeclaration(declaration); Elements elements = body.select(".contentContainer .details > ul > li > ul > li"); for (Element element : elements) { MemberType type = MemberType.UNKNOWN; Element a = element.child(0); String name = a.attr("name"); switch (name) { case "constructor.detail": type = MemberType.CONSTRUCTOR; break; case "method.detail": type = MemberType.METHOD; break; case "field.detail": type = MemberType.FIELD; break; } for (Element ul : element.select("> ul")) { String methodName = ul.select("h4").text(); Elements dds = ul.select("dl > dd"); for (Element dd : dds) { statistics.maxMembers++; if (newType || dd.text().equals(JAVA_VERSION)) { MemberInfo memberInfo = new MemberInfo(); memberInfo.setType(type); memberInfo.setName(methodName); memberInfo.setDeclaration(ul.select("pre").first().html()); typeInfo.getMembers().add(memberInfo); statistics.newMembers++; switch (memberInfo.getType()) { case METHOD: statistics.newMethods++; if (fileType == FileType.INTERFACE && memberInfo.isDefault()) { statistics.newDefaulInterfacetMethods++; } if (fileType == FileType.INTERFACE && memberInfo.isStatic()) { statistics.newStaticInterfaceMethods++; } break; case CONSTRUCTOR: statistics.newConstructors++; break; case FIELD: statistics.newFields++; break; } break; } } } } if (typeInfo.getMembers().isEmpty()) { return Optional.empty(); } if (newType) { statistics.newFiles++; switch (fileType) { case CLASS: statistics.newClasses++; break; case INTERFACE: statistics.newInterfaces++; break; case ENUM: statistics.newEnums++; break; } } if (typeInfo.isFunctionalInterface()) { statistics.maxFunctionalInterfaces++; } return Optional.of(typeInfo); } }
package crazypants.render; import net.minecraftforge.common.util.ForgeDirection; import crazypants.vecmath.Vector3d; public class VertexRotationFacing extends VertexRotation { private static final double ROTATION_AMOUNT = Math.PI / 2; private ForgeDirection defaultDir; public VertexRotationFacing(ForgeDirection defaultDir) { super(0, new Vector3d(0, 0.5, 0), new Vector3d(0, 0, 0)); this.defaultDir = defaultDir; } public void setRotation(ForgeDirection dir) { if(dir == defaultDir) { setAngle(0); } else if(dir == defaultDir.getOpposite()) { setAngle(ROTATION_AMOUNT * 2); } else if(dir == defaultDir.getRotation(ForgeDirection.DOWN)) { setAngle(ROTATION_AMOUNT); } else { setAngle(ROTATION_AMOUNT * 3); } } }
package de.hwrberlin.it2014.sweproject.cbr; import de.hwrberlin.it2014.sweproject.cbr.Case; import de.hwrberlin.it2014.sweproject.model.Judgement; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; /** * controls the cbr-cycle. Start the algorithm with startCBR(ArrayList<String>) method. * * @author Max Bock & Felix Lehmann * */ public class CBR { private ArrayList<Case> activeCases; //all cases from current userRequests private int COUNT_TO_RETURN; public CBR() { activeCases = new ArrayList<Case>(); COUNT_TO_RETURN=30; } public CBR(int count) { activeCases = new ArrayList<Case>(); COUNT_TO_RETURN=count; } /** * @author Max Bock * @param usersInput (String[]) * @return hnliche Flle */ public ArrayList<Judgement> startCBR(String[] usersInput) { ArrayList<String> al = new ArrayList<>(); for(String s : usersInput){ al.add(s); } return startCBR(al); } /** * @author Max Bock * @param usersInput (String) * @return hnliche Flle */ public ArrayList<Judgement> startCBR(String usersInput) { String[] ar = usersInput.split(" "); return startCBR(ar); } /** * @author Max Bock * @param usersInput (ArrayList<String>) * @return hnliche Flle */ public ArrayList<Judgement> startCBR(ArrayList<String> usersInput) { ArrayList<Judgement> judgList; try { judgList=retrieve(usersInput); } catch (SQLException e) { judgList=new ArrayList<>(); e.printStackTrace(); } return judgList; } /** * speichert die Bewertung zu einem Fall einer Anfrage * @param id der Anfrage * @param numberOfJudgement ist die Nummer des Falls in der bestimmten Anfrage * @param evaluation Bewertung * @return */ public String saveUserEvaluate(int id, int numberOfJudgement, float evaluation) { Case c = getCaseByID(id); c.saveEvaluation(numberOfJudgement, evaluation); if(c.isCompletelyEvaluated()) removeCaseByID(c.getID()); return null; } /** * Lscht einen Fall aus den activeCases * @author Max Bock * @param CaseID * @return boolean */ private boolean removeCaseByID(int id) { Case c = getCaseByID(id); if(null!=c) return activeCases.remove(c); else return false; } /** * liefert fr die Bewertung anhand der ID den Case zurck * @author Max Bock * @param interne Case ID * @return Case */ private Case getCaseByID(int id) { for(Case c :activeCases) { if(c.getID()==id) { return c; } } return null; } /** * interne Methode fr den CBR-Zyklus * @author Max Bock * @param usersInput * @return hnliche Flle * @throws SQLException */ private ArrayList<Judgement> retrieve(ArrayList<String> usersInput) throws SQLException { Case c = new Case(getHighestID()+1,usersInput); activeCases.add(c); return c.getSimiliarFromDB(COUNT_TO_RETURN); //change for more cases } /** * @author Max Bock * @return highest ID in activeCases */ private int getHighestID() { int id=0; for(Case c: activeCases) { if(c.getID()>id) { id=c.getID(); } } return id; } public ArrayList<Case> getActiveCases() { return activeCases; } /** * lscht alle Flle aus den activeCases, die lter als ein Tag sind * @author Max Bock * @return count of deleted cases(/requests) */ public int removeOldCases() { return removeOldCases((int)24); } /** * lscht alle Flle aus den activeCases, die lter als hours (Parameter int) sind * @author Max Bock * @param hours - int * @return count of deleted cases(/requests) */ private int removeOldCases(int hours) { long time = (long) hours * 60 * 60 * 1000; return removeOldCases(time); } /** * lscht alle Flle aus den active Cases, die lter als der Parameter(miliseconds) sind * sollte regelmig benutzt werden, damit nicht komplett bewertete Anfragen gelscht werden * miliseconds <= 1 lscht alle Flle * @author Max Bock * @param miliseconds * @return count of deleted cases(/requests) */ public int removeOldCases(long miliseconds) { int count = 0; if(1>=miliseconds) { count=activeCases.size(); activeCases.clear(); } else { Date current = new Date(); Date before = new Date(current.getTime()-miliseconds); for(Case c : activeCases) { if(c.getDateOfRequest().before(before)) { removeCaseByID(c.getID()); count++; } } } return count; } }
package edu.harvard.iq.dataverse; import edu.harvard.iq.dataverse.UserNotification.Type; import edu.harvard.iq.dataverse.engine.command.Command; import edu.harvard.iq.dataverse.engine.command.exception.CommandException; import edu.harvard.iq.dataverse.engine.command.impl.CreateDataverseCommand; import edu.harvard.iq.dataverse.engine.command.impl.DeleteDataverseCommand; import edu.harvard.iq.dataverse.engine.command.impl.PublishDataverseCommand; import edu.harvard.iq.dataverse.engine.command.impl.UpdateDataverseCommand; import static edu.harvard.iq.dataverse.util.JsfHelper.JH; import java.util.List; import javax.ejb.EJB; import javax.ejb.EJBException; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import javax.persistence.NoResultException; import java.util.ArrayList; import java.util.logging.Logger; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; import org.primefaces.model.DualListModel; import java.net.InetAddress; import java.net.UnknownHostException; /** * * @author gdurand */ @ViewScoped @Named("DataversePage") public class DataversePage implements java.io.Serializable { private static final Logger logger = Logger.getLogger(DataversePage.class.getCanonicalName()); public enum EditMode { CREATE, INFO, PERMISSIONS, SETUP, THEME } @EJB DataverseServiceBean dataverseService; @EJB DatasetServiceBean datasetService; @Inject DataverseSession session; @EJB EjbDataverseEngine commandEngine; @EJB SearchServiceBean searchService; @EJB DatasetFieldServiceBean datasetFieldService; @EJB DataverseFacetServiceBean dataverseFacetService; @EJB UserNotificationServiceBean userNotificationService; @EJB FeaturedDataverseServiceBean featuredDataverseService; private Dataverse dataverse = new Dataverse(); private EditMode editMode; private Long ownerId; private DualListModel<DatasetFieldType> facets; private DualListModel<Dataverse> featuredDataverses; // private TreeNode treeWidgetRootNode = new DefaultTreeNode("Root", null); public Dataverse getDataverse() { return dataverse; } public void setDataverse(Dataverse dataverse) { this.dataverse = dataverse; } public EditMode getEditMode() { return editMode; } public void setEditMode(EditMode editMode) { this.editMode = editMode; } public Long getOwnerId() { return ownerId; } public void setOwnerId(Long ownerId) { this.ownerId = ownerId; } // public TreeNode getTreeWidgetRootNode() { // return treeWidgetRootNode; // public void setTreeWidgetRootNode(TreeNode treeWidgetRootNode) { // this.treeWidgetRootNode = treeWidgetRootNode; public void init() { // FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Create Root Dataverse", " - To get started, you need to create your root dataverse.")); if (dataverse.getId() != null) { // view mode for a dataverse dataverse = dataverseService.find(dataverse.getId()); ownerId = dataverse.getOwner() != null ? dataverse.getOwner().getId() : null; } else if (ownerId != null) { // create mode for a new child dataverse editMode = EditMode.INFO; dataverse.setOwner(dataverseService.find(ownerId)); dataverse.setContactEmail(session.getUser().getEmail()); dataverse.setAffiliation(session.getUser().getAffiliation()); // FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Create New Dataverse", " - Create a new dataverse that will be a child dataverse of the parent you clicked from. Asterisks indicate required fields.")); } else { // view mode for root dataverse (or create root dataverse) try { dataverse = dataverseService.findRootDataverse(); } catch (EJBException e) { if (e.getCause() instanceof NoResultException) { editMode = EditMode.INFO; FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Create Root Dataverse", " - To get started, you need to create your root dataverse. Asterisks indicate required fields.")); } else { throw e; } } } List<DatasetFieldType> facetsSource = new ArrayList<>(); List<DatasetFieldType> facetsTarget = new ArrayList<>(); facetsSource.addAll(datasetFieldService.findAllFacetableFieldTypes()); List<DataverseFacet> facetsList = dataverseFacetService.findByDataverseId(dataverse.getId()); for (DataverseFacet dvFacet : facetsList) { DatasetFieldType dsfType = dvFacet.getDatasetFieldType(); facetsTarget.add(dsfType); facetsSource.remove(dsfType); } facets = new DualListModel<>(facetsSource, facetsTarget); List<Dataverse> featuredSource = new ArrayList<>(); List<Dataverse> featuredTarget = new ArrayList<>(); featuredSource.addAll(dataverseService.findAllPublishedByOwnerId(dataverse.getId())); List<DataverseFeaturedDataverse> featuredList = featuredDataverseService.findByDataverseId(dataverse.getId()); for (DataverseFeaturedDataverse dfd : featuredList) { Dataverse fd = dfd.getFeaturedDataverse(); featuredTarget.add(fd); featuredSource.remove(fd); } featuredDataverses = new DualListModel<>(featuredSource, featuredTarget); } // TODO: // this method will need to be moved somewhere else, possibly some // equivalent of the old VDCRequestBean - but maybe application-scoped? // -- L.A. 4.0 beta public String getDataverseSiteUrl() { String hostUrl = System.getProperty("dataverse.siteUrl"); if (hostUrl != null && !"".equals(hostUrl)) { return hostUrl; } String hostName = System.getProperty("dataverse.fqdn"); if (hostName == null) { try { hostName = InetAddress.getLocalHost().getCanonicalHostName(); } catch (UnknownHostException e) { return null; } } hostUrl = "http://"+hostName; return hostUrl; } public List<Dataverse> getCarouselFeaturedDataverses() { List<Dataverse> retList = new ArrayList(); List<DataverseFeaturedDataverse> featuredList = featuredDataverseService.findByDataverseId(dataverse.getId()); for (DataverseFeaturedDataverse dfd : featuredList) { Dataverse fd = dfd.getFeaturedDataverse(); retList.add(fd); } return retList; } public List getContents() { List contentsList = dataverseService.findByOwnerId(dataverse.getId()); contentsList.addAll(datasetService.findByOwnerId(dataverse.getId())); return contentsList; } public void edit(EditMode editMode) { this.editMode = editMode; if (editMode == EditMode.INFO) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Edit Dataverse", " - Edit your dataverse and click Save. Asterisks indicate required fields.")); } else if (editMode == EditMode.SETUP) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Edit Dataverse Setup", " - Edit the Metadata Blocks and Facets you want to associate with your dataverse. Note: facets will appear in the order shown on the list.")); } } public String save() { Command<Dataverse> cmd = null; //TODO change to Create - for now the page is expecting INFO instead. if (dataverse.getId() == null) { dataverse.setOwner(ownerId != null ? dataverseService.find(ownerId) : null); cmd = new CreateDataverseCommand(dataverse, session.getUser()); } else { cmd = new UpdateDataverseCommand(dataverse, facets.getTarget(), featuredDataverses.getTarget(), session.getUser()); } try { dataverse = commandEngine.submit(cmd); userNotificationService.sendNotification(session.getUser(), dataverse.getCreateDate(), Type.CREATEDV, dataverse.getId()); editMode = null; } catch (CommandException ex) { JH.addMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage()); return null; } return "/dataverse.xhtml?id=" + dataverse.getId() + "&faces-redirect=true"; } public void cancel(ActionEvent e) { // reset values dataverse = dataverseService.find(dataverse.getId()); ownerId = dataverse.getOwner() != null ? dataverse.getOwner().getId() : null; editMode = null; } public boolean isRootDataverse() { return dataverse.getOwner() == null; } public Dataverse getOwner() { return (ownerId != null) ? dataverseService.find(ownerId) : null; } // METHODS for Dataverse Setup public boolean isInheritMetadataBlockFromParent() { return !dataverse.isMetadataBlockRoot(); } public void setInheritMetadataBlockFromParent(boolean inheritMetadataBlockFromParent) { dataverse.setMetadataBlockRoot(!inheritMetadataBlockFromParent); } public void editMetadataBlocks() { if (dataverse.isMetadataBlockRoot()) { dataverse.getMetadataBlocks().addAll(dataverse.getOwner().getMetadataBlocks()); } else { dataverse.getMetadataBlocks(true).clear(); } } public boolean isInheritFacetFromParent() { return !dataverse.isFacetRoot(); } public void setInheritFacetFromParent(boolean inheritFacetFromParent) { dataverse.setFacetRoot(!inheritFacetFromParent); } public void editFacets() { if (dataverse.isFacetRoot()) { dataverse.getDataverseFacets().addAll(dataverse.getOwner().getDataverseFacets()); } else { dataverse.getDataverseFacets(true).clear(); } } public DualListModel<DatasetFieldType> getFacets() { return facets; } public void setFacets(DualListModel<DatasetFieldType> facets) { this.facets = facets; } public DualListModel<Dataverse> getFeaturedDataverses() { return featuredDataverses; } public void setFeaturedDataverses(DualListModel<Dataverse> featuredDataverses) { this.featuredDataverses = featuredDataverses; } public String releaseDataverse() { PublishDataverseCommand cmd = new PublishDataverseCommand(session.getUser(), dataverse); try { commandEngine.submit(cmd); FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "DataverseReleased", "Your dataverse is now public."); FacesContext.getCurrentInstance().addMessage(null, message); return "/dataverse.xhtml?id=" + dataverse.getId() + "&faces-redirect=true"; } catch (CommandException ex) { String msg = "There was a problem publishing your dataverse: " + ex; logger.severe(msg); /** * @todo how do we get this message to show up in the GUI? */ FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "DataverseNotReleased", msg); FacesContext.getCurrentInstance().addMessage(null, message); return "/dataverse.xhtml?id=" + dataverse.getId() + "&faces-redirect=true"; } } public String deleteDataverse() { DeleteDataverseCommand cmd = new DeleteDataverseCommand(session.getUser(), dataverse); try { commandEngine.submit(cmd); FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "DataverseDeleted", "Your dataverse ihas been deleted."); FacesContext.getCurrentInstance().addMessage(null, message); return "/dataverse.xhtml?id=" + dataverse.getOwner().getId() + "&faces-redirect=true"; } catch (CommandException ex) { String msg = "There was a problem deleting your dataverse: " + ex; logger.severe(msg); /** * @todo how do we get this message to show up in the GUI? */ FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "DataverseNotDeleted", msg); FacesContext.getCurrentInstance().addMessage(null, message); return "/dataverse.xhtml?id=" + dataverse.getId() + "&faces-redirect=true"; } } public String getMetadataBlockPreview(MetadataBlock mdb, int numberOfItems) { /// for beta, we will just preview the first n fields StringBuilder mdbPreview = new StringBuilder(); int count = 0; for (DatasetFieldType dsfType : mdb.getDatasetFieldTypes()) { if (!dsfType.isChild()) { if (count != 0) { mdbPreview.append(", "); if (count == numberOfItems) { mdbPreview.append("etc."); break; } } mdbPreview.append(dsfType.getDisplayName()); count++; } } return mdbPreview.toString(); } public Boolean isEmptyDataverse() { return !dataverseService.hasData(dataverse); } public void validateAlias(FacesContext context, UIComponent toValidate, Object value) { String alias = (String) value; boolean aliasFound = false; Dataverse dv = dataverseService.findByAlias(alias); if (editMode == DataversePage.EditMode.CREATE) { if (dv != null) { aliasFound = true; } } else { if (dv != null && !dv.getId().equals(dataverse.getId())) { aliasFound = true; } } if (aliasFound) { ((UIInput) toValidate).setValid(false); FacesMessage message = new FacesMessage("This Alias is already taken."); context.addMessage(toValidate.getClientId(context), message); } } }
package edu.harvard.iq.dataverse; import edu.harvard.iq.dataverse.UserNotification.Type; import edu.harvard.iq.dataverse.authorization.Permission; import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser; import edu.harvard.iq.dataverse.engine.command.Command; import edu.harvard.iq.dataverse.engine.command.exception.CommandException; import edu.harvard.iq.dataverse.engine.command.impl.CreateDataverseCommand; import edu.harvard.iq.dataverse.engine.command.impl.DeleteDataverseCommand; import edu.harvard.iq.dataverse.engine.command.impl.PublishDataverseCommand; import edu.harvard.iq.dataverse.engine.command.impl.UpdateDataverseCommand; import edu.harvard.iq.dataverse.util.JsfHelper; import static edu.harvard.iq.dataverse.util.JsfHelper.JH; import java.util.List; import javax.ejb.EJB; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import java.util.ArrayList; import java.util.logging.Logger; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; import org.primefaces.model.DualListModel; import java.net.InetAddress; import java.net.UnknownHostException; import javax.ejb.EJBException; import javax.faces.model.SelectItem; import org.apache.commons.lang.StringUtils; /** * * @author gdurand */ @ViewScoped @Named("DataversePage") public class DataversePage implements java.io.Serializable { private static final Logger logger = Logger.getLogger(DataversePage.class.getCanonicalName()); public enum EditMode { CREATE, INFO, PERMISSIONS, SETUP, THEME } @EJB DataverseServiceBean dataverseService; @EJB DatasetServiceBean datasetService; @Inject DataverseSession session; @EJB EjbDataverseEngine commandEngine; @EJB SearchServiceBean searchService; @EJB DatasetFieldServiceBean datasetFieldService; @EJB DataverseFacetServiceBean dataverseFacetService; @EJB UserNotificationServiceBean userNotificationService; @EJB FeaturedDataverseServiceBean featuredDataverseService; @EJB DataverseFieldTypeInputLevelServiceBean dataverseFieldTypeInputLevelService; @EJB PermissionServiceBean permissionService; private Dataverse dataverse = new Dataverse(); private EditMode editMode; private Long ownerId; private DualListModel<DatasetFieldType> facets; private DualListModel<Dataverse> featuredDataverses; // private TreeNode treeWidgetRootNode = new DefaultTreeNode("Root", null); public Dataverse getDataverse() { return dataverse; } public void setDataverse(Dataverse dataverse) { this.dataverse = dataverse; } public EditMode getEditMode() { return editMode; } public void setEditMode(EditMode editMode) { this.editMode = editMode; } public Long getOwnerId() { return ownerId; } public void setOwnerId(Long ownerId) { this.ownerId = ownerId; } // public TreeNode getTreeWidgetRootNode() { // return treeWidgetRootNode; // public void setTreeWidgetRootNode(TreeNode treeWidgetRootNode) { // this.treeWidgetRootNode = treeWidgetRootNode; public String init() { if (dataverse.getAlias() != null || dataverse.getId() != null || ownerId == null ){// view mode for a dataverse if (dataverse.getAlias() != null) { dataverse = dataverseService.findByAlias(dataverse.getAlias()); } else if (dataverse.getId() != null) { dataverse = dataverseService.find(dataverse.getId()); } else { try { dataverse = dataverseService.findRootDataverse(); } catch (EJBException e) { // @todo handle case with no root dataverse (a fresh installation) with message about using API to create the root dataverse = null; } } if (dataverse == null) { return "/404.xhtml"; } if (!dataverse.isReleased() && !permissionService.on(dataverse).has(Permission.ViewUnpublishedDataverse)) { return "/loginpage.xhtml" + DataverseHeaderFragment.getRedirectPage(); } ownerId = dataverse.getOwner() != null ? dataverse.getOwner().getId() : null; } else { // ownerId != null; create mode for a new child dataverse editMode = EditMode.INFO; dataverse.setOwner(dataverseService.find(ownerId)); if (dataverse.getOwner() == null) { return "/404.xhtml"; } else if (!permissionService.on(dataverse.getOwner()).has(Permission.AddDataverse)) { return "/loginpage.xhtml" + DataverseHeaderFragment.getRedirectPage(); } // set defaults - contact e-mail and affiliation from user dataverse.getDataverseContacts().add(new DataverseContact(dataverse, session.getUser().getDisplayInfo().getEmailAddress())); dataverse.setAffiliation(session.getUser().getDisplayInfo().getAffiliation()); // FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Create New Dataverse", " - Create a new dataverse that will be a child dataverse of the parent you clicked from. Asterisks indicate required fields.")); } List<DatasetFieldType> facetsSource = new ArrayList<>(); List<DatasetFieldType> facetsTarget = new ArrayList<>(); facetsSource.addAll(datasetFieldService.findAllFacetableFieldTypes()); List<DataverseFacet> facetsList = dataverseFacetService.findByDataverseId(dataverse.getFacetRootId()); for (DataverseFacet dvFacet : facetsList) { DatasetFieldType dsfType = dvFacet.getDatasetFieldType(); facetsTarget.add(dsfType); facetsSource.remove(dsfType); } facets = new DualListModel<>(facetsSource, facetsTarget); List<Dataverse> featuredSource = new ArrayList<>(); List<Dataverse> featuredTarget = new ArrayList<>(); featuredSource.addAll(dataverseService.findAllPublishedByOwnerId(dataverse.getId())); List<DataverseFeaturedDataverse> featuredList = featuredDataverseService.findByDataverseId(dataverse.getId()); for (DataverseFeaturedDataverse dfd : featuredList) { Dataverse fd = dfd.getFeaturedDataverse(); featuredTarget.add(fd); featuredSource.remove(fd); } featuredDataverses = new DualListModel<>(featuredSource, featuredTarget); refreshAllMetadataBlocks(); return null; } public List<Dataverse> getCarouselFeaturedDataverses() { List<Dataverse> retList = new ArrayList(); List<DataverseFeaturedDataverse> featuredList = featuredDataverseService.findByDataverseId(dataverse.getId()); for (DataverseFeaturedDataverse dfd : featuredList) { Dataverse fd = dfd.getFeaturedDataverse(); retList.add(fd); } return retList; } public List getContents() { List contentsList = dataverseService.findByOwnerId(dataverse.getId()); contentsList.addAll(datasetService.findByOwnerId(dataverse.getId())); return contentsList; } public void edit(EditMode editMode) { this.editMode = editMode; if (editMode == EditMode.INFO) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Edit Dataverse", " - Edit your dataverse and click Save. Asterisks indicate required fields.")); } else if (editMode == EditMode.SETUP) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Edit Dataverse Setup", " - Edit the Metadata Blocks and Facets you want to associate with your dataverse. Note: facets will appear in the order shown on the list.")); } } public void refresh(){ } private boolean openMetadataBlock; public boolean isOpenMetadataBlock() { return openMetadataBlock; } public void setOpenMetadataBlock(boolean openMetadataBlock) { this.openMetadataBlock = openMetadataBlock; } public void showDatasetFieldTypes(Long mdbId) { for (MetadataBlock mdb : allMetadataBlocks){ if(mdb.getId().equals(mdbId)){ mdb.setShowDatasetFieldTypes(true); openMetadataBlock = true; } } } public void hideDatasetFieldTypes(Long mdbId) { for (MetadataBlock mdb : allMetadataBlocks){ if(mdb.getId().equals(mdbId)){ mdb.setShowDatasetFieldTypes(false); openMetadataBlock = false; } } } public void updateInclude(Long mdbId, long dsftId) { List<DatasetFieldType> childDSFT = new ArrayList(); for (MetadataBlock mdb : allMetadataBlocks) { if (mdb.getId().equals(mdbId)) { for (DatasetFieldType dsftTest : mdb.getDatasetFieldTypes()) { if (dsftTest.getId().equals(dsftId)) { dsftTest.setOptionSelectItems(resetSelectItems(dsftTest)); if ((dsftTest.isHasParent() && !dsftTest.getParentDatasetFieldType().isInclude()) || (!dsftTest.isHasParent() && !dsftTest.isInclude())){ dsftTest.setRequiredDV(false); } if (dsftTest.isHasChildren() && !dsftTest.isInclude()) { childDSFT.addAll(dsftTest.getChildDatasetFieldTypes()); } } } } } if (!childDSFT.isEmpty()) { for (DatasetFieldType dsftUpdate : childDSFT) { for (MetadataBlock mdb : allMetadataBlocks) { if (mdb.getId().equals(mdbId)) { for (DatasetFieldType dsftTest : mdb.getDatasetFieldTypes()) { if (dsftTest.getId().equals(dsftUpdate.getId())) { dsftTest.setOptionSelectItems(resetSelectItems(dsftTest)); } } } } } } } public List<SelectItem> resetSelectItems(DatasetFieldType typeIn){ List retList = new ArrayList(); if ((typeIn.isHasParent() && typeIn.getParentDatasetFieldType().isInclude()) || (!typeIn.isHasParent() && typeIn.isInclude())){ SelectItem requiredItem = new SelectItem(); requiredItem.setLabel("Required"); requiredItem.setValue(true); retList.add(requiredItem); SelectItem optional = new SelectItem(); optional.setLabel("Optional"); optional.setValue(false); retList.add(optional); } else { SelectItem hidden = new SelectItem(); hidden.setLabel("Hidden"); hidden.setValue(false); hidden.setDisabled(true); retList.add(hidden); } return retList; } public void updateRequiredDatasetFieldTypes(Long mdbId, Long dsftId, boolean inVal) { for (MetadataBlock mdb : allMetadataBlocks){ if(mdb.getId().equals(mdbId)){ for (DatasetFieldType dsft : mdb.getDatasetFieldTypes()){ if (dsft.getId().equals(dsftId)){ dsft.setRequiredDV(!inVal); } } } } } public void updateOptionsRadio(Long mdbId, Long dsftId) { for (MetadataBlock mdb : allMetadataBlocks){ if(mdb.getId().equals(mdbId)){ for (DatasetFieldType dsft : mdb.getDatasetFieldTypes()){ if (dsft.getId().equals(dsftId)){ dsft.setOptionSelectItems(resetSelectItems(dsft)); } } } } } public String save() { List<DataverseFieldTypeInputLevel> listDFTIL = new ArrayList(); List<MetadataBlock> selectedBlocks = new ArrayList(); if (dataverse.isMetadataBlockRoot()) { dataverse.getMetadataBlocks().clear(); } for (MetadataBlock mdb : this.allMetadataBlocks) { if (dataverse.isMetadataBlockRoot() && (mdb.isSelected() || mdb.isRequired())) { selectedBlocks.add(mdb); for (DatasetFieldType dsft : mdb.getDatasetFieldTypes()) { if (dsft.isRequiredDV() && !dsft.isRequired() && ((!dsft.isHasParent() && dsft.isInclude()) || (dsft.isHasParent() && dsft.getParentDatasetFieldType().isInclude()))) { DataverseFieldTypeInputLevel dftil = new DataverseFieldTypeInputLevel(); dftil.setDatasetFieldType(dsft); dftil.setDataverse(dataverse); dftil.setRequired(true); dftil.setInclude(true); listDFTIL.add(dftil); } if ( (!dsft.isHasParent() && !dsft.isInclude()) || (dsft.isHasParent() && !dsft.getParentDatasetFieldType().isInclude())) { DataverseFieldTypeInputLevel dftil = new DataverseFieldTypeInputLevel(); dftil.setDatasetFieldType(dsft); dftil.setDataverse(dataverse); dftil.setRequired(false); dftil.setInclude(false); listDFTIL.add(dftil); } } } } if (!selectedBlocks.isEmpty()) { dataverse.setMetadataBlocks(selectedBlocks); } if(!dataverse.isFacetRoot()){ facets.getTarget().clear(); } Command<Dataverse> cmd = null; //TODO change to Create - for now the page is expecting INFO instead. Boolean create; if (dataverse.getId() == null) { dataverse.setOwner(ownerId != null ? dataverseService.find(ownerId) : null); create = Boolean.TRUE; cmd = new CreateDataverseCommand(dataverse, session.getUser(), facets.getTarget(), listDFTIL); } else { create=Boolean.FALSE; cmd = new UpdateDataverseCommand(dataverse, facets.getTarget(), featuredDataverses.getTarget(), session.getUser(), listDFTIL); } try { dataverse = commandEngine.submit(cmd); if (session.getUser() instanceof AuthenticatedUser) { userNotificationService.sendNotification((AuthenticatedUser) session.getUser(), dataverse.getCreateDate(), Type.CREATEDV, dataverse.getId()); } editMode = null; } catch (CommandException ex) { JH.addMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage()); return null; } String msg = (create)? "You have successfully created your dataverse!": "You have successfully updated your dataverse!"; JsfHelper.addFlashMessage(msg); return "/dataverse.xhtml?alias=" + dataverse.getAlias() + "&faces-redirect=true"; } public void cancel(ActionEvent e) { // reset values dataverse = dataverseService.find(dataverse.getId()); ownerId = dataverse.getOwner() != null ? dataverse.getOwner().getId() : null; editMode = null; } public boolean isRootDataverse() { return dataverse.getOwner() == null; } public Dataverse getOwner() { return (ownerId != null) ? dataverseService.find(ownerId) : null; } // METHODS for Dataverse Setup public boolean isInheritMetadataBlockFromParent() { return !dataverse.isMetadataBlockRoot(); } public void setInheritMetadataBlockFromParent(boolean inheritMetadataBlockFromParent) { dataverse.setMetadataBlockRoot(!inheritMetadataBlockFromParent); } public void editMetadataBlocks() { refreshAllMetadataBlocks(); } public boolean isInheritFacetFromParent() { return !dataverse.isFacetRoot(); } public void setInheritFacetFromParent(boolean inheritFacetFromParent) { dataverse.setFacetRoot(!inheritFacetFromParent); } public void editFacets() { List<DatasetFieldType> facetsSource = new ArrayList<>(); List<DatasetFieldType> facetsTarget = new ArrayList<>(); facetsSource.addAll(datasetFieldService.findAllFacetableFieldTypes()); List<DataverseFacet> facetsList = dataverseFacetService.findByDataverseId(dataverse.getFacetRootId()); for (DataverseFacet dvFacet : facetsList) { DatasetFieldType dsfType = dvFacet.getDatasetFieldType(); facetsTarget.add(dsfType); facetsSource.remove(dsfType); } facets = new DualListModel<>(facetsSource, facetsTarget); } public DualListModel<DatasetFieldType> getFacets() { return facets; } public void setFacets(DualListModel<DatasetFieldType> facets) { this.facets = facets; } public DualListModel<Dataverse> getFeaturedDataverses() { return featuredDataverses; } public void setFeaturedDataverses(DualListModel<Dataverse> featuredDataverses) { this.featuredDataverses = featuredDataverses; } public String releaseDataverse() { PublishDataverseCommand cmd = new PublishDataverseCommand(session.getUser(), dataverse); try { commandEngine.submit(cmd); FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "DataverseReleased", "Your dataverse is now public."); FacesContext.getCurrentInstance().addMessage(null, message); return "/dataverse.xhtml?alias=" + dataverse.getAlias() + "&faces-redirect=true"; } catch (CommandException ex) { String msg = "There was a problem publishing your dataverse: " + ex; logger.severe(msg); /** * @todo how do we get this message to show up in the GUI? */ FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "DataverseNotReleased", msg); FacesContext.getCurrentInstance().addMessage(null, message); return "/dataverse.xhtml?alias=" + dataverse.getAlias() + "&faces-redirect=true"; } } public String deleteDataverse() { DeleteDataverseCommand cmd = new DeleteDataverseCommand(session.getUser(), dataverse); try { commandEngine.submit(cmd); FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "DataverseDeleted", "Your dataverse ihas been deleted."); FacesContext.getCurrentInstance().addMessage(null, message); return "/dataverse.xhtml?alias=" + dataverse.getOwner().getAlias() + "&faces-redirect=true"; } catch (CommandException ex) { String msg = "There was a problem deleting your dataverse: " + ex; logger.severe(msg); /** * @todo how do we get this message to show up in the GUI? */ FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "DataverseNotDeleted", msg); FacesContext.getCurrentInstance().addMessage(null, message); return "/dataverse.xhtml?alias=" + dataverse.getAlias() + "&faces-redirect=true"; } } public String getMetadataBlockPreview(MetadataBlock mdb, int numberOfItems) { /// for beta, we will just preview the first n fields StringBuilder mdbPreview = new StringBuilder(); int count = 0; for (DatasetFieldType dsfType : mdb.getDatasetFieldTypes()) { if (!dsfType.isChild()) { if (count != 0) { mdbPreview.append(", "); if (count == numberOfItems) { mdbPreview.append("etc."); break; } } mdbPreview.append(dsfType.getDisplayName()); count++; } } return mdbPreview.toString(); } public Boolean isEmptyDataverse() { return !dataverseService.hasData(dataverse); } private List<MetadataBlock> allMetadataBlocks; public List<MetadataBlock> getAllMetadataBlocks() { return this.allMetadataBlocks; } public void setAllMetadataBlocks(List<MetadataBlock> inBlocks) { this.allMetadataBlocks = inBlocks; } private void refreshAllMetadataBlocks() { Long dataverseIdForInputLevel = dataverse.getId(); List<MetadataBlock> retList = new ArrayList(); for (MetadataBlock mdb : dataverseService.findAllMetadataBlocks()) { mdb.setSelected(false); mdb.setShowDatasetFieldTypes(false); if (!dataverse.isMetadataBlockRoot() && dataverse.getOwner() != null) { dataverseIdForInputLevel = dataverse.getMetadataRootId(); for (MetadataBlock mdbTest : dataverse.getOwner().getMetadataBlocks()) { if (mdb.equals(mdbTest)) { mdb.setSelected(true); } } } else { for (MetadataBlock mdbTest : dataverse.getMetadataBlocks(true)) { if (mdb.equals(mdbTest)) { mdb.setSelected(true); } } } for (DatasetFieldType dsft : mdb.getDatasetFieldTypes()) { DataverseFieldTypeInputLevel dsfIl = dataverseFieldTypeInputLevelService.findByDataverseIdDatasetFieldTypeId(dataverseIdForInputLevel, dsft.getId()); if (dsfIl != null) { dsft.setRequiredDV(dsfIl.isRequired()); dsft.setInclude(dsfIl.isInclude()); } else { dsft.setRequiredDV(dsft.isRequired()); dsft.setInclude(true); } dsft.setOptionSelectItems(resetSelectItems(dsft)); } retList.add(mdb); } setAllMetadataBlocks(retList); } public void validateAlias(FacesContext context, UIComponent toValidate, Object value) { if (!StringUtils.isEmpty((String)value)) { String alias = (String) value; boolean aliasFound = false; Dataverse dv = dataverseService.findByAlias(alias); if (editMode == DataversePage.EditMode.CREATE) { if (dv != null) { aliasFound = true; } } else { if (dv != null && !dv.getId().equals(dataverse.getId())) { aliasFound = true; } } if (aliasFound) { ((UIInput) toValidate).setValid(false); FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "alias", "This Alias is already taken."); context.addMessage(toValidate.getClientId(context), message); } } } }
package edu.jhu.pacaya.gm.feat; import java.io.Serializable; import edu.jhu.pacaya.gm.data.UFgExample; import edu.jhu.pacaya.gm.model.FactorGraph; import edu.jhu.pacaya.util.FeatureNames; import edu.jhu.prim.map.IntDoubleEntry; /** Cache of feature vectors for a factor graph. */ public class ObsFeatureCache implements ObsFeatureExtractor, Serializable { private static final long serialVersionUID = 1L; /** Indexed by factor ID. */ private FeatureVector[] feats; /** The feature extractor to cache. */ private ObsFeatureExtractor featExtractor; public ObsFeatureCache(ObsFeatureExtractor featExtractor) { this.featExtractor = featExtractor; } @Override public void init(UFgExample ex, FactorTemplateList fts) { FactorGraph fg = ex.getFactorGraph(); this.featExtractor.init(ex, fts); init(fg); } @Deprecated public void init(FactorGraph fg) { this.feats = new FeatureVector[fg.getNumFactors()]; } /** Gets the feature vector for the specified factor and config. */ public FeatureVector calcObsFeatureVector(ObsFeExpFamFactor factor) { int factorId = factor.getId(); if (feats[factorId] == null) { feats[factorId] = featExtractor.calcObsFeatureVector(factor); } return feats[factorId]; } public String toString(FeatureNames alphabet) { StringBuilder sb = new StringBuilder(); for (int a = 0; a < feats.length; a++) { FeatureVector fv = feats[a]; if (fv != null) { int i=0; for (IntDoubleEntry entry : fv) { if (i++ > 0) { sb.append(", "); } sb.append(alphabet.lookupObject(entry.index())); sb.append("="); sb.append(entry.get()); } } else { sb.append("null"); } sb.append("\n"); } return sb.toString(); } }
package edu.jhu.util.semiring; import edu.jhu.prim.util.math.FastMath; public class LogPosNegAlgebra implements Semiring, Algebra { // We choose the least significant digit of the mantissa as our sign bit. // This bit is chosen for two reasons: (1) the various bit representations // of NaN, +inf, and -inf seem to use only the most significant bits of the // mantissa or none of the mantissa at all and (2) if there's a bug in our code // in which we forget to convert from this semiring back to the reals, it should // only result in a sign error which will (hopefully) be easier to find. private static final int SIGN_BIT = 1; private static final long SIGN_MASK = 0x1 << (SIGN_BIT-1); private static final long FLOAT_MASK = ~SIGN_MASK; private static final long POSITIVE = 0; private static final long NEGATIVE = 1; /** Converts a compacted number to its real value. */ @Override public double toReal(double x) { double unsignedReal = FastMath.exp(natlog(x)); return (sign(x) == POSITIVE) ? unsignedReal : -unsignedReal; } /** Converts a real value to its compacted representation. */ @Override public double fromReal(double x) { long sign = POSITIVE; if (x < 0) { sign = NEGATIVE; x = -x; } return compact(sign, FastMath.log(x)); } @Override public double toLogProb(double nonReal) { if (sign(nonReal) == NEGATIVE) { throw new IllegalStateException("Unable to take the log of a negative number."); } return natlog(nonReal); } @Override public double fromLogProb(double logProb) { return compact(POSITIVE, natlog(logProb)); } /** Gets the sign bit of the compacted number. */ public static final long sign(double xd) { return SIGN_MASK & Double.doubleToRawLongBits(xd); } /** Gets the natural log portion of the compacted number. */ public static final double natlog(double xd) { return Double.longBitsToDouble(FLOAT_MASK & Double.doubleToRawLongBits(xd)); } /** Gets the compacted version from the sign and natural log. */ public static final double compact(long sign, double natlog) { return Double.longBitsToDouble(sign | (FLOAT_MASK & Double.doubleToRawLongBits(natlog))); } /** Negates the compacted number. */ public double negate(double xd) { return Double.longBitsToDouble(SIGN_MASK ^ Double.doubleToRawLongBits(xd)); } @Override public double abs(double xd) { return compact(POSITIVE, natlog(xd)); } @Override public double plus(double x, double y) { long sx = sign(x); long sy = sign(y); double lx = natlog(x); double ly = natlog(y); if (sx == POSITIVE && sy == POSITIVE) { return compact(POSITIVE, FastMath.logAdd(lx, ly)); } else if (sx == POSITIVE && sy == NEGATIVE) { double diff = FastMath.logSubtract(Math.max(lx, ly), Math.min(lx, ly)); long sign = (lx >= ly) ? POSITIVE : NEGATIVE; return compact(sign, diff); } else if (sx == NEGATIVE && sy == POSITIVE) { double diff = FastMath.logSubtract(Math.max(lx, ly), Math.min(lx, ly)); long sign = (lx >= ly) ? NEGATIVE : POSITIVE; return compact(sign, diff); } else { return compact(NEGATIVE, FastMath.logAdd(lx, ly)); } } @Override public double times(double x, double y) { long sign = (sign(x) == sign(y)) ? POSITIVE : NEGATIVE; return compact(sign, natlog(x) + natlog(y)); } @Override public double minus(double x, double y) { return plus(x, negate(y)); } @Override public double divide(double x, double y) { long sign = (sign(x) == sign(y)) ? POSITIVE : NEGATIVE; return compact(sign, natlog(x) - natlog(y)); } public double exp(double x) { return compact(POSITIVE, toReal(x)); } public double log(double x) { if (sign(x) == NEGATIVE) { throw new IllegalStateException("Unable to take the log of a negative number."); } return fromReal(natlog(x)); } @Override public double zero() { return Double.NEGATIVE_INFINITY; } @Override public double one() { return 0; } @Override public double posInf() { return fromReal(Double.POSITIVE_INFINITY); } @Override public double negInf() { return fromReal(Double.NEGATIVE_INFINITY); } @Override public double minValue() { return fromReal(Double.NEGATIVE_INFINITY); } @Override public boolean gt(double x, double y) { long sx = sign(x); long sy = sign(y); double lx = natlog(x); double ly = natlog(y); if (sx == POSITIVE && sy == POSITIVE) { return lx > ly; } else if (sx == POSITIVE && sy == NEGATIVE) { return true; } else if (sx == NEGATIVE && sy == POSITIVE) { return false; } else { return lx < ly; } } @Override public boolean lt(double x, double y) { return gt(y, x); } @Override public boolean gte(double x, double y) { long sx = sign(x); long sy = sign(y); double lx = natlog(x); double ly = natlog(y); if (sx == POSITIVE && sy == POSITIVE) { return lx >= ly; } else if (sx == POSITIVE && sy == NEGATIVE) { return true; } else if (sx == NEGATIVE && sy == POSITIVE) { return false; } else { return lx <= ly; } } @Override public boolean lte(double x, double y) { return gte(y, x); } @Override public boolean eq(double x, double y, double delta) { throw new RuntimeException("not yet implemented"); } @Override public boolean isNaN(double x) { // TODO: This requires testing. return Double.isNaN(natlog(x)); } // Two Algebras / Semirings are equal if they are of the same class. public boolean equals(Object other) { if (this == other) { return true; } if (other == null) { return false; } if (this.getClass() == other.getClass()) { return true; } return false; } }
package fi.csc.chipster.rest; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class CORSServletFilter implements Filter { @SuppressWarnings("unused") private static final Logger logger = LogManager.getLogger(); @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse)resp; //response.addHeader("Access-Control-Allow-Origin", "*"); response.addHeader("Access-Control-Allow-Origin", request.getHeader("origin")); response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); response.addHeader("Access-Control-Allow-Headers", "authorization, content-type, range"); // request response.addHeader("Access-Control-Expose-Headers", "location, Accept-Ranges, Content-Encoding, Content-Length, Accept-Ranges, Content-Range"); // response response.addHeader("Access-Control-Allow-Credentials", "true"); response.addHeader("Access-Control-Max-Age", "1728000"); // in seconds, 20 days //response.addHeader("Access-Control-Max-Age", "1"); // makes debugging easier chain.doFilter(request, response); } @Override public void destroy() { } }
package innovimax.mixthem.io; import innovimax.mixthem.interfaces.IInputChar; import java.io.File; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; /** * <p>Reads characters from a character-input file.</p> * <p>This is the default implementation of IInputChar.</p> * @see IInputChar * @author Innovimax * @version 1.0 */ public class DefaultCharReader implements IInputChar { private final BufferedReader reader; private boolean jump; /** * Creates a character reader. * @param file The input file to be read * @throws IOException - If an I/O error occurs */ public DefaultCharReader(File input, boolean first) throws IOException { this.reader = new BufferedReader(new FileReader(input)); this.jump = !first; } @Override public boolean hasCharacter() throws IOException { return this.reader.ready(); } @Override public int nextCharacter(ReadType type, boolean force) throws IOException { int c = -1; if (hasCharacter()) { switch (type) { case _ALT_SIMPLE: if (!this.jump || force) { c = this.reader.read(); } else { this.reader.read(); } this.jump = !this.jump; break; } } return c; } @Override public int nextCharacters(char[] buffer, int len) throws IOException { return this.reader.read(buffer, 0, len); } @Override public void close() throws IOException { this.reader.close(); } }
package io.github.data4all.model.data; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import android.os.Parcel; import android.os.Parcelable; /** * Relation represents an OSM relation element which essentially is a collection * of other OSM elements. A relation consists of one or more tags and also an * ordered list of one or more nodes, ways and/or relations as members which is * used to define logical or geographic relationships between other elements. * * @author simon, fkirchge * */ public class Relation extends OsmElement { /** * List of all member of the relation. */ private ArrayList<RelationMember> members = null; /** * Default constructor * * @param osmId * @param osmVersion */ public Relation(final long osmId, final long osmVersion) { super(osmId, osmVersion); members = new ArrayList<RelationMember>(); } /** * Adds a new member to the relation. * * @param member */ public void addMember(final RelationMember member) { members.add(member); } /** * Returns all member of the relation. * * @return */ public List<RelationMember> getMembers() { return members; } /** * Returns the relation member of the osm element. * * @param e * @return relation member */ public RelationMember getMember(OsmElement e) { for (int i = 0; i < members.size(); i++) { RelationMember member = members.get(i); if (member.getElement() == e) { return member; } } return null; } /** * Returns the relation member which matches with the type and the id. * * @param type * @param id * @return relation member */ public RelationMember getMember(String type, long id) { for (int i = 0; i < members.size(); i++) { RelationMember member = members.get(i); if (member.getRef() == id && member.getType().equals(type)) { return member; } } return null; } /** * Returns the position of a relation member in the list of members. * * @param e * @return position */ public int getPosition(RelationMember e) { return members.indexOf(e); } /** * Returns a iterator for the relation member. * * @return list of members allowing {@link Iterator#remove()}. */ public Iterator<RelationMember> getRemovableMembers() { return members.iterator(); } /** * Check if the given member belongs to the relation. * * @param member * @return */ public boolean hasMember(final RelationMember member) { return members.contains(member); } /** * Removes a member from the relation. * * @param member */ public void removeMember(final RelationMember member) { while (members.remove(member)) { ; } } /** * Append a new member at the begin or at the end of the relation member * list. * * @param refMember * @param newMember */ public void appendMember(final RelationMember refMember, final RelationMember newMember) { if (members.get(0) == refMember) { members.add(0, newMember); } else if (members.get(members.size() - 1) == refMember) { members.add(newMember); } } /** * Inserts a new relation member after the reference member. * * @param memberBefore * @param newMember */ public void addMemberAfter(final RelationMember memberBefore, final RelationMember newMember) { members.add(members.indexOf(memberBefore) + 1, newMember); } /** * Adds a new relation member to a given position. * * @param pos * @param newMember */ public void addMember(int pos, final RelationMember newMember) { if (pos < 0 || pos > members.size()) { pos = members.size(); // append } members.add(pos, newMember); } /** * Adds multiple elements to the relation in the order in which they appear * in the list. They can be either prepended or appended to the existing * nodes. * * @param newMembers * a list of new members * @param atBeginning * if true, nodes are prepended, otherwise, they are appended */ public void addMembers(List<RelationMember> newMembers, boolean atBeginning) { if (atBeginning) { members.addAll(0, newMembers); } else { members.addAll(newMembers); } } /** * Returns a list of member with the current role. * * @param role * the name of the role * @return list of relation member */ public ArrayList<RelationMember> getMembersWithRole(String role) { ArrayList<RelationMember> rl = new ArrayList<RelationMember>(); for (RelationMember rm : members) { // Log.d(getClass().getSimpleName(), "getMembersWithRole " + // rm.getRole()); if (role.equals(rm.getRole())) { rl.add(rm); } } return rl; } /** * Replace an existing member in a relation with a different member. * * @param existing * The existing member to be replaced. * @param newMember * The new member. */ public void replaceMember(RelationMember existing, RelationMember newMember) { int idx; while ((idx = members.indexOf(existing)) != -1) { members.set(idx, newMember); } } /** * Return a list of the downloaded elements. Return a list of relation * member object which have an osm element reference (getElement() != null). * * @return list of osm elements */ public ArrayList<OsmElement> getMemberElements() { ArrayList<OsmElement> result = new ArrayList<OsmElement>(); for (RelationMember rm : getMembers()) { if (rm.getElement() != null) result.add(rm.getElement()); } return result; } /** * Methods to write and restore a Parcel */ public static final Parcelable.Creator<Relation> CREATOR = new Parcelable.Creator<Relation>() { public Relation createFromParcel(Parcel in) { return new Relation(in); } public Relation[] newArray(int size) { return new Relation[size]; } }; public int describeContents() { return 0; } /** * Writes the lat and the lon to the given parcel */ public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeTypedList(members); } /** * Constructor to create a node from a parcel * @param in */ private Relation(Parcel in) { super(in); members = new ArrayList<RelationMember>(); in.readTypedList(members, RelationMember.CREATOR); } }
package logbook.internal.gui; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Arrays; import java.util.Comparator; import java.util.stream.Collectors; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.chart.LineChart; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.control.CheckBox; import javafx.scene.control.ChoiceBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Spinner; import javafx.scene.control.SpinnerValueFactory; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.image.ImageView; import logbook.bean.AppConfig; import logbook.bean.DeckPortCollection; import logbook.bean.Ship; import logbook.bean.ShipCollection; import logbook.bean.ShipMst; import logbook.internal.ExpTable; import logbook.internal.Rank; import logbook.internal.SeaArea; import logbook.internal.Ships; public class CalcExpController extends WindowController { @FXML private ComboBox<ShipWrapper> shipList; @FXML private Spinner<Integer> nowLv; @FXML private TextField nowExp; @FXML private Spinner<Integer> goalLv; @FXML private TextField goalExp; @FXML private ChoiceBox<SeaArea> sea; @FXML private ChoiceBox<Rank> rank; @FXML private CheckBox flagShip; @FXML private CheckBox mvp; @FXML private TextField getExp; @FXML private TextField needExp; @FXML private TextField battleCount; @FXML private LineChart<Number, Number> expChart; @FXML private NumberAxis xAxis; @FXML private NumberAxis yAxis; @FXML private TableView<ShortageShipItem> shortageShip; @FXML private TableColumn<ShortageShipItem, Integer> id; @FXML private TableColumn<ShortageShipItem, Ship> ship; @FXML private TableColumn<ShortageShipItem, Integer> lv; @FXML private TableColumn<ShortageShipItem, Integer> afterLv; private ObservableList<ShipWrapper> ships = FXCollections.observableArrayList(); private ObservableList<ShortageShipItem> item = FXCollections.observableArrayList(); private int nowExpValue; private int goalExpValue; @FXML void initialize() { // Spinner this.nowLv.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(1, 155, 1, 1)); this.goalLv.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(1, 155, 100, 1)); this.shipList.setItems(this.ships); this.shipList(); this.sea.setItems(FXCollections.observableArrayList( Arrays.stream(SeaArea.values()) .filter(s -> s.getSeaExp() > 0) .collect(Collectors.toList()))); this.sea.getSelectionModel().select(AppConfig.get().getBattleSeaArea()); this.rank.setItems(FXCollections.observableArrayList(Rank.values())); this.rank.getSelectionModel().select(AppConfig.get().getResultRank()); this.id.setCellValueFactory(new PropertyValueFactory<>("id")); this.ship.setCellValueFactory(new PropertyValueFactory<>("ship")); this.ship.setCellFactory(p -> new ShipImageTableCell()); this.lv.setCellValueFactory(new PropertyValueFactory<>("lv")); this.afterLv.setCellValueFactory(new PropertyValueFactory<>("afterLv")); this.shortageShip.setItems(this.item); this.shortageShip(); this.shipList.getSelectionModel() .selectedItemProperty() .addListener((ChangeListener<ShipWrapper>) this::changeShip); this.nowLv.getValueFactory() .valueProperty() .addListener((ChangeListener<Integer>) this::changeNowLv); this.goalLv.getValueFactory() .valueProperty() .addListener((ChangeListener<Integer>) this::changeGoalLv); this.sea.getSelectionModel() .selectedItemProperty() .addListener((ChangeListener<SeaArea>) (ov, o, n) -> this.update()); this.rank.getSelectionModel() .selectedItemProperty() .addListener((ChangeListener<Rank>) (ov, o, n) -> this.update()); this.shortageShip.getSelectionModel() .selectedItemProperty() .addListener((ChangeListener<ShortageShipItem>) this::changeShip); Integer flagShipId = DeckPortCollection.get() .getDeckPortMap() .get(1) .getShip() .get(0); ShipWrapper flagShip = this.ships.stream() .filter(w -> w.getShip().getId().equals(flagShipId)) .findAny() .get(); // select this.shipList.getSelectionModel().select(flagShip); } /** * * * @param event ActionEvent */ @FXML void reloadAction(ActionEvent event) { Integer selectId = this.shipList.getValue().getShip().getId(); this.shipList(); ShipWrapper select = this.ships.stream() .filter(w -> w.getShip().getId().equals(selectId)) .findAny() .orElse(this.ships.get(0)); this.shipList.getSelectionModel().select(select); this.update(); } /** * * * @param event ActionEvent */ @FXML void update(ActionEvent event) { this.update(); } private void changeShip(Ship ship) { this.nowLv.getValueFactory().setValue(ship.getLv()); this.nowExpValue = ship.getExp().get(0); this.nowExp.setText(Integer.toString(this.nowExpValue)); int afterLv = Ships.shipMst(ship) .map(ShipMst::getAfterlv) .orElse(0); int goal = Math.min(Math.max(afterLv, ship.getLv() + 1), ExpTable.maxLv()); this.goalExpValue = ExpTable.get().get(goal); this.goalLv.getValueFactory().setValue(goal); this.goalExp.setText(String.valueOf(this.goalExpValue)); this.update(); } /** * From Combo */ private void changeShip(ObservableValue<? extends ShipWrapper> observable, ShipWrapper oldValue, ShipWrapper value) { if (value != null) { Ship ship = value.getShip(); this.changeShip(ship); // Table for (ShortageShipItem ss : this.item.filtered(ss -> ss.shipProperty().get().equals(ship))) { ShortageShipItem selected = this.shortageShip.getSelectionModel().getSelectedItem(); if (selected != null && selected.equals(ss)) { continue; } this.shortageShip.getSelectionModel().select(ss); this.shortageShip.scrollTo(ss); } } } /** * From Table */ private void changeShip(ObservableValue<? extends ShortageShipItem> observable, ShortageShipItem oldValue, ShortageShipItem value) { if (value != null) { Ship ship = value.shipProperty().get(); this.changeShip(ship); // Combo this.ships.filtered(sw -> sw.getShip().equals(ship)).forEach(this.shipList.getSelectionModel()::select); } } private void changeNowLv(ObservableValue<? extends Integer> observable, Integer oldValue, Integer value) { if (value != null) { this.nowExpValue = ExpTable.get().get(value); this.nowExp.setText(String.valueOf(this.nowExpValue)); this.update(); } } private void changeGoalLv(ObservableValue<? extends Integer> observable, Integer oldValue, Integer value) { if (value != null) { this.goalExpValue = ExpTable.get().get(value); this.goalExp.setText(String.valueOf(this.goalExpValue)); this.update(); } } private void update() { int base = this.sea.getValue().getSeaExp(); double eval = this.rank.getValue().getRatio(); int getExpValue = getExp(base, eval, this.flagShip.isSelected(), this.mvp.isSelected()); int battleCountValue = getCount(this.goalExpValue - this.nowExpValue, getExpValue); this.getExp.setText(String.valueOf(getExpValue)); this.needExp.setText(String.valueOf(this.goalExpValue - this.nowExpValue)); this.battleCount.setText(String.valueOf(battleCountValue)); this.chart(); AppConfig.get().setBattleSeaArea(this.sea.getValue()); AppConfig.get().setResultRank(this.rank.getValue()); } private void shipList() { this.ships.clear(); this.ships.addAll(ShipCollection.get() .getShipMap() .values() .stream() .sorted(Comparator.comparing(Ship::getLv).reversed()) .map(ShipWrapper::new) .collect(Collectors.toList())); } private void shortageShip() { this.item.addAll(ShipCollection.get() .getShipMap() .values() .stream() .map(ShortageShipItem::toShipItem) .filter(item -> item.getAfterLv() > item.getLv()) .sorted(Comparator.comparing(ShortageShipItem::getLv).reversed()) .collect(Collectors.toList())); } private void chart() { int nowExpValue = this.nowExpValue; int nowLvValue = this.nowLv.getValue(); int goalLvValue = this.goalLv.getValue(); XYChart.Series<Number, Number> total = new XYChart.Series<>(); XYChart.Series<Number, Number> goal = new XYChart.Series<>(); XYChart.Series<Number, Number> now = new XYChart.Series<>(); if (goalLvValue <= 100) { total.getData().addAll(ExpTable.get().entrySet() .stream() .filter(e -> e.getKey() < 100) .map(e -> new XYChart.Data<Number, Number>(e.getKey(), e.getValue())) .collect(Collectors.toList())); } else { total.getData().addAll(ExpTable.get().entrySet() .stream() .map(e -> new XYChart.Data<Number, Number>(e.getKey(), e.getValue())) .collect(Collectors.toList())); } goal.getData().addAll(ExpTable.get().entrySet() .stream() .filter(e -> e.getKey() <= goalLvValue) .map(e -> new XYChart.Data<Number, Number>(e.getKey(), e.getValue())) .collect(Collectors.toList())); now.getData().addAll(ExpTable.get().entrySet() .stream() .filter(e -> e.getKey() <= nowLvValue) .map(e -> new XYChart.Data<Number, Number>(e.getKey(), e.getValue())) .collect(Collectors.toList())); if (ExpTable.get().containsKey(nowLvValue + 1) && !ExpTable.get().get(nowLvValue).equals(ExpTable.get().get(nowLvValue + 1))) { double per = ((double) nowExpValue - ExpTable.get().get(nowLvValue)) / ((double) ExpTable.get().get(nowLvValue + 1) - ExpTable.get().get(nowLvValue)); now.getData().add(new XYChart.Data<Number, Number>(nowLvValue + per, nowExpValue)); } this.expChart.getData().clear(); this.expChart.getData().addAll(Arrays.asList(total, goal, now)); } /** * * * @param baseexp Exp * @param eval * @param isFlagship * @param isMvp MVP * @return */ private static int getExp(int baseexp, double eval, boolean isFlagship, boolean isMvp) { double getexpd = baseexp * eval; if (isFlagship) { getexpd *= 1.5; } if (isMvp) { getexpd *= 2; } return (int) Math.round(getexpd); } /** * 1 * * @param needexp * @param exp 1 * @return */ private static int getCount(int needexp, int exp) { return BigDecimal.valueOf(needexp).divide(BigDecimal.valueOf(exp), RoundingMode.CEILING) .intValue(); } private static class ShipImageTableCell extends TableCell<ShortageShipItem, Ship> { @Override protected void updateItem(Ship ship, boolean empty) { super.updateItem(ship, empty); if (!empty) { this.setGraphic(new ImageView(Ships.shipWithItemImage(ship))); this.setText(Ships.shipMst(ship) .map(ShipMst::getName) .orElse("")); } else { this.setGraphic(null); this.setText(null); } } } /** * (toString) * */ private static class ShipWrapper { private Ship ship; public ShipWrapper(Ship ship) { this.ship = ship; } /** * * @return */ public Ship getShip() { return this.ship; } @Override public String toString() { return Ships.toName(this.ship); } } }
package logbook.internal.gui; import java.awt.GraphicsConfiguration; import java.awt.Rectangle; import java.awt.Robot; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.PrintWriter; import java.nio.file.Path; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.concurrent.TimeUnit; import javax.imageio.ImageIO; import javafx.animation.Animation; import javafx.animation.Animation.Status; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.embed.swing.SwingFXUtils; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.geometry.Point2D; import javafx.scene.Cursor; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.CheckBox; import javafx.scene.control.CheckMenuItem; import javafx.scene.control.Label; import javafx.scene.control.MenuButton; import javafx.scene.control.ScrollPane; import javafx.scene.control.ToggleGroup; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.image.WritableImage; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.stage.DirectoryChooser; import javafx.stage.Stage; import javafx.stage.Window; import javafx.stage.WindowEvent; import logbook.bean.AppConfig; import logbook.internal.LoggerHolder; import logbook.internal.ThreadManager; import logbook.internal.gui.ScreenCapture.ImageData; import lombok.AllArgsConstructor; import lombok.Data; import lombok.Getter; public class CaptureController extends WindowController { @FXML private MenuButton config; @FXML private CheckMenuItem cyclic; @FXML private CheckMenuItem movie; @FXML private ToggleGroup cut; @FXML private Button capture; @FXML private Button save; @FXML private CheckBox direct; @FXML private Label message; @FXML private ScrollPane imageParent; @FXML private ImageView image; private ObservableList<ImageData> images = FXCollections.observableArrayList(); private ObjectProperty<ImageData> preview = new SimpleObjectProperty<>(); private ScreenCapture sc; private Timeline timeline = new Timeline(); private boolean processRunning; private Process process; private Path directPath; @FXML void initialize() { ImageIO.setUseCache(false); this.image.fitWidthProperty().bind(this.imageParent.widthProperty()); this.image.fitHeightProperty().bind(this.imageParent.heightProperty()); this.preview.addListener(this::viewImage); this.direct.selectedProperty().addListener((ov, o, n) -> { if (n) { DirectoryChooser dc = new DirectoryChooser(); dc.setTitle(""); File initDir = Optional.ofNullable(AppConfig.get().getCaptureDir()) .map(File::new) .filter(File::isDirectory) .orElse(null); if (initDir != null) { dc.setInitialDirectory(initDir); } File file = dc.showDialog(this.getWindow()); if (file != null) { this.directPath = file.toPath(); } else { this.direct.setSelected(false); if (this.movie.isSelected()) { this.movie.setSelected(false); this.setCatureButtonState(ButtonState.CAPTURE); } } } else { if (this.movie.isSelected()) { this.movie.setSelected(false); this.setCatureButtonState(ButtonState.CAPTURE); } } }); } @FXML void cutNone(ActionEvent event) { this.sc.setCutRect(ScreenCapture.CutType.NONE.getAngle()); } @FXML void cutUnit(ActionEvent event) { this.sc.setCutRect(ScreenCapture.CutType.UNIT.getAngle()); } @FXML void cutUnitWithoutShip(ActionEvent event) { this.sc.setCutRect(ScreenCapture.CutType.UNIT_WITHOUT_SHIP.getAngle()); } @FXML void detect(ActionEvent event) { this.detectAction(); } @FXML void detectManual(ActionEvent event) { this.detectManualAction(); } @FXML void input(ActionEvent event) { if (this.sc != null) { Rectangle rectangle = this.sc.getRectangle(); RectangleBean bean = new RectangleBean(rectangle.x, rectangle.y, rectangle.width, rectangle.height); new PropertyDialog<>(this.getWindow(), bean, "").showAndWait(); rectangle.x = bean.getX(); rectangle.y = bean.getY(); rectangle.width = bean.getWidth(); rectangle.height = bean.getHeight(); this.setBounds(this.sc.getRobot(), rectangle); } else { Tools.Conrtols.alert(AlertType.INFORMATION, "", "", this.getWindow()); } } @FXML void cyclic(ActionEvent event) { this.stopTimeLine(); this.movie.setSelected(false); if (this.cyclic.isSelected()) { this.setCatureButtonState(ButtonState.START); } else { this.setCatureButtonState(ButtonState.CAPTURE); } } @FXML void movie(ActionEvent event) { this.stopTimeLine(); this.cyclic.setSelected(false); if ((AppConfig.get().getFfmpegPath() == null || AppConfig.get().getFfmpegPath().isEmpty()) || (AppConfig.get().getFfmpegArgs() == null || AppConfig.get().getFfmpegArgs().isEmpty()) || (AppConfig.get().getFfmpegExt() == null || AppConfig.get().getFfmpegExt().isEmpty())) { Tools.Conrtols.alert(AlertType.INFORMATION, "", "[][]" + "FFmpeg", this.getWindow()); this.movie.setSelected(false); } if (this.movie.isSelected()) { this.setCatureButtonState(ButtonState.START); this.direct.setSelected(true); } else { this.setCatureButtonState(ButtonState.CAPTURE); } } @FXML void capture(ActionEvent event) { boolean running = this.timeline.getStatus() == Status.RUNNING; if (running) { this.stopTimeLine(); } if (this.processRunning) { this.stopProcess(); } if (this.cyclic.isSelected()) { this.processRunning = false; if (running) { this.setCatureButtonState(ButtonState.START); } else { this.timeline.setCycleCount(Animation.INDEFINITE); this.timeline.getKeyFrames().clear(); this.timeline.getKeyFrames() .add(new KeyFrame(javafx.util.Duration.millis(100), this::captureAction)); this.timeline.play(); this.setCatureButtonState(ButtonState.STOP); } } else if (this.movie.isSelected()) { if (this.processRunning) { this.setCatureButtonState(ButtonState.START); this.processRunning = false; } else { this.startProcess(); this.processRunning = true; this.setCatureButtonState(ButtonState.STOP); } } else { this.processRunning = false; this.captureAction(event); } } @FXML void save(ActionEvent event) { try { InternalFXMLLoader.showWindow("logbook/gui/capturesave.fxml", this.getWindow(), "", controller -> { ((CaptureSaveController) controller).setItems(this.images); }, null); } catch (Exception ex) { LoggerHolder.get().error("", ex); } } @Override public void setWindow(Stage window) { super.setWindow(window); this.detectAction(); this.getWindow().addEventHandler(WindowEvent.WINDOW_HIDDEN, this::onclose); } private void detectAction() { try { GraphicsConfiguration gc = this.currentGraphicsConfiguration(); Robot robot = new Robot(gc.getDevice()); BufferedImage image = robot.createScreenCapture(gc.getBounds()); Rectangle relative = ScreenCapture.detectGameScreen(image); Rectangle screenBounds = gc.getBounds(); this.setBounds(robot, relative, screenBounds); } catch (Exception e) { LoggerHolder.get().error("", e); } } private Point2D start; private Point2D end; private void detectManualAction() { try { GraphicsConfiguration gcnf = this.currentGraphicsConfiguration(); Robot robot = new Robot(gcnf.getDevice()); BufferedImage bufferedImage = robot.createScreenCapture(gcnf.getBounds()); WritableImage image = SwingFXUtils.toFXImage(bufferedImage, null); Stage stage = new Stage(); Group root = new Group(); Canvas canvas = new Canvas(); canvas.widthProperty().bind(stage.widthProperty()); canvas.heightProperty().bind(stage.heightProperty()); canvas.setCursor(Cursor.CROSSHAIR); GraphicsContext gc = canvas.getGraphicsContext2D(); gc.setStroke(Color.BLACK); gc.setLineWidth(1); gc.setLineDashes(5, 5); canvas.addEventHandler(MouseEvent.MOUSE_PRESSED, e -> { this.start = new Point2D(e.getX(), e.getY()); }); canvas.addEventFilter(MouseEvent.MOUSE_DRAGGED, e -> { gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight()); Point2D now = new Point2D(e.getX(), e.getY()); double x = Math.min(this.start.getX(), now.getX()) + 0.5; double y = Math.min(this.start.getY(), now.getY()) + 0.5; double w = Math.abs(this.start.getX() - now.getX()); double h = Math.abs(this.start.getY() - now.getY()); gc.strokeRect(x, y, w, h); }); canvas.addEventHandler(MouseEvent.MOUSE_RELEASED, e -> { this.end = new Point2D(e.getX(), e.getY()); if (!this.start.equals(this.end)) { Optional<ButtonType> buttonType = Tools.Conrtols.alert(Alert.AlertType.CONFIRMATION, "", "", stage); if (buttonType.orElse(null) == ButtonType.OK) { int x = (int) Math.min(this.start.getX(), this.end.getX()); int y = (int) Math.min(this.start.getY(), this.end.getY()); int w = (int) Math.abs(this.start.getX() - this.end.getX()); int h = (int) Math.abs(this.start.getY() - this.end.getY()); Rectangle tmp = getTrimSize(bufferedImage.getSubimage(x, y, w, h)); Rectangle relative = new Rectangle( (int) (x + tmp.getX()), (int) (y + tmp.getY()), (int) tmp.getWidth(), (int) tmp.getHeight()); Rectangle screenBounds = gcnf.getBounds(); this.setBounds(robot, relative, screenBounds); stage.setFullScreen(false); } } gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight()); }); root.getChildren().addAll(new ImageView(image), canvas); stage.setScene(new Scene(root)); stage.setX(gcnf.getBounds().getX()); stage.setY(gcnf.getBounds().getY()); stage.setTitle(""); stage.setFullScreenExitHint(" [Esc]"); stage.setFullScreen(true); stage.fullScreenProperty().addListener((ov, o, n) -> { if (!n) stage.close(); }); stage.setAlwaysOnTop(true); stage.show(); } catch (Exception e) { LoggerHolder.get().error("", e); } } private void captureAction(ActionEvent event) { try { if (this.sc != null) { boolean isDirect = this.direct.isSelected() && this.directPath != null; if (isDirect) { this.sc.captureDirect(this.directPath); } else { this.sc.capture(); } } } catch (Exception e) { LoggerHolder.get().error("", e); } } /** * * * @param event WindowEvent */ private void onclose(WindowEvent event) { this.images.clear(); this.timeline.stop(); this.stopProcess(); } /** * * * @param ov ObservableValue * @param o * @param n */ private void viewImage(ObservableValue<? extends ImageData> ov, ImageData o, ImageData n) { ImageData image = this.preview.getValue(); if (image != null) { this.image.setImage(new Image(new ByteArrayInputStream(image.getImage()))); } } private void stopTimeLine() { if (this.timeline.getStatus() == Status.RUNNING) { this.timeline.stop(); } } private void startProcess() { Rectangle rectangle = this.sc.getRectangle(); Path to = this.directPath.resolve(CaptureSaveController.DATE_FORMAT.format(ZonedDateTime.now()) + "." + AppConfig.get().getFfmpegExt()); Map<String, String> param = new HashMap<>(); param.put("{x}", String.valueOf((int) rectangle.getX())); param.put("{y}", String.valueOf((int) rectangle.getY())); param.put("{width}", String.valueOf((int) rectangle.getWidth())); param.put("{height}", String.valueOf((int) rectangle.getHeight())); param.put("{path}", to.toAbsolutePath().toString()); List<String> args = new ArrayList<>(); args.add(AppConfig.get().getFfmpegPath()); Arrays.stream(AppConfig.get().getFfmpegArgs().split("\n")) .flatMap(str -> Arrays.stream(str.split(" "))) .map(str -> { String r = str; for (Entry<String, String> entry : param.entrySet()) { r = r.replace(entry.getKey(), entry.getValue()); } return r; }) .forEach(args::add); try { ProcessBuilder pb = new ProcessBuilder(args); pb.redirectError(ProcessBuilder.Redirect.INHERIT); this.process = pb.start(); } catch (Exception e) { this.stopProcess(); Tools.Conrtols.alert(AlertType.ERROR, "", "\n:" + args.toString(), e, this.getWindow()); } } private void stopProcess() { if (this.process != null) { Process process = this.process; ThreadManager.getExecutorService().execute(() -> { if (process.isAlive()) { PrintWriter pw = new PrintWriter(process.getOutputStream(), true); pw.println("q"); try { process.waitFor(2, TimeUnit.MINUTES); } catch (InterruptedException e) { // NOP } finally { process.destroy(); } } }); } } private void setCatureButtonState(ButtonState state) { for (ButtonState val : ButtonState.values()) { this.capture.getStyleClass().remove(val.getClassName()); } this.capture.setText(state.getName()); this.capture.getStyleClass().add(state.getClassName()); } private static Rectangle getTrimSize(BufferedImage image) { int width = image.getWidth(); int height = image.getHeight(); int startwidth = width / 2; int startheightTop = (height / 3) * 2; int startheightButton = height / 3; int x = 0; int y = 0; int w = 0; int h = 0; int color = image.getRGB(0, 0); for (int i = 0; i < width; i++) { if (image.getRGB(i, startheightTop) != color) { x = i; break; } } for (int i = 0; i < width; i++) { if (image.getRGB(i, startheightButton) != color) { x = Math.min(x, i); break; } } for (int i = 0; i < height; i++) { if (image.getRGB(startwidth, i) != color) { y = i; break; } } for (int i = width - 1; i >= 0; i if (image.getRGB(i, startheightTop) != color) { w = (i - x) + 1; break; } } for (int i = width - 1; i >= 0; i if (image.getRGB(i, startheightButton) != color) { w = Math.max(w, (i - x) + 1); break; } } for (int i = height - 1; i >= 0; i if (image.getRGB(startwidth, i) != color) { h = (i - y) + 1; break; } } if ((w == 0) || (h == 0)) { return new Rectangle(0, 0, image.getWidth(), image.getHeight()); } else { return new Rectangle(x, y, w, h); } } private void setBounds(Robot robot, Rectangle relative, Rectangle screenBounds) { if (relative != null) { Rectangle fixed = new Rectangle(relative.x + screenBounds.x, relative.y + screenBounds.y, relative.width, relative.height); this.setBounds(robot, fixed); } else { this.message.setText(""); this.capture.setDisable(true); this.config.setDisable(true); this.sc = null; } } private void setBounds(Robot robot, Rectangle fixed) { String text = "(" + (int) fixed.getMinX() + "," + (int) fixed.getMinY() + ")"; this.message.setText(text); this.capture.setDisable(false); this.config.setDisable(false); this.sc = new ScreenCapture(robot, fixed); this.sc.setItems(this.images); this.sc.setCurrent(this.preview); } private GraphicsConfiguration currentGraphicsConfiguration() { Window window = this.getWindow(); int x = (int) window.getX(); int y = (int) window.getY(); return ScreenCapture.detectScreenDevice(x, y); } private static enum ButtonState { CAPTURE("", "start"), START("", "start"), STOP("", "stop"); @Getter private String name; @Getter private String className; private ButtonState(String name, String className) { this.name = name; this.className = className; } } @Data @AllArgsConstructor public static class RectangleBean { private int x; private int y; private int width; private int height; } }
package com.intellij.uiDesigner.palette; import com.intellij.ide.ui.LafManager; import com.intellij.ide.ui.LafManagerListener; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.components.ProjectComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.JDOMExternalizable; import com.intellij.uiDesigner.Properties; import com.intellij.uiDesigner.SwingProperties; import com.intellij.uiDesigner.UIDesignerBundle; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.lw.LwXmlReader; import com.intellij.uiDesigner.lw.StringDescriptor; import com.intellij.uiDesigner.propertyInspector.IntrospectedProperty; import com.intellij.uiDesigner.propertyInspector.Property; import com.intellij.uiDesigner.propertyInspector.PropertyEditor; import com.intellij.uiDesigner.propertyInspector.PropertyRenderer; import com.intellij.uiDesigner.propertyInspector.editors.IntEnumEditor; import com.intellij.uiDesigner.propertyInspector.properties.*; import com.intellij.uiDesigner.propertyInspector.renderers.IntEnumRenderer; import com.intellij.uiDesigner.radComponents.RadComponent; import org.jdom.Document; import org.jdom.Element; import org.jdom.input.SAXBuilder; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Anton Katilin * @author Vladimir Kondratyev */ public final class Palette implements ProjectComponent, JDOMExternalizable{ private static final Logger LOG = Logger.getInstance("#com.intellij.uiDesigner.palette.Palette"); private final MyLafManagerListener myLafManagerListener; private final HashMap<Class, IntrospectedProperty[]> myClass2Properties; private final HashMap<String, ComponentItem> myClassName2Item; /*All groups in the palette*/ private final ArrayList<GroupItem> myGroups; /*Listeners, etc*/ private final ArrayList<Listener> myListeners; private Project myProject; private GroupItem mySpecialGroup = new GroupItem(true); /** * Predefined item for javax.swing.JPanel */ private ComponentItem myPanelItem; @NonNls private static final String ATTRIBUTE_VSIZE_POLICY = "vsize-policy"; @NonNls private static final String ATTRIBUTE_HSIZE_POLICY = "hsize-policy"; @NonNls private static final String ATTRIBUTE_ANCHOR = "anchor"; @NonNls private static final String ATTRIBUTE_FILL = "fill"; @NonNls private static final String ELEMENT_MINIMUM_SIZE = "minimum-size"; @NonNls private static final String ATTRIBUTE_WIDTH = "width"; @NonNls private static final String ATTRIBUTE_HEIGHT = "height"; @NonNls private static final String ELEMENT_PREFERRED_SIZE = "preferred-size"; @NonNls private static final String ELEMENT_MAXIMUM_SIZE = "maximum-size"; @NonNls private static final String ATTRIBUTE_CLASS = "class"; @NonNls private static final String ATTRIBUTE_ICON = "icon"; @NonNls private static final String ATTRIBUTE_TOOLTIP_TEXT = "tooltip-text"; @NonNls private static final String ELEMENT_DEFAULT_CONSTRAINTS = "default-constraints"; @NonNls private static final String ELEMENT_INITIAL_VALUES = "initial-values"; @NonNls private static final String ELEMENT_PROPERTY = "property"; @NonNls private static final String ATTRIBUTE_NAME = "name"; @NonNls private static final String ATTRIBUTE_VALUE = "value"; @NonNls private static final String ATTRIBUTE_REMOVABLE = "removable"; @NonNls private static final String ELEMENT_ITEM = "item"; @NonNls private static final String ELEMENT_GROUP = "group"; @NonNls private static final String ATTRIBUTE_VERSION = "version"; @NonNls private static final String ATTRIBUTE_SINCE_VERSION = "since-version"; @NonNls private static final String ATTRIBUTE_AUTO_CREATE_BINDING = "auto-create-binding"; @NonNls private static final String ATTRIBUTE_CAN_ATTACH_LABEL = "can-attach-label"; public static Palette getInstance(@NotNull final Project project) { return project.getComponent(Palette.class); } /** Invoked by reflection */ public Palette(Project project) { myProject = project; myLafManagerListener = new MyLafManagerListener(); myClass2Properties = new HashMap<Class, IntrospectedProperty[]>(); myClassName2Item = new HashMap<String, ComponentItem>(); myGroups = new ArrayList<GroupItem>(); myListeners = new ArrayList<Listener>(); if (project != null) { mySpecialGroup.setReadOnly(true); mySpecialGroup.addItem(ComponentItem.createAnyComponentItem(project)); } } /**Adds specified listener.*/ public void addListener(@NotNull final Listener l){ LOG.assertTrue(!myListeners.contains(l)); myListeners.add(l); } /**Removes specified listener.*/ public void removeListener(@NotNull final Listener l){ LOG.assertTrue(myListeners.contains(l)); myListeners.remove(l); } void fireGroupsChanged() { final Listener[] listeners = myListeners.toArray(new Listener[myListeners.size()]); for(Listener listener : listeners) { listener.groupsChanged(this); } } public String getComponentName(){ return "Palette2"; } public void projectOpened() { LafManager.getInstance().addLafManagerListener(myLafManagerListener); } public void projectClosed() { LafManager.getInstance().removeLafManagerListener(myLafManagerListener); } public void readExternal(@NotNull final Element element) { ApplicationManager.getApplication().assertIsDispatchThread(); // It seems that IDEA inokes readExternal twice: first time for node in defaults XML // the second time for node in project file. Stupidity... :( myClass2Properties.clear(); myClassName2Item.clear(); myGroups.clear(); // Parse XML final List groupElements = element.getChildren(ELEMENT_GROUP); processGroups(groupElements); // Ensure that all predefined items are loaded LOG.assertTrue(myPanelItem != null); if (!element.getAttributeValue(ATTRIBUTE_VERSION, "1").equals("2")) { upgradePalette(); } } private void upgradePalette() { // load new components from the predefined Palette2.xml try { //noinspection HardCodedStringLiteral final Document document = new SAXBuilder().build(getClass().getResourceAsStream("/idea/Palette2.xml")); for(Object o: document.getRootElement().getChildren(ELEMENT_GROUP)) { Element groupElement = (Element) o; for(GroupItem group: myGroups) { if (group.getName().equals(groupElement.getAttributeValue(ATTRIBUTE_NAME))) { upgradeGroup(group, groupElement); break; } } } } catch (Exception e) { LOG.error(e); } } private void upgradeGroup(final GroupItem group, final Element groupElement) { for(Object o: groupElement.getChildren(ELEMENT_ITEM)) { Element itemElement = (Element) o; if (itemElement.getAttributeValue(ATTRIBUTE_SINCE_VERSION, "").equals("2")) { processItemElement(itemElement, group, true); } final String className = LwXmlReader.getRequiredString(itemElement, ATTRIBUTE_CLASS); final ComponentItem item = getItem(className); if (item != null) { if (LwXmlReader.getOptionalBoolean(itemElement, ATTRIBUTE_AUTO_CREATE_BINDING, false)) { item.setAutoCreateBinding(true); } if (LwXmlReader.getOptionalBoolean(itemElement, ATTRIBUTE_CAN_ATTACH_LABEL, false)) { item.setCanAttachLabel(true); } } } } public void writeExternal(@NotNull final Element element) { ApplicationManager.getApplication().assertIsDispatchThread(); writeGroups(element); //element.setAttribute(ATTRIBUTE_VERSION, "2"); } public void initComponent() {} public void disposeComponent() {} /** * @return a predefined palette item which corresponds to the JPanel. */ @NotNull public ComponentItem getPanelItem(){ return myPanelItem; } /** * @return <code>ComponentItem</code> for the UI bean with the specified <code>componentClassName</code>. * The method returns <code>null</code> if palette has no information about the specified * class. */ @Nullable public ComponentItem getItem(@NotNull final String componentClassName) { return myClassName2Item.get(componentClassName); } /** * @return read-only list of all groups in the palette. * <em>DO NOT MODIFY OR CACHE THIS LIST</em>. */ public ArrayList<GroupItem> getGroups(){ return myGroups; } public GroupItem[] getToolWindowGroups() { GroupItem[] groups = new GroupItem[myGroups.size()+1]; for(int i=0; i<myGroups.size(); i++) { groups [i] = myGroups.get(i); } groups [myGroups.size()] = mySpecialGroup; return groups; } /** * @param groups list of new groups. */ public void setGroups(@NotNull final ArrayList<GroupItem> groups){ myGroups.clear(); myGroups.addAll(groups); fireGroupsChanged(); } public void addItem(@NotNull final GroupItem group, @NotNull final ComponentItem item) { // class -> item final String componentClassName = item.getClassName(); if (getItem(componentClassName) != null) { Messages.showMessageDialog( UIDesignerBundle.message("error.item.already.added", componentClassName), ApplicationNamesInfo.getInstance().getFullProductName(), Messages.getErrorIcon() ); return; } myClassName2Item.put(componentClassName, item); // group -> items group.addItem(item); // Process special predefined item for JPanel if("javax.swing.JPanel".equals(item.getClassName())){ myPanelItem = item; } } public void replaceItem(GroupItem group, ComponentItem oldItem, ComponentItem newItem) { group.replaceItem(oldItem, newItem); myClassName2Item.put(oldItem.getClassName(), newItem); } public void removeItem(final GroupItem group, final ComponentItem selectedItem) { group.removeItem(selectedItem); myClassName2Item.remove(selectedItem.getClassName()); } /** * Helper method. */ private static GridConstraints processDefaultConstraintsElement(@NotNull final Element element){ final GridConstraints constraints = new GridConstraints(); // grid related attributes constraints.setVSizePolicy(LwXmlReader.getRequiredInt(element, ATTRIBUTE_VSIZE_POLICY)); constraints.setHSizePolicy(LwXmlReader.getRequiredInt(element, ATTRIBUTE_HSIZE_POLICY)); constraints.setAnchor(LwXmlReader.getRequiredInt(element, ATTRIBUTE_ANCHOR)); constraints.setFill(LwXmlReader.getRequiredInt(element, ATTRIBUTE_FILL)); // minimum size final Element minSizeElement = element.getChild(ELEMENT_MINIMUM_SIZE); if (minSizeElement != null) { constraints.myMinimumSize.width = LwXmlReader.getRequiredInt(minSizeElement, ATTRIBUTE_WIDTH); constraints.myMinimumSize.height = LwXmlReader.getRequiredInt(minSizeElement, ATTRIBUTE_HEIGHT); } // preferred size final Element prefSizeElement = element.getChild(ELEMENT_PREFERRED_SIZE); if (prefSizeElement != null){ constraints.myPreferredSize.width = LwXmlReader.getRequiredInt(prefSizeElement, ATTRIBUTE_WIDTH); constraints.myPreferredSize.height = LwXmlReader.getRequiredInt(prefSizeElement, ATTRIBUTE_HEIGHT); } // maximum size final Element maxSizeElement = element.getChild(ELEMENT_MAXIMUM_SIZE); if (maxSizeElement != null) { constraints.myMaximumSize.width = LwXmlReader.getRequiredInt(maxSizeElement, ATTRIBUTE_WIDTH); constraints.myMaximumSize.height = LwXmlReader.getRequiredInt(maxSizeElement, ATTRIBUTE_HEIGHT); } return constraints; } private void processItemElement(@NotNull final Element itemElement, @NotNull final GroupItem group, final boolean skipExisting){ // Class name. It's OK if class does not exist. final String className = LwXmlReader.getRequiredString(itemElement, ATTRIBUTE_CLASS); if (skipExisting && getItem(className) != null) { return; } // Icon (optional) final String iconPath = LwXmlReader.getString(itemElement, ATTRIBUTE_ICON); // Tooltip text (optional) final String toolTipText = LwXmlReader.getString(itemElement, ATTRIBUTE_TOOLTIP_TEXT); // can be null boolean autoCreateBinding = LwXmlReader.getOptionalBoolean(itemElement, ATTRIBUTE_AUTO_CREATE_BINDING, false); boolean canAttachLabel = LwXmlReader.getOptionalBoolean(itemElement, ATTRIBUTE_CAN_ATTACH_LABEL, false); // Default constraint final GridConstraints constraints; final Element defaultConstraints = itemElement.getChild(ELEMENT_DEFAULT_CONSTRAINTS); if (defaultConstraints != null) { constraints = processDefaultConstraintsElement(defaultConstraints); } else { constraints = new GridConstraints(); } final HashMap<String, StringDescriptor> propertyName2initialValue = new HashMap<String, StringDescriptor>(); { final Element initialValues = itemElement.getChild(ELEMENT_INITIAL_VALUES); if (initialValues != null){ for(final Object o : initialValues.getChildren(ELEMENT_PROPERTY)) { final Element e = (Element)o; final String name = LwXmlReader.getRequiredString(e, ATTRIBUTE_NAME); // TODO[all] currently all initial values are strings final StringDescriptor value = StringDescriptor.create(LwXmlReader.getRequiredString(e, ATTRIBUTE_VALUE)); propertyName2initialValue.put(name, value); } } } final boolean removable = LwXmlReader.getOptionalBoolean(itemElement, ATTRIBUTE_REMOVABLE, true); final ComponentItem item = new ComponentItem( myProject, className, iconPath, toolTipText, constraints, propertyName2initialValue, removable, autoCreateBinding, canAttachLabel ); addItem(group, item); } /** * Reads PaletteElements from */ private void processGroups(final List groupElements){ for(final Object groupElement1 : groupElements) { final Element groupElement = (Element)groupElement1; final String groupName = LwXmlReader.getRequiredString(groupElement, ATTRIBUTE_NAME); final GroupItem group = new GroupItem(groupName); myGroups.add(group); for (final Object o : groupElement.getChildren(ELEMENT_ITEM)) { final Element itemElement = (Element)o; try { processItemElement(itemElement, group, false); } catch (Exception ex) { LOG.error(ex); } } } } /** Helper method */ private static void writeDefaultConstraintsElement(@NotNull final Element itemElement, @NotNull final GridConstraints c){ LOG.assertTrue(ELEMENT_ITEM.equals(itemElement.getName())); final Element element = new Element(ELEMENT_DEFAULT_CONSTRAINTS); itemElement.addContent(element); // grid related attributes { element.setAttribute(ATTRIBUTE_VSIZE_POLICY, Integer.toString(c.getVSizePolicy())); element.setAttribute(ATTRIBUTE_HSIZE_POLICY, Integer.toString(c.getHSizePolicy())); element.setAttribute(ATTRIBUTE_ANCHOR, Integer.toString(c.getAnchor())); element.setAttribute(ATTRIBUTE_FILL, Integer.toString(c.getFill())); } // minimum size { if (c.myMinimumSize.width != -1 || c.myMinimumSize.height != -1) { final Element _element = new Element(ELEMENT_MINIMUM_SIZE); element.addContent(_element); _element.setAttribute(ATTRIBUTE_WIDTH, Integer.toString(c.myMinimumSize.width)); _element.setAttribute(ATTRIBUTE_HEIGHT, Integer.toString(c.myMinimumSize.height)); } } // preferred size { if (c.myPreferredSize.width != -1 || c.myPreferredSize.height != -1) { final Element _element = new Element(ELEMENT_PREFERRED_SIZE); element.addContent(_element); _element.setAttribute(ATTRIBUTE_WIDTH, Integer.toString(c.myPreferredSize.width)); _element.setAttribute(ATTRIBUTE_HEIGHT, Integer.toString(c.myPreferredSize.height)); } } // maximum size { if (c.myMaximumSize.width != -1 || c.myMaximumSize.height != -1) { final Element _element = new Element(ELEMENT_MAXIMUM_SIZE); element.addContent(_element); _element.setAttribute(ATTRIBUTE_WIDTH, Integer.toString(c.myMaximumSize.width)); _element.setAttribute(ATTRIBUTE_HEIGHT, Integer.toString(c.myMaximumSize.height)); } } } /** Helper method */ private static void writeInitialValuesElement( final Element itemElement, final HashMap<String, StringDescriptor> name2value ){ LOG.assertTrue(itemElement != null); LOG.assertTrue(ELEMENT_ITEM.equals(itemElement.getName())); LOG.assertTrue(name2value != null); if(name2value.size() == 0){ // do not append 'initial-values' subtag return; } final Element initialValuesElement = new Element(ELEMENT_INITIAL_VALUES); itemElement.addContent(initialValuesElement); for (final Map.Entry<String, StringDescriptor> entry : name2value.entrySet()) { final Element propertyElement = new Element(ELEMENT_PROPERTY); initialValuesElement.addContent(propertyElement); propertyElement.setAttribute(ATTRIBUTE_NAME, entry.getKey()); propertyElement.setAttribute(ATTRIBUTE_VALUE, entry.getValue().getValue()/*descriptor is always trivial*/); } } /** Helper method */ private static void writeComponentItem(@NotNull final Element groupElement, @NotNull final ComponentItem item){ LOG.assertTrue(ELEMENT_GROUP.equals(groupElement.getName())); final Element itemElement = new Element(ELEMENT_ITEM); groupElement.addContent(itemElement); // Class itemElement.setAttribute(ATTRIBUTE_CLASS, item.getClassName()); // Tooltip text (if any) if(item.myToolTipText != null){ itemElement.setAttribute(ATTRIBUTE_TOOLTIP_TEXT, item.myToolTipText); } // Icon (if any) final String iconPath = item.getIconPath(); if(iconPath != null){ itemElement.setAttribute(ATTRIBUTE_ICON, iconPath); } // Removable itemElement.setAttribute(ATTRIBUTE_REMOVABLE, Boolean.toString(item.isRemovable())); itemElement.setAttribute(ATTRIBUTE_AUTO_CREATE_BINDING, Boolean.toString(item.isAutoCreateBinding())); itemElement.setAttribute(ATTRIBUTE_CAN_ATTACH_LABEL, Boolean.toString(item.isCanAttachLabel())); // Default constraints writeDefaultConstraintsElement(itemElement, item.getDefaultConstraints()); // Initial values (if any) writeInitialValuesElement(itemElement, item.getInitialValues()); } /** * @param parentElement element to which all "group" elements will be appended */ private void writeGroups(@NotNull final Element parentElement){ for (final GroupItem group : myGroups) { final Element groupElement = new Element(ELEMENT_GROUP); parentElement.addContent(groupElement); groupElement.setAttribute(ATTRIBUTE_NAME, group.getName()); final ComponentItem[] itemList = group.getItems(); for (ComponentItem aItemList : itemList) { writeComponentItem(groupElement, aItemList); } } } /** * Helper method */ private static IntroIntProperty createIntEnumProperty( final String name, final Method readMethod, final Method writeMethod, final IntEnumEditor.Pair[] pairs ){ return new IntroIntProperty( name, readMethod, writeMethod, new IntEnumRenderer(pairs), new IntEnumEditor(pairs), false); } @NotNull public IntrospectedProperty[] getIntrospectedProperties(@NotNull final RadComponent component) { return getIntrospectedProperties(component.getComponentClass(), component.getDelegee().getClass()); } /** * @return arrys of all properties that can be introspected from the * specified class. Only properties with getter and setter methods are * returned. */ @NotNull public IntrospectedProperty[] getIntrospectedProperties(@NotNull final Class aClass, @NotNull final Class delegeeClass) { // Try the cache first // TODO[vova, anton] update cache after class reloading (its properties caould be hanged). if (myClass2Properties.containsKey(aClass)) { return myClass2Properties.get(aClass); } final ArrayList<IntrospectedProperty> result = new ArrayList<IntrospectedProperty>(); try { final BeanInfo beanInfo = Introspector.getBeanInfo(aClass); final PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); for (final PropertyDescriptor descriptor : descriptors) { Method readMethod = descriptor.getReadMethod(); Method writeMethod = descriptor.getWriteMethod(); if (writeMethod == null || readMethod == null) { continue; } boolean storeAsClient = false; try { delegeeClass.getMethod(readMethod.getName(), readMethod.getParameterTypes()); delegeeClass.getMethod(writeMethod.getName(), writeMethod.getParameterTypes()); } catch (NoSuchMethodException e) { storeAsClient = true; } @NonNls final String name = descriptor.getName(); if (name.equals("preferredSize") || name.equals("minimumSize") || name.equals("maximumSize")) { // our own properties must be used instead continue; } final IntrospectedProperty property; final Class propertyType = descriptor.getPropertyType(); final Properties properties = (myProject == null) ? new Properties() : Properties.getInstance(); if (int.class.equals(propertyType)) { // int IntEnumEditor.Pair[] enumPairs = properties.getEnumPairs(aClass, name); if (enumPairs != null) { property = createIntEnumProperty(name, readMethod, writeMethod, enumPairs); } else if (JLabel.class.isAssignableFrom(aClass)) { // special handling for javax.swing.JLabel if (JLabel.class.isAssignableFrom(aClass) && ("displayedMnemonic".equals(name) || "displayedMnemonicIndex".equals(name))) { // skip JLabel#displayedMnemonic and JLabel#displayedMnemonicIndex continue; } else { property = new IntroIntProperty(name, readMethod, writeMethod, storeAsClient); } } else if (AbstractButton.class.isAssignableFrom(aClass)) { // special handling AbstractButton subclasses if ("mnemonic".equals(name) || "displayedMnemonicIndex".equals(name)) { // AbstractButton#mnemonic continue; } else { property = new IntroIntProperty(name, readMethod, writeMethod, storeAsClient); } } else { property = new IntroIntProperty(name, readMethod, writeMethod, storeAsClient); } } else if (boolean.class.equals(propertyType)) { // boolean property = new IntroBooleanProperty(name, readMethod, writeMethod, storeAsClient); } else if (double.class.equals(propertyType)) { // double property = new IntroDoubleProperty(name, readMethod, writeMethod, storeAsClient); } else if (String.class.equals(propertyType)) { // java.lang.String property = new IntroStringProperty(name, readMethod, writeMethod, myProject, storeAsClient); } else if (Insets.class.equals(propertyType)) { // java.awt.Insets property = new IntroInsetsProperty(name, readMethod, writeMethod, storeAsClient); } else if (Dimension.class.equals(propertyType)) { // java.awt.Dimension property = new IntroDimensionProperty(name, readMethod, writeMethod, storeAsClient); } else if (Rectangle.class.equals(propertyType)) { // java.awt.Rectangle property = new IntroRectangleProperty(name, readMethod, writeMethod, storeAsClient); } else if (Component.class.isAssignableFrom(propertyType)) { if (JSplitPane.class.isAssignableFrom(aClass) && (name.equals("leftComponent") || name.equals("rightComponent") || name.equals("topComponent") || name.equals("bottomComponent"))) { // these properties are set through layout continue; } if (JMenuBar.class.isAssignableFrom(propertyType) || JPopupMenu.class.isAssignableFrom(propertyType)) { // no menu editing yet continue; } Condition<RadComponent> filter = null; if (name.equals(SwingProperties.LABEL_FOR)) { filter = new Condition<RadComponent>() { public boolean value(final RadComponent t) { ComponentItem item = getItem(t.getComponentClassName()); return item != null && item.isCanAttachLabel(); } }; } property = new IntroComponentProperty(name, readMethod, writeMethod, propertyType, filter, storeAsClient); } else if (Color.class.equals(propertyType)) { property = new IntroColorProperty(name, readMethod, writeMethod, storeAsClient); } else if (Font.class.equals(propertyType)) { property = new IntroFontProperty(name, readMethod, writeMethod, storeAsClient); } else if (Icon.class.equals(propertyType)) { property = new IntroIconProperty(name, readMethod, writeMethod, storeAsClient); } else if (ListModel.class.isAssignableFrom(propertyType)) { property = new IntroListModelProperty(name, readMethod, writeMethod, storeAsClient); } else if (Enum.class.isAssignableFrom(propertyType)) { property = new IntroEnumProperty(name, readMethod, writeMethod, storeAsClient, propertyType); } else { // other types are not supported (yet?) continue; } result.add(property); } } catch (IntrospectionException e) { throw new RuntimeException(e); } final IntrospectedProperty[] properties = result.toArray(new IntrospectedProperty[result.size()]); myClass2Properties.put(aClass, properties); return properties; } /** * @return introspected property with the given <code>name</code> of the * specified <code>class</code>. The method returns <code>null</code> if there is no * property with the such name. */ @Nullable public IntrospectedProperty getIntrospectedProperty(@NotNull final RadComponent component, @NotNull final String name){ final IntrospectedProperty[] properties = getIntrospectedProperties(component); for (final IntrospectedProperty property: properties) { if (name.equals(property.getName())) { return property; } } return null; } /** * @return "inplace" property for the component with the specified class. * <b>DO NOT USE THIS METHOD DIRECTLY</b>. Use {@link com.intellij.uiDesigner.radComponents.RadComponent#getInplaceProperty(int, int) } * instead. */ @Nullable public IntrospectedProperty getInplaceProperty(@NotNull final RadComponent component) { final String inplaceProperty = Properties.getInstance().getInplaceProperty(component.getComponentClass()); final IntrospectedProperty[] properties = getIntrospectedProperties(component); for (int i = properties.length - 1; i >= 0; i final IntrospectedProperty property = properties[i]; if(property.getName().equals(inplaceProperty)){ return property; } } return null; } public static boolean isRemovable(@NotNull final GroupItem group){ final ComponentItem[] items = group.getItems(); for(int i = items.length - 1; i >=0; i if(!items [i].isRemovable()){ return false; } } return true; } /** * Updates UI of editors and renderers of all introspected properties */ private final class MyLafManagerListener implements LafManagerListener{ private void updateUI(final Property property){ final PropertyRenderer renderer = property.getRenderer(); renderer.updateUI(); final PropertyEditor editor = property.getEditor(); if(editor != null){ editor.updateUI(); } final Property[] children = property.getChildren(null); for (int i = children.length - 1; i >= 0; i updateUI(children[i]); } } public void lookAndFeelChanged(final LafManager source) { for (final IntrospectedProperty[] properties : myClass2Properties.values()) { LOG.assertTrue(properties != null); for (int j = properties.length - 1; j >= 0; j updateUI(properties[j]); } } } } static interface Listener{ void groupsChanged(Palette palette); } }
package mcjty.rftoolsdim.blocks; import mcjty.lib.McJtyRegister; import mcjty.rftoolsdim.RFToolsDim; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.entity.Entity; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumBlockRenderType; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.annotation.Nullable; import java.util.Collections; import java.util.List; public class FakeWaterBlock extends Block { public FakeWaterBlock() { super(Material.GLASS); setHardness(100.0f); setLightOpacity(3); setUnlocalizedName(RFToolsDim.MODID + "." + "fake_water"); setRegistryName("fake_water"); // setLightLevel(0.6f); // setCreativeTab(RFToolsDim.tabRfToolsDim); McJtyRegister.registerLater(this, RFToolsDim.instance, ItemBlock.class); } @Override public void addCollisionBoxToList(IBlockState state, World worldIn, BlockPos pos, AxisAlignedBB entityBox, List<AxisAlignedBB> collidingBoxes, @Nullable Entity entityIn, boolean p_185477_7_) { } @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { return FULL_BLOCK_AABB; } @Nullable @Override public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, IBlockAccess worldIn, BlockPos pos) { return NULL_AABB; } @Override public boolean isPassable(IBlockAccess worldIn, BlockPos pos) { return true; } @Override public boolean isFullCube(IBlockState state) { return false; } /** * Used to determine ambient occlusion and culling when rebuilding chunks for render */ @Override public boolean isOpaqueCube(IBlockState state) { return false; } public boolean isBlockSolid(IBlockAccess worldIn, BlockPos pos, EnumFacing side) { return false; } @SideOnly(Side.CLIENT) @Override public boolean shouldSideBeRendered(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side) { return blockAccess.getBlockState(pos.offset(side)).getBlock() == this ? false : (side == EnumFacing.UP ? true : super.shouldSideBeRendered(blockState, blockAccess, pos, side)); } @Override public EnumBlockRenderType getRenderType(IBlockState state) { return EnumBlockRenderType.MODEL; } @SideOnly(Side.CLIENT) @Override public BlockRenderLayer getBlockLayer() { return BlockRenderLayer.TRANSLUCENT; } @Override public List<ItemStack> getDrops(IBlockAccess world, BlockPos pos, IBlockState state, int fortune) { return Collections.emptyList(); } @SideOnly(Side.CLIENT) public void initModel() { ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(this), 0, new ModelResourceLocation(getRegistryName(), "inventory")); } }
package me.lemire.integercompression; import com.kamikaze.pfordelta.PForDelta; import me.lemire.integercompression.synth.ClusteredDataGenerator; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; /** * * Simple class meant to compare the speed of different schemes. * @author Daniel Lemire * */ public class Benchmark { /** * Standard benchmark * * @param c the codec * @param data arrays of input data * @param repeat How many times to repeat the test * @param verbose whether to output result on screen */ private static void testCodec(IntegerCODEC c, int[][] data, int repeat, boolean verbose) { DecimalFormat df = new DecimalFormat("0.00"); DecimalFormat dfspeed = new DecimalFormat("0"); if (verbose) System.out.println("# " + c.toString()); if (verbose) System.out.println("# bits per int, compress speed (mis), decompression speed (mis) "); long bef, aft; String line = ""; int N = data.length; int totalsize = 0; int maxlength = 0; for (int k = 0; k < N; ++k) { totalsize += data[k].length; if (data[k].length > maxlength) maxlength = data[k].length; } int[] buffer = new int[maxlength + 1024]; int[] dataout = new int[4 * maxlength + 1024]; /* 4x + 1024 to account for the possibility of some negative compression */ int size = 0; int comptime = 0; long decomptime = 0; IntWrapper inpos = new IntWrapper(); IntWrapper outpos = new IntWrapper(); for (int r = 0; r < repeat; ++r) { size = 0; for (int k = 0; k < N; ++k) { int[] backupdata = Arrays.copyOf(data[k], data[k].length); bef = System.nanoTime() / 1000; inpos.set(1); outpos.set(0); if (!(c instanceof IntegratedIntegerCODEC)) { Delta.delta(backupdata); } c.compress(backupdata, inpos, backupdata.length - inpos.get(), dataout, outpos); aft = System.nanoTime() / 1000; comptime += aft - bef; final int thiscompsize = outpos.get() + 1; size += thiscompsize; bef = System.nanoTime() / 1000; inpos.set(0); outpos.set(1); buffer[0] = backupdata[0]; c.uncompress(dataout, inpos, thiscompsize - 1, buffer, outpos); if (!(c instanceof IntegratedIntegerCODEC)) Delta.fastinverseDelta(buffer); aft = System.nanoTime() / 1000; decomptime += aft - bef; if (outpos.get() != data[k].length) throw new RuntimeException("we have a bug (diff length) " + c + " expected " + data[k].length + " got " + outpos.get()); for (int m = 0; m < outpos.get(); ++m) if (buffer[m] != data[k][m]) { throw new RuntimeException( "we have a bug (actual difference), expected " + data[k][m] + " found " + buffer[m] + " at " + m); } } } line += "\t" + df.format(size * 32.0 / totalsize); line += "\t" + dfspeed.format(totalsize * repeat / (comptime)); line += "\t" + dfspeed.format(totalsize * repeat / (decomptime)); if (verbose) System.out.println(line); } /** * Main method. * * @param args command-line arguments */ public static void main(String args[]) { System.out.println("# benchmark based on the ClusterData model from:"); System.out.println("# Vo Ngoc Anh and Alistair Moffat. "); System.out.println("# Index compression using 64-bit words.") ; System.out.println("# Softw. Pract. Exper.40, 2 (February 2010), 131-147. "); System.out.println(); test(20, 18, 10); } /** * Standard test for the Kamikaze library * * @param data input data * @param repeat how many times to repeat * @param verbose whether to output data on screen */ public static void testKamikaze(int[][] data, int repeat, boolean verbose) { DecimalFormat df = new DecimalFormat("0.00"); DecimalFormat dfspeed = new DecimalFormat("0"); if (verbose) System.out.println("# kamikaze PForDelta"); if (verbose) System.out .println("# bits per int, compress speed (mis), decompression speed (mis) "); long bef, aft; String line = ""; int N = data.length; int totalsize = 0; int maxlength = 0; for (int k = 0; k < N; ++k) { totalsize += data[k].length; if (data[k].length > maxlength) maxlength = data[k].length; } int[] buffer = new int[maxlength + 1024]; /* 4x + 1024 to account for the possibility of some negative compression */ int size = 0; int comptime = 0; long decomptime = 0; for (int r = 0; r < repeat; ++r) { size = 0; for (int k = 0; k < N; ++k) { int outpos = 0; int[] backupdata = Arrays.copyOf(data[k], data[k].length); bef = System.nanoTime() / 1000; Delta.delta(backupdata); ArrayList<int[]> dataout = new ArrayList<int[]>(data[k].length / 128); for (int K = 0; K < data[k].length; K += 128) { final int[] compressedbuf = PForDelta.compressOneBlockOpt(Arrays.copyOfRange(backupdata, K, K + 128), 128); dataout.add(compressedbuf); outpos += compressedbuf.length; } aft = System.nanoTime() / 1000; comptime += aft - bef; final int thiscompsize = outpos; size += thiscompsize; bef = System.nanoTime() / 1000; //buffer[0] = backupdata[0]; ArrayList<int[]> datauncomp = new ArrayList<int[]>(dataout.size()); int deltaoffset = 0; for (int[] compbuf : dataout) { int[] tmpbuf = new int[128]; PForDelta.decompressOneBlock(tmpbuf, compbuf, 128); tmpbuf[0] += deltaoffset; Delta.fastinverseDelta(tmpbuf); deltaoffset = tmpbuf[127]; datauncomp.add(tmpbuf); } aft = System.nanoTime() / 1000; decomptime += aft - bef; if (datauncomp.size() * 128 != data[k].length) throw new RuntimeException("we have a bug (diff length) " + " expected " + data[k].length + " got " + datauncomp.size() * 128); for (int m = 0; m < data[k].length; ++m) if (datauncomp.get(m / 128)[m % 128] != data[k][m]) { throw new RuntimeException( "we have a bug (actual difference), expected " + data[k][m] + " found " + buffer[m] + " at " + m); } } } line += "\t" + df.format(size * 32.0 / totalsize); line += "\t" + dfspeed.format(totalsize * repeat / (comptime)); line += "\t" + dfspeed.format(totalsize * repeat / (decomptime)); if (verbose) System.out.println(line); } /** * Generate test data. * * @param N How many input arrays to generate * @param nbr How big (in log2) should the arrays be * @param sparsity How sparse test data generated */ private static int[][] generateTestData( ClusteredDataGenerator dataGen, int N, int nbr, int sparsity) { final int[][] data = new int[N][]; final int dataSize = (1 << (nbr + sparsity)); for (int i = 0; i < N; ++i) { data[i] = dataGen.generateClustered((1 << nbr), dataSize); } return data; } /** * Generates data and calls other tests. * * @param N How many input arrays to generate * @param nbr how big (in log2) should the arrays be * @param repeat How many times should we repeat tests. */ private static void test(int N, int nbr, int repeat) { ClusteredDataGenerator cdg = new ClusteredDataGenerator(); final int max_sparsity = 31 - nbr; for (int sparsity = 1; sparsity < max_sparsity; ++sparsity) { System.out.println("# sparsity " + sparsity); System.out.println("# generating random data..."); int[][] data = generateTestData(cdg, N, nbr, sparsity); System.out.println("# generating random data... ok."); testKamikaze(data, repeat, false); testKamikaze(data, repeat, false); testKamikaze(data, repeat, true); System.out.println(); testCodec(new IntegratedComposition(new IntegratedBinaryPacking(), new IntegratedVariableByte()), data, repeat, false); testCodec(new IntegratedComposition(new IntegratedBinaryPacking(), new IntegratedVariableByte()), data, repeat, false); testCodec(new IntegratedComposition(new IntegratedBinaryPacking(), new IntegratedVariableByte()), data, repeat, true); System.out.println(); testCodec(new JustCopy(), data, repeat, false); testCodec(new JustCopy(), data, repeat, false); testCodec(new JustCopy(), data, repeat, true); System.out.println(); testCodec(new VariableByte(), data, repeat, false); testCodec(new VariableByte(), data, repeat, false); testCodec(new VariableByte(), data, repeat, true); System.out.println(); testCodec(new IntegratedVariableByte(), data, repeat, false); testCodec(new IntegratedVariableByte(), data, repeat, false); testCodec(new IntegratedVariableByte(), data, repeat, true); System.out.println(); testCodec(new Composition(new BinaryPacking(), new VariableByte()), data, repeat, false); testCodec(new Composition(new BinaryPacking(), new VariableByte()), data, repeat, false); testCodec(new Composition(new BinaryPacking(), new VariableByte()), data, repeat, true); System.out.println(); testCodec(new Composition(new NewPFD(), new VariableByte()), data, repeat, false); testCodec(new Composition(new NewPFD(), new VariableByte()), data, repeat, false); testCodec(new Composition(new NewPFD(), new VariableByte()), data, repeat, true); System.out.println(); testCodec(new Composition(new NewPFDS9(), new VariableByte()), data, repeat, false); testCodec(new Composition(new NewPFDS9(), new VariableByte()), data, repeat, false); testCodec(new Composition(new NewPFDS9(), new VariableByte()), data, repeat, true); System.out.println(); testCodec(new Composition(new NewPFDS16(), new VariableByte()), data, repeat, false); testCodec(new Composition(new NewPFDS16(), new VariableByte()), data, repeat, false); testCodec(new Composition(new NewPFDS16(), new VariableByte()), data, repeat, true); System.out.println(); testCodec(new Composition(new OptPFD(), new VariableByte()), data, repeat, false); testCodec(new Composition(new OptPFD(), new VariableByte()), data, repeat, false); testCodec(new Composition(new OptPFD(), new VariableByte()), data, repeat, true); System.out.println(); testCodec(new Composition(new OptPFDS9(), new VariableByte()), data, repeat, false); testCodec(new Composition(new OptPFDS9(), new VariableByte()), data, repeat, false); testCodec(new Composition(new OptPFDS9(), new VariableByte()), data, repeat, true); System.out.println(); testCodec(new Composition(new OptPFDS16(), new VariableByte()), data, repeat, false); testCodec(new Composition(new OptPFDS16(), new VariableByte()), data, repeat, false); testCodec(new Composition(new OptPFDS16(), new VariableByte()), data, repeat, true); System.out.println(); testCodec(new Composition(new FastPFOR(), new VariableByte()), data, repeat, false); testCodec(new Composition(new FastPFOR(), new VariableByte()), data, repeat, false); testCodec(new Composition(new FastPFOR(), new VariableByte()), data, repeat, true); System.out.println(); testCodec(new Simple9(), data, repeat, false); testCodec(new Simple9(), data, repeat, false); testCodec(new Simple9(), data, repeat, true); System.out.println(); } } }
package mil.nga.geopackage; /** * GeoPackage constants * * @author osbornb */ public class GeoPackageConstants { /** * Extension to GeoPackage files */ public static final String GEOPACKAGE_EXTENSION = "gpkg"; /** * Extension to GeoPackage extension files * * @deprecated in GeoPackage version 1.2 */ public static final String GEOPACKAGE_EXTENDED_EXTENSION = "gpkx"; /** * GeoPackage application id */ public static final String APPLICATION_ID = "GPKG"; /** * GeoPackage user version * * @since 1.2.1 */ public static final int USER_VERSION = 10201; /** * Expected magic number */ public static final String GEO_PACKAGE_GEOMETRY_MAGIC_NUMBER = "GP"; /** * Expected version 1 value */ public static final byte GEO_PACKAGE_GEOMETRY_VERSION_1 = 0; /** * SQLite header string prefix */ public static final String SQLITE_HEADER_PREFIX = "SQLite format 3"; /** * GeoPackage author */ public static final String GEO_PACKAGE_EXTENSION_AUTHOR = GEOPACKAGE_EXTENSION; /** * Geometry extension prefix */ public static final String GEOMETRY_EXTENSION_PREFIX = "geom"; }
package net.adrouet.broceliande.struct; import net.adrouet.broceliande.util.InspectionUtils; import java.beans.IntrospectionException; import java.lang.reflect.Method; import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; public class DataSet<D extends IData<R>, R extends Comparable<R>> { private Class<D> dataClass; private List<D> data; private Set<Method> p; public DataSet(Class<D> cl) { this.p = InspectionUtils.findFeatures(cl); this.dataClass = cl; } /** * @return set of possible results */ public Set<R> getJ() { return data.stream().map(IData::getResult).distinct().collect(Collectors.toSet()); } /** * @return set of possible features (getters) */ public Set<Method> getP() { return p; } /** * @return the subset of node samples falling into node t */ public List<D> getL_t() { return data; } /** * Set the data for the dataset * * @param data */ public void setData(List<D> data) { this.data = data; } /** * split the dataset into two sub data sets depending on the cutting point * * @param cut the cutting point * @return */ public SubDataSets split(Predicate<IData> cut) { List<D> left = new ArrayList<>(); List<D> right = new ArrayList<>(); getL_t().forEach(d -> { if (cut.test(d)) { left.add(d); } else { right.add(d); } }); DataSet leftDataSet = new DataSet<>(dataClass); leftDataSet.setData(left); DataSet rightDataSet = new DataSet<>(dataClass); rightDataSet.setData(right); return new SubDataSets(leftDataSet, rightDataSet); } public R getDominantResult() { Map<R, Long> count = data.stream() .collect(Collectors.groupingBy(d -> d.getResult(), Collectors.counting())); return Collections.max(count.entrySet(), Map.Entry.comparingByValue()).getKey(); } }
package com.angcyo.uiview.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.design.widget.TextInputLayout; import android.support.v4.content.res.ResourcesCompat; import android.support.v7.widget.AppCompatEditText; import android.text.Editable; import android.text.InputFilter; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextPaint; import android.text.TextUtils; import android.text.TextWatcher; import android.text.method.ArrowKeyMovementMethod; import android.text.method.LinkMovementMethod; import android.text.method.PasswordTransformationMethod; import android.text.style.ClickableSpan; import android.util.AttributeSet; import android.view.Gravity; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputConnectionWrapper; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.TextView; import com.angcyo.library.utils.Anim; import com.angcyo.library.utils.L; import com.angcyo.uiview.R; import com.angcyo.uiview.RApplication; import com.angcyo.uiview.kotlin.ExKt; import com.angcyo.uiview.skin.SkinHelper; import com.angcyo.uiview.utils.RTextPaint; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ExEditText extends AppCompatEditText { Rect clearRect = new Rect(); boolean isDownIn = false; Drawable clearDrawable; boolean showClear = true; boolean isPassword = false; boolean handleTouch = false; long downTime = 0; /** * , touch down */ boolean autoHideSoftInput = false; List<String> mAllMention = new ArrayList<>(5); /** * , inputType EditorInfo.TYPE_CLASS_NUMBER */ float mMaxNumber = Float.MAX_VALUE; /** * , inputType EditorInfo.TYPE_NUMBER_FLAG_DECIMAL */ int mDecimalCount = Integer.MAX_VALUE; private List<Range> mRangeArrayList = new ArrayList<>(5); private OnMentionInputListener mOnMentionInputListener; private boolean mIsSelected = false; private Range mLastSelectedRange; /** * @, ,{@link #setOnMentionInputListener(OnMentionInputListener)}, */ private boolean enableMention = false; private boolean enableCallback = true; private RTextPaint mTextPaint; private String mLeftString; private String mInputTipText = ""; /** * hint, hint */ private String mRHintText; private List<String> mInputTipTextList = new ArrayList<>(); private int mLeftOffset; private int mDrawLeftOffset; private int mPaddingLeft; public ExEditText(Context context) { super(context); } public ExEditText(Context context, AttributeSet attrs) { super(context, attrs); initView(context, attrs); } public ExEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(context, attrs); } /** * TextView@ */ public static void checkMentionSpannable(TextView textView, String content, List<String> allMention) { if (textView == null) { return; } if (allMention.isEmpty() || TextUtils.isEmpty(content)) { textView.setText(content); textView.setMovementMethod(ArrowKeyMovementMethod.getInstance()); return; } SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(content); int lastMentionIndex = -1; for (String mention : allMention) { Matcher matcher = Pattern.compile("@" + mention).matcher(content); while (matcher.find()) { String mentionText = matcher.group(); int start; if (lastMentionIndex != -1) { start = content.indexOf(mentionText, lastMentionIndex); } else { start = content.indexOf(mentionText); } int end = start + mentionText.length(); spannableStringBuilder.setSpan(new MentionSpan(mentionText), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } textView.setText(spannableStringBuilder); textView.setMovementMethod(LinkMovementMethod.getInstance()); } public static boolean canVerticalScroll(EditText editText) { int scrollY = editText.getScrollY(); int scrollRange = editText.getLayout().getHeight(); int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() - editText.getCompoundPaddingBottom(); int scrollDifference = scrollRange - scrollExtent; if (scrollDifference == 0) { return false; } return (scrollY > 0) || (scrollY < scrollDifference - 1); } /** * string */ public static boolean isPhone(String string) { if (TextUtils.isEmpty(string)) { return false; } final String phone = string.trim(); return !TextUtils.isEmpty(phone) && phone.matches("^1[3-8]\\d{9}$"); } public boolean unableCallback() { enableCallback = false; return enableCallback; } public boolean enableCallback() { enableCallback = true; return enableCallback; } public void setEnableMention(boolean enableMention) { this.enableMention = enableMention; } public void setMaxNumber(float mMaxNumber) { this.mMaxNumber = mMaxNumber; } public void setDecimalCount(int mDecimalCount) { this.mDecimalCount = mDecimalCount; } private void initView(Context context, AttributeSet attrs) { mPaddingLeft = getPaddingLeft(); ensurePaint(); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExEditText); int color = typedArray.getColor(R.styleable.ExEditText_r_left_text_color, getCurrentTextColor()); mLeftOffset = typedArray.getDimensionPixelOffset(R.styleable.ExEditText_r_left_text_offset, getResources().getDimensionPixelOffset(R.dimen.base_ldpi)); String string = typedArray.getString(R.styleable.ExEditText_r_left_text); mRHintText = typedArray.getString(R.styleable.ExEditText_r_hint_text); mMaxNumber = typedArray.getFloat(R.styleable.ExEditText_r_max_number, mMaxNumber); mDecimalCount = typedArray.getInteger(R.styleable.ExEditText_r_decimal_count, mDecimalCount); typedArray.recycle(); setLeftString(string); mTextPaint.setTextColor(color); } public boolean canVerticalScroll() { return canVerticalScroll(this); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (!TextUtils.isEmpty(mLeftString)) { //mTextPaint.drawOriginText(canvas, mLeftString, getPaddingLeft(), getMeasuredHeight() - getPaddingBottom()); canvas.save(); canvas.translate(-getPaddingLeft() + getScrollX(), 0); mTextPaint.drawOriginText(canvas, mLeftString, getPaddingLeft() + mPaddingLeft, (getMeasuredHeight() - getPaddingBottom() - getPaddingTop()) / 2 + getPaddingTop() + mTextPaint.getTextHeight() / 2); canvas.restore(); } if (isFocused()) { if (isInputTipPattern()) { canvas.save(); final TextPaint textPaint = getPaint(); textPaint.setColor(SkinHelper.getTranColor(getCurrentTextColor(), 0x40)); int lineHeight = getLayout().getLineDescent(0) - getLayout().getLineAscent(0); int top = getMeasuredHeight() / 2 - lineHeight / 2; int bottom = getPaddingTop() + (getMeasuredHeight() - getPaddingTop() - getPaddingBottom()) / 2 + lineHeight / 2; canvas.clipRect(textPaint.measureText(String.valueOf(getText()), 0, getText().length()) + getInputTipDrawLeft(), 0, getMeasuredWidth(), getMeasuredHeight()); canvas.drawText(mInputTipText, getInputTipDrawLeft(), bottom - getLayout().getLineDescent(0), textPaint); canvas.restore(); } } //RHint if (TextUtils.isEmpty(getText()) && TextUtils.isEmpty(getHint()) && !TextUtils.isEmpty(mRHintText)) { canvas.save(); final TextPaint textPaint = getPaint(); textPaint.setColor(getCurrentHintTextColor()); // textPaint.setColor(Color.RED); int lineHeight = getLayout().getLineDescent(0) - getLayout().getLineAscent(0); int bottom = getPaddingTop() + (getMeasuredHeight() - getPaddingTop() - getPaddingBottom()) / 2 + lineHeight / 2; float x = 0, y = 0; y = bottom - getLayout().getLineDescent(0); if (ExKt.have(getGravity(), Gravity.LEFT)) { x = getInputTipDrawLeft(); } else if (ExKt.have(getGravity(), Gravity.RIGHT)) { //rightinputType ,BUG. x = getMeasuredWidth() - getInputTipDrawRight() - textPaint.measureText(mRHintText); } canvas.drawText(mRHintText, x, y, textPaint); canvas.restore(); } } private int getInputTipDrawLeft() { int left = getPaddingLeft(); Drawable[] drawables = getCompoundDrawables(); if (drawables[0] != null) { left += drawables[0].getIntrinsicWidth(); left += getCompoundDrawablePadding(); } return left; } private int getInputTipDrawRight() { int right = getPaddingRight(); Drawable[] drawables = getCompoundDrawables(); if (drawables[2] != null) { right += drawables[2].getIntrinsicWidth(); right += getCompoundDrawablePadding(); } return right; } private boolean isCenterVertical() { return Gravity.CENTER_VERTICAL == (getGravity() & Gravity.CENTER_VERTICAL); } private boolean isInputTipPattern() { String text = getText().toString(); // return isCenterVertical() /*Gravity.CENTER_VERTICAL*/ && // !TextUtils.isEmpty(mInputTipText) && // !TextUtils.isEmpty(text) && // mInputTipText.startsWith(text) && // !TextUtils.equals(mInputTipText, text) ; mInputTipText = ""; for (String s : mInputTipTextList) { if (s.startsWith(text)) { mInputTipText = s; break; } } return isCenterVertical() /*Gravity.CENTER_VERTICAL*/ && !mInputTipTextList.isEmpty() && !TextUtils.isEmpty(text) && !TextUtils.isEmpty(mInputTipText) && !TextUtils.equals(mInputTipText, text) ; } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); initView(); ensurePaint(); } @Override public void setTag(Object tag) { super.setTag(tag); initView(); } private void ensurePaint() { if (mTextPaint == null) { mTextPaint = new RTextPaint(getPaint()); } } public void setInputText(String text) { setText(text); setSelection(TextUtils.isEmpty(text) ? 0 : text.length()); //checkEdit(true); } public void setSelectionLast() { setSelection(TextUtils.isEmpty(getText()) ? 0 : getText().length()); } private void initView() { Object tag = getTag(); if (tag != null) { String tagString = String.valueOf(tag); if (tagString.contains("emoji")) { //emoji addFilter(new EmojiFilter()); } if (tagString.contains("password")) { isPassword = true; } if (tagString.contains("hide")) { showClear = false; } else if (tagString.contains("show")) { showClear = true; } } getClearDrawable(); } private Drawable getClearDrawable() { if (showClear && clearDrawable == null) { clearDrawable = ResourcesCompat.getDrawable( getResources(), R.drawable.base_edit_delete_selector, getContext().getTheme()); if (getCompoundDrawablePadding() == 0) { setCompoundDrawablePadding((int) (4 * getResources().getDisplayMetrics().density)); } } return clearDrawable; } private void addFilter(InputFilter filter) { final InputFilter[] filters = getFilters(); final InputFilter[] newFilters = new InputFilter[filters.length + 1]; System.arraycopy(filters, 0, newFilters, 0, filters.length); newFilters[filters.length] = filter; setFilters(newFilters); } @Override protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { super.onFocusChanged(focused, direction, previouslyFocusedRect); checkEdit(focused); if (!focused) { if (isInputTipPattern()) { setText(mInputTipText); } } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); if (showClear) { clearRect.set(w - getPaddingRight() - getClearDrawable().getIntrinsicWidth(), getPaddingTop(), w - getPaddingRight(), Math.min(w, h) - getPaddingBottom()); } } @Override public boolean onTouchEvent(MotionEvent event) { int action = event.getAction(); if (showClear && isFocused()) { if (action == MotionEvent.ACTION_DOWN) { isDownIn = checkClear(event.getX(), event.getY()); updateState(isDownIn); } else if (action == MotionEvent.ACTION_MOVE) { updateState(checkClear(event.getX(), event.getY())); } else if (action == MotionEvent.ACTION_UP) { updateState(false); if (isDownIn && checkClear(event.getX(), event.getY())) { if (!TextUtils.isEmpty(getText())) { setText(""); return true; } } isDownIn = false; if (autoHideSoftInput && isSoftKeyboardShow()) { post(new Runnable() { @Override public void run() { hideSoftInput(); } }); } } else if (action == MotionEvent.ACTION_CANCEL) { updateState(false); isDownIn = false; } } //L.e("call: onTouchEvent([event])-> canVerticalScroll:" + canVerticalScroll(this)); // if (isPassword) { // if (action == MotionEvent.ACTION_DOWN) { // downTime = System.currentTimeMillis(); // } else if (action == MotionEvent.ACTION_MOVE) { // if ((System.currentTimeMillis() - downTime) > 100) { // if (isDownIn) { // hidePassword(); // } else { // showPassword(); // } else if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { // hidePassword(); return super.onTouchEvent(event); } private void updateState(boolean isDownIn) { final Drawable clearDrawable = getCompoundDrawables()[2]; if (clearDrawable == null) { return; } if (isDownIn) { clearDrawable.setState(new int[]{android.R.attr.state_checked}); } else { clearDrawable.setState(new int[]{}); } } public void checkEdit(boolean focused) { if (showClear) { final Drawable[] compoundDrawables = getCompoundDrawables(); if (TextUtils.isEmpty(getText()) || !focused) { if (compoundDrawables[2] != null) { setCompoundDrawablesWithIntrinsicBounds(compoundDrawables[0], compoundDrawables[1], null, compoundDrawables[3]); } } else { setError(null); setCompoundDrawablesWithIntrinsicBounds(compoundDrawables[0], compoundDrawables[1], getClearDrawable(), compoundDrawables[3]); } } } private boolean checkClear(float x, float y) { return clearRect.contains(((int) x), (int) y); } @Override public void setText(CharSequence text, BufferType type) { super.setText(text, type); checkEdit(isFocused()); } @Override protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { super.onTextChanged(text, start, lengthBefore, lengthAfter); checkEdit(isFocused()); if (enableMention) { checkMentionString(); } if (isInputTypeNumber()) { if (!TextUtils.isEmpty(text)) { Float value; try { value = Float.valueOf(String.valueOf(text)); } catch (Exception e) { value = 0f; } if (value > mMaxNumber) { String maxValue; if (isInputTypeDecimal()) { maxValue = Float.valueOf(mMaxNumber).toString(); } else { maxValue = String.valueOf(Float.valueOf(mMaxNumber).intValue()); } resetSelectionText(maxValue); setSelection(maxValue.length()); } if (isInputTypeDecimal()) { String string = String.valueOf(text); int lastIndexOf = string.lastIndexOf("."); if (lastIndexOf != -1 && string.length() - lastIndexOf - 1 > mDecimalCount) { resetSelectionText(string.substring(0, lastIndexOf + mDecimalCount + 1)); } } if (text.length() > 1) { if (text.charAt(0) == '0' && text.charAt(1) != '.') { resetSelectionText(String.valueOf(text.subSequence(1, text.length()))); } } } } } private boolean isInputTypeNumber() { return (getInputType() & EditorInfo.TYPE_CLASS_NUMBER) == EditorInfo.TYPE_CLASS_NUMBER; } private boolean isInputTypeDecimal() { return (getInputType() & EditorInfo.TYPE_NUMBER_FLAG_DECIMAL) == EditorInfo.TYPE_NUMBER_FLAG_DECIMAL; } private void resetSelectionText(String text) { int start = getSelectionStart(); setText(text); setSelection(Math.min(start, text.length())); } public float getInputNumber() { Float value; try { value = Float.valueOf(getText().toString()); } catch (Exception e) { value = 0f; } return value; } @Override protected void onSelectionChanged(int selStart, int selEnd) { super.onSelectionChanged(selStart, selEnd); if (!enableMention) { return; } //avoid infinite recursion after calling setSelection() if (mLastSelectedRange != null && mLastSelectedRange.isEqual(selStart, selEnd)) { return; } //if user cancel a selection of show string, reset the state of 'mIsSelected' Range closestRange = getRangeOfClosestMentionString(selStart, selEnd); if (closestRange != null && closestRange.to == selEnd) { mIsSelected = false; } Range nearbyRange = getRangeOfNearbyMentionString(selStart, selEnd); //if there is no show string nearby the cursor, just skip if (nearbyRange == null) { return; } //forbid cursor located in the show string. if (selStart == selEnd) { setSelection(nearbyRange.getAnchorPosition(selStart)); } else { if (selEnd < nearbyRange.to) { setSelection(selStart, nearbyRange.to); } if (selStart > nearbyRange.from) { setSelection(nearbyRange.from, selEnd); } } } private boolean hasPasswordTransformation() { return this.getTransformationMethod() instanceof PasswordTransformationMethod; } public void showPassword() { final int selection = getSelectionEnd(); setTransformationMethod(null); setSelection(selection); } public void hidePassword() { final int selection = getSelectionEnd(); setTransformationMethod(PasswordTransformationMethod.getInstance()); setSelection(selection); } void passwordVisibilityToggleRequested() { final int selection = getSelectionEnd(); if (hasPasswordTransformation()) { setTransformationMethod(null); } else { setTransformationMethod(PasswordTransformationMethod.getInstance()); } // And restore the cursor position setSelection(selection); } public boolean isPhone() { return isPhone(string()); } public boolean isPassword() { final String string = string().trim(); return !TextUtils.isEmpty(string) && string.matches("^[a-zA-Z0-9_-]{6,12}$"); } public boolean isSoftKeyboardShow() { int screenHeight = getScreenHeightPixels(); int keyboardHeight = getSoftKeyboardHeight(); return screenHeight != keyboardHeight && keyboardHeight > 100; } public void hideSoftInput() { InputMethodManager manager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); manager.hideSoftInputFromWindow(getWindowToken(), 0); } public void setAutoHideSoftInput(boolean autoHideSoftInput) { this.autoHideSoftInput = autoHideSoftInput; } public int getSoftKeyboardHeight() { int screenHeight = getScreenHeightPixels(); Rect rect = new Rect(); getWindowVisibleDisplayFrame(rect); int visibleBottom = rect.bottom; return screenHeight - visibleBottom; } private int getScreenHeightPixels() { return getResources().getDisplayMetrics().heightPixels; } public int length() { return string().length(); } public String string() { String rawText = getText().toString().trim(); String tipText = mInputTipText.trim(); if (TextUtils.isEmpty(rawText)) { return rawText; } else if (TextUtils.isEmpty(tipText)) { return rawText; } else { return tipText; } } public boolean isEmpty() { return TextUtils.isEmpty(string()); } public void setMaxLength(int length) { InputFilter[] filters = getFilters(); boolean have = false; InputFilter.LengthFilter lengthFilter = new InputFilter.LengthFilter(length); for (int i = 0; i < filters.length; i++) { InputFilter filter = filters[i]; if (filter instanceof InputFilter.LengthFilter) { have = true; filters[i] = lengthFilter; setFilters(filters); break; } } if (!have) { addFilter(lengthFilter); } } @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { return new HackInputConnection(super.onCreateInputConnection(outAttrs), true, this); } public void addMention(String mention) { addMention(mention, true); } /** * @param auto true, */ public void addMention(String mention, boolean auto) { int start = getSelectionStart(); boolean insetAt = false; if (start == 0 || (start > 0 && '@' != getText().charAt(start - 1))) { // mention = "@" + mention;//@, @ insetAt = true; } if (auto) { if (isContains(mention)) { if ('@' == getText().charAt(start - 1)) { deleteLast(start); } } else { mAllMention.add(mention); insert((insetAt ? '@' : "") + mention + ' '); } } else { mAllMention.add(mention); } } /** * text */ public void insert(int where, CharSequence text) { if (text == null) { return; } int start = getSelectionStart(); int end = getSelectionEnd(); int length = text.length(); if (start == end) { getText().insert(where, text); setSelection(where + length, where + length); } else { getText().replace(start, end, text, 0, length); setSelection(start + length, start + length); } } public void insert(CharSequence text) { insert(getSelectionStart(), text); } public boolean isContains(String mention) { return mAllMention.contains(mention); } public void removeMention(String mention) { mAllMention.remove(mention); } public void deleteLast(int position) { Editable text = getText(); if (text != null && text.length() >= position) { text.delete(position - 1, position); } } public List<String> getAllMention() { return mAllMention; } public void setOnMentionInputListener(OnMentionInputListener onMentionInputListener) { enableMention = true; if (mOnMentionInputListener == null) { addTextChangedListener(new MentionTextWatcher()); //@span //setMovementMethod(LinkMovementMethod.getInstance()); } mOnMentionInputListener = onMentionInputListener; } private Range getRangeOfClosestMentionString(int selStart, int selEnd) { if (mRangeArrayList == null) { return null; } for (Range range : mRangeArrayList) { if (range.contains(selStart, selEnd)) { return range; } } return null; } private Range getRangeOfNearbyMentionString(int selStart, int selEnd) { if (mRangeArrayList == null) { return null; } for (Range range : mRangeArrayList) { if (range.isWrappedBy(selStart, selEnd)) { return range; } } return null; } //@span private void checkMentionString() { //reset state mIsSelected = false; if (mRangeArrayList != null) { mRangeArrayList.clear(); } Editable spannableText = getText(); if (mAllMention.isEmpty() || spannableText == null || TextUtils.isEmpty(spannableText.toString())) { mAllMention.clear(); return; } //remove previous spans MentionSpan[] oldSpans = spannableText.getSpans(0, spannableText.length(), MentionSpan.class); for (MentionSpan oldSpan : oldSpans) { spannableText.removeSpan(oldSpan); } //find show string and color it int lastMentionIndex = -1; String text = spannableText.toString(); //, , List List<String> mentions = new ArrayList<>(); for (String mention : mAllMention) { Matcher matcher = Pattern.compile("@" + mention).matcher(text); boolean isFind = false; while (matcher.find()) { isFind = true; String mentionText = matcher.group(); int start; if (lastMentionIndex != -1) { start = text.indexOf(mentionText, lastMentionIndex); } else { start = text.indexOf(mentionText); } int end = start + mentionText.length(); spannableText.setSpan(new MentionSpan(text.substring(start, end)), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); lastMentionIndex = end; //recordRunnable all show-string's position mRangeArrayList.add(new Range(start, end)); } if (!isFind) { String temp = "@" + mention; if (text.contains(temp)) { int start = text.indexOf(temp); int end = start + temp.length(); spannableText.setSpan(new MentionSpan(text.substring(start, end)), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); mRangeArrayList.add(new Range(start, end)); isFind = true; } } if (isFind) { mentions.add(mention); } } mAllMention.clear(); mAllMention.addAll(mentions); if (mOnMentionInputListener != null) { mOnMentionInputListener.onMentionTextChanged(mAllMention); } } public String fixMentionString(getIdFromUserName getIdFromUserName) { String string = string(); List<String> allMention = getAllMention(); for (String s : allMention) { string = string.replaceAll("@" + s.replaceAll("\\(", "\\\\(").replaceAll("\\)", "\\\\)"), createStringWithUserName(getIdFromUserName.userId(s))); } return string; } public String fixShowMentionString(getIdFromUserName getIdFromUserName) { String string = string(); List<String> allMention = getAllMention(); for (String s : allMention) { string = string.replaceAll("@" + s.replaceAll("\\(", "\\\\(").replaceAll("\\)", "\\\\)"), createShowString(getIdFromUserName.userId(s), "@" + s)); } return string; } private String createStringWithUserName(String id) { return "<m>" + id + "</m>"; } private String createShowString(String id, String name) { return String.format(Locale.CHINA, "<m id='%s'>%s</m>", id, name);// "<m>" + id + "</m>";//<m id='60763'>@i<\/m> } @Override public void setError(CharSequence error) { super.setError(error); } @Override public void setError(CharSequence error, Drawable icon) { requestFocus(); super.setError(error, icon); } public void setExText(CharSequence text) { requestFocus(); setText(text); setSelection(TextUtils.isEmpty(text) ? 0 : text.length()); } public void error() { Anim.band(this); } public boolean checkEmpty() { return checkEmpty(false); } public boolean checkEmpty(boolean checkPhone) { if (isEmpty()) { error(); requestFocus(); if (!isSoftKeyboardShow()) { if (getParent() instanceof FrameLayout && getParent().getParent() instanceof TextInputLayout) { postDelayed(new Runnable() { @Override public void run() { RSoftInputLayout.showSoftInput(ExEditText.this); } }, 200); } else { RSoftInputLayout.showSoftInput(ExEditText.this); } } return true; } if (checkPhone) { if (isPhone()) { } else { error(); requestFocus(); return true; } } return false; } public boolean checkMinLength(int minLength) { if (checkEmpty()) { return true; } if (string().length() < minLength) { error(); requestFocus(); return true; } return false; } public void setIsPassword(boolean isPassword) { int inputType = getInputType(); if (isPassword) { setInputType(inputType | EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD); } else { setInputType(inputType & ~EditorInfo.TYPE_TEXT_VARIATION_PASSWORD); } } public void setIsText(boolean isText) { int inputType = getInputType(); if (isText) { setIsPassword(false); setInputType(EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS); } else { setInputType(inputType & ~EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS); } } public void setIsPhone(boolean isPhone, int maxLength) { int inputType = getInputType(); if (isPhone) { setInputType(inputType | EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_CLASS_NUMBER); } else { setInputType(inputType & ~EditorInfo.TYPE_CLASS_NUMBER); } if (maxLength < 0) { maxLength = Integer.MAX_VALUE; } setMaxLength(maxLength); } public void setLeftString(String leftString) { mLeftString = leftString; if (!TextUtils.isEmpty(mLeftString)) { float textWidth = mTextPaint.getTextWidth(mLeftString); mDrawLeftOffset = (int) textWidth + mLeftOffset; setPadding(mPaddingLeft + mDrawLeftOffset, getPaddingTop(), getPaddingRight(), getPaddingBottom()); } else { setPadding(mPaddingLeft, getPaddingTop(), getPaddingRight(), getPaddingBottom()); } } public void setInputTipText(String inputTipText) { mInputTipTextList.clear(); mInputTipTextList.add(inputTipText); } public void setInputTipTextList(List<String> list) { mInputTipTextList.clear(); mInputTipTextList.addAll(list); } public interface getIdFromUserName { String userId(String userName); } /** * Listener for '@' character */ public interface OnMentionInputListener { /** * call when '@' character is inserted into EditText, @, */ void onMentionCharacterInput(); void onMentionTextChanged(List<String> allMention); } /** * {@code @}Span */ public static class MentionSpan extends ClickableSpan { String mention; public MentionSpan(String mention) { this.mention = mention; } @Override public void onClick(View widget) { L.i("onClick @: " + mention); } @Override public void updateDrawState(TextPaint ds) { ds.bgColor = RApplication.getApp().getResources().getColor(R.color.theme_color_primary_dark_tran3); //ds.setColor(getResources().getColor(R.color.theme_color_accent)); } } private class MentionTextWatcher implements TextWatcher { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int index, int i1, int count) { if (!enableCallback) { return; } if (count == 1 && !TextUtils.isEmpty(charSequence)) { char mentionChar = charSequence.toString().charAt(index); if ('@' == mentionChar && mOnMentionInputListener != null) { mOnMentionInputListener.onMentionCharacterInput(); } } } @Override public void afterTextChanged(Editable editable) { //, BUG if (editable.length() > 0) { setMovementMethod(LinkMovementMethod.getInstance()); } else { setMovementMethod(getDefaultMovementMethod()); } } } private class HackInputConnection extends InputConnectionWrapper { private ExEditText editText; public HackInputConnection(InputConnection target, boolean mutable, ExEditText editText) { super(target, mutable); this.editText = editText; } @Override public boolean commitText(CharSequence text, int newCursorPosition) { //editText.getText(); return super.commitText(text, newCursorPosition); } @Override public boolean sendKeyEvent(KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_DEL) { int selectionStart = editText.getSelectionStart(); int selectionEnd = editText.getSelectionEnd(); Range closestRange = getRangeOfClosestMentionString(selectionStart, selectionEnd); if (closestRange == null) { mIsSelected = false; return super.sendKeyEvent(event); } //if show string has been selected or the cursor is at the beginning of show string, just use default action(delete) if (mIsSelected || selectionStart == closestRange.from) { mIsSelected = false; return super.sendKeyEvent(event); } else { //select the show string mIsSelected = true; mLastSelectedRange = closestRange; setSelection(closestRange.to, closestRange.from); return super.sendKeyEvent(event); } //return true; } return super.sendKeyEvent(event); } @Override public boolean deleteSurroundingText(int beforeLength, int afterLength) { if (beforeLength == 1 && afterLength == 0) { return sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL)) && sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL)); } return super.deleteSurroundingText(beforeLength, afterLength); } } /** * {@code @} */ private class Range { int from; int to; public Range(int from, int to) { this.from = from; this.to = to; } public boolean isWrappedBy(int start, int end) { return (start > from && start < to) || (end > from && end < to); } public boolean contains(int start, int end) { return from <= start && to >= end; } public boolean isEqual(int start, int end) { return (from == start && to == end) || (from == end && to == start); } public int getAnchorPosition(int value) { if ((value - from) - (to - value) > 0) { return to; } else { return from; } } } }
package com.angcyo.uiview.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.design.widget.TextInputLayout; import android.support.v4.content.res.ResourcesCompat; import android.support.v7.widget.AppCompatEditText; import android.text.Editable; import android.text.InputFilter; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextPaint; import android.text.TextUtils; import android.text.TextWatcher; import android.text.method.ArrowKeyMovementMethod; import android.text.method.LinkMovementMethod; import android.text.method.PasswordTransformationMethod; import android.text.style.ClickableSpan; import android.util.AttributeSet; import android.view.Gravity; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputConnectionWrapper; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.TextView; import com.angcyo.library.utils.Anim; import com.angcyo.library.utils.L; import com.angcyo.uiview.R; import com.angcyo.uiview.RApplication; import com.angcyo.uiview.kotlin.ExKt; import com.angcyo.uiview.skin.SkinHelper; import com.angcyo.uiview.utils.RTextPaint; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ExEditText extends AppCompatEditText { Rect clearRect = new Rect(); boolean isDownIn = false; Drawable clearDrawable; boolean showClear = true; boolean isPassword = false; boolean handleTouch = false; long downTime = 0; /** * , touch down */ boolean autoHideSoftInput = false; List<String> mAllMention = new ArrayList<>(5); /** * , inputType EditorInfo.TYPE_CLASS_NUMBER */ float mMaxNumber = Float.MAX_VALUE; /** * , inputType EditorInfo.TYPE_NUMBER_FLAG_DECIMAL */ int mDecimalCount = Integer.MAX_VALUE; private List<Range> mRangeArrayList = new ArrayList<>(5); private OnMentionInputListener mOnMentionInputListener; private boolean mIsSelected = false; private Range mLastSelectedRange; /** * @, ,{@link #setOnMentionInputListener(OnMentionInputListener)}, */ private boolean enableMention = false; private boolean enableCallback = true; private RTextPaint mTextPaint; private String mLeftString; private String mInputTipText = ""; /** * hint, hint */ private String mRHintText; private List<String> mInputTipTextList = new ArrayList<>(); private int mLeftOffset; private int mDrawLeftOffset; private int mPaddingLeft; public ExEditText(Context context) { super(context); } public ExEditText(Context context, AttributeSet attrs) { super(context, attrs); initView(context, attrs); } public ExEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(context, attrs); } /** * TextView@ */ public static void checkMentionSpannable(TextView textView, String content, List<String> allMention) { if (textView == null) { return; } if (allMention.isEmpty() || TextUtils.isEmpty(content)) { textView.setText(content); textView.setMovementMethod(ArrowKeyMovementMethod.getInstance()); return; } SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(content); int lastMentionIndex = -1; for (String mention : allMention) { Matcher matcher = Pattern.compile("@" + mention).matcher(content); while (matcher.find()) { String mentionText = matcher.group(); int start; if (lastMentionIndex != -1) { start = content.indexOf(mentionText, lastMentionIndex); } else { start = content.indexOf(mentionText); } int end = start + mentionText.length(); spannableStringBuilder.setSpan(new MentionSpan(mentionText), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } textView.setText(spannableStringBuilder); textView.setMovementMethod(LinkMovementMethod.getInstance()); } public static boolean canVerticalScroll(EditText editText) { int scrollY = editText.getScrollY(); int scrollRange = editText.getLayout().getHeight(); int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() - editText.getCompoundPaddingBottom(); int scrollDifference = scrollRange - scrollExtent; if (scrollDifference == 0) { return false; } return (scrollY > 0) || (scrollY < scrollDifference - 1); } /** * string */ public static boolean isPhone(String string) { if (TextUtils.isEmpty(string)) { return false; } final String phone = string.trim(); return !TextUtils.isEmpty(phone) && phone.matches("^1[3-8]\\d{9}$"); } public boolean unableCallback() { enableCallback = false; return enableCallback; } public boolean enableCallback() { enableCallback = true; return enableCallback; } public void setEnableMention(boolean enableMention) { this.enableMention = enableMention; } public void setMaxNumber(float mMaxNumber) { this.mMaxNumber = mMaxNumber; } public void setDecimalCount(int mDecimalCount) { this.mDecimalCount = mDecimalCount; } private void initView(Context context, AttributeSet attrs) { mPaddingLeft = getPaddingLeft(); ensurePaint(); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExEditText); int color = typedArray.getColor(R.styleable.ExEditText_r_left_text_color, getCurrentTextColor()); mLeftOffset = typedArray.getDimensionPixelOffset(R.styleable.ExEditText_r_left_text_offset, getResources().getDimensionPixelOffset(R.dimen.base_ldpi)); String string = typedArray.getString(R.styleable.ExEditText_r_left_text); mRHintText = typedArray.getString(R.styleable.ExEditText_r_hint_text); mMaxNumber = typedArray.getFloat(R.styleable.ExEditText_r_max_number, mMaxNumber); mDecimalCount = typedArray.getInteger(R.styleable.ExEditText_r_decimal_count, mDecimalCount); typedArray.recycle(); setLeftString(string); mTextPaint.setTextColor(color); } public boolean canVerticalScroll() { return canVerticalScroll(this); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (!TextUtils.isEmpty(mLeftString)) { //mTextPaint.drawOriginText(canvas, mLeftString, getPaddingLeft(), getMeasuredHeight() - getPaddingBottom()); canvas.save(); canvas.translate(-getPaddingLeft() + getScrollX(), 0); mTextPaint.drawOriginText(canvas, mLeftString, getPaddingLeft() + mPaddingLeft, (getMeasuredHeight() - getPaddingBottom() - getPaddingTop()) / 2 + getPaddingTop() + mTextPaint.getTextHeight() / 2); canvas.restore(); } if (isFocused()) { if (isInputTipPattern()) { canvas.save(); final TextPaint textPaint = getPaint(); textPaint.setColor(SkinHelper.getTranColor(getCurrentTextColor(), 0x40)); int lineHeight = getLayout().getLineDescent(0) - getLayout().getLineAscent(0); int top = getMeasuredHeight() / 2 - lineHeight / 2; int bottom = getPaddingTop() + (getMeasuredHeight() - getPaddingTop() - getPaddingBottom()) / 2 + lineHeight / 2; canvas.clipRect(textPaint.measureText(String.valueOf(getText()), 0, getText().length()) + getInputTipDrawLeft(), 0, getMeasuredWidth(), getMeasuredHeight()); canvas.drawText(mInputTipText, getInputTipDrawLeft(), bottom - getLayout().getLineDescent(0), textPaint); canvas.restore(); } } //RHint if (TextUtils.isEmpty(getText()) && TextUtils.isEmpty(getHint()) && !TextUtils.isEmpty(mRHintText)) { canvas.save(); final TextPaint textPaint = getPaint(); // textPaint.setColor(getCurrentHintTextColor()); textPaint.setColor(Color.RED); int lineHeight = getLayout().getLineDescent(0) - getLayout().getLineAscent(0); int bottom = getPaddingTop() + (getMeasuredHeight() - getPaddingTop() - getPaddingBottom()) / 2 + lineHeight / 2; float x = 0, y = 0; y = bottom - getLayout().getLineDescent(0); if (ExKt.have(getGravity(), Gravity.LEFT)) { x = getInputTipDrawLeft(); } else if (ExKt.have(getGravity(), Gravity.RIGHT)) { //rightinputType ,BUG. x = getMeasuredWidth() - getInputTipDrawRight() - textPaint.measureText(mRHintText); } canvas.drawText(mRHintText, x, y, textPaint); canvas.restore(); } } private int getInputTipDrawLeft() { int left = getPaddingLeft(); Drawable[] drawables = getCompoundDrawables(); if (drawables[0] != null) { left += drawables[0].getIntrinsicWidth(); left += getCompoundDrawablePadding(); } return left; } private int getInputTipDrawRight() { int right = getPaddingRight(); Drawable[] drawables = getCompoundDrawables(); if (drawables[2] != null) { right += drawables[2].getIntrinsicWidth(); right += getCompoundDrawablePadding(); } return right; } private boolean isCenterVertical() { return Gravity.CENTER_VERTICAL == (getGravity() & Gravity.CENTER_VERTICAL); } private boolean isInputTipPattern() { String text = getText().toString(); // return isCenterVertical() /*Gravity.CENTER_VERTICAL*/ && // !TextUtils.isEmpty(mInputTipText) && // !TextUtils.isEmpty(text) && // mInputTipText.startsWith(text) && // !TextUtils.equals(mInputTipText, text) ; mInputTipText = ""; for (String s : mInputTipTextList) { if (s.startsWith(text)) { mInputTipText = s; break; } } return isCenterVertical() /*Gravity.CENTER_VERTICAL*/ && !mInputTipTextList.isEmpty() && !TextUtils.isEmpty(text) && !TextUtils.isEmpty(mInputTipText) && !TextUtils.equals(mInputTipText, text) ; } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); initView(); ensurePaint(); } @Override public void setTag(Object tag) { super.setTag(tag); initView(); } private void ensurePaint() { if (mTextPaint == null) { mTextPaint = new RTextPaint(getPaint()); } } public void setInputText(String text) { setText(text); setSelection(TextUtils.isEmpty(text) ? 0 : text.length()); //checkEdit(true); } private void initView() { Object tag = getTag(); if (tag != null) { String tagString = String.valueOf(tag); if (tagString.contains("emoji")) { //emoji addFilter(new EmojiFilter()); } if (tagString.contains("password")) { isPassword = true; } if (tagString.contains("hide")) { showClear = false; } else if (tagString.contains("show")) { showClear = true; } } getClearDrawable(); } private Drawable getClearDrawable() { if (showClear && clearDrawable == null) { clearDrawable = ResourcesCompat.getDrawable( getResources(), R.drawable.base_edit_delete_selector, getContext().getTheme()); if (getCompoundDrawablePadding() == 0) { setCompoundDrawablePadding((int) (4 * getResources().getDisplayMetrics().density)); } } return clearDrawable; } private void addFilter(InputFilter filter) { final InputFilter[] filters = getFilters(); final InputFilter[] newFilters = new InputFilter[filters.length + 1]; System.arraycopy(filters, 0, newFilters, 0, filters.length); newFilters[filters.length] = filter; setFilters(newFilters); } @Override protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { super.onFocusChanged(focused, direction, previouslyFocusedRect); checkEdit(focused); if (!focused) { if (isInputTipPattern()) { setText(mInputTipText); } } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); if (showClear) { clearRect.set(w - getPaddingRight() - getClearDrawable().getIntrinsicWidth(), getPaddingTop(), w - getPaddingRight(), Math.min(w, h) - getPaddingBottom()); } } @Override public boolean onTouchEvent(MotionEvent event) { int action = event.getAction(); if (showClear && isFocused()) { if (action == MotionEvent.ACTION_DOWN) { isDownIn = checkClear(event.getX(), event.getY()); updateState(isDownIn); } else if (action == MotionEvent.ACTION_MOVE) { updateState(checkClear(event.getX(), event.getY())); } else if (action == MotionEvent.ACTION_UP) { updateState(false); if (isDownIn && checkClear(event.getX(), event.getY())) { if (!TextUtils.isEmpty(getText())) { setText(""); return true; } } isDownIn = false; if (autoHideSoftInput && isSoftKeyboardShow()) { post(new Runnable() { @Override public void run() { hideSoftInput(); } }); } } else if (action == MotionEvent.ACTION_CANCEL) { updateState(false); isDownIn = false; } } //L.e("call: onTouchEvent([event])-> canVerticalScroll:" + canVerticalScroll(this)); // if (isPassword) { // if (action == MotionEvent.ACTION_DOWN) { // downTime = System.currentTimeMillis(); // } else if (action == MotionEvent.ACTION_MOVE) { // if ((System.currentTimeMillis() - downTime) > 100) { // if (isDownIn) { // hidePassword(); // } else { // showPassword(); // } else if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { // hidePassword(); return super.onTouchEvent(event); } private void updateState(boolean isDownIn) { final Drawable clearDrawable = getCompoundDrawables()[2]; if (clearDrawable == null) { return; } if (isDownIn) { clearDrawable.setState(new int[]{android.R.attr.state_checked}); } else { clearDrawable.setState(new int[]{}); } } public void checkEdit(boolean focused) { if (showClear) { final Drawable[] compoundDrawables = getCompoundDrawables(); if (TextUtils.isEmpty(getText()) || !focused) { if (compoundDrawables[2] != null) { setCompoundDrawablesWithIntrinsicBounds(compoundDrawables[0], compoundDrawables[1], null, compoundDrawables[3]); } } else { setError(null); setCompoundDrawablesWithIntrinsicBounds(compoundDrawables[0], compoundDrawables[1], getClearDrawable(), compoundDrawables[3]); } } } private boolean checkClear(float x, float y) { return clearRect.contains(((int) x), (int) y); } @Override public void setText(CharSequence text, BufferType type) { super.setText(text, type); checkEdit(isFocused()); } @Override protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { super.onTextChanged(text, start, lengthBefore, lengthAfter); checkEdit(isFocused()); if (enableMention) { checkMentionString(); } if (isInputTypeNumber()) { if (!TextUtils.isEmpty(text)) { Float value; try { value = Float.valueOf(String.valueOf(text)); } catch (Exception e) { value = 0f; } if (value > mMaxNumber) { String maxValue; if (isInputTypeDecimal()) { maxValue = Float.valueOf(mMaxNumber).toString(); } else { maxValue = String.valueOf(Float.valueOf(mMaxNumber).intValue()); } resetSelectionText(maxValue); setSelection(maxValue.length()); } if (isInputTypeDecimal()) { String string = String.valueOf(text); int lastIndexOf = string.lastIndexOf("."); if (lastIndexOf != -1 && string.length() - lastIndexOf - 1 > mDecimalCount) { resetSelectionText(string.substring(0, lastIndexOf + mDecimalCount + 1)); } } if (text.length() > 1) { if (text.charAt(0) == '0' && text.charAt(1) != '.') { resetSelectionText(String.valueOf(text.subSequence(1, text.length()))); } } } } } private boolean isInputTypeNumber() { return (getInputType() & EditorInfo.TYPE_CLASS_NUMBER) == EditorInfo.TYPE_CLASS_NUMBER; } private boolean isInputTypeDecimal() { return (getInputType() & EditorInfo.TYPE_NUMBER_FLAG_DECIMAL) == EditorInfo.TYPE_NUMBER_FLAG_DECIMAL; } private void resetSelectionText(String text) { int start = getSelectionStart(); setText(text); setSelection(Math.min(start, text.length())); } public float getInputNumber() { Float value; try { value = Float.valueOf(getText().toString()); } catch (Exception e) { value = 0f; } return value; } @Override protected void onSelectionChanged(int selStart, int selEnd) { super.onSelectionChanged(selStart, selEnd); if (!enableMention) { return; } //avoid infinite recursion after calling setSelection() if (mLastSelectedRange != null && mLastSelectedRange.isEqual(selStart, selEnd)) { return; } //if user cancel a selection of show string, reset the state of 'mIsSelected' Range closestRange = getRangeOfClosestMentionString(selStart, selEnd); if (closestRange != null && closestRange.to == selEnd) { mIsSelected = false; } Range nearbyRange = getRangeOfNearbyMentionString(selStart, selEnd); //if there is no show string nearby the cursor, just skip if (nearbyRange == null) { return; } //forbid cursor located in the show string. if (selStart == selEnd) { setSelection(nearbyRange.getAnchorPosition(selStart)); } else { if (selEnd < nearbyRange.to) { setSelection(selStart, nearbyRange.to); } if (selStart > nearbyRange.from) { setSelection(nearbyRange.from, selEnd); } } } private boolean hasPasswordTransformation() { return this.getTransformationMethod() instanceof PasswordTransformationMethod; } public void showPassword() { final int selection = getSelectionEnd(); setTransformationMethod(null); setSelection(selection); } public void hidePassword() { final int selection = getSelectionEnd(); setTransformationMethod(PasswordTransformationMethod.getInstance()); setSelection(selection); } void passwordVisibilityToggleRequested() { final int selection = getSelectionEnd(); if (hasPasswordTransformation()) { setTransformationMethod(null); } else { setTransformationMethod(PasswordTransformationMethod.getInstance()); } // And restore the cursor position setSelection(selection); } public boolean isPhone() { return isPhone(string()); } public boolean isPassword() { final String string = string().trim(); return !TextUtils.isEmpty(string) && string.matches("^[a-zA-Z0-9_-]{6,12}$"); } public boolean isSoftKeyboardShow() { int screenHeight = getScreenHeightPixels(); int keyboardHeight = getSoftKeyboardHeight(); return screenHeight != keyboardHeight && keyboardHeight > 100; } public void hideSoftInput() { InputMethodManager manager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); manager.hideSoftInputFromWindow(getWindowToken(), 0); } public void setAutoHideSoftInput(boolean autoHideSoftInput) { this.autoHideSoftInput = autoHideSoftInput; } public int getSoftKeyboardHeight() { int screenHeight = getScreenHeightPixels(); Rect rect = new Rect(); getWindowVisibleDisplayFrame(rect); int visibleBottom = rect.bottom; return screenHeight - visibleBottom; } private int getScreenHeightPixels() { return getResources().getDisplayMetrics().heightPixels; } public int length() { return string().length(); } public String string() { String rawText = getText().toString().trim(); String tipText = mInputTipText.trim(); if (TextUtils.isEmpty(rawText)) { return rawText; } else if (TextUtils.isEmpty(tipText)) { return rawText; } else { return tipText; } } public boolean isEmpty() { return TextUtils.isEmpty(string()); } public void setMaxLength(int length) { InputFilter[] filters = getFilters(); boolean have = false; InputFilter.LengthFilter lengthFilter = new InputFilter.LengthFilter(length); for (int i = 0; i < filters.length; i++) { InputFilter filter = filters[i]; if (filter instanceof InputFilter.LengthFilter) { have = true; filters[i] = lengthFilter; setFilters(filters); break; } } if (!have) { addFilter(lengthFilter); } } @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { return new HackInputConnection(super.onCreateInputConnection(outAttrs), true, this); } public void addMention(String mention) { addMention(mention, true); } /** * @param auto true, */ public void addMention(String mention, boolean auto) { int start = getSelectionStart(); boolean insetAt = false; if (start == 0 || (start > 0 && '@' != getText().charAt(start - 1))) { // mention = "@" + mention;//@, @ insetAt = true; } if (auto) { if (isContains(mention)) { if ('@' == getText().charAt(start - 1)) { deleteLast(start); } } else { mAllMention.add(mention); insert((insetAt ? '@' : "") + mention + ' '); } } else { mAllMention.add(mention); } } /** * text */ public void insert(int where, CharSequence text) { if (text == null) { return; } int start = getSelectionStart(); int end = getSelectionEnd(); int length = text.length(); if (start == end) { getText().insert(where, text); setSelection(where + length, where + length); } else { getText().replace(start, end, text, 0, length); setSelection(start + length, start + length); } } public void insert(CharSequence text) { insert(getSelectionStart(), text); } public boolean isContains(String mention) { return mAllMention.contains(mention); } public void removeMention(String mention) { mAllMention.remove(mention); } public void deleteLast(int position) { Editable text = getText(); if (text != null && text.length() >= position) { text.delete(position - 1, position); } } public List<String> getAllMention() { return mAllMention; } public void setOnMentionInputListener(OnMentionInputListener onMentionInputListener) { enableMention = true; if (mOnMentionInputListener == null) { addTextChangedListener(new MentionTextWatcher()); //@span //setMovementMethod(LinkMovementMethod.getInstance()); } mOnMentionInputListener = onMentionInputListener; } private Range getRangeOfClosestMentionString(int selStart, int selEnd) { if (mRangeArrayList == null) { return null; } for (Range range : mRangeArrayList) { if (range.contains(selStart, selEnd)) { return range; } } return null; } private Range getRangeOfNearbyMentionString(int selStart, int selEnd) { if (mRangeArrayList == null) { return null; } for (Range range : mRangeArrayList) { if (range.isWrappedBy(selStart, selEnd)) { return range; } } return null; } //@span private void checkMentionString() { //reset state mIsSelected = false; if (mRangeArrayList != null) { mRangeArrayList.clear(); } Editable spannableText = getText(); if (mAllMention.isEmpty() || spannableText == null || TextUtils.isEmpty(spannableText.toString())) { mAllMention.clear(); return; } //remove previous spans MentionSpan[] oldSpans = spannableText.getSpans(0, spannableText.length(), MentionSpan.class); for (MentionSpan oldSpan : oldSpans) { spannableText.removeSpan(oldSpan); } //find show string and color it int lastMentionIndex = -1; String text = spannableText.toString(); //, , List List<String> mentions = new ArrayList<>(); for (String mention : mAllMention) { Matcher matcher = Pattern.compile("@" + mention).matcher(text); boolean isFind = false; while (matcher.find()) { isFind = true; String mentionText = matcher.group(); int start; if (lastMentionIndex != -1) { start = text.indexOf(mentionText, lastMentionIndex); } else { start = text.indexOf(mentionText); } int end = start + mentionText.length(); spannableText.setSpan(new MentionSpan(text.substring(start, end)), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); lastMentionIndex = end; //recordRunnable all show-string's position mRangeArrayList.add(new Range(start, end)); } if (!isFind) { String temp = "@" + mention; if (text.contains(temp)) { int start = text.indexOf(temp); int end = start + temp.length(); spannableText.setSpan(new MentionSpan(text.substring(start, end)), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); mRangeArrayList.add(new Range(start, end)); isFind = true; } } if (isFind) { mentions.add(mention); } } mAllMention.clear(); mAllMention.addAll(mentions); if (mOnMentionInputListener != null) { mOnMentionInputListener.onMentionTextChanged(mAllMention); } } public String fixMentionString(getIdFromUserName getIdFromUserName) { String string = string(); List<String> allMention = getAllMention(); for (String s : allMention) { string = string.replaceAll("@" + s.replaceAll("\\(", "\\\\(").replaceAll("\\)", "\\\\)"), createStringWithUserName(getIdFromUserName.userId(s))); } return string; } public String fixShowMentionString(getIdFromUserName getIdFromUserName) { String string = string(); List<String> allMention = getAllMention(); for (String s : allMention) { string = string.replaceAll("@" + s.replaceAll("\\(", "\\\\(").replaceAll("\\)", "\\\\)"), createShowString(getIdFromUserName.userId(s), "@" + s)); } return string; } private String createStringWithUserName(String id) { return "<m>" + id + "</m>"; } private String createShowString(String id, String name) { return String.format(Locale.CHINA, "<m id='%s'>%s</m>", id, name);// "<m>" + id + "</m>";//<m id='60763'>@i<\/m> } @Override public void setError(CharSequence error) { super.setError(error); } @Override public void setError(CharSequence error, Drawable icon) { requestFocus(); super.setError(error, icon); } public void setExText(CharSequence text) { requestFocus(); setText(text); setSelection(TextUtils.isEmpty(text) ? 0 : text.length()); } public void error() { Anim.band(this); } public boolean checkEmpty() { return checkEmpty(false); } public boolean checkEmpty(boolean checkPhone) { if (isEmpty()) { error(); requestFocus(); if (!isSoftKeyboardShow()) { if (getParent() instanceof FrameLayout && getParent().getParent() instanceof TextInputLayout) { postDelayed(new Runnable() { @Override public void run() { RSoftInputLayout.showSoftInput(ExEditText.this); } }, 200); } else { RSoftInputLayout.showSoftInput(ExEditText.this); } } return true; } if (checkPhone) { if (isPhone()) { } else { error(); requestFocus(); return true; } } return false; } public boolean checkMinLength(int minLength) { if (checkEmpty()) { return true; } if (string().length() < minLength) { error(); requestFocus(); return true; } return false; } public void setIsPassword(boolean isPassword) { int inputType = getInputType(); if (isPassword) { setInputType(inputType | EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD); } else { setInputType(inputType & ~EditorInfo.TYPE_TEXT_VARIATION_PASSWORD); } } public void setIsText(boolean isText) { int inputType = getInputType(); if (isText) { setIsPassword(false); setInputType(EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS); } else { setInputType(inputType & ~EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS); } } public void setIsPhone(boolean isPhone, int maxLength) { int inputType = getInputType(); if (isPhone) { setInputType(inputType | EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_CLASS_NUMBER); } else { setInputType(inputType & ~EditorInfo.TYPE_CLASS_NUMBER); } if (maxLength < 0) { maxLength = Integer.MAX_VALUE; } setMaxLength(maxLength); } public void setLeftString(String leftString) { mLeftString = leftString; if (!TextUtils.isEmpty(mLeftString)) { float textWidth = mTextPaint.getTextWidth(mLeftString); mDrawLeftOffset = (int) textWidth + mLeftOffset; setPadding(mPaddingLeft + mDrawLeftOffset, getPaddingTop(), getPaddingRight(), getPaddingBottom()); } else { setPadding(mPaddingLeft, getPaddingTop(), getPaddingRight(), getPaddingBottom()); } } public void setInputTipText(String inputTipText) { mInputTipTextList.clear(); mInputTipTextList.add(inputTipText); } public void setInputTipTextList(List<String> list) { mInputTipTextList.clear(); mInputTipTextList.addAll(list); } public interface getIdFromUserName { String userId(String userName); } /** * Listener for '@' character */ public interface OnMentionInputListener { /** * call when '@' character is inserted into EditText, @, */ void onMentionCharacterInput(); void onMentionTextChanged(List<String> allMention); } /** * {@code @}Span */ public static class MentionSpan extends ClickableSpan { String mention; public MentionSpan(String mention) { this.mention = mention; } @Override public void onClick(View widget) { L.i("onClick @: " + mention); } @Override public void updateDrawState(TextPaint ds) { ds.bgColor = RApplication.getApp().getResources().getColor(R.color.theme_color_primary_dark_tran3); //ds.setColor(getResources().getColor(R.color.theme_color_accent)); } } private class MentionTextWatcher implements TextWatcher { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int index, int i1, int count) { if (!enableCallback) { return; } if (count == 1 && !TextUtils.isEmpty(charSequence)) { char mentionChar = charSequence.toString().charAt(index); if ('@' == mentionChar && mOnMentionInputListener != null) { mOnMentionInputListener.onMentionCharacterInput(); } } } @Override public void afterTextChanged(Editable editable) { //, BUG if (editable.length() > 0) { setMovementMethod(LinkMovementMethod.getInstance()); } else { setMovementMethod(getDefaultMovementMethod()); } } } private class HackInputConnection extends InputConnectionWrapper { private ExEditText editText; public HackInputConnection(InputConnection target, boolean mutable, ExEditText editText) { super(target, mutable); this.editText = editText; } @Override public boolean commitText(CharSequence text, int newCursorPosition) { //editText.getText(); return super.commitText(text, newCursorPosition); } @Override public boolean sendKeyEvent(KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_DEL) { int selectionStart = editText.getSelectionStart(); int selectionEnd = editText.getSelectionEnd(); Range closestRange = getRangeOfClosestMentionString(selectionStart, selectionEnd); if (closestRange == null) { mIsSelected = false; return super.sendKeyEvent(event); } //if show string has been selected or the cursor is at the beginning of show string, just use default action(delete) if (mIsSelected || selectionStart == closestRange.from) { mIsSelected = false; return super.sendKeyEvent(event); } else { //select the show string mIsSelected = true; mLastSelectedRange = closestRange; setSelection(closestRange.to, closestRange.from); return super.sendKeyEvent(event); } //return true; } return super.sendKeyEvent(event); } @Override public boolean deleteSurroundingText(int beforeLength, int afterLength) { if (beforeLength == 1 && afterLength == 0) { return sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL)) && sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL)); } return super.deleteSurroundingText(beforeLength, afterLength); } } /** * {@code @} */ private class Range { int from; int to; public Range(int from, int to) { this.from = from; this.to = to; } public boolean isWrappedBy(int start, int end) { return (start > from && start < to) || (end > from && end < to); } public boolean contains(int start, int end) { return from <= start && to >= end; } public boolean isEqual(int start, int end) { return (from == start && to == end) || (from == end && to == start); } public int getAnchorPosition(int value) { if ((value - from) - (to - value) > 0) { return to; } else { return from; } } } }
package net.glider.src.blocks; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; public class MaterialInvisble extends Material { public MaterialInvisble(MapColor p_i2113_1_) { super(p_i2113_1_); } public boolean isSolid() { return false; } /** * Will prevent grass from growing on dirt underneath and kill any grass below it if it returns true */ public boolean getCanBlockGrass() { return false; } /** * Returns if this material is considered solid or not */ public boolean blocksMovement() { return true; } }
package org.unipop.elastic.helpers; import org.elasticsearch.action.get.*; import org.elasticsearch.client.Client; import org.unipop.structure.BaseVertex; import java.util.*; public class LazyGetter { private static final int MAX_LAZY_GET = 50; private Client client; private TimingAccessor timing; private boolean executed = false; private HashMap<GetKey, List<BaseVertex>> keyToVertices = new HashMap(); public LazyGetter(Client client, TimingAccessor timing) { this.client = client; this.timing = timing; } public Boolean canRegister() { return !executed && keyToVertices.keySet().size() < MAX_LAZY_GET; } public void register(BaseVertex v, String label, String indexName) { if(executed) System.out.println("This LazyGetter has already been executed."); GetKey key = new GetKey(v.id(), label, indexName); List<BaseVertex> vertices = keyToVertices.get(key); if (vertices == null) { vertices = new ArrayList(); keyToVertices.put(key, vertices); } vertices.add(v); } public void execute() { if (executed) return; executed = true; timing.start("lazyMultiGet"); MultiGetRequestBuilder multiGetRequestBuilder = client.prepareMultiGet(); keyToVertices.keySet().forEach(key -> multiGetRequestBuilder.add(key.indexName, key.type, key.id)); MultiGetResponse multiGetItemResponses = multiGetRequestBuilder.execute().actionGet(); timing.stop("lazyMultiGet"); multiGetItemResponses.forEach(response -> { if (response.isFailed()) { System.out.println(response.getFailure().getMessage()); return; } if (!response.getResponse().isExists()) { return; } List<BaseVertex> vertices = keyToVertices.get(new GetKey(response.getId(), response.getType(), response.getIndex())); if (vertices == null) return; vertices.forEach(vertex -> vertex.applyLazyFields(response.getType(), response.getResponse().getSource())); }); keyToVertices = null; client = null; } private class GetKey { private final String id; private final String type; private final String indexName; public GetKey(Object id, String type, String indexName) { this.id = id.toString(); this.type = type; this.indexName = indexName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GetKey getKey = (GetKey) o; if (!id.equals(getKey.id)) return false; if (type != null && getKey.type != null && !type.equals(getKey.type)) return false; return indexName.equals(getKey.indexName); } @Override public int hashCode() { int result = id.hashCode(); result = 31 * result + indexName.hashCode(); return result; } } }
package net.imagej.updater.util; /** * A default implementation of the {@link Progress} interface. * * @author Johannes Schindelin */ public class StderrProgress implements Progress { protected final static boolean redirected = System.console() == null; protected final static String end = redirected ? "\n" : "\033[K\r"; protected String label; protected Object item; protected long lastShown, minShowDelay = 500; protected int lineWidth = -1, dotCounter = 0; private boolean skipProgress; public StderrProgress() {} public StderrProgress(final int lineWidth) { this.lineWidth = lineWidth; } protected void print(String label, final String rest) { if (lineWidth < 0) System.err.print(label + " " + rest + end); else { if (label.length() >= lineWidth - 3) label = label.substring(0, lineWidth - 3) + "..."; else { final int diff = label.length() + 1 + rest.length() - lineWidth; if (diff < 0) label += " " + rest; else label += (" " + rest).substring(0, rest.length() - diff - 3) + "..."; } System.err.print(label + end); } } protected boolean skipShow() { final long now = System.currentTimeMillis(); if (now - lastShown < minShowDelay) return true; lastShown = now; return false; } @Override public void setTitle(final String title) { label = title; skipProgress = redirected && "Checksummer".equals(title); } @Override public void setCount(final int count, final int total) { if (skipProgress || skipShow()) return; print(label, "" + count + "/" + total); } @Override public void addItem(final Object item) { this.item = item; if (skipProgress || skipShow()) return; print(label, "(" + item + ") "); } @Override public void setItemCount(final int count, final int total) { if (skipProgress || redirected || skipShow()) return; print(label, "(" + item + ") [" + count + "/" + total + "]"); } @Override public void itemDone(final Object item) { if (skipProgress) { if ((++dotCounter % 80) == 1 && dotCounter > 1) { System.err.print("\n"); } System.err.print("."); } else print(item.toString(), "done"); } @Override public void done() { if (skipProgress) System.err.print("\n"); print("Done:", label); System.err.println(""); } }
package net.morematerials.listeners; import net.morematerials.MoreMaterials; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.getspout.spout.block.SpoutCraftBlock; import org.getspout.spoutapi.inventory.SpoutItemStack; import org.getspout.spoutapi.material.Block; import org.getspout.spoutapi.material.block.GenericCustomBlock; import org.getspout.spoutapi.material.item.GenericCustomItem; public class MMListener implements Listener { private MoreMaterials plugin; public MMListener(MoreMaterials plugin) { this.plugin = plugin; } @EventHandler public void onBlockBreak(BlockBreakEvent event) { // Make sure we have a valid event. if (event.getPlayer() == null || event.getPlayer().getGameMode() == GameMode.CREATIVE) { return; } // Events for broken custom blocks. Block block = ((SpoutCraftBlock) event.getBlock()).getBlockType(); if (block instanceof GenericCustomBlock) { this.plugin.getHandlerManager().triggerHandlers("BlockBreak", ((GenericCustomBlock) block).getCustomId(), event); } // Events for the item held while breaking a block. SpoutItemStack stack = new SpoutItemStack(event.getPlayer().getItemInHand()); if (stack.getMaterial() instanceof GenericCustomItem) { this.plugin.getHandlerManager().triggerHandlers("HoldBlockBreak", ((GenericCustomItem) stack.getMaterial()).getCustomId(), event); } } @EventHandler public void onPlayerInteract(PlayerInteractEvent event) { // The click events for hold item. if (event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_BLOCK) { SpoutItemStack stack = new SpoutItemStack(event.getPlayer().getItemInHand()); if (stack.getMaterial() instanceof GenericCustomItem) { this.plugin.getHandlerManager().triggerHandlers("HoldLeftClick", ((GenericCustomItem) stack.getMaterial()).getCustomId(), event); } else if (stack.getMaterial() instanceof GenericCustomBlock) { this.plugin.getHandlerManager().triggerHandlers("HoldLeftClick", ((GenericCustomBlock) stack.getMaterial()).getCustomId(), event); } } else if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) { SpoutItemStack stack = new SpoutItemStack(event.getPlayer().getItemInHand()); if (stack.getMaterial() instanceof GenericCustomItem) { this.plugin.getHandlerManager().triggerHandlers("HoldRightClick", ((GenericCustomItem) stack.getMaterial()).getCustomId(), event); } else if (stack.getMaterial() instanceof GenericCustomBlock) { this.plugin.getHandlerManager().triggerHandlers("HoldRightClick", ((GenericCustomBlock) stack.getMaterial()).getCustomId(), event); } } // The click event for the block you clicked on if (event.getAction() == Action.LEFT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_BLOCK) { Block block = ((SpoutCraftBlock) event.getClickedBlock()).getBlockType(); if (block instanceof GenericCustomBlock) { if (event.getAction() == Action.LEFT_CLICK_BLOCK) { this.plugin.getHandlerManager().triggerHandlers("LeftClick", ((GenericCustomBlock) block).getCustomId(), event); } else { this.plugin.getHandlerManager().triggerHandlers("RightClick", ((GenericCustomBlock) block).getCustomId(), event); } } } } @EventHandler public void onPlayerMove(PlayerMoveEvent event) { Location location = event.getPlayer().getLocation(); Block block = ((SpoutCraftBlock) location.getWorld().getBlockAt(location)).getBlockType(); // Touch represents a block you are standing in. if (block instanceof GenericCustomBlock) { this.plugin.getHandlerManager().triggerHandlers("Touch", ((GenericCustomBlock) block).getCustomId(), event); } block = ((SpoutCraftBlock) location.getWorld().getBlockAt(location.subtract(0, 1, 0))).getBlockType(); // Walkover represents the block under your position. if (block instanceof GenericCustomBlock) { this.plugin.getHandlerManager().triggerHandlers("Walkover", ((GenericCustomBlock) block).getCustomId(), event); } } }
package org.jboss.cx.remoting.util; import java.net.URI; import java.net.URISyntaxException; /** * A parser for JBoss Remoting URI types. */ public final class ServiceURI { public static final String SCHEME = "jrs"; private ServiceURI() { } /** * Determine if this URI is a valid Remoting service URI. * * @param uri the URI * @return {@code true} if the given URI is a valid Remoting service URI */ public static boolean isRemotingServiceUri(final URI uri) { return SCHEME.equals(uri.getScheme()) && uri.isOpaque(); } public static String getServiceType(final URI uri) throws IllegalArgumentException { if (! isRemotingServiceUri(uri)) { throw new IllegalArgumentException("Not a valid remoting service URI"); } final String ssp = uri.getSchemeSpecificPart(); final int firstColon = ssp.indexOf(':'); final String serviceType; if (firstColon == -1) { serviceType = ssp; } else { serviceType = ssp.substring(0, firstColon); } return serviceType; } public static String getGroupName(final URI uri) throws IllegalArgumentException { if (! isRemotingServiceUri(uri)) { throw new IllegalArgumentException("Not a valid remoting service URI"); } final String ssp = uri.getSchemeSpecificPart(); final int firstColon = ssp.indexOf(':'); final String groupName; if (firstColon == -1) { return ""; } final int secondColon = ssp.indexOf(':', firstColon + 1); if (secondColon == -1) { groupName = ssp.substring(firstColon + 1); } else { groupName = ssp.substring(firstColon + 1, secondColon); } return groupName; } public static String getEndpointName(final URI uri) throws IllegalArgumentException { if (! isRemotingServiceUri(uri)) { throw new IllegalArgumentException("Not a valid remoting service URI"); } final String ssp = uri.getSchemeSpecificPart(); final int firstColon = ssp.indexOf(':'); final String endpointName; if (firstColon == -1) { return ""; } final int secondColon = ssp.indexOf(':', firstColon + 1); if (secondColon == -1) { return ""; } // ::: is not officially supported, but this leaves room for extensions final int thirdColon = ssp.indexOf(':', secondColon + 1); if (thirdColon == -1) { endpointName = ssp.substring(secondColon + 1); } else { endpointName = ssp.substring(secondColon + 1, thirdColon); } return endpointName; } /** * Create a Remoting service URI. * * @param serviceType the service type, if any * @param groupName the group name, if any * @param endpointName the endpoint name, if any * @return the URI */ public static URI create(String serviceType, String groupName, String endpointName) { try { StringBuilder builder = new StringBuilder(serviceType.length() + groupName.length() + endpointName.length() + 2); if (serviceType != null && serviceType.length() > 0) { builder.append(serviceType); } builder.append(':'); if (groupName != null && groupName.length() > 0) { builder.append(groupName); } builder.append(':'); if (endpointName != null && endpointName.length() > 0) { builder.append(endpointName); } return new URI(SCHEME, builder.toString(), null); } catch (URISyntaxException e) { throw new IllegalStateException("URI syntax exception should not be possible here", e); } } }
package org.wso2.carbon.uuf; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.wso2.carbon.uuf.core.UriPatten; import static java.lang.Integer.signum; public class UriPattenTest { @DataProvider public Object[][] pattenProvider() { return new Object[][]{ {"/a", "/{a}"}, {"/a/b", "/{a}/b"}, {"/a/b", "/a/{b}"}, {"/a/b/", "/a/{b}/"}, {"/a/b", "/{a}/{b}"}, {"/a/b/", "/{a}/{b}/"}, {"/{a}/b", "/{a}/{b}"}, {"/a/{b}", "/{a}/{b}"}, {"/ab", "/a{x}"}, {"/ab", "/{x}b"} }; } @DataProvider public Object[][] uriProvider() { return new Object[][]{ {"/", "/"}, {"/a", "/a"}, {"/a-b", "/a-b"}, {"/{a}", "/x"}, // {"/{a}", "/x-y"}, {"/{a}b", "/xb"}, {"/a/{b}", "/a/x"}, {"/a{b}c/d{e}f", "/axc/dyf"}, {"/a/{b}/c", "/a/x/c"}, {"/a/b/{c}/d", "/a/b/x/d"} }; } @Test(dataProvider = "pattenProvider") public void testOrdering(String a, String b) throws Exception { UriPatten aPatten = new UriPatten(a); UriPatten bPatten = new UriPatten(b); int i = aPatten.compareTo(bPatten); int j = bPatten.compareTo(aPatten); Assert.assertTrue(i < 0, a + " should be more specific than " + b); Assert.assertTrue(j > 0, a + " should be more specific than " + b); } @Test(dataProvider = "uriProvider") public void testMatching(String a, String b) throws Exception { Assert.assertTrue(new UriPatten(a).match(b)); } @Test public void testInvariants() throws Exception { UriPatten[] pattens = new UriPatten[]{ new UriPatten("/"), new UriPatten("/a"), new UriPatten("/ab"), new UriPatten("/a{b}"), new UriPatten("/{a}/{b}"), new UriPatten("/{a}"), new UriPatten("/{a}"), new UriPatten("/a/{b}"), new UriPatten("/ab/{b}"), new UriPatten("/{a}/b"), }; //following invariants are specified in java.lang.Comparable for (int x = 0; x < pattens.length; x++) { for (int y = x + 1; y < pattens.length; y++) { int xy = pattens[x].compareTo(pattens[y]); int yx = pattens[y].compareTo(pattens[x]); Assert.assertTrue(signum(xy) == -signum(yx)); for (int z = y + 1; z < pattens.length; z++) { int xz = pattens[x].compareTo(pattens[z]); int yz = pattens[y].compareTo(pattens[z]); if (xy > 0 && yz > 0) { Assert.assertTrue(xz > 0); } else if (yx > 0 && yz > 0) { Assert.assertTrue(yz > 0); } else if (xy == 0) { Assert.assertTrue(signum(xz) == signum(yz)); } } } } } }
package net.sf.ij_plugins.util; import ij.IJ; import ij.ImagePlus; import ij.gui.GenericDialog; import ij.plugin.filter.PlugInFilter; import ij.process.ByteProcessor; import ij.process.ImageProcessor; import java.util.concurrent.atomic.AtomicInteger; /** * @author Jarek Sacha * @since Sep 22, 2009 9:54:28 PM */ public final class SetPixelsPlugin implements PlugInFilter { final private static String TITLE = "Set Pixels"; final private static AtomicInteger value = new AtomicInteger(1); final private static int flags = DOES_8G + ROI_REQUIRED + SUPPORTS_MASKING; @Override public int setup(final String arg, final ImagePlus imp) { return IJ.setupDialog(imp, flags); } @Override public void run(final ImageProcessor ip) { final GenericDialog gd = new GenericDialog(TITLE); gd.addMessage("Set pixels in current ROI to a specified value [0 to 255]."); gd.addNumericField("Value:", value.get(), 0); gd.showDialog(); if (gd.wasCanceled()) { return; } value.set(Math.max(0, Math.min(255, (int) Math.round(gd.getNextNumber())))); IJ.showStatus("Setting ROI pixels to " + value); final ByteProcessor bp = (ByteProcessor) ip; bp.setColor(value.get()); bp.fill(); } }
package nl.dykam.dev.reutil.data; import nl.dykam.dev.reutil.ReUtilPlugin; import nl.dykam.dev.reutil.data.annotations.*; import org.bukkit.Bukkit; import org.bukkit.configuration.serialization.ConfigurationSerializable; import java.lang.reflect.Array; class ComponentInfo { public static final ObjectType[] ALL_OBJECT_TYPES = ObjectType.values(); @SuppressWarnings("unchecked") public static final Class<? extends Component>[] NO_CLASSES = (Class<? extends Component>[]) Array.newInstance(Class.class, 0); private static final SaveMoment[] DEFAULT_SAVE_MOMENTS = {}; public static <T extends Component> Defaults getDefaults(Class<T> type) { return type.getAnnotation(Defaults.class); } private static <T extends Component> ComponentBuilder<T> getBuilder(Class<T> type) { return ComponentBuilder.getBuilder(type); } public static <T extends Component> ObjectType[] getApplicables(Class<T> type) { ApplicableTo annotation = type.getAnnotation(ApplicableTo.class); return annotation == null ? ALL_OBJECT_TYPES : annotation.value(); } @SuppressWarnings("unchecked") public static <T extends Component> Class<? extends Component>[] getRequired(Class<T> type) { Require annotation = type.getAnnotation(Require.class); return annotation == null ? NO_CLASSES : annotation.value(); } public static SaveMoment[] getSaveMoments(Component component) { Class<? extends Component> componentClass = component.getClass(); Persistent annotation = componentClass.getAnnotation(Persistent.class); SaveMoment[] result = DEFAULT_SAVE_MOMENTS; if(annotation == null) { return DEFAULT_SAVE_MOMENTS; } else if(!ConfigurationSerializable.class.isAssignableFrom(componentClass)) { ReUtilPlugin.getMessage().warn(Bukkit.getConsoleSender(), "ConfigurationSerializable not implemented by @Persistent " + componentClass.getName()); } return annotation.value(); } public static Defaults getDefaults(Component component) { return getDefaults(component.getClass()); } }
package nl.peterbloem.motive.exec; import static nl.peterbloem.kit.Functions.log2; import static nl.peterbloem.kit.Series.series; import static org.apache.commons.math3.util.ArithmeticUtils.binomialCoefficientLog; import static org.nodes.models.USequenceEstimator.CIMethod; import static org.nodes.models.USequenceEstimator.CIType; import static org.nodes.motifs.MotifCompressor.exDegree; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.json.JSONObject; import org.nodes.DGraph; import org.nodes.DLink; import org.nodes.DNode; import org.nodes.Graph; import org.nodes.Graphs; import org.nodes.Subgraph; import org.nodes.TGraph; import org.nodes.TLink; import org.nodes.UGraph; import org.nodes.ULink; import org.nodes.UNode; import org.nodes.algorithms.Nauty; import org.nodes.compression.BinomialCompressor; import org.nodes.compression.EdgeListCompressor; import org.nodes.compression.NeighborListCompressor; import org.nodes.data.Data; import org.nodes.models.DSequenceEstimator; import org.nodes.models.DegreeSequenceModel.Prior; import org.nodes.models.ERSimpleModel; import org.nodes.models.EdgeListModel; import org.nodes.models.USequenceEstimator; import org.nodes.motifs.MotifCompressor; import org.nodes.random.RandomGraphs; import org.nodes.random.SimpleSubgraphGenerator; import org.nodes.util.bootstrap.BCaCI; import org.nodes.util.bootstrap.LogBCaCI; import org.nodes.util.bootstrap.LogNormalCI; import nl.peterbloem.kit.FileIO; import nl.peterbloem.kit.Functions; import nl.peterbloem.kit.Generator; import nl.peterbloem.kit.Generators; import nl.peterbloem.kit.Global; import nl.peterbloem.kit.OnlineModel; import nl.peterbloem.kit.Order; import nl.peterbloem.kit.Series; import nl.peterbloem.motive.DPlainMotifExtractor; import nl.peterbloem.motive.MotifModel; import nl.peterbloem.motive.MotifSearchModel; import nl.peterbloem.motive.UPlainMotifExtractor; /** * Compares the code length under the motifs to that under a given null-model * * For undirected data. * * @author Peter */ public class CompareLarge { private static final int BS_SAMPLES = 10000; /** * Number of samples to take to find potential motifs */ public int motifSamples = 1000000; /** * Minimum motif size (inclusive) */ public int motifMinSize = 3; /** * Maximum motif size (inclusive) */ public int motifMaxSize = 6; /** * The dataset. */ public DGraph<String> data = null; /** * Name of the dataset (to appear in the plot) */ public String dataName = "<no dataset name given>"; /** * The maximum number of motifs to test */ public int maxMotifs = 100; /** * Minimum frequency for a motif to be considered */ public int minFreq = 2; /** * Depth to which to search for which instances to consider (more is better, but slower, -1 is maximal depth always). */ public int searchDepth = -1; /** * Whether to reset the DM model at every motif instance. */ private boolean resets = true; public void main() throws IOException { nl.peterbloem.kit.Global.secureRandom(42); Global.log().info("Computing motif code lengths"); DPlainMotifExtractor<String> ex = new DPlainMotifExtractor<String>( (DGraph<String>)data, motifSamples, motifMinSize, motifMaxSize, minFreq); List<? extends DGraph<String>> subs = new ArrayList<DGraph<String>>(ex.subgraphs()); List<Double> frequencies = new ArrayList<Double>(subs.size()); for(Graph<String> sub : subs) frequencies.add(ex.frequency((DGraph<String>)sub)); List<List<List<Integer>>> occurrences = new ArrayList<List<List<Integer>>>(subs.size()); for(Graph<String> sub : subs) occurrences.add(ex.occurrences((DGraph<String>)sub)); if(subs.size() > maxMotifs) { subs = new ArrayList<DGraph<String>>(subs.subList(0, maxMotifs)); frequencies = new ArrayList<Double>(frequencies.subList(0, maxMotifs)); } List<Double> factorsER = new ArrayList<Double>(subs.size()); List<Double> factorsEL = new ArrayList<Double>(subs.size()); List<Double> maxFactors = new ArrayList<Double>(subs.size()); double baselineER = (new ERSimpleModel(false)).codelength(data); double baselineEL = (new EdgeListModel(Prior.ML)).codelength(data); for(int i : series(subs.size())) { DGraph<String> sub = subs.get(i); List<List<Integer>> occs = occurrences.get(i); Global.log().info("Analysing sub ("+ (i+1) +" of " + subs.size() + "): " + sub); Global.log().info("freq: " + frequencies.get(i)); double max = Double.NEGATIVE_INFINITY; Global.log().info("null model: ER"); { double sizeER = MotifSearchModel.sizeER(data, sub, occs, resets, searchDepth); double factorER = baselineER - sizeER; factorsER.add(factorER); Global.log().info("ER baseline: " + baselineER); Global.log().info("ER motif code: " + sizeER); Global.log().info("ER factor: " + factorER); max = Math.max(max, factorER); } Global.log().info("null model: EL"); { double sizeEL = MotifSearchModel.sizeEL(data, sub, occs, resets, searchDepth); double factorEL = baselineEL - sizeEL; factorsEL.add(factorEL); Global.log().info("EL baseline: " + baselineEL); Global.log().info("EL motif code: " + sizeEL); Global.log().info("EL factor: " + factorEL); max = Math.max(max, factorEL); } maxFactors.add(max); } Comparator<Double> comp = Functions.natural(); Functions.sort( factorsEL, Collections.reverseOrder(comp), (List) frequencies, (List) factorsER, (List) factorsEL, (List) subs); File numbersFile = new File("numbers.csv"); BufferedWriter numbersWriter = new BufferedWriter(new FileWriter(numbersFile)); for(int i : series(subs.size())) numbersWriter.write(frequencies.get(i) + ", " + factorsER.get(i) + ", " + factorsEL.get(i) + "\n"); numbersWriter.close(); int i = 0; for(Graph<String> sub : subs) { File graphFile = new File(String.format("motif.%03d.edgelist", i)); Data.writeEdgeList(sub, graphFile); i++; } JSONObject obj = new JSONObject(); obj.put("data", dataName); obj.put("directed", true); obj.put("baseline er", baselineER); obj.put("baseline el", baselineEL); Functions.write(obj.toString(), new File("metadata.json")); try { FileIO.python(new File("."), "scripts/plot.large.py"); } catch (Exception e) { System.out.println("Failed to run plot script. " + e); } } }
package nl.topicus.jdbc; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.Statement; import java.util.Arrays; import java.util.Properties; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import com.google.auth.oauth2.AccessToken; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.auth.oauth2.UserCredentials; import com.google.cloud.Timestamp; import com.google.cloud.spanner.DatabaseAdminClient; import com.google.cloud.spanner.DatabaseClient; import com.google.cloud.spanner.DatabaseId; import com.google.cloud.spanner.Operation; import com.google.cloud.spanner.Spanner; import com.google.cloud.spanner.SpannerException; import com.google.cloud.spanner.SpannerOptions; import com.google.cloud.spanner.SpannerOptions.Builder; import com.google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata; import nl.topicus.jdbc.MetaDataStore.TableKeyMetaData; import nl.topicus.jdbc.statement.CloudSpannerPreparedStatement; import nl.topicus.jdbc.statement.CloudSpannerStatement; import nl.topicus.jdbc.transaction.CloudSpannerTransaction; /** * JDBC Driver for Google Cloud Spanner. * * @author loite * */ public class CloudSpannerConnection extends AbstractCloudSpannerConnection { private final CloudSpannerDriver driver; private Spanner spanner; private String clientId; private DatabaseClient dbClient; private DatabaseAdminClient adminClient; private boolean autoCommit = true; private boolean closed; private boolean readOnly; private final String url; private final Properties suppliedProperties; private final boolean allowExtendedMode; private String simulateProductName; private String instanceId; private String database; private CloudSpannerTransaction transaction; private Timestamp lastCommitTimestamp; private MetaDataStore metaDataStore; CloudSpannerConnection(CloudSpannerDriver driver, String url, String projectId, String instanceId, String database, String credentialsPath, String oauthToken, boolean allowExtendedMode, Properties suppliedProperties) throws SQLException { this.driver = driver; this.instanceId = instanceId; this.database = database; this.url = url; this.allowExtendedMode = allowExtendedMode; this.suppliedProperties = suppliedProperties; try { Builder builder = SpannerOptions.newBuilder(); if (projectId != null) builder.setProjectId(projectId); GoogleCredentials credentials = null; if (credentialsPath != null) { credentials = getCredentialsFromFile(credentialsPath); builder.setCredentials(credentials); } else if (oauthToken != null) { credentials = getCredentialsFromOAuthToken(oauthToken); builder.setCredentials(credentials); } if (credentials != null) { if (credentials instanceof UserCredentials) { clientId = ((UserCredentials) credentials).getClientId(); } if (credentials instanceof ServiceAccountCredentials) { clientId = ((ServiceAccountCredentials) credentials).getClientId(); } } SpannerOptions options = builder.build(); spanner = options.getService(); dbClient = spanner.getDatabaseClient(DatabaseId.of(options.getProjectId(), instanceId, database)); adminClient = spanner.getDatabaseAdminClient(); transaction = new CloudSpannerTransaction(dbClient, this); metaDataStore = new MetaDataStore(this); } catch (Exception e) { throw new SQLException("Error when opening Google Cloud Spanner connection: " + e.getMessage(), e); } } public static GoogleCredentials getCredentialsFromOAuthToken(String oauthToken) { GoogleCredentials credentials = null; if (oauthToken != null && oauthToken.length() > 0) { credentials = new GoogleCredentials(new AccessToken(oauthToken, null)); } return credentials; } public static GoogleCredentials getCredentialsFromFile(String credentialsPath) throws IOException { if (credentialsPath == null || credentialsPath.length() == 0) throw new IllegalArgumentException("credentialsPath may not be null or empty"); GoogleCredentials credentials = null; File credentialsFile = new File(credentialsPath); if (!credentialsFile.isFile()) { throw new IOException( String.format("Error reading credential file %s: File does not exist", credentialsPath)); } try (InputStream credentialsStream = new FileInputStream(credentialsFile)) { credentials = GoogleCredentials.fromStream(credentialsStream, CloudSpannerOAuthUtil.HTTP_TRANSPORT_FACTORY); } return credentials; } public static String getServiceAccountProjectId(String credentialsPath) { String project = null; if (credentialsPath != null) { try (InputStream credentialsStream = new FileInputStream(credentialsPath)) { JSONObject json = new JSONObject(new JSONTokener(credentialsStream)); project = json.getString("project_id"); } catch (IOException | JSONException ex) { // ignore } } return project; } Spanner getSpanner() { return spanner; } public void setSimulateProductName(String productName) { this.simulateProductName = productName; } public Void executeDDL(String sql) throws SQLException { try { Operation<Void, UpdateDatabaseDdlMetadata> operation = adminClient.updateDatabaseDdl(instanceId, database, Arrays.asList(sql), null); operation = operation.waitFor(); return operation.getResult(); } catch (SpannerException e) { throw new SQLException("Could not execute DDL statement " + sql + ": " + e.getLocalizedMessage(), e); } } String getProductName() { if (simulateProductName != null) return simulateProductName; return "Google Cloud Spanner"; } @Override public CloudSpannerStatement createStatement() throws SQLException { return new CloudSpannerStatement(this, dbClient); } @Override public CloudSpannerPreparedStatement prepareStatement(String sql) throws SQLException { return new CloudSpannerPreparedStatement(sql, this, dbClient); } @Override public CallableStatement prepareCall(String sql) throws SQLException { throw new SQLFeatureNotSupportedException(); } @Override public String nativeSQL(String sql) throws SQLException { return sql; } @Override public void setAutoCommit(boolean autoCommit) throws SQLException { this.autoCommit = autoCommit; } @Override public boolean getAutoCommit() throws SQLException { return autoCommit; } @Override public void commit() throws SQLException { lastCommitTimestamp = transaction.commit(); } @Override public void rollback() throws SQLException { transaction.rollback(); } public CloudSpannerTransaction getTransaction() { return transaction; } @Override public void close() throws SQLException { transaction.rollback(); closed = true; driver.closeConnection(this); } @Override public boolean isClosed() throws SQLException { return closed; } @Override public CloudSpannerDatabaseMetaData getMetaData() throws SQLException { return new CloudSpannerDatabaseMetaData(this); } @Override public void setReadOnly(boolean readOnly) throws SQLException { if (transaction.isRunning()) throw new SQLException( "There is currently a transaction running. Commit or rollback the running transaction before changing read-only mode."); this.readOnly = readOnly; } @Override public boolean isReadOnly() throws SQLException { return readOnly; } @Override public void setTransactionIsolation(int level) throws SQLException { if (level != Connection.TRANSACTION_SERIALIZABLE) { throw new SQLException("Transaction level " + level + " is not supported. Only Connection.TRANSACTION_SERIALIZABLE is supported"); } } @Override public int getTransactionIsolation() throws SQLException { return Connection.TRANSACTION_SERIALIZABLE; } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { return new CloudSpannerStatement(this, dbClient); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return new CloudSpannerPreparedStatement(sql, this, dbClient); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return new CloudSpannerStatement(this, dbClient); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return new CloudSpannerPreparedStatement(sql, this, dbClient); } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { return new CloudSpannerPreparedStatement(sql, this, dbClient); } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { return new CloudSpannerPreparedStatement(sql, this, dbClient); } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { return new CloudSpannerPreparedStatement(sql, this, dbClient); } public String getUrl() { return url; } public String getClientId() { return clientId; } @Override public boolean isValid(int timeout) throws SQLException { if (isClosed()) return false; Statement statement = createStatement(); statement.setQueryTimeout(timeout); try (ResultSet rs = statement.executeQuery("SELECT 1")) { if (rs.next()) return true; } return false; } @Override public CloudSpannerArray createArrayOf(String typeName, Object[] elements) throws SQLException { return CloudSpannerArray.createArray(typeName, elements); } public TableKeyMetaData getTable(String name) throws SQLException { return metaDataStore.getTable(name); } public Properties getSuppliedProperties() { return suppliedProperties; } public boolean isAllowExtendedMode() { return allowExtendedMode; } /** * * @return The commit timestamp of the last transaction that committed * succesfully */ public Timestamp getLastCommitTimestamp() { return lastCommitTimestamp; } }
package org.almibe.codeeditor; import javafx.concurrent.Worker; import javafx.scene.Parent; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; import netscape.javascript.JSObject; import java.net.URI; import java.util.Arrays; import java.util.Queue; import java.util.concurrent.LinkedBlockingQueue; public class CodeMirrorEditor implements CodeEditor { private final WebView webView; private final WebEngine webEngine; private boolean isEditorInitialized = false; //TODO make atomic var? private final Queue<Runnable> queue = new LinkedBlockingQueue<>(); private final EditorLoadedCallback editorLoadedCallback = new EditorLoadedCallback(); public CodeMirrorEditor() { webView = new WebView(); webEngine = webView.getEngine(); } public void init(URI editorUri, Runnable... runAfterLoading) { queue.addAll(Arrays.asList(runAfterLoading)); webEngine.load(editorUri.toString()); webEngine.getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) -> { if(newValue == Worker.State.SUCCEEDED) { JSObject window = fetchWindow(); window.call("editorLoaded", editorLoadedCallback); } }); } //because of JavaFX/WebKit access policy this callback has to be a public inner class and can't be a lambda or anonymous inner class public class EditorLoadedCallback implements Runnable { @Override public void run() { isEditorInitialized = true; handleQueue(); } } @Override public String getContent() { return (String) fetchEditor().call("getValue"); } @Override public void setContent(String newContent) { fetchEditor().call("setValue", newContent); } @Override public boolean isEditorInitialized() { return isEditorInitialized; } @Override public Parent getWidget() { return this.webView; } @Override public boolean isReadOnly() { return (Boolean) fetchEditor().call("getOption","readOnly"); } @Override public void setReadOnly(boolean readOnly) { fetchEditor().call("setOption", "readOnly", readOnly); } @Override public JSObject fetchEditor() { Object editor = webEngine.executeScript("require('codeeditor').codeMirror;"); if(editor instanceof JSObject) { return (JSObject) editor; } throw new IllegalStateException("CodeMirror not loaded."); } @Override public String getMode() { return (String) fetchEditor().call("getOption", "mode"); } @Override public void setMode(String mode) { webEngine.executeScript("require('codeeditor').setMode('" + mode + "')"); } @Override public void includeJSModules(String[] modules, Runnable runnable) { //TODO test this fetchCodeEditorObject().call("importJSModules", modules, runnable); } @Override public JSObject fetchRequireJSObject() { return (JSObject) webEngine.executeScript("require();"); } @Override public String getTheme() { return (String) fetchEditor().call("getOption", "theme"); } @Override public void setTheme(String theme) { webEngine.executeScript("require('codeeditor').setTheme('" + theme + "')"); } @Override public void runWhenReady(Runnable runnable) { if(isEditorInitialized) { runnable.run(); } else { queue.add(runnable); handleQueue(); } } private void handleQueue() { if(isEditorInitialized) { while(!queue.isEmpty()) { Runnable runnable = queue.remove(); runnable.run(); } } } private JSObject fetchCodeEditorObject() { return (JSObject) webEngine.executeScript("require('codeeditor');"); } private JSObject fetchWindow() { return (JSObject) webEngine.executeScript("window;"); } }
package com.cascadia.hidenseek; import android.annotation.SuppressLint; import android.app.Activity; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class Settings extends Activity implements OnClickListener { Button submit, exit; String username, counttime, seektime; EditText userinput, userctime, userstime; SharedPreferences sh_Pref; Editor toEdit; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.settings); initSettings(); getInit(); } //Get any stored preferences and put them in the fields when form is loaded private void initSettings(){ username = getSharedPreferences("HideNSeek_shared_pref", MODE_PRIVATE).getString("Username",""); EditText uName = (EditText)findViewById(R.id.prefPlayerNameInput); uName.setText(username); counttime = getSharedPreferences("HideNSeek_shared_pref", MODE_PRIVATE).getString("Counttime", ""); EditText cTime = (EditText)findViewById(R.id.prefCountTimeInput); if (counttime == null || counttime == "") { counttime = "30"; } cTime.setText(counttime); seektime = getSharedPreferences("HideNSeek_shared_pref", MODE_PRIVATE).getString("Seektime", ""); EditText sTime = (EditText)findViewById(R.id.prefSeekTimeInput); if (seektime == null || seektime == "") { seektime = "3"; } sTime.setText(seektime); } public void getInit() { submit = (Button) findViewById(R.id.submit); exit = (Button) findViewById(R.id.exit); userinput = (EditText) findViewById(R.id.prefPlayerNameInput); userctime = (EditText) findViewById(R.id.prefCountTimeInput); userstime = (EditText) findViewById(R.id.prefSeekTimeInput); submit.setOnClickListener(this); exit.setOnClickListener(this); } public void sharedPreferences() { sh_Pref = getSharedPreferences("HideNSeek_shared_pref", MODE_PRIVATE); toEdit = sh_Pref.edit(); toEdit.putString("Username", username); toEdit.putString("Counttime", counttime); toEdit.putString("Seektime", seektime); toEdit.commit(); } @SuppressLint("ShowToast") @Override public void onClick(View currentButton) { switch (currentButton.getId()) { case R.id.submit: username = userinput.getText().toString(); counttime = userctime.getText().toString(); seektime = userstime.getText().toString(); sharedPreferences(); Toast.makeText(this, "Details are saved", 20).show(); break; case R.id.exit: finish(); } } }
package org.apdplat.superword.tools; import org.apache.commons.dbcp2.*; import org.apache.commons.lang.StringUtils; import org.apache.commons.pool2.ObjectPool; import org.apache.commons.pool2.impl.GenericObjectPool; import org.apdplat.superword.model.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.sql.DataSource; import java.sql.*; import java.sql.Date; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.Collectors; /** * * @author */ public class MySQLUtils { private static final Logger LOG = LoggerFactory.getLogger(MySQLUtils.class); private static final String DRIVER = "com.mysql.jdbc.Driver"; private static final String URL = "jdbc:mysql://127.0.0.1:3306/superword?useUnicode=true&characterEncoding=utf8"; private static final String USER = "root"; private static final String PASSWORD = "root"; private static DataSource dataSource = null; private static final ExecutorService EXECUTOR_SERVICE = Executors.newCachedThreadPool(); static { try { Class.forName(DRIVER); dataSource = setupDataSource(URL, USER, PASSWORD); } catch (ClassNotFoundException e) { LOG.error("MySQL", e); } } private MySQLUtils() { } public static List<String> getWordPurePronunciation(String word, String dictionary){ String pronunciation = getWordPronunciation(word, dictionary); return extractPurePronunciation(pronunciation); } public static List<String> extractPurePronunciation(String pronunciation){ Set<String> set = new HashSet<>(); String[] attrs = pronunciation.split(" \\| "); if(attrs != null){ for(String attr : attrs){ attr = attr.replace("", "") .replace("", "") .replace("[", "") .replace("]", "") .replace("/", "") .replace("\\", "") .replaceAll("\\s+", ""); if(StringUtils.isNotBlank(attr)){ String[] items = attr.split(";"); if(items != null){ Collections.addAll(set, items); } } } } List<String> list = new ArrayList<>(); list.addAll(set); return list; } public static String getWordPronunciation(String word, String dictionary) { String sql = "select pronunciation from word_pronunciation where word=? and dictionary=?"; Connection con = getConnection(); if(con == null){ return ""; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, word); pst.setString(2, dictionary); rs = pst.executeQuery(); if (rs.next()) { return rs.getString(1); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return ""; } public static void saveWordPronunciation(String word, String dictionary, String pronunciation) { String sql = "insert into word_pronunciation (word, dictionary, pronunciation) values (?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, word); pst.setString(2, dictionary); pst.setString(3, pronunciation); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static boolean deleteWordDefinition(String word) { String sql = "delete from word_definition where word=?"; Connection con = getConnection(); if(con == null){ return false; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, word); return pst.execute(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return false; } public static Map<String, String> getWordAndPronunciationBySymbol(String symbol, String dictionary, int limit, Set<Word> words) { Map<String, String> map = new LinkedHashMap<>(); String sql = "select word, pronunciation from word_pronunciation where dictionary=?"; Connection con = getConnection(); if(con == null){ return map; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, dictionary); rs = pst.executeQuery(); while (rs.next()) { String word = rs.getString(1); String pronunciation = rs.getString(2); if (words.contains(new Word(word, "")) && StringUtils.isNotBlank(pronunciation) && pronunciation.contains(symbol)) { map.put(word, pronunciation); } if(map.size() >= limit){ break; } } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return map; } public static List<String> getWordsByPOS(String pos, String dictionary, int limit) { List<String> words = new ArrayList<>(); String sql = "select word, definition from word_definition where dictionary=?"; Connection con = getConnection(); if(con == null){ return words; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, dictionary); rs = pst.executeQuery(); while (rs.next()) { String word = rs.getString(1); String definition = rs.getString(2); String[] attrs = definition.split("<br/>"); for(String attr : attrs) { if (StringUtils.isNotBlank(attr) && attr.startsWith(pos)) { words.add(word); break; } } if(words.size() >= limit){ break; } } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return words; } public static Map<String, Set<String>> getAllWordPronunciation(String dictionary, Set<Word> words) { Map<String, Set<String>> map = new HashMap<>(); String sql = "select word, pronunciation from word_pronunciation where dictionary=?"; Connection con = getConnection(); if(con == null){ return map; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, dictionary); rs = pst.executeQuery(); while (rs.next()) { String word = rs.getString(1); String pronunciation = rs.getString(2); if(StringUtils.isNotBlank(word) && StringUtils.isNotBlank(pronunciation) && words.contains(new Word(word, ""))) { for(String item : extractPurePronunciation(pronunciation)){ map.putIfAbsent(item, new HashSet()); map.get(item).add(word); } } } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return map; } public static List<String> getAllWordDefinition(String dictionary, Set<Word> words) { List<String> set = new ArrayList<>(); String sql = "select word, definition from word_definition where dictionary=?"; Connection con = getConnection(); if(con == null){ return set; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, dictionary); rs = pst.executeQuery(); while (rs.next()) { String word = rs.getString(1); String definition = rs.getString(2); if(StringUtils.isNotBlank(word) && StringUtils.isNotBlank(definition) && words.contains(new Word(word, ""))) { set.add(word + "_" + definition); } } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return set; } public static String getWordDefinition(String word, String dictionary) { String sql = "select definition from word_definition where word=? and dictionary=?"; Connection con = getConnection(); if(con == null){ return ""; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, word); pst.setString(2, dictionary); rs = pst.executeQuery(); if (rs.next()) { return rs.getString(1); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return ""; } public static void saveWordDefinition(String word, String dictionary, String definition) { String sql = "insert into word_definition (word, dictionary, definition) values (?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, word); pst.setString(2, dictionary); pst.setString(3, definition); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static boolean existUser(User user, String table){ String sql = "select id from "+table+" where user_name=?"; Connection con = getConnection(); if(con == null){ return false; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, user.getUserName()); rs = pst.executeQuery(); if (rs.next()) { return true; } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return false; } public static boolean login(User user){ String sql = "select password from user where user_name=?"; Connection con = getConnection(); if(con == null){ return false; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, user.getUserName()); rs = pst.executeQuery(); if (rs.next()) { String password = rs.getString(1); if(StringUtils.isNotBlank(user.getPassword()) && user.getPassword().equals(password)){ return true; } } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return false; } public static boolean register(User user) { String sql = "insert into user (user_name, password, date_time) values (?, ?, ?)"; Connection con = getConnection(); if(con == null){ return false; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, user.getUserName()); pst.setString(2, user.getPassword()); pst.setTimestamp(3, new Timestamp(user.getDateTime().getTime())); pst.executeUpdate(); return true; } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return false; } public static UserText getUseTextFromDatabase(int id) { String sql = "select id,text,date_time,user_name from user_text where id=?"; Connection con = getConnection(); if(con == null){ return null; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setInt(1, id); rs = pst.executeQuery(); if (rs.next()) { int _id = rs.getInt(1); String text = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3);; String user_name = rs.getString(4); UserText userText = new UserText(); userText.setId(id); userText.setText(text); userText.setDateTime(new java.util.Date(timestamp.getTime())); userText.setUserName(user_name); return userText; } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return null; } public static List<UserDynamicPrefix> getHistoryUserDynamicPrefixesFromDatabase(String userName) { List<UserDynamicPrefix> userDynamicPrefixes = new ArrayList<>(); String sql = "select id,dynamic_prefix,date_time from user_dynamic_prefix where user_name=?"; Connection con = getConnection(); if(con == null){ return userDynamicPrefixes; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String dynamicPrefix = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3); UserDynamicPrefix userDynamicPrefix = new UserDynamicPrefix(); userDynamicPrefix.setId(id); userDynamicPrefix.setDynamicPrefix(dynamicPrefix); userDynamicPrefix.setDateTime(new java.util.Date(timestamp.getTime())); userDynamicPrefix.setUserName(userName); userDynamicPrefixes.add(userDynamicPrefix); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return userDynamicPrefixes; } public static List<UserDynamicSuffix> getHistoryUserDynamicSuffixesFromDatabase(String userName) { List<UserDynamicSuffix> userDynamicSuffixes = new ArrayList<>(); String sql = "select id,dynamic_suffix,date_time from user_dynamic_suffix where user_name=?"; Connection con = getConnection(); if(con == null){ return userDynamicSuffixes; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String dynamicSuffix = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3); UserDynamicSuffix userDynamicSuffix = new UserDynamicSuffix(); userDynamicSuffix.setId(id); userDynamicSuffix.setDynamicSuffix(dynamicSuffix); userDynamicSuffix.setDateTime(new java.util.Date(timestamp.getTime())); userDynamicSuffix.setUserName(userName); userDynamicSuffixes.add(userDynamicSuffix); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return userDynamicSuffixes; } public static List<UserSimilarWord> getHistoryUserSimilarWordsFromDatabase(String userName) { List<UserSimilarWord> userSimilarWords = new ArrayList<>(); String sql = "select id,similar_word,date_time from user_similar_word where user_name=?"; Connection con = getConnection(); if(con == null){ return userSimilarWords; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String similarWord = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3); UserSimilarWord userSimilarWord = new UserSimilarWord(); userSimilarWord.setId(id); userSimilarWord.setSimilarWord(similarWord); userSimilarWord.setDateTime(new java.util.Date(timestamp.getTime())); userSimilarWord.setUserName(userName); userSimilarWords.add(userSimilarWord); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return userSimilarWords; } public static List<UserBook> getHistoryUserBooksFromDatabase(String userName) { List<UserBook> userBooks = new ArrayList<>(); String sql = "select id,book,date_time from user_book where user_name=?"; Connection con = getConnection(); if(con == null){ return userBooks; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String book = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3); UserBook userBook = new UserBook(); userBook.setId(id); userBook.setBook(book); userBook.setDateTime(new java.util.Date(timestamp.getTime())); userBook.setUserName(userName); userBooks.add(userBook); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return userBooks; } public static List<UserUrl> getHistoryUserUrlsFromDatabase(String userName) { List<UserUrl> userUrls = new ArrayList<>(); String sql = "select id,url,date_time from user_url where user_name=?"; Connection con = getConnection(); if(con == null){ return userUrls; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String url = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3); UserUrl userUrl = new UserUrl(); userUrl.setId(id); userUrl.setUrl(url); userUrl.setDateTime(new java.util.Date(timestamp.getTime())); userUrl.setUserName(userName); userUrls.add(userUrl); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return userUrls; } public static List<UserText> getHistoryUserTextsFromDatabase(String userName) { List<UserText> userTexts = new ArrayList<>(); String sql = "select id,text,date_time from user_text where user_name=?"; Connection con = getConnection(); if(con == null){ return userTexts; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String text = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3); UserText userText = new UserText(); userText.setId(id); userText.setText(text); userText.setDateTime(new java.util.Date(timestamp.getTime())); userText.setUserName(userName); userTexts.add(userText); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return userTexts; } public static boolean deleteMyNewWord(String userName, String word) { String sql = "delete from my_new_words where user_name=? and word=?"; Connection con = getConnection(); if(con == null){ return false; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); pst.setString(2, word); return pst.execute(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return false; } public static List<MyNewWord> getMyNewWordsFromDatabase(String userName) { List<MyNewWord> myNewWords = new ArrayList<>(); String sql = "select word,date_time from my_new_words where user_name=? order by date_time desc"; Connection con = getConnection(); if(con == null){ return myNewWords; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { String word = rs.getString(1); Timestamp timestamp = rs.getTimestamp(2); MyNewWord myNewWord = new MyNewWord(); myNewWord.setWord(word); myNewWord.setDateTime(new java.util.Date(timestamp.getTime())); myNewWord.setUserName(userName); myNewWords.add(myNewWord); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return myNewWords; } public static List<UserWord> getHistoryUserWordsFromDatabase(String userName) { List<UserWord> userWords = new ArrayList<>(); String sql = "select id,word,date_time from user_word where user_name=? order by date_time desc"; Connection con = getConnection(); if(con == null){ return userWords; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String word = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3); UserWord userWord = new UserWord(); userWord.setId(id); userWord.setWord(word); userWord.setDateTime(new java.util.Date(timestamp.getTime())); userWord.setUserName(userName); userWords.add(userWord); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return userWords; } public static void saveUserSimilarWordToDatabase(UserSimilarWord userSimilarWord) { EXECUTOR_SERVICE.execute(()->_saveUserSimilarWordToDatabase(userSimilarWord)); } public static void _saveUserSimilarWordToDatabase(UserSimilarWord userSimilarWord) { String sql = "insert into user_similar_word (user_name, similar_word, md5, date_time) values (?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userSimilarWord.getUserName()); pst.setString(2, userSimilarWord.getSimilarWord()); pst.setString(3, MD5(userSimilarWord.getUserName()+userSimilarWord.getSimilarWord())); pst.setTimestamp(4, new Timestamp(userSimilarWord.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static void saveUserDynamicPrefixToDatabase(UserDynamicPrefix userDynamicPrefix) { EXECUTOR_SERVICE.execute(()->_saveUserDynamicPrefixToDatabase(userDynamicPrefix)); } public static void _saveUserDynamicPrefixToDatabase(UserDynamicPrefix userDynamicPrefix) { String sql = "insert into user_dynamic_prefix (user_name, dynamic_prefix, md5, date_time) values (?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userDynamicPrefix.getUserName()); pst.setString(2, userDynamicPrefix.getDynamicPrefix()); pst.setString(3, MD5(userDynamicPrefix.getUserName()+userDynamicPrefix.getDynamicPrefix())); pst.setTimestamp(4, new Timestamp(userDynamicPrefix.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static void saveUserDynamicSuffixToDatabase(UserDynamicSuffix userDynamicSuffix) { EXECUTOR_SERVICE.execute(()->_saveUserDynamicSuffixToDatabase(userDynamicSuffix)); } public static void _saveUserDynamicSuffixToDatabase(UserDynamicSuffix userDynamicSuffix) { String sql = "insert into user_dynamic_suffix (user_name, dynamic_suffix, md5, date_time) values (?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userDynamicSuffix.getUserName()); pst.setString(2, userDynamicSuffix.getDynamicSuffix()); pst.setString(3, MD5(userDynamicSuffix.getUserName()+userDynamicSuffix.getDynamicSuffix())); pst.setTimestamp(4, new Timestamp(userDynamicSuffix.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static void saveUserBookToDatabase(UserBook userBook) { EXECUTOR_SERVICE.execute(()->_saveUserBookToDatabase(userBook)); } public static void _saveUserBookToDatabase(UserBook userBook) { String sql = "insert into user_book (user_name, book, md5, date_time) values (?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userBook.getUserName()); pst.setString(2, userBook.getBook()); pst.setString(3, MD5(userBook.getUserName()+userBook.getBook())); pst.setTimestamp(4, new Timestamp(userBook.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static void saveUserUrlToDatabase(UserUrl userUrl) { EXECUTOR_SERVICE.execute(()->_saveUserUrlToDatabase(userUrl)); } public static void _saveUserUrlToDatabase(UserUrl userUrl) { String sql = "insert into user_url (user_name, url, md5, date_time) values (?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userUrl.getUserName()); pst.setString(2, userUrl.getUrl()); pst.setString(3, MD5(userUrl.getUserName()+userUrl.getUrl())); pst.setTimestamp(4, new Timestamp(userUrl.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static void saveUserTextToDatabase(UserText userText) { EXECUTOR_SERVICE.execute(()->_saveUserTextToDatabase(userText)); } public static void _saveUserTextToDatabase(UserText userText) { String sql = "insert into user_text (user_name, text, md5, date_time) values (?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userText.getUserName()); pst.setString(2, userText.getText()); pst.setString(3, MD5(userText.getUserName() + userText.getText())); pst.setTimestamp(4, new Timestamp(userText.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static void saveMyNewWordsToDatabase(MyNewWord myNewWord) { EXECUTOR_SERVICE.execute(()->_saveMyNewWordsToDatabase(myNewWord)); } public static void _saveMyNewWordsToDatabase(MyNewWord myNewWord) { String sql = "insert into my_new_words (user_name, word, date_time) values (?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, myNewWord.getUserName()); pst.setString(2, myNewWord.getWord()); pst.setTimestamp(3, new Timestamp(myNewWord.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static void saveUserWordToDatabase(UserWord userWord) { EXECUTOR_SERVICE.execute(()->_saveUserWordToDatabase(userWord)); } public static void _saveUserWordToDatabase(UserWord userWord) { String sql = "insert into user_word (user_name, word, date_time) values (?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userWord.getUserName()); pst.setString(2, userWord.getWord()); pst.setTimestamp(3, new Timestamp(userWord.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static Connection getConnection() { Connection con = null; try { con = dataSource.getConnection(); } catch (Exception e) { LOG.error("MySQL", e); } return con; } private static DataSource setupDataSource(String connectUri, String uname, String passwd) { // First, we'll create a ConnectionFactory that the // pool will use to create Connections. // We'll use the DriverManagerConnectionFactory, // using the connect string passed in the command line // arguments. ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectUri, uname, passwd); // Next we'll create the PoolableConnectionFactory, which wraps // the classes that implement the pooling functionality. PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null); // Now we'll need a ObjectPool that serves as the // actual pool of connections. // We'll use a GenericObjectPool instance, although // any ObjectPool implementation will suffice. ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory); // Set the factory's pool property to the owning pool poolableConnectionFactory.setPool(connectionPool); // Finally, we create the PoolingDriver itself, // passing in the object pool we created. PoolingDataSource<PoolableConnection> dataSource = new PoolingDataSource<>(connectionPool); return dataSource; } public static void close(Statement st) { close(null, st, null); } public static void close(Statement st, ResultSet rs) { close(null, st, rs); } public static void close(Connection con, Statement st, ResultSet rs) { try { if (rs != null) { rs.close(); rs = null; } if (st != null) { st.close(); st = null; } if (con != null) { con.close(); con = null; } } catch (SQLException e) { LOG.error("", e); } } public static void close(Connection con, Statement st) { close(con, st, null); } public static void close(Connection con) { close(con, null, null); } public static String MD5(String md5) { try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); byte[] array = md.digest(md5.getBytes()); StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; ++i) { sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3)); } return sb.toString(); } catch (java.security.NoSuchAlgorithmException e) { } return null; } public static void main(String[] args) throws Exception { UserWord userWord = new UserWord(); userWord.setDateTime(new Date(System.currentTimeMillis())); userWord.setWord("fabulous"); userWord.setUserName("ysc"); MySQLUtils.saveUserWordToDatabase(userWord); System.out.println(MySQLUtils.getHistoryUserWordsFromDatabase("ysc")); } public static boolean processQQUser(QQUser qqUser) { if(qqUser.getUserName() == null){ return false; } qqUser.setPassword(""); if(!existUser(qqUser, "user")){ register(qqUser); } if(!existUser(qqUser, "user_qq")){ saveQQUser(qqUser); } return true; } private static void saveQQUser(QQUser user) { String sql = "insert into user_qq (user_name, password, nickname, gender, birthday, location, avatarURL30, avatarURL50, avatarURL100, date_time) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, user.getUserName()); pst.setString(2, user.getPassword()); pst.setString(3, user.getNickname()); pst.setString(4, user.getGender()); pst.setString(5, user.getBirthday()); pst.setString(6, user.getLocation()); pst.setString(7, user.getAvatarURL30()); pst.setString(8, user.getAvatarURL50()); pst.setString(9, user.getAvatarURL100()); pst.setTimestamp(10, new Timestamp(user.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); LOG.error("", e); } finally { close(con, pst, rs); } } }
package org.apdplat.superword.tools; import org.apdplat.superword.model.UserText; import org.apdplat.superword.model.UserWord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.*; import java.util.ArrayList; import java.util.List; /** * * @author */ public class MySQLUtils { private static final Logger LOG = LoggerFactory.getLogger(MySQLUtils.class); private static final String DRIVER = "com.mysql.jdbc.Driver"; private static final String URL = "jdbc:mysql://127.0.0.1:3306/superword?useUnicode=true&characterEncoding=utf8"; private static final String USER = "root"; private static final String PASSWORD = "root"; static { try { Class.forName(DRIVER); } catch (ClassNotFoundException e) { LOG.error("MySQL", e); } } private MySQLUtils() { } public static List<UserText> getHistoryUseTextsFromDatabase(String userName) { List<UserText> userTexts = new ArrayList<>(); String sql = "select text,date_time from user_text where user_name=?"; Connection con = getConnection(); if(con == null){ return userTexts; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { String text = rs.getString(1); Timestamp timestamp = rs.getTimestamp(2); UserText userText = new UserText(); userText.setText(text); userText.setDateTime(new java.util.Date(timestamp.getTime())); userText.setUserName(userName); userTexts.add(userText); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return userTexts; } public static List<UserWord> getHistoryUserWordsFromDatabase(String userName) { List<UserWord> userWords = new ArrayList<>(); String sql = "select word,dictionary,date_time from user_word where user_name=?"; Connection con = getConnection(); if(con == null){ return userWords; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { String word = rs.getString(1); String dictionary = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3); UserWord userWord = new UserWord(); userWord.setWord(word); userWord.setDictionary(dictionary); userWord.setDateTime(new java.util.Date(timestamp.getTime())); userWord.setUserName(userName); userWords.add(userWord); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return userWords; } public static void saveUserTextToDatabase(UserText userText) { String sql = "insert into user_text (user_name, text, date_time) values (?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userText.getUserName()); pst.setString(2, userText.getText()); pst.setTimestamp(3, new Timestamp(userText.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static void saveUserWordToDatabase(UserWord userWord) { String sql = "insert into user_word (user_name, word, dictionary, date_time) values (?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userWord.getUserName()); pst.setString(2, userWord.getWord()); pst.setString(3, userWord.getDictionary()); pst.setTimestamp(4, new Timestamp(userWord.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static Connection getConnection() { Connection con = null; try { con = DriverManager.getConnection(URL, USER, PASSWORD); } catch (SQLException e) { LOG.error("MySQL", e); } return con; } public static void close(Statement st) { close(null, st, null); } public static void close(Statement st, ResultSet rs) { close(null, st, rs); } public static void close(Connection con, Statement st, ResultSet rs) { try { if (rs != null) { rs.close(); rs = null; } if (st != null) { st.close(); st = null; } if (con != null) { con.close(); con = null; } } catch (SQLException e) { LOG.error("", e); } } public static void close(Connection con, Statement st) { close(con, st, null); } public static void close(Connection con) { close(con, null, null); } public static void main(String[] args) throws Exception { UserWord userWord = new UserWord(); userWord.setDateTime(new Date(System.currentTimeMillis())); userWord.setWord("fabulous"); userWord.setUserName("ysc"); MySQLUtils.saveUserWordToDatabase(userWord); System.out.println(MySQLUtils.getHistoryUserWordsFromDatabase("ysc")); } }
package org.cobbzilla.util.daemon; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.SystemUtils; import org.cobbzilla.util.collection.ToStringTransformer; import org.cobbzilla.util.error.ExceptionHandler; import org.cobbzilla.util.error.GeneralErrorHandler; import org.cobbzilla.util.io.StreamUtil; import org.cobbzilla.util.string.StringUtil; import org.slf4j.Logger; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import static java.lang.Long.toHexString; import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.stream.LongStream.range; import static org.apache.commons.collections.CollectionUtils.collect; import static org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace; import static org.cobbzilla.util.error.ExceptionHandler.DEFAULT_EX_RUNNABLE; import static org.cobbzilla.util.io.FileUtil.abs; import static org.cobbzilla.util.io.FileUtil.list; import static org.cobbzilla.util.reflect.ReflectionUtil.instantiate; import static org.cobbzilla.util.security.ShaUtil.sha256_hex; import static org.cobbzilla.util.string.StringUtil.truncate; import static org.cobbzilla.util.system.Sleep.sleep; import static org.cobbzilla.util.time.TimeUtil.formatDuration; /** * the Zilla doesn't mess around. */ @Slf4j public class ZillaRuntime { public static final String CLASSPATH_PREFIX = "classpath:"; public static String getJava() { return System.getProperty("java.home") + "/bin/java"; } public static boolean terminate(Thread thread, long timeout) { if (thread == null || !thread.isAlive()) return true; thread.interrupt(); final long start = realNow(); while (thread.isAlive() && realNow() - start < timeout) { sleep(100, "terminate: waiting for thread to die: "+thread); } if (thread.isAlive()) { log.warn("terminate: thread did not die voluntarily, killing it: "+thread); thread.stop(); } return false; } public static boolean bool(Boolean b) { return b != null && b; } public static boolean bool(Boolean b, boolean val) { return b != null ? b : val; } public static Thread background (Runnable r) { return background(r, DEFAULT_EX_RUNNABLE); } public static Thread background (Runnable r, ExceptionHandler ex) { final Thread t = new Thread(() -> { try { r.run(); } catch (Exception e) { ex.handle(e); } }); t.start(); return t; } public static final Function<Integer, Long> DEFAULT_RETRY_BACKOFF = SECONDS::toMillis; public static <T> T retry (Callable<T> func, int tries) { return retry(func, tries, DEFAULT_RETRY_BACKOFF, DEFAULT_EX_RUNNABLE); } public static <T> T retry (Callable<T> func, int tries, Function<Integer, Long> backoff) { return retry(func, tries, backoff, DEFAULT_EX_RUNNABLE); } public static <T> T retry (Callable<T> func, int tries, Logger logger) { return retry(func, tries, DEFAULT_RETRY_BACKOFF, e -> logger.error("Error: "+e)); } public static <T> T retry (Callable<T> func, int tries, Function<Integer, Long> backoff, Logger logger) { return retry(func, tries, backoff, e -> logger.error("Error: "+e)); } public static <T> T retry (Callable<T> func, int tries, Function<Integer, Long> backoff, ExceptionHandler ex) { Exception lastEx = null; try { for (int i = 0; i < tries; i++) { try { final T rVal = func.call(); log.debug("retry: successful, returning: " + rVal); return rVal; } catch (Exception e) { lastEx = e; log.debug("retry: failed (attempt " + (i + 1) + "/" + tries + "): " + e); ex.handle(e); sleep(backoff.apply(i), "waiting to retry " + func.getClass().getSimpleName()); } } } catch (Exception e) { return die("retry: fatal exception, exiting: "+e); } return die("retry: max tries ("+tries+") exceeded. last exception: "+lastEx); } public static Thread daemon (Runnable r) { final Thread t = new Thread(r); t.setDaemon(true); t.start(); return t; } @Getter @Setter private static ErrorApi errorApi; public static <T> T die(String message) { return _throw(new IllegalStateException(message, null)); } public static <T> T die(String message, Exception e) { return _throw(new IllegalStateException(message, e)); } public static <T> T die(Exception e) { return _throw(new IllegalStateException("(no message)", e)); } public static <T> T notSupported() { return notSupported("not supported"); } public static <T> T notSupported(String message) { return _throw(new UnsupportedOperationException(message)); } private static <T> T _throw (RuntimeException e) { final String message = e.getMessage(); final Throwable cause = e.getCause(); if (errorApi != null) { if (cause instanceof Exception) errorApi.report(message, (Exception) cause); else errorApi.report(e); } if (cause != null) log.error("Inner exception: " + message, cause); throw e; } public static String shortError(Exception e) { return e.getClass().getName()+": "+e.getMessage(); } public static String errorString(Exception e) { return errorString(e, 1000); } public static String errorString(Exception e, int maxlen) { return truncate(shortError(e)+"\n"+ getStackTrace(e), maxlen); } public static boolean empty(String s) { return s == null || s.length() == 0; } /** * Determines if the parameter is "empty", by criteria described in @return * Tries to avoid throwing exceptions, handling just about any case in a true/false fashion. * * @param o anything * @return true if and only o is: * * null * * a collection, map, iterable or array that contains no objects * * a file that does not exist or whose size is zero * * a directory that does not exist or that contains no files * * any object whose .toString method returns a zero-length string */ public static boolean empty(Object o) { if (o == null) return true; if (o instanceof String) return o.toString().length() == 0; if (o instanceof Collection) return ((Collection)o).isEmpty(); if (o instanceof Map) return ((Map)o).isEmpty(); if (o instanceof JsonNode) { if (o instanceof ObjectNode) return ((ObjectNode) o).size() == 0; if (o instanceof ArrayNode) return ((ArrayNode) o).size() == 0; final String json = ((JsonNode) o).textValue(); return json == null || json.length() == 0; } if (o instanceof Iterable) return !((Iterable)o).iterator().hasNext(); if (o instanceof File) { final File f = (File) o; return !f.exists() || f.length() == 0 || (f.isDirectory() && list(f).length == 0); } if (o.getClass().isArray()) { if (o.getClass().getComponentType().isPrimitive()) { switch (o.getClass().getComponentType().getName()) { case "boolean": return ((boolean[]) o).length == 0; case "byte": return ((byte[]) o).length == 0; case "short": return ((short[]) o).length == 0; case "char": return ((char[]) o).length == 0; case "int": return ((int[]) o).length == 0; case "long": return ((long[]) o).length == 0; case "float": return ((float[]) o).length == 0; case "double": return ((double[]) o).length == 0; default: return o.toString().length() == 0; } } else { return ((Object[]) o).length == 0; } } return o.toString().length() == 0; } public static <T> T first (Iterable<T> o) { return (T) ((Iterable) o).iterator().next(); } public static <K, T> T first (Map<K, T> o) { return first(o.values()); } public static <T> T first (T[] o) { return o[0]; } public static <T> T sorted(T o) { if (empty(o)) return o; if (o.getClass().isArray()) { final Object[] copy = (Object[]) Array.newInstance(o.getClass().getComponentType(), ((Object[])o).length); System.arraycopy(o, 0, copy, 0 , copy.length); Arrays.sort(copy); return (T) copy; } if (o instanceof Collection) { final List list = new ArrayList((Collection) o); Collections.sort(list); final Collection copy = (Collection) instantiate(o.getClass()); copy.addAll(list); return (T) copy; } return die("sorted: cannot sort a "+o.getClass().getSimpleName()+", can only sort arrays and Collections"); } public static <T> List toList(T o) { if (o == null) return null; if (o instanceof Collection) return new ArrayList((Collection) o); if (o instanceof Object[]) return Arrays.asList((Object[]) o); return die("sortedList: cannot sort a "+o.getClass().getSimpleName()+", can only sort arrays and Collections"); } public static Boolean safeBoolean(String val, Boolean ifNull) { return empty(val) ? ifNull : Boolean.valueOf(val); } public static Boolean safeBoolean(String val) { return safeBoolean(val, null); } public static Integer safeInt(String val, Integer ifNull) { return empty(val) ? ifNull : Integer.valueOf(val); } public static Integer safeInt(String val) { return safeInt(val, null); } public static Long safeLong(String val, Long ifNull) { return empty(val) ? ifNull : Long.valueOf(val); } public static Long safeLong(String val) { return safeLong(val, null); } public static BigInteger bigint(long val) { return new BigInteger(String.valueOf(val)); } public static BigInteger bigint(int val) { return new BigInteger(String.valueOf(val)); } public static BigInteger bigint(byte val) { return new BigInteger(String.valueOf(val)); } public static BigDecimal big(String val) { return new BigDecimal(val); } public static BigDecimal big(double val) { return new BigDecimal(String.valueOf(val)); } public static BigDecimal big(float val) { return new BigDecimal(String.valueOf(val)); } public static BigDecimal big(long val) { return new BigDecimal(String.valueOf(val)); } public static BigDecimal big(int val) { return new BigDecimal(String.valueOf(val)); } public static BigDecimal big(byte val) { return new BigDecimal(String.valueOf(val)); } public static int percent(int value, double pct) { return percent(value, pct, RoundingMode.HALF_UP); } public static int percent(int value, double pct, RoundingMode rounding) { return big(value).multiply(big(pct)).setScale(0, rounding).intValue(); } public static int percent(BigDecimal value, BigDecimal pct) { return percent(value.intValue(), pct.multiply(big(0.01)).doubleValue(), RoundingMode.HALF_UP); } public static String uuid() { return UUID.randomUUID().toString(); } private static AtomicLong systemTimeOffset = new AtomicLong(0L); public static long getSystemTimeOffset () { return systemTimeOffset.get(); } public static void setSystemTimeOffset (long t) { systemTimeOffset.set(t); } public static long incrementSystemTimeOffset(long t) { return systemTimeOffset.addAndGet(t); } public static long now() { return System.currentTimeMillis() + systemTimeOffset.get(); } public static String hexnow() { return toHexString(now()); } public static String hexnow(long now) { return toHexString(now); } public static long realNow() { return System.currentTimeMillis(); } public static <T> T pickRandom(T[] things) { return things[RandomUtils.nextInt(0, things.length)]; } public static <T> T pickRandom(List<T> things) { return things.get(RandomUtils.nextInt(0, things.size())); } public static BufferedReader stdin() { return new BufferedReader(new InputStreamReader(System.in)); } public static BufferedWriter stdout() { return new BufferedWriter(new OutputStreamWriter(System.out)); } public static String readStdin() { return StreamUtil.toStringOrDie(System.in); } public static int envInt (String name, int defaultValue) { return envInt(name, defaultValue, null, null); } public static int envInt (String name, int defaultValue, Integer maxValue) { return envInt(name, defaultValue, null, maxValue); } public static int envInt (String name, int defaultValue, Integer minValue, Integer maxValue) { return envInt(name, defaultValue, minValue, maxValue, System.getenv()); } public static int envInt (String name, int defaultValue, Integer minValue, Integer maxValue, Map<String, String> env) { final String s = env.get(name); if (!empty(s)) { try { final int val = Integer.parseInt(s); if (val <= 0) { log.warn("envInt: invalid value("+name+"): " +val+", returning "+defaultValue); return defaultValue; } else if (maxValue != null && val > maxValue) { log.warn("envInt: value too large ("+name+"): " +val+ ", returning " + maxValue); return maxValue; } else if (minValue != null && val < minValue) { log.warn("envInt: value too small ("+name+"): " +val+ ", returning " + minValue); return minValue; } return val; } catch (Exception e) { log.warn("envInt: invalid value("+name+"): " +s+", returning "+defaultValue); return defaultValue; } } return defaultValue; } public static int processorCount() { return Runtime.getRuntime().availableProcessors(); } public static String hashOf (Object... things) { final StringBuilder b = new StringBuilder(); for (Object thing : things) { if (b.length() > 0) b.append("\t"); b.append(thing == null ? "null" : (thing instanceof Object[]) ? Arrays.deepHashCode((Object[]) thing) : thing.hashCode()); } return sha256_hex(b.toString()); } public static String hexToBase36(String hex) { return new BigInteger(hex, 16).toString(36); } public static Collection<String> stringRange(Number start, Number end) { return collect(range(start.longValue(), end.longValue()).boxed().iterator(), ToStringTransformer.instance); } public static String zcat() { return SystemUtils.IS_OS_MAC ? "gzcat" : "zcat"; } public static String zcat(File f) { return (SystemUtils.IS_OS_MAC ? "gzcat" : "zcat") + " " + abs(f); } public static final String[] JAVA_DEBUG_OPTIONS = {"-Xdebug", "-agentlib", "-Xrunjdwp"}; public static boolean isDebugOption (String arg) { for (String opt : JAVA_DEBUG_OPTIONS) if (arg.startsWith(opt)) return true; return false; } public static String javaOptions() { return javaOptions(true); } public static String javaOptions(boolean excludeDebugOptions) { final List<String> opts = new ArrayList<>(); for (String arg : ManagementFactory.getRuntimeMXBean().getInputArguments()) { if (excludeDebugOptions && isDebugOption(arg)) continue; opts.add(arg); } return StringUtil.toString(opts, " "); } public static <T> T dcl (AtomicReference<T> target, Callable<T> init) { return dcl(target, init, null); } @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") public static <T> T dcl (AtomicReference<T> target, Callable<T> init, GeneralErrorHandler error) { if (target.get() == null) { synchronized (target) { if (target.get() == null) { try { target.set(init.call()); } catch (Exception e) { if (error != null) { error.handleError("dcl: error initializing: "+e, e); } else { log.warn("dcl: "+e); return null; } } } } } return target.get(); } public static String stacktrace() { return getStackTrace(new Exception()); } private static final AtomicLong selfDestructInitiated = new AtomicLong(-1); public static void setSelfDestruct (long t) { setSelfDestruct(t, 0); } public static void setSelfDestruct (long t, int status) { synchronized (selfDestructInitiated) { final long dieTime = selfDestructInitiated.get(); if (dieTime == -1) { selfDestructInitiated.set(now()+t); daemon(() -> { sleep(t); System.exit(status); }); } else { log.warn("setSelfDestruct: already set: self-destructing in "+formatDuration(dieTime-now())); } } } }
package org.deepsymmetry.beatlink.data; import io.kaitai.struct.ByteBufferKaitaiStream; import org.deepsymmetry.beatlink.Util; import org.deepsymmetry.beatlink.dbserver.BinaryField; import org.deepsymmetry.beatlink.dbserver.Message; import org.deepsymmetry.beatlink.dbserver.NumberField; import org.deepsymmetry.cratedigger.pdb.RekordboxAnlz; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.awt.*; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.util.*; import java.util.List; /** * Provides information about each memory point, hot cue, and loop stored for a track. * * @author James Elliott */ @SuppressWarnings("WeakerAccess") public class CueList { private static final Logger logger = LoggerFactory.getLogger(CueList.class); /** * The message holding the cue list information as it was read over the network. This can be used to analyze fields * that have not yet been reliably understood, and is also used for storing the cue list in a cache file. This will * be {@code null} if the cue list was not obtained from a dbserver query. */ public final Message rawMessage; /** * The bytes from which the Kaitai Struct tags holding cue list information were parsed from an ANLZ file. * Will be {@code null} if the cue list was obtained from a dbserver query. */ public final List<ByteBuffer> rawTags; /** * The bytes from which the Kaitai Struct tags holding the nxs2 cue list information (which can include DJ-assigned * comment text for each cue) were parsed from an extended ANLZ file. Will be {@code null} if the cue list was * obtained from a dbserver query, and empty if there were no nxs2 cue tags available in the analysis data. */ public final List<ByteBuffer> rawExtendedTags; /** * Return the number of entries in the cue list that represent hot cues. * * @return the number of cue list entries that are hot cues */ public int getHotCueCount() { if (rawMessage != null) { return (int) ((NumberField) rawMessage.arguments.get(5)).getValue(); } int total = 0; for (Entry entry : entries) { if (entry.hotCueNumber > 0) { ++total; } } return total; } /** * Return the number of entries in the cue list that represent ordinary memory points, rather than hot cues. * The memory points can also be loops. * * @return the number of cue list entries other than hot cues */ public int getMemoryPointCount() { if (rawMessage != null) { return (int) ((NumberField) rawMessage.arguments.get(6)).getValue(); } int total = 0; for (Entry entry : entries) { if (entry.hotCueNumber == 0) { ++total; } } return total; } /** * Returns the entry whose track position comes most closely before the specified number of milliseconds, if any. * If there is a cue which falls exactly at the specified time, it will be returned (and it will also be returned * by {@link #findEntryAfter(long)}). If there is more than one entry at the exact time as the one that is returned, * the one chosen will be unpredictable. * * All times are rounded to half frame units, because that is the resolution at which cues are stored. * * @param milliseconds the time of interest within the track * @return the cue whose start time is closest to the specified time but not after it */ public Entry findEntryBefore(long milliseconds) { final Entry target = new Entry(0, Util.timeToHalfFrameRounded(milliseconds), "", null, null); int index = Collections.binarySearch(entries, target, TIME_ONLY_COMPARATOR); if (index >= 0) { // An exact match return entries.get(index); } // The exact time was not found, so convert the result to the index where the time would be inserted. index = -(index + 1); if (index > 0) { // If there is a value before where we should insert this time, that's what we should return. return entries.get((index - 1)); } // There was no cue at or before the desired time. return null; } /** * Returns the entry whose track position comes most closely after the specified number of milliseconds, if any. * If there is a cue which falls exactly at the specified time, it will be returned (and it will also be returned * by {@link #findEntryBefore(long)}). If there is more than one entry at the exact time as the one that is returned, * the one chosen will be unpredictable. * * All times are rounded to half frame units, because that is the resolution at which cues are stored. * * @param milliseconds the time of interest within the track * @return the cue whose start time is closest to the specified time but not before it */ public Entry findEntryAfter(long milliseconds) { final Entry target = new Entry(0, Util.timeToHalfFrameRounded(milliseconds), "", null, null); int index = Collections.binarySearch(entries, target, TIME_ONLY_COMPARATOR); if (index >= 0) { return entries.get(index); } // The exact time was not found, so convert the result to the index where the time would be inserted. index = -(index + 1); if (index < entries.size()) { // If there is a value where we should insert this time, that's what we should return. return entries.get(index); } // There was no cue at or after the desired time. return null; } /** * Breaks out information about each entry in the cue list. */ public static class Entry { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Entry entry = (Entry) o; if (hotCueNumber != entry.hotCueNumber) return false; if (isLoop != entry.isLoop) return false; if (cuePosition != entry.cuePosition) return false; if (cueTime != entry.cueTime) return false; if (loopPosition != entry.loopPosition) return false; return loopTime == entry.loopTime; } @Override public int hashCode() { int result = hotCueNumber; result = 31 * result + (isLoop ? 1 : 0); result = 31 * result + (int) (cuePosition ^ (cuePosition >>> 32)); result = 31 * result + (int) (cueTime ^ (cueTime >>> 32)); result = 31 * result + (int) (loopPosition ^ (loopPosition >>> 32)); result = 31 * result + (int) (loopTime ^ (loopTime >>> 32)); return result; } /** * If this has a non-zero value, this entry is a hot cue with that identifier. */ public final int hotCueNumber; /** * Indicates whether this entry represents a loop, as opposed to a simple cue point. */ public final boolean isLoop; /** * Indicates the location of the cue in half-frame units, which are 1/150 of a second. If the cue is a loop, * this is the start of the loop. */ public final long cuePosition; /** * Indicates the location of the cue in milliseconds. If the cue is a loop, this is the start of the loop. */ public final long cueTime; /** * If the entry represents a loop, indicates the loop point in half-frame units, which are 1/150 of a second. * The loop point is the end of the loop, at which point playback jumps back to {@link #cuePosition}. */ public final long loopPosition; /** * If the entry represents a loop, indicates the loop point in milliseconds. The loop point is the end of the * loop, at which point playback jumps back to {@link #cueTime}. */ public final long loopTime; /** * If the entry was constructed from an extended nxs2-style commented cue tag, and the DJ assigned a comment * to the cue, this will contain the comment text. Otherwise it will be an empty string. */ public final String comment; /** * The explicit color embedded into the cue, or {@code null} if there was none. */ public final Color embeddedColor; /** * The color with which this cue will be displayed in rekordbox, if it is a hot cue with a recognized * color code, or {@code null} if that does not apply. */ public final Color rekordboxColor; /** * Constructor for non-loop entries. * * @param number if non-zero, this is a hot cue, with the specified identifier * @param position the position of this cue/memory point in half-frame units, which are 1/150 of a second * @param comment the DJ-assigned comment, or an empty string if none was assigned * @param embeddedColor the explicit color embedded in the cue, if any * @param rekordboxColor the color that rekordbox will display for this cue, if available */ public Entry(int number, long position, String comment, Color embeddedColor, Color rekordboxColor) { if (comment == null) throw new NullPointerException("comment must not be null"); hotCueNumber = number; cuePosition = position; cueTime = Util.halfFrameToTime(position); isLoop = false; loopPosition = 0; loopTime = 0; this.comment = comment.trim(); this.embeddedColor = embeddedColor; this.rekordboxColor = rekordboxColor; } /** * Constructor for loop entries. * * @param number if non-zero, this is a hot cue, with the specified identifier * @param startPosition the position of the start of this loop in half-frame units, which are 1/150 of a second * @param endPosition the position of the end of this loop in half-frame units * @param comment the DJ-assigned comment, or an empty string if none was assigned * @param embeddedColor the explicit color embedded in the cue, if any * @param rekordboxColor the color that rekordbox will display for this cue, if available */ public Entry(int number, long startPosition, long endPosition, String comment, Color embeddedColor, Color rekordboxColor) { if (comment == null) throw new NullPointerException("comment must not be null"); hotCueNumber = number; cuePosition = startPosition; cueTime = Util.halfFrameToTime(startPosition); isLoop = true; loopPosition = endPosition; loopTime = Util.halfFrameToTime(endPosition); this.comment = comment.trim(); this.embeddedColor = embeddedColor; this.rekordboxColor = rekordboxColor; } /** * Determine the color that an original Nexus series player would use to display this cue. Hot cues are * green, loops are orange, and ordinary memory points are red. * * @return the color that represents this cue on players that don't support nxs2 colored cues. */ public Color getNexusColor() { if (hotCueNumber > 0) { return Color.GREEN; } if (isLoop) { return Color.ORANGE; } return Color.RED; } /** * Determine the best color to be used to display this cue. If there is an indexed rekordbox color in the cue, * use that; otherwise, if there is an explicit color embedded, use that, and if neither of those is available, * delegate to {@link #getNexusColor()}. * * @return the most suitable available display color for the cue */ public Color getColor() { if (rekordboxColor != null) { return rekordboxColor; } if (embeddedColor != null) { return embeddedColor; } return getNexusColor(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (hotCueNumber == 0) { if (isLoop) { sb.append("Loop["); } else { sb.append("Memory Point["); } } else { sb.append("Hot Cue ").append((char)(hotCueNumber + '@')).append('['); } sb.append("time ").append(cueTime).append("ms"); if (isLoop) { sb.append(", loop time ").append(loopTime).append("ms"); } if (!comment.isEmpty()) { sb.append(", comment ").append(comment); } sb.append(']'); return sb.toString(); } } /** * The entries present in the cue list, sorted into order by increasing position, with hot cues coming after * ordinary memory points if both are at the same position (as often seems to happen). */ public final List<Entry> entries; /** * A comparator for sorting or searching entries that considers only their position within the track, and * not whether they are a hot cue. */ public static final Comparator<Entry> TIME_ONLY_COMPARATOR = new Comparator<Entry>() { @Override public int compare(Entry entry1, Entry entry2) { return (int) (entry1.cuePosition - entry2.cuePosition); } }; /** * The comparator used for sorting the cue list entries during construction, which orders them by position * within the track, with hot cues coming after ordinary memory points if both exist at the same position. * This often happens, and moving hot cues to the end ensures the waveform display components identify that * position as a hot cue, which is important information. */ public static final Comparator<Entry> SORT_COMPARATOR = new Comparator<Entry>() { @Override public int compare(Entry entry1, Entry entry2) { int result = (int) (entry1.cuePosition - entry2.cuePosition); if (result == 0) { int h1 = (entry1.hotCueNumber != 0) ? 1 : 0; int h2 = (entry2.hotCueNumber != 0) ? 1 : 0; result = h1 - h2; } return result; } }; /** * Sorts the entries into the order we want to present them in, which is by position, with hot cues coming after * ordinary memory points if both exist at the same position, which often happens. * * @param loadedEntries the unsorted entries we have loaded from a dbserver message, metadata cache, or rekordbox * database export * @return an immutable list of the collections in the proper order */ private List<Entry> sortEntries(List<Entry> loadedEntries) { Collections.sort(loadedEntries, SORT_COMPARATOR); return Collections.unmodifiableList(loadedEntries); } /** * Helper method to add cue list entries from a parsed ANLZ cue tag * * @param entries the list of entries being accumulated * @param tag the tag whose entries are to be added */ private void addEntriesFromTag(List<Entry> entries, RekordboxAnlz.CueTag tag) { for (RekordboxAnlz.CueEntry cueEntry : tag.cues()) { // TODO: Need to figure out how to identify deleted entries to ignore. if (cueEntry.type() == RekordboxAnlz.CueEntryType.LOOP) { entries.add(new Entry((int)cueEntry.hotCue(), Util.timeToHalfFrame(cueEntry.time()), Util.timeToHalfFrame(cueEntry.loopTime()), "", null, null)); } else { entries.add(new Entry((int)cueEntry.hotCue(), Util.timeToHalfFrame(cueEntry.time()), "", null, null)); } } } /** * Look up the embedded color that we expect to be paired with a given rekordbox color code, so we can warn if * something else is found instead, which implies our understanding of cue colors is incorrect. * * @param colorCode the first color byte * @return the color corresponding to the three bytes that are expected to follow it */ private Color expectedEmbeddedColor(int colorCode) { switch (colorCode) { case 0x31: // magenta return new Color(0xff, 0x00, 0xa1); case 0x38: // violet return new Color(0x83, 0x00, 0xff); case 0x3c: // fuchsia return new Color(0x80, 0x00, 0xff); case 0x3e: // light slate blue return new Color(0x33, 0x00, 0xff); case 0x01: // blue return new Color(0x00, 0x00, 0xff); case 0x05: // steel blue return new Color(0x50, 0x07, 0xff); case 0x09: // aqua return new Color(0x00, 0xe0, 0xff); case 0x0e: // sea green return new Color(0x1f, 0xff, 0xa3); case 0x12: // teal return new Color(0x00, 0xff, 0x47); case 0x16: // green return new Color(0x1a, 0xff, 0x00); case 0x1a: // lime return new Color(0x80,0xff, 0x00); case 0x1e: // olive return new Color(0xe6, 0xff, 0x00); case 0x20: // yellow return new Color(0xff, 0xe8, 0x00); case 0x26: // orange return new Color(0xff, 0x5e, 0x00); case 0x2a: // red return new Color(0xff, 0x00, 0x00); case 0x2d: // pink return new Color(0xff, 0x00, 0x73); case 0: // Nothing, default to pure green return Color.green; default: return null; } } /** * Decode the embedded color present in the cue entry, if there is one. * * @param entry the parsed cue entry * @return the embedded color value, or {@code null} if there is none present */ private Color findEmbeddedColor(RekordboxAnlz.CueExtendedEntry entry) { if (entry.colorRed() == null || entry.colorGreen() == null || entry.colorBlue() == null || (entry.colorRed() == 0 && entry.colorGreen() == 0 && entry.colorBlue() == 0)) { return null; } return new Color(entry.colorRed(), entry.colorGreen(), entry.colorBlue()); } /** * Look up the color that rekordbox would use to display a cue. The colors in this table correspond * to the 4x4 grid that is available inside the hot cue configuration interface. * * @param colorCode the color index found in the cue * @return the corresponding color or {@code null} if the index is not recognized */ public static Color findRekordboxColor(int colorCode) { switch (colorCode) { case 0x31: // magenta return new Color(0xde, 0x44, 0xcf); case 0x38: // violet return new Color(0x84, 0x32, 0xff); case 0x3c: // fuchsia return new Color(0xaa, 0x72, 0xff); case 0x3e: // light slate blue return new Color(0x64, 0x73, 0xff); case 0x01: // blue return new Color(0x30, 0x5a, 0xff); case 0x05: // steel blue return new Color(0x50, 0xb4, 0xff); case 0x09: // aqua return new Color(0x00, 0xe0, 0xff); case 0x0e: // sea green return new Color(0x1f, 0xa3, 0x92); case 0x12: // teal return new Color(0x10, 0xb1, 0x76); case 0x16: // green return new Color(0x28, 0xe2, 0x14); case 0x1a: // lime return new Color(0xa2,0xdd, 0x16); case 0x1e: // olive return new Color(0xb4, 0xbe, 0x04); case 0x20: // yellow return new Color(0xc3, 0xaf, 0x04); case 0x26: // orange return new Color(0xe0, 0x64, 0x1b); case 0x2a: // red return new Color(0xe5, 0x28, 0x28); case 0x2d: // pink return new Color(0xfe, 0x12, 0x7a); case 0x00: // none return null; default: logger.warn("Unrecognized rekordbox color code, " + colorCode + ", returning null."); return null; } } /** * Helper method to add cue list entries from a parsed extended ANLZ nxs2 comment cue tag * * @param entries the list of entries being accumulated * @param tag the tag whose entries are to be added */ private void addEntriesFromTag(List<Entry> entries, RekordboxAnlz.CueExtendedTag tag) { for (RekordboxAnlz.CueExtendedEntry cueEntry : tag.cues()) { final Color embeddedColor = findEmbeddedColor(cueEntry); final int colorCode = cueEntry.colorCode() == null? 0 : cueEntry.colorCode(); final Color expectedColor = expectedEmbeddedColor(colorCode); final Color rekordboxColor = findRekordboxColor(colorCode); if (((embeddedColor == null && expectedColor != null) || (embeddedColor != null && !embeddedColor.equals(expectedColor))) && (colorCode != 0 || embeddedColor != null)) { logger.warn("Was expecting embedded color " + expectedColor + " for rekordbox color code " + colorCode + ", but found color " + embeddedColor); } final String comment = (cueEntry.comment() != null)? cueEntry.comment() : ""; // Normalize missing comments to empty strings. if (cueEntry.type() == RekordboxAnlz.CueEntryType.LOOP) { entries.add(new Entry((int)cueEntry.hotCue(), Util.timeToHalfFrame(cueEntry.time()), Util.timeToHalfFrame(cueEntry.loopTime()), comment, embeddedColor, rekordboxColor)); } else { entries.add(new Entry((int)cueEntry.hotCue(), Util.timeToHalfFrame(cueEntry.time()), comment, embeddedColor, rekordboxColor)); } } } /** * Constructor for when reading from a rekordbox track analysis file. Finds the cues sections and * translates them into the objects Beat Link uses to represent them. * * @param anlzFile the recordbox analysis file corresponding to that track */ public CueList(RekordboxAnlz anlzFile) { rawMessage = null; // We did not create this from a dbserver response. List<ByteBuffer> tagBuffers = new ArrayList<ByteBuffer>(2); List<ByteBuffer> extendedTagBuffers = new ArrayList<ByteBuffer>(2); List<Entry> mutableEntries = new ArrayList<Entry>(); // First see if there are any nxs2-style cue comment tags available. for (RekordboxAnlz.TaggedSection section : anlzFile.sections()) { if (section.body() instanceof RekordboxAnlz.CueExtendedTag) { RekordboxAnlz.CueExtendedTag tag = (RekordboxAnlz.CueExtendedTag) section.body(); extendedTagBuffers.add(ByteBuffer.wrap(section._raw_body()).asReadOnlyBuffer()); addEntriesFromTag(mutableEntries, tag); } } // Then, collect any old style cue tags, but ignore their entries if we found nxs2-style ones. for (RekordboxAnlz.TaggedSection section : anlzFile.sections()) { if (section.body() instanceof RekordboxAnlz.CueTag) { RekordboxAnlz.CueTag tag = (RekordboxAnlz.CueTag) section.body(); tagBuffers.add(ByteBuffer.wrap(section._raw_body()).asReadOnlyBuffer()); if (extendedTagBuffers.isEmpty()) { addEntriesFromTag(mutableEntries, tag); } } } entries = sortEntries(mutableEntries); rawTags = Collections.unmodifiableList(tagBuffers); rawExtendedTags = Collections.unmodifiableList(extendedTagBuffers); } /** * Constructor for when recreating from cache files containing the raw tag bytes if there were no nxs2-style * extended cue tags. Included for backwards compatibility. * @param rawTags the un-parsed ANLZ file tags holding the cue list entries */ public CueList(List<ByteBuffer> rawTags) { this (rawTags, Collections.<ByteBuffer>emptyList()); } /** * Constructor for when recreating from cache files containing the raw tag bytes and raw nxs2-style * cue comment tag bytes. * @param rawTags the un-parsed ANLZ file tags holding the cue list entries * @param rawExtendedTags the un-parsed extended ANLZ file tags holding the nxs2-style commented cue list entries */ public CueList(List<ByteBuffer> rawTags, List<ByteBuffer> rawExtendedTags) { rawMessage = null; this.rawTags = Collections.unmodifiableList(rawTags); this.rawExtendedTags = Collections.unmodifiableList(rawExtendedTags); List<Entry> mutableEntries = new ArrayList<Entry>(); if (rawExtendedTags.isEmpty()) { for (ByteBuffer buffer : rawTags) { RekordboxAnlz.CueTag tag = new RekordboxAnlz.CueTag(new ByteBufferKaitaiStream(buffer)); addEntriesFromTag(mutableEntries, tag); } } else { for (ByteBuffer buffer : rawExtendedTags) { RekordboxAnlz.CueExtendedTag tag = new RekordboxAnlz.CueExtendedTag(new ByteBufferKaitaiStream(buffer)); addEntriesFromTag(mutableEntries, tag); } } entries = sortEntries(mutableEntries); } /** * Constructor when reading from the network or a cache file. * * @param message the response holding the cue list information, in either original nexus or extended nxs2 format */ public CueList(Message message) { rawMessage = message; rawTags = null; rawExtendedTags = null; if (message.knownType == Message.KnownType.CUE_LIST) { entries = parseNexusEntries(message); } else { entries = parseNxs2Entries(message); } } /** * Parse the memory points, loops, and hot cues from an original nexus style cue list response * * @param message the response holding the cue list information * * @return the parsed entries, sorted properly for searching and display */ private List<Entry> parseNexusEntries(Message message) { byte[] entryBytes = ((BinaryField) message.arguments.get(3)).getValueAsArray(); final int entryCount = entryBytes.length / 36; ArrayList<Entry> mutableEntries = new ArrayList<Entry>(entryCount); for (int i = 0; i < entryCount; i++) { final int offset = i * 36; final int cueFlag = entryBytes[offset + 1]; final int hotCueNumber = entryBytes[offset + 2]; if ((cueFlag != 0) || (hotCueNumber != 0)) { // This entry is not empty, so represent it. final long position = Util.bytesToNumberLittleEndian(entryBytes, offset + 12, 4); if (entryBytes[offset] != 0) { // This is a loop final long endPosition = Util.bytesToNumberLittleEndian(entryBytes, offset + 16, 4); mutableEntries.add(new Entry(hotCueNumber, position, endPosition, "", null, null)); } else { mutableEntries.add(new Entry(hotCueNumber, position, "", null, null)); } } } return sortEntries(mutableEntries); } /** * Attempt to load a color byte from the end of an extended cue entry. Since these are sometimes missing, will * return 0 when asked for a value past the end of the entry. * * @param entryBytes the bytes of the extended cue entry * @param address the index of the byte that might hold color information * @return the unsigned byte value found at the specified location, or 0 if it was past the end of the entry. */ private int safelyFetchColorByte(byte[] entryBytes, int address) { if (address < entryBytes.length) { return Util.unsign(entryBytes[address]); } return 0; } /** * Parse the memory points, loops, and hot cues from an extended nxs2 style cue list response * * @param message the response holding the cue list information * * @return the parsed entries, sorted properly for searching and display */ private List<Entry> parseNxs2Entries(Message message) { byte[] entryBytes = ((BinaryField) message.arguments.get(3)).getValueAsArray(); final int entryCount = (int) ((NumberField) message.arguments.get(4)).getValue(); ArrayList<Entry> mutableEntries = new ArrayList<Entry>(entryCount); int offset = 0; for (int i = 0; i < entryCount; i++) { final int entrySize = (int) Util.bytesToNumberLittleEndian(entryBytes, offset, 4); final int cueFlag = entryBytes[offset + 6]; final int hotCueNumber = entryBytes[offset + 4]; if ((cueFlag != 0) || (hotCueNumber != 0)) { // This entry is not empty, so represent it. final long position = Util.timeToHalfFrame(Util.bytesToNumberLittleEndian(entryBytes, offset + 12, 4)); // See if there is a comment. String comment = ""; int commentSize = 0; if (entrySize > 0x49) { // This entry is large enough to have a comment. commentSize = (int) Util.bytesToNumberLittleEndian(entryBytes, offset + 0x48, 2); } if (commentSize > 0) { try { comment = new String(entryBytes, offset + 0x4a, commentSize - 2, "UTF-16LE"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Java no longer supports UTF-16LE encoding?!", e); } } // See if there is a color. final int colorCode = safelyFetchColorByte(entryBytes, offset + commentSize + 0x4e); final int red = safelyFetchColorByte(entryBytes, offset + commentSize + 0x4f); final int green = safelyFetchColorByte(entryBytes, offset + commentSize + 0x50); final int blue = safelyFetchColorByte(entryBytes, offset + commentSize + 0x51); final Color rekordboxColor = findRekordboxColor(colorCode); final Color expectedColor = expectedEmbeddedColor(colorCode); final Color embeddedColor = (red == 0 && green == 0 && blue == 0)? null : new Color(red, green, blue); if (((embeddedColor == null && expectedColor != null) || (embeddedColor != null && !embeddedColor.equals(expectedColor))) && (colorCode != 0 || embeddedColor != null)) { logger.warn("Was expecting embedded color " + expectedColor + " for rekordbox color code " + colorCode + ", but found color " + embeddedColor); } if (cueFlag == 2) { // This is a loop final long endPosition = Util.timeToHalfFrame(Util.bytesToNumberLittleEndian(entryBytes, offset + 16, 4)); mutableEntries.add(new Entry(hotCueNumber, position, endPosition, comment, embeddedColor, rekordboxColor)); } else { mutableEntries.add(new Entry(hotCueNumber, position, comment, embeddedColor, rekordboxColor)); } } offset += entrySize; // Move on to the next entry. } return sortEntries(mutableEntries); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CueList cueList = (CueList) o; return entries != null ? entries.equals(cueList.entries) : cueList.entries == null; } @Override public int hashCode() { return entries != null ? entries.hashCode() : 0; } @Override public String toString() { return "Cue List[entries: " + entries + "]"; } }
package org.egordorichev.lasttry; import org.egordorichev.lasttry.entity.Enemy; import org.egordorichev.lasttry.entity.Player; import org.egordorichev.lasttry.entity.EnemyID; import org.egordorichev.lasttry.item.Item; import org.egordorichev.lasttry.item.ItemHolder; import org.egordorichev.lasttry.item.modifier.Modifier; import org.egordorichev.lasttry.item.tiles.Block; import org.egordorichev.lasttry.mod.ModLoader; import org.egordorichev.lasttry.graphics.Assets; import org.egordorichev.lasttry.world.WorldProvider; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.GL11; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import org.newdawn.slick.state.BasicGameState; import org.newdawn.slick.state.StateBasedGame; public class GamePlayState extends BasicGameState { private Enemy enemy; public GamePlayState() { String worldName = "test"; // Must be powers of two int worldWidth = 512; int worldHeight = 512; if (WorldProvider.exists(worldName)) { LastTry.world = WorldProvider.load(worldName); } else { LastTry.world = WorldProvider.generate(worldName, worldWidth, worldHeight); } int spawnX = worldWidth / 2; int spawnY = LastTry.world.getHighest(spawnX); LastTry.player = new Player("George"); LastTry.player.spawn(spawnX, spawnY); for(int i = 0; i < 10; i++) { LastTry.world.spawnEnemy(EnemyID.greenSlime, 40 + LastTry.random.nextInt(100), 60); LastTry.world.spawnEnemy(EnemyID.blueSlime, 10 + LastTry.random.nextInt(100), 60); } LastTry.modLoader = new ModLoader(); LastTry.modLoader.load(); LastTry.ui.add(LastTry.player.inventory); LastTry.player.inventory.add(new ItemHolder(Item.woodenSword, 1, Modifier.melee.legendary)); LastTry.player.inventory.add(new ItemHolder(Item.ironPickaxe, 1, Modifier.melee.light)); LastTry.player.inventory.add(new ItemHolder(Item.crimsandBlock, 10)); LastTry.player.inventory.add(new ItemHolder(Item.crimstoneBlock, 10)); LastTry.player.inventory.add(new ItemHolder(Item.redIceBlock, 10)); LastTry.player.inventory.add(new ItemHolder(Item.viciousMushroom, 10)); LastTry.player.inventory.add(new ItemHolder(Item.stoneBlock, 10)); LastTry.player.inventory.add(new ItemHolder(Item.ebonsandBlock, 990)); LastTry.player.inventory.add(new ItemHolder(Item.ebonsandBlock, 100)); LastTry.player.inventory.add(new ItemHolder(Item.ebonstoneBlock, 200)); LastTry.player.inventory.add(new ItemHolder(Item.purpleIceBlock, 10)); LastTry.player.inventory.add(new ItemHolder(Item.vileMushroom, 10)); this.enemy = LastTry.world.spawnEnemy(EnemyID.eyeOfCthulhu, LastTry.player.getGridX(), LastTry.player.getGridY() - 100); } @Override public int getID() { return 1; } @Override public void init(GameContainer gameContainer, StateBasedGame stateBasedGame) throws SlickException { } @Override public void render(GameContainer gameContainer, StateBasedGame stateBasedGame, Graphics graphics) throws SlickException { if (Display.wasResized()) { GL11.glViewport(0, 0, Display.getWidth(), Display.getHeight()); // Doesnt // work, // FIXME } LastTry.camera.set(); LastTry.world.render(); LastTry.player.render(); LastTry.camera.unset(); int mouseX = LastTry.input.getMouseX(); int mouseY = LastTry.input.getMouseY(); Assets.radialTexture.draw(mouseX - mouseX % Block.TEX_SIZE - 48 - LastTry.camera.getX() % Block.TEX_SIZE, mouseY - mouseY % Block.TEX_SIZE - 48 - LastTry.camera.getY() % Block.TEX_SIZE); // TODO: fix it position int hp = LastTry.player.getHp(); int x = LastTry.getWindowWidth() - 260; Assets.font.drawString(x, 4, String.format("Life: %d/%d", hp, LastTry.player.getMaxHp())); for (int i = 0; i < hp / 20; i++) { Assets.hpTexture.draw(x + i * 22 + i * 2, 28); } LastTry.ui.render(); LastTry.debug.render(); } @Override public void update(GameContainer gameContainer, StateBasedGame stateBasedGame, int dt) throws SlickException { LastTry.world.update(dt); LastTry.player.update(dt); LastTry.camera .setPosition( Math.min((LastTry.world.getWidth() - 1) * Block.TEX_SIZE - LastTry.getWindowWidth(), Math.max(Block.TEX_SIZE, LastTry.player.getX() + LastTry.player.getWidth() / 2 - LastTry.getWindowWidth() / 2)), Math.min((LastTry.world.getHeight() - 1) * Block.TEX_SIZE - LastTry.getWindowHeight(), Math.max( Block.TEX_SIZE, LastTry.player.getY() + LastTry.player.getHeight() / 2 - LastTry.getWindowHeight() / 2))); if (LastTry.input.isKeyPressed(Input.KEY_TAB)) { LastTry.debug.toggle(); this.enemy.die(); } } }
package org.gbif.api.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation that marks a resource method to throw a NotFoundException (becomes http 404) * when null is returned by the method. */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface NullToNotFound { /** * Resource URI which was not found. */ String value() default "/"; }
package org.jtrfp.trcl.obj; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.concurrent.CopyOnWriteArrayList; import javax.imageio.ImageIO; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.math3.geometry.euclidean.threed.Rotation; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.jtrfp.trcl.RenderableSpacePartitioningGrid; import org.jtrfp.trcl.core.Features; import org.jtrfp.trcl.core.TRFactory; import org.jtrfp.trcl.core.TRFactory.TR; import org.jtrfp.trcl.ext.tr.GPUFactory.GPUFeature; import org.jtrfp.trcl.game.Game; import org.jtrfp.trcl.gpu.Texture; import org.jtrfp.trcl.gpu.TextureManager; import org.jtrfp.trcl.gpu.VQTexture; import org.jtrfp.trcl.math.Vect3D; import org.jtrfp.trcl.shell.GameShellFactory.GameShell; public class NAVRadarBlipFactory implements NAVRadarBlipFactoryListener { private static final int POOL_SIZE=15; private static final int RADAR_RANGE=800000; private static final double DEFAULT_RADAR_GUI_RADIUS=.17; private Double radarGUIRadius; //private static final double RADAR_SCALAR=RADAR_GUI_RADIUS/RADAR_RANGE; private final Blip [][] blipPool = new Blip[BlipType.values().length][POOL_SIZE]; private final int []poolIndices = new int[POOL_SIZE]; private final TR tr; //private final DashboardLayout layout; private Vector3D topOrigin = Vector3D.PLUS_J, headingOrigin = Vector3D.PLUS_K; private Vector3D positionOrigin = Vector3D.ZERO; private Rotation vectorHack = Rotation.IDENTITY; private Collection<Blip> activeBlips = new ArrayList<Blip>(); private Collection<NAVRadarBlipFactoryListener> listeners = new ArrayList<NAVRadarBlipFactoryListener>(); private boolean radarEnabled = true; private GameShell gameShell; private final RenderableSpacePartitioningGrid grid; final Collection<Blip> newActiveBlips = new ArrayList<Blip>(); final HashSet<Blip> newlyEnabledBlips = new HashSet<Blip>(); public NAVRadarBlipFactory(TR tr, RenderableSpacePartitioningGrid g, String debugName, boolean ignoreCamera){ this(tr,g,null,debugName,ignoreCamera); } public NAVRadarBlipFactory(TR tr, RenderableSpacePartitioningGrid g, Double radarGUIRadius, String debugName, boolean ignoreCamera){ this.tr =tr; this.grid =g; setRadarGUIRadius(radarGUIRadius); final BlipType [] types = BlipType.values(); final TextureManager textureManager = Features.get(tr, GPUFeature.class).textureManager.get(); for(int ti=0; ti<types.length; ti++){ InputStream is = null; try{ final VQTexture tex = textureManager.newTexture(ImageIO.read(is = this.getClass().getResourceAsStream("/"+types[ti].getSprite())),null,"",false, true); for(int pi=0; pi<POOL_SIZE; pi++){ final Blip blip = new Blip(tex,debugName, ignoreCamera, .04*(getRadarGUIRadius()/DEFAULT_RADAR_GUI_RADIUS)); blip.setVisible(false); blipPool[ti][pi]= blip; //g.add(blip); }//end for(pi) }catch(Exception e){e.printStackTrace();} finally{try{if(is!=null)is.close();}catch(Exception e){e.printStackTrace();}} }//end for(ti) }//end constructor public static enum BlipType{ AIR_ABOVE("RedPlus.png"), AIR_BELOW("RedMinus.png"), GRND_ABOVE("CyanPlus.png"), GRND_BELOW("CyanMinus.png"), PWR_ABOVE("BluePlus.png"), PWR_BELOW("BlueMinus.png"), TUN_ABOVE("YellowPlus.png"), TUN_BELOW("YellowMinus.png"); private final String blipSprite; private BlipType(String blipSprite){ this.blipSprite=blipSprite; }//end constructor public String getSprite(){return blipSprite;} }//end BlipType private class Blip extends Sprite2D{ private Positionable representativeObject; public Blip(Texture tex, String debugName, boolean ignoreCamera, double diameter) { super(0,diameter,diameter,tex,true,debugName); setImmuneToOpaqueDepthTest(true); if(!ignoreCamera) unsetRenderFlag(RenderFlags.IgnoreCamera); }//end constructor public void setRepresentativeObject(Positionable representativeObject) { this.representativeObject = representativeObject; } public void refreshPosition() { setVisible(isRadarEnabled()); if(!isRadarEnabled()) return; final double []blipPos = getPosition(); final Game game = getGameShell().getGame(); final double [] playerPos=game.getPlayer().getPosition(); TRFactory.twosComplimentSubtract(representativeObject.getPosition(), playerPos, blipPos); Vect3D.scalarMultiply(blipPos, getRadarScalar(), blipPos); final double [] heading = game.getPlayer().getHeadingArray(); double hX=heading[0]; double hY=heading[2]; double norm = Math.sqrt(hX*hX+hY*hY); if(norm!=0){ hX/=norm;hY/=norm; }else{hX=1;hY=0;} blipPos[1]=blipPos[2]; blipPos[2]=0; double newX=blipPos[0]*hY-blipPos[1]*hX; double newY=blipPos[0]*hX+blipPos[1]*hY; blipPos[0]=-newX; blipPos[1]= newY; Rotation rot = new Rotation(Vector3D.PLUS_J, Vector3D.PLUS_K, getTopOrigin(), getHeadingOrigin()); final Vector3D rotationResult = rot.applyTo(getVectorHack().applyTo(new Vector3D(blipPos))); blipPos[0] = rotationResult.getX(); blipPos[1] = rotationResult.getY(); blipPos[2] = rotationResult.getZ(); setHeading(getHeadingOrigin().negate()); setTop(getTopOrigin()); final Vector3D bp = getPositionOrigin(); blipPos[0]+=bp.getX(); blipPos[1]+=bp.getY(); blipPos[2]+=bp.getZ(); notifyPositionChange(); }//end refreshPosition() }//end Blip private final Collection<Blip> activeBlipBuffer = new CopyOnWriteArrayList<Blip>(); public void refreshActiveBlips(){ synchronized(activeBlips){ activeBlipBuffer.addAll(activeBlips);} for(Blip b: activeBlipBuffer) b.refreshPosition(); activeBlipBuffer.clear(); }//end refreshActiveBlips() protected Blip submitRadarBlip(Positionable positionable){ if(! (positionable instanceof DEFObject || positionable instanceof PowerupObject || positionable instanceof TunnelEntranceObject) ) return null; final double [] otherPos = positionable.getPosition(); final double [] playerPos=getGameShell().getGame().getPlayer().getPosition(); BlipType type=null; if(TRFactory.twosComplimentDistance(playerPos, otherPos)<RADAR_RANGE){ if(positionable instanceof TunnelEntranceObject){ if(!((TunnelEntranceObject)positionable).isVisible()) return null;//Invisible entrances are no-go. } if(otherPos[1]>playerPos[1]){ //Higher if(positionable instanceof DEFObject){ final DEFObject def = (DEFObject)positionable; if(!def.isFoliage() && (!def.isMobile())||(def.isGroundLocked())){ type=BlipType.GRND_ABOVE; }else if(def.isMobile()&&!def.isGroundLocked()){ type=BlipType.AIR_ABOVE; } }else if(positionable instanceof PowerupObject || positionable instanceof Jumpzone || positionable instanceof Checkpoint){ type=BlipType.PWR_ABOVE; }else if(positionable instanceof TunnelEntranceObject){ type=BlipType.TUN_ABOVE; }//end if(TunnelEntranceObject) }else{ //Lower if(positionable instanceof DEFObject){ final DEFObject def = (DEFObject)positionable; if(!def.isFoliage() && (!def.isMobile())||(def.isGroundLocked())){ type=BlipType.GRND_BELOW; }else if(def.isMobile()&&!def.isGroundLocked()){ type=BlipType.AIR_BELOW; } }else if(positionable instanceof PowerupObject || positionable instanceof Jumpzone || positionable instanceof Checkpoint){ type=BlipType.PWR_BELOW; }else if(positionable instanceof TunnelEntranceObject){ type=BlipType.TUN_BELOW; }//end if(TunnelEntranceObject) }//end lower if(type!=null){ final Blip blip = newBlip(type); blip.setRepresentativeObject(positionable); blip.refreshPosition();//TODO: Use listeners instead? return blip; }//end if(type == null) }//end if(RADAR_RANGE) return null; }//end submitRadarBlip(...) public void refreshBlips(Collection<WorldObject> newBlipObjects){ resetBlipCounters(); final Collection<Blip> oldActiveBlips = activeBlipBuffer; final Collection<Blip> activeBlipBuffer = this.activeBlipBuffer; final Collection<Blip> newActiveBlips = this.newActiveBlips; final Collection<Blip> activeBlips = this.activeBlips; final Collection<Blip> newlyEnabledBlips = this.newlyEnabledBlips; synchronized(activeBlips){ activeBlipBuffer.clear(); activeBlipBuffer.addAll(activeBlips); activeBlips.clear();} newActiveBlips.clear(); for(WorldObject wo : newBlipObjects){ final Blip blip = submitRadarBlip(wo); if(blip != null) newActiveBlips.add(blip); } synchronized(activeBlips){ activeBlips.clear(); activeBlips.addAll(newActiveBlips); } if(!newActiveBlips.equals(activeBlips)) throw new RuntimeException("Activeblips mismatch!"); newlyEnabledBlips.clear(); newlyEnabledBlips.addAll(newActiveBlips); newlyEnabledBlips.removeAll(oldActiveBlips); //final Collection<Blip> enabledBlips = CollectionUtils.subtract(newActiveBlips, oldActiveBlips); final Collection<Blip> disabledBlips = CollectionUtils.subtract(oldActiveBlips, newActiveBlips); if(CollectionUtils.containsAny(newlyEnabledBlips, disabledBlips)) throw new RuntimeException("Enabled and disabled contain same"); if(CollectionUtils.containsAny(newlyEnabledBlips, oldActiveBlips)) throw new RuntimeException("Old and enabled contain same"); enableNewBlips(newlyEnabledBlips); disableBlips(disabledBlips); for(NAVRadarBlipFactoryListener l:listeners) l.refreshBlips(newBlipObjects); }//end refreshBlips(...) protected void enableNewBlips(Collection<Blip> newBlipsToActivate){ grid.addAll(newBlipsToActivate); } protected void disableBlips(Collection<Blip> newBlipsToDeactivate){ grid.removeAll(newBlipsToDeactivate); } private Blip newBlip(BlipType t){ Blip result = blipPool[t.ordinal()][poolIndices[t.ordinal()]++]; poolIndices[t.ordinal()]%=poolIndices.length; return result; } protected void resetBlipCounters(){ for( int i = 0; i < poolIndices.length; i++ ) poolIndices[i]=0;//reset index }//end resetBlipCounters() protected void clearUnusedRadarBlips(Collection<Blip> previouslyActiveBlips){ final ArrayList<Blip> blipsToRemove = new ArrayList<Blip>(); final int numPools = blipPool.length; for(int poolTypeIndex = 0; poolTypeIndex < numPools; poolTypeIndex++){ final Blip [] pool = blipPool[poolTypeIndex]; int blipStartIndex = poolIndices[poolTypeIndex]; for(int blipIndex = blipStartIndex; blipIndex < POOL_SIZE; blipIndex++){ final Blip blip = pool[blipIndex]; if(previouslyActiveBlips.contains(blip)){//Off transient blipsToRemove.add(blip); }//end (off transient) }//end for(blips) }//end for(pools) for(Blip blip : blipsToRemove) blip.setVisible(false);//TODO: Remove from grid }//end clearUnusedRadarBlips() public void clearRadarBlips(){ final Collection<Blip> activeBlips = getActiveBlips(); synchronized(activeBlips){ activeBlips.clear(); } int i=0; for(Blip [] pool:blipPool){ poolIndices[i++]=0;//reset index for(Blip blip : pool) blip.setVisible(false); }//end for(pool) }//end clearRadarBlips() public Vector3D getTopOrigin() { return topOrigin; } public void setTopOrigin(Vector3D topOrigin) { this.topOrigin = topOrigin; } public Vector3D getHeadingOrigin() { return headingOrigin; } public void setHeadingOrigin(Vector3D headingOrigin) { this.headingOrigin = headingOrigin; } public Rotation getVectorHack() { return vectorHack; } public void setVectorHack(Rotation vectorHack) { this.vectorHack = vectorHack; } protected Collection<Blip> getActiveBlips() { return activeBlips; } protected Vector3D getPositionOrigin() { return positionOrigin; } public void setPositionOrigin(Vector3D positionOrigin) { this.positionOrigin = positionOrigin; refreshActiveBlips(); } public Double getRadarGUIRadius() { if(radarGUIRadius == null) radarGUIRadius = DEFAULT_RADAR_GUI_RADIUS; return radarGUIRadius; } protected void setRadarGUIRadius(Double radarGUIRadius) { this.radarGUIRadius = radarGUIRadius; } protected double getRadarScalar(){ return getRadarGUIRadius()/RADAR_RANGE; } public void addBlipListener(NAVRadarBlipFactoryListener listener) { listeners.add(listener); } public void removeBlipListener(NAVRadarBlipFactoryListener listener) { listeners.remove(listener); } public boolean isRadarEnabled() { return radarEnabled; } public void setRadarEnabled(boolean radarEnabled) { this.radarEnabled = radarEnabled; refreshActiveBlips(); } public GameShell getGameShell() { if(gameShell == null){ gameShell = Features.get(getTr(), GameShell.class);} return gameShell; } public void setGameShell(GameShell gameShell) { this.gameShell = gameShell; } public TR getTr(){ return tr; } }//end NAVRadarBlipFactory
package org.jusecase.properties.ui; import net.miginfocom.swing.MigLayout; import org.jusecase.properties.usecases.*; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import java.awt.*; import java.io.File; import java.util.function.Consumer; public class Application { private UsecaseExecutor usecaseExecutor = new UsecaseExecutor(); private JFrame frame; private JPanel panel; private ApplicationMenuBar menuBar; private JList<String> keyList; KeyListModel keyListModel = new KeyListModel(); private JTextField searchField; private JPanel keyPanel; private TranslationsPanel translationsPanel; public static void main(String args[]) { // TODO adjust for swing Thread.currentThread().setUncaughtExceptionHandler(new ExceptionHandler()); try { System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Test"); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { throw new RuntimeException("Startup failed!", e); } SwingUtilities.invokeLater(() -> { new Application().start(); }); } public void loadProperties(File file) { LoadBundle.Request request = new LoadBundle.Request(); request.propertiesFile = file.toPath(); usecaseExecutor.execute(request, this::onLoadPropertiesComplete); } public void saveProperties() { usecaseExecutor.execute(new SaveBundle.Request()); } public void search(String query) { Search.Request request = new Search.Request(); request.query = query; usecaseExecutor.execute(request, (Consumer<Search.Response>) response -> { keyListModel.setKeys(response.keys); }); } private void onLoadPropertiesComplete(LoadBundle.Response response) { if (response.keys != null) { keyListModel.setKeys(response.keys); translationsPanel.setFileNames(response.fileNames); } } private void start() { initFrame(); initMenuBar(); initPanel(); usecaseExecutor.execute(new Initialize.Request(), this::onLoadPropertiesComplete); } private void initPanel() { panel = new JPanel(new MigLayout("insets 0")); initKeyPanel(); initTranslationsPanel(); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, keyPanel, translationsPanel); splitPane.setDividerLocation(0.3); panel.add(splitPane, "push,grow"); frame.add(panel); } private void initKeyPanel() { keyPanel = new JPanel(new MigLayout("insets 2,fill")); initSearchField(); initKeyList(); } private void initKeyList() { keyList = new JList<>(keyListModel); keyList.setVisibleRowCount(40); JScrollPane scrollPane = new JScrollPane(keyList); keyList.addListSelectionListener(e -> { String key = keyList.getSelectedValue(); if (key != null) { GetProperties.Request request = new GetProperties.Request(); request.key = key; usecaseExecutor.execute(request, (Consumer<GetProperties.Response>) response -> { translationsPanel.setProperties(response.properties); }); } else { translationsPanel.reset(); } }); keyList.setComponentPopupMenu(new KeyListMenu()); keyPanel.add(scrollPane, "wrap,push,grow"); } private void initSearchField() { searchField = new JTextField(); searchField.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { search(searchField.getText()); } @Override public void removeUpdate(DocumentEvent e) { search(searchField.getText()); } @Override public void changedUpdate(DocumentEvent e) { search(searchField.getText()); } }); keyPanel.add(searchField, "wrap,growx"); } private void initMenuBar() { menuBar = new ApplicationMenuBar(this); frame.setJMenuBar(menuBar); } private void initFrame() { frame = new JFrame("Properties Editor"); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); frame.setBounds(0,0,screenSize.width, screenSize.height); frame.setVisible(true); } private void initTranslationsPanel() { translationsPanel = new TranslationsPanel(new MigLayout("insets 2"), this); } public JFrame getFrame() { return frame; } public UsecaseExecutor getUsecaseExecutor() { return usecaseExecutor; } }
package org.lazan.t5.stitch.demo.pages; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import javax.inject.Inject; import org.apache.tapestry5.ComponentResources; import org.apache.tapestry5.StreamResponse; import org.apache.tapestry5.annotations.Cached; import org.apache.tapestry5.annotations.Property; import org.apache.tapestry5.services.Response; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PiePlot3D; import org.jfree.data.DefaultKeyedValues; import org.jfree.data.general.DefaultPieDataset; import org.jfree.data.general.PieDataset; public class PDFDemo { @Property private CountryStats stats; @Inject private ComponentResources componentResources; public static class CountryStats { public int rank; public String country; public int population; public CountryStats(int rank, String country, int population) { super(); this.rank = rank; this.country = country; this.population = population; } } StreamResponse onChart() { DefaultKeyedValues values = new DefaultKeyedValues(); for (CountryStats current : getCountryStats()) { values.addValue(current.country, current.population); } PieDataset pieDataset = new DefaultPieDataset(values); PiePlot3D plot = new PiePlot3D(pieDataset); plot.setForegroundAlpha(0.7f); plot.setDepthFactor(0.1); plot.setCircular(true); final JFreeChart chart = new JFreeChart(plot); chart.removeLegend(); chart.setTitle("Top 10 Country Populations"); return new StreamResponse() { public String getContentType() { return "image/png"; } public InputStream getStream() throws IOException { BufferedImage image = chart.createBufferedImage(400, 370); ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); ChartUtilities.writeBufferedImageAsPNG(byteArray, image); return new ByteArrayInputStream(byteArray.toByteArray()); } public void prepareResponse(Response response) { } }; } public String getChartURI() { return componentResources.createEventLink("chart").toAbsoluteURI(); } @Cached public CountryStats[] getCountryStats() { return new CountryStats[] { new CountryStats(1, "China", 1347350000), new CountryStats(2, "India", 1210193422), new CountryStats(3, "United States", 314814000), new CountryStats(4, "Indonesia", 237641326), new CountryStats(5, "Brazil", 193946886), new CountryStats(6, "Pakistan", 181301000), new CountryStats(7, "Nigeria", 166629000), new CountryStats(8, "Bangladesh", 152518015), new CountryStats(9, "Russia", 143228300), new CountryStats(10, "Japan", 127530000) }; } }
package org.mybatis.jpetstore.domain; import java.io.Serializable; import java.math.BigDecimal; public class Calculate implements Serializable { public void hello() { System.out.println("JPET Store Application"); System.out.println("Class name: Calculate.java"); System.out.println("Hello World"); System.out.println("Making a new Entry at Sat Feb 4 11:00:00 UTC 2017"); System.out.println("Sat Feb 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Feb 2 11:00:00 UTC 2017"); System.out.println("Thu Feb 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 30 11:00:00 UTC 2017"); System.out.println("Mon Jan 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Jan 28 11:00:15 UTC 2017"); System.out.println("Sat Jan 28 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Thu Jan 26 11:00:15 UTC 2017"); System.out.println("Thu Jan 26 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Tue Jan 24 11:00:15 UTC 2017"); System.out.println("Tue Jan 24 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sun Jan 22 11:00:15 UTC 2017"); System.out.println("Sun Jan 22 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Jan 20 11:00:15 UTC 2017"); System.out.println("Fri Jan 20 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Wed Jan 18 11:00:15 UTC 2017"); System.out.println("Wed Jan 18 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 16 11:00:15 UTC 2017"); System.out.println("Mon Jan 16 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sat Jan 14 11:00:15 UTC 2017"); System.out.println("Sat Jan 14 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Thu Jan 12 11:00:15 UTC 2017"); System.out.println("Thu Jan 12 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Tue Jan 10 11:00:15 UTC 2017"); System.out.println("Tue Jan 10 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sun Jan 8 11:00:15 UTC 2017"); System.out.println("Sun Jan 8 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Jan 6 11:00:15 UTC 2017"); System.out.println("Fri Jan 6 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Wed Jan 4 11:00:15 UTC 2017"); System.out.println("Wed Jan 4 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 2 11:00:15 UTC 2017"); System.out.println("Mon Jan 2 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Dec 30 11:00:16 UTC 2016"); System.out.println("Fri Dec 30 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Wed Dec 28 11:00:16 UTC 2016"); System.out.println("Wed Dec 28 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Mon Dec 26 11:00:16 UTC 2016"); System.out.println("Mon Dec 26 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sat Dec 24 11:00:16 UTC 2016"); System.out.println("Sat Dec 24 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Thu Dec 22 11:00:16 UTC 2016"); System.out.println("Thu Dec 22 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Tue Dec 20 11:00:16 UTC 2016"); System.out.println("Tue Dec 20 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sun Dec 18 11:00:16 UTC 2016"); System.out.println("Sun Dec 18 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Fri Dec 16 11:00:16 UTC 2016"); System.out.println("Fri Dec 16 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Wed Dec 14 11:00:16 UTC 2016"); System.out.println("Wed Dec 14 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Mon Dec 12 11:00:16 UTC 2016"); System.out.println("Mon Dec 12 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sat Dec 10 11:00:16 UTC 2016"); System.out.println("Sat Dec 10 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Thu Dec 8 11:00:16 UTC 2016"); System.out.println("Thu Dec 8 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Tue Dec 6 11:00:16 UTC 2016"); System.out.println("Tue Dec 6 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Fri Dec 2 12:52:58 UTC 2016"); System.out.println("Fri Dec 2 12:52:58 UTC 2016"); } } //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck
package org.mybatis.jpetstore.domain; import java.io.Serializable; import java.math.BigDecimal; public class Calculate implements Serializable { public void hello() { System.out.println("Hello World"); } } //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck
package org.ojlang.models.syswords; import org.ojlang.models.contracts.SystemState; /** * Interpreter word. * * @author Bahman Movaqar [Bahman AT BahmanM.com] */ public class Interpreter extends AbstractSystemWord { final static private long serialVersionUID = -1299211002338774173L; @Override public SystemState execute( SystemState systat ) { throw new UnsupportedOperationException(); } @Override public String name() { return "INTERPRETER"; } }
package org.yaml.snakeyaml.emitter; import java.io.IOException; import java.io.Writer; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.TreeSet; import java.util.regex.Pattern; import org.yaml.snakeyaml.YamlConfig; import org.yaml.snakeyaml.events.AliasEvent; import org.yaml.snakeyaml.events.CollectionEndEvent; import org.yaml.snakeyaml.events.CollectionStartEvent; import org.yaml.snakeyaml.events.DocumentEndEvent; import org.yaml.snakeyaml.events.DocumentStartEvent; import org.yaml.snakeyaml.events.Event; import org.yaml.snakeyaml.events.MappingEndEvent; import org.yaml.snakeyaml.events.MappingStartEvent; import org.yaml.snakeyaml.events.NodeEvent; import org.yaml.snakeyaml.events.ScalarEvent; import org.yaml.snakeyaml.events.SequenceEndEvent; import org.yaml.snakeyaml.events.SequenceStartEvent; import org.yaml.snakeyaml.events.StreamEndEvent; import org.yaml.snakeyaml.events.StreamStartEvent; /** * <pre> * Emitter expects events obeying the following grammar: * stream ::= STREAM-START document* STREAM-END * document ::= DOCUMENT-START node DOCUMENT-END * node ::= SCALAR | sequence | mapping * sequence ::= SEQUENCE-START node* SEQUENCE-END * mapping ::= MAPPING-START (node node)* MAPPING-END * </pre> * * @see PyYAML 3.06 for more information */ public class EmitterImpl implements Emitter { private static final Map<Character, String> ESCAPE_REPLACEMENTS = new HashMap<Character, String>(); static { ESCAPE_REPLACEMENTS.put(new Character('\0'), "0"); ESCAPE_REPLACEMENTS.put(new Character('\u0007'), "a"); ESCAPE_REPLACEMENTS.put(new Character('\u0008'), "b"); ESCAPE_REPLACEMENTS.put(new Character('\u0009'), "t"); ESCAPE_REPLACEMENTS.put(new Character('\n'), "n"); ESCAPE_REPLACEMENTS.put(new Character('\u000B'), "v"); ESCAPE_REPLACEMENTS.put(new Character('\u000C'), "f"); ESCAPE_REPLACEMENTS.put(new Character('\r'), "r"); ESCAPE_REPLACEMENTS.put(new Character('\u001B'), "e"); ESCAPE_REPLACEMENTS.put(new Character('"'), "\""); ESCAPE_REPLACEMENTS.put(new Character('\\'), "\\"); ESCAPE_REPLACEMENTS.put(new Character('\u0085'), "N"); ESCAPE_REPLACEMENTS.put(new Character('\u00A0'), "_"); ESCAPE_REPLACEMENTS.put(new Character('\u2028'), "L"); ESCAPE_REPLACEMENTS.put(new Character('\u2029'), "P"); } private final static Map<String, String> DEFAULT_TAG_PREFIXES = new HashMap<String, String>(); static { DEFAULT_TAG_PREFIXES.put("!", "!"); DEFAULT_TAG_PREFIXES.put("tag:yaml.org,2002:", "!!"); } // The stream should have the methods `write` and possibly `flush`. private Writer stream; // Encoding is defined by Writer (cannot be overriden by STREAM-START.) // private Charset encoding; // Emitter is a state machine with a stack of states to handle nested // structures. private LinkedList<EmitterState> states; private EmitterState state; // Current event and the event queue. private Queue<Event> events; private Event event; // The current indentation level and the stack of previous indents. private LinkedList<Integer> indents; private Integer indent; // Flow level. private int flowLevel; // Contexts. private boolean mappingContext; private boolean simpleKeyContext; // Characteristics of the last emitted character: // - current position. // - is it a whitespace? // - is it an indention character // (indentation space, '-', '?', or ':')? private int line; private int column; private boolean whitespace; private boolean indention; // Formatting details. private Boolean canonical; private int bestIndent; private int bestWidth; private String bestLineBreak; // Tag prefixes. private Map<String, String> tagPrefixes; // Prepared anchor and tag. private String preparedAnchor; private String preparedTag; // Scalar analysis and style. private ScalarAnalysis analysis; private char style = 0; public EmitterImpl(Writer stream, YamlConfig opts) { // The stream should have the methods `write` and possibly `flush`. this.stream = stream; // Emitter is a state machine with a stack of states to handle nested // structures. this.states = new LinkedList<EmitterState>(); this.state = new ExpectStreamStart(); // Current event and the event queue. this.events = new LinkedList<Event>(); this.event = null; // The current indentation level and the stack of previous indents. this.indents = new LinkedList<Integer>(); this.indent = null; // Flow level. this.flowLevel = 0; // Contexts. mappingContext = false; simpleKeyContext = false; // Characteristics of the last emitted character: // - current position. // - is it a whitespace? // - is it an indention character // (indentation space, '-', '?', or ':')? line = 0; column = 0; whitespace = true; indention = true; // Formatting details. this.canonical = opts.isCanonical(); this.bestIndent = 2; if ((opts.getIndent() > 1) && (opts.getIndent() < 10)) { this.bestIndent = opts.getIndent(); } this.bestWidth = 80; if (opts.getWidth() > this.bestIndent * 2) { this.bestWidth = opts.getWidth(); } this.bestLineBreak = "\n"; if (opts.getLineBreak().equals("\n") || opts.getLineBreak().equals("\r") || opts.getLineBreak().equals("\r\n")) { this.bestLineBreak = opts.getLineBreak(); } // Tag prefixes. this.tagPrefixes = new HashMap<String, String>(); // Prepared anchor and tag. this.preparedAnchor = null; this.preparedTag = null; // Scalar analysis and style. this.analysis = null; this.style = (char) 0; } public void emit(final Event event) throws IOException { this.events.offer(event); while (!needMoreEvents()) { this.event = this.events.poll(); this.state.expect(); this.event = null; } } // In some cases, we wait for a few next events before emitting. private boolean needMoreEvents() { if (events.isEmpty()) { return true; } Event event = events.peek(); if (event instanceof DocumentStartEvent) { return needEvents(1); } else if (event instanceof SequenceStartEvent) { return needEvents(2); } else if (event instanceof MappingStartEvent) { return needEvents(3); } else { return false; } } private boolean needEvents(int count) { int level = 0; Iterator<Event> iter = events.iterator(); iter.next(); while (iter.hasNext()) { Event event = iter.next(); if (event instanceof DocumentStartEvent || event instanceof CollectionStartEvent) { level++; } else if (event instanceof DocumentEndEvent || event instanceof CollectionEndEvent) { level } else if (event instanceof StreamEndEvent) { level = -1; } if (level < 0) { return false; } } return events.size() < count + 1; } private void increaseIndent(boolean flow, boolean indentless) { indents.push(indent); if (indent == null) { if (flow) { indent = bestIndent; } else { indent = 0; } } else if (!indentless) { this.indent += bestIndent; } } // States // Stream handlers. private class ExpectStreamStart implements EmitterState { public void expect() throws IOException { if (event instanceof StreamStartEvent) { writeStreamStart(); state = new ExpectFirstDocumentStart(); } else { throw new EmitterException("expected StreamStartEvent, but got " + event); } } } private class ExpectNothing implements EmitterState { public void expect() throws IOException { throw new EmitterException("expecting nothing, but got " + event); } } // Document handlers. private class ExpectFirstDocumentStart implements EmitterState { public void expect() throws IOException { new ExpectDocumentStart(true).expect(); } } private class ExpectDocumentStart implements EmitterState { private boolean first; public ExpectDocumentStart(boolean first) { this.first = first; } public void expect() throws IOException { if (event instanceof DocumentStartEvent) { DocumentStartEvent ev = (DocumentStartEvent) event; if (ev.getVersion() != null) { String versionText = prepareVersion(ev.getVersion()); writeVersionDirective(versionText); } tagPrefixes = new HashMap<String, String>(DEFAULT_TAG_PREFIXES); if (ev.getTags() != null) { Set<String> handles = new TreeSet<String>(ev.getTags().keySet()); for (String handle : handles) { String prefix = ev.getTags().get(handle); tagPrefixes.put(prefix, handle); String handleText = prepareTagHandle(handle); String prefixText = prepareTagPrefix(prefix); writeTagDirective(handleText, prefixText); } } boolean implicit = first && !ev.getExplicit() && !canonical && ev.getVersion() == null && ev.getTags() == null && !checkEmptyDocument(); if (!implicit) { writeIndent(); writeIndicator("---", true, false, false); if (canonical) { writeIndent(); } } state = new ExpectDocumentRoot(); } else if (event instanceof StreamEndEvent) { writeStreamEnd(); state = new ExpectNothing(); } else { throw new EmitterException("expected DocumentStartEvent, but got " + event); } } } private class ExpectDocumentEnd implements EmitterState { public void expect() throws IOException { if (event instanceof DocumentEndEvent) { writeIndent(); if (((DocumentEndEvent) event).getExplicit()) { writeIndicator("...", true, false, false); writeIndent(); } flushStream(); state = new ExpectDocumentStart(false); } else { throw new EmitterException("expected DocumentEndEvent, but got " + event); } } } private class ExpectDocumentRoot implements EmitterState { public void expect() throws IOException { states.push(new ExpectDocumentEnd()); expectNode(true, false, false, false); } } // Node handlers. private void expectNode(boolean root, boolean sequence, boolean mapping, boolean simpleKey) throws IOException { mappingContext = mapping; simpleKeyContext = simpleKey; if (event instanceof AliasEvent) { expectAlias(); } else if (event instanceof ScalarEvent || event instanceof CollectionStartEvent) { processAnchor("&"); processTag(); if (event instanceof ScalarEvent) { expectScalar(); } else if (event instanceof SequenceStartEvent) { if (flowLevel != 0 || canonical || ((SequenceStartEvent) event).getFlowStyle() || checkEmptySequence()) { expectFlowSequence(); } else { expectBlockSequence(); } } else if (event instanceof MappingStartEvent) { if (flowLevel != 0 || canonical || ((MappingStartEvent) event).getFlowStyle() || checkEmptyMapping()) { expectFlowMapping(); } else { expectBlockMapping(); } } } else { throw new EmitterException("expected NodeEvent, but got " + event); } } private void expectAlias() throws IOException { if (((NodeEvent) event).getAnchor() == null) { throw new EmitterException("anchor is not specified for alias"); } processAnchor("*"); state = states.pop(); } private void expectScalar() throws IOException { increaseIndent(true, false); processScalar(); indent = indents.pop(); state = states.pop(); } // Flow sequence handlers. private void expectFlowSequence() throws IOException { writeIndicator("[", true, true, false); flowLevel++; increaseIndent(true, false); state = new ExpectFirstFlowSequenceItem(); } private class ExpectFirstFlowSequenceItem implements EmitterState { public void expect() throws IOException { if (event instanceof SequenceEndEvent) { indent = indents.pop(); flowLevel writeIndicator("]", false, false, false); state = states.pop(); } else { if (canonical || column > bestWidth) { writeIndent(); } states.push(new ExpectFlowSequenceItem()); expectNode(false, true, false, false); } } } private class ExpectFlowSequenceItem implements EmitterState { public void expect() throws IOException { if (event instanceof SequenceEndEvent) { indent = indents.pop(); flowLevel if (canonical) { writeIndicator(",", false, false, false); writeIndent(); } writeIndicator("]", false, false, false); state = states.pop(); } else { writeIndicator(",", false, false, false); if (canonical || column > bestWidth) { writeIndent(); } states.push(new ExpectFlowSequenceItem()); expectNode(false, true, false, false); } } } // Flow mapping handlers. private void expectFlowMapping() throws IOException { writeIndicator("{", true, true, false); flowLevel++; increaseIndent(true, false); state = new ExpectFirstFlowMappingKey(); } private class ExpectFirstFlowMappingKey implements EmitterState { public void expect() throws IOException { if (event instanceof MappingEndEvent) { indent = indents.pop(); flowLevel writeIndicator("}", false, false, false); state = states.pop(); } else { if (canonical || column > bestWidth) { writeIndent(); } if (!canonical && checkSimpleKey()) { states.push(new ExpectFlowMappingSimpleValue()); expectNode(false, false, true, true); } else { writeIndicator("?", true, false, false); states.push(new ExpectFlowMappingValue()); expectNode(false, false, true, false); } } } } private class ExpectFlowMappingKey implements EmitterState { public void expect() throws IOException { if (event instanceof MappingEndEvent) { indent = indents.pop(); flowLevel if (canonical) { writeIndicator(",", false, false, false); writeIndent(); } writeIndicator("}", false, false, false); state = states.pop(); } else { writeIndicator(",", false, false, false); if (canonical || column > bestWidth) { writeIndent(); } if (!canonical && checkSimpleKey()) { states.push(new ExpectFlowMappingSimpleValue()); expectNode(false, false, true, true); } else { writeIndicator("?", true, false, false); states.push(new ExpectFlowMappingValue()); expectNode(false, false, true, false); } } } } private class ExpectFlowMappingSimpleValue implements EmitterState { public void expect() throws IOException { writeIndicator(":", false, false, false); states.push(new ExpectFlowMappingKey()); expectNode(false, false, true, false); } } private class ExpectFlowMappingValue implements EmitterState { public void expect() throws IOException { if (canonical || column > bestWidth) { writeIndent(); } writeIndicator(":", true, false, false); states.push(new ExpectFlowMappingKey()); expectNode(false, false, true, false); } } // Block sequence handlers. private void expectBlockSequence() throws IOException { boolean indentless = (mappingContext && !indention); increaseIndent(false, indentless); state = new ExpectFirstBlockSequenceItem(); } private class ExpectFirstBlockSequenceItem implements EmitterState { public void expect() throws IOException { new ExpectBlockSequenceItem(true).expect(); } } private class ExpectBlockSequenceItem implements EmitterState { private boolean first; public ExpectBlockSequenceItem(boolean first) { this.first = first; } public void expect() throws IOException { if (!this.first && event instanceof SequenceEndEvent) { indent = indents.pop(); state = states.pop(); } else { writeIndent(); writeIndicator("-", true, false, true); states.push(new ExpectBlockSequenceItem(false)); expectNode(false, true, false, false); } } } // Block mapping handlers. private void expectBlockMapping() throws IOException { increaseIndent(false, false); state = new ExpectFirstBlockMappingKey(); } private class ExpectFirstBlockMappingKey implements EmitterState { public void expect() throws IOException { new ExpectBlockMappingKey(true).expect(); } } private class ExpectBlockMappingKey implements EmitterState { private boolean first; public ExpectBlockMappingKey(boolean first) { this.first = first; } public void expect() throws IOException { if (!this.first && event instanceof MappingEndEvent) { indent = indents.pop(); state = states.pop(); } else { writeIndent(); if (checkSimpleKey()) { states.push(new ExpectBlockMappingSimpleValue()); expectNode(false, false, true, true); } else { writeIndicator("?", true, false, true); states.push(new ExpectBlockMappingValue()); expectNode(false, false, true, false); } } } } private class ExpectBlockMappingSimpleValue implements EmitterState { public void expect() throws IOException { writeIndicator(":", false, false, false); states.push(new ExpectBlockMappingKey(false)); expectNode(false, false, true, false); } } private class ExpectBlockMappingValue implements EmitterState { public void expect() throws IOException { writeIndent(); writeIndicator(":", true, false, true); states.push(new ExpectBlockMappingKey(false)); expectNode(false, false, true, false); } } // Checkers. private boolean checkEmptySequence() { return (event instanceof SequenceStartEvent && !events.isEmpty() && events.peek() instanceof SequenceEndEvent); } private boolean checkEmptyMapping() { return (event instanceof MappingStartEvent && !events.isEmpty() && events.peek() instanceof MappingEndEvent); } private boolean checkEmptyDocument() { if (!(event instanceof DocumentStartEvent) || events.isEmpty()) { return false; } Event event = events.peek(); if (event instanceof ScalarEvent) { ScalarEvent e = (ScalarEvent) event; return (e.getAnchor() == null && e.getTag() == null && e.getImplicit() != null && e .getValue() == ""); } else { return false; } } private boolean checkSimpleKey() { int length = 0; if (event instanceof NodeEvent && ((NodeEvent) event).getAnchor() != null) { if (preparedAnchor == null) { preparedAnchor = prepareAnchor(((NodeEvent) event).getAnchor()); } length += preparedAnchor.length(); } String tag = null; if (event instanceof ScalarEvent) { tag = ((ScalarEvent) event).getTag(); } else if (event instanceof CollectionStartEvent) { tag = ((CollectionStartEvent) event).getTag(); } if (tag != null) { if (preparedTag == null) { preparedTag = prepareTag(tag); } length += preparedTag.length(); } if (event instanceof ScalarEvent) { if (analysis == null) { analysis = analyzeScalar(((ScalarEvent) event).getValue()); } length += analysis.scalar.length(); } return (length < 128 && (event instanceof AliasEvent || (event instanceof ScalarEvent && !analysis.empty && !analysis.multiline) || checkEmptySequence() || checkEmptyMapping())); } // Anchor, Tag, and Scalar processors. private void processAnchor(String indicator) throws IOException { NodeEvent ev = (NodeEvent) event; if (ev.getAnchor() == null) { preparedAnchor = null; return; } if (preparedAnchor == null) { preparedAnchor = prepareAnchor(ev.getAnchor()); } if (preparedAnchor != null && !"".equals(preparedAnchor)) { writeIndicator(indicator + preparedAnchor, true, false, false); } preparedAnchor = null; } private void processTag() throws IOException { String tag = null; if (event instanceof ScalarEvent) { ScalarEvent ev = (ScalarEvent) event; tag = ev.getTag(); if (style == 0) { style = chooseScalarStyle(); } if (((!canonical || tag == null) && ((style == 0 && ev.getImplicit()[0]) || (style != 0 && ev .getImplicit()[1])))) { preparedTag = null; return; } if (ev.getImplicit()[0] && tag == null) { tag = "!"; preparedTag = null; } } else { CollectionStartEvent ev = (CollectionStartEvent) event; tag = ev.getTag(); if ((!canonical || tag == null) && ev.getImplicit()) { preparedTag = null; return; } } if (tag == null) { throw new EmitterException("tag is not specified"); } if (preparedTag == null) { preparedTag = prepareTag(tag); } if (preparedTag != null && !"".equals(preparedTag)) { writeIndicator(preparedTag, true, false, false); } preparedTag = null; } private char chooseScalarStyle() { ScalarEvent ev = (ScalarEvent) event; if (analysis == null) { analysis = analyzeScalar(ev.getValue()); } if (ev.getStyle() == '"' || this.canonical) { return '"'; } if (ev.getStyle() == 0 && ev.getImplicit()[0]) { if (!(simpleKeyContext && (analysis.empty || analysis.multiline)) && ((flowLevel != 0 && analysis.allowFlowPlain) || (flowLevel == 0 && analysis.allowBlockPlain))) { return 0; } } if (ev.getStyle() == '|' || ev.getStyle() == '>') { if (flowLevel == 0 && !simpleKeyContext && analysis.allowBlock) { return ev.getStyle(); } } if (ev.getStyle() == 0 || ev.getStyle() == '\'') { if (analysis.allowSingleQuoted && !(simpleKeyContext && analysis.multiline)) { return '\''; } } return '"'; } private void processScalar() throws IOException { ScalarEvent ev = (ScalarEvent) event; if (analysis == null) { analysis = analyzeScalar(ev.getValue()); } if (style == 0) { style = chooseScalarStyle(); } boolean split = !simpleKeyContext; if (style == '"') { writeDoubleQuoted(analysis.scalar, split); } else if (style == '\'') { writeSingleQuoted(analysis.scalar, split); } else if (style == '>') { writeFolded(analysis.scalar); } else if (style == '|') { writeLiteral(analysis.scalar); } else { writePlain(analysis.scalar, split); } analysis = null; style = 0; } // Analyzers. private String prepareVersion(final Integer[] version) { Integer major = version[0]; Integer minor = version[1]; if (major != 1) { throw new EmitterException("unsupported YAML version: " + version[0] + "." + version[1]); } return major.toString() + "." + minor.toString(); } private final static Pattern HANDLE_FORMAT = Pattern.compile("^![-_\\w]*!$"); private String prepareTagHandle(String handle) { if (handle == null || "".equals(handle)) { throw new EmitterException("tag handle must not be empty"); } else if (handle.charAt(0) != '!' || handle.charAt(handle.length() - 1) != '!') { throw new EmitterException("tag handle must start and end with '!': " + handle); } else if (!"!".equals(handle) && !HANDLE_FORMAT.matcher(handle).matches()) { throw new EmitterException("invalid character in the tag handle: " + handle); } return handle; } private String prepareTagPrefix(String prefix) { if (prefix == null || "".equals(prefix)) { throw new EmitterException("tag prefix must not be empty"); } StringBuffer chunks = new StringBuffer(); int start = 0; int end = 0; if (prefix.charAt(0) == '!') { end = 1; } while (end < prefix.length()) { // TODO unclear what is written in PyYAML end++; } if (start < end) { chunks.append(prefix.substring(start, end)); } return chunks.toString(); } private String prepareTag(final String tag) { if (tag == null || "".equals(tag)) { throw new EmitterException("tag must not be empty"); } if (tag.equals("!")) { return tag; } String handle = null; String suffix = tag; for (String prefix : tagPrefixes.keySet()) { if (tag.startsWith(prefix) && (prefix.equals("!") || prefix.length() < tag.length())) { handle = tagPrefixes.get(prefix); suffix = tag.substring(prefix.length()); } } StringBuffer chunks = new StringBuffer(); int start = 0; int end = 0; while (end < suffix.length()) { // TODO unclear PYYAML code end++; } if (start < end) { chunks.append(suffix.substring(start, end)); } String suffixText = chunks.toString(); if (handle != null) { return handle + suffixText; } else { return "!<" + suffixText + ">"; } } private final static Pattern ANCHOR_FORMAT = Pattern.compile("^[-_\\w]*$"); static String prepareAnchor(String anchor) { if (anchor == null || "".equals(anchor)) { throw new EmitterException("anchor must not be empty"); } if (!ANCHOR_FORMAT.matcher(anchor).matches()) { throw new EmitterException("invalid character in the anchor: " + anchor); } return anchor; } private ScalarAnalysis analyzeScalar(final String scalar) { // Empty scalar is a special case. if (scalar == null || "".equals(scalar)) { return new ScalarAnalysis(scalar, true, false, false, true, true, true, false); } // Indicators and special characters. boolean blockIndicators = false; boolean flowIndicators = false; boolean lineBreaks = false; boolean specialCharacters = false; // Whitespaces. boolean leadingSpaces = false; // ^ space+ (non-space | $) boolean leadingBreaks = false; // ^ break+ (non-space | $) boolean trailingSpaces = false; // (^ | non-space) space+ $ boolean trailingBreaks = false; // (^ | non-space) break+ $ boolean inlineBreaksSpaces = false; // non-space break+ space+ non-space boolean mixedBreaksSpaces = false; // anything else // Check document indicators. if (scalar.startsWith("---") || scalar.startsWith("...")) { blockIndicators = true; flowIndicators = true; } // First character or preceded by a whitespace. boolean preceededBySpace = true; boolean followedBySpace = (scalar.length() == 1 || "\0 \t\r\n\u0085\u2029\u2029" .indexOf(scalar.charAt(1)) != -1); // The current series of whitespaces contain plain spaces. boolean spaces = false; // The current series of whitespaces contain line breaks. boolean breaks = false; // The current series of whitespaces contain a space followed by a // break. boolean mixed = false; // The current series of whitespaces start at the beginning of the // scalar. boolean leading = false; int index = 0; while (index < scalar.length()) { char ch = scalar.charAt(index); // Check for indicators. if (index == 0) { // Leading indicators are special characters. if ("#,[]{}&*!|>\'\"%@`".indexOf(ch) != -1) { flowIndicators = true; blockIndicators = true; } if (ch == '?' || ch == ':') { flowIndicators = true; if (followedBySpace) { blockIndicators = true; } } if (ch == '-' && followedBySpace) { flowIndicators = true; blockIndicators = true; } } else { // Some indicators cannot appear within a scalar as well. if (",?[]{}".indexOf(ch) != -1) { flowIndicators = true; } if (ch == ':') { flowIndicators = true; if (followedBySpace) { blockIndicators = true; } } if (ch == '#' && preceededBySpace) { flowIndicators = true; blockIndicators = true; } } // Check for line breaks, special, and unicode characters. if (ch == '\n' || ch == '\u0085' || ch == '\u2028' || ch == '\u2029') { lineBreaks = true; } if (!(ch == '\n' || ('\u0020' <= ch && ch <= '\u007E'))) { if ((ch == '\u0085' || ('\u00A0' <= ch && ch <= '\uD7FF') || ('\uE000' <= ch && ch <= '\uFFFD')) && (ch != '\uFEFF')) { // unicode is used } else { specialCharacters = true; } } // Spaces, line breaks, and how they are mixed. State machine. // Start or continue series of whitespaces. if (" \n\u0085\u2028\u2029".indexOf(ch) != -1) { if (spaces && breaks) { // break+ (space+ break+) => mixed if (ch != ' ') { mixed = true; } } else if (spaces) { // (space+ break+) => mixed if (ch != ' ') { breaks = true; mixed = true; } } else if (breaks) { // break+ space+ if (ch == ' ') { spaces = true; } } else { leading = (index == 0); if (ch == ' ') { // space+ spaces = true; } else { // break+ breaks = true; } } // Series of whitespaces ended with a non-space. } else if (spaces || breaks) { if (leading) { if (spaces && breaks) { mixedBreaksSpaces = true; } else if (spaces) { leadingSpaces = true; } else if (breaks) { leadingBreaks = true; } } else { if (mixed) { mixedBreaksSpaces = true; } else if (spaces && breaks) { inlineBreaksSpaces = true; } } spaces = breaks = mixed = leading = false; } // Series of whitespaces reach the end. if ((spaces || breaks) && (index == scalar.length() - 1)) { if (spaces && breaks) { mixedBreaksSpaces = true; } else if (spaces) { trailingSpaces = true; if (leading) { leadingSpaces = true; } } else if (breaks) { trailingBreaks = true; if (leading) { leadingBreaks = true; } } spaces = breaks = mixed = leading = false; } // Prepare for the next character. index++; preceededBySpace = "\0 \t\r\n\u0085\u2028\u2029".indexOf(ch) != -1; followedBySpace = (index + 1 >= scalar.length() || "\0 \t\r\n\u0085\u2028\u2029" .indexOf(scalar.charAt(index + 1)) != -1); } // Let's decide what styles are allowed. boolean allowFlowPlain = true; boolean allowBlockPlain = true; boolean allowSingleQuoted = true; boolean allowDoubleQuoted = true; boolean allowBlock = true; // Leading and trailing whitespace are bad for plain scalars. We also // do not want to mess with leading whitespaces for block scalars. if (leadingSpaces || leadingBreaks || trailingSpaces) { allowFlowPlain = allowBlockPlain = allowBlock = false; } // Trailing breaks are fine for block scalars, but unacceptable for // plain scalars. if (trailingBreaks) { allowFlowPlain = allowBlockPlain = false; } // The combination of (space+ break+) is only acceptable for block // scalars. if (inlineBreaksSpaces) { allowFlowPlain = allowBlockPlain = allowSingleQuoted = false; } // Mixed spaces and breaks, as well as special character are only // allowed for double quoted scalars. if (mixedBreaksSpaces || specialCharacters) { allowFlowPlain = allowBlockPlain = allowSingleQuoted = allowBlock = false; } // We don't emit multiline plain scalars. if (lineBreaks) { allowFlowPlain = allowBlockPlain = false; } // Flow indicators are forbidden for flow plain scalars. if (flowIndicators) { allowFlowPlain = false; } // Block indicators are forbidden for block plain scalars. if (blockIndicators) { allowBlockPlain = false; } return new ScalarAnalysis(scalar, false, lineBreaks, allowFlowPlain, allowBlockPlain, allowSingleQuoted, allowDoubleQuoted, allowBlock); } // Writers. void flushStream() throws IOException { stream.flush(); } void writeStreamStart() { // BOM is written by Writer. } void writeStreamEnd() throws IOException { flushStream(); } void writeIndicator(String indicator, boolean needWhitespace, boolean whitespace, boolean indentation) throws IOException { String data = null; if (this.whitespace || !needWhitespace) { data = indicator; } else { data = " " + indicator; } this.whitespace = whitespace; this.indention = this.indention && indentation; this.column += data.length(); stream.write(data); } void writeIndent() throws IOException { int indent; if (this.indent != null) { indent = this.indent; } else { indent = 0; } if (!this.indention || this.column > indent || (this.column == indent && !this.whitespace)) { writeLineBreak(null); } if (this.column < indent) { this.whitespace = true; StringBuffer data = new StringBuffer(); for (int i = 0; i < indent - this.column; i++) { data.append(" "); } this.column = indent; stream.write(data.toString()); } } private void writeLineBreak(String data) throws IOException { if (data == null) { data = this.bestLineBreak; } this.whitespace = true; this.indention = true; this.line++; this.column = 0; stream.write(data); } void writeVersionDirective(String versionText) throws IOException { stream.write("%YAML " + versionText); writeLineBreak(null); } void writeTagDirective(String handleText, String prefixText) throws IOException { stream.write("%TAG " + handleText + " " + prefixText); writeLineBreak(null); } // Scalar streams. private void writeSingleQuoted(String text, boolean split) throws IOException { writeIndicator("'", true, false, false); boolean spaces = false; boolean breaks = false; int start = 0, end = 0; char ch; while (end <= text.length()) { ch = 0; if (end < text.length()) { ch = text.charAt(end); } if (spaces) { if (ch == 0 || ch != ' ') { if (start + 1 == end && this.column > this.bestWidth && split && start != 0 && end != text.length()) { writeIndent(); } else { String data = text.substring(start, end); this.column += data.length(); stream.write(data); } start = end; } } else if (breaks) { if (ch == 0 || "\n\u0085\u2028\u2029".indexOf(ch) == -1) { if (text.charAt(start) == '\n') { writeLineBreak(null); } String data = text.substring(start, end); for (int i = 0; i < data.length(); i++) { char br = data.charAt(i); if (br == '\n') { writeLineBreak(null); } else { writeLineBreak(String.valueOf(br)); } } writeIndent(); start = end; } } else { if (ch == 0 || " \n\u0085\u2028\u2029".indexOf(ch) != -1 || ch == '\'') { if (start < end) { String data = text.substring(start, end); this.column += data.length(); stream.write(data); start = end; } } } if (ch == '\'') { String data = "''"; this.column += 2; stream.write(data); start = end + 1; } if (ch != 0) { spaces = ch == ' '; breaks = "\n\u0085\u2028\u2029".indexOf(ch) != -1; } end++; } writeIndicator("'", false, false, false); } private void writeDoubleQuoted(final String text, final boolean split) throws IOException { writeIndicator("\"", true, false, false); int start = 0; int end = 0; while (end <= text.length()) { char ch = 0; if (end < text.length()) { ch = text.charAt(end); } if (ch == 0 || "\"\\\u0085\u2028\u2029\uFEFF".indexOf(ch) != -1 || !('\u0020' <= ch && ch <= '\u007E')) { if (start < end) { String data = text.substring(start, end); this.column += data.length(); stream.write(data); start = end; } if (ch != 0) { String data; if (ESCAPE_REPLACEMENTS.containsKey(new Character(ch))) { data = "\\" + ESCAPE_REPLACEMENTS.get(new Character(ch)); } else if (ch <= '\u00FF') { String s = "0" + Integer.toString(ch, 16); data = "\\x" + s.substring(s.length() - 2); } else { String s = "000" + Integer.toString(ch, 16); data = "\\u" + s.substring(s.length() - 4); } this.column += data.length(); stream.write(data); start = end + 1; } } if ((0 < end && end < (text.length() - 1)) && (ch == ' ' || start >= end) && (this.column + (end - start)) > this.bestWidth && split) { String data = text.substring(start, end) + "\\"; if (start < end) { start = end; } this.column += data.length(); stream.write(data); this.column += data.length(); stream.write(data); writeIndent(); this.whitespace = false; this.indention = false; if (text.charAt(start) == ' ') { data = "\\"; this.column += data.length(); stream.write(data); } } end += 1; } writeIndicator("\"", false, false, false); } private String determineChomp(String text) { String tail = text.substring(text.length() - 2); while (tail.length() < 2) { tail = " " + tail; } char ch1 = tail.charAt(tail.length() - 1); char ch2 = tail.charAt(tail.length() - 2); if ("\n\0085\u2028\u2029".indexOf(ch1) != -1) { if ("\n\0085\u2028\u2029".indexOf(ch2) != -1) { return "+"; } else { return ""; } } else { return "-"; } } void writeFolded(String text) throws IOException { String chomp = determineChomp(text); writeIndicator(">" + chomp, true, false, false); writeIndent(); boolean leadingSpace = false; boolean spaces = false; boolean breaks = false; int start = 0, end = 0; while (end <= text.length()) { char ch = 0; if (end < text.length()) { ch = text.charAt(end); } if (breaks) { if (ch == 0 || ("\n\0085\u2028\u2029".indexOf(ch) == -1)) { if (!leadingSpace && ch != 0 && ch != ' ' && text.charAt(start) == '\n') { writeLineBreak(null); } leadingSpace = (ch == ' '); String data = text.substring(start, end); for (int i = 0; i < data.length(); i++) { char br = data.charAt(i); if (br == '\n') { writeLineBreak(null); } else { writeLineBreak(String.valueOf(br)); } } if (ch != 0) { writeIndent(); } start = end; } } else if (spaces) { if (ch != ' ') { if (start + 1 == end && this.column > this.bestWidth) { writeIndent(); } else { String data = text.substring(start, end); this.column += data.length(); stream.write(data); } start = end; } } else { if (ch == 0 || " \n\0085\u2028\u2029".indexOf(ch) != -1) { String data = text.substring(start, end); stream.write(data); if (ch == 0) { writeLineBreak(null); } start = end; } } if (ch != 0) { breaks = ("\n\0085\u2028\u2029".indexOf(ch) != -1); spaces = (ch == ' '); } end++; } } void writeLiteral(String text) throws IOException { String chomp = determineChomp(text); writeIndicator("|" + chomp, true, false, false); writeIndent(); boolean breaks = false; int start = 0, end = 0; while (end <= text.length()) { char ch = 0; if (end < text.length()) { ch = text.charAt(end); } if (breaks) { if (ch == 0 || "\n\u0085\u2028\u2029".indexOf(ch) == -1) { String data = text.substring(start, end); for (int i = 0; i < data.length(); i++) { char br = data.charAt(i); if (br == '\n') { writeLineBreak(null); } else { writeLineBreak(String.valueOf(br)); } } if (ch != 0) { writeIndent(); } start = end; } } else { if (ch == 0 || "\n\u0085\u2028\u2029".indexOf(ch) != -1) { String data = text.substring(start, end); stream.write(data); if (ch == 0) { writeLineBreak(null); } start = end; } } if (ch != 0) { breaks = ("\n\u0085\u2028\u2029".indexOf(ch) != -1); } end++; } } void writePlain(String text, boolean split) throws IOException { if (text == null || "".equals(text)) { return; } if (!this.whitespace) { String data = " "; this.column += data.length(); stream.write(data); } this.whitespace = false; this.indention = false; boolean spaces = false; boolean breaks = false; int start = 0, end = 0; while (end <= text.length()) { char ch = 0; if (end < text.length()) { ch = text.charAt(end); } if (spaces) { if (ch != ' ') { if (start + 1 == end && this.column > this.bestWidth && split) { writeIndent(); this.whitespace = false; this.indention = false; } else { String data = text.substring(start, end); this.column += data.length(); stream.write(data); } start = end; } } else if (breaks) { if ("\n\u0085\u2028\u2029".indexOf(ch) == -1) { if (text.charAt(start) == '\n') { writeLineBreak(null); } String data = text.substring(start, end); for (int i = 0; i < data.length(); i++) { char br = data.charAt(i); if (br == '\n') { writeLineBreak(null); } else { writeLineBreak(String.valueOf(br)); } } writeIndent(); this.whitespace = false; this.indention = false; start = end; } } else { if (ch == 0 || "\n\u0085\u2028\u2029".indexOf(ch) != -1) { String data = text.substring(start, end); this.column += data.length(); stream.write(data); start = end; } } if (ch != 0) { spaces = (ch == ' '); breaks = ("\n\u0085\u2028\u2029".indexOf(ch) != -1); } end++; } } }
package programminglife.model.drawing; import org.eclipse.collections.impl.factory.Sets; import programminglife.model.GenomeGraph; import programminglife.model.XYCoordinate; import programminglife.utility.Console; import java.util.*; /** * A part of a {@link programminglife.model.GenomeGraph}. It uses a centerNode and a radius. * Roughly, every node reachable within radius steps from centerNode is included in this graph. * When updating the centerNode or the radius, it also updates the Nodes within this SubGraph. */ public class SubGraph { private static final int DEFAULT_DYNAMIC_RADIUS = 50; private static final int DEFAULT_NODE_Y = 50; private static final int BORDER_BUFFER = 40; private static final int MIN_RADIUS_DEFAULT = 50; /** * The amount of padding between layers (horizontal padding). */ private static final double LAYER_PADDING = 20; private static final double DIFF_LAYER_PADDING = 7; private double zoomLevel; /** * The amount of padding between nodes within a Layer (vertical padding). */ private GenomeGraph graph; private LinkedHashMap<Integer, DrawableNode> nodes; private LinkedHashMap<Integer, DrawableNode> rootNodes; private LinkedHashMap<Integer, DrawableNode> endNodes; private ArrayList<Layer> layers; private Map<DrawableNode, Map<DrawableNode, Collection<Integer>>> genomes; private int numberOfGenomes; // TODO: cache topological sorting (inside topoSort(), only recalculate when adding / removing nodes) // important: directly invalidate cache (set to null), because otherwise removed nodes // can't be garbage collected until next call to topoSort() /** * Create a SubGraph from a graph, without any nodes initially. * @param graph The {@link GenomeGraph} that this SubGraph is based on. */ private SubGraph(GenomeGraph graph, double zoomLevel) { this(graph, zoomLevel, new LinkedHashMap<>(), new LinkedHashMap<>(), new LinkedHashMap<>()); } /** * Create a SubGraph with the specified nodes, rootNodes and endNodes. * @param graph The {@link GenomeGraph} that this SubGraph is based on. * @param nodes The nodes of this SubGraph. * @param rootNodes The rootNodes of this SubGraph. * @param endNodes The endNodes of this SubGraph. */ private SubGraph(GenomeGraph graph, double zoomLevel, LinkedHashMap<Integer, DrawableNode> nodes, LinkedHashMap<Integer, DrawableNode> rootNodes, LinkedHashMap<Integer, DrawableNode> endNodes) { this.graph = graph; this.zoomLevel = zoomLevel; this.nodes = nodes; this.rootNodes = rootNodes; this.endNodes = endNodes; this.createLayers(); } /** * Create a SubGraph using a centerNode and a radius around that centerNode. * This SubGraph will include all Nodes within radius steps to a parent, * and then another 2radius steps to a child, and symmetrically the same with children / parents reversed. * @param centerNode The centerNode * @param radius The radius * @param replaceSNPs */ public SubGraph(DrawableSegment centerNode, int radius, boolean replaceSNPs) { this(centerNode, 1, MIN_RADIUS_DEFAULT, Math.max(radius, MIN_RADIUS_DEFAULT), replaceSNPs); Layer firstLayer = layers.get(0); assert (firstLayer != null); firstLayer.setX(0); firstLayer.setDrawLocations(DEFAULT_NODE_Y); this.setRightDrawLocations(this.layers, 0); } /** * Create a SubGraph using a centerNode and a radius around that centerNode. * This SubGraph will include all Nodes within radius steps to a parent, * and then another 2radius steps to a child, and symmetrically the same with children / parents reversed. * @param centerNode The centerNode * @param minRadius The minimum radius. * @param radius The radius * @param replaceSNPs */ SubGraph(DrawableSegment centerNode, double zoomLevel, int minRadius, int radius, boolean replaceSNPs) { assert (minRadius <= radius); this.graph = centerNode.getGraph(); this.zoomLevel = zoomLevel; this.layers = null; this.genomes = new LinkedHashMap<>(); this.numberOfGenomes = graph.getTotalGenomeNumber(); findNodes(this, Collections.singleton(centerNode), new LinkedHashMap<>(), radius); if (replaceSNPs) { this.replaceSNPs(); } calculateGenomes(); layout(); colorize(); } /** * Detect SNPs and replace them. */ public void replaceSNPs() { Map<Integer, DrawableNode> nodesCopy = new LinkedHashMap<>(this.nodes); for (Map.Entry<Integer, DrawableNode> entry : nodesCopy.entrySet()) { DrawableNode parent = entry.getValue(); DrawableSNP snp = parent.createSNPIfPossible(this); if (snp != null) { snp.getMutations().stream().map(DrawableNode::getIdentifier).forEach(id -> { this.nodes.remove(id); parent.getChildren().remove(id); snp.getChild().getParents().remove(id); }); this.nodes.put(snp.getIdentifier(), snp); } } } // TODO: change findParents and findChildren to reliably only find nodes with a *longest* path of at most radius. // (maybe give that their own method, or possibly two methods with a // boolean flag for using longest or shortest path as determining factor for the radius) /** * Find nodes within radius steps from centerNode. * This resets the {@link #nodes}, {@link #rootNodes} and {@link #endNodes} * * @param subGraph The SubGraph to find these nodes for. * @param startNodes The Nodes to start searching from. * @param excludedNodes The nodes that will not be added to this graph, even if they are found. * @param radius The number of steps to search. */ private static void findNodes(SubGraph subGraph, Collection<DrawableNode> startNodes, LinkedHashMap<Integer, DrawableNode> excludedNodes, int radius) { long startTime = System.nanoTime(); subGraph.nodes = new LinkedHashMap<>(); subGraph.rootNodes = new LinkedHashMap<>(); subGraph.endNodes = new LinkedHashMap<>(); /* * The queue for the BFS. This Queue uses null as separators between radii. * Example: A B null C D: first A, then B, then null, so we go to the next layer, then C, then D * layer 1: A B * layer 2: C D */ Queue<FoundNode> queue = new LinkedList<>(); startNodes.forEach(node -> queue.add(new FoundNode(node, null))); queue.add(null); boolean lastRow = radius == 0; while (!queue.isEmpty()) { FoundNode current = queue.poll(); // Note: may still be null if the actual element is null! if (current == null) { radius if (radius == 0) { lastRow = true; } else if (radius < 0) { break; } queue.add(null); continue; } if (!startNodes.contains(current.node) && excludedNodes.containsKey(current.node.getIdentifier())) { continue; } // save this node, save the result to check whether we had found it earlier. DrawableNode previous = subGraph.nodes.put(current.node.getIdentifier(), current.node); if (lastRow) { // last row, add this node to rootNodes / endNodes even if we already found this node // (for when a node is both a root and an end node) if (current.foundFrom == FoundNode.FoundFrom.CHILD && (previous == null || subGraph.endNodes.containsKey(current.node.getIdentifier()))) { subGraph.rootNodes.put(current.node.getIdentifier(), current.node); } else if (current.foundFrom == FoundNode.FoundFrom.PARENT && (previous == null || subGraph.rootNodes.containsKey(current.node.getIdentifier()))) { subGraph.endNodes.put(current.node.getIdentifier(), current.node); } // else: current.foundFrom == null, true for the centerNode. // Note: since radius is always at least MIN_RADIUS, we could else instead of else if. // But that would be premature optimization. } else if (previous != null) { // we already found this node, continue to next node. assert (previous.equals(current.node)); } else { // this is not the last row, and this node was not added yet Collection<Integer> children = current.node.getChildren(); Collection<Integer> parents = current.node.getParents(); children.forEach(node -> { queue.add( new FoundNode(new DrawableSegment(subGraph.graph, node), FoundNode.FoundFrom.PARENT)); }); parents.forEach(node -> { queue.add( new FoundNode(new DrawableSegment(subGraph.graph, node), FoundNode.FoundFrom.CHILD)); }); } } long endTime = System.nanoTime(); long difference = endTime - startTime; double difInSeconds = difference / 1000000000.0; Console.println("Time for finding nodes: %f s", difInSeconds); } /** * Checks whether a dynamic load is necessary. This includes both loading new nodes * into the datastructure as well as removing nodes from the datastructure. * @param leftBorder The left border of the canvas. * @param rightBorder The right border of the canvas. */ public void checkDynamicLoad(int leftBorder, double rightBorder) { assert (leftBorder < rightBorder); if (layers.get(BORDER_BUFFER).getX() > leftBorder) { this.addFromRootNodes(SubGraph.DEFAULT_DYNAMIC_RADIUS); } if (layers.get(layers.size() - BORDER_BUFFER - 1).getX() < rightBorder) { this.addFromEndNodes(SubGraph.DEFAULT_DYNAMIC_RADIUS); } int amountOfLayersLeft = 0; int amountOfLayersRight = 0; for (int i = 0; i < layers.size(); i++) { if (layers.get(i).getX() < 0) { amountOfLayersLeft++; } else if (layers.get(i).getX() > rightBorder) { amountOfLayersRight = layers.size() - i; break; } } if (amountOfLayersLeft > 3 * BORDER_BUFFER) { removeLeftLayers(BORDER_BUFFER); } if (amountOfLayersRight > 3 * BORDER_BUFFER) { removeRightLayers(BORDER_BUFFER); } System.out.println(this.nodes.size()); } /** * Removes layers from the right of the graph. * @param numberOfLayers The number of layers to remove from the graph. */ private void removeRightLayers(int numberOfLayers) { for (Layer layer : this.layers.subList(this.layers.size() - numberOfLayers, this.layers.size())) { layer.forEach(node -> this.nodes.remove(node.getIdentifier())); } this.layers = new ArrayList<>(this.layers.subList(0, this.layers.size() - numberOfLayers)); this.endNodes = new LinkedHashMap<>(); this.layers.get(this.layers.size() - 1). forEach(node -> endNodes.put(node.getIdentifier(), node)); } /** * Removes layers from the left of the graph. * @param numberOfLayers The number of layers to remove from the graph. */ private void removeLeftLayers(int numberOfLayers) { for (Layer layer : this.layers.subList(0, numberOfLayers)) { layer.forEach(node -> this.nodes.remove(node.getIdentifier())); } this.layers = new ArrayList<>(this.layers.subList(numberOfLayers, this.layers.size())); this.rootNodes = new LinkedHashMap<>(); this.layers.get(0). forEach(node -> rootNodes.put(node.getIdentifier(), node)); } /** * A class for keeping track of how a Node was found. Only used within {@link SubGraph#findNodes}. */ private static final class FoundNode { /** * Whether a node was found from a parent or a child. */ private enum FoundFrom { PARENT, CHILD } private DrawableNode node; private FoundFrom foundFrom; /** * simple constructor for a FoundNode. * @param node The node that was found. * @param foundFrom Whether it was found from a parent or a child. */ private FoundNode(DrawableNode node, FoundFrom foundFrom) { this.node = node; this.foundFrom = foundFrom; } } /** * Find out which {@link Drawable} is at the given location. * * @param loc The location to search for Drawables. * @return The {@link Drawable} that is on top at the given location. */ public Drawable atLocation(XYCoordinate loc) { return this.atLocation(loc.getX(), loc.getY()); } /** * Find out which {@link Drawable} is at the given location. * * @param x The x coordinate * @param y The y coordinate * @return The {@link Drawable} that is on top at the given location. */ public Drawable atLocation(double x, double y) { int layerIndex = getLayerIndex(this.layers, x); // TODO: implement; // 1: check that x is actually within the layer. // 2: check nodes in layer for y coordinate. throw new Error("Not implemented yet"); } /** * Get the index of the {@link Layer} closest to an x coordinate. * If two layers are equally close (x is exactly in the middle of end * of left layer and start of the right layer), the right Layer is returned, as this * one is likely to have nodes closer (nodes in the left layer do not necessarily extend to the end) * @param x The coordinate * @param layers The list of layers to look through. * @return The index of the closest layer. */ private int getLayerIndex(List<Layer> layers, double x) { int resultIndex = Collections.binarySearch(layers, x); if (resultIndex >= layers.size()) { // x is right outside list, last layer is closest. return layers.size() - 1; } else if (resultIndex >= 0) { // x is exactly at the start of a layer, that layer is closest. return resultIndex; } else { // x < 0, -x is the closest layer on the right, -x - 1 is the closest // layer on the left. (see binarySearch documentation) // check which of the two layers is closest. int insertionPoint = -(resultIndex + 1); int rightLayerIndex = insertionPoint; int leftLayerIndex = insertionPoint - 1; Layer rightLayer = layers.get(rightLayerIndex); Layer leftLayer = layers.get(leftLayerIndex); if (rightLayer.getX() - x > x - (leftLayer.getX() + leftLayer.getWidth())) { // distance from right layer is greater, so left layer is closer return leftLayerIndex; } else { return rightLayerIndex; } } } /** * Lay out the {@link Drawable Drawables} in this SubGraph. */ public void layout() { createLayers(); int minimumLayerIndex = findMinimumNodesLayerIndex(this.layers); sortLayersLeftFrom(minimumLayerIndex); sortLayersRightFrom(minimumLayerIndex); } /** * Assign nodes to {@link Layer layers} and create dummyNodes for edges that span multiple layers. */ private void createLayers() { this.layers = findLayers(); createDummyNodes(layers, true); } /** * Set the coordinates for all {@link Layer layers} to the right of the given Layer. * @param layers The Layers to set the coordinates for. * @param setLayerIndex The index of the Layer to start from (exclusive, * so coordinates are not set for this layer). */ public void setRightDrawLocations(ArrayList<Layer> layers, int setLayerIndex) { ListIterator<Layer> layerIterator = layers.listIterator(setLayerIndex); Layer setLayer = layerIterator.next(); double x = setLayer.getX() + setLayer.getWidth(); double firstY = setLayer.getY(); int size = setLayer.size(); while (layerIterator.hasNext()) { Layer layer = layerIterator.next(); // layer.setSize(zoomLevel); int newSize = layer.size(); int diff = Math.abs(newSize - size); x += (LAYER_PADDING * zoomLevel) + (DIFF_LAYER_PADDING * zoomLevel) * diff; layer.setX(x); layer.setDrawLocations(firstY); x += layer.getWidth() + (LAYER_PADDING * zoomLevel) * 0.1 + newSize; size = newSize; } } /** * Set the coordinates for all {@link Layer layers} to the left of the given Layer. * @param layers The Layers to set the coordinates for. * @param setLayerIndex The index of the Layer to start from (exclusive, * so coordinates are not set for this layer). */ public void setLeftDrawLocations(ArrayList<Layer> layers, int setLayerIndex) { ListIterator<Layer> layerIterator = layers.listIterator(setLayerIndex + 1); Layer setLayer = layerIterator.previous(); double x = setLayer.getX(); double firstY = setLayer.getY(); int size = setLayer.size(); while (layerIterator.hasPrevious()) { Layer layer = layerIterator.previous(); layer.setSize(zoomLevel); int newSize = layer.size(); int diff = Math.abs(newSize - size); x -= (LAYER_PADDING * zoomLevel) + diff * (DIFF_LAYER_PADDING * zoomLevel) + layer.getWidth(); layer.setX(x); layer.setDrawLocations(firstY); x -= (LAYER_PADDING * zoomLevel) * 0.1 + newSize; size = newSize; } } /** * Create {@link DrawableDummy} nodes for layers to avoid more crossing edges. * * @param layers {@link List} representing all layers to be drawn. */ private int createDummyNodes(List<Layer> layers, boolean returnHighestLayer) { int lowestOrHighest = -1; int layerIndex = 0; Layer current = new Layer(); for (Layer next : layers) { for (DrawableNode node : current) { for (DrawableNode child : this.getChildren(node)) { if (!next.contains(child)) { DrawableDummy dummy = new DrawableDummy( DrawableNode.getUniqueId(), node, child, this.getGraph(), this); node.replaceChild(child, dummy); child.replaceParent(node, dummy); dummy.setWidth(next.getWidth()); this.nodes.put(dummy.getIdentifier(), dummy); dummy.setLayer(next); next.add(dummy); if (returnHighestLayer || lowestOrHighest == -1) { lowestOrHighest = layerIndex; } } } } current = next; layerIndex++; } return lowestOrHighest; } /** * Put all nodes in {@link Layer Layers}. This method is used when {@link #layout laying out} the graph. * This will put each node in a Layer one higher than each of its parents. * * @return A {@link List} of Layers with all the nodes (all nodes are divided over the Layers). */ private ArrayList<Layer> findLayers() { long startTime = System.nanoTime(); List<DrawableNode> sorted = topoSort(); long finishTime = System.nanoTime(); long differenceTime = finishTime - startTime; long millisecondTime = differenceTime / 1000000; Console.println("TIME OF TOPOSORT: " + millisecondTime); Console.println("Amount of nodes: " + sorted.size()); Map<DrawableNode, Integer> nodeLevel = new HashMap<>(); ArrayList<Layer> layerList = new ArrayList<>(); for (DrawableNode node : sorted) { int maxParentLevel = -1; for (DrawableNode parent : this.getParents(node)) { Integer parentLevel = nodeLevel.get(parent); if (maxParentLevel < parentLevel) { maxParentLevel = parentLevel; } } maxParentLevel++; // we want this node one level higher than the highest parent. nodeLevel.put(node, maxParentLevel); if (layerList.size() <= maxParentLevel) { layerList.add(new Layer()); } node.setLayer(layerList.get(maxParentLevel)); layerList.get(maxParentLevel).add(node); } return layerList; } /** * Get the parents of {@link DrawableNode} node. * * @param node The {@link DrawableNode} to get * @return A {@link Collection} of {@link DrawableNode} */ public Collection<DrawableNode> getParents(DrawableNode node) { Collection<DrawableNode> parents = new LinkedHashSet<>(); for (int parentID : node.getParents()) { if (this.nodes.containsKey(parentID)) { parents.add(this.nodes.get(parentID)); } } return parents; } /** * Get the children of {@link DrawableNode} node. * * @param node The {@link DrawableNode} to get * @return A {@link Collection} of {@link DrawableNode} */ public Collection<DrawableNode> getChildren(DrawableNode node) { Collection<DrawableNode> children = new LinkedHashSet<>(); for (int childID : node.getChildren()) { if (this.nodes.containsKey(childID)) { children.add(this.nodes.get(childID)); } } return children; } /** * Find the Layer with the least number of nodes. * @param layers The {@link Layer Layers} to search through. * @return The index of the Layer with the minimum number of nodes, or -1 if the list of layers is empty. */ private int findMinimumNodesLayerIndex(List<Layer> layers) { // find a layer with a single node int index = -1; int min = Integer.MAX_VALUE; Iterator<Layer> layerIterator = layers.iterator(); for (int i = 0; layerIterator.hasNext(); i++) { Layer currentLayer = layerIterator.next(); int currentSize = currentLayer.size(); if (currentSize < min) { min = currentSize; index = i; if (currentSize <= 1) { // There should be no layers with less than 1 node, // so this layer has the least amount of nodes. break; } } } return index; } /** * Sort all {@link Layer Layers} right from a given layer. * @param layerIndex The index of the layer to start sorting from (exclusive, so that layer is not sorted). */ private void sortLayersRightFrom(int layerIndex) { ListIterator<Layer> iterator = layers.listIterator(layerIndex); Layer prev = iterator.next(); while (iterator.hasNext()) { Layer layer = iterator.next(); layer.sort(this, prev, true); prev = layer; } } /** * Sort all {@link Layer Layers} left from a given layer. * @param layerIndex The index of the layer to start sorting from (exclusive, so that layer is not sorted). */ private void sortLayersLeftFrom(int layerIndex) { ListIterator<Layer> iterator = layers.listIterator(layerIndex + 1); Layer prev = iterator.previous(); while (iterator.hasPrevious()) { Layer layer = iterator.previous(); layer.sort(this, prev, false); prev = layer; } } /** * Topologically sort the nodes from this graph. <br /> * * Assumption: graph is a DAG. * * @return a topologically sorted list of nodes */ public List<DrawableNode> topoSort() { // topo sorted list ArrayList<DrawableNode> res = new ArrayList<>(this.nodes.size()); // nodes that have not yet been added to the list. LinkedHashSet<DrawableNode> found = new LinkedHashSet<>(); // tactic: // take any node. see if any parents were not added yet. // If so, clearly that parent needs to be added first. Continue searching from parent. // If not, we found a node that can be next in the ordering. Add it to the list. // Repeat until all nodes are added to the list. for (DrawableNode n : this.nodes.values()) { if (!found.add(n)) { continue; } topoSortFromNode(res, found, n); } // TODO: use better strategy // 1 O(1) create sorted set of (number, node) pairs (sort by number) // 2 O(n) for each node, add to set as (node.parents.size(), node) // 3 O(n+m) for each node in the list { // 3.1 O(1) remove first pair from list (assert that number = 0), add node to resultList. // 3.2 O((deg(v)) for each child of node, decrease number by one (make sure that list is still sorted!). // done. // TODO: add a test that this works. see assert below. // assert that list is sorted? // create set found // for each node: add to found, check if any of children in found. If yes, fail. // if none of the children for all nodes were in found: pass. assert (res.size() == this.nodes.size()); return res; } /** * Toposort all ancestors of a node. * * @param result The result list to which these nodes will be added, * @param found The nodes that have already been found, * @param node The node to start searching from. */ private void topoSortFromNode(ArrayList<DrawableNode> result, LinkedHashSet<DrawableNode> found, DrawableNode node) { for (int parentID : node.getParents()) { DrawableNode drawableParent = this.nodes.get(parentID); if (drawableParent != null && found.add(drawableParent)) { topoSortFromNode(result, found, drawableParent); } } result.add(node); } /** * Calculate genomes through all outgoing edges of a parent. * @param parent find all genomes through edges from this parent * @return a {@link Map} of collections of genomes through links */ Map<DrawableNode, Collection<Integer>> calculateGenomes(DrawableNode parent) { Map<DrawableNode, Collection<Integer>> outgoingGenomes = new LinkedHashMap<>(); // Create set of parent genomes Set<Integer> parentGenomes = new LinkedHashSet<>(parent.getParentGenomes()); // Topo sort (= natural order) children Collection<DrawableNode> children = this.getChildren(parent); // For every child (in order); do children.stream() .map(DrawableNode::getChildSegment) .sorted(Comparator.comparingInt(DrawableNode::getIdentifier)) .forEach(child -> { Set<Integer> childGenomes = new LinkedHashSet<>(child.getGenomes()); // Find mutual genomes between parent and child Set<Integer> mutualGenomes = Sets.intersect(parentGenomes, childGenomes); // Add mutual genomes to edge outgoingGenomes.put(child, mutualGenomes); // Subtract mutual genomes from parent set parentGenomes.removeAll(mutualGenomes); }); return outgoingGenomes; } /** * Calculate genomes through edge, based on topological ordering and node-genome information. * @return a {@link Map} of {@link Map Maps} of collections of genomes through links */ public Map<DrawableNode, Map<DrawableNode, Collection<Integer>>> calculateGenomes() { // For every node in the subGraph this.nodes.values().stream().map(DrawableNode::getParentSegment).forEach(parent -> { Map<DrawableNode, Collection<Integer>> parentGenomes = this.calculateGenomes(parent); this.genomes.put(parent, parentGenomes); }); return this.genomes; } /** * Add nodes from the {@link #rootNodes}. * @param radius The number of steps to take from the rootNodes before stopping the search. */ private void addFromRootNodes(int radius) { if (this.rootNodes.isEmpty()) { return; } Console.println("Increasing graph with radius %d", radius); SubGraph subGraph = new SubGraph(graph, zoomLevel); this.rootNodes.forEach((id, node) -> this.endNodes.remove(id)); findNodes(subGraph, rootNodes.values(), this.nodes, radius); subGraph.createLayers(); this.mergeLeftSubGraphIntoThisSubGraph(subGraph); } /** * Add nodes from the {@link #endNodes}. * @param radius The number of steps to take from the endNodes before stopping the search. */ public void addFromEndNodes(int radius) { if (this.endNodes.isEmpty()) { return; } Console.println("Increasing graph with radius %d", radius); SubGraph subGraph = new SubGraph(graph, zoomLevel); this.endNodes.forEach((id, node) -> System.out.println(id)); this.endNodes.forEach((id, node) -> this.rootNodes.remove(id)); findNodes(subGraph, endNodes.values(), this.nodes, radius); subGraph.createLayers(); this.mergeRightSubGraphIntoThisSubGraph(subGraph); } private void mergeRightSubGraphIntoThisSubGraph(SubGraph rightSubGraph) { this.nodes.putAll(rightSubGraph.nodes); this.endNodes = rightSubGraph.endNodes; rightSubGraph.rootNodes.forEach((id, node) -> { boolean addToEndNodes = false; for (Integer parentId : node.getParents()) { if (this.nodes.containsKey(parentId)) { addToEndNodes = true; break; } } if (!addToEndNodes) { for (Integer childId : node.getChildren()) { if (this.nodes.containsKey(childId)) { addToEndNodes = true; break; } } } if (addToEndNodes) { this.endNodes.put(id, node); } }); int oldLastIndex = this.layers.size() - 1; this.layers.addAll(rightSubGraph.layers); // TODO: find DummyNodes between subgraphs. Just use findDummyNodes on full graph? this.sortLayersRightFrom(oldLastIndex); this.setRightDrawLocations(this.layers, oldLastIndex); } /** * Merge another {@link SubGraph} into this SubGraph, by putting it on the left of this SubGraph, * and then drawing connecting edges between nodes that should have them. * @param leftSubGraph The other SubGraph that will be merged into this one. */ private void mergeLeftSubGraphIntoThisSubGraph(SubGraph leftSubGraph) { this.nodes.putAll(leftSubGraph.nodes); this.rootNodes = leftSubGraph.rootNodes; leftSubGraph.endNodes.forEach((id, node) -> { boolean addToRootNodes = false; for (Integer childId : node.getChildren()) { if (this.nodes.containsKey(childId)) { addToRootNodes = true; break; } } if (!addToRootNodes) { for (Integer parentId : node.getParents()) { if (this.nodes.containsKey(parentId)) { addToRootNodes = true; break; } } } if (addToRootNodes) { this.rootNodes.put(id, node); } }); int oldFirstIndex = leftSubGraph.layers.size(); this.layers.addAll(0, leftSubGraph.layers); // TODO: find DummyNodes between subgraphs. Just use findDummyNodes on full graph? this.sortLayersLeftFrom(oldFirstIndex); this.setLeftDrawLocations(this.layers, oldFirstIndex); } /** * Set the radius of this SubGraph. * Nodes that are now outside the radius of this SubGraph will be removed, * and Nodes that are now inside will be added. * * @param radius The new radius. */ public void setRadius(int radius) { // TODO // when getting bigger: include new nodes // when getting smaller: drop nodes outside new radius. } public LinkedHashMap<Integer, DrawableNode> getNodes() { return this.nodes; } public GenomeGraph getGraph() { return graph; } public void translate(double xDifference, double yDifference) { for (Layer layer : this.layers) { layer.setX(layer.getX() + xDifference); for (DrawableNode node : layer) { double oldX = node.getLocation().getX(); double oldY = node.getLocation().getY(); node.setLocation(oldX + xDifference, oldY + yDifference); } } } public void zoom(double scale) { for (Layer layer : this.layers) { layer.setX(layer.getX() / scale); for (DrawableNode node : layer) { double oldXLocation = node.getLocation().getX(); double oldYLocation = node.getLocation().getY(); node.setHeight(node.getHeight() / scale); node.setWidth(node.getWidth() / scale); node.setStrokeWidth(node.getStrokeWidth() / scale); node.setLocation(oldXLocation / scale, oldYLocation / scale); } } zoomLevel /= scale; } public void colorize() { for (DrawableNode drawableNode : this.nodes.values()) { drawableNode.colorize(this); } } public Map<DrawableNode, Map<DrawableNode, Collection<Integer>>> getGenomes() { return genomes; } public int getNumberOfGenomes() { return numberOfGenomes; } }
package ru.taximaxim.pgsqlblocks.ui; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.log4j.WriterAppender; import org.apache.log4j.spi.LoggingEvent; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.custom.StyledTextContent; import org.eclipse.swt.events.*; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.*; import org.eclipse.swt.widgets.Composite; public class UIAppender extends WriterAppender{ private static final int TEXT_LIMIT = 5000; private Composite parent; private StyledText text; private Display display; private ModifyListener modifyListener = new ModifyListener() { @Override public void modifyText(ModifyEvent e) { if(text.getText().length() > TEXT_LIMIT) { StyledTextContent styledTextContent = text.getContent(); // cut excess text styledTextContent.replaceTextRange(0,text.getText().length() - TEXT_LIMIT - 1, ""); // cut lopped line styledTextContent.replaceTextRange(0, styledTextContent.getLine(0).length(), ""); text.setContent(styledTextContent); } text.setTopIndex(text.getLineCount() - 1); } }; public UIAppender(Composite parent) { this.parent = parent; this.display = parent.getDisplay(); createControl(); } private void createControl() { text = new StyledText(parent, SWT.MULTI | SWT.READ_ONLY | SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER); text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); text.setMargins(3, 3, 3, 3); text.layout(true); text.addModifyListener(modifyListener); parent.layout(true, true); // add empty string on ENTER pressed text.addTraverseListener(e -> { switch (e.detail) { case SWT.TRAVERSE_RETURN: if (!text.isDisposed()) { text.append("\n"); text.setTopIndex(text.getLineCount() - 1); } break; default: break; } }); // wheel up and down text.addMouseWheelListener(e -> { if (e.count > 0) { text.removeModifyListener(modifyListener); } else { text.addModifyListener(modifyListener); } }); } public void append(LoggingEvent event) { boolean displayIsFine = display == null || display.isDisposed(); boolean parentIsFine = parent == null || parent.isDisposed(); if(displayIsFine || parentIsFine || text == null) { return; } SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); Date time = new Date(event.getTimeStamp()); String dateTime = sdf.format(time); String excMessage = ""; Object message = event.getMessage(); if (message instanceof String) { excMessage = (String) message; } else { return; } final String logMessage = String.format("[%s] %s%n", dateTime, excMessage); parent.getDisplay().asyncExec(() -> { if (!text.isDisposed()) { text.append(logMessage); } }); } }
package sizebay.catalog.client.http; import java.io.*; import java.net.*; import java.util.*; import lombok.RequiredArgsConstructor; import sizebay.catalog.client.model.ProductIntegration; @RequiredArgsConstructor public class RESTClient { static final String METHOD_POST = "POST"; static final String METHOD_GET = "GET"; static final String METHOD_PUT = "PUT"; static final String METHOD_DELETE = "DELETE"; final String baseUrl; final MimeType mime; final RESTClientConfiguration config; public void delete( String serverEndpoint ) { callEndpoint( METHOD_DELETE, serverEndpoint ); } public <T> T getSingle( String serverEndpoint, Class<T> expectedResponseClass ) { final Response response = callEndpoint( METHOD_GET, serverEndpoint ); return serialize( response.body, expectedResponseClass ); } private <T> T serialize( String response, Class<T> expectedResponseClass ) { if ( response == null ) return null; return mime.unserialize( response, expectedResponseClass ); } public <T> List<T> getList( String serverEndpoint, Class<T> expectedResponseClass ) { final Response response = callEndpoint( METHOD_GET, serverEndpoint ); return serializeList( response.body, expectedResponseClass ); } private <T> List<T> serializeList( String response, Class<T> expectedResponseClass ) { if ( response == null ) return null; return mime.unserializeList( response, expectedResponseClass ); } public long post( String serverEndpoint, Object request ) { final String jsonBodyData = mime.serialize( request ); final Response response = sendToEndpoint( METHOD_POST, serverEndpoint, jsonBodyData ); return response.connection.getHeaderFieldLong( "ID", -1 ); } public <T> T post(String serverEndpoint, Object request, Class<T> expectedResponseClass) { final String jsonBodyData = mime.serialize(request); final Response response = sendToEndpoint( METHOD_POST, serverEndpoint, jsonBodyData ); return serialize(response.body, expectedResponseClass); } public void put( String serverEndpoint, Object request ) { final String jsonBodyData = mime.serialize( request ); sendToEndpoint( METHOD_PUT, serverEndpoint, jsonBodyData ); } public <T> T put( String serverEndpoint, Object request, Class<T> expectedResponseClass ) { final String jsonBodyData = mime.serialize( request ); final Response response = sendToEndpoint( METHOD_PUT, serverEndpoint, jsonBodyData ); return serialize( response.body, expectedResponseClass ); } private Response sendToEndpoint( String httpMethod, String serverEndpoint, final String body ) { try { final URL url = buildURL( serverEndpoint ); final HttpURLConnection connection = connect( httpMethod, url ); sendDefaultHeaders( connection ); sendData( connection, body ); final String response = readData( connection ); if ( connection.getResponseCode() / 100 >= 3 ) handleFailure( connection, response, body ); return new Response( response, connection ); } catch ( final IOException e ) { throw new ApiException( "Failed to send data to endpoint " + serverEndpoint, e ); } } private void handleFailure( final HttpURLConnection connection, final String response, String body ) throws IOException { final String msg = "Status: " + connection.getResponseCode() + "\n\t\tResponse: " + response + "\n\t\tRequest: " + body; System.out.println( msg ); throw new ApiException( connection.getResponseCode(), response ); } private Response callEndpoint( String httpMethod, String serverEndpoint ) { try { final URL url = buildURL( serverEndpoint ); final HttpURLConnection connection = connect( httpMethod, url ); sendDefaultHeaders( connection ); final String response = readData( connection ); if ( connection.getResponseCode() / 100 >= 3 ) throw new ApiException( connection.getResponseCode(), response ); return new Response( response, connection ); } catch ( final IOException e ) { throw new ApiException( e ); } } private URL buildURL( String path ) { try { path = path.replace( "%", "%25" ).replace(" ", "%20"); final String rootPath = ( baseUrl + "/" + path ).replaceAll( "([^:]) return new URL( rootPath ); } catch ( final MalformedURLException e ) { throw new RuntimeException( e ); } } private HttpURLConnection connect( String method, URL url ) throws IOException { final HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod( method ); configureConnection( connection ); return connection; } private void sendDefaultHeaders( HttpURLConnection connection ) { connection.setRequestProperty( "Content-Type", mime.contentType() ); connection.setRequestProperty( "Accept", mime.contentType() ); connection.setRequestProperty( "charset", mime.charset() ); } private void configureConnection( HttpURLConnection connection ) { connection.setDoInput( true ); connection.setDoOutput( true ); connection.setUseCaches( false ); connection.setConnectTimeout( 5000 ); connection.setInstanceFollowRedirects( false ); config.configureRequest( connection ); } private void sendData( HttpURLConnection connection, String jsonBodyData ) throws IOException { final OutputStream outputStream = connection.getOutputStream(); outputStream.write( jsonBodyData.getBytes( mime.charset() ) ); outputStream.flush(); outputStream.close(); connection.connect(); } private String readData( final HttpURLConnection connection ) throws IOException { try { final InputStream stream = connection.getInputStream(); return convertStreamToString( stream ); } catch ( final IOException ioe ) { return ioe.getMessage(); } } private String convertStreamToString( InputStream is ) { try ( Scanner s = new Scanner( is, mime.charset() ) ) { s.useDelimiter( "\\A" ); return s.hasNext() ? s.next() : ""; } } } @RequiredArgsConstructor class Response { final String body; final HttpURLConnection connection; }
package xdi2.core.impl.redis; import java.io.IOException; import org.apache.commons.codec.binary.Base64; import redis.clients.jedis.Jedis; import xdi2.core.GraphFactory; import xdi2.core.impl.keyvalue.AbstractKeyValueGraphFactory; import xdi2.core.impl.keyvalue.KeyValueStore; /** * GraphFactory that creates graphs in Redis. * * @author markus */ public class RedisGraphFactory extends AbstractKeyValueGraphFactory implements GraphFactory { public static final boolean DEFAULT_SUPPORT_GET_CONTEXTNODES = true; public static final boolean DEFAULT_SUPPORT_GET_RELATIONS = true; public static final String DEFAULT_HOST = "localhost"; public static final Integer DEFAULT_PORT = null; private String host; private Integer port; public RedisGraphFactory() { super(DEFAULT_SUPPORT_GET_CONTEXTNODES, DEFAULT_SUPPORT_GET_RELATIONS); this.host = DEFAULT_HOST; this.port = DEFAULT_PORT; } @Override protected KeyValueStore openKeyValueStore(String identifier) throws IOException { // create jedis Jedis jedis = this.getPort() == null ? new Jedis(this.getHost()) : new Jedis(this.getHost(), this.getPort().intValue()); // create prefix String prefix = identifier == null ? "" : new String(Base64.encodeBase64(identifier.getBytes("UTF-8")), "UTF-8") + "."; // open store KeyValueStore keyValueStore; keyValueStore = new RedisKeyValueStore(jedis, prefix); keyValueStore.init(); // done return keyValueStore; } public String getHost() { return this.host; } public void setHost(String host) { this.host = host; } public Integer getPort() { return this.port; } public void setPort(Integer port) { this.port = port; } }
package xyz.rc24.bot.commands.wii; import ch.qos.logback.classic.Logger; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import com.jagrosh.jdautilities.command.Command; import com.jagrosh.jdautilities.command.CommandEvent; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.Permission; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import org.jetbrains.annotations.NotNull; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import xyz.rc24.bot.Bot; import xyz.rc24.bot.RiiConnect24Bot; import xyz.rc24.bot.commands.Categories; import java.awt.Color; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Looks up errors using the Wiimmfi API. * * @author Spotlight, Artuto */ public class ErrorInfoCmd extends Command { private final boolean debug; private final OkHttpClient httpClient; private final Pattern CHANNEL = Pattern.compile("(NEWS|FORE)0{4}\\d{2}", Pattern.CASE_INSENSITIVE); private final Pattern CHANNEL_CODE = Pattern.compile("0{4}\\d{2}"); private final Pattern CODE = Pattern.compile("\\d{1,6}"); private final Gson gson = new Gson(); private final Logger logger = RiiConnect24Bot.getLogger(ErrorInfoCmd.class); public ErrorInfoCmd(Bot bot) { this.debug = bot.getConfig().isDebug(); this.httpClient = bot.getHttpClient(); this.name = "error"; this.help = "Looks up errors using the Wiimmfi API."; this.category = Categories.WII; this.botPermissions = new Permission[]{Permission.MESSAGE_EMBED_LINKS}; this.guildOnly = false; } @Override protected void execute(CommandEvent event) { Matcher channelCheck = CHANNEL.matcher(event.getArgs()); // Check for Fore/News if(channelCheck.find()) { // First match will be the type, then second our actual code. int code; try { // Make sure the code's actually a code. Matcher codeCheck = CHANNEL_CODE.matcher(channelCheck.group()); if(!(codeCheck.find())) throw new NumberFormatException(); code = Integer.parseInt(codeCheck.group(0)); if(channelErrors.get(code) == null) throw new NumberFormatException(); } catch(NumberFormatException ignored) { event.replyError("Could not find the specified app error code."); return; } EmbedBuilder builder = new EmbedBuilder(); builder.setTitle("Here's information about your error:"); builder.setDescription(channelErrors.get(code)); builder.setColor(Color.decode("#D32F2F")); builder.setFooter("All information provided by RC24 Developers.", null); event.reply(builder.build()); } else { int code; try { // Validate if it is a number. Matcher codeCheck = CODE.matcher(event.getArgs()); if(!(codeCheck.find())) throw new NumberFormatException(); code = Integer.parseInt(codeCheck.group(0)); if(code == 0) { // We'll just treat it as an error. throw new NumberFormatException(); } } catch(NumberFormatException ignored) { event.replyError("Enter a valid error code!"); return; } // Get method String method = (debug ? "t=" : "e=") + code; String url = "https://wiimmfi.de/error?" + method + "&m=json"; if(debug) logger.info("Sending request to '{}'", url); Request request = new Request.Builder().url(url).build(); httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { event.replyError("Hm, something went wrong on our end. Ask a dev to check out my console."); logger.error("Something went wrong whilst checking error code '" + code + "' with Wiimmfi: {}", e.getMessage(), e); } @Override public void onResponse(@NotNull Call call, @NotNull Response response) { if(!(response.isSuccessful())) { onFailure(call, new IOException("Not success response code: " + response.code())); return; } success(event, response); } }); } } @SuppressWarnings("ConstantConditions") // Response body can't be null at this point of the execution private void success(@NotNull CommandEvent event, @NotNull Response response) { JSONFormat json = gson.fromJson(new InputStreamReader(response.body().byteStream()), JSONFormat[].class)[0]; if(!(json.found == 1)) { event.replyError("Could not find the specified error from Wiimmfi."); return; } StringBuilder infoBuilder = new StringBuilder(); for(InfoListFormat format : json.infolists) { String htmlToMarkdown = format.info; Document infoSegment = Jsoup.parseBodyFragment(htmlToMarkdown); // Replace links with markdown format for(Element hRef : infoSegment.select("a[href]")) { // So, we have to transform &amp; back to &. // It's funny, the same issue happened with Nokogiri and Ruby. String realOuterHTML = hRef.outerHtml(); realOuterHTML = realOuterHTML.replace("&amp;", "&"); htmlToMarkdown = htmlToMarkdown.replace(realOuterHTML, "[" + hRef.text() + "](" + hRef.attr("href") + ")"); } // Parse again to handle updates infoSegment = Jsoup.parseBodyFragment(htmlToMarkdown); for(Element bold : infoSegment.select("b")) htmlToMarkdown = htmlToMarkdown.replace(bold.outerHtml(), "**" + bold.text() + "**"); // ...and parse, once more. infoSegment = Jsoup.parseBodyFragment(htmlToMarkdown); for(Element italics : infoSegment.select("i")) htmlToMarkdown = htmlToMarkdown.replace(italics.outerHtml(), "*" + italics.text() + "*"); infoBuilder.append(format.type).append(" for error ").append(format.name).append(": ").append(htmlToMarkdown).append("\n"); } // Check for dev note if(codeNotes.containsKey(json.error)) infoBuilder.append("Note from RiiConnect24: ").append(codeNotes.get(json.error)); EmbedBuilder builder = new EmbedBuilder(); builder.setTitle("Here's information about your error:"); builder.setDescription(infoBuilder.toString()); builder.setColor(Color.decode("#D32F2F")); builder.setFooter("All information is from Wiimmfi unless noted.", null); event.reply(builder.build()); response.close(); } private class JSONFormat { @SerializedName("error") int error; @SerializedName("found") int found; @SerializedName("infolist") InfoListFormat[] infolists; } private class InfoListFormat { @SerializedName("type") String type; @SerializedName("name") String name; @SerializedName("info") String info; } private final Map<Integer, String> channelErrors = new HashMap<Integer, String>() {{ put(1, "Can't open the VFF Follow https://wii.guide/riiconnect24-troubleshooting to fix it."); put(2, "WiiConnect24 file problem."); put(3, "VFF file corrupted. Follow https://wii.guide/riiconnect24-troubleshooting to fix it."); put(4, "Unknown (it probably doesn't exist)."); put(5, "VFF processing error. Follow https://wii.guide/riiconnect24-troubleshooting to fix it."); put(6, "Invalid data. If getting this on the **Forecast Channel**, try again in a few minutes. " + "If you're still getting this error, follow https://wii.guide/riiconnect24-batteryfix " + "and it might fix it."); put(99, "Other error. Follow https://wii.guide/riiconnect24-troubleshooting to potentially fix it."); }}; private final Map<Integer, String> codeNotes = new HashMap<Integer, String>() {{ put(101409, "If you are getting this problem while doing something with Wii Mail, check if you patched the nwc24msg.cfg correctly. https://bit.ly/2QUrsyD"); put(102032, "The IOS the app/game uses is not patched for RiiConnect24."); put(102409, "If you are getting this problem while doing something with Wii Mail, check if you patched the nwc24msg.cfg correctly. https://bit.ly/2QUrsyD"); put(103409, "If you are getting this problem while doing something with Wii Mail, check if you patched the nwc24msg.cfg correctly. https://bit.ly/2QUrsyD"); put(104409, "If you are getting this problem while doing something with Wii Mail, check if you patched the nwc24msg.cfg correctly. https://bit.ly/2QUrsyD"); put(105409, "If you are getting this problem while doing something with Wii Mail, check if you patched the nwc24msg.cfg correctly. https://bit.ly/2QUrsyD"); put(107006, "Are you getting this on the News Channel? If so, please tell Larsenv you're getting this error and tell him your country and language your Wii is set to."); put(107245, "Your IOS probably aren't patched. Go to https://wii.guide/riiconnect24 for instructions on how to patch them."); put(107304, "This error can be caused by your ISP blocking custom DNS servers, or simply not having it entered. Make sure it is entered correctly, if you still get this error use https://github.com/RiiConnect24/DNS-Server to resolve it."); put(107305, "Try again. If it still doesn't work, it might be a problem with your Internet or RiiConnect24's servers."); put(110211, "If you're getting this, tell Larsenv or KcrPL your Wii Number and they will delete it from the database so you can reregister with the mail patcher."); put(110220, "Looks like the password your Wii uses isn't matching the one on the server. If you're getting this, tell Larsenv or KcrPL your Wii Number and they will delete it from the database so you can reregister with the mail patcher."); put(110230, "Looks like the password your Wii uses isn't matching the one on the server. If you're getting this, tell Larsenv or KcrPL your Wii Number and they will delete it from the database so you can reregister with the mail patcher."); put(110240, "Looks like the password your Wii uses isn't matching the one on the server. If you're getting this, tell Larsenv or KcrPL your Wii Number and they will delete it from the database so you can reregister with the mail patcher."); put(110250, "Looks like the password your Wii uses isn't matching the one on the server. If you're getting this, tell Larsenv or KcrPL your Wii Number and they will delete it from the database so you can reregister with the mail patcher."); put(117403, "This is a 403 Forbidden error. If you're getting this, tell Larsenv where you're getting this error on."); put(117404, "This is a 404 Not Found error. If you're getting this on the Everybody Votes Channel, what questions does this appear on?"); put(117500, "This is a 500 Internal Server error. If you're getting this, tell Larsenv where you're getting this error on."); put(117503, "This is a 503 Service Unavailable error. If you're getting this, tell Larsenv where you're getting this error on."); put(123456, "CMOC/MCC Contests are not supported yet."); put(20103, "Delete DWC_AUTHDATA file stored in nand:/shared2/ using WiiXplorer."); put(231000, "Restart the Channel or your Wii then try again. We hope to fix this error from happening in the future, sorry for the inconvenience!"); put(231401, "You are not using the patched WAD for the Everybody Votes Channel. Please follow this tutorial: https://wii.guide/riiconnect24-evc"); put(231409, "You are not using the patched WAD for the Everybody Votes Channel. Please follow this tutorial: https://wii.guide/riiconnect24-evc"); put(239001, "Your IOS probably aren't patched. Go to https://wii.guide/riiconnect24 for instructions on how to patch them. Occasionally, this error can mean it downloaded invalid data."); put(258503, "This is a 503 Service Unavailable error. If you are getting this on Nintendo Channel, just ignore it and press ok"); put(258404, "This is a 404 Not Found error. If you are getting this on Nintendo Channel it means the item hasn't been added yet"); put(51330, "Try the suggestions found on Nintendo's site: https://bit.ly/2OoC0c2"); put(51331, "Try the suggestions found on Nintendo's site: https://bit.ly/2OoC0c2"); put(51332, "Try the suggestions found on Nintendo's site: https://bit.ly/2OoC0c2"); }}; }
package org.strongback.hardware; import org.strongback.annotation.Experimental; import org.strongback.components.Accelerometer; import org.strongback.components.AngleSensor; import org.strongback.components.DistanceSensor; import org.strongback.components.Gyroscope; import org.strongback.components.Motor; import org.strongback.components.PneumaticsModule; import org.strongback.components.PowerPanel; import org.strongback.components.Relay; import org.strongback.components.Solenoid; import org.strongback.components.Switch; import org.strongback.components.TalonSRX; import org.strongback.components.ThreeAxisAccelerometer; import org.strongback.components.TwoAxisAccelerometer; import org.strongback.components.ui.FlightStick; import org.strongback.components.ui.Gamepad; import org.strongback.components.ui.InputDevice; import org.strongback.control.TalonController; import org.strongback.function.DoubleToDoubleFunction; import org.strongback.util.Values; import com.ctre.CANTalon; import com.ctre.CANTalon.TalonControlMode; import edu.wpi.first.wpilibj.ADXL345_I2C; import edu.wpi.first.wpilibj.ADXL345_SPI; import edu.wpi.first.wpilibj.ADXRS450_Gyro; import edu.wpi.first.wpilibj.AnalogAccelerometer; import edu.wpi.first.wpilibj.AnalogGyro; import edu.wpi.first.wpilibj.AnalogInput; import edu.wpi.first.wpilibj.AnalogPotentiometer; import edu.wpi.first.wpilibj.AnalogTrigger; import edu.wpi.first.wpilibj.BuiltInAccelerometer; import edu.wpi.first.wpilibj.Compressor; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.DoubleSolenoid; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.I2C; import edu.wpi.first.wpilibj.Jaguar; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.PowerDistributionPanel; import edu.wpi.first.wpilibj.SPI; import edu.wpi.first.wpilibj.Spark; import edu.wpi.first.wpilibj.Talon; import edu.wpi.first.wpilibj.Ultrasonic; import edu.wpi.first.wpilibj.Victor; import edu.wpi.first.wpilibj.VictorSP; import edu.wpi.first.wpilibj.interfaces.Accelerometer.Range; import edu.wpi.first.wpilibj.interfaces.Gyro; public class Hardware { /** * Gets the {@link PowerPanel} of the robot. * * @return the {@link PowerPanel} of the robot */ public static PowerPanel powerPanel() { PowerDistributionPanel pdp = new PowerDistributionPanel(); return PowerPanel.create(pdp::getCurrent, pdp::getTotalCurrent, pdp::getVoltage, pdp::getTemperature); } /** * Gets the {@link PneumaticsModule} of the robot with the default CAN ID of 0. * * @return the {@link PneumaticsModule} of the robot; never null */ public static PneumaticsModule pneumaticsModule() { return new HardwarePneumaticsModule(new Compressor()); } /** * Gets the {@link PneumaticsModule} of the robot with the supplied CAN ID. Multiple pneumatics modules can be used by * * @param canID the CAN ID of the module * @return the {@link PneumaticsModule} of the robot; never null */ public static PneumaticsModule pneumaticsModule(int canID) { return new HardwarePneumaticsModule(new Compressor(canID)); } /** * Factory method for angle sensors. */ public static final class AngleSensors { /** * Create a {@link Gyroscope} that uses a WPILib {@link AnalogGyro} on the specified channel. * * @param channel the channel the gyroscope is plugged into * @return the gyroscope; never null */ public static Gyroscope gyroscope(int channel) { return gyroscope(new AnalogGyro(channel)); } /** * Create a {@link Gyroscope} that uses a WPILib {@link ADXRS450_Gyro} on the specified SPI bus port. * * @param port the port on SPI bus into which the digital ADXRS450 gyroscope is connected * @return the gyroscope; never null */ public static Gyroscope gyroscope(SPI.Port port) { return gyroscope(new ADXRS450_Gyro(port)); } /** * Create a {@link Gyroscope} that uses the provided WPILib {@link Gyro}. Use this method if you need to * {@link Gyro#calibrate() calibrate} before using it. * * @param gyro the low-level WPILib gyroscope * @return the gyroscope; never null */ public static Gyroscope gyroscope(Gyro gyro) { return Gyroscope.create(gyro::getAngle, gyro::getRate); } /** * Creates a new {@link AngleSensor} from an {@link Encoder} using the specified channels with the specified distance * per pulse. * * @param aChannel the a channel of the encoder * @param bChannel the b channel of the encoder * @param distancePerPulse the distance the end shaft spins per pulse * @return the angle sensor; never null */ public static AngleSensor encoder(int aChannel, int bChannel, double distancePerPulse) { Encoder encoder = new Encoder(aChannel, bChannel); encoder.setDistancePerPulse(distancePerPulse); return AngleSensor.create(encoder::getDistance); } /** * Create a new {@link AngleSensor} from an {@link AnalogPotentiometer} using the specified channel and scaling. Since * no offset is provided, the resulting angle sensor may often be used with a limit switch to know precisely where a * mechanism might be located in space, and the angle sensor can be {@link AngleSensor#zero() zeroed} at that position. * (See {@link #potentiometer(int, double, double)} when another switch is not used to help determine the location, and * instead the zero point is pre-determined by the physical design of the mechanism.) * <p> * The scale factor multiplies the 0-1 ratiometric value to return the angle in degrees. * <p> * For example, let's say you have an ideal 10-turn linear potentiometer attached to a motor attached by chains and a * 25x gear reduction to an arm. If the potentiometer (attached to the motor shaft) turned its full 3600 degrees, the * arm would rotate 144 degrees. Therefore, the {@code fullVoltageRangeToInches} scale factor is * {@code 144 degrees / 5 V}, or {@code 28.8 degrees/volt}. * * @param channel The analog channel this potentiometer is plugged into. * @param fullVoltageRangeToDegrees The scaling factor multiplied by the analog voltage value to obtain the angle in * degrees. * @return the angle sensor that uses the potentiometer on the given channel; never null */ public static AngleSensor potentiometer(int channel, double fullVoltageRangeToDegrees) { return potentiometer(channel, fullVoltageRangeToDegrees, 0.0); } /** * Create a new {@link AngleSensor} from an {@link AnalogPotentiometer} using the specified channel, scaling, and * offset. This method is often used when the offset can be hard-coded by measuring the value of the potentiometer at * the mechanism's zero-point. On the other hand, if a limit switch is used to always determine the position of the * mechanism upon startup, then see {@link #potentiometer(int, double)}. * <p> * The scale factor multiplies the 0-1 ratiometric value to return the angle in degrees. * <p> * For example, let's say you have an ideal 10-turn linear potentiometer attached to a motor attached by chains and a * 25x gear reduction to an arm. If the potentiometer (attached to the motor shaft) turned its full 3600 degrees, the * arm would rotate 144 degrees. Therefore, the {@code fullVoltageRangeToInches} scale factor is * {@code 144 degrees / 5 V}, or {@code 28.8 degrees/volt}. * <p> * To prevent the potentiometer from breaking due to minor shifting in alignment of the mechanism, the potentiometer may * be installed with the "zero-point" of the mechanism (e.g., arm in this case) a little ways into the potentiometer's * range (for example 30 degrees). In this case, the {@code offset} value of {@code 30} is determined from the * mechanical design. * * @param channel The analog channel this potentiometer is plugged into. * @param fullVoltageRangeToDegrees The scaling factor multiplied by the analog voltage value to obtain the angle in * degrees. * @param offsetInDegrees The offset in degrees that the angle sensor will subtract from the underlying value before * returning the angle * @return the angle sensor that uses the potentiometer on the given channel; never null */ public static AngleSensor potentiometer(int channel, double fullVoltageRangeToDegrees, double offsetInDegrees) { AnalogPotentiometer pot = new AnalogPotentiometer(channel, fullVoltageRangeToDegrees, offsetInDegrees); return AngleSensor.create(pot::get); } } /** * Factory method for accelerometers. */ public static final class Accelerometers { /** * Create a new {@link ThreeAxisAccelerometer} for the ADXL345 with the desired range using the specified I2C port. * * @param port the I2C port used by the accelerometer * @param range the desired range of the accelerometer * @return the accelerometer; never null */ public static ThreeAxisAccelerometer accelerometer(I2C.Port port, Range range) { if (port == null) throw new IllegalArgumentException("The I2C port must be specified"); if (range == null) throw new IllegalArgumentException("The accelerometer range must be specified"); ADXL345_I2C accel = new ADXL345_I2C(port, range); return ThreeAxisAccelerometer.create(accel::getX, accel::getY, accel::getZ); } /** * Create a new {@link ThreeAxisAccelerometer} for the ADXL345 with the desired range using the specified SPI port. * * @param port the SPI port used by the accelerometer * @param range the desired range of the accelerometer * @return the accelerometer; never null */ public static ThreeAxisAccelerometer accelerometer(SPI.Port port, Range range) { if (port == null) throw new IllegalArgumentException("The I2C port must be specified"); if (range == null) throw new IllegalArgumentException("The accelerometer range must be specified"); ADXL345_SPI accel = new ADXL345_SPI(port, range); return ThreeAxisAccelerometer.create(accel::getX, accel::getY, accel::getZ); } /** * Create a new {@link ThreeAxisAccelerometer} using the RoboRIO's built-in accelerometer. * * @return the accelerometer; never null */ public static ThreeAxisAccelerometer builtIn() { BuiltInAccelerometer accel = new BuiltInAccelerometer(); return ThreeAxisAccelerometer.create(accel::getX, accel::getY, accel::getZ); } /** * Create a new single-axis {@link Accelerometer} using the {@link AnalogAccelerometer} on the specified channel, with * has the given sensitivity and zero value. * * @param channel the channel for the analog accelerometer * @param sensitivity the desired sensitivity in Volts per G (depends on actual hardware, such as 18mV/g or * {@code 0.018} for ADXL193) * @param zeroValueInVolts the voltage that represents no acceleration (should be determine experimentally) * @return the accelerometer; never null */ public static Accelerometer analogAccelerometer(int channel, double sensitivity, double zeroValueInVolts) { AnalogAccelerometer accel = new AnalogAccelerometer(channel); accel.setSensitivity(sensitivity); accel.setZero(zeroValueInVolts); return accel::getAcceleration; } /** * Create a new single-axis {@link Accelerometer} using two {@link AnalogAccelerometer}s on the specified channels, with * each have the given sensitivity and zero value. * * @param xAxisChannel the channel for the X-axis analog accelerometer * @param yAxisChannel the channel for the Y-axis analog accelerometer * @param sensitivity the desired sensitivity in Volts per G (depends on actual hardware, such as 18mV/g or * {@code 0.018} for ADXL193) * @param zeroValueInVolts the voltage that represents no acceleration (should be determine experimentally) * @return the accelerometer; never null */ public static TwoAxisAccelerometer analogAccelerometer(int xAxisChannel, int yAxisChannel, double sensitivity, double zeroValueInVolts) { if (xAxisChannel == yAxisChannel) throw new IllegalArgumentException( "The x- and y-axis channels may not be the same"); Accelerometer xAxis = analogAccelerometer(xAxisChannel, sensitivity, zeroValueInVolts); Accelerometer yAxis = analogAccelerometer(yAxisChannel, sensitivity, zeroValueInVolts); return TwoAxisAccelerometer.create(xAxis::getAcceleration, yAxis::getAcceleration); } } /** * Factory method for different kinds of switches. */ public static final class Switches { /** * Create a generic normally closed digital switch sensor on the specified digital channel. * * @param channel the channel the switch is connected to * @return a switch on the specified channel */ public static Switch normallyClosed(int channel) { DigitalInput input = new DigitalInput(channel); return () -> !input.get(); } /** * Create a generic normally open digital switch sensor on the specified digital channel. * * @param channel the channel the switch is connected to * @return a switch on the specified channel */ public static Switch normallyOpen(int channel) { DigitalInput input = new DigitalInput(channel); return input::get; } /** * Option for analog switches. * * @see Switches#analog(int, double, double, AnalogOption, TriggerMode) */ public static enum AnalogOption { /** * The filtering option of the analog trigger uses a 3-point average reject filter. This filter uses a circular * buffer of the last three data points and selects the outlier point nearest the median as the output. The primary * use of this filter is to reject data points which errantly (due to averaging or sampling) appear within the * window when detecting transitions using the Rising Edge and Falling Edge functionality of the analog trigger */ FILTERED, /** * The analog output is averaged and over sampled. */ AVERAGED, /** * No filtering or averaging is to be used. */ NONE; } /** * Trigger mode for analog switches. * * @see Switches#analog(int, double, double, AnalogOption, TriggerMode) */ public static enum TriggerMode { /** * The switch is triggered only when the analog value is inside the range, and not triggered if it is outside (above * or below) */ IN_WINDOW, /** * The switch is triggered only when the value is above the upper limit, and not triggered if it is below the lower * limit and maintains the previous state if in between (hysteresis) */ AVERAGED; } /** * Create an analog switch sensor that is triggered when the value exceeds the specified upper voltage and that is no * longer triggered when the value drops below the specified lower voltage. * * @param channel the port to use for the analog trigger 0-3 are on-board, 4-7 are on the MXP port * @param lowerVoltage the lower voltage limit that below which will result in the switch no longer being triggered * @param upperVoltage the upper voltage limit that above which will result in triggering the switch * @param option the trigger option; may not be null * @param mode the trigger mode; may not be null * @return the analog switch; never null */ public static Switch analog(int channel, double lowerVoltage, double upperVoltage, AnalogOption option, TriggerMode mode) { if (option == null) throw new IllegalArgumentException("The analog option must be specified"); if (mode == null) throw new IllegalArgumentException("The analog mode must be specified"); AnalogTrigger trigger = new AnalogTrigger(channel); trigger.setLimitsVoltage(lowerVoltage, upperVoltage); switch (option) { case AVERAGED: trigger.setAveraged(true); break; case FILTERED: trigger.setFiltered(true); break; case NONE: break; } return mode == TriggerMode.AVERAGED ? trigger::getTriggerState : trigger::getInWindow; } } /** * Factory method for distance sensors. */ public static final class DistanceSensors { /** * Create a digital ultrasonic {@link DistanceSensor} for an {@link Ultrasonic} sensor that uses the specified channels. * * @param pingChannel the digital output channel to use for sending pings * @param echoChannel the digital input channel to use for receiving echo responses * @return a {@link DistanceSensor} linked to the specified channels */ public static DistanceSensor digitalUltrasonic(int pingChannel, int echoChannel) { Ultrasonic ultrasonic = new Ultrasonic(pingChannel, echoChannel); ultrasonic.setAutomaticMode(true); return DistanceSensor.create(ultrasonic::getRangeInches); } /** * Create an analog {@link DistanceSensor} for an {@link AnalogInput} sensor using the specified channel. * * @param channel the channel the sensor is connected to * @param voltsToInches the conversion from analog volts to inches * @return a {@link DistanceSensor} linked to the specified channel */ public static DistanceSensor analogUltrasonic(int channel, double voltsToInches) { AnalogInput sensor = new AnalogInput(channel); return DistanceSensor.create(() -> sensor.getVoltage() * voltsToInches); } /** * Create a new {@link DistanceSensor} from an {@link AnalogPotentiometer} using the specified channel and scaling. * Since no offset is provided, the resulting distance sensor may often be used with a limit switch to know precisely * where a mechanism might be located in space, and the distance sensor can be {@link DistanceSensor#zero() zeroed} at * that position. (See {@link #potentiometer(int, double, double)} when another switch is not used to help determine the * location, and instead the zero point is pre-determined by the physical design of the mechanism.) * <p> * The scale factor multiplies the 0-1 ratiometric value to return useful units. Generally, the most useful scale factor * will be the angular or linear full scale of the potentiometer. * <p> * For example, let's say you have an ideal single-turn linear potentiometer attached to a robot arm. This pot will turn * 270 degrees over the 0V-5V range while the end of the arm travels 20 inches. Therefore, the * {@code fullVoltageRangeToInches} scale factor is {@code 20 inches / 5 V}, or {@code 4 inches/volt}. * * @param channel The analog channel this potentiometer is plugged into. * @param fullVoltageRangeToInches The scaling factor multiplied by the analog voltage value to obtain inches. * @return the distance sensor that uses the potentiometer on the given channel; never null */ public static DistanceSensor potentiometer(int channel, double fullVoltageRangeToInches) { return potentiometer(channel, fullVoltageRangeToInches, 0.0); } /** * Create a new {@link DistanceSensor} from an {@link AnalogPotentiometer} using the specified channel, scaling, and * offset. This method is often used when the offset can be hard-coded by first measuring the value of the potentiometer * at the mechanism's zero-point. On the other hand, if a limit switch is used to always determine the position of the * mechanism upon startup, then see {@link #potentiometer(int, double)}. * <p> * The scale factor multiplies the 0-1 ratiometric value to return useful units, and an offset to add after the scaling. * Generally, the most useful scale factor will be the angular or linear full scale of the potentiometer. * <p> * For example, let's say you have an ideal single-turn linear potentiometer attached to a robot arm. This pot will turn * 270 degrees over the 0V-5V range while the end of the arm travels 20 inches. Therefore, the * {@code fullVoltageRangeToInches} scale factor is {@code 20 inches / 5 V}, or {@code 4 inches/volt}. * <p> * To prevent the potentiometer from breaking due to minor shifting in alignment of the mechanism, the potentiometer may * be installed with the "zero-point" of the mechanism (e.g., arm in this case) a little ways into the potentiometer's * range (for example 10 degrees). In this case, the {@code offset} value is measured from the physical mechanical * design and can be specified to automatically remove the 10 degrees from the potentiometer output. * * @param channel The analog channel this potentiometer is plugged into. * @param fullVoltageRangeToInches The scaling factor multiplied by the analog voltage value to obtain inches. * @param offsetInInches The offset in inches that the distance sensor will subtract from the underlying value before * returning the distance * @return the distance sensor that uses the potentiometer on the given channel; never null */ public static DistanceSensor potentiometer(int channel, double fullVoltageRangeToInches, double offsetInInches) { AnalogPotentiometer pot = new AnalogPotentiometer(channel, fullVoltageRangeToInches, offsetInInches); return DistanceSensor.create(pot::get); } } /** * Factory method for different kinds of motors. */ public static final class Motors { private static final DoubleToDoubleFunction SPEED_LIMITER = Values.limiter(-1.0, 1.0); /** * Create a motor driven by a Talon speed controller on the specified channel. The speed output is limited to [-1.0,1.0] * inclusive. * * @param channel the channel the controller is connected to * @return a motor on the specified channel */ public static Motor talon(int channel) { return talon(channel, SPEED_LIMITER); } /** * Create a motor driven by a Talon speed controller on the specified channel, with a custom speed limiting function. * * @param channel the channel the controller is connected to * @param speedLimiter function that will be used to limit the speed; may not be null * @return a motor on the specified channel */ public static Motor talon(int channel, DoubleToDoubleFunction speedLimiter) { return new HardwareMotor(new Talon(channel), speedLimiter); } /** * Create a motor driven by a Jaguar speed controller on the specified channel. The speed output is limited to * [-1.0,1.0] inclusive. * * @param channel the channel the controller is connected to * @return a motor on the specified channel */ public static Motor jaguar(int channel) { return jaguar(channel, SPEED_LIMITER); } /** * Create a motor driven by a Jaguar speed controller on the specified channel, with a custom speed limiting function * * @param channel the channel the controller is connected to * @param speedLimiter function that will be used to limit the speed; may not be null * @return a motor on the specified channel */ public static Motor jaguar(int channel, DoubleToDoubleFunction speedLimiter) { return new HardwareMotor(new Jaguar(channel), SPEED_LIMITER); } /** * Create a motor driven by a Victor speed controller on the specified channel. The speed output is limited to * [-1.0,1.0] inclusive. * * @param channel the channel the controller is connected to * @return a motor on the specified channel */ public static Motor victor(int channel) { return victor(channel, SPEED_LIMITER); } /** * Create a motor driven by a Victor speed controller on the specified channel, with a custom speed limiting function * * @param channel the channel the controller is connected to * @param speedLimiter function that will be used to limit the speed (input voltage); may not be null * @return a motor on the specified channel */ public static Motor victor(int channel, DoubleToDoubleFunction speedLimiter) { return new HardwareMotor(new Victor(channel), SPEED_LIMITER); } /** * Create a motor driven by a VEX Robotics Victor SP speed controller on the specified channel. The speed output is * limited to [-1.0,1.0] inclusive. * * @param channel the channel the controller is connected to * @return a motor on the specified channel */ public static Motor victorSP(int channel) { return victorSP(channel, SPEED_LIMITER); } /** * Create a motor driven by a VEX Robotics Victor SP speed controller on the specified channel, with a custom speed * limiting function. * * @param channel the channel the controller is connected to * @param speedLimiter function that will be used to limit the speed (input voltage); may not be null * @return a motor on the specified channel */ public static Motor victorSP(int channel, DoubleToDoubleFunction speedLimiter) { return new HardwareMotor(new VictorSP(channel), speedLimiter); } /** * Creates a {@link TalonSRX} motor controlled by a Talon SRX with no sensors wired as inputs. * <p> * The resulting {@link TalonSRX} will have a null {@link TalonSRX#getAnalogInput()} and a null * {@link TalonSRX#getEncoderInput()}. * * @param deviceNumber the CAN device number for the Talon SRX; may not be null * @return a {@link TalonSRX} motor; never null */ public static TalonSRX talonSRX(int deviceNumber) { return talonSRX(deviceNumber, 0.0d, 0.0d); } /** * Creates a {@link TalonSRX} motor controlled by a Talon SRX with an optional quadrature encoder and no analog input * wired into the Talon. * <p> * The resulting {@link TalonSRX} will have a non-null {@link TalonSRX#getEncoderInput()} when the * <code>pulsesPerDegree</code> is non-zero. But the resulting {@link TalonSRX} will always have a null * {@link TalonSRX#getAnalogInput()}. * * @param deviceNumber the CAN device number for the Talon SRX; may not be null * @param pulsesPerDegree the number of encoder pulses per degree of revolution of the final shaft; may be 0 if unused * @return a {@link TalonSRX} motor; never null */ @Experimental public static TalonSRX talonSRX(int deviceNumber, double pulsesPerDegree) { return talonSRX(deviceNumber, pulsesPerDegree, 0.0d); } /** * Creates a {@link TalonSRX} motor controlled by a Talon SRX with an optional quadrature encoder and no an analog 3.3V * input wired into the Talon. * <p> * The resulting {@link TalonSRX} will have a non-null {@link TalonSRX#getEncoderInput()} when the * <code>pulsesPerDegree</code> is non-zero. Likewise, the resulting {@link TalonSRX} will have a non-null * {@link TalonSRX#getAnalogInput()} when the <code>analogTurnsOverVoltageRange</code> is non-zero. * * @param deviceNumber the CAN device number for the Talon SRX; may not be null * @param pulsesPerDegree the number of encoder pulses per degree of revolution of the final shaft; may be 0 if unused * @param analogTurnsOverVoltageRange the number of turns of an analog pot or analog encoder over the 0-3.3V range; may * be 0 if unused * @return a {@link TalonSRX} motor; never null */ @Experimental public static TalonSRX talonSRX(int deviceNumber, double pulsesPerDegree, double analogTurnsOverVoltageRange) { CANTalon talon = new CANTalon(deviceNumber); return talonSRX(talon, pulsesPerDegree, analogTurnsOverVoltageRange); } /** * Creates a {@link TalonSRX} motor controlled by a Talon SRX. The {@link CANTalon} object passed into this method * should be already configured by the calling code. * <p> * The resulting {@link TalonSRX} will have a null {@link TalonSRX#getEncoderInput()} and a null * {@link TalonSRX#getAnalogInput()}, and the {@link TalonSRX#getSelectedSensor()} will always return 0. * * @param talon the already configured {@link CANTalon} instance; may not be null * @return a {@link TalonSRX} motor; never null */ public static TalonSRX talonSRX(CANTalon talon) { return talonSRX(talon, 0.0, 0.0d); } /** * Creates a {@link TalonSRX} motor controlled by a Talon SRX with an optional (angle) sensor. The {@link CANTalon} * object passed into this method should be already configured by the calling code. * <p> * The resulting {@link TalonSRX} will have a non-null {@link TalonSRX#getEncoderInput()} when the * <code>pulsesPerDegree</code> is non-zero. But the resulting {@link TalonSRX} will always have a null * {@link TalonSRX#getAnalogInput()}. * * @param talon the already configured {@link CANTalon} instance; may not be null * @param pulsesPerDegree the number of encoder pulses per degree of revolution of the final shaft * @return a {@link TalonSRX} motor; never null */ @Experimental public static TalonSRX talonSRX(CANTalon talon, double pulsesPerDegree) { return talonSRX(talon, pulsesPerDegree, 0.0d); } /** * Creates a {@link TalonSRX} motor controlled by a Talon SRX with and optional quadrature encoder and/or an analog 3.3V * input wired into the Talon. The {@link CANTalon} object passed into this method should be already configured by the * calling code. * <p> * The resulting {@link TalonSRX} will have a non-null {@link TalonSRX#getEncoderInput()} when the * <code>pulsesPerDegree</code> is non-zero. Likewise, the resulting {@link TalonSRX} will have a non-null * {@link TalonSRX#getAnalogInput()} when the <code>analogTurnsOverVoltageRange</code> is non-zero. * * @param talon the already configured {@link CANTalon} instance; may not be null * @param pulsesPerDegree the number of encoder pulses per degree of revolution of the final shaft * @param analogTurnsOverVoltageRange the number of turns of an analog pot or analog encoder over the 0-3.3V range; may * be 0 if unused * @return a {@link TalonSRX} motor; never null */ @Experimental public static TalonSRX talonSRX(CANTalon talon, double pulsesPerDegree, double analogTurnsOverVoltageRange) { if (talon == null) throw new IllegalArgumentException("The CANTalon reference may not be null"); return new HardwareTalonSRX(talon, pulsesPerDegree, analogTurnsOverVoltageRange); } /** * Creates a {@link TalonSRX} motor controller that follows another Talon SRX. The resulting TalonSRX will have neither * a {@link TalonSRX#getAnalogInput()} or a {@link TalonSRX#getEncoderInput()}. * * @param deviceNumber the CAN device number for the Talon SRX; may not be null * @param leader the Talon SRX that is to be followed; may not be null * @param reverse <code>true</code> if the resulting Talon should have inverted output compared to the leader, or * <code>false</code> if the output should exactly match the leader * @return a {@link TalonSRX} motor controller that follows the leader; never null */ public static TalonSRX talonSRX(int deviceNumber, TalonSRX leader, boolean reverse) { CANTalon talon = new CANTalon(deviceNumber); talon.changeControlMode(TalonControlMode.Follower); talon.set(leader.getDeviceID()); talon.reverseOutput(reverse); return talonSRX(talon, 0.0d, 0.0d); } public static Motor spark(int channel) { return spark(channel, SPEED_LIMITER); } public static Motor spark(int channel, DoubleToDoubleFunction speedLimiter) { return new HardwareSpark(new Spark(channel), SPEED_LIMITER); } } /** * Factory method for hardware-based controllers. */ public static final class Controllers { /** * Create a component that manages and uses the hardware-based PID controller on the Talon SRX with a quadrature encoder * and/or an analog 3.3V input sensor wired into the Talon. * <p> * The resulting {@link TalonSRX} will have a non-null {@link TalonSRX#getEncoderInput()} when the * <code>pulsesPerDegree</code> is non-zero. Likewise, the resulting {@link TalonSRX} will have a non-null * {@link TalonSRX#getAnalogInput()} when the <code>analogTurnsOverVoltageRange</code> is non-zero. * * @param deviceNumber the CAN device number; may not be null * @param pulsesPerDegree the number of encoder pulses per degree of revolution of the final shaft * @param analogTurnsOverVoltageRange the number of turns of an analog pot or analog encoder over the 0-3.3V range; may * be 0 if unused * @return the interface for managing and using the Talon SRX hardware-based PID controller; never null */ @Experimental public static TalonController talonController(int deviceNumber, double pulsesPerDegree, double analogTurnsOverVoltageRange) { CANTalon talon = new CANTalon(deviceNumber); HardwareTalonController c = new HardwareTalonController(talon, pulsesPerDegree, analogTurnsOverVoltageRange); return c; } } /** * Factory methods for solenoids. */ public static final class Solenoids { /** * Create a double-acting solenoid that uses the specified channels on the default module. * * @param extendChannel the channel that extends the solenoid * @param retractChannel the channel that retracts the solenoid * @param initialDirection the initial direction for the solenoid; may not be null * @return a solenoid on the specified channels; never null */ public static Solenoid doubleSolenoid(int extendChannel, int retractChannel, Solenoid.Direction initialDirection) { DoubleSolenoid solenoid = new DoubleSolenoid(extendChannel, retractChannel); return new HardwareDoubleSolenoid(solenoid, initialDirection); } /** * Create a double-acting solenoid that uses the specified channels on the given module. * * @param module the module for the channels * @param extendChannel the channel that extends the solenoid * @param retractChannel the channel that retracts the solenoid * @param initialDirection the initial direction for the solenoid; may not be null * @return a solenoid on the specified channels; never null */ public static Solenoid doubleSolenoid(int module, int extendChannel, int retractChannel, Solenoid.Direction initialDirection) { DoubleSolenoid solenoid = new DoubleSolenoid(module, extendChannel, retractChannel); return new HardwareDoubleSolenoid(solenoid, initialDirection); } /** * Create a relay on the specified channel. * * @param channel the channel the relay is connected to * @return a relay on the specified channel */ public static Relay relay(int channel) { return new HardwareRelay(channel); } } public static final class HumanInterfaceDevices { private static void verifyJoystickConnected(Joystick joystick) { joystick.getButtonCount(); } /** * Create an generic input device controlled by the Driver Station. * * @param port the port on the driver station that the joystick is plugged into * @return the input device; never null */ public static InputDevice driverStationJoystick(int port) { Joystick joystick = new Joystick(port); verifyJoystickConnected(joystick); return InputDevice.create(joystick::getRawAxis, joystick::getRawButton, joystick::getPOV); } /** * Create a Logitech Attack 3 flight stick controlled by the Driver Station. * * @param port the port on the driver station that the flight stick is plugged into * @return the input device; never null */ public static FlightStick logitechAttack3D(int port) { Joystick joystick = new Joystick(port); verifyJoystickConnected(joystick); return FlightStick.create(joystick::getRawAxis, joystick::getRawButton, joystick::getPOV, joystick::getY, // pitch () -> joystick.getTwist() * -1, // yaw is reversed joystick::getX, // roll joystick::getThrottle, // throttle () -> joystick.getRawButton(1), // trigger () -> joystick.getRawButton(2)); // thumb } /** * Create a Logitech Extreme 3D flight stick controlled by the Driver Station. * * @param port the port on the driver station that the flight stick is plugged into * @return the input device; never null */ public static FlightStick logitechExtreme3D(int port) { Joystick joystick = new Joystick(port); verifyJoystickConnected(joystick); return FlightStick.create(joystick::getRawAxis, joystick::getRawButton, joystick::getPOV, joystick::getY, // pitch joystick::getTwist, // yaw joystick::getX, // roll joystick::getThrottle, // flapper thing on bottom () -> joystick.getRawButton(1), // trigger () -> joystick.getRawButton(2)); // thumb } /** * Create a Microsoft SideWinder flight stick controlled by the Driver Station. * * @param port the port on the driver station that the flight stick is plugged into * @return the input device; never null */ public static FlightStick microsoftSideWinder(int port) { Joystick joystick = new Joystick(port); verifyJoystickConnected(joystick); return FlightStick.create(joystick::getRawAxis, joystick::getRawButton, joystick::getPOV, () -> joystick.getY() * -1, // pitch is reversed joystick::getTwist, // yaw joystick::getX, // roll joystick::getThrottle, // throttle () -> joystick.getRawButton(1), // trigger () -> joystick.getRawButton(2)); // thumb } /** * Create a Logitech DualAction gamepad controlled by the Driver Station. * * @param port the port on the driver station that the gamepad is plugged into * @return the input device; never null */ public static Gamepad logitechDualAction(int port) { Joystick joystick = new Joystick(port); verifyJoystickConnected(joystick); return Gamepad.create(joystick::getRawAxis, joystick::getRawButton, joystick::getPOV, () -> joystick.getRawAxis(0), () -> joystick.getRawAxis(1) * -1, () -> joystick.getRawAxis(2), () -> joystick.getRawAxis(3) * -1, () -> joystick.getRawButton(6) ? 1.0 : 0.0, () -> joystick.getRawButton(7) ? 1.0 : 0.0, () -> joystick.getRawButton(4), () -> joystick.getRawButton(5), () -> joystick.getRawButton(1), () -> joystick.getRawButton(2), () -> joystick.getRawButton(0), () -> joystick.getRawButton(3), () -> joystick.getRawButton(9), () -> joystick.getRawButton(8), () -> joystick.getRawButton(10), () -> joystick.getRawButton(11)); } /** * Create a Logitech F310 gamepad controlled by the Driver Station. * * @param port the port on the driver station that the gamepad is plugged into * @return the input device; never null */ public static Gamepad logitechF310(int port) { Joystick joystick = new Joystick(port); verifyJoystickConnected(joystick); return Gamepad.create(joystick::getRawAxis, joystick::getRawButton, joystick::getPOV, () -> joystick.getRawAxis(0), () -> joystick.getRawAxis(1) * -1, () -> joystick.getRawAxis(4), () -> joystick.getRawAxis(5) * -1, () -> joystick.getRawAxis(2), () -> joystick.getRawAxis(3), () -> joystick.getRawButton(4), () -> joystick.getRawButton(5), () -> joystick.getRawButton(0), () -> joystick.getRawButton(1), () -> joystick.getRawButton(2), () -> joystick.getRawButton(3), () -> joystick.getRawButton(7), () -> joystick.getRawButton(6), () -> joystick.getRawButton(8), () -> joystick.getRawButton(9)); } /** * Create a Microsoft Xbox360 gamepad controlled by the Driver Station. * * @param port the port on the driver station that the gamepad is plugged into * @return the input device; never null */ public static Gamepad xbox360(int port) { Joystick joystick = new Joystick(port); verifyJoystickConnected(joystick); return Gamepad.create(joystick::getRawAxis, joystick::getRawButton, joystick::getPOV, () -> joystick.getRawAxis(0), () -> joystick.getRawAxis(1) * -1, () -> joystick.getRawAxis(4), () -> joystick.getRawAxis(5) * -1, () -> joystick.getRawAxis(2), () -> joystick.getRawAxis(3), () -> joystick.getRawButton(5), () -> joystick.getRawButton(6), () -> joystick.getRawButton(1), () -> joystick.getRawButton(2), () -> joystick.getRawButton(3), () -> joystick.getRawButton(4), () -> joystick.getRawButton(8), () -> joystick.getRawButton(7), () -> joystick.getRawButton(9), () -> joystick.getRawButton(10)); } } }
package retrobox.utils; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.List; import android.app.Activity; import android.os.AsyncTask; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationSet; import android.view.animation.DecelerateInterpolator; import android.view.animation.TranslateAnimation; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import retrobox.content.LoginInfo; import retrobox.content.SaveStateInfo; import retrobox.fileselector.FilesPanel; import xtvapps.core.AndroidFonts; import xtvapps.core.Callback; import xtvapps.core.SimpleCallback; import xtvapps.core.Utils; import xtvapps.core.content.KeyValue; import xtvapps.vfile.VirtualFile; public class RetroBoxDialog { protected static final String LOGTAG = RetroBoxDialog.class.getSimpleName(); private static final int DIALOG_OPENING_THRESHOLD = 800; private static Callback<String> cbListDialogDismiss = null; private static SimpleCallback cbGamepadDialog = null; private static String preselected = null; private static long openTimeStart = 0; public static void showAlert(final Activity activity, String message) { showAlertAsk(activity, null, message, null, null, null, null); } public static void showAlert(final Activity activity, String message, final SimpleCallback callback) { showAlertAsk(activity, null, message, null, null, callback, null); } public static void showAlert(final Activity activity, String title, String message) { showAlertAsk(activity, title, message, null, null, null, null); } public static void showAlert(final Activity activity, String title, String message, final SimpleCallback callback) { showAlertAsk(activity, title, message, null, null, callback, null); } public static void showAlertAsk(final Activity activity, String message, String optYes, String optNo, final SimpleCallback callback) { showAlertAsk(activity, null, message, optYes, optNo, callback, null); } public static void showAlertAsk(final Activity activity, String message, String optYes, String optNo, final SimpleCallback callbackYes, final SimpleCallback callbackNo) { showAlertAsk(activity, null, message, optYes, optNo, callbackYes, callbackNo); } public static void showException(final Activity activity, Exception e, SimpleCallback callback) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); Throwable cause = e.getCause(); if (cause!=null) { cause.printStackTrace(pw); } else { e.printStackTrace(pw); } final TextView text = (TextView)activity.findViewById(R.id.txtDialogAction); text.setTextSize(12); String msg = e.toString() + "\n" + e.getMessage() + "\n" + sw.toString(); showAlert(activity, "Error", msg, callback); } public static void showAlertAsk(final Activity activity, String title, String message, String optYes, String optNo, final SimpleCallback callback, final SimpleCallback callbackNo) { activity.findViewById(R.id.modal_dialog_actions).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { closeDialog(activity, R.id.modal_dialog_actions, new SimpleCallback(){ @Override public void onResult() { if (callback!=null) { callback.onError(); callback.onFinally(); } } }); } }); TextView txtMessage = (TextView)activity.findViewById(R.id.txtDialogAction); txtMessage.setText(message); TextView txtTitle = (TextView)activity.findViewById(R.id.txtDialogActionTitle); if (Utils.isEmptyString(title)) { txtTitle.setVisibility(View.GONE); } else { txtTitle.setText(title); txtTitle.setVisibility(View.VISIBLE); } final Button btnYes = (Button)activity.findViewById(R.id.btnDialogActionPositive); final Button btnNo = (Button)activity.findViewById(R.id.btnDialogActionNegative); if (Utils.isEmptyString(optYes)) optYes = "OK"; btnYes.setText(optYes); btnYes.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { closeDialog(activity, R.id.modal_dialog_actions, callback); } }); final boolean hasNoButton = !Utils.isEmptyString(optNo); if (hasNoButton) { btnNo.setVisibility(View.VISIBLE); btnNo.setText(optNo); btnNo.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { closeDialog(activity, R.id.modal_dialog_actions, new SimpleCallback() { @Override public void onResult() { if (callbackNo!=null) callbackNo.onResult(); if (callback!=null) callback.onError(); if (callbackNo!=null) callbackNo.onFinally(); if (callback!=null) callback.onFinally(); } }); } }); } else { btnNo.setVisibility(View.GONE); } openDialog(activity, R.id.modal_dialog_actions, new SimpleCallback(){ @Override public void onResult() { Button activeButton = hasNoButton?btnNo:btnYes; activeButton.setFocusable(true); activeButton.setFocusableInTouchMode(true); activeButton.requestFocus(); } }); } public static void showAlertCustom(final Activity activity, int viewResourceId, Callback<View> customViewCallback, final Callback<View> customViewFocusCallback, String optYes, String optNo, final SimpleCallback callback, final SimpleCallback callbackNo) { activity.findViewById(R.id.modal_dialog_custom).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { closeDialog(activity, R.id.modal_dialog_custom, new SimpleCallback(){ @Override public void onResult() { if (callback!=null) { callback.onError(); callback.onFinally(); } } }); } }); ViewGroup container = (ViewGroup)activity.findViewById(R.id.modal_dialog_custom_container); container.removeAllViews(); LayoutInflater layoutInflater = activity.getLayoutInflater(); View customView = layoutInflater.inflate(viewResourceId, container); if (customViewCallback!=null) customViewCallback.onResult(customView); final Button btnYes = (Button)activity.findViewById(R.id.btnDialogCustomPositive); final Button btnNo = (Button)activity.findViewById(R.id.btnDialogCustomNegative); final boolean hasNoButton = !Utils.isEmptyString(optNo); final boolean hasButtons = optYes != null || optNo != null; View actions = activity.findViewById(R.id.modal_dialog_custom_buttons); if (!hasButtons) { actions.setVisibility(View.GONE); } else { actions.setVisibility(View.VISIBLE); if (Utils.isEmptyString(optYes)) optYes = "OK"; btnYes.setText(optYes); btnYes.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { closeDialog(activity, R.id.modal_dialog_custom, new SimpleCallback() { @Override public void onResult() { if (callback!=null) { callback.onResult(); callback.onFinally(); } } }); } }); if (hasNoButton) { btnNo.setVisibility(View.VISIBLE); btnNo.setText(optNo); btnNo.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { closeDialog(activity, R.id.modal_dialog_custom, new SimpleCallback() { @Override public void onResult() { if (callbackNo!=null) callbackNo.onResult(); if (callback!=null) callback.onError(); if (callbackNo!=null) callbackNo.onFinally(); if (callback!=null) callback.onFinally(); } }); } }); } else { btnNo.setVisibility(View.GONE); } } openDialog(activity, R.id.modal_dialog_custom, new SimpleCallback(){ @Override public void onResult() { if (customViewFocusCallback!=null) { customViewFocusCallback.onResult(activity.findViewById(R.id.modal_dialog_custom)); } else { if (hasButtons) { Button activeButton = hasNoButton?btnNo:btnYes; activeButton.setFocusable(true); activeButton.setFocusableInTouchMode(true); activeButton.requestFocus(); } } } }); } public static void showLogin(final Activity activity, String title, String user, String password, String optLogin, String optCancel, final Callback<LoginInfo> callback) { activity.findViewById(R.id.modal_dialog_login).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { closeDialog(activity, R.id.modal_dialog_login, new SimpleCallback(){ @Override public void onResult() { if (callback!=null) { callback.onError(); callback.onFinally(); } } }); } }); TextView txtTitle = (TextView)activity.findViewById(R.id.txtDialogLogin); if (Utils.isEmptyString(title)) { txtTitle.setVisibility(View.GONE); } else { txtTitle.setText(title); txtTitle.setVisibility(View.VISIBLE); } final SimpleCallback wrapCallback = new SimpleCallback() { @Override public void onResult() { EditText txtUser = (EditText)activity.findViewById(R.id.txtDialogLoginUser); EditText txtPass = (EditText)activity.findViewById(R.id.txtDialogLoginPassword); LoginInfo loginInfo = new LoginInfo(); loginInfo.user = txtUser.getText().toString(); loginInfo.password = txtPass.getText().toString(); callback.onResult(loginInfo); callback.onFinally(); } @Override public void onError() { callback.onError(); } @Override public void onFinally() { callback.onFinally(); } }; final Button btnYes = (Button)activity.findViewById(R.id.btnDialogLoginPositive); final Button btnNo = (Button)activity.findViewById(R.id.btnDialogLoginNegative); if (!Utils.isEmptyString(optLogin)) { btnYes.setText(optLogin); } if (!Utils.isEmptyString(optCancel)) { btnNo.setText(optCancel); } btnYes.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { closeDialog(activity, R.id.modal_dialog_login, wrapCallback); } }); btnNo.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { closeDialog(activity, R.id.modal_dialog_login, new SimpleCallback() { @Override public void onResult() { if (callback!=null) callback.onError(); if (callback!=null) callback.onFinally(); } }); } }); openDialog(activity, R.id.modal_dialog_login, new SimpleCallback(){ @Override public void onResult() { activity.findViewById(R.id.txtDialogLoginUser).requestFocus(); } }); } private static void dismissGamepadDialog(Activity activity, SimpleCallback callback) { closeDialog(activity, R.id.modal_dialog_gamepad, callback); } // ingame gamepad dialog has fixed labels, and alwas calls callback on close public static void showGamepadDialogIngame(final Activity activity, GamepadInfoDialog dialog, final SimpleCallback callback) { dialog.updateGamepadVisible(activity); activity.findViewById(R.id.modal_dialog_gamepad).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dismissGamepadDialog(activity, callback); } }); openDialog(activity, R.id.modal_dialog_gamepad, null); } // this is called by retrobox client: // * it can be cancelled // * if it has a callback, call it and then hide the dialog (called when starting a game) public static void showGamepadDialog(final Activity activity, GamepadInfoDialog dialog, String[] labels, String textTop, String textBottom, SimpleCallback callback) { cbGamepadDialog = callback; activity.findViewById(R.id.modal_dialog_gamepad).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (cbGamepadDialog!=null) { cbGamepadDialog.onResult(); cbGamepadDialog = null; activity.runOnUiThread(new Runnable() { @Override public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } setDialogVisible(activity, R.id.modal_dialog_gamepad, false); } }); } else { dismissGamepadDialog(activity, null); } } }); dialog.setLabels(labels); dialog.updateGamepadVisible(activity); dialog.setInfo(textTop, textBottom); openDialog(activity, R.id.modal_dialog_gamepad, new SimpleCallback() { @Override public void onResult() { activity.findViewById(R.id.modal_dialog_gamepad).requestFocus(); } }); } public static void showListDialog(final Activity activity, String title, List<ListOption> options, Callback<KeyValue> callback) { showListDialog(activity, title, new ListOptionAdapter(options), callback, null); } public static void showListDialog(final Activity activity, String title, List<ListOption> options, Callback<KeyValue> callback, Callback<String> callbackDismiss) { showListDialog(activity, title, new ListOptionAdapter(options), callback, callbackDismiss); } public static void showListDialog(final Activity activity, String title, final BaseAdapter adapter, Callback<KeyValue> callback) { showListDialog(activity, title, adapter, callback, null); } public static void showListDialog(final Activity activity, String title, final BaseAdapter adapter, final Callback<KeyValue> callback, Callback<String> callbackDismiss) { activity.findViewById(R.id.modal_dialog_list).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { closeDialog(activity, R.id.modal_dialog_list, new SimpleCallback(){ @Override public void onResult() { callback.onError(); callback.onFinally(); } }); } }); TextView txtTitle = (TextView)activity.findViewById(R.id.txtDialogListTitle); if (Utils.isEmptyString(title)) { txtTitle.setVisibility(View.GONE); } else { txtTitle.setText(title); txtTitle.setVisibility(View.VISIBLE); } TextView txtInfo = (TextView)activity.findViewById(R.id.txtDialogListInfo); txtInfo.setVisibility(View.GONE); preselected = null; cbListDialogDismiss = callbackDismiss; final ListView lv = (ListView)activity.findViewById(R.id.lstDialogList); lv.setAdapter(adapter); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> vadapter, View v, int position, long id) { final KeyValue result = (KeyValue)adapter.getItem(position); preselected = result.getKey(); closeDialog(activity, R.id.modal_dialog_list, new SimpleCallback() { @Override public void onResult() { if (callback!=null) { callback.onResult(result); callback.onFinally(); } } }); } }); openDialog(activity, R.id.modal_dialog_list, new SimpleCallback() { @Override public void onResult() { lv.setSelection(0); lv.setFocusable(true); lv.setFocusableInTouchMode(true); lv.requestFocus(); } }); } public static void dismissListDialog(Activity activity) { closeDialog(activity, R.id.modal_dialog_list, new SimpleCallback() { @Override public void onResult() { if (cbListDialogDismiss!=null) cbListDialogDismiss.onResult(preselected); cbListDialogDismiss = null; } }); } public static boolean cancelDialog(Activity activity) { View dialog = getVisibleDialog(activity); if (dialog == null) return false; dialog.performClick(); return true; } private static boolean isVisible(View v) { return v!=null && v.getVisibility() == View.VISIBLE; } private static boolean isVisible(Activity activity, int dialogResourceId) { View dialog = activity.findViewById(dialogResourceId); return dialog !=null && dialog.getVisibility() == View.VISIBLE; } private static View getVisibleDialog(Activity activity) { View sideBar = activity.findViewById(R.id.modal_sidebar); View dialogActions = activity.findViewById(R.id.modal_dialog_actions); View dialogList = activity.findViewById(R.id.modal_dialog_list); View dialogChooser = activity.findViewById(R.id.modal_dialog_chooser); View gamepadDialog = activity.findViewById(R.id.modal_dialog_gamepad); View saveStateDialog = activity.findViewById(R.id.modal_dialog_savestates); View loginDialog = activity.findViewById(R.id.modal_dialog_login); View customDialog = activity.findViewById(R.id.modal_dialog_custom); View dialog = isVisible(gamepadDialog)? gamepadDialog : isVisible(dialogActions)? dialogActions : isVisible(dialogList) ? dialogList : isVisible(dialogChooser) ? dialogChooser : isVisible(saveStateDialog) ? saveStateDialog : isVisible(loginDialog) ? loginDialog : isVisible(customDialog) ? customDialog : isVisible(sideBar) ? sideBar : null; return dialog; } public static boolean isDialogVisible(Activity activity) { return getVisibleDialog(activity) != null; } public static boolean onKeyDown(Activity activity, int keyCode, final KeyEvent event) { if (isVisible(activity, R.id.modal_dialog_gamepad)) { return true; } return false; } public static boolean onKeyUp(Activity activity, int keyCode, final KeyEvent event) { // TODO use gamepad mappings //Log.v("RetroBoxDialog", "UP keyCode: " + keyCode + " elapsed " + (System.currentTimeMillis() - openTimeStart)); if (keyCode == KeyEvent.KEYCODE_BACK && isDialogVisible(activity)) { if ((System.currentTimeMillis() - openTimeStart) < DIALOG_OPENING_THRESHOLD) { // ignore if this is a key up from a tap on the BACK/SELECT key return true; } if (cbGamepadDialog!=null) { cbGamepadDialog.onError(); } cbGamepadDialog = null; cancelDialog(activity); return true; } if (isVisible(activity, R.id.modal_dialog_gamepad)) { cancelDialog(activity); return true; } return false; } private static void openDialog(Activity activity, int dialogResourceId, final SimpleCallback callback) { Animation fadeIn = new AlphaAnimation(0, 1); fadeIn.setInterpolator(new DecelerateInterpolator()); fadeIn.setDuration(400); final View view = activity.findViewById(dialogResourceId); fadeIn.setAnimationListener(new AnimationListener() { @Override public void onAnimationEnd(Animation animation) { if (callback!=null) callback.onResult(); } @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationStart(Animation animation) { view.setVisibility(View.VISIBLE); } }); openTimeStart = System.currentTimeMillis(); view.startAnimation(fadeIn); } private static void closeDialog(Activity activity, int dialogResourceId, final SimpleCallback callback) { Animation fadeOut = new AlphaAnimation(1, 0); fadeOut.setInterpolator(new DecelerateInterpolator()); fadeOut.setDuration(300); final View view = activity.findViewById(dialogResourceId); fadeOut.setAnimationListener(new AnimationListener() { @Override public void onAnimationEnd(Animation animation) { view.setVisibility(View.GONE); if (callback!=null) { callback.onResult(); callback.onFinally(); } } @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationStart(Animation animation) {} }); view.startAnimation(fadeOut); } public static void showSaveStatesDialog(final Activity activity, String title, final SaveStateSelectorAdapter adapter, final Callback<Integer> callback) { OnClickListener closingClickListener = new OnClickListener() { @Override public void onClick(View v) { closeDialog(activity, R.id.modal_dialog_savestates, new SimpleCallback(){ @Override public void onResult() { adapter.releaseImages(); callback.onError(); callback.onFinally(); } }); } }; activity.findViewById(R.id.modal_dialog_savestates).setOnClickListener(closingClickListener); activity.findViewById(R.id.btnSaveStateCancel).setOnClickListener(closingClickListener); AndroidFonts.setViewFont(activity.findViewById(R.id.txtDialogSaveStatesTitle), RetroBoxUtils.FONT_DEFAULT_B); AndroidFonts.setViewFont(activity.findViewById(R.id.txtDialogSaveStatesInfo), RetroBoxUtils.FONT_DEFAULT_M); AndroidFonts.setViewFont(activity.findViewById(R.id.txtDialogSaveStatesSlot), RetroBoxUtils.FONT_DEFAULT_M); AndroidFonts.setViewFont(activity.findViewById(R.id.btnSaveStateCancel), RetroBoxUtils.FONT_DEFAULT_M); TextView txtTitle = (TextView)activity.findViewById(R.id.txtDialogSaveStatesTitle); if (Utils.isEmptyString(title)) { txtTitle.setVisibility(View.GONE); } else { txtTitle.setText(title); txtTitle.setVisibility(View.VISIBLE); } final TextView txtSlot = (TextView)activity.findViewById(R.id.txtDialogSaveStatesSlot); final TextView txtInfo = (TextView)activity.findViewById(R.id.txtDialogSaveStatesInfo); final Callback<Integer> onSelectCallback = new Callback<Integer>(){ @Override public void onResult(Integer index) { System.out.println("show info " + index); if (index >= 0 && index < adapter.getCount()) { SaveStateInfo info = (SaveStateInfo)adapter.getItem(index); txtSlot.setText(info.getSlotInfo()); txtInfo.setText(info.getInfo()); } else { txtInfo.setText(""); } }}; final GridView grid = (GridView)activity.findViewById(R.id.savestates_grid); grid.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View view, int index, long arg3) { System.out.println("on item selected " + index); onSelectCallback.onResult(index); } @Override public void onNothingSelected(AdapterView<?> arg0) { System.out.println("on nothing selected "); onSelectCallback.onResult(-1); } }); grid.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { System.out.println("on onFocusChange " + hasFocus); if (!hasFocus) { onSelectCallback.onResult(-1); } else { int selected = grid.getSelectedItemPosition(); onSelectCallback.onResult(selected); } } }); grid.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) { System.out.println("on click listener"); callback.onResult(index); } }); grid.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int index, long arg3) { System.out.println("on long click listener"); onSelectCallback.onResult(index); return true; } }); AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { adapter.loadImages(); return null; } @Override protected void onPostExecute(Void result) { final GridView grid = (GridView)activity.findViewById(R.id.savestates_grid); grid.setAdapter(adapter); grid.setSelection(getSelectedSaveState(adapter)); openDialog(activity, R.id.modal_dialog_savestates, new SimpleCallback() { @Override public void onResult() { grid.requestFocus(); } }); } }; task.execute(); } private static int getSelectedSaveState(SaveStateSelectorAdapter adapter) { for(int i=0; i<adapter.getCount(); i++) { SaveStateInfo info = (SaveStateInfo)adapter.getItem(i); if (info.isSelected()) { return i; } } return 0; } public static void showSidebar(final Activity activity, final BaseAdapter mainAdapter, final BaseAdapter secondaryAdapter, final Callback<KeyValue> callback) { final ListView lv = (ListView)activity.findViewById(R.id.lstSidebarList); lv.setAdapter(mainAdapter); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> vadapter, View v, int position, long id) { dismissSidebar(activity); KeyValue result = (KeyValue)mainAdapter.getItem(position); callback.onResult(result); } }); final ListView lvBottom = (ListView)activity.findViewById(R.id.lstSidebarBottom); lvBottom.setAdapter(secondaryAdapter); lvBottom.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> vadapter, View v, int position, long id) { dismissSidebar(activity); KeyValue result = (KeyValue)secondaryAdapter.getItem(position); callback.onResult(result); } }); activity.findViewById(R.id.modal_sidebar).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dismissSidebar(activity); } }); lv.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { lv.setItemChecked(-1, false); } } }); lvBottom.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { lvBottom.setItemChecked(-1, false); } } }); openSidebar(activity, lv); } private static void openSidebar(Activity activity, final ListView lv) { setDialogVisible(activity, R.id.modal_sidebar, true); View sidebar = activity.findViewById(R.id.sidebar); AnimationSet animationSet = new AnimationSet(true); animationSet.setInterpolator(new DecelerateInterpolator()); animationSet.setDuration(500); Animation fadeIn = new AlphaAnimation(0.25f, 1); TranslateAnimation animation = new TranslateAnimation(-sidebar.getWidth(), 0, 0, 0); animationSet.addAnimation(fadeIn); animationSet.addAnimation(animation); sidebar.setAnimation(animationSet); animationSet.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) {} @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { lv.setSelection(0); lv.setFocusable(true); lv.setFocusableInTouchMode(true); lv.requestFocus(); } }); sidebar.startAnimation(animationSet); } public static void dismissSidebar(final Activity activity) { View sidebar = activity.findViewById(R.id.sidebar); AnimationSet animationSet = new AnimationSet(true); animationSet.setInterpolator(new DecelerateInterpolator()); animationSet.setDuration(300); Animation fadeIn = new AlphaAnimation(1, 0); TranslateAnimation animation = new TranslateAnimation(0, -sidebar.getWidth(), 0, 0); animationSet.addAnimation(fadeIn); animationSet.addAnimation(animation); animationSet.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) {} @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { setDialogVisible(activity, R.id.modal_sidebar, false); } }); sidebar.startAnimation(animationSet); } private static void setDialogVisible(Activity activity, int id, boolean visible) { activity.findViewById(id).setVisibility(visible?View.VISIBLE:View.INVISIBLE); } public static class FileChooserConfig { public String title; public VirtualFile initialDir; public List<String> matchList; public Callback<VirtualFile> callback; public Callback<VirtualFile> browseCallback; public boolean isDirOnly; public boolean isDirOptional; } public static void showFileChooserDialog(final Activity activity, final VirtualFile sysRoot, final FileChooserConfig config) { final Callback<VirtualFile> listCallback = new Callback<VirtualFile>() { @Override public void onResult(final VirtualFile result) { closeDialog(activity, R.id.modal_dialog_chooser, new SimpleCallback() { @Override public void onResult() { config.callback.onResult(result); config.callback.onFinally(); } }); } @Override public void onError() { closeDialog(activity, R.id.modal_dialog_chooser, new SimpleCallback(){ @Override public void onResult() { config.callback.onError(); config.callback.onFinally(); } }); } }; activity.findViewById(R.id.modal_dialog_chooser).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { listCallback.onError(); } }); TextView txtTitle = (TextView)activity.findViewById(R.id.txtDialogChooserTitle); if (Utils.isEmptyString(config.title)) { txtTitle.setVisibility(View.GONE); } else { txtTitle.setText(config.title); txtTitle.setVisibility(View.VISIBLE); } RetroBoxUtils.runOnBackground(activity, new ThreadedBackgroundTask() { @Override public void onBackground() { if (config.initialDir == null) return; try { if (config.initialDir.exists()) return; } catch (IOException e) { e.printStackTrace(); } config.initialDir = null; } @Override public void onUIThread() { final ListView lv = (ListView)activity.findViewById(R.id.lstDialogChooser); TextView txtStatus1 = (TextView)activity.findViewById(R.id.txtPanelStatus1); TextView txtStatus2 = (TextView)activity.findViewById(R.id.txtPanelStatus2); TextView txtStorage = (TextView)activity.findViewById(R.id.txtStorage); ImageView imgStorage = (ImageView)activity.findViewById(R.id.imgStorage); FilesPanel filesPanel = new FilesPanel(activity, sysRoot, lv, txtStorage, imgStorage, txtStatus1, txtStatus2, listCallback, config); filesPanel.refresh(); openDialog(activity, R.id.modal_dialog_chooser, new SimpleCallback() { @Override public void onResult() { if (lv.getChildCount()>0) { lv.setSelection(0); } lv.setFocusable(true); lv.setFocusableInTouchMode(true); lv.requestFocus(); } }); } }); } }
package cn.cerc.db.nas; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cn.cerc.core.ISession; import cn.cerc.core.Utils; import cn.cerc.db.core.DataQuery; import cn.cerc.db.core.IHandle; import cn.cerc.db.queue.QueueOperator; public class NasQuery extends DataQuery { private static final Logger log = LoggerFactory.getLogger(NasQuery.class); private static final long serialVersionUID = 1L; private String filePath; private String fileName; private QueueOperator operator; private NasModel nasMode = NasModel.create; public NasQuery(ISession session) { super(session); } public NasQuery(IHandle owner) { this(owner.getSession()); } @Override public DataQuery open() { try { this.fileName = this.getSqlText().getText().substring(this.getSqlText().getText().indexOf("select") + 6, this.getSqlText().getText().indexOf("from")).trim(); this.filePath = getOperator().findTableName(this.getSqlText().getText()); } catch (Exception e) { throw new RuntimeException("command suggest: select fileName from filePath"); } if (Utils.isEmpty(this.filePath)) { throw new RuntimeException("please enter the file path"); } if (nasMode == NasModel.readWrite) { File file = FileUtils.getFile(this.filePath, this.fileName); try { this.setJSON(FileUtils.readFileToString(file, StandardCharsets.UTF_8.name())); this.setActive(true); } catch (IOException e) { e.printStackTrace(); } } return this; } @Override public void delete() { File file = FileUtils.getFile(this.filePath, this.fileName); FileUtils.deleteQuietly(file); log.info(":" + file.getPath() + ""); } @Override public void save() { File file = FileUtils.getFile(this.filePath, this.fileName); try { String content = this.getJSON(); FileUtils.writeStringToFile(file, content, StandardCharsets.UTF_8.name(), false); } catch (IOException e) { log.info(":" + file.getPath() + ""); e.printStackTrace(); } log.info(":" + file.getPath() + ""); } @Override public QueueOperator getOperator() { if (operator == null) { operator = new QueueOperator(); } return operator; } public NasModel getNasMode() { return nasMode; } public void setNasMode(NasModel nasMode) { this.nasMode = nasMode; } @Override public NasQuery add(String sql) { super.add(sql); return this; } @Override public NasQuery add(String format, Object... args) { super.add(format, args); return this; } }
package org.jboss.as.version; import java.io.BufferedReader; import java.io.Closeable; import java.io.File; import java.io.InputStream; import java.io.Serializable; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Map; import java.util.Properties; import java.util.jar.Manifest; import org.jboss.modules.Module; import org.jboss.modules.ModuleIdentifier; import org.jboss.modules.ModuleLoader; /** * Common location to manage the AS based product name and version. * */ public class ProductConfig implements Serializable { private static final long serialVersionUID = 1L; private final String name; private final String version; private final String consoleSlot; private boolean isProduct; public static ProductConfig fromFilesystemSlot(ModuleLoader loader, String home, Map<?, ?> providedProperties) { return new ProductConfig(loader, getProductConfProperties(home), providedProperties); } public static ProductConfig fromKnownSlot(String slot, ModuleLoader loader, Map<?, ?> providedProperties) { return new ProductConfig(loader, new ProductConfProps(slot), providedProperties); } /** @deprecated use {@link #fromFilesystemSlot(ModuleLoader, String, Map)}. May be removed at any time. */ @Deprecated public ProductConfig(ModuleLoader loader, String home, Map<?, ?> providedProperties) { this(loader, getProductConfProperties(home), providedProperties); } private ProductConfig(ModuleLoader loader, ProductConfProps productConfProps, Map<?, ?> providedProperties) { String productName = null; String projectName = null; String productVersion = null; String consoleSlot = null; InputStream manifestStream = null; try { if (productConfProps.productModuleId != null) { Module module = loader.loadModule(productConfProps.productModuleId); manifestStream = module.getClassLoader().getResourceAsStream("META-INF/MANIFEST.MF"); Manifest manifest = null; if (manifestStream != null) { manifest = new Manifest(manifestStream); } if (manifest != null) { productName = manifest.getMainAttributes().getValue("JBoss-Product-Release-Name"); productVersion = manifest.getMainAttributes().getValue("JBoss-Product-Release-Version"); consoleSlot = manifest.getMainAttributes().getValue("JBoss-Product-Console-Slot"); projectName = manifest.getMainAttributes().getValue("JBoss-Project-Release-Name"); } } setSystemProperties(productConfProps.miscProperties, providedProperties); } catch (Exception e) { // Don't care } finally { safeClose(manifestStream); } isProduct = productName != null && !productName.isEmpty() && projectName == null; name = isProduct ? productName : projectName; version = productVersion; this.consoleSlot = consoleSlot; } private static String getProductConf(String home) { final String defaultVal = home + File.separator + "bin" + File.separator + "product.conf"; PrivilegedAction<String> action = new PrivilegedAction<String>() { public String run() { String env = System.getenv("JBOSS_PRODUCT_CONF"); if (env == null) { env = defaultVal; } return env; } }; return System.getSecurityManager() == null ? action.run() : AccessController.doPrivileged(action); } private static ProductConfProps getProductConfProperties(String home) { Properties props = new Properties(); BufferedReader reader = null; try { reader = Files.newBufferedReader(Paths.get(getProductConf(home)), StandardCharsets.UTF_8); props.load(reader); } catch (Exception e) { // Don't care } finally { safeClose(reader); } return new ProductConfProps(props); } /** Solely for use in unit testing */ public ProductConfig(final String productName, final String productVersion, final String consoleSlot) { this.name = productName; this.version = productVersion; this.consoleSlot = consoleSlot; } public String getProductName() { return name; } public String getProductVersion() { return version; } public boolean isProduct() { return isProduct; } public String getConsoleSlot() { return consoleSlot; } public String getPrettyVersionString() { if (name != null) { return String.format("%s %s (WildFly Core %s)", name, version, Version.AS_VERSION); } if (Version.UNKNOWN_CODENAME.equals(Version.AS_RELEASE_CODENAME)) { return String.format("WildFly Core %s", Version.AS_VERSION); } return String.format("WildFly Core %s \"%s\"", Version.AS_VERSION, Version.AS_RELEASE_CODENAME); } public String resolveVersion() { return version != null ? version : Version.AS_VERSION; } public String resolveName() { return name != null ? name : "WildFly"; } public static String getPrettyVersionString(final String name, String version1, String version2) { if(name != null) { return String.format("JBoss %s %s (WildFly %s)", name, version1, version2); } return String.format("WildFly %s \"%s\"", version1, version2); } private void setSystemProperties(final Properties propConfProps, final Map providedProperties) { if (propConfProps.size() == 0) { return; } PrivilegedAction<Void> action = new PrivilegedAction<Void>() { @Override public Void run() { for (Map.Entry<Object, Object> entry : propConfProps.entrySet()) { String key = (String)entry.getKey(); if (!key.equals("slot") && System.getProperty(key) == null) { //Only set the property if it was not defined by other means //System properties defined in standalone.xml, domain.xml or host.xml will overwrite System.setProperty(key, (String)entry.getValue()); //Add it to the provided properties used on reload by the server environment providedProperties.put(key, entry.getValue()); } } return null; } }; if (System.getSecurityManager() == null) { action.run(); } else { AccessController.doPrivileged(action); } } private static void safeClose(Closeable c) { if (c != null) try { c.close(); } catch (Throwable ignored) {} } private static class ProductConfProps { private final Properties miscProperties; private final ModuleIdentifier productModuleId; private ProductConfProps(String slot) { this.productModuleId = slot == null ? null : ModuleIdentifier.create("org.jboss.as.product", slot); this.miscProperties = new Properties(); } private ProductConfProps(Properties properties) { this(properties.getProperty("slot")); if (productModuleId != null) { properties.remove("slot"); } if (!properties.isEmpty()) { for (String key : properties.stringPropertyNames()) { this.miscProperties.setProperty(key, properties.getProperty(key)); } } } } }
package bookmark.views; import java.util.ArrayList; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.part.*; import org.eclipse.jface.util.DelegatingDragAdapter; import org.eclipse.jface.util.TransferDragSourceListener; import org.eclipse.jface.viewers.*; import org.eclipse.jface.window.Window; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.action.*; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.*; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.SWT; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.IPath; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; /** * This sample class demonstrates how to plug-in a new * workbench view. The view shows data obtained from the * model. The sample creates a dummy model on the fly, * but a real implementation would connect to the model * available either in this or another plug-in (e.g. the workspace). * The view is connected to the model using a content provider. * <p> * The view uses a label provider to define how model * objects should be presented in the view. Each * view can present the same model objects using * different labels and icons, if needed. Alternatively, * a single label provider can be shared between views * in order to ensure that objects of the same type are * presented in the same way everywhere. * <p> */ public class BookmarkView extends ViewPart { /** * The ID of the view as specified by the extension. */ public static final String ID = "bookmark.views.BookmarkView"; public static final int PARENT = 1; public static final int CHILD = 0; private TreeViewer viewer; private DrillDownAdapter drillDownAdapter; private Action action1; private Action action2; private Action action3; private Action action4; private Action action5; private Action doubleClickAction; /* * The content provider class is responsible for * providing objects to the view. It can wrap * existing objects in adapters or simply return * objects as-is. These objects may be sensitive * to the current input of the view, or ignore * it and always show the same content * (like Task List, for example). */ class TreeObject implements IAdaptable { private String name; private TreeParent parent; protected int flag; private String projectName; public TreeObject(String name) { this.name = name; this.flag = CHILD; this.projectName = ""; } public TreeObject(String name, String projectName) { this.name = name; this.flag = CHILD; this.projectName = projectName; } public String getName() { return name; } public String getProjectName() { return this.projectName; } public void setParent(TreeParent parent) { this.parent = parent; } public TreeParent getParent() { return parent; } public String toString() { return getName(); } /** * Override equals method to use name to compare two TreeObject */ public boolean equals(Object object) { if ((object instanceof TreeObject) && ((TreeObject) object).getName() == this.getName()) { return true; } else { return false; } } public Object getAdapter(Class key) { return null; } } class TreeParent extends TreeObject { private ArrayList<TreeObject> children; public TreeParent(String name) { super(name); this.flag = PARENT; children = new ArrayList<TreeObject>(); } public void addChild(TreeObject child) { children.add(child); child.setParent(this); } public void removeChild(TreeObject child) { children.remove(child); child.setParent(null); } /** * * @return TreeObject list or TreeObject[] when no children */ public TreeObject [] getChildren() { return (TreeObject [])children.toArray(new TreeObject[children.size()]); } public boolean hasChildren() { return children.size()>0; } /** * Add child to specified target node * * Use recursion way to add child, if child is leaf, to find his parent and add to its parent * * @param obj * @param path */ public boolean addChild(TreeObject target, TreeObject child) { TreeObject[] children = this.getChildren(); for (int i = 0; i < children.length; i++) { if (children[i].flag == PARENT) { // if target is folder if (target == children[i]) { // insert child ((TreeParent)children[i]).addChild(child); return true; } boolean is_ok = ((TreeParent)children[i]).addChild(target, child); if (is_ok) { return true; } } else if (children[i].flag == CHILD) { if (children[i] == target) { TreeParent parent = children[i].getParent(); if (parent.getParent() != null) { parent.getParent().addChild(parent, child); } else { // when it is invisibleRoot, so there is // no parent, directly to add parent.addChild(child); } return true; } } } return false; } /** * Remove child from target node * @param target * @return true when remove successfully or else false */ public boolean removeSelectedChild(TreeObject target) { TreeObject[] children = this.getChildren(); for (int i = 0; i < children.length; i++) { if (children[i].flag == PARENT) { // if target is folder if (target == children[i]) { // delete child this.removeChild(target); return true; } boolean is_ok = ((TreeParent)children[i]).removeSelectedChild(target); if (is_ok) { return true; } } else if (children[i].flag == CHILD) { if (children[i] == target) { TreeParent parent = children[i].getParent(); parent.removeChild(target); return true; } } } return false; } } class ViewContentProvider implements IStructuredContentProvider, ITreeContentProvider { public void inputChanged(Viewer v, Object oldInput, Object newInput) { } public void dispose() { } public Object[] getElements(Object parent) { return getChildren(parent); } public Object getParent(Object child) { if (child instanceof TreeObject) { return ((TreeObject)child).getParent(); } return null; } public Object [] getChildren(Object parent) { if (parent instanceof TreeParent) { return ((TreeParent)parent).getChildren(); } return new Object[0]; } public boolean hasChildren(Object parent) { if (parent instanceof TreeParent) return ((TreeParent)parent).hasChildren(); return false; } } class ViewLabelProvider extends LabelProvider { public String getText(Object obj) { return obj.toString(); } public Image getImage(Object obj) { String imageKey = ISharedImages.IMG_OBJ_ELEMENT; if (obj instanceof TreeParent) imageKey = ISharedImages.IMG_OBJ_FOLDER; return PlatformUI.getWorkbench().getSharedImages().getImage(imageKey); // if need to change customize image // return new Image(null, new FileInputStream("images/file.gif")); } } class NameSorter extends ViewerSorter { } /** * The constructor. */ public BookmarkView() { } /** * This is a callback that will allow us * to create the viewer and initialize it. */ public void createPartControl(Composite parent) { viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); drillDownAdapter = new DrillDownAdapter(viewer); viewer.setContentProvider(new ViewContentProvider()); viewer.setLabelProvider(new ViewLabelProvider()); viewer.setSorter(new NameSorter()); //viewer.setInput(getViewSite()); // test customize data TreeParent invisibleRoot = new TreeParent(""); TreeParent root = new TreeParent("Root"); TreeParent parent1 = new TreeParent("Parent1"); TreeParent parent2 = new TreeParent("Parent2"); TreeObject leaf1 = new TreeObject("leaf1"); TreeObject leaf2 = new TreeObject("leaf2"); parent1.addChild(leaf1); parent2.addChild(leaf2); root.addChild(parent1); root.addChild(parent2); invisibleRoot.addChild(root); viewer.setInput(invisibleRoot); Object obj = viewer.getInput(); System.out.println("here: " + (TreeParent)obj); // Create the help context id for the viewer's control PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), "bookmark.viewer"); makeActions(); hookContextMenu(); hookDoubleClickAction(); contributeToActionBars(); // add drop feature in tree DelegatingDragAdapter dragAdapter = new DelegatingDragAdapter(); dragAdapter.addDragSourceListener(new TransferDragSourceListener() { @Override public void dragStart(DragSourceEvent event) { // TODO Auto-generated method stub System.out.println("Drag start"); } @Override public void dragSetData(DragSourceEvent event) { // TODO Auto-generated method stub } @Override public void dragFinished(DragSourceEvent event) { // TODO Auto-generated method stub System.out.println("Drag end"); } @Override public Transfer getTransfer() { // TODO Auto-generated method stub return null; } }); viewer.addDragSupport(DND.DROP_COPY | DND.DROP_MOVE, dragAdapter.getTransfers(), dragAdapter); } private void hookContextMenu() { MenuManager menuMgr = new MenuManager("#PopupMenu"); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { BookmarkView.this.fillContextMenu(manager); } }); Menu menu = menuMgr.createContextMenu(viewer.getControl()); viewer.getControl().setMenu(menu); getSite().registerContextMenu(menuMgr, viewer); } private void contributeToActionBars() { IActionBars bars = getViewSite().getActionBars(); fillLocalPullDown(bars.getMenuManager()); fillLocalToolBar(bars.getToolBarManager()); } private void fillLocalPullDown(IMenuManager manager) { manager.add(action1); manager.add(new Separator()); manager.add(action2); } private void fillContextMenu(IMenuManager manager) { manager.add(action1); manager.add(action2); manager.add(new Separator()); drillDownAdapter.addNavigationActions(manager); // Other plug-ins can contribute there actions here manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); } private void fillLocalToolBar(IToolBarManager manager) { /** * add actions to tool bar */ manager.add(action1); manager.add(action2); manager.add(action3); manager.add(action4); manager.add(action5); manager.add(new Separator()); drillDownAdapter.addNavigationActions(manager); } private void makeActions() { // get active file info action action1 = new Action() { public void run() { //showMessage("Action 1 executed"); System.out.println("Action 1 executed"); // get the path of active editor file IWorkbench wb = PlatformUI.getWorkbench(); IWorkbenchWindow window = wb.getActiveWorkbenchWindow(); IWorkbenchPage page = window.getActivePage(); IEditorPart editor = page.getActiveEditor(); if (editor != null) { IFileEditorInput input = (IFileEditorInput)editor.getEditorInput(); IFile file = input.getFile(); System.out.println("relative path: " + file.getProjectRelativePath()); IPath path = ((FileEditorInput) input).getPath(); System.out.println("absolute path: " + path); System.out.println("project name: " + file.getProject().getName()); } else { System.out.println("no active editor"); } } }; action1.setText("Action 1"); action1.setToolTipText("Action 1 tooltip"); action1.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages(). getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK)); // open file in editor action action2 = new Action() { public void run() { //showMessage("Action 2 executed"); System.out.println("Action 2 executed"); //String absolutePath = "/Users/han.zhou/runtime-EclipseApplication/test/src/test.java"; String relativePath = "src/test.java"; IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); IProject project = workspaceRoot.getProject("test"); IFile file1 = project.getFile((new Path(relativePath))); //IFile file2 = workspaceRoot.getFileForLocation(Path.fromOSString(absolutePath)); IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IWorkbenchPage page = window.getActivePage(); // count editor id from file type IEditorDescriptor desc = PlatformUI.getWorkbench(). getEditorRegistry().getDefaultEditor(file1.getName()); try { page.openEditor(new FileEditorInput(file1), desc.getId()); System.out.println("relative is ok"); } catch (PartInitException e) { // TODO Auto-generated catch block e.printStackTrace(); } // try { // page.openEditor(new FileEditorInput(file2), desc.getId()); // System.out.println("absolute is ok"); // } catch (PartInitException e) { // // TODO Auto-generated catch block // e.printStackTrace(); } }; action2.setText("Action 2"); action2.setToolTipText("Action 2 tooltip"); action2.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages(). getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK)); // add directory and leaf action action3 = new Action() { public void run() { // get invisibleRoot TreeParent invisibleRoot = (TreeParent)viewer.getInput(); // get selection ISelection selection = viewer.getSelection(); Object obj = ((IStructuredSelection)selection).getFirstElement(); if (obj == null) { showMessage("No selection in Bookmark View."); } else { TreeObject target = (TreeObject)obj; // confirm dialog String title = "Confirm"; String question = "Do you really want to delelte this whole node?"; boolean answer = MessageDialog.openConfirm(null, title, question); if (answer) { invisibleRoot.removeSelectedChild(target); } } // update data source viewer.setInput(invisibleRoot); } }; action3.setText("Action 3"); action3.setToolTipText("Action 3 tooltip"); action3.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages(). getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK)); // use user input to add parent action4 = new Action() { public void run() { String parentName; // create an input dialog to get user input String title = "Input"; String question = "Please enter folder name:"; String initValue = ""; InputDialog dlg = new InputDialog(null, title, question, initValue, null); dlg.open(); if (dlg.getReturnCode() != Window.OK) { return ; } else { parentName = dlg.getValue(); System.out.println(parentName); } // new a folder TreeParent newParent = new TreeParent(parentName); // get invisible root TreeParent invisibleRoot = (TreeParent)viewer.getInput(); // get selection ISelection selection = viewer.getSelection(); Object obj = ((IStructuredSelection)selection).getFirstElement(); if (obj == null) { // no selection, default to add to the invisibleRoot invisibleRoot.addChild(newParent); } else { invisibleRoot.addChild((TreeObject)obj, newParent); } // add back to viewer viewer.setInput(invisibleRoot); } }; action4.setText("Action 4"); action4.setToolTipText("Action 4 tooltip"); action4.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages(). getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK)); // add book mark to selected parent action5 = new Action() { public void run() { //get active editor info String relativePath = ""; String projectName = ""; IWorkbench wb = PlatformUI.getWorkbench(); IWorkbenchWindow window = wb.getActiveWorkbenchWindow(); IWorkbenchPage page = window.getActivePage(); IEditorPart editor = page.getActiveEditor(); if (editor != null) { IFileEditorInput input = (IFileEditorInput)editor.getEditorInput(); IFile file = input.getFile(); relativePath = file.getProjectRelativePath().toOSString(); projectName = file.getProject().getName(); } else { showMessage("no active editor"); return ; } // create leaf with file info TreeObject child = new TreeObject(relativePath, projectName); // get invisibleRoot TreeParent invisibleRoot = (TreeParent)viewer.getInput(); // get selection ISelection selection = viewer.getSelection(); Object obj = ((IStructuredSelection)selection).getFirstElement(); if (obj == null) { // default to insert invisibleRoot invisibleRoot.addChild(child); } else { TreeObject targetParent = (TreeObject)obj; invisibleRoot.addChild(targetParent, child); } // update data source viewer.setInput(invisibleRoot); } }; action5.setText("Action 5"); action5.setToolTipText("Action 5 tooltip"); action5.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages(). getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK)); // double click action to open file doubleClickAction = new Action() { public void run() { ISelection selection = viewer.getSelection(); Object obj = ((IStructuredSelection)selection).getFirstElement(); //showMessage("Double-click detected on "+obj.toString()); if (obj != null) { TreeObject treeObject = (TreeObject)obj; if (treeObject.flag == 1) { showMessage("Please select a bookmark."); return ; } String relativePath = treeObject.getName(); IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); IProject project = workspaceRoot.getProject(treeObject.getProjectName()); IFile file1 = project.getFile((new Path(relativePath))); IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IWorkbenchPage page = window.getActivePage(); IEditorDescriptor desc = PlatformUI.getWorkbench().getEditorRegistry().getDefaultEditor(file1.getName()); try { page.openEditor(new FileEditorInput(file1), desc.getId()); //pageid } catch (PartInitException e) { e.printStackTrace(); } } } }; } private void hookDoubleClickAction() { viewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { doubleClickAction.run(); } }); } private void showMessage(String message) { MessageDialog.openInformation( viewer.getControl().getShell(), "Bookmark View", message); } /** * Passing the focus request to the viewer's control. */ public void setFocus() { viewer.getControl().setFocus(); } }
package com.oldterns.vilebot.handlers.user; import ca.szc.keratin.bot.annotation.HandlerContainer; import ca.szc.keratin.core.event.message.recieve.ReceivePrivmsg; import net.engio.mbassy.listener.Handler; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; @HandlerContainer public class GetInfoOn { private static final Pattern questionPattern = Pattern.compile("^!(infoon)\\s(.+)$"); private static final Pattern dumbQuestionPattern = Pattern.compile("^!(infun)\\s(.+)$"); @Handler public void getInfo(ReceivePrivmsg event) { String text = event.getText(); Matcher foonMatch = questionPattern.matcher( text ); Matcher funMatch = dumbQuestionPattern.matcher( text ); if (foonMatch.matches()) { String question = foonMatch.group(2); question += " site:wikipedia.org"; String answer = getWiki(question); event.reply(answer); } else if(funMatch.matches()) { String question = funMatch.group(2); question += "site:wikipedia.org"; String answer = getWiki(question); event.reply(answer); } } String getWiki(String query) { try { String wikiURL = getWikiURLFromGoogle(query); String wikipediaContent = getContent(wikiURL); String parsedWikiContent = parseResponse(wikipediaContent); return parsedWikiContent; } catch(Exception e) { return "Look I don't know."; } } String getWikiURLFromGoogle(String query) throws Exception { String googleURL = makeGoogleURL(query); String googleResponse = getContent(googleURL); String wikiURL = getWikiLink(googleResponse); return wikiURL; } String makeGoogleURL(String query) { query = encode(query); return "https: } String getWikiLink(String googleHTML) { Document doc = Jsoup.parse(googleHTML); Element link = doc.select("a[href*=/url?q=https://en.wikipedia]").first(); return link.attr("href").replace("/url?q=","").split("&")[0]; } String getContent(String URL) throws Exception { String content; URLConnection connection; connection = new URL(URL).openConnection(); connection.addRequestProperty( "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)" ); Scanner scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\Z"); content = scanner.next(); return content; } String parseResponse(String response) throws Exception { Document doc = Jsoup.parse(response); Element bodyDiv = doc.getElementById("mw-content-text"); Element firstParagraph = bodyDiv.getElementsByTag("p").first(); String answer = firstParagraph.text(); if(answer.isEmpty()) { throw new Exception(); } answer = answer.replaceAll("\\[[0-9]+\\]", ""); return answer; } String encode(String string) { try { return URLEncoder.encode(string, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return string; } } }
package bruce.common.utils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.RandomAccessFile; import java.io.Reader; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import bruce.common.functional.Action1; import bruce.common.functional.EAction1; import bruce.common.functional.Func1; import bruce.common.functional.LambdaUtils; import bruce.common.functional.PersistentSet; /** * * @author Bruce * */ public final class FileUtil { public static final String DEFAULT_CHARSET = "utf-8"; private static final int BUFFER_SIZE = 1024 * 8; private static final Pattern FILENAME_IN_PATH_PATTERN = Pattern.compile("(.+(?:\\/|\\\\))(.+)?$"); private static final Set<String> IMAGE_SUFFIX_SET = new PersistentSet<>("JPG", "GIF", "PNG", "JPEG", "BMP").getModifiableCollection(); public static boolean isImageFileSuffix(String path) { String suffix = getSuffixByFileName(getBaseNameByPath(path)); return IMAGE_SUFFIX_SET.contains(CommonUtils.emptyIfNull(suffix).toUpperCase()); } public static String getSuffixByFileName(String fileName) { if (CommonUtils.isStringNullOrWhiteSpace(fileName)) { return null; } else { int lastIndexOfPoint = fileName.lastIndexOf('.'); return lastIndexOfPoint == -1 ? null : fileName.substring(lastIndexOfPoint + 1); } } public static void copy(File src, File dst) { FileInputStream is = null; try { is = new FileInputStream(src); writeFile(dst, is); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } } /** * * @param resPath * @return */ public static String readTextFileForDefaultEncoding(final String resPath) { return readResourceTextFile(resPath, DEFAULT_CHARSET); } /** * * @param resPath * @param encodingName * @return */ public static String readResourceTextFile(final String resPath, final String encodingName) { InputStream xmlResourceInputStream = FileUtil.class.getClassLoader() .getResourceAsStream(resPath); BufferedReader xmlFileReader = new BufferedReader( new InputStreamReader(xmlResourceInputStream, Charset.forName(encodingName))); return readTextFromReader(xmlFileReader); } public static boolean writeTextFile(File filePath, String fileContent) { return writeFile(filePath, new ByteArrayInputStream(fileContent.getBytes())); } public static boolean writeTextFile(File filePath, String fileContent, String enc) { try { return writeFile(filePath, new ByteArrayInputStream(fileContent.getBytes(enc))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } public static boolean writeFile(File filePath, InputStream is) { return writeFile(filePath, is, null); } public static boolean writeFile(File filePath, InputStream is, Action1<Long> progressCallback) { FileOutputStream os = null; File outFile = new File(filePath.getAbsolutePath() + ".tmp"); if (!outFile.getParentFile().exists()) outFile.mkdirs(); try { if (outFile.exists() && !outFile.delete()) { throw new IllegalStateException("File already writing"); } os = new FileOutputStream(outFile); copy(is, os, progressCallback); return true; } catch (Exception e) { throw new RuntimeException(e); } finally { if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } finally { filePath.delete(); if (!outFile.renameTo(filePath)) { throw new IllegalStateException("Writing to an opening file!"); } } } } } public static boolean writeObj(Serializable src, String absPath) { ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(absPath))); oos.writeObject(src); oos.flush(); return true; } catch (IOException e) { e.printStackTrace(); } finally { try { if (oos != null) oos.close(); } catch (IOException e) { e.printStackTrace(); } } return false; } @SuppressWarnings("unchecked") public static <T> T readObj(String absPath) { ObjectInputStream ois = null; try { ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(absPath))); return (T) ois.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { try { if (ois != null) ois.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } public static void catFile(final File destFile, final File...files) { catFile(destFile, Arrays.asList(files)); } /** * * @param destFile * @param files * @throws IOException */ public static void catFile(final File destFile, final List<File> files) { if (files == null || files.isEmpty()) return; withOpen(destFile.getAbsolutePath(), "rw", new EAction1<RandomAccessFile>() { @Override public void call(RandomAccessFile writing) throws Throwable { byte[] buf = new byte[1024 * 8]; int nRead = 0; writing.seek(destFile.length()); for (File file : files) { RandomAccessFile reading = new RandomAccessFile(file, "r"); while ((nRead = reading.read(buf)) > 0) { writing.write(buf, 0, nRead); } reading.close(); } } }); } /** * * @param textFile * @return */ public static String readTextFile(File textFile) { return readTextFile(textFile, DEFAULT_CHARSET); } /** * * @param file * @param encoding * @return */ public static String readTextFile(final File file, String encoding) { BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); return readTextFromReader(br); } catch (Exception e) { throw new RuntimeException(e); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * * @param path * @return */ public static String getBaseNameByPath(final String path) { Matcher m = FILENAME_IN_PATH_PATTERN.matcher(path); if (!m.matches()) return null; return m.group(2); } /** * * @param path * @return */ public static String getFileDirPath(final String path) { Matcher m = FILENAME_IN_PATH_PATTERN.matcher(path); if (!m.matches()) return null; return m.group(1); } /** * BufferedReader * @param reader bufferedReader * @return */ public static String readTextFromReader(final Reader reader) { StringBuffer sb = new StringBuffer(); char[] buf = new char[1024 * 4]; int readLen; try { while (-1 != (readLen = reader.read(buf))) { sb.append(buf, 0, readLen); } } catch (IOException e) { e.printStackTrace(); } finally { if (null != reader) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return sb.toString(); } public static void withOpen(String filePath, String mode, EAction1<RandomAccessFile> block) { RandomAccessFile recordFile = null; try { recordFile = new RandomAccessFile(filePath, mode); block.call(recordFile); } catch (Throwable e) { throw new RuntimeException(e); } finally { try { if (recordFile != null) recordFile.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void writeObject(String parent, String fileName, Serializable obj) { File parentDir = new File(parent); parentDir.mkdirs(); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(new File(parentDir, fileName)))); oos.writeObject(obj); oos.flush(); } catch (IOException e) { CommonUtils.throwRuntimeExceptionAndPrint(e); } finally { if (oos != null) try { oos.close(); } catch (IOException e) { CommonUtils.throwRuntimeExceptionAndPrint(e); } } } @SuppressWarnings("unchecked") public static <T> T readObject(String path) { ObjectInputStream ois = null; try { ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(path))); return (T) ois.readObject(); } catch (Exception e) { CommonUtils.throwRuntimeExceptionAndPrint(e); } finally { try { if (ois != null) ois.close(); } catch (Exception e) { CommonUtils.throwRuntimeExceptionAndPrint(e); } } return null; } public static List<File> recurListFiles(File root, final String ...suffixs) { File[] dirs = root.listFiles(new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory(); } }); List<File> selectMany = LambdaUtils.selectMany(Arrays.asList(dirs), new Func1<Collection<File>, File>() { @Override public Collection<File> call(File dir) { return recurListFiles(dir, suffixs); } }); File[] files = root.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { for (String suffix : suffixs) { if (name.endsWith(suffix)) return true; } return false; } }); selectMany.addAll(Arrays.asList(files)); return selectMany; } public static long copy(InputStream input, OutputStream output) throws IOException { return copy(input, output, null); } public static long copy(InputStream input, OutputStream output, Action1<Long> progressCallback) throws IOException { byte[] buffer = new byte[BUFFER_SIZE]; long count = 0; int n; while ((n = input.read(buffer)) != -1) { output.write(buffer, 0, n); count += n; if (progressCallback != null) progressCallback.call(count); } return count; } public static String zip(String[] files, String zipFile) throws IOException { ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile))); try { byte data[] = new byte[BUFFER_SIZE]; BufferedInputStream origin = null; for (String file : files) { origin = new BufferedInputStream(new FileInputStream(file), BUFFER_SIZE); try { out.putNextEntry(new ZipEntry(FileUtil.getBaseNameByPath(file))); int count; while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) { out.write(data, 0, count); } } finally { origin.close(); } } } finally { out.close(); } return zipFile; } public static void unzip(String zipFile, String location) throws IOException { try { File f = new File(location); if (!f.isDirectory()) f.mkdirs(); ZipInputStream zin = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile))); try { ZipEntry ze = null; while ((ze = zin.getNextEntry()) != null) { String path = location + ze.getName(); if (ze.isDirectory()) { File unzipFile = new File(path); if (!unzipFile.isDirectory()) unzipFile.mkdirs(); } else { BufferedOutputStream fout = new BufferedOutputStream(new FileOutputStream(path, false)); try { for (int c = zin.read(); c != -1; c = zin.read()) { fout.write(c); } zin.closeEntry(); } finally { fout.close(); } } } } finally { zin.close(); } } catch (Exception e) { CommonUtils.throwRuntimeExceptionAndPrint(e); } } public static int recurEncodingConvert(String path, String fileSuffix, String originalEnc, String finalEnc) { List<File> txtFiles = recurListFiles(new File(path), fileSuffix); for (File f : txtFiles) { String content = readTextFile(f, originalEnc); writeTextFile(f, content, finalEnc); } return txtFiles.size(); } public static void deleteDir(File dir) { if (!dir.isDirectory()) return; File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) deleteDir(files[i]); else files[i].delete(); } dir.delete(); } public static void main(String[] args) { } }
package bruce.common.utils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.RandomAccessFile; import java.io.Reader; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import bruce.common.functional.Action1; import bruce.common.functional.EAction1; import bruce.common.functional.Func1; import bruce.common.functional.LambdaUtils; import bruce.common.functional.PersistentSet; /** * * @author Bruce * */ public final class FileUtil { public static final String DEFAULT_CHARSET = "utf-8"; private static final int BUFFER_SIZE = 1024 * 8; private static final Pattern FILENAME_IN_PATH_PATTERN = Pattern.compile("(.+(?:\\/|\\\\))([^?]+)(\\?.+)?$"); private static final Set<String> IMAGE_SUFFIX_SET = new PersistentSet<>("JPG", "GIF", "PNG", "JPEG", "BMP").getModifiableCollection(); private static final Set<String> MEDIA_SUFFIX_SET = new PersistentSet<>( "MP3", "MP4", "FLV", "OGG", "WMV", "WMA", "AVI", "MPEG").getModifiableCollection(); public static boolean isMediaFileSuffix(String path) { String suffix = getSuffixByFileName(getBaseNameByPath(path)); return MEDIA_SUFFIX_SET.contains(CommonUtils.emptyIfNull(suffix).toUpperCase()); } public static boolean isImageFileSuffix(String path) { String suffix = getSuffixByFileName(getBaseNameByPath(path)); return IMAGE_SUFFIX_SET.contains(CommonUtils.emptyIfNull(suffix).toUpperCase()); } public static String getSuffixByFileName(String fileName) { if (CommonUtils.isStringNullOrWhiteSpace(fileName)) { return null; } else { int lastIndexOfPoint = fileName.lastIndexOf('.'); return lastIndexOfPoint == -1 ? null : fileName.substring(lastIndexOfPoint + 1); } } public static void copy(File src, File dst) { FileInputStream is = null; try { is = new FileInputStream(src); writeFile(dst, is); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } } /** * * @param resPath * @return */ public static String readTextFileForDefaultEncoding(final String resPath) { return readResourceTextFile(resPath, DEFAULT_CHARSET); } /** * * @param resPath * @param encodingName * @return */ public static String readResourceTextFile(final String resPath, final String encodingName) { InputStream xmlResourceInputStream = FileUtil.class.getClassLoader() .getResourceAsStream(resPath); BufferedReader xmlFileReader = new BufferedReader( new InputStreamReader(xmlResourceInputStream, Charset.forName(encodingName))); return readTextFromReader(xmlFileReader); } public static boolean writeTextFile(File filePath, String fileContent) { return writeFile(filePath, new ByteArrayInputStream(fileContent.getBytes())); } public static boolean writeTextFile(File filePath, String fileContent, String enc) { try { return writeFile(filePath, new ByteArrayInputStream(fileContent.getBytes(enc))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } public static boolean writeFile(File filePath, InputStream is) { return writeFile(filePath, is, null); } public static boolean writeFile(File filePath, InputStream is, Action1<Long> progressCallback) { FileOutputStream os = null; File outFile = new File(filePath.getAbsolutePath() + ".tmp"); if (!outFile.getParentFile().exists()) outFile.mkdirs(); try { if (outFile.exists() && !outFile.delete()) { throw new IllegalStateException("File already writing"); } os = new FileOutputStream(outFile); copy(is, os, progressCallback); return true; } catch (Exception e) { throw new RuntimeException(e); } finally { if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } finally { filePath.delete(); if (!outFile.renameTo(filePath)) { throw new IllegalStateException("Writing to an opening file!"); } } } } } public static boolean writeObj(Serializable src, String absPath) { ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(absPath))); oos.writeObject(src); oos.flush(); return true; } catch (IOException e) { e.printStackTrace(); } finally { try { if (oos != null) oos.close(); } catch (IOException e) { e.printStackTrace(); } } return false; } @SuppressWarnings("unchecked") public static <T> T readObj(String absPath) { ObjectInputStream ois = null; try { ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(absPath))); return (T) ois.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { try { if (ois != null) ois.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } public static void catFile(final File destFile, final File...files) { catFile(destFile, Arrays.asList(files)); } /** * * @param destFile * @param files * @throws IOException */ public static void catFile(final File destFile, final List<File> files) { if (files == null || files.isEmpty()) return; withOpen(destFile.getAbsolutePath(), "rw", new EAction1<RandomAccessFile>() { @Override public void call(RandomAccessFile writing) throws Throwable { byte[] buf = new byte[1024 * 8]; int nRead = 0; writing.seek(destFile.length()); for (File file : files) { RandomAccessFile reading = new RandomAccessFile(file, "r"); while ((nRead = reading.read(buf)) > 0) { writing.write(buf, 0, nRead); } reading.close(); } } }); } /** * * @param textFile * @return */ public static String readTextFile(File textFile) { return readTextFile(textFile, DEFAULT_CHARSET); } /** * * @param file * @param encoding * @return */ public static String readTextFile(final File file, String encoding) { BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); return readTextFromReader(br); } catch (Exception e) { throw new RuntimeException(e); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * * @param path * @return */ public static String getBaseNameByPath(final String path) { Matcher m = FILENAME_IN_PATH_PATTERN.matcher(path); if (!m.matches()) return null; return m.group(2); } /** * * @param path * @return */ public static String getFileDirPath(final String path) { Matcher m = FILENAME_IN_PATH_PATTERN.matcher(path); if (!m.matches()) return null; return m.group(1); } /** * BufferedReader * @param reader bufferedReader * @return */ public static String readTextFromReader(final Reader reader) { StringBuffer sb = new StringBuffer(); char[] buf = new char[1024 * 4]; int readLen; try { while (-1 != (readLen = reader.read(buf))) { sb.append(buf, 0, readLen); } } catch (IOException e) { e.printStackTrace(); } finally { if (null != reader) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return sb.toString(); } public static void withOpen(String filePath, String mode, EAction1<RandomAccessFile> block) { RandomAccessFile recordFile = null; try { recordFile = new RandomAccessFile(filePath, mode); block.call(recordFile); } catch (Throwable e) { throw new RuntimeException(e); } finally { try { if (recordFile != null) recordFile.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void writeObject(String parent, String fileName, Serializable obj) { File parentDir = new File(parent); parentDir.mkdirs(); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(new File(parentDir, fileName)))); oos.writeObject(obj); oos.flush(); } catch (IOException e) { CommonUtils.throwRuntimeExceptionAndPrint(e); } finally { if (oos != null) try { oos.close(); } catch (IOException e) { CommonUtils.throwRuntimeExceptionAndPrint(e); } } } @SuppressWarnings("unchecked") public static <T> T readObject(String path) { ObjectInputStream ois = null; try { ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(path))); return (T) ois.readObject(); } catch (Exception e) { CommonUtils.throwRuntimeExceptionAndPrint(e); } finally { try { if (ois != null) ois.close(); } catch (Exception e) { CommonUtils.throwRuntimeExceptionAndPrint(e); } } return null; } public static List<File> recurListFiles(File root, final String ...suffixs) { File[] dirs = root.listFiles(new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory(); } }); List<File> selectMany = LambdaUtils.selectMany(Arrays.asList(dirs), new Func1<Collection<File>, File>() { @Override public Collection<File> call(File dir) { return recurListFiles(dir, suffixs); } }); File[] files = root.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { for (String suffix : suffixs) { if (name.endsWith(suffix)) return true; } return false; } }); selectMany.addAll(Arrays.asList(files)); return selectMany; } public static long copy(InputStream input, OutputStream output) throws IOException { return copy(input, output, null); } public static long copy(InputStream input, OutputStream output, Action1<Long> progressCallback) throws IOException { byte[] buffer = new byte[BUFFER_SIZE]; long count = 0; int n; while ((n = input.read(buffer)) != -1) { output.write(buffer, 0, n); count += n; if (progressCallback != null) progressCallback.call(count); } return count; } public static String zip(String[] files, String zipFile) throws IOException { ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile))); try { byte data[] = new byte[BUFFER_SIZE]; BufferedInputStream origin = null; for (String file : files) { origin = new BufferedInputStream(new FileInputStream(file), BUFFER_SIZE); try { out.putNextEntry(new ZipEntry(FileUtil.getBaseNameByPath(file))); int count; while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) { out.write(data, 0, count); } } finally { origin.close(); } } } finally { out.close(); } return zipFile; } public static void unzip(String zipFile, String location) throws IOException { try { File f = new File(location); if (!f.isDirectory()) f.mkdirs(); ZipInputStream zin = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile))); try { ZipEntry ze = null; while ((ze = zin.getNextEntry()) != null) { String path = location + ze.getName(); if (ze.isDirectory()) { File unzipFile = new File(path); if (!unzipFile.isDirectory()) unzipFile.mkdirs(); } else { BufferedOutputStream fout = new BufferedOutputStream(new FileOutputStream(path, false)); try { for (int c = zin.read(); c != -1; c = zin.read()) { fout.write(c); } zin.closeEntry(); } finally { fout.close(); } } } } finally { zin.close(); } } catch (Exception e) { CommonUtils.throwRuntimeExceptionAndPrint(e); } } public static int recurEncodingConvert(String path, String fileSuffix, String originalEnc, String finalEnc) { List<File> txtFiles = recurListFiles(new File(path), fileSuffix); for (File f : txtFiles) { String content = readTextFile(f, originalEnc); writeTextFile(f, content, finalEnc); } return txtFiles.size(); } public static void deleteDir(File dir) { if (!dir.isDirectory()) return; File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) deleteDir(files[i]); else files[i].delete(); } dir.delete(); } public static void main(String[] args) { } }
package businessmodel; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import org.joda.time.DateTime; import businessmodel.assemblyline.AssemblyLine; import businessmodel.assemblyline.AssemblyLineAFactory; import businessmodel.assemblyline.AssemblyLineBFactory; import businessmodel.assemblyline.AssemblyLineCFactory; import businessmodel.assemblyline.AssemblyLineScheduler; import businessmodel.category.VehicleOption; import businessmodel.order.Order; /** * The Main Scheduler who's in charge for the individual AssemblyLineSchedulers. * * @author Team 10 * */ public class MainScheduler { private OrderManager ordermanager; private ArrayList<AssemblyLine> assemblylines; private String systemWideAlgo; private final int nbOrdersSpecificationBatch = 3; /** * Constructor to create MainScheduler and set the OrderManager. * @param ordermanager */ public MainScheduler(OrderManager ordermanager){ this.setOrderManager(ordermanager); this.generateAssemblyLines(); changeSystemWideAlgorithm("FIFO", null); } /** * Generate the AssemblyLines. */ private void generateAssemblyLines() { ArrayList<AssemblyLine> assemblylines = new ArrayList<AssemblyLine>(); AssemblyLineAFactory factoryA = new AssemblyLineAFactory(); AssemblyLineBFactory factoryB = new AssemblyLineBFactory(); AssemblyLineCFactory factoryC = new AssemblyLineCFactory(); AssemblyLine line1 = factoryA.createAssemblyLine(this); AssemblyLine line2 = factoryB.createAssemblyLine(this); AssemblyLine line3 = factoryC.createAssemblyLine(this); assemblylines.add(line1); assemblylines.add(line2); assemblylines.add(line3); this.setAssemblyLines(assemblylines); } /** * Schedule pending orders. */ public void schedulePendingOrders() { this.ordermanager.schedulePendingOrders(); } /** * Finish given order. * @param completedorder */ public void finishedOrder(Order completedorder) { this.ordermanager.finishedOrder(completedorder); } /** * Place order in front of pending orders queue. * @param order */ public void placeOrderInFront(Order order) { this.ordermanager.placeOrderInFront(order); } /** * Get the pending orders of the system. * @return */ public LinkedList<Order> getPendingOrders() { return this.ordermanager.getPendingOrders(); } /** * Get AssemblyLineSchedulers. * @return AssemblyLineSchedulers */ public ArrayList<AssemblyLineScheduler> getAssemblyLineSchedulers() { ArrayList<AssemblyLineScheduler> schedulers = new ArrayList<AssemblyLineScheduler>(); for (AssemblyLine assemblyLine: this.getAssemblyLines()) { schedulers.add(assemblyLine.getAssemblyLineScheduler()); } return schedulers; } /** * Get the system wide algorithm. * @return */ public String getAlgorithm() { return systemWideAlgo; } /** * Get the OrderManager. * @return ordermanager */ protected OrderManager getOrderManager() { return ordermanager; } /** * Place the given order. * @param order */ protected void placeOrder(Order order){ ArrayList<AssemblyLine> possibleAssemblyLines = getPossibleAssemblyLinesToPlaceOrder(order); if(possibleAssemblyLines.size() != 0){ AssemblyLine fastestAssemblyLine = possibleAssemblyLines.get(0); for(AssemblyLine assem2 : getPossibleAssemblyLinesToPlaceOrder(order)){ if(assem2.getEstimatedCompletionTimeOfNewOrder(order).isBefore(fastestAssemblyLine.getEstimatedCompletionTimeOfNewOrder(order))) fastestAssemblyLine = assem2; } fastestAssemblyLine.getAssemblyLineScheduler().addOrder(order); } } /** * Get all the AssemblyLines. * @return assemblylines */ protected ArrayList<AssemblyLine> getAssemblyLines() { return this.assemblylines; } /** * Change the algorithm. * @param algo * @param options */ protected void changeSystemWideAlgorithm(String algo, ArrayList<VehicleOption> options) { this.systemWideAlgo = algo; for (AssemblyLine assemblyLine: this.getAssemblyLines()) { assemblyLine.getAssemblyLineScheduler().changeAlgorithm(algo, options); } } /** * Check if the given options satisfy the restraint of occurrence of the given amount of orders. * @param options * @return */ private boolean checkOptionsForSpecificationBatch(ArrayList<VehicleOption> options) { int orderCount = 0; for(AssemblyLine assem: this.getAssemblyLines()){ for(Order order: assem.getAssemblyLineScheduler().getOrders()){ int count = 0; for(VehicleOption opt: options){ for(VehicleOption opt2: order.getOptions()){ if (opt.toString().equals(opt2.toString())) count++; } } if (count == options.size()) orderCount++; } } if (orderCount < this.nbOrdersSpecificationBatch) return false; return true; } /** * Get the possible AssemblyLines to place the given order. * @param order * @return */ private ArrayList<AssemblyLine> getPossibleAssemblyLinesToPlaceOrder(Order order){ ArrayList<AssemblyLine> possiblelines = new ArrayList<AssemblyLine>(); for(AssemblyLine assem : this.getAssemblyLines()){ if(assem.canAddOrder(order)) possiblelines.add(assem); } return possiblelines; } /** * Set the OrderManager. * @param ordermanager */ private void setOrderManager(OrderManager ordermanager) { this.ordermanager = ordermanager; } /** * Set the AssemblyLines with the given AssemblyLines. * @param assemblylines */ private void setAssemblyLines(ArrayList<AssemblyLine> assemblylines) { this.assemblylines = assemblylines; } /** * Get the latest time of the AssemblyLines. * @return */ protected DateTime getTime(){ DateTime currenttime = this.getAssemblyLines().get(0).getAssemblyLineScheduler().getCurrentTime(); for(AssemblyLine line: this.getAssemblyLines()){ if(currenttime.isAfter(line.getAssemblyLineScheduler().getCurrentTime())); } return currenttime; } /* // TODO: miss maken ni zeker public void startNewDay(){ boolean ready = true; for(AssemblyLineScheduler scheduler: this.getAssemblyLineSchedulers()){ if(!scheduler.checkNewDay()) ready = false; } } */ /** * Get the sets of VehicleOptions that occur in more than the given amount of orders. * @return iterator of the sets */ public Iterator<ArrayList<VehicleOption>> getUnscheduledVehicleOptions() { ArrayList<ArrayList<VehicleOption>> choices = new ArrayList<ArrayList<VehicleOption>>(); HashSet<VehicleOption> set = new HashSet<VehicleOption>(); for (AssemblyLine line : this.getAssemblyLines()){ for(Order order: line.getAssemblyLineScheduler().getOrders()){ ArrayList<VehicleOption> options = new ArrayList<VehicleOption>(); for(VehicleOption opt: order.getOptions()){ ArrayList<VehicleOption> temp = new ArrayList<VehicleOption>(); temp.add(opt); if (!set.contains(opt)){ if (this.checkOptionsForSpecificationBatch(temp)){ options.add(opt); set.add(opt); } }else{ options.add(opt); } } boolean duplicate = true; for(ArrayList<VehicleOption> opts: choices){ if(opts.size() != options.size()) break; for(int i=0; i < opts.size(); i++){ if(!options.get(i).toString().equals(opts.get(i).toString())) duplicate = false; } if(duplicate) break; } if (!duplicate || choices.size() == 0) choices.add(options); } } // for(ArrayList<VehicleOption> list: choices){ // System.out.println(list.toString()); return choices.iterator(); } }
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ package ca.team3161.iapetus; import ca.team3161.lib.robot.ThreadedAutoRobot; import ca.team3161.lib.utils.controls.LogitechDualAction; import ca.team3161.lib.robot.Drivetrain; import ca.team3161.lib.robot.PIDDrivetrain; import ca.team3161.lib.robot.pid.EncoderPidSrc; import ca.team3161.lib.robot.pid.GyroPidSrc; import ca.team3161.lib.robot.pid.PID; import ca.team3161.lib.utils.controls.Joystick; import edu.wpi.first.wpilibj.Compressor; import edu.wpi.first.wpilibj.SpeedController; import edu.wpi.first.wpilibj.Victor; import edu.wpi.first.wpilibj.Talon; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.Gyro; import edu.wpi.first.wpilibj.Relay; import com.team254.lib.CheesyVisionServer; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Iapetus extends ThreadedAutoRobot { private final SpeedController leftDrive = new Drivetrain(new SpeedController[]{new Talon(1), new Victor(2), new Talon(3)}).setInverted(true); private final SpeedController rightDrive = new Drivetrain(new SpeedController[]{new Talon(4), new Victor(5), new Talon(6)}).setInverted(false); private final Shooter shooter = Shooter.getInstance(); private final Gyro gyro = new Gyro(1); private final Encoder leftEncoder = new Encoder(2, 3), rightEncoder = new Encoder(4, 5); private final PIDDrivetrain pidDrive = new PIDDrivetrain(leftDrive, rightDrive, new PID(new EncoderPidSrc(leftEncoder), 25.0f, -0.0075f, -0.003f, 0.0065f), new PID(new EncoderPidSrc(rightEncoder), 25.0f, -0.0075f, -0.003f, 0.0065f), new PID(new GyroPidSrc(gyro), 5.0f, 0.9f, 0.0f, 0.6f)); private final Compressor compressor = new Compressor(7, 2); private final CheesyVisionServer visionServer = CheesyVisionServer.getInstance(RobotConstants.Auto.VISION_PORT); private final LogitechDualAction gamepad = new LogitechDualAction(RobotConstants.Gamepad.PORT, RobotConstants.Gamepad.DEADZONE); private final LogitechDualAction gamepad2 = new LogitechDualAction(RobotConstants.Gamepad2.PORT, RobotConstants.Gamepad2.DEADZONE); private DriverStation.Alliance alliance = DriverStation.Alliance.kInvalid; private final Relay underglowController = new Relay(1); private static final Relay.Value BLUE_UNDERGLOW = Relay.Value.kForward; private static final Relay.Value RED_UNDERGLOW = Relay.Value.kReverse; private static final Relay.Value PURPLE_UNDERGLOW = Relay.Value.kOn; /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { gamepad.setInverted(true); gamepad2.setInverted(true); alliance = DriverStation.getInstance().getAlliance(); dsLcd.clear(); dsLcd.println(0, "Alliance: " + alliance.name.toUpperCase()); shooter.disableAll(); shooter.start(); shooter.setForkAngle(RobotConstants.Positions.START); shooter.closeClaw(); shooter.drawWinch(); restartEncoders(); visionServer.start(); } public void restartEncoders() { leftEncoder.stop(); rightEncoder.stop(); leftEncoder.reset(); rightEncoder.reset(); leftEncoder.start(); rightEncoder.start(); } /** * This method is invoked by a new Thread. * The main robot thread's role during autonomous is simply to maintain * core robot functionality, eg feeding the Watchdog and responding to * FMS events. A new Thread handles autonomous behaviour so that we can * use Thread.sleep() rather than checking Timer values. * This method's semantics are one-shot, as opposed to continuous looping * as provided by autonomousPeriodic or autonomousContinuous. This allows * simpler scripting and also avoids busy-wait conditions. * @throws Exception */ public void autonomousThreaded() throws Exception { underglowController.set(PURPLE_UNDERGLOW); compressor.stop(); visionServer.reset(); visionServer.startSamplingCounts(); pidDrive.reset(); restartEncoders(); gyro.reset(); dsLcd.println(1, "Starting AUTO"); shooter.drawWinch(); shooter.setForkAngle(RobotConstants.Positions.START); shooter.closeClaw(); pidDrive.start(); /* NORMAL AUTO ROUTINE */ // drive closer to goal dsLcd.println(1, "Driving up..."); pidDrive.setTask(pidDrive.DRIVE); pidDrive.setTicksTarget(RobotConstants.Auto.DRIVE_DISTANCE); pidDrive.waitForTarget(); // try to ensure we are facing forward dsLcd.println(1, "Correcting bearing"); pidDrive.setTask(pidDrive.TURN); waitFor(250); pidDrive.turnByDegrees(-(float) gyro.getAngle()); dsLcd.println(1, "Assuming firing position"); shooter.setForkAngle(RobotConstants.Positions.SHOOTING); waitFor(500); if (!visionServer.getLeftStatus() && !visionServer.getRightStatus()) { dsLcd.println(1, "Waiting for hot goal"); waitFor(RobotConstants.Auto.HOTGOAL_DELAY); } // fire dsLcd.println(1, "Firing"); shooter.fire(); waitFor(750); // reset and turn around dsLcd.println(1, "Turning around"); shooter.closeClaw(); shooter.setForkAngle(RobotConstants.Positions.START); pidDrive.setTask(pidDrive.TURN); pidDrive.turnByDegrees(180.0f); pidDrive.waitForTarget(); dsLcd.println(1, "AUTO complete"); visionServer.stopSamplingCounts(); } /** * Put anything here that needs to be performed by the main robot thread * during the autonomous period. DO NOT use any Drivetrain, Gamepad, * Solenoid, etc. fields in here - these are reserved for use ONLY * within autonomousThreaded()! */ public void autonomousPeriodic() { if (visionServer.hasClientConnection()) { dsLcd.println(2, "Vision connected"); } else { dsLcd.println(2, "WARNING: NO VISION"); } } /** * Runs through once at the start of teleop */ public void teleopInit() { visionServer.stopSamplingCounts(); alliance = DriverStation.getInstance().getAlliance(); if (alliance.equals(DriverStation.Alliance.kBlue)) { underglowController.set(BLUE_UNDERGLOW); } else { underglowController.set(RED_UNDERGLOW); } pidDrive.cancel(); shooter.setForkAngle(RobotConstants.Positions.START); dsLcd.clear(); restartEncoders(); compressor.start(); shooter.closeClaw(); } /** * This function is called periodically during operator control, just like * teleopPeriodic in the IterativeRobot base class. * We use teleopThreadsafe instead to ensure safety with our separate * autonomous thread. DO NOT create a teleopPeriodic in this class or any * subclasses! Use teleopThreadsafe instead, only! */ public void teleopThreadsafe() { //semi-arcade drive //leftDrive.set(joystick.getY() + joystick.getX()); //rightDrive.set(joystick.getY() - joystick.getX()); //trigger piston mechanism if (gamepad.getRightBumper()) { shooter.fire(); } //shoulder motor (fork) control if (gamepad.getDpadVertical() > 0.0) { shooter.setForkAngle(RobotConstants.Positions.START); } if (gamepad.getDpadHorizontal() == -1.0) { shooter.setForkAngle(RobotConstants.Positions.SHOOTING); } if (gamepad.getDpadHorizontal() == 1.0) { shooter.setForkAngle(RobotConstants.Positions.LOWGOAL); } if (gamepad.getButton(LogitechDualAction.SELECT)) { shooter.setForkAngle(RobotConstants.Positions.TRUSS); } if (gamepad.getDpadVertical() < 0.0) { shooter.setForkAngle(RobotConstants.Positions.INTAKE); } //roller up/down if (gamepad.getButton(2)) { shooter.closeClaw(); } if (gamepad.getButton(1)) { shooter.openClaw(); } if (gamepad.getLeftBumper()) { shooter.setRoller(RobotConstants.Shooter.ROLLER_SPEED); } if (gamepad.getRightTrigger()) { shooter.setRoller(-RobotConstants.Shooter.ROLLER_SPEED); } if (!(gamepad.getLeftBumper() || gamepad.getRightTrigger())) { shooter.setRoller(0.0f); } // GAMEPAD2 for claw control using 2015 Driver Station if (gamepad2.getButton(1)) { shooter.setForkAngle(RobotConstants.Positions.INTAKE); } else if (gamepad2.getButton(2)) { shooter.setForkAngle(RobotConstants.Positions.LOWGOAL); } else if (gamepad2.getButton(3)) { shooter.setForkAngle(RobotConstants.Positions.SHOOTING); } else if (gamepad2.getButton(4)) { shooter.setForkAngle(RobotConstants.Positions.START); } } /** * Called once when the robot enters the disabled state */ public void disabledInit() { pidDrive.cancel(); leftEncoder.stop(); rightEncoder.stop(); leftEncoder.reset(); rightEncoder.reset(); leftDrive.disable(); rightDrive.disable(); shooter.disableAll(); shooter.setForkAngle(RobotConstants.Positions.START); shooter.closeClaw(); compressor.stop(); visionServer.stopSamplingCounts(); } /** * Called periodically while the robot is in the disabled state */ public void disabledPeriodic() { leftDrive.disable(); rightDrive.disable(); shooter.disableAll(); dsLcd.println(5, "VOLT: " + shooter.getPotVoltage()); } /** * Called once when the robot enters test mode */ public void testInit() { } /** * This function is called periodically during test mode */ public void testPeriodic() { leftDrive.disable(); rightDrive.disable(); shooter.disableAll(); } }
package ch.ntb.inf.deep.lowLevel; public class LL { /** get bits of floating point value */ public static long doubleToBits(double d) { return 0; } /** set double from bits */ public static double bitsToDouble(long val) { return 0; } public void imDelegI1Mm(){ } public void imDelegIiMm(){ } }
package com.lenddo.javaapi; public class LenddoConfig { public static final String api_version = "2.9.0"; public static final String score_base_url = "https://scoreservice.lenddo.com"; public static final String whitelabel_base_url = "https://networkservice.lenddo.com"; public static final String onboarding_base_url = "https://authorize.lenddo.com"; public static final String authorize_base_url = "https://authorize-api.partner-service.link"; public static final String applications_base_url = "https://frodo.partner-service.link"; public static final String ENDPOINT_SCORE_APPLICATIONSCORECARDS = "/ApplicationScorecards/"; public static final String ENDPOINT_SCORE_APPLICATIONSCORE = "/ApplicationScore/"; public static final String ENDPOINT_SCORE_APPLICATIONVERIFICATION = "/ApplicationVerification/"; public static final String ENDPOINT_SCORE_APPLICATIONFEATURES = "/ApplicationFeatures/"; public static final String ENDPOINT_SCORE_APPLICATIONMULTIPLESCORES = "/ApplicationMultipleScores/"; public static final String ENDPOINT_WL_PARTNERTOKEN = "/PartnerToken"; public static final String ENDPOINT_WL_COMMITPARTNERJOB = "/CommitPartnerJob"; public static final String ENDPOINT_NETWORK_SENDEXTRADATA = "/ExtraApplicationData"; public static final String ENDPOINT_NETWORK_MOBILEDATA = "/MobileData"; public static final String ENDPOINT_AUTHORIZE_HEALTHCHECK = "/healthcheck"; public static final String ENDPOINT_AUTHORIZE_ONBOARDING_PRIORITYDATA = "/onboarding/prioritydata"; public static final String ENDPOINT_APPLICATIONS = "/applications"; private static boolean isDebugMode = false; public static boolean isDebugMode() { return isDebugMode; } public static void setDebugMode(boolean debugMode) { isDebugMode = debugMode; } }
package com.knox.tree; import com.knox.Asserts; import com.knox.tree.printer.BinaryTreeInfo; import com.knox.tree.printer.BinaryTrees; import java.util.Comparator; import java.util.LinkedList; import java.util.Queue; public class BinarySearchTree<T> implements BinaryTreeInfo { public static abstract class Visitor<T> { boolean stop; // @return true, abstract boolean visit(T element); } private TreeNode<T> root; private int size; private Comparator<T> comparator; public BinarySearchTree(Comparator<T> comparator) { this.comparator = comparator; } public BinarySearchTree() { this(null); } public int size() { return size; } public boolean isEmpty() { return size == 0; } public void add(T element) { elementNotNullCheck(element); if (root == null) { root = new TreeNode<T>(element, null); size++; return; } TreeNode<T> cur = root; TreeNode<T> parent = root; int cmp = 0; while (cur != null) { parent = cur; cmp = compare(element, cur.value); if (cmp < 0) { cur = cur.left; } else if (cmp > 0) { cur = cur.right; } else { cur.value = element; return; } } TreeNode<T> newNode = new TreeNode(element, parent); if (cmp < 0) { parent.left = newNode; } else { parent.right = newNode; } size++; } public void remove(T element) { TreeNode<T> node = node(element); remove(node); } private void remove_v1(TreeNode<T> node) { if (node == null) return; size // MECE if (node.hasTwoChildren()) { TreeNode<T> s = successor(node); node.value = s.value; node = s; } if (node.isLeaf()) { if (node.parent == null) { root = null; } else if (node == node.parent.left) { node.parent.left = null; } else { // node == node.parent.right node.parent.right = null; } } else { TreeNode<T> repacement = node.left != null ? node.left : node.right; repacement.parent = node.parent; if (node.parent == null) { // node root = repacement; } else if (node == node.parent.left) { node.parent.left = repacement; } else { node.parent.right = repacement; } } } private void remove(TreeNode<T> node) { if (node == null) return; size if (node.hasTwoChildren()) { TreeNode<T> s = successor(node); node.value = s.value; node = s; } // 01, 0, replacement == null, TreeNode<T> replacement = node.left != null ? node.left : node.right; if (replacement != null) { replacement.parent = node.parent; } if (node.parent == null) { root = replacement; } else { if (node == node.parent.left) { node.parent.left = replacement; } else { // node == node.parent.right node.parent.right = replacement; } } } public boolean contains(T element) { return node(element) != null; } public void clear() { root = null; size = 0; } private TreeNode<T> node(T element) { TreeNode<T> node = root; while (node != null) { int cmp = compare(element, node.value); if (cmp == 0) { return node; } else if (cmp < 0) { node = node.left; } else { node = node.right; } } return null; } private TreeNode<T> predecessor(TreeNode<T> node) { if (node == null) return null; // left.right.right.right.... if (node.left != null) { TreeNode<T> p = node.left; while (p.right != null) { p = p.right; } return p; } /* * * * parent, node == node.parent.left, * 1. node == node.parent.right, node.parent * 2. , node.parent == null, * */ while (node.parent != null && node == node.parent.left) { node = node.parent; } return node.parent; } private TreeNode<T> successor(TreeNode<T> node) { if (node == null) return null; if (node.right != null) { TreeNode<T> p = node.right; while (p.left != null) { p = p.left; } return p; } // , node, while (node.parent != null && node == node.parent.right) { node = node.parent; } return node.parent; } public int height() { // return height_v1(root); return height_v2(); } /* * * * : * , height1 * 1. levelSize * 2. , , 1 * 3. , levelSize1, * 4. levelSize == 0, , queue.size(), height1 * * */ private int height_v2() { if (root == null) return 0; Queue<TreeNode<T>> queue = new LinkedList<>(); queue.offer(root); int levelSize = 1; int height = 0; while (!queue.isEmpty()) { TreeNode<T> node = queue.poll(); levelSize if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } if (levelSize == 0) { levelSize = queue.size(); height++; } } return height; } /* * * * 1. * 2. * 3. +1 * */ private int height_v1(TreeNode<T> node) { if (node == null) return 0; int leftHeight = height_v1(node.left); int rightHeight = height_v1(node.right); return Math.max(leftHeight, rightHeight) + 1; } public boolean isComplete() { if (root == null) return true; Queue<TreeNode<T>> queue = new LinkedList<>(); queue.offer(root); boolean leaf = false; while (!queue.isEmpty()) { TreeNode<T> node = queue.poll(); if (leaf && !node.isLeaf()) return false; if (node.left != null) { queue.offer(node.left); } else if (node.right != null) { // node.left == null && node.right != null return false; } if (node.right != null) { queue.offer(node.right); } else { // node.right == null , leaf = true; } } return true; } private void elementNotNullCheck(T element) { if (element == null) { throw new NullPointerException("element should not be null"); } } private int compare(T lhs, T rhs) { if (comparator != null) { return comparator.compare(lhs, rhs); } else { return ((Comparable<T>)lhs).compareTo(rhs); } } public void preorder(Visitor<T> visitor) { if (visitor == null) return; preorder(root, visitor); } private void preorder(TreeNode<T> root, Visitor<T> visitor) { if (root == null || visitor.stop) return; visitor.stop = visitor.visit(root.value); preorder(root.left, visitor); preorder(root.right, visitor); } public void inorder(Visitor<T> visitor) { if (visitor == null) return; inorder(root, visitor); } private void inorder(TreeNode<T> root, Visitor<T> visitor) { if (root == null || visitor.stop) return; inorder(root.left, visitor); if (visitor.stop) return; visitor.stop = visitor.visit(root.value); inorder(root.right, visitor); } public void postorder(Visitor<T> visitor) { if (visitor == null) return; postorder(root, visitor); } private void postorder(TreeNode<T> root, Visitor<T> visitor) { if (root == null || visitor.stop) return; postorder(root.left, visitor); postorder(root.right, visitor); if (visitor.stop) return; visitor.stop = visitor.visit(root.value); } public void levelOrder(Visitor<T> visitor) { if (root == null || visitor == null) return; Queue<TreeNode<T>> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { TreeNode<T> node = queue.poll(); if (visitor.visit(node.value)) return; if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } } } @Override public Object root() { return root; } @Override public Object left(Object node) { return ((TreeNode<T>)node).left; } @Override public Object right(Object node) { return ((TreeNode<T>)node).right; } @Override public Object string(Object node) { TreeNode<T> treeNode = ((TreeNode<T>)node); String parentStr = treeNode.parent == null ? "null" : treeNode.parent.value.toString(); return treeNode.value.toString() + "_p(" + parentStr + ")"; } public static void main(String[] args) { // BinarySearchTree<Integer> bst = createTree(); // BinaryTrees.print(bst); // test_preoder(bst); // test_inoder(bst); // test_postoder(bst); // test_isComplete(); // test_height(); // test_predecessor(); // test_levelOrder(); test_remove(); } private static void test_remove() { Integer[] arr = new Integer[] { 8, 4, 13, 2, 6, 10, 1, 3, 5, 7, 9, 12, 11 }; BinarySearchTree<Integer> bst = createTree(arr); BinaryTrees.print(bst); // bst.remove(11); // 1 // bst.remove(10); // 2 bst.remove(8); BinaryTrees.print(bst); } private static void test_predecessor() { Integer[] arr = new Integer[] { 8, 4, 13, 2, 6, 10, 1, 3, 5, 7, 9, 12, 11 }; BinarySearchTree<Integer> bst = createTree(arr); BinaryTrees.print(bst); { // node.left != null TreeNode<Integer> node = bst.root.left; TreeNode<Integer> target = node.left.right; TreeNode<Integer> ret = bst.predecessor(node); Asserts.testEqual(ret, target); } { // node.left == null && node,parent != null TreeNode<Integer> node = bst.root.right.left.left; TreeNode<Integer> target = bst.root; TreeNode<Integer> ret = bst.predecessor(node); Asserts.testEqual(ret, target); node = bst.root.left.left.left; target = null; ret = bst.predecessor(node); Asserts.testEqual(ret, target); } { arr = new Integer[] { 8, 13, 10, 9, 12, 11 }; bst = createTree(arr); BinaryTrees.print(bst); // node.left == null && node,parent == null, TreeNode<Integer> node = bst.root; TreeNode<Integer> ret = bst.predecessor(node); TreeNode<Integer> target = null; Asserts.testEqual(ret, target); } } private static void test_height() { BinarySearchTree<Integer> bst = randomCreateTree(10); BinaryTrees.print(bst); System.out.println("height = " + bst.height()); } private static void test_isComplete() { { Integer[] arr = new Integer[] { 7, 4, 9 }; BinarySearchTree<Integer> bst = createTree(arr); Asserts.testTrue(bst.isComplete()); } { Integer[] arr = new Integer[] { 7, 4, 9, 2 }; BinarySearchTree<Integer> bst = createTree(arr); Asserts.testTrue(bst.isComplete()); } { Integer[] arr = new Integer[] { 7, 4, 9, 8 }; BinarySearchTree<Integer> bst = createTree(arr); Asserts.testFalse(bst.isComplete()); } } private static void test_preoder(BinarySearchTree<Integer> bst) { LinkedList<Integer> ret = new LinkedList<>(); bst.preorder(new Visitor<Integer>() { @Override public boolean visit(Integer element) { ret.add(element); return element == 4; } }); System.out.println("preorder : " + ret.toString()); } private static void test_inoder(BinarySearchTree<Integer> bst) { LinkedList<Integer> ret = new LinkedList<>(); bst.inorder(new Visitor<Integer>() { @Override public boolean visit(Integer element) { ret.add(element); return false; } }); System.out.println("inorder : " + ret.toString()); } private static void test_postoder(BinarySearchTree<Integer> bst) { LinkedList<Integer> ret = new LinkedList<>(); bst.postorder(new Visitor<Integer>() { @Override public boolean visit(Integer element) { ret.add(element); return element == 4; } }); System.out.println("postorder : " + ret.toString()); } private static void test_levelOrder() { BinarySearchTree<Integer> bst = createTree(); BinaryTrees.print(bst); LinkedList<Integer> ret = new LinkedList<>(); bst.levelOrder(new Visitor<Integer>() { @Override public boolean visit(Integer element) { ret.add(element); return element == 5; } }); System.out.println("levelOrder : " + ret.toString()); } private static void test1() { BinarySearchTree<Integer> bst = new BinarySearchTree<>(new Comparator<Integer>() { // , javaComparator, @Override public int compare(Integer o1, Integer o2) { return o1.intValue() - o2.intValue(); } }); for (int i = 0; i < 10; i++) { int value = (int)(Math.random() * 100); bst.add(value); } BinaryTrees.print(bst); } private static BinarySearchTree<Integer> createTree() { BinarySearchTree<Integer> bst = new BinarySearchTree<>(); int[] arr = new int[] { 7, 4, 9, 2, 5, 8, 11, 1, 3, 10, 12 }; for (int i = 0; i < arr.length; i++) { bst.add(arr[i]); } return bst; } private static BinarySearchTree<Integer> createTree(Integer[] arr) { BinarySearchTree<Integer> bst = new BinarySearchTree<>(); for (int i = 0; i < arr.length; i++) { bst.add(arr[i]); } return bst; } private static BinarySearchTree<Integer> randomCreateTree(int size) { Integer[] arr = new Integer[size]; for (int i = 0; i < size; i++) { arr[i] = (int)(Math.random() * 100); } return createTree(arr); } }
package Ordered_Jobs.solution1; import org.jetbrains.annotations.NotNull; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.TreeSet; import static org.testng.AssertJUnit.assertEquals; public class OrderedJobsTest { private OrderedJobs jobs; @Before public void setUp() throws Exception { jobs = new OrderedJobsImpl(); } @Test public void givenNull_sortReturnsEmptyString() throws Exception { assertEquals("", jobs.sort()); } @Test public void givenRegisterA_sortReturnsA() throws Exception { jobs.register('A'); assertEquals("A", jobs.sort()); } @Test public void givenMultipleRegistrationsOfA_sortReturnsA() throws Exception { jobs.register('A'); jobs.register('A'); jobs.register('A'); assertEquals("A", jobs.sort()); } @Test public void givenRegisterBDependentOnA_sortReturnsAB() throws Exception { jobs.register('B', 'A'); assertEquals("AB", jobs.sort()); } @Test public void givenRegisterBDependentOnAAndCAndD_sortReturnsACDB() throws Exception { jobs.register('B', 'A'); jobs.register('B', 'C'); jobs.register('B', 'D'); assertEquals("ACDB", jobs.sort()); } @Test public void integrationABC() throws Exception { jobs.register('C'); jobs.register('B', 'A'); jobs.register('C', 'B'); assertEquals("ABC", jobs.sort()); } private class OrderedJobsImpl implements OrderedJobs { final TreeSet<Job> jobs = new TreeSet<>(); @Override public void register(char dependentJob, char independentJob) { addDependency(registerJob(dependentJob), independentJob); } private void addDependency(Job dependentJob, char independentJobID) { Job dependency = registerJob(independentJobID); dependentJob.addDependency(dependency); } private Job getJob(char jobID) { for (Job element : jobs) { if (element.jobID == jobID) return element; } return null; } @Override public void register(char jobID) { registerJob(jobID); } private Job registerJob(char jobID) { Job job = new Job(jobID); if (!isRegistered(jobID) && jobs.add(job)) return job; else return this.getJob(jobID); } private boolean isRegistered(char jobID) { for (Job next : jobs) { if (next.jobID == jobID) return true; } return false; } @Override public String sort() { return jobsToString(); } @NotNull private String jobsToString() { String out = ""; for (Job job : jobs) { out += job.jobID; } return out; } private class Job implements Comparable { private final ArrayList<Job> dependencies = new ArrayList<>(); private final char jobID; private Job(char jobID) { this.jobID = jobID; } private void addDependency(Job dependency) { this.dependencies.add(dependency); } @Override public int compareTo(@NotNull Object o) { if (((Job) o).jobID == this.jobID) return 0; int out = (this.jobID + getDependencyValue()) - (((Job) o).jobID + ((Job) o).getDependencyValue()); if (out == 0) out = -1; return out; } private int getDependencyValue() { int out = 0; for (Job dependency : dependencies) { if (dependency.dependencies.isEmpty()) return jobID; out += dependency.getDependencyValue(); } return out; } } } }
package org.pillowsky.securehttp; import java.nio.file.Paths; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class Guard { private SecretKey desKey; private PublicKey rsaPublicKey; private PrivateKey rsaPrivateKey; private Cipher desEnCipher; private Cipher desDeCipher; private Signature rsaSigner; private Signature rsaVerifier; public Guard(String desKeyfile, String privateKeyfile, String publicKeyfile) throws Exception { try { desKey = new SecretKeySpec(Files.readAllBytes(Paths.get(desKeyfile)), "DES"); System.out.format("Load des key from %s%n", desKeyfile); } catch (NoSuchFileException e) { desKey = KeyGenerator.getInstance("DES").generateKey(); Files.write(Paths.get(desKeyfile), desKey.getEncoded()); System.out.format("Create and save des key to %s%n", desKeyfile); } try { KeyFactory factory = KeyFactory.getInstance("RSA"); rsaPrivateKey = factory.generatePrivate(new PKCS8EncodedKeySpec(Files.readAllBytes(Paths.get(privateKeyfile)))); rsaPublicKey = factory.generatePublic(new X509EncodedKeySpec(Files.readAllBytes(Paths.get(publicKeyfile)))); System.out.format("Load rsa private key from %s%n", privateKeyfile); System.out.format("Load rsa public key from %s%n", publicKeyfile); } catch (NoSuchFileException e) { KeyPair pair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); rsaPrivateKey = pair.getPrivate(); rsaPublicKey = pair.getPublic(); Files.write(Paths.get(privateKeyfile), new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded()).getEncoded()); Files.write(Paths.get(publicKeyfile), new X509EncodedKeySpec(rsaPublicKey.getEncoded()).getEncoded()); System.out.format("Create and save rsa private key to %s%n", privateKeyfile); System.out.format("Create and save rsa public key to %s%n", publicKeyfile); System.out.println("Distribute rsa keyfile and run again."); System.exit(1); } desEnCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); desEnCipher.init(Cipher.ENCRYPT_MODE, desKey); desDeCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); desDeCipher.init(Cipher.DECRYPT_MODE, desKey); rsaSigner = Signature.getInstance("SHA1withRSA"); rsaSigner.initSign(rsaPrivateKey); rsaVerifier = Signature.getInstance("SHA1withRSA"); rsaVerifier.initVerify(rsaPublicKey); } public byte[] desEncrypt(byte[] plaintext) throws Exception { return desEnCipher.doFinal(plaintext); } public byte[] desDecrypt(byte[] ciphertext) throws Exception { return desDeCipher.doFinal(ciphertext); } public byte[] rsaSign(byte[] data) throws Exception { rsaSigner.update(data); return rsaSigner.sign(); } public boolean rsaVerify(byte[] data, byte[] sign) throws Exception { rsaVerifier.update(data); return rsaVerifier.verify(sign); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.colar.netbeans.fan.wizard; import java.awt.Component; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.openide.WizardDescriptor; import org.openide.util.HelpCtx; /** * Panel for new Fan file wizard * @author thibautc */ public class FanPodWizardPanel1 implements WizardDescriptor.Panel { /** * The visual component that displays this panel. If you need to access the * component from this class, just use getComponent(). */ private Component component; private final String dir; FanPodWizardPanel1(String folder) { super(); this.dir = folder; } // Get the visual component for the panel. In this template, the component // is kept separate. This can be more efficient: if the wizard is created // but never displayed, or not all panels are displayed, it is better to // create only those which really need to be visible. public Component getComponent() { if (component == null) { component = new FanPodPanel1(this, dir); } return component; } public HelpCtx getHelp() { // Show no Help button for this panel: return HelpCtx.DEFAULT_HELP; // If you have context help: // return new HelpCtx(SampleWizardPanel1.class); } public boolean isValid() { if (component == null) { return false; } return ((FanPodPanel1) component).isValid(); } private final Set<ChangeListener> listeners = new HashSet<ChangeListener>(1); // or can use ChangeSupport in NB 6.0 public final void addChangeListener(ChangeListener l) { synchronized (listeners) { listeners.add(l); } } public final void removeChangeListener(ChangeListener l) { synchronized (listeners) { listeners.remove(l); } } protected final void fireChangeEvent() { Iterator<ChangeListener> it; synchronized (listeners) { it = new HashSet<ChangeListener>(listeners).iterator(); } ChangeEvent ev = new ChangeEvent(this); while (it.hasNext()) { it.next().stateChanged(ev); } } // You can use a settings object to keep track of state. Normally the // settings object will be the WizardDescriptor, so you can use // WizardDescriptor.getProperty & putProperty to store information entered // by the user. public void readSettings(Object settings) { } public void storeSettings(Object settings) { } private FanPodPanel1 getPanel() { return (FanPodPanel1) getComponent(); } public String getPodName() { return getPanel().getPodName(); } public String getProjectFolder() { return getPanel().getProjectFolder(); } public String getPodDesc() { return getPanel().getPodDesc(); } public String getPodVersion() { return getPanel().getPodVersion(); } public boolean getCreateBuildFile() { return getPanel().getCreateBuildFile(); } public String getMainClassName() { return getPanel().getMainClassName(); } public String getDependencies() { return getPanel().getDependencies(); } public String getIndex() { return getPanel().getIndex(); } public String getMeta() { return getPanel().getMeta(); } public String getOutDir() { return getPanel().getOutputDirectory(); } public boolean getDocApi() { return getPanel().getDocApi(); } public boolean getDocSrc() { return getPanel().getDocSrc(); } public String getSourceDirs() { return getPanel().getSourceDirs(); } public String getResourceDirs() { return getPanel().getResourceDirs(); } }
package net.devrieze.chatterbox.server; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import javax.jdo.JDOHelper; import javax.jdo.JDOObjectNotFoundException; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.users.UserServiceFactory; public class ChatterboxServlet extends HttpServlet { private static final long serialVersionUID = 3717262307787043062L; private static PersistenceManagerFactory _pmf = null; public static PersistenceManagerFactory getPMF() { if (_pmf != null) return _pmf; synchronized(ChatterboxServlet.class) { if (_pmf != null) return _pmf; _pmf = JDOHelper.getPersistenceManagerFactory("transactions-optional"); } return _pmf; } private ChannelManager channelManager = new ChannelManager(); private static enum Method { GET, POST, DELETE, PUT; } private static enum Target { LOGOUT("/logout") { public boolean handle(ChatterboxServlet servlet, Method method, HttpServletRequest req, HttpServletResponse resp) throws IOException { if (method == Method.GET) { return servlet.handleLogout(req, resp); } return false; } }, CONNECT("/connect") { public boolean handle(ChatterboxServlet servlet, Method method, HttpServletRequest req, HttpServletResponse resp) throws IOException { if (method == Method.POST) { return servlet.handleConnect(req, resp); } return false; } }, MESSAGES("/messages"){ public boolean handle(ChatterboxServlet servlet, Method method, HttpServletRequest req, HttpServletResponse resp) throws IOException { switch (method) { case GET: return servlet.handleMessages(req, resp); case POST: return servlet.handleMessage(req, resp); case DELETE: return servlet.handleClear(req, resp); } return false; } }, BOXES("/boxes"){ public boolean handle(ChatterboxServlet servlet, Method method, HttpServletRequest req, HttpServletResponse resp) throws IOException { if (method == Method.GET) { return servlet.handleBoxes(req, resp); } return false; } }, DEFAULT("/"){ public boolean isTargetted(String target) { return target.endsWith(".html")|| "/".equals(target); } @Override public boolean handle(ChatterboxServlet servlet, Method method, HttpServletRequest req, HttpServletResponse resp) throws IOException { if (method == Method.GET) { return servlet.handleFile(req, resp); } return false; } } ; private String prefix; Target(String prefix) { this.prefix = prefix; } public abstract boolean handle(ChatterboxServlet servlet, Method method, HttpServletRequest req, HttpServletResponse resp) throws IOException; public boolean isTargetted(String myPath) { return prefix.equals(myPath); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Target t = getTarget(req); if (t==null || (! t.handle(this, Method.GET, req, resp))) { super.doGet(req, resp); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Target t = getTarget(req); if (t==null || (! t.handle(this, Method.POST, req, resp))) { super.doPost(req, resp); } } @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Target t = getTarget(req); if (t==null || (! t.handle(this, Method.DELETE, req, resp))) { super.doDelete(req, resp); } } @Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Target t = getTarget(req); if (t==null || (! t.handle(this, Method.PUT, req, resp))) { super.doPut(req, resp); } } private Box getDefaultBox(PersistenceManager pm) { try { return pm.getObjectById(Box.class, "defaultBox"); } catch (JDOObjectNotFoundException e) { return pm.makePersistent(new Box("defaultBox")); } } private boolean handleMessage(HttpServletRequest req, HttpServletResponse resp) throws IOException { int contentLength = req.getContentLength(); if (contentLength > 10240) { resp.setContentType("text/html"); resp.getWriter().println("<html><head><title>Error, too long</title></head><body><p>Message of length "+ contentLength+" is longer than 10 kilobytes.</p></body></html>"); resp.setStatus(414); return true; } resp.setContentType("text/xml"); BufferedReader in = req.getReader(); // Assume most text will be ascii and as such contentlength == string length char[] buffer = new char[contentLength]; StringBuilder message = new StringBuilder(contentLength); { int read = in.read(buffer); while (read >=0) { message.append(buffer,0,read); read = in.read(buffer); } } Message m = channelManager.sendMessageToChannels(Util.sanitizeHtml(message.toString())); resp.getWriter().append(m.toXML()); resp.setStatus(HttpServletResponse.SC_OK); return true; } protected boolean handleLogout(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.sendRedirect(UserServiceFactory.getUserService().createLogoutURL("/")); return true; } private boolean handleFile(HttpServletRequest req, HttpServletResponse resp) throws IOException { // System.err.println("handlefile called for path "+req.getPathTranslated()); String path = req.getPathTranslated(); if (path==null) { path = req.getRequestURI(); } else if (! path.startsWith("/")) { return false; } path = path.substring(1); if (path.length()==0) { path = "Chatterbox.html"; } if (path.contains("..")) { return false; } FileReader in = new FileReader(path); char[] buffer = new char[10000]; StringBuilder result = new StringBuilder(); int c = in.read(buffer); while (c>=0) { result.append(buffer,0,c); c = in.read(buffer); } resp.getWriter().append(result); resp.setStatus(HttpServletResponse.SC_OK); return true; } private boolean handleMessages(HttpServletRequest req, HttpServletResponse resp) throws IOException { PrintWriter out = resp.getWriter(); resp.setContentType("text/xml"); out.println("<?xml version=\"1.0\"?>"); out.println("<messages>"); PersistenceManager pm = getPMF().getPersistenceManager(); try { Box b = getDefaultBox(pm); long start = b.getFirstMessageIndex(); long end = b.getLastMessageIndex(); { String startAttr = req.getParameter("start"); if("last".equalsIgnoreCase(startAttr)) { start=end; } else { try { if (startAttr!=null) { start = Math.max(start, Long.parseLong(startAttr)); } } catch (NumberFormatException e) { /* Just ignore */ } } } { String endAttr = req.getParameter("end"); if ("first".equalsIgnoreCase(endAttr)) { end=b.getFirstMessageIndex(); } else { try { if (endAttr!=null) { end = Math.min(end, Long.parseLong(endAttr)); } } catch (NumberFormatException e) { /* Just ignore */ } } } for (Message m:b.getMessages(start, end)) { out.println(m.toXML()); } } finally { pm.close(); out.println("</messages>"); } resp.setStatus(HttpServletResponse.SC_OK); return true; } private boolean handleBoxes(HttpServletRequest req, HttpServletResponse resp) throws IOException { PrintWriter out = resp.getWriter(); resp.setContentType("text/xml"); out.println("<?xml version=\"1.0\"?>"); out.println("<boxes>"); out.println(" <box default=\"true\">main</box>"); out.println("</boxes>"); resp.setStatus(HttpServletResponse.SC_OK); return true; } private boolean handleClear(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (! UserServiceFactory.getUserService().isUserAdmin()) { resp.setStatus(HttpServletResponse.SC_FORBIDDEN); return true; } PersistenceManager pm = getPMF().getPersistenceManager(); try { Box b = getDefaultBox(pm); b.clear(); } finally { pm.close(); } PrintWriter out = resp.getWriter(); resp.setContentType("text/xml"); out.println("<?xml version=\"1.0\"?>"); out.println("<messages>"); out.println("</messages>"); resp.setStatus(HttpServletResponse.SC_OK); return true; } private boolean handleConnect(HttpServletRequest req, HttpServletResponse resp) throws IOException { String response = channelManager.createChannel(); resp.getWriter().append(response); resp.setContentType("text/xml"); resp.setStatus(HttpServletResponse.SC_OK); return true; } private Target getTarget(HttpServletRequest req) { String myPath = req.getPathInfo(); if (myPath==null) { myPath=req.getRequestURI(); } for (Target t:Target.values()) { if(t.isTargetted(myPath)) { return t; } } return null; } }
//FILE: MMStudioMainFrame.java //PROJECT: Micro-Manager //SUBSYSTEM: mmstudio // Modifications by Arthur Edelstein, Nico Stuurman, Henry Pinkard // This file is distributed in the hope that it will be useful, // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. //CVS: $Id$ package org.micromanager; import ij.IJ; import ij.ImageJ; import ij.ImagePlus; import ij.WindowManager; import ij.gui.Line; import ij.gui.Roi; import ij.process.ImageProcessor; import ij.process.ShortProcessor; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.Point2D; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.prefs.Preferences; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComboBox; 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.JTextField; import javax.swing.JToggleButton; import javax.swing.SpringLayout; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import javax.swing.UIManager; import javax.swing.event.AncestorEvent; import mmcorej.CMMCore; import mmcorej.DeviceType; import mmcorej.MMCoreJ; import mmcorej.MMEventCallback; import mmcorej.StrVector; import org.json.JSONObject; import org.micromanager.acquisition.AcquisitionManager; import org.micromanager.api.AcquisitionEngine; import org.micromanager.api.Autofocus; import org.micromanager.api.MMPlugin; import org.micromanager.api.ScriptInterface; import org.micromanager.api.MMListenerInterface; import org.micromanager.conf2.ConfiguratorDlg2; import org.micromanager.conf2.MMConfigFileException; import org.micromanager.conf2.MicroscopeModel; import org.micromanager.graph.GraphData; import org.micromanager.graph.GraphFrame; import org.micromanager.navigation.CenterAndDragListener; import org.micromanager.navigation.PositionList; import org.micromanager.navigation.XYZKeyListener; import org.micromanager.navigation.ZWheelListener; import org.micromanager.utils.AutofocusManager; import org.micromanager.utils.ContrastSettings; import org.micromanager.utils.GUIColors; import org.micromanager.utils.GUIUtils; import org.micromanager.utils.JavaUtils; import org.micromanager.utils.MMException; import org.micromanager.utils.MMScriptException; import org.micromanager.utils.NumberUtils; import org.micromanager.utils.TextUtils; import org.micromanager.utils.TooltipTextMaker; import org.micromanager.utils.WaitDialog; import bsh.EvalError; import bsh.Interpreter; import com.swtdesigner.SwingResourceManager; import ij.Menus; import ij.gui.ImageCanvas; import ij.gui.ImageWindow; import ij.gui.Toolbar; import java.awt.Cursor; import java.awt.Frame; import java.awt.KeyboardFocusManager; import java.awt.Menu; import java.awt.MenuItem; import java.awt.dnd.DropTarget; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Collections; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.JSplitPane; import javax.swing.event.AncestorListener; import mmcorej.TaggedImage; import org.json.JSONException; import org.micromanager.acquisition.AcquisitionWrapperEngine; import org.micromanager.acquisition.LiveModeTimer; import org.micromanager.acquisition.MMAcquisition; import org.micromanager.api.ImageCache; import org.micromanager.acquisition.MetadataPanel; import org.micromanager.acquisition.ProcessorStack; import org.micromanager.acquisition.TaggedImageQueue; import org.micromanager.acquisition.TaggedImageStorageDiskDefault; import org.micromanager.acquisition.TaggedImageStorageMultipageTiff; import org.micromanager.acquisition.VirtualAcquisitionDisplay; import org.micromanager.api.DeviceControlGUI; import org.micromanager.api.IAcquisitionEngine2010; import org.micromanager.graph.HistogramSettings; import org.micromanager.utils.DragDropUtil; import org.micromanager.utils.FileDialogs; import org.micromanager.utils.FileDialogs.FileType; import org.micromanager.utils.HotKeysDialog; import org.micromanager.utils.ImageUtils; import org.micromanager.utils.MDUtils; import org.micromanager.utils.MMKeyDispatcher; import org.micromanager.utils.ReportingUtils; import org.micromanager.utils.UIMonitor; /* * Main panel and application class for the MMStudio. */ public class MMStudioMainFrame extends JFrame implements ScriptInterface, DeviceControlGUI { private static final String MICRO_MANAGER_TITLE = "Micro-Manager"; private static final long serialVersionUID = 3556500289598574541L; private static final String MAIN_FRAME_X = "x"; private static final String MAIN_FRAME_Y = "y"; private static final String MAIN_FRAME_WIDTH = "width"; private static final String MAIN_FRAME_HEIGHT = "height"; private static final String MAIN_FRAME_DIVIDER_POS = "divider_pos"; private static final String MAIN_EXPOSURE = "exposure"; private static final String MAIN_SAVE_METHOD = "saveMethod"; private static final String SYSTEM_CONFIG_FILE = "sysconfig_file"; private static final String OPEN_ACQ_DIR = "openDataDir"; private static final String SCRIPT_CORE_OBJECT = "mmc"; private static final String SCRIPT_ACQENG_OBJECT = "acq"; private static final String SCRIPT_GUI_OBJECT = "gui"; private static final String AUTOFOCUS_DEVICE = "autofocus_device"; private static final String MOUSE_MOVES_STAGE = "mouse_moves_stage"; private static final String EXPOSURE_SETTINGS_NODE = "MainExposureSettings"; private static final String CONTRAST_SETTINGS_NODE = "MainContrastSettings"; private static final int TOOLTIP_DISPLAY_DURATION_MILLISECONDS = 15000; private static final int TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS = 2000; // cfg file saving private static final String CFGFILE_ENTRY_BASE = "CFGFileEntry"; // + {0, 1, 2, 3, 4} // GUI components private JComboBox comboBinning_; private JComboBox shutterComboBox_; private JTextField textFieldExp_; private JLabel labelImageDimensions_; private JToggleButton toggleButtonLive_; private JButton toAlbumButton_; private JCheckBox autoShutterCheckBox_; private MMOptions options_; private boolean runsAsPlugin_; private JCheckBoxMenuItem centerAndDragMenuItem_; private JButton buttonSnap_; private JButton autofocusNowButton_; private JButton autofocusConfigureButton_; private JToggleButton toggleButtonShutter_; private GUIColors guiColors_; private GraphFrame profileWin_; private PropertyEditor propertyBrowser_; private CalibrationListDlg calibrationListDlg_; private AcqControlDlg acqControlWin_; private ReportProblemDialog reportProblemDialog_; private JMenu pluginMenu_; private ArrayList<PluginItem> plugins_; private List<MMListenerInterface> MMListeners_ = (List<MMListenerInterface>) Collections.synchronizedList(new ArrayList<MMListenerInterface>()); private List<Component> MMFrames_ = (List<Component>) Collections.synchronizedList(new ArrayList<Component>()); private AutofocusManager afMgr_; private final static String DEFAULT_CONFIG_FILE_NAME = "MMConfig_demo.cfg"; private ArrayList<String> MRUConfigFiles_; private static final int maxMRUCfgs_ = 5; private String sysConfigFile_; private String startupScriptFile_; private String sysStateFile_ = "MMSystemState.cfg"; private ConfigGroupPad configPad_; private LiveModeTimer liveModeTimer_; private GraphData lineProfileData_; // labels for standard devices private String cameraLabel_; private String zStageLabel_; private String shutterLabel_; private String xyStageLabel_; // applications settings private Preferences mainPrefs_; private Preferences systemPrefs_; private Preferences colorPrefs_; private Preferences exposurePrefs_; private Preferences contrastPrefs_; // MMcore private CMMCore core_; private AcquisitionEngine engine_; private PositionList posList_; private PositionListDlg posListDlg_; private String openAcqDirectory_ = ""; private boolean running_; private boolean configChanged_ = false; private StrVector shutters_ = null; private JButton saveConfigButton_; private ScriptPanel scriptPanel_; private org.micromanager.utils.HotKeys hotKeys_; private CenterAndDragListener centerAndDragListener_; private ZWheelListener zWheelListener_; private XYZKeyListener xyzKeyListener_; private AcquisitionManager acqMgr_; private static VirtualAcquisitionDisplay simpleDisplay_; private Color[] multiCameraColors_ = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.CYAN}; private int snapCount_ = -1; private boolean liveModeSuspended_; public Font defaultScriptFont_ = null; public static final String SIMPLE_ACQ = "Snap/Live Window"; public static FileType MM_CONFIG_FILE = new FileType("MM_CONFIG_FILE", "Micro-Manager Config File", "./MyScope.cfg", true, "cfg"); // Our instance private static MMStudioMainFrame gui_; // Callback private CoreEventCallback cb_; // Lock invoked while shutting down private final Object shutdownLock_ = new Object(); private JMenuBar menuBar_; private ConfigPadButtonPanel configPadButtonPanel_; private final JMenu switchConfigurationMenu_; private final MetadataPanel metadataPanel_; public static FileType MM_DATA_SET = new FileType("MM_DATA_SET", "Micro-Manager Image Location", System.getProperty("user.home") + "/Untitled", false, (String[]) null); private Thread acquisitionEngine2010LoadingThread = null; private Class acquisitionEngine2010Class = null; private IAcquisitionEngine2010 acquisitionEngine2010 = null; private final JSplitPane splitPane_; private volatile boolean ignorePropertyChanges_; private JButton setRoiButton_; private JButton clearRoiButton_; private DropTarget dt_; public ImageWindow getImageWin() { return getSnapLiveWin(); } public ImageWindow getSnapLiveWin() { return simpleDisplay_.getHyperImage().getWindow(); } public static VirtualAcquisitionDisplay getSimpleDisplay() { return simpleDisplay_; } public static void createSimpleDisplay(String name, ImageCache cache) throws MMScriptException { simpleDisplay_ = new VirtualAcquisitionDisplay(cache, name); } public void checkSimpleAcquisition() { if (core_.getCameraDevice().length() == 0) { ReportingUtils.showError("No camera configured"); return; } int width = (int) core_.getImageWidth(); int height = (int) core_.getImageHeight(); int depth = (int) core_.getBytesPerPixel(); int bitDepth = (int) core_.getImageBitDepth(); int numCamChannels = (int) core_.getNumberOfCameraChannels(); try { if (acquisitionExists(SIMPLE_ACQ)) { if ((getAcquisitionImageWidth(SIMPLE_ACQ) != width) || (getAcquisitionImageHeight(SIMPLE_ACQ) != height) || (getAcquisitionImageByteDepth(SIMPLE_ACQ) != depth) || (getAcquisitionImageBitDepth(SIMPLE_ACQ) != bitDepth) || (getAcquisitionMultiCamNumChannels(SIMPLE_ACQ) != numCamChannels)) { //Need to close and reopen simple window closeAcquisitionWindow(SIMPLE_ACQ); } } if (!acquisitionExists(SIMPLE_ACQ)) { openAcquisition(SIMPLE_ACQ, "", 1, numCamChannels, 1, true); if (numCamChannels > 1) { for (long i = 0; i < numCamChannels; i++) { String chName = core_.getCameraChannelName(i); int defaultColor = multiCameraColors_[(int) i % multiCameraColors_.length].getRGB(); setChannelColor(SIMPLE_ACQ, (int) i, getChannelColor(chName, defaultColor)); setChannelName(SIMPLE_ACQ, (int) i, chName); } } initializeSimpleAcquisition(SIMPLE_ACQ, width, height, depth, bitDepth, numCamChannels); getAcquisition(SIMPLE_ACQ).promptToSave(false); getAcquisition(SIMPLE_ACQ).toFront(); this.updateCenterAndDragListener(); } } catch (Exception ex) { ReportingUtils.showError(ex); } } public void checkSimpleAcquisition(TaggedImage image) { try { JSONObject tags = image.tags; int width = MDUtils.getWidth(tags); int height = MDUtils.getHeight(tags); int depth = MDUtils.getDepth(tags); int bitDepth = MDUtils.getBitDepth(tags); int numCamChannels = (int) core_.getNumberOfCameraChannels(); if (acquisitionExists(SIMPLE_ACQ)) { if ((getAcquisitionImageWidth(SIMPLE_ACQ) != width) || (getAcquisitionImageHeight(SIMPLE_ACQ) != height) || (getAcquisitionImageByteDepth(SIMPLE_ACQ) != depth) || (getAcquisitionImageBitDepth(SIMPLE_ACQ) != bitDepth) || (getAcquisitionMultiCamNumChannels(SIMPLE_ACQ) != numCamChannels)) { //Need to close and reopen simple window closeAcquisitionWindow(SIMPLE_ACQ); // Seems that closeAcquisitionWindow also closes the acquisition... //closeAcquisition(SIMPLE_ACQ); } } if (!acquisitionExists(SIMPLE_ACQ)) { openAcquisition(SIMPLE_ACQ, "", 1, numCamChannels, 1, true); if (numCamChannels > 1) { for (long i = 0; i < numCamChannels; i++) { String chName = core_.getCameraChannelName(i); int defaultColor = multiCameraColors_[(int) i % multiCameraColors_.length].getRGB(); setChannelColor(SIMPLE_ACQ, (int) i, getChannelColor(chName, defaultColor)); setChannelName(SIMPLE_ACQ, (int) i, chName); } } initializeSimpleAcquisition(SIMPLE_ACQ, width, height, depth, bitDepth, numCamChannels); getAcquisition(SIMPLE_ACQ).promptToSave(false); getAcquisition(SIMPLE_ACQ).toFront(); this.updateCenterAndDragListener(); } } catch (Exception ex) { ReportingUtils.showError(ex); } } public void saveChannelColor(String chName, int rgb) { if (colorPrefs_ != null) { colorPrefs_.putInt("Color_" + chName, rgb); } } public Color getChannelColor(String chName, int defaultColor) { if (colorPrefs_ != null) { defaultColor = colorPrefs_.getInt("Color_" + chName, defaultColor); } return new Color(defaultColor); } public void enableRoiButtons(final boolean enabled) { SwingUtilities.invokeLater(new Runnable() { public void run() { setRoiButton_.setEnabled(enabled); clearRoiButton_.setEnabled(enabled); } }); } public void copyFromLiveModeToAlbum(VirtualAcquisitionDisplay display) throws MMScriptException, JSONException { ImageCache ic = display.getImageCache(); int channels = ic.getSummaryMetadata().getInt("Channels"); if (channels == 1) { //RGB or monchrome addToAlbum(ic.getImage(0, 0, 0, 0), ic.getDisplayAndComments()); } else { //multicamera for (int i = 0; i < channels; i++) { addToAlbum(ic.getImage(i, 0, 0, 0), ic.getDisplayAndComments()); } } } private void initializeHelpMenu() { // add help menu item final JMenu helpMenu = new JMenu(); helpMenu.setText("Help"); menuBar_.add(helpMenu); final JMenuItem usersGuideMenuItem = new JMenuItem(); usersGuideMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { ij.plugin.BrowserLauncher.openURL("http://valelab.ucsf.edu/~MM/MMwiki/index.php/Micro-Manager_User%27s_Guide"); } catch (IOException e1) { ReportingUtils.showError(e1); } } }); usersGuideMenuItem.setText("User's Guide"); helpMenu.add(usersGuideMenuItem); final JMenuItem configGuideMenuItem = new JMenuItem(); configGuideMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { ij.plugin.BrowserLauncher.openURL("http://valelab.ucsf.edu/~MM/MMwiki/index.php/Micro-Manager_Configuration_Guide"); } catch (IOException e1) { ReportingUtils.showError(e1); } } }); configGuideMenuItem.setText("Configuration Guide"); helpMenu.add(configGuideMenuItem); if (!systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false)) { final JMenuItem registerMenuItem = new JMenuItem(); registerMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { RegistrationDlg regDlg = new RegistrationDlg(systemPrefs_); regDlg.setVisible(true); } catch (Exception e1) { ReportingUtils.showError(e1); } } }); registerMenuItem.setText("Register your copy of Micro-Manager..."); helpMenu.add(registerMenuItem); } final MMStudioMainFrame thisFrame = this; final JMenuItem reportProblemMenuItem = new JMenuItem(); reportProblemMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (null == reportProblemDialog_) { reportProblemDialog_ = new ReportProblemDialog(core_, thisFrame, options_); thisFrame.addMMBackgroundListener(reportProblemDialog_); reportProblemDialog_.setBackground(guiColors_.background.get(options_.displayBackground_)); } reportProblemDialog_.setVisible(true); } }); reportProblemMenuItem.setText("Report Problem..."); helpMenu.add(reportProblemMenuItem); final JMenuItem aboutMenuItem = new JMenuItem(); aboutMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { MMAboutDlg dlg = new MMAboutDlg(); String versionInfo = "MM Studio version: " + MMVersion.VERSION_STRING; versionInfo += "\n" + core_.getVersionInfo(); versionInfo += "\n" + core_.getAPIVersionInfo(); versionInfo += "\nUser: " + core_.getUserId(); versionInfo += "\nHost: " + core_.getHostName(); dlg.setVersionInfo(versionInfo); dlg.setVisible(true); } }); aboutMenuItem.setText("About Micromanager"); helpMenu.add(aboutMenuItem); menuBar_.validate(); } private void updateSwitchConfigurationMenu() { switchConfigurationMenu_.removeAll(); for (final String configFile : MRUConfigFiles_) { if (! configFile.equals(sysConfigFile_)) { JMenuItem configMenuItem = new JMenuItem(); configMenuItem.setText(configFile); configMenuItem.addActionListener(new ActionListener() { String theConfigFile = configFile; public void actionPerformed(ActionEvent e) { sysConfigFile_ = theConfigFile; loadSystemConfiguration(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); } }); switchConfigurationMenu_.add(configMenuItem); } } } /** * Allows MMListeners to register themselves */ public void addMMListener(MMListenerInterface newL) { if (MMListeners_.contains(newL)) return; MMListeners_.add(newL); } /** * Allows MMListeners to remove themselves */ public void removeMMListener(MMListenerInterface oldL) { if (!MMListeners_.contains(oldL)) return; MMListeners_.remove(oldL); } /** * Lets JComponents register themselves so that their background can be * manipulated */ public void addMMBackgroundListener(Component comp) { if (MMFrames_.contains(comp)) return; MMFrames_.add(comp); } /** * Lets JComponents remove themselves from the list whose background gets * changes */ public void removeMMBackgroundListener(Component comp) { if (!MMFrames_.contains(comp)) return; MMFrames_.remove(comp); } /** * Part of ScriptInterface * Manipulate acquisition so that it looks like a burst */ public void runBurstAcquisition() throws MMScriptException { double interval = engine_.getFrameIntervalMs(); int nr = engine_.getNumFrames(); boolean doZStack = engine_.isZSliceSettingEnabled(); boolean doChannels = engine_.isChannelsSettingEnabled(); engine_.enableZSliceSetting(false); engine_.setFrames(nr, 0); engine_.enableChannelsSetting(false); try { engine_.acquire(); } catch (MMException e) { throw new MMScriptException(e); } engine_.setFrames(nr, interval); engine_.enableZSliceSetting(doZStack); engine_.enableChannelsSetting(doChannels); } public void runBurstAcquisition(int nr) throws MMScriptException { int originalNr = engine_.getNumFrames(); double interval = engine_.getFrameIntervalMs(); engine_.setFrames(nr, 0); this.runBurstAcquisition(); engine_.setFrames(originalNr, interval); } public void runBurstAcquisition(int nr, String name, String root) throws MMScriptException { //String originalName = engine_.getDirName(); String originalRoot = engine_.getRootName(); engine_.setDirName(name); engine_.setRootName(root); this.runBurstAcquisition(nr); engine_.setRootName(originalRoot); //engine_.setDirName(originalDirName); } public void logStartupProperties() { core_.enableDebugLog(options_.debugLogEnabled_); core_.logMessage("MM Studio version: " + getVersion()); core_.logMessage(core_.getVersionInfo()); core_.logMessage(core_.getAPIVersionInfo()); core_.logMessage("Operating System: " + System.getProperty("os.name") + " " + System.getProperty("os.version")); core_.logMessage("JVM: " + System.getProperty("java.vm.name") + ", version " + System.getProperty("java.version") + "; " + System.getProperty("sun.arch.data.model") + " bit"); } /** * @deprecated * @throws MMScriptException */ public void startBurstAcquisition() throws MMScriptException { runAcquisition(); } public boolean isBurstAcquisitionRunning() throws MMScriptException { if (engine_ == null) return false; return engine_.isAcquisitionRunning(); } private void startLoadingPipelineClass() { Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); acquisitionEngine2010LoadingThread = new Thread("Pipeline Class loading thread") { @Override public void run() { try { acquisitionEngine2010Class = Class.forName("org.micromanager.AcquisitionEngine2010"); } catch (Exception ex) { ReportingUtils.logError(ex); acquisitionEngine2010Class = null; } } }; acquisitionEngine2010LoadingThread.start(); } public ImageCache getAcquisitionImageCache(String acquisitionName) throws MMScriptException { return getAcquisition(acquisitionName).getImageCache(); } /* * Shows images as they appear in the default display window. Uses * the default processor stack to process images as they arrive on * the rawImageQueue. */ public void runDisplayThread(BlockingQueue rawImageQueue, final DisplayImageRoutine displayImageRoutine) { final BlockingQueue processedImageQueue = ProcessorStack.run(rawImageQueue, getAcquisitionEngine().getImageProcessors()); new Thread("Display thread") { @Override public void run() { try { TaggedImage image = null; do { image = (TaggedImage) processedImageQueue.take(); if (image != TaggedImageQueue.POISON) { displayImageRoutine.show(image); } } while (image != TaggedImageQueue.POISON); } catch (InterruptedException ex) { ReportingUtils.logError(ex); } } }.start(); } public interface DisplayImageRoutine { public void show(TaggedImage image); } /** * Callback to update GUI when a change happens in the MMCore. */ public class CoreEventCallback extends MMEventCallback { public CoreEventCallback() { super(); } @Override public void onPropertiesChanged() { // TODO: remove test once acquisition engine is fully multithreaded if (engine_ != null && engine_.isAcquisitionRunning()) { core_.logMessage("Notification from MMCore ignored because acquistion is running!", true); } else { if (ignorePropertyChanges_) { core_.logMessage("Notification from MMCore ignored since the system is still loading", true); } else { core_.updateSystemStateCache(); updateGUI(true); // update all registered listeners for (MMListenerInterface mmIntf : MMListeners_) { mmIntf.propertiesChangedAlert(); } core_.logMessage("Notification from MMCore!", true); } } } @Override public void onPropertyChanged(String deviceName, String propName, String propValue) { core_.logMessage("Notification for Device: " + deviceName + " Property: " + propName + " changed to value: " + propValue, true); // update all registered listeners for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.propertyChangedAlert(deviceName, propName, propValue); } } @Override public void onConfigGroupChanged(String groupName, String newConfig) { try { configPad_.refreshGroup(groupName, newConfig); for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.configGroupChangedAlert(groupName, newConfig); } } catch (Exception e) { } } @Override public void onPixelSizeChanged(double newPixelSizeUm) { updatePixSizeUm (newPixelSizeUm); for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.pixelSizeChangedAlert(newPixelSizeUm); } } @Override public void onStagePositionChanged(String deviceName, double pos) { if (deviceName.equals(zStageLabel_)) { updateZPos(pos); for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.stagePositionChangedAlert(deviceName, pos); } } } @Override public void onStagePositionChangedRelative(String deviceName, double pos) { if (deviceName.equals(zStageLabel_)) updateZPosRelative(pos); } @Override public void onXYStagePositionChanged(String deviceName, double xPos, double yPos) { if (deviceName.equals(xyStageLabel_)) { updateXYPos(xPos, yPos); for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.xyStagePositionChanged(deviceName, xPos, yPos); } } } @Override public void onXYStagePositionChangedRelative(String deviceName, double xPos, double yPos) { if (deviceName.equals(xyStageLabel_)) updateXYPosRelative(xPos, yPos); } @Override public void onExposureChanged(String deviceName, double exposure) { if (deviceName.equals(cameraLabel_)){ // update exposure in gui textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure)); } for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.exposureChanged(deviceName, exposure); } } } private class PluginItem { public Class<?> pluginClass = null; public String menuItem = "undefined"; public MMPlugin plugin = null; public String className = ""; public void instantiate() { try { if (plugin == null) { plugin = (MMPlugin) pluginClass.newInstance(); } } catch (InstantiationException e) { ReportingUtils.logError(e); } catch (IllegalAccessException e) { ReportingUtils.logError(e); } plugin.setApp(MMStudioMainFrame.this); } } /* * Simple class used to cache static info */ private class StaticInfo { public long width_; public long height_; public long bytesPerPixel_; public long imageBitDepth_; public double pixSizeUm_; public double zPos_; public double x_; public double y_; } private StaticInfo staticInfo_ = new StaticInfo(); /** * Main procedure for stand alone operation. */ public static void main(String args[]) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); MMStudioMainFrame frame = new MMStudioMainFrame(false); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); } catch (Throwable e) { ReportingUtils.showError(e, "A java error has caused Micro-Manager to exit."); System.exit(1); } } public MMStudioMainFrame(boolean pluginStatus) { super(); startLoadingPipelineClass(); options_ = new MMOptions(); try { options_.loadSettings(); } catch (NullPointerException ex) { ReportingUtils.logError(ex); } UIMonitor.enable(options_.debugLogEnabled_); guiColors_ = new GUIColors(); plugins_ = new ArrayList<PluginItem>(); gui_ = this; runsAsPlugin_ = pluginStatus; setIconImage(SwingResourceManager.getImage(MMStudioMainFrame.class, "icons/microscope.gif")); running_ = true; acqMgr_ = new AcquisitionManager(); sysConfigFile_ = System.getProperty("user.dir") + "/" + DEFAULT_CONFIG_FILE_NAME; if (options_.startupScript_.length() > 0) { startupScriptFile_ = System.getProperty("user.dir") + "/" + options_.startupScript_; } else { startupScriptFile_ = ""; } ReportingUtils.SetContainingFrame(gui_); // set the location for app preferences try { mainPrefs_ = Preferences.userNodeForPackage(this.getClass()); } catch (Exception e) { ReportingUtils.logError(e); } systemPrefs_ = mainPrefs_; colorPrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + "/" + AcqControlDlg.COLOR_SETTINGS_NODE); exposurePrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + "/" + EXPOSURE_SETTINGS_NODE); contrastPrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + "/" + CONTRAST_SETTINGS_NODE); // check system preferences try { Preferences p = Preferences.systemNodeForPackage(this.getClass()); if (null != p) { // if we can not write to the systemPrefs, use AppPrefs instead if (JavaUtils.backingStoreAvailable(p)) { systemPrefs_ = p; } } } catch (Exception e) { ReportingUtils.logError(e); } // show registration dialog if not already registered // first check user preferences (for legacy compatibility reasons) boolean userReg = mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false) || mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false); if (!userReg) { boolean systemReg = systemPrefs_.getBoolean( RegistrationDlg.REGISTRATION, false) || systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false); if (!systemReg) { // prompt for registration info RegistrationDlg dlg = new RegistrationDlg(systemPrefs_); dlg.setVisible(true); } } // load application preferences // NOTE: only window size and position preferences are loaded, // not the settings for the camera and live imaging - // attempting to set those automatically on startup may cause problems // with the hardware int x = mainPrefs_.getInt(MAIN_FRAME_X, 100); int y = mainPrefs_.getInt(MAIN_FRAME_Y, 100); int width = mainPrefs_.getInt(MAIN_FRAME_WIDTH, 644); int height = mainPrefs_.getInt(MAIN_FRAME_HEIGHT, 570); int dividerPos = mainPrefs_.getInt(MAIN_FRAME_DIVIDER_POS, 200); openAcqDirectory_ = mainPrefs_.get(OPEN_ACQ_DIR, ""); try { ImageUtils.setImageStorageClass(Class.forName (mainPrefs_.get(MAIN_SAVE_METHOD, ImageUtils.getImageStorageClass().getName()) ) ); } catch (ClassNotFoundException ex) { ReportingUtils.logError(ex, "Class not found error. Should never happen"); } ToolTipManager ttManager = ToolTipManager.sharedInstance(); ttManager.setDismissDelay(TOOLTIP_DISPLAY_DURATION_MILLISECONDS); ttManager.setInitialDelay(TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS); setBounds(x, y, width, height); setExitStrategy(options_.closeOnExit_); setTitle(MICRO_MANAGER_TITLE + " " + MMVersion.VERSION_STRING); setBackground(guiColors_.background.get((options_.displayBackground_))); SpringLayout topLayout = new SpringLayout(); this.setMinimumSize(new Dimension(605,480)); JPanel topPanel = new JPanel(); topPanel.setLayout(topLayout); topPanel.setMinimumSize(new Dimension(580, 195)); class ListeningJPanel extends JPanel implements AncestorListener { public void ancestorMoved(AncestorEvent event) { //System.out.println("moved!"); } public void ancestorRemoved(AncestorEvent event) {} public void ancestorAdded(AncestorEvent event) {} } ListeningJPanel bottomPanel = new ListeningJPanel(); bottomPanel.setLayout(topLayout); splitPane_ = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, topPanel, bottomPanel); splitPane_.setBorder(BorderFactory.createEmptyBorder()); splitPane_.setDividerLocation(dividerPos); splitPane_.setResizeWeight(0.0); splitPane_.addAncestorListener(bottomPanel); getContentPane().add(splitPane_); // Snap button buttonSnap_ = new JButton(); buttonSnap_.setIconTextGap(6); buttonSnap_.setText("Snap"); buttonSnap_.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/camera.png")); buttonSnap_.setFont(new Font("Arial", Font.PLAIN, 10)); buttonSnap_.setToolTipText("Snap single image"); buttonSnap_.setMaximumSize(new Dimension(0, 0)); buttonSnap_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doSnap(); } }); topPanel.add(buttonSnap_); topLayout.putConstraint(SpringLayout.SOUTH, buttonSnap_, 25, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, buttonSnap_, 4, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.EAST, buttonSnap_, 95, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, buttonSnap_, 7, SpringLayout.WEST, topPanel); // Initialize // Exposure field final JLabel label_1 = new JLabel(); label_1.setFont(new Font("Arial", Font.PLAIN, 10)); label_1.setText("Exposure [ms]"); topPanel.add(label_1); topLayout.putConstraint(SpringLayout.EAST, label_1, 198, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, label_1, 111, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.SOUTH, label_1, 39, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, label_1, 23, SpringLayout.NORTH, topPanel); textFieldExp_ = new JTextField(); textFieldExp_.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent fe) { synchronized(shutdownLock_) { if (core_ != null) setExposure(); } } }); textFieldExp_.setFont(new Font("Arial", Font.PLAIN, 10)); textFieldExp_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setExposure(); } }); topPanel.add(textFieldExp_); topLayout.putConstraint(SpringLayout.SOUTH, textFieldExp_, 40, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, textFieldExp_, 21, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.EAST, textFieldExp_, 276, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, textFieldExp_, 203, SpringLayout.WEST, topPanel); // Live button toggleButtonLive_ = new JToggleButton(); toggleButtonLive_.setName("Live"); toggleButtonLive_.setMargin(new Insets(2, 2, 2, 2)); toggleButtonLive_.setIconTextGap(1); toggleButtonLive_.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/camera_go.png")); toggleButtonLive_.setIconTextGap(6); toggleButtonLive_.setToolTipText("Continuous live view"); toggleButtonLive_.setFont(new Font("Arial", Font.PLAIN, 10)); toggleButtonLive_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { enableLiveMode(!isLiveModeOn()); } }); toggleButtonLive_.setText("Live"); topPanel.add(toggleButtonLive_); topLayout.putConstraint(SpringLayout.SOUTH, toggleButtonLive_, 47, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, toggleButtonLive_, 26, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.EAST, toggleButtonLive_, 95, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, toggleButtonLive_, 7, SpringLayout.WEST, topPanel); // Acquire button toAlbumButton_ = new JButton(); toAlbumButton_.setMargin(new Insets(2, 2, 2, 2)); toAlbumButton_.setIconTextGap(1); toAlbumButton_.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/camera_plus_arrow.png")); toAlbumButton_.setIconTextGap(6); toAlbumButton_.setToolTipText("Acquire single frame and add to an album"); toAlbumButton_.setFont(new Font("Arial", Font.PLAIN, 10)); toAlbumButton_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { snapAndAddToImage5D(); } }); toAlbumButton_.setText("Album"); topPanel.add(toAlbumButton_); topLayout.putConstraint(SpringLayout.SOUTH, toAlbumButton_, 69, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, toAlbumButton_, 48, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.EAST, toAlbumButton_, 95, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, toAlbumButton_, 7, SpringLayout.WEST, topPanel); // Shutter button toggleButtonShutter_ = new JToggleButton(); toggleButtonShutter_.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { toggleShutter(); } }); toggleButtonShutter_.setToolTipText("Open/close the shutter"); toggleButtonShutter_.setIconTextGap(6); toggleButtonShutter_.setFont(new Font("Arial", Font.BOLD, 10)); toggleButtonShutter_.setText("Open"); topPanel.add(toggleButtonShutter_); topLayout.putConstraint(SpringLayout.EAST, toggleButtonShutter_, 275, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, toggleButtonShutter_, 203, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.SOUTH, toggleButtonShutter_, 138 - 21, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, toggleButtonShutter_, 117 - 21, SpringLayout.NORTH, topPanel); // Active shutter label final JLabel activeShutterLabel = new JLabel(); activeShutterLabel.setFont(new Font("Arial", Font.PLAIN, 10)); activeShutterLabel.setText("Shutter"); topPanel.add(activeShutterLabel); topLayout.putConstraint(SpringLayout.SOUTH, activeShutterLabel, 108 - 22, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, activeShutterLabel, 95 - 22, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.EAST, activeShutterLabel, 160 - 2, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, activeShutterLabel, 113 - 2, SpringLayout.WEST, topPanel); // Active shutter Combo Box shutterComboBox_ = new JComboBox(); shutterComboBox_.setName("Shutter"); shutterComboBox_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { if (shutterComboBox_.getSelectedItem() != null) { core_.setShutterDevice((String) shutterComboBox_.getSelectedItem()); } } catch (Exception e) { ReportingUtils.showError(e); } return; } }); topPanel.add(shutterComboBox_); topLayout.putConstraint(SpringLayout.SOUTH, shutterComboBox_, 114 - 22, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, shutterComboBox_, 92 - 22, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.EAST, shutterComboBox_, 275, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, shutterComboBox_, 170, SpringLayout.WEST, topPanel); menuBar_ = new JMenuBar(); setJMenuBar(menuBar_); // File menu final JMenu fileMenu = new JMenu(); fileMenu.setText("File"); menuBar_.add(fileMenu); final JMenuItem openMenuItem = new JMenuItem(); openMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { new Thread() { @Override public void run() { openAcquisitionData(false); } }.start(); } }); openMenuItem.setText("Open (Virtual)..."); fileMenu.add(openMenuItem); final JMenuItem openInRamMenuItem = new JMenuItem(); openInRamMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { new Thread() { @Override public void run() { openAcquisitionData(true); } }.start(); } }); openInRamMenuItem.setText("Open (RAM)..."); fileMenu.add(openInRamMenuItem); fileMenu.addSeparator(); final JMenuItem exitMenuItem = new JMenuItem(); exitMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { closeSequence(false); } }); fileMenu.add(exitMenuItem); exitMenuItem.setText("Exit"); // Tools menu final JMenu toolsMenu = new JMenu(); toolsMenu.setText("Tools"); menuBar_.add(toolsMenu); final JMenuItem refreshMenuItem = new JMenuItem(); refreshMenuItem.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "icons/arrow_refresh.png")); refreshMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { core_.updateSystemStateCache(); updateGUI(true); } }); refreshMenuItem.setText("Refresh GUI"); refreshMenuItem.setToolTipText("Refresh all GUI controls directly from the hardware"); toolsMenu.add(refreshMenuItem); final JMenuItem rebuildGuiMenuItem = new JMenuItem(); rebuildGuiMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { initializeGUI(); core_.updateSystemStateCache(); } }); rebuildGuiMenuItem.setText("Rebuild GUI"); rebuildGuiMenuItem.setToolTipText("Regenerate micromanager user interface"); toolsMenu.add(rebuildGuiMenuItem); toolsMenu.addSeparator(); final JMenuItem scriptPanelMenuItem = new JMenuItem(); toolsMenu.add(scriptPanelMenuItem); scriptPanelMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { scriptPanel_.setVisible(true); } }); scriptPanelMenuItem.setText("Script Panel..."); scriptPanelMenuItem.setToolTipText("Open micromanager script editor window"); final JMenuItem hotKeysMenuItem = new JMenuItem(); toolsMenu.add(hotKeysMenuItem); hotKeysMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { HotKeysDialog hk = new HotKeysDialog (guiColors_.background.get((options_.displayBackground_))); //hk.setBackground(guiColors_.background.get((options_.displayBackground_))); } }); hotKeysMenuItem.setText("Shortcuts..."); hotKeysMenuItem.setToolTipText("Create keyboard shortcuts to activate image acquisition, mark positions, or run custom scripts"); final JMenuItem propertyEditorMenuItem = new JMenuItem(); toolsMenu.add(propertyEditorMenuItem); propertyEditorMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { createPropertyEditor(); } }); propertyEditorMenuItem.setText("Device/Property Browser..."); propertyEditorMenuItem.setToolTipText("Open new window to view and edit property values in current configuration"); toolsMenu.addSeparator(); final JMenuItem xyListMenuItem = new JMenuItem(); xyListMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { showXYPositionList(); } }); xyListMenuItem.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "icons/application_view_list.png")); xyListMenuItem.setText("XY List..."); toolsMenu.add(xyListMenuItem); xyListMenuItem.setToolTipText("Open position list manager window"); final JMenuItem acquisitionMenuItem = new JMenuItem(); acquisitionMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { openAcqControlDialog(); } }); acquisitionMenuItem.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "icons/film.png")); acquisitionMenuItem.setText("Multi-Dimensional Acquisition..."); toolsMenu.add(acquisitionMenuItem); acquisitionMenuItem.setToolTipText("Open multi-dimensional acquisition window"); centerAndDragMenuItem_ = new JCheckBoxMenuItem(); centerAndDragMenuItem_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateCenterAndDragListener(); IJ.setTool(Toolbar.HAND); mainPrefs_.putBoolean(MOUSE_MOVES_STAGE, centerAndDragMenuItem_.isSelected()); } }); centerAndDragMenuItem_.setText("Mouse Moves Stage (use Hand Tool)"); centerAndDragMenuItem_.setSelected(mainPrefs_.getBoolean(MOUSE_MOVES_STAGE, false)); centerAndDragMenuItem_.setToolTipText("When enabled, double clicking or dragging in the snap/live\n" + "window moves the XY-stage. Requires the hand tool."); toolsMenu.add(centerAndDragMenuItem_); final JMenuItem calibrationMenuItem = new JMenuItem(); toolsMenu.add(calibrationMenuItem); calibrationMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { createCalibrationListDlg(); } }); calibrationMenuItem.setText("Pixel Size Calibration..."); toolsMenu.add(calibrationMenuItem); String calibrationTooltip = "Define size calibrations specific to each objective lens. " + "When the objective in use has a calibration defined, " + "micromanager will automatically use it when " + "calculating metadata"; String mrjProp = System.getProperty("mrj.version"); if (mrjProp != null && !mrjProp.equals("")) {// running on a mac calibrationMenuItem.setToolTipText(calibrationTooltip); } else { calibrationMenuItem.setToolTipText(TooltipTextMaker.addHTMLBreaksForTooltip(calibrationTooltip)); } toolsMenu.addSeparator(); final JMenuItem configuratorMenuItem = new JMenuItem(); configuratorMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { runHardwareWizard(); } }); configuratorMenuItem.setText("Hardware Configuration Wizard..."); toolsMenu.add(configuratorMenuItem); configuratorMenuItem.setToolTipText("Open wizard to create new hardware configuration"); final JMenuItem loadSystemConfigMenuItem = new JMenuItem(); toolsMenu.add(loadSystemConfigMenuItem); loadSystemConfigMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { loadConfiguration(); initializeGUI(); } }); loadSystemConfigMenuItem.setText("Load Hardware Configuration..."); loadSystemConfigMenuItem.setToolTipText("Un-initialize current configuration and initialize new one"); switchConfigurationMenu_ = new JMenu(); for (int i=0; i<5; i++) { JMenuItem configItem = new JMenuItem(); configItem.setText(Integer.toString(i)); switchConfigurationMenu_.add(configItem); } final JMenuItem reloadConfigMenuItem = new JMenuItem(); toolsMenu.add(reloadConfigMenuItem); reloadConfigMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { loadSystemConfiguration(); initializeGUI(); } }); reloadConfigMenuItem.setText("Reload Hardware Configuration"); reloadConfigMenuItem.setToolTipText("Un-initialize current configuration and initialize most recently loaded configuration"); switchConfigurationMenu_.setText("Switch Hardware Configuration"); toolsMenu.add(switchConfigurationMenu_); switchConfigurationMenu_.setToolTipText("Switch between recently used configurations"); final JMenuItem saveConfigurationPresetsMenuItem = new JMenuItem(); saveConfigurationPresetsMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { saveConfigPresets(); updateChannelCombos(); } }); saveConfigurationPresetsMenuItem.setText("Save Configuration Settings as..."); toolsMenu.add(saveConfigurationPresetsMenuItem); saveConfigurationPresetsMenuItem.setToolTipText("Save current configuration settings as new configuration file"); toolsMenu.addSeparator(); final MMStudioMainFrame thisInstance = this; final JMenuItem optionsMenuItem = new JMenuItem(); optionsMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { int oldBufsize = options_.circularBufferSizeMB_; OptionsDlg dlg = new OptionsDlg(options_, core_, mainPrefs_, thisInstance, sysConfigFile_); dlg.setVisible(true); // adjust memory footprint if necessary if (oldBufsize != options_.circularBufferSizeMB_) { try { core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_); } catch (Exception exc) { ReportingUtils.showError(exc); } } } }); optionsMenuItem.setText("Options..."); toolsMenu.add(optionsMenuItem); final JLabel binningLabel = new JLabel(); binningLabel.setFont(new Font("Arial", Font.PLAIN, 10)); binningLabel.setText("Binning"); topPanel.add(binningLabel); topLayout.putConstraint(SpringLayout.SOUTH, binningLabel, 64, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, binningLabel, 43, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.EAST, binningLabel, 200 - 1, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, binningLabel, 112 - 1, SpringLayout.WEST, topPanel); metadataPanel_ = new MetadataPanel(); bottomPanel.add(metadataPanel_); topLayout.putConstraint(SpringLayout.SOUTH, metadataPanel_, 0, SpringLayout.SOUTH, bottomPanel); topLayout.putConstraint(SpringLayout.NORTH, metadataPanel_, 0, SpringLayout.NORTH, bottomPanel); topLayout.putConstraint(SpringLayout.EAST, metadataPanel_, 0, SpringLayout.EAST, bottomPanel); topLayout.putConstraint(SpringLayout.WEST, metadataPanel_, 0, SpringLayout.WEST, bottomPanel); metadataPanel_.setBorder(BorderFactory.createEmptyBorder()); comboBinning_ = new JComboBox(); comboBinning_.setName("Binning"); comboBinning_.setFont(new Font("Arial", Font.PLAIN, 10)); comboBinning_.setMaximumRowCount(4); comboBinning_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { changeBinning(); } }); topPanel.add(comboBinning_); topLayout.putConstraint(SpringLayout.EAST, comboBinning_, 275, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, comboBinning_, 200, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.SOUTH, comboBinning_, 66, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, comboBinning_, 43, SpringLayout.NORTH, topPanel); final JLabel cameraSettingsLabel = new JLabel(); cameraSettingsLabel.setFont(new Font("Arial", Font.BOLD, 11)); cameraSettingsLabel.setText("Camera settings"); topPanel.add(cameraSettingsLabel); topLayout.putConstraint(SpringLayout.EAST, cameraSettingsLabel, 211, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.NORTH, cameraSettingsLabel, 6, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.WEST, cameraSettingsLabel, 109, SpringLayout.WEST, topPanel); labelImageDimensions_ = new JLabel(); labelImageDimensions_.setFont(new Font("Arial", Font.PLAIN, 10)); topPanel.add(labelImageDimensions_); topLayout.putConstraint(SpringLayout.SOUTH, labelImageDimensions_, 0, SpringLayout.SOUTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, labelImageDimensions_, -20, SpringLayout.SOUTH, topPanel); topLayout.putConstraint(SpringLayout.EAST, labelImageDimensions_, 0, SpringLayout.EAST, topPanel); topLayout.putConstraint(SpringLayout.WEST, labelImageDimensions_, 5, SpringLayout.WEST, topPanel); configPad_ = new ConfigGroupPad(); configPadButtonPanel_ = new ConfigPadButtonPanel(); configPadButtonPanel_.setConfigPad(configPad_); configPadButtonPanel_.setGUI(MMStudioMainFrame.getInstance()); configPad_.setFont(new Font("", Font.PLAIN, 10)); topPanel.add(configPad_); topLayout.putConstraint(SpringLayout.EAST, configPad_, -4, SpringLayout.EAST, topPanel); topLayout.putConstraint(SpringLayout.WEST, configPad_, 5, SpringLayout.EAST, comboBinning_); topLayout.putConstraint(SpringLayout.SOUTH, configPad_, -4, SpringLayout.NORTH, configPadButtonPanel_); topLayout.putConstraint(SpringLayout.NORTH, configPad_, 21, SpringLayout.NORTH, topPanel); topPanel.add(configPadButtonPanel_); topLayout.putConstraint(SpringLayout.EAST, configPadButtonPanel_, -4, SpringLayout.EAST, topPanel); topLayout.putConstraint(SpringLayout.WEST, configPadButtonPanel_, 5, SpringLayout.EAST, comboBinning_); topLayout.putConstraint(SpringLayout.NORTH, configPadButtonPanel_, -40, SpringLayout.SOUTH, topPanel); topLayout.putConstraint(SpringLayout.SOUTH, configPadButtonPanel_, -20, SpringLayout.SOUTH, topPanel); final JLabel stateDeviceLabel = new JLabel(); stateDeviceLabel.setFont(new Font("Arial", Font.BOLD, 11)); stateDeviceLabel.setText("Configuration settings"); topPanel.add(stateDeviceLabel); topLayout.putConstraint(SpringLayout.SOUTH, stateDeviceLabel, 0, SpringLayout.SOUTH, cameraSettingsLabel); topLayout.putConstraint(SpringLayout.NORTH, stateDeviceLabel, 0, SpringLayout.NORTH, cameraSettingsLabel); topLayout.putConstraint(SpringLayout.EAST, stateDeviceLabel, 150, SpringLayout.WEST, configPad_); topLayout.putConstraint(SpringLayout.WEST, stateDeviceLabel, 0, SpringLayout.WEST, configPad_); final JButton buttonAcqSetup = new JButton(); buttonAcqSetup.setMargin(new Insets(2, 2, 2, 2)); buttonAcqSetup.setIconTextGap(1); buttonAcqSetup.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/film.png")); buttonAcqSetup.setToolTipText("Open multi-dimensional acquisition window"); buttonAcqSetup.setFont(new Font("Arial", Font.PLAIN, 10)); buttonAcqSetup.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openAcqControlDialog(); } }); buttonAcqSetup.setText("Multi-D Acq."); topPanel.add(buttonAcqSetup); topLayout.putConstraint(SpringLayout.SOUTH, buttonAcqSetup, 91, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, buttonAcqSetup, 70, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.EAST, buttonAcqSetup, 95, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, buttonAcqSetup, 7, SpringLayout.WEST, topPanel); autoShutterCheckBox_ = new JCheckBox(); autoShutterCheckBox_.setFont(new Font("Arial", Font.PLAIN, 10)); autoShutterCheckBox_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { shutterLabel_ = core_.getShutterDevice(); if (shutterLabel_.length() == 0) { toggleButtonShutter_.setEnabled(false); return; } if (autoShutterCheckBox_.isSelected()) { try { core_.setAutoShutter(true); core_.setShutterOpen(false); toggleButtonShutter_.setSelected(false); toggleButtonShutter_.setText("Open"); toggleButtonShutter_.setEnabled(false); } catch (Exception e2) { ReportingUtils.logError(e2); } } else { try { core_.setAutoShutter(false); core_.setShutterOpen(false); toggleButtonShutter_.setEnabled(true); toggleButtonShutter_.setText("Open"); } catch (Exception exc) { ReportingUtils.logError(exc); } } } }); autoShutterCheckBox_.setIconTextGap(6); autoShutterCheckBox_.setHorizontalTextPosition(SwingConstants.LEADING); autoShutterCheckBox_.setText("Auto shutter"); topPanel.add(autoShutterCheckBox_); topLayout.putConstraint(SpringLayout.EAST, autoShutterCheckBox_, 202 - 3, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, autoShutterCheckBox_, 110 - 3, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.SOUTH, autoShutterCheckBox_, 141 - 22, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, autoShutterCheckBox_, 118 - 22, SpringLayout.NORTH, topPanel); final JButton refreshButton = new JButton(); refreshButton.setMargin(new Insets(2, 2, 2, 2)); refreshButton.setIconTextGap(1); refreshButton.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/arrow_refresh.png")); refreshButton.setFont(new Font("Arial", Font.PLAIN, 10)); refreshButton.setToolTipText("Refresh all GUI controls directly from the hardware"); refreshButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { core_.updateSystemStateCache(); updateGUI(true); } }); refreshButton.setText("Refresh"); topPanel.add(refreshButton); topLayout.putConstraint(SpringLayout.SOUTH, refreshButton, 113, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, refreshButton, 92, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.EAST, refreshButton, 95, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, refreshButton, 7, SpringLayout.WEST, topPanel); JLabel citePleaLabel = new JLabel("<html>Please <a href=\"http://micro-manager.org\">cite Micro-Manager</a> so funding will continue!</html>"); topPanel.add(citePleaLabel); citePleaLabel.setFont(new Font("Arial", Font.PLAIN, 11)); topLayout.putConstraint(SpringLayout.SOUTH, citePleaLabel, 139, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, citePleaLabel, 119, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.EAST, citePleaLabel, 270, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, citePleaLabel, 7, SpringLayout.WEST, topPanel); class Pleader extends Thread{ Pleader(){ super("pleader"); } @Override public void run(){ try { ij.plugin.BrowserLauncher.openURL("https://valelab.ucsf.edu/~MM/MMwiki/index.php/Citing_Micro-Manager"); } catch (IOException e1) { ReportingUtils.showError(e1); } } } citePleaLabel.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { Pleader p = new Pleader(); p.start(); } }); // add a listener to the main ImageJ window to catch it quitting out on us if (ij.IJ.getInstance() != null) { ij.IJ.getInstance().addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { closeSequence(true); }; }); } // add window listeners addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { closeSequence(false); } @Override public void windowOpened(WindowEvent e) { // initialize hardware try { core_ = new CMMCore(); } catch(UnsatisfiedLinkError ex) { ReportingUtils.showError(ex, "Failed to open libMMCoreJ_wrap.jnilib"); return; } ReportingUtils.setCore(core_); logStartupProperties(); cameraLabel_ = ""; shutterLabel_ = ""; zStageLabel_ = ""; xyStageLabel_ = ""; engine_ = new AcquisitionWrapperEngine(); // register callback for MMCore notifications, this is a global // to avoid garbage collection cb_ = new CoreEventCallback(); core_.registerCallback(cb_); try { core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_); } catch (Exception e2) { ReportingUtils.showError(e2); } MMStudioMainFrame parent = (MMStudioMainFrame) e.getWindow(); if (parent != null) { engine_.setParentGUI(parent); } loadMRUConfigFiles(); initializePlugins(); toFront(); if (!options_.doNotAskForConfigFile_) { MMIntroDlg introDlg = new MMIntroDlg(MMVersion.VERSION_STRING, MRUConfigFiles_); introDlg.setConfigFile(sysConfigFile_); introDlg.setBackground(guiColors_.background.get((options_.displayBackground_))); introDlg.setVisible(true); sysConfigFile_ = introDlg.getConfigFile(); } saveMRUConfigFiles(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); paint(MMStudioMainFrame.this.getGraphics()); engine_.setCore(core_, afMgr_); posList_ = new PositionList(); engine_.setPositionList(posList_); // load (but do no show) the scriptPanel createScriptPanel(); // Create an instance of HotKeys so that they can be read in from prefs hotKeys_ = new org.micromanager.utils.HotKeys(); hotKeys_.loadSettings(); // if an error occurred during config loading, // do not display more errors than needed if (!loadSystemConfiguration()) ReportingUtils.showErrorOn(false); executeStartupScript(); // Create Multi-D window here but do not show it. // This window needs to be created in order to properly set the "ChannelGroup" // based on the Multi-D parameters acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, MMStudioMainFrame.this, options_); addMMBackgroundListener(acqControlWin_); configPad_.setCore(core_); if (parent != null) { configPad_.setParentGUI(parent); } configPadButtonPanel_.setCore(core_); // initialize controls // initializeGUI(); Not needed since it is already called in loadSystemConfiguration initializeHelpMenu(); String afDevice = mainPrefs_.get(AUTOFOCUS_DEVICE, ""); if (afMgr_.hasDevice(afDevice)) { try { afMgr_.selectDevice(afDevice); } catch (MMException e1) { // this error should never happen ReportingUtils.showError(e1); } } centerAndDragListener_ = new CenterAndDragListener(gui_); // switch error reporting back on ReportingUtils.showErrorOn(true); } private void initializePlugins() { pluginMenu_ = new JMenu(); pluginMenu_.setText("Plugins"); menuBar_.add(pluginMenu_); new Thread("Plugin loading") { @Override public void run() { // Needed for loading clojure-based jars: Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); loadPlugins(); } }.start(); } }); setRoiButton_ = new JButton(); setRoiButton_.setName("setRoiButton"); setRoiButton_.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/shape_handles.png")); setRoiButton_.setFont(new Font("Arial", Font.PLAIN, 10)); setRoiButton_.setToolTipText("Set Region Of Interest to selected rectangle"); setRoiButton_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setROI(); } }); topPanel.add(setRoiButton_); topLayout.putConstraint(SpringLayout.EAST, setRoiButton_, 37, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, setRoiButton_, 7, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.SOUTH, setRoiButton_, 174, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, setRoiButton_, 154, SpringLayout.NORTH, topPanel); clearRoiButton_ = new JButton(); clearRoiButton_.setName("clearRoiButton"); clearRoiButton_.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/arrow_out.png")); clearRoiButton_.setFont(new Font("Arial", Font.PLAIN, 10)); clearRoiButton_.setToolTipText("Reset Region of Interest to full frame"); clearRoiButton_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { clearROI(); } }); topPanel.add(clearRoiButton_); topLayout.putConstraint(SpringLayout.EAST, clearRoiButton_, 70, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, clearRoiButton_, 40, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.SOUTH, clearRoiButton_, 174, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, clearRoiButton_, 154, SpringLayout.NORTH, topPanel); final JLabel regionOfInterestLabel = new JLabel(); regionOfInterestLabel.setFont(new Font("Arial", Font.BOLD, 11)); regionOfInterestLabel.setText("ROI"); topPanel.add(regionOfInterestLabel); topLayout.putConstraint(SpringLayout.SOUTH, regionOfInterestLabel, 154, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, regionOfInterestLabel, 140, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.EAST, regionOfInterestLabel, 71, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, regionOfInterestLabel, 8, SpringLayout.WEST, topPanel); final JLabel regionOfInterestLabel_1 = new JLabel(); regionOfInterestLabel_1.setFont(new Font("Arial", Font.BOLD, 11)); regionOfInterestLabel_1.setText("Zoom"); topPanel.add(regionOfInterestLabel_1); topLayout.putConstraint(SpringLayout.SOUTH, regionOfInterestLabel_1, 154, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, regionOfInterestLabel_1, 140, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.EAST, regionOfInterestLabel_1, 139, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, regionOfInterestLabel_1, 81, SpringLayout.WEST, topPanel); final JButton zoomInButton = new JButton(); zoomInButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { zoomIn(); } }); zoomInButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/zoom_in.png")); zoomInButton.setName("zoomInButton"); zoomInButton.setToolTipText("Zoom in"); zoomInButton.setFont(new Font("Arial", Font.PLAIN, 10)); topPanel.add(zoomInButton); topLayout.putConstraint(SpringLayout.SOUTH, zoomInButton, 174, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, zoomInButton, 154, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.EAST, zoomInButton, 110, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, zoomInButton, 80, SpringLayout.WEST, topPanel); final JButton zoomOutButton = new JButton(); zoomOutButton.setName("zoomOutButton"); zoomOutButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { zoomOut(); } }); zoomOutButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/zoom_out.png")); zoomOutButton.setToolTipText("Zoom out"); zoomOutButton.setFont(new Font("Arial", Font.PLAIN, 10)); topPanel.add(zoomOutButton); topLayout.putConstraint(SpringLayout.SOUTH, zoomOutButton, 174, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, zoomOutButton, 154, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.EAST, zoomOutButton, 143, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, zoomOutButton, 113, SpringLayout.WEST, topPanel); // Profile final JLabel profileLabel_ = new JLabel(); profileLabel_.setFont(new Font("Arial", Font.BOLD, 11)); profileLabel_.setText("Profile"); topPanel.add(profileLabel_); topLayout.putConstraint(SpringLayout.SOUTH, profileLabel_, 154, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, profileLabel_, 140, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.EAST, profileLabel_, 217, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, profileLabel_, 154, SpringLayout.WEST, topPanel); final JButton lineProfileButton = new JButton(); lineProfileButton.setName("lineProfileButton"); lineProfileButton.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/chart_curve.png")); lineProfileButton.setFont(new Font("Arial", Font.PLAIN, 10)); lineProfileButton.setToolTipText("Open line profile window (requires line selection)"); lineProfileButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { openLineProfileWindow(); } }); // buttonProf.setText("Profile"); topPanel.add(lineProfileButton); topLayout.putConstraint(SpringLayout.SOUTH, lineProfileButton, 174, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, lineProfileButton, 154, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.EAST, lineProfileButton, 183, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, lineProfileButton, 153, SpringLayout.WEST, topPanel); // Autofocus final JLabel autofocusLabel_ = new JLabel(); autofocusLabel_.setFont(new Font("Arial", Font.BOLD, 11)); autofocusLabel_.setText("Autofocus"); topPanel.add(autofocusLabel_); topLayout.putConstraint(SpringLayout.SOUTH, autofocusLabel_, 154, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, autofocusLabel_, 140, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.EAST, autofocusLabel_, 274, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, autofocusLabel_, 194, SpringLayout.WEST, topPanel); autofocusNowButton_ = new JButton(); autofocusNowButton_.setName("autofocusNowButton"); autofocusNowButton_.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/find.png")); autofocusNowButton_.setFont(new Font("Arial", Font.PLAIN, 10)); autofocusNowButton_.setToolTipText("Autofocus now"); autofocusNowButton_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (afMgr_.getDevice() != null) { new Thread() { @Override public void run() { try { boolean lmo = isLiveModeOn(); if (lmo) { enableLiveMode(false); } afMgr_.getDevice().fullFocus(); if (lmo) { enableLiveMode(true); } } catch (MMException ex) { ReportingUtils.logError(ex); } } }.start(); // or any other method from Autofocus.java API } } }); topPanel.add(autofocusNowButton_); topLayout.putConstraint(SpringLayout.SOUTH, autofocusNowButton_, 174, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, autofocusNowButton_, 154, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.EAST, autofocusNowButton_, 223, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, autofocusNowButton_, 193, SpringLayout.WEST, topPanel); autofocusConfigureButton_ = new JButton(); autofocusConfigureButton_.setName("autofocusConfigureButton_"); autofocusConfigureButton_.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/wrench_orange.png")); autofocusConfigureButton_.setFont(new Font("Arial", Font.PLAIN, 10)); autofocusConfigureButton_.setToolTipText("Set autofocus options"); autofocusConfigureButton_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showAutofocusDialog(); } }); topPanel.add(autofocusConfigureButton_); topLayout.putConstraint(SpringLayout.SOUTH, autofocusConfigureButton_, 174, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, autofocusConfigureButton_, 154, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.EAST, autofocusConfigureButton_, 256, SpringLayout.WEST, topPanel); topLayout.putConstraint(SpringLayout.WEST, autofocusConfigureButton_, 226, SpringLayout.WEST, topPanel); saveConfigButton_ = new JButton(); saveConfigButton_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { saveConfigPresets(); } }); saveConfigButton_.setToolTipText("Save current presets to the configuration file"); saveConfigButton_.setText("Save"); saveConfigButton_.setEnabled(false); topPanel.add(saveConfigButton_); topLayout.putConstraint(SpringLayout.SOUTH, saveConfigButton_, 20, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.NORTH, saveConfigButton_, 2, SpringLayout.NORTH, topPanel); topLayout.putConstraint(SpringLayout.EAST, saveConfigButton_, -5, SpringLayout.EAST, topPanel); topLayout.putConstraint(SpringLayout.WEST, saveConfigButton_, -80, SpringLayout.EAST, topPanel); // Add our own keyboard manager that handles Micro-Manager shortcuts MMKeyDispatcher mmKD = new MMKeyDispatcher(gui_); KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(mmKD); dt_ = new DropTarget(this, new DragDropUtil()); overrideImageJMenu(); } private void overrideImageJMenu() { // final Menu colorMenu = ((Menu) Menus.getMenuBar().getMenu(2).getItem(5)); // MenuItem stackToRGB = colorMenu.getItem(4); // final ActionListener ij = stackToRGB.getActionListeners()[0]; // stackToRGB.removeActionListener(ij); // stackToRGB.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // ImagePlus img = WindowManager.getCurrentImage(); // if (img != null && img instanceof VirtualAcquisitionDisplay.MMCompositeImage) { // int selection = JOptionPane.showConfirmDialog(img.getWindow(), // "Because of the way Micro-Manager internally handles Color images, this command may\n" // + "and then merging them. Would you like Micro-Manager to perform this operation\n" // + "automatically?\n\n" // + "Yes--Split and merge channels to create RGB image/stack\n" // + "No--Proceed with Stack to RGB command (may have unexpected effects on pixel data) ", // "Convert Stack to RGB", JOptionPane.YES_NO_CANCEL_OPTION); // if (selection == 0) { //yes // IJ.run("Split Channels"); // WindowManager.getCurrentImage().setTitle("BlueChannel"); // WindowManager.getImage(WindowManager.getNthImageID(2)).setTitle("GreenChannel"); // WindowManager.getImage(WindowManager.getNthImageID(1)).setTitle("RedChannel"); // IJ.run("Merge Channels...", "red=[RedChannel] green=[GreenChannel] blue=[BlueChannel] gray=*None*"); // } else if (selection == 1) { //no // ij.actionPerformed(e); // } else { // //If not an MM CompositImage, do the normal command // ij.actionPerformed(e); } private void handleException(Exception e, String msg) { String errText = "Exception occurred: "; if (msg.length() > 0) { errText += msg + " } if (options_.debugLogEnabled_) { errText += e.getMessage(); } else { errText += e.toString() + "\n"; ReportingUtils.showError(e); } handleError(errText); } private void handleException(Exception e) { handleException(e, ""); } private void handleError(String message) { if (isLiveModeOn()) { // Should we always stop live mode on any error? enableLiveMode(false); } JOptionPane.showMessageDialog(this, message); core_.logMessage(message); } @Override public void makeActive() { toFront(); } /** * used to store contrast settings to be later used for initialization of contrast of new windows. * Shouldn't be called by loaded data sets, only * ones that have been acquired */ public void saveChannelHistogramSettings(String channelGroup, String channel, boolean mda, HistogramSettings settings) { String type = mda ? "MDA_" : "SnapLive_"; if (options_.syncExposureMainAndMDA_) { type = ""; //only one group of contrast settings } contrastPrefs_.putInt("ContrastMin_" + channelGroup + "_" + type + channel, settings.min_); contrastPrefs_.putInt("ContrastMax_" + channelGroup + "_" + type + channel, settings.max_); contrastPrefs_.putDouble("ContrastGamma_" + channelGroup + "_" + type + channel, settings.gamma_); contrastPrefs_.putInt("ContrastHistMax_" + channelGroup + "_" + type + channel, settings.histMax_); contrastPrefs_.putInt("ContrastHistDisplayMode_" + channelGroup + "_" + type + channel, settings.displayMode_); } public HistogramSettings loadStoredChannelHisotgramSettings(String channelGroup, String channel, boolean mda) { String type = mda ? "MDA_" : "SnapLive_"; if (options_.syncExposureMainAndMDA_) { type = ""; //only one group of contrast settings } return new HistogramSettings( contrastPrefs_.getInt("ContrastMin_" + channelGroup + "_" + type + channel,0), contrastPrefs_.getInt("ContrastMax_" + channelGroup + "_" + type + channel, 65536), contrastPrefs_.getDouble("ContrastGamma_" + channelGroup + "_" + type + channel, 1.0), contrastPrefs_.getInt("ContrastHistMax_" + channelGroup + "_" + type + channel, -1), contrastPrefs_.getInt("ContrastHistDisplayMode_" + channelGroup + "_" + type + channel, 1) ); } private void setExposure() { try { if (!isLiveModeOn()) { core_.setExposure(NumberUtils.displayStringToDouble( textFieldExp_.getText())); } else { liveModeTimer_.stop(); core_.setExposure(NumberUtils.displayStringToDouble( textFieldExp_.getText())); try { liveModeTimer_.begin(); } catch (Exception e) { ReportingUtils.showError("Couldn't restart live mode"); liveModeTimer_.stop(); } } // Display the new exposure time double exposure = core_.getExposure(); textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure)); // update current channel in MDA window with this exposure String channelGroup = core_.getChannelGroup(); String channel = core_.getCurrentConfigFromCache(channelGroup); if (!channel.equals("") ) { exposurePrefs_.putDouble("Exposure_" + channelGroup + "_" + channel, exposure); if (options_.syncExposureMainAndMDA_) { getAcqDlg().setChannelExposureTime(channelGroup, channel, exposure); } } } catch (Exception exp) { // Do nothing. } } /** * Returns exposure time for the desired preset in the given channelgroup * Acquires its info from the preferences * Same thing is used in MDA window, but this class keeps its own copy * * @param channelGroup * @param channel - * @param defaultExp - default value * @return exposure time */ public double getChannelExposureTime(String channelGroup, String channel, double defaultExp) { return exposurePrefs_.getDouble("Exposure_" + channelGroup + "_" + channel, defaultExp); } /** * Updates the exposure time in the given preset * Will also update current exposure if it the given channel and channelgroup * are the current one * * @param channelGroup - * * @param channel - preset for which to change exposure time * @param exposure - desired exposure time */ public void setChannelExposureTime(String channelGroup, String channel, double exposure) { try { exposurePrefs_.putDouble("Exposure_" + channelGroup + "_" + channel, exposure); if (channelGroup != null && channelGroup.equals(core_.getChannelGroup())) { if (channel != null && !channel.equals("") && channel.equals(core_.getCurrentConfigFromCache(channelGroup))) { textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure)); setExposure(); } } } catch (Exception ex) { ReportingUtils.logError("Failed to set Exposure prefs using Channelgroup: " + channelGroup + ", channel: " + channel + ", exposure: " + exposure); } } @Override public boolean getAutoreloadOption() { return options_.autoreloadDevices_; } public double getPreferredWindowMag() { return options_.windowMag_; } public boolean getMetadataFileWithMultipageTiff() { return options_.mpTiffMetadataFile_; } public boolean getSeparateFilesForPositionsMPTiff() { return options_.mpTiffSeparateFilesForPositions_; } public boolean getHideMDADisplayOption() { return options_.hideMDADisplay_; } public boolean getFastStorageOption() { return options_.fastStorage_; } private void updateTitle() { this.setTitle(MICRO_MANAGER_TITLE + " " + MMVersion.VERSION_STRING + " - " + sysConfigFile_); } public void updateLineProfile() { if (WindowManager.getCurrentWindow() == null || profileWin_ == null || !profileWin_.isShowing()) { return; } calculateLineProfileData(WindowManager.getCurrentImage()); profileWin_.setData(lineProfileData_); } private void openLineProfileWindow() { if (WindowManager.getCurrentWindow() == null || WindowManager.getCurrentWindow().isClosed()) { return; } calculateLineProfileData(WindowManager.getCurrentImage()); if (lineProfileData_ == null) { return; } profileWin_ = new GraphFrame(); profileWin_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); profileWin_.setData(lineProfileData_); profileWin_.setAutoScale(); profileWin_.setTitle("Live line profile"); profileWin_.setBackground(guiColors_.background.get((options_.displayBackground_))); addMMBackgroundListener(profileWin_); profileWin_.setVisible(true); } @Override public Rectangle getROI() throws MMScriptException { // ROI values are given as x,y,w,h in individual one-member arrays (pointers in C++): int[][] a = new int[4][1]; try { core_.getROI(a[0], a[1], a[2], a[3]); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } // Return as a single array with x,y,w,h: return new Rectangle(a[0][0], a[1][0], a[2][0], a[3][0]); } private void calculateLineProfileData(ImagePlus imp) { // generate line profile Roi roi = imp.getRoi(); if (roi == null || !roi.isLine()) { // if there is no line ROI, create one Rectangle r = imp.getProcessor().getRoi(); int iWidth = r.width; int iHeight = r.height; int iXROI = r.x; int iYROI = r.y; if (roi == null) { iXROI += iWidth / 2; iYROI += iHeight / 2; } roi = new Line(iXROI - iWidth / 4, iYROI - iWidth / 4, iXROI + iWidth / 4, iYROI + iHeight / 4); imp.setRoi(roi); roi = imp.getRoi(); } ImageProcessor ip = imp.getProcessor(); ip.setInterpolate(true); Line line = (Line) roi; if (lineProfileData_ == null) { lineProfileData_ = new GraphData(); } lineProfileData_.setData(line.getPixels()); } @Override public void setROI(Rectangle r) throws MMScriptException { boolean liveRunning = false; if (isLiveModeOn()) { liveRunning = true; enableLiveMode(false); } try { core_.setROI(r.x, r.y, r.width, r.height); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } updateStaticInfo(); if (liveRunning) { enableLiveMode(true); } } private void setROI() { ImagePlus curImage = WindowManager.getCurrentImage(); if (curImage == null) { return; } Roi roi = curImage.getRoi(); try { if (roi == null) { // if there is no ROI, create one Rectangle r = curImage.getProcessor().getRoi(); int iWidth = r.width; int iHeight = r.height; int iXROI = r.x; int iYROI = r.y; if (roi == null) { iWidth /= 2; iHeight /= 2; iXROI += iWidth / 2; iYROI += iHeight / 2; } curImage.setRoi(iXROI, iYROI, iWidth, iHeight); roi = curImage.getRoi(); } if (roi.getType() != Roi.RECTANGLE) { handleError("ROI must be a rectangle.\nUse the ImageJ rectangle tool to draw the ROI."); return; } Rectangle r = roi.getBoundingRect(); // if we already had an ROI defined, correct for the offsets Rectangle cameraR = getROI(); r.x += cameraR.x; r.y += cameraR.y; // Stop (and restart) live mode if it is running setROI(r); } catch (Exception e) { ReportingUtils.showError(e); } } private void clearROI() { try { boolean liveRunning = false; if (isLiveModeOn()) { liveRunning = true; enableLiveMode(false); } core_.clearROI(); updateStaticInfo(); if (liveRunning) { enableLiveMode(true); } } catch (Exception e) { ReportingUtils.showError(e); } } /** * Returns instance of the core uManager object; */ @Override public CMMCore getMMCore() { return core_; } /** * Returns singleton instance of MMStudioMainFrame */ public static MMStudioMainFrame getInstance() { return gui_; } public MetadataPanel getMetadataPanel() { return metadataPanel_; } public final void setExitStrategy(boolean closeOnExit) { if (closeOnExit) { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } else { setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } } @Override public void saveConfigPresets() { MicroscopeModel model = new MicroscopeModel(); try { model.loadFromFile(sysConfigFile_); model.createSetupConfigsFromHardware(core_); model.createResolutionsFromHardware(core_); File f = FileDialogs.save(this, "Save the configuration file", MM_CONFIG_FILE); if (f != null) { model.saveToFile(f.getAbsolutePath()); sysConfigFile_ = f.getAbsolutePath(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); configChanged_ = false; setConfigSaveButtonStatus(configChanged_); updateTitle(); } } catch (MMConfigFileException e) { ReportingUtils.showError(e); } } protected void setConfigSaveButtonStatus(boolean changed) { saveConfigButton_.setEnabled(changed); } public String getAcqDirectory() { return openAcqDirectory_; } /** * Get currently used configuration file * @return - Path to currently used configuration file */ public String getSysConfigFile() { return sysConfigFile_; } public void setAcqDirectory(String dir) { openAcqDirectory_ = dir; } /** * Open an existing acquisition directory and build viewer window. * */ public void openAcquisitionData(boolean inRAM) { // choose the directory File f = FileDialogs.openDir(this, "Please select an image data set", MM_DATA_SET); if (f != null) { if (f.isDirectory()) { openAcqDirectory_ = f.getAbsolutePath(); } else { openAcqDirectory_ = f.getParent(); } String acq = null; try { acq = openAcquisitionData(openAcqDirectory_, inRAM); } catch (MMScriptException ex) { ReportingUtils.showError(ex); } finally { try { acqMgr_.closeAcquisition(acq); } catch (MMScriptException ex) { ReportingUtils.logError(ex); } } } } public String openAcquisitionData(String dir, boolean inRAM, boolean show) throws MMScriptException { String rootDir = new File(dir).getAbsolutePath(); String name = new File(dir).getName(); rootDir = rootDir.substring(0, rootDir.length() - (name.length() + 1)); acqMgr_.openAcquisition(name, rootDir, show, !inRAM, true); try { getAcquisition(name).initialize(); } catch (MMScriptException mex) { acqMgr_.closeAcquisition(name); throw (mex); } return name; } /** * Opens an existing data set. Shows the acquisition in a window. * @return The acquisition object. */ public String openAcquisitionData(String dir, boolean inRam) throws MMScriptException { return openAcquisitionData(dir, inRam, true); } protected void zoomOut() { ImageWindow curWin = WindowManager.getCurrentWindow(); if (curWin != null) { ImageCanvas canvas = curWin.getCanvas(); Rectangle r = canvas.getBounds(); canvas.zoomOut(r.width / 2, r.height / 2); VirtualAcquisitionDisplay vad = VirtualAcquisitionDisplay.getDisplay(curWin.getImagePlus()); if (vad != null) { vad.storeWindowSizeAfterZoom(curWin); vad.updateWindowTitleAndStatus(); } } } protected void zoomIn() { ImageWindow curWin = WindowManager.getCurrentWindow(); if (curWin != null) { ImageCanvas canvas = curWin.getCanvas(); Rectangle r = canvas.getBounds(); canvas.zoomIn(r.width / 2, r.height / 2); VirtualAcquisitionDisplay vad = VirtualAcquisitionDisplay.getDisplay(curWin.getImagePlus()); if (vad != null) { vad.storeWindowSizeAfterZoom(curWin); vad.updateWindowTitleAndStatus(); } } } protected void changeBinning() { try { boolean liveRunning = false; if (isLiveModeOn() ) { liveRunning = true; enableLiveMode(false); } if (isCameraAvailable()) { Object item = comboBinning_.getSelectedItem(); if (item != null) { core_.setProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning(), item.toString()); } } updateStaticInfo(); if (liveRunning) { enableLiveMode(true); } } catch (Exception e) { ReportingUtils.showError(e); } } private void createPropertyEditor() { if (propertyBrowser_ != null) { propertyBrowser_.dispose(); } propertyBrowser_ = new PropertyEditor(); propertyBrowser_.setGui(this); propertyBrowser_.setVisible(true); propertyBrowser_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); propertyBrowser_.setCore(core_); } private void createCalibrationListDlg() { if (calibrationListDlg_ != null) { calibrationListDlg_.dispose(); } calibrationListDlg_ = new CalibrationListDlg(core_); calibrationListDlg_.setVisible(true); calibrationListDlg_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); calibrationListDlg_.setParentGUI(this); } public CalibrationListDlg getCalibrationListDlg() { if (calibrationListDlg_ == null) { createCalibrationListDlg(); } return calibrationListDlg_; } private void createScriptPanel() { if (scriptPanel_ == null) { scriptPanel_ = new ScriptPanel(core_, options_, this); scriptPanel_.insertScriptingObject(SCRIPT_CORE_OBJECT, core_); scriptPanel_.insertScriptingObject(SCRIPT_ACQENG_OBJECT, engine_); scriptPanel_.setParentGUI(this); scriptPanel_.setBackground(guiColors_.background.get((options_.displayBackground_))); addMMBackgroundListener(scriptPanel_); } } /** * Updates Status line in main window from cached values */ private void updateStaticInfoFromCache() { String dimText = "Image info (from camera): " + staticInfo_.width_ + " X " + staticInfo_.height_ + " X " + staticInfo_.bytesPerPixel_ + ", Intensity range: " + staticInfo_.imageBitDepth_ + " bits"; dimText += ", " + TextUtils.FMT0.format(staticInfo_.pixSizeUm_ * 1000) + "nm/pix"; if (zStageLabel_.length() > 0) { dimText += ", Z=" + TextUtils.FMT2.format(staticInfo_.zPos_) + "um"; } if (xyStageLabel_.length() > 0) { dimText += ", XY=(" + TextUtils.FMT2.format(staticInfo_.x_) + "," + TextUtils.FMT2.format(staticInfo_.y_) + ")um"; } labelImageDimensions_.setText(dimText); } public void updateXYPos(double x, double y) { staticInfo_.x_ = x; staticInfo_.y_ = y; updateStaticInfoFromCache(); } public void updateZPos(double z) { staticInfo_.zPos_ = z; updateStaticInfoFromCache(); } public void updateXYPosRelative(double x, double y) { staticInfo_.x_ += x; staticInfo_.y_ += y; updateStaticInfoFromCache(); } public void updateZPosRelative(double z) { staticInfo_.zPos_ += z; updateStaticInfoFromCache(); } public void updateXYStagePosition(){ double x[] = new double[1]; double y[] = new double[1]; try { if (xyStageLabel_.length() > 0) core_.getXYPosition(xyStageLabel_, x, y); } catch (Exception e) { ReportingUtils.showError(e); } staticInfo_.x_ = x[0]; staticInfo_.y_ = y[0]; updateStaticInfoFromCache(); } private void updatePixSizeUm (double pixSizeUm) { staticInfo_.pixSizeUm_ = pixSizeUm; updateStaticInfoFromCache(); } private void updateStaticInfo() { double zPos = 0.0; double x[] = new double[1]; double y[] = new double[1]; try { if (zStageLabel_.length() > 0) { zPos = core_.getPosition(zStageLabel_); } if (xyStageLabel_.length() > 0) { core_.getXYPosition(xyStageLabel_, x, y); } } catch (Exception e) { handleException(e); } staticInfo_.width_ = core_.getImageWidth(); staticInfo_.height_ = core_.getImageHeight(); staticInfo_.bytesPerPixel_ = core_.getBytesPerPixel(); staticInfo_.imageBitDepth_ = core_.getImageBitDepth(); staticInfo_.pixSizeUm_ = core_.getPixelSizeUm(); staticInfo_.zPos_ = zPos; staticInfo_.x_ = x[0]; staticInfo_.y_ = y[0]; updateStaticInfoFromCache(); } public void toggleShutter() { try { if (!toggleButtonShutter_.isEnabled()) return; toggleButtonShutter_.requestFocusInWindow(); if (toggleButtonShutter_.getText().equals("Open")) { setShutterButton(true); core_.setShutterOpen(true); } else { core_.setShutterOpen(false); setShutterButton(false); } } catch (Exception e1) { ReportingUtils.showError(e1); } } private void updateCenterAndDragListener() { if (centerAndDragMenuItem_.isSelected()) { centerAndDragListener_.start(); } else { centerAndDragListener_.stop(); } } private void setShutterButton(boolean state) { if (state) { toggleButtonShutter_.setText("Close"); } else { toggleButtonShutter_.setText("Open"); } } // public interface available for scripting access public void snapSingleImage() { doSnap(); } public Object getPixels() { ImagePlus ip = WindowManager.getCurrentImage(); if (ip != null) { return ip.getProcessor().getPixels(); } return null; } public void setPixels(Object obj) { ImagePlus ip = WindowManager.getCurrentImage(); if (ip == null) { return; } ip.getProcessor().setPixels(obj); } public int getImageHeight() { ImagePlus ip = WindowManager.getCurrentImage(); if (ip != null) return ip.getHeight(); return 0; } public int getImageWidth() { ImagePlus ip = WindowManager.getCurrentImage(); if (ip != null) return ip.getWidth(); return 0; } public int getImageDepth() { ImagePlus ip = WindowManager.getCurrentImage(); if (ip != null) return ip.getBitDepth(); return 0; } public ImageProcessor getImageProcessor() { ImagePlus ip = WindowManager.getCurrentImage(); if (ip == null) return null; return ip.getProcessor(); } private boolean isCameraAvailable() { return cameraLabel_.length() > 0; } /** * Part of ScriptInterface API * Opens the XYPositionList when it is not opened * Adds the current position to the list (same as pressing the "Mark" button) */ public void markCurrentPosition() { if (posListDlg_ == null) { showXYPositionList(); } if (posListDlg_ != null) { posListDlg_.markPosition(); } } /** * Implements ScriptInterface */ public AcqControlDlg getAcqDlg() { return acqControlWin_; } /** * Implements ScriptInterface */ public PositionListDlg getXYPosListDlg() { if (posListDlg_ == null) posListDlg_ = new PositionListDlg(core_, this, posList_, options_); return posListDlg_; } /** * Implements ScriptInterface */ public boolean isAcquisitionRunning() { if (engine_ == null) return false; return engine_.isAcquisitionRunning(); } /** * Implements ScriptInterface */ public boolean versionLessThan(String version) throws MMScriptException { try { String[] v = MMVersion.VERSION_STRING.split(" ", 2); String[] m = v[0].split("\\.", 3); String[] v2 = version.split(" ", 2); String[] m2 = v2[0].split("\\.", 3); for (int i=0; i < 3; i++) { if (Integer.parseInt(m[i]) < Integer.parseInt(m2[i])) { ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater"); return true; } if (Integer.parseInt(m[i]) > Integer.parseInt(m2[i])) { return false; } } if (v2.length < 2 || v2[1].equals("") ) return false; if (v.length < 2 ) { ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater"); return true; } if (Integer.parseInt(v[1]) < Integer.parseInt(v2[1])) { ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater"); return false; } return true; } catch (Exception ex) { throw new MMScriptException ("Format of version String should be \"a.b.c\""); } } public boolean isLiveModeOn() { return liveModeTimer_ != null && liveModeTimer_.isRunning(); } public LiveModeTimer getLiveModeTimer() { if (liveModeTimer_ == null) { liveModeTimer_ = new LiveModeTimer(); } return liveModeTimer_; } public void enableLiveMode(boolean enable) { if (core_ == null) { return; } if (enable == isLiveModeOn()) { return; } if (enable) { try { if (core_.getCameraDevice().length() == 0) { ReportingUtils.showError("No camera configured"); updateButtonsForLiveMode(false); return; } if (liveModeTimer_ == null) { liveModeTimer_ = new LiveModeTimer(); } liveModeTimer_.begin(); enableLiveModeListeners(enable); } catch (Exception e) { ReportingUtils.showError(e); liveModeTimer_.stop(); enableLiveModeListeners(false); updateButtonsForLiveMode(false); return; } } else { liveModeTimer_.stop(); enableLiveModeListeners(enable); } updateButtonsForLiveMode(enable); } public void updateButtonsForLiveMode(boolean enable) { autoShutterCheckBox_.setEnabled(!enable); if (core_.getAutoShutter()) { toggleButtonShutter_.setText(enable ? "Close" : "Open" ); } buttonSnap_.setEnabled(!enable); //toAlbumButton_.setEnabled(!enable); toggleButtonLive_.setIcon(enable ? SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/cancel.png") : SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/camera_go.png")); toggleButtonLive_.setSelected(false); toggleButtonLive_.setText(enable ? "Stop Live" : "Live"); } private void enableLiveModeListeners(boolean enable) { if (enable) { // attach mouse wheel listener to control focus: if (zWheelListener_ == null) zWheelListener_ = new ZWheelListener(core_, this); zWheelListener_.start(getImageWin()); // attach key listener to control the stage and focus: if (xyzKeyListener_ == null) xyzKeyListener_ = new XYZKeyListener(core_, this); xyzKeyListener_.start(getImageWin()); } else { if (zWheelListener_ != null) zWheelListener_.stop(); if (xyzKeyListener_ != null) xyzKeyListener_.stop(); } } public boolean getLiveMode() { return isLiveModeOn(); } public boolean updateImage() { try { if (isLiveModeOn()) { enableLiveMode(false); return true; // nothing to do, just show the last image } if (WindowManager.getCurrentWindow() == null) { return false; } ImagePlus ip = WindowManager.getCurrentImage(); core_.snapImage(); Object img = core_.getImage(); ip.getProcessor().setPixels(img); ip.updateAndRepaintWindow(); if (!isCurrentImageFormatSupported()) { return false; } updateLineProfile(); } catch (Exception e) { ReportingUtils.showError(e); return false; } return true; } public boolean displayImage(final Object pixels) { if (pixels instanceof TaggedImage) { return displayTaggedImage((TaggedImage) pixels, true); } else { return displayImage(pixels, true); } } public boolean displayImage(final Object pixels, boolean wait) { checkSimpleAcquisition(); try { int width = getAcquisition(SIMPLE_ACQ).getWidth(); int height = getAcquisition(SIMPLE_ACQ).getHeight(); int byteDepth = getAcquisition(SIMPLE_ACQ).getByteDepth(); TaggedImage ti = ImageUtils.makeTaggedImage(pixels, 0, 0, 0,0, width, height, byteDepth); simpleDisplay_.getImageCache().putImage(ti); simpleDisplay_.showImage(ti, wait); return true; } catch (Exception ex) { ReportingUtils.showError(ex); return false; } } public boolean displayImageWithStatusLine(Object pixels, String statusLine) { boolean ret = displayImage(pixels); simpleDisplay_.displayStatusLine(statusLine); return ret; } public void displayStatusLine(String statusLine) { ImagePlus ip = WindowManager.getCurrentImage(); if (!(ip.getWindow() instanceof VirtualAcquisitionDisplay.DisplayWindow)) { return; } VirtualAcquisitionDisplay.getDisplay(ip).displayStatusLine(statusLine); } private boolean isCurrentImageFormatSupported() { boolean ret = false; long channels = core_.getNumberOfComponents(); long bpp = core_.getBytesPerPixel(); if (channels > 1 && channels != 4 && bpp != 1) { handleError("Unsupported image format."); } else { ret = true; } return ret; } public void doSnap() { doSnap(false); } public void doSnap(final boolean album) { if (core_.getCameraDevice().length() == 0) { ReportingUtils.showError("No camera configured"); return; } BlockingQueue snapImageQueue = new LinkedBlockingQueue(); try { core_.snapImage(); long c = core_.getNumberOfCameraChannels(); runDisplayThread(snapImageQueue, new DisplayImageRoutine() { public void show(final TaggedImage image) { if (album) { try { addToAlbum(image); } catch (MMScriptException ex) { ReportingUtils.showError(ex); } } else { displayImage(image); } } }); for (int i = 0; i < c; ++i) { TaggedImage img = core_.getTaggedImage(i); img.tags.put("Channels", c); snapImageQueue.put(img); } snapImageQueue.put(TaggedImageQueue.POISON); if (simpleDisplay_ != null) { ImagePlus imgp = simpleDisplay_.getImagePlus(); if (imgp != null) { ImageWindow win = imgp.getWindow(); if (win != null) { win.toFront(); } } } } catch (Exception ex) { ReportingUtils.showError(ex); } } public void normalizeTags(TaggedImage ti) { if (ti != TaggedImageQueue.POISON) { int channel = 0; try { if (ti.tags.has("Multi Camera-CameraChannelIndex")) { channel = ti.tags.getInt("Multi Camera-CameraChannelIndex"); } else if (ti.tags.has("CameraChannelIndex")) { channel = ti.tags.getInt("CameraChannelIndex"); } else if (ti.tags.has("ChannelIndex")) { channel = MDUtils.getChannelIndex(ti.tags); } ti.tags.put("ChannelIndex", channel); ti.tags.put("PositionIndex", 0); ti.tags.put("SliceIndex", 0); ti.tags.put("FrameIndex", 0); } catch (JSONException ex) { ReportingUtils.logError(ex); } } } public boolean displayImage(TaggedImage ti) { normalizeTags(ti); return displayTaggedImage(ti, true); } private boolean displayTaggedImage(TaggedImage ti, boolean update) { try { checkSimpleAcquisition(ti); setCursor(new Cursor(Cursor.WAIT_CURSOR)); ti.tags.put("Summary", getAcquisition(SIMPLE_ACQ).getSummaryMetadata()); addStagePositionToTags(ti); addImage(SIMPLE_ACQ, ti, update, true); } catch (Exception ex) { ReportingUtils.logError(ex); return false; } if (update) { setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); updateLineProfile(); } return true; } public void addStagePositionToTags(TaggedImage ti) throws JSONException { if (gui_.xyStageLabel_.length() > 0) { ti.tags.put("XPositionUm", gui_.staticInfo_.x_); ti.tags.put("YPositionUm", gui_.staticInfo_.y_); } if (gui_.zStageLabel_.length() > 0) { ti.tags.put("ZPositionUm", gui_.staticInfo_.zPos_); } } private void configureBinningCombo() throws Exception { if (cameraLabel_.length() > 0) { ActionListener[] listeners; // binning combo if (comboBinning_.getItemCount() > 0) { comboBinning_.removeAllItems(); } StrVector binSizes = core_.getAllowedPropertyValues( cameraLabel_, MMCoreJ.getG_Keyword_Binning()); listeners = comboBinning_.getActionListeners(); for (int i = 0; i < listeners.length; i++) { comboBinning_.removeActionListener(listeners[i]); } for (int i = 0; i < binSizes.size(); i++) { comboBinning_.addItem(binSizes.get(i)); } comboBinning_.setMaximumRowCount((int) binSizes.size()); if (binSizes.size() == 0) { comboBinning_.setEditable(true); } else { comboBinning_.setEditable(false); } for (int i = 0; i < listeners.length; i++) { comboBinning_.addActionListener(listeners[i]); } } } public void initializeGUI() { try { // establish device roles cameraLabel_ = core_.getCameraDevice(); shutterLabel_ = core_.getShutterDevice(); zStageLabel_ = core_.getFocusDevice(); xyStageLabel_ = core_.getXYStageDevice(); engine_.setZStageDevice(zStageLabel_); configureBinningCombo(); // active shutter combo try { shutters_ = core_.getLoadedDevicesOfType(DeviceType.ShutterDevice); } catch (Exception e) { ReportingUtils.logError(e); } if (shutters_ != null) { String items[] = new String[(int) shutters_.size()]; for (int i = 0; i < shutters_.size(); i++) { items[i] = shutters_.get(i); } GUIUtils.replaceComboContents(shutterComboBox_, items); String activeShutter = core_.getShutterDevice(); if (activeShutter != null) { shutterComboBox_.setSelectedItem(activeShutter); } else { shutterComboBox_.setSelectedItem(""); } } // Autofocus autofocusConfigureButton_.setEnabled(afMgr_.getDevice() != null); autofocusNowButton_.setEnabled(afMgr_.getDevice() != null); // Rebuild stage list in XY PositinList if (posListDlg_ != null) { posListDlg_.rebuildAxisList(); } updateGUI(true); } catch (Exception e) { ReportingUtils.showError(e); } } public String getVersion() { return MMVersion.VERSION_STRING; } private void addPluginToMenu(final PluginItem plugin, Class<?> cl) { // add plugin menu items final JMenuItem newMenuItem = new JMenuItem(); newMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { ReportingUtils.logMessage("Plugin command: " + e.getActionCommand()); plugin.instantiate(); plugin.plugin.show(); } }); newMenuItem.setText(plugin.menuItem); String toolTipDescription = ""; try { // Get this static field from the class implementing MMPlugin. toolTipDescription = (String) cl.getDeclaredField("tooltipDescription").get(null); } catch (SecurityException e) { ReportingUtils.logError(e); toolTipDescription = "Description not available"; } catch (NoSuchFieldException e) { toolTipDescription = "Description not available"; ReportingUtils.logError(cl.getName() + " fails to implement static String tooltipDescription."); } catch (IllegalArgumentException e) { ReportingUtils.logError(e); } catch (IllegalAccessException e) { ReportingUtils.logError(e); } String mrjProp = System.getProperty("mrj.version"); if (mrjProp != null) // running on a mac newMenuItem.setToolTipText(toolTipDescription); else newMenuItem.setToolTipText( TooltipTextMaker.addHTMLBreaksForTooltip(toolTipDescription) ); pluginMenu_.add(newMenuItem); pluginMenu_.validate(); menuBar_.validate(); } public void updateGUI(boolean updateConfigPadStructure) { updateGUI(updateConfigPadStructure, false); } public void updateGUI(boolean updateConfigPadStructure, boolean fromCache) { try { // establish device roles cameraLabel_ = core_.getCameraDevice(); shutterLabel_ = core_.getShutterDevice(); zStageLabel_ = core_.getFocusDevice(); xyStageLabel_ = core_.getXYStageDevice(); afMgr_.refresh(); // camera settings if (isCameraAvailable()) { double exp = core_.getExposure(); textFieldExp_.setText(NumberUtils.doubleToDisplayString(exp)); configureBinningCombo(); String binSize = ""; if (fromCache) { binSize = core_.getPropertyFromCache(cameraLabel_, MMCoreJ.getG_Keyword_Binning()); } else { binSize = core_.getProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning()); } GUIUtils.setComboSelection(comboBinning_, binSize); } if (liveModeTimer_ == null || !liveModeTimer_.isRunning()) { autoShutterCheckBox_.setSelected(core_.getAutoShutter()); boolean shutterOpen = core_.getShutterOpen(); setShutterButton(shutterOpen); if (autoShutterCheckBox_.isSelected()) { toggleButtonShutter_.setEnabled(false); } else { toggleButtonShutter_.setEnabled(true); } } // active shutter combo if (shutters_ != null) { String activeShutter = core_.getShutterDevice(); if (activeShutter != null) { shutterComboBox_.setSelectedItem(activeShutter); } else { shutterComboBox_.setSelectedItem(""); } } // state devices if (updateConfigPadStructure && (configPad_ != null)) { configPad_.refreshStructure(fromCache); // Needed to update read-only properties. May slow things down... if (!fromCache) core_.updateSystemStateCache(); } // update Channel menus in Multi-dimensional acquisition dialog updateChannelCombos(); } catch (Exception e) { ReportingUtils.logError(e); } updateStaticInfo(); updateTitle(); } @Override public boolean okToAcquire() { return !isLiveModeOn(); } @Override public void stopAllActivity() { if (this.acquisitionEngine2010 != null) { this.acquisitionEngine2010.stop(); } enableLiveMode(false); } private boolean cleanupOnClose(boolean calledByImageJ) { // Save config presets if they were changed. if (configChanged_) { Object[] options = {"Yes", "No"}; int n = JOptionPane.showOptionDialog(null, "Save Changed Configuration?", "Micro-Manager", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (n == JOptionPane.YES_OPTION) { saveConfigPresets(); } } if (liveModeTimer_ != null) liveModeTimer_.stop(); // check needed to avoid deadlock if (!calledByImageJ) { if (!WindowManager.closeAllWindows()) { core_.logMessage("Failed to close some windows"); } } if (profileWin_ != null) { removeMMBackgroundListener(profileWin_); profileWin_.dispose(); } if (scriptPanel_ != null) { removeMMBackgroundListener(scriptPanel_); scriptPanel_.closePanel(); } if (propertyBrowser_ != null) { removeMMBackgroundListener(propertyBrowser_); propertyBrowser_.dispose(); } if (acqControlWin_ != null) { removeMMBackgroundListener(acqControlWin_); acqControlWin_.close(); } if (engine_ != null) { engine_.shutdown(); } if (afMgr_ != null) { afMgr_.closeOptionsDialog(); } // dispose plugins for (int i = 0; i < plugins_.size(); i++) { MMPlugin plugin = (MMPlugin) plugins_.get(i).plugin; if (plugin != null) { plugin.dispose(); } } synchronized (shutdownLock_) { try { if (core_ != null){ core_.delete(); core_ = null; } } catch (Exception err) { ReportingUtils.showError(err); } } return true; } private void saveSettings() { Rectangle r = this.getBounds(); mainPrefs_.putInt(MAIN_FRAME_X, r.x); mainPrefs_.putInt(MAIN_FRAME_Y, r.y); mainPrefs_.putInt(MAIN_FRAME_WIDTH, r.width); mainPrefs_.putInt(MAIN_FRAME_HEIGHT, r.height); mainPrefs_.putInt(MAIN_FRAME_DIVIDER_POS, this.splitPane_.getDividerLocation()); mainPrefs_.put(OPEN_ACQ_DIR, openAcqDirectory_); mainPrefs_.put(MAIN_SAVE_METHOD, ImageUtils.getImageStorageClass().getName()); // save field values from the main window // NOTE: automatically restoring these values on startup may cause // problems mainPrefs_.put(MAIN_EXPOSURE, textFieldExp_.getText()); // NOTE: do not save auto shutter state if (afMgr_ != null && afMgr_.getDevice() != null) { mainPrefs_.put(AUTOFOCUS_DEVICE, afMgr_.getDevice().getDeviceName()); } } private void loadConfiguration() { File f = FileDialogs.openFile(this, "Load a config file",MM_CONFIG_FILE); if (f != null) { sysConfigFile_ = f.getAbsolutePath(); configChanged_ = false; setConfigSaveButtonStatus(configChanged_); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); loadSystemConfiguration(); } } public synchronized void closeSequence(boolean calledByImageJ) { if (!this.isRunning()) { if (core_ != null) { core_.logMessage("MMStudioMainFrame::closeSequence called while running_ is false"); } this.dispose(); return; } if (engine_ != null && engine_.isAcquisitionRunning()) { int result = JOptionPane.showConfirmDialog( this, "Acquisition in progress. Are you sure you want to exit and discard all data?", "Micro-Manager", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE); if (result == JOptionPane.NO_OPTION) { return; } } stopAllActivity(); if (!cleanupOnClose(calledByImageJ)) return; running_ = false; saveSettings(); try { configPad_.saveSettings(); options_.saveSettings(); hotKeys_.saveSettings(); } catch (NullPointerException e) { if (core_ != null) this.logError(e); } // disposing sometimes hangs ImageJ! // this.dispose(); if (options_.closeOnExit_) { if (!runsAsPlugin_) { System.exit(0); } else { ImageJ ij = IJ.getInstance(); if (ij != null) { ij.quit(); } } } else { this.dispose(); } } public void applyContrastSettings(ContrastSettings contrast8, ContrastSettings contrast16) { ImagePlus img = WindowManager.getCurrentImage(); if (img == null|| VirtualAcquisitionDisplay.getDisplay(img) == null ) return; if (img.getBytesPerPixel() == 1) VirtualAcquisitionDisplay.getDisplay(img).setChannelContrast(0, contrast8.min, contrast8.max, contrast8.gamma); else VirtualAcquisitionDisplay.getDisplay(img).setChannelContrast(0, contrast16.min, contrast16.max, contrast16.gamma); } @Override public ContrastSettings getContrastSettings() { ImagePlus img = WindowManager.getCurrentImage(); if (img == null || VirtualAcquisitionDisplay.getDisplay(img) == null ) return null; return VirtualAcquisitionDisplay.getDisplay(img).getChannelContrastSettings(0); } public boolean is16bit() { ImagePlus ip = WindowManager.getCurrentImage(); if (ip != null && ip.getProcessor() instanceof ShortProcessor) { return true; } return false; } public boolean isRunning() { return running_; } /** * Executes the beanShell script. This script instance only supports * commands directed to the core object. */ private void executeStartupScript() { // execute startup script File f = new File(startupScriptFile_); if (startupScriptFile_.length() > 0 && f.exists()) { WaitDialog waitDlg = new WaitDialog( "Executing startup script, please wait..."); waitDlg.showDialog(); Interpreter interp = new Interpreter(); try { // insert core object only interp.set(SCRIPT_CORE_OBJECT, core_); interp.set(SCRIPT_ACQENG_OBJECT, engine_); interp.set(SCRIPT_GUI_OBJECT, this); // read text file and evaluate interp.eval(TextUtils.readTextFile(startupScriptFile_)); } catch (IOException exc) { ReportingUtils.showError(exc, "Unable to read the startup script (" + startupScriptFile_ + ")."); } catch (EvalError exc) { ReportingUtils.showError(exc); } finally { waitDlg.closeDialog(); } } else { if (startupScriptFile_.length() > 0) ReportingUtils.logMessage("Startup script file ("+startupScriptFile_+") not present."); } } /** * Loads system configuration from the cfg file. */ private boolean loadSystemConfiguration() { boolean result = true; saveMRUConfigFiles(); final WaitDialog waitDlg = new WaitDialog( "Loading system configuration, please wait..."); waitDlg.setAlwaysOnTop(true); waitDlg.showDialog(); this.setEnabled(false); try { if (sysConfigFile_.length() > 0) { GUIUtils.preventDisplayAdapterChangeExceptions(); core_.waitForSystem(); ignorePropertyChanges_ = true; core_.loadSystemConfiguration(sysConfigFile_); ignorePropertyChanges_ = false; GUIUtils.preventDisplayAdapterChangeExceptions(); } } catch (final Exception err) { GUIUtils.preventDisplayAdapterChangeExceptions(); ReportingUtils.showError(err); result = false; } finally { waitDlg.closeDialog(); } setEnabled(true); initializeGUI(); updateSwitchConfigurationMenu(); FileDialogs.storePath(MM_CONFIG_FILE, new File(sysConfigFile_)); return result; } private void saveMRUConfigFiles() { if (0 < sysConfigFile_.length()) { if (MRUConfigFiles_.contains(sysConfigFile_)) { MRUConfigFiles_.remove(sysConfigFile_); } if (maxMRUCfgs_ <= MRUConfigFiles_.size()) { MRUConfigFiles_.remove(maxMRUCfgs_ - 1); } MRUConfigFiles_.add(0, sysConfigFile_); // save the MRU list to the preferences for (Integer icfg = 0; icfg < MRUConfigFiles_.size(); ++icfg) { String value = ""; if (null != MRUConfigFiles_.get(icfg)) { value = MRUConfigFiles_.get(icfg).toString(); } mainPrefs_.put(CFGFILE_ENTRY_BASE + icfg.toString(), value); } } } private void loadMRUConfigFiles() { sysConfigFile_ = mainPrefs_.get(SYSTEM_CONFIG_FILE, sysConfigFile_); // startupScriptFile_ = mainPrefs_.get(STARTUP_SCRIPT_FILE, // startupScriptFile_); MRUConfigFiles_ = new ArrayList<String>(); for (Integer icfg = 0; icfg < maxMRUCfgs_; ++icfg) { String value = ""; value = mainPrefs_.get(CFGFILE_ENTRY_BASE + icfg.toString(), value); if (0 < value.length()) { File ruFile = new File(value); if (ruFile.exists()) { if (!MRUConfigFiles_.contains(value)) { MRUConfigFiles_.add(value); } } } } // initialize MRU list from old persistant data containing only SYSTEM_CONFIG_FILE if (0 < sysConfigFile_.length()) { if (!MRUConfigFiles_.contains(sysConfigFile_)) { // in case persistant data is inconsistent if (maxMRUCfgs_ <= MRUConfigFiles_.size()) { MRUConfigFiles_.remove(maxMRUCfgs_ - 1); } MRUConfigFiles_.add(0, sysConfigFile_); } } } /** * Opens Acquisition dialog. */ private void openAcqControlDialog() { try { if (acqControlWin_ == null) { acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, this, options_); } if (acqControlWin_.isActive()) { acqControlWin_.setTopPosition(); } acqControlWin_.setVisible(true); acqControlWin_.repaint(); // TODO: this call causes a strange exception the first time the // dialog is created // something to do with the order in which combo box creation is // performed // acqControlWin_.updateGroupsCombo(); } catch (Exception exc) { ReportingUtils.showError(exc, "\nAcquistion window failed to open due to invalid or corrupted settings.\n" + "Try resetting registry settings to factory defaults (Menu Tools|Options)."); } } /** * Opens a dialog to record stage positions */ @Override public void showXYPositionList() { if (posListDlg_ == null) { posListDlg_ = new PositionListDlg(core_, this, posList_, options_); } posListDlg_.setVisible(true); } private void updateChannelCombos() { if (this.acqControlWin_ != null) { this.acqControlWin_.updateChannelAndGroupCombo(); } } @Override public void setConfigChanged(boolean status) { configChanged_ = status; setConfigSaveButtonStatus(configChanged_); } /** * Returns the current background color * @return current background color */ @Override public Color getBackgroundColor() { return guiColors_.background.get((options_.displayBackground_)); } /* * Changes background color of this window and all other MM windows */ @Override public void setBackgroundStyle(String backgroundType) { setBackground(guiColors_.background.get((backgroundType))); paint(MMStudioMainFrame.this.getGraphics()); // sets background of all registered Components for (Component comp:MMFrames_) { if (comp != null) comp.setBackground(guiColors_.background.get(backgroundType)); } } @Override public String getBackgroundStyle() { return options_.displayBackground_; } // Scripting interface private class ExecuteAcq implements Runnable { public ExecuteAcq() { } @Override public void run() { if (acqControlWin_ != null) { acqControlWin_.runAcquisition(); } } } private void testForAbortRequests() throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) { throw new MMScriptException("Script interrupted by the user!"); } } } @Override public void startAcquisition() throws MMScriptException { testForAbortRequests(); SwingUtilities.invokeLater(new ExecuteAcq()); } @Override public String runAcquisition() throws MMScriptException { if (SwingUtilities.isEventDispatchThread()) { throw new MMScriptException("Acquisition can not be run from this (EDT) thread"); } testForAbortRequests(); if (acqControlWin_ != null) { String name = acqControlWin_.runAcquisition(); try { while (acqControlWin_.isAcquisitionRunning()) { Thread.sleep(50); } } catch (InterruptedException e) { ReportingUtils.showError(e); } return name; } else { throw new MMScriptException( "Acquisition setup window must be open for this command to work."); } } @Override public String runAcquisition(String name, String root) throws MMScriptException { testForAbortRequests(); if (acqControlWin_ != null) { String acqName = acqControlWin_.runAcquisition(name, root); try { while (acqControlWin_.isAcquisitionRunning()) { Thread.sleep(100); } // ensure that the acquisition has finished. // This does not seem to work, needs something better MMAcquisition acq = acqMgr_.getAcquisition(acqName); boolean finished = false; while (!finished) { ImageCache imCache = acq.getImageCache(); if (imCache != null) { if (imCache.isFinished()) { finished = true; } else { Thread.sleep(100); } } } } catch (InterruptedException e) { ReportingUtils.showError(e); } return acqName; } else { throw new MMScriptException( "Acquisition setup window must be open for this command to work."); } } @Override public String runAcqusition(String name, String root) throws MMScriptException { return runAcquisition(name, root); } /** * Loads acquisition settings from file * @param path file containing previously saved acquisition settings * @throws MMScriptException */ @Override public void loadAcquisition(String path) throws MMScriptException { testForAbortRequests(); try { engine_.shutdown(); // load protocol if (acqControlWin_ != null) { acqControlWin_.loadAcqSettingsFromFile(path); } } catch (Exception ex) { throw new MMScriptException(ex.getMessage()); } } @Override public void setPositionList(PositionList pl) throws MMScriptException { testForAbortRequests(); // use serialization to clone the PositionList object posList_ = pl; // PositionList.newInstance(pl); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (posListDlg_ != null) { posListDlg_.setPositionList(posList_); engine_.setPositionList(posList_); } } }); } @Override public PositionList getPositionList() throws MMScriptException { testForAbortRequests(); // use serialization to clone the PositionList object return posList_; //PositionList.newInstance(posList_); } @Override public void sleep(long ms) throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) { throw new MMScriptException("Script interrupted by the user!"); } scriptPanel_.sleep(ms); } } @Override public String getUniqueAcquisitionName(String stub) { return acqMgr_.getUniqueAcquisitionName(stub); } /** * @deprecated -- this function was never implemented. getAcquisition(String name) should * be used instead */ @Override public MMAcquisition getCurrentAcquisition() { return null; // if none available } @Override public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, int nrPositions) throws MMScriptException { this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, nrPositions, true, false); } @Override public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices) throws MMScriptException { openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0); } @Override public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, int nrPositions, boolean show) throws MMScriptException { this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, nrPositions, show, false); } @Override public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, boolean show) throws MMScriptException { this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, false); } @Override public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, int nrPositions, boolean show, boolean virtual) throws MMScriptException { acqMgr_.openAcquisition(name, rootDir, show, virtual); MMAcquisition acq = acqMgr_.getAcquisition(name); acq.setDimensions(nrFrames, nrChannels, nrSlices, nrPositions); } @Override public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, boolean show, boolean virtual) throws MMScriptException { this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, virtual); } public String createAcquisition(JSONObject summaryMetadata, boolean diskCached) { return createAcquisition(summaryMetadata, diskCached, false); } public String createAcquisition(JSONObject summaryMetadata, boolean diskCached, boolean displayOff) { return acqMgr_.createAcquisition(summaryMetadata, diskCached, engine_, displayOff); } private void openAcquisitionSnap(String name, String rootDir, boolean show) throws MMScriptException { /* MMAcquisition acq = acqMgr_.openAcquisitionSnap(name, rootDir, this, show); acq.setDimensions(0, 1, 1, 1); try { // acq.getAcqData().setPixelSizeUm(core_.getPixelSizeUm()); acq.setProperty(SummaryKeys.IMAGE_PIXEL_SIZE_UM, String.valueOf(core_.getPixelSizeUm())); } catch (Exception e) { ReportingUtils.showError(e); } * */ } @Override public void initializeSimpleAcquisition(String name, int width, int height, int byteDepth, int bitDepth, int multiCamNumCh) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(name); acq.setImagePhysicalDimensions(width, height, byteDepth, bitDepth, multiCamNumCh); acq.initializeSimpleAcq(); } @Override public void initializeAcquisition(String name, int width, int height, int depth) throws MMScriptException { initializeAcquisition(name,width,height,depth,8*depth); } @Override public void initializeAcquisition(String name, int width, int height, int byteDepth, int bitDepth) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(name); //number of multi-cam cameras is set to 1 here for backwards compatibility //might want to change this later acq.setImagePhysicalDimensions(width, height, byteDepth, bitDepth,1); acq.initialize(); } @Override public int getAcquisitionImageWidth(String acqName) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(acqName); return acq.getWidth(); } @Override public int getAcquisitionImageHeight(String acqName) throws MMScriptException{ MMAcquisition acq = acqMgr_.getAcquisition(acqName); return acq.getHeight(); } @Override public int getAcquisitionImageBitDepth(String acqName) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(acqName); return acq.getBitDepth(); } @Override public int getAcquisitionImageByteDepth(String acqName) throws MMScriptException{ MMAcquisition acq = acqMgr_.getAcquisition(acqName); return acq.getByteDepth(); } @Override public int getAcquisitionMultiCamNumChannels(String acqName) throws MMScriptException{ MMAcquisition acq = acqMgr_.getAcquisition(acqName); return acq.getMultiCameraNumChannels(); } @Override public Boolean acquisitionExists(String name) { return acqMgr_.acquisitionExists(name); } @Override public void closeAcquisition(String name) throws MMScriptException { acqMgr_.closeAcquisition(name); } /** * @deprecated use closeAcquisitionWindow instead */ @Override public void closeAcquisitionImage5D(String acquisitionName) throws MMScriptException { acqMgr_.closeImageWindow(acquisitionName); } @Override public void closeAcquisitionWindow(String acquisitionName) throws MMScriptException { acqMgr_.closeImageWindow(acquisitionName); } /** * Since Burst and normal acquisition are now carried out by the same engine, * loadBurstAcquistion simply calls loadAcquisition * t * @param path - path to file specifying acquisition settings */ @Override public void loadBurstAcquisition(String path) throws MMScriptException { this.loadAcquisition(path); } @Override public void refreshGUI() { updateGUI(true); } @Override public void refreshGUIFromCache() { updateGUI(true, true); } public void setAcquisitionProperty(String acqName, String propertyName, String value) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(acqName); acq.setProperty(propertyName, value); } public void setAcquisitionSystemState(String acqName, JSONObject md) throws MMScriptException { // acqMgr_.getAcquisition(acqName).setSystemState(md); setAcquisitionSummary(acqName, md); } public void setAcquisitionSummary(String acqName, JSONObject md) throws MMScriptException { acqMgr_.getAcquisition(acqName).setSummaryProperties(md); } public void setImageProperty(String acqName, int frame, int channel, int slice, String propName, String value) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(acqName); acq.setProperty(frame, channel, slice, propName, value); } public void snapAndAddImage(String name, int frame, int channel, int slice) throws MMScriptException { snapAndAddImage(name, frame, channel, slice, 0); } public void snapAndAddImage(String name, int frame, int channel, int slice, int position) throws MMScriptException { TaggedImage ti; try { if (core_.isSequenceRunning()) { ti = core_.getLastTaggedImage(); } else { core_.snapImage(); ti = core_.getTaggedImage(); } ti.tags.put("ChannelIndex", channel); ti.tags.put("FrameIndex", frame); ti.tags.put("SliceIndex", slice); ti.tags.put("PositionIndex", position); MMAcquisition acq = acqMgr_.getAcquisition(name); if (!acq.isInitialized()) { long width = core_.getImageWidth(); long height = core_.getImageHeight(); long depth = core_.getBytesPerPixel(); long bitDepth = core_.getImageBitDepth(); int multiCamNumCh = (int) core_.getNumberOfCameraChannels(); acq.setImagePhysicalDimensions((int) width, (int) height, (int) depth, (int) bitDepth, multiCamNumCh); acq.initialize(); } if (acq.getPositions() > 1) { ti.tags.put("PositionName", "Pos" + position); } addImage(name, ti, true); } catch (Exception e) { ReportingUtils.showError(e); } } public String getCurrentAlbum() { return acqMgr_.getCurrentAlbum(); } public String createNewAlbum() { return acqMgr_.createNewAlbum(); } public void appendImage(String name, TaggedImage taggedImg) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(name); int f = 1 + acq.getLastAcquiredFrame(); try { MDUtils.setFrameIndex(taggedImg.tags, f); } catch (JSONException e) { throw new MMScriptException("Unable to set the frame index."); } acq.insertTaggedImage(taggedImg, f, 0, 0); } public void addToAlbum(TaggedImage taggedImg) throws MMScriptException { addToAlbum(taggedImg, null); } public void addToAlbum(TaggedImage taggedImg, JSONObject displaySettings) throws MMScriptException { normalizeTags(taggedImg); acqMgr_.addToAlbum(taggedImg,displaySettings); } public void addImage(String name, Object img, int frame, int channel, int slice) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(name); acq.insertImage(img, frame, channel, slice); } public void addImage(String name, TaggedImage taggedImg) throws MMScriptException { acqMgr_.getAcquisition(name).insertImage(taggedImg); } public void addImage(String name, TaggedImage taggedImg, boolean updateDisplay) throws MMScriptException { acqMgr_.getAcquisition(name).insertImage(taggedImg, updateDisplay); } public void addImage(String name, TaggedImage taggedImg, boolean updateDisplay, boolean waitForDisplay) throws MMScriptException { acqMgr_.getAcquisition(name).insertImage(taggedImg, updateDisplay, waitForDisplay); } public void addImage(String name, TaggedImage taggedImg, int frame, int channel, int slice, int position) throws MMScriptException { try { acqMgr_.getAcquisition(name).insertImage(taggedImg, frame, channel, slice, position); } catch (JSONException ex) { ReportingUtils.showError(ex); } } public void addImage(String name, TaggedImage taggedImg, int frame, int channel, int slice, int position, boolean updateDisplay) throws MMScriptException { try { acqMgr_.getAcquisition(name).insertImage(taggedImg, frame, channel, slice, position, updateDisplay); } catch (JSONException ex) { ReportingUtils.showError(ex); } } public void addImage(String name, TaggedImage taggedImg, int frame, int channel, int slice, int position, boolean updateDisplay, boolean waitForDisplay) throws MMScriptException { try { acqMgr_.getAcquisition(name).insertImage(taggedImg, frame, channel, slice, position, updateDisplay, waitForDisplay); } catch (JSONException ex) { ReportingUtils.showError(ex); } } public void closeAllAcquisitions() { acqMgr_.closeAll(); } public String[] getAcquisitionNames() { return acqMgr_.getAcqusitionNames(); } public MMAcquisition getAcquisition(String name) throws MMScriptException { return acqMgr_.getAcquisition(name); } private class ScriptConsoleMessage implements Runnable { String msg_; public ScriptConsoleMessage(String text) { msg_ = text; } public void run() { if (scriptPanel_ != null) scriptPanel_.message(msg_); } } public void message(String text) throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) { throw new MMScriptException("Script interrupted by the user!"); } SwingUtilities.invokeLater(new ScriptConsoleMessage(text)); } } public void clearMessageWindow() throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) { throw new MMScriptException("Script interrupted by the user!"); } scriptPanel_.clearOutput(); } } public void clearOutput() throws MMScriptException { clearMessageWindow(); } public void clear() throws MMScriptException { clearMessageWindow(); } public void setChannelContrast(String title, int channel, int min, int max) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(title); acq.setChannelContrast(channel, min, max); } public void setChannelName(String title, int channel, String name) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(title); acq.setChannelName(channel, name); } public void setChannelColor(String title, int channel, Color color) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(title); acq.setChannelColor(channel, color.getRGB()); } public void setContrastBasedOnFrame(String title, int frame, int slice) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(title); acq.setContrastBasedOnFrame(frame, slice); } public void setStagePosition(double z) throws MMScriptException { try { core_.setPosition(core_.getFocusDevice(),z); core_.waitForDevice(core_.getFocusDevice()); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } public void setRelativeStagePosition(double z) throws MMScriptException { try { core_.setRelativePosition(core_.getFocusDevice(), z); core_.waitForDevice(core_.getFocusDevice()); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } public void setXYStagePosition(double x, double y) throws MMScriptException { try { core_.setXYPosition(core_.getXYStageDevice(), x, y); core_.waitForDevice(core_.getXYStageDevice()); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } public void setRelativeXYStagePosition(double x, double y) throws MMScriptException { try { core_.setRelativeXYPosition(core_.getXYStageDevice(), x, y); core_.waitForDevice(core_.getXYStageDevice()); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } public Point2D.Double getXYStagePosition() throws MMScriptException { String stage = core_.getXYStageDevice(); if (stage.length() == 0) { throw new MMScriptException("XY Stage device is not available"); } double x[] = new double[1]; double y[] = new double[1]; try { core_.getXYPosition(stage, x, y); Point2D.Double pt = new Point2D.Double(x[0], y[0]); return pt; } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } public String getXYStageName() { return core_.getXYStageDevice(); } public void setXYOrigin(double x, double y) throws MMScriptException { String xyStage = core_.getXYStageDevice(); try { core_.setAdapterOriginXY(xyStage, x, y); } catch (Exception e) { throw new MMScriptException(e); } } public AcquisitionEngine getAcquisitionEngine() { return engine_; } public String installPlugin(Class<?> cl) { String className = cl.getSimpleName(); String msg = className + " module loaded."; try { for (PluginItem plugin : plugins_) { if (plugin.className.contentEquals(className)) { return className + " already loaded."; } } PluginItem pi = new PluginItem(); pi.className = className; try { // Get this static field from the class implementing MMPlugin. pi.menuItem = (String) cl.getDeclaredField("menuName").get(null); } catch (SecurityException e) { ReportingUtils.logError(e); pi.menuItem = className; } catch (NoSuchFieldException e) { pi.menuItem = className; ReportingUtils.logError(className + " fails to implement static String menuName."); } catch (IllegalArgumentException e) { ReportingUtils.logError(e); } catch (IllegalAccessException e) { ReportingUtils.logError(e); } if (pi.menuItem == null) { pi.menuItem = className; //core_.logMessage(className + " fails to implement static String menuName."); } pi.menuItem = pi.menuItem.replace("_", " "); pi.pluginClass = cl; plugins_.add(pi); final PluginItem pi2 = pi; final Class<?> cl2 = cl; SwingUtilities.invokeLater( new Runnable() { public void run() { addPluginToMenu(pi2, cl2); } }); } catch (NoClassDefFoundError e) { msg = className + " class definition not found."; ReportingUtils.logError(e, msg); } return msg; } public String installPlugin(String className, String menuName) { String msg = "installPlugin(String className, String menuName) is deprecated. Use installPlugin(String className) instead."; core_.logMessage(msg); installPlugin(className); return msg; } public String installPlugin(String className) { String msg = ""; try { Class clazz = Class.forName(className); return installPlugin(clazz); } catch (ClassNotFoundException e) { msg = className + " plugin not found."; ReportingUtils.logError(e, msg); return msg; } } public String installAutofocusPlugin(String className) { try { return installAutofocusPlugin(Class.forName(className)); } catch (ClassNotFoundException e) { String msg = "Internal error: AF manager not instantiated."; ReportingUtils.logError(e, msg); return msg; } } public String installAutofocusPlugin(Class<?> autofocus) { String msg = autofocus.getSimpleName() + " module loaded."; if (afMgr_ != null) { try { afMgr_.refresh(); } catch (MMException e) { msg = e.getMessage(); ReportingUtils.logError(e); } afMgr_.setAFPluginClassName(autofocus.getSimpleName()); } else { msg = "Internal error: AF manager not instantiated."; } return msg; } public CMMCore getCore() { return core_; } public IAcquisitionEngine2010 getAcquisitionEngine2010() { try { acquisitionEngine2010LoadingThread.join(); if (acquisitionEngine2010 == null) { acquisitionEngine2010 = (IAcquisitionEngine2010) acquisitionEngine2010Class.getConstructors()[0].newInstance(this); } return acquisitionEngine2010; } catch (Exception e) { ReportingUtils.logError(e); return null; } } public void snapAndAddToImage5D() { if (core_.getCameraDevice().length() == 0) { ReportingUtils.showError("No camera configured"); return; } try { if (this.isLiveModeOn()) { copyFromLiveModeToAlbum(simpleDisplay_); } else { doSnap(true); } } catch (Exception ex) { ReportingUtils.logError(ex); } } public void setAcquisitionEngine(AcquisitionEngine eng) { engine_ = eng; } public void suspendLiveMode() { liveModeSuspended_ = isLiveModeOn(); enableLiveMode(false); } public void resumeLiveMode() { if (liveModeSuspended_) { enableLiveMode(true); } } public Autofocus getAutofocus() { return afMgr_.getDevice(); } public void showAutofocusDialog() { if (afMgr_.getDevice() != null) { afMgr_.showOptionsDialog(); } } public AutofocusManager getAutofocusManager() { return afMgr_; } public void selectConfigGroup(String groupName) { configPad_.setGroup(groupName); } public String regenerateDeviceList() { Cursor oldc = Cursor.getDefaultCursor(); Cursor waitc = new Cursor(Cursor.WAIT_CURSOR); setCursor(waitc); StringBuffer resultFile = new StringBuffer(); MicroscopeModel.generateDeviceListFile(resultFile, core_); //MicroscopeModel.generateDeviceListFile(); setCursor(oldc); return resultFile.toString(); } public void setImageSavingFormat(Class imageSavingClass) throws MMScriptException { if (! (imageSavingClass.equals(TaggedImageStorageDiskDefault.class) || imageSavingClass.equals(TaggedImageStorageMultipageTiff.class))) { throw new MMScriptException("Unrecognized saving class"); } ImageUtils.setImageStorageClass(imageSavingClass); if (acqControlWin_ != null) { acqControlWin_.updateSavingTypeButtons(); } } private void loadPlugins() { afMgr_ = new AutofocusManager(this); ArrayList<Class<?>> pluginClasses = new ArrayList<Class<?>>(); ArrayList<Class<?>> autofocusClasses = new ArrayList<Class<?>>(); List<Class<?>> classes; try { long t1 = System.currentTimeMillis(); classes = JavaUtils.findClasses(new File("mmplugins"), 2); //System.out.println("findClasses: " + (System.currentTimeMillis() - t1)); //System.out.println(classes.size()); for (Class<?> clazz : classes) { for (Class<?> iface : clazz.getInterfaces()) { //core_.logMessage("interface found: " + iface.getName()); if (iface == MMPlugin.class) { pluginClasses.add(clazz); } } } classes = JavaUtils.findClasses(new File("mmautofocus"), 2); for (Class<?> clazz : classes) { for (Class<?> iface : clazz.getInterfaces()) { //core_.logMessage("interface found: " + iface.getName()); if (iface == Autofocus.class) { autofocusClasses.add(clazz); } } } } catch (ClassNotFoundException e1) { ReportingUtils.logError(e1); } for (Class<?> plugin : pluginClasses) { try { ReportingUtils.logMessage("Attempting to install plugin " + plugin.getName()); installPlugin(plugin); } catch (Exception e) { ReportingUtils.logError(e, "Failed to install the \"" + plugin.getName() + "\" plugin ."); } } for (Class<?> autofocus : autofocusClasses) { try { ReportingUtils.logMessage("Attempting to install autofocus plugin " + autofocus.getName()); installAutofocusPlugin(autofocus.getName()); } catch (Exception e) { ReportingUtils.logError("Failed to install the \"" + autofocus.getName() + "\" autofocus plugin."); } } } public void logMessage(String msg) { ReportingUtils.logMessage(msg); } public void showMessage(String msg) { ReportingUtils.showMessage(msg); } public void logError(Exception e, String msg) { ReportingUtils.logError(e, msg); } public void logError(Exception e) { ReportingUtils.logError(e); } public void logError(String msg) { ReportingUtils.logError(msg); } public void showError(Exception e, String msg) { ReportingUtils.showError(e, msg); } public void showError(Exception e) { ReportingUtils.showError(e); } public void showError(String msg) { ReportingUtils.showError(msg); } private void runHardwareWizard() { try { if (configChanged_) { Object[] options = {"Yes", "No"}; int n = JOptionPane.showOptionDialog(null, "Save Changed Configuration?", "Micro-Manager", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (n == JOptionPane.YES_OPTION) { saveConfigPresets(); } configChanged_ = false; } boolean liveRunning = false; if (isLiveModeOn()) { liveRunning = true; enableLiveMode(false); } // unload all devices before starting configurator core_.reset(); GUIUtils.preventDisplayAdapterChangeExceptions(); // run Configurator ConfiguratorDlg2 cfg2 = null; try { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); cfg2 = new ConfiguratorDlg2(core_, sysConfigFile_); } finally { setCursor(Cursor.getDefaultCursor()); } cfg2.setVisible(true); GUIUtils.preventDisplayAdapterChangeExceptions(); // re-initialize the system with the new configuration file sysConfigFile_ = cfg2.getFileName(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); loadSystemConfiguration(); GUIUtils.preventDisplayAdapterChangeExceptions(); if (liveRunning) { enableLiveMode(liveRunning); } } catch (Exception e) { ReportingUtils.showError(e); return; } } } class BooleanLock extends Object { private boolean value; public BooleanLock(boolean initialValue) { value = initialValue; } public BooleanLock() { this(false); } public synchronized void setValue(boolean newValue) { if (newValue != value) { value = newValue; notifyAll(); } } public synchronized boolean waitToSetTrue(long msTimeout) throws InterruptedException { boolean success = waitUntilFalse(msTimeout); if (success) { setValue(true); } return success; } public synchronized boolean waitToSetFalse(long msTimeout) throws InterruptedException { boolean success = waitUntilTrue(msTimeout); if (success) { setValue(false); } return success; } public synchronized boolean isTrue() { return value; } public synchronized boolean isFalse() { return !value; } public synchronized boolean waitUntilTrue(long msTimeout) throws InterruptedException { return waitUntilStateIs(true, msTimeout); } public synchronized boolean waitUntilFalse(long msTimeout) throws InterruptedException { return waitUntilStateIs(false, msTimeout); } public synchronized boolean waitUntilStateIs( boolean state, long msTimeout) throws InterruptedException { if (msTimeout == 0L) { while (value != state) { wait(); } return true; } long endTime = System.currentTimeMillis() + msTimeout; long msRemaining = msTimeout; while ((value != state) && (msRemaining > 0L)) { wait(msRemaining); msRemaining = endTime - System.currentTimeMillis(); } return (value == state); } }
package com.thaiopensource.util; public abstract class Utf16 { // 110110XX XXXXXX 110111XX XXXXXX static public boolean isSurrogate(char c) { return (c & 0xF800) == 0xD800; } static public boolean isSurrogate(int c) { return c >= 0 && c <= 0xFFFF && isSurrogate((char)c); } static public boolean isSurrogate1(char c) { return (c & 0xFC00) == 0xD800; } static public boolean isSurrogate2(char c) { return (c & 0xFC00) == 0xDC00; } static public int scalarValue(char c1, char c2) { return (((c1 & 0x3FF) << 10) | (c2 & 0x3FF)) + 0x10000; } static public char surrogate1(int c) { return (char)(((c - 0x10000) >> 10) | 0xD800); } static public char surrogate2(int c) { return (char)(((c - 0x10000) & 0x3FF) | 0xDC00); } }
package thredds.dqc.server; import thredds.servlet.ServletUtil; import thredds.servlet.AbstractServlet; import thredds.servlet.ThreddsConfig; import thredds.servlet.UsageLog; import thredds.catalog.InvCatalogFactory; import thredds.catalog.InvCatalogImpl; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.Iterator; /** * Servlet for handling DQC requests. * To implement a DQC request handler specific to your data and DQC document, * you need to write your own DQC request handler by extending the abstract * class <tt>DqcHandler</tt>. * * @see thredds.dqc.server.DqcHandler */ public class DqcServlet extends AbstractServlet { private boolean allow; private File dqcRootPath; private File dqcContentPath, dqcConfigPath; private String configFileName; private DqcServletConfig mainConfig = null; private String servletName = "dqcServlet"; private String dqcDocDirName = "doc"; private String dqcConfigDirName = "config"; private String dqcCatalog = "catalog.xml"; * GET /doc/* rootPath/dqcServlet/docs/* * GET "" redirect to "/" * GET / Create HTML doc on the fly that points to /catalog.xml and * has other information, e.g., links to documentation and THREDDS * servlet top level information. * GET /catalog.xml Catalog that reflects datasets available here. * GET /<dqcHandlerName>.xml * DQC document for the DqcHandler named. * GET /<dqcHandlerName>* * Contents specific to each DqcHandler. */ protected String getPath() { return ( servletName + "/" ); } protected void makeDebugActions() { } /** Initialize the servlet. */ public void init() throws javax.servlet.ServletException { super.init(); this.allow = ThreddsConfig.getBoolean( "DqcService.allow", false ); if ( ! this.allow ) { String msg = "DqcServlet not enabled in threddsConfig.xml."; log.info( "init(): " + msg ); log.info( "init(): " + UsageLog.closingMessageNonRequestContext() ); return; } // Get various paths and file names. this.dqcRootPath = new File( ServletUtil.getRootPath(), this.servletName); this.dqcContentPath = new File( this.contentPath ); this.dqcConfigPath = new File( this.dqcContentPath, this.dqcConfigDirName ); this.configFileName = this.getInitParameter( "configFile"); // Some debug info. log.debug( "init(): dqc root path = " + this.dqcRootPath.toString() ); log.debug( "init(): dqc content path = " + this.dqcContentPath.toString() ); log.debug( "init(): dqc config path = " + this.dqcConfigPath.toString() ); log.debug( "init(): config file = " + this.configFileName ); // Make sure config directory exists. If not, create. if ( ! this.dqcConfigPath.exists() ) { if ( ! this.dqcConfigPath.mkdirs()) { this.allow = false; log.warn( "init(): DqcServlet disabled - failed to create config directory." ); log.info( "init(): " + UsageLog.closingMessageNonRequestContext() ); return; } } // Make sure config file exists. If not, create. File configFile = new File( this.dqcConfigPath, this.configFileName ); if ( ! configFile.exists() ) { boolean b = false; try { b = configFile.createNewFile(); } catch ( IOException e ) { this.allow = false; log.warn( "init(): DqcServlet disabled - I/O error while creating config file." ); log.info( "init(): " + UsageLog.closingMessageNonRequestContext() ); return; } if ( ! b ) { this.allow = false; log.warn( "init(): DqcServlet disabled - failed to create config file." ); log.info( "init(): " + UsageLog.closingMessageNonRequestContext() ); return; } // Write blank config file. Yuck!!! if ( ! this.writeEmptyConfigDocToFile( configFile )) { this.allow = false; log.warn( "init(): DqcServlet disabled - failed to write empty config file." ); log.info( "init(): " + UsageLog.closingMessageNonRequestContext() ); return; } } try { this.mainConfig = this.readInConfigDoc(); } catch ( java.io.IOException e ) { String tmpMsg = "IOException thrown while reading DqcServlet config: " + e.getMessage(); log.error( "init():" + tmpMsg, e ); throw new javax.servlet.ServletException( tmpMsg, e ); } log.info( "init(): " + UsageLog.closingMessageNonRequestContext() ); } /** * * @return * @throws IOException * @throws SecurityException if config document cannot be read. */ private DqcServletConfig readInConfigDoc() throws IOException { DqcServletConfig retValue = null; // Instantiate the configuration for this servlet. retValue = new DqcServletConfig( this.dqcConfigPath, this.configFileName ); return( retValue ); } /** * Handle all GET requests. This includes requests for: documentation files, * a top-level catalog listing each DQC described dataset available through * this servlet installation, the DQC documents for those datasets, and * the queries for each of those DQC documents. * * @param req - the HttpServletRequest * @param res - the HttpServletResponse * @throws ServletException if the request could not be handled for some reason. * @throws IOException if an I/O error is detected (when communicating with client not for servlet internal IO problems?). */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.info( "doGet(): " + UsageLog.setupRequestContext( req) ); if ( ! this.allow ) { String msg = "DQC service not supported."; log.info( "doGet(): " + UsageLog.closingMessageForRequestContext( HttpServletResponse.SC_FORBIDDEN, msg.length() )); res.sendError( HttpServletResponse.SC_FORBIDDEN, msg ); return; } String tmpMsg = null; PrintWriter out = null; String handlerName; DqcServletConfigItem reqHandlerInfo = null; DqcHandler reqHandler = null; // Get the request path information. String reqPath = req.getPathInfo(); // Redirect empty path request to the root request (i.e., add a "/" to end of URL). if ( reqPath == null ) { res.sendRedirect( res.encodeRedirectURL( req.getContextPath() + req.getServletPath() + "/" ) ); ServletUtil.logServerAccess( HttpServletResponse.SC_MOVED_PERMANENTLY, 0 ); return; } // Handle root request: create HTML page that lists each available DQC described dataset. else if ( reqPath.equals( "/" ) ) { out = res.getWriter(); res.setContentType( "text/html" ); String resString = this.htmlOfConfig( req.getContextPath() + req.getServletPath() ); res.setStatus( HttpServletResponse.SC_OK ); out.print( resString); ServletUtil.logServerAccess( HttpServletResponse.SC_OK, resString.length() ); return; } // Handle requests for documentation files. else if ( reqPath.startsWith( "/" + this.dqcDocDirName + "/" ) ) { /** * Build an HTML page that lists the DQC documents handled by this servlet. * * @param contextServletPath - the Context servlet path * @return An HTML page that lists the DQC documents handled by this servlet. */ private String htmlOfConfig( String contextServletPath) { // @todo Add links to other things, e.g., docs and THREDDS server top-level StringBuffer buf = new StringBuffer(); buf.append( "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n" ) .append( " \"http: .append( "<html>\n" ); buf.append( "<head><title>DQC Servlet - Available Datasets</title></head>\n"); buf.append( "<body>" + "\n"); buf.append( "<h1>DQC Servlet - Available Datasets</h1>\n"); buf.append( "<table border=\"1\">\n"); buf.append( "<tr>\n"); buf.append( "<th> Name</th>\n"); buf.append( "<th> Description</th>\n"); buf.append( "<th> DQC Document</th>\n"); buf.append( "</tr>\n"); Iterator iter = null; DqcServletConfigItem curItem = null; iter = this.mainConfig.getIterator(); while( iter.hasNext()) { curItem = (DqcServletConfigItem) iter.next(); buf.append( "<tr>\n") .append( " <td>" ).append( curItem.getName() ).append( "</td>\n" ) .append( " <td>" ).append( curItem.getDescription() ).append( "</td>\n" ) .append( " <td><a href=\"" ).append( contextServletPath ).append( "/" ).append( curItem.getName() ).append( ".xml\">" ).append( curItem.getName() ).append( "</a></td>\n" ) .append( "<tr>\n"); } buf.append( "<table>\n"); buf.append( "<p>\n"); buf.append( "This listing is also available as a <a href=\"catalog.xml\">THREDDS catalog</a>.\n"); buf.append( "</p>\n"); buf.append( "</body>\n"); buf.append( "</html>\n"); return( buf.toString()); } private boolean writeEmptyConfigDocToFile( File configFile ) { FileOutputStream fos = null; OutputStreamWriter writer = null; try { fos = new FileOutputStream( configFile); writer = new OutputStreamWriter( fos, "UTF-8"); writer.append( this.genEmptyConfigDocAsString() ); writer.flush(); } catch ( IOException e ) { log.debug( "writeEmptyConfigDocToFile(): IO error writing blank config file: " + e.getMessage() ); return false; } finally { try { if ( writer != null ) writer.close(); if ( fos != null ) fos.close(); } catch ( IOException e ) { log.debug( "writeEmptyConfigDocToFile(): IO error closing just written blank config file: " + e.getMessage() ); return true; } } return true; } private String genEmptyConfigDocAsString() { StringBuilder sb = new StringBuilder() .append( "<?xml version='1.0' encoding='UTF-8'?>") .append("<preferences EXTERNAL_XML_VERSION='1.0'>") .append(" <root type='user'>") .append(" <map>") .append(" <beanCollection key='config' class='thredds.cataloggen.servlet.CatGenTimerTask'>") .append(" </beanCollection>") .append(" </map>") .append(" </root>") .append("</preferences>"); return sb.toString(); } }
package org.adaptlab.chpir.android.cloudtable; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import org.json.JSONException; import org.json.JSONObject; import android.net.Uri; import android.util.Log; public class HttpFetchr { private static final String TAG = "HttpFetchr"; private static final String ENDPOINT = "endpointapiurl"; private ReceiveTable mReceiveTable; public HttpFetchr(ReceiveTable receiveTable) { mReceiveTable = receiveTable; } public String getUrl(String urlSpec) throws IOException { return new String(getUrlBytes(urlSpec)); } public ArrayList<ReceiveTable> fetch() { ArrayList<ReceiveTable> items = new ArrayList<ReceiveTable>(); try { String url = Uri.parse(ENDPOINT).buildUpon() .appendQueryParameter("last_id", mReceiveTable.lastId().toString()) .build().toString(); String jsonString = getUrl(url); } catch (IOException ioe) { Log.e(TAG, "Failed to fetch items", ioe); } return items; } private byte[] getUrlBytes(String urlSpec) throws IOException { URL url = new URL(urlSpec); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = connection.getInputStream(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { return null; } int bytesRead = 0; byte[] buffer = new byte[1024]; while ((bytesRead = in.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); } out.close(); return out.toByteArray(); } finally { connection.disconnect(); } } }
package org.apache.qpid.contrib.json; import java.io.IOException; import org.apache.commons.configuration2.Configuration; import org.apache.commons.configuration2.FileBasedConfiguration; import org.apache.commons.configuration2.PropertiesConfiguration; import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder; import org.apache.commons.configuration2.builder.fluent.Parameters; import org.apache.commons.configuration2.ex.ConfigurationException; import org.apache.qpid.contrib.json.processer.EventProcesser; import com.alibaba.fastjson.JSON; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.Consumer; import com.rabbitmq.client.DefaultConsumer; import com.rabbitmq.client.Envelope; public class ReceiveMessageUtils { private Channel channel; private Connection connection; /** * * @param queueName * * @param eventProcesser * * @param clazz * * @throws Exception */ public void receiveMessage(String queueName, EventProcesser eventProcesser, Class<?> clazz) throws Exception { setConfig(null); channel = connection.createChannel(); channel.queueDeclare(queueName, true, false, false, null); // System.out.println(" [*] Waiting for messages. To exit press // CTRL+C"); channel.basicQos(1);// RabbitMQ Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body); if (clazz != null) { eventProcesser.process(JSON.parseObject(message, clazz)); } else { eventProcesser.process(JSON.parse(message)); } } }; channel.basicConsume(queueName, true, consumer); } public ReceiveMessageUtils(Connection connection) { super(); this.connection = connection; } public void close() throws Exception { connection.close(); } }
package org.biojava.bio.program.tagvalue; import org.biojava.utils.ParserException; public abstract class TagValueWrapper implements TagValueListener { private TagValueListener delegate; public TagValueWrapper(TagValueListener delegate) { this.delegate = delegate; } public TagValueListener getDelegate() { return delegate; } public void startRecord() { delegate.startRecord(); } public void endRecord() { delegate.endRecord(); } public void startTag(Object tag) throws ParserException { delegate.startTag(tag); } public void endTag() throws ParserException { delegate.endTag(); } public void value(TagValueContext ctxt, Object value) throws ParserException { delegate.value(ctxt, value); } }
package org.jitsi.impl.neomedia.conference; import java.lang.ref.*; import javax.media.*; /** * Caches <tt>int</tt> arrays for the purposes of reducing garbage collection. * * @author Lyubomir Marinov */ class IntArrayCache { /** * The cache of <tt>int</tt> arrays managed by this instance for the * purposes of reducing garbage collection. */ private SoftReference<int[][]> elements; /** * The number of elements at the head of {@link #elements} which are * currently utilized. Introduced to limit the scope of iteration. */ private int length; /** * Allocates an <tt>int</tt> array with length/size greater than or equal to * a specific number. The returned array may be a newly-initialized instance * or one of the elements cached/pooled by this instance. * * @param minSize the minimum length/size of the array to be returned * @return an <tt>int</tt> array with length/size greater than or equal to * <tt>minSize</tt> */ public synchronized int[] allocateIntArray(int minSize) { int[][] elements = (this.elements == null) ? null : this.elements.get(); if (elements != null) { for (int i = 0; i < length; i++) { int[] element = elements[i]; if ((element != null) && element.length >= minSize) { elements[i] = null; return element; } } } return new int[minSize]; } /** * Returns a specific non-<tt>null</tt> <tt>int</tt> array into the * cache/pool implemented by this instance. * * @param intArray the <tt>int</tt> array to be returned into the cache/pool * implemented by this instance. If <tt>null</tt>, the method does nothing. */ public synchronized void deallocateIntArray(int[] intArray) { if (intArray == null) return; int[][] elements; if ((this.elements == null) || ((elements = this.elements.get()) == null)) { elements = new int[8][]; this.elements = new SoftReference<int[][]>(elements); length = 0; } if (length != 0) for (int i = 0; i < length; i++) if (elements[i] == intArray) return; if (length == elements.length) { /* * Compact the non-null elements at the head of the storage in order * to possibly prevent reallocation. */ int newLength = 0; for (int i = 0; i < length; i++) { int[] element = elements[i]; if (element != null) { if (i != newLength) { elements[newLength] = element; elements[i] = null; } newLength++; } } if (newLength == length) { // Expand the storage. int[][] newElements = new int[elements.length + 4][]; System.arraycopy(elements, 0, newElements, 0, elements.length); elements = newElements; this.elements = new SoftReference<int[][]>(elements); } else { length = newLength; } } elements[length++] = intArray; } /** * Ensures that the <tt>data</tt> property of a specific <tt>Buffer</tt> is * set to an <tt>int</tt> array with length/size greater than or equal to a * specific number. * * @param buffer the <tt>Buffer</tt> the <tt>data</tt> property of which is * to be validated * @param newSize the minimum length/size of the <tt>int</tt> array to be * set as the value of the <tt>data</tt> property of the specified * <tt>buffer</tt> and to be returned * @return the value of the <tt>data</tt> property of the specified * <tt>buffer</tt> which is guaranteed to have a length/size of at least * <tt>newSize</tt> elements */ public int[] validateIntArraySize(Buffer buffer, int newSize) { Object data = buffer.getData(); int[] intArray; if (data instanceof int[]) { intArray = (int[]) data; if (intArray.length < newSize) { deallocateIntArray(intArray); intArray = null; } } else intArray = null; if (intArray == null) { intArray = allocateIntArray(newSize); buffer.setData(intArray); } return intArray; } }
package com.datdo.mobilib.carrier; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.View; import android.widget.FrameLayout; import com.datdo.mobilib.event.MblCommonEvents; import com.datdo.mobilib.event.MblEventCenter; import com.datdo.mobilib.event.MblEventListener; import com.datdo.mobilib.util.MblUtils; import junit.framework.Assert; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Stack; /** * <pre> * Carrier/Interceptor is a alternative of old Activity/Fragment model. * * Due to the fact that Activity/Fragment model has too many drawbacks: * 1. Quite complicated to start and manage lifecycle. * :::How you start a Fragment with parameters * {@code * Fragment newFragment = new ExampleFragment(); * Bundle args = new Bundle(); * args.putInt("param1", param1); * args.putInt("param2", param2); * newFragment.setArguments(args); * FragmentTransaction transaction = getFragmentManager().beginTransaction(); // or getSupportFragmentManager() * transaction.replace(R.id.fragment_container, newFragment); * transaction.addToBackStack(null); * transaction.commit(); * } * :::Fragment 's lifecycle (quite different from Activity 's lifecycle, why Google didn't make coding simpler?) * onAttach -> onCreate -> onCreateView -> onActivityCreated -> onStart -> onResume -> onPause -> onStop -> onDestroyView -> onDestroy -> onDetach * 2. Cause potential bugs (especially {@code Fragment#getActivity()} method which causes {@link java.lang.NullPointerException}. * 3. Fragment can not contain another fragment (for example: you can not add Google MapFragment into your fragment) * 4. Unable to start a fragment directly from another fragment while an Activity can be started directly from another Activity (you can do it by using getActivity() method, but it is still complicated, as mentioned in [1]) * 5. Activity must be subclass of FragmentActivity. * * it is recommended to use Carrier/Interceptor alternative when you need to render multiple sub-screens in a parent screen. * * Benefits of Carrier/Interceptor: * 1. Easy to use * :::How you start an Interceptor with parameters * {@code * carrier.startInterceptor(ExampleInterceptor.class, null, "param1", param1, "param2", param2); * } * :::Interceptor 's lifecycle just looks like Activity 's lifecycle, even simpler * onCreate -> onResume -> onPause -> onDestroy * 2. Interceptor can contains another interceptor due to the fact that interceptor is just a View * 3. You can start an interceptor from another interceptor, just like starting Activity from another Activity, even simpler * {@code * public class ExampleInterceptor extends MblInterceptor { * public void foo() { * startInterceptor(NextInterceptor.class, null, "param1", param1, "param2", param2); * } * } * } * 4. MblCarrier is just an object wrapping a {@link FrameLayout} view which is the container view of its Interceptors, therefore Carrier can be plugged in any Activity or View. * * Sample code: * * {@code * FrameLayout interceptorContainerView = (FrameLayout) findViewById(R.id.interceptor_container); * mCarrier = new MblSlidingCarrier(this, interceptorContainerView, new MblCarrier.MblCarrierCallback() { * @Override * public void onNoInterceptor() { * // ... handle when Carrier does not contain any Interceptor * } * }); * mCarrier.startInterceptor(Interceptor1.class, new Options().newInterceptorStack(), "param1", param1); * } * * P/S: the name "Carrier/Interceptor" is inspired by legendary game Starcraft ;) * </pre> * @see com.datdo.mobilib.carrier.MblInterceptor */ @SuppressLint("InflateParams") public abstract class MblCarrier implements MblEventListener { private static final String TAG = MblUtils.getTag(MblCarrier.class); /** * <pre> * Extra options when starting new interceptor. * All options is OFF (false) by default. * </pre> */ public static final class Options { private boolean mNewInterceptorStack; private boolean mNoAnimation; /** * <pre> * Clear all interceptor in stack before starting new interceptor. * </pre> * @return this */ public Options newInterceptorStack() { mNewInterceptorStack = true; return this; } /** * Configure whether animation is played when interceptor is started/finished. */ public Options noAnimation() { mNoAnimation = true; return this; } } /** * Callback interface for {@link com.datdo.mobilib.carrier.MblCarrier}. */ public static class MblCarrierCallback { public void beforeStart(Class<? extends MblInterceptor> clazz, Options options, Map<String, Object> extras) {} public void afterStart(Class<? extends MblInterceptor> clazz, Options options, Map<String, Object> extras) {} public void beforeFinish(MblInterceptor currentInterceptor) {} public void afterFinish(MblInterceptor currentInterceptor) {} } protected Context mContext; protected FrameLayout mInterceptorContainerView; protected MblCarrierCallback mCallback; private boolean mInterceptorBeingStarted; private final Stack<MblInterceptor> mInterceptorStack = new Stack<MblInterceptor>(); /** * Constructor * @param context activity in which this Carrier is plugged * @param interceptorContainerView view that contains all Interceptors of this Carrier * @param callback instance of {@link com.datdo.mobilib.carrier.MblCarrier.MblCarrierCallback} */ public MblCarrier(Context context, FrameLayout interceptorContainerView, MblCarrierCallback callback) { mContext = context; mInterceptorContainerView = interceptorContainerView; mCallback = callback != null ? callback : new MblCarrierCallback(); MblEventCenter.addListener(this, new String[] { MblCommonEvents.ACTIVITY_RESUMED, MblCommonEvents.ACTIVITY_PAUSED, MblCommonEvents.ACTIVITY_DESTROYED }); } /** * <pre> * Overridden by subclasses. * This method defines the animations when navigating from currentInterceptor to nextInterceptor. * </pre> * @param currentInterceptor interceptor which is currently displayed * @param nextInterceptor next interceptor to navigate * @param onAnimationEnd invoked when animation has ended */ protected abstract void animateForStarting( final MblInterceptor currentInterceptor, final MblInterceptor nextInterceptor, final Runnable onAnimationEnd); /** * <pre> * Overridden by subclasses. * This method defines the animations when navigating from current interceptor back to previous interceptor. * </pre> * @param currentInterceptor interceptor which is currently displayed * @param previousInterceptor previous interceptor to navigate back * @param onAnimationEnd invoked when animation has ended */ protected abstract void animateForFinishing( final MblInterceptor currentInterceptor, final MblInterceptor previousInterceptor, final Runnable onAnimationEnd); /** * Destroy all interceptors. */ public void finishAllInterceptors() { if (isVisible()) { onPause(); } destroyAllInterceptors(); } @SuppressWarnings("unchecked") @Override public void onEvent(Object sender, String name, Object... args) { Activity activity = (Activity) args[0]; if (activity != mContext) { return; } if (MblCommonEvents.ACTIVITY_RESUMED == name) { if (isVisible()) { onResume(); } } if (MblCommonEvents.ACTIVITY_PAUSED == name) { if (isVisible()) { onPause(); } } if (MblCommonEvents.ACTIVITY_DESTROYED == name) { onDestroy(); } } /** * Start an interceptor for this Carrier. * @param clazz class of interceptor to start * @param options extra option when adding new interceptor to carrier * @param extras parameters passed to the new interceptor, in key,value (for example: "param1", param1Value, "param1", param2Value, ...) * @return the new interceptor instance */ public MblInterceptor startInterceptor(Class<? extends MblInterceptor> clazz, Options options, Object... extras) { return startInterceptor(clazz, options, convertExtraArrayToMap(extras)); } /** * Start an interceptor for this Carrier. * @param clazz class of interceptor to start * @param options extra option when adding new interceptor to carrier * @param extras parameters passed to the new interceptor, in key,value * @return the new interceptor instance */ public MblInterceptor startInterceptor(final Class<? extends MblInterceptor> clazz, final Options options, final Map<String, Object> extras) { if (mInterceptorBeingStarted) { return null; } mInterceptorBeingStarted = true; if (options != null) { if (options.mNewInterceptorStack) { finishAllInterceptors(); } } try { final MblInterceptor nextInterceptor = clazz.getConstructor(Context.class, MblCarrier.class, Map.class).newInstance(mContext, this, extras); if (mInterceptorStack.isEmpty()) { mCallback.beforeStart(clazz, options, extras); mInterceptorContainerView.addView(nextInterceptor); mInterceptorStack.push(nextInterceptor); nextInterceptor.onResume(); mInterceptorBeingStarted = false; mCallback.afterStart(clazz, options, extras); } else { mCallback.beforeStart(clazz, options, extras); final MblInterceptor currentInterceptor = mInterceptorStack.peek(); mInterceptorContainerView.addView(nextInterceptor); mInterceptorStack.push(nextInterceptor); Runnable action = new Runnable() { @Override public void run() { currentInterceptor.setVisibility(View.INVISIBLE); currentInterceptor.onPause(); nextInterceptor.onResume(); mInterceptorBeingStarted = false; mCallback.afterStart(clazz, options, extras); } }; if (options != null && options.mNoAnimation) { action.run(); } else { animateForStarting(currentInterceptor, nextInterceptor, action); } } return nextInterceptor; } catch (Throwable e) { Log.e(TAG, "Unable to start interceptor: " + clazz, e); return null; } } /** * Destroy an interceptor. * @param currentInterceptor interceptor to destroy */ public void finishInterceptor(MblInterceptor currentInterceptor) { finishInterceptor(currentInterceptor, null); } /** * Destroy an interceptor with options * @param currentInterceptor interceptor to destroy * @param options extra option when finishing an interceptor */ public void finishInterceptor(final MblInterceptor currentInterceptor, Options options) { try { boolean isTop = currentInterceptor == mInterceptorStack.peek(); if (isTop) { mCallback.beforeFinish(currentInterceptor); mInterceptorStack.pop(); if (mInterceptorStack.isEmpty()) { // just remove top interceptor mInterceptorContainerView.removeView(currentInterceptor); currentInterceptor.onPause(); currentInterceptor.onDestroy(); mCallback.afterFinish(currentInterceptor); } else { final MblInterceptor previousInterceptor = mInterceptorStack.peek(); previousInterceptor.setVisibility(View.VISIBLE); Runnable action = new Runnable() { @Override public void run() { mInterceptorContainerView.removeView(currentInterceptor); currentInterceptor.onPause(); currentInterceptor.onDestroy(); previousInterceptor.onResume(); mCallback.afterFinish(currentInterceptor); } }; if (options != null && options.mNoAnimation) { action.run(); } else { animateForFinishing(currentInterceptor, previousInterceptor, action); } } } else { // just remove interceptor from stack silently mCallback.beforeFinish(currentInterceptor); mInterceptorStack.remove(currentInterceptor); mInterceptorContainerView.removeView(currentInterceptor); currentInterceptor.onPause(); currentInterceptor.onDestroy(); mCallback.afterFinish(currentInterceptor); } } catch (Throwable e) { Log.e(TAG, "Unable to finish interceptor: " + currentInterceptor, e); } } /** * <pre> * Bring an interceptor to front. * Do nothing if interceptor is not in this carrier, or it is already on top of stack. * </pre> */ public void bringToFront(MblInterceptor interceptor) { if (interceptor == null || !mInterceptorStack.contains(interceptor) || mInterceptorContainerView.indexOfChild(interceptor) < 0) { return; } boolean isTop = interceptor == mInterceptorStack.peek(); if (isTop) { return; } MblInterceptor topInterceptor = mInterceptorStack.peek(); mInterceptorStack.remove(interceptor); mInterceptorStack.push(interceptor); topInterceptor.setVisibility(View.INVISIBLE); topInterceptor.onPause(); interceptor.setVisibility(View.VISIBLE); interceptor.onResume(); } /** * Manually trigger onResume() for top interceptor. */ public void onResume() { try { MblInterceptor currentInterceptor = mInterceptorStack.peek(); currentInterceptor.onResume(); } catch (Throwable e) { Log.e(TAG, "Unable to handle onResume()", e); } } /** * Manually trigger onPause() for top interceptor. */ public void onPause() { try { MblInterceptor currentInterceptor = mInterceptorStack.peek(); currentInterceptor.onPause(); } catch (Throwable e) { Log.e(TAG, "Unable to handle onPause()", e); } } /** * Manually trigger onDestroy() for all interceptors. */ public void onDestroy() { destroyAllInterceptors(); } private void destroyAllInterceptors() { try { while(!mInterceptorStack.isEmpty()) { MblInterceptor interceptor = mInterceptorStack.pop(); interceptor.onDestroy(); mInterceptorContainerView.removeView(interceptor); } } catch (Throwable e) { Log.e(TAG, "Unable to destroy all interceptors", e); } } /** * <pre> * Handle when user pressed Android Back button. * This method is called by parent Activity of this carrier * {@code * public class ExampleActivity extends MblBaseActivity { * @Override * public void onBackPressed() { * if (mCarrier.onBackPressed()) { * return; * } * // ... * super.onBackPressed(); * } * } * } * </pre> * @return true if this event is handled by current interceptor */ public boolean onBackPressed() { try { MblInterceptor currentInterceptor = mInterceptorStack.peek(); return currentInterceptor.onBackPressed(); } catch (Throwable e) { Log.e(TAG, "Unable to handle onBackPressed()", e); return false; } } /** * <pre> * Handle when parent Activity of this carrier receives activity result. * This method is called by parent Activity of this carrier * {@code * public class ExampleActivity extends MblBaseActivity { * @Override * public void onActivityResult(int requestCode, int resultCode, Intent data) { * if (mCarrier.onActivityResult(requestCode, resultCode, data)) { * return; * } * // ... * super.onActivityResult(); * } * } * } * </pre> * @return true if this event is handled by current interceptor */ public boolean onActivityResult(int requestCode, int resultCode, Intent data) { try { MblInterceptor currentInterceptor = mInterceptorStack.peek(); return currentInterceptor.onActivityResult(requestCode, resultCode, data); } catch (Throwable e) { Log.e(TAG, "Unable to handle onBackPressed()", e); return false; } } static Map<String, Object> convertExtraArrayToMap(Object... extras) { Assert.assertTrue(extras == null || extras.length % 2 == 0); Map<String, Object> mapExtras = new HashMap<String, Object>(); if (!MblUtils.isEmpty(extras)) { int i = 0; while (i < extras.length) { Object key = extras[i]; Object value = extras[i+1]; Assert.assertTrue(key != null && key instanceof String); if (value != null) { mapExtras.put((String) key, value); } i += 2; } } return mapExtras; } /** * Get {@link com.datdo.mobilib.carrier.MblInterceptor} instances bound with this carrier * @return */ public List<MblInterceptor> getInterceptors() { return new ArrayList<MblInterceptor>(mInterceptorStack); } /** * Show/hide this carrier and all of its children. */ public void setVisible(boolean isVisible) { if (isVisible() != isVisible) { if (isVisible) { mInterceptorContainerView.setVisibility(View.VISIBLE); onResume(); } else { mInterceptorContainerView.setVisibility(View.INVISIBLE); onPause(); } } } /** * Check if this carrier is visible. */ public boolean isVisible() { return mInterceptorContainerView.getVisibility() == View.VISIBLE; } }
package org.kwstudios.play.ragemode.events; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Sign; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Arrow; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Snowball; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.entity.FoodLevelChangeEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.entity.ProjectileHitEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.kwstudios.play.ragemode.gameLogic.GameSpawnGetter; import org.kwstudios.play.ragemode.gameLogic.PlayerList; import org.kwstudios.play.ragemode.items.CombatAxe; import org.kwstudios.play.ragemode.loader.PluginLoader; import org.kwstudios.play.ragemode.scores.RageScores; import org.kwstudios.play.ragemode.signs.SignCreator; import org.kwstudios.play.ragemode.toolbox.ConfigFactory; import org.kwstudios.play.ragemode.toolbox.ConstantHolder; import org.kwstudios.play.ragemode.toolbox.GameBroadcast; import org.kwstudios.play.ragemode.toolbox.GetGames; public class EventListener implements Listener { public FileConfiguration fileConfiguration = null; private Map<UUID, UUID> explosionVictims = new HashMap<UUID, UUID>(); //shot, shooter public EventListener(PluginLoader plugin, FileConfiguration fileconfiguration) { plugin.getServer().getPluginManager().registerEvents(this, plugin); fileConfiguration = fileconfiguration; } @EventHandler public void onPlayerQuit(PlayerQuitEvent event) { Player player = event.getPlayer(); // Bukkit.broadcastMessage("Ragemode noticed that " + player.getName() + // " disconnected."); if (PlayerList.isPlayerPlaying(event.getPlayer().getUniqueId().toString())) { if (PlayerList.removePlayer(player)) { // Bukkit.broadcastMessage(player.getName() + " was removed // successfully."); } } } @EventHandler(priority = EventPriority.LOWEST) public void onProjectileHit(ProjectileHitEvent event) { //RageArrow explosion event if (event.getEntity() instanceof Arrow) { Arrow arrow = (Arrow) event.getEntity(); if (arrow.getShooter() instanceof Player) { Player shooter = (Player) arrow.getShooter(); if (PlayerList.isPlayerPlaying(shooter.getUniqueId().toString())) { Location location = arrow.getLocation(); World world = arrow.getWorld(); double x = location.getX(); double y = location.getY(); double z = location.getZ(); List<Entity> nears = arrow.getNearbyEntities(10, 10, 10); world.createExplosion(x, y, z, 2f, false, false); //original 4f arrow.remove(); int i = 0; int imax = nears.size(); while(i < imax) { if(nears.get(i) instanceof Player /*&& !nears.get(i).getUniqueId().toString().equals(shooter.getUniqueId().toString())*/) { Player near = (Player) nears.get(i); if(explosionVictims != null) { if(explosionVictims.containsKey(near.getUniqueId())) { explosionVictims.remove(near.getUniqueId()); explosionVictims.put(near.getUniqueId(), shooter.getUniqueId()); } } explosionVictims.put(near.getUniqueId(), shooter.getUniqueId()); } i++; } } } } } @EventHandler public void onRageKnifeHit(EntityDamageByEntityEvent event){ //RageKnife hit event if(event.getDamager() instanceof Player && event.getEntity() instanceof Player){ Player killer = (Player) event.getDamager(); Player victim = (Player) event.getEntity(); if(PlayerList.isPlayerPlaying(killer.getUniqueId().toString()) && PlayerList.isPlayerPlaying(victim.getUniqueId().toString())){ if(killer.getItemInHand() != null && killer.getItemInHand().getItemMeta() != null && killer.getItemInHand().getItemMeta().getDisplayName() != null) { if(killer.getItemInHand().getItemMeta().getDisplayName().equals(ChatColor.GOLD + "RageKnife")){ //TODO check if "killer.getItemInHand() instanceof MATERIAL.SHEARS" also works (maybe more stable) event.setDamage(25); } } } if(PlayerList.isPlayerPlaying(victim.getUniqueId().toString())) { if(!PlayerList.isGameRunning(PlayerList.getPlayersGame(victim))) { event.setDamage(0); } } } //TODO add Constant for "RageKnife" for unexpected error preventing } @EventHandler(priority = EventPriority.HIGHEST) public void onItemSpawn(PlayerDropItemEvent event){ Player player = event.getPlayer(); if(PlayerList.isPlayerPlaying(player.getUniqueId().toString())){ event.setCancelled(true); } } @EventHandler public void onArrowHitPlayer(EntityDamageEvent event){ //Arrow hit player event if(event.getEntity() instanceof Player) { if(PlayerList.isPlayerPlaying(event.getEntity().getUniqueId().toString())) { if(event.getCause().equals(DamageCause.PROJECTILE)) { Player victim = (Player) event.getEntity(); if(PlayerList.isPlayerPlaying(victim.getUniqueId().toString())){ if(event.getDamage() == 0.0d) { event.setDamage(28.34d); } else { event.setDamage(27.114); } } } if(event.getCause().equals(DamageCause.FALL)) { event.setCancelled(true); } } } } @EventHandler public void onPlayerDeath(PlayerDeathEvent event) { //Player autorespawn Player deceased; if(event.getEntity() instanceof Player && event.getEntity() != null){ deceased = (Player) event.getEntity(); } else{ return; } if(PlayerList.isPlayerPlaying(event.getEntity().getUniqueId().toString())) { if((deceased.getKiller() != null && PlayerList.isPlayerPlaying(deceased.getKiller().getUniqueId().toString())) || deceased.getKiller() == null) { String game = PlayerList.getPlayersGame(deceased); if(!fileConfiguration.isSet("setting.global.deathmessages")) { ConfigFactory.setBoolean("settings.global", "deathmessages", false, fileConfiguration); } boolean doDeathBroadcast = ConfigFactory.getBoolean("settings.global", "deathmessages", fileConfiguration); if(deceased.getLastDamage() == 0.0f) { if(deceased.getKiller() == null) { if(doDeathBroadcast) GameBroadcast.broadcastToGame(game, ConstantHolder.RAGEMODE_PREFIX + ChatColor.GREEN + deceased.getName() + ChatColor.DARK_AQUA + " was killed by " + ChatColor.GREEN + deceased.getName() + ChatColor.DARK_AQUA + " with a" + ChatColor.GOLD + "CombatAxe" + ChatColor.DARK_AQUA + "."); RageScores.addPointsToPlayer(deceased, deceased, "combataxe"); } else { if(doDeathBroadcast) GameBroadcast.broadcastToGame(game, ConstantHolder.RAGEMODE_PREFIX + ChatColor.GREEN + deceased.getName() + ChatColor.DARK_AQUA + " was killed by " + ChatColor.GREEN + deceased.getKiller().getName() + ChatColor.DARK_AQUA + " with a " + ChatColor.GOLD + "CombatAxe" + ChatColor.DARK_AQUA + "."); RageScores.addPointsToPlayer(deceased.getKiller(), deceased, "combataxe"); } } else if(deceased.getLastDamageCause().getCause().equals(DamageCause.PROJECTILE)) { if(deceased.getKiller() == null) { if(doDeathBroadcast) GameBroadcast.broadcastToGame(game, ConstantHolder.RAGEMODE_PREFIX + ChatColor.GREEN + deceased.getName() + ChatColor.DARK_AQUA + " was killed by a direct " + ChatColor.GOLD + "arrow" + ChatColor.DARK_AQUA + " hit from " + ChatColor.GREEN + deceased.getName() + ChatColor.DARK_AQUA + "."); RageScores.addPointsToPlayer(deceased, deceased, "ragebow"); } else { if(doDeathBroadcast) GameBroadcast.broadcastToGame(game, ConstantHolder.RAGEMODE_PREFIX + ChatColor.GREEN + deceased.getName() + ChatColor.DARK_AQUA + " was killed by a direct " + ChatColor.GOLD + "arrow" + ChatColor.DARK_AQUA + " hit from " + ChatColor.GREEN + deceased.getKiller().getName() + ChatColor.DARK_AQUA + "."); RageScores.addPointsToPlayer(deceased.getKiller(), deceased, "ragebow"); } } else if(deceased.getLastDamageCause().getCause().equals(DamageCause.ENTITY_ATTACK)) { if(deceased.getKiller() == null) { if(doDeathBroadcast) GameBroadcast.broadcastToGame(game, ConstantHolder.RAGEMODE_PREFIX + ChatColor.GREEN + deceased.getName() + ChatColor.DARK_AQUA + " was killed by " + ChatColor.GOLD + deceased.getName() + ChatColor.DARK_AQUA + " with a " + ChatColor.GOLD + "RageKnife" + ChatColor.DARK_AQUA + "."); RageScores.addPointsToPlayer(deceased, deceased, "rageknife"); } else { if(doDeathBroadcast) GameBroadcast.broadcastToGame(game, ConstantHolder.RAGEMODE_PREFIX + ChatColor.GREEN + deceased.getName() + ChatColor.DARK_AQUA + " was killed by " + ChatColor.GOLD + deceased.getKiller().getName() + ChatColor.DARK_AQUA + " with a " + ChatColor.GOLD + "RageKnife" + ChatColor.DARK_AQUA + "."); RageScores.addPointsToPlayer(deceased.getKiller(), deceased, "rageknife"); } } else if(deceased.getLastDamageCause().getCause().equals(DamageCause.BLOCK_EXPLOSION)) { if(explosionVictims.containsKey(deceased.getUniqueId())) { if(doDeathBroadcast) GameBroadcast.broadcastToGame(game, ConstantHolder.RAGEMODE_PREFIX + ChatColor.GREEN + deceased.getName() + ChatColor.DARK_AQUA + " was " + ChatColor.GOLD + "blown up" + ChatColor.DARK_AQUA + " by " + ChatColor.GREEN + Bukkit.getPlayer(explosionVictims.get(deceased.getUniqueId())).getName() + ChatColor.DARK_AQUA + "."); RageScores.addPointsToPlayer(Bukkit.getPlayer(explosionVictims.get(deceased.getUniqueId())), deceased, "explosion"); } else { if(doDeathBroadcast) GameBroadcast.broadcastToGame(game, ConstantHolder.RAGEMODE_PREFIX + "Whoops, that shouldn't happen normally..."); deceased.sendMessage(ConstantHolder.RAGEMODE_PREFIX + "Do you know who killed you? Because we don't know it..."); } } else { if(doDeathBroadcast) GameBroadcast.broadcastToGame(game, ConstantHolder.RAGEMODE_PREFIX + ChatColor.GREEN + deceased.getName() + ChatColor.DARK_AQUA + " was killed by something unexpected."); } event.setDeathMessage(""); } event.setKeepInventory(true); GameSpawnGetter gameSpawnGetter = new GameSpawnGetter(PlayerList.getPlayersGame(deceased), fileConfiguration); List<Location> spawns = gameSpawnGetter.getSpawnLocations(); Random rand = new Random(); int x = rand.nextInt(spawns.size() - 1); deceased.setHealth(20); deceased.teleport(spawns.get(x)); //deceased.getInventory().clear(); //deceased.getInventory().setItem(0, RageBow.getRageBow()); // //deceased.getInventory().setItem(1, RageKnife.getRageKnife()); // give him a new set of items //deceased.getInventory().setItem(9, RageArrow.getRageArrow()); // deceased.getInventory().setItem(2, CombatAxe.getCombatAxe()); } } @EventHandler public void onHungerGain(FoodLevelChangeEvent event) { if(event.getEntity() instanceof Player) { Player player = (Player) event.getEntity(); if(PlayerList.isPlayerPlaying(player.getUniqueId().toString())) { event.setCancelled(true); } } } @EventHandler public void onBlockBreak(BlockBreakEvent event) { if(PlayerList.isPlayerPlaying(event.getPlayer().getUniqueId().toString())) { event.setCancelled(true); } if(event.getBlock() instanceof Sign){ SignCreator.removeSign((Sign)event.getBlock()); } } @EventHandler public void onCommand(PlayerCommandPreprocessEvent event) { if(PlayerList.isPlayerPlaying(event.getPlayer().getUniqueId().toString()) && !event.getPlayer().hasPermission("ragemode.admin.cmd")) { if(event.getMessage() != null) { String cmd = event.getMessage().toLowerCase(); if(cmd.equals("/rm leave") || cmd.equals("/ragemode leave") || cmd.equals("/rm list") || cmd.equals("/ragemode list")|| cmd.equals("/rm stop") || cmd.equals("/ragemode stop") || cmd.equals("/l") || cmd.equals("/lobby") || cmd.equals("/spawn")) { } else { event.setCancelled(true); } } } } @EventHandler public void onCombatAxeThrow(PlayerInteractEvent event) { if(PlayerList.isPlayerPlaying(event.getPlayer().getUniqueId().toString())) { Player thrower = event.getPlayer(); if(thrower.getItemInHand() != null && thrower.getItemInHand().getItemMeta() != null && thrower.getItemInHand().getItemMeta().getDisplayName() != null) { if(thrower.getItemInHand().getItemMeta().getDisplayName().equals(ChatColor.GOLD + "CombatAxe")) { thrower.launchProjectile(Snowball.class); thrower.getInventory().setItemInHand(null); } } } } @EventHandler public void onInventoryInteractEvent(InventoryClickEvent event){ if(PlayerList.isPlayerPlaying(event.getWhoClicked().getUniqueId().toString())){ event.setCancelled(true); } } @EventHandler public void onItemPickedUpEvent(PlayerPickupItemEvent event){ if(PlayerList.isPlayerPlaying(event.getPlayer().getUniqueId().toString())){ event.setCancelled(true); } } @EventHandler public void onSignChange(SignChangeEvent event){ Sign sign; if(event.getBlock() instanceof Sign){ sign = (Sign) event.getBlock(); }else{ return; } if(event.getLine(1).trim().equalsIgnoreCase("[rm]") || event.getLine(2).trim().equalsIgnoreCase("[ragemode]")){ String[] allGames = GetGames.getGameNames(PluginLoader.getInstance().getConfig()); for(String game : allGames){ if(event.getLine(1).trim().equalsIgnoreCase(game.trim())){ SignCreator.createNewSign(sign, game); SignCreator.updateSign(sign); } } } } }
package org.nusco.swimmers.creature.genetics; class OrganParser { private final int[] genes; private int index_in_genes = 0; public OrganParser(DNA dna) { genes = dna.getGenes(); } public int[] nextPart() { int[] result = new int[OrganBuilder.GENES_PER_PART]; int index_in_result = 0; while(index_in_result < result.length) { if(index_in_genes >= genes.length) return result; result[index_in_result] = genes[index_in_genes]; index_in_result++; index_in_genes++; } return result; } }
package org.objectweb.proactive.core.gc; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Vector; import org.apache.log4j.Level; import org.objectweb.proactive.core.ProActiveRuntimeException; import org.objectweb.proactive.core.UniqueID; import org.objectweb.proactive.core.body.AbstractBody; import org.objectweb.proactive.core.body.HalfBody; import org.objectweb.proactive.core.body.LocalBodyStore; import org.objectweb.proactive.core.body.proxy.UniversalBodyProxy; import org.objectweb.proactive.core.body.request.BodyRequest; import org.objectweb.proactive.core.exceptions.body.SendReplyCommunicationException; import org.objectweb.proactive.core.exceptions.manager.TypedNFEListener; /** * Remember if we terminated and why. */ enum FinishedState { /** We didn't terminate */ NOT_FINISHED, /** Acyclic garbage */ ACYCLIC, /** Cyclic garbage, notify referencers */ CYCLIC; } /** * Locking: single lock: the GarbageCollector instance * * Broadcasting is done in a separate thread to avoid blocking. It would suck * less to use non-blocking I/O instead of threads. */ public class GarbageCollector { /** * TimeToBroadcast * Time is always in milliseconds. It is fundamental for this value * to be the same in all JVM of the distributed system, so think twice * before changing it. * TODO: make it dynamic. */ static final int TTB = 30000; /** * TimeToAlone * After this delay, we suppose we got a message from all our referencers. */ static final int TTA = 5 * TTB; static { if (dgcIsEnabled()) { GarbageCollectorThread.start(); } } /** * Number of consecutive consensus to agree on until the object decides * to belong to some garbage cycle. * My gut feeling oscillates between 1 and 3 with a preference to 1 but * the theoretical proof will tell us. */ private static final int NR_CONSENSUS = 1; /** * Whether the object is pinned somewhere. */ private boolean registered; /** * Whether the GC should stop being part of the algorithm. * This flag is used to stop the GC thread, and notify the referencers * of some cyclic garbage. */ private FinishedState finished; /** * Statistical info: count the number of iterations. */ private long iterations; /** * My last activity * Lamport clock * Incremented for every activity: * - service stopped => between each service * - loss of a referencer => avoid cycle with no owner * - loss of a referenced => maybe loss of parent * * It is always the maximum of my activity and those received. */ private Activity lastActivity; /** * My parent in the reverse spanning tree. */ private Referenced parent; /** * Count consecutively reached consensus up to NR_CONSENSUS */ private int nrReachedConsensus; /** * List of (weak references to) referenced proxies. * We have to track every proxy instance, but * for a given target object, one proxy is enough for the broadcast. */ private final HashMap<UniqueID, Referenced> referenced; /** * New referenced proxies are kept as strong references on the first round, * to be sure they are sent at least one message before vanishing. */ private final List<UniversalBodyProxy> newReferenced; /** * These are just strings, not remote references. * We keep track of referencers to know when we lose one. */ private final HashMap<UniqueID, Referencer> referencers; /** * For how long did no one reference us? This is to be compared to TTA. */ private long aloneTimestamp; /** * The AO we belong to */ protected final AbstractBody body; /** * To detect new activities */ private boolean previouslyBusy; /** * Build a GarbageCollector instance for each active object */ public GarbageCollector(AbstractBody body) { this.registered = body instanceof HalfBody; this.finished = FinishedState.NOT_FINISHED; this.iterations = 0; this.lastActivity = new Activity(body.getID(), 0); this.parent = null; this.nrReachedConsensus = 0; this.referenced = new HashMap<UniqueID, Referenced>(); this.newReferenced = new LinkedList<UniversalBodyProxy>(); this.referencers = new HashMap<UniqueID, Referencer>(); this.aloneTimestamp = System.currentTimeMillis(); this.body = body; this.previouslyBusy = true; body.addNFEListener(new TypedNFEListener( SendReplyCommunicationException.class, SendReplyCommunicationExceptionHandler.instance)); } /** * A new activity has been made, either from myself or a referencer */ private synchronized void setLastActivity(Activity ac) { this.lastActivity = ac; this.nrReachedConsensus = 0; this.parent = null; } /** * Something happened on the active object */ public synchronized void incActivity() { Activity newActivity = new Activity(this.body.getID(), this.lastActivity.getCounter() + 1); this.setLastActivity(newActivity); } /** * Remove old referencers, this can cause an increase * of the activity. */ private void purgeReferencers() { Collection<String> removed = new Vector<String>(); Collection<UniqueID> removedId = new Vector<UniqueID>(); long pastTimestamp = System.currentTimeMillis() - TTA; for (Map.Entry<UniqueID, Referencer> entry : this.referencers.entrySet()) { UniqueID id = entry.getKey(); long timestamp = entry.getValue().getLastMessageTimestamp(); if (timestamp < pastTimestamp) { removedId.add(id); removed.add(id.shortString()); } } if (!removed.isEmpty()) { this.log(Level.DEBUG, "Removed " + removed.size() + " referencers: " + removed); this.incActivity(); for (UniqueID i : removedId) { this.referencers.remove(i); } if (this.referencers.isEmpty()) { this.aloneTimestamp = System.currentTimeMillis(); } } } /** * Build the message we are going to send to the referenced p */ private GCSimpleMessage buildMessageForProxy(boolean isMyActivity, Referenced parent, Referenced p) { boolean consensus = false; GCSimpleResponse resp = p.getLastResponse(); if (!isBusy() && (resp != null) && resp.getConsensusActivity().equals(this.lastActivity) && (isMyActivity || (parent != null))) { consensus = true; if (p.equals(parent)) { for (Referencer kr : this.referencers.values()) { boolean krConsensus = kr.getConsensus(this.lastActivity); consensus = consensus && krConsensus; if (!consensus) { break; } } } } return new GCSimpleMessage(p, this.body.getID(), consensus, this.lastActivity); } /** * A new referenced has been sent a GC message to, so now we can add it to * our weak references. */ private void promoteReferenced(UniversalBodyProxy ubp) { UniqueID proxyBodyId = ubp.getBodyID(); Referenced p = this.referenced.get(proxyBodyId); if (p == null) { p = new Referenced(ubp, this); this.referenced.put(proxyBodyId, p); } else { p.add(ubp); } } /** * Remove our referenced which weak reference is null. This can cause a * new activity. */ private Collection<Referenced> purgeReferenced() { Collection<Referenced> deleted = new LinkedList<Referenced>(); for (Map.Entry<UniqueID, Referenced> entry : this.referenced.entrySet()) { Referenced p = entry.getValue(); if (!p.isReferenced()) { deleted.add(p); } } if (!deleted.isEmpty()) { for (Referenced r : deleted) { this.referenced.remove(r.getBodyID()); } this.incActivity(); } return deleted; } private boolean isLastActivityMine() { return this.lastActivity.getBodyID().equals(this.body.getID()); } /** * Check if we found a new parent */ void newResponse(Referenced ref) { if (this.parent == null) { Activity refActivity = ref.getLastResponse().getConsensusActivity(); if (this.lastActivity.equals(refActivity) && !isLastActivityMine()) { this.parent = ref; } } } /** * Queue a message for each referenced */ private Collection<GCSimpleMessage> broadcast() { /* Remove old referencers */ purgeReferencers(); /* Add new referenced proxys */ for (UniversalBodyProxy ubp : this.newReferenced) { promoteReferenced(ubp); } this.newReferenced.clear(); /* Remove failing or unreferenced referenced proxys */ Collection<Referenced> deleted = this.purgeReferenced(); boolean isMyActivity = this.isLastActivityMine(); Collection<Referenced> refs = this.referenced.values(); this.log(Level.DEBUG, "Sending GC Message to " + refs.size() + " referencers: " + refs); Vector<GCSimpleMessage> messages = new Vector<GCSimpleMessage>(refs.size()); for (Referenced p : refs) { messages.add(buildMessageForProxy(isMyActivity, parent, p)); } if (!deleted.isEmpty()) { this.log(Level.DEBUG, "Deleting " + deleted.size() + " referenced: " + deleted); } return messages; } /** * The DGC found out that the AO is garbage */ private void terminateBody() { try { BodyRequest br = new BodyRequest(this.body, "terminate", new Class[0], new Object[0], false); br.send(this.body); // this.body.terminate(); Does not wake up the AO } catch (ProActiveRuntimeException e) { // org.objectweb.proactive.core.ProActiveRuntimeException: // Cannot perform this call because this body is inactive } catch (Exception e) { e.printStackTrace(); } } /** * Did the GC already do its job? */ boolean isFinished() { return this.finished != FinishedState.NOT_FINISHED; } /** * The GC has just done its job */ void setFinishedState(FinishedState state) { if (this.finished != FinishedState.NOT_FINISHED) { throw new IllegalStateException("Was already finished:" + this.finished); } this.finished = state; } /** * Terminate the AO if the DGC decides so */ private String checkConsensus() { if (this.isBusy()) { return null; } String goodbye = null; /* Did someone notify us of a cycle? */ boolean consensusAlreadyReached = false; for (Map.Entry<UniqueID, Referenced> entry : this.referenced.entrySet()) { if (entry.getValue().hasTerminated()) { goodbye = " entry.getKey().shortString() + " => PAF: " + this.lastActivity; this.setFinishedState(FinishedState.CYCLIC); consensusAlreadyReached = true; break; } } if (!consensusAlreadyReached) { if (this.referencers.isEmpty()) { if ((System.currentTimeMillis() - this.aloneTimestamp) <= TTA) { return null; } goodbye = " this.setFinishedState(FinishedState.ACYCLIC); } else { if (this.lastActivity.getBodyID().equals(this.body.getID())) { for (Referencer kr : this.referencers.values()) { if (!kr.getConsensus(this.lastActivity)) { return null; } } this.nrReachedConsensus++; /* We reached a consensus on my activity */ if (this.nrReachedConsensus < GarbageCollector.NR_CONSENSUS) { int backupNrReachedConsensus = this.nrReachedConsensus; // setLastActivity() will clear it this.incActivity(); this.nrReachedConsensus = backupNrReachedConsensus; return null; } goodbye = " this.lastActivity; this.setFinishedState(FinishedState.CYCLIC); } else { return null; } } } if (!(this.body instanceof HalfBody)) { terminateBody(); } return goodbye; } /** * Locally decide if an AO is busy, this can make a new activity * We don't handle the case of immediate services playing with the * request queue. */ protected boolean isBusy() { boolean currentlyBusy = this.registered; try { currentlyBusy = currentlyBusy || this.body.isInImmediateService(); } catch (IOException ioe) { ioe.printStackTrace(); } try { currentlyBusy = currentlyBusy || !this.body.getRequestQueue().isWaitingForRequest(); } catch (ProActiveRuntimeException pre) { /* Cannot perform this call because this body is inactive */ } if (previouslyBusy && !currentlyBusy) { this.incActivity(); } this.previouslyBusy = currentlyBusy; return currentlyBusy; } /** * Run by the broadcasting thread */ protected synchronized Collection<GCSimpleMessage> iteration() { if (!this.isFinished() && this.body.isAlive()) { String goodbye = this.checkConsensus(); this.iterations++; if (this.isFinished()) { this.log(Level.INFO, "Goodbye because: " + goodbye + " after " + iterations + " iterations"); } else { return this.broadcast(); } } return null; } /** * A new referenced was deserialized */ public synchronized void addProxy(AbstractBody body, UniversalBodyProxy proxy) { if (body != this.body) { this.log(Level.FATAL, "Wrong body"); } UniqueID proxyID = proxy.getBodyID(); if (!proxyID.equals(this.body.getID()) && !this.referenced.containsKey(proxyID)) { newReferenced.add(proxy); this.log(Level.DEBUG, "New referenced: " + proxy.getBodyID().shortString()); } } /** * For IC2D and the logs */ private String getStatus() { String state = this.isBusy() ? "busy" : "idle"; return state + " " + this.lastActivity + " from " + this.parent; } /** * For IC2D */ public static String getDgcState(UniqueID bodyID) { if (!dgcIsEnabled()) { return "DGC Disabled"; } AbstractBody body = (AbstractBody) LocalBodyStore.getInstance() .getLocalBody(bodyID); if (body == null) { AsyncLogger.queueLog(Level.WARN, "Body " + bodyID + " not found"); return "Body not found"; } GarbageCollector gc = body.getGarbageCollector(); return gc.body.getID().shortString() + ": " + gc.getStatus(); } /** * For IC2D */ public Collection<UniqueID> getReferencesID() { return new Vector<UniqueID>(this.referenced.keySet()); } /** * The method remotely called by the referencer on the referenced */ public synchronized GCResponse receiveGCMessage(GCMessage mesg) { long start = System.currentTimeMillis(); GCResponse response = new GCResponse(); this.log(Level.DEBUG, "Beginning processing of " + mesg.size() + " messages"); for (GCSimpleMessage m : mesg) { response.add(this.receiveSimpleGCMessage(m)); } long duration = System.currentTimeMillis() - start; this.log(Level.DEBUG, "Ending processing of " + mesg.size() + " messages in " + duration + " ms"); return response; } /** * Called for each message */ synchronized GCSimpleResponse receiveSimpleGCMessage(GCSimpleMessage mesg) { UniqueID senderID = mesg.getSender(); Referencer kr = this.referencers.get(senderID); GCSimpleResponse resp = null; if (this.finished == FinishedState.CYCLIC) { this.log(Level.DEBUG, "cycle to " + mesg.getSender().shortString()); if (kr == null) { this.log(Level.FATAL, "Cycle notification to a newcomer"); } resp = new GCTerminationResponse(this.lastActivity); } else if (this.finished == FinishedState.ACYCLIC) { throw new IllegalStateException(this.body.getID().shortString() + " thought it was alone but received " + mesg); } if (mesg.getLastActivity().strictlyMoreRecentThan(this.lastActivity)) { this.setLastActivity(mesg.getLastActivity()); } if (resp == null) { resp = new GCSimpleResponse(this.lastActivity); } if (kr == null) { /* new known referencer */ kr = new Referencer(); this.referencers.put(senderID, kr); this.log(Level.DEBUG, "New referencer: " + senderID.shortString()); } kr.setLastGCMessage(mesg); kr.setGivenActivity(resp.getConsensusActivity()); this.log(Level.DEBUG, mesg + " -> " + this.getStatus()); return resp; } /** * Check if we have to use the DGC */ private static Boolean cache = null; public static boolean dgcIsEnabled() { if (cache == null) { cache = new Boolean("true".equals(System.getProperty( "proactive.dgc"))); } return cache.booleanValue(); } /** * Wrapper for the logging method prefixing the message with the ID. */ public void log(Level level, String msg) { if (AsyncLogger.isEnabledFor(level)) { String prefix = level.toString().charAt(0) + ">"; prefix += ((this.body instanceof HalfBody) ? "h" : "b"); prefix += this.body.getID().shortString(); prefix += (" " + System.currentTimeMillis() + " "); msg = prefix + msg; AsyncLogger.queueLog(level, msg); } } /** * Inform the DGC whether the AO is pinned somewhere or not */ public synchronized void setRegistered(boolean registered) { this.registered = registered; } }
package org.opencms.file.types; import org.opencms.configuration.CmsConfigurationException; import org.opencms.db.CmsSecurityManager; import org.opencms.file.CmsFile; import org.opencms.file.CmsObject; import org.opencms.file.CmsProperty; import org.opencms.file.CmsPropertyDefinition; import org.opencms.file.CmsRequestContext; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.loader.CmsXmlSitemapLoader; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import org.opencms.relations.CmsLink; import org.opencms.relations.CmsRelationType; import org.opencms.relations.I_CmsLinkParseable; import org.opencms.security.CmsPermissionSet; import org.opencms.xml.CmsXmlContentDefinition; import org.opencms.xml.CmsXmlUtils; import org.opencms.xml.sitemap.CmsXmlSitemap; import org.opencms.xml.sitemap.CmsXmlSitemapFactory; import org.opencms.xml.types.CmsXmlVfsFileValue; import org.opencms.xml.types.I_CmsXmlContentValue; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Set; import org.apache.commons.logging.Log; /** * Resource type descriptor for the type "sitemap".<p> * * It is just a xml content with a fixed schema and id.<p> * * @author Michael Moossen * * @version $Revision: 1.10 $ * * @since 7.6 */ public class CmsResourceTypeXmlSitemap extends CmsResourceTypeXmlContent { /** Fixed detail page for sitemap pages. */ public static final String DETAIL_PAGE = "/system/workplace/editors/sitemap/sitemap.jsp"; /** Fixed schema for sitemap pages. */ public static final String SCHEMA = "/system/workplace/editors/sitemap/schemas/sitemap.xsd"; /** The log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsResourceTypeXmlSitemap.class); /** Indicates that the static configuration of the resource type has been frozen. */ private static boolean m_staticFrozen; /** The type id of this resource type. */ private static final int RESOURCE_TYPE_ID = 15; /** The name of this resource type. */ private static final String RESOURCE_TYPE_NAME = "sitemap"; /** * Default constructor that sets the fixed schema for container pages.<p> */ public CmsResourceTypeXmlSitemap() { super(); m_typeName = RESOURCE_TYPE_NAME; m_typeId = CmsResourceTypeXmlSitemap.RESOURCE_TYPE_ID; addConfigurationParameter(CONFIGURATION_SCHEMA, SCHEMA); try { addDefaultProperty(new CmsProperty(CmsPropertyDefinition.PROPERTY_TEMPLATE_ELEMENTS, null, DETAIL_PAGE)); } catch (CmsConfigurationException e) { // should never happen LOG.error(e.getLocalizedMessage(), e); } } /** * Returns the static type id of this (default) resource type.<p> * * @return the static type id of this (default) resource type */ public static int getStaticTypeId() { return RESOURCE_TYPE_ID; } /** * Returns the static type name of this (default) resource type.<p> * * @return the static type name of this (default) resource type */ public static String getStaticTypeName() { return RESOURCE_TYPE_NAME; } /** * Returns <code>true</code> in case the given resource is a sitemap.<p> * * Internally this checks if the type id for the given resource is * identical type id of the sitemap.<p> * * @param resource the resource to check * * @return <code>true</code> in case the given resource is a sitemap */ public static boolean isSitemap(CmsResource resource) { boolean result = false; if (resource != null) { result = (resource.getTypeId() == RESOURCE_TYPE_ID); } return result; } /** * @see org.opencms.file.types.CmsResourceTypeXmlContent#createResource(org.opencms.file.CmsObject, org.opencms.db.CmsSecurityManager, java.lang.String, byte[], java.util.List) */ @Override public CmsResource createResource( CmsObject cms, CmsSecurityManager securityManager, String resourcename, byte[] content, List<CmsProperty> properties) throws CmsException { boolean hasModelUri = false; CmsXmlSitemap newContent = null; if ((getSchema() != null) && ((content == null) || (content.length == 0))) { // unmarshal the content definition for the new resource CmsXmlContentDefinition contentDefinition = CmsXmlContentDefinition.unmarshal(cms, getSchema()); // read the default locale for the new resource Locale locale = OpenCms.getLocaleManager().getDefaultLocales(cms, CmsResource.getParentFolder(resourcename)).get( 0); String modelUri = (String)cms.getRequestContext().getAttribute(CmsRequestContext.ATTRIBUTE_MODEL); // must set URI of OpenCms user context to parent folder of created resource, // in order to allow reading of properties for default values CmsObject newCms = OpenCms.initCmsObject(cms); newCms.getRequestContext().setUri(CmsResource.getParentFolder(resourcename)); if (modelUri != null) { // create the new content from the model file newContent = CmsXmlSitemapFactory.createDocument(newCms, locale, modelUri); hasModelUri = true; } else { // create the new content from the content definition newContent = CmsXmlSitemapFactory.createDocument( newCms, locale, OpenCms.getSystemInfo().getDefaultEncoding(), contentDefinition); } // get the bytes from the created content content = newContent.marshal(); } // now create the resource using the super class CmsResource resource = super.createResource(cms, securityManager, resourcename, content, properties); // a model file was used, call the content handler for post-processing if (hasModelUri) { newContent = CmsXmlSitemapFactory.unmarshal(cms, resource); resource = newContent.getContentDefinition().getContentHandler().prepareForWrite( cms, newContent, newContent.getFile()); } return resource; } /** * @see org.opencms.file.types.CmsResourceTypeXmlContent#getLoaderId() */ @Override public int getLoaderId() { return CmsXmlSitemapLoader.RESOURCE_LOADER_ID; } /** * @see org.opencms.file.types.A_CmsResourceType#initConfiguration(java.lang.String, java.lang.String, String) */ @Override public void initConfiguration(String name, String id, String className) throws CmsConfigurationException { if ((OpenCms.getRunLevel() > OpenCms.RUNLEVEL_2_INITIALIZING) && m_staticFrozen) { // configuration already frozen throw new CmsConfigurationException(Messages.get().container( Messages.ERR_CONFIG_FROZEN_3, this.getClass().getName(), getStaticTypeName(), new Integer(getStaticTypeId()))); } if (!RESOURCE_TYPE_NAME.equals(name)) { // default resource type MUST have default name throw new CmsConfigurationException(Messages.get().container( Messages.ERR_INVALID_RESTYPE_CONFIG_NAME_3, this.getClass().getName(), RESOURCE_TYPE_NAME, name)); } if (!id.equals("" + RESOURCE_TYPE_ID)) { // default resource type MUST have id equals RESOURCE_TYPE_ID throw new CmsConfigurationException(Messages.get().container( Messages.ERR_INVALID_RESTYPE_CONFIG_ID_3, this.getClass().getName(), RESOURCE_TYPE_NAME, name)); } // freeze the configuration m_staticFrozen = true; super.initConfiguration(RESOURCE_TYPE_NAME, "" + RESOURCE_TYPE_ID, className); } /** * @see org.opencms.relations.I_CmsLinkParseable#parseLinks(org.opencms.file.CmsObject, org.opencms.file.CmsFile) */ @Override public List<CmsLink> parseLinks(CmsObject cms, CmsFile file) { if (file.getLength() == 0) { return Collections.emptyList(); } CmsXmlSitemap xmlContent; long requestTime = cms.getRequestContext().getRequestTime(); try { // prevent the check rules to remove the broken links cms.getRequestContext().setRequestTime(CmsResource.DATE_RELEASED_EXPIRED_IGNORE); xmlContent = CmsXmlSitemapFactory.unmarshal(cms, file); } catch (CmsException e) { if (LOG.isErrorEnabled()) { LOG.error(org.opencms.db.Messages.get().getBundle().key( org.opencms.db.Messages.ERR_READ_RESOURCE_1, cms.getSitePath(file)), e); } return Collections.emptyList(); } finally { cms.getRequestContext().setRequestTime(requestTime); } Set<CmsLink> links = new HashSet<CmsLink>(); // add XSD link CmsLink xsdLink = getXsdLink(cms, xmlContent); if (xsdLink != null) { links.add(xsdLink); } // iterate over all languages List<Locale> locales = xmlContent.getLocales(); Iterator<Locale> i = locales.iterator(); while (i.hasNext()) { Locale locale = i.next(); List<I_CmsXmlContentValue> values = xmlContent.getValues(locale); // iterate over all body elements per language Iterator<I_CmsXmlContentValue> j = values.iterator(); while (j.hasNext()) { I_CmsXmlContentValue value = j.next(); if (!(value instanceof CmsXmlVfsFileValue)) { // filter only relations relevant fields // sitemaps do not have XmlHtml nor VarFiles continue; } CmsXmlVfsFileValue refValue = (CmsXmlVfsFileValue)value; CmsLink link = refValue.getLink(cms); if (link == null) { // empty node continue; } if (CmsXmlUtils.removeXpathIndex(value.getPath()).equals(CmsXmlSitemap.XmlNode.EntryPoint.name())) { // entry points have an own relation type link = new CmsLink( link.getName(), CmsRelationType.ENTRY_POINT, link.getStructureId(), link.getUri(), true); } links.add(link); } } return new ArrayList<CmsLink>(links); } /** * @see org.opencms.file.types.CmsResourceTypeXmlContent#writeFile(org.opencms.file.CmsObject, org.opencms.db.CmsSecurityManager, org.opencms.file.CmsFile) */ @Override public CmsFile writeFile(CmsObject cms, CmsSecurityManager securityManager, CmsFile resource) throws CmsException { // check if the user has write access and if resource is locked securityManager.checkPermissions( cms.getRequestContext(), resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); // read the XML content, use the encoding set in the property CmsXmlSitemap xmlContent = CmsXmlSitemapFactory.unmarshal(cms, resource, false); // call the content handler for post-processing resource = xmlContent.getContentDefinition().getContentHandler().prepareForWrite(cms, xmlContent, resource); // now write the file CmsFile file = securityManager.writeFile(cms.getRequestContext(), resource); I_CmsResourceType type = getResourceType(file); // update the relations after writing!! List<CmsLink> links = null; if (type instanceof I_CmsLinkParseable) { // this check is needed because of type change // if the new type is link parseable links = ((I_CmsLinkParseable)type).parseLinks(cms, file); } // this has to be always executed, even if not link parseable to remove old links securityManager.updateRelationsForResource(cms.getRequestContext(), file, links); return file; } }
package org.pentaho.di.trans.steps.getxmldata; import java.io.FileInputStream; import java.io.StringReader; import java.util.List; import org.dom4j.io.SAXReader; import org.dom4j.XPath; import org.dom4j.tree.AbstractNode; import org.apache.commons.vfs.FileObject; import org.pentaho.di.core.Const; import org.pentaho.di.core.ResultFile; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.fileinput.FileInputList; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; /** * Read XML files, parse them and convert them to rows and writes these to one or more output * streams. * * @author Samatar,Brahim * @since 20-06-2007 */ public class GetXMLData extends BaseStep implements StepInterface { private GetXMLDataMeta meta; private GetXMLDataData data; public GetXMLData(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } protected boolean setDocument(String StringXML,FileObject file,boolean IsInXMLField) throws KettleException { try{ SAXReader reader = new SAXReader(); // Validate XML against specified schema? if(meta.isValidating()) { reader.setValidation(true); reader.setFeature("http://apache.org/xml/features/validation/schema", true); } if (IsInXMLField) { data.document= reader.read(new StringReader(StringXML)); } else { // get encoding. By default UTF-8 String encoding="UTF-8"; if (!Const.isEmpty(meta.getEncoding())) encoding=meta.getEncoding(); data.document = reader.read(new FileInputStream(KettleVFS.getFilename(file)),encoding); } }catch (Exception e) { throw new KettleException(e); } return true; } /** * Build an empty row based on the meta-data. * * @return */ private Object[] buildEmptyRow() { Object[] rowData = RowDataUtil.allocateRowData(data.outputRowMeta.size()); return rowData; } private void handleMissingFiles() throws KettleException { List<FileObject> nonExistantFiles = data.files.getNonExistantFiles(); if (nonExistantFiles.size() != 0) { String message = FileInputList.getRequiredFilesDescription(nonExistantFiles); if(log.isBasic()) log.logBasic("Required files", "WARNING: Missing " + message); throw new KettleException("Following required files are missing " +message); } List<FileObject> nonAccessibleFiles = data.files.getNonAccessibleFiles(); if (nonAccessibleFiles.size() != 0) { String message = FileInputList.getRequiredFilesDescription(nonAccessibleFiles); if(log.isBasic()) log.logBasic("Required files", "WARNING: Not accessible " + message); throw new KettleException("Following required files are not accessible " +message); } } private boolean ReadNextString() { try{ data.readrow= getRow(); // Grab another row ... if (data.readrow==null) // finished processing! { if (log.isDetailed()) logDetailed(Messages.getString("GetXMLData.Log.FinishedProcessing")); return false; } if(first) { first=false; if(meta.getIsInFields()) { data.inputRowMeta = getInputRowMeta(); data.outputRowMeta = data.inputRowMeta.clone(); meta.getFields(data.outputRowMeta, getStepname(), null, null, this); // Get total previous fields data.totalpreviousfields=data.inputRowMeta.size(); // Create convert meta-data objects that will contain Date & Number formatters data.convertRowMeta = data.outputRowMeta.clone(); for (int i=0;i<data.convertRowMeta.size();i++) data.convertRowMeta.getValueMeta(i).setType(ValueMetaInterface.TYPE_STRING); // For String to <type> conversions, we allocate a conversion meta data row as well... data.convertRowMeta = data.outputRowMeta.clone(); for (int i=0;i<data.convertRowMeta.size();i++) { data.convertRowMeta.getValueMeta(i).setType(ValueMetaInterface.TYPE_STRING); } // Check is XML field is provided if (Const.isEmpty(meta.getXMLField())) { logError(Messages.getString("GetXMLData.Log.NoField")); throw new KettleException(Messages.getString("GetXMLData.Log.NoField")); } // cache the position of the field if (data.indexOfXmlField<0) { data.indexOfXmlField =getInputRowMeta().indexOfValue(meta.getXMLField()); if (data.indexOfXmlField<0) { // The field is unreachable ! logError(Messages.getString("GetXMLData.Log.ErrorFindingField")+ "[" + meta.getXMLField()+"]"); //$NON-NLS-1$ //$NON-NLS-2$ throw new KettleException(Messages.getString("GetXMLData.Exception.CouldnotFindField",meta.getXMLField())); //$NON-NLS-1$ //$NON-NLS-2$ } } } } if(meta.getIsInFields()) { // get XML field value String Fieldvalue= getInputRowMeta().getString(data.readrow,data.indexOfXmlField); if(log.isDetailed()) log.logDetailed(toString(),Messages.getString("GetXMLData.Log.XMLStream", meta.getXMLField(),Fieldvalue)); if(meta.getIsAFile()) { FileObject file=null; try { // XML source is a file. file= KettleVFS.getFileObject(Fieldvalue); //Open the XML document if(!setDocument(null,file,false)) { throw new KettleException (Messages.getString("GetXMLData.Log.UnableCreateDocument")); } // Apply XPath and set node list if(!applyXPath()) { throw new KettleException (Messages.getString("GetXMLData.Log.UnableApplyXPath")); } addFileToResultFilesname(file); if(log.isDetailed()) log.logDetailed(toString(),Messages.getString("GetXMLData.Log.LoopFileOccurences",""+data.nodesize,file.getName().getBaseName())); } catch (Exception e) { throw new KettleException (e); }finally{try {if(file!=null) file.close();}catch (Exception e){} } } else { //Open the XML document if(!setDocument(Fieldvalue,null,true)) { throw new KettleException (Messages.getString("GetXMLData.Log.UnableCreateDocument")); } // Apply XPath and set node list if(!applyXPath()) { throw new KettleException (Messages.getString("GetXMLData.Log.UnableApplyXPath")); } if(log.isDetailed()) log.logDetailed(toString(),Messages.getString("GetXMLData.Log.LoopFileOccurences",""+data.nodesize)); } } } catch(Exception e) { logError(Messages.getString("GetXMLData.Log.UnexpectedError", e.toString())); stopAll(); logError(Const.getStackTracker(e)); setErrors(1); return false; } return true; } private void addFileToResultFilesname(FileObject file) throws Exception { if(meta.addResultFile()) { // Add this to the result file names... ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, file, getTransMeta().getName(), getStepname()); resultFile.setComment("File was read by an get XML Data step"); addResultFile(resultFile); } } @SuppressWarnings("unchecked") private boolean applyXPath() { try{ XPath xpath = data.document.createXPath(data.PathValue); data.an = (List<AbstractNode>) xpath.selectNodes(data.document); data.nodesize=data.an.size(); data.nodenr=0; }catch (Exception e) { log.logError(toString(),Messages.getString("GetXMLData.Log.ErrorApplyXPath",e.getMessage())); return false; } return true; } private boolean openNextFile() { try { if (data.filenr>=data.files.nrOfFiles()) // finished processing! { if (log.isDetailed()) logDetailed(Messages.getString("GetXMLData.Log.FinishedProcessing")); return false; } // Is this the last file? data.last_file = ( data.filenr==data.files.nrOfFiles()-1); data.file = (FileObject) data.files.getFile(data.filenr); // Check if file is empty long fileSize= data.file.getContent().getSize(); // Move file pointer ahead! data.filenr++; if(meta.isIgnoreEmptyFile() && fileSize==0) { log.logError(toString(),Messages.getString("GetXMLData.Error.FileSizeZero", ""+data.file.getName())); openNextFile(); }else { if (log.isDetailed()) log.logDetailed(toString(),Messages.getString("GetXMLData.Log.OpeningFile", data.file.toString())); //Open the XML document if(!setDocument(null,data.file,false)) { throw new KettleException (Messages.getString("GetXMLData.Log.UnableCreateDocument")); } // Apply XPath and set node list if(!applyXPath()) { throw new KettleException (Messages.getString("GetXMLData.Log.UnableApplyXPath")); } addFileToResultFilesname(data.file); if (log.isDetailed()) { logDetailed(Messages.getString("GetXMLData.Log.FileOpened", data.file.toString())); log.logDetailed(toString(),Messages.getString("GetXMLData.Log.LoopFileOccurences",""+data.nodesize,data.file.getName().getBaseName())); } } } catch(Exception e) { logError(Messages.getString("GetXMLData.Log.UnableToOpenFile", ""+data.filenr, data.file.toString(), e.toString())); stopAll(); setErrors(1); return false; } return true; } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { // Grab a row Object[] r=getXMLRow(); if (r==null) { setOutputDone(); // signal end to receiver(s) return false; // end of data or error. } return putRowOut(r); } private boolean putRowOut(Object[] r) throws KettleException { if (r==null) { setOutputDone(); // signal end to receiver(s) return false; // end of data or error. } if (log.isRowLevel()) logRowlevel(Messages.getString("GetXMLData.Log.ReadRow", r.toString())); incrementLinesInput(); data.rownr++; putRow(data.outputRowMeta, r); // copy row to output rowset(s); if (meta.getRowLimit()>0 && data.rownr>meta.getRowLimit()) // limit has been reached: stop now. { setOutputDone(); return false; } return true; } private Object[] getXMLRow() throws KettleException { if(!meta.getIsInFields()) { while ((data.nodenr>=data.nodesize || data.file==null)) { if (!openNextFile()) { return null; } } } // Build an empty row based on the meta-data Object[] r=null; boolean sendToErrorRow=false; String errorMessage = null; try{ if(meta.getIsInFields()) { while ((data.nodenr>=data.nodesize || data.readrow==null)) { if(!ReadNextString()) { return null; } if(data.readrow==null) { return null; } } } if(meta.getIsInFields()) r= processPutRow(data.readrow,(AbstractNode)data.an.get(data.nodenr)); else r= processPutRow(null,(AbstractNode)data.an.get(data.nodenr)); } catch (Exception e) { if (getStepMeta().isDoingErrorHandling()) { sendToErrorRow = true; errorMessage = e.toString(); } else { throw new KettleException("Unable to read row from XML file", e); } if (sendToErrorRow) { // Simply add this row to the error row putError(getInputRowMeta(), r, 1, errorMessage, null, "GetXMLData001"); } } return r; } private Object[] processPutRow(Object[] row,AbstractNode node) throws KettleException { // Create new row... Object[] outputRowData = buildEmptyRow(); try { data.nodenr++; if(row!=null) outputRowData = row.clone(); // Read fields... for (int i=0;i<data.nrInputFields;i++) { // Get field GetXMLDataField xmlDataField = meta.getInputFields()[i]; // Get the Path to look for String XPathValue = environmentSubstitute(xmlDataField.getXPath()); // Get the path type String Element_Type = xmlDataField.getElementTypeCode(); if(meta.isuseToken()) { // See if user use Token inside path field // The syntax is : @_Fieldname- // PDI will search for Fieldname value and replace it // Fieldname must be defined before the current node int indexvarstart=XPathValue.indexOf(data.tokenStart); int indexvarend=XPathValue.indexOf(data.tokenEnd); if(indexvarstart>=0 && indexvarend>=0) { String NameVarInputField = XPathValue.substring(indexvarstart+2, indexvarend); for (int k=0;k<meta.getInputFields().length;k++) { GetXMLDataField Tmp_xmlInputField = meta.getInputFields()[k]; if(Tmp_xmlInputField.getName().equalsIgnoreCase(NameVarInputField)) { XPathValue = XPathValue.replaceAll(data.tokenStart+NameVarInputField+data.tokenEnd,"'"+ outputRowData[k] +"'"); if ( log.isDetailed() ) { if(log.isDetailed()) log.logDetailed(toString(),XPathValue); } } } } } // Get node value String nodevalue =null; if (!Element_Type.equals("node")) XPathValue='@'+XPathValue; // Get node value nodevalue=node.valueOf(XPathValue); // Do trimming switch (xmlDataField.getTrimType()) { case GetXMLDataField.TYPE_TRIM_LEFT: nodevalue = Const.ltrim(nodevalue); break; case GetXMLDataField.TYPE_TRIM_RIGHT: nodevalue = Const.rtrim(nodevalue); break; case GetXMLDataField.TYPE_TRIM_BOTH: nodevalue = Const.trim(nodevalue); break; default: break; } if(meta.getIsInFields()) { // Add result field to input stream outputRowData = RowDataUtil.addValueData(outputRowData,data.totalpreviousfields+i, nodevalue); } // Do conversions ValueMetaInterface targetValueMeta = data.outputRowMeta.getValueMeta(data.totalpreviousfields+i); ValueMetaInterface sourceValueMeta = data.convertRowMeta.getValueMeta(data.totalpreviousfields+i); outputRowData[data.totalpreviousfields+i] = targetValueMeta.convertData(sourceValueMeta, nodevalue); // Do we need to repeat this field if it is null? if (meta.getInputFields()[i].isRepeated()) { if (data.previousRow!=null && Const.isEmpty(nodevalue)) { outputRowData[i] = data.previousRow[i]; } } }// End of loop over fields... int rowIndex = data.nrInputFields; // See if we need to add the filename to the row... if ( meta.includeFilename() && !Const.isEmpty(meta.getFilenameField()) ) { outputRowData[rowIndex++] = KettleVFS.getFilename(data.file); } // See if we need to add the row number to the row... if (meta.includeRowNumber() && !Const.isEmpty(meta.getRowNumberField())) { outputRowData[rowIndex++] = new Long(data.rownr); } RowMetaInterface irow = getInputRowMeta(); data.previousRow = irow==null?outputRowData:(Object[])irow.cloneRow(outputRowData); // copy it to make // surely the next step doesn't change it in between... } catch(Exception e) { log.logError(toString(), e.toString()); throw new KettleException(e.toString()); } return outputRowData; } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta=(GetXMLDataMeta)smi; data=(GetXMLDataData)sdi; if (super.init(smi, sdi)) { if(!meta.getIsInFields()) { // We process given file list data.files = meta.getFiles(this); if (data.files.nrOfFiles() == 0 && data.files.nrOfMissingFiles() == 0) { logError(Messages.getString("GetXMLData.Log.NoFiles")); return false; } try{ handleMissingFiles(); // Create the output row meta-data data.outputRowMeta = new RowMeta(); meta.getFields(data.outputRowMeta, getStepname(), null, null, this); // Create convert meta-data objects that will contain Date & Number formatters data.convertRowMeta = data.outputRowMeta.clone(); for (int i=0;i<data.convertRowMeta.size();i++) data.convertRowMeta.getValueMeta(i).setType(ValueMetaInterface.TYPE_STRING); // For String to <type> conversions, we allocate a conversion meta data row as well... data.convertRowMeta = data.outputRowMeta.clone(); for (int i=0;i<data.convertRowMeta.size();i++) { data.convertRowMeta.getValueMeta(i).setType(ValueMetaInterface.TYPE_STRING); } } catch(Exception e) { logError("Error initializing step: "+e.toString()); logError(Const.getStackTracker(e)); return false; } } data.rownr = 1L; data.nrInputFields=meta.getInputFields().length; data.PathValue=environmentSubstitute(meta.getLoopXPath()); if(!data.PathValue.substring(0,1).equals("/")) data.PathValue="/" + data.PathValue; if(log.isDetailed()) log.logDetailed(toString(),Messages.getString("GetXMLData.Log.LoopXPath",data.PathValue)); return true; } return false; } public void dispose(StepMetaInterface smi, StepDataInterface sdi) { meta = (GetXMLDataMeta) smi; data = (GetXMLDataData) sdi; if(data.file!=null) { try{ data.file.close(); }catch (Exception e){} } super.dispose(smi, sdi); } // Run is were the action happens! public void run() { BaseStep.runStepThread(this, meta, data); } }
package sudoku; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.Collections; import java.util.List; import java.util.Scanner; import java.util.function.BiConsumer; import java.util.stream.Collectors; import java.util.stream.IntStream; import sudoku.parse.Parser; import sudoku.Claim; import sudoku.Puzzle; import sudoku.Puzzle.IndexValue; import sudoku.Rule; /** * <p>This class provides less verbose {@link #log(String) access} * to a log file to which to print debugging information.</p> * @author fiveham * */ public class Debug { private static final State state = State.LOG; private static final PrintStream log = System.out;// initLog(); /** * <p>Creates the PrintStream referred to by {@code log}, * which points to a file named "dump.txt".</p> * <p>{@code log} is initialized by a call to this method.</p> * @return the PrintStream to be stored in {@code log} */ private static PrintStream initLog(){ try{ File f = new File("dump.txt"); System.out.println("Creating log file: "+f.getAbsolutePath()); return new PrintStream(f); } catch(FileNotFoundException e){ System.out.println("Error: Could not open log file for writing."); System.exit(1); return null; } } /** * <p>Prints {@code s} to the file specified by {@code log}.</p> * @param s the string to be printed to the file specified by * {@code log} */ public static void log(Object s){ state.log(log,s); } public static void log(boolean wrap, Object s){ state.log(log, wrap?wrap(s.toString()):s); } private static final int WRAP_LEN = 2+"[Rule: The 1 in BOX 1, Rule: The 1 in BOX 2, Rule: The 1 in BOX 3, Rule: The 1 in BOX 8, Rule: The 1 in BOX 9, Rule: The 2 in BOX 6, Rule: The 2 in BOX 7, Rule: The 3 in BOX 2, Ru".length(); private static String wrap(String s){ StringBuilder out = new StringBuilder(); Scanner scanner = new Scanner(s); while(scanner.hasNextLine()){ List<String> newLines = wrapLine(scanner.nextLine()); for(String newLine : newLines){ out.append(newLine).append(System.lineSeparator()); } } scanner.close(); return out.toString(); } private static List<String> wrapLine(String line){ List<String> result = new java.util.ArrayList<>(); for(int breakIndex, pointer = 0; pointer < line.length(); pointer = breakIndex){ breakIndex = breakIndex(line); result.add(line.substring(pointer, breakIndex)); } return result; } private static int breakIndex(String line){ int i = WRAP_LEN; for(; i>0; --i){ char c = line.charAt(i); if(Character.isWhitespace(c)){ return i; } } for(i=WRAP_LEN+1; i<line.length(); ++i){ char c = line.charAt(i); if(Character.isWhitespace(c)){ return i; } } return i; } /** * <p>Prints a newline to the file specified by {@code log}.</p> */ public static void log(){ state.log(log,""); } private static enum State{ NO_LOG( (ps,o) -> {}), LOG(PrintStream::println); private final BiConsumer<PrintStream,Object> writer; private State(BiConsumer<PrintStream,Object> writer){ this.writer = writer; } private void log(PrintStream ps, Object o){ writer.accept(ps,o); } } public static void main(String[] args){ Puzzle p = new Puzzle(new Parser(){ @Override public List<Integer> values(){ return IntStream.range(0, 81).map((i) -> 0).mapToObj(Integer.class::cast).collect(Collectors.toList()); } @Override public int mag(){ return 3; } }); IndexValue indexValue = p.indexValues().get(3); Claim c = new Claim(p, indexValue, indexValue, indexValue); Rule r; { List<Claim> claims = Collections.singletonList(c); Puzzle.IndexInstance y = p.indexInstances(Puzzle.DimensionType.Y).get(3); Puzzle.IndexInstance x = p.indexInstances(Puzzle.DimensionType.X).get(3); r = new Rule(p, Puzzle.RuleType.CELL, claims, y, x); } System.out.println(); System.out.println("Created and linked R and C"); System.out.println(); System.out.println(c); System.out.println(c.contentString()); System.out.println(); System.out.println(r); System.out.println(r.contentString()); c.remove(r); System.out.println(); System.out.println("Pulled R out of C"); System.out.println(); System.out.println(c); System.out.println(c.contentString()); System.out.println(); System.out.println(r); System.out.println(r.contentString()); r.remove(c); System.out.println(); System.out.println("Pulled C out of R"); System.out.println(); System.out.println(c); System.out.println(c.contentString()); System.out.println(); System.out.println(r); System.out.println(r.contentString()); } }
package org.rubyforge.debugcommons.model; import java.io.File; import org.rubyforge.debugcommons.RubyDebuggerException; import org.rubyforge.debugcommons.RubyDebuggerProxy; import org.rubyforge.debugcommons.Util; public final class RubyDebugTarget extends RubyEntity { private final Process process; private final int port; private final String debuggedFile; private final File baseDir; private RubyThread[] threads; public RubyDebugTarget(RubyDebuggerProxy proxy, Process process, int port, String debuggedFile, File baseDir) { super(proxy); this.process = process; this.port = port; this.debuggedFile = new File(debuggedFile).getName(); this.baseDir = baseDir; this.threads = new RubyThread[0]; } public Process getProcess() { return process; } public int getPort() { return port; } public String getDebuggedFile() { return debuggedFile; } public File getBaseDir() { return baseDir; } private void updateThreads() throws RubyDebuggerException { // preconditions: // 1) both threadInfos and updatedThreads are sorted by their id attribute // 2) once a thread has died its id is never reused for new threads again. // Instead each new thread gets an id which is the currently highest id + 1. Util.fine("udpating threads"); RubyThreadInfo[] threadInfos = getProxy().readThreadInfo(); RubyThread[] updatedThreads = new RubyThread[threadInfos.length]; int threadIndex = 0; synchronized (this) { for (int i = 0; i < threadInfos.length; i++) { while (threadIndex < threads.length && threadInfos[i].getId() != threads[threadIndex].getId()) { // step over dead threads, which do not occur in threadInfos anymore threadIndex += 1; } if (threadIndex == threads.length) { updatedThreads[i] = new RubyThread(this, threadInfos[i].getId()); } else { updatedThreads[i] = threads[threadIndex]; } } threads = updatedThreads; } } public void suspensionOccurred(SuspensionPoint suspensionPoint) { RubyThread thread = null; try { updateThreads(); } catch (RubyDebuggerException e) { if (getProxy().checkConnection()) { throw new RuntimeException("Cannot update threads", e); } else { Util.fine("Session has finished. Ignoring unsuccessful thread update."); return; } } thread = getThreadById(suspensionPoint.getThreadId()); if (thread == null) { Util.warning("Thread with id " + suspensionPoint.getThreadId() + " was not found"); return; } thread.suspend(suspensionPoint); } /** * Look up Ruby thread corresponding to the given id. * * @return {@link RubyThread} instance or <code>null</code> if no thread if * found. */ public synchronized RubyThread getThreadById(int id) { for (RubyThread thread : threads) { if (thread.getId() == id) { return thread; } } return null; } public boolean isRunning() { return Util.isRunning(process); } }
package jfxtras.scene.control.window; import javafx.animation.Animation; import javafx.animation.ScaleTransition; import javafx.animation.Transition; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.Property; import javafx.beans.property.ReadOnlyBooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Bounds; import javafx.scene.control.Control; import javafx.scene.layout.Pane; import javafx.scene.layout.StackPane; import javafx.util.Duration; import jfxtras.util.NodeUtil; public class Window extends Control implements SelectableNode { /** * Default css style. */ public static final String DEFAULT_STYLE = "/jfxtras/labs/scene/control/window/default.css"; /** * Default style class for css. */ public static final String DEFAULT_STYLE_CLASS = "window"; /** * Defines whether window is moved to front when user clicks on it */ private boolean moveToFront = true; /** * Window title property (used by titlebar) */ private final StringProperty titleProperty = new SimpleStringProperty("Title"); /** * Minimize property (defines whether to minimize the window,performed by * skin) */ private final BooleanProperty minimizeProperty = new SimpleBooleanProperty(); /** * Resize property (defines whether is the window resizeable,performed by * skin) */ private final BooleanProperty resizableProperty = new SimpleBooleanProperty(true); /** * Resize property (defines whether is the window movable,performed by skin) */ private final BooleanProperty movableProperty = new SimpleBooleanProperty(true); /** * Content pane property. The content pane is the pane that is responsible * for showing user defined nodes/content. */ private final Property<Pane> contentPaneProperty = new SimpleObjectProperty<>(); /** * List of icons shown on the left. TODO replace left/right with more * generic position property? */ private final ObservableList<WindowIcon> leftIcons = FXCollections.observableArrayList(); /** * List of icons shown on the right. TODO replace left/right with more * generic position property? */ private final ObservableList<WindowIcon> rightIcons = FXCollections.observableArrayList(); /** * Defines the width of the border /area where the user can grab the window * and resize it. */ private final DoubleProperty resizableBorderWidthProperty = new SimpleDoubleProperty(5); /** * Defines the titlebar class name. This can be used to define css * properties specifically for the titlebar, e.g., background. */ private final StringProperty titleBarStyleClassProperty = new SimpleStringProperty("window-titlebar"); /** * defines the action that shall be performed before the window is closed. */ private final ObjectProperty<EventHandler<ActionEvent>> onCloseActionProperty = new SimpleObjectProperty<>(); /** * defines the action that shall be performed after the window has been * closed. */ private final ObjectProperty<EventHandler<ActionEvent>> onClosedActionProperty = new SimpleObjectProperty<>(); /** * defines the transition that shall be played when closing the window. */ private final ObjectProperty<Transition> closeTransitionProperty = new SimpleObjectProperty<>(); /** * Selected property (defines whether this window is selected. */ private final BooleanProperty selectedProperty = new SimpleBooleanProperty(false); /** * Selectable property (defines whether this window is selectable. */ private final BooleanProperty selectableProperty = new SimpleBooleanProperty(true); private final BooleanProperty boundsListenerEnabledProperty = new SimpleBooleanProperty(true); private ChangeListener<Bounds> boundsListener; /** * Constructor. */ public Window() { init(); } /** * Constructor. * * @param title window title */ public Window(String title) { setTitle(title); init(); } private void init() { getStyleClass().setAll(DEFAULT_STYLE_CLASS); setContentPane(new StackPane()); // TODO ugly to do this in control? probably violates pattern rules? boundsListener = (ObservableValue<? extends Bounds> ov, Bounds t, Bounds t1) -> { if (getParent() != null) { if (t1.equals(t)) { return; } getParent().requestLayout(); double x = Math.max(0, getLayoutX()); double y = Math.max(0, getLayoutY()); setLayoutX(x); setLayoutY(y); } }; boundsListenerEnabledProperty.addListener((ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> { if (newValue) { boundsInParentProperty().addListener(boundsListener); } else { boundsInParentProperty().removeListener(boundsListener); } }); closeTransitionProperty.addListener(new ChangeListener<Transition>() { @Override public void changed(ObservableValue<? extends Transition> ov, Transition t, Transition t1) { t1.statusProperty().addListener(new ChangeListener<Animation.Status>() { @Override public void changed(ObservableValue<? extends Animation.Status> observableValue, Animation.Status oldValue, Animation.Status newValue) { if (newValue == Animation.Status.STOPPED) { // we don't fire action events twice if (Window.this.getParent() == null) { return; } if (getOnCloseAction() != null) { getOnCloseAction().handle(new ActionEvent(this, Window.this)); } // if someone manually removed us from parent, we don't // do anything if (Window.this.getParent() != null) { NodeUtil.removeFromParent(Window.this); } if (getOnClosedAction() != null) { getOnClosedAction().handle(new ActionEvent(this, Window.this)); } } } }); } }); ScaleTransition st = new ScaleTransition(); st.setNode(this); st.setFromX(1); st.setFromY(1); st.setToX(0); st.setToY(0); st.setDuration(Duration.seconds(0.2)); setCloseTransition(st); } @Override protected String getUserAgentStylesheet() { return this.getClass().getResource(DEFAULT_STYLE).toExternalForm(); } /** * @return the content pane of this window */ public Pane getContentPane() { return contentPaneProperty.getValue(); } /** * Defines the content pane of this window. * * @param contentPane content pane to set */ public void setContentPane(Pane contentPane) { contentPaneProperty.setValue(contentPane); } /** * Content pane property. * * @return content pane property */ public Property<Pane> contentPaneProperty() { return contentPaneProperty; } /** * Defines whether this window shall be moved to front when a user clicks on * the window. * * @param moveToFront the state to set */ public void setMoveToFront(boolean moveToFront) { this.moveToFront = moveToFront; } /** * Indicates whether the window shall be moved to front when a user clicks * on the window. * * @return <code>true</code> if the window shall be moved to front when a * user clicks on the window; <code>false</code> otherwise */ public boolean isMoveToFront() { return moveToFront; } /** * Returns the window title. * * @return the title */ public final String getTitle() { return titleProperty.get(); } /** * Defines the window title. * * @param title the title to set */ public final void setTitle(String title) { this.titleProperty.set(title); } /** * Returns the window title property. * * @return the window title property */ public final StringProperty titleProperty() { return titleProperty; } /** * Returns a list that contains the icons that are placed on the left side * of the titlebar. Add icons to the list to add them to the left side of * the window titlebar. * * @return a list containing the left icons * * @see #getRightIcons() */ public ObservableList<WindowIcon> getLeftIcons() { return leftIcons; } /** * Returns a list that contains the icons that are placed on the right side * of the titlebar. Add icons to the list to add them to the right side of * the window titlebar. * * @return a list containing the right icons * * @see #getLeftIcons() */ public ObservableList<WindowIcon> getRightIcons() { return rightIcons; } /** * Defines whether this window shall be minimized. * * @param v the state to set */ public void setMinimized(boolean v) { minimizeProperty.set(v); } /** * Indicates whether the window is currently minimized. * * @return <code>true</code> if the window is currently minimized; * <code>false</code> otherwise */ public boolean isMinimized() { return minimizeProperty.get(); } /** * Returns the minimize property. * * @return the minimize property */ public BooleanProperty minimizedProperty() { return minimizeProperty; } /** * Defines whether this window shall be resizeable by the user. * * @param v the state to set */ public void setResizableWindow(boolean v) { resizableProperty.set(v); } /** * Indicates whether the window is resizeable by the user. * * @return <code>true</code> if the window is resizeable; <code>false</code> * otherwise */ public boolean isResizableWindow() { return resizableProperty.get(); } /** * Returns the resize property. * * @return the minimize property */ public BooleanProperty resizeableWindowProperty() { return resizableProperty; } /** * Defines whether this window shall be movable. * * @param v the state to set */ public void setMovable(boolean v) { movableProperty.set(v); } /** * Indicates whether the window is movable. * * @return <code>true</code> if the window is movable; <code>false</code> * otherwise */ public boolean isMovable() { return movableProperty.get(); } /** * Returns the movable property. * * @return the minimize property */ public BooleanProperty movableProperty() { return movableProperty; } /** * Returns the titlebar style class property. * * @return the titlebar style class property */ public StringProperty titleBarStyleClassProperty() { return titleBarStyleClassProperty; } /** * Defines the CSS style class of the titlebar. * * @param name the CSS style class name */ public void setTitleBarStyleClass(String name) { titleBarStyleClassProperty.set(name); } /** * Returns the CSS style class of the titlebar. * * @return the CSS style class of the titlebar */ public String getTitleBarStyleClass() { return titleBarStyleClassProperty.get(); } /** * Returns the resizable border width property. * * @return the resizable border width property * * @see #setResizableBorderWidth(double) */ public DoubleProperty resizableBorderWidthProperty() { return resizableBorderWidthProperty; } /** * Defines the width of the "resizable border" of the window. The resizable * border is usually defined as a rectangular border around the layout * bounds of the window where the mouse cursor changes to "resizable" and * which allows to resize the window by performing a "dragging gesture", * i.e., the user can "grab" the window border and change the size of the * window. * * @param v border width */ public void setResizableBorderWidth(double v) { resizableBorderWidthProperty.set(v); } /** * Returns the width of the "resizable border" of the window. * * @return the width of the "resizable border" of the window * * @see #setResizableBorderWidth(double) */ public double getResizableBorderWidth() { return resizableBorderWidthProperty.get(); } /** * Closes this window. */ public void close() { // if already closed, we do nothing if (this.getParent() == null) { return; } if (getCloseTransition() != null) { getCloseTransition().play(); } else { if (getOnCloseAction() != null) { getOnCloseAction().handle(new ActionEvent(this, Window.this)); } NodeUtil.removeFromParent(Window.this); if (getOnClosedAction() != null) { getOnClosedAction().handle(new ActionEvent(this, Window.this)); } } } /** * Returns the "on-closed-action" property. * * @return the "on-closed-action" property. * * @see #setOnClosedAction(javafx.event.EventHandler) */ public ObjectProperty<EventHandler<ActionEvent>> onClosedActionProperty() { return onClosedActionProperty; } /** * Defines the action that shall be performed after the window has been * closed. * * @param onClosedAction the action to set */ public void setOnClosedAction(EventHandler<ActionEvent> onClosedAction) { this.onClosedActionProperty.set(onClosedAction); } /** * Returns the action that shall be performed after the window has been * closed. * * @return the action that shall be performed after the window has been * closed or <code>null</code> if no such action has been defined */ public EventHandler<ActionEvent> getOnClosedAction() { return this.onClosedActionProperty.get(); } /** * Returns the "on-close-action" property. * * @return the "on-close-action" property. * * @see #setOnCloseAction(javafx.event.EventHandler) */ public ObjectProperty<EventHandler<ActionEvent>> onCloseActionProperty() { return onCloseActionProperty; } /** * Defines the action that shall be performed before the window will be * closed. * * @param onClosedAction the action to set */ public void setOnCloseAction(EventHandler<ActionEvent> onClosedAction) { this.onCloseActionProperty.set(onClosedAction); } /** * Returns the action that shall be performed before the window will be * closed. * * @return the action that shall be performed before the window will be * closed or <code>null</code> if no such action has been defined */ public EventHandler<ActionEvent> getOnCloseAction() { return this.onCloseActionProperty.get(); } /** * Returns the "close-transition" property. * * @return the "close-transition" property. * * @see #setCloseTransition(javafx.animation.Transition) */ public ObjectProperty<Transition> closeTransitionProperty() { return closeTransitionProperty; } /** * Defines the transition that shall be used to indicate window closing. * * @param t the transition that shall be used to indicate window closing or * <code>null</code> if no transition shall be used. */ public void setCloseTransition(Transition t) { closeTransitionProperty.set(t); } /** * Returns the transition that shall be used to indicate window closing. * * @return the transition that shall be used to indicate window closing or * <code>null</code> if no such transition has been defined */ public Transition getCloseTransition() { return closeTransitionProperty.get(); } @Override public boolean requestSelection(boolean select) { if (!select) { selectedProperty.set(false); } if (isSelectable()) { selectedProperty.set(select); return true; } else { return false; } } /** * @return the selectableProperty */ public BooleanProperty selectableProperty() { return selectableProperty; } public void setSelectable(Boolean selectable) { selectableProperty.set(selectable); } public boolean isSelectable() { return selectableProperty.get(); } /** * @return the selectedProperty */ public ReadOnlyBooleanProperty selectedProperty() { return selectedProperty; } public boolean isSelected() { return selectedProperty.get(); } /** * @return the boundsListenerEnabledProperty */ public BooleanProperty boundsListenerEnabledProperty() { return boundsListenerEnabledProperty; } public void setBoundsListenerEnabled(boolean state) { boundsListenerEnabledProperty().set(state); } public boolean getBoundsListenerEnabled() { return boundsListenerEnabledProperty.get(); } }
package com.belladati.sdk; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import com.belladati.sdk.exception.InvalidImplementationException; /** * Serves as the entry point to the BellaDati SDK. Use either of the connect * methods to connect to a server, then authenticate to access a user's data. * <p /> * It is recommended to use only one {@link BellaDatiConnection} per server to * allow reuse of connection resources. Most client applications will connect * only to a single BellaDati server - BellaDati cloud or an on-premise * installation - meaning only one connection should be used. * <p /> * The SDK uses default timeouts of 10 seconds which should work fine for most * servers and internet connections. For environments that require different * settings, timeouts and connection management can be configured using system * properties: * <ul> * <li><strong>bdTimeout</strong>: Sets all timeouts without an individual * setting to the given value.</li> * <li><strong>bdConnectionRequestTimeout</strong>: Timeout for getting a * connection from the local connection manager.</li> * <li><strong>bdConnectTimeout</strong>: Timeout for establishing a connection * to the server.</li> * <li><strong>bdSocketTimeout</strong>: Timeout while waiting for data from the * server.</li> * <li><strong>bdMaxConnections</strong>: Maximum number of simultaneous API * connections. Defaults to 40, which should be plenty for most applications. If * your application sends large amounts of concurrent requests, local caching * may result in better performance than increasing this setting.</li> * </ul> * All timeouts are set in milliseconds. These properties only affect new * connections being created and don't change existing connections. If needed, * set the timeouts before calling any of the {@link #connect()} methods. * * * @author Chris Hennigfeld */ public class BellaDati { /** * Connects to the BellaDati cloud service. * * @return a connection to the BellaDati cloud service */ public static BellaDatiConnection connect() { return connect("https://service.belladati.com/"); } /** * Connects to a BellaDati server hosted at the specified URL. * * @param baseUrl URL of the BellaDati server * @return a connection to the BellaDati server hosted at the specified URL */ public static BellaDatiConnection connect(String baseUrl) { return connect(baseUrl, false); } /** * Connects to a BellaDati server hosted at the specified URL. This * connection accepts servers using self-signed SSL certificates. * <p /> * <b>Warning:</b> Avoid using this type of connection whenever possible. * When using a server without a certificate signed by a known certificate * authority, an attacker could impersonate your server and intercept * passwords or sensitive data sent by the SDK. * * @param baseUrl URL of the BellaDati server * @return a connection to the BellaDati server hosted at the specified URL */ public static BellaDatiConnection connectInsecure(String baseUrl) { return connect(baseUrl, true); } private static BellaDatiConnection connect(String baseUrl, boolean trustSelfSigned) { try { return (BellaDatiConnection) getConnectionConstructor().newInstance(baseUrl, trustSelfSigned); } catch (ClassNotFoundException e) { throw new InvalidImplementationException("Failed to instantiate connection", e); } catch (NoSuchMethodException e) { throw new InvalidImplementationException("Failed to instantiate connection", e); } catch (InvocationTargetException e) { throw new InvalidImplementationException("Failed to instantiate connection", e); } catch (IllegalAccessException e) { throw new InvalidImplementationException("Failed to instantiate connection", e); } catch (InstantiationException e) { throw new InvalidImplementationException("Failed to instantiate connection", e); } catch (IllegalArgumentException e) { throw new InvalidImplementationException("Failed to instantiate connection", e); } catch (SecurityException e) { throw new InvalidImplementationException("Failed to instantiate connection", e); } catch (ClassCastException e) { throw new InvalidImplementationException("Failed to instantiate connection", e); } } /** * Reflectively loads the implementation's constructor to open a * {@link BellaDatiConnection}. * * @return the constructor of a {@link BellaDatiConnection} implementation * @throws ClassNotFoundException if the implementing class isn't found * @throws NoSuchMethodException if no constructor exists for the expected * arguments * @throws SecurityException if access is denied */ private static Constructor<?> getConnectionConstructor() throws ClassNotFoundException, NoSuchMethodException, SecurityException { Class<?> clazz = Class.forName("com.belladati.sdk.impl.BellaDatiConnectionImpl"); Constructor<?> constructor = clazz.getDeclaredConstructor(String.class, Boolean.TYPE); constructor.setAccessible(true); return constructor; } }
package com.dmdirc.parser; import com.dmdirc.parser.callbacks.CallbackManager; import com.dmdirc.parser.callbacks.CallbackOnConnectError; import com.dmdirc.parser.callbacks.CallbackOnDataIn; import com.dmdirc.parser.callbacks.CallbackOnDataOut; import com.dmdirc.parser.callbacks.CallbackOnDebugInfo; import com.dmdirc.parser.callbacks.CallbackOnErrorInfo; import com.dmdirc.parser.callbacks.CallbackOnServerError; import com.dmdirc.parser.callbacks.CallbackOnSocketClosed; import com.dmdirc.parser.callbacks.CallbackOnPingFailed; import com.dmdirc.parser.callbacks.CallbackOnPingSent; import com.dmdirc.parser.callbacks.CallbackOnPingSuccess; import com.dmdirc.parser.callbacks.CallbackOnPost005; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.Socket; import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.Collection; import java.util.Hashtable; import java.util.LinkedList; import java.util.Timer; import java.util.Queue; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; /** * IRC Parser. * * @author Shane Mc Cormack * @version $Id$ */ public class IRCParser implements Runnable { /** Max length an outgoing line should be (NOT including \r\n). */ public static final int MAX_LINELENGTH = 510; /** General Debug Information. */ public static final int DEBUG_INFO = 1; /** Socket Debug Information. */ public static final int DEBUG_SOCKET = 2; /** Processing Manager Debug Information. */ public static final int DEBUG_PROCESSOR = 4; /** List Mode Queue Debug Information. */ public static final int DEBUG_LMQ = 8; // public static final int DEBUG_SOMETHING = 16; //Next thingy /** Socket is not created yet. */ public static final byte STATE_NULL = 0; /** Socket is closed. */ public static final byte STATE_CLOSED = 1; /** Socket is Open. */ public static final byte STATE_OPEN = 2; /** Attempt to update user host all the time, not just on Who/Add/NickChange. */ static final boolean ALWAYS_UPDATECLIENT = true; /** Byte used to show that a non-boolean mode is a list (b). */ static final byte MODE_LIST = 1; /** Byte used to show that a non-boolean mode is not a list, and requires a parameter to set (lk). */ static final byte MODE_SET = 2; /** Byte used to show that a non-boolean mode is not a list, and requires a parameter to unset (k). */ static final byte MODE_UNSET = 4; /** * This is what the user wants settings to be. * Nickname here is *not* always accurate.<br><br> * ClientInfo variable tParser.getMyself() should be used for accurate info. */ public MyInfo me = new MyInfo(); /** Server Info requested by user. */ public ServerInfo server = new ServerInfo(); /** Timer for server ping. */ private Timer pingTimer = null; /** Length of time to wait between ping stuff. */ private long pingTimerLength = 10000; /** Is a ping needed? */ private volatile Boolean pingNeeded = false; /** Time last ping was sent at. */ private long pingTime; /** Current Server Lag. */ private long serverLag; /** Last value sent as a ping argument. */ private String lastPingValue = ""; /** * Count down to next ping. * The timer fires every 10 seconds, this value is decreased every time the * timer fires.<br> * Once it reaches 0, we send a ping, and reset it to 6, this means we ping * the server every minute. * * @see setPingCountDownLength */ private byte pingCountDown; /** * Amount of times the timer has to fire for inactivity before sending a ping. * * @see setPingCountDownLength */ private byte pingCountDownLength = 6; /** Name the server calls itself. */ String sServerName; /** Network name. This is "" if no network name is provided */ String sNetworkName; /** This is what we think the nickname should be. */ String sThinkNickname; /** When using inbuilt pre-001 NickInUse handler, have we tried our AltNick. */ boolean triedAlt; /** Have we recieved the 001. */ boolean got001; /** Have we fired post005? */ boolean post005; /** Has the thread started execution yet, (Prevents run() being called multiple times). */ boolean hasBegan; /** Is this line the first line we have seen? */ boolean isFirst = true; /** Hashtable storing known prefix modes (ohv). */ Hashtable<Character, Long> hPrefixModes = new Hashtable<Character, Long>(); /** * Hashtable maping known prefix modes (ohv) to prefixes (@%+) - Both ways. * Prefix map contains 2 pairs for each mode. (eg @ => o and o => @) */ Hashtable<Character, Character> hPrefixMap = new Hashtable<Character, Character>(); /** Integer representing the next avaliable integer value of a prefix mode. */ long nNextKeyPrefix = 1; /** Hashtable storing known user modes (owxis etc). */ Hashtable<Character, Long> hUserModes = new Hashtable<Character, Long>(); /** Integer representing the next avaliable integer value of a User mode. */ long nNextKeyUser = 1; /** * Hashtable storing known boolean chan modes (cntmi etc). * Valid Boolean Modes are stored as Hashtable.pub('m',1); where 'm' is the mode and 1 is a numeric value.<br><br> * Numeric values are powers of 2. This allows up to 32 modes at present (expandable to 64)<br><br> * ChannelInfo/ChannelClientInfo etc provide methods to view the modes in a human way.<br><br> * <br> * Channel modes discovered but not listed in 005 are stored as boolean modes automatically (and a ERROR_WARNING Error is called) */ Hashtable<Character, Long> hChanModesBool = new Hashtable<Character, Long>(); /** Integer representing the next avaliable integer value of a Boolean mode. */ long nNextKeyCMBool = 1; /** * Hashtable storing known non-boolean chan modes (klbeI etc). * Non Boolean Modes (for Channels) are stored together in this hashtable, the value param * is used to show the type of variable. (List (1), Param just for set (2), Param for Set and Unset (2+4=6))<br><br> * <br> * see MODE_LIST<br> * see MODE_SET<br> * see MODE_UNSET<br> */ Hashtable<Character, Byte> hChanModesOther = new Hashtable<Character, Byte>(); /** The last line of input recieved from the server */ String lastLine = ""; /** Should the lastline (where given) be appended to the "data" part of any onErrorInfo call? */ boolean addLastLine = false; /** * Channel Prefixes (ie # + etc). * The "value" for these is always true. */ Hashtable<Character, Boolean> hChanPrefix = new Hashtable<Character, Boolean>(); /** Hashtable storing all known clients based on nickname (in lowercase). */ private Hashtable<String, ClientInfo> hClientList = new Hashtable<String, ClientInfo>(); /** Hashtable storing all known channels based on chanel name (inc prefix - in lowercase). */ private Hashtable<String, ChannelInfo> hChannelList = new Hashtable<String, ChannelInfo>(); /** Reference to the ClientInfo object that references ourself. */ private ClientInfo cMyself = new ClientInfo(this, "myself").setFake(true); /** Hashtable storing all information gathered from 005. */ Hashtable<String, String> h005Info = new Hashtable<String, String>(); /** Ignore List. */ RegexStringList myIgnoreList = new RegexStringList(); /** Reference to the callback Manager. */ CallbackManager myCallbackManager = new CallbackManager(this); /** Reference to the Processing Manager. */ ProcessingManager myProcessingManager = new ProcessingManager(this); /** Should we automatically disconnect on fatal errors?. */ private boolean disconnectOnFatal = true; /** Current Socket State. */ protected byte currentSocketState; /** This is the socket used for reading from/writing to the IRC server. */ private Socket socket; /** Used for writing to the server. */ private PrintWriter out; /** Used for reading from the server. */ private BufferedReader in; /** This is the default TrustManager for SSL Sockets, it trusts all ssl certs. */ private final TrustManager[] trustAllCerts = { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(final X509Certificate[] certs, final String authType) { } public void checkServerTrusted(final X509Certificate[] certs, final String authType) { } }, }; /** Should fake (channel)clients be created for callbacks where they do not exist? */ boolean createFake = false; /** Should channels automatically request list modes? */ boolean autoListMode = true; /** Should part/quit/kick callbacks be fired before removing the user internally? */ boolean removeAfterCallback = true; /** This is the TrustManager used for SSL Sockets. */ private TrustManager[] myTrustManager = trustAllCerts; /** This is the IP we want to bind to. */ private String bindIP = ""; /** * Default constructor, ServerInfo and MyInfo need to be added separately (using IRC.me and IRC.server). */ public IRCParser() { this(null, null); } /** * Constructor with ServerInfo, MyInfo needs to be added separately (using IRC.me). * * @param serverDetails Server information. */ public IRCParser(final ServerInfo serverDetails) { this(null, serverDetails); } /** * Constructor with MyInfo, ServerInfo needs to be added separately (using IRC.server). * * @param myDetails Client information. */ public IRCParser(final MyInfo myDetails) { this(myDetails, null); } /** * Constructor with ServerInfo and MyInfo. * * @param serverDetails Server information. * @param myDetails Client information. */ public IRCParser(final MyInfo myDetails, final ServerInfo serverDetails) { if (myDetails != null) { this.me = myDetails; } if (serverDetails != null) { this.server = serverDetails; } resetState(); } /** * Get the current Value of bindIP. * * @return Value of bindIP ("" for default IP) */ public String getBindIP() { return bindIP; } /** * Set the current Value of bindIP. * * @param newValue New value to set bindIP */ public void setBindIP(final String newValue) { bindIP = newValue; } /** * Get the current Value of createFake. * * @return Value of createFake (true if fake clients will be added for callbacks, else false) */ public boolean getCreateFake() { return createFake; } /** * Set the current Value of createFake. * * @param newValue New value to set createFake */ public void setCreateFake(final boolean newValue) { createFake = newValue; } /** * Get the current Value of autoListMode. * * @return Value of autoListMode (true if channels automatically ask for list modes on join, else false) */ public boolean getAutoListMode() { return autoListMode; } /** * Set the current Value of autoListMode. * * @param newValue New value to set autoListMode */ public void setAutoListMode(final boolean newValue) { autoListMode = newValue; } /** * Get the current Value of removeAfterCallback. * * @return Value of removeAfterCallback (true if kick/part/quit callbacks are fired before internal removal) */ public boolean getRemoveAfterCallback() { return removeAfterCallback; } /** * Get the current Value of removeAfterCallback. * * @param newValue New value to set removeAfterCallback */ public void setRemoveAfterCallback(final boolean newValue) { removeAfterCallback = newValue; } /** * Get the current Value of addLastLine. * * @return Value of addLastLine (true if lastLine info will be automatically * added to the errorInfo data line). This should be true if lastLine * isn't handled any other way. */ public boolean getAddLastLine() { return addLastLine; } /** * Get the current Value of addLastLine. * This returns "this" and thus can be used in the construction line. * * @param newValue New value to set addLastLine */ public void setAddLastLine(final boolean newValue) { addLastLine = newValue; } /** * Get the current socket State. * * @return Current SocketState (STATE_NULL, STATE_CLOSED or STATE_OPEN) */ public byte getSocketState() { return currentSocketState; } /** * Get a reference to the Processing Manager. * * @return Reference to the CallbackManager */ public ProcessingManager getProcessingManager() { return myProcessingManager; } /** * Get a reference to the CallbackManager. * * @return Reference to the CallbackManager */ public CallbackManager getCallbackManager() { return myCallbackManager; } /** * Get a reference to the default TrustManager for SSL Sockets. * * @return a reference to trustAllCerts */ public TrustManager[] getDefaultTrustManager() { return trustAllCerts; } /** * Get a reference to the current TrustManager for SSL Sockets. * * @return a reference to myTrustManager; */ public TrustManager[] getTrustManager() { return myTrustManager; } /** * Replace the current TrustManager for SSL Sockets with a new one. * * @param newTrustManager Replacement TrustManager for SSL Sockets. */ public void setTrustManager(final TrustManager[] newTrustManager) { myTrustManager = newTrustManager; } /** * Get a reference to the ignorelist. * * @return a reference to the ignorelist */ public RegexStringList getIgnoreList() { return myIgnoreList; } /** * Replaces the current ignorelist with a new one. * * @param ignoreList Replacement ignorelist */ public void setIgnoreList(final RegexStringList ignoreList) { myIgnoreList = ignoreList; } // Start Callbacks /** * Callback to all objects implementing the ServerError Callback. * * @see com.dmdirc.parser.callbacks.interfaces.IServerError * @param message The error message * @return true if a method was called, false otherwise */ protected boolean callServerError(final String message) { final CallbackOnServerError cb = (CallbackOnServerError) myCallbackManager.getCallbackType("OnServerError"); if (cb != null) { return cb.call(message); } return false; } /** * Callback to all objects implementing the DataIn Callback. * * @see com.dmdirc.parser.callbacks.interfaces.IDataIn * @param data Incomming Line. * @return true if a method was called, false otherwise */ protected boolean callDataIn(final String data) { final CallbackOnDataIn cb = (CallbackOnDataIn) myCallbackManager.getCallbackType("OnDataIn"); if (cb != null) { return cb.call(data); } return false; } /** * Callback to all objects implementing the DataOut Callback. * * @param data Outgoing Data * @param fromParser True if parser sent the data, false if sent using .sendLine * @return true if a method was called, false otherwise * @see com.dmdirc.parser.callbacks.interfaces.IDataOut */ protected boolean callDataOut(final String data, final boolean fromParser) { final CallbackOnDataOut cb = (CallbackOnDataOut) myCallbackManager.getCallbackType("OnDataOut"); if (cb != null) { return cb.call(data, fromParser); } return false; } /** * Callback to all objects implementing the DebugInfo Callback. * * @see com.dmdirc.parser.callbacks.interfaces.IDebugInfo * @param level Debugging Level (DEBUG_INFO, DEBUG_SOCKET etc) * @param data Debugging Information as a format string * @param args Formatting String Options * @return true if a method was called, false otherwise */ protected boolean callDebugInfo(final int level, final String data, final Object... args) { return callDebugInfo(level, String.format(data, args)); } /** * Callback to all objects implementing the DebugInfo Callback. * * @see com.dmdirc.parser.callbacks.interfaces.IDebugInfo * @param level Debugging Level (DEBUG_INFO, DEBUG_SOCKET etc) * @param data Debugging Information * @return true if a method was called, false otherwise */ protected boolean callDebugInfo(final int level, final String data) { final CallbackOnDebugInfo cb = (CallbackOnDebugInfo) myCallbackManager.getCallbackType("OnDebugInfo"); if (cb != null) { return cb.call(level, data); } return false; } /** * Callback to all objects implementing the IErrorInfo Interface. * * @see com.dmdirc.parser.callbacks.interfaces.IErrorInfo * @param errorInfo ParserError object representing the error. * @return true if a method was called, false otherwise */ protected boolean callErrorInfo(final ParserError errorInfo) { final CallbackOnErrorInfo cb = (CallbackOnErrorInfo) myCallbackManager.getCallbackType("OnErrorInfo"); if (cb != null) { return cb.call(errorInfo); } return false; } /** * Callback to all objects implementing the IConnectError Interface. * * @see com.dmdirc.parser.callbacks.interfaces.IConnectError * @param errorInfo ParserError object representing the error. * @return true if a method was called, false otherwise */ protected boolean callConnectError(final ParserError errorInfo) { final CallbackOnConnectError cb = (CallbackOnConnectError) myCallbackManager.getCallbackType("OnConnectError"); if (cb != null) { return cb.call(errorInfo); } return false; } /** * Callback to all objects implementing the SocketClosed Callback. * * @see com.dmdirc.parser.callbacks.interfaces.ISocketClosed * @return true if a method was called, false otherwise */ protected boolean callSocketClosed() { final CallbackOnSocketClosed cb = (CallbackOnSocketClosed) myCallbackManager.getCallbackType("OnSocketClosed"); if (cb != null) { return cb.call(); } return false; } /** * Callback to all objects implementing the PingFailed Callback. * * @see com.dmdirc.parser.callbacks.interfaces.IPingFailed * @return true if a method was called, false otherwise */ protected boolean callPingFailed() { final CallbackOnPingFailed cb = (CallbackOnPingFailed) myCallbackManager.getCallbackType("OnPingFailed"); if (cb != null) { return cb.call(); } return false; } /** * Callback to all objects implementing the PingSent Callback. * * @see com.dmdirc.parser.callbacks.interfaces.IPingSent * @return true if a method was called, false otherwise */ protected boolean callPingSent() { final CallbackOnPingSent cb = (CallbackOnPingSent) myCallbackManager.getCallbackType("OnPingSent"); if (cb != null) { return cb.call(); } return false; } /** * Callback to all objects implementing the PingSuccess Callback. * * @see com.dmdirc.parser.callbacks.interfaces.IPingSuccess * @return true if a method was called, false otherwise */ protected boolean callPingSuccess() { final CallbackOnPingSuccess cb = (CallbackOnPingSuccess) myCallbackManager.getCallbackType("OnPingSuccess"); if (cb != null) { return cb.call(); } return false; } /** * Callback to all objects implementing the Post005 Callback. * * @return true if any callbacks were called. * @see IPost005 */ protected synchronized boolean callPost005() { if (post005) { return false; } post005 = true; final CallbackOnPost005 cb = (CallbackOnPost005)getCallbackManager().getCallbackType("OnPost005"); if (cb != null) { return cb.call(); } return false; } // End Callbacks /** Reset internal state (use before connect). */ private void resetState() { // Reset General State info triedAlt = false; got001 = false; post005 = false; // Clear the hash tables hChannelList.clear(); hClientList.clear(); h005Info.clear(); hPrefixModes.clear(); hPrefixMap.clear(); hChanModesOther.clear(); hChanModesBool.clear(); hUserModes.clear(); hChanPrefix.clear(); // Reset the mode indexes nNextKeyPrefix = 1; nNextKeyCMBool = 1; nNextKeyUser = 1; sServerName = ""; sNetworkName = ""; lastLine = ""; cMyself = new ClientInfo(this, "myself").setFake(true); if (pingTimer != null) { pingTimer.cancel(); pingTimer = null; } currentSocketState = STATE_CLOSED; // Char Mapping updateCharArrays((byte)4); } /** * Called after other error callbacks. * CallbackOnErrorInfo automatically calls this *AFTER* any registered callbacks * for it are called. * * @param errorInfo ParserError object representing the error. * @param called True/False depending on the the success of other callbacks. */ public void onPostErrorInfo(final ParserError errorInfo, final boolean called) { if (errorInfo.isFatal() && disconnectOnFatal) { disconnect("Fatal Parser Error"); } } /** * Get the current Value of disconnectOnFatal. * * @return Value of disconnectOnFatal (true if the parser automatically disconnects on fatal errors, else false) */ public boolean getDisconnectOnFatal() { return disconnectOnFatal; } /** * Set the current Value of disconnectOnFatal. * * @param newValue New value to set disconnectOnFatal */ public void setDisconnectOnFatal(final boolean newValue) { disconnectOnFatal = newValue; } /** * Connect to IRC. * * @throws IOException if the socket can not be connected * @throws UnknownHostException if the hostname can not be resolved * @throws NoSuchAlgorithmException if SSL is not available * @throws KeyManagementException if the trustManager is invalid */ private void connect() throws UnknownHostException, IOException, NoSuchAlgorithmException, KeyManagementException { resetState(); callDebugInfo(DEBUG_SOCKET, "Connecting to " + server.getHost() + ":" + server.getPort()); if (server.getUseSocks()) { callDebugInfo(DEBUG_SOCKET, "Using Proxy"); if (bindIP != null && bindIP != "") { callDebugInfo(DEBUG_SOCKET, "IP Binding is not possible when using a proxy."); } final Proxy.Type proxyType = Proxy.Type.SOCKS; socket = new Socket(new Proxy(proxyType, new InetSocketAddress(server.getProxyHost(), server.getProxyPort()))); socket.connect(new InetSocketAddress(server.getHost(), server.getPort())); } else { callDebugInfo(DEBUG_SOCKET, "Not using Proxy"); if (!server.getSSL()) { if (bindIP == null || bindIP.isEmpty()) { socket = new Socket(server.getHost(), server.getPort()); } else { callDebugInfo(DEBUG_SOCKET, "Binding to IP: "+bindIP); try { socket = new Socket(server.getHost(), server.getPort(), InetAddress.getByName(bindIP), 0); } catch (IOException e) { callDebugInfo(DEBUG_SOCKET, "Binding failed: "+e.getMessage()); socket = new Socket(server.getHost(), server.getPort()); } } } } if (server.getSSL()) { callDebugInfo(DEBUG_SOCKET, "Server is SSL."); if (myTrustManager == null) { myTrustManager = trustAllCerts; } final SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, myTrustManager, new java.security.SecureRandom()); final SSLSocketFactory socketFactory = sc.getSocketFactory(); if (server.getUseSocks()) { socket = socketFactory.createSocket(socket, server.getHost(), server.getPort(), false); } else { if (bindIP == null || bindIP.isEmpty()) { socket = socketFactory.createSocket(server.getHost(), server.getPort()); } else { callDebugInfo(DEBUG_SOCKET, "Binding to IP: "+bindIP); try { socket = socketFactory.createSocket(server.getHost(), server.getPort(), InetAddress.getByName(bindIP), 0); } catch (UnknownHostException e) { callDebugInfo(DEBUG_SOCKET, "Bind failed: "+e.getMessage()); socket = socketFactory.createSocket(server.getHost(), server.getPort()); } } } } callDebugInfo(DEBUG_SOCKET, "\t-> Opening socket output stream PrintWriter"); out = new PrintWriter(socket.getOutputStream(), true); currentSocketState = STATE_OPEN; callDebugInfo(DEBUG_SOCKET, "\t-> Opening socket input stream BufferedReader"); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); callDebugInfo(DEBUG_SOCKET, "\t-> Socket Opened"); } /** * Send server connection strings (NICK/USER/PASS). */ protected void sendConnectionStrings() { if (!server.getPassword().isEmpty()) { sendString("PASS " + server.getPassword()); } setNickname(me.getNickname()); String localhost; try { localhost = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException uhe) { localhost = "*"; } sendString("USER " + toLowerCase(me.getUsername()) + " "+localhost+" "+server.getHost()+" :" + me.getRealname()); isFirst = false; } /** * Begin execution. * Connect to server, and start parsing incomming lines */ public void run() { callDebugInfo(DEBUG_INFO, "Begin Thread Execution"); if (hasBegan) { return; } else { hasBegan = true; } try { connect(); } catch (Exception e) { callDebugInfo(DEBUG_SOCKET, "Error Connecting (" + e.getMessage() + "), Aborted"); final ParserError ei = new ParserError(ParserError.ERROR_ERROR, "Error connecting to server"); ei.setException(e); callConnectError(ei); return; } callDebugInfo(DEBUG_SOCKET, "Socket Connected"); sendConnectionStrings(); while (true) { try { lastLine = in.readLine(); // Blocking :/ if (lastLine == null) { if (currentSocketState != STATE_CLOSED) { currentSocketState = STATE_CLOSED; callSocketClosed(); } resetState(); break; } else { processLine(lastLine); } } catch (IOException e) { if (currentSocketState != STATE_CLOSED) { currentSocketState = STATE_CLOSED; callSocketClosed(); } resetState(); break; } } callDebugInfo(DEBUG_INFO, "End Thread Execution"); } /** * Get the current local port number. * * @return 0 if not connected, else the current local port number */ public int getLocalPort() { if (currentSocketState == STATE_OPEN) { return socket.getLocalPort(); } else { return 0; } } /** Close socket on destroy. */ protected void finalize() throws Throwable { try { socket.close(); } catch (IOException e) { callDebugInfo(DEBUG_SOCKET, "Could not close socket"); } super.finalize(); } /** * Get the trailing parameter for a line. * The parameter is everything after the first occurance of " :" ot the last token in the line after a space. * * @param line Line to get parameter for * @return Parameter of the line */ public static String getParam(final String line) { String[] params = null; params = line.split(" :", 2); return params[params.length - 1]; } /** * Tokenise a line. * splits by " " up to the first " :" everything after this is a single token * * @param line Line to tokenise * @return Array of tokens */ public static String[] tokeniseLine(final String line) { if (line == null) { return new String[]{"", }; // Return empty string[] } final int lastarg = line.indexOf(" :"); String[] tokens; if (lastarg > -1) { final String[] temp = line.substring(0, lastarg).split(" "); tokens = new String[temp.length + 1]; System.arraycopy(temp, 0, tokens, 0, temp.length); tokens[temp.length] = line.substring(lastarg + 2); } else { tokens = line.split(" "); } return tokens; } /** * Get the ClientInfo object for a person. * * @param sHost Who can be any valid identifier for a client as long as it contains a nickname (?:)nick(?!ident)(?@host) * @return ClientInfo Object for the client, or null */ public ClientInfo getClientInfo(final String sHost) { final String sWho = toLowerCase(ClientInfo.parseHost(sHost)); if (hClientList.containsKey(sWho)) { return hClientList.get(sWho); } else { return null; } } /** * Get the ClientInfo object for a person, or create a fake client info object. * * @param sHost Who can be any valid identifier for a client as long as it contains a nickname (?:)nick(?!ident)(?@host) * @return ClientInfo Object for the client. */ public ClientInfo getClientInfoOrFake(final String sHost) { final String sWho = toLowerCase(ClientInfo.parseHost(sHost)); if (hClientList.containsKey(sWho)) { return hClientList.get(sWho); } else { return new ClientInfo(this, sHost).setFake(true); } } /** * Get the ChannelInfo object for a channel. * * @param sWhat This is the name of the channel. * @return ChannelInfo Object for the channel, or null */ public ChannelInfo getChannelInfo(String sWhat) { synchronized (hChannelList) { sWhat = toLowerCase(sWhat); if (hChannelList.containsKey(sWhat)) { return hChannelList.get(sWhat); } else { return null; } } } /** * Send a line to the server. * * @param line Line to send (\r\n termination is added automatically) */ public void sendLine(final String line) { doSendString(line, false); } /** * Send a line to the server and add proper line ending. * * @param line Line to send (\r\n termination is added automatically) */ protected void sendString(final String line) { doSendString(line, true); } /** * Send a line to the server and add proper line ending. * * @param line Line to send (\r\n termination is added automatically) * @param fromParser is this line from the parser? (used for callDataOut) */ protected void doSendString(final String line, final boolean fromParser) { if (out == null) { return; } callDataOut(line, fromParser); out.printf("%s\r\n", line); final String[] newLine = tokeniseLine(line); if (newLine[0].equalsIgnoreCase("away") && newLine.length > 1) { cMyself.setAwayReason(newLine[newLine.length-1]); } else if (newLine[0].equalsIgnoreCase("mode") && newLine.length == 3) { // This makes sure we don't add the same item to the LMQ twice, even if its requested twice, // as the ircd will only reply once. LinkedList<Character> foundModes = new LinkedList<Character>(); ChannelInfo channel = getChannelInfo(newLine[1]); if (channel != null) { Queue<Character> listModeQueue = channel.getListModeQueue(); for (int i = 0; i < newLine[2].length() ; ++i) { Character mode = newLine[2].charAt(i); callDebugInfo(DEBUG_LMQ, "Intercepted mode request for "+channel+" for mode "+mode); if (hChanModesOther.containsKey(mode) && hChanModesOther.get(mode) == MODE_LIST) { if (foundModes.contains(mode)) { callDebugInfo(DEBUG_LMQ, "Already added to LMQ"); } else { listModeQueue.offer(mode); foundModes.offer(mode); callDebugInfo(DEBUG_LMQ, "Added to LMQ"); } } } } } } /** * Get the network name given in 005. * * @return network name from 005 */ public String getNetworkName() { return sNetworkName; } /** * Get the server name given in 001. * * @return server name from 001 */ public String getServerName() { return sServerName; } /** * Get the last line of input recieved from the server. * * @return the last line of input recieved from the server. */ public String getLastLine() { return lastLine; } /** * Process a line and call relevent methods for handling. * * @param line IRC Line to process */ protected void processLine(final String line) { callDataIn(line); final String[] token = tokeniseLine(line); int nParam; setPingNeeded(false); // pingCountDown = pingCountDownLength; if (token.length < 2) { return; } try { final String sParam = token[1]; if (token[0].equalsIgnoreCase("PING") || token[1].equalsIgnoreCase("PING")) { sendString("PONG :" + sParam); } else if (token[0].equalsIgnoreCase("PONG") || token[1].equalsIgnoreCase("PONG")) { if (!lastPingValue.equals("") && lastPingValue.equals(token[token.length-1])) { lastPingValue = ""; serverLag = System.currentTimeMillis() - pingTime; callPingSuccess(); } } else if (token[0].equalsIgnoreCase("ERROR")) { StringBuilder errorMessage = new StringBuilder(); for (int i = 1; i < token.length; ++i) { errorMessage.append(token[i]); } callServerError(errorMessage.toString()); } else { if (got001) { // Freenode sends a random notice in a stupid place, others might do aswell // These shouldn't cause post005 to be fired, so handle them here. if (token[0].equalsIgnoreCase("NOTICE")) { try { myProcessingManager.process("Notice Auth", token); } catch (Exception e) { } return; } if (!post005) { try { nParam = Integer.parseInt(token[1]); } catch (Exception e) { nParam = -1; } if (nParam < 0 || nParam > 5) { callPost005(); } } // After 001 we potentially care about everything! try { myProcessingManager.process(sParam, token); } catch (Exception e) { /* No Processor found */ } } else { // Before 001 we don't care about much. try { nParam = Integer.parseInt(token[1]); } catch (Exception e) { nParam = -1; } switch (nParam) { case 1: // 001 - Welcome to IRC case 464: // Password Required case 433: // Nick In Use try { myProcessingManager.process(sParam, token); } catch (Exception e) { } break; default: // Unknown - Send to Notice Auth // Some networks send a CTCP during the auth process, handle it if (token.length > 3 && !token[3].isEmpty() && token[3].charAt(0) == (char)1 && token[3].charAt(token[3].length()-1) == (char)1) { try { myProcessingManager.process(sParam, token); } catch (Exception e) { } break; } // Otherwise, send to Notice Auth try { myProcessingManager.process("Notice Auth", token); } catch (Exception e) { } break; } } } } catch (Exception e) { final ParserError ei = new ParserError(ParserError.ERROR_FATAL, "Exception in Parser.", lastLine); ei.setException(e); callErrorInfo(ei); } } /** Characters to use when converting tolowercase. */ private char[] lowercase; /** Characters to use when converting touppercase. */ private char[] uppercase; /** Previous char array limit */ private byte lastLimit = (byte)3; /** * Get last used chararray limit. * * @return last used chararray limit */ protected int getLastLimit() { return lastLimit; } /** * Update the character arrays. * * @param limit Number of post-alphabetical characters to convert * 0 = ascii encoding * 3 = strict-rfc1459 encoding * 4 = rfc1459 encoding */ protected void updateCharArrays(final byte limit) { // If limit is out side the boundries, use rfc1459 if (limit > 4 || limit < 0 ) { updateCharArrays((byte)4); return; } lastLimit = limit; lowercase = new char[127]; uppercase = new char[127]; // Normal Chars for (char i = 0; i < lowercase.length; ++i) { lowercase[i] = i; uppercase[i] = i; } // Replace the uppercase chars with lowercase for (char i = 65; i <= (90 + limit); ++i) { lowercase[i] = (char)(i + 32); uppercase[i + 32] = i; } } /** * Get the lowercase version of a String for this Server. * * @param input String to convert lowercase * @return input String converterd to lowercase */ public String toLowerCase(final String input) { final char[] result = input.toCharArray(); for (int i = 0; i < input.length(); ++i) { if (result[i] >= 0 && result[i] < lowercase.length) { result[i] = lowercase[result[i]]; } else { result[i] = result[i]; } } return new String(result); } /** * Get the uppercase version of a String for this Server. * * @param input String to convert uppercase * @return input String converterd to uppercase */ public String toUpperCase(final String input) { final char[] result = input.toCharArray(); for (int i = 0; i < input.length(); ++i) { if (result[i] >= 0 && result[i] < uppercase.length) { result[i] = uppercase[result[i]]; } else { result[i] = result[i]; } } return new String(result); } /** * Check if 2 strings are equal to each other ignoring case. * * @param first First string to check * @param second Second string to check * @return True if both strings are equal after being lowercased */ public boolean equalsIgnoreCase(final String first, final String second) { if (first == null && second == null) { return true; } if (first == null || second == null) { return false; } boolean result = (first.length() == second.length()); if (result) { final char[] firstChar = first.toCharArray(); final char[] secondChar = second.toCharArray(); for (int i = 0; i < first.length(); ++i) { if (firstChar[i] < lowercase.length && secondChar[i] < lowercase.length) { result = (lowercase[firstChar[i]] == lowercase[secondChar[i]]); } else { result = firstChar[i] == secondChar[i]; } if (!result) { break; } } } return result; } /** * Get the known boolean chanmodes in 005 order. * Modes are returned in the order that the ircd specifies the modes in 005 * with any newly-found modes (mode being set that wasn't specified in 005) * being added at the end. * * @return All the currently known boolean modes */ public String getBoolChanModes005() { // This code isn't the nicest, as Hashtable's don't lend themselves to being // ordered. // Order isn't really important, and this code only takes 3 lines of we // don't care about it but ordered guarentees that on a specific ircd this // method will ALWAYs return the same value. final char[] modes = new char[hChanModesBool.size()]; long nTemp; double pos; for (char cTemp : hChanModesBool.keySet()) { nTemp = hChanModesBool.get(cTemp); // nTemp should never be less than 0 if (nTemp > 0) { pos = Math.log(nTemp) / Math.log(2); modes[(int)pos] = cTemp; } /* // Is there an easier way to find out the power of 2 value for a number? // ie 1024 = 10, 512 = 9 ? for (int i = 0; i < modes.length; i++) { if (Math.pow(2, i) == (double) nTemp) { modes[i] = cTemp; break; } }*/ } return new String(modes); } /** * Process CHANMODES from 005. */ public void parseChanModes() { final StringBuilder sDefaultModes = new StringBuilder("b,k,l,"); String[] bits = null; String modeStr; if (h005Info.containsKey("USERCHANMODES")) { if (getIRCD(true).equalsIgnoreCase("dancer")) { sDefaultModes.insert(0, "dqeI"); } else if (getIRCD(true).equalsIgnoreCase("austirc")) { sDefaultModes.insert(0, "e"); } modeStr = h005Info.get("USERCHANMODES"); char mode; for (int i = 0; i < modeStr.length(); ++i) { mode = modeStr.charAt(i); if (!hPrefixModes.containsKey(mode) && sDefaultModes.indexOf(Character.toString(mode)) < 0) { sDefaultModes.append(mode); } } } else { sDefaultModes.append("imnpstrc"); } if (h005Info.containsKey("CHANMODES")) { modeStr = h005Info.get("CHANMODES"); } else { modeStr = sDefaultModes.toString(); h005Info.put("CHANMODES", modeStr); } bits = modeStr.split(",", 5); if (bits.length < 4) { modeStr = sDefaultModes.toString(); callErrorInfo(new ParserError(ParserError.ERROR_ERROR, "CHANMODES String not valid. Using default string of \"" + modeStr + "\"")); h005Info.put("CHANMODES", modeStr); bits = modeStr.split(",", 5); } // resetState hChanModesOther.clear(); hChanModesBool.clear(); nNextKeyCMBool = 1; // List modes. for (int i = 0; i < bits[0].length(); ++i) { final Character cMode = bits[0].charAt(i); callDebugInfo(DEBUG_INFO, "Found List Mode: %c", cMode); if (!hChanModesOther.containsKey(cMode)) { hChanModesOther.put(cMode, MODE_LIST); } } // Param for Set and Unset. final Byte nBoth = MODE_SET + MODE_UNSET; for (int i = 0; i < bits[1].length(); ++i) { final Character cMode = bits[1].charAt(i); callDebugInfo(DEBUG_INFO, "Found Set/Unset Mode: %c", cMode); if (!hChanModesOther.containsKey(cMode)) { hChanModesOther.put(cMode, nBoth); } } // Param just for Set for (int i = 0; i < bits[2].length(); ++i) { final Character cMode = bits[2].charAt(i); callDebugInfo(DEBUG_INFO, "Found Set Only Mode: %c", cMode); if (!hChanModesOther.containsKey(cMode)) { hChanModesOther.put(cMode, MODE_SET); } } // Boolean Mode for (int i = 0; i < bits[3].length(); ++i) { final Character cMode = bits[3].charAt(i); callDebugInfo(DEBUG_INFO, "Found Boolean Mode: %c [%d]", cMode, nNextKeyCMBool); if (!hChanModesBool.containsKey(cMode)) { hChanModesBool.put(cMode, nNextKeyCMBool); nNextKeyCMBool = nNextKeyCMBool * 2; } } } /** * Get the known prefixmodes in priority order. * * @return All the currently known usermodes */ public String getPrefixModes() { if (h005Info.containsKey("PREFIXSTRING")) { return h005Info.get("PREFIXSTRING"); } else { return ""; } } /** * Get the known boolean chanmodes in alphabetical order. * Modes are returned in alphabetic order * * @return All the currently known boolean modes */ public String getBoolChanModes() { final char[] modes = new char[hChanModesBool.size()]; int i = 0; for (char mode : hChanModesBool.keySet()) { modes[i++] = mode; } // Alphabetically sort the array Arrays.sort(modes); return new String(modes); } /** * Get the known List chanmodes. * Modes are returned in alphabetical order * * @return All the currently known List modes */ public String getListChanModes() { return getOtherModeString(MODE_LIST); } /** * Get the known Set-Only chanmodes. * Modes are returned in alphabetical order * * @return All the currently known Set-Only modes */ public String getSetOnlyChanModes() { return getOtherModeString(MODE_SET); } /** * Get the known Set-Unset chanmodes. * Modes are returned in alphabetical order * * @return All the currently known Set-Unset modes */ public String getSetUnsetChanModes() { return getOtherModeString((byte) (MODE_SET + MODE_UNSET)); } /** * Get modes from hChanModesOther that have a specific value. * Modes are returned in alphabetical order * * @param nValue Value mode must have to be included * @return All the currently known Set-Unset modes */ protected String getOtherModeString(final byte nValue) { final char[] modes = new char[hChanModesOther.size()]; Byte nTemp; int i = 0; for (char cTemp : hChanModesOther.keySet()) { nTemp = hChanModesOther.get(cTemp); if (nTemp == nValue) { modes[i++] = cTemp; } } // Alphabetically sort the array Arrays.sort(modes); return new String(modes).trim(); } /** * Get the known usermodes. * Modes are returned in the order specified by the ircd. * * @return All the currently known usermodes (returns "" if usermodes are unknown) */ public String getUserModeString() { if (h005Info.containsKey("USERMODES")) { return h005Info.get("USERMODES"); } else { return ""; } } /** * Process USERMODES from 004. */ protected void parseUserModes() { final String sDefaultModes = "nwdoi"; String modeStr; if (h005Info.containsKey("USERMODES")) { modeStr = h005Info.get("USERMODES"); } else { modeStr = sDefaultModes; h005Info.put("USERMODES", sDefaultModes); } // resetState hUserModes.clear(); nNextKeyUser = 1; // Boolean Mode for (int i = 0; i < modeStr.length(); ++i) { final Character cMode = modeStr.charAt(i); callDebugInfo(DEBUG_INFO, "Found User Mode: %c [%d]", cMode, nNextKeyUser); if (!hUserModes.containsKey(cMode)) { hUserModes.put(cMode, nNextKeyUser); nNextKeyUser = nNextKeyUser * 2; } } } /** * Process CHANTYPES from 005. */ protected void parseChanPrefix() { final String sDefaultModes = " String modeStr; if (h005Info.containsKey("CHANTYPES")) { modeStr = h005Info.get("CHANTYPES"); } else { modeStr = sDefaultModes; h005Info.put("CHANTYPES", sDefaultModes); } // resetState hChanPrefix.clear(); // Boolean Mode for (int i = 0; i < modeStr.length(); ++i) { final Character cMode = modeStr.charAt(i); callDebugInfo(DEBUG_INFO, "Found Chan Prefix: %c", cMode); if (!hChanPrefix.containsKey(cMode)) { hChanPrefix.put(cMode, true); } } } /** * Process PREFIX from 005. */ public void parsePrefixModes() { final String sDefaultModes = "(ohv)@%+"; String[] bits; String modeStr; if (h005Info.containsKey("PREFIX")) { modeStr = h005Info.get("PREFIX"); } else { modeStr = sDefaultModes; } if (modeStr.substring(0, 1).equals("(")) { modeStr = modeStr.substring(1); } else { modeStr = sDefaultModes.substring(1); h005Info.put("PREFIX", sDefaultModes); } bits = modeStr.split("\\)", 2); if (bits.length != 2 || bits[0].length() != bits[1].length()) { modeStr = sDefaultModes; callErrorInfo(new ParserError(ParserError.ERROR_ERROR, "PREFIX String not valid. Using default string of \"" + modeStr + "\"")); h005Info.put("PREFIX", modeStr); modeStr = modeStr.substring(1); bits = modeStr.split("\\)", 2); } // resetState hPrefixModes.clear(); hPrefixMap.clear(); nNextKeyPrefix = 1; for (int i = bits[0].length() - 1; i > -1; --i) { final Character cMode = bits[0].charAt(i); final Character cPrefix = bits[1].charAt(i); callDebugInfo(DEBUG_INFO, "Found Prefix Mode: %c => %c [%d]", cMode, cPrefix, nNextKeyPrefix); if (!hPrefixModes.containsKey(cMode)) { hPrefixModes.put(cMode, nNextKeyPrefix); hPrefixMap.put(cMode, cPrefix); hPrefixMap.put(cPrefix, cMode); nNextKeyPrefix = nNextKeyPrefix * 2; } } h005Info.put("PREFIXSTRING", bits[0]); } /** * Check if server is ready. * * @return true if 001 has been recieved, false otherwise. */ public boolean isReady() { return got001; } /** * Join a Channel. * * @param sChannelName Name of channel to join */ public void joinChannel(final String sChannelName) { joinChannel(sChannelName, "", true); } /** * Join a Channel. * * @param sChannelName Name of channel to join * @param autoPrefix Automatically prepend the first channel prefix defined * in 005 if sChannelName is an invalid channel. * **This only applies to the first channel if given a list** */ public void joinChannel(final String sChannelName, final boolean autoPrefix) { joinChannel(sChannelName, "", autoPrefix); } /** * Join a Channel with a key. * * @param sChannelName Name of channel to join * @param sKey Key to use to try and join the channel */ public void joinChannel(final String sChannelName, final String sKey) { joinChannel(sChannelName, sKey, true); } /** * Join a Channel with a key. * * @param sChannelName Name of channel to join * @param sKey Key to use to try and join the channel * @param autoPrefix Automatically prepend the first channel prefix defined * in 005 if sChannelName is an invalid channel. * **This only applies to the first channel if given a list** */ public void joinChannel(final String sChannelName, final String sKey, final boolean autoPrefix) { final String channelName; if (!isValidChannelName(sChannelName)) { if (autoPrefix) { if (h005Info.containsKey("CHANTYPES")) { final String chantypes = h005Info.get("CHANTYPES"); if (!chantypes.isEmpty()) { channelName = chantypes.charAt(0)+sChannelName; } else { channelName = "#"+sChannelName; } } else { return; } } else { return; } } else { channelName = sChannelName; } if (sKey.isEmpty()) { sendString("JOIN " + channelName); } else { sendString("JOIN " + channelName + " " + sKey); } } /** * Leave a Channel. * * @param sChannelName Name of channel to part * @param sReason Reason for leaving (Nothing sent if sReason is "") */ public void partChannel(final String sChannelName, final String sReason) { if (getChannelInfo(sChannelName) == null) { return; } if (sReason.isEmpty()) { sendString("PART " + sChannelName); } else { sendString("PART " + sChannelName + " :" + sReason); } } /** * Set Nickname. * * @param sNewNickName New nickname wanted. */ public void setNickname(final String sNewNickName) { if (getSocketState() == STATE_OPEN) { if (!cMyself.isFake() && cMyself.getNickname().equals(sNewNickName)) { return; } sendString("NICK " + sNewNickName); } else { me.setNickname(sNewNickName); } sThinkNickname = sNewNickName; } /** * Get the max length a message can be. * * @param sType Type of message (ie PRIVMSG) * @param sTarget Target for message (eg #DMDirc) * @return Max Length message should be. */ public int getMaxLength(final String sType, final String sTarget) { // If my host is "nick!user@host" and we are sending "#Channel" // a "PRIVMSG" this will find the length of ":nick!user@host PRIVMSG #channel :" // and subtract it from the MAX_LINELENGTH. This should be sufficient in most cases. // Lint = the 2 ":" at the start and end and the 3 separating " "s int length = 0; if (sType != null) { length = length + sType.length(); } if (sTarget != null) { length = length + sTarget.length(); } return getMaxLength(length); } /** * Get the max length a message can be. * * @param nLength Length of stuff. (Ie "PRIVMSG"+"#Channel") * @return Max Length message should be. */ public int getMaxLength(final int nLength) { final int lineLint = 5; if (cMyself.isFake()) { callErrorInfo(new ParserError(ParserError.ERROR_ERROR, "getMaxLength() called, but I don't know who I am?", lastLine)); return MAX_LINELENGTH - nLength - lineLint; } else { return MAX_LINELENGTH - cMyself.toString().length() - nLength - lineLint; } } /** * Get the max number of list modes. * * @param mode The mode to know the max number for * @return The max number of list modes for the given mode. * - returns 0 if MAXLIST does not contain the mode, unless MAXBANS is * set, then this is returned instead. * - returns -1 if: * - MAXLIST or MAXBANS were not in 005 * - Values for MAXLIST or MAXBANS were invalid (non integer, empty) */ public int getMaxListModes(final char mode) { // MAXLIST=bdeI:50 // MAXLIST=b:60,e:60,I:60 // MAXBANS=30 int result = -2; callDebugInfo(DEBUG_INFO, "Looking for maxlistmodes for: "+mode); // Try in MAXLIST if (h005Info.get("MAXLIST") != null) { if (h005Info.get("MAXBANS") == null) { result = 0; } final String maxlist = h005Info.get("MAXLIST"); callDebugInfo(DEBUG_INFO, "Found maxlist ("+maxlist+")"); final String[] bits = maxlist.split(","); for (String bit : bits) { final String[] parts = bit.split(":", 2); callDebugInfo(DEBUG_INFO, "Bit: "+bit+" | parts.length = "+parts.length+" ("+parts[0]+" -> "+parts[0].indexOf(mode)+")"); if (parts.length == 2 && parts[0].indexOf(mode) > -1) { callDebugInfo(DEBUG_INFO, "parts[0] = '"+parts[0]+"' | parts[1] = '"+parts[1]+"'"); try { result = Integer.parseInt(parts[1]); break; } catch (NumberFormatException nfe) { result = -1; } } } } // If not in max list, try MAXBANS if (result == -2 && h005Info.get("MAXBANS") != null) { callDebugInfo(DEBUG_INFO, "Trying max bans"); try { result = Integer.parseInt(h005Info.get("MAXBANS")); } catch (NumberFormatException nfe) { result = -1; } } else if (result == -2) { result = -1; callDebugInfo(DEBUG_INFO, "Failed"); callErrorInfo(new ParserError(ParserError.ERROR_ERROR, "Unable to discover max list modes.")); } callDebugInfo(DEBUG_INFO, "Result: "+result); return result; } /** * Send a private message to a target. * * @param sTarget Target * @param sMessage Message to send */ public void sendMessage(final String sTarget, final String sMessage) { if (sTarget == null || sMessage == null) { return; } if (sTarget.isEmpty()/* || sMessage.isEmpty()*/) { return; } sendString("PRIVMSG " + sTarget + " :" + sMessage); } /** * Send a notice message to a target. * * @param sTarget Target * @param sMessage Message to send */ public void sendNotice(final String sTarget, final String sMessage) { if (sTarget == null || sMessage == null) { return; } if (sTarget.isEmpty()/* || sMessage.isEmpty()*/) { return; } sendString("NOTICE " + sTarget + " :" + sMessage); } /** * Send a Action to a target. * * @param sTarget Target * @param sMessage Action to send */ public void sendAction(final String sTarget, final String sMessage) { sendCTCP(sTarget, "ACTION", sMessage); } /** * Send a CTCP to a target. * * @param sTarget Target * @param sType Type of CTCP * @param sMessage Optional Additional Parameters */ public void sendCTCP(final String sTarget, final String sType, final String sMessage) { if (sTarget == null || sMessage == null) { return; } if (sTarget.isEmpty() || sType.isEmpty()) { return; } final char char1 = (char) 1; sendString("PRIVMSG " + sTarget + " :" + char1 + sType.toUpperCase() + " " + sMessage + char1); } /** * Send a CTCPReply to a target. * * @param sTarget Target * @param sType Type of CTCP * @param sMessage Optional Additional Parameters */ public void sendCTCPReply(final String sTarget, final String sType, final String sMessage) { if (sTarget == null || sMessage == null) { return; } if (sTarget.isEmpty() || sType.isEmpty()) { return; } final char char1 = (char) 1; sendString("NOTICE " + sTarget + " :" + char1 + sType.toUpperCase() + " " + sMessage + char1); } /** * Quit IRC. * This method will wait for the server to close the socket. * * @param sReason Reason for quitting. */ public void quit(final String sReason) { if (sReason.isEmpty()) { sendString("QUIT"); } else { sendString("QUIT :" + sReason); } } /** * Disconnect from server. * This method will quit and automatically close the socket without waiting for * the server. * * @param sReason Reason for quitting. */ public void disconnect(final String sReason) { if (currentSocketState == STATE_OPEN && got001) { quit(sReason); } try { socket.close(); } catch (Exception e) { /* Do Nothing */ } finally { if (currentSocketState != STATE_CLOSED) { currentSocketState = STATE_CLOSED; callSocketClosed(); } resetState(); } } /** * Check if a channel name is valid. * * @param sChannelName Channel name to test * @return true if name is valid on the current connection, false otherwise. * - Before channel prefixes are known (005/noMOTD/MOTDEnd), this checks * that the first character is either #, &amp;, ! or + * - Assumes that any channel that is already known is valid, even if * 005 disagrees. */ public boolean isValidChannelName(final String sChannelName) { // Check sChannelName is not empty or null if (sChannelName == null || sChannelName.isEmpty()) { return false; } // Check its not ourself (PM recieved before 005) if (equalsIgnoreCase(getMyNickname(), sChannelName)) { return false; } // Check if we are already on this channel if (getChannelInfo(sChannelName) != null) { return true; } // Check if we know of any valid chan prefixes if (hChanPrefix.size() == 0) { // We don't. Lets check against RFC2811-Specified channel types char first = sChannelName.charAt(0); return first == '#' || first == '&' || first == '!' || first == '+'; } // Otherwise return true if: // Channel equals "0" // first character of the channel name is a valid channel prefix. return hChanPrefix.containsKey(sChannelName.charAt(0)) || sChannelName.equals("0"); } /** * Check if a given chanmode is user settable. * * @param mode Mode to test * @return true if mode is settable by users, false if servers only */ public boolean isUserSettable(final Character mode) { String validmodes; if (h005Info.containsKey("USERCHANMODES")) { validmodes = h005Info.get("USERCHANMODES"); } else { validmodes = "bklimnpstrc"; } return validmodes.matches(".*" + mode + ".*"); } /** * Get the 005 info. * * @return 005Info hashtable. */ public Hashtable<String, String> get005() { return h005Info; } /** * Get the name of the ircd. * * @param getType if this is false the string from 004 is returned. Else a guess of the type (ircu, hybrid, ircnet) * @return IRCD Version or Type */ public String getIRCD(final boolean getType) { if (h005Info.containsKey("004IRCD")) { final String version = h005Info.get("004IRCD"); if (getType) { // but keeping groups of ircd's together (ie hybrid-based, ircu-based) if (version.matches("(?i).*unreal.*")) { return "unreal"; } else if (version.matches("(?i).*bahamut.*")) { return "bahamut"; } else if (version.matches("(?i).*nefarious.*")) { return "nefarious"; } else if (version.matches("(?i).*asuka.*")) { return "asuka"; } else if (version.matches("(?i).*snircd.*")) { return "snircd"; } else if (version.matches("(?i).*beware.*")) { return "bircd"; } else if (version.matches("(?i).*u2\\.[0-9]+\\.H\\..*")) { return "irchispano"; } else if (version.matches("(?i).*u2\\.[0-9]+\\..*")) { return "ircu"; } else if (version.matches("(?i).*ircu.*")) { return "ircu"; } else if (version.matches("(?i).*plexus.*")) { return "plexus"; } else if (version.matches("(?i).*ircd.hybrid.*")) { return "hybrid7"; } else if (version.matches("(?i).*hybrid.*")) { return "hybrid"; } else if (version.matches("(?i).*charybdis.*")) { return "charybdis"; } else if (version.matches("(?i).*inspircd.*")) { return "inspircd"; } else if (version.matches("(?i).*ultimateircd.*")) { return "ultimateircd"; } else if (version.matches("(?i).*critenircd.*")) { return "critenircd"; } else if (version.matches("(?i).*fqircd.*")) { return "fqircd"; } else if (version.matches("(?i).*conferenceroom.*")) { return "conferenceroom"; } else if (version.matches("(?i).*hyperion.*")) { return "hyperion"; } else if (version.matches("(?i).*dancer.*")) { return "dancer"; } else if (version.matches("(?i).*austhex.*")) { return "austhex"; } else if (version.matches("(?i).*austirc.*")) { return "austirc"; } else if (version.matches("(?i).*ratbox.*")) { return "ratbox"; } else { // Stupid networks/ircds go here... if (sNetworkName.equalsIgnoreCase("ircnet")) { return "ircnet"; } else if (sNetworkName.equalsIgnoreCase("starchat")) { return "starchat"; } else { return "generic"; } } } else { return version; } } else { if (getType) { return "generic"; } else { return ""; } } } /** * Get the time used for the ping Timer. * * @return current time used. * @see setPingCountDownLength */ public long getPingTimerLength() { return pingTimerLength; } /** * Set the time used for the ping Timer. * This will also reset the pingTimer. * * @param newValue New value to use. * @see setPingCountDownLength */ public void setPingTimerLength(final long newValue) { pingTimerLength = newValue; startPingTimer(); } /** * Get the time used for the pingCountdown. * * @return current time used. * @see setPingCountDownLength */ public byte getPingCountDownLength() { return pingCountDownLength; } /** * Set the time used for the ping countdown. * The pingTimer fires every pingTimerLength/1000 seconds, whenever a line of data * is received, the "waiting for ping" flag is set to false, if the line is * a "PONG", then onPingSuccess is also called. * * When waiting for a ping reply, onPingFailed() is called every time the * timer is fired. * * When not waiting for a ping reply, the pingCountDown is decreased by 1 * every time the timer fires, when it reaches 0 is is reset to * pingCountDownLength and a PING is sent to the server. * * To ping the server after 30 seconds of inactivity you could use: * pingTimerLength = 5000, pingCountDown = 6 * or * pingTimerLength = 10000, pingCountDown = 3 * * @param newValue New value to use. * @see pingCountDown * @see pingTimerLength * @see pingTimerTask */ public void setPingCountDownLength(final byte newValue) { pingCountDownLength = newValue; } /** * Start the pingTimer. */ protected void startPingTimer() { setPingNeeded(false); if (pingTimer != null) { pingTimer.cancel(); } pingTimer = new Timer("IRCParser pingTimer"); pingTimer.schedule(new PingTimer(this, pingTimer), 0, pingTimerLength); pingCountDown = 1; } /** * This is called when the ping Timer has been executed. * As the timer is restarted on every incomming message, this will only be * called when there has been no incomming line for 10 seconds. * * @param timer The timer that called this. */ protected void pingTimerTask(final Timer timer) { if (pingTimer == null || !pingTimer.equals(timer)) { return; } if (getPingNeeded()) { if (!callPingFailed()) { pingTimer.cancel(); disconnect("Server not responding."); } } else { --pingCountDown; if (pingCountDown < 1) { pingTime = System.currentTimeMillis(); setPingNeeded(true); pingCountDown = pingCountDownLength; callPingSent(); lastPingValue = ""+System.currentTimeMillis(); sendLine("PING "+lastPingValue); } } } /** * Get the current server lag. * * @return Last time between sending a PING and recieving a PONG */ public long getServerLag() { return serverLag; } /** * Get the current server lag. * * @param actualTime if True the value returned will be the actual time the ping was sent * else it will be the amount of time sinse the last ping was sent. * @return Time last ping was sent */ public long getPingTime(final boolean actualTime) { if (actualTime) { return pingTime; } else { return System.currentTimeMillis() - pingTime; } } /** * Set if a ping is needed or not. * * @param newStatus new value to set pingNeeded to. */ private void setPingNeeded(final boolean newStatus) { synchronized (pingNeeded) { pingNeeded = newStatus; } } /** * Get if a ping is needed or not. * * @return value of pingNeeded. */ private boolean getPingNeeded() { synchronized (pingNeeded) { return pingNeeded; } } /** * Get a reference to the cMyself object. * * @return cMyself reference */ public synchronized ClientInfo getMyself() { return cMyself; } /** * Get the current nickname. * If after 001 this returns the exact same as getMyself.getNickname(); * Before 001 it returns the nickname that the parser Thinks it has. * * @return Current nickname. */ public String getMyNickname() { if (cMyself.isFake()) { return sThinkNickname; } else { return cMyself.getNickname(); } } /** * Get the current username (Specified in MyInfo on construction). * Get the username given in MyInfo * * @return My username. */ public String getMyUsername() { return me.getUsername(); } /** * Add a client to the ClientList. * * @param client Client to add */ public void addClient(final ClientInfo client) { hClientList.put(toLowerCase(client.getNickname()),client); } /** * Remove a client from the ClientList. * This WILL NOT allow cMyself to be removed from the list. * * @param client Client to remove */ public void removeClient(final ClientInfo client) { if (client != cMyself) { forceRemoveClient(client); } } /** * Remove a client from the ClientList. . * This WILL allow cMyself to be removed from the list * * @param client Client to remove */ protected void forceRemoveClient(final ClientInfo client) { hClientList.remove(toLowerCase(client.getNickname())); } /** * Get the number of known clients. * * @return Count of known clients */ public int knownClients() { return hClientList.size(); } /** * Get the known clients as a collection. * * @return Known clients as a collection */ public Collection<ClientInfo> getClients() { return hClientList.values(); } /** * Clear the client list. */ public void clearClients() { hClientList.clear(); addClient(getMyself()); } /** * Add a channel to the ChannelList. * * @param channel Channel to add */ public void addChannel(final ChannelInfo channel) { synchronized (hChannelList) { hChannelList.put(toLowerCase(channel.getName()), channel); } } /** * Remove a channel from the ChannelList. * * @param channel Channel to remove */ public void removeChannel(final ChannelInfo channel) { synchronized (hChannelList) { hChannelList.remove(toLowerCase(channel.getName())); } } /** * Get the number of known channel. * * @return Count of known channel */ public int knownChannels() { synchronized (hChannelList) { return hChannelList.size(); } } /** * Get the known channels as a collection. * * @return Known channels as a collection */ public Collection<ChannelInfo> getChannels() { synchronized (hChannelList) { return hChannelList.values(); } } /** * Clear the channel list. */ public void clearChannels() { synchronized (hChannelList) { hChannelList.clear(); } } }
package com.example.timestamp; import com.example.timestamp.model.TimePost; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; public class Start extends Activity { final Context context = this; String[] projectsMenuString = {"Projekt 1", "Projekt 2", "Nytt projekt"}; String[] overviewMenuString = {"Graf", "Bar", "Summering"}; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_start); //getWindow().requestFeature(Window.FEATURE_ACTION_BAR); getActionBar().hide(); setContentView(R.layout.activity_confirmreport); activityInitConfirmReport(); } /*@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_activity_actions, menu); return super.onCreateOptionsMenu(menu); }*/ public void activitySwitchOne(View v){ setContentView(R.layout.activity_confirmreport); activityInitConfirmReport(); } public void activitySwitchToMain(View v){ setContentView(R.layout.activity_start); activityInitMain(); } private void activityInitMain(){ //Letar efter en spinner i activity_main.xml med ett specifict id Spinner spinnerProjectView = (Spinner) findViewById(R.id.spinnerProjectView); //Spinner spinnerOverView = (Spinner) findViewById(R.id.spinnerOverView); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, projectsMenuString); //Fr att vlja vilken typ av graf man vill se. //ArrayAdapter<String> adapterView = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, overviewMenuString); //Spinnern anvnder items frn en valt adapter. spinnerProjectView.setAdapter(adapter); //Fr overview //spinnerOverView.setAdapter(adapterView); //Hur spinnern ska se ut //adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } private void activityInitConfirmReport(){ //Letar efter en spinner i activity_main.xml med ett specifict id Spinner spinner = (Spinner) findViewById(R.id.projects_menu_spinner2); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, projectsMenuString){ public View getView(int position, View convertView,ViewGroup parent) { View v = super.getView(position, convertView, parent); ((TextView) v).setGravity(Gravity.CENTER); ((TextView) v).setTextSize(36); return v; } public View getDropDownView(int position, View convertView,ViewGroup parent) { View v = super.getDropDownView(position, convertView,parent); ((TextView) v).setGravity(Gravity.CENTER); ((TextView) v).setTextSize(20); return v; } }; spinner.setAdapter(adapter); button = (Button) findViewById(R.id.sendReportButton); button.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View arg0){ Toast.makeText(getApplicationContext(), "Tidrapport inskickad\n"+new TimePost().printStartTime() , Toast.LENGTH_LONG).show(); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("Är du säker på att du vill skicka in rapporten?"); // 2. Chain together various setter methods to set the dialog characteristics builder.setPositiveButton("Skicka", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked OK button } }); builder.setNegativeButton("Avbryt", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } }); } public void startTime(View view){ AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); // set title alertDialogBuilder.setTitle("Timestamp"); // set dialog message alertDialogBuilder .setMessage("Du har nu stämplat in") .setCancelable(false) .setPositiveButton("Avsluta",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { // if this button is clicked, close // current activity Start.this.finish(); } }) .setNegativeButton("Okej",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { // if this button is clicked, just close // the dialog box and do nothing dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } } /* button = (Button) findViewById(R.id.sendReportButton); button.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0){ AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("r du skert p att du vill skicka in rapporten?"); // 2. Chain together various setter methods to set the dialog characteristics builder.setPositiveButton("Skicka", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked OK button } }); builder.setNegativeButton("Avbryt", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } });*/
package pitt.search.semanticvectors.vectors; import java.io.IOException; import java.util.ArrayList; import java.util.Random; import java.util.logging.Logger; import org.apache.lucene.store.IndexInput; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.util.OpenBitSet; import pitt.search.semanticvectors.FlagConfig; /** * Binary implementation of Vector. * * Uses an "elemental" representation which is a single bit string (Lucene OpenBitSet). * * Superposes on this a "semantic" representation which contains the weights with which different * vectors have been added (superposed) onto this one. Calling {@link #superpose} causes the * voting record to be updated, but for performance the votes are not tallied back into the * elemental bit set representation until {@link #normalize} or one of the writing functions * is called. * * @author Trevor Cohen */ public class BinaryVector implements Vector { public static final Logger logger = Logger.getLogger(BinaryVector.class.getCanonicalName()); // TODO: Determing proper interface for default constants. /** * Number of decimal places to consider in weighted superpositions of binary vectors. * Higher precision requires additional memory during training. */ public static final int BINARY_VECTOR_DECIMAL_PLACES = 2; public static final boolean BINARY_BINDING_WITH_PERMUTE = false; private static final int DEBUG_PRINT_LENGTH = 64; private final int dimension; /** * Elemental representation for binary vectors. */ protected OpenBitSet bitSet; private boolean isSparse; /** * Representation of voting record for superposition. Each OpenBitSet object contains one bit * of the count for the vote in each dimension. The count for any given dimension is derived from * all of the bits in that dimension across the OpenBitSets in the voting record. * * The precision of the voting record (in number of decimal places) is defined upon initialization. * By default, if the first weight added is an integer, rounding occurs to the nearest integer. * Otherwise, rounding occurs to the second binary place. */ private ArrayList<OpenBitSet> votingRecord; int decimalPlaces = 0; /** Accumulated sum of the weights with which vectors have been added into the voting record */ int totalNumberOfVotes = 0; // TODO(widdows) Understand and comment this. int minimum = 0; // Used only for temporary internal storage. private OpenBitSet tempSet; public BinaryVector(int dimension) { // Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks if (dimension % 64 != 0) { throw new IllegalArgumentException("Dimension should be a multiple of 64: " + dimension + " will lead to trouble!"); } this.dimension = dimension; this.bitSet = new OpenBitSet(dimension); this.isSparse = true; } /** * Returns a new copy of this vector, in dense format. */ @SuppressWarnings("unchecked") public BinaryVector copy() { BinaryVector copy = new BinaryVector(dimension); copy.bitSet = (OpenBitSet) bitSet.clone(); if (!isSparse) copy.votingRecord = (ArrayList<OpenBitSet>) votingRecord.clone(); return copy; } public String toString() { StringBuilder debugString = new StringBuilder("BinaryVector."); if (isSparse) { debugString.append(" Elemental. First " + DEBUG_PRINT_LENGTH + " values are:\n"); for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(bitSet.getBit(x) + " "); debugString.append("\nCardinality " + bitSet.cardinality()+"\n"); } else { debugString.append(" Semantic. First " + DEBUG_PRINT_LENGTH + " values are:\n"); // output voting record for first DEBUG_PRINT_LENGTH dimension debugString.append("\nVOTING RECORD: \n"); for (int y =0; y < votingRecord.size(); y++) { for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(votingRecord.get(y).getBit(x) + " "); debugString.append("\n"); } // TODO - output count from first DEBUG_PRINT_LENGTH dimension debugString.append("\nNORMALIZED: "); this.normalize(); for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(bitSet.getBit(x) + " "); debugString.append("\n"); // Calculate actual values for first 20 dimension double[] actualvals = new double[DEBUG_PRINT_LENGTH]; debugString.append("COUNTS : "); for (int x =0; x < votingRecord.size(); x++) { for (int y = 0; y < DEBUG_PRINT_LENGTH; y++) { if (votingRecord.get(x).fastGet(y)) actualvals[y] += Math.pow(2, x); } } for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) { debugString.append((int) ((minimum + actualvals[x]) / Math.pow(10, decimalPlaces)) + " "); } debugString.append("\nCardinality " + bitSet.cardinality()+"\n"); debugString.append("Votes " + totalNumberOfVotes+"\n"); debugString.append("Minimum " + minimum + "\n"); } return debugString.toString(); } @Override public int getDimension() { return dimension; } public BinaryVector createZeroVector(int dimension) { // Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks if (dimension % 64 != 0) { logger.severe("Dimension should be a multiple of 64: " + dimension + " will lead to trouble!"); } return new BinaryVector(dimension); } @Override public boolean isZeroVector() { if (isSparse) { return bitSet.cardinality() == 0; } else { return (votingRecord == null) || (votingRecord.size() == 0); } } @Override /** * Generates a basic elemental vector with a given number of 1's and otherwise 0's. * For binary vectors, the numnber of 1's and 0's must be the same, half the dimension. * * @return representation of basic binary vector. */ public BinaryVector generateRandomVector(int dimension, int numEntries, Random random) { // Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks if (dimension % 64 != 0) { throw new IllegalArgumentException("Dimension should be a multiple of 64: " + dimension + " will lead to trouble!"); } // Check for balance between 1's and 0's if (numEntries != dimension / 2) { logger.severe("Attempting to create binary vector with unequal number of zeros and ones." + " Unlikely to produce meaningful results. Therefore, seedlength has been set to " + " dimension/2, as recommended for binary vectors"); numEntries = dimension / 2; } BinaryVector randomVector = new BinaryVector(dimension); randomVector.bitSet = new OpenBitSet(dimension); int testPlace = dimension - 1, entryCount = 0; // Iterate across dimension of bitSet, changing 0 to 1 if random(1) > 0.5 // until dimension/2 1's added. while (entryCount < numEntries) { testPlace = random.nextInt(dimension); if (!randomVector.bitSet.fastGet(testPlace)) { randomVector.bitSet.fastSet(testPlace); entryCount++; } } return randomVector; } @Override /** * Measures overlap of two vectors using 1 - normalized Hamming distance * * Causes this and other vector to be converted to dense representation. */ public double measureOverlap(Vector other) { IncompatibleVectorsException.checkVectorsCompatible(this, other); if (isZeroVector()) return 0; BinaryVector binaryOther = (BinaryVector) other; if (binaryOther.isZeroVector()) return 0; // Calculate hamming distance in place using cardinality and XOR, then return bitset to // original state. double hammingDistance = OpenBitSet.xorCount(binaryOther.bitSet, this.bitSet); return 2*(0.5 - (hammingDistance / (double) dimension)); } @Override /** * Adds the other vector to this one. If this vector was an elemental vector, the * "semantic vector" components (i.e. the voting record and temporary bitset) will be * initialized. * * Note that the precision of the voting record (in decimal places) is decided at this point: * if the initialization weight is an integer, rounding will occur to the nearest integer. * If not, rounding will occur to the second decimal place. * * This is an attempt to save space, as voting records can be prohibitively expansive * if not contained. */ public void superpose(Vector other, double weight, int[] permutation) { IncompatibleVectorsException.checkVectorsCompatible(this, other); if (weight == 0d) return; if (other.isZeroVector()) return; BinaryVector binaryOther = (BinaryVector) other; if (isSparse) { if (Math.round(weight) != weight) { decimalPlaces = BINARY_VECTOR_DECIMAL_PLACES; } elementalToSemantic(); } if (permutation != null) { // Rather than permuting individual dimensions, we permute 64 bit groups at a time. // This should be considerably quicker, and dimension/64 should allow for sufficient // permutations if (permutation.length != dimension / 64) { throw new IllegalArgumentException("Binary vector of dimension " + dimension + " must have permutation of length " + dimension / 64 + " not " + permutation.length); } //TODO permute in place and reverse, to avoid creating a new BinaryVector here BinaryVector temp = binaryOther.copy(); temp.permute(permutation); superposeBitSet(temp.bitSet, weight); } else { superposeBitSet(binaryOther.bitSet, weight); } } /** * This method is the first of two required to facilitate superposition. The underlying representation * (i.e. the voting record) is an ArrayList of OpenBitSet, each with dimension "dimension", which can * be thought of as an expanding 2D array of bits. Each column keeps count (in binary) for the respective * dimension, and columns are incremented in parallel by sweeping a bitset across the rows. In any dimension * in which the BitSet to be added contains a "1", the effect will be that 1's are changed to 0's until a * new 1 is added (e.g. the column '110' would become '001' and so forth). * * The first method deals with floating point issues, and accelerates superposition by decomposing * the task into segments. * * @param incomingBitSet * @param weight */ protected void superposeBitSet(OpenBitSet incomingBitSet, double weight) { // If fractional weights are used, encode all weights as integers (1000 x double value). weight = (int) Math.round(weight * Math.pow(10, decimalPlaces)); if (weight == 0) return; // Keep track of number (or cumulative weight) of votes. totalNumberOfVotes += weight; // Decompose superposition task such that addition of some power of 2 (e.g. 64) is accomplished // by beginning the process at the relevant row (e.g. 7) instead of starting multiple (e.g. 64) // superposition processes at the first row. int logFloorOfWeight = (int) (Math.floor(Math.log(weight)/Math.log(2))); if (logFloorOfWeight < votingRecord.size() - 1) { while (logFloorOfWeight > 0) { superposeBitSetFromRowFloor(incomingBitSet, logFloorOfWeight); weight = weight - (int) Math.pow(2,logFloorOfWeight); logFloorOfWeight = (int) (Math.floor(Math.log(weight)/Math.log(2))); } } // Add remaining component of weight incrementally. for (int x = 0; x < weight; x++) superposeBitSetFromRowFloor(incomingBitSet, 0); } /** * Performs superposition from a particular row by sweeping a bitset across the voting record * such that for any column in which the incoming bitset contains a '1', 1's are changed * to 0's until a new 1 can be added, facilitating incrementation of the * binary number represented in this column. * * @param incomingBitSet the bitset to be added * @param rowfloor the index of the place in the voting record to start the sweep at */ protected void superposeBitSetFromRowFloor(OpenBitSet incomingBitSet, int rowfloor) { // Attempt to save space when minimum value across all columns > 0 // by decrementing across the board and raising the minimum where possible. int max = getMaximumSharedWeight(); if (max > 0) { decrement(max); } // Handle overflow: if any column that will be incremented // contains all 1's, add a new row to the voting record. tempSet.xor(tempSet); tempSet.xor(incomingBitSet); for (int x = rowfloor; x < votingRecord.size() && tempSet.cardinality() > 0; x++) { tempSet.and(votingRecord.get(x)); } if (tempSet.cardinality() > 0) { votingRecord.add(new OpenBitSet(dimension)); } // Sweep copy of bitset to be added across rows of voting record. // If a new '1' is added, this position in the copy is changed to zero // and will not affect future rows. // The xor step will transform 1's to 0's or vice versa for // dimension in which the temporary bitset contains a '1'. votingRecord.get(rowfloor).xor(incomingBitSet); tempSet.xor(tempSet); tempSet.xor(incomingBitSet); for (int x = rowfloor + 1; x < votingRecord.size(); x++) { tempSet.andNot(votingRecord.get(x-1)); //if 1 already added, eliminate dimension from tempSet votingRecord.get(x).xor(tempSet); votingRecord.get(x).trimTrailingZeros(); //attempt to save in sparsely populated rows } } /** * Reverses a string - simplifies the decoding of the binary vector for the 'exact' method * although it wouldn't be difficult to reverse the counter instead */ public static String reverse(String str) { if ((null == str) || (str.length() <= 1)) { return str; } return new StringBuffer(str).reverse().toString(); } /** * Sets {@link #tempSet} to be a bitset with a "1" in the position of every dimension * in the {@link #votingRecord} that exactly matches the target number. */ private void setTempSetToExactMatches(int target) { if (target == 0) { tempSet.set(0, dimension); tempSet.xor(votingRecord.get(0)); for (int x = 1; x < votingRecord.size(); x++) tempSet.andNot(votingRecord.get(x)); } String inbinary = reverse(Integer.toBinaryString(target)); tempSet.xor(tempSet); tempSet.xor(votingRecord.get(inbinary.indexOf("1"))); for (int q =0; q < votingRecord.size(); q++) { if (q < inbinary.length()) if (inbinary.charAt(q) == '1') tempSet.and(votingRecord.get(q)); else tempSet.andNot(votingRecord.get(q)); } } /** * This method is used determine which dimension will receive 1 and which 0 when the voting * process is concluded. It produces an OpenBitSet in which * "1" is assigned to all dimension with a count > 50% of the total number of votes (i.e. more 1's than 0's added) * "0" is assigned to all dimension with a count < 50% of the total number of votes (i.e. more 0's than 1's added) * "0" or "1" are assigned to all dimension with a count = 50% of the total number of votes (i.e. equal 1's and 0's added) * * @return an OpenBitSet representing the superposition of all vectors added up to this point */ protected OpenBitSet concludeVote() { if (votingRecord.size() == 0 || votingRecord.size() == 1 && votingRecord.get(0).cardinality() ==0) return new OpenBitSet(dimension); else return concludeVote(totalNumberOfVotes); } protected OpenBitSet concludeVote(int target) { int target2 = (int) Math.ceil((double) target / (double) 2); target2 = target2 - minimum; // Unlikely other than in testing: minimum more than half the votes if (target2 < 0) { OpenBitSet ans = new OpenBitSet(dimension); ans.set(0, dimension); return ans; } boolean even = (target % 2 == 0); OpenBitSet result = concludeVote(target2, votingRecord.size() - 1); if (even) { setTempSetToExactMatches(target2); boolean switcher = true; // 50% chance of being true with split vote. for (int q = 0; q < dimension; q++) { if (tempSet.fastGet(q)) { switcher = !switcher; if (switcher) tempSet.fastClear(q); } } result.andNot(tempSet); } return result; } protected OpenBitSet concludeVote(int target, int row_ceiling) { /** logger.info("Entering conclude vote, target " + target + " row_ceiling " + row_ceiling + "voting record " + votingRecord.size() + " minimum "+ minimum + " index "+ Math.log(target)/Math.log(2) + " vector\n" + toString()); **/ if (target == 0) { OpenBitSet atLeastZero = new OpenBitSet(dimension); atLeastZero.set(0, dimension); return atLeastZero; } double rowfloor = Math.log(target)/Math.log(2); int row_floor = (int) Math.floor(rowfloor); //for 0 index int remainder = target - (int) Math.pow(2,row_floor); //System.out.println(target+"\t"+rowfloor+"\t"+row_floor+"\t"+remainder); if (row_ceiling == 0 && target == 1) { return votingRecord.get(0); } if (remainder == 0) { // Simple case - the number we're looking for is 2^n, so anything with a "1" in row n or above is true. OpenBitSet definitePositives = new OpenBitSet(dimension); for (int q = row_floor; q <= row_ceiling; q++) definitePositives.or(votingRecord.get(q)); return definitePositives; } else { // Simple part of complex case: first get anything with a "1" in a row above n (all true). OpenBitSet definitePositives = new OpenBitSet(dimension); for (int q = row_floor+1; q <= row_ceiling; q++) definitePositives.or(votingRecord.get(q)); // Complex part of complex case: get those that have a "1" in the row of n. OpenBitSet possiblePositives = (OpenBitSet) votingRecord.get(row_floor).clone(); OpenBitSet definitePositives2 = concludeVote(remainder, row_floor-1); possiblePositives.and(definitePositives2); definitePositives.or(possiblePositives); return definitePositives; } } /** * Decrement every dimension. Assumes at least one count in each dimension * i.e: no underflow check currently - will wreak havoc with zero counts */ public void decrement() { tempSet.set(0, dimension); for (int q = 0; q < votingRecord.size(); q++) { votingRecord.get(q).xor(tempSet); tempSet.and(votingRecord.get(q)); } } /** * Decrement every dimension by the number passed as a parameter. Again at least one count in each dimension * i.e: no underflow check currently - will wreak havoc with zero counts */ public void decrement(int weight) { if (weight == 0) return; minimum+= weight; int logfloor = (int) (Math.floor(Math.log(weight)/Math.log(2))); if (logfloor < votingRecord.size() - 1) { while (logfloor > 0) { selectedDecrement(logfloor); weight = weight - (int) Math.pow(2,logfloor); logfloor = (int) (Math.floor(Math.log(weight)/Math.log(2))); } } for (int x = 0; x < weight; x++) { decrement(); } } public void selectedDecrement(int floor) { tempSet.set(0, dimension); for (int q = floor; q < votingRecord.size(); q++) { votingRecord.get(q).xor(tempSet); tempSet.and(votingRecord.get(q)); } } /** * Returns the highest value shared by all dimensions. */ protected int getMaximumSharedWeight() { int thismaximum = 0; tempSet.xor(tempSet); // Reset tempset to zeros. for (int x = votingRecord.size() - 1; x >= 0; x tempSet.or(votingRecord.get(x)); if (tempSet.cardinality() == dimension) { thismaximum += (int) Math.pow(2, x); tempSet.xor(tempSet); } } return thismaximum; } @Override /** * Implements binding using permutations and XOR. */ public void bind(Vector other, int direction) { IncompatibleVectorsException.checkVectorsCompatible(this, other); BinaryVector binaryOther = (BinaryVector) other.copy(); if (direction > 0) { //as per Kanerva 2009: bind(A,B) = perm+(A) XOR B = C //this also functions as the left inverse: left inverse (A,C) = perm+(A) XOR C = B this.permute(PermutationUtils.getShiftPermutation(VectorType.BINARY, dimension, 1)); //perm+(A) this.bitSet.xor(binaryOther.bitSet); //perm+(A) XOR B } else { //as per Kanerva 2009: right inverse(C,B) = perm-(C XOR B) = perm-(perm+(A)) = A this.bitSet.xor(binaryOther.bitSet); //C XOR B this.permute(PermutationUtils.getShiftPermutation(VectorType.BINARY, dimension, -1)); //perm-(C XOR B) = A } } @Override /** * Implements inverse of binding using permutations and XOR. */ public void release(Vector other, int direction) { if (!BINARY_BINDING_WITH_PERMUTE) bind(other); else bind (other, direction); } @Override /** * Implements binding using exclusive OR. */ public void bind(Vector other) { IncompatibleVectorsException.checkVectorsCompatible(this, other); if (!BINARY_BINDING_WITH_PERMUTE) { BinaryVector binaryOther = (BinaryVector) other; this.bitSet.xor(binaryOther.bitSet); } else { bind(other, 1); } } @Override /** * Implements inverse binding using exclusive OR. */ public void release(Vector other) { if (!BINARY_BINDING_WITH_PERMUTE) bind(other); else bind(other, -1); } @Override /** * Normalizes the vector, converting sparse to dense representations in the process. */ public void normalize() { if (!isSparse) this.bitSet = concludeVote(); } @Override /** * Writes vector out to object output stream. Converts to dense format if necessary. */ public void writeToLuceneStream(IndexOutput outputStream) { if (isSparse) { elementalToSemantic(); } long[] bitArray = bitSet.getBits(); for (int i = 0; i < bitArray.length; i++) { try { outputStream.writeLong(bitArray[i]); } catch (IOException e) { logger.severe("Couldn't write binary vector to lucene output stream."); e.printStackTrace(); } } } @Override /** * Reads a (dense) version of a vector from a Lucene input stream. */ public void readFromLuceneStream(IndexInput inputStream) { long bitArray[] = new long[(dimension / 64)]; for (int i = 0; i < dimension / 64; ++i) { try { bitArray[i] = inputStream.readLong(); } catch (IOException e) { logger.severe("Couldn't read binary vector from lucene output stream."); e.printStackTrace(); } } this.bitSet = new OpenBitSet(bitArray, bitArray.length); this.isSparse = true; } @Override /** * Writes vector to a string of the form 010 etc. (no delimiters). * * No terminating newline or delimiter. */ public String writeToString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < dimension; ++i) { builder.append(Integer.toString(bitSet.getBit(i))); } return builder.toString(); } /** * Writes vector to a string of the form 010 etc. (no delimiters). * * No terminating newline or delimiter. */ public String writeLongToString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < (bitSet.getBits().length); ++i) { builder.append(Long.toString(bitSet.getBits()[i])+"|"); } return builder.toString(); } @Override /** * Writes vector from a string of the form 01001 etc. */ public void readFromString(String input) { if (input.length() != dimension) { throw new IllegalArgumentException("Found " + (input.length()) + " possible coordinates: " + "expected " + dimension); } for (int i = 0; i < dimension; ++i) { if (input.charAt(i) == '1') bitSet.fastSet(i); } } /** * Automatically translate elemental vector (no storage capacity) into * semantic vector (storage capacity initialized, this will occupy RAM) */ protected void elementalToSemantic() { if (!isSparse) { logger.warning("Tried to transform an elemental vector which is not in fact elemental." + "This may be a programming error."); return; } votingRecord = new ArrayList<OpenBitSet>(); votingRecord.add((OpenBitSet) bitSet.clone()); tempSet = new OpenBitSet(dimension); isSparse = false; } /** * Permute the long[] array underlying the OpenBitSet binary representation */ public void permute(int[] permutation) { if (permutation.length != getDimension() / 64) { throw new IllegalArgumentException("Binary vector of dimension " + getDimension() + " must have permutation of length " + getDimension() / 64 + " not " + permutation.length); } //TODO permute in place without creating additional long[] (if proves problematic at scale) long[] coordinates = bitSet.getBits(); long[] newCoordinates = new long[coordinates.length]; for (int i = 0; i < coordinates.length; ++i) { int positionToAdd = i; positionToAdd = permutation[positionToAdd]; newCoordinates[i] = coordinates[positionToAdd]; } bitSet.setBits(newCoordinates); } // Available for testing and copying. protected BinaryVector(OpenBitSet inSet) { this.dimension = (int) inSet.size(); this.bitSet = inSet; } // Available for testing protected int bitLength() { return bitSet.getBits().length; } // Monitor growth of voting record. protected int numRows() { if (isSparse) return 0; return votingRecord.size(); } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.awt.image.RescaleOp; import java.io.IOException; import java.io.InputStream; import java.util.Optional; import javax.imageio.ImageIO; import javax.swing.*; public final class MainPanel extends JPanel { private MainPanel() { super(); String path = "example/test.png"; ClassLoader cl = Thread.currentThread().getContextClassLoader(); Icon icon = Optional.ofNullable(cl.getResource(path)).map(url -> { try (InputStream s = url.openStream()) { return new ImageIcon(ImageIO.read(s)); } catch (IOException ex) { return new MissingIcon(); } }).orElseGet(MissingIcon::new); JLabel label = new LabelWithToolBox(icon); label.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(new Color(0xDE_DE_DE)), BorderFactory.createLineBorder(Color.WHITE, 4))); add(label); setPreferredSize(new Dimension(320, 240)); } 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.DISPOSE_ON_CLOSE); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class LabelWithToolBox extends JLabel { public static final int DELAY = 8; protected final Timer animator = new Timer(DELAY, null); private transient ToolBoxHandler handler; protected boolean isHidden; protected int counter; protected int yy; private final JToolBar toolBox = new JToolBar() { private transient MouseListener listener; @Override protected void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g.create(); g2.setPaint(getBackground()); g2.fillRect(0, 0, getWidth(), getHeight()); g2.dispose(); super.paintComponent(g); } @Override public void updateUI() { removeMouseListener(listener); super.updateUI(); listener = new ParentDispatchMouseListener(); addMouseListener(listener); setFloatable(false); setOpaque(false); setBackground(new Color(0x0, true)); setForeground(Color.WHITE); setBorder(BorderFactory.createEmptyBorder(2, 4, 4, 4)); } }; protected LabelWithToolBox(Icon icon) { super(icon); animator.addActionListener(e -> { int height = toolBox.getPreferredSize().height; double h = (double) height; if (isHidden) { double a = AnimationUtil.easeInOut(++counter / h); yy = (int) (.5 + a * h); toolBox.setBackground(new Color(0f, 0f, 0f, (float) (.6 * a))); if (yy >= height) { yy = height; animator.stop(); } } else { double a = AnimationUtil.easeInOut(--counter / h); yy = (int) (.5 + a * h); toolBox.setBackground(new Color(0f, 0f, 0f, (float) (.6 * a))); if (yy <= 0) { yy = 0; animator.stop(); } } toolBox.revalidate(); }); // toolBox.setLayout(new BoxLayout(toolBox, BoxLayout.X_AXIS)); toolBox.add(Box.createGlue()); toolBox.add(makeToolButton("ATTACHMENT_16x16-32.png")); toolBox.add(Box.createHorizontalStrut(2)); toolBox.add(makeToolButton("RECYCLE BIN - EMPTY_16x16-32.png")); add(toolBox); } @Override public void updateUI() { removeMouseListener(handler); addHierarchyListener(handler); super.updateUI(); setLayout(new OverlayLayout(this) { @Override public void layoutContainer(Container parent) { // Insets insets = parent.getInsets(); int ncomponents = parent.getComponentCount(); if (ncomponents == 0) { return; } int width = parent.getWidth(); // - insets.left - insets.right; int height = parent.getHeight(); // - insets.left - insets.right; int x = 0; // insets.left; int y = insets.top; // for (int i = 0; i < ncomponents; i++) { Component c = parent.getComponent(0); // = toolBox; c.setBounds(x, height - yy, width, c.getPreferredSize().height); } }); handler = new ToolBoxHandler(); addMouseListener(handler); addHierarchyListener(handler); } private class ToolBoxHandler extends MouseAdapter implements HierarchyListener { @Override public void mouseEntered(MouseEvent e) { if (!animator.isRunning()) { // && yy != toolBox.getPreferredSize().height) { isHidden = true; animator.start(); } } @Override public void mouseExited(MouseEvent e) { if (!contains(e.getPoint())) { // !animator.isRunning()) { isHidden = false; animator.start(); } } @Override public void hierarchyChanged(HierarchyEvent e) { boolean b = (e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0; if (b && !e.getComponent().isDisplayable()) { animator.stop(); } } } private JButton makeToolButton(String name) { String path = "example/" + name; ClassLoader cl = Thread.currentThread().getContextClassLoader(); Image image = Optional.ofNullable(cl.getResource(path)).map(url -> { try (InputStream s = url.openStream()) { return ImageIO.read(s); } catch (IOException ex) { return makeMissingImage(); } }).orElseGet(LabelWithToolBox::makeMissingImage); ImageIcon icon = new ImageIcon(image); JButton b = new JButton(); b.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); // b.addChangeListener(new ChangeListener() { // @Override public void stateChanged(ChangeEvent e) { // JButton button = (JButton) e.getSource(); // ButtonModel model = button.getModel(); // if (button.isRolloverEnabled() && model.isRollover()) { // button.setBorder(BorderFactory.createLineBorder(Color.WHITE)); // } else { // button.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); b.setIcon(makeRolloverIcon(icon)); b.setRolloverIcon(icon); b.setContentAreaFilled(false); // b.setBorderPainted(false); b.setFocusPainted(false); b.setFocusable(false); b.setToolTipText(name); return b; } private static Image makeMissingImage() { Icon missingIcon = UIManager.getIcon("html.missingImage"); int iw = missingIcon.getIconWidth(); int ih = missingIcon.getIconHeight(); BufferedImage bi = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = bi.createGraphics(); missingIcon.paintIcon(null, g2, (16 - iw) / 2, (16 - ih) / 2); g2.dispose(); return bi; } private static ImageIcon makeRolloverIcon(ImageIcon srcIcon) { int w = srcIcon.getIconWidth(); int h = srcIcon.getIconHeight(); BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = img.createGraphics(); srcIcon.paintIcon(null, g2, 0, 0); float[] scaleFactors = {.5f, .5f, .5f, 1f}; float[] offsets = {0f, 0f, 0f, 0f}; RescaleOp op = new RescaleOp(scaleFactors, offsets, g2.getRenderingHints()); g2.dispose(); return new ImageIcon(op.filter(img, null)); } } class ParentDispatchMouseListener extends MouseAdapter { @Override public void mouseEntered(MouseEvent e) { dispatchMouseEvent(e); } @Override public void mouseExited(MouseEvent e) { dispatchMouseEvent(e); } private void dispatchMouseEvent(MouseEvent e) { Component src = e.getComponent(); Optional.ofNullable(SwingUtilities.getUnwrappedParent(src)).ifPresent(tgt -> tgt.dispatchEvent(SwingUtilities.convertMouseEvent(src, e, tgt))); } } final class AnimationUtil { private static final int N = 3; private AnimationUtil() { /* Singleton */ } // Math: EaseIn EaseOut, EaseInOut and Bezier Curves | Anima Entertainment GmbH public static double easeIn(double t) { // range: 0.0 <= t <= 1.0 return Math.pow(t, N); } public static double easeOut(double t) { return Math.pow(t - 1d, N) + 1d; } public static double easeInOut(double t) { double ret; boolean isFirstHalf = t < .5; if (isFirstHalf) { ret = .5 * intpow(t * 2d, N); } else { ret = .5 * (intpow(t * 2d - 2d, N) + 2d); } return ret; } public static double intpow(double da, int ib) { int b = ib; if (b < 0) { // return d / intpow(a, -b); throw new IllegalArgumentException("B must be a positive integer or zero"); } double a = da; double d = 1d; for (; b > 0; a *= a, b >>>= 1) { if ((b & 1) != 0) { d *= a; } } return d; } // public static double delta(double t) { // return 1d - Math.sin(Math.acos(t)); } class MissingIcon implements Icon { @Override public void paintIcon(Component c, Graphics g, int x, int y) { Graphics2D g2 = (Graphics2D) g.create(); int w = getIconWidth(); int h = getIconHeight(); int gap = w / 5; g2.setColor(Color.WHITE); g2.fillRect(x, y, w, h); g2.setColor(Color.RED); g2.setStroke(new BasicStroke(w / 8f)); g2.drawLine(x + gap, y + gap, x + w - gap, y + h - gap); g2.drawLine(x + gap, y + h - gap, x + w - gap, y + gap); g2.dispose(); } @Override public int getIconWidth() { return 240; } @Override public int getIconHeight() { return 160; } }
import org.json.simple.JSONArray; import org.json.simple.JSONObject; import spark.Request; import spark.Response; import spark.servlet.SparkApplication; import spark.utils.IOUtils; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.math.BigInteger; import java.nio.charset.Charset; import java.util.Base64; import java.util.Date; import java.util.Iterator; import java.util.Set; import java.util.logging.FileHandler; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import static spark.Spark.*; public class SparkServer implements SparkApplication { private static final Logger logger = Logger.getLogger(SparkServer.class.getName()); static PrintClass print = new PrintClass(); static private JsonPersistency jsonPersistency; static Bank bank; static FileHandler fh; //Change to true when using authentication boolean authentication = false; private class SMTPAuth extends Authenticator { public PasswordAuthentication authenticateSender() { return new PasswordAuthentication("username@gmail.com", "password"); } } static public void main(String args[]) { SparkApplication sparkApplication = new SparkServer(); sparkApplication.init(); } public void init() { Runtime.getRuntime().addShutdownHook(new ShutdownThread()); apiLogSetup(); loadBank(); createAccounts();
package com.jme.scene; import java.io.IOException; import java.io.Serializable; import com.jme.renderer.RenderContext; import com.jme.renderer.Renderer; import com.jme.scene.state.RenderState; import com.jme.util.export.InputCapsule; import com.jme.util.export.JMEExporter; import com.jme.util.export.JMEImporter; import com.jme.util.export.OutputCapsule; import com.jme.util.export.Savable; /** PassNodeState Creator: rikard.herlitz, 2007-maj-10 */ public class PassNodeState implements Savable, Serializable { /** if false, pass will not be updated or rendered. */ protected boolean enabled = true; /** * offset params to use to differentiate multiple passes of the same scene * in the zbuffer. */ protected float zFactor; protected float zOffset; /** * RenderStates registered with this pass - if a given state is not null it * overrides the corresponding state set during rendering. */ protected RenderState[] passStates = new RenderState[RenderState.RS_MAX_STATE]; /** * a place to internally save previous states setup before rendering this * pass */ protected RenderState[] savedStates = new RenderState[RenderState.RS_MAX_STATE]; /** * Applies all currently set renderstates and z offset parameters to the * supplied context * * @param r * @param context */ public void applyPassNodeState(Renderer r, RenderContext context) { applyPassStates(context); r.setPolygonOffset(zFactor, zOffset); } /** * Resets currently set renderstates and z offset parameters on the supplied * context * * @param r * @param context */ public void resetPassNodeStates(Renderer r, RenderContext context) { r.clearPolygonOffset(); resetOldStates(context); } /** * Enforce a particular state. In other words, the given state will override * any state of the same type set on a scene object. Remember to clear the * state when done enforcing. Very useful for multipass techniques where * multiple sets of states need to be applied to a scenegraph drawn multiple * times. * * @param state state to enforce */ public void setPassState(RenderState state) { passStates[state.getType()] = state; } /** * @param renderStateType * the type to query * @return the state enforced for a give state type, or null if none. */ public RenderState getPassState(int renderStateType) { return passStates[renderStateType]; } /** * Clears an enforced render state index by setting it to null. This allows * object specific states to be used. * * @param renderStateType The type of RenderState to clear enforcement on. */ public void clearPassState(int renderStateType) { passStates[renderStateType] = null; } /** * sets all enforced states to null. * * @see RenderContext#clearEnforcedState(int) */ public void clearPassStates() { for (int i = 0; i < passStates.length; i++) { passStates[i] = null; } } /** * Applies all currently set renderstates to the supplied context * * @param context */ protected void applyPassStates(RenderContext context) { for (int x = RenderState.RS_MAX_STATE; --x >= 0;) { if (passStates[x] != null) { savedStates[x] = context.enforcedStateList[x]; context.enforcedStateList[x] = passStates[x]; } } } /** * Resets all renderstates on the supplied context * * @param context */ protected void resetOldStates(RenderContext context) { for (int x = RenderState.RS_MAX_STATE; --x >= 0;) { if (passStates[x] != null) { context.enforcedStateList[x] = savedStates[x]; } } } /** @return Returns the enabled. */ public boolean isEnabled() { return enabled; } /** @param enabled The enabled to set. */ public void setEnabled(boolean enabled) { this.enabled = enabled; } /** @return Returns the zFactor. */ public float getZFactor() { return zFactor; } /** * Sets the polygon offset param - factor - for this Pass. * * @param factor The zFactor to set. */ public void setZFactor(float factor) { zFactor = factor; } /** @return Returns the zOffset. */ public float getZOffset() { return zOffset; } /** * Sets the polygon offset param - offset - for this Pass. * * @param offset The zOffset to set. */ public void setZOffset(float offset) { zOffset = offset; } public Class getClassTag() { return this.getClass(); } public void write(JMEExporter e) throws IOException { OutputCapsule oc = e.getCapsule(this); oc.write(enabled, "enabled", true); oc.write(zFactor, "zFactor", 0); oc.write(zOffset, "zOffset", 0); oc.write(passStates, "passStates", null); oc.write(savedStates, "savedStates", null); } public void read(JMEImporter e) throws IOException { InputCapsule ic = e.getCapsule(this); enabled = ic.readBoolean("enabled", true); zFactor = ic.readFloat("zFactor", 0); zOffset = ic.readFloat("zOffset", 0); Savable[] temp = ic.readSavableArray("passStates", null); // XXX: Perhaps this should be redone to use the state type to place it // in the right spot in the array? passStates = new RenderState[temp.length]; for (int i = 0; i < temp.length; i++) { passStates[i] = (RenderState) temp[i]; } temp = ic.readSavableArray("savedStates", null); savedStates = new RenderState[temp.length]; for (int i = 0; i < temp.length; i++) { savedStates[i] = (RenderState) temp[i]; } } }