diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/main/java/com/thalesgroup/hudson/plugins/gnat/gnatcheck/GnatcheckPublisher.java b/src/main/java/com/thalesgroup/hudson/plugins/gnat/gnatcheck/GnatcheckPublisher.java
index bffe766..4ca8b41 100644
--- a/src/main/java/com/thalesgroup/hudson/plugins/gnat/gnatcheck/GnatcheckPublisher.java
+++ b/src/main/java/com/thalesgroup/hudson/plugins/gnat/gnatcheck/GnatcheckPublisher.java
@@ -1,192 +1,194 @@
/*******************************************************************************
* Copyright (c) 2009 Thales Corporate Services SAS *
* Author : Gregory Boissinot *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy *
* of this software and associated documentation files (the "Software"), to deal*
* in the Software without restriction, including without limitation the rights *
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell *
* copies of the Software, and to permit persons to whom the Software is *
* furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,*
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN *
* THE SOFTWARE. *
*******************************************************************************/
package com.thalesgroup.hudson.plugins.gnat.gnatcheck;
import com.thalesgroup.hudson.plugins.gnat.GnatInstallation;
import com.thalesgroup.hudson.plugins.gnat.gnatmake.GnatmakeBuilder;
import com.thalesgroup.hudson.plugins.gnat.util.GnatException;
import com.thalesgroup.hudson.plugins.gnat.util.GnatUtil;
import hudson.Extension;
import hudson.Launcher;
import hudson.Util;
import hudson.matrix.MatrixProject;
import hudson.model.*;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Publisher;
import hudson.tasks.Recorder;
import hudson.util.ArgumentListBuilder;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.StaplerRequest;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
public class GnatcheckPublisher extends Recorder implements Serializable {
private static final long serialVersionUID = 1L;
public final GnatcheckType[] types;
public GnatcheckPublisher(GnatcheckType[] types) {
this.types = types;
}
@Extension
public static final class GnatcheckPublisherDescriptor extends
BuildStepDescriptor<Publisher> {
public GnatcheckPublisherDescriptor() {
super(GnatcheckPublisher.class);
load();
}
@Override
public String getDisplayName() {
return "Run gnatcheck";
}
@Override
public Publisher newInstance(StaplerRequest req, JSONObject formData) throws FormException {
List<GnatcheckType> buildTypes = Descriptor.newInstancesFromHeteroList(
req, formData, "types", GnatcheckTypeDescriptor.LIST);
return new GnatcheckPublisher(buildTypes.toArray(new GnatcheckType[buildTypes.size()]));
}
@Override
public String getHelpFile() {
return "/plugin/gnat/gnatcheck/help.html";
}
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return FreeStyleProject.class.isAssignableFrom(jobType) || MatrixProject.class.isAssignableFrom(jobType);
}
public GnatInstallation[] getInstallations() {
return GnatmakeBuilder.DESCRIPTOR.getInstallations();
}
public List<GnatcheckTypeDescriptor> getBuildTypes() {
return GnatcheckTypeDescriptor.LIST;
}
}
@Override
public boolean needsToRunAfterFinalized() {
return true;
}
@Override
public boolean prebuild(AbstractBuild<?, ?> build, BuildListener listener) {
return true;
}
@SuppressWarnings("unchecked")
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
BuildListener listener) throws InterruptedException, IOException {
if (build.getResult().equals(Result.SUCCESS)
|| (build.getResult().equals(Result.UNSTABLE))) {
for (GnatcheckType type : types) {
ArgumentListBuilder args = new ArgumentListBuilder();
if (type instanceof ProjectGnatcheckType) {
ProjectGnatcheckType projectGnatcheckType = (ProjectGnatcheckType) type;
String execPathGnat = null;
try {
execPathGnat = GnatUtil.getExecutable(projectGnatcheckType.getDescriptor().getInstallations(), type.gnatName, launcher, listener, GnatInstallation.GNAT_TYPE.GNAT);
}
catch (GnatException ge) {
ge.printStackTrace(listener.fatalError("error"));
build.setResult(Result.FAILURE);
return false;
}
args.add(execPathGnat);
args.add("check");
args.add("-P");
String normalizedProjectFile = projectGnatcheckType.projectFile.replaceAll("[\t\r\n]+", " ");
GnatUtil.addTokenIfExist(build.getModuleRoot() + File.separator + normalizedProjectFile, args, true, build);
GnatUtil.addTokenIfExist(projectGnatcheckType.options, args, false, build);
GnatUtil.addTokenIfExist(projectGnatcheckType.rule_options, args, false, build, "-rules");
} else {
FreeStyleGnatcheckType freeStyleGnatcheckType = (FreeStyleGnatcheckType) type;
String execPathGnatcheck = null;
try {
execPathGnatcheck = GnatUtil.getExecutable(freeStyleGnatcheckType.getDescriptor().getInstallations(), type.gnatName, launcher, listener, GnatInstallation.GNAT_TYPE.GNATCHECK);
}
catch (GnatException ge) {
ge.printStackTrace(listener.fatalError("error"));
build.setResult(Result.FAILURE);
return false;
}
args.add(execPathGnatcheck);
GnatUtil.addTokenIfExist(freeStyleGnatcheckType.switches, args, false, build);
GnatUtil.addTokenIfExist(freeStyleGnatcheckType.filename, args, true, build);
GnatUtil.addTokenIfExist(freeStyleGnatcheckType.gcc_switches, args, false, build, "-cargs");
GnatUtil.addTokenIfExist(freeStyleGnatcheckType.rule_options, args, false, build, "-rules");
}
try {
int r = launcher.launch().cmds(args)
.envs(build.getEnvironment(listener)).stdout(listener)
.pwd(build.getModuleRoot()).join();
- if (r != 0) {
+ //On Windows, gnatchek returns an exit code different of zero, even if there is no errors.
+ //Ignoring Windows return code.
+ if (r != 0 && launcher.isUnix()) {
build.setResult(Result.FAILURE);
return false;
}
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError("error"));
build.setResult(Result.FAILURE);
return false;
}
}
}
return true;
}
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.BUILD;
}
}
| true | true | public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
BuildListener listener) throws InterruptedException, IOException {
if (build.getResult().equals(Result.SUCCESS)
|| (build.getResult().equals(Result.UNSTABLE))) {
for (GnatcheckType type : types) {
ArgumentListBuilder args = new ArgumentListBuilder();
if (type instanceof ProjectGnatcheckType) {
ProjectGnatcheckType projectGnatcheckType = (ProjectGnatcheckType) type;
String execPathGnat = null;
try {
execPathGnat = GnatUtil.getExecutable(projectGnatcheckType.getDescriptor().getInstallations(), type.gnatName, launcher, listener, GnatInstallation.GNAT_TYPE.GNAT);
}
catch (GnatException ge) {
ge.printStackTrace(listener.fatalError("error"));
build.setResult(Result.FAILURE);
return false;
}
args.add(execPathGnat);
args.add("check");
args.add("-P");
String normalizedProjectFile = projectGnatcheckType.projectFile.replaceAll("[\t\r\n]+", " ");
GnatUtil.addTokenIfExist(build.getModuleRoot() + File.separator + normalizedProjectFile, args, true, build);
GnatUtil.addTokenIfExist(projectGnatcheckType.options, args, false, build);
GnatUtil.addTokenIfExist(projectGnatcheckType.rule_options, args, false, build, "-rules");
} else {
FreeStyleGnatcheckType freeStyleGnatcheckType = (FreeStyleGnatcheckType) type;
String execPathGnatcheck = null;
try {
execPathGnatcheck = GnatUtil.getExecutable(freeStyleGnatcheckType.getDescriptor().getInstallations(), type.gnatName, launcher, listener, GnatInstallation.GNAT_TYPE.GNATCHECK);
}
catch (GnatException ge) {
ge.printStackTrace(listener.fatalError("error"));
build.setResult(Result.FAILURE);
return false;
}
args.add(execPathGnatcheck);
GnatUtil.addTokenIfExist(freeStyleGnatcheckType.switches, args, false, build);
GnatUtil.addTokenIfExist(freeStyleGnatcheckType.filename, args, true, build);
GnatUtil.addTokenIfExist(freeStyleGnatcheckType.gcc_switches, args, false, build, "-cargs");
GnatUtil.addTokenIfExist(freeStyleGnatcheckType.rule_options, args, false, build, "-rules");
}
try {
int r = launcher.launch().cmds(args)
.envs(build.getEnvironment(listener)).stdout(listener)
.pwd(build.getModuleRoot()).join();
if (r != 0) {
build.setResult(Result.FAILURE);
return false;
}
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError("error"));
build.setResult(Result.FAILURE);
return false;
}
}
}
return true;
}
| public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
BuildListener listener) throws InterruptedException, IOException {
if (build.getResult().equals(Result.SUCCESS)
|| (build.getResult().equals(Result.UNSTABLE))) {
for (GnatcheckType type : types) {
ArgumentListBuilder args = new ArgumentListBuilder();
if (type instanceof ProjectGnatcheckType) {
ProjectGnatcheckType projectGnatcheckType = (ProjectGnatcheckType) type;
String execPathGnat = null;
try {
execPathGnat = GnatUtil.getExecutable(projectGnatcheckType.getDescriptor().getInstallations(), type.gnatName, launcher, listener, GnatInstallation.GNAT_TYPE.GNAT);
}
catch (GnatException ge) {
ge.printStackTrace(listener.fatalError("error"));
build.setResult(Result.FAILURE);
return false;
}
args.add(execPathGnat);
args.add("check");
args.add("-P");
String normalizedProjectFile = projectGnatcheckType.projectFile.replaceAll("[\t\r\n]+", " ");
GnatUtil.addTokenIfExist(build.getModuleRoot() + File.separator + normalizedProjectFile, args, true, build);
GnatUtil.addTokenIfExist(projectGnatcheckType.options, args, false, build);
GnatUtil.addTokenIfExist(projectGnatcheckType.rule_options, args, false, build, "-rules");
} else {
FreeStyleGnatcheckType freeStyleGnatcheckType = (FreeStyleGnatcheckType) type;
String execPathGnatcheck = null;
try {
execPathGnatcheck = GnatUtil.getExecutable(freeStyleGnatcheckType.getDescriptor().getInstallations(), type.gnatName, launcher, listener, GnatInstallation.GNAT_TYPE.GNATCHECK);
}
catch (GnatException ge) {
ge.printStackTrace(listener.fatalError("error"));
build.setResult(Result.FAILURE);
return false;
}
args.add(execPathGnatcheck);
GnatUtil.addTokenIfExist(freeStyleGnatcheckType.switches, args, false, build);
GnatUtil.addTokenIfExist(freeStyleGnatcheckType.filename, args, true, build);
GnatUtil.addTokenIfExist(freeStyleGnatcheckType.gcc_switches, args, false, build, "-cargs");
GnatUtil.addTokenIfExist(freeStyleGnatcheckType.rule_options, args, false, build, "-rules");
}
try {
int r = launcher.launch().cmds(args)
.envs(build.getEnvironment(listener)).stdout(listener)
.pwd(build.getModuleRoot()).join();
//On Windows, gnatchek returns an exit code different of zero, even if there is no errors.
//Ignoring Windows return code.
if (r != 0 && launcher.isUnix()) {
build.setResult(Result.FAILURE);
return false;
}
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError("error"));
build.setResult(Result.FAILURE);
return false;
}
}
}
return true;
}
|
diff --git a/OpERP/src/main/java/devopsdistilled/operp/client/items/panes/controllers/impl/CreateItemPaneControllerImpl.java b/OpERP/src/main/java/devopsdistilled/operp/client/items/panes/controllers/impl/CreateItemPaneControllerImpl.java
index 9550ae21..3f53c6e7 100644
--- a/OpERP/src/main/java/devopsdistilled/operp/client/items/panes/controllers/impl/CreateItemPaneControllerImpl.java
+++ b/OpERP/src/main/java/devopsdistilled/operp/client/items/panes/controllers/impl/CreateItemPaneControllerImpl.java
@@ -1,68 +1,69 @@
package devopsdistilled.operp.client.items.panes.controllers.impl;
import javax.inject.Inject;
import devopsdistilled.operp.client.items.exceptions.ItemNameExistsException;
import devopsdistilled.operp.client.items.exceptions.NullFieldException;
import devopsdistilled.operp.client.items.exceptions.ProductBrandPairExistsException;
import devopsdistilled.operp.client.items.models.BrandModel;
import devopsdistilled.operp.client.items.models.ItemModel;
import devopsdistilled.operp.client.items.models.ProductModel;
import devopsdistilled.operp.client.items.panes.CreateItemPane;
import devopsdistilled.operp.client.items.panes.controllers.CreateItemPaneController;
import devopsdistilled.operp.client.items.panes.models.CreateItemPaneModel;
import devopsdistilled.operp.server.data.entity.items.Item;
public class CreateItemPaneControllerImpl implements CreateItemPaneController {
@Inject
private CreateItemPaneModel model;
@Inject
private CreateItemPane view;
@Inject
private ItemModel itemModel;
@Inject
private ProductModel productModel;
@Inject
private BrandModel brandModel;
@Override
public void init() {
view.init();
model.registerObserver(view);
productModel.registerObserver(view);
brandModel.registerObserver(view);
}
@Override
public void validate(Item item) throws ProductBrandPairExistsException,
ItemNameExistsException, NullFieldException {
- if (item.getItemName() == null || item.getProduct() == null
- || item.getBrand() == null || item.getPrice() == null) {
+ if (item.getItemName().equalsIgnoreCase("")
+ || item.getProduct() == null || item.getBrand() == null
+ || item.getPrice() == null) {
throw new NullFieldException();
}
if (itemModel.getService().isProductBrandPairExists(item.getProduct(),
item.getBrand())) {
throw new ProductBrandPairExistsException();
}
if (itemModel.getService().isItemNameExists(item.getItemName())) {
throw new ItemNameExistsException();
}
}
@Override
public Item save(Item item) {
Item savedItem = itemModel.saveAndUpdateModel(item);
return savedItem;
}
}
| true | true | public void validate(Item item) throws ProductBrandPairExistsException,
ItemNameExistsException, NullFieldException {
if (item.getItemName() == null || item.getProduct() == null
|| item.getBrand() == null || item.getPrice() == null) {
throw new NullFieldException();
}
if (itemModel.getService().isProductBrandPairExists(item.getProduct(),
item.getBrand())) {
throw new ProductBrandPairExistsException();
}
if (itemModel.getService().isItemNameExists(item.getItemName())) {
throw new ItemNameExistsException();
}
}
| public void validate(Item item) throws ProductBrandPairExistsException,
ItemNameExistsException, NullFieldException {
if (item.getItemName().equalsIgnoreCase("")
|| item.getProduct() == null || item.getBrand() == null
|| item.getPrice() == null) {
throw new NullFieldException();
}
if (itemModel.getService().isProductBrandPairExists(item.getProduct(),
item.getBrand())) {
throw new ProductBrandPairExistsException();
}
if (itemModel.getService().isItemNameExists(item.getItemName())) {
throw new ItemNameExistsException();
}
}
|
diff --git a/src/core/java/org/wyona/yanel/core/source/YanelHtdocsResolver.java b/src/core/java/org/wyona/yanel/core/source/YanelHtdocsResolver.java
index 9e31effa8..1ac210b00 100644
--- a/src/core/java/org/wyona/yanel/core/source/YanelHtdocsResolver.java
+++ b/src/core/java/org/wyona/yanel/core/source/YanelHtdocsResolver.java
@@ -1,78 +1,78 @@
package org.wyona.yanel.core.source;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import org.apache.log4j.Logger;
import org.wyona.yanel.core.Resource;
public class YanelHtdocsResolver implements URIResolver {
private static Logger log = Logger.getLogger(YanelHtdocsResolver.class);
private static final String SCHEME = "yanelhtdocs";
private static final String PATH_PREFIX = "htdocs";
private Resource resource;
public YanelHtdocsResolver(Resource resource) {
this.resource = resource;
}
protected String getScheme() { return SCHEME; }
public Source resolve(String href, String base) throws TransformerException {
String prefix = getScheme() + ":";
// only accept '<scheme>:' URIs
if (href == null || !href.startsWith(prefix)){
return null;
}
// we can't resolve to a Collection (indicated by a trailing '/')
if (href.endsWith("/")){
return null;
}
String path = href.substring(prefix.length());
HttpServletRequest request = resource.getEnvironment().getRequest();
//XXX HACK: we have no other way to have access to this directory from the Yanel environment alone:
String localFilePath = request.getRealPath("/" + PATH_PREFIX + path);
- log.fatal("localFilePath: "+localFilePath);
+ if (log.isDebugEnabled()) log.debug("localFilePath: "+localFilePath);
File resourceFile = new File(localFilePath);
//return new YanelStreamSource(resourceFile);
InputStream in;
try {
in = new java.io.FileInputStream(resourceFile);
} catch (FileNotFoundException e) {
throw new SourceException(e.getMessage(), e);
}
YanelStreamSource source = new YanelStreamSource(in);
long resourceLastModified = resourceFile.lastModified();
source.setLastModified(resourceLastModified);
return source;
/*TODO REMOVEME does not work with HTTPS, credential problems...
StringBuffer sb = request.getRequestURL();
- log.fatal("sb: "+sb);
+ if (log.isDebugEnabled()) log.debug("sb: "+sb);
String globalHtdocsPath = PathUtil.getGlobalHtdocsPath(resource);
- log.fatal("globalHtdocsPath: "+globalHtdocsPath);
+ if (log.isDebugEnabled()) log.debug("globalHtdocsPath: "+globalHtdocsPath);
try {
URL url = new URL(sb.toString() + globalHtdocsPath + path);
if (log.isDebugEnabled()) log.debug("Resolve: " + url.toString());
return new StreamSource(url.openConnection().getInputStream());
} catch (Exception e) {
String errorMsg = "Could not resolve URI: <" + href + ">: " + e.toString();
throw new SourceException(errorMsg, e);
}
*/
/*TODO REMOVEME does not work, the reserved area is indeed not handled by a resource-type!
String reservedPrefix = resource.getYanel().getReservedPrefix();
return resolver.resolve("yanelresource:" + "/" + reservedPrefix + path, base);
*/
}
}
| false | true | public Source resolve(String href, String base) throws TransformerException {
String prefix = getScheme() + ":";
// only accept '<scheme>:' URIs
if (href == null || !href.startsWith(prefix)){
return null;
}
// we can't resolve to a Collection (indicated by a trailing '/')
if (href.endsWith("/")){
return null;
}
String path = href.substring(prefix.length());
HttpServletRequest request = resource.getEnvironment().getRequest();
//XXX HACK: we have no other way to have access to this directory from the Yanel environment alone:
String localFilePath = request.getRealPath("/" + PATH_PREFIX + path);
log.fatal("localFilePath: "+localFilePath);
File resourceFile = new File(localFilePath);
//return new YanelStreamSource(resourceFile);
InputStream in;
try {
in = new java.io.FileInputStream(resourceFile);
} catch (FileNotFoundException e) {
throw new SourceException(e.getMessage(), e);
}
YanelStreamSource source = new YanelStreamSource(in);
long resourceLastModified = resourceFile.lastModified();
source.setLastModified(resourceLastModified);
return source;
/*TODO REMOVEME does not work with HTTPS, credential problems...
StringBuffer sb = request.getRequestURL();
log.fatal("sb: "+sb);
String globalHtdocsPath = PathUtil.getGlobalHtdocsPath(resource);
log.fatal("globalHtdocsPath: "+globalHtdocsPath);
try {
URL url = new URL(sb.toString() + globalHtdocsPath + path);
if (log.isDebugEnabled()) log.debug("Resolve: " + url.toString());
return new StreamSource(url.openConnection().getInputStream());
} catch (Exception e) {
String errorMsg = "Could not resolve URI: <" + href + ">: " + e.toString();
throw new SourceException(errorMsg, e);
}
*/
/*TODO REMOVEME does not work, the reserved area is indeed not handled by a resource-type!
String reservedPrefix = resource.getYanel().getReservedPrefix();
return resolver.resolve("yanelresource:" + "/" + reservedPrefix + path, base);
*/
}
| public Source resolve(String href, String base) throws TransformerException {
String prefix = getScheme() + ":";
// only accept '<scheme>:' URIs
if (href == null || !href.startsWith(prefix)){
return null;
}
// we can't resolve to a Collection (indicated by a trailing '/')
if (href.endsWith("/")){
return null;
}
String path = href.substring(prefix.length());
HttpServletRequest request = resource.getEnvironment().getRequest();
//XXX HACK: we have no other way to have access to this directory from the Yanel environment alone:
String localFilePath = request.getRealPath("/" + PATH_PREFIX + path);
if (log.isDebugEnabled()) log.debug("localFilePath: "+localFilePath);
File resourceFile = new File(localFilePath);
//return new YanelStreamSource(resourceFile);
InputStream in;
try {
in = new java.io.FileInputStream(resourceFile);
} catch (FileNotFoundException e) {
throw new SourceException(e.getMessage(), e);
}
YanelStreamSource source = new YanelStreamSource(in);
long resourceLastModified = resourceFile.lastModified();
source.setLastModified(resourceLastModified);
return source;
/*TODO REMOVEME does not work with HTTPS, credential problems...
StringBuffer sb = request.getRequestURL();
if (log.isDebugEnabled()) log.debug("sb: "+sb);
String globalHtdocsPath = PathUtil.getGlobalHtdocsPath(resource);
if (log.isDebugEnabled()) log.debug("globalHtdocsPath: "+globalHtdocsPath);
try {
URL url = new URL(sb.toString() + globalHtdocsPath + path);
if (log.isDebugEnabled()) log.debug("Resolve: " + url.toString());
return new StreamSource(url.openConnection().getInputStream());
} catch (Exception e) {
String errorMsg = "Could not resolve URI: <" + href + ">: " + e.toString();
throw new SourceException(errorMsg, e);
}
*/
/*TODO REMOVEME does not work, the reserved area is indeed not handled by a resource-type!
String reservedPrefix = resource.getYanel().getReservedPrefix();
return resolver.resolve("yanelresource:" + "/" + reservedPrefix + path, base);
*/
}
|
diff --git a/src/main/java/de/cismet/cismap/navigatorplugin/CismapPlugin.java b/src/main/java/de/cismet/cismap/navigatorplugin/CismapPlugin.java
index 7264b53..c46ba25 100644
--- a/src/main/java/de/cismet/cismap/navigatorplugin/CismapPlugin.java
+++ b/src/main/java/de/cismet/cismap/navigatorplugin/CismapPlugin.java
@@ -1,6577 +1,6573 @@
/***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
/*
* CismapPlugin.java
*
* Created on 14. Februar 2006, 12:34
*/
package de.cismet.cismap.navigatorplugin;
import Sirius.navigator.plugin.context.PluginContext;
import Sirius.navigator.plugin.interfaces.FloatingPluginUI;
import Sirius.navigator.plugin.interfaces.PluginMethod;
import Sirius.navigator.plugin.interfaces.PluginProperties;
import Sirius.navigator.plugin.interfaces.PluginSupport;
import Sirius.navigator.plugin.interfaces.PluginUI;
import Sirius.navigator.plugin.listener.MetaNodeSelectionListener;
import Sirius.navigator.search.CidsSearchExecutor;
import Sirius.navigator.search.dynamic.SearchProgressDialog;
import Sirius.navigator.types.iterator.AttributeRestriction;
import Sirius.navigator.types.iterator.ComplexAttributeRestriction;
import Sirius.navigator.types.iterator.SingleAttributeIterator;
import Sirius.navigator.types.treenode.DefaultMetaTreeNode;
import Sirius.navigator.types.treenode.ObjectTreeNode;
import Sirius.navigator.ui.ComponentRegistry;
import Sirius.server.localserver.attribute.ObjectAttribute;
import Sirius.server.middleware.types.MetaObject;
import Sirius.server.middleware.types.MetaObjectNode;
import Sirius.server.search.builtin.GeoSearch;
import com.jgoodies.looks.HeaderStyle;
import com.jgoodies.looks.Options;
import com.jgoodies.looks.plastic.Plastic3DLookAndFeel;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryCollection;
import com.vividsolutions.jts.geom.GeometryFactory;
import net.infonode.docking.DockingWindow;
import net.infonode.docking.RootWindow;
import net.infonode.docking.SplitWindow;
import net.infonode.docking.TabWindow;
import net.infonode.docking.View;
import net.infonode.docking.mouse.DockingWindowActionMouseButtonListener;
import net.infonode.docking.properties.RootWindowProperties;
import net.infonode.docking.theme.DockingWindowsTheme;
import net.infonode.docking.theme.ShapedGradientDockingTheme;
import net.infonode.docking.util.DockingUtil;
import net.infonode.docking.util.PropertiesUtil;
import net.infonode.docking.util.StringViewMap;
import net.infonode.gui.componentpainter.AlphaGradientComponentPainter;
import net.infonode.util.Direction;
import org.jdom.Element;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Handler;
import org.mortbay.jetty.HttpConnection;
import org.mortbay.jetty.Request;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.AbstractHandler;
import org.mortbay.jetty.handler.HandlerCollection;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
import java.applet.AppletContext;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.KeyStroke;
import javax.swing.RepaintManager;
import javax.swing.SwingWorker;
import javax.swing.ToolTipManager;
import javax.swing.filechooser.FileFilter;
import javax.swing.tree.DefaultMutableTreeNode;
import de.cismet.cids.navigator.utils.CidsBeanDropTarget;
import de.cismet.cismap.commons.BoundingBox;
import de.cismet.cismap.commons.CrsTransformer;
import de.cismet.cismap.commons.RestrictedFileSystemView;
import de.cismet.cismap.commons.debug.DebugPanel;
import de.cismet.cismap.commons.features.DefaultFeatureCollection;
import de.cismet.cismap.commons.features.Feature;
import de.cismet.cismap.commons.features.FeatureCollectionEvent;
import de.cismet.cismap.commons.features.FeatureCollectionListener;
import de.cismet.cismap.commons.features.FeatureGroup;
import de.cismet.cismap.commons.features.FeatureGroups;
import de.cismet.cismap.commons.features.PureNewFeature;
import de.cismet.cismap.commons.features.SearchFeature;
import de.cismet.cismap.commons.gui.ClipboardWaitDialog;
import de.cismet.cismap.commons.gui.MappingComponent;
import de.cismet.cismap.commons.gui.ToolbarComponentDescription;
import de.cismet.cismap.commons.gui.ToolbarComponentsProvider;
import de.cismet.cismap.commons.gui.about.AboutDialog;
import de.cismet.cismap.commons.gui.capabilitywidget.CapabilityWidget;
import de.cismet.cismap.commons.gui.featurecontrolwidget.FeatureControl;
import de.cismet.cismap.commons.gui.featureinfowidget.FeatureInfoWidget;
import de.cismet.cismap.commons.gui.infowidgets.LayerInfo;
import de.cismet.cismap.commons.gui.infowidgets.Legend;
import de.cismet.cismap.commons.gui.infowidgets.ServerInfo;
import de.cismet.cismap.commons.gui.layerwidget.ActiveLayerModel;
import de.cismet.cismap.commons.gui.layerwidget.LayerWidget;
import de.cismet.cismap.commons.gui.overviewwidget.OverviewComponent;
import de.cismet.cismap.commons.gui.piccolo.PFeature;
import de.cismet.cismap.commons.gui.piccolo.eventlistener.CreateGeometryListenerInterface;
import de.cismet.cismap.commons.gui.piccolo.eventlistener.CreateNewGeometryListener;
import de.cismet.cismap.commons.gui.piccolo.eventlistener.MetaSearchCreateSearchGeometryListener;
import de.cismet.cismap.commons.gui.piccolo.eventlistener.actions.CustomAction;
import de.cismet.cismap.commons.gui.printing.Scale;
import de.cismet.cismap.commons.gui.shapeexport.ShapeExport;
import de.cismet.cismap.commons.gui.statusbar.StatusBar;
import de.cismet.cismap.commons.interaction.CismapBroker;
import de.cismet.cismap.commons.interaction.MapDnDListener;
import de.cismet.cismap.commons.interaction.MapSearchListener;
import de.cismet.cismap.commons.interaction.StatusListener;
import de.cismet.cismap.commons.interaction.events.MapDnDEvent;
import de.cismet.cismap.commons.interaction.events.MapSearchEvent;
import de.cismet.cismap.commons.interaction.events.StatusEvent;
import de.cismet.cismap.commons.interaction.memento.MementoInterface;
import de.cismet.cismap.commons.util.DnDUtils;
import de.cismet.cismap.commons.wfsforms.AbstractWFSForm;
import de.cismet.cismap.commons.wfsforms.WFSFormFactory;
import de.cismet.cismap.navigatorplugin.metasearch.MetaSearch;
import de.cismet.cismap.navigatorplugin.metasearch.SearchTopic;
import de.cismet.cismap.tools.gui.CidsBeanDropJPopupMenuButton;
import de.cismet.lookupoptions.gui.OptionsClient;
import de.cismet.lookupoptions.gui.OptionsDialog;
import de.cismet.tools.CismetThreadPool;
import de.cismet.tools.CurrentStackTrace;
import de.cismet.tools.StaticDebuggingTools;
import de.cismet.tools.StaticDecimalTools;
import de.cismet.tools.configuration.Configurable;
import de.cismet.tools.configuration.ConfigurationManager;
import de.cismet.tools.groovysupport.GroovierConsole;
import de.cismet.tools.gui.BasicGuiComponentProvider;
import de.cismet.tools.gui.CheckThreadViolationRepaintManager;
import de.cismet.tools.gui.CustomButtonProvider;
import de.cismet.tools.gui.EventDispatchThreadHangMonitor;
import de.cismet.tools.gui.HighlightingRadioButtonMenuItem;
import de.cismet.tools.gui.JPopupMenuButton;
import de.cismet.tools.gui.Static2DTools;
import de.cismet.tools.gui.StaticSwingTools;
import de.cismet.tools.gui.StayOpenCheckBoxMenuItem;
import de.cismet.tools.gui.downloadmanager.DownloadManagerAction;
import de.cismet.tools.gui.historybutton.HistoryModelListener;
import de.cismet.tools.gui.historybutton.JHistoryButton;
import de.cismet.tools.gui.log4jquickconfig.Log4JQuickConfig;
/**
* DOCUMENT ME!
*
* @author [email protected]
* @version $Revision$, $Date$
*/
public class CismapPlugin extends javax.swing.JFrame implements PluginSupport,
Observer,
FloatingPluginUI,
Configurable,
MapSearchListener,
MapDnDListener,
StatusListener,
HistoryModelListener,
FeatureCollectionListener,
PropertyChangeListener {
//~ Enums ------------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
public static enum ViewSection {
//~ Enum constants -----------------------------------------------------
MAP, WFS, LAYER, LAYER_INFO, CAPABILITIES
}
//~ Instance fields --------------------------------------------------------
int httpInterfacePort = 9098;
boolean nodeSelectionEventBlocker = false;
boolean featureCollectionEventBlocker = false;
DataFlavor fromCapabilityWidget = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType, "SelectionAndCapabilities"); // NOI18N
DataFlavor fromNavigatorNode = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + ";class=" // NOI18N
+ DefaultMetaTreeNode.class.getName(),
"a DefaultMetaTreeNode"); // NOI18N
DataFlavor fromNavigatorCollection = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + ";class=" // NOI18N
+ java.util.Collection.class.getName(),
"a java.util.Collection of Sirius.navigator.types.treenode.DefaultMetaTreeNode objects"); // NOI18N
BoundingBox buffer;
private final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(this.getClass());
private MappingComponent mapC;
private LayerWidget activeLayers;
private CapabilityWidget capabilities;
private StatusBar statusBar;
private MetaSearch metaSearch;
private Legend legend;
private JScrollPane scroller;
private ServerInfo serverInfo;
private LayerInfo layerInfo;
private FeatureInfoWidget featureInfo;
private FeatureControl featureControl;
private DebugPanel debugPanel;
private GroovierConsole groovyConsole;
private ShapeExport shapeExport;
private View vLayers;
private View vCaps;
private View vServerInfo;
private View vLayerInfo;
private View vMap;
private View vLegend;
private View vFeatureInfo;
private View vFeatureControl;
private View vOverview;
private RootWindow rootWindow;
private final StringViewMap viewMap = new StringViewMap();
private final Map<String, JMenuItem> viewMenuMap = new HashMap<String, JMenuItem>();
private final ConfigurationManager configurationManager = new ConfigurationManager();
private ShowObjectsMethod showObjectsMethod = new ShowObjectsMethod();
private final Map<String, PluginMethod> pluginMethods = new HashMap<String, PluginMethod>();
private final MyPluginProperties myPluginProperties = new MyPluginProperties();
private final List<JMenuItem> menues = new ArrayList<JMenuItem>();
private final Map<DefaultMetaTreeNode, CidsFeature> featuresInMap = new HashMap<DefaultMetaTreeNode, CidsFeature>();
private final Map<Feature, DefaultMetaTreeNode> featuresInMapReverse = new HashMap<Feature, DefaultMetaTreeNode>();
private String newGeometryMode = CreateGeometryListenerInterface.LINESTRING;
private WFSFormFactory wfsFormFactory;
private final Set<View> wfsFormViews = new HashSet<View>();
private final List<View> wfs = new ArrayList<View>();
private DockingWindow[] wfsViews;
private DockingWindow[] legendTab = new DockingWindow[3];
private ClipboardWaitDialog clipboarder;
private PluginContext context;
private boolean plugin = false;
private String home = System.getProperty("user.home"); // NOI18N
private String fs = System.getProperty("file.separator"); // NOI18N
private String standaloneLayoutName = "cismap.layout"; // NOI18N
private String pluginLayoutName = "plugin.layout"; // NOI18N
private ShowObjectsWaitDialog showObjectsWaitDialog;
private String cismapDirectory = home + fs + ".cismap"; // NOI18N
private javax.swing.ImageIcon miniBack = new javax.swing.ImageIcon(getClass().getResource("/images/miniBack.png")); // NOI18N
private javax.swing.ImageIcon miniForward = new javax.swing.ImageIcon(getClass().getResource(
"/images/miniForward.png")); // NOI18N
private javax.swing.ImageIcon current = new javax.swing.ImageIcon(getClass().getResource("/images/current.png")); // NOI18N
private javax.swing.ImageIcon logo = new javax.swing.ImageIcon(getClass().getResource("/images/cismetlogo16.png")); // NOI18N
private AppletContext appletContext;
private boolean isInit = true;
private String helpUrl;
private String newsUrl;
private AboutDialog about;
private OverviewComponent overviewComponent = null;
private Dimension oldWindowDimension = new Dimension(-1, -1);
private int oldWindowPositionX = -1;
private int oldWindowPositionY = -1;
private String dirExtension = ""; // NOI18N
private Element cismapPluginUIPreferences;
private List<String> windows2skip;
private SearchProgressDialog searchProgressDialog;
private final transient Map<BasicGuiComponentProvider, DockingWindow> extensionWindows;
private Action searchMenuSelectedAction = new AbstractAction() {
@Override
public void actionPerformed(final ActionEvent e) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
if (log.isDebugEnabled()) {
log.debug("searchMenuSelectedAction"); // NOI18N
}
final MetaSearchCreateSearchGeometryListener searchListener =
(MetaSearchCreateSearchGeometryListener)mapC.getInputListener(
MappingComponent.CREATE_SEARCH_POLYGON);
final PureNewFeature lastGeometry = searchListener.getLastSearchFeature();
if (lastGeometry == null) {
mniSearchShowLastFeature.setIcon(null);
mniSearchShowLastFeature.setEnabled(false);
mniSearchRedo.setIcon(null);
mniSearchRedo.setEnabled(false);
mniSearchBuffer.setEnabled(false);
} else {
switch (lastGeometry.getGeometryType()) {
case ELLIPSE: {
mniSearchRedo.setIcon(mniSearchEllipse.getIcon());
break;
}
case LINESTRING: {
mniSearchRedo.setIcon(mniSearchPolyline.getIcon());
break;
}
case POLYGON: {
mniSearchRedo.setIcon(mniSearchPolygon.getIcon());
break;
}
case RECTANGLE: {
mniSearchRedo.setIcon(mniSearchRectangle.getIcon());
break;
}
}
mniSearchShowLastFeature.setIcon(mniSearchRedo.getIcon());
mniSearchRedo.setEnabled(true);
mniSearchBuffer.setEnabled(true);
mniSearchShowLastFeature.setEnabled(true);
}
// kopieren nach popupmenu im grünen M
mniSearchRectangle1.setSelected(mniSearchRectangle.isSelected());
mniSearchPolygon1.setSelected(mniSearchPolygon.isSelected());
mniSearchEllipse1.setSelected(mniSearchEllipse.isSelected());
mniSearchPolyline1.setSelected(mniSearchPolyline.isSelected());
mniSearchRedo1.setIcon(mniSearchRedo.getIcon());
mniSearchRedo1.setEnabled(mniSearchRedo.isEnabled());
mniSearchBuffer1.setEnabled(mniSearchBuffer.isEnabled());
mniSearchShowLastFeature1.setIcon(mniSearchShowLastFeature.getIcon());
mniSearchShowLastFeature1.setEnabled(mniSearchShowLastFeature.isEnabled());
}
});
}
};
private Action searchAction = new AbstractAction() {
@Override
public void actionPerformed(final ActionEvent e) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
if (log.isDebugEnabled()) {
log.debug("searchAction"); // NOI18N
}
cmdPluginSearch.setSelected(true);
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
mapC.setInteractionMode(MappingComponent.CREATE_SEARCH_POLYGON);
if (mniSearchRectangle.isSelected()) {
((MetaSearchCreateSearchGeometryListener)mapC.getInputListener(
MappingComponent.CREATE_SEARCH_POLYGON)).setMode(
MetaSearchCreateSearchGeometryListener.RECTANGLE);
} else if (mniSearchPolygon.isSelected()) {
((MetaSearchCreateSearchGeometryListener)mapC.getInputListener(
MappingComponent.CREATE_SEARCH_POLYGON)).setMode(
MetaSearchCreateSearchGeometryListener.POLYGON);
} else if (mniSearchEllipse.isSelected()) {
((MetaSearchCreateSearchGeometryListener)mapC.getInputListener(
MappingComponent.CREATE_SEARCH_POLYGON)).setMode(
MetaSearchCreateSearchGeometryListener.ELLIPSE);
} else if (mniSearchPolyline.isSelected()) {
((MetaSearchCreateSearchGeometryListener)mapC.getInputListener(
MappingComponent.CREATE_SEARCH_POLYGON)).setMode(
MetaSearchCreateSearchGeometryListener.LINESTRING);
}
}
});
}
});
}
};
private Action searchRectangleAction = new AbstractAction() {
@Override
public void actionPerformed(final ActionEvent e) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
if (log.isDebugEnabled()) {
log.debug("searchRectangleAction"); // NOI18N
}
cmdPluginSearch.setSelected(true);
mniSearchRectangle.setSelected(true);
cmdPluginSearch.setIcon(
new javax.swing.ImageIcon(getClass().getResource("/images/pluginSearchRectangle.png"))); // NOI18N
cmdPluginSearch.setSelectedIcon(
new javax.swing.ImageIcon(getClass().getResource("/images/pluginSearchRectangle.png"))); // NOI18N
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
mapC.setInteractionMode(MappingComponent.CREATE_SEARCH_POLYGON);
((MetaSearchCreateSearchGeometryListener)mapC.getInputListener(
MappingComponent.CREATE_SEARCH_POLYGON)).setMode(
MetaSearchCreateSearchGeometryListener.RECTANGLE);
}
});
}
});
}
};
private Action searchPolygonAction = new AbstractAction() {
@Override
public void actionPerformed(final ActionEvent e) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
if (log.isDebugEnabled()) {
log.debug("searchPolygonAction"); // NOI18N
}
cmdPluginSearch.setSelected(true);
mniSearchPolygon.setSelected(true);
cmdPluginSearch.setIcon(
new javax.swing.ImageIcon(getClass().getResource("/images/pluginSearchPolygon.png"))); // NOI18N
cmdPluginSearch.setSelectedIcon(
new javax.swing.ImageIcon(getClass().getResource("/images/pluginSearchPolygon.png"))); // NOI18N
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
mapC.setInteractionMode(MappingComponent.CREATE_SEARCH_POLYGON);
((MetaSearchCreateSearchGeometryListener)mapC.getInputListener(
MappingComponent.CREATE_SEARCH_POLYGON)).setMode(
MetaSearchCreateSearchGeometryListener.POLYGON);
}
});
}
});
}
};
private Action searchCidsFeatureAction = new AbstractAction() {
@Override
public void actionPerformed(final ActionEvent e) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
if (log.isDebugEnabled()) {
log.debug("searchCidsFeatureAction"); // NOI18N
}
cmdPluginSearch.setSelected(true);
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
mapC.setInteractionMode(MappingComponent.CREATE_SEARCH_POLYGON);
final MetaSearchCreateSearchGeometryListener searchListener =
((MetaSearchCreateSearchGeometryListener)mapC.getInputListener(
MappingComponent.CREATE_SEARCH_POLYGON));
de.cismet.tools.CismetThreadPool.execute(
new javax.swing.SwingWorker<SearchFeature, Void>() {
@Override
protected SearchFeature doInBackground() throws Exception {
final DefaultMetaTreeNode[] nodes = ComponentRegistry.getRegistry()
.getActiveCatalogue()
.getSelectedNodesArray();
final Collection<Geometry> searchGeoms = new ArrayList<Geometry>();
for (final DefaultMetaTreeNode dmtn : nodes) {
if (dmtn instanceof ObjectTreeNode) {
final MetaObject mo = ((ObjectTreeNode)dmtn)
.getMetaObject();
final CidsFeature cf = new CidsFeature(mo);
searchGeoms.add(cf.getGeometry());
}
}
final Geometry[] searchGeomsArr = searchGeoms.toArray(
new Geometry[0]);
final GeometryCollection coll =
new GeometryFactory().createGeometryCollection(searchGeomsArr);
final Geometry newG = coll.buffer(0.1d);
if (log.isDebugEnabled()) {
log.debug("SearchGeom " + newG.toText()); // NOI18N
}
final SearchFeature sf = new SearchFeature(newG);
sf.setGeometryType(PureNewFeature.geomTypes.MULTIPOLYGON);
return sf;
}
@Override
protected void done() {
try {
final SearchFeature search = get();
if (search != null) {
searchListener.search(search);
}
} catch (final Exception e) {
log.error("Exception in Background Thread", e); // NOI18N
}
}
});
}
});
}
});
}
};
private Action searchEllipseAction = new AbstractAction() {
@Override
public void actionPerformed(final ActionEvent e) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
if (log.isDebugEnabled()) {
log.debug("searchEllipseAction"); // NOI18N
}
cmdPluginSearch.setSelected(true);
mniSearchEllipse.setSelected(true);
cmdPluginSearch.setIcon(
new javax.swing.ImageIcon(getClass().getResource("/images/pluginSearchEllipse.png"))); // NOI18N
cmdPluginSearch.setSelectedIcon(
new javax.swing.ImageIcon(getClass().getResource("/images/pluginSearchEllipse.png"))); // NOI18N
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
mapC.setInteractionMode(MappingComponent.CREATE_SEARCH_POLYGON);
((MetaSearchCreateSearchGeometryListener)mapC.getInputListener(
MappingComponent.CREATE_SEARCH_POLYGON)).setMode(
MetaSearchCreateSearchGeometryListener.ELLIPSE);
}
});
}
});
}
};
private Action searchPolylineAction = new AbstractAction() {
@Override
public void actionPerformed(final ActionEvent e) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
if (log.isDebugEnabled()) {
log.debug("searchPolylineAction"); // NOI18N
}
cmdPluginSearch.setSelected(true);
mniSearchPolyline.setSelected(true);
cmdPluginSearch.setIcon(
new javax.swing.ImageIcon(getClass().getResource("/images/pluginSearchPolyline.png"))); // NOI18N
cmdPluginSearch.setSelectedIcon(
new javax.swing.ImageIcon(getClass().getResource("/images/pluginSearchPolyline.png"))); // NOI18N
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
mapC.setInteractionMode(MappingComponent.CREATE_SEARCH_POLYGON);
((MetaSearchCreateSearchGeometryListener)mapC.getInputListener(
MappingComponent.CREATE_SEARCH_POLYGON)).setMode(
MetaSearchCreateSearchGeometryListener.LINESTRING);
}
});
}
});
}
};
private Action searchRedoAction = new AbstractAction() {
@Override
public void actionPerformed(final ActionEvent e) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
if (log.isDebugEnabled()) {
log.debug("redoSearchAction"); // NOI18N
}
final MetaSearchCreateSearchGeometryListener searchListener =
(MetaSearchCreateSearchGeometryListener)mapC.getInputListener(
MappingComponent.CREATE_SEARCH_POLYGON);
searchListener.redoLastSearch();
mapC.setInteractionMode(MappingComponent.CREATE_SEARCH_POLYGON);
}
});
}
};
private Action searchShowLastFeatureAction = new AbstractAction() {
@Override
public void actionPerformed(final ActionEvent e) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
if (log.isDebugEnabled()) {
log.debug("searchShowLastFeatureAction"); // NOI18N
}
final MetaSearchCreateSearchGeometryListener searchListener =
(MetaSearchCreateSearchGeometryListener)mapC.getInputListener(
MappingComponent.CREATE_SEARCH_POLYGON);
searchListener.showLastFeature();
mapC.setInteractionMode(MappingComponent.CREATE_SEARCH_POLYGON);
}
});
}
};
private Action searchBufferAction = new AbstractAction() {
@Override
public void actionPerformed(final ActionEvent e) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
if (log.isDebugEnabled()) {
log.debug("bufferSearchGeometry"); // NOI18N
}
cmdPluginSearch.setSelected(true);
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
final String s = (String)JOptionPane.showInputDialog(
null,
"Geben Sie den Abstand des zu erzeugenden\n" // NOI18N
+ "Puffers der letzten Suchgeometrie an.", // NOI18N
"Puffer", // NOI18N
JOptionPane.PLAIN_MESSAGE,
null,
null,
""); // NOI18N
if (log.isDebugEnabled()) {
log.debug(s);
}
// , statt . ebenfalls erlauben
if (s.matches("\\d*,\\d*")) { // NOI18N
s.replace(",", "."); // NOI18N
}
try {
final float buffer = Float.valueOf(s);
final MetaSearchCreateSearchGeometryListener searchListener =
(MetaSearchCreateSearchGeometryListener)mapC.getInputListener(
MappingComponent.CREATE_SEARCH_POLYGON);
final PureNewFeature lastFeature = searchListener.getLastSearchFeature();
if (lastFeature != null) {
// Geometrie-Daten holen
final Geometry geom = lastFeature.getGeometry();
// Puffer-Geometrie holen
final Geometry bufferGeom = geom.buffer(buffer);
// und setzen
lastFeature.setGeometry(bufferGeom);
// Geometrie ist jetzt eine Polygon (keine Linie, Ellipse, oder
// ähnliches mehr)
lastFeature.setGeometryType(PureNewFeature.geomTypes.POLYGON);
for (final Object feature
: mapC.getFeatureCollection().getAllFeatures()) {
final PFeature sel = (PFeature)mapC.getPFeatureHM().get(feature);
if (sel.getFeature().equals(lastFeature)) {
// Koordinaten der Puffer-Geometrie als Feature-Koordinaten
// setzen
sel.setCoordArr(bufferGeom.getCoordinates());
// refresh
sel.syncGeometry();
final List v = new ArrayList();
v.add(sel.getFeature());
((DefaultFeatureCollection)mapC.getFeatureCollection())
.fireFeaturesChanged(v);
}
}
searchListener.search(lastFeature);
mapC.setInteractionMode(MappingComponent.CREATE_SEARCH_POLYGON);
}
} catch (final NumberFormatException ex) {
JOptionPane.showMessageDialog(
null,
"The given value was not a floating point value.!",
"Error",
JOptionPane.ERROR_MESSAGE); // NOI18N
} catch (final Exception ex) {
if (log.isDebugEnabled()) {
log.debug("", ex); // NOI18N
}
}
}
});
}
});
}
};
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton cmdBack;
private javax.swing.JButton cmdClipboard;
private javax.swing.JButton cmdDownloads;
private javax.swing.JToggleButton cmdFeatureInfo;
private javax.swing.JButton cmdForward;
private javax.swing.ButtonGroup cmdGroupNodes;
private javax.swing.ButtonGroup cmdGroupPrimaryInteractionMode;
private javax.swing.ButtonGroup cmdGroupSearch;
private javax.swing.ButtonGroup cmdGroupSearch1;
private javax.swing.JButton cmdHome;
private javax.swing.JToggleButton cmdMoveGeometry;
private javax.swing.JToggleButton cmdNewLinearReferencing;
private javax.swing.JToggleButton cmdNewLinestring;
private javax.swing.JToggleButton cmdNewPoint;
private javax.swing.JToggleButton cmdNewPolygon;
private javax.swing.JToggleButton cmdNodeAdd;
private javax.swing.JToggleButton cmdNodeMove;
private javax.swing.JToggleButton cmdNodeRemove;
private javax.swing.JToggleButton cmdNodeRotateGeometry;
private javax.swing.JToggleButton cmdPan;
private javax.swing.JButton cmdPluginSearch;
private javax.swing.JButton cmdPrint;
private javax.swing.JButton cmdReconfig;
private javax.swing.JButton cmdRedo;
private javax.swing.JButton cmdRefresh;
private javax.swing.JToggleButton cmdRemoveGeometry;
private javax.swing.JToggleButton cmdSelect;
private javax.swing.JToggleButton cmdSnap;
private javax.swing.JButton cmdUndo;
private javax.swing.JToggleButton cmdZoom;
private javax.swing.JPopupMenu jPopupMenu1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator10;
private javax.swing.JSeparator jSeparator11;
private javax.swing.JSeparator jSeparator12;
private javax.swing.JSeparator jSeparator13;
private javax.swing.JSeparator jSeparator14;
private javax.swing.JSeparator jSeparator15;
private javax.swing.JSeparator jSeparator16;
private javax.swing.JPopupMenu.Separator jSeparator17;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JSeparator jSeparator4;
private javax.swing.JSeparator jSeparator5;
private javax.swing.JSeparator jSeparator6;
private javax.swing.JSeparator jSeparator8;
private javax.swing.JSeparator jSeparator9;
private javax.swing.JMenu menBookmarks;
private javax.swing.JMenu menEdit;
private javax.swing.JMenu menExtras;
private javax.swing.JMenu menFile;
private javax.swing.JMenu menHelp;
private javax.swing.JMenu menHistory;
private javax.swing.JMenu menSearch;
private javax.swing.JMenu menWindows;
private javax.swing.JMenuItem mniAbout;
private javax.swing.JMenuItem mniAddBookmark;
private javax.swing.JMenuItem mniBack;
private javax.swing.JMenuItem mniBookmarkManager;
private javax.swing.JMenuItem mniBookmarkSidebar;
private javax.swing.JMenuItem mniBufferSelectedGeom;
private javax.swing.JMenuItem mniCapabilities;
private javax.swing.JMenuItem mniClipboard;
private javax.swing.JMenuItem mniClose;
private javax.swing.JMenuItem mniFeatureControl;
private javax.swing.JMenuItem mniFeatureInfo;
private javax.swing.JMenuItem mniForward;
private javax.swing.JMenuItem mniGeoLinkClipboard;
private javax.swing.JMenuItem mniGotoPoint;
private javax.swing.JMenuItem mniHistorySidebar;
private javax.swing.JMenuItem mniHome;
private javax.swing.JMenuItem mniLayer;
private javax.swing.JMenuItem mniLayerInfo;
private javax.swing.JMenuItem mniLegend;
private javax.swing.JMenuItem mniLoadConfig;
private javax.swing.JMenuItem mniLoadConfigFromServer;
private javax.swing.JMenuItem mniLoadLayout;
private javax.swing.JMenuItem mniMap;
private javax.swing.JMenuItem mniNews;
private javax.swing.JMenuItem mniOnlineHelp;
private javax.swing.JMenuItem mniOptions;
private javax.swing.JMenuItem mniOverview;
private javax.swing.JMenuItem mniPrint;
private javax.swing.JMenuItem mniRefresh;
private javax.swing.JMenuItem mniRemoveAllObjects;
private javax.swing.JMenuItem mniRemoveSelectedObject;
private javax.swing.JMenuItem mniResetWindowLayout;
private javax.swing.JMenuItem mniSaveConfig;
private javax.swing.JMenuItem mniSaveLayout;
private javax.swing.JMenuItem mniScale;
private javax.swing.JMenuItem mniSearchBuffer;
private javax.swing.JMenuItem mniSearchBuffer1;
private javax.swing.JRadioButtonMenuItem mniSearchCidsFeature;
private javax.swing.JRadioButtonMenuItem mniSearchCidsFeature1;
private javax.swing.JRadioButtonMenuItem mniSearchEllipse;
private javax.swing.JRadioButtonMenuItem mniSearchEllipse1;
private javax.swing.JRadioButtonMenuItem mniSearchPolygon;
private javax.swing.JRadioButtonMenuItem mniSearchPolygon1;
private javax.swing.JRadioButtonMenuItem mniSearchPolyline;
private javax.swing.JRadioButtonMenuItem mniSearchPolyline1;
private javax.swing.JRadioButtonMenuItem mniSearchRectangle;
private javax.swing.JRadioButtonMenuItem mniSearchRectangle1;
private javax.swing.JMenuItem mniSearchRedo;
private javax.swing.JMenuItem mniSearchRedo1;
private javax.swing.JMenuItem mniSearchShowLastFeature;
private javax.swing.JMenuItem mniSearchShowLastFeature1;
private javax.swing.JMenuItem mniServerInfo;
private javax.swing.JMenuItem mniZoomToAllObjects;
private javax.swing.JMenuItem mniZoomToSelectedObjects;
private javax.swing.JMenuBar mnuBar;
private javax.swing.JMenuItem mnuConfigServer;
private javax.swing.JPanel panAll;
private javax.swing.JPanel panMain;
private javax.swing.JPanel panSearchSelection;
private javax.swing.JPanel panStatus;
private javax.swing.JPanel panToolbar;
private javax.swing.JPopupMenu popMen;
private javax.swing.JPopupMenu popMenSearch;
private javax.swing.JSeparator sepAfterPos;
private javax.swing.JSeparator sepBeforePos;
private javax.swing.JSeparator sepResetWindowLayout;
private javax.swing.JSeparator sepServerProfilesEnd;
private javax.swing.JSeparator sepServerProfilesStart;
private javax.swing.JToolBar tlbMain;
private javax.swing.JToggleButton togInvisible;
// End of variables declaration//GEN-END:variables
//~ Constructors -----------------------------------------------------------
/**
* Creates a new CismapPlugin object.
*/
public CismapPlugin() {
this(null);
}
/**
* Creates a new CismapPlugin object.
*
* @param context DOCUMENT ME!
*/
public CismapPlugin(final PluginContext context) {
this.extensionWindows = new HashMap<BasicGuiComponentProvider, DockingWindow>(1);
if (StaticDebuggingTools.checkHomeForFile("cismetCheckForEDThreadVialoation")) { // NOI18N
RepaintManager.setCurrentManager(new CheckThreadViolationRepaintManager());
}
try {
final String l = System.getProperty("user.language"); // NOI18N
final String c = System.getProperty("user.country"); // NOI18N
System.out.println("Locale=" + l + "_" + c); // NOI18N
Locale.setDefault(new Locale(l, c));
} catch (Exception e) {
log.warn("Error while changing the user language and country"); // NOI18N
}
try {
final String ext = System.getProperty("directory.extension"); // NOI18N
System.out.println("SystemdirExtension=:" + ext); // NOI18N
if (ext != null) {
dirExtension = ext;
cismapDirectory += ext;
}
} catch (final Exception e) {
log.warn("Error while adding DirectoryExtension"); // NOI18N
}
CismapBroker.getInstance().setCismapFolderPath(cismapDirectory);
this.setIconImage(logo.getImage());
System.setSecurityManager(null);
this.context = context;
plugin = (context != null);
try {
if (plugin && (context.getEnvironment() != null) && this.context.getEnvironment().isProgressObservable()) {
this.context.getEnvironment()
.getProgressObserver()
.setProgress(
0,
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.CismapPlugin(PluginContext).initializingCismapPlugin")); // NOI18N
}
if (!plugin) {
try {
org.apache.log4j.PropertyConfigurator.configure(getClass().getResource("/cismap.log4j.properties")); // NOI18N
if (StaticDebuggingTools.checkHomeForFile("cismetDebuggingInitEventDispatchThreadHangMonitor")) { // NOI18N
EventDispatchThreadHangMonitor.initMonitoring();
}
if (StaticDebuggingTools.checkHomeForFile("cismetCheckForEDThreadVialoation")) { // NOI18N
RepaintManager.setCurrentManager(new CheckThreadViolationRepaintManager());
}
} catch (Exception e) {
System.err.println("LOG4J is not configured propperly\n\n"); // NOI18N
e.printStackTrace();
}
}
try {
javax.swing.UIManager.setLookAndFeel(new Plastic3DLookAndFeel());
} catch (final Exception e) {
log.warn("Error while creating Look&Feel!", e); // NOI18N
}
clipboarder = new ClipboardWaitDialog(this, true);
showObjectsWaitDialog = new ShowObjectsWaitDialog(this, false);
if (plugin && (context.getEnvironment() != null) && this.context.getEnvironment().isProgressObservable()) {
this.context.getEnvironment()
.getProgressObserver()
.setProgress(
100,
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.CismapPlugin(PluginContext).createWidgets")); // NOI18N
}
// Erzeugen der Widgets
serverInfo = new ServerInfo();
layerInfo = new LayerInfo();
mapC = new MappingComponent(true);
CismapBroker.getInstance().addCrsChangeListener(mapC);
mapC.addHistoryModelListener(this);
activeLayers = new LayerWidget(mapC);
activeLayers.setPreferredSize(new Dimension(100, 120));
legend = new Legend();
metaSearch = MetaSearch.instance();
statusBar = new StatusBar(mapC);
featureInfo = new FeatureInfoWidget();
capabilities = new CapabilityWidget();
featureControl = new FeatureControl(mapC);
debugPanel = new DebugPanel();
debugPanel.setPCanvas(mapC);
groovyConsole = new GroovierConsole();
groovyConsole.setVariable("map", mapC); // NOI18N
shapeExport = new ShapeExport();
wfsFormFactory = WFSFormFactory.getInstance(mapC);
overviewComponent = new OverviewComponent();
overviewComponent.setMasterMap(mapC);
if (plugin && (context.getEnvironment() != null) && this.context.getEnvironment().isProgressObservable()) {
this.context.getEnvironment()
.getProgressObserver()
.setProgress(
200,
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.CismapPlugin(PluginContext).initializingGUI")); // NOI18N
}
if (plugin) {
final MetaSearchCreateSearchGeometryListener listener = new MetaSearchCreateSearchGeometryListener(
mapC,
metaSearch);
mapC.addInputListener(MappingComponent.CREATE_SEARCH_POLYGON, listener);
mapC.addPropertyChangeListener(listener);
listener.addPropertyChangeListener(this);
}
CismapBroker.getInstance().setMetaSearch(metaSearch);
try {
initComponents();
((CidsBeanDropJPopupMenuButton)cmdPluginSearch).setTargetIcon(new javax.swing.ImageIcon(
getClass().getResource("/images/pluginSearchTarget.png"))); // NOI18N
} catch (final Exception e) {
log.fatal("Error in initComponents.", e); // NOI18N
}
new CidsBeanDropTarget(cmdPluginSearch);
mapC.setInteractionButtonGroup(cmdGroupPrimaryInteractionMode);
if (!plugin) {
menSearch.setVisible(false);
cmdPluginSearch.setVisible(false);
final KeyStroke configLoggerKeyStroke = KeyStroke.getKeyStroke(
'L',
InputEvent.CTRL_MASK
+ InputEvent.SHIFT_MASK);
final Action configAction = new AbstractAction() {
@Override
public void actionPerformed(final ActionEvent e) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
Log4JQuickConfig.getSingletonInstance().setVisible(true);
}
});
}
};
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(configLoggerKeyStroke,
"CONFIGLOGGING"); // NOI18N
getRootPane().getActionMap().put("CONFIGLOGGING", configAction); // NOI18N
}
if (plugin) {
visualizeSearchMode();
menExtras.remove(mniOptions);
menExtras.remove(jSeparator16);
}
// Menu
menues.add(menFile);
menues.add(menEdit);
menues.add(menHistory);
menues.add(menSearch);
menues.add(menBookmarks);
menues.add(menExtras);
menues.add(menWindows);
menues.add(menHelp);
panStatus.add(statusBar, BorderLayout.CENTER);
tlbMain.putClientProperty("JToolBar.isRollover", Boolean.TRUE); // NOI18N
tlbMain.putClientProperty(Options.HEADER_STYLE_KEY, HeaderStyle.BOTH);
tlbMain.putClientProperty(Options.HEADER_STYLE_KEY, HeaderStyle.BOTH);
if (plugin) {
tlbMain.remove(cmdDownloads);
}
if (plugin && (context.getEnvironment() != null) && this.context.getEnvironment().isProgressObservable()) {
this.context.getEnvironment()
.getProgressObserver()
.setProgress(
300,
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.CismapPlugin(PluginContext).connectingWidgets")); // NOI18N
}
// Wire the components
// add Listeners
((JHistoryButton)cmdForward).setDirection(JHistoryButton.DIRECTION_FORWARD);
((JHistoryButton)cmdBack).setDirection(JHistoryButton.DIRECTION_BACKWARD);
((JHistoryButton)cmdForward).setHistoryModel(mapC);
((JHistoryButton)cmdBack).setHistoryModel(mapC);
CismapBroker.getInstance().addCapabilityListener(serverInfo);
CismapBroker.getInstance().addCapabilityListener(layerInfo);
CismapBroker.getInstance().addActiveLayerListener(serverInfo);
CismapBroker.getInstance().addActiveLayerListener(layerInfo);
CismapBroker.getInstance().addActiveLayerListener(legend);
CismapBroker.getInstance().addActiveLayerListener(featureInfo);
CismapBroker.getInstance().addActiveLayerListener(statusBar);
CismapBroker.getInstance().addStatusListener(statusBar);
if (legend instanceof StatusListener) {
CismapBroker.getInstance().addStatusListener(legend);
}
CismapBroker.getInstance().addMapClickListener(featureInfo);
CismapBroker.getInstance().addMapSearchListener(this);
CismapBroker.getInstance().addMapDnDListener(this);
CismapBroker.getInstance().addStatusListener(this);
mapC.getFeatureCollection().addFeatureCollectionListener(featureControl);
mapC.getFeatureCollection().addFeatureCollectionListener(statusBar);
CismapBroker.getInstance().addMapBoundsListener(featureControl);
CismapBroker.getInstance().addMapBoundsListener(capabilities);
// set the components in the broker
CismapBroker.getInstance().setMappingComponent(mapC);
String cismapconfig = null;
String fallBackConfig = null;
try {
final String prefix = "cismapconfig:"; // NOI18N
final String username = Sirius.navigator.connection.SessionManager.getSession().getUser().getName();
final String groupname = Sirius.navigator.connection.SessionManager.getSession()
.getUser()
.getUserGroup()
.getName();
final String domainname = Sirius.navigator.connection.SessionManager.getSession()
.getUser()
.getUserGroup()
.getDomain();
// First try: cismapconfig:username@usergroup@domainserver
if (cismapconfig == null) {
cismapconfig = context.getEnvironment()
.getParameter(prefix + username + "@" + groupname + "@" // NOI18N
+ domainname);
}
// Second try: cismapconfig:*@usergroup@domainserver
if (cismapconfig == null) {
cismapconfig = context.getEnvironment()
.getParameter(prefix + "*" + "@" + groupname + "@" // NOI18N
+ domainname);
}
// Third try: cismapconfig:*@*@domainserver//NOI18N
if (cismapconfig == null) {
cismapconfig = context.getEnvironment().getParameter(prefix + "*" + "@" + "*" + "@" + domainname); // NOI18N
}
// Default from pluginXML
if (cismapconfig == null) {
cismapconfig = context.getEnvironment().getParameter(prefix + "default"); // NOI18N
}
fallBackConfig = context.getEnvironment().getParameter(prefix + "default"); // NOI18N
} catch (final Exception e) {
log.info("cismap started standalone", e); // NOI18N
}
// Default
if (cismapconfig == null) {
cismapconfig = "defaultCismapProperties.xml"; // NOI18N
}
if (fallBackConfig == null) {
fallBackConfig = "defaultCismapProperties.xml"; // NOI18N
}
log.info("ServerConfigFile=" + cismapconfig); // NOI18N
configurationManager.setDefaultFileName(cismapconfig);
configurationManager.setFallBackFileName(fallBackConfig);
if (!plugin) {
configurationManager.setFileName("configuration.xml"); // NOI18N
} else {
configurationManager.setFileName("configurationPlugin.xml"); // NOI18N
configurationManager.addConfigurable(metaSearch);
}
configurationManager.setClassPathFolder("/"); // NOI18N
configurationManager.setFolder(".cismap" + dirExtension); // NOI18N
configurationManager.addConfigurable(this);
configurationManager.addConfigurable(capabilities);
configurationManager.addConfigurable(wfsFormFactory);
configurationManager.addConfigurable(mapC);
configurationManager.addConfigurable(activeLayers);
configurationManager.addConfigurable(featureControl);
configurationManager.addConfigurable(overviewComponent);
configurationManager.addConfigurable(shapeExport);
if (!plugin) {
configurationManager.addConfigurable(OptionsClient.getInstance());
}
if (plugin && (context.getEnvironment() != null) && this.context.getEnvironment().isProgressObservable()) {
this.context.getEnvironment()
.getProgressObserver()
.setProgress(
400,
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.CismapPlugin(PluginContext).initializingDockingsystem")); // NOI18N
}
// Flexdock stuff
final Icon icoLayers = new ImageIcon(getClass().getResource(
"/de/cismet/cismap/commons/raster/wms/res/layers.png")); // NOI18N
final Icon icoServer = new ImageIcon(getClass().getResource(
"/de/cismet/cismap/commons/raster/wms/res/server.png")); // NOI18N
final Icon icoServerInfo = new ImageIcon(getClass().getResource(
"/de/cismet/cismap/commons/gui/capabilitywidget/res/serverInfo.png")); // NOI18N
final Icon icoLayerInfo = new ImageIcon(getClass().getResource(
"/de/cismet/cismap/commons/gui/capabilitywidget/res/layerInfo.png")); // NOI18N
final Icon icoFeatureInfo = new ImageIcon(getClass().getResource(
"/de/cismet/cismap/commons/gui/featureinfowidget/res/featureInfo16.png")); // NOI18N
final Icon icoLegend = new ImageIcon(getClass().getResource(
"/de/cismet/cismap/navigatorplugin/res/legend.png")); // NOI18N
final Icon icoMap = new ImageIcon(getClass().getResource("/de/cismet/cismap/navigatorplugin/map.png")); // NOI18N
final Icon icoFeatureControl = new ImageIcon(getClass().getResource("/images/objects.png")); // NOI18N
// -------------------------InfoNode initialization-------------------------------------------//
rootWindow = DockingUtil.createRootWindow(viewMap, true);
vMap = new View(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.CismapPlugin(PluginContext).vMap.title"), // NOI18N
Static2DTools.borderIcon(icoMap, 0, 3, 0, 1),
mapC);
viewMap.addView("map", vMap); // NOI18N
viewMenuMap.put("map", mniMap); // NOI18N
vLayers = new View(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.CismapPlugin(PluginContext).vLayer.title"), // NOI18N
Static2DTools.borderIcon(icoLayers, 0, 3, 0, 1),
activeLayers);
viewMap.addView("activeLayers", vLayers); // NOI18N
viewMenuMap.put("activeLayers", mniLayer); // NOI18N
vCaps = new View(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.CismapPlugin(PluginContext).vCapabilities.title"), // NOI18N
Static2DTools.borderIcon(icoServer, 0, 3, 0, 1),
capabilities);
viewMap.addView("capabilities", vCaps); // NOI18N
viewMenuMap.put("capabilities", mniCapabilities); // NOI18N
vServerInfo = new View(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.CismapPlugin(PluginContext).vServerInfo.title"), // NOI18N
Static2DTools.borderIcon(icoServerInfo, 0, 3, 0, 1),
serverInfo);
viewMap.addView("serverinfo", vServerInfo); // NOI18N
viewMenuMap.put("serverinfo", mniServerInfo); // NOI18N
vOverview = new View(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.CismapPlugin(PluginContext).vOverview.title"), // NOI18N
Static2DTools.borderIcon(icoMap, 0, 3, 0, 1),
overviewComponent);
viewMap.addView("overview", vOverview); // NOI18N
viewMenuMap.put("overview", mniOverview); // NOI18N
legendTab[1] = vOverview;
vLayerInfo = new View(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.CismapPlugin(PluginContext).vLayerInfo.title"), // NOI18N
Static2DTools.borderIcon(icoLayerInfo, 0, 3, 0, 1),
layerInfo);
viewMap.addView("layerinfo", vLayerInfo); // NOI18N
viewMenuMap.put("layerinfo", mniLayerInfo); // NOI18N
legendTab[2] = vLayerInfo;
vLegend = new View(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.CismapPlugin(PluginContext).vLegende.title"), // NOI18N
Static2DTools.borderIcon(icoLegend, 0, 3, 0, 1),
legend);
viewMap.addView("legend", vLegend); // NOI18N
viewMenuMap.put("legend", mniLegend); // NOI18N
vFeatureInfo = new View(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.CismapPlugin(PluginContext).vFeatureInfo.title"), // NOI18N
Static2DTools.borderIcon(icoFeatureInfo, 0, 3, 0, 1),
featureInfo);
viewMap.addView("featureInfo", vFeatureInfo); // NOI18N
viewMenuMap.put("featureInfo", mniFeatureInfo); // NOI18N
vFeatureControl = new View(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.CismapPlugin(PluginContext).vFeatureControl.title"), // NOI18N
Static2DTools.borderIcon(icoFeatureControl, 0, 3, 0, 1),
featureControl);
viewMap.addView("featureControl", vFeatureControl); // NOI18N
viewMenuMap.put("featureControl", mniFeatureControl); // NOI18N
configurationManager.configure(wfsFormFactory);
// WFSForms
final Set<String> keySet = wfsFormFactory.getForms().keySet();
final JMenu wfsFormsMenu = new JMenu(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.CismapPlugin(PluginContext).wfsFormMenu.title")); // NOI18N
for (final String key : keySet) {
// View
final AbstractWFSForm form = wfsFormFactory.getForms().get(key);
form.setMappingComponent(mapC);
if (log.isDebugEnabled()) {
log.debug("WFSForms: key,form" + key + "," + form); // NOI18N
}
final View formView = new View(form.getTitle(),
Static2DTools.borderIcon(form.getIcon(), 0, 3, 0, 1),
form);
if (log.isDebugEnabled()) {
log.debug("WFSForms: formView" + formView); // NOI18N
}
viewMap.addView(form.getId(), formView);
wfsFormViews.add(formView);
wfs.add(formView);
// Menu
final JMenuItem menuItem = new JMenuItem(form.getMenuString());
menuItem.setIcon(form.getIcon());
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
if (log.isDebugEnabled()) {
log.debug("showOrHideView:" + formView); // NOI18N
}
showOrHideView(formView);
}
});
wfsFormsMenu.add(menuItem);
}
wfsViews = new DockingWindow[wfsFormViews.size()];
for (int i = 0; i < wfsViews.length; i++) {
wfsViews[i] = wfs.get(i);
}
if (keySet.size() > 0) {
menues.remove(menHelp);
menues.add(wfsFormsMenu);
menues.add(menHelp);
mnuBar.remove(menHelp);
mnuBar.add(wfsFormsMenu);
mnuBar.add(menHelp);
}
// Cismap Extensions
final Collection<? extends BasicGuiComponentProvider> guiCompProviders = Lookup.getDefault()
.lookupAll(
BasicGuiComponentProvider.class);
if (guiCompProviders != null) {
initExtensionViewComponents(guiCompProviders);
}
legendTab[0] = vLegend;
rootWindow.addTabMouseButtonListener(DockingWindowActionMouseButtonListener.MIDDLE_BUTTON_CLOSE_LISTENER);
final DockingWindowsTheme theme = new ShapedGradientDockingTheme();
rootWindow.getRootWindowProperties().addSuperObject(
theme.getRootWindowProperties());
final RootWindowProperties titleBarStyleProperties = PropertiesUtil
.createTitleBarStyleRootWindowProperties();
rootWindow.getRootWindowProperties().addSuperObject(
titleBarStyleProperties);
rootWindow.getRootWindowProperties().getDockingWindowProperties().setUndockEnabled(true);
final AlphaGradientComponentPainter x = new AlphaGradientComponentPainter(
java.awt.SystemColor.inactiveCaptionText,
java.awt.SystemColor.activeCaptionText,
java.awt.SystemColor.activeCaptionText,
java.awt.SystemColor.inactiveCaptionText);
vMap.getViewProperties()
.getViewTitleBarProperties()
.getNormalProperties()
.getCloseButtonProperties()
.setVisible(true);
rootWindow.getRootWindowProperties().getDragRectangleShapedPanelProperties().setComponentPainter(x);
if (!EventQueue.isDispatchThread()) {
EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
if (plugin) {
loadLayout(cismapDirectory + fs + pluginLayoutName);
} else {
loadLayout(cismapDirectory + fs + standaloneLayoutName);
}
}
});
} else {
if (plugin) {
loadLayout(cismapDirectory + fs + pluginLayoutName);
} else {
loadLayout(cismapDirectory + fs + standaloneLayoutName);
}
}
if (plugin && (context.getEnvironment() != null) && this.context.getEnvironment().isProgressObservable()) {
this.context.getEnvironment()
.getProgressObserver()
.setProgress(
500,
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.CismapPlugin(PluginContext).loadPreferences")); // NOI18N
}
} catch (Exception ex) {
log.fatal("Error in Constructor of CismapPlugin", ex); // NOI18N
System.err.println("Error in Constructor of CismapPlugin"); // NOI18N
ex.printStackTrace();
}
// Damit mehrere Geometrien angelegt werden koennen
mapC.setReadOnly(false);
final Object blocker = new Object();
if (plugin) {
try {
try {
synchronized (blocker) {
if ((context != null) && (context.getEnvironment() != null)
&& (context.getEnvironment().getProgressObserver() != null)
&& this.context.getEnvironment().isProgressObservable()) {
this.context.getEnvironment()
.getProgressObserver()
.setProgress(
500,
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.CismapPlugin(PluginContext).loadMethods")); // NOI18N
}
}
} catch (Exception e) {
log.warn("No progress report available", e); // NOI18N
}
mniClose.setVisible(false);
pluginMethods.put(showObjectsMethod.getId(), showObjectsMethod);
appletContext = context.getEnvironment().getAppletContext();
// TODO What the hell is this?
this.context.getMetadata().addMetaNodeSelectionListener(new NodeChangeListener());
if ((context != null) && (context.getEnvironment() != null)
&& this.context.getEnvironment().isProgressObservable()) {
this.context.getEnvironment()
.getProgressObserver()
.setProgress(
650,
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.CismapPlugin(PluginContext).loadConfiguration")); // NOI18N
}
if ((context != null) && (context.getEnvironment() != null)
&& this.context.getEnvironment().isProgressObservable()) {
this.context.getEnvironment()
.getProgressObserver()
.setProgress(
1000,
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.CismapPlugin(PluginContext).cismapPluginReady")); // NOI18N
}
if ((context != null) && (context.getEnvironment() != null)
&& context.getEnvironment().isProgressObservable()) {
this.context.getEnvironment().getProgressObserver().setFinished(true);
}
} catch (Throwable t) {
context.getLogger().fatal("Error in CismapPlugin constructor", t); // NOI18N
}
}
log.info("add InfoNode main component to the panMain Panel"); // NOI18N
panMain.add(rootWindow, BorderLayout.CENTER);
vMap.doLayout();
mapC.setMappingModel(activeLayers.getMappingModel());
setVisible(true);
// validateTree();
configureApp(false);
if ((metaSearch.getSearchTopics() != null) && !metaSearch.getSearchTopics().isEmpty()) {
popMenSearch.add(new JSeparator());
menSearch.add(new JSeparator());
for (final SearchTopic searchTopic : metaSearch.getSearchTopics()) {
popMenSearch.add(new StayOpenCheckBoxMenuItem(
(Action)searchTopic,
javax.swing.UIManager.getDefaults().getColor("ProgressBar.foreground"), // NOI18N
Color.WHITE));
menSearch.add(new StayOpenCheckBoxMenuItem(
(Action)searchTopic,
javax.swing.UIManager.getDefaults().getColor("ProgressBar.foreground"), // NOI18N
Color.WHITE));
searchTopic.addPropertyChangeListener((PropertyChangeListener)mapC.getInputListener(
MappingComponent.CREATE_SEARCH_POLYGON));
}
}
// configureActiveTabAfterVisibility();
isInit = false;
for (final Scale s : mapC.getScales()) {
if (s.getDenominator() > 0) {
menExtras.add(getScaleMenuItem(s.getText(), s.getDenominator()));
}
}
statusBar.addScalePopups();
statusBar.addCrsPopups();
cmdReconfig.setVisible(false);
jSeparator1.setVisible(false);
mapC.getFeatureCollection().addFeatureCollectionListener(this);
repaint();
if (!StaticDebuggingTools.checkHomeForFile("cismetTurnOffInternalWebserver")) { // NOI18N
initHttpServer();
}
if (log.isDebugEnabled()) {
log.debug("CismapPlugin als Observer anmelden"); // NOI18N
}
((Observable)mapC.getMemUndo()).addObserver(CismapPlugin.this);
((Observable)mapC.getMemRedo()).addObserver(CismapPlugin.this);
mapC.unlock();
overviewComponent.getOverviewMap().unlock();
layerInfo.initDividerLocation();
try {
initPluginToolbarComponents();
} catch (final Exception e) {
log.error("Exception while initializing Toolbar!", e); // NOI18N
}
}
//~ Methods ----------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @param guiCompProviders DOCUMENT ME!
*/
private void initExtensionViewComponents(final Collection<? extends BasicGuiComponentProvider> guiCompProviders) {
final List<BasicGuiComponentProvider> gcpList = new ArrayList<BasicGuiComponentProvider>(guiCompProviders);
Collections.sort(gcpList, new Comparator<BasicGuiComponentProvider>() {
@Override
public int compare(final BasicGuiComponentProvider o1, final BasicGuiComponentProvider o2) {
return o1.getName().compareTo(o2.getName());
}
});
boolean first = true;
menWindows.remove(mniResetWindowLayout);
menWindows.remove(sepResetWindowLayout);
try {
for (final BasicGuiComponentProvider gcp : gcpList) {
if (gcp.getType() == BasicGuiComponentProvider.GuiType.GUICOMPONENT) {
gcp.setLinkObject(this);
if (log.isDebugEnabled()) {
log.debug(gcp.getName() + " (try to add)"); // NOI18N
}
Icon icon = null;
try {
icon = Static2DTools.borderIcon(gcp.getIcon(), 0, 3, 0, 1);
} catch (final Exception e) {
if (log.isDebugEnabled()) {
log.debug("cannot create extension view border icon: " + gcp.getName(), e); // NOI18N
}
}
final View extensionView = new View(gcp.getName(), icon, gcp.getComponent());
final JMenuItem newItem = new JMenuItem(gcp.getName(), icon);
newItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
showOrHideView(extensionView);
}
});
if (first) {
first = false;
menWindows.add(new JSeparator());
}
menWindows.add(newItem);
viewMap.addView(gcp.getId(), extensionView);
viewMenuMap.put(gcp.getId(), newItem);
extensionWindows.put(gcp, extensionView);
if (log.isDebugEnabled()) {
log.debug(gcp.getName() + " added"); // NOI18N
}
if (gcp instanceof CustomButtonProvider) {
extensionView.getCustomTitleBarComponents()
.addAll(((CustomButtonProvider)gcp).getCustomButtons());
}
}
}
} finally {
menWindows.add(sepResetWindowLayout);
menWindows.add(mniResetWindowLayout);
}
}
/**
* DOCUMENT ME!
*/
private void initPluginToolbarComponents() {
final Collection<? extends ToolbarComponentsProvider> toolbarCompProviders = Lookup.getDefault()
.lookupAll(
ToolbarComponentsProvider.class);
if (toolbarCompProviders != null) {
for (final ToolbarComponentsProvider toolbarCompProvider : toolbarCompProviders) {
if (log.isDebugEnabled()) {
log.debug("Registering Toolbar Components for Plugin: " + toolbarCompProvider.getPluginName()); // NOI18N
}
final Collection<ToolbarComponentDescription> componentDescriptions =
toolbarCompProvider.getToolbarComponents();
if (componentDescriptions != null) {
for (final ToolbarComponentDescription componentDescription : componentDescriptions) {
int insertionIndex = tlbMain.getComponentCount();
final String anchor = componentDescription.getAnchorComponentName();
if (anchor != null) {
for (int i = tlbMain.getComponentCount(); --i >= 0;) {
final Component currentAnchorCandidate = tlbMain.getComponent(i);
if (anchor.equals(currentAnchorCandidate.getName())) {
if (ToolbarComponentsProvider.ToolbarPositionHint.BEFORE.equals(
componentDescription.getPositionHint())) {
insertionIndex = i;
} else {
insertionIndex = i + 1;
}
break;
}
}
}
tlbMain.add(componentDescription.getComponent(), insertionIndex);
}
}
}
}
final Collection<? extends BasicGuiComponentProvider> toolbarguiCompProviders = Lookup.getDefault()
.lookupAll(BasicGuiComponentProvider.class);
if (toolbarguiCompProviders != null) {
for (final BasicGuiComponentProvider gui : toolbarguiCompProviders) {
if (gui.getType() == BasicGuiComponentProvider.GuiType.TOOLBARCOMPONENT) {
final int insertionIndex = tlbMain.getComponentCount();
tlbMain.add(gui.getComponent(), insertionIndex);
}
}
}
}
/**
* DOCUMENT ME!
*
* @param t DOCUMENT ME!
* @param d DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private JMenuItem getScaleMenuItem(final String t, final int d) {
final JMenuItem jmi = new JMenuItem(t);
jmi.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
mapC.gotoBoundingBoxWithHistory(mapC.getBoundingBoxFromScale(d));
}
});
return jmi;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public MappingComponent getMappingComponent() {
return mapC;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public ConfigurationManager getConfigurationManager() {
return configurationManager;
}
/**
* DOCUMENT ME!
*/
private void setupDefaultLayout() {
final List<DockingWindow> capabilitiesSection = new ArrayList<DockingWindow>(2);
capabilitiesSection.add(vCaps);
capabilitiesSection.add(vServerInfo);
final List<DockingWindow> layerSection = new ArrayList<DockingWindow>(3);
layerSection.add(vLayers);
layerSection.add(vFeatureControl);
layerSection.add(vFeatureInfo);
final List<DockingWindow> layerInfoSection = new ArrayList<DockingWindow>(Arrays.asList(legendTab));
final List<DockingWindow> mapSection = new ArrayList<DockingWindow>(1);
mapSection.add(vMap);
final List<DockingWindow> wfsSection = new ArrayList<DockingWindow>(Arrays.asList(wfsViews));
for (final Entry<BasicGuiComponentProvider, DockingWindow> entry : extensionWindows.entrySet()) {
final Object positionHint = entry.getKey().getPositionHint();
if (positionHint instanceof ViewSection) {
final ViewSection section = (ViewSection)positionHint;
switch (section) {
case CAPABILITIES: {
capabilitiesSection.add(entry.getValue());
break;
}
case LAYER: {
layerSection.add(entry.getValue());
break;
}
case LAYER_INFO: {
layerInfoSection.add(entry.getValue());
break;
}
case MAP: {
mapSection.add(entry.getValue());
break;
}
case WFS: {
wfsSection.add(entry.getValue());
break;
}
default: {
log.warn("unrecognised view section: " + section); // NOI18N
}
}
} else {
if (log.isDebugEnabled()) {
log.debug(
"ignoring extension window in layout, because the position hint is not a ViewSection" // NOI18N
+ entry.getKey().getName());
}
}
}
final TabWindow capabilitiesTabs = new TabWindow(capabilitiesSection.toArray(
new DockingWindow[capabilitiesSection.size()]));
final TabWindow layerTabs = new TabWindow(layerSection.toArray(new DockingWindow[layerSection.size()]));
final TabWindow layerInfoTabs = new TabWindow(layerInfoSection.toArray(
new DockingWindow[layerInfoSection.size()]));
final TabWindow mapTabs = new TabWindow(mapSection.toArray(new DockingWindow[mapSection.size()]));
final TabWindow wfsTabs = wfsSection.isEmpty()
? null : new TabWindow(wfsSection.toArray(new DockingWindow[wfsSection.size()]));
rootWindow.setWindow(new SplitWindow(
true,
0.716448f,
new SplitWindow(
false,
0.72572404f,
(wfsTabs == null) ? mapTabs : new SplitWindow(false, 0.21391752f, wfsTabs, mapTabs),
layerTabs),
new SplitWindow(
false,
0.66f,
capabilitiesTabs,
layerInfoTabs)));
for (int i = 0; i
< wfsViews.length; i++) {
wfsViews[i].close();
}
rootWindow.getWindowBar(Direction.LEFT).setEnabled(true);
rootWindow.getWindowBar(Direction.RIGHT).setEnabled(true);
vLegend.restoreFocus();
vCaps.restoreFocus();
vLayers.restoreFocus();
vMap.restoreFocus();
if (windows2skip != null) {
for (final String id : windows2skip) {
final View v = viewMap.getView(id);
if (v != null) {
v.close();
}
final JMenuItem menu = viewMenuMap.get(id);
if (menu != null) {
menu.setVisible(false);
}
}
}
}
/**
* DOCUMENT ME!
*
* @param url DOCUMENT ME!
*/
private void openUrlInExternalBrowser(final String url) {
try {
if (appletContext == null) {
de.cismet.tools.BrowserLauncher.openURL(url);
} else {
final java.net.URL u = new java.net.URL(url);
appletContext.showDocument(u, "cismetBrowser"); // NOI18N
}
} catch (final Exception e) {
log.warn("Error while opening: " + url + ". Try again", e); // NOI18N
// Nochmal zur Sicherheit mit dem BrowserLauncher probieren
try {
de.cismet.tools.BrowserLauncher.openURL(url);
} catch (final Exception e2) {
log.warn("The second time failed, too. Error while trying to open: " + url + " last attempt", e2); // NOI18N
try {
de.cismet.tools.BrowserLauncher.openURL("file://" + url); // NOI18N
} catch (Exception e3) {
log.error("3rd time fail:file://" + url, e3); // NOI18N
}
}
}
}
/**
* This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
* content of this method is always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
cmdGroupPrimaryInteractionMode = new javax.swing.ButtonGroup();
panSearchSelection = new javax.swing.JPanel();
popMen = new javax.swing.JPopupMenu();
mnuConfigServer = new javax.swing.JMenuItem();
cmdGroupNodes = new javax.swing.ButtonGroup();
buttonGroup1 = new javax.swing.ButtonGroup();
jPopupMenu1 = new javax.swing.JPopupMenu();
menBookmarks = new javax.swing.JMenu();
mniAddBookmark = new javax.swing.JMenuItem();
mniBookmarkManager = new javax.swing.JMenuItem();
mniBookmarkSidebar = new javax.swing.JMenuItem();
popMenSearch = new javax.swing.JPopupMenu();
mniSearchRectangle1 = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
mniSearchPolygon1 = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
mniSearchEllipse1 = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
mniSearchPolyline1 = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
jSeparator12 = new javax.swing.JSeparator();
mniSearchCidsFeature1 = new javax.swing.JRadioButtonMenuItem();
mniSearchShowLastFeature1 = new javax.swing.JMenuItem();
mniSearchRedo1 = new javax.swing.JMenuItem();
mniSearchBuffer1 = new javax.swing.JMenuItem();
cmdGroupSearch = new javax.swing.ButtonGroup();
cmdGroupSearch1 = new javax.swing.ButtonGroup();
panAll = new javax.swing.JPanel();
panToolbar = new javax.swing.JPanel();
panMain = new javax.swing.JPanel();
tlbMain = new javax.swing.JToolBar();
cmdReconfig = new JPopupMenuButton();
((JPopupMenuButton)cmdReconfig).setPopupMenu(popMen);
jSeparator1 = new javax.swing.JSeparator();
cmdBack = new JHistoryButton() {
@Override
public void historyActionPerformed() {
if (mapC != null) {
mapC.back(true);
}
}
};
cmdHome = new javax.swing.JButton();
cmdForward = new JHistoryButton() {
@Override
public void historyActionPerformed() {
if (mapC != null) {
mapC.forward(true);
}
}
};
;
jSeparator2 = new javax.swing.JSeparator();
cmdRefresh = new javax.swing.JButton();
jSeparator6 = new javax.swing.JSeparator();
cmdPrint = new javax.swing.JButton();
cmdClipboard = new javax.swing.JButton();
cmdDownloads = new javax.swing.JButton();
jSeparator4 = new javax.swing.JSeparator();
togInvisible = new javax.swing.JToggleButton();
togInvisible.setVisible(false);
cmdSelect = new javax.swing.JToggleButton();
cmdZoom = new javax.swing.JToggleButton();
cmdPan = new javax.swing.JToggleButton();
cmdFeatureInfo = new javax.swing.JToggleButton();
cmdPluginSearch = new CidsBeanDropJPopupMenuButton(MappingComponent.CREATE_SEARCH_POLYGON, mapC, null);
cmdNewPolygon = new javax.swing.JToggleButton();
cmdNewLinestring = new javax.swing.JToggleButton();
cmdNewPoint = new javax.swing.JToggleButton();
cmdNewLinearReferencing = new javax.swing.JToggleButton();
cmdMoveGeometry = new javax.swing.JToggleButton();
cmdRemoveGeometry = new javax.swing.JToggleButton();
jSeparator3 = new javax.swing.JSeparator();
cmdNodeMove = new javax.swing.JToggleButton();
cmdNodeAdd = new javax.swing.JToggleButton();
cmdNodeRemove = new javax.swing.JToggleButton();
cmdNodeRotateGeometry = new javax.swing.JToggleButton();
jSeparator5 = new javax.swing.JSeparator();
cmdSnap = new javax.swing.JToggleButton();
jSeparator11 = new javax.swing.JSeparator();
cmdUndo = new javax.swing.JButton();
cmdRedo = new javax.swing.JButton();
panStatus = new javax.swing.JPanel();
mnuBar = new javax.swing.JMenuBar();
menFile = new javax.swing.JMenu();
mniLoadConfig = new javax.swing.JMenuItem();
mniSaveConfig = new javax.swing.JMenuItem();
mniLoadConfigFromServer = new javax.swing.JMenuItem();
sepServerProfilesStart = new javax.swing.JSeparator();
sepServerProfilesEnd = new javax.swing.JSeparator();
mniSaveLayout = new javax.swing.JMenuItem();
mniLoadLayout = new javax.swing.JMenuItem();
jSeparator9 = new javax.swing.JSeparator();
mniClipboard = new javax.swing.JMenuItem();
mniGeoLinkClipboard = new javax.swing.JMenuItem();
mniPrint = new javax.swing.JMenuItem();
jSeparator10 = new javax.swing.JSeparator();
mniClose = new javax.swing.JMenuItem();
menEdit = new javax.swing.JMenu();
mniRefresh = new javax.swing.JMenuItem();
jSeparator13 = new javax.swing.JSeparator();
mniZoomToSelectedObjects = new javax.swing.JMenuItem();
mniZoomToAllObjects = new javax.swing.JMenuItem();
jSeparator15 = new javax.swing.JSeparator();
mniRemoveSelectedObject = new javax.swing.JMenuItem();
mniRemoveAllObjects = new javax.swing.JMenuItem();
menHistory = new javax.swing.JMenu();
mniBack = new javax.swing.JMenuItem();
mniForward = new javax.swing.JMenuItem();
mniHome = new javax.swing.JMenuItem();
sepBeforePos = new javax.swing.JSeparator();
sepAfterPos = new javax.swing.JSeparator();
mniHistorySidebar = new javax.swing.JMenuItem();
menSearch = new javax.swing.JMenu();
mniSearchRectangle = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
mniSearchPolygon = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
mniSearchEllipse = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
mniSearchPolyline = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
jSeparator8 = new javax.swing.JSeparator();
mniSearchCidsFeature = new javax.swing.JRadioButtonMenuItem();
mniSearchShowLastFeature = new javax.swing.JMenuItem();
mniSearchRedo = new javax.swing.JMenuItem();
mniSearchBuffer = new javax.swing.JMenuItem();
menExtras = new javax.swing.JMenu();
mniOptions = new javax.swing.JMenuItem();
jSeparator16 = new javax.swing.JSeparator();
mniBufferSelectedGeom = new javax.swing.JMenuItem();
jSeparator17 = new javax.swing.JPopupMenu.Separator();
mniGotoPoint = new javax.swing.JMenuItem();
jSeparator14 = new javax.swing.JSeparator();
mniScale = new javax.swing.JMenuItem();
menWindows = new javax.swing.JMenu();
mniLayer = new javax.swing.JMenuItem();
mniCapabilities = new javax.swing.JMenuItem();
mniFeatureInfo = new javax.swing.JMenuItem();
mniServerInfo = new javax.swing.JMenuItem();
mniLayerInfo = new javax.swing.JMenuItem();
mniLegend = new javax.swing.JMenuItem();
mniFeatureControl = new javax.swing.JMenuItem();
mniMap = new javax.swing.JMenuItem();
mniOverview = new javax.swing.JMenuItem();
sepResetWindowLayout = new javax.swing.JSeparator();
mniResetWindowLayout = new javax.swing.JMenuItem();
menHelp = new javax.swing.JMenu();
mniOnlineHelp = new javax.swing.JMenuItem();
mniNews = new javax.swing.JMenuItem();
mniAbout = new javax.swing.JMenuItem();
mnuConfigServer.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/raster/wms/res/server.png"))); // NOI18N
mnuConfigServer.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mnuConfigServer.text")); // NOI18N
mnuConfigServer.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mnuConfigServerActionPerformed(evt);
}
});
popMen.add(mnuConfigServer);
menBookmarks.setMnemonic('L');
menBookmarks.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.menBookmarks.text")); // NOI18N
mniAddBookmark.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/bookmark_add.png"))); // NOI18N
mniAddBookmark.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniAddBookmark.text")); // NOI18N
mniAddBookmark.setEnabled(false);
menBookmarks.add(mniAddBookmark);
mniBookmarkManager.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/bookmark_folder.png"))); // NOI18N
mniBookmarkManager.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniBookmarkManager.text")); // NOI18N
mniBookmarkManager.setEnabled(false);
menBookmarks.add(mniBookmarkManager);
mniBookmarkSidebar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/bookmark.png"))); // NOI18N
mniBookmarkSidebar.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniBookmarkSidebar.text")); // NOI18N
mniBookmarkSidebar.setEnabled(false);
menBookmarks.add(mniBookmarkSidebar);
popMenSearch.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
@Override
public void popupMenuCanceled(final javax.swing.event.PopupMenuEvent evt) {
}
@Override
public void popupMenuWillBecomeInvisible(final javax.swing.event.PopupMenuEvent evt) {
}
@Override
public void popupMenuWillBecomeVisible(final javax.swing.event.PopupMenuEvent evt) {
popMenSearchPopupMenuWillBecomeVisible(evt);
}
});
mniSearchRectangle1.setAction(searchRectangleAction);
cmdGroupSearch1.add(mniSearchRectangle1);
mniSearchRectangle1.setSelected(true);
mniSearchRectangle1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchRectangle1.text")); // NOI18N
mniSearchRectangle1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/rectangle.png"))); // NOI18N
popMenSearch.add(mniSearchRectangle1);
mniSearchPolygon1.setAction(searchPolygonAction);
cmdGroupSearch1.add(mniSearchPolygon1);
mniSearchPolygon1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchPolygon1.text")); // NOI18N
mniSearchPolygon1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/polygon.png"))); // NOI18N
popMenSearch.add(mniSearchPolygon1);
mniSearchEllipse1.setAction(searchEllipseAction);
cmdGroupSearch1.add(mniSearchEllipse1);
mniSearchEllipse1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchEllipse1.text")); // NOI18N
mniSearchEllipse1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ellipse.png"))); // NOI18N
popMenSearch.add(mniSearchEllipse1);
mniSearchPolyline1.setAction(searchPolylineAction);
cmdGroupSearch1.add(mniSearchPolyline1);
mniSearchPolyline1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchPolyline1.text")); // NOI18N
mniSearchPolyline1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/polyline.png"))); // NOI18N
popMenSearch.add(mniSearchPolyline1);
popMenSearch.add(jSeparator12);
mniSearchCidsFeature1.setAction(searchCidsFeatureAction);
cmdGroupSearch.add(mniSearchCidsFeature1);
mniSearchCidsFeature1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchCidsFeature.text")); // NOI18N
mniSearchCidsFeature1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/polygon.png"))); // NOI18N
popMenSearch.add(mniSearchCidsFeature1);
mniSearchShowLastFeature1.setAction(searchShowLastFeatureAction);
mniSearchShowLastFeature1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Y,
java.awt.event.InputEvent.CTRL_MASK));
mniSearchShowLastFeature1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchShowLastFeature1.text")); // NOI18N
mniSearchShowLastFeature1.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchShowLastFeature1.toolTipText")); // NOI18N
popMenSearch.add(mniSearchShowLastFeature1);
mniSearchRedo1.setAction(searchRedoAction);
mniSearchRedo1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Y,
java.awt.event.InputEvent.ALT_MASK
| java.awt.event.InputEvent.CTRL_MASK));
mniSearchRedo1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchRedo1.text")); // NOI18N
mniSearchRedo1.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchRedo1.toolTipText")); // NOI18N
popMenSearch.add(mniSearchRedo1);
mniSearchBuffer1.setAction(searchBufferAction);
mniSearchBuffer1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/buffer.png"))); // NOI18N
mniSearchBuffer1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchBuffer1.text")); // NOI18N
mniSearchBuffer1.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchBuffer1.toolTipText")); // NOI18N
popMenSearch.add(mniSearchBuffer1);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.Form.title")); // NOI18N
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosed(final java.awt.event.WindowEvent evt) {
formWindowClosed(evt);
}
});
addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentResized(final java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
@Override
public void componentShown(final java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
panAll.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
panAll.setLayout(new java.awt.BorderLayout());
panToolbar.setLayout(new java.awt.BorderLayout());
panAll.add(panToolbar, java.awt.BorderLayout.NORTH);
panMain.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 4, 4, 4));
panMain.setFocusCycleRoot(true);
panMain.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseEntered(final java.awt.event.MouseEvent evt) {
panMainMouseEntered(evt);
}
@Override
public void mouseExited(final java.awt.event.MouseEvent evt) {
panMainMouseExited(evt);
}
});
panMain.setLayout(new java.awt.BorderLayout());
tlbMain.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(final java.awt.event.MouseEvent evt) {
tlbMainMouseClicked(evt);
}
});
cmdReconfig.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/open.gif"))); // NOI18N
cmdReconfig.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdReconfig.toolTipText")); // NOI18N
cmdReconfig.setBorderPainted(false);
cmdReconfig.setFocusPainted(false);
cmdReconfig.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdReconfigActionPerformed(evt);
}
});
tlbMain.add(cmdReconfig);
jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator1.setMaximumSize(new java.awt.Dimension(2, 32767));
jSeparator1.setPreferredSize(new java.awt.Dimension(2, 10));
tlbMain.add(jSeparator1);
cmdBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/back.png"))); // NOI18N
cmdBack.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdBack.toolTipText")); // NOI18N
cmdBack.setBorderPainted(false);
cmdBack.setFocusPainted(false);
cmdBack.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdBackActionPerformed(evt);
}
});
tlbMain.add(cmdBack);
cmdHome.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/home.gif"))); // NOI18N
cmdHome.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdHome.toolTipText")); // NOI18N
cmdHome.setBorderPainted(false);
cmdHome.setFocusPainted(false);
cmdHome.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdHomeActionPerformed(evt);
}
});
tlbMain.add(cmdHome);
cmdForward.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/forward.png"))); // NOI18N
cmdForward.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdForward.toolTipText")); // NOI18N
cmdForward.setBorderPainted(false);
cmdForward.setFocusPainted(false);
tlbMain.add(cmdForward);
jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator2.setMaximumSize(new java.awt.Dimension(2, 32767));
jSeparator2.setPreferredSize(new java.awt.Dimension(2, 10));
tlbMain.add(jSeparator2);
cmdRefresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/reload.gif"))); // NOI18N
cmdRefresh.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdRefresh.toolTipText")); // NOI18N
cmdRefresh.setBorderPainted(false);
cmdRefresh.setFocusPainted(false);
cmdRefresh.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdRefreshActionPerformed(evt);
}
});
tlbMain.add(cmdRefresh);
jSeparator6.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator6.setMaximumSize(new java.awt.Dimension(2, 32767));
jSeparator6.setPreferredSize(new java.awt.Dimension(2, 10));
tlbMain.add(jSeparator6);
cmdPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/frameprint.png"))); // NOI18N
cmdPrint.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.cmdPrint.text")); // NOI18N
cmdPrint.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdPrint.toolTipText")); // NOI18N
cmdPrint.setBorderPainted(false);
cmdPrint.setFocusPainted(false);
cmdPrint.setName("cmdPrint"); // NOI18N
cmdPrint.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdPrintActionPerformed(evt);
}
});
tlbMain.add(cmdPrint);
cmdClipboard.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/clipboard.png"))); // NOI18N
cmdClipboard.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdClipboard.text")); // NOI18N
cmdClipboard.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdClipboard.toolTipText")); // NOI18N
cmdClipboard.setBorderPainted(false);
cmdClipboard.setFocusPainted(false);
cmdClipboard.setName("cmdClipboard"); // NOI18N
cmdClipboard.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdClipboardActionPerformed(evt);
}
});
tlbMain.add(cmdClipboard);
cmdDownloads.setAction(new DownloadManagerAction(this));
cmdDownloads.setBorderPainted(false);
tlbMain.add(cmdDownloads);
jSeparator4.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator4.setMaximumSize(new java.awt.Dimension(2, 32767));
jSeparator4.setPreferredSize(new java.awt.Dimension(2, 10));
tlbMain.add(jSeparator4);
cmdGroupPrimaryInteractionMode.add(togInvisible);
togInvisible.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.togInvisible.text")); // NOI18N
togInvisible.setFocusPainted(false);
tlbMain.add(togInvisible);
cmdGroupPrimaryInteractionMode.add(cmdSelect);
cmdSelect.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/select.png"))); // NOI18N
cmdSelect.setSelected(true);
cmdSelect.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdSelect.toolTipText")); // NOI18N
cmdSelect.setBorderPainted(false);
cmdSelect.setFocusPainted(false);
cmdSelect.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdSelectActionPerformed(evt);
}
});
tlbMain.add(cmdSelect);
cmdGroupPrimaryInteractionMode.add(cmdZoom);
cmdZoom.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/zoom.gif"))); // NOI18N
cmdZoom.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdZoom.toolTipText")); // NOI18N
cmdZoom.setBorderPainted(false);
cmdZoom.setFocusPainted(false);
cmdZoom.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdZoomActionPerformed(evt);
}
});
tlbMain.add(cmdZoom);
cmdGroupPrimaryInteractionMode.add(cmdPan);
cmdPan.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/pan.gif"))); // NOI18N
cmdPan.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdPan.toolTipText")); // NOI18N
cmdPan.setBorderPainted(false);
cmdPan.setFocusPainted(false);
cmdPan.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdPanActionPerformed(evt);
}
});
tlbMain.add(cmdPan);
cmdGroupPrimaryInteractionMode.add(cmdFeatureInfo);
cmdFeatureInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/featureInfos.gif"))); // NOI18N
cmdFeatureInfo.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdFeatureInfo.toolTipText")); // NOI18N
cmdFeatureInfo.setBorderPainted(false);
cmdFeatureInfo.setFocusPainted(false);
cmdFeatureInfo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdFeatureInfoActionPerformed(evt);
}
});
tlbMain.add(cmdFeatureInfo);
cmdPluginSearch.setAction(searchAction);
cmdPluginSearch.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/pluginSearchRectangle.png"))); // NOI18N
cmdPluginSearch.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdPluginSearch.toolTipText")); // NOI18N
cmdGroupPrimaryInteractionMode.add(cmdPluginSearch);
cmdPluginSearch.setFocusPainted(false);
tlbMain.add(cmdPluginSearch);
cmdGroupPrimaryInteractionMode.add(cmdNewPolygon);
cmdNewPolygon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/newPolygon.png"))); // NOI18N
cmdNewPolygon.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNewPolygon.toolTipText")); // NOI18N
cmdNewPolygon.setBorderPainted(false);
cmdNewPolygon.setFocusPainted(false);
cmdNewPolygon.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdNewPolygonActionPerformed(evt);
}
});
tlbMain.add(cmdNewPolygon);
cmdGroupPrimaryInteractionMode.add(cmdNewLinestring);
cmdNewLinestring.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/newLinestring.png"))); // NOI18N
cmdNewLinestring.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNewLinestring.toolTipText")); // NOI18N
cmdNewLinestring.setBorderPainted(false);
cmdNewLinestring.setFocusPainted(false);
cmdNewLinestring.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
createGeometryAction(evt);
}
});
tlbMain.add(cmdNewLinestring);
cmdGroupPrimaryInteractionMode.add(cmdNewPoint);
cmdNewPoint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/newPoint.png"))); // NOI18N
cmdNewPoint.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNewPoint.toolTipText")); // NOI18N
cmdNewPoint.setBorderPainted(false);
cmdNewPoint.setFocusPainted(false);
cmdNewPoint.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdNewPointActionPerformed(evt);
}
});
tlbMain.add(cmdNewPoint);
cmdGroupPrimaryInteractionMode.add(cmdNewLinearReferencing);
cmdNewLinearReferencing.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/linref.png"))); // NOI18N
cmdNewLinearReferencing.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNewLinearReferencing.text")); // NOI18N
cmdNewLinearReferencing.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNewLinearReferencing.toolTipText")); // NOI18N
cmdNewLinearReferencing.setFocusPainted(false);
cmdNewLinearReferencing.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdNewLinearReferencingcreateGeometryAction(evt);
}
});
tlbMain.add(cmdNewLinearReferencing);
cmdNewLinearReferencing.setVisible(false);
cmdGroupPrimaryInteractionMode.add(cmdMoveGeometry);
cmdMoveGeometry.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/move.png"))); // NOI18N
cmdMoveGeometry.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdMoveGeometry.toolTipText")); // NOI18N
cmdMoveGeometry.setBorderPainted(false);
cmdMoveGeometry.setFocusPainted(false);
cmdMoveGeometry.setMaximumSize(new java.awt.Dimension(29, 29));
cmdMoveGeometry.setMinimumSize(new java.awt.Dimension(29, 29));
cmdMoveGeometry.setPreferredSize(new java.awt.Dimension(29, 29));
cmdMoveGeometry.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdMoveGeometryActionPerformed(evt);
}
});
tlbMain.add(cmdMoveGeometry);
cmdGroupPrimaryInteractionMode.add(cmdRemoveGeometry);
cmdRemoveGeometry.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.png"))); // NOI18N
cmdRemoveGeometry.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdRemoveGeometry.toolTipText")); // NOI18N
cmdRemoveGeometry.setBorderPainted(false);
cmdRemoveGeometry.setFocusPainted(false);
cmdRemoveGeometry.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdRemoveGeometryActionPerformed(evt);
}
});
tlbMain.add(cmdRemoveGeometry);
jSeparator3.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator3.setMaximumSize(new java.awt.Dimension(2, 32767));
jSeparator3.setPreferredSize(new java.awt.Dimension(2, 10));
tlbMain.add(jSeparator3);
cmdGroupNodes.add(cmdNodeMove);
cmdNodeMove.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/moveNodes.png"))); // NOI18N
cmdNodeMove.setSelected(true);
cmdNodeMove.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNodeMove.toolTipText")); // NOI18N
cmdNodeMove.setBorderPainted(false);
cmdNodeMove.setFocusPainted(false);
cmdNodeMove.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdNodeMoveActionPerformed(evt);
}
});
tlbMain.add(cmdNodeMove);
cmdGroupNodes.add(cmdNodeAdd);
cmdNodeAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/insertNodes.png"))); // NOI18N
cmdNodeAdd.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNodeAdd.toolTipText")); // NOI18N
cmdNodeAdd.setBorderPainted(false);
cmdNodeAdd.setFocusPainted(false);
cmdNodeAdd.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdNodeAddActionPerformed(evt);
}
});
tlbMain.add(cmdNodeAdd);
cmdGroupNodes.add(cmdNodeRemove);
cmdNodeRemove.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/removeNodes.png"))); // NOI18N
cmdNodeRemove.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNodeRemove.toolTipText")); // NOI18N
cmdNodeRemove.setBorderPainted(false);
cmdNodeRemove.setFocusPainted(false);
cmdNodeRemove.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdNodeRemoveActionPerformed(evt);
}
});
tlbMain.add(cmdNodeRemove);
cmdGroupNodes.add(cmdNodeRotateGeometry);
cmdNodeRotateGeometry.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/rotate.png"))); // NOI18N
cmdNodeRotateGeometry.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNodeRotateGeometry.toolTipText")); // NOI18N
cmdNodeRotateGeometry.setBorderPainted(false);
cmdNodeRotateGeometry.setFocusPainted(false);
cmdNodeRotateGeometry.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdNodeRotateGeometryActionPerformed(evt);
}
});
tlbMain.add(cmdNodeRotateGeometry);
jSeparator5.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator5.setMaximumSize(new java.awt.Dimension(2, 32767));
jSeparator5.setPreferredSize(new java.awt.Dimension(2, 10));
tlbMain.add(jSeparator5);
cmdSnap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/snap.png"))); // NOI18N
cmdSnap.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdSnap.toolTipText")); // NOI18N
cmdSnap.setBorderPainted(false);
cmdSnap.setFocusPainted(false);
cmdSnap.setMaximumSize(new java.awt.Dimension(29, 29));
cmdSnap.setMinimumSize(new java.awt.Dimension(29, 29));
cmdSnap.setPreferredSize(new java.awt.Dimension(29, 29));
cmdSnap.setRolloverSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/images/snap_selected.png"))); // NOI18N
cmdSnap.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/images/snap_selected.png"))); // NOI18N
cmdSnap.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdSnapActionPerformed(evt);
}
});
tlbMain.add(cmdSnap);
jSeparator11.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator11.setMaximumSize(new java.awt.Dimension(2, 32767));
jSeparator11.setPreferredSize(new java.awt.Dimension(2, 10));
tlbMain.add(jSeparator11);
cmdUndo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/undo.png"))); // NOI18N
cmdUndo.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdUndo.toolTipText")); // NOI18N
cmdUndo.setBorderPainted(false);
cmdUndo.setEnabled(false);
cmdUndo.setFocusPainted(false);
cmdUndo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniUndoPerformed(evt);
}
});
tlbMain.add(cmdUndo);
cmdRedo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/redo.png"))); // NOI18N
cmdRedo.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdRedo.toolTipText")); // NOI18N
cmdRedo.setBorderPainted(false);
cmdRedo.setEnabled(false);
cmdRedo.setFocusPainted(false);
cmdRedo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniRedoPerformed(evt);
}
});
tlbMain.add(cmdRedo);
panMain.add(tlbMain, java.awt.BorderLayout.NORTH);
panAll.add(panMain, java.awt.BorderLayout.CENTER);
panStatus.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 4, 1, 4));
panStatus.setLayout(new java.awt.BorderLayout());
panAll.add(panStatus, java.awt.BorderLayout.SOUTH);
getContentPane().add(panAll, java.awt.BorderLayout.CENTER);
menFile.setMnemonic('D');
menFile.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.menFile.text")); // NOI18N
mniLoadConfig.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_L,
java.awt.event.InputEvent.CTRL_MASK));
mniLoadConfig.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/config.png"))); // NOI18N
mniLoadConfig.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLoadConfig.text")); // NOI18N
mniLoadConfig.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLoadConfig.tooltip")); // NOI18N
mniLoadConfig.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniLoadConfigActionPerformed(evt);
}
});
menFile.add(mniLoadConfig);
mniSaveConfig.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_K,
java.awt.event.InputEvent.CTRL_MASK));
mniSaveConfig.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/config.png"))); // NOI18N
mniSaveConfig.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSaveConfig.text")); // NOI18N
mniSaveConfig.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSaveConfig.tooltip")); // NOI18N
mniSaveConfig.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniSaveConfigActionPerformed(evt);
}
});
menFile.add(mniSaveConfig);
mniLoadConfigFromServer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/config.png"))); // NOI18N
mniLoadConfigFromServer.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLoadConfigFromServer.text")); // NOI18N
mniLoadConfigFromServer.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLoadConfigFromServer.tooltip")); // NOI18N
mniLoadConfigFromServer.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniLoadConfigFromServerActionPerformed(evt);
}
});
menFile.add(mniLoadConfigFromServer);
sepServerProfilesStart.setName("sepServerProfilesStart"); // NOI18N
menFile.add(sepServerProfilesStart);
sepServerProfilesEnd.setName("sepServerProfilesEnd"); // NOI18N
menFile.add(sepServerProfilesEnd);
mniSaveLayout.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_S,
java.awt.event.InputEvent.CTRL_MASK));
mniSaveLayout.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/layout.png"))); // NOI18N
mniSaveLayout.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSaveLayout.text")); // NOI18N
mniSaveLayout.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSaveLayout.tooltip")); // NOI18N
mniSaveLayout.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniSaveLayoutActionPerformed(evt);
}
});
menFile.add(mniSaveLayout);
mniLoadLayout.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_O,
java.awt.event.InputEvent.CTRL_MASK));
mniLoadLayout.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/layout.png"))); // NOI18N
mniLoadLayout.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLoadLayout.text")); // NOI18N
mniLoadLayout.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLoadLayout.tooltip")); // NOI18N
mniLoadLayout.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniLoadLayoutActionPerformed(evt);
}
});
menFile.add(mniLoadLayout);
menFile.add(jSeparator9);
mniClipboard.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_C,
java.awt.event.InputEvent.CTRL_MASK));
mniClipboard.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/clipboard16.png"))); // NOI18N
mniClipboard.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniClipboard.text")); // NOI18N
mniClipboard.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniClipboard.tooltip")); // NOI18N
mniClipboard.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniClipboardActionPerformed(evt);
}
});
menFile.add(mniClipboard);
mniGeoLinkClipboard.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_C,
java.awt.event.InputEvent.ALT_MASK
| java.awt.event.InputEvent.CTRL_MASK));
mniGeoLinkClipboard.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/clipboard16.png"))); // NOI18N
mniGeoLinkClipboard.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniGeoLinkClipboard.text")); // NOI18N
mniGeoLinkClipboard.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniGeoLinkClipboard.tooltip")); // NOI18N
mniGeoLinkClipboard.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniGeoLinkClipboardActionPerformed(evt);
}
});
menFile.add(mniGeoLinkClipboard);
mniPrint.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_P,
java.awt.event.InputEvent.CTRL_MASK));
mniPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/frameprint16.png"))); // NOI18N
mniPrint.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniPrint.text")); // NOI18N
mniPrint.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniPrint.tooltip")); // NOI18N
mniPrint.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniPrintActionPerformed(evt);
}
});
menFile.add(mniPrint);
menFile.add(jSeparator10);
mniClose.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_F4,
java.awt.event.InputEvent.ALT_MASK));
mniClose.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniClose.text")); // NOI18N
mniClose.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniClose.tooltip")); // NOI18N
mniClose.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniCloseActionPerformed(evt);
}
});
menFile.add(mniClose);
mnuBar.add(menFile);
menEdit.setMnemonic('B');
menEdit.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.menEdit.text")); // NOI18N
menEdit.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
menEditActionPerformed(evt);
}
});
mniRefresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/reload16.gif"))); // NOI18N
mniRefresh.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniRefresh.text")); // NOI18N
mniRefresh.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniRefresh.tooltip")); // NOI18N
mniRefresh.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniRefreshActionPerformed(evt);
}
});
menEdit.add(mniRefresh);
menEdit.add(jSeparator13);
mniZoomToSelectedObjects.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/gui/res/zoomToSelection.png"))); // NOI18N
mniZoomToSelectedObjects.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniZoomToSelectedObjects.text")); // NOI18N
mniZoomToSelectedObjects.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniZoomToSelectedObjects.tooltip")); // NOI18N
mniZoomToSelectedObjects.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniZoomToSelectedObjectsActionPerformed(evt);
}
});
menEdit.add(mniZoomToSelectedObjects);
mniZoomToAllObjects.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/gui/res/zoomToAll.png"))); // NOI18N
mniZoomToAllObjects.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniZoomToAllObjects.text")); // NOI18N
mniZoomToAllObjects.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniZoomToAllObjects.tooltip")); // NOI18N
mniZoomToAllObjects.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniZoomToAllObjectsActionPerformed(evt);
}
});
menEdit.add(mniZoomToAllObjects);
menEdit.add(jSeparator15);
mniRemoveSelectedObject.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/gui/res/removerow.png"))); // NOI18N
mniRemoveSelectedObject.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniRemoveSelectedObject.text")); // NOI18N
mniRemoveSelectedObject.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniRemoveSelectedObject.tooltip")); // NOI18N
mniRemoveSelectedObject.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniRemoveSelectedObjectActionPerformed(evt);
}
});
menEdit.add(mniRemoveSelectedObject);
mniRemoveAllObjects.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/gui/res/removeAll.png"))); // NOI18N
mniRemoveAllObjects.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniRemoveAllObjects.text")); // NOI18N
mniRemoveAllObjects.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniRemoveAllObjects.tooltip")); // NOI18N
mniRemoveAllObjects.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniRemoveAllObjectsActionPerformed(evt);
}
});
menEdit.add(mniRemoveAllObjects);
mnuBar.add(menEdit);
menHistory.setMnemonic('C');
menHistory.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.menHistory.text")); // NOI18N
mniBack.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_LEFT,
java.awt.event.InputEvent.CTRL_MASK));
mniBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/back16.png"))); // NOI18N
mniBack.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniBack.text")); // NOI18N
mniBack.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniBack.tooltip")); // NOI18N
mniBack.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniBackActionPerformed(evt);
}
});
menHistory.add(mniBack);
mniForward.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_RIGHT,
java.awt.event.InputEvent.CTRL_MASK));
mniForward.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/forward16.png"))); // NOI18N
mniForward.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniForward.text")); // NOI18N
mniForward.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniForward.tooltip")); // NOI18N
mniForward.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniForwardActionPerformed(evt);
}
});
menHistory.add(mniForward);
mniHome.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_HOME, 0));
mniHome.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/home16.png"))); // NOI18N
mniHome.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniHome.text")); // NOI18N
mniHome.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniHome.tooltip")); // NOI18N
mniHome.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniHomeActionPerformed(evt);
}
});
menHistory.add(mniHome);
menHistory.add(sepBeforePos);
menHistory.add(sepAfterPos);
mniHistorySidebar.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniHistorySidebar.text")); // NOI18N
mniHistorySidebar.setEnabled(false);
menHistory.add(mniHistorySidebar);
mnuBar.add(menHistory);
menSearch.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.menSearch.text")); // NOI18N
menSearch.addMenuListener(new javax.swing.event.MenuListener() {
@Override
public void menuCanceled(final javax.swing.event.MenuEvent evt) {
}
@Override
public void menuDeselected(final javax.swing.event.MenuEvent evt) {
}
@Override
public void menuSelected(final javax.swing.event.MenuEvent evt) {
menSearchMenuSelected(evt);
}
});
mniSearchRectangle.setAction(searchRectangleAction);
cmdGroupSearch.add(mniSearchRectangle);
mniSearchRectangle.setSelected(true);
mniSearchRectangle.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchRectangle.text")); // NOI18N
mniSearchRectangle.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchRectangle.tooltip")); // NOI18N
mniSearchRectangle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/rectangle.png"))); // NOI18N
menSearch.add(mniSearchRectangle);
mniSearchPolygon.setAction(searchPolygonAction);
cmdGroupSearch.add(mniSearchPolygon);
mniSearchPolygon.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchPolygon.text")); // NOI18N
mniSearchPolygon.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchPolygon.tooltip")); // NOI18N
mniSearchPolygon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/polygon.png"))); // NOI18N
menSearch.add(mniSearchPolygon);
mniSearchEllipse.setAction(searchEllipseAction);
cmdGroupSearch.add(mniSearchEllipse);
mniSearchEllipse.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchEllipse.text_1")); // NOI18N
mniSearchEllipse.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchEllipse.tooltip")); // NOI18N
mniSearchEllipse.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ellipse.png"))); // NOI18N
menSearch.add(mniSearchEllipse);
mniSearchPolyline.setAction(searchPolylineAction);
cmdGroupSearch.add(mniSearchPolyline);
mniSearchPolyline.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchPolyline.text_1")); // NOI18N
mniSearchPolyline.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchLine.tooltip")); // NOI18N
mniSearchPolyline.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/polyline.png"))); // NOI18N
menSearch.add(mniSearchPolyline);
menSearch.add(jSeparator8);
mniSearchCidsFeature.setAction(searchCidsFeatureAction);
cmdGroupSearch.add(mniSearchCidsFeature);
mniSearchCidsFeature.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchCidsFeature.text")); // NOI18N
mniSearchCidsFeature.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchCidsFeature.tooltip")); // NOI18N
mniSearchCidsFeature.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/polygon.png"))); // NOI18N
mniSearchCidsFeature.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniSearchCidsFeatureActionPerformed(evt);
}
});
menSearch.add(mniSearchCidsFeature);
mniSearchShowLastFeature.setAction(searchShowLastFeatureAction);
mniSearchShowLastFeature.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Y,
java.awt.event.InputEvent.CTRL_MASK));
mniSearchShowLastFeature.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchShowLastFeature.text")); // NOI18N
mniSearchShowLastFeature.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchShowLastFeature.toolTipText")); // NOI18N
menSearch.add(mniSearchShowLastFeature);
mniSearchRedo.setAction(searchRedoAction);
mniSearchRedo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Y,
java.awt.event.InputEvent.ALT_MASK
| java.awt.event.InputEvent.CTRL_MASK));
mniSearchRedo.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchRedo.text")); // NOI18N
mniSearchRedo.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchRedo.toolTipText")); // NOI18N
menSearch.add(mniSearchRedo);
mniSearchBuffer.setAction(searchBufferAction);
mniSearchBuffer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/buffer.png"))); // NOI18N
mniSearchBuffer.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchBuffer.text_1")); // NOI18N
mniSearchBuffer.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchBuffer.toolTipText")); // NOI18N
menSearch.add(mniSearchBuffer);
mnuBar.add(menSearch);
// copyMenu(menSearch, popMenSearch);
((JPopupMenuButton)cmdPluginSearch).setPopupMenu(popMenSearch);
menExtras.setMnemonic('E');
menExtras.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.menExtras.text")); // NOI18N
mniOptions.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/tooloptions.png"))); // NOI18N
mniOptions.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniOptions.text")); // NOI18N
mniOptions.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniOptions.tooltip")); // NOI18N
mniOptions.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniOptionsActionPerformed(evt);
}
});
menExtras.add(mniOptions);
menExtras.add(jSeparator16);
mniBufferSelectedGeom.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_B,
java.awt.event.InputEvent.CTRL_MASK));
mniBufferSelectedGeom.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/buffer.png"))); // NOI18N
mniBufferSelectedGeom.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniBufferSelectedGeom.text")); // NOI18N
mniBufferSelectedGeom.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniBufferSelectedGeom.tooltip")); // NOI18N
mniBufferSelectedGeom.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniBufferSelectedGeomActionPerformed(evt);
}
});
menExtras.add(mniBufferSelectedGeom);
menExtras.add(jSeparator17);
mniGotoPoint.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_G,
java.awt.event.InputEvent.CTRL_MASK));
mniGotoPoint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/goto.png"))); // NOI18N
mniGotoPoint.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniGotoPoint.text")); // NOI18N
mniGotoPoint.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniGotoPoint.tooltip")); // NOI18N
mniGotoPoint.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniGotoPointActionPerformed(evt);
}
});
menExtras.add(mniGotoPoint);
menExtras.add(jSeparator14);
mniScale.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_M,
java.awt.event.InputEvent.CTRL_MASK));
mniScale.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/scale.png"))); // NOI18N
mniScale.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniScale.text")); // NOI18N
mniScale.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniScale.tooltip")); // NOI18N
mniScale.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniScaleActionPerformed(evt);
}
});
menExtras.add(mniScale);
mnuBar.add(menExtras);
menWindows.setMnemonic('F');
menWindows.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.menWindows.text")); // NOI18N
menWindows.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
menWindowsActionPerformed(evt);
}
});
mniLayer.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_1,
java.awt.event.InputEvent.CTRL_MASK));
mniLayer.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/raster/wms/res/layers.png"))); // NOI18N
mniLayer.setMnemonic('L');
mniLayer.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniLayer.text")); // NOI18N
mniLayer.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLayer.tooltip")); // NOI18N
mniLayer.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniLayerActionPerformed(evt);
}
});
menWindows.add(mniLayer);
mniCapabilities.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_2,
java.awt.event.InputEvent.CTRL_MASK));
mniCapabilities.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/raster/wms/res/server.png"))); // NOI18N
mniCapabilities.setMnemonic('C');
mniCapabilities.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniCapabilities.text")); // NOI18N
mniCapabilities.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniCapabilities.tooltip")); // NOI18N
mniCapabilities.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniCapabilitiesActionPerformed(evt);
}
});
menWindows.add(mniCapabilities);
mniFeatureInfo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_3,
java.awt.event.InputEvent.CTRL_MASK));
mniFeatureInfo.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/gui/featureinfowidget/res/featureInfo16.png"))); // NOI18N
mniFeatureInfo.setMnemonic('F');
mniFeatureInfo.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniFeatureInfo.text")); // NOI18N
mniFeatureInfo.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniFeatureInfo.tooltip")); // NOI18N
mniFeatureInfo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniFeatureInfoActionPerformed(evt);
}
});
menWindows.add(mniFeatureInfo);
mniServerInfo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_5,
java.awt.event.InputEvent.CTRL_MASK));
mniServerInfo.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/gui/capabilitywidget/res/serverInfo.png"))); // NOI18N
mniServerInfo.setMnemonic('S');
mniServerInfo.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniServerInfo.text")); // NOI18N
mniServerInfo.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniServerInfo.tooltip")); // NOI18N
mniServerInfo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniServerInfoActionPerformed(evt);
}
});
menWindows.add(mniServerInfo);
mniLayerInfo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_6,
java.awt.event.InputEvent.CTRL_MASK));
mniLayerInfo.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/gui/capabilitywidget/res/layerInfo.png"))); // NOI18N
mniLayerInfo.setMnemonic('L');
mniLayerInfo.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLayerInfo.text")); // NOI18N
mniLayerInfo.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLayerInfo.tooltip")); // NOI18N
mniLayerInfo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniLayerInfoActionPerformed(evt);
}
});
menWindows.add(mniLayerInfo);
mniLegend.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_7,
java.awt.event.InputEvent.CTRL_MASK));
mniLegend.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/navigatorplugin/res/legend.png"))); // NOI18N
mniLegend.setMnemonic('L');
mniLegend.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniLegend.text")); // NOI18N
mniLegend.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLegend.tooltip")); // NOI18N
mniLegend.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniLegendActionPerformed(evt);
}
});
menWindows.add(mniLegend);
mniFeatureControl.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_8,
java.awt.event.InputEvent.CTRL_MASK));
mniFeatureControl.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/objects.png"))); // NOI18N
mniFeatureControl.setMnemonic('O');
mniFeatureControl.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniFeatureControl.text")); // NOI18N
mniFeatureControl.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniFeatureControl.tooltip")); // NOI18N
mniFeatureControl.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniFeatureControlActionPerformed(evt);
}
});
menWindows.add(mniFeatureControl);
mniMap.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_9,
java.awt.event.InputEvent.CTRL_MASK));
mniMap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cismap/navigatorplugin/map.png"))); // NOI18N
mniMap.setMnemonic('M');
mniMap.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniMap.text")); // NOI18N
mniMap.setToolTipText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniMap.tooltip")); // NOI18N
mniMap.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniMapActionPerformed(evt);
}
});
menWindows.add(mniMap);
mniOverview.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_0,
java.awt.event.InputEvent.CTRL_MASK));
mniOverview.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/navigatorplugin/map.png"))); // NOI18N
mniOverview.setMnemonic('M');
mniOverview.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniOverview.text")); // NOI18N
mniOverview.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniOverview.tooltip")); // NOI18N
mniOverview.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniOverviewActionPerformed(evt);
}
});
menWindows.add(mniOverview);
menWindows.add(sepResetWindowLayout);
mniResetWindowLayout.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_R,
java.awt.event.InputEvent.CTRL_MASK));
mniResetWindowLayout.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/layout.png"))); // NOI18N
mniResetWindowLayout.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniResetWindowLayout.text")); // NOI18N
mniResetWindowLayout.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniResetWindowLayout.toolTipText")); // NOI18N
mniResetWindowLayout.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniResetWindowLayoutActionPerformed(evt);
}
});
menWindows.add(mniResetWindowLayout);
mnuBar.add(menWindows);
menHelp.setMnemonic('H');
menHelp.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.menHelp.text")); // NOI18N
menHelp.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
menHelpActionPerformed(evt);
}
});
mniOnlineHelp.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
mniOnlineHelp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/help.png"))); // NOI18N
mniOnlineHelp.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniOnlineHelp.text")); // NOI18N
mniOnlineHelp.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniOnlineHelp.tooltip")); // NOI18N
mniOnlineHelp.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniOnlineHelpActionPerformed(evt);
}
});
menHelp.add(mniOnlineHelp);
mniNews.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/news.png"))); // NOI18N
mniNews.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniNews.text")); // NOI18N
mniNews.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniNews.tooltip")); // NOI18N
mniNews.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniNewsActionPerformed(evt);
}
});
menHelp.add(mniNews);
- mniAbout.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
- java.awt.event.KeyEvent.VK_A,
- java.awt.event.InputEvent.ALT_MASK
- | java.awt.event.InputEvent.CTRL_MASK));
mniAbout.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniAbout.text")); // NOI18N
mniAbout.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniAbout.tooltip")); // NOI18N
mniAbout.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniAboutActionPerformed(evt);
}
});
menHelp.add(mniAbout);
mnuBar.add(menHelp);
setJMenuBar(mnuBar);
} // </editor-fold>//GEN-END:initComponents
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniSearchCidsFeatureActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_mniSearchCidsFeatureActionPerformed
// TODO add your handling code here:
} //GEN-LAST:event_mniSearchCidsFeatureActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cmdNewLinearReferencingcreateGeometryAction(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_cmdNewLinearReferencingcreateGeometryAction
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
mapC.setInteractionMode(MappingComponent.LINEAR_REFERENCING);
}
});
} //GEN-LAST:event_cmdNewLinearReferencingcreateGeometryAction
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniBufferSelectedGeomActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_mniBufferSelectedGeomActionPerformed
final Collection c = mapC.getFeatureCollection().getSelectedFeatures();
if ((c != null) && (c.size() > 0)) {
final String s = (String)JOptionPane.showInputDialog(
null,
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniBufferSelectedGeom.Dialog.text"), // NOI18N
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniBufferSelectedGeom.Dialog.title"), // NOI18N
JOptionPane.PLAIN_MESSAGE,
null,
null,
""); // NOI18N
for (final Object o : c) {
if (o instanceof Feature) {
final int srid = ((Feature)o).getGeometry().getSRID();
final Geometry oldG = CrsTransformer.transformToMetricCrs(((Feature)o).getGeometry());
Geometry newG = oldG.buffer(Double.parseDouble(s));
newG = CrsTransformer.transformToGivenCrs(newG, CrsTransformer.createCrsFromSrid(srid));
if (o instanceof PureNewFeature) {
((Feature)o).setGeometry(newG);
((PureNewFeature)o).setGeometryType(PureNewFeature.geomTypes.POLYGON);
final PFeature sel = (PFeature)mapC.getPFeatureHM().get(o);
// Koordinaten der Puffer-Geometrie als Feature-Koordinaten
// setzen
sel.setCoordArr(newG.getCoordinates());
// refresh
sel.syncGeometry();
final List v = new ArrayList();
v.add(sel.getFeature());
((DefaultFeatureCollection)mapC.getFeatureCollection()).fireFeaturesChanged(v);
} else {
final PureNewFeature pnf = new PureNewFeature(newG);
pnf.setGeometryType(PureNewFeature.geomTypes.POLYGON);
((DefaultFeatureCollection)mapC.getFeatureCollection()).addFeature(pnf);
((DefaultFeatureCollection)mapC.getFeatureCollection()).holdFeature(pnf);
}
}
}
} else {
JOptionPane.showMessageDialog(
null,
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniBufferSelectedGeom.Dialog.noneselected"), // NOI18N
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniBufferSelectedGeom.Dialog.title"), // NOI18N
JOptionPane.WARNING_MESSAGE);
}
} //GEN-LAST:event_mniBufferSelectedGeomActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniRedoPerformed(final java.awt.event.ActionEvent evt) {
log.info("REDO"); // NOI18N
final CustomAction a = mapC.getMemRedo().getLastAction();
if (log.isDebugEnabled()) {
log.debug("... execute action: " + a.info()); // NOI18N
}
try {
a.doAction();
} catch (Exception e) {
log.error("Error while executing an action", e); // NOI18N
}
final CustomAction inverse = a.getInverse();
mapC.getMemUndo().addAction(inverse);
if (log.isDebugEnabled()) {
log.debug("... new action on UNDO stack: " + inverse); // NOI18N
log.debug("... completed"); // NOI18N
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniUndoPerformed(final java.awt.event.ActionEvent evt) {
log.info("UNDO"); // NOI18N
final CustomAction a = mapC.getMemUndo().getLastAction();
if (log.isDebugEnabled()) {
log.debug("... execute action: " + a.info()); // NOI18N
}
try {
a.doAction();
} catch (Exception e) {
log.error("Error while executing action", e); // NOI18N
}
final CustomAction inverse = a.getInverse();
mapC.getMemRedo().addAction(inverse);
if (log.isDebugEnabled()) {
log.debug("... new action on REDO stack: " + inverse); // NOI18N
log.debug("... completed"); // NOI18N
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniGeoLinkClipboardActionPerformed(final java.awt.event.ActionEvent evt) {
final Thread t = new Thread(new Runnable() {
@Override
public void run() {
final BoundingBox bb = mapC.getCurrentBoundingBox();
final String u = "http://localhost:" + httpInterfacePort + "/gotoBoundingBox?x1="
+ bb.getX1() // NOI18N
+ "&y1=" + bb.getY1() + "&x2=" + bb.getX2() + "&y2=" + bb.getY2(); // NOI18N
final GeoLinkUrl url = new GeoLinkUrl(u);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(url, null);
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
clipboarder.dispose();
}
});
}
});
t.start();
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void menHelpActionPerformed(final java.awt.event.ActionEvent evt) {
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniAboutActionPerformed(final java.awt.event.ActionEvent evt) {
if (about == null) {
about = new AboutDialog(StaticSwingTools.getParentFrame(this.panAll), true);
}
StaticSwingTools.showDialog(about);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniNewsActionPerformed(final java.awt.event.ActionEvent evt) {
openUrlInExternalBrowser(newsUrl);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniOnlineHelpActionPerformed(final java.awt.event.ActionEvent evt) {
openUrlInExternalBrowser(helpUrl);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniGotoPointActionPerformed(final java.awt.event.ActionEvent evt) {
if (log.isDebugEnabled()) {
log.debug("mniGotoPointActionPerformed"); // NOI18N
}
try {
final BoundingBox c = mapC.getCurrentBoundingBox();
final double x = (c.getX1() + c.getX2()) / 2;
final double y = (c.getY1() + c.getY2()) / 2;
final String s = JOptionPane.showInputDialog(
this,
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniGotoPointActionPerformed.JOptionPane.message"), // NOI18N
StaticDecimalTools.round(x)
+ "," // NOI18N
+ StaticDecimalTools.round(y));
final String[] sa = s.split(","); // NOI18N
final Double gotoX = new Double(sa[0]);
final Double gotoY = new Double(sa[1]);
final BoundingBox bb = new BoundingBox(gotoX, gotoY, gotoX, gotoY);
mapC.gotoBoundingBox(bb, true, false, mapC.getAnimationDuration());
} catch (final Exception skip) {
log.error("Error in mniGotoPointActionPerformed", skip); // NOI18N
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniScaleActionPerformed(final java.awt.event.ActionEvent evt) {
try {
final String s = JOptionPane.showInputDialog(
this,
org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.scaleManually"),
((int)mapC.getScaleDenominator())
+ ""); // NOI18N
final Integer i = new Integer(s);
mapC.gotoBoundingBoxWithHistory(mapC.getBoundingBoxFromScale(i));
} catch (Exception skip) {
log.error("Error in mniScaleActionPerformed", skip); // NOI18N
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniMapActionPerformed(final java.awt.event.ActionEvent evt) {
showOrHideView(vMap);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniRemoveAllObjectsActionPerformed(final java.awt.event.ActionEvent evt) {
if (mapC != null) {
final List v = new ArrayList(mapC.getFeatureCollection().getAllFeatures());
mapC.getFeatureCollection().removeFeatures(v);
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniZoomToSelectedObjectsActionPerformed(final java.awt.event.ActionEvent evt) {
if (mapC != null) {
mapC.zoomToSelection();
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniZoomToAllObjectsActionPerformed(final java.awt.event.ActionEvent evt) {
if (mapC != null) {
mapC.zoomToFeatureCollection();
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniForwardActionPerformed(final java.awt.event.ActionEvent evt) {
if ((mapC != null) && mapC.isForwardPossible()) {
mapC.forward(true);
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniBackActionPerformed(final java.awt.event.ActionEvent evt) {
if ((mapC != null) && mapC.isBackPossible()) {
mapC.back(true);
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniHomeActionPerformed(final java.awt.event.ActionEvent evt) {
cmdHomeActionPerformed(null);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniRefreshActionPerformed(final java.awt.event.ActionEvent evt) {
cmdRefreshActionPerformed(null);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniRemoveSelectedObjectActionPerformed(final java.awt.event.ActionEvent evt) {
if (mapC != null) {
final List v = new ArrayList(mapC.getFeatureCollection().getSelectedFeatures());
mapC.getFeatureCollection().removeFeatures(v);
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniLoadConfigActionPerformed(final java.awt.event.ActionEvent evt) {
JFileChooser fc;
try {
fc = new JFileChooser(cismapDirectory);
} catch (Exception bug) {
// Bug Workaround http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6544857
fc = new JFileChooser(cismapDirectory, new RestrictedFileSystemView());
}
fc.setFileFilter(new FileFilter() {
@Override
public boolean accept(final File f) {
return f.getName().toLowerCase().endsWith(".xml"); // NOI18N
}
@Override
public String getDescription() {
return org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLoadConfigActionPerformed.FileFiltergetDescription.return"); // NOI18N
}
});
final int state = fc.showOpenDialog(this);
if (state == JFileChooser.APPROVE_OPTION) {
final File file = fc.getSelectedFile();
String name = file.getAbsolutePath();
name = name.toLowerCase();
if (name.endsWith(".xml")) { // NOI18N
activeLayers.removeAllLayers();
mapC.getRasterServiceLayer().removeAllChildren();
configurationManager.configure(name);
} else {
activeLayers.removeAllLayers();
mapC.getRasterServiceLayer().removeAllChildren();
configurationManager.configure(name + ".xml"); // NOI18N
}
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniSaveConfigActionPerformed(final java.awt.event.ActionEvent evt) {
JFileChooser fc;
try {
fc = new JFileChooser(cismapDirectory);
} catch (Exception bug) {
// Bug Workaround http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6544857
fc = new JFileChooser(cismapDirectory, new RestrictedFileSystemView());
}
fc.setFileFilter(new FileFilter() {
@Override
public boolean accept(final File f) {
return f.getName().toLowerCase().endsWith(".xml"); // NOI18N
}
@Override
public String getDescription() {
return org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSaveConfigActionPerformed.FileFilter.getDescription.return"); // NOI18N
}
});
final int state = fc.showSaveDialog(this);
if (log.isDebugEnabled()) {
log.debug("state:" + state); // NOI18N
}
if (state == JFileChooser.APPROVE_OPTION) {
final File file = fc.getSelectedFile();
String name = file.getAbsolutePath();
name = name.toLowerCase();
if (name.endsWith(".xml")) { // NOI18N
configurationManager.writeConfiguration(name);
} else {
configurationManager.writeConfiguration(name + ".xml"); // NOI18N
}
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniLoadConfigFromServerActionPerformed(final java.awt.event.ActionEvent evt) {
activeLayers.removeAllLayers();
mapC.getMapServiceLayer().removeAllChildren();
configureApp(true);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniPrintActionPerformed(final java.awt.event.ActionEvent evt) {
cmdPrintActionPerformed(null);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniSaveLayoutActionPerformed(final java.awt.event.ActionEvent evt) {
JFileChooser fc;
try {
fc = new JFileChooser(cismapDirectory);
} catch (final Exception bug) {
// Bug Workaround http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6544857
fc = new JFileChooser(cismapDirectory, new RestrictedFileSystemView());
}
fc.setFileFilter(new FileFilter() {
@Override
public boolean accept(final File f) {
return f.getName().toLowerCase().endsWith(".layout"); // NOI18N
}
@Override
public String getDescription() {
return "Layout"; // NOI18N
}
});
fc.setMultiSelectionEnabled(false);
final int state = fc.showSaveDialog(this);
if (log.isDebugEnabled()) {
log.debug("state:" + state); // NOI18N
}
if (state == JFileChooser.APPROVE_OPTION) {
final File file = fc.getSelectedFile();
if (log.isDebugEnabled()) {
log.debug("file:" + file); // NOI18N
}
String name = file.getAbsolutePath();
name = name.toLowerCase();
if (name.endsWith(".layout")) { // NOI18N
saveLayout(name);
} else {
saveLayout(name + ".layout"); // NOI18N
}
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniLoadLayoutActionPerformed(final java.awt.event.ActionEvent evt) {
JFileChooser fc;
try {
fc = new JFileChooser(cismapDirectory);
} catch (final Exception bug) {
// Bug Workaround http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6544857
fc = new JFileChooser(cismapDirectory, new RestrictedFileSystemView());
}
fc.setFileFilter(new FileFilter() {
@Override
public boolean accept(final File f) {
return f.getName().toLowerCase().endsWith(".layout"); // NOI18N
}
@Override
public String getDescription() {
return "Layout"; // NOI18N
}
});
fc.setMultiSelectionEnabled(false);
final int state = fc.showOpenDialog(this);
if (state == JFileChooser.APPROVE_OPTION) {
final File file = fc.getSelectedFile();
String name = file.getAbsolutePath();
name = name.toLowerCase();
if (name.endsWith(".layout")) { // NOI18N
loadLayout(name);
} else {
JOptionPane.showMessageDialog(
this,
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLoadLayoutActionPerformed(ActionEvent).JOptionPane.msg"), // NOI18N
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLoadLayoutActionPerformed(ActionEvent).JOptionPane.title"), // NOI18N
JOptionPane.INFORMATION_MESSAGE);
}
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniClipboardActionPerformed(final java.awt.event.ActionEvent evt) {
cmdClipboardActionPerformed(null);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniCloseActionPerformed(final java.awt.event.ActionEvent evt) {
this.dispose();
System.exit(0);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void menEditActionPerformed(final java.awt.event.ActionEvent evt) {
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void menWindowsActionPerformed(final java.awt.event.ActionEvent evt) {
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void tlbMainMouseClicked(final java.awt.event.MouseEvent evt) {
if (evt.getClickCount() == 3) {
// DockingManager.dock((Dockable)vDebug,(Dockable)vMap, DockingConstants.SOUTH_REGION, .25f);
// DockingManager.dock((Dockable)vGroovy,(Dockable)vMap);
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cmdPrintActionPerformed(final java.awt.event.ActionEvent evt) {
final String oldMode = mapC.getInteractionMode();
if (log.isDebugEnabled()) {
log.debug("oldInteractionMode:" + oldMode); // NOI18N
}
togInvisible.setSelected(true);
mapC.showPrintingSettingsDialog(oldMode);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cmdClipboardActionPerformed(final java.awt.event.ActionEvent evt) {
final Thread t = new Thread(new Runnable() {
@Override
public void run() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
StaticSwingTools.showDialog(clipboarder);
}
});
final ImageSelection imgSel = new ImageSelection(mapC.getImage());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(imgSel, null);
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
clipboarder.dispose();
}
});
}
});
t.start();
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cmdSnapActionPerformed(final java.awt.event.ActionEvent evt) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
mapC.setSnappingEnabled(cmdSnap.isSelected());
}
});
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cmdRemoveGeometryActionPerformed(final java.awt.event.ActionEvent evt) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
mapC.setInteractionMode(MappingComponent.REMOVE_POLYGON);
}
});
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cmdMoveGeometryActionPerformed(final java.awt.event.ActionEvent evt) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
mapC.setInteractionMode(MappingComponent.MOVE_POLYGON);
}
});
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cmdNewPointActionPerformed(final java.awt.event.ActionEvent evt) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
((CreateNewGeometryListener)mapC.getInputListener(MappingComponent.NEW_POLYGON)).setMode(
CreateGeometryListenerInterface.POINT);
mapC.setInteractionMode(MappingComponent.NEW_POLYGON);
}
});
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cmdNewPolygonActionPerformed(final java.awt.event.ActionEvent evt) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
((CreateNewGeometryListener)mapC.getInputListener(MappingComponent.NEW_POLYGON)).setMode(
CreateGeometryListenerInterface.POLYGON);
mapC.setInteractionMode(MappingComponent.NEW_POLYGON);
}
});
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void createGeometryAction(final java.awt.event.ActionEvent evt) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
((CreateNewGeometryListener)mapC.getInputListener(MappingComponent.NEW_POLYGON)).setMode(
CreateGeometryListenerInterface.LINESTRING);
mapC.setInteractionMode(MappingComponent.NEW_POLYGON);
}
});
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cmdNodeRemoveActionPerformed(final java.awt.event.ActionEvent evt) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
mapC.setHandleInteractionMode(MappingComponent.REMOVE_HANDLE);
mapC.setInteractionMode(MappingComponent.SELECT);
}
});
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cmdNodeAddActionPerformed(final java.awt.event.ActionEvent evt) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
mapC.setHandleInteractionMode(MappingComponent.ADD_HANDLE);
mapC.setInteractionMode(MappingComponent.SELECT);
}
});
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cmdNodeMoveActionPerformed(final java.awt.event.ActionEvent evt) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
mapC.setHandleInteractionMode(MappingComponent.MOVE_HANDLE);
mapC.setInteractionMode(MappingComponent.SELECT);
}
});
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cmdSelectActionPerformed(final java.awt.event.ActionEvent evt) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
mapC.setInteractionMode(MappingComponent.SELECT);
}
});
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniResetWindowLayoutActionPerformed(final java.awt.event.ActionEvent evt) {
setupDefaultLayout();
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniFeatureControlActionPerformed(final java.awt.event.ActionEvent evt) {
showOrHideView(vFeatureControl);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cmdReconfigActionPerformed(final java.awt.event.ActionEvent evt) {
activeLayers.removeAllLayers();
mapC.getRasterServiceLayer().removeAllChildren();
// mapC.resetWtst();
configureApp(false);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniFeatureInfoActionPerformed(final java.awt.event.ActionEvent evt) {
showOrHideView(vFeatureInfo);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniServerInfoActionPerformed(final java.awt.event.ActionEvent evt) {
showOrHideView(vServerInfo);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniLayerInfoActionPerformed(final java.awt.event.ActionEvent evt) {
showOrHideView(vLayerInfo);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniLegendActionPerformed(final java.awt.event.ActionEvent evt) {
showOrHideView(vLegend);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniCapabilitiesActionPerformed(final java.awt.event.ActionEvent evt) {
showOrHideView(vCaps);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniLayerActionPerformed(final java.awt.event.ActionEvent evt) {
showOrHideView(vLayers);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cmdFeatureInfoActionPerformed(final java.awt.event.ActionEvent evt) {
mapC.setInteractionMode(MappingComponent.FEATURE_INFO);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void formComponentShown(final java.awt.event.ComponentEvent evt) {
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void formWindowClosed(final java.awt.event.WindowEvent evt) {
log.info("CLOSE"); // NOI18N
}
/**
* DOCUMENT ME!
*
* @param v DOCUMENT ME!
*/
private void showOrHideView(final View v) {
///irgendwas besser als Closable ??
// Problem wenn floating --> close -> open (muss zweimal open)
if (v.isClosable()) {
v.close();
} else {
v.restore();
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cmdPanActionPerformed(final java.awt.event.ActionEvent evt) {
if (mapC != null) {
mapC.setInteractionMode(MappingComponent.PAN);
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cmdZoomActionPerformed(final java.awt.event.ActionEvent evt) {
if (mapC != null) {
mapC.setInteractionMode(MappingComponent.ZOOM);
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cmdRefreshActionPerformed(final java.awt.event.ActionEvent evt) {
if (mapC != null) {
mapC.refresh();
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cmdHomeActionPerformed(final java.awt.event.ActionEvent evt) {
if (mapC != null) {
mapC.gotoInitialBoundingBox();
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cmdBackActionPerformed(final java.awt.event.ActionEvent evt) {
// mapC.back(true);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void panMainMouseEntered(final java.awt.event.MouseEvent evt) {
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void panMainMouseExited(final java.awt.event.MouseEvent evt) {
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cmdNodeRotateGeometryActionPerformed(final java.awt.event.ActionEvent evt) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
// mapC.setInteractionMode(MappingComponent.SELECT);
mapC.setHandleInteractionMode(MappingComponent.ROTATE_POLYGON);
}
});
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniOverviewActionPerformed(final java.awt.event.ActionEvent evt) {
showOrHideView(vOverview);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void formComponentResized(final java.awt.event.ComponentEvent evt) {
if (this.getExtendedState() != MAXIMIZED_BOTH) {
oldWindowDimension.setSize(getWidth(), getHeight());
oldWindowPositionX = (int)this.getLocation().getX();
oldWindowPositionY = (int)this.getLocation().getY();
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mniOptionsActionPerformed(final java.awt.event.ActionEvent evt) {
final OptionsDialog od = new OptionsDialog(StaticSwingTools.getParentFrame(this.panAll), true);
StaticSwingTools.showDialog(od);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void popMenSearchPopupMenuWillBecomeVisible(final javax.swing.event.PopupMenuEvent evt) {
searchMenuSelectedAction.actionPerformed(new ActionEvent(popMenSearch, ActionEvent.ACTION_PERFORMED, null));
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void menSearchMenuSelected(final javax.swing.event.MenuEvent evt) {
searchMenuSelectedAction.actionPerformed(new ActionEvent(menSearch, ActionEvent.ACTION_PERFORMED, null));
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void mnuConfigServerActionPerformed(final java.awt.event.ActionEvent evt) {
activeLayers.removeAllLayers();
mapC.getRasterServiceLayer().removeAllChildren();
// mapC.resetWtst();
configureApp(true);
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cmdPluginSearchActionPerformed(final java.awt.event.ActionEvent evt) {
}
/**
* DOCUMENT ME!
*
* @param args the command line arguments
*/
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
ToolTipManager.sharedInstance().setLightWeightPopupEnabled(false);
final CismapPlugin cp = new CismapPlugin();
cp.setVisible(true);
}
});
}
/**
* DOCUMENT ME!
*
* @param serverFirst DOCUMENT ME!
*/
private void configureApp(final boolean serverFirst) {
try {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
validateTree();
}
});
} catch (final Throwable t) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
log.warn("Error in validateTree()", t); // NOI18N
validateTree();
}
});
}
if (serverFirst) {
configurationManager.configureFromClasspath();
} else {
configurationManager.configure();
}
setButtonSelectionAccordingToMappingComponent();
}
/**
* DOCUMENT ME!
*/
private void activateLineRef() {
if (cismapPluginUIPreferences != null) {
try {
final boolean isLineRefActivated =
cismapPluginUIPreferences.getChild("LinearReferencedMarks") // NOI18N
.getAttribute("isActivated") // NOI18N
.getBooleanValue();
cmdNewLinearReferencing.setVisible(isLineRefActivated);
} catch (final Exception ex) {
if (log.isDebugEnabled()) {
log.debug("error reading LinearReferencedMarks from cismapPluginUIPreferences", ex); // NOI18N
}
}
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public List<Feature> getAllFeaturesSorted() {
return featureControl.getAllFeaturesSorted();
}
/**
* DOCUMENT ME!
*
* @param str DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public PluginUI getUI(final String str) {
return this;
}
/**
* DOCUMENT ME!
*
* @param str DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public PluginMethod getMethod(final String str) {
return pluginMethods.get(str);
}
/**
* DOCUMENT ME!
*
* @param param DOCUMENT ME!
*/
@Override
public void setActive(final boolean param) {
if (log.isDebugEnabled()) {
log.debug("setActive:" + param); // NOI18N
}
if (!param) {
configurationManager.writeConfiguration();
CismapBroker.getInstance().writePropertyFile();
// CismapBroker.getInstance().cleanUpSystemRegistry();
saveLayout(cismapDirectory + fs + pluginLayoutName);
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public java.util.Iterator getUIs() {
final LinkedList ll = new LinkedList();
ll.add(this);
return ll.iterator();
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public PluginProperties getProperties() {
return myPluginProperties;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public java.util.Iterator getMethods() {
return this.pluginMethods.values().iterator();
}
/**
* DOCUMENT ME!
*/
@Override
public void shown() {
}
/**
* DOCUMENT ME!
*/
@Override
public void resized() {
}
/**
* DOCUMENT ME!
*/
@Override
public void moved() {
}
/**
* DOCUMENT ME!
*/
@Override
public void hidden() {
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public java.util.Collection getMenus() {
return menues;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public String getId() {
return "cismap"; // NOI18N
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public JComponent getComponent() {
return panAll;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public java.util.Collection getButtons() {
// return Arrays.asList(this.tobVerdis.getComponents());
return null;
}
/**
* DOCUMENT ME!
*/
@Override
public void floatingStopped() {
}
/**
* DOCUMENT ME!
*/
@Override
public void floatingStarted() {
}
/**
* DOCUMENT ME!
*
* @param b DOCUMENT ME!
*/
@Override
public void setVisible(final boolean b) {
if (plugin) {
final JFrame mainWindow = ComponentRegistry.getRegistry().getMainWindow();
clipboarder = new ClipboardWaitDialog(mainWindow, true);
showObjectsWaitDialog = new ShowObjectsWaitDialog(mainWindow, false);
} else {
super.setVisible(b);
}
}
/**
* DOCUMENT ME!
*/
@Override
public void dispose() {
try {
if (log.isDebugEnabled()) {
log.debug("dispose().CIAO"); // NOI18N
}
saveLayout(cismapDirectory + fs + standaloneLayoutName);
configurationManager.writeConfiguration();
CismapBroker.getInstance().writePropertyFile();
// CismapBroker.getInstance().cleanUpSystemRegistry();
super.dispose();
System.exit(0);
} catch (Throwable t) {
log.fatal("Error during disposing frame.", t); // NOI18N
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public Element getConfiguration() {
final Element ret = new Element("cismapPluginUIPreferences"); // NOI18N
final Element window = new Element("window"); // NOI18N
final int windowHeight = this.getHeight();
final int windowWidth = this.getWidth();
final int windowX = (int)this.getLocation().getX();
final int windowY = (int)this.getLocation().getY();
final boolean windowMaximised = (this.getExtendedState() == MAXIMIZED_BOTH);
if (windowMaximised) {
window.setAttribute("height", "" + (int)oldWindowDimension.getHeight()); // NOI18N
window.setAttribute("width", "" + (int)oldWindowDimension.getWidth()); // NOI18N
window.setAttribute("x", "" + oldWindowPositionX); // NOI18N
window.setAttribute("y", "" + oldWindowPositionY); // NOI18N
} else {
window.setAttribute("height", "" + windowHeight); // NOI18N
window.setAttribute("width", "" + windowWidth); // NOI18N
window.setAttribute("x", "" + windowX); // NOI18N
window.setAttribute("y", "" + windowY); // NOI18N
}
window.setAttribute("max", "" + windowMaximised); // NOI18N
ret.addContent(window);
return ret;
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void masterConfigure(final Element e) {
final Element prefs = e.getChild("cismapPluginUIPreferences"); // NOI18N
cismapPluginUIPreferences = prefs;
activateLineRef();
try {
final Element help_url_element = prefs.getChild("help_url"); // NOI18N
final Element news_url_element = prefs.getChild("news_url"); // NOI18N
final Element httpInterfacePortElement = prefs.getChild("httpInterfacePort"); // NOI18N
try {
httpInterfacePort = new Integer(httpInterfacePortElement.getText());
} catch (Throwable t) {
log.warn("httpInterface was not configured. Set default value: " + httpInterfacePort, t); // NOI18N
}
helpUrl = help_url_element.getText();
if (log.isDebugEnabled()) {
log.debug("helpUrl:" + helpUrl); // NOI18N
}
newsUrl = news_url_element.getText();
} catch (Throwable t) {
log.error("Error while loading the help urls (" + prefs.getChildren() + ")", t); // NOI18N
}
windows2skip = new ArrayList<String>();
try {
final Element windows2SkipElement = e.getChild("skipWindows"); // NOI18N
final Iterator<Element> it = windows2SkipElement.getChildren("skip").iterator(); // NOI18N
while (it.hasNext()) {
final Element next = it.next();
final String id = next.getAttributeValue("windowid"); // NOI18N
windows2skip.add(id);
final View v = viewMap.getView(id);
if (v != null) {
v.close();
}
final JMenuItem menu = viewMenuMap.get(id);
if (menu != null) {
menu.setVisible(false);
}
}
} catch (final Exception x) {
log.info("No skipWindow Info available or error while reading the configuration", x); // NOI18N
}
try {
// Analysieren des FileMenues
final List<Component> before = new ArrayList<Component>();
final List<Component> after = new ArrayList<Component>();
after.add(sepServerProfilesEnd);
final Component[] comps = menFile.getMenuComponents();
List<Component> active = before;
for (final Component comp : comps) {
if (active != null) {
active.add(comp);
}
if ((active == before) && (comp.getName() != null)
&& comp.getName().trim().equals("sepServerProfilesStart")) { // erster Separator//NOI18N
active = null;
} else if ((active == null) && (comp.getName() != null)
&& comp.getName().trim().equals("sepServerProfilesEnd")) { // zweiter Separator//NOI18N
active = after;
}
}
final List<JMenuItem> serverProfileItems = new ArrayList<JMenuItem>();
final Element serverprofiles = e.getChild("serverProfiles"); // NOI18N
final Iterator<Element> it = serverprofiles.getChildren("profile").iterator(); // NOI18N
while (it.hasNext()) {
final Element next = it.next();
final String id = next.getAttributeValue("id"); // NOI18N
final String sorter = next.getAttributeValue("sorter"); // NOI18N
final String name = next.getAttributeValue("name"); // NOI18N
final String path = next.getAttributeValue("path"); // NOI18N
final String icon = next.getAttributeValue("icon"); // NOI18N
final String descr = next.getAttributeValue("descr"); // NOI18N
final String descrWidth = next.getAttributeValue("descrwidth"); // NOI18N
final String complexDescriptionText = next.getTextTrim();
final String complexDescriptionSwitch = next.getAttributeValue("complexdescr"); // NOI18N
final JMenuItem serverProfileMenuItem = new JMenuItem();
serverProfileMenuItem.setText(name);
serverProfileMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
try {
((ActiveLayerModel)mapC.getMappingModel()).removeAllLayers();
configurationManager.configureFromClasspath(path, null);
setButtonSelectionAccordingToMappingComponent();
} catch (Throwable ex) {
log.fatal("No ServerProfile", ex); // NOI18N
}
}
});
serverProfileMenuItem.setName("ServerProfile:" + sorter + ":" + name); // NOI18N
if ((complexDescriptionSwitch != null) && complexDescriptionSwitch.equalsIgnoreCase("true") // NOI18N
&& (complexDescriptionText != null)) {
serverProfileMenuItem.setToolTipText(complexDescriptionText);
} else if (descrWidth != null) {
serverProfileMenuItem.setToolTipText("<html><table width=\"" + descrWidth // NOI18N
+ "\" border=\"0\"><tr><td>" + descr + "</p></td></tr></table></html>"); // NOI18N
} else {
serverProfileMenuItem.setToolTipText(descr);
}
try {
serverProfileMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource(icon)));
} catch (Exception iconE) {
log.warn("Could not create Icon for ServerProfile.", iconE); // NOI18N
}
serverProfileItems.add(serverProfileMenuItem);
}
Collections.sort(serverProfileItems, new Comparator<JMenuItem>() {
@Override
public int compare(final JMenuItem o1, final JMenuItem o2) {
if ((o1.getName() != null) && (o2.getName() != null)) {
return o1.getName().compareTo(o2.getName());
} else {
return 0;
}
}
});
menFile.removeAll();
for (final Component c : before) {
menFile.add(c);
}
for (final JMenuItem jmi : serverProfileItems) {
menFile.add(jmi);
}
for (final Component c : after) {
menFile.add(c);
}
} catch (Exception x) {
log.info("No server profile available, or error while cerating analysis.", x); // NOI18N
}
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void configure(final Element e) {
final Element prefs = e.getChild("cismapPluginUIPreferences"); // NOI18N
cismapPluginUIPreferences = prefs;
activateLineRef();
try {
final Element window = prefs.getChild("window"); // NOI18N
final int windowHeight = window.getAttribute("height").getIntValue(); // NOI18N
final int windowWidth = window.getAttribute("width").getIntValue(); // NOI18N
final int windowX = window.getAttribute("x").getIntValue(); // NOI18N
final int windowY = window.getAttribute("y").getIntValue(); // NOI18N
oldWindowDimension.setSize(windowWidth, windowHeight);
oldWindowPositionX = windowX;
oldWindowPositionY = windowY;
final boolean windowMaximised = window.getAttribute("max").getBooleanValue(); // NOI18N
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
CismapPlugin.this.setSize(windowWidth, windowHeight);
CismapPlugin.this.setLocation(windowX, windowY);
mapC.formComponentResized(null);
if (windowMaximised) {
CismapPlugin.this.setExtendedState(MAXIMIZED_BOTH);
}
}
});
} catch (Throwable t) {
log.error("Error while loading the sie of the window.", t); // NOI18N
}
}
/**
* DOCUMENT ME!
*
* @param file DOCUMENT ME!
*/
public void loadLayout(final String file) {
setupDefaultLayout();
if (log.isDebugEnabled()) {
log.debug("Load Layout.. from " + file); // NOI18N
}
final File layoutFile = new File(file);
if (layoutFile.exists()) {
if (log.isDebugEnabled()) {
log.debug("Layout File exists"); // NOI18N
}
try {
final FileInputStream layoutInput = new FileInputStream(layoutFile);
final ObjectInputStream in = new ObjectInputStream(layoutInput);
rootWindow.read(in);
in.close();
rootWindow.getWindowBar(Direction.LEFT).setEnabled(true);
rootWindow.getWindowBar(Direction.DOWN).setEnabled(true);
rootWindow.getWindowBar(Direction.RIGHT).setEnabled(true);
if (log.isDebugEnabled()) {
log.debug("Loading Layout successfull"); // NOI18N
}
} catch (IOException ex) {
log.error("Layout File IO Exception --> loading default Layout", ex); // NOI18N
if (isInit) {
JOptionPane.showMessageDialog(
this,
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.loadLayout(String).JOptionPane.message1"), // NOI18N
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.loadLayout(String).JOptionPane.title"), // NOI18N
JOptionPane.INFORMATION_MESSAGE);
setupDefaultLayout();
} else {
JOptionPane.showMessageDialog(
this,
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.loadLayout(String).JOptionPane.message2"), // NOI18N
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.loadLayout(String).JOptionPane.title"), // NOI18N
JOptionPane.INFORMATION_MESSAGE);
}
}
} else {
if (isInit) {
log.fatal("File does not exist --> default layout (init)"); // NOI18N
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
// UGLY WINNING --> Gefixed durch IDW Version 1.5
// setupDefaultLayout();
// DeveloperUtil.createWindowLayoutFrame("nach setup1",rootWindow).setVisible(true);
setupDefaultLayout();
// DeveloperUtil.createWindowLayoutFrame("nach setup2",rootWindow).setVisible(true);
}
});
} else {
log.fatal("File does not exist)"); // NOI18N
JOptionPane.showMessageDialog(
this,
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.loadLayout(String).JOptionPane.message3"), // NOI18N
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.loadLayout(String).JOptionPane.title"), // NOI18N
JOptionPane.INFORMATION_MESSAGE);
}
}
}
/**
* DOCUMENT ME!
*
* @param file DOCUMENT ME!
*/
public void saveLayout(final String file) {
if (log.isDebugEnabled()) {
log.debug("Saving Layout.. to " + file, new CurrentStackTrace()); // NOI18N
}
final File layoutFile = new File(file);
try {
if (!layoutFile.exists()) {
if (log.isDebugEnabled()) {
log.debug("Saving Layout.. File does not exit"); // NOI18N
}
layoutFile.createNewFile();
} else {
if (log.isDebugEnabled()) {
log.debug("Saving Layout.. File does exit"); // NOI18N
}
}
final FileOutputStream layoutOutput = new FileOutputStream(layoutFile);
final ObjectOutputStream out = new ObjectOutputStream(layoutOutput);
rootWindow.write(out);
out.flush();
out.close();
if (log.isDebugEnabled()) {
log.debug("Saving Layout.. to " + file + " successfull"); // NOI18N
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(
this,
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.saveLayout(String).JOptionPane.message"), // NOI18N
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.saveLayout(String).JOptionPane.title"), // NOI18N
JOptionPane.INFORMATION_MESSAGE);
log.error("A failure occured during writing the layout file", ex); // NOI18N
}
}
/**
* DOCUMENT ME!
*
* @param mse DOCUMENT ME!
*/
@Override
public void mapSearchStarted(final MapSearchEvent mse) {
initMetaSearch(mse.getGeometry());
}
/**
* DOCUMENT ME!
*
* @param geom DOCUMENT ME!
*/
private void initMetaSearch(final Geometry geom) {
if (log.isDebugEnabled()) {
log.debug("selected Search Classes " + metaSearch.getSelectedSearchClassesForQuery()); // NOI18N
}
final Geometry transformed = CrsTransformer.transformToDefaultCrs(geom);
// Damits auch mit -1 funzt:
transformed.setSRID(CismapBroker.getInstance().getDefaultCrsAlias());
final GeoSearch gs = new GeoSearch(transformed);
gs.setValidClassesFromStrings(metaSearch.getSelectedSearchClassesForQuery());
CidsSearchExecutor.searchAndDisplayResultsWithDialog(gs);
}
/**
* DOCUMENT ME!
*
* @param mde DOCUMENT ME!
*/
@Override
public void dropOnMap(final MapDnDEvent mde) {
if (log.isDebugEnabled()) {
log.debug("drop on map"); // NOI18N
}
if (mde.getDte() instanceof DropTargetDropEvent) {
final DropTargetDropEvent dtde = (DropTargetDropEvent)mde.getDte();
if (dtde.getTransferable().isDataFlavorSupported(fromCapabilityWidget)) {
activeLayers.drop(dtde);
} else if (dtde.getTransferable().isDataFlavorSupported(fromNavigatorNode)
&& dtde.getTransferable().isDataFlavorSupported(fromNavigatorCollection)) {
// Drop von MetaObjects
try {
final Object object = dtde.getTransferable().getTransferData(fromNavigatorCollection);
if (object instanceof Collection) {
final Collection c = (Collection)object;
showObjectsMethod.invoke(c);
}
} catch (Throwable t) {
log.fatal("Error on drop", t); // NOI18N
}
} else if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)
|| dtde.isDataFlavorSupported(DnDUtils.URI_LIST_FLAVOR)) {
activeLayers.drop((DropTargetDropEvent)mde.getDte());
} else {
JOptionPane.showMessageDialog(
this,
org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.dropOnMap(MapDnDEvent).JOptionPane.message")); // NOI18N
log.error("Unable to process the datatype." + dtde.getTransferable().getTransferDataFlavors()[0]); // NOI18N
}
}
}
/**
* DOCUMENT ME!
*
* @param c DOCUMENT ME!
* @param editable DOCUMENT ME!
*
* @throws Exception DOCUMENT ME!
*/
public void showInMap(final Collection c, final boolean editable) throws Exception {
showObjectsMethod.invoke(c, editable);
}
/**
* DOCUMENT ME!
*
* @param mo DOCUMENT ME!
* @param editable DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws Exception DOCUMENT ME!
*/
public CidsFeature showInMap(final MetaObject mo, final boolean editable) throws Exception {
return showObjectsMethod.invoke(mo, editable);
}
/**
* DOCUMENT ME!
*
* @param mde DOCUMENT ME!
*/
@Override
public void dragOverMap(final MapDnDEvent mde) {
}
/**
* DOCUMENT ME!
*/
private void setButtonSelectionAccordingToMappingComponent() {
if (mapC.getInteractionMode().equals(MappingComponent.ZOOM)) {
if (!cmdZoom.isSelected()) {
cmdZoom.setSelected(true);
}
} else if (mapC.getInteractionMode().equals(MappingComponent.PAN)) {
if (!cmdPan.isSelected()) {
cmdPan.setSelected(true);
}
} else if (mapC.getInteractionMode().equals(MappingComponent.FEATURE_INFO)) {
if (!cmdFeatureInfo.isSelected()) {
cmdFeatureInfo.setSelected(true);
}
} else if (mapC.getInteractionMode().equals(MappingComponent.CREATE_SEARCH_POLYGON)) {
if (!cmdPluginSearch.isSelected()) {
cmdPluginSearch.setSelected(true);
}
} else if (mapC.getInteractionMode().equals(MappingComponent.SELECT)) {
if (!cmdSelect.isSelected()) {
cmdSelect.setSelected(true);
}
// } else if (mapC.getInteractionMode().equals(MappingComponent.LINEAR_REFERENCING)) {
// if (!cmdMeasurement.isSelected()) {
// cmdMeasurement.setSelected(true);
// }
} else if (mapC.getInteractionMode().equals(MappingComponent.NEW_POLYGON)) {
if (((CreateNewGeometryListener)mapC.getInputListener(MappingComponent.NEW_POLYGON)).isInMode(
CreateGeometryListenerInterface.POLYGON)) {
if (!cmdNewPolygon.isSelected()) {
cmdNewPolygon.setSelected(true);
}
} else if (((CreateNewGeometryListener)mapC.getInputListener(MappingComponent.NEW_POLYGON)).isInMode(
CreateGeometryListenerInterface.LINESTRING)) {
if (!cmdNewLinestring.isSelected()) {
cmdNewLinestring.setSelected(true);
}
} else if (((CreateNewGeometryListener)mapC.getInputListener(MappingComponent.NEW_POLYGON)).isInMode(
CreateGeometryListenerInterface.POINT)) {
if (!cmdNewPoint.isSelected()) {
cmdNewPoint.setSelected(true);
}
}
} else if (mapC.getInteractionMode().equals(MappingComponent.MOVE_POLYGON)) {
if (!cmdMoveGeometry.isSelected()) {
cmdMoveGeometry.setSelected(true);
}
} else if (mapC.getInteractionMode().equals(MappingComponent.REMOVE_POLYGON)) {
if (!cmdRemoveGeometry.isSelected()) {
cmdRemoveGeometry.setSelected(true);
}
} else if (mapC.getInteractionMode().equals(MappingComponent.LINEAR_REFERENCING)) {
cmdNewLinearReferencing.setSelected(true);
}
if (mapC.getHandleInteractionMode().equals(MappingComponent.MOVE_HANDLE)) {
if (!cmdNodeMove.isSelected()) {
cmdNodeMove.setSelected(true);
}
} else if (mapC.getHandleInteractionMode().equals(MappingComponent.ADD_HANDLE)) {
if (!cmdNodeAdd.isSelected()) {
cmdNodeAdd.setSelected(true);
}
} else if (mapC.getHandleInteractionMode().equals(MappingComponent.REMOVE_HANDLE)) {
if (!cmdNodeRemove.isSelected()) {
cmdNodeRemove.setSelected(true);
}
} else if (mapC.getHandleInteractionMode().equals(MappingComponent.ROTATE_POLYGON)) {
if (!cmdNodeRemove.isSelected()) {
cmdNodeRotateGeometry.setSelected(true);
}
}
if (mapC.isSnappingEnabled()) {
if (!cmdSnap.isSelected()) {
cmdSnap.setSelected(true);
}
} else {
if (cmdSnap.isSelected()) {
cmdSnap.setSelected(false);
}
}
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void statusValueChanged(final StatusEvent e) {
if (e.getName().equals(StatusEvent.MAPPING_MODE)) {
// besser nur aufrufen wenn falsch
setButtonSelectionAccordingToMappingComponent();
}
}
/**
* DOCUMENT ME!
*/
@Override
public void historyChanged() {
final List backPos = mapC.getBackPossibilities();
final List forwPos = mapC.getForwardPossibilities();
if (menHistory != null) {
menHistory.removeAll();
menHistory.add(mniBack);
menHistory.add(mniForward);
menHistory.add(mniHome);
menHistory.add(sepBeforePos);
int counter = 0;
int start = 0;
if ((backPos.size() - 10) > 0) {
start = backPos.size() - 10;
}
for (int index = start; index < backPos.size(); ++index) {
final Object elem = backPos.get(index);
final JMenuItem item = new JMenuItem(elem.toString());
item.setIcon(miniBack);
final int pos = backPos.size() - 1 - index;
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
for (int i = 0; i < pos; ++i) {
mapC.back(false);
}
mapC.back(true);
}
});
menHistory.add(item);
}
final JMenuItem currentItem = new JMenuItem(mapC.getCurrentElement().toString());
currentItem.setEnabled(false);
currentItem.setIcon(current);
menHistory.add(currentItem);
counter = 0;
for (int index = forwPos.size() - 1; index >= 0; --index) {
final Object elem = forwPos.get(index);
final JMenuItem item = new JMenuItem(elem.toString()); // +":"+new Integer(forwPos.size()-1-index));
item.setIcon(miniForward);
final int pos = forwPos.size() - 1 - index;
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
for (int i = 0; i < pos; ++i) {
mapC.forward(false);
}
mapC.forward(true);
}
});
menHistory.add(item);
if (counter++ > 10) {
break;
}
}
menHistory.add(sepAfterPos);
menHistory.add(mniHistorySidebar);
}
}
/**
* DOCUMENT ME!
*/
@Override
public void historyActionPerformed() {
log.fatal("historyActionPerformed"); // NOI18N
}
/**
* DOCUMENT ME!
*/
@Override
public void forwardStatusChanged() {
mniForward.setEnabled(mapC.isForwardPossible());
}
/**
* DOCUMENT ME!
*/
@Override
public void backStatusChanged() {
mniBack.setEnabled(mapC.isBackPossible());
}
/**
* DOCUMENT ME!
*
* @param fce DOCUMENT ME!
*/
@Override
public void featuresRemoved(final FeatureCollectionEvent fce) {
for (final Feature feature : fce.getEventFeatures()) {
final DefaultMetaTreeNode node = featuresInMapReverse.get(feature);
if (node != null) {
featuresInMapReverse.remove(feature);
featuresInMap.remove(node);
}
}
}
/**
* DOCUMENT ME!
*
* @param fce DOCUMENT ME!
*/
@Override
public void featuresChanged(final FeatureCollectionEvent fce) {
}
/**
* DOCUMENT ME!
*
* @param fce DOCUMENT ME!
*/
@Override
public void featuresAdded(final FeatureCollectionEvent fce) {
}
/**
* DOCUMENT ME!
*
* @param fce DOCUMENT ME!
*/
@Override
public void featureSelectionChanged(final FeatureCollectionEvent fce) {
if (plugin && !featureCollectionEventBlocker) {
final Collection<Feature> fc = new ArrayList<Feature>(mapC.getFeatureCollection().getSelectedFeatures());
final List<DefaultMutableTreeNode> nodeVector = new ArrayList<DefaultMutableTreeNode>();
for (final Feature f : fc) {
if ((f instanceof CidsFeature) || (f instanceof FeatureGroup)) {
nodeVector.add(featuresInMapReverse.get(f));
}
}
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
nodeSelectionEventBlocker = true;
// Baumselektion wird hier propagiert
ComponentRegistry.getRegistry().getActiveCatalogue().setSelectedNodes(nodeVector, true);
nodeSelectionEventBlocker = false;
}
});
}
}
/**
* DOCUMENT ME!
*
* @param fce DOCUMENT ME!
*/
@Override
public void featureReconsiderationRequested(final FeatureCollectionEvent fce) {
}
/**
* DOCUMENT ME!
*
* @param fce DOCUMENT ME!
*/
@Override
public void allFeaturesRemoved(final FeatureCollectionEvent fce) {
featuresInMap.clear();
featuresInMapReverse.clear();
}
/**
* DOCUMENT ME!
*/
private void initHttpServer() {
try {
final Thread http = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1500); // Bugfix Try Deadlock
if (log.isDebugEnabled()) {
log.debug("Http Interface initialisieren"); // NOI18N
}
final Server server = new Server();
final Connector connector = new SelectChannelConnector();
connector.setPort(9098);
server.setConnectors(new Connector[] { connector });
final Handler param = new AbstractHandler() {
@Override
public void handle(final String target,
final HttpServletRequest request,
final HttpServletResponse response,
final int dispatch) throws IOException, ServletException {
final Request base_request = (request instanceof Request)
? (Request)request : HttpConnection.getCurrentConnection().getRequest();
base_request.setHandled(true);
response.setContentType("text/html"); // NOI18N
response.setStatus(HttpServletResponse.SC_ACCEPTED);
response.getWriter()
.println(
"<html><head><title>HTTP interface</title></head><body><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"80%\"><tr><td width=\"30%\" align=\"center\" valign=\"middle\"><img border=\"0\" src=\"http://www.cismet.de/images/cismetLogo250M.png\" ><br></td><td width=\"%\"> </td><td width=\"50%\" align=\"left\" valign=\"middle\"><font face=\"Arial\" size=\"3\" color=\"#1c449c\">... and <b><font face=\"Arial\" size=\"3\" color=\"#1c449c\">http://</font></b> just works</font><br><br><br></td></tr></table></body></html>"); // NOI18N
}
};
final Handler hello = new AbstractHandler() {
@Override
public void handle(final String target,
final HttpServletRequest request,
final HttpServletResponse response,
final int dispatch) throws IOException, ServletException {
try {
if (request.getLocalAddr().equals(request.getRemoteAddr())) {
log.info("HttpInterface connected"); // NOI18N
if (target.equalsIgnoreCase("/gotoBoundingBox")) { // NOI18N
final String x1 = request.getParameter("x1"); // NOI18N
final String y1 = request.getParameter("y1"); // NOI18N
final String x2 = request.getParameter("x2"); // NOI18N
final String y2 = request.getParameter("y2"); // NOI18N
try {
final BoundingBox bb = new BoundingBox(
new Double(x1),
new Double(y1),
new Double(x2),
new Double(y2));
mapC.gotoBoundingBoxWithHistory(bb);
} catch (Exception e) {
log.warn("gotoBoundingBox failed", e); // NOI18N
}
}
if (target.equalsIgnoreCase("/gotoScale")) { // NOI18N
final String x1 = request.getParameter("x1"); // NOI18N
final String y1 = request.getParameter("y1"); // NOI18N
final String scaleDenominator = request.getParameter(
"scaleDenominator"); // NOI18N
try {
final BoundingBox bb = new BoundingBox(
new Double(x1),
new Double(y1),
new Double(x1),
new Double(y1));
mapC.gotoBoundingBoxWithHistory(
mapC.getScaledBoundingBox(
new Double(scaleDenominator).doubleValue(),
bb));
} catch (Exception e) {
log.warn("gotoBoundingBox failed", e); // NOI18N
}
}
if (target.equalsIgnoreCase("/centerOnPoint")) { // NOI18N
final String x1 = request.getParameter("x1"); // NOI18N
final String y1 = request.getParameter("y1"); // NOI18N
try {
final BoundingBox bb = new BoundingBox(
new Double(x1),
new Double(y1),
new Double(x1),
new Double(y1));
mapC.gotoBoundingBoxWithHistory(bb);
} catch (Exception e) {
log.warn("centerOnPoint failed", e); // NOI18N
}
} else {
log.warn("Unknown target: " + target); // NOI18N
}
} else {
log.warn(
"Someone tries to access the http interface from an other computer. Access denied."); // NOI18N
}
} catch (Throwable t) {
log.error("Error while handle http requests", t); // NOI18N
}
}
};
final HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers(new Handler[] { param, hello });
server.setHandler(handlers);
server.start();
server.join();
} catch (Throwable t) {
log.error("Error in the HttpInterface of cismap", t); // NOI18N
}
}
});
http.start();
if (log.isDebugEnabled()) {
log.debug("Initialise HTTP interface"); // NOI18N
}
} catch (Throwable t) {
log.fatal("Nothing at all", t); // NOI18N
}
}
/**
* DOCUMENT ME!
*/
@Override
public void featureCollectionChanged() {
}
/**
* DOCUMENT ME!
*
* @param o DOCUMENT ME!
* @param arg DOCUMENT ME!
*/
@Override
public void update(final Observable o, final Object arg) {
if (o.equals(mapC.getMemUndo())) {
if (arg.equals(MementoInterface.ACTIVATE) && !cmdUndo.isEnabled()) {
if (log.isDebugEnabled()) {
log.debug("activate UNDO button"); // NOI18N
}
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
cmdUndo.setEnabled(true);
}
});
} else if (arg.equals(MementoInterface.DEACTIVATE) && cmdUndo.isEnabled()) {
if (log.isDebugEnabled()) {
log.debug("deactivate UNDO button"); // NOI18N
}
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
cmdUndo.setEnabled(false);
}
});
}
} else if (o.equals(mapC.getMemRedo())) {
if (arg.equals(MementoInterface.ACTIVATE) && !cmdRedo.isEnabled()) {
if (log.isDebugEnabled()) {
log.debug("activate REDO button"); // NOI18N
}
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
cmdRedo.setEnabled(true);
}
});
} else if (arg.equals(MementoInterface.DEACTIVATE) && cmdRedo.isEnabled()) {
if (log.isDebugEnabled()) {
log.debug("deactivate REDO button"); // NOI18N
}
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
cmdRedo.setEnabled(false);
}
});
}
}
}
/**
* DOCUMENT ME!
*/
protected void visualizeSearchMode() {
final MetaSearchCreateSearchGeometryListener searchListener = (MetaSearchCreateSearchGeometryListener)
mapC.getInputListener(
MappingComponent.CREATE_SEARCH_POLYGON);
final String searchMode = searchListener.getMode();
final PureNewFeature lastGeometry = searchListener.getLastSearchFeature();
if (MetaSearchCreateSearchGeometryListener.RECTANGLE.equals(searchMode)) {
cmdPluginSearch.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/images/pluginSearchRectangle.png"))); // NOI18N
cmdPluginSearch.setSelectedIcon(new javax.swing.ImageIcon(
getClass().getResource("/images/pluginSearchRectangle.png"))); // NOI18N
} else if (MetaSearchCreateSearchGeometryListener.POLYGON.equals(searchMode)) {
cmdPluginSearch.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/images/pluginSearchPolygon.png"))); // NOI18N
cmdPluginSearch.setSelectedIcon(new javax.swing.ImageIcon(
getClass().getResource("/images/pluginSearchPolygon.png"))); // NOI18N
} else if (MetaSearchCreateSearchGeometryListener.ELLIPSE.equals(searchMode)) {
cmdPluginSearch.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/images/pluginSearchEllipse.png"))); // NOI18N
cmdPluginSearch.setSelectedIcon(new javax.swing.ImageIcon(
getClass().getResource("/images/pluginSearchEllipse.png"))); // NOI18N
} else if (MetaSearchCreateSearchGeometryListener.LINESTRING.equals(searchMode)) {
cmdPluginSearch.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/images/pluginSearchPolyline.png"))); // NOI18N
cmdPluginSearch.setSelectedIcon(new javax.swing.ImageIcon(
getClass().getResource("/images/pluginSearchPolyline.png"))); // NOI18N
}
mniSearchRectangle.setSelected(MetaSearchCreateSearchGeometryListener.RECTANGLE.equals(searchMode));
mniSearchPolygon.setSelected(MetaSearchCreateSearchGeometryListener.POLYGON.equals(searchMode));
mniSearchEllipse.setSelected(MetaSearchCreateSearchGeometryListener.ELLIPSE.equals(searchMode));
mniSearchPolyline.setSelected(MetaSearchCreateSearchGeometryListener.LINESTRING.equals(searchMode));
if (lastGeometry == null) {
mniSearchShowLastFeature.setIcon(null);
mniSearchShowLastFeature.setEnabled(false);
mniSearchRedo.setIcon(null);
mniSearchRedo.setEnabled(false);
mniSearchBuffer.setEnabled(false);
} else {
switch (lastGeometry.getGeometryType()) {
case ELLIPSE: {
mniSearchRedo.setIcon(mniSearchEllipse.getIcon());
break;
}
case LINESTRING: {
mniSearchRedo.setIcon(mniSearchPolyline.getIcon());
break;
}
case POLYGON: {
mniSearchRedo.setIcon(mniSearchPolygon.getIcon());
break;
}
case RECTANGLE: {
mniSearchRedo.setIcon(mniSearchRectangle.getIcon());
break;
}
}
mniSearchRedo.setEnabled(true);
mniSearchBuffer.setEnabled(true);
mniSearchShowLastFeature.setIcon(mniSearchRedo.getIcon());
mniSearchShowLastFeature.setEnabled(true);
}
// kopieren nach popupmenu im grünen M
mniSearchRectangle1.setSelected(mniSearchRectangle.isSelected());
mniSearchPolygon1.setSelected(mniSearchPolygon.isSelected());
mniSearchEllipse1.setSelected(mniSearchEllipse.isSelected());
mniSearchPolyline1.setSelected(mniSearchPolyline.isSelected());
mniSearchRedo1.setIcon(mniSearchRedo.getIcon());
mniSearchRedo1.setEnabled(mniSearchRedo.isEnabled());
mniSearchBuffer1.setEnabled(mniSearchBuffer.isEnabled());
mniSearchShowLastFeature1.setIcon(mniSearchShowLastFeature.getIcon());
mniSearchShowLastFeature1.setEnabled(mniSearchShowLastFeature.isEnabled());
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
@Override
public void propertyChange(final PropertyChangeEvent evt) {
if (MetaSearchCreateSearchGeometryListener.PROPERTY_FORGUI_LAST_FEATURE.equals(evt.getPropertyName())
|| MetaSearchCreateSearchGeometryListener.PROPERTY_FORGUI_MODE.equals(evt.getPropertyName())
|| MetaSearchCreateSearchGeometryListener.PROPERTY_MODE.equals(evt.getPropertyName())) {
visualizeSearchMode();
}
}
//~ Inner Classes ----------------------------------------------------------
/**
* DOCUMENT ME!
*
* @author $author$
* @version $Revision$, $Date$
*/
class ShutdownHook extends Thread {
//~ Methods ------------------------------------------------------------
/**
* DOCUMENT ME!
*/
@Override
public void run() {
if (log.isDebugEnabled()) {
log.debug("CIAO"); // NOI18N
}
configurationManager.writeConfiguration();
CismapBroker.getInstance().writePropertyFile();
if (log.isDebugEnabled()) {
log.debug("Shutdownhook --> saving layout"); // NOI18N
}
saveLayout(cismapDirectory + fs + standaloneLayoutName);
}
}
/**
* DOCUMENT ME!
*
* @author $author$
* @version $Revision$, $Date$
*/
private class NodeChangeListener extends MetaNodeSelectionListener {
//~ Instance fields ----------------------------------------------------
private final SingleAttributeIterator attributeIterator;
private final Collection classNames;
private final Collection attributeNames;
//~ Constructors -------------------------------------------------------
/**
* Creates a new NodeChangeListener object.
*/
private NodeChangeListener() {
this.classNames = context.getEnvironment().getAttributeMappings("className"); // NOI18N
this.attributeNames = context.getEnvironment().getAttributeMappings("attributeName"); // NOI18N
if (this.attributeNames.size() == 0) {
this.attributeNames.add("id"); // NOI18N
}
final AttributeRestriction attributeRestriction = new ComplexAttributeRestriction(
AttributeRestriction.OBJECT,
AttributeRestriction.IGNORE,
null,
this.attributeNames,
null);
this.attributeIterator = new SingleAttributeIterator(attributeRestriction, false);
}
//~ Methods ------------------------------------------------------------
// TODO: WTF?
/**
* DOCUMENT ME!
*
* @param wirdNichtGebrauchtWeilScheissevonPascalgefuelltCollection DOCUMENT ME!
*/
@Override
protected void nodeSelectionChanged(
final Collection wirdNichtGebrauchtWeilScheissevonPascalgefuelltCollection) {
if (!nodeSelectionEventBlocker) {
try {
final Collection c = context.getMetadata().getSelectedNodes();
if ((c != null) && !(c.isEmpty())) {
if (featureControl.isWizardMode()) {
showObjectsMethod.invoke(c);
} else {
final Object[] nodes = c.toArray();
boolean oneHit = false;
final List<Feature> features = new ArrayList<Feature>();
for (final Object o : nodes) {
if (o instanceof DefaultMetaTreeNode) {
final DefaultMetaTreeNode node = (DefaultMetaTreeNode)o;
if (featuresInMap.containsKey(node)) {
oneHit = true;
features.add(featuresInMap.get(node));
}
}
}
if (oneHit) {
featureCollectionEventBlocker = true;
mapC.getFeatureCollection().select(features);
featureCollectionEventBlocker = false;
} else {
featureCollectionEventBlocker = true;
mapC.getFeatureCollection().unselectAll();
featureCollectionEventBlocker = false;
if (log.isDebugEnabled()) {
log.debug("featuresInMap:" + featuresInMap); // NOI18N
}
}
}
}
} catch (final Exception t) {
log.error("Error in WizardMode:", t); // NOI18N
}
}
}
}
/**
* DOCUMENT ME!
*
* @author $author$
* @version $Revision$, $Date$
*/
private class ShowObjectsMethod implements PluginMethod {
//~ Methods ------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @throws Exception DOCUMENT ME!
*/
@Override
public void invoke() throws Exception {
final Collection selectedNodes = context.getMetadata().getSelectedNodes();
invoke(selectedNodes);
}
/**
* DOCUMENT ME!
*
* @param nodes DOCUMENT ME!
*
* @throws Exception DOCUMENT ME!
*/
public void invoke(final Collection nodes) throws Exception {
invoke(nodes, false);
}
/**
* DOCUMENT ME!
*
* @param mo DOCUMENT ME!
* @param editable DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws Exception DOCUMENT ME!
*/
public synchronized CidsFeature invoke(final MetaObject mo, final boolean editable) throws Exception {
final CidsFeature cidsFeature = new CidsFeature(mo);
invoke(cidsFeature, editable);
return cidsFeature;
}
/**
* DOCUMENT ME!
*
* @param cidsFeature DOCUMENT ME!
* @param editable DOCUMENT ME!
*
* @throws Exception DOCUMENT ME!
*/
private void invoke(final CidsFeature cidsFeature, final boolean editable) throws Exception {
final List<Feature> v = new ArrayList<Feature>();
cidsFeature.setEditable(editable);
v.add(cidsFeature);
if (log.isDebugEnabled()) {
log.debug("mapC.getFeatureCollection().getAllFeatures():" // NOI18N
+ mapC.getFeatureCollection().getAllFeatures());
}
if (log.isDebugEnabled()) {
log.debug("cidsFeature:" + cidsFeature); // NOI18N
log.debug("mapC.getFeatureCollection().getAllFeatures().contains(cidsFeature):"
+ mapC.getFeatureCollection().getAllFeatures().contains(cidsFeature)); // NOI18N
}
mapC.getFeatureLayer().setVisible(true);
mapC.getFeatureCollection().removeFeature(cidsFeature);
if (log.isDebugEnabled()) {
log.debug("mapC.getFeatureCollection().getAllFeatures():" // NOI18N
+ mapC.getFeatureCollection().getAllFeatures());
}
mapC.getFeatureCollection().substituteFeatures(v);
if (editable) {
mapC.getFeatureCollection().select(v);
}
if (!mapC.isFixedMapExtent()) {
mapC.zoomToFeatureCollection(mapC.isFixedMapScale());
mapC.showHandles(true);
}
}
/**
* DOCUMENT ME!
*
* @param node DOCUMENT ME!
* @param oAttr DOCUMENT ME!
* @param editable DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws Exception DOCUMENT ME!
*/
public synchronized CidsFeature invoke(final DefaultMetaTreeNode node,
final ObjectAttribute oAttr,
final boolean editable) throws Exception {
final MetaObject loader = ((ObjectTreeNode)node).getMetaObject();
final MetaObjectNode mon = ((ObjectTreeNode)node).getMetaObjectNode();
CidsFeature cidsFeature = invoke(loader, editable);
if (oAttr != null) {
cidsFeature = new CidsFeature(mon, oAttr);
} else {
cidsFeature = new CidsFeature(mon);
}
featuresInMap.put(node, cidsFeature);
featuresInMapReverse.put(cidsFeature, node);
invoke(cidsFeature, editable);
return cidsFeature;
}
/**
* DOCUMENT ME!
*
* @param nodes DOCUMENT ME!
* @param editable DOCUMENT ME!
*
* @throws Exception DOCUMENT ME!
*/
public synchronized void invoke(final Collection<DefaultMetaTreeNode> nodes, final boolean editable)
throws Exception {
log.info("invoke shows objects in the map"); // NOI18N
final Runnable showWaitRunnable = new Runnable() {
@Override
public void run() {
StaticSwingTools.showDialog(showObjectsWaitDialog);
final SwingWorker<List<Feature>, Void> addToMapWorker = new SwingWorker<List<Feature>, Void>() {
private Map<DefaultMetaTreeNode, CidsFeature> tmpFeaturesInMap = null;
private Map<Feature, DefaultMetaTreeNode> tmpFeaturesInMapReverse = null;
@Override
protected List<Feature> doInBackground() throws Exception {
final Iterator<DefaultMetaTreeNode> mapIter = featuresInMap.keySet().iterator();
while (mapIter.hasNext()) {
final DefaultMetaTreeNode node = mapIter.next();
final Feature f = featuresInMap.get(node);
if (!mapC.getFeatureCollection().isHoldFeature(f)) {
mapIter.remove();
featuresInMapReverse.remove(f);
}
}
final List<Feature> v = new ArrayList<Feature>();
for (final DefaultMetaTreeNode node : nodes) {
final MetaObjectNode mon = ((ObjectTreeNode)node).getMetaObjectNode();
MetaObject mo = mon.getObject();
if (mo == null) {
mo = ((ObjectTreeNode)node).getMetaObject();
}
final CidsFeature cidsFeature = new CidsFeature(mo);
cidsFeature.setEditable(editable);
final List<Feature> allFeaturesToAdd = new ArrayList<Feature>(
FeatureGroups.expandAll(cidsFeature));
if (log.isDebugEnabled()) {
log.debug("allFeaturesToAdd:" + allFeaturesToAdd); // NOI18N
}
if (!(featuresInMap.containsValue(cidsFeature))) {
v.addAll(allFeaturesToAdd);
// node -> masterfeature
featuresInMap.put(node, cidsFeature);
for (final Feature feature : allFeaturesToAdd) {
// master and all subfeatures -> node
featuresInMapReverse.put(feature, node);
}
if (log.isDebugEnabled()) {
log.debug("featuresInMap.put(node,cidsFeature):" + node + "," // NOI18Ns
+ cidsFeature);
}
}
}
tmpFeaturesInMap = new HashMap<DefaultMetaTreeNode, CidsFeature>(featuresInMap);
tmpFeaturesInMapReverse = new HashMap<Feature, DefaultMetaTreeNode>(
featuresInMapReverse);
return v;
}
@Override
protected void done() {
try {
showObjectsWaitDialog.setVisible(false);
final List<Feature> v = get();
mapC.getFeatureLayer().setVisible(true);
mapC.getFeatureCollection().substituteFeatures(v);
featuresInMap.clear();
featuresInMap.putAll(tmpFeaturesInMap);
featuresInMapReverse.clear();
featuresInMapReverse.putAll(tmpFeaturesInMapReverse);
if (!mapC.isFixedMapExtent()) {
mapC.zoomToFeatureCollection(mapC.isFixedMapScale());
}
} catch (final InterruptedException e) {
if (log.isDebugEnabled()) {
log.debug(e, e);
}
} catch (final Exception e) {
log.error("Error while displaying objects:", e); // NOI18N
}
}
};
CismetThreadPool.execute(addToMapWorker);
}
};
if (EventQueue.isDispatchThread()) {
showWaitRunnable.run();
} else {
EventQueue.invokeLater(showWaitRunnable);
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public String getId() {
return this.getClass().getName();
}
}
/**
* DOCUMENT ME!
*
* @author $author$
* @version $Revision$, $Date$
*/
class MyPluginProperties implements PluginProperties {
//~ Methods ------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @param propertyName DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public Object getProperty(final String propertyName) {
if (log.isDebugEnabled()) {
log.debug("GetProperty was invoked from CismapPlugin"); // NOI18N
}
if (propertyName.equalsIgnoreCase("coordinate")) { // NOI18N
// hier erwartet der Navigator ein double[][] mit allen Punkten
final double[][] pointCoordinates = new double[4][2];
// x1 y1
pointCoordinates[0][0] = mapC.getCurrentBoundingBox().getX1();
pointCoordinates[0][1] = mapC.getCurrentBoundingBox().getY1();
// x2 y1
pointCoordinates[1][0] = mapC.getCurrentBoundingBox().getX2();
pointCoordinates[1][1] = mapC.getCurrentBoundingBox().getY1();
// x2 y2
pointCoordinates[2][0] = mapC.getCurrentBoundingBox().getX2();
pointCoordinates[2][1] = mapC.getCurrentBoundingBox().getY2();
// x1 y2
pointCoordinates[3][0] = mapC.getCurrentBoundingBox().getX1();
pointCoordinates[3][1] = mapC.getCurrentBoundingBox().getY2();
return pointCoordinates;
} else if (propertyName.equalsIgnoreCase("coordinateString")) { // NOI18N
return "(" // NOI18N
+ mapC.getCurrentBoundingBox().getX1() + "," // NOI18N
+ mapC.getCurrentBoundingBox().getX1() + ") (" // NOI18N
+ mapC.getCurrentBoundingBox().getX2() + "," // NOI18N
+ mapC.getCurrentBoundingBox().getX2() + ") (" // NOI18N
+ mapC.getCurrentBoundingBox().getX2() + "," // NOI18N
+ mapC.getCurrentBoundingBox().getY2() + ") (" // NOI18N
+ mapC.getCurrentBoundingBox().getX1() + "," // NOI18N
+ mapC.getCurrentBoundingBox().getY2() + ")"; // NOI18N
} else if (propertyName.equalsIgnoreCase("ogcFeatureString")) { // NOI18N
mapC.getCurrentBoundingBox().getGeometryFromTextCompatibleString();
}
return null;
}
/**
* DOCUMENT ME!
*
* @param propertyName DOCUMENT ME!
* @param value DOCUMENT ME!
*/
@Override
public void setProperty(final String propertyName, final Object value) {
}
/**
* DOCUMENT ME!
*
* @param listener DOCUMENT ME!
*/
@Override
public void addPropertyChangeListener(final PropertyChangeListener listener) {
}
/**
* DOCUMENT ME!
*
* @param propertyName DOCUMENT ME!
* @param listener DOCUMENT ME!
*/
@Override
public void addPropertyChangeListener(final String propertyName, final PropertyChangeListener listener) {
}
/**
* DOCUMENT ME!
*
* @param listener DOCUMENT ME!
*/
@Override
public void removePropertyChangeListener(final PropertyChangeListener listener) {
}
/**
* DOCUMENT ME!
*
* @param propertyName DOCUMENT ME!
* @param listener DOCUMENT ME!
*/
@Override
public void removePropertyChangeListener(final String propertyName, final PropertyChangeListener listener) {
}
}
}
/**
* DOCUMENT ME!
*
* @author $author$
* @version $Revision$, $Date$
*/
class GeoLinkUrl implements Transferable {
//~ Instance fields --------------------------------------------------------
String url;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new GeoLinkUrl object.
*
* @param url DOCUMENT ME!
*/
public GeoLinkUrl(final String url) {
this.url = url;
}
//~ Methods ----------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { DataFlavor.stringFlavor };
}
/**
* DOCUMENT ME!
*
* @param flavor DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public boolean isDataFlavorSupported(final DataFlavor flavor) {
return DataFlavor.stringFlavor.equals(flavor);
}
/**
* DOCUMENT ME!
*
* @param flavor DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws UnsupportedFlavorException DOCUMENT ME!
* @throws IOException DOCUMENT ME!
*/
@Override
public Object getTransferData(final DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (!DataFlavor.stringFlavor.equals(flavor)) {
throw (new UnsupportedFlavorException(flavor));
}
return url;
}
}
/**
* DOCUMENT ME!
*
* @author $author$
* @version $Revision$, $Date$
*/
class ImageSelection implements Transferable {
//~ Instance fields --------------------------------------------------------
private Image image;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new ImageSelection object.
*
* @param image DOCUMENT ME!
*/
public ImageSelection(final Image image) {
this.image = image;
}
//~ Methods ----------------------------------------------------------------
/**
* Returns supported flavors.
*
* @return DOCUMENT ME!
*/
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { DataFlavor.imageFlavor };
}
/**
* Returns true if flavor is supported.
*
* @param flavor DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public boolean isDataFlavorSupported(final DataFlavor flavor) {
return DataFlavor.imageFlavor.equals(flavor);
}
/**
* Returns image.
*
* @param flavor DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws UnsupportedFlavorException DOCUMENT ME!
* @throws IOException DOCUMENT ME!
*/
@Override
public Object getTransferData(final DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (!DataFlavor.imageFlavor.equals(flavor)) {
throw (new UnsupportedFlavorException(flavor));
}
return image;
}
}
| true | true | private void initComponents() {
cmdGroupPrimaryInteractionMode = new javax.swing.ButtonGroup();
panSearchSelection = new javax.swing.JPanel();
popMen = new javax.swing.JPopupMenu();
mnuConfigServer = new javax.swing.JMenuItem();
cmdGroupNodes = new javax.swing.ButtonGroup();
buttonGroup1 = new javax.swing.ButtonGroup();
jPopupMenu1 = new javax.swing.JPopupMenu();
menBookmarks = new javax.swing.JMenu();
mniAddBookmark = new javax.swing.JMenuItem();
mniBookmarkManager = new javax.swing.JMenuItem();
mniBookmarkSidebar = new javax.swing.JMenuItem();
popMenSearch = new javax.swing.JPopupMenu();
mniSearchRectangle1 = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
mniSearchPolygon1 = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
mniSearchEllipse1 = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
mniSearchPolyline1 = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
jSeparator12 = new javax.swing.JSeparator();
mniSearchCidsFeature1 = new javax.swing.JRadioButtonMenuItem();
mniSearchShowLastFeature1 = new javax.swing.JMenuItem();
mniSearchRedo1 = new javax.swing.JMenuItem();
mniSearchBuffer1 = new javax.swing.JMenuItem();
cmdGroupSearch = new javax.swing.ButtonGroup();
cmdGroupSearch1 = new javax.swing.ButtonGroup();
panAll = new javax.swing.JPanel();
panToolbar = new javax.swing.JPanel();
panMain = new javax.swing.JPanel();
tlbMain = new javax.swing.JToolBar();
cmdReconfig = new JPopupMenuButton();
((JPopupMenuButton)cmdReconfig).setPopupMenu(popMen);
jSeparator1 = new javax.swing.JSeparator();
cmdBack = new JHistoryButton() {
@Override
public void historyActionPerformed() {
if (mapC != null) {
mapC.back(true);
}
}
};
cmdHome = new javax.swing.JButton();
cmdForward = new JHistoryButton() {
@Override
public void historyActionPerformed() {
if (mapC != null) {
mapC.forward(true);
}
}
};
;
jSeparator2 = new javax.swing.JSeparator();
cmdRefresh = new javax.swing.JButton();
jSeparator6 = new javax.swing.JSeparator();
cmdPrint = new javax.swing.JButton();
cmdClipboard = new javax.swing.JButton();
cmdDownloads = new javax.swing.JButton();
jSeparator4 = new javax.swing.JSeparator();
togInvisible = new javax.swing.JToggleButton();
togInvisible.setVisible(false);
cmdSelect = new javax.swing.JToggleButton();
cmdZoom = new javax.swing.JToggleButton();
cmdPan = new javax.swing.JToggleButton();
cmdFeatureInfo = new javax.swing.JToggleButton();
cmdPluginSearch = new CidsBeanDropJPopupMenuButton(MappingComponent.CREATE_SEARCH_POLYGON, mapC, null);
cmdNewPolygon = new javax.swing.JToggleButton();
cmdNewLinestring = new javax.swing.JToggleButton();
cmdNewPoint = new javax.swing.JToggleButton();
cmdNewLinearReferencing = new javax.swing.JToggleButton();
cmdMoveGeometry = new javax.swing.JToggleButton();
cmdRemoveGeometry = new javax.swing.JToggleButton();
jSeparator3 = new javax.swing.JSeparator();
cmdNodeMove = new javax.swing.JToggleButton();
cmdNodeAdd = new javax.swing.JToggleButton();
cmdNodeRemove = new javax.swing.JToggleButton();
cmdNodeRotateGeometry = new javax.swing.JToggleButton();
jSeparator5 = new javax.swing.JSeparator();
cmdSnap = new javax.swing.JToggleButton();
jSeparator11 = new javax.swing.JSeparator();
cmdUndo = new javax.swing.JButton();
cmdRedo = new javax.swing.JButton();
panStatus = new javax.swing.JPanel();
mnuBar = new javax.swing.JMenuBar();
menFile = new javax.swing.JMenu();
mniLoadConfig = new javax.swing.JMenuItem();
mniSaveConfig = new javax.swing.JMenuItem();
mniLoadConfigFromServer = new javax.swing.JMenuItem();
sepServerProfilesStart = new javax.swing.JSeparator();
sepServerProfilesEnd = new javax.swing.JSeparator();
mniSaveLayout = new javax.swing.JMenuItem();
mniLoadLayout = new javax.swing.JMenuItem();
jSeparator9 = new javax.swing.JSeparator();
mniClipboard = new javax.swing.JMenuItem();
mniGeoLinkClipboard = new javax.swing.JMenuItem();
mniPrint = new javax.swing.JMenuItem();
jSeparator10 = new javax.swing.JSeparator();
mniClose = new javax.swing.JMenuItem();
menEdit = new javax.swing.JMenu();
mniRefresh = new javax.swing.JMenuItem();
jSeparator13 = new javax.swing.JSeparator();
mniZoomToSelectedObjects = new javax.swing.JMenuItem();
mniZoomToAllObjects = new javax.swing.JMenuItem();
jSeparator15 = new javax.swing.JSeparator();
mniRemoveSelectedObject = new javax.swing.JMenuItem();
mniRemoveAllObjects = new javax.swing.JMenuItem();
menHistory = new javax.swing.JMenu();
mniBack = new javax.swing.JMenuItem();
mniForward = new javax.swing.JMenuItem();
mniHome = new javax.swing.JMenuItem();
sepBeforePos = new javax.swing.JSeparator();
sepAfterPos = new javax.swing.JSeparator();
mniHistorySidebar = new javax.swing.JMenuItem();
menSearch = new javax.swing.JMenu();
mniSearchRectangle = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
mniSearchPolygon = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
mniSearchEllipse = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
mniSearchPolyline = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
jSeparator8 = new javax.swing.JSeparator();
mniSearchCidsFeature = new javax.swing.JRadioButtonMenuItem();
mniSearchShowLastFeature = new javax.swing.JMenuItem();
mniSearchRedo = new javax.swing.JMenuItem();
mniSearchBuffer = new javax.swing.JMenuItem();
menExtras = new javax.swing.JMenu();
mniOptions = new javax.swing.JMenuItem();
jSeparator16 = new javax.swing.JSeparator();
mniBufferSelectedGeom = new javax.swing.JMenuItem();
jSeparator17 = new javax.swing.JPopupMenu.Separator();
mniGotoPoint = new javax.swing.JMenuItem();
jSeparator14 = new javax.swing.JSeparator();
mniScale = new javax.swing.JMenuItem();
menWindows = new javax.swing.JMenu();
mniLayer = new javax.swing.JMenuItem();
mniCapabilities = new javax.swing.JMenuItem();
mniFeatureInfo = new javax.swing.JMenuItem();
mniServerInfo = new javax.swing.JMenuItem();
mniLayerInfo = new javax.swing.JMenuItem();
mniLegend = new javax.swing.JMenuItem();
mniFeatureControl = new javax.swing.JMenuItem();
mniMap = new javax.swing.JMenuItem();
mniOverview = new javax.swing.JMenuItem();
sepResetWindowLayout = new javax.swing.JSeparator();
mniResetWindowLayout = new javax.swing.JMenuItem();
menHelp = new javax.swing.JMenu();
mniOnlineHelp = new javax.swing.JMenuItem();
mniNews = new javax.swing.JMenuItem();
mniAbout = new javax.swing.JMenuItem();
mnuConfigServer.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/raster/wms/res/server.png"))); // NOI18N
mnuConfigServer.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mnuConfigServer.text")); // NOI18N
mnuConfigServer.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mnuConfigServerActionPerformed(evt);
}
});
popMen.add(mnuConfigServer);
menBookmarks.setMnemonic('L');
menBookmarks.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.menBookmarks.text")); // NOI18N
mniAddBookmark.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/bookmark_add.png"))); // NOI18N
mniAddBookmark.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniAddBookmark.text")); // NOI18N
mniAddBookmark.setEnabled(false);
menBookmarks.add(mniAddBookmark);
mniBookmarkManager.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/bookmark_folder.png"))); // NOI18N
mniBookmarkManager.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniBookmarkManager.text")); // NOI18N
mniBookmarkManager.setEnabled(false);
menBookmarks.add(mniBookmarkManager);
mniBookmarkSidebar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/bookmark.png"))); // NOI18N
mniBookmarkSidebar.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniBookmarkSidebar.text")); // NOI18N
mniBookmarkSidebar.setEnabled(false);
menBookmarks.add(mniBookmarkSidebar);
popMenSearch.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
@Override
public void popupMenuCanceled(final javax.swing.event.PopupMenuEvent evt) {
}
@Override
public void popupMenuWillBecomeInvisible(final javax.swing.event.PopupMenuEvent evt) {
}
@Override
public void popupMenuWillBecomeVisible(final javax.swing.event.PopupMenuEvent evt) {
popMenSearchPopupMenuWillBecomeVisible(evt);
}
});
mniSearchRectangle1.setAction(searchRectangleAction);
cmdGroupSearch1.add(mniSearchRectangle1);
mniSearchRectangle1.setSelected(true);
mniSearchRectangle1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchRectangle1.text")); // NOI18N
mniSearchRectangle1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/rectangle.png"))); // NOI18N
popMenSearch.add(mniSearchRectangle1);
mniSearchPolygon1.setAction(searchPolygonAction);
cmdGroupSearch1.add(mniSearchPolygon1);
mniSearchPolygon1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchPolygon1.text")); // NOI18N
mniSearchPolygon1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/polygon.png"))); // NOI18N
popMenSearch.add(mniSearchPolygon1);
mniSearchEllipse1.setAction(searchEllipseAction);
cmdGroupSearch1.add(mniSearchEllipse1);
mniSearchEllipse1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchEllipse1.text")); // NOI18N
mniSearchEllipse1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ellipse.png"))); // NOI18N
popMenSearch.add(mniSearchEllipse1);
mniSearchPolyline1.setAction(searchPolylineAction);
cmdGroupSearch1.add(mniSearchPolyline1);
mniSearchPolyline1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchPolyline1.text")); // NOI18N
mniSearchPolyline1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/polyline.png"))); // NOI18N
popMenSearch.add(mniSearchPolyline1);
popMenSearch.add(jSeparator12);
mniSearchCidsFeature1.setAction(searchCidsFeatureAction);
cmdGroupSearch.add(mniSearchCidsFeature1);
mniSearchCidsFeature1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchCidsFeature.text")); // NOI18N
mniSearchCidsFeature1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/polygon.png"))); // NOI18N
popMenSearch.add(mniSearchCidsFeature1);
mniSearchShowLastFeature1.setAction(searchShowLastFeatureAction);
mniSearchShowLastFeature1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Y,
java.awt.event.InputEvent.CTRL_MASK));
mniSearchShowLastFeature1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchShowLastFeature1.text")); // NOI18N
mniSearchShowLastFeature1.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchShowLastFeature1.toolTipText")); // NOI18N
popMenSearch.add(mniSearchShowLastFeature1);
mniSearchRedo1.setAction(searchRedoAction);
mniSearchRedo1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Y,
java.awt.event.InputEvent.ALT_MASK
| java.awt.event.InputEvent.CTRL_MASK));
mniSearchRedo1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchRedo1.text")); // NOI18N
mniSearchRedo1.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchRedo1.toolTipText")); // NOI18N
popMenSearch.add(mniSearchRedo1);
mniSearchBuffer1.setAction(searchBufferAction);
mniSearchBuffer1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/buffer.png"))); // NOI18N
mniSearchBuffer1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchBuffer1.text")); // NOI18N
mniSearchBuffer1.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchBuffer1.toolTipText")); // NOI18N
popMenSearch.add(mniSearchBuffer1);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.Form.title")); // NOI18N
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosed(final java.awt.event.WindowEvent evt) {
formWindowClosed(evt);
}
});
addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentResized(final java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
@Override
public void componentShown(final java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
panAll.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
panAll.setLayout(new java.awt.BorderLayout());
panToolbar.setLayout(new java.awt.BorderLayout());
panAll.add(panToolbar, java.awt.BorderLayout.NORTH);
panMain.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 4, 4, 4));
panMain.setFocusCycleRoot(true);
panMain.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseEntered(final java.awt.event.MouseEvent evt) {
panMainMouseEntered(evt);
}
@Override
public void mouseExited(final java.awt.event.MouseEvent evt) {
panMainMouseExited(evt);
}
});
panMain.setLayout(new java.awt.BorderLayout());
tlbMain.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(final java.awt.event.MouseEvent evt) {
tlbMainMouseClicked(evt);
}
});
cmdReconfig.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/open.gif"))); // NOI18N
cmdReconfig.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdReconfig.toolTipText")); // NOI18N
cmdReconfig.setBorderPainted(false);
cmdReconfig.setFocusPainted(false);
cmdReconfig.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdReconfigActionPerformed(evt);
}
});
tlbMain.add(cmdReconfig);
jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator1.setMaximumSize(new java.awt.Dimension(2, 32767));
jSeparator1.setPreferredSize(new java.awt.Dimension(2, 10));
tlbMain.add(jSeparator1);
cmdBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/back.png"))); // NOI18N
cmdBack.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdBack.toolTipText")); // NOI18N
cmdBack.setBorderPainted(false);
cmdBack.setFocusPainted(false);
cmdBack.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdBackActionPerformed(evt);
}
});
tlbMain.add(cmdBack);
cmdHome.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/home.gif"))); // NOI18N
cmdHome.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdHome.toolTipText")); // NOI18N
cmdHome.setBorderPainted(false);
cmdHome.setFocusPainted(false);
cmdHome.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdHomeActionPerformed(evt);
}
});
tlbMain.add(cmdHome);
cmdForward.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/forward.png"))); // NOI18N
cmdForward.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdForward.toolTipText")); // NOI18N
cmdForward.setBorderPainted(false);
cmdForward.setFocusPainted(false);
tlbMain.add(cmdForward);
jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator2.setMaximumSize(new java.awt.Dimension(2, 32767));
jSeparator2.setPreferredSize(new java.awt.Dimension(2, 10));
tlbMain.add(jSeparator2);
cmdRefresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/reload.gif"))); // NOI18N
cmdRefresh.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdRefresh.toolTipText")); // NOI18N
cmdRefresh.setBorderPainted(false);
cmdRefresh.setFocusPainted(false);
cmdRefresh.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdRefreshActionPerformed(evt);
}
});
tlbMain.add(cmdRefresh);
jSeparator6.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator6.setMaximumSize(new java.awt.Dimension(2, 32767));
jSeparator6.setPreferredSize(new java.awt.Dimension(2, 10));
tlbMain.add(jSeparator6);
cmdPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/frameprint.png"))); // NOI18N
cmdPrint.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.cmdPrint.text")); // NOI18N
cmdPrint.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdPrint.toolTipText")); // NOI18N
cmdPrint.setBorderPainted(false);
cmdPrint.setFocusPainted(false);
cmdPrint.setName("cmdPrint"); // NOI18N
cmdPrint.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdPrintActionPerformed(evt);
}
});
tlbMain.add(cmdPrint);
cmdClipboard.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/clipboard.png"))); // NOI18N
cmdClipboard.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdClipboard.text")); // NOI18N
cmdClipboard.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdClipboard.toolTipText")); // NOI18N
cmdClipboard.setBorderPainted(false);
cmdClipboard.setFocusPainted(false);
cmdClipboard.setName("cmdClipboard"); // NOI18N
cmdClipboard.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdClipboardActionPerformed(evt);
}
});
tlbMain.add(cmdClipboard);
cmdDownloads.setAction(new DownloadManagerAction(this));
cmdDownloads.setBorderPainted(false);
tlbMain.add(cmdDownloads);
jSeparator4.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator4.setMaximumSize(new java.awt.Dimension(2, 32767));
jSeparator4.setPreferredSize(new java.awt.Dimension(2, 10));
tlbMain.add(jSeparator4);
cmdGroupPrimaryInteractionMode.add(togInvisible);
togInvisible.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.togInvisible.text")); // NOI18N
togInvisible.setFocusPainted(false);
tlbMain.add(togInvisible);
cmdGroupPrimaryInteractionMode.add(cmdSelect);
cmdSelect.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/select.png"))); // NOI18N
cmdSelect.setSelected(true);
cmdSelect.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdSelect.toolTipText")); // NOI18N
cmdSelect.setBorderPainted(false);
cmdSelect.setFocusPainted(false);
cmdSelect.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdSelectActionPerformed(evt);
}
});
tlbMain.add(cmdSelect);
cmdGroupPrimaryInteractionMode.add(cmdZoom);
cmdZoom.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/zoom.gif"))); // NOI18N
cmdZoom.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdZoom.toolTipText")); // NOI18N
cmdZoom.setBorderPainted(false);
cmdZoom.setFocusPainted(false);
cmdZoom.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdZoomActionPerformed(evt);
}
});
tlbMain.add(cmdZoom);
cmdGroupPrimaryInteractionMode.add(cmdPan);
cmdPan.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/pan.gif"))); // NOI18N
cmdPan.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdPan.toolTipText")); // NOI18N
cmdPan.setBorderPainted(false);
cmdPan.setFocusPainted(false);
cmdPan.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdPanActionPerformed(evt);
}
});
tlbMain.add(cmdPan);
cmdGroupPrimaryInteractionMode.add(cmdFeatureInfo);
cmdFeatureInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/featureInfos.gif"))); // NOI18N
cmdFeatureInfo.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdFeatureInfo.toolTipText")); // NOI18N
cmdFeatureInfo.setBorderPainted(false);
cmdFeatureInfo.setFocusPainted(false);
cmdFeatureInfo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdFeatureInfoActionPerformed(evt);
}
});
tlbMain.add(cmdFeatureInfo);
cmdPluginSearch.setAction(searchAction);
cmdPluginSearch.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/pluginSearchRectangle.png"))); // NOI18N
cmdPluginSearch.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdPluginSearch.toolTipText")); // NOI18N
cmdGroupPrimaryInteractionMode.add(cmdPluginSearch);
cmdPluginSearch.setFocusPainted(false);
tlbMain.add(cmdPluginSearch);
cmdGroupPrimaryInteractionMode.add(cmdNewPolygon);
cmdNewPolygon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/newPolygon.png"))); // NOI18N
cmdNewPolygon.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNewPolygon.toolTipText")); // NOI18N
cmdNewPolygon.setBorderPainted(false);
cmdNewPolygon.setFocusPainted(false);
cmdNewPolygon.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdNewPolygonActionPerformed(evt);
}
});
tlbMain.add(cmdNewPolygon);
cmdGroupPrimaryInteractionMode.add(cmdNewLinestring);
cmdNewLinestring.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/newLinestring.png"))); // NOI18N
cmdNewLinestring.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNewLinestring.toolTipText")); // NOI18N
cmdNewLinestring.setBorderPainted(false);
cmdNewLinestring.setFocusPainted(false);
cmdNewLinestring.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
createGeometryAction(evt);
}
});
tlbMain.add(cmdNewLinestring);
cmdGroupPrimaryInteractionMode.add(cmdNewPoint);
cmdNewPoint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/newPoint.png"))); // NOI18N
cmdNewPoint.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNewPoint.toolTipText")); // NOI18N
cmdNewPoint.setBorderPainted(false);
cmdNewPoint.setFocusPainted(false);
cmdNewPoint.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdNewPointActionPerformed(evt);
}
});
tlbMain.add(cmdNewPoint);
cmdGroupPrimaryInteractionMode.add(cmdNewLinearReferencing);
cmdNewLinearReferencing.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/linref.png"))); // NOI18N
cmdNewLinearReferencing.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNewLinearReferencing.text")); // NOI18N
cmdNewLinearReferencing.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNewLinearReferencing.toolTipText")); // NOI18N
cmdNewLinearReferencing.setFocusPainted(false);
cmdNewLinearReferencing.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdNewLinearReferencingcreateGeometryAction(evt);
}
});
tlbMain.add(cmdNewLinearReferencing);
cmdNewLinearReferencing.setVisible(false);
cmdGroupPrimaryInteractionMode.add(cmdMoveGeometry);
cmdMoveGeometry.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/move.png"))); // NOI18N
cmdMoveGeometry.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdMoveGeometry.toolTipText")); // NOI18N
cmdMoveGeometry.setBorderPainted(false);
cmdMoveGeometry.setFocusPainted(false);
cmdMoveGeometry.setMaximumSize(new java.awt.Dimension(29, 29));
cmdMoveGeometry.setMinimumSize(new java.awt.Dimension(29, 29));
cmdMoveGeometry.setPreferredSize(new java.awt.Dimension(29, 29));
cmdMoveGeometry.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdMoveGeometryActionPerformed(evt);
}
});
tlbMain.add(cmdMoveGeometry);
cmdGroupPrimaryInteractionMode.add(cmdRemoveGeometry);
cmdRemoveGeometry.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.png"))); // NOI18N
cmdRemoveGeometry.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdRemoveGeometry.toolTipText")); // NOI18N
cmdRemoveGeometry.setBorderPainted(false);
cmdRemoveGeometry.setFocusPainted(false);
cmdRemoveGeometry.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdRemoveGeometryActionPerformed(evt);
}
});
tlbMain.add(cmdRemoveGeometry);
jSeparator3.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator3.setMaximumSize(new java.awt.Dimension(2, 32767));
jSeparator3.setPreferredSize(new java.awt.Dimension(2, 10));
tlbMain.add(jSeparator3);
cmdGroupNodes.add(cmdNodeMove);
cmdNodeMove.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/moveNodes.png"))); // NOI18N
cmdNodeMove.setSelected(true);
cmdNodeMove.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNodeMove.toolTipText")); // NOI18N
cmdNodeMove.setBorderPainted(false);
cmdNodeMove.setFocusPainted(false);
cmdNodeMove.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdNodeMoveActionPerformed(evt);
}
});
tlbMain.add(cmdNodeMove);
cmdGroupNodes.add(cmdNodeAdd);
cmdNodeAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/insertNodes.png"))); // NOI18N
cmdNodeAdd.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNodeAdd.toolTipText")); // NOI18N
cmdNodeAdd.setBorderPainted(false);
cmdNodeAdd.setFocusPainted(false);
cmdNodeAdd.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdNodeAddActionPerformed(evt);
}
});
tlbMain.add(cmdNodeAdd);
cmdGroupNodes.add(cmdNodeRemove);
cmdNodeRemove.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/removeNodes.png"))); // NOI18N
cmdNodeRemove.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNodeRemove.toolTipText")); // NOI18N
cmdNodeRemove.setBorderPainted(false);
cmdNodeRemove.setFocusPainted(false);
cmdNodeRemove.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdNodeRemoveActionPerformed(evt);
}
});
tlbMain.add(cmdNodeRemove);
cmdGroupNodes.add(cmdNodeRotateGeometry);
cmdNodeRotateGeometry.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/rotate.png"))); // NOI18N
cmdNodeRotateGeometry.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNodeRotateGeometry.toolTipText")); // NOI18N
cmdNodeRotateGeometry.setBorderPainted(false);
cmdNodeRotateGeometry.setFocusPainted(false);
cmdNodeRotateGeometry.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdNodeRotateGeometryActionPerformed(evt);
}
});
tlbMain.add(cmdNodeRotateGeometry);
jSeparator5.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator5.setMaximumSize(new java.awt.Dimension(2, 32767));
jSeparator5.setPreferredSize(new java.awt.Dimension(2, 10));
tlbMain.add(jSeparator5);
cmdSnap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/snap.png"))); // NOI18N
cmdSnap.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdSnap.toolTipText")); // NOI18N
cmdSnap.setBorderPainted(false);
cmdSnap.setFocusPainted(false);
cmdSnap.setMaximumSize(new java.awt.Dimension(29, 29));
cmdSnap.setMinimumSize(new java.awt.Dimension(29, 29));
cmdSnap.setPreferredSize(new java.awt.Dimension(29, 29));
cmdSnap.setRolloverSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/images/snap_selected.png"))); // NOI18N
cmdSnap.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/images/snap_selected.png"))); // NOI18N
cmdSnap.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdSnapActionPerformed(evt);
}
});
tlbMain.add(cmdSnap);
jSeparator11.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator11.setMaximumSize(new java.awt.Dimension(2, 32767));
jSeparator11.setPreferredSize(new java.awt.Dimension(2, 10));
tlbMain.add(jSeparator11);
cmdUndo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/undo.png"))); // NOI18N
cmdUndo.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdUndo.toolTipText")); // NOI18N
cmdUndo.setBorderPainted(false);
cmdUndo.setEnabled(false);
cmdUndo.setFocusPainted(false);
cmdUndo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniUndoPerformed(evt);
}
});
tlbMain.add(cmdUndo);
cmdRedo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/redo.png"))); // NOI18N
cmdRedo.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdRedo.toolTipText")); // NOI18N
cmdRedo.setBorderPainted(false);
cmdRedo.setEnabled(false);
cmdRedo.setFocusPainted(false);
cmdRedo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniRedoPerformed(evt);
}
});
tlbMain.add(cmdRedo);
panMain.add(tlbMain, java.awt.BorderLayout.NORTH);
panAll.add(panMain, java.awt.BorderLayout.CENTER);
panStatus.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 4, 1, 4));
panStatus.setLayout(new java.awt.BorderLayout());
panAll.add(panStatus, java.awt.BorderLayout.SOUTH);
getContentPane().add(panAll, java.awt.BorderLayout.CENTER);
menFile.setMnemonic('D');
menFile.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.menFile.text")); // NOI18N
mniLoadConfig.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_L,
java.awt.event.InputEvent.CTRL_MASK));
mniLoadConfig.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/config.png"))); // NOI18N
mniLoadConfig.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLoadConfig.text")); // NOI18N
mniLoadConfig.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLoadConfig.tooltip")); // NOI18N
mniLoadConfig.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniLoadConfigActionPerformed(evt);
}
});
menFile.add(mniLoadConfig);
mniSaveConfig.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_K,
java.awt.event.InputEvent.CTRL_MASK));
mniSaveConfig.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/config.png"))); // NOI18N
mniSaveConfig.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSaveConfig.text")); // NOI18N
mniSaveConfig.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSaveConfig.tooltip")); // NOI18N
mniSaveConfig.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniSaveConfigActionPerformed(evt);
}
});
menFile.add(mniSaveConfig);
mniLoadConfigFromServer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/config.png"))); // NOI18N
mniLoadConfigFromServer.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLoadConfigFromServer.text")); // NOI18N
mniLoadConfigFromServer.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLoadConfigFromServer.tooltip")); // NOI18N
mniLoadConfigFromServer.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniLoadConfigFromServerActionPerformed(evt);
}
});
menFile.add(mniLoadConfigFromServer);
sepServerProfilesStart.setName("sepServerProfilesStart"); // NOI18N
menFile.add(sepServerProfilesStart);
sepServerProfilesEnd.setName("sepServerProfilesEnd"); // NOI18N
menFile.add(sepServerProfilesEnd);
mniSaveLayout.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_S,
java.awt.event.InputEvent.CTRL_MASK));
mniSaveLayout.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/layout.png"))); // NOI18N
mniSaveLayout.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSaveLayout.text")); // NOI18N
mniSaveLayout.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSaveLayout.tooltip")); // NOI18N
mniSaveLayout.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniSaveLayoutActionPerformed(evt);
}
});
menFile.add(mniSaveLayout);
mniLoadLayout.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_O,
java.awt.event.InputEvent.CTRL_MASK));
mniLoadLayout.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/layout.png"))); // NOI18N
mniLoadLayout.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLoadLayout.text")); // NOI18N
mniLoadLayout.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLoadLayout.tooltip")); // NOI18N
mniLoadLayout.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniLoadLayoutActionPerformed(evt);
}
});
menFile.add(mniLoadLayout);
menFile.add(jSeparator9);
mniClipboard.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_C,
java.awt.event.InputEvent.CTRL_MASK));
mniClipboard.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/clipboard16.png"))); // NOI18N
mniClipboard.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniClipboard.text")); // NOI18N
mniClipboard.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniClipboard.tooltip")); // NOI18N
mniClipboard.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniClipboardActionPerformed(evt);
}
});
menFile.add(mniClipboard);
mniGeoLinkClipboard.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_C,
java.awt.event.InputEvent.ALT_MASK
| java.awt.event.InputEvent.CTRL_MASK));
mniGeoLinkClipboard.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/clipboard16.png"))); // NOI18N
mniGeoLinkClipboard.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniGeoLinkClipboard.text")); // NOI18N
mniGeoLinkClipboard.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniGeoLinkClipboard.tooltip")); // NOI18N
mniGeoLinkClipboard.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniGeoLinkClipboardActionPerformed(evt);
}
});
menFile.add(mniGeoLinkClipboard);
mniPrint.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_P,
java.awt.event.InputEvent.CTRL_MASK));
mniPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/frameprint16.png"))); // NOI18N
mniPrint.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniPrint.text")); // NOI18N
mniPrint.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniPrint.tooltip")); // NOI18N
mniPrint.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniPrintActionPerformed(evt);
}
});
menFile.add(mniPrint);
menFile.add(jSeparator10);
mniClose.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_F4,
java.awt.event.InputEvent.ALT_MASK));
mniClose.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniClose.text")); // NOI18N
mniClose.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniClose.tooltip")); // NOI18N
mniClose.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniCloseActionPerformed(evt);
}
});
menFile.add(mniClose);
mnuBar.add(menFile);
menEdit.setMnemonic('B');
menEdit.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.menEdit.text")); // NOI18N
menEdit.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
menEditActionPerformed(evt);
}
});
mniRefresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/reload16.gif"))); // NOI18N
mniRefresh.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniRefresh.text")); // NOI18N
mniRefresh.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniRefresh.tooltip")); // NOI18N
mniRefresh.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniRefreshActionPerformed(evt);
}
});
menEdit.add(mniRefresh);
menEdit.add(jSeparator13);
mniZoomToSelectedObjects.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/gui/res/zoomToSelection.png"))); // NOI18N
mniZoomToSelectedObjects.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniZoomToSelectedObjects.text")); // NOI18N
mniZoomToSelectedObjects.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniZoomToSelectedObjects.tooltip")); // NOI18N
mniZoomToSelectedObjects.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniZoomToSelectedObjectsActionPerformed(evt);
}
});
menEdit.add(mniZoomToSelectedObjects);
mniZoomToAllObjects.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/gui/res/zoomToAll.png"))); // NOI18N
mniZoomToAllObjects.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniZoomToAllObjects.text")); // NOI18N
mniZoomToAllObjects.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniZoomToAllObjects.tooltip")); // NOI18N
mniZoomToAllObjects.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniZoomToAllObjectsActionPerformed(evt);
}
});
menEdit.add(mniZoomToAllObjects);
menEdit.add(jSeparator15);
mniRemoveSelectedObject.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/gui/res/removerow.png"))); // NOI18N
mniRemoveSelectedObject.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniRemoveSelectedObject.text")); // NOI18N
mniRemoveSelectedObject.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniRemoveSelectedObject.tooltip")); // NOI18N
mniRemoveSelectedObject.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniRemoveSelectedObjectActionPerformed(evt);
}
});
menEdit.add(mniRemoveSelectedObject);
mniRemoveAllObjects.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/gui/res/removeAll.png"))); // NOI18N
mniRemoveAllObjects.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniRemoveAllObjects.text")); // NOI18N
mniRemoveAllObjects.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniRemoveAllObjects.tooltip")); // NOI18N
mniRemoveAllObjects.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniRemoveAllObjectsActionPerformed(evt);
}
});
menEdit.add(mniRemoveAllObjects);
mnuBar.add(menEdit);
menHistory.setMnemonic('C');
menHistory.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.menHistory.text")); // NOI18N
mniBack.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_LEFT,
java.awt.event.InputEvent.CTRL_MASK));
mniBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/back16.png"))); // NOI18N
mniBack.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniBack.text")); // NOI18N
mniBack.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniBack.tooltip")); // NOI18N
mniBack.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniBackActionPerformed(evt);
}
});
menHistory.add(mniBack);
mniForward.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_RIGHT,
java.awt.event.InputEvent.CTRL_MASK));
mniForward.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/forward16.png"))); // NOI18N
mniForward.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniForward.text")); // NOI18N
mniForward.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniForward.tooltip")); // NOI18N
mniForward.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniForwardActionPerformed(evt);
}
});
menHistory.add(mniForward);
mniHome.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_HOME, 0));
mniHome.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/home16.png"))); // NOI18N
mniHome.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniHome.text")); // NOI18N
mniHome.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniHome.tooltip")); // NOI18N
mniHome.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniHomeActionPerformed(evt);
}
});
menHistory.add(mniHome);
menHistory.add(sepBeforePos);
menHistory.add(sepAfterPos);
mniHistorySidebar.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniHistorySidebar.text")); // NOI18N
mniHistorySidebar.setEnabled(false);
menHistory.add(mniHistorySidebar);
mnuBar.add(menHistory);
menSearch.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.menSearch.text")); // NOI18N
menSearch.addMenuListener(new javax.swing.event.MenuListener() {
@Override
public void menuCanceled(final javax.swing.event.MenuEvent evt) {
}
@Override
public void menuDeselected(final javax.swing.event.MenuEvent evt) {
}
@Override
public void menuSelected(final javax.swing.event.MenuEvent evt) {
menSearchMenuSelected(evt);
}
});
mniSearchRectangle.setAction(searchRectangleAction);
cmdGroupSearch.add(mniSearchRectangle);
mniSearchRectangle.setSelected(true);
mniSearchRectangle.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchRectangle.text")); // NOI18N
mniSearchRectangle.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchRectangle.tooltip")); // NOI18N
mniSearchRectangle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/rectangle.png"))); // NOI18N
menSearch.add(mniSearchRectangle);
mniSearchPolygon.setAction(searchPolygonAction);
cmdGroupSearch.add(mniSearchPolygon);
mniSearchPolygon.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchPolygon.text")); // NOI18N
mniSearchPolygon.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchPolygon.tooltip")); // NOI18N
mniSearchPolygon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/polygon.png"))); // NOI18N
menSearch.add(mniSearchPolygon);
mniSearchEllipse.setAction(searchEllipseAction);
cmdGroupSearch.add(mniSearchEllipse);
mniSearchEllipse.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchEllipse.text_1")); // NOI18N
mniSearchEllipse.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchEllipse.tooltip")); // NOI18N
mniSearchEllipse.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ellipse.png"))); // NOI18N
menSearch.add(mniSearchEllipse);
mniSearchPolyline.setAction(searchPolylineAction);
cmdGroupSearch.add(mniSearchPolyline);
mniSearchPolyline.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchPolyline.text_1")); // NOI18N
mniSearchPolyline.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchLine.tooltip")); // NOI18N
mniSearchPolyline.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/polyline.png"))); // NOI18N
menSearch.add(mniSearchPolyline);
menSearch.add(jSeparator8);
mniSearchCidsFeature.setAction(searchCidsFeatureAction);
cmdGroupSearch.add(mniSearchCidsFeature);
mniSearchCidsFeature.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchCidsFeature.text")); // NOI18N
mniSearchCidsFeature.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchCidsFeature.tooltip")); // NOI18N
mniSearchCidsFeature.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/polygon.png"))); // NOI18N
mniSearchCidsFeature.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniSearchCidsFeatureActionPerformed(evt);
}
});
menSearch.add(mniSearchCidsFeature);
mniSearchShowLastFeature.setAction(searchShowLastFeatureAction);
mniSearchShowLastFeature.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Y,
java.awt.event.InputEvent.CTRL_MASK));
mniSearchShowLastFeature.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchShowLastFeature.text")); // NOI18N
mniSearchShowLastFeature.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchShowLastFeature.toolTipText")); // NOI18N
menSearch.add(mniSearchShowLastFeature);
mniSearchRedo.setAction(searchRedoAction);
mniSearchRedo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Y,
java.awt.event.InputEvent.ALT_MASK
| java.awt.event.InputEvent.CTRL_MASK));
mniSearchRedo.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchRedo.text")); // NOI18N
mniSearchRedo.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchRedo.toolTipText")); // NOI18N
menSearch.add(mniSearchRedo);
mniSearchBuffer.setAction(searchBufferAction);
mniSearchBuffer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/buffer.png"))); // NOI18N
mniSearchBuffer.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchBuffer.text_1")); // NOI18N
mniSearchBuffer.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchBuffer.toolTipText")); // NOI18N
menSearch.add(mniSearchBuffer);
mnuBar.add(menSearch);
// copyMenu(menSearch, popMenSearch);
((JPopupMenuButton)cmdPluginSearch).setPopupMenu(popMenSearch);
menExtras.setMnemonic('E');
menExtras.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.menExtras.text")); // NOI18N
mniOptions.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/tooloptions.png"))); // NOI18N
mniOptions.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniOptions.text")); // NOI18N
mniOptions.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniOptions.tooltip")); // NOI18N
mniOptions.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniOptionsActionPerformed(evt);
}
});
menExtras.add(mniOptions);
menExtras.add(jSeparator16);
mniBufferSelectedGeom.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_B,
java.awt.event.InputEvent.CTRL_MASK));
mniBufferSelectedGeom.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/buffer.png"))); // NOI18N
mniBufferSelectedGeom.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniBufferSelectedGeom.text")); // NOI18N
mniBufferSelectedGeom.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniBufferSelectedGeom.tooltip")); // NOI18N
mniBufferSelectedGeom.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniBufferSelectedGeomActionPerformed(evt);
}
});
menExtras.add(mniBufferSelectedGeom);
menExtras.add(jSeparator17);
mniGotoPoint.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_G,
java.awt.event.InputEvent.CTRL_MASK));
mniGotoPoint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/goto.png"))); // NOI18N
mniGotoPoint.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniGotoPoint.text")); // NOI18N
mniGotoPoint.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniGotoPoint.tooltip")); // NOI18N
mniGotoPoint.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniGotoPointActionPerformed(evt);
}
});
menExtras.add(mniGotoPoint);
menExtras.add(jSeparator14);
mniScale.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_M,
java.awt.event.InputEvent.CTRL_MASK));
mniScale.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/scale.png"))); // NOI18N
mniScale.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniScale.text")); // NOI18N
mniScale.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniScale.tooltip")); // NOI18N
mniScale.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniScaleActionPerformed(evt);
}
});
menExtras.add(mniScale);
mnuBar.add(menExtras);
menWindows.setMnemonic('F');
menWindows.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.menWindows.text")); // NOI18N
menWindows.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
menWindowsActionPerformed(evt);
}
});
mniLayer.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_1,
java.awt.event.InputEvent.CTRL_MASK));
mniLayer.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/raster/wms/res/layers.png"))); // NOI18N
mniLayer.setMnemonic('L');
mniLayer.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniLayer.text")); // NOI18N
mniLayer.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLayer.tooltip")); // NOI18N
mniLayer.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniLayerActionPerformed(evt);
}
});
menWindows.add(mniLayer);
mniCapabilities.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_2,
java.awt.event.InputEvent.CTRL_MASK));
mniCapabilities.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/raster/wms/res/server.png"))); // NOI18N
mniCapabilities.setMnemonic('C');
mniCapabilities.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniCapabilities.text")); // NOI18N
mniCapabilities.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniCapabilities.tooltip")); // NOI18N
mniCapabilities.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniCapabilitiesActionPerformed(evt);
}
});
menWindows.add(mniCapabilities);
mniFeatureInfo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_3,
java.awt.event.InputEvent.CTRL_MASK));
mniFeatureInfo.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/gui/featureinfowidget/res/featureInfo16.png"))); // NOI18N
mniFeatureInfo.setMnemonic('F');
mniFeatureInfo.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniFeatureInfo.text")); // NOI18N
mniFeatureInfo.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniFeatureInfo.tooltip")); // NOI18N
mniFeatureInfo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniFeatureInfoActionPerformed(evt);
}
});
menWindows.add(mniFeatureInfo);
mniServerInfo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_5,
java.awt.event.InputEvent.CTRL_MASK));
mniServerInfo.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/gui/capabilitywidget/res/serverInfo.png"))); // NOI18N
mniServerInfo.setMnemonic('S');
mniServerInfo.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniServerInfo.text")); // NOI18N
mniServerInfo.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniServerInfo.tooltip")); // NOI18N
mniServerInfo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniServerInfoActionPerformed(evt);
}
});
menWindows.add(mniServerInfo);
mniLayerInfo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_6,
java.awt.event.InputEvent.CTRL_MASK));
mniLayerInfo.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/gui/capabilitywidget/res/layerInfo.png"))); // NOI18N
mniLayerInfo.setMnemonic('L');
mniLayerInfo.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLayerInfo.text")); // NOI18N
mniLayerInfo.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLayerInfo.tooltip")); // NOI18N
mniLayerInfo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniLayerInfoActionPerformed(evt);
}
});
menWindows.add(mniLayerInfo);
mniLegend.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_7,
java.awt.event.InputEvent.CTRL_MASK));
mniLegend.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/navigatorplugin/res/legend.png"))); // NOI18N
mniLegend.setMnemonic('L');
mniLegend.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniLegend.text")); // NOI18N
mniLegend.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLegend.tooltip")); // NOI18N
mniLegend.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniLegendActionPerformed(evt);
}
});
menWindows.add(mniLegend);
mniFeatureControl.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_8,
java.awt.event.InputEvent.CTRL_MASK));
mniFeatureControl.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/objects.png"))); // NOI18N
mniFeatureControl.setMnemonic('O');
mniFeatureControl.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniFeatureControl.text")); // NOI18N
mniFeatureControl.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniFeatureControl.tooltip")); // NOI18N
mniFeatureControl.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniFeatureControlActionPerformed(evt);
}
});
menWindows.add(mniFeatureControl);
mniMap.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_9,
java.awt.event.InputEvent.CTRL_MASK));
mniMap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cismap/navigatorplugin/map.png"))); // NOI18N
mniMap.setMnemonic('M');
mniMap.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniMap.text")); // NOI18N
mniMap.setToolTipText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniMap.tooltip")); // NOI18N
mniMap.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniMapActionPerformed(evt);
}
});
menWindows.add(mniMap);
mniOverview.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_0,
java.awt.event.InputEvent.CTRL_MASK));
mniOverview.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/navigatorplugin/map.png"))); // NOI18N
mniOverview.setMnemonic('M');
mniOverview.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniOverview.text")); // NOI18N
mniOverview.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniOverview.tooltip")); // NOI18N
mniOverview.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniOverviewActionPerformed(evt);
}
});
menWindows.add(mniOverview);
menWindows.add(sepResetWindowLayout);
mniResetWindowLayout.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_R,
java.awt.event.InputEvent.CTRL_MASK));
mniResetWindowLayout.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/layout.png"))); // NOI18N
mniResetWindowLayout.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniResetWindowLayout.text")); // NOI18N
mniResetWindowLayout.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniResetWindowLayout.toolTipText")); // NOI18N
mniResetWindowLayout.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniResetWindowLayoutActionPerformed(evt);
}
});
menWindows.add(mniResetWindowLayout);
mnuBar.add(menWindows);
menHelp.setMnemonic('H');
menHelp.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.menHelp.text")); // NOI18N
menHelp.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
menHelpActionPerformed(evt);
}
});
mniOnlineHelp.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
mniOnlineHelp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/help.png"))); // NOI18N
mniOnlineHelp.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniOnlineHelp.text")); // NOI18N
mniOnlineHelp.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniOnlineHelp.tooltip")); // NOI18N
mniOnlineHelp.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniOnlineHelpActionPerformed(evt);
}
});
menHelp.add(mniOnlineHelp);
mniNews.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/news.png"))); // NOI18N
mniNews.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniNews.text")); // NOI18N
mniNews.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniNews.tooltip")); // NOI18N
mniNews.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniNewsActionPerformed(evt);
}
});
menHelp.add(mniNews);
mniAbout.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_A,
java.awt.event.InputEvent.ALT_MASK
| java.awt.event.InputEvent.CTRL_MASK));
mniAbout.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniAbout.text")); // NOI18N
mniAbout.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniAbout.tooltip")); // NOI18N
mniAbout.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniAboutActionPerformed(evt);
}
});
menHelp.add(mniAbout);
mnuBar.add(menHelp);
setJMenuBar(mnuBar);
} // </editor-fold>//GEN-END:initComponents
| private void initComponents() {
cmdGroupPrimaryInteractionMode = new javax.swing.ButtonGroup();
panSearchSelection = new javax.swing.JPanel();
popMen = new javax.swing.JPopupMenu();
mnuConfigServer = new javax.swing.JMenuItem();
cmdGroupNodes = new javax.swing.ButtonGroup();
buttonGroup1 = new javax.swing.ButtonGroup();
jPopupMenu1 = new javax.swing.JPopupMenu();
menBookmarks = new javax.swing.JMenu();
mniAddBookmark = new javax.swing.JMenuItem();
mniBookmarkManager = new javax.swing.JMenuItem();
mniBookmarkSidebar = new javax.swing.JMenuItem();
popMenSearch = new javax.swing.JPopupMenu();
mniSearchRectangle1 = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
mniSearchPolygon1 = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
mniSearchEllipse1 = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
mniSearchPolyline1 = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
jSeparator12 = new javax.swing.JSeparator();
mniSearchCidsFeature1 = new javax.swing.JRadioButtonMenuItem();
mniSearchShowLastFeature1 = new javax.swing.JMenuItem();
mniSearchRedo1 = new javax.swing.JMenuItem();
mniSearchBuffer1 = new javax.swing.JMenuItem();
cmdGroupSearch = new javax.swing.ButtonGroup();
cmdGroupSearch1 = new javax.swing.ButtonGroup();
panAll = new javax.swing.JPanel();
panToolbar = new javax.swing.JPanel();
panMain = new javax.swing.JPanel();
tlbMain = new javax.swing.JToolBar();
cmdReconfig = new JPopupMenuButton();
((JPopupMenuButton)cmdReconfig).setPopupMenu(popMen);
jSeparator1 = new javax.swing.JSeparator();
cmdBack = new JHistoryButton() {
@Override
public void historyActionPerformed() {
if (mapC != null) {
mapC.back(true);
}
}
};
cmdHome = new javax.swing.JButton();
cmdForward = new JHistoryButton() {
@Override
public void historyActionPerformed() {
if (mapC != null) {
mapC.forward(true);
}
}
};
;
jSeparator2 = new javax.swing.JSeparator();
cmdRefresh = new javax.swing.JButton();
jSeparator6 = new javax.swing.JSeparator();
cmdPrint = new javax.swing.JButton();
cmdClipboard = new javax.swing.JButton();
cmdDownloads = new javax.swing.JButton();
jSeparator4 = new javax.swing.JSeparator();
togInvisible = new javax.swing.JToggleButton();
togInvisible.setVisible(false);
cmdSelect = new javax.swing.JToggleButton();
cmdZoom = new javax.swing.JToggleButton();
cmdPan = new javax.swing.JToggleButton();
cmdFeatureInfo = new javax.swing.JToggleButton();
cmdPluginSearch = new CidsBeanDropJPopupMenuButton(MappingComponent.CREATE_SEARCH_POLYGON, mapC, null);
cmdNewPolygon = new javax.swing.JToggleButton();
cmdNewLinestring = new javax.swing.JToggleButton();
cmdNewPoint = new javax.swing.JToggleButton();
cmdNewLinearReferencing = new javax.swing.JToggleButton();
cmdMoveGeometry = new javax.swing.JToggleButton();
cmdRemoveGeometry = new javax.swing.JToggleButton();
jSeparator3 = new javax.swing.JSeparator();
cmdNodeMove = new javax.swing.JToggleButton();
cmdNodeAdd = new javax.swing.JToggleButton();
cmdNodeRemove = new javax.swing.JToggleButton();
cmdNodeRotateGeometry = new javax.swing.JToggleButton();
jSeparator5 = new javax.swing.JSeparator();
cmdSnap = new javax.swing.JToggleButton();
jSeparator11 = new javax.swing.JSeparator();
cmdUndo = new javax.swing.JButton();
cmdRedo = new javax.swing.JButton();
panStatus = new javax.swing.JPanel();
mnuBar = new javax.swing.JMenuBar();
menFile = new javax.swing.JMenu();
mniLoadConfig = new javax.swing.JMenuItem();
mniSaveConfig = new javax.swing.JMenuItem();
mniLoadConfigFromServer = new javax.swing.JMenuItem();
sepServerProfilesStart = new javax.swing.JSeparator();
sepServerProfilesEnd = new javax.swing.JSeparator();
mniSaveLayout = new javax.swing.JMenuItem();
mniLoadLayout = new javax.swing.JMenuItem();
jSeparator9 = new javax.swing.JSeparator();
mniClipboard = new javax.swing.JMenuItem();
mniGeoLinkClipboard = new javax.swing.JMenuItem();
mniPrint = new javax.swing.JMenuItem();
jSeparator10 = new javax.swing.JSeparator();
mniClose = new javax.swing.JMenuItem();
menEdit = new javax.swing.JMenu();
mniRefresh = new javax.swing.JMenuItem();
jSeparator13 = new javax.swing.JSeparator();
mniZoomToSelectedObjects = new javax.swing.JMenuItem();
mniZoomToAllObjects = new javax.swing.JMenuItem();
jSeparator15 = new javax.swing.JSeparator();
mniRemoveSelectedObject = new javax.swing.JMenuItem();
mniRemoveAllObjects = new javax.swing.JMenuItem();
menHistory = new javax.swing.JMenu();
mniBack = new javax.swing.JMenuItem();
mniForward = new javax.swing.JMenuItem();
mniHome = new javax.swing.JMenuItem();
sepBeforePos = new javax.swing.JSeparator();
sepAfterPos = new javax.swing.JSeparator();
mniHistorySidebar = new javax.swing.JMenuItem();
menSearch = new javax.swing.JMenu();
mniSearchRectangle = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
mniSearchPolygon = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
mniSearchEllipse = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
mniSearchPolyline = new HighlightingRadioButtonMenuItem(javax.swing.UIManager.getDefaults().getColor(
"ProgressBar.foreground"),
Color.WHITE);
jSeparator8 = new javax.swing.JSeparator();
mniSearchCidsFeature = new javax.swing.JRadioButtonMenuItem();
mniSearchShowLastFeature = new javax.swing.JMenuItem();
mniSearchRedo = new javax.swing.JMenuItem();
mniSearchBuffer = new javax.swing.JMenuItem();
menExtras = new javax.swing.JMenu();
mniOptions = new javax.swing.JMenuItem();
jSeparator16 = new javax.swing.JSeparator();
mniBufferSelectedGeom = new javax.swing.JMenuItem();
jSeparator17 = new javax.swing.JPopupMenu.Separator();
mniGotoPoint = new javax.swing.JMenuItem();
jSeparator14 = new javax.swing.JSeparator();
mniScale = new javax.swing.JMenuItem();
menWindows = new javax.swing.JMenu();
mniLayer = new javax.swing.JMenuItem();
mniCapabilities = new javax.swing.JMenuItem();
mniFeatureInfo = new javax.swing.JMenuItem();
mniServerInfo = new javax.swing.JMenuItem();
mniLayerInfo = new javax.swing.JMenuItem();
mniLegend = new javax.swing.JMenuItem();
mniFeatureControl = new javax.swing.JMenuItem();
mniMap = new javax.swing.JMenuItem();
mniOverview = new javax.swing.JMenuItem();
sepResetWindowLayout = new javax.swing.JSeparator();
mniResetWindowLayout = new javax.swing.JMenuItem();
menHelp = new javax.swing.JMenu();
mniOnlineHelp = new javax.swing.JMenuItem();
mniNews = new javax.swing.JMenuItem();
mniAbout = new javax.swing.JMenuItem();
mnuConfigServer.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/raster/wms/res/server.png"))); // NOI18N
mnuConfigServer.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mnuConfigServer.text")); // NOI18N
mnuConfigServer.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mnuConfigServerActionPerformed(evt);
}
});
popMen.add(mnuConfigServer);
menBookmarks.setMnemonic('L');
menBookmarks.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.menBookmarks.text")); // NOI18N
mniAddBookmark.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/bookmark_add.png"))); // NOI18N
mniAddBookmark.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniAddBookmark.text")); // NOI18N
mniAddBookmark.setEnabled(false);
menBookmarks.add(mniAddBookmark);
mniBookmarkManager.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/bookmark_folder.png"))); // NOI18N
mniBookmarkManager.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniBookmarkManager.text")); // NOI18N
mniBookmarkManager.setEnabled(false);
menBookmarks.add(mniBookmarkManager);
mniBookmarkSidebar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/bookmark.png"))); // NOI18N
mniBookmarkSidebar.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniBookmarkSidebar.text")); // NOI18N
mniBookmarkSidebar.setEnabled(false);
menBookmarks.add(mniBookmarkSidebar);
popMenSearch.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
@Override
public void popupMenuCanceled(final javax.swing.event.PopupMenuEvent evt) {
}
@Override
public void popupMenuWillBecomeInvisible(final javax.swing.event.PopupMenuEvent evt) {
}
@Override
public void popupMenuWillBecomeVisible(final javax.swing.event.PopupMenuEvent evt) {
popMenSearchPopupMenuWillBecomeVisible(evt);
}
});
mniSearchRectangle1.setAction(searchRectangleAction);
cmdGroupSearch1.add(mniSearchRectangle1);
mniSearchRectangle1.setSelected(true);
mniSearchRectangle1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchRectangle1.text")); // NOI18N
mniSearchRectangle1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/rectangle.png"))); // NOI18N
popMenSearch.add(mniSearchRectangle1);
mniSearchPolygon1.setAction(searchPolygonAction);
cmdGroupSearch1.add(mniSearchPolygon1);
mniSearchPolygon1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchPolygon1.text")); // NOI18N
mniSearchPolygon1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/polygon.png"))); // NOI18N
popMenSearch.add(mniSearchPolygon1);
mniSearchEllipse1.setAction(searchEllipseAction);
cmdGroupSearch1.add(mniSearchEllipse1);
mniSearchEllipse1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchEllipse1.text")); // NOI18N
mniSearchEllipse1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ellipse.png"))); // NOI18N
popMenSearch.add(mniSearchEllipse1);
mniSearchPolyline1.setAction(searchPolylineAction);
cmdGroupSearch1.add(mniSearchPolyline1);
mniSearchPolyline1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchPolyline1.text")); // NOI18N
mniSearchPolyline1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/polyline.png"))); // NOI18N
popMenSearch.add(mniSearchPolyline1);
popMenSearch.add(jSeparator12);
mniSearchCidsFeature1.setAction(searchCidsFeatureAction);
cmdGroupSearch.add(mniSearchCidsFeature1);
mniSearchCidsFeature1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchCidsFeature.text")); // NOI18N
mniSearchCidsFeature1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/polygon.png"))); // NOI18N
popMenSearch.add(mniSearchCidsFeature1);
mniSearchShowLastFeature1.setAction(searchShowLastFeatureAction);
mniSearchShowLastFeature1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Y,
java.awt.event.InputEvent.CTRL_MASK));
mniSearchShowLastFeature1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchShowLastFeature1.text")); // NOI18N
mniSearchShowLastFeature1.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchShowLastFeature1.toolTipText")); // NOI18N
popMenSearch.add(mniSearchShowLastFeature1);
mniSearchRedo1.setAction(searchRedoAction);
mniSearchRedo1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Y,
java.awt.event.InputEvent.ALT_MASK
| java.awt.event.InputEvent.CTRL_MASK));
mniSearchRedo1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchRedo1.text")); // NOI18N
mniSearchRedo1.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchRedo1.toolTipText")); // NOI18N
popMenSearch.add(mniSearchRedo1);
mniSearchBuffer1.setAction(searchBufferAction);
mniSearchBuffer1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/buffer.png"))); // NOI18N
mniSearchBuffer1.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchBuffer1.text")); // NOI18N
mniSearchBuffer1.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchBuffer1.toolTipText")); // NOI18N
popMenSearch.add(mniSearchBuffer1);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.Form.title")); // NOI18N
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosed(final java.awt.event.WindowEvent evt) {
formWindowClosed(evt);
}
});
addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentResized(final java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
@Override
public void componentShown(final java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
panAll.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
panAll.setLayout(new java.awt.BorderLayout());
panToolbar.setLayout(new java.awt.BorderLayout());
panAll.add(panToolbar, java.awt.BorderLayout.NORTH);
panMain.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 4, 4, 4));
panMain.setFocusCycleRoot(true);
panMain.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseEntered(final java.awt.event.MouseEvent evt) {
panMainMouseEntered(evt);
}
@Override
public void mouseExited(final java.awt.event.MouseEvent evt) {
panMainMouseExited(evt);
}
});
panMain.setLayout(new java.awt.BorderLayout());
tlbMain.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(final java.awt.event.MouseEvent evt) {
tlbMainMouseClicked(evt);
}
});
cmdReconfig.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/open.gif"))); // NOI18N
cmdReconfig.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdReconfig.toolTipText")); // NOI18N
cmdReconfig.setBorderPainted(false);
cmdReconfig.setFocusPainted(false);
cmdReconfig.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdReconfigActionPerformed(evt);
}
});
tlbMain.add(cmdReconfig);
jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator1.setMaximumSize(new java.awt.Dimension(2, 32767));
jSeparator1.setPreferredSize(new java.awt.Dimension(2, 10));
tlbMain.add(jSeparator1);
cmdBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/back.png"))); // NOI18N
cmdBack.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdBack.toolTipText")); // NOI18N
cmdBack.setBorderPainted(false);
cmdBack.setFocusPainted(false);
cmdBack.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdBackActionPerformed(evt);
}
});
tlbMain.add(cmdBack);
cmdHome.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/home.gif"))); // NOI18N
cmdHome.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdHome.toolTipText")); // NOI18N
cmdHome.setBorderPainted(false);
cmdHome.setFocusPainted(false);
cmdHome.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdHomeActionPerformed(evt);
}
});
tlbMain.add(cmdHome);
cmdForward.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/forward.png"))); // NOI18N
cmdForward.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdForward.toolTipText")); // NOI18N
cmdForward.setBorderPainted(false);
cmdForward.setFocusPainted(false);
tlbMain.add(cmdForward);
jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator2.setMaximumSize(new java.awt.Dimension(2, 32767));
jSeparator2.setPreferredSize(new java.awt.Dimension(2, 10));
tlbMain.add(jSeparator2);
cmdRefresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/reload.gif"))); // NOI18N
cmdRefresh.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdRefresh.toolTipText")); // NOI18N
cmdRefresh.setBorderPainted(false);
cmdRefresh.setFocusPainted(false);
cmdRefresh.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdRefreshActionPerformed(evt);
}
});
tlbMain.add(cmdRefresh);
jSeparator6.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator6.setMaximumSize(new java.awt.Dimension(2, 32767));
jSeparator6.setPreferredSize(new java.awt.Dimension(2, 10));
tlbMain.add(jSeparator6);
cmdPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/frameprint.png"))); // NOI18N
cmdPrint.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.cmdPrint.text")); // NOI18N
cmdPrint.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdPrint.toolTipText")); // NOI18N
cmdPrint.setBorderPainted(false);
cmdPrint.setFocusPainted(false);
cmdPrint.setName("cmdPrint"); // NOI18N
cmdPrint.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdPrintActionPerformed(evt);
}
});
tlbMain.add(cmdPrint);
cmdClipboard.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/clipboard.png"))); // NOI18N
cmdClipboard.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdClipboard.text")); // NOI18N
cmdClipboard.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdClipboard.toolTipText")); // NOI18N
cmdClipboard.setBorderPainted(false);
cmdClipboard.setFocusPainted(false);
cmdClipboard.setName("cmdClipboard"); // NOI18N
cmdClipboard.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdClipboardActionPerformed(evt);
}
});
tlbMain.add(cmdClipboard);
cmdDownloads.setAction(new DownloadManagerAction(this));
cmdDownloads.setBorderPainted(false);
tlbMain.add(cmdDownloads);
jSeparator4.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator4.setMaximumSize(new java.awt.Dimension(2, 32767));
jSeparator4.setPreferredSize(new java.awt.Dimension(2, 10));
tlbMain.add(jSeparator4);
cmdGroupPrimaryInteractionMode.add(togInvisible);
togInvisible.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.togInvisible.text")); // NOI18N
togInvisible.setFocusPainted(false);
tlbMain.add(togInvisible);
cmdGroupPrimaryInteractionMode.add(cmdSelect);
cmdSelect.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/select.png"))); // NOI18N
cmdSelect.setSelected(true);
cmdSelect.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdSelect.toolTipText")); // NOI18N
cmdSelect.setBorderPainted(false);
cmdSelect.setFocusPainted(false);
cmdSelect.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdSelectActionPerformed(evt);
}
});
tlbMain.add(cmdSelect);
cmdGroupPrimaryInteractionMode.add(cmdZoom);
cmdZoom.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/zoom.gif"))); // NOI18N
cmdZoom.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdZoom.toolTipText")); // NOI18N
cmdZoom.setBorderPainted(false);
cmdZoom.setFocusPainted(false);
cmdZoom.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdZoomActionPerformed(evt);
}
});
tlbMain.add(cmdZoom);
cmdGroupPrimaryInteractionMode.add(cmdPan);
cmdPan.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/pan.gif"))); // NOI18N
cmdPan.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdPan.toolTipText")); // NOI18N
cmdPan.setBorderPainted(false);
cmdPan.setFocusPainted(false);
cmdPan.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdPanActionPerformed(evt);
}
});
tlbMain.add(cmdPan);
cmdGroupPrimaryInteractionMode.add(cmdFeatureInfo);
cmdFeatureInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/featureInfos.gif"))); // NOI18N
cmdFeatureInfo.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdFeatureInfo.toolTipText")); // NOI18N
cmdFeatureInfo.setBorderPainted(false);
cmdFeatureInfo.setFocusPainted(false);
cmdFeatureInfo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdFeatureInfoActionPerformed(evt);
}
});
tlbMain.add(cmdFeatureInfo);
cmdPluginSearch.setAction(searchAction);
cmdPluginSearch.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/pluginSearchRectangle.png"))); // NOI18N
cmdPluginSearch.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdPluginSearch.toolTipText")); // NOI18N
cmdGroupPrimaryInteractionMode.add(cmdPluginSearch);
cmdPluginSearch.setFocusPainted(false);
tlbMain.add(cmdPluginSearch);
cmdGroupPrimaryInteractionMode.add(cmdNewPolygon);
cmdNewPolygon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/newPolygon.png"))); // NOI18N
cmdNewPolygon.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNewPolygon.toolTipText")); // NOI18N
cmdNewPolygon.setBorderPainted(false);
cmdNewPolygon.setFocusPainted(false);
cmdNewPolygon.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdNewPolygonActionPerformed(evt);
}
});
tlbMain.add(cmdNewPolygon);
cmdGroupPrimaryInteractionMode.add(cmdNewLinestring);
cmdNewLinestring.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/newLinestring.png"))); // NOI18N
cmdNewLinestring.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNewLinestring.toolTipText")); // NOI18N
cmdNewLinestring.setBorderPainted(false);
cmdNewLinestring.setFocusPainted(false);
cmdNewLinestring.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
createGeometryAction(evt);
}
});
tlbMain.add(cmdNewLinestring);
cmdGroupPrimaryInteractionMode.add(cmdNewPoint);
cmdNewPoint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/newPoint.png"))); // NOI18N
cmdNewPoint.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNewPoint.toolTipText")); // NOI18N
cmdNewPoint.setBorderPainted(false);
cmdNewPoint.setFocusPainted(false);
cmdNewPoint.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdNewPointActionPerformed(evt);
}
});
tlbMain.add(cmdNewPoint);
cmdGroupPrimaryInteractionMode.add(cmdNewLinearReferencing);
cmdNewLinearReferencing.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/linref.png"))); // NOI18N
cmdNewLinearReferencing.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNewLinearReferencing.text")); // NOI18N
cmdNewLinearReferencing.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNewLinearReferencing.toolTipText")); // NOI18N
cmdNewLinearReferencing.setFocusPainted(false);
cmdNewLinearReferencing.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdNewLinearReferencingcreateGeometryAction(evt);
}
});
tlbMain.add(cmdNewLinearReferencing);
cmdNewLinearReferencing.setVisible(false);
cmdGroupPrimaryInteractionMode.add(cmdMoveGeometry);
cmdMoveGeometry.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/move.png"))); // NOI18N
cmdMoveGeometry.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdMoveGeometry.toolTipText")); // NOI18N
cmdMoveGeometry.setBorderPainted(false);
cmdMoveGeometry.setFocusPainted(false);
cmdMoveGeometry.setMaximumSize(new java.awt.Dimension(29, 29));
cmdMoveGeometry.setMinimumSize(new java.awt.Dimension(29, 29));
cmdMoveGeometry.setPreferredSize(new java.awt.Dimension(29, 29));
cmdMoveGeometry.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdMoveGeometryActionPerformed(evt);
}
});
tlbMain.add(cmdMoveGeometry);
cmdGroupPrimaryInteractionMode.add(cmdRemoveGeometry);
cmdRemoveGeometry.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.png"))); // NOI18N
cmdRemoveGeometry.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdRemoveGeometry.toolTipText")); // NOI18N
cmdRemoveGeometry.setBorderPainted(false);
cmdRemoveGeometry.setFocusPainted(false);
cmdRemoveGeometry.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdRemoveGeometryActionPerformed(evt);
}
});
tlbMain.add(cmdRemoveGeometry);
jSeparator3.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator3.setMaximumSize(new java.awt.Dimension(2, 32767));
jSeparator3.setPreferredSize(new java.awt.Dimension(2, 10));
tlbMain.add(jSeparator3);
cmdGroupNodes.add(cmdNodeMove);
cmdNodeMove.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/moveNodes.png"))); // NOI18N
cmdNodeMove.setSelected(true);
cmdNodeMove.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNodeMove.toolTipText")); // NOI18N
cmdNodeMove.setBorderPainted(false);
cmdNodeMove.setFocusPainted(false);
cmdNodeMove.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdNodeMoveActionPerformed(evt);
}
});
tlbMain.add(cmdNodeMove);
cmdGroupNodes.add(cmdNodeAdd);
cmdNodeAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/insertNodes.png"))); // NOI18N
cmdNodeAdd.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNodeAdd.toolTipText")); // NOI18N
cmdNodeAdd.setBorderPainted(false);
cmdNodeAdd.setFocusPainted(false);
cmdNodeAdd.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdNodeAddActionPerformed(evt);
}
});
tlbMain.add(cmdNodeAdd);
cmdGroupNodes.add(cmdNodeRemove);
cmdNodeRemove.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/removeNodes.png"))); // NOI18N
cmdNodeRemove.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNodeRemove.toolTipText")); // NOI18N
cmdNodeRemove.setBorderPainted(false);
cmdNodeRemove.setFocusPainted(false);
cmdNodeRemove.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdNodeRemoveActionPerformed(evt);
}
});
tlbMain.add(cmdNodeRemove);
cmdGroupNodes.add(cmdNodeRotateGeometry);
cmdNodeRotateGeometry.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/rotate.png"))); // NOI18N
cmdNodeRotateGeometry.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdNodeRotateGeometry.toolTipText")); // NOI18N
cmdNodeRotateGeometry.setBorderPainted(false);
cmdNodeRotateGeometry.setFocusPainted(false);
cmdNodeRotateGeometry.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdNodeRotateGeometryActionPerformed(evt);
}
});
tlbMain.add(cmdNodeRotateGeometry);
jSeparator5.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator5.setMaximumSize(new java.awt.Dimension(2, 32767));
jSeparator5.setPreferredSize(new java.awt.Dimension(2, 10));
tlbMain.add(jSeparator5);
cmdSnap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/snap.png"))); // NOI18N
cmdSnap.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdSnap.toolTipText")); // NOI18N
cmdSnap.setBorderPainted(false);
cmdSnap.setFocusPainted(false);
cmdSnap.setMaximumSize(new java.awt.Dimension(29, 29));
cmdSnap.setMinimumSize(new java.awt.Dimension(29, 29));
cmdSnap.setPreferredSize(new java.awt.Dimension(29, 29));
cmdSnap.setRolloverSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/images/snap_selected.png"))); // NOI18N
cmdSnap.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/images/snap_selected.png"))); // NOI18N
cmdSnap.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmdSnapActionPerformed(evt);
}
});
tlbMain.add(cmdSnap);
jSeparator11.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator11.setMaximumSize(new java.awt.Dimension(2, 32767));
jSeparator11.setPreferredSize(new java.awt.Dimension(2, 10));
tlbMain.add(jSeparator11);
cmdUndo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/undo.png"))); // NOI18N
cmdUndo.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdUndo.toolTipText")); // NOI18N
cmdUndo.setBorderPainted(false);
cmdUndo.setEnabled(false);
cmdUndo.setFocusPainted(false);
cmdUndo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniUndoPerformed(evt);
}
});
tlbMain.add(cmdUndo);
cmdRedo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/redo.png"))); // NOI18N
cmdRedo.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.cmdRedo.toolTipText")); // NOI18N
cmdRedo.setBorderPainted(false);
cmdRedo.setEnabled(false);
cmdRedo.setFocusPainted(false);
cmdRedo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniRedoPerformed(evt);
}
});
tlbMain.add(cmdRedo);
panMain.add(tlbMain, java.awt.BorderLayout.NORTH);
panAll.add(panMain, java.awt.BorderLayout.CENTER);
panStatus.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 4, 1, 4));
panStatus.setLayout(new java.awt.BorderLayout());
panAll.add(panStatus, java.awt.BorderLayout.SOUTH);
getContentPane().add(panAll, java.awt.BorderLayout.CENTER);
menFile.setMnemonic('D');
menFile.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.menFile.text")); // NOI18N
mniLoadConfig.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_L,
java.awt.event.InputEvent.CTRL_MASK));
mniLoadConfig.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/config.png"))); // NOI18N
mniLoadConfig.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLoadConfig.text")); // NOI18N
mniLoadConfig.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLoadConfig.tooltip")); // NOI18N
mniLoadConfig.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniLoadConfigActionPerformed(evt);
}
});
menFile.add(mniLoadConfig);
mniSaveConfig.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_K,
java.awt.event.InputEvent.CTRL_MASK));
mniSaveConfig.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/config.png"))); // NOI18N
mniSaveConfig.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSaveConfig.text")); // NOI18N
mniSaveConfig.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSaveConfig.tooltip")); // NOI18N
mniSaveConfig.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniSaveConfigActionPerformed(evt);
}
});
menFile.add(mniSaveConfig);
mniLoadConfigFromServer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/config.png"))); // NOI18N
mniLoadConfigFromServer.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLoadConfigFromServer.text")); // NOI18N
mniLoadConfigFromServer.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLoadConfigFromServer.tooltip")); // NOI18N
mniLoadConfigFromServer.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniLoadConfigFromServerActionPerformed(evt);
}
});
menFile.add(mniLoadConfigFromServer);
sepServerProfilesStart.setName("sepServerProfilesStart"); // NOI18N
menFile.add(sepServerProfilesStart);
sepServerProfilesEnd.setName("sepServerProfilesEnd"); // NOI18N
menFile.add(sepServerProfilesEnd);
mniSaveLayout.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_S,
java.awt.event.InputEvent.CTRL_MASK));
mniSaveLayout.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/layout.png"))); // NOI18N
mniSaveLayout.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSaveLayout.text")); // NOI18N
mniSaveLayout.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSaveLayout.tooltip")); // NOI18N
mniSaveLayout.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniSaveLayoutActionPerformed(evt);
}
});
menFile.add(mniSaveLayout);
mniLoadLayout.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_O,
java.awt.event.InputEvent.CTRL_MASK));
mniLoadLayout.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/layout.png"))); // NOI18N
mniLoadLayout.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLoadLayout.text")); // NOI18N
mniLoadLayout.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLoadLayout.tooltip")); // NOI18N
mniLoadLayout.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniLoadLayoutActionPerformed(evt);
}
});
menFile.add(mniLoadLayout);
menFile.add(jSeparator9);
mniClipboard.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_C,
java.awt.event.InputEvent.CTRL_MASK));
mniClipboard.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/clipboard16.png"))); // NOI18N
mniClipboard.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniClipboard.text")); // NOI18N
mniClipboard.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniClipboard.tooltip")); // NOI18N
mniClipboard.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniClipboardActionPerformed(evt);
}
});
menFile.add(mniClipboard);
mniGeoLinkClipboard.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_C,
java.awt.event.InputEvent.ALT_MASK
| java.awt.event.InputEvent.CTRL_MASK));
mniGeoLinkClipboard.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/clipboard16.png"))); // NOI18N
mniGeoLinkClipboard.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniGeoLinkClipboard.text")); // NOI18N
mniGeoLinkClipboard.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniGeoLinkClipboard.tooltip")); // NOI18N
mniGeoLinkClipboard.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniGeoLinkClipboardActionPerformed(evt);
}
});
menFile.add(mniGeoLinkClipboard);
mniPrint.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_P,
java.awt.event.InputEvent.CTRL_MASK));
mniPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/frameprint16.png"))); // NOI18N
mniPrint.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniPrint.text")); // NOI18N
mniPrint.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniPrint.tooltip")); // NOI18N
mniPrint.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniPrintActionPerformed(evt);
}
});
menFile.add(mniPrint);
menFile.add(jSeparator10);
mniClose.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_F4,
java.awt.event.InputEvent.ALT_MASK));
mniClose.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniClose.text")); // NOI18N
mniClose.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniClose.tooltip")); // NOI18N
mniClose.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniCloseActionPerformed(evt);
}
});
menFile.add(mniClose);
mnuBar.add(menFile);
menEdit.setMnemonic('B');
menEdit.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.menEdit.text")); // NOI18N
menEdit.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
menEditActionPerformed(evt);
}
});
mniRefresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/reload16.gif"))); // NOI18N
mniRefresh.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniRefresh.text")); // NOI18N
mniRefresh.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniRefresh.tooltip")); // NOI18N
mniRefresh.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniRefreshActionPerformed(evt);
}
});
menEdit.add(mniRefresh);
menEdit.add(jSeparator13);
mniZoomToSelectedObjects.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/gui/res/zoomToSelection.png"))); // NOI18N
mniZoomToSelectedObjects.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniZoomToSelectedObjects.text")); // NOI18N
mniZoomToSelectedObjects.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniZoomToSelectedObjects.tooltip")); // NOI18N
mniZoomToSelectedObjects.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniZoomToSelectedObjectsActionPerformed(evt);
}
});
menEdit.add(mniZoomToSelectedObjects);
mniZoomToAllObjects.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/gui/res/zoomToAll.png"))); // NOI18N
mniZoomToAllObjects.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniZoomToAllObjects.text")); // NOI18N
mniZoomToAllObjects.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniZoomToAllObjects.tooltip")); // NOI18N
mniZoomToAllObjects.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniZoomToAllObjectsActionPerformed(evt);
}
});
menEdit.add(mniZoomToAllObjects);
menEdit.add(jSeparator15);
mniRemoveSelectedObject.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/gui/res/removerow.png"))); // NOI18N
mniRemoveSelectedObject.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniRemoveSelectedObject.text")); // NOI18N
mniRemoveSelectedObject.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniRemoveSelectedObject.tooltip")); // NOI18N
mniRemoveSelectedObject.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniRemoveSelectedObjectActionPerformed(evt);
}
});
menEdit.add(mniRemoveSelectedObject);
mniRemoveAllObjects.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/gui/res/removeAll.png"))); // NOI18N
mniRemoveAllObjects.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniRemoveAllObjects.text")); // NOI18N
mniRemoveAllObjects.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniRemoveAllObjects.tooltip")); // NOI18N
mniRemoveAllObjects.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniRemoveAllObjectsActionPerformed(evt);
}
});
menEdit.add(mniRemoveAllObjects);
mnuBar.add(menEdit);
menHistory.setMnemonic('C');
menHistory.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.menHistory.text")); // NOI18N
mniBack.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_LEFT,
java.awt.event.InputEvent.CTRL_MASK));
mniBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/back16.png"))); // NOI18N
mniBack.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniBack.text")); // NOI18N
mniBack.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniBack.tooltip")); // NOI18N
mniBack.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniBackActionPerformed(evt);
}
});
menHistory.add(mniBack);
mniForward.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_RIGHT,
java.awt.event.InputEvent.CTRL_MASK));
mniForward.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/forward16.png"))); // NOI18N
mniForward.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniForward.text")); // NOI18N
mniForward.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniForward.tooltip")); // NOI18N
mniForward.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniForwardActionPerformed(evt);
}
});
menHistory.add(mniForward);
mniHome.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_HOME, 0));
mniHome.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/home16.png"))); // NOI18N
mniHome.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniHome.text")); // NOI18N
mniHome.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniHome.tooltip")); // NOI18N
mniHome.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniHomeActionPerformed(evt);
}
});
menHistory.add(mniHome);
menHistory.add(sepBeforePos);
menHistory.add(sepAfterPos);
mniHistorySidebar.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniHistorySidebar.text")); // NOI18N
mniHistorySidebar.setEnabled(false);
menHistory.add(mniHistorySidebar);
mnuBar.add(menHistory);
menSearch.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.menSearch.text")); // NOI18N
menSearch.addMenuListener(new javax.swing.event.MenuListener() {
@Override
public void menuCanceled(final javax.swing.event.MenuEvent evt) {
}
@Override
public void menuDeselected(final javax.swing.event.MenuEvent evt) {
}
@Override
public void menuSelected(final javax.swing.event.MenuEvent evt) {
menSearchMenuSelected(evt);
}
});
mniSearchRectangle.setAction(searchRectangleAction);
cmdGroupSearch.add(mniSearchRectangle);
mniSearchRectangle.setSelected(true);
mniSearchRectangle.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchRectangle.text")); // NOI18N
mniSearchRectangle.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchRectangle.tooltip")); // NOI18N
mniSearchRectangle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/rectangle.png"))); // NOI18N
menSearch.add(mniSearchRectangle);
mniSearchPolygon.setAction(searchPolygonAction);
cmdGroupSearch.add(mniSearchPolygon);
mniSearchPolygon.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchPolygon.text")); // NOI18N
mniSearchPolygon.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchPolygon.tooltip")); // NOI18N
mniSearchPolygon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/polygon.png"))); // NOI18N
menSearch.add(mniSearchPolygon);
mniSearchEllipse.setAction(searchEllipseAction);
cmdGroupSearch.add(mniSearchEllipse);
mniSearchEllipse.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchEllipse.text_1")); // NOI18N
mniSearchEllipse.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchEllipse.tooltip")); // NOI18N
mniSearchEllipse.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ellipse.png"))); // NOI18N
menSearch.add(mniSearchEllipse);
mniSearchPolyline.setAction(searchPolylineAction);
cmdGroupSearch.add(mniSearchPolyline);
mniSearchPolyline.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchPolyline.text_1")); // NOI18N
mniSearchPolyline.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchLine.tooltip")); // NOI18N
mniSearchPolyline.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/polyline.png"))); // NOI18N
menSearch.add(mniSearchPolyline);
menSearch.add(jSeparator8);
mniSearchCidsFeature.setAction(searchCidsFeatureAction);
cmdGroupSearch.add(mniSearchCidsFeature);
mniSearchCidsFeature.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchCidsFeature.text")); // NOI18N
mniSearchCidsFeature.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchCidsFeature.tooltip")); // NOI18N
mniSearchCidsFeature.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/polygon.png"))); // NOI18N
mniSearchCidsFeature.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniSearchCidsFeatureActionPerformed(evt);
}
});
menSearch.add(mniSearchCidsFeature);
mniSearchShowLastFeature.setAction(searchShowLastFeatureAction);
mniSearchShowLastFeature.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Y,
java.awt.event.InputEvent.CTRL_MASK));
mniSearchShowLastFeature.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchShowLastFeature.text")); // NOI18N
mniSearchShowLastFeature.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchShowLastFeature.toolTipText")); // NOI18N
menSearch.add(mniSearchShowLastFeature);
mniSearchRedo.setAction(searchRedoAction);
mniSearchRedo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Y,
java.awt.event.InputEvent.ALT_MASK
| java.awt.event.InputEvent.CTRL_MASK));
mniSearchRedo.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchRedo.text")); // NOI18N
mniSearchRedo.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchRedo.toolTipText")); // NOI18N
menSearch.add(mniSearchRedo);
mniSearchBuffer.setAction(searchBufferAction);
mniSearchBuffer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/buffer.png"))); // NOI18N
mniSearchBuffer.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchBuffer.text_1")); // NOI18N
mniSearchBuffer.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniSearchBuffer.toolTipText")); // NOI18N
menSearch.add(mniSearchBuffer);
mnuBar.add(menSearch);
// copyMenu(menSearch, popMenSearch);
((JPopupMenuButton)cmdPluginSearch).setPopupMenu(popMenSearch);
menExtras.setMnemonic('E');
menExtras.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.menExtras.text")); // NOI18N
mniOptions.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/tooloptions.png"))); // NOI18N
mniOptions.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniOptions.text")); // NOI18N
mniOptions.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniOptions.tooltip")); // NOI18N
mniOptions.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniOptionsActionPerformed(evt);
}
});
menExtras.add(mniOptions);
menExtras.add(jSeparator16);
mniBufferSelectedGeom.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_B,
java.awt.event.InputEvent.CTRL_MASK));
mniBufferSelectedGeom.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/buffer.png"))); // NOI18N
mniBufferSelectedGeom.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniBufferSelectedGeom.text")); // NOI18N
mniBufferSelectedGeom.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniBufferSelectedGeom.tooltip")); // NOI18N
mniBufferSelectedGeom.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniBufferSelectedGeomActionPerformed(evt);
}
});
menExtras.add(mniBufferSelectedGeom);
menExtras.add(jSeparator17);
mniGotoPoint.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_G,
java.awt.event.InputEvent.CTRL_MASK));
mniGotoPoint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/goto.png"))); // NOI18N
mniGotoPoint.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniGotoPoint.text")); // NOI18N
mniGotoPoint.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniGotoPoint.tooltip")); // NOI18N
mniGotoPoint.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniGotoPointActionPerformed(evt);
}
});
menExtras.add(mniGotoPoint);
menExtras.add(jSeparator14);
mniScale.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_M,
java.awt.event.InputEvent.CTRL_MASK));
mniScale.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/scale.png"))); // NOI18N
mniScale.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniScale.text")); // NOI18N
mniScale.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniScale.tooltip")); // NOI18N
mniScale.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniScaleActionPerformed(evt);
}
});
menExtras.add(mniScale);
mnuBar.add(menExtras);
menWindows.setMnemonic('F');
menWindows.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.menWindows.text")); // NOI18N
menWindows.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
menWindowsActionPerformed(evt);
}
});
mniLayer.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_1,
java.awt.event.InputEvent.CTRL_MASK));
mniLayer.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/raster/wms/res/layers.png"))); // NOI18N
mniLayer.setMnemonic('L');
mniLayer.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniLayer.text")); // NOI18N
mniLayer.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLayer.tooltip")); // NOI18N
mniLayer.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniLayerActionPerformed(evt);
}
});
menWindows.add(mniLayer);
mniCapabilities.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_2,
java.awt.event.InputEvent.CTRL_MASK));
mniCapabilities.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/raster/wms/res/server.png"))); // NOI18N
mniCapabilities.setMnemonic('C');
mniCapabilities.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniCapabilities.text")); // NOI18N
mniCapabilities.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniCapabilities.tooltip")); // NOI18N
mniCapabilities.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniCapabilitiesActionPerformed(evt);
}
});
menWindows.add(mniCapabilities);
mniFeatureInfo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_3,
java.awt.event.InputEvent.CTRL_MASK));
mniFeatureInfo.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/gui/featureinfowidget/res/featureInfo16.png"))); // NOI18N
mniFeatureInfo.setMnemonic('F');
mniFeatureInfo.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniFeatureInfo.text")); // NOI18N
mniFeatureInfo.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniFeatureInfo.tooltip")); // NOI18N
mniFeatureInfo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniFeatureInfoActionPerformed(evt);
}
});
menWindows.add(mniFeatureInfo);
mniServerInfo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_5,
java.awt.event.InputEvent.CTRL_MASK));
mniServerInfo.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/gui/capabilitywidget/res/serverInfo.png"))); // NOI18N
mniServerInfo.setMnemonic('S');
mniServerInfo.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniServerInfo.text")); // NOI18N
mniServerInfo.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniServerInfo.tooltip")); // NOI18N
mniServerInfo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniServerInfoActionPerformed(evt);
}
});
menWindows.add(mniServerInfo);
mniLayerInfo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_6,
java.awt.event.InputEvent.CTRL_MASK));
mniLayerInfo.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/commons/gui/capabilitywidget/res/layerInfo.png"))); // NOI18N
mniLayerInfo.setMnemonic('L');
mniLayerInfo.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLayerInfo.text")); // NOI18N
mniLayerInfo.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLayerInfo.tooltip")); // NOI18N
mniLayerInfo.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniLayerInfoActionPerformed(evt);
}
});
menWindows.add(mniLayerInfo);
mniLegend.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_7,
java.awt.event.InputEvent.CTRL_MASK));
mniLegend.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/navigatorplugin/res/legend.png"))); // NOI18N
mniLegend.setMnemonic('L');
mniLegend.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniLegend.text")); // NOI18N
mniLegend.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniLegend.tooltip")); // NOI18N
mniLegend.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniLegendActionPerformed(evt);
}
});
menWindows.add(mniLegend);
mniFeatureControl.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_8,
java.awt.event.InputEvent.CTRL_MASK));
mniFeatureControl.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/objects.png"))); // NOI18N
mniFeatureControl.setMnemonic('O');
mniFeatureControl.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniFeatureControl.text")); // NOI18N
mniFeatureControl.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniFeatureControl.tooltip")); // NOI18N
mniFeatureControl.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniFeatureControlActionPerformed(evt);
}
});
menWindows.add(mniFeatureControl);
mniMap.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_9,
java.awt.event.InputEvent.CTRL_MASK));
mniMap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cismap/navigatorplugin/map.png"))); // NOI18N
mniMap.setMnemonic('M');
mniMap.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniMap.text")); // NOI18N
mniMap.setToolTipText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniMap.tooltip")); // NOI18N
mniMap.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniMapActionPerformed(evt);
}
});
menWindows.add(mniMap);
mniOverview.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_0,
java.awt.event.InputEvent.CTRL_MASK));
mniOverview.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cismap/navigatorplugin/map.png"))); // NOI18N
mniOverview.setMnemonic('M');
mniOverview.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniOverview.text")); // NOI18N
mniOverview.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniOverview.tooltip")); // NOI18N
mniOverview.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniOverviewActionPerformed(evt);
}
});
menWindows.add(mniOverview);
menWindows.add(sepResetWindowLayout);
mniResetWindowLayout.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_R,
java.awt.event.InputEvent.CTRL_MASK));
mniResetWindowLayout.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/layout.png"))); // NOI18N
mniResetWindowLayout.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniResetWindowLayout.text")); // NOI18N
mniResetWindowLayout.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniResetWindowLayout.toolTipText")); // NOI18N
mniResetWindowLayout.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniResetWindowLayoutActionPerformed(evt);
}
});
menWindows.add(mniResetWindowLayout);
mnuBar.add(menWindows);
menHelp.setMnemonic('H');
menHelp.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.menHelp.text")); // NOI18N
menHelp.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
menHelpActionPerformed(evt);
}
});
mniOnlineHelp.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
mniOnlineHelp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/help.png"))); // NOI18N
mniOnlineHelp.setText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniOnlineHelp.text")); // NOI18N
mniOnlineHelp.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniOnlineHelp.tooltip")); // NOI18N
mniOnlineHelp.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniOnlineHelpActionPerformed(evt);
}
});
menHelp.add(mniOnlineHelp);
mniNews.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/news.png"))); // NOI18N
mniNews.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniNews.text")); // NOI18N
mniNews.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniNews.tooltip")); // NOI18N
mniNews.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniNewsActionPerformed(evt);
}
});
menHelp.add(mniNews);
mniAbout.setText(org.openide.util.NbBundle.getMessage(CismapPlugin.class, "CismapPlugin.mniAbout.text")); // NOI18N
mniAbout.setToolTipText(org.openide.util.NbBundle.getMessage(
CismapPlugin.class,
"CismapPlugin.mniAbout.tooltip")); // NOI18N
mniAbout.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
mniAboutActionPerformed(evt);
}
});
menHelp.add(mniAbout);
mnuBar.add(menHelp);
setJMenuBar(mnuBar);
} // </editor-fold>//GEN-END:initComponents
|
diff --git a/src/com/avona/games/towerdefence/TickRater.java b/src/com/avona/games/towerdefence/TickRater.java
index 28797ea..b3cf8a3 100644
--- a/src/com/avona/games/towerdefence/TickRater.java
+++ b/src/com/avona/games/towerdefence/TickRater.java
@@ -1,26 +1,30 @@
package com.avona.games.towerdefence;
public class TickRater {
static final float INITIAL_TICKRATE = 60.0f;
public float tickRate = INITIAL_TICKRATE;
public TimeTrack time;
public TickRater(TimeTrack time) {
this.time = time;
}
public void updateTickRate() {
if (!time.isRunning()) {
tickRate = INITIAL_TICKRATE;
return;
}
if (time.tick < 0.00001f) {
Util.log("zero tick: " + time.tick);
return;
}
+ if (time.tick > 1.0f) {
+ tickRate = 0.99f; // less than 1 fps, dont bother
+ return;
+ }
tickRate = (1.0f - time.tick) * tickRate + 1.0f;
}
}
| true | true | public void updateTickRate() {
if (!time.isRunning()) {
tickRate = INITIAL_TICKRATE;
return;
}
if (time.tick < 0.00001f) {
Util.log("zero tick: " + time.tick);
return;
}
tickRate = (1.0f - time.tick) * tickRate + 1.0f;
}
| public void updateTickRate() {
if (!time.isRunning()) {
tickRate = INITIAL_TICKRATE;
return;
}
if (time.tick < 0.00001f) {
Util.log("zero tick: " + time.tick);
return;
}
if (time.tick > 1.0f) {
tickRate = 0.99f; // less than 1 fps, dont bother
return;
}
tickRate = (1.0f - time.tick) * tickRate + 1.0f;
}
|
diff --git a/src/main/java/org/basex/query/expr/GFLWOR.java b/src/main/java/org/basex/query/expr/GFLWOR.java
index 8c16cd73f..846c68dde 100644
--- a/src/main/java/org/basex/query/expr/GFLWOR.java
+++ b/src/main/java/org/basex/query/expr/GFLWOR.java
@@ -1,393 +1,394 @@
package org.basex.query.expr;
import static org.basex.query.QueryText.*;
import java.io.IOException;
import org.basex.io.serial.Serializer;
import org.basex.query.QueryContext;
import org.basex.query.QueryException;
import org.basex.query.func.Function;
import org.basex.query.item.Empty;
import org.basex.query.item.Item;
import org.basex.query.item.SeqType;
import org.basex.query.iter.Iter;
import org.basex.query.path.AxisPath;
import org.basex.query.util.ValueList;
import org.basex.query.util.Var;
import org.basex.util.Array;
import org.basex.util.InputInfo;
import org.basex.util.list.ObjList;
/**
* GFLWOR clause.
*
* @author BaseX Team 2005-11, BSD License
* @author Christian Gruen
*/
public class GFLWOR extends ParseExpr {
/** Return expression. */
protected Expr ret;
/** For/Let expression. */
protected ForLet[] fl;
/** Where clause. */
protected Expr where;
/** Order clause. */
protected Order order;
/** Group by clause. */
protected Group group;
/**
* GFLWOR constructor.
* @param f variable inputs
* @param w where clause
* @param o order expression
* @param g group by expression
* @param r return expression
* @param ii input info
*/
GFLWOR(final ForLet[] f, final Expr w, final Order o, final Group g,
final Expr r, final InputInfo ii) {
super(ii);
ret = r;
fl = f;
where = w;
group = g;
order = o;
}
/**
* Returns a GFLWOR instance.
* @param f variable inputs
* @param w where clause
* @param o order expression
* @param g group by expression
* @param r return expression
* @param ii input info
* @return GFLWOR instance
*/
public static GFLWOR get(final ForLet[] f, final Expr w, final OrderBy[] o,
final Var[][] g, final Expr r, final InputInfo ii) {
if(o == null && g == null) return new FLWR(f, w, r, ii);
final Order ord = o == null ? null : new Order(ii, o);
final Group grp = g == null ? null : new Group(ii, g[0], g[1], g[2]);
return new GFLWOR(f, w, ord, grp, r, ii);
}
@Override
public Expr comp(final QueryContext ctx) throws QueryException {
compHoist(ctx);
compWhere(ctx);
final boolean grp = ctx.grouping;
ctx.grouping = group != null;
// optimize for/let clauses
final int vs = ctx.vars.size();
for(int f = 0; f < fl.length; ++f) {
final ForLet flt = fl[f];
flt.comp(ctx);
// bind variable if it contains a value or occurs only once
if(flt.expr.value() || count(flt.var, f) == 1) flt.bind(ctx);
/* ...or if all inner clauses return only one item. This rewriting would
* disallow repeated evaluations of the same expression, but it prevents
* index-based rewritings (e.g. for XMark 9)
boolean one = true;
for(int g = f + 1; g < fl.length; g++) one &= fl[g].size() == 1;
if(flt.expr.value() || count(flt.var, f) == 1 && one) flt.bind(ctx);
*/
}
// optimize where clause
boolean empty = false;
if(where != null) {
where = checkUp(where, ctx).comp(ctx).compEbv(ctx);
if(where.value()) {
// test is always false: no results
empty = !where.ebv(ctx, input).bool(input);
if(!empty) {
// always true: test can be skipped
ctx.compInfo(OPTREMOVE, desc(), where);
where = null;
}
}
}
if(group != null) group.comp(ctx);
if(order != null) order.comp(ctx);
ret = ret.comp(ctx);
ctx.vars.reset(vs);
ctx.grouping = grp;
// remove FLWOR expression if WHERE clause always returns false
if(empty) {
ctx.compInfo(OPTREMOVE, desc(), where);
return Empty.SEQ;
}
// check if return always yields an empty sequence
if(ret == Empty.SEQ) {
ctx.compInfo(OPTFLWOR);
return ret;
}
// remove declarations of statically bound or unused variables
for(int f = 0; f < fl.length; ++f) {
final ForLet l = fl[f];
- if(l.var.expr() != null || l.simple(true) && count(l.var, f) == 0) {
+ if(l.var.expr() != null || l.simple(true) && count(l.var, f) == 0 &&
+ !l.expr.uses(Use.CTX)) {
ctx.compInfo(OPTVAR, l.var);
fl = Array.delete(fl, f--);
}
}
// no clauses left: simplify expression
// an optional order clause can be safely ignored
if(fl.length == 0) {
// if where clause exists: where A return B -> if A then B else ()
// otherwise: return B -> B
ctx.compInfo(OPTFLWOR);
return where != null ? new If(input, where, ret, Empty.SEQ) : ret;
}
// remove FLWOR expression if a FOR clause yields an empty sequence
for(final ForLet f : fl) {
if(f instanceof For && f.size() == 0) {
ctx.compInfo(OPTFLWOR);
return Empty.SEQ;
}
}
// compute number of results to speed up count() operations
if(where == null && group == null) {
size = ret.size();
if(size != -1) {
// multiply loop runs
for(final ForLet f : fl) {
final long s = f.size();
if(s == -1) {
size = s;
break;
}
size *= s;
}
}
}
type = SeqType.get(ret.type().type, size);
compHoist(ctx);
return this;
}
/**
* Hoists loop-invariant code. Avoids repeated evaluation of independent
* variables that return a single value. This method is called twice
* (before and after all other optimizations).
* @param ctx query context
*/
private void compHoist(final QueryContext ctx) {
// modification counter
int m = 0;
for(int i = 1; i < fl.length; i++) {
final ForLet in = fl[i];
// move clauses upwards that contain a single value.
// expressions that depend on the current context (e.g. math:random())
// or fragment constructors creating unique nodes are ignored
if(in.size() != 1 || in.uses(Use.CTX) || in.uses(Use.CNS)) continue;
// find most outer clause that declares no variables that are used in the
// inner clause
int p = -1;
for(int o = i; o-- != 0 && in.count(fl[o]) == 0; p = o);
if(p == -1) continue;
// move clause
Array.move(fl, p, 1, i - p);
fl[p] = in;
if(m++ == 0) ctx.compInfo(OPTFORLET);
}
}
/**
* Rewrites a where clause to one or more predicates.
* @param ctx query context
*/
private void compWhere(final QueryContext ctx) {
// no where clause specified
if(where == null) return;
// check if all clauses are simple, and if variables are removable
for(final ForLet f : fl) {
if(f instanceof For && (!f.simple(false) || !where.removable(f.var)))
return;
}
// create array with tests
final Expr[] tests = where instanceof And ? ((And) where).expr :
new Expr[] { where };
// find which tests access which variables. if a test will not use any of
// the variables defined in the local context, they will be added to the
// first binding
final int[] tar = new int[tests.length];
for(int t = 0; t < tests.length; ++t) {
int fr = -1;
for(int f = fl.length - 1; f >= 0; --f) {
// remember index of most inner FOR clause
if(fl[f] instanceof For) fr = f;
// predicate is found that uses the current variable
if(tests[t].count(fl[f].var) != 0) {
// stop rewriting if no most inner FOR clause is defined
if(fr == -1) return;
// attach predicate to the corresponding FOR clause, and stop
tar[t] = fr;
break;
}
}
}
// convert where clause to predicate(s)
ctx.compInfo(OPTWHERE);
// bind tests to the corresponding variables
for(int t = 0; t < tests.length; ++t) {
final ForLet f = fl[tar[t]];
// remove variable reference and optionally wrap test with boolean()
Expr e = tests[t].remove(f.var);
e = Function.BOOLEAN.get(input, e).compEbv(ctx);
// attach predicates to axis path or filter, or create a new filter
if(f.expr instanceof AxisPath) {
f.expr = ((AxisPath) f.expr).addPreds(e);
} else if(f.expr instanceof Filter) {
f.expr = ((Filter) f.expr).addPred(e);
} else {
f.expr = new Filter(input, f.expr, e);
}
}
// eliminate where clause
where = null;
}
@Override
public Iter iter(final QueryContext ctx) throws QueryException {
final Iter[] iter = new Iter[fl.length];
final int vs = ctx.vars.size();
for(int f = 0; f < fl.length; ++f) iter[f] = ctx.iter(fl[f]);
// evaluate pre grouping tuples
ObjList<Item[]> keys = null;
ValueList vals = null;
if(order != null) {
keys = new ObjList<Item[]>();
vals = new ValueList();
}
if(group != null) group.init(order);
iter(ctx, iter, 0, keys, vals);
ctx.vars.reset(vs);
for(final ForLet f : fl) ctx.vars.add(f.var);
// order != null, otherwise it would have been handled in group
final Iter ir = group != null ?
group.gp.ret(ctx, ret, keys, vals) : ctx.iter(order.set(keys, vals));
ctx.vars.reset(vs);
return ir;
}
/**
* Performs a recursive iteration on the specified variable position.
* @param ctx query context
* @param it iterator
* @param p variable position
* @param ks sort keys
* @param vs values to sort
* @throws QueryException query exception
*/
private void iter(final QueryContext ctx, final Iter[] it, final int p,
final ObjList<Item[]> ks, final ValueList vs) throws QueryException {
final boolean more = p + 1 != fl.length;
while(it[p].next() != null) {
if(more) {
iter(ctx, it, p + 1, ks, vs);
} else if(where == null || where.ebv(ctx, input).bool(input)) {
if(group != null) {
group.gp.add(ctx);
} else if(order != null) {
// order by will be handled in group by otherwise
order.add(ctx, ret, ks, vs);
}
}
}
}
@Override
public final boolean uses(final Use u) {
return u == Use.VAR || ret.uses(u);
}
@Override
public final int count(final Var v) {
return count(v, 0);
}
/**
* Counts how often the specified variable is used, starting from the
* specified for/let index.
* @param v variable to be checked
* @param i index
* @return number of occurrences
*/
public final int count(final Var v, final int i) {
int c = 0;
for(int f = i; f < fl.length; f++) c += fl[f].count(v);
if(where != null) c += where.count(v);
if(order != null) c += order.count(v);
if(group != null) c += group.count(v);
return c + ret.count(v);
}
@Override
public final boolean removable(final Var v) {
for(final ForLet f : fl) if(!f.removable(v)) return false;
return (where == null || where.removable(v))
&& (order == null || order.removable(v))
&& (group == null || group.removable(v)) && ret.removable(v);
}
@Override
public final Expr remove(final Var v) {
for(final ForLet f : fl) f.remove(v);
if(where != null) where = where.remove(v);
if(order != null) order = order.remove(v);
ret = ret.remove(v);
return this;
}
@Override
public final void plan(final Serializer ser) throws IOException {
ser.openElement(this);
for(final ForLet f : fl) f.plan(ser);
if(where != null) {
ser.openElement(WHR);
where.plan(ser);
ser.closeElement();
}
if(group != null) group.plan(ser);
if(order != null) order.plan(ser);
ser.openElement(RET);
ret.plan(ser);
ser.closeElement();
ser.closeElement();
}
@Override
public final String toString() {
final StringBuilder sb = new StringBuilder();
for(int i = 0; i != fl.length; ++i) sb.append((i != 0 ? " " : "") + fl[i]);
if(where != null) sb.append(" " + WHERE + " " + where);
if(group != null) sb.append(group);
if(order != null) sb.append(order);
return sb.append(" " + RETURN + " " + ret).toString();
}
}
| true | true | public Expr comp(final QueryContext ctx) throws QueryException {
compHoist(ctx);
compWhere(ctx);
final boolean grp = ctx.grouping;
ctx.grouping = group != null;
// optimize for/let clauses
final int vs = ctx.vars.size();
for(int f = 0; f < fl.length; ++f) {
final ForLet flt = fl[f];
flt.comp(ctx);
// bind variable if it contains a value or occurs only once
if(flt.expr.value() || count(flt.var, f) == 1) flt.bind(ctx);
/* ...or if all inner clauses return only one item. This rewriting would
* disallow repeated evaluations of the same expression, but it prevents
* index-based rewritings (e.g. for XMark 9)
boolean one = true;
for(int g = f + 1; g < fl.length; g++) one &= fl[g].size() == 1;
if(flt.expr.value() || count(flt.var, f) == 1 && one) flt.bind(ctx);
*/
}
// optimize where clause
boolean empty = false;
if(where != null) {
where = checkUp(where, ctx).comp(ctx).compEbv(ctx);
if(where.value()) {
// test is always false: no results
empty = !where.ebv(ctx, input).bool(input);
if(!empty) {
// always true: test can be skipped
ctx.compInfo(OPTREMOVE, desc(), where);
where = null;
}
}
}
if(group != null) group.comp(ctx);
if(order != null) order.comp(ctx);
ret = ret.comp(ctx);
ctx.vars.reset(vs);
ctx.grouping = grp;
// remove FLWOR expression if WHERE clause always returns false
if(empty) {
ctx.compInfo(OPTREMOVE, desc(), where);
return Empty.SEQ;
}
// check if return always yields an empty sequence
if(ret == Empty.SEQ) {
ctx.compInfo(OPTFLWOR);
return ret;
}
// remove declarations of statically bound or unused variables
for(int f = 0; f < fl.length; ++f) {
final ForLet l = fl[f];
if(l.var.expr() != null || l.simple(true) && count(l.var, f) == 0) {
ctx.compInfo(OPTVAR, l.var);
fl = Array.delete(fl, f--);
}
}
// no clauses left: simplify expression
// an optional order clause can be safely ignored
if(fl.length == 0) {
// if where clause exists: where A return B -> if A then B else ()
// otherwise: return B -> B
ctx.compInfo(OPTFLWOR);
return where != null ? new If(input, where, ret, Empty.SEQ) : ret;
}
// remove FLWOR expression if a FOR clause yields an empty sequence
for(final ForLet f : fl) {
if(f instanceof For && f.size() == 0) {
ctx.compInfo(OPTFLWOR);
return Empty.SEQ;
}
}
// compute number of results to speed up count() operations
if(where == null && group == null) {
size = ret.size();
if(size != -1) {
// multiply loop runs
for(final ForLet f : fl) {
final long s = f.size();
if(s == -1) {
size = s;
break;
}
size *= s;
}
}
}
type = SeqType.get(ret.type().type, size);
compHoist(ctx);
return this;
}
| public Expr comp(final QueryContext ctx) throws QueryException {
compHoist(ctx);
compWhere(ctx);
final boolean grp = ctx.grouping;
ctx.grouping = group != null;
// optimize for/let clauses
final int vs = ctx.vars.size();
for(int f = 0; f < fl.length; ++f) {
final ForLet flt = fl[f];
flt.comp(ctx);
// bind variable if it contains a value or occurs only once
if(flt.expr.value() || count(flt.var, f) == 1) flt.bind(ctx);
/* ...or if all inner clauses return only one item. This rewriting would
* disallow repeated evaluations of the same expression, but it prevents
* index-based rewritings (e.g. for XMark 9)
boolean one = true;
for(int g = f + 1; g < fl.length; g++) one &= fl[g].size() == 1;
if(flt.expr.value() || count(flt.var, f) == 1 && one) flt.bind(ctx);
*/
}
// optimize where clause
boolean empty = false;
if(where != null) {
where = checkUp(where, ctx).comp(ctx).compEbv(ctx);
if(where.value()) {
// test is always false: no results
empty = !where.ebv(ctx, input).bool(input);
if(!empty) {
// always true: test can be skipped
ctx.compInfo(OPTREMOVE, desc(), where);
where = null;
}
}
}
if(group != null) group.comp(ctx);
if(order != null) order.comp(ctx);
ret = ret.comp(ctx);
ctx.vars.reset(vs);
ctx.grouping = grp;
// remove FLWOR expression if WHERE clause always returns false
if(empty) {
ctx.compInfo(OPTREMOVE, desc(), where);
return Empty.SEQ;
}
// check if return always yields an empty sequence
if(ret == Empty.SEQ) {
ctx.compInfo(OPTFLWOR);
return ret;
}
// remove declarations of statically bound or unused variables
for(int f = 0; f < fl.length; ++f) {
final ForLet l = fl[f];
if(l.var.expr() != null || l.simple(true) && count(l.var, f) == 0 &&
!l.expr.uses(Use.CTX)) {
ctx.compInfo(OPTVAR, l.var);
fl = Array.delete(fl, f--);
}
}
// no clauses left: simplify expression
// an optional order clause can be safely ignored
if(fl.length == 0) {
// if where clause exists: where A return B -> if A then B else ()
// otherwise: return B -> B
ctx.compInfo(OPTFLWOR);
return where != null ? new If(input, where, ret, Empty.SEQ) : ret;
}
// remove FLWOR expression if a FOR clause yields an empty sequence
for(final ForLet f : fl) {
if(f instanceof For && f.size() == 0) {
ctx.compInfo(OPTFLWOR);
return Empty.SEQ;
}
}
// compute number of results to speed up count() operations
if(where == null && group == null) {
size = ret.size();
if(size != -1) {
// multiply loop runs
for(final ForLet f : fl) {
final long s = f.size();
if(s == -1) {
size = s;
break;
}
size *= s;
}
}
}
type = SeqType.get(ret.type().type, size);
compHoist(ctx);
return this;
}
|
diff --git a/src/main/java/com/github/pmerienne/trident/cf/UpdateUserSimilarity.java b/src/main/java/com/github/pmerienne/trident/cf/UpdateUserSimilarity.java
index ee12254..720c830 100644
--- a/src/main/java/com/github/pmerienne/trident/cf/UpdateUserSimilarity.java
+++ b/src/main/java/com/github/pmerienne/trident/cf/UpdateUserSimilarity.java
@@ -1,142 +1,146 @@
/**
* Copyright 2013-2015 Pierre Merienne
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.pmerienne.trident.cf;
import java.util.List;
import com.github.pmerienne.trident.cf.state.CFState;
import storm.trident.operation.TridentCollector;
import storm.trident.state.BaseStateUpdater;
import storm.trident.tuple.TridentTuple;
public class UpdateUserSimilarity extends BaseStateUpdater<CFState> {
private static final long serialVersionUID = -6168810550629879261L;
@Override
public void updateState(CFState state, List<TridentTuple> tuples, TridentCollector collector) {
for (TridentTuple tuple : tuples) {
this.updateUserSimilarity(state, tuple, collector);
}
}
public void updateUserSimilarity(CFState state, TridentTuple tuple, TridentCollector collector) {
long user1 = this.getUser1(tuple);
long user2 = this.getUser2(tuple);
@SuppressWarnings("unused")
long item = this.getItem(tuple);
double user1NewRating = this.getUser1NewRating(tuple);
Double user1OldRating = this.getUser1OldRating(tuple);
Double user2Rating = this.getUser2Rating(tuple);
double user1NewAverageRating = this.getNewAverageRating(tuple);
double user1OldAverageRating = this.getOldAverageRating(tuple);
double averageRatingDifference = user1NewAverageRating - user1OldAverageRating;
double user2AverageRating = state.getAverageRating(user2);
long coRatedCount = this.getOldCoRatedCount(tuple);
double coRatedSum1 = this.getOldCoRatedSum1(tuple);
double coRatedSum2 = this.getOldCoRatedSum2(tuple);
double magic1 = averageRatingDifference * (coRatedSum1 - coRatedCount * user1OldAverageRating);
double magic2 = averageRatingDifference * (coRatedSum2 - coRatedCount * user2AverageRating);
double e = 0, f = 0, g = 0;
if (user1OldRating == null) {
if (user2Rating != null) {
// Submission of a new rating and uy had rated ia
e = (user1NewRating - user1NewAverageRating) * (user2Rating - user2AverageRating) - magic2;
f = Math.pow(user1NewRating - user1NewAverageRating, 2) + coRatedCount * Math.pow(averageRatingDifference, 2) - 2 * magic1;
g = Math.pow(user2Rating - user2AverageRating, 2);
} else {
// Submission of a new rating and uy had not rated ia
e = -magic2;
f = coRatedCount * Math.pow(averageRatingDifference, 2) - 2 * magic1;
g = 0.0;
}
} else {
double druaia = user1NewRating - user1OldRating;
if (user2Rating != null) {
// Update of an existing rating and uy had rated ia
e = druaia * (user2Rating - user2AverageRating) - magic2;
f = Math.pow(druaia, 2) + 2 * druaia * (user1OldRating - user1NewAverageRating) + coRatedCount * Math.pow(averageRatingDifference, 2) - 2 * magic1;
g = 0.0;
} else {
// Update of an existing rating and uy had not rated ia
e = -magic2;
f = coRatedCount * Math.pow(averageRatingDifference, 2) - 2 * magic1;
g = 0.0;
}
}
// Update cached a, b, c, d
Double b = state.getB(user1, user2);
Double c = state.getC(user1, user2);
Double d = state.getD(user1, user2);
b = b + e;
c = c + f;
d = d + g;
- state.setA(user1, user2, b / (Math.sqrt(c) * Math.sqrt(d)));
+ double a = b / (Math.sqrt(c) * Math.sqrt(d));
+ if (Double.isInfinite(a) || Double.isNaN(a)) {
+ a = -1.0;
+ }
+ state.setA(user1, user2, a);
state.setB(user1, user2, b);
state.setC(user1, user2, c);
state.setD(user1, user2, d);
}
protected long getUser1(TridentTuple tuple) {
return tuple.getLong(0);
}
protected long getUser2(TridentTuple tuple) {
return tuple.getLong(1);
}
protected long getItem(TridentTuple tuple) {
return tuple.getLong(2);
}
private double getUser1NewRating(TridentTuple tuple) {
return tuple.getDouble(3);
}
private Double getUser1OldRating(TridentTuple tuple) {
return tuple.getDouble(4);
}
private Double getUser2Rating(TridentTuple tuple) {
return tuple.getDouble(5);
}
private double getNewAverageRating(TridentTuple tuple) {
return tuple.getDouble(6);
}
private Double getOldAverageRating(TridentTuple tuple) {
return tuple.getDouble(7);
}
private long getOldCoRatedCount(TridentTuple tuple) {
return tuple.getLong(8);
}
private double getOldCoRatedSum1(TridentTuple tuple) {
return tuple.getDouble(9);
}
private double getOldCoRatedSum2(TridentTuple tuple) {
return tuple.getDouble(10);
}
}
| true | true | public void updateUserSimilarity(CFState state, TridentTuple tuple, TridentCollector collector) {
long user1 = this.getUser1(tuple);
long user2 = this.getUser2(tuple);
@SuppressWarnings("unused")
long item = this.getItem(tuple);
double user1NewRating = this.getUser1NewRating(tuple);
Double user1OldRating = this.getUser1OldRating(tuple);
Double user2Rating = this.getUser2Rating(tuple);
double user1NewAverageRating = this.getNewAverageRating(tuple);
double user1OldAverageRating = this.getOldAverageRating(tuple);
double averageRatingDifference = user1NewAverageRating - user1OldAverageRating;
double user2AverageRating = state.getAverageRating(user2);
long coRatedCount = this.getOldCoRatedCount(tuple);
double coRatedSum1 = this.getOldCoRatedSum1(tuple);
double coRatedSum2 = this.getOldCoRatedSum2(tuple);
double magic1 = averageRatingDifference * (coRatedSum1 - coRatedCount * user1OldAverageRating);
double magic2 = averageRatingDifference * (coRatedSum2 - coRatedCount * user2AverageRating);
double e = 0, f = 0, g = 0;
if (user1OldRating == null) {
if (user2Rating != null) {
// Submission of a new rating and uy had rated ia
e = (user1NewRating - user1NewAverageRating) * (user2Rating - user2AverageRating) - magic2;
f = Math.pow(user1NewRating - user1NewAverageRating, 2) + coRatedCount * Math.pow(averageRatingDifference, 2) - 2 * magic1;
g = Math.pow(user2Rating - user2AverageRating, 2);
} else {
// Submission of a new rating and uy had not rated ia
e = -magic2;
f = coRatedCount * Math.pow(averageRatingDifference, 2) - 2 * magic1;
g = 0.0;
}
} else {
double druaia = user1NewRating - user1OldRating;
if (user2Rating != null) {
// Update of an existing rating and uy had rated ia
e = druaia * (user2Rating - user2AverageRating) - magic2;
f = Math.pow(druaia, 2) + 2 * druaia * (user1OldRating - user1NewAverageRating) + coRatedCount * Math.pow(averageRatingDifference, 2) - 2 * magic1;
g = 0.0;
} else {
// Update of an existing rating and uy had not rated ia
e = -magic2;
f = coRatedCount * Math.pow(averageRatingDifference, 2) - 2 * magic1;
g = 0.0;
}
}
// Update cached a, b, c, d
Double b = state.getB(user1, user2);
Double c = state.getC(user1, user2);
Double d = state.getD(user1, user2);
b = b + e;
c = c + f;
d = d + g;
state.setA(user1, user2, b / (Math.sqrt(c) * Math.sqrt(d)));
state.setB(user1, user2, b);
state.setC(user1, user2, c);
state.setD(user1, user2, d);
}
| public void updateUserSimilarity(CFState state, TridentTuple tuple, TridentCollector collector) {
long user1 = this.getUser1(tuple);
long user2 = this.getUser2(tuple);
@SuppressWarnings("unused")
long item = this.getItem(tuple);
double user1NewRating = this.getUser1NewRating(tuple);
Double user1OldRating = this.getUser1OldRating(tuple);
Double user2Rating = this.getUser2Rating(tuple);
double user1NewAverageRating = this.getNewAverageRating(tuple);
double user1OldAverageRating = this.getOldAverageRating(tuple);
double averageRatingDifference = user1NewAverageRating - user1OldAverageRating;
double user2AverageRating = state.getAverageRating(user2);
long coRatedCount = this.getOldCoRatedCount(tuple);
double coRatedSum1 = this.getOldCoRatedSum1(tuple);
double coRatedSum2 = this.getOldCoRatedSum2(tuple);
double magic1 = averageRatingDifference * (coRatedSum1 - coRatedCount * user1OldAverageRating);
double magic2 = averageRatingDifference * (coRatedSum2 - coRatedCount * user2AverageRating);
double e = 0, f = 0, g = 0;
if (user1OldRating == null) {
if (user2Rating != null) {
// Submission of a new rating and uy had rated ia
e = (user1NewRating - user1NewAverageRating) * (user2Rating - user2AverageRating) - magic2;
f = Math.pow(user1NewRating - user1NewAverageRating, 2) + coRatedCount * Math.pow(averageRatingDifference, 2) - 2 * magic1;
g = Math.pow(user2Rating - user2AverageRating, 2);
} else {
// Submission of a new rating and uy had not rated ia
e = -magic2;
f = coRatedCount * Math.pow(averageRatingDifference, 2) - 2 * magic1;
g = 0.0;
}
} else {
double druaia = user1NewRating - user1OldRating;
if (user2Rating != null) {
// Update of an existing rating and uy had rated ia
e = druaia * (user2Rating - user2AverageRating) - magic2;
f = Math.pow(druaia, 2) + 2 * druaia * (user1OldRating - user1NewAverageRating) + coRatedCount * Math.pow(averageRatingDifference, 2) - 2 * magic1;
g = 0.0;
} else {
// Update of an existing rating and uy had not rated ia
e = -magic2;
f = coRatedCount * Math.pow(averageRatingDifference, 2) - 2 * magic1;
g = 0.0;
}
}
// Update cached a, b, c, d
Double b = state.getB(user1, user2);
Double c = state.getC(user1, user2);
Double d = state.getD(user1, user2);
b = b + e;
c = c + f;
d = d + g;
double a = b / (Math.sqrt(c) * Math.sqrt(d));
if (Double.isInfinite(a) || Double.isNaN(a)) {
a = -1.0;
}
state.setA(user1, user2, a);
state.setB(user1, user2, b);
state.setC(user1, user2, c);
state.setD(user1, user2, d);
}
|
diff --git a/pentaho-gwt-widgets/src/org/pentaho/gwt/widgets/client/listbox/DefaultListItem.java b/pentaho-gwt-widgets/src/org/pentaho/gwt/widgets/client/listbox/DefaultListItem.java
index 93110a4..aaf7ef0 100644
--- a/pentaho-gwt-widgets/src/org/pentaho/gwt/widgets/client/listbox/DefaultListItem.java
+++ b/pentaho-gwt-widgets/src/org/pentaho/gwt/widgets/client/listbox/DefaultListItem.java
@@ -1,201 +1,201 @@
package org.pentaho.gwt.widgets.client.listbox;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import org.pentaho.gwt.widgets.client.utils.ElementUtils;
/**
*
* User: Nick Baker
* Date: Mar 9, 2009
* Time: 11:28:45 AM
*/
public class DefaultListItem implements ListItem<Object> {
private String text = ""; //$NON-NLS-1$
private CustomListBox listBox;
private Widget widget;
private Widget dropWidget;
private Image img;
private Widget extraWidget;
private String baseStyleName = "default-list"; //$NON-NLS-1$
private Object value;
public DefaultListItem(){
}
public DefaultListItem(String str){
this();
this.text = str;
this.value = this.text;
createWidgets();
}
/**
* Convenience constructor for creating a listItem with an Image followed by a string..
* <p>
* NOTE: The Image needs to have been constructed with a specified size (ie new Image("src.png",0,0,100,100);)
*
* @param str
* @param img
*/
public DefaultListItem(String str, Image img){
this();
this.text = str;
this.value = this.text;
this.img = img;
createWidgets();
}
public DefaultListItem(String str, Widget widget){
this();
this.text = str;
this.extraWidget = widget;
createWidgets();
}
public void setStylePrimaryName(String style){
baseStyleName = style;
dropWidget.setStylePrimaryName(style+"-item"); //$NON-NLS-1$
widget.setStylePrimaryName(style+"-item"); //$NON-NLS-1$
}
/**
* There are two widgets that need to be maintaned. One that shows in the drop-down when not opened, and
* another that shows in the drop-down popup itself.
*/
private void createWidgets(){
HorizontalPanel hbox = new WrapperPanel(baseStyleName+"-item"); //$NON-NLS-1$
formatWidget(hbox);
widget = hbox;
hbox = new HorizontalPanel();
hbox.setStylePrimaryName(baseStyleName+"-item"); //$NON-NLS-1$
formatWidget(hbox);
dropWidget = hbox;
}
private void formatWidget(HorizontalPanel panel){
panel.sinkEvents(Event.MOUSEEVENTS);
if(img != null){
Image i = new Image(img.getUrl());
panel.add(i);
panel.setCellVerticalAlignment(i, HasVerticalAlignment.ALIGN_MIDDLE);
i.getElement().getStyle().setProperty("marginRight","2px"); //$NON-NLS-1$ //$NON-NLS-2$
} else if(extraWidget != null){
Element ele = DOM.clone(extraWidget.getElement(), true);
Widget w = new WrapperWidget(ele);
panel.add(w);
panel.setCellVerticalAlignment(w, HasVerticalAlignment.ALIGN_MIDDLE);
w.getElement().getStyle().setProperty("marginRight","2px"); //$NON-NLS-1$ //$NON-NLS-2$
}
Label label = new Label(text);
label.getElement().getStyle().setProperty("cursor","pointer"); //$NON-NLS-1$ //$NON-NLS-2$
label.setWidth("100%"); //$NON-NLS-1$
SimplePanel sp = new SimplePanel();
sp.getElement().getStyle().setProperty("overflowX","auto");
sp.add(label);
panel.add(sp);
- panel.setCellWidth(label, "100%"); //$NON-NLS-1$
+ panel.setCellWidth(sp, "100%"); //$NON-NLS-1$
panel.setCellVerticalAlignment(label, HasVerticalAlignment.ALIGN_MIDDLE);
ElementUtils.preventTextSelection(panel.getElement());
label.setStylePrimaryName("custom-list-item"); //$NON-NLS-1$
panel.setWidth("100%"); //$NON-NLS-1$
}
public Widget getWidgetForDropdown() {
return dropWidget;
}
public Widget getWidget() {
return widget;
}
public Object getValue() {
return this.value;
}
public void setValue(Object o) {
this.value = o;
}
public void onHoverEnter() {
}
public void onHoverExit() {
}
public void onSelect() {
widget.addStyleDependentName("selected"); //$NON-NLS-1$
}
public void onDeselect() {
widget.removeStyleDependentName("selected"); //$NON-NLS-1$
}
private class WrapperPanel extends HorizontalPanel {
public WrapperPanel(String styleName){
this.sinkEvents(Event.MOUSEEVENTS);
if(styleName == null){
styleName = "default-list-item"; //$NON-NLS-1$
}
this.setStylePrimaryName(styleName);
}
@Override
public void onBrowserEvent(Event event) {
int code = event.getTypeInt();
switch(code){
case Event.ONMOUSEOVER:
this.addStyleDependentName("hover"); //$NON-NLS-1$
break;
case Event.ONMOUSEOUT:
this.removeStyleDependentName("hover"); //$NON-NLS-1$
break;
case Event.ONMOUSEUP:
listBox.setSelectedItem(DefaultListItem.this);
this.removeStyleDependentName("hover"); //$NON-NLS-1$
default:
break;
}
super.onBrowserEvent(event);
}
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public CustomListBox getListBox() {
return listBox;
}
public void setListBox(CustomListBox listBox) {
this.listBox = listBox;
}
private static class WrapperWidget extends Widget{
public WrapperWidget(Element ele){
this.setElement(ele);
}
}
}
| true | true | private void formatWidget(HorizontalPanel panel){
panel.sinkEvents(Event.MOUSEEVENTS);
if(img != null){
Image i = new Image(img.getUrl());
panel.add(i);
panel.setCellVerticalAlignment(i, HasVerticalAlignment.ALIGN_MIDDLE);
i.getElement().getStyle().setProperty("marginRight","2px"); //$NON-NLS-1$ //$NON-NLS-2$
} else if(extraWidget != null){
Element ele = DOM.clone(extraWidget.getElement(), true);
Widget w = new WrapperWidget(ele);
panel.add(w);
panel.setCellVerticalAlignment(w, HasVerticalAlignment.ALIGN_MIDDLE);
w.getElement().getStyle().setProperty("marginRight","2px"); //$NON-NLS-1$ //$NON-NLS-2$
}
Label label = new Label(text);
label.getElement().getStyle().setProperty("cursor","pointer"); //$NON-NLS-1$ //$NON-NLS-2$
label.setWidth("100%"); //$NON-NLS-1$
SimplePanel sp = new SimplePanel();
sp.getElement().getStyle().setProperty("overflowX","auto");
sp.add(label);
panel.add(sp);
panel.setCellWidth(label, "100%"); //$NON-NLS-1$
panel.setCellVerticalAlignment(label, HasVerticalAlignment.ALIGN_MIDDLE);
ElementUtils.preventTextSelection(panel.getElement());
label.setStylePrimaryName("custom-list-item"); //$NON-NLS-1$
panel.setWidth("100%"); //$NON-NLS-1$
}
| private void formatWidget(HorizontalPanel panel){
panel.sinkEvents(Event.MOUSEEVENTS);
if(img != null){
Image i = new Image(img.getUrl());
panel.add(i);
panel.setCellVerticalAlignment(i, HasVerticalAlignment.ALIGN_MIDDLE);
i.getElement().getStyle().setProperty("marginRight","2px"); //$NON-NLS-1$ //$NON-NLS-2$
} else if(extraWidget != null){
Element ele = DOM.clone(extraWidget.getElement(), true);
Widget w = new WrapperWidget(ele);
panel.add(w);
panel.setCellVerticalAlignment(w, HasVerticalAlignment.ALIGN_MIDDLE);
w.getElement().getStyle().setProperty("marginRight","2px"); //$NON-NLS-1$ //$NON-NLS-2$
}
Label label = new Label(text);
label.getElement().getStyle().setProperty("cursor","pointer"); //$NON-NLS-1$ //$NON-NLS-2$
label.setWidth("100%"); //$NON-NLS-1$
SimplePanel sp = new SimplePanel();
sp.getElement().getStyle().setProperty("overflowX","auto");
sp.add(label);
panel.add(sp);
panel.setCellWidth(sp, "100%"); //$NON-NLS-1$
panel.setCellVerticalAlignment(label, HasVerticalAlignment.ALIGN_MIDDLE);
ElementUtils.preventTextSelection(panel.getElement());
label.setStylePrimaryName("custom-list-item"); //$NON-NLS-1$
panel.setWidth("100%"); //$NON-NLS-1$
}
|
diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Engine.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Engine.java
index 9536fdba3..0b28237de 100644
--- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Engine.java
+++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Engine.java
@@ -1,121 +1,123 @@
/*******************************************************************************
* Copyright (c) 2007, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.equinox.internal.p2.engine;
import org.eclipse.core.runtime.*;
import org.eclipse.equinox.internal.p2.core.helpers.LogHelper;
import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus;
import org.eclipse.equinox.p2.core.IProvisioningAgent;
import org.eclipse.equinox.p2.engine.*;
/**
* Concrete implementation of the {@link IEngine} API.
*/
public class Engine implements IEngine {
private static final String ENGINE = "engine"; //$NON-NLS-1$
private IProvisioningAgent agent;
public Engine(IProvisioningAgent agent) {
this.agent = agent;
agent.registerService(ActionManager.SERVICE_NAME, new ActionManager());
}
private void checkArguments(IProfile iprofile, PhaseSet phaseSet, Operand[] operands, ProvisioningContext context, IProgressMonitor monitor) {
if (iprofile == null)
throw new IllegalArgumentException(Messages.null_profile);
if (phaseSet == null)
throw new IllegalArgumentException(Messages.null_phaseset);
if (operands == null)
throw new IllegalArgumentException(Messages.null_operands);
}
public IStatus perform(IProvisioningPlan plan, IPhaseSet phaseSet, IProgressMonitor monitor) {
return perform(plan.getProfile(), phaseSet, ((ProvisioningPlan) plan).getOperands(), plan.getContext(), monitor);
}
public IStatus perform(IProvisioningPlan plan, IProgressMonitor monitor) {
return perform(plan, PhaseSetFactory.createDefaultPhaseSet(), monitor);
}
public IStatus perform(IProfile iprofile, IPhaseSet phases, Operand[] operands, ProvisioningContext context, IProgressMonitor monitor) {
PhaseSet phaseSet = (PhaseSet) phases;
checkArguments(iprofile, phaseSet, operands, context, monitor);
+ if (operands.length == 0)
+ return Status.OK_STATUS;
SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME);
IProvisioningEventBus eventBus = (IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME);
if (context == null)
context = new ProvisioningContext(agent);
if (monitor == null)
monitor = new NullProgressMonitor();
Profile profile = profileRegistry.validate(iprofile);
profileRegistry.lockProfile(profile);
try {
eventBus.publishEvent(new BeginOperationEvent(profile, phaseSet, operands, this));
if (DebugHelper.DEBUG_ENGINE)
DebugHelper.debug(ENGINE, "Beginning engine operation for profile=" + profile.getProfileId() + " [" + profile.getTimestamp() + "]:" + DebugHelper.LINE_SEPARATOR + DebugHelper.formatOperation(phaseSet, operands, context)); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
EngineSession session = new EngineSession(agent, profile, context);
MultiStatus result = phaseSet.perform(session, operands, monitor);
if (result.isOK() || result.matches(IStatus.INFO | IStatus.WARNING)) {
if (DebugHelper.DEBUG_ENGINE)
DebugHelper.debug(ENGINE, "Preparing to commit engine operation for profile=" + profile.getProfileId()); //$NON-NLS-1$
result.merge(session.prepare(monitor));
}
if (result.matches(IStatus.ERROR | IStatus.CANCEL)) {
if (DebugHelper.DEBUG_ENGINE)
DebugHelper.debug(ENGINE, "Rolling back engine operation for profile=" + profile.getProfileId() + ". Reason was: " + result.toString()); //$NON-NLS-1$ //$NON-NLS-2$
IStatus status = session.rollback(monitor, result.getSeverity());
if (status.matches(IStatus.ERROR))
LogHelper.log(status);
eventBus.publishEvent(new RollbackOperationEvent(profile, phaseSet, operands, this, result));
} else {
if (DebugHelper.DEBUG_ENGINE)
DebugHelper.debug(ENGINE, "Committing engine operation for profile=" + profile.getProfileId()); //$NON-NLS-1$
if (profile.isChanged())
profileRegistry.updateProfile(profile);
IStatus status = session.commit(monitor);
if (status.matches(IStatus.ERROR))
LogHelper.log(status);
eventBus.publishEvent(new CommitOperationEvent(profile, phaseSet, operands, this));
}
//if there is only one child status, return that status instead because it will have more context
IStatus[] children = result.getChildren();
return children.length == 1 ? children[0] : result;
} finally {
profileRegistry.unlockProfile(profile);
profile.setChanged(false);
}
}
protected IStatus validate(IProfile iprofile, PhaseSet phaseSet, Operand[] operands, ProvisioningContext context, IProgressMonitor monitor) {
checkArguments(iprofile, phaseSet, operands, context, monitor);
if (context == null)
context = new ProvisioningContext(agent);
if (monitor == null)
monitor = new NullProgressMonitor();
ActionManager actionManager = (ActionManager) agent.getService(ActionManager.SERVICE_NAME);
return phaseSet.validate(actionManager, iprofile, operands, context, monitor);
}
public IProvisioningPlan createPlan(IProfile profile, ProvisioningContext context) {
return new ProvisioningPlan(profile, null, context);
}
}
| true | true | public IStatus perform(IProfile iprofile, IPhaseSet phases, Operand[] operands, ProvisioningContext context, IProgressMonitor monitor) {
PhaseSet phaseSet = (PhaseSet) phases;
checkArguments(iprofile, phaseSet, operands, context, monitor);
SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME);
IProvisioningEventBus eventBus = (IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME);
if (context == null)
context = new ProvisioningContext(agent);
if (monitor == null)
monitor = new NullProgressMonitor();
Profile profile = profileRegistry.validate(iprofile);
profileRegistry.lockProfile(profile);
try {
eventBus.publishEvent(new BeginOperationEvent(profile, phaseSet, operands, this));
if (DebugHelper.DEBUG_ENGINE)
DebugHelper.debug(ENGINE, "Beginning engine operation for profile=" + profile.getProfileId() + " [" + profile.getTimestamp() + "]:" + DebugHelper.LINE_SEPARATOR + DebugHelper.formatOperation(phaseSet, operands, context)); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
EngineSession session = new EngineSession(agent, profile, context);
MultiStatus result = phaseSet.perform(session, operands, monitor);
if (result.isOK() || result.matches(IStatus.INFO | IStatus.WARNING)) {
if (DebugHelper.DEBUG_ENGINE)
DebugHelper.debug(ENGINE, "Preparing to commit engine operation for profile=" + profile.getProfileId()); //$NON-NLS-1$
result.merge(session.prepare(monitor));
}
if (result.matches(IStatus.ERROR | IStatus.CANCEL)) {
if (DebugHelper.DEBUG_ENGINE)
DebugHelper.debug(ENGINE, "Rolling back engine operation for profile=" + profile.getProfileId() + ". Reason was: " + result.toString()); //$NON-NLS-1$ //$NON-NLS-2$
IStatus status = session.rollback(monitor, result.getSeverity());
if (status.matches(IStatus.ERROR))
LogHelper.log(status);
eventBus.publishEvent(new RollbackOperationEvent(profile, phaseSet, operands, this, result));
} else {
if (DebugHelper.DEBUG_ENGINE)
DebugHelper.debug(ENGINE, "Committing engine operation for profile=" + profile.getProfileId()); //$NON-NLS-1$
if (profile.isChanged())
profileRegistry.updateProfile(profile);
IStatus status = session.commit(monitor);
if (status.matches(IStatus.ERROR))
LogHelper.log(status);
eventBus.publishEvent(new CommitOperationEvent(profile, phaseSet, operands, this));
}
//if there is only one child status, return that status instead because it will have more context
IStatus[] children = result.getChildren();
return children.length == 1 ? children[0] : result;
} finally {
profileRegistry.unlockProfile(profile);
profile.setChanged(false);
}
}
| public IStatus perform(IProfile iprofile, IPhaseSet phases, Operand[] operands, ProvisioningContext context, IProgressMonitor monitor) {
PhaseSet phaseSet = (PhaseSet) phases;
checkArguments(iprofile, phaseSet, operands, context, monitor);
if (operands.length == 0)
return Status.OK_STATUS;
SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME);
IProvisioningEventBus eventBus = (IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME);
if (context == null)
context = new ProvisioningContext(agent);
if (monitor == null)
monitor = new NullProgressMonitor();
Profile profile = profileRegistry.validate(iprofile);
profileRegistry.lockProfile(profile);
try {
eventBus.publishEvent(new BeginOperationEvent(profile, phaseSet, operands, this));
if (DebugHelper.DEBUG_ENGINE)
DebugHelper.debug(ENGINE, "Beginning engine operation for profile=" + profile.getProfileId() + " [" + profile.getTimestamp() + "]:" + DebugHelper.LINE_SEPARATOR + DebugHelper.formatOperation(phaseSet, operands, context)); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
EngineSession session = new EngineSession(agent, profile, context);
MultiStatus result = phaseSet.perform(session, operands, monitor);
if (result.isOK() || result.matches(IStatus.INFO | IStatus.WARNING)) {
if (DebugHelper.DEBUG_ENGINE)
DebugHelper.debug(ENGINE, "Preparing to commit engine operation for profile=" + profile.getProfileId()); //$NON-NLS-1$
result.merge(session.prepare(monitor));
}
if (result.matches(IStatus.ERROR | IStatus.CANCEL)) {
if (DebugHelper.DEBUG_ENGINE)
DebugHelper.debug(ENGINE, "Rolling back engine operation for profile=" + profile.getProfileId() + ". Reason was: " + result.toString()); //$NON-NLS-1$ //$NON-NLS-2$
IStatus status = session.rollback(monitor, result.getSeverity());
if (status.matches(IStatus.ERROR))
LogHelper.log(status);
eventBus.publishEvent(new RollbackOperationEvent(profile, phaseSet, operands, this, result));
} else {
if (DebugHelper.DEBUG_ENGINE)
DebugHelper.debug(ENGINE, "Committing engine operation for profile=" + profile.getProfileId()); //$NON-NLS-1$
if (profile.isChanged())
profileRegistry.updateProfile(profile);
IStatus status = session.commit(monitor);
if (status.matches(IStatus.ERROR))
LogHelper.log(status);
eventBus.publishEvent(new CommitOperationEvent(profile, phaseSet, operands, this));
}
//if there is only one child status, return that status instead because it will have more context
IStatus[] children = result.getChildren();
return children.length == 1 ? children[0] : result;
} finally {
profileRegistry.unlockProfile(profile);
profile.setChanged(false);
}
}
|
diff --git a/src/edu/sc/seis/sod/MotionVectorArm.java b/src/edu/sc/seis/sod/MotionVectorArm.java
index 799e92026..ffb1ddc4e 100644
--- a/src/edu/sc/seis/sod/MotionVectorArm.java
+++ b/src/edu/sc/seis/sod/MotionVectorArm.java
@@ -1,444 +1,444 @@
/**
* MotionVectorArm.java
*
* @author Created by Omnicore CodeGuide
*/
package edu.sc.seis.sod;
import edu.sc.seis.sod.subsetter.waveformArm.*;
import edu.iris.Fissures.FissuresException;
import edu.iris.Fissures.IfEvent.EventAccessOperations;
import edu.iris.Fissures.IfNetwork.Channel;
import edu.iris.Fissures.IfSeismogramDC.LocalSeismogram;
import edu.iris.Fissures.IfSeismogramDC.RequestFilter;
import edu.iris.Fissures.model.MicroSecondDate;
import edu.iris.Fissures.network.ChannelIdUtil;
import edu.iris.Fissures.seismogramDC.LocalSeismogramImpl;
import edu.sc.seis.fissuresUtil.cache.ProxySeismogramDC;
import edu.sc.seis.sod.process.waveformArm.ChannelGroupLocalSeismogramProcess;
import edu.sc.seis.sod.process.waveformArm.LocalSeismogramProcess;
import edu.sc.seis.sod.process.waveformArm.LocalSeismogramProcessWrapper;
import edu.sc.seis.sod.subsetter.Subsetter;
import java.util.Iterator;
import java.util.LinkedList;
import org.apache.log4j.Logger;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class MotionVectorArm implements Subsetter{
public MotionVectorArm(Element config) throws ConfigurationException{
processConfig(config);
}
/**
* Returns SeisSubsetter
*
* @return a ChannelGroupLocalSeismogramSubsetter
*/
public ChannelGroupLocalSeismogramSubsetter getChannelGroupLocalSeismogramSubsetter() {
return seisSubsetter;
}
/**
* Returns AvailData
*
* @return a ChannelGroupAvailableDataSubsetter
*/
public ChannelGroupAvailableDataSubsetter getChannelGroupAvailableDataSubsetter() {
return availData;
}
/**
* Returns DcLocator
*
* @return a SeismogramDCLocator
*/
public SeismogramDCLocator getSeismogramDCLocator() {
return dcLocator;
}
/**
* Returns Request
*
* @return a ChannelGroupRequestSubsetter
*/
public ChannelGroupRequestSubsetter getChannelGroupRequestSubsetter() {
return request;
}
/**
* Returns RequestGenerator
*
* @return a ChannelGroupRequestGenerator
*/
public ChannelGroupRequestGenerator getChannelGroupRequestGenerator() {
return requestGenerator;
}
/**
* Returns EventChannelGroup
*
* @return an EventChannelGroupSubsetter
*/
public EventChannelGroupSubsetter getEventChannelGroupSubsetter() {
return eventChannelGroup;
}
public ChannelGroupLocalSeismogramProcess[] getProcesses() {
return (ChannelGroupLocalSeismogramProcess[])processes.toArray(new ChannelGroupLocalSeismogramProcess[0]);
}
protected void processConfig(Element config)
throws ConfigurationException {
NodeList children = config.getChildNodes();
for (int i=0; i<children.getLength(); i++) {
Node node = children.item(i);
if (node instanceof Element) {
if (((Element)node).getTagName().equals("description")) {
// skip description element
continue;
}
Object sodElement = SodUtil.load((Element)node,"waveformArm");
if(sodElement instanceof EventChannelGroupSubsetter) {
eventChannelGroup = (EventChannelGroupSubsetter)sodElement;
} else if(sodElement instanceof ChannelGroupRequestGenerator) {
requestGenerator = (ChannelGroupRequestGenerator)sodElement;
} else if(sodElement instanceof RequestGenerator) {
requestGenerator = new RequestGeneratorWrapper((RequestGenerator)sodElement);
} else if(sodElement instanceof ChannelGroupRequestSubsetter) {
request = (ChannelGroupRequestSubsetter)sodElement;
} else if(sodElement instanceof SeismogramDCLocator) {
dcLocator = (SeismogramDCLocator)sodElement;
} else if(sodElement instanceof ChannelGroupAvailableDataSubsetter) {
availData = (ChannelGroupAvailableDataSubsetter)sodElement;
} else if(sodElement instanceof ChannelGroupLocalSeismogramSubsetter) {
seisSubsetter = (ChannelGroupLocalSeismogramSubsetter)sodElement;
} else if(sodElement instanceof ChannelGroupLocalSeismogramProcess) {
processes.add(sodElement);
} else if(sodElement instanceof LocalSeismogramProcess) {
processes.add(new LocalSeismogramProcessWrapper((LocalSeismogramProcess)sodElement));
} else {
logger.warn("Unknown tag in MotionVectorArm config. " +sodElement.getClass().getName());
} // end of else
} // end of if (node instanceof Element)
} // end of for (int i=0; i<children.getSize(); i++)
}
public void processMotionVectorArm(EventChannelGroupPair ecp) {
boolean passed;
EventAccessOperations eventAccess = ecp.getEvent();
ChannelGroup channel = ecp.getChannelGroup();
synchronized (eventChannelGroup) {
try {
passed = eventChannelGroup.accept(eventAccess,channel, ecp.getCookieJar());
} catch (Throwable e) {
handle(ecp, Stage.EVENT_CHANNEL_SUBSETTER, e);
return;
}
}
if( passed ) {
ecp.update(Status.get(Stage.REQUEST_SUBSETTER, Standing.IN_PROG));
processRequestGeneratorSubsetter(ecp);
} else {
logger.info("FAIL event channel");
ecp.update(Status.get(Stage.EVENT_CHANNEL_SUBSETTER,Standing.REJECT));
}
}
public void processRequestGeneratorSubsetter(EventChannelGroupPair ecp){
RequestFilter[][] infilters;
synchronized (requestGenerator) {
try {
infilters=requestGenerator.generateRequest(ecp.getEvent(),
ecp.getChannelGroup(),
ecp.getCookieJar());
} catch (Throwable e) {
handle(ecp, Stage.REQUEST_SUBSETTER, e);
return;
}
}
processRequestSubsetter(ecp, infilters);
}
public void processRequestSubsetter(EventChannelGroupPair ecp, RequestFilter[][] infilters){
boolean passed;
synchronized (request) {
try {
passed = request.accept(ecp.getEvent(), ecp.getChannelGroup(),
infilters, ecp.getCookieJar());
} catch (Throwable e) {
handle(ecp, Stage.REQUEST_SUBSETTER, e);
return;
}
}
if( passed ) {
ecp.update(Status.get(Stage.AVAILABLE_DATA_SUBSETTER, Standing.IN_PROG));
ProxySeismogramDC dataCenter;
synchronized(dcLocator) {
try {
//********************************************************
// WARNING, the dcLocator only uses the first channel!!! *
//********************************************************
dataCenter = dcLocator.getSeismogramDC(ecp.getEvent(),
ecp.getChannelGroup().getChannels()[0],
infilters[0],
ecp.getCookieJar());
} catch (Throwable e) {
handle(ecp, Stage.AVAILABLE_DATA_SUBSETTER, e);
return;
}
}
RequestFilter[][] outfilters = new RequestFilter[ecp.getChannelGroup().getChannels().length][];
for (int i = 0; i < outfilters.length; i++) {
logger.debug("Trying available_data for "+ChannelIdUtil.toString(infilters[0][0].channel_id)+
" from "+infilters[0][0].start_time.date_time+" to "+infilters[0][0].end_time.date_time);
int retries = 0;
int MAX_RETRY = 5;
while(retries < MAX_RETRY) {
try {
logger.debug("before available_data call retries="+retries);
outfilters[i] = dataCenter.available_data(infilters[i]);
logger.debug("after successful available_data call retries="+retries);
break;
} catch (org.omg.CORBA.SystemException e) {
retries++;
logger.debug("after failed available_data call retries="+retries+" "+e.toString());
if (retries < MAX_RETRY) {
// sleep is 10 seconds times num retries
int sleepTime = 10*retries;
logger.info("Caught CORBA exception, sleep for "+sleepTime+" then retry..."+retries, e);
try {
Thread.sleep(sleepTime*1000); // change seconds to milliseconds
} catch(InterruptedException ex) {}
if (retries % 2 == 0) {
//force reload from name service evey other try
dataCenter.reset();
}
} else {
handle(ecp, Stage.AVAILABLE_DATA_SUBSETTER, e);
return;
}
}
}
if (outfilters[i].length != 0) {
logger.debug("Got available_data for "+ChannelIdUtil.toString(outfilters[i][0].channel_id)+
" from "+outfilters[i][0].start_time.date_time+" to "+outfilters[i][0].end_time.date_time);
} else {
logger.debug("No available_data for "+ChannelIdUtil.toString(infilters[i][0].channel_id));
}
}
processAvailableDataSubsetter(ecp,dataCenter,infilters,outfilters);
} else {
logger.info("FAIL request subsetter");
ecp.update(Status.get(Stage.REQUEST_SUBSETTER, Standing.REJECT));
}
}
public void processAvailableDataSubsetter(EventChannelGroupPair ecp,
ProxySeismogramDC dataCenter,
RequestFilter[][] infilters,
RequestFilter[][] outfilters){
boolean passed;
synchronized (availData) {
try {
passed = availData.accept(ecp.getEvent(), ecp.getChannelGroup(),
infilters, outfilters, ecp.getCookieJar());
} catch (Throwable e) {
handle(ecp, Stage.AVAILABLE_DATA_SUBSETTER, e);
return;
}
}
if( passed ) {
ecp.update(Status.get(Stage.DATA_SUBSETTER, Standing.IN_PROG));
for (int i=0; i<infilters.length; i++) {
for (int j = 0; j < infilters[i].length; j++) {
logger.debug("Getting seismograms "
+ChannelIdUtil.toString(infilters[i][j].channel_id)
+" from "
+infilters[i][j].start_time.date_time
+" to "
+infilters[i][j].end_time.date_time);
} // end of for (int i=0; i<outFilters.length; i++)
}
logger.debug("Using infilters, fix this when DMC fixes server");
MicroSecondDate before = new MicroSecondDate();
LocalSeismogram[][] localSeismograms = new LocalSeismogram[ecp.getChannelGroup().getChannels().length][0];
LocalSeismogramImpl[][] tempLocalSeismograms = new LocalSeismogramImpl[ecp.getChannelGroup().getChannels().length][0];
for (int i = 0; i < localSeismograms.length; i++) {
if (outfilters[i].length != 0) {
int retries = 0;
int MAX_RETRY = 5;
while(retries < MAX_RETRY) {
try {
logger.debug("before retrieve_seismograms");
try {
localSeismograms[i] = dataCenter.retrieve_seismograms(infilters[i]);
} catch (FissuresException e) {
handle(ecp, Stage.DATA_SUBSETTER, e);
return;
}
logger.debug("after successful retrieve_seismograms");
if (localSeismograms.length > 0 && ! ChannelIdUtil.areEqual(localSeismograms[i][0].channel_id, infilters[i][0].channel_id)) {
// must be server error
logger.warn("X Channel id in returned seismogram doesn not match channelid in request. req="
+ChannelIdUtil.toString(infilters[i][0].channel_id)
+" seis="
+ChannelIdUtil.toString(localSeismograms[i][0].channel_id));
}
break;
} catch (org.omg.CORBA.SystemException e) {
retries++;
logger.debug("after failed retrieve_seismograms, retries="+retries);
if (retries < MAX_RETRY) {
logger.info("Caught CORBA exception, retrying..."+retries, e);
try {
Thread.sleep(1000*retries);
} catch(InterruptedException ex) {}
if (retries % 2 == 0) {
// reget from Name service every other time
dataCenter.reset();
}
} else {
handle(ecp, Stage.DATA_SUBSETTER, e);
return;
}
}
}
} else {
logger.debug("Failed, retrieve data returned no requestFilters ");
- localSeismograms = new LocalSeismogram[i][0];
+ localSeismograms[i] = new LocalSeismogram[0];
} // end of else
MicroSecondDate after = new MicroSecondDate();
logger.info("After getting seismograms, time taken="+after.subtract(before));
LinkedList tempForCast = new LinkedList();
- for (int j=0; j<localSeismograms.length; j++) {
+ for (int j=0; j<localSeismograms[i].length; j++) {
if (localSeismograms[i][j] == null) {
ecp.update(Status.get(Stage.DATA_SUBSETTER, Standing.REJECT));
logger.error("Got null in seismogram array "+ChannelIdUtil.toString(ecp.getChannelGroup().getChannels()[i].get_id()));
return;
}
Channel ecpChan = ecp.getChannelGroup().getChannels()[i];
if ( ! ChannelIdUtil.areEqual(localSeismograms[i][j].channel_id, ecpChan.get_id())) {
// must be server error
logger.warn("Channel id in returned seismogram doesn not match channelid in request. req="
+ChannelIdUtil.toString(ecpChan.get_id())
+" seis="
+ChannelIdUtil.toString(localSeismograms[i][j].channel_id));
// fix seis with original id
localSeismograms[i][j].channel_id = ecpChan.get_id();
} // end of if ()
tempForCast.add(localSeismograms[i][j]);
} // end of for (int i=0; i<localSeismograms.length; i++)
tempLocalSeismograms[i] =
(LocalSeismogramImpl[])tempForCast.toArray(new LocalSeismogramImpl[0]);
}
processLocalSeismogramSubsetter(ecp,
infilters,
outfilters,
tempLocalSeismograms);
} else {
logger.info("FAIL available data");
ecp.update(Status.get(Stage.AVAILABLE_DATA_SUBSETTER,
Standing.REJECT));
}
}
public void processLocalSeismogramSubsetter(EventChannelGroupPair ecp,
RequestFilter[][] infilters,
RequestFilter[][] outfilters,
LocalSeismogramImpl[][] localSeismograms) {
boolean passed;
synchronized (seisSubsetter) {
try {
passed = seisSubsetter.accept(ecp.getEvent(),
ecp.getChannelGroup(),
infilters,
outfilters,
localSeismograms,
ecp.getCookieJar());
} catch (Throwable e) {
handle(ecp, Stage.DATA_SUBSETTER, e);
return;
}
}
if( passed ) {
ecp.update(Status.get(Stage.PROCESSOR, Standing.IN_PROG));
try {
processSeismograms(ecp, infilters, outfilters, localSeismograms);
} catch (Throwable e) {
handle(ecp, Stage.DATA_SUBSETTER, e);
}
} else {
logger.info("FAIL seismogram subsetter");
ecp.update(Status.get(Stage.DATA_SUBSETTER, Standing.REJECT));
}
}
public void processSeismograms(EventChannelGroupPair ecp,
RequestFilter[][] infilters,
RequestFilter[][] outfilters,
LocalSeismogramImpl[][] localSeismograms)
throws Exception {
ChannelGroupLocalSeismogramProcess processor;
Iterator it = processes.iterator();
while (it.hasNext()) {
processor = (ChannelGroupLocalSeismogramProcess)it.next();
synchronized (processor) {
try {
localSeismograms = processor.process(ecp.getEvent(),
ecp.getChannelGroup(),
infilters,
outfilters,
localSeismograms,
ecp.getCookieJar());
} catch (Throwable e) { handle(ecp, Stage.PROCESSOR, e); }
}
} // end of while (it.hasNext())
logger.debug("finished with "+
ChannelIdUtil.toStringNoDates(ecp.getChannelGroup().getChannels()[0].get_id()));
ecp.update(Status.get(Stage.PROCESSOR, Standing.SUCCESS));
}
private static void handle(EventChannelGroupPair ecp, Stage stage, Throwable t){
if(t instanceof org.omg.CORBA.SystemException){
ecp.update(t, Status.get(stage, Standing.CORBA_FAILURE));
}else{
ecp.update(t, Status.get(stage, Standing.SYSTEM_FAILURE));
}
}
private EventChannelGroupSubsetter eventChannelGroup = new NullEventChannelSubsetter();
private ChannelGroupRequestGenerator requestGenerator;
private ChannelGroupRequestSubsetter request = new NullRequestSubsetter();
private SeismogramDCLocator dcLocator;
private ChannelGroupAvailableDataSubsetter availData = new NullAvailableDataSubsetter();
private ChannelGroupLocalSeismogramSubsetter seisSubsetter = new NullLocalSeismogramSubsetter();
private LinkedList processes = new LinkedList();
private static final Logger logger = Logger.getLogger(MotionVectorArm.class);
}
| false | true | public void processAvailableDataSubsetter(EventChannelGroupPair ecp,
ProxySeismogramDC dataCenter,
RequestFilter[][] infilters,
RequestFilter[][] outfilters){
boolean passed;
synchronized (availData) {
try {
passed = availData.accept(ecp.getEvent(), ecp.getChannelGroup(),
infilters, outfilters, ecp.getCookieJar());
} catch (Throwable e) {
handle(ecp, Stage.AVAILABLE_DATA_SUBSETTER, e);
return;
}
}
if( passed ) {
ecp.update(Status.get(Stage.DATA_SUBSETTER, Standing.IN_PROG));
for (int i=0; i<infilters.length; i++) {
for (int j = 0; j < infilters[i].length; j++) {
logger.debug("Getting seismograms "
+ChannelIdUtil.toString(infilters[i][j].channel_id)
+" from "
+infilters[i][j].start_time.date_time
+" to "
+infilters[i][j].end_time.date_time);
} // end of for (int i=0; i<outFilters.length; i++)
}
logger.debug("Using infilters, fix this when DMC fixes server");
MicroSecondDate before = new MicroSecondDate();
LocalSeismogram[][] localSeismograms = new LocalSeismogram[ecp.getChannelGroup().getChannels().length][0];
LocalSeismogramImpl[][] tempLocalSeismograms = new LocalSeismogramImpl[ecp.getChannelGroup().getChannels().length][0];
for (int i = 0; i < localSeismograms.length; i++) {
if (outfilters[i].length != 0) {
int retries = 0;
int MAX_RETRY = 5;
while(retries < MAX_RETRY) {
try {
logger.debug("before retrieve_seismograms");
try {
localSeismograms[i] = dataCenter.retrieve_seismograms(infilters[i]);
} catch (FissuresException e) {
handle(ecp, Stage.DATA_SUBSETTER, e);
return;
}
logger.debug("after successful retrieve_seismograms");
if (localSeismograms.length > 0 && ! ChannelIdUtil.areEqual(localSeismograms[i][0].channel_id, infilters[i][0].channel_id)) {
// must be server error
logger.warn("X Channel id in returned seismogram doesn not match channelid in request. req="
+ChannelIdUtil.toString(infilters[i][0].channel_id)
+" seis="
+ChannelIdUtil.toString(localSeismograms[i][0].channel_id));
}
break;
} catch (org.omg.CORBA.SystemException e) {
retries++;
logger.debug("after failed retrieve_seismograms, retries="+retries);
if (retries < MAX_RETRY) {
logger.info("Caught CORBA exception, retrying..."+retries, e);
try {
Thread.sleep(1000*retries);
} catch(InterruptedException ex) {}
if (retries % 2 == 0) {
// reget from Name service every other time
dataCenter.reset();
}
} else {
handle(ecp, Stage.DATA_SUBSETTER, e);
return;
}
}
}
} else {
logger.debug("Failed, retrieve data returned no requestFilters ");
localSeismograms = new LocalSeismogram[i][0];
} // end of else
MicroSecondDate after = new MicroSecondDate();
logger.info("After getting seismograms, time taken="+after.subtract(before));
LinkedList tempForCast = new LinkedList();
for (int j=0; j<localSeismograms.length; j++) {
if (localSeismograms[i][j] == null) {
ecp.update(Status.get(Stage.DATA_SUBSETTER, Standing.REJECT));
logger.error("Got null in seismogram array "+ChannelIdUtil.toString(ecp.getChannelGroup().getChannels()[i].get_id()));
return;
}
Channel ecpChan = ecp.getChannelGroup().getChannels()[i];
if ( ! ChannelIdUtil.areEqual(localSeismograms[i][j].channel_id, ecpChan.get_id())) {
// must be server error
logger.warn("Channel id in returned seismogram doesn not match channelid in request. req="
+ChannelIdUtil.toString(ecpChan.get_id())
+" seis="
+ChannelIdUtil.toString(localSeismograms[i][j].channel_id));
// fix seis with original id
localSeismograms[i][j].channel_id = ecpChan.get_id();
} // end of if ()
tempForCast.add(localSeismograms[i][j]);
} // end of for (int i=0; i<localSeismograms.length; i++)
tempLocalSeismograms[i] =
(LocalSeismogramImpl[])tempForCast.toArray(new LocalSeismogramImpl[0]);
}
processLocalSeismogramSubsetter(ecp,
infilters,
outfilters,
tempLocalSeismograms);
} else {
logger.info("FAIL available data");
ecp.update(Status.get(Stage.AVAILABLE_DATA_SUBSETTER,
Standing.REJECT));
}
}
| public void processAvailableDataSubsetter(EventChannelGroupPair ecp,
ProxySeismogramDC dataCenter,
RequestFilter[][] infilters,
RequestFilter[][] outfilters){
boolean passed;
synchronized (availData) {
try {
passed = availData.accept(ecp.getEvent(), ecp.getChannelGroup(),
infilters, outfilters, ecp.getCookieJar());
} catch (Throwable e) {
handle(ecp, Stage.AVAILABLE_DATA_SUBSETTER, e);
return;
}
}
if( passed ) {
ecp.update(Status.get(Stage.DATA_SUBSETTER, Standing.IN_PROG));
for (int i=0; i<infilters.length; i++) {
for (int j = 0; j < infilters[i].length; j++) {
logger.debug("Getting seismograms "
+ChannelIdUtil.toString(infilters[i][j].channel_id)
+" from "
+infilters[i][j].start_time.date_time
+" to "
+infilters[i][j].end_time.date_time);
} // end of for (int i=0; i<outFilters.length; i++)
}
logger.debug("Using infilters, fix this when DMC fixes server");
MicroSecondDate before = new MicroSecondDate();
LocalSeismogram[][] localSeismograms = new LocalSeismogram[ecp.getChannelGroup().getChannels().length][0];
LocalSeismogramImpl[][] tempLocalSeismograms = new LocalSeismogramImpl[ecp.getChannelGroup().getChannels().length][0];
for (int i = 0; i < localSeismograms.length; i++) {
if (outfilters[i].length != 0) {
int retries = 0;
int MAX_RETRY = 5;
while(retries < MAX_RETRY) {
try {
logger.debug("before retrieve_seismograms");
try {
localSeismograms[i] = dataCenter.retrieve_seismograms(infilters[i]);
} catch (FissuresException e) {
handle(ecp, Stage.DATA_SUBSETTER, e);
return;
}
logger.debug("after successful retrieve_seismograms");
if (localSeismograms.length > 0 && ! ChannelIdUtil.areEqual(localSeismograms[i][0].channel_id, infilters[i][0].channel_id)) {
// must be server error
logger.warn("X Channel id in returned seismogram doesn not match channelid in request. req="
+ChannelIdUtil.toString(infilters[i][0].channel_id)
+" seis="
+ChannelIdUtil.toString(localSeismograms[i][0].channel_id));
}
break;
} catch (org.omg.CORBA.SystemException e) {
retries++;
logger.debug("after failed retrieve_seismograms, retries="+retries);
if (retries < MAX_RETRY) {
logger.info("Caught CORBA exception, retrying..."+retries, e);
try {
Thread.sleep(1000*retries);
} catch(InterruptedException ex) {}
if (retries % 2 == 0) {
// reget from Name service every other time
dataCenter.reset();
}
} else {
handle(ecp, Stage.DATA_SUBSETTER, e);
return;
}
}
}
} else {
logger.debug("Failed, retrieve data returned no requestFilters ");
localSeismograms[i] = new LocalSeismogram[0];
} // end of else
MicroSecondDate after = new MicroSecondDate();
logger.info("After getting seismograms, time taken="+after.subtract(before));
LinkedList tempForCast = new LinkedList();
for (int j=0; j<localSeismograms[i].length; j++) {
if (localSeismograms[i][j] == null) {
ecp.update(Status.get(Stage.DATA_SUBSETTER, Standing.REJECT));
logger.error("Got null in seismogram array "+ChannelIdUtil.toString(ecp.getChannelGroup().getChannels()[i].get_id()));
return;
}
Channel ecpChan = ecp.getChannelGroup().getChannels()[i];
if ( ! ChannelIdUtil.areEqual(localSeismograms[i][j].channel_id, ecpChan.get_id())) {
// must be server error
logger.warn("Channel id in returned seismogram doesn not match channelid in request. req="
+ChannelIdUtil.toString(ecpChan.get_id())
+" seis="
+ChannelIdUtil.toString(localSeismograms[i][j].channel_id));
// fix seis with original id
localSeismograms[i][j].channel_id = ecpChan.get_id();
} // end of if ()
tempForCast.add(localSeismograms[i][j]);
} // end of for (int i=0; i<localSeismograms.length; i++)
tempLocalSeismograms[i] =
(LocalSeismogramImpl[])tempForCast.toArray(new LocalSeismogramImpl[0]);
}
processLocalSeismogramSubsetter(ecp,
infilters,
outfilters,
tempLocalSeismograms);
} else {
logger.info("FAIL available data");
ecp.update(Status.get(Stage.AVAILABLE_DATA_SUBSETTER,
Standing.REJECT));
}
}
|
diff --git a/DanmakuFlameMaster/src/main/java/master/flame/danmaku/danmaku/model/android/Danmakus.java b/DanmakuFlameMaster/src/main/java/master/flame/danmaku/danmaku/model/android/Danmakus.java
index cbbf540..2dac410 100644
--- a/DanmakuFlameMaster/src/main/java/master/flame/danmaku/danmaku/model/android/Danmakus.java
+++ b/DanmakuFlameMaster/src/main/java/master/flame/danmaku/danmaku/model/android/Danmakus.java
@@ -1,197 +1,197 @@
/*
* Copyright (C) 2013 Chen Hui <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package master.flame.danmaku.danmaku.model.android;
import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.Danmaku;
import master.flame.danmaku.danmaku.model.IDanmakus;
import master.flame.danmaku.danmaku.util.DanmakuUtils;
import java.util.*;
public class Danmakus implements IDanmakus {
public static final int ST_BY_TIME = 0;
public static final int ST_BY_YPOS = 1;
public static final int ST_BY_YPOS_DESC = 2;
public Set<BaseDanmaku> items;
private Danmakus subItems;
private BaseDanmaku startItem, endItem;
public Danmakus() {
this(ST_BY_TIME);
}
public Danmakus(int sortType) {
Comparator<BaseDanmaku> comparator = null;
if (sortType == ST_BY_TIME) {
comparator = new TimeComparator();
} else if (sortType == ST_BY_YPOS) {
comparator = new YPosComparator();
} else if (sortType == ST_BY_YPOS_DESC) {
comparator = new YPosDescComparator();
}
items = new TreeSet<BaseDanmaku>(comparator);
}
public Danmakus(Set<BaseDanmaku> items) {
setItems(items);
}
public void setItems(Set<BaseDanmaku> items) {
Set<BaseDanmaku> oldItems = this.items;
this.items = items;
if (oldItems != null) {
Iterator<BaseDanmaku> it = oldItems.iterator();
while (it.hasNext()) {
BaseDanmaku item = it.next();
if (item.isOutside()) {
item.setVisibility(false);
} else {
break;
}
}
}
}
public Iterator<BaseDanmaku> iterator() {
if (items != null) {
return items.iterator();
}
return null;
}
@Override
public void addItem(BaseDanmaku item) {
if (items != null)
items.add(item);
}
@Override
public void removeItem(BaseDanmaku item) {
if (item.isOutside()) {
item.setVisibility(false);
}
if (items != null) {
items.remove(item);
}
}
@Override
public IDanmakus sub(long startTime, long endTime) {
if(items==null || items.size()==0){
return null;
}
if (subItems == null) {
subItems = new Danmakus();
}
if (startItem == null) {
startItem = createItem("start");
}
if (endItem == null) {
endItem = createItem("end");
}
if (subItems != null) {
long dtime = startTime - startItem.time;
if (dtime >= 0 && endTime <= endItem.time) {
return subItems;
}
- if (dtime >= 0 && ((endItem.time - startTime) > dtime)) {
- startItem.time = startTime;
- Set<BaseDanmaku> retItems = ((SortedSet<BaseDanmaku>) subItems.items).subSet(
- startItem, endItem);
- subItems.setItems(retItems);
- startItem.time = endItem.time + 1;
- endItem.time = endTime;
- retItems = ((SortedSet<BaseDanmaku>) items).subSet(startItem, endItem);
- subItems.items.addAll(retItems);
- startItem.time = startTime;
- return subItems;
- }
+// if (dtime >= 0 && ((endItem.time - startTime) > dtime)) {
+// startItem.time = startTime;
+// Set<BaseDanmaku> retItems = ((SortedSet<BaseDanmaku>) subItems.items).subSet(
+// startItem, endItem);
+// subItems.setItems(retItems);
+// startItem.time = endItem.time + 1;
+// endItem.time = endTime;
+// retItems = ((SortedSet<BaseDanmaku>) items).subSet(startItem, endItem);
+// subItems.items.addAll(retItems);
+// startItem.time = startTime;
+// return subItems;
+// }
}
startItem.time = startTime;
endItem.time = endTime;
subItems.setItems(((SortedSet<BaseDanmaku>) items).subSet(startItem, endItem));
return subItems;
}
private BaseDanmaku createItem(String text) {
return new Danmaku(text);
}
public int size() {
if (items != null) {
return items.size();
}
return 0;
}
@Override
public void clear() {
if (items != null)
items.clear();
if (subItems != null) {
Iterator<BaseDanmaku> it = subItems.iterator();
while (it.hasNext()) {
BaseDanmaku item = it.next();
item.setVisibility(false);
}
subItems.clear();
}
}
private class TimeComparator implements Comparator<BaseDanmaku> {
@Override
public int compare(BaseDanmaku obj1, BaseDanmaku obj2) {
return DanmakuUtils.compare(obj1, obj2);
}
}
private class YPosComparator implements Comparator<BaseDanmaku> {
@Override
public int compare(BaseDanmaku obj1, BaseDanmaku obj2) {
int result = Float.compare(obj1.getTop(), obj2.getTop());
if (result != 0) {
return result;
}
return DanmakuUtils.compare(obj1, obj2);
}
}
private class YPosDescComparator implements Comparator<BaseDanmaku> {
@Override
public int compare(BaseDanmaku obj1, BaseDanmaku obj2) {
int result = Float.compare(obj2.getTop(), obj1.getTop());
if (result != 0) {
return result;
}
return DanmakuUtils.compare(obj1, obj2);
}
}
}
| true | true | public IDanmakus sub(long startTime, long endTime) {
if(items==null || items.size()==0){
return null;
}
if (subItems == null) {
subItems = new Danmakus();
}
if (startItem == null) {
startItem = createItem("start");
}
if (endItem == null) {
endItem = createItem("end");
}
if (subItems != null) {
long dtime = startTime - startItem.time;
if (dtime >= 0 && endTime <= endItem.time) {
return subItems;
}
if (dtime >= 0 && ((endItem.time - startTime) > dtime)) {
startItem.time = startTime;
Set<BaseDanmaku> retItems = ((SortedSet<BaseDanmaku>) subItems.items).subSet(
startItem, endItem);
subItems.setItems(retItems);
startItem.time = endItem.time + 1;
endItem.time = endTime;
retItems = ((SortedSet<BaseDanmaku>) items).subSet(startItem, endItem);
subItems.items.addAll(retItems);
startItem.time = startTime;
return subItems;
}
}
startItem.time = startTime;
endItem.time = endTime;
subItems.setItems(((SortedSet<BaseDanmaku>) items).subSet(startItem, endItem));
return subItems;
}
| public IDanmakus sub(long startTime, long endTime) {
if(items==null || items.size()==0){
return null;
}
if (subItems == null) {
subItems = new Danmakus();
}
if (startItem == null) {
startItem = createItem("start");
}
if (endItem == null) {
endItem = createItem("end");
}
if (subItems != null) {
long dtime = startTime - startItem.time;
if (dtime >= 0 && endTime <= endItem.time) {
return subItems;
}
// if (dtime >= 0 && ((endItem.time - startTime) > dtime)) {
// startItem.time = startTime;
// Set<BaseDanmaku> retItems = ((SortedSet<BaseDanmaku>) subItems.items).subSet(
// startItem, endItem);
// subItems.setItems(retItems);
// startItem.time = endItem.time + 1;
// endItem.time = endTime;
// retItems = ((SortedSet<BaseDanmaku>) items).subSet(startItem, endItem);
// subItems.items.addAll(retItems);
// startItem.time = startTime;
// return subItems;
// }
}
startItem.time = startTime;
endItem.time = endTime;
subItems.setItems(((SortedSet<BaseDanmaku>) items).subSet(startItem, endItem));
return subItems;
}
|
diff --git a/cruisecontrol/reporting/jsp/src/net/sourceforge/cruisecontrol/taglib/CurrentBuildStatusTag.java b/cruisecontrol/reporting/jsp/src/net/sourceforge/cruisecontrol/taglib/CurrentBuildStatusTag.java
index 8c6d0bad..e2a9d444 100644
--- a/cruisecontrol/reporting/jsp/src/net/sourceforge/cruisecontrol/taglib/CurrentBuildStatusTag.java
+++ b/cruisecontrol/reporting/jsp/src/net/sourceforge/cruisecontrol/taglib/CurrentBuildStatusTag.java
@@ -1,86 +1,102 @@
/********************************************************************************
* CruiseControl, a Continuous Integration Toolkit
* Copyright (c) 2003, ThoughtWorks, Inc.
* 651 W Washington Ave. Suite 500
* Chicago, IL 60661 USA
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* + Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* + Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* + Neither the name of ThoughtWorks, Inc., CruiseControl, nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
********************************************************************************/
package net.sourceforge.cruisecontrol.taglib;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.File;
import javax.servlet.jsp.JspException;
public class CurrentBuildStatusTag extends CruiseControlTagSupport {
public int doEndTag() throws JspException {
writeStatus(getPageContext().getOut());
return EVAL_PAGE;
}
private void writeStatus(java.io.Writer out) throws JspException {
BufferedReader br = null;
File logDir = findLogDir();
String currentBuildFileName = getContextParam("currentBuildStatusFile");
- if (currentBuildFileName == null) {
- throw new JspException("You need to declare the current build file");
+ if (currentBuildFileName == null || currentBuildFileName.equals("")) {
+ System.err.println("CruiseControl: currentBuildStatusFile not defined in the web.xml");
+ return;
}
File currentBuildFile = new File(logDir, currentBuildFileName);
+ if (currentBuildFile.isDirectory()) {
+ System.err.println(
+ "CruiseControl: currentBuildStatusFile "
+ + currentBuildFile.getAbsolutePath()
+ + " is a directory."
+ + " Edit the web.xml to provide the path to the correct file.");
+ return;
+ }
if (!currentBuildFile.exists()) {
+ System.err.println(
+ "CruiseControl: currentBuildStatusFile "
+ + currentBuildFile.getAbsolutePath()
+ + "does not exist."
+ + " You may need to update the value in the web.xml"
+ + " or the location specified in your CruiseControl config.xml.");
return;
}
try {
br = new BufferedReader(new FileReader(currentBuildFile));
String s = br.readLine();
while (s != null) {
out.write(s);
s = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
- throw new JspException("Error reading status file: " + currentBuildFileName + " : " + e.getMessage());
+ throw new JspException(
+ "Error reading status file: " + currentBuildFileName + " : " + e.getMessage());
} finally {
try {
- if (br != null) {
- br.close();
- }
+ if (br != null) {
+ br.close();
+ }
} catch (IOException e) {
e.printStackTrace();
}
br = null;
}
}
}
| false | true | private void writeStatus(java.io.Writer out) throws JspException {
BufferedReader br = null;
File logDir = findLogDir();
String currentBuildFileName = getContextParam("currentBuildStatusFile");
if (currentBuildFileName == null) {
throw new JspException("You need to declare the current build file");
}
File currentBuildFile = new File(logDir, currentBuildFileName);
if (!currentBuildFile.exists()) {
return;
}
try {
br = new BufferedReader(new FileReader(currentBuildFile));
String s = br.readLine();
while (s != null) {
out.write(s);
s = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
throw new JspException("Error reading status file: " + currentBuildFileName + " : " + e.getMessage());
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
br = null;
}
}
| private void writeStatus(java.io.Writer out) throws JspException {
BufferedReader br = null;
File logDir = findLogDir();
String currentBuildFileName = getContextParam("currentBuildStatusFile");
if (currentBuildFileName == null || currentBuildFileName.equals("")) {
System.err.println("CruiseControl: currentBuildStatusFile not defined in the web.xml");
return;
}
File currentBuildFile = new File(logDir, currentBuildFileName);
if (currentBuildFile.isDirectory()) {
System.err.println(
"CruiseControl: currentBuildStatusFile "
+ currentBuildFile.getAbsolutePath()
+ " is a directory."
+ " Edit the web.xml to provide the path to the correct file.");
return;
}
if (!currentBuildFile.exists()) {
System.err.println(
"CruiseControl: currentBuildStatusFile "
+ currentBuildFile.getAbsolutePath()
+ "does not exist."
+ " You may need to update the value in the web.xml"
+ " or the location specified in your CruiseControl config.xml.");
return;
}
try {
br = new BufferedReader(new FileReader(currentBuildFile));
String s = br.readLine();
while (s != null) {
out.write(s);
s = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
throw new JspException(
"Error reading status file: " + currentBuildFileName + " : " + e.getMessage());
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
br = null;
}
}
|
diff --git a/Carbonado/src/main/java/com/amazon/carbonado/repo/replicated/ReplicationTrigger.java b/Carbonado/src/main/java/com/amazon/carbonado/repo/replicated/ReplicationTrigger.java
index 3ab69c0..bdacca4 100644
--- a/Carbonado/src/main/java/com/amazon/carbonado/repo/replicated/ReplicationTrigger.java
+++ b/Carbonado/src/main/java/com/amazon/carbonado/repo/replicated/ReplicationTrigger.java
@@ -1,401 +1,399 @@
/*
* Copyright 2006 Amazon Technologies, Inc. or its affiliates.
* Amazon, Amazon.com and Carbonado are trademarks or registered trademarks
* of Amazon Technologies, Inc. or its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazon.carbonado.repo.replicated;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.amazon.carbonado.FetchException;
import com.amazon.carbonado.OptimisticLockException;
import com.amazon.carbonado.PersistException;
import com.amazon.carbonado.PersistNoneException;
import com.amazon.carbonado.Repository;
import com.amazon.carbonado.Storable;
import com.amazon.carbonado.Storage;
import com.amazon.carbonado.Transaction;
import com.amazon.carbonado.Trigger;
import com.amazon.carbonado.UniqueConstraintException;
import com.amazon.carbonado.spi.RepairExecutor;
import com.amazon.carbonado.spi.TriggerManager;
/**
* All inserts/updates/deletes are first committed to the master storage, then
* duplicated and committed to the replica.
*
* @author Don Schneider
* @author Brian S O'Neill
*/
class ReplicationTrigger<S extends Storable> extends Trigger<S> {
private final Repository mRepository;
private final Storage<S> mReplicaStorage;
private final Storage<S> mMasterStorage;
private final TriggerManager<S> mTriggerManager;
ReplicationTrigger(Repository repository,
Storage<S> replicaStorage,
Storage<S> masterStorage)
{
mRepository = repository;
mReplicaStorage = replicaStorage;
mMasterStorage = masterStorage;
// Use TriggerManager to locally disable trigger execution during
// resync and repairs.
mTriggerManager = new TriggerManager<S>();
mTriggerManager.addTrigger(this);
BlobReplicationTrigger<S> blobTrigger = BlobReplicationTrigger.create(masterStorage);
if (blobTrigger != null) {
mTriggerManager.addTrigger(blobTrigger);
}
ClobReplicationTrigger<S> clobTrigger = ClobReplicationTrigger.create(masterStorage);
if (clobTrigger != null) {
mTriggerManager.addTrigger(clobTrigger);
}
replicaStorage.addTrigger(mTriggerManager);
}
@Override
public Object beforeInsert(S replica) throws PersistException {
return beforeInsert(replica, false);
}
@Override
public Object beforeTryInsert(S replica) throws PersistException {
return beforeInsert(replica, true);
}
private Object beforeInsert(S replica, boolean forTry) throws PersistException {
final S master = mMasterStorage.prepare();
replica.copyAllProperties(master);
try {
if (forTry) {
if (!master.tryInsert()) {
throw abortTry();
}
} else {
master.insert();
}
} catch (UniqueConstraintException e) {
// This may be caused by an inconsistency between replica and
// master. Here's one scenerio: user called tryLoad and saw the
// entry does not exist. So instead of calling update, he/she calls
// insert. If the master entry exists, then there is an
// inconsistency. The code below checks for this specific kind of
// error and repairs it by inserting a record in the replica.
// Here's another scenerio: Unique constraint was caused by an
// inconsistency with the values of the alternate keys. User
// expected alternate keys to have unique values, as indicated by
// replica.
repair(replica);
// Throw exception since we don't know what the user's intentions
// really are.
throw e;
}
// Master may have applied sequences to unitialized primary keys, so
// copy primary keys to replica. Mark properties as dirty to allow
// primary key to be changed.
replica.markPropertiesDirty();
// Copy all properties in order to trigger constraints that
// master should have resolved.
master.copyAllProperties(replica);
return null;
}
@Override
public Object beforeUpdate(S replica) throws PersistException {
return beforeUpdate(replica, false);
}
@Override
public Object beforeTryUpdate(S replica) throws PersistException {
return beforeUpdate(replica, true);
}
private Object beforeUpdate(S replica, boolean forTry) throws PersistException {
final S master = mMasterStorage.prepare();
replica.copyPrimaryKeyProperties(master);
replica.copyVersionProperty(master);
replica.copyDirtyProperties(master);
try {
if (forTry) {
if (!master.tryUpdate()) {
// Master record does not exist. To ensure consistency,
// delete record from replica.
tryDeleteReplica(replica);
throw abortTry();
}
} else {
try {
master.update();
} catch (PersistNoneException e) {
// Master record does not exist. To ensure consistency,
// delete record from replica.
tryDeleteReplica(replica);
throw e;
}
}
} catch (OptimisticLockException e) {
// This may be caused by an inconsistency between replica and
// master.
repair(replica);
// Throw original exception since we don't know what the user's
// intentions really are.
throw e;
}
// Copy master properties back, since its repository may have
// altered property values as a side effect.
master.copyUnequalProperties(replica);
return null;
}
@Override
public Object beforeDelete(S replica) throws PersistException {
S master = mMasterStorage.prepare();
replica.copyPrimaryKeyProperties(master);
// If this fails to delete anything, don't care. Any delete failure
// will be detected when the replica is deleted. If there was an
// inconsistency, it is resolved after the replica is deleted.
master.tryDelete();
return null;
}
/**
* Re-sync the replica to the master. The primary keys of both entries are
* assumed to match.
*
* @param replicaEntry current replica entry, or null if none
* @param masterEntry current master entry, or null if none
*/
void resyncEntries(S replicaEntry, S masterEntry) throws FetchException, PersistException {
if (replicaEntry == null && masterEntry == null) {
return;
}
Log log = LogFactory.getLog(ReplicatedRepository.class);
setReplicationDisabled();
try {
Transaction txn = mRepository.enterTransaction();
try {
if (replicaEntry != null) {
if (masterEntry == null) {
log.info("Deleting bogus replica entry: " + replicaEntry);
}
try {
replicaEntry.tryDelete();
} catch (PersistException e) {
log.error("Unable to delete replica entry: " + replicaEntry, e);
if (masterEntry != null) {
// Try to update instead.
S newReplicaEntry = mReplicaStorage.prepare();
transferToReplicaEntry(replicaEntry, masterEntry, newReplicaEntry);
log.info("Replacing corrupt replica entry with: " + newReplicaEntry);
try {
newReplicaEntry.update();
} catch (PersistException e2) {
log.error("Unable to update replica entry: " + replicaEntry, e2);
return;
}
}
}
}
if (masterEntry != null) {
S newReplicaEntry = mReplicaStorage.prepare();
if (replicaEntry == null) {
masterEntry.copyAllProperties(newReplicaEntry);
log.info("Adding missing replica entry: " + newReplicaEntry);
} else {
if (replicaEntry.equalProperties(masterEntry)) {
return;
}
transferToReplicaEntry(replicaEntry, masterEntry, newReplicaEntry);
log.info("Replacing stale replica entry with: " + newReplicaEntry);
}
if (!newReplicaEntry.tryInsert()) {
// Try to correct bizarre corruption.
newReplicaEntry.tryDelete();
newReplicaEntry.tryInsert();
}
}
txn.commit();
} finally {
txn.exit();
}
} finally {
setReplicationEnabled();
}
}
private void transferToReplicaEntry(S replicaEntry, S masterEntry, S newReplicaEntry) {
// First copy from old replica to preserve values of any independent
// properties. Be sure not to copy nulls from old replica to new
// replica, in case new non-nullable properties have been added. This
// is why copyUnequalProperties is called instead of copyAllProperties.
replicaEntry.copyUnequalProperties(newReplicaEntry);
// Calling copyAllProperties will skip unsupported independent
// properties in master, thus preserving old independent property values.
masterEntry.copyAllProperties(newReplicaEntry);
}
/**
* Runs a repair in a background thread. This is done for two reasons: It
* allows repair to not be hindered by locks acquired by transactions and
* repairs don't get rolled back when culprit exception is thrown. Culprit
* may be UniqueConstraintException or OptimisticLockException.
*/
private void repair(S replica) throws PersistException {
replica = (S) replica.copy();
S master = mMasterStorage.prepare();
// Must copy more than just primary key properties to master since
// replica object might only have alternate keys.
replica.copyAllProperties(master);
try {
if (replica.tryLoad()) {
if (master.tryLoad()) {
if (replica.equalProperties(master)) {
// Both are equal -- no repair needed.
return;
}
}
} else {
- try {
- if (!master.tryLoad()) {
- // Both are missing -- no repair needed.
- return;
- }
- } catch (IllegalStateException e) {
- // Can be caused by not fully defining the primary key on
- // the replica, but an alternate key is. The insert will
- // fail anyhow, so don't try to repair.
+ if (!master.tryLoad()) {
+ // Both are missing -- no repair needed.
return;
}
}
+ } catch (IllegalStateException e) {
+ // Can be caused by not fully defining the primary key on the
+ // replica, but an alternate key is. The insert will fail anyhow,
+ // so don't try to repair.
+ return;
} catch (FetchException e) {
throw e.toPersistException();
}
final S finalReplica = replica;
final S finalMaster = master;
RepairExecutor.execute(new Runnable() {
public void run() {
try {
Transaction txn = mRepository.enterTransaction();
try {
txn.setForUpdate(true);
if (finalReplica.tryLoad()) {
if (finalMaster.tryLoad()) {
resyncEntries(finalReplica, finalMaster);
} else {
resyncEntries(finalReplica, null);
}
} else if (finalMaster.tryLoad()) {
resyncEntries(null, finalMaster);
}
txn.commit();
} finally {
txn.exit();
}
} catch (FetchException fe) {
Log log = LogFactory.getLog(ReplicatedRepository.class);
log.warn("Unable to check if repair is required for " +
finalReplica.toStringKeyOnly(), fe);
} catch (PersistException pe) {
Log log = LogFactory.getLog(ReplicatedRepository.class);
log.error("Unable to repair entry " +
finalReplica.toStringKeyOnly(), pe);
}
}
});
}
boolean addTrigger(Trigger<? super S> trigger) {
return mTriggerManager.addTrigger(trigger);
}
boolean removeTrigger(Trigger<? super S> trigger) {
return mTriggerManager.removeTrigger(trigger);
}
/**
* Deletes the replica entry with replication disabled.
*/
boolean tryDeleteReplica(Storable replica) throws PersistException {
// Prevent trigger from being invoked by deleting replica.
TriggerManager tm = mTriggerManager;
tm.locallyDisableDelete();
try {
return replica.tryDelete();
} finally {
tm.locallyEnableDelete();
}
}
/**
* Deletes the replica entry with replication disabled.
*/
void deleteReplica(Storable replica) throws PersistException {
// Prevent trigger from being invoked by deleting replica.
TriggerManager tm = mTriggerManager;
tm.locallyDisableDelete();
try {
replica.delete();
} finally {
tm.locallyEnableDelete();
}
}
void setReplicationDisabled() {
// This method disables not only this trigger, but all triggers added
// to manager.
TriggerManager tm = mTriggerManager;
tm.locallyDisableInsert();
tm.locallyDisableUpdate();
tm.locallyDisableDelete();
tm.locallyDisableLoad();
}
void setReplicationEnabled() {
TriggerManager tm = mTriggerManager;
tm.locallyEnableInsert();
tm.locallyEnableUpdate();
tm.locallyEnableDelete();
tm.locallyEnableLoad();
}
}
| false | true | private void repair(S replica) throws PersistException {
replica = (S) replica.copy();
S master = mMasterStorage.prepare();
// Must copy more than just primary key properties to master since
// replica object might only have alternate keys.
replica.copyAllProperties(master);
try {
if (replica.tryLoad()) {
if (master.tryLoad()) {
if (replica.equalProperties(master)) {
// Both are equal -- no repair needed.
return;
}
}
} else {
try {
if (!master.tryLoad()) {
// Both are missing -- no repair needed.
return;
}
} catch (IllegalStateException e) {
// Can be caused by not fully defining the primary key on
// the replica, but an alternate key is. The insert will
// fail anyhow, so don't try to repair.
return;
}
}
} catch (FetchException e) {
throw e.toPersistException();
}
final S finalReplica = replica;
final S finalMaster = master;
RepairExecutor.execute(new Runnable() {
public void run() {
try {
Transaction txn = mRepository.enterTransaction();
try {
txn.setForUpdate(true);
if (finalReplica.tryLoad()) {
if (finalMaster.tryLoad()) {
resyncEntries(finalReplica, finalMaster);
} else {
resyncEntries(finalReplica, null);
}
} else if (finalMaster.tryLoad()) {
resyncEntries(null, finalMaster);
}
txn.commit();
} finally {
txn.exit();
}
} catch (FetchException fe) {
Log log = LogFactory.getLog(ReplicatedRepository.class);
log.warn("Unable to check if repair is required for " +
finalReplica.toStringKeyOnly(), fe);
} catch (PersistException pe) {
Log log = LogFactory.getLog(ReplicatedRepository.class);
log.error("Unable to repair entry " +
finalReplica.toStringKeyOnly(), pe);
}
}
});
}
| private void repair(S replica) throws PersistException {
replica = (S) replica.copy();
S master = mMasterStorage.prepare();
// Must copy more than just primary key properties to master since
// replica object might only have alternate keys.
replica.copyAllProperties(master);
try {
if (replica.tryLoad()) {
if (master.tryLoad()) {
if (replica.equalProperties(master)) {
// Both are equal -- no repair needed.
return;
}
}
} else {
if (!master.tryLoad()) {
// Both are missing -- no repair needed.
return;
}
}
} catch (IllegalStateException e) {
// Can be caused by not fully defining the primary key on the
// replica, but an alternate key is. The insert will fail anyhow,
// so don't try to repair.
return;
} catch (FetchException e) {
throw e.toPersistException();
}
final S finalReplica = replica;
final S finalMaster = master;
RepairExecutor.execute(new Runnable() {
public void run() {
try {
Transaction txn = mRepository.enterTransaction();
try {
txn.setForUpdate(true);
if (finalReplica.tryLoad()) {
if (finalMaster.tryLoad()) {
resyncEntries(finalReplica, finalMaster);
} else {
resyncEntries(finalReplica, null);
}
} else if (finalMaster.tryLoad()) {
resyncEntries(null, finalMaster);
}
txn.commit();
} finally {
txn.exit();
}
} catch (FetchException fe) {
Log log = LogFactory.getLog(ReplicatedRepository.class);
log.warn("Unable to check if repair is required for " +
finalReplica.toStringKeyOnly(), fe);
} catch (PersistException pe) {
Log log = LogFactory.getLog(ReplicatedRepository.class);
log.error("Unable to repair entry " +
finalReplica.toStringKeyOnly(), pe);
}
}
});
}
|
diff --git a/src/com/utopia/lijiang/contacts/ContactProjectionBuilder.java b/src/com/utopia/lijiang/contacts/ContactProjectionBuilder.java
index 59c61b8..9cdacfa 100644
--- a/src/com/utopia/lijiang/contacts/ContactProjectionBuilder.java
+++ b/src/com/utopia/lijiang/contacts/ContactProjectionBuilder.java
@@ -1,68 +1,69 @@
package com.utopia.lijiang.contacts;
import java.util.ArrayList;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.Photo;
public class ContactProjectionBuilder {
static final String[] PHONES_PROJECTION =
new String[] {Phone.DISPLAY_NAME, Phone.NUMBER, Photo.PHOTO_ID,Phone.CONTACT_ID };
static final int PHONES_DISPLAY_NAME_INDEX = 0;
static final int PHONES_NUMBER_INDEX = 1;
static final int PHONES_PHOTO_ID_INDEX = 2;
static final int PHONES_CONTACT_ID_INDEX = 3;
private Boolean[] includeField = new Boolean[4];
public void inlcudeDisplayName(Boolean value){
includeField[PHONES_DISPLAY_NAME_INDEX] = value;
}
public void inlcudeNumber(Boolean value){
includeField[PHONES_NUMBER_INDEX] = value;
}
public void inlcudePhotoId(Boolean value){
includeField[PHONES_PHOTO_ID_INDEX] = value;
}
public void inlcudeContactId(Boolean value){
includeField[PHONES_CONTACT_ID_INDEX] = value;
}
public Boolean isIncludeDisplayName(){
return includeField[PHONES_DISPLAY_NAME_INDEX];
}
public Boolean isIncludeNumber(){
return includeField[PHONES_NUMBER_INDEX];
}
public Boolean isIncludePhotoId(){
return includeField[PHONES_PHOTO_ID_INDEX];
}
public Boolean isIncludeContanctId(){
return includeField[PHONES_CONTACT_ID_INDEX];
}
public String[] getProjection() {
ArrayList<String> projection = new ArrayList<String>();
int index=0;
while(index< includeField.length){
if(includeField[index]){
projection.add(PHONES_PROJECTION[index]);
}
+ index++;
}
return (String[]) projection.toArray();
}
}
| true | true | public String[] getProjection() {
ArrayList<String> projection = new ArrayList<String>();
int index=0;
while(index< includeField.length){
if(includeField[index]){
projection.add(PHONES_PROJECTION[index]);
}
}
return (String[]) projection.toArray();
}
| public String[] getProjection() {
ArrayList<String> projection = new ArrayList<String>();
int index=0;
while(index< includeField.length){
if(includeField[index]){
projection.add(PHONES_PROJECTION[index]);
}
index++;
}
return (String[]) projection.toArray();
}
|
diff --git a/src/com/android/settings/SecuritySettings.java b/src/com/android/settings/SecuritySettings.java
index e9e3a193e..ce59fddee 100644
--- a/src/com/android/settings/SecuritySettings.java
+++ b/src/com/android/settings/SecuritySettings.java
@@ -1,616 +1,618 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings;
import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.KeyguardManager;
import android.app.admin.DevicePolicyManager;
import android.appwidget.AppWidgetHost;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.UserHandle;
import android.os.Vibrator;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import android.security.KeyStore;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import com.android.internal.widget.LockPatternUtils;
import java.util.ArrayList;
import java.util.List;
/**
* Gesture lock pattern settings.
*/
public class SecuritySettings extends SettingsPreferenceFragment
implements OnPreferenceChangeListener, DialogInterface.OnClickListener {
static final String TAG = "SecuritySettings";
// Lock Settings
private static final String KEY_UNLOCK_SET_OR_CHANGE = "unlock_set_or_change";
private static final String KEY_CHOOSE_USER_SELECTED_LOCKSCREEN_WIDGET =
"choose_user_selected_lockscreen_widget";
private static final String KEY_BIOMETRIC_WEAK_IMPROVE_MATCHING =
"biometric_weak_improve_matching";
private static final String KEY_BIOMETRIC_WEAK_LIVELINESS = "biometric_weak_liveliness";
private static final String KEY_LOCK_ENABLED = "lockenabled";
private static final String KEY_VISIBLE_PATTERN = "visiblepattern";
private static final String KEY_TACTILE_FEEDBACK_ENABLED = "unlock_tactile_feedback";
private static final String KEY_SECURITY_CATEGORY = "security_category";
private static final String KEY_LOCK_AFTER_TIMEOUT = "lock_after_timeout";
private static final String EXTRA_NO_WIDGET = "com.android.settings.NO_WIDGET";
private static final int SET_OR_CHANGE_LOCK_METHOD_REQUEST = 123;
private static final int CONFIRM_EXISTING_FOR_BIOMETRIC_WEAK_IMPROVE_REQUEST = 124;
private static final int CONFIRM_EXISTING_FOR_BIOMETRIC_WEAK_LIVELINESS_OFF = 125;
private static final int REQUEST_PICK_APPWIDGET = 126;
private static final int REQUEST_CREATE_APPWIDGET = 127;
// Misc Settings
private static final String KEY_SIM_LOCK = "sim_lock";
private static final String KEY_SHOW_PASSWORD = "show_password";
private static final String KEY_RESET_CREDENTIALS = "reset_credentials";
private static final String KEY_TOGGLE_INSTALL_APPLICATIONS = "toggle_install_applications";
private static final String KEY_TOGGLE_VERIFY_APPLICATIONS = "toggle_verify_applications";
private static final String KEY_POWER_INSTANTLY_LOCKS = "power_button_instantly_locks";
private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
DevicePolicyManager mDPM;
private ChooseLockSettingsHelper mChooseLockSettingsHelper;
private Preference mUserSelectedWidget;
private LockPatternUtils mLockPatternUtils;
private ListPreference mLockAfter;
private CheckBoxPreference mBiometricWeakLiveliness;
private CheckBoxPreference mVisiblePattern;
private CheckBoxPreference mTactileFeedback;
private CheckBoxPreference mShowPassword;
private Preference mResetCredentials;
private CheckBoxPreference mToggleAppInstallation;
private DialogInterface mWarnInstallApps;
private CheckBoxPreference mToggleVerifyApps;
private CheckBoxPreference mPowerButtonInstantlyLocks;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLockPatternUtils = new LockPatternUtils(getActivity());
mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
mChooseLockSettingsHelper = new ChooseLockSettingsHelper(getActivity());
}
private PreferenceScreen createPreferenceHierarchy() {
PreferenceScreen root = getPreferenceScreen();
if (root != null) {
root.removeAll();
}
addPreferencesFromResource(R.xml.security_settings);
root = getPreferenceScreen();
// Add options for lock/unlock screen
int resid = 0;
if (!mLockPatternUtils.isSecure()) {
if (mLockPatternUtils.isLockScreenDisabled()) {
resid = R.xml.security_settings_lockscreen;
} else {
resid = R.xml.security_settings_chooser;
}
} else if (mLockPatternUtils.usingBiometricWeak() &&
mLockPatternUtils.isBiometricWeakInstalled()) {
resid = R.xml.security_settings_biometric_weak;
} else {
switch (mLockPatternUtils.getKeyguardStoredPasswordQuality()) {
case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
resid = R.xml.security_settings_pattern;
break;
case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
resid = R.xml.security_settings_pin;
break;
case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
resid = R.xml.security_settings_password;
break;
}
}
addPreferencesFromResource(resid);
// Add options for device encryption
DevicePolicyManager dpm =
(DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
if (UserHandle.myUserId() == 0) {
switch (dpm.getStorageEncryptionStatus()) {
case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
// The device is currently encrypted.
addPreferencesFromResource(R.xml.security_settings_encrypted);
break;
case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
// This device supports encryption but isn't encrypted.
addPreferencesFromResource(R.xml.security_settings_unencrypted);
break;
}
}
// lock after preference
mLockAfter = (ListPreference) root.findPreference(KEY_LOCK_AFTER_TIMEOUT);
if (mLockAfter != null) {
setupLockAfterPreference();
updateLockAfterPreferenceSummary();
}
// biometric weak liveliness
mBiometricWeakLiveliness =
(CheckBoxPreference) root.findPreference(KEY_BIOMETRIC_WEAK_LIVELINESS);
// visible pattern
mVisiblePattern = (CheckBoxPreference) root.findPreference(KEY_VISIBLE_PATTERN);
// lock instantly on power key press
mPowerButtonInstantlyLocks = (CheckBoxPreference) root.findPreference(
KEY_POWER_INSTANTLY_LOCKS);
// don't display visible pattern if biometric and backup is not pattern
if (resid == R.xml.security_settings_biometric_weak &&
mLockPatternUtils.getKeyguardStoredPasswordQuality() !=
DevicePolicyManager.PASSWORD_QUALITY_SOMETHING) {
PreferenceGroup securityCategory = (PreferenceGroup)
root.findPreference(KEY_SECURITY_CATEGORY);
if (securityCategory != null && mVisiblePattern != null) {
securityCategory.removePreference(root.findPreference(KEY_VISIBLE_PATTERN));
}
}
// tactile feedback. Should be common to all unlock preference screens.
mTactileFeedback = (CheckBoxPreference) root.findPreference(KEY_TACTILE_FEEDBACK_ENABLED);
if (!((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).hasVibrator()) {
PreferenceGroup securityCategory = (PreferenceGroup)
root.findPreference(KEY_SECURITY_CATEGORY);
if (securityCategory != null && mTactileFeedback != null) {
securityCategory.removePreference(mTactileFeedback);
}
}
if (UserHandle.myUserId() > 0) {
return root;
}
// Rest are for primary user...
// Append the rest of the settings
addPreferencesFromResource(R.xml.security_settings_misc);
// Do not display SIM lock for devices without an Icc card
TelephonyManager tm = TelephonyManager.getDefault();
if (!tm.hasIccCard()) {
root.removePreference(root.findPreference(KEY_SIM_LOCK));
} else {
// Disable SIM lock if sim card is missing or unknown
if ((TelephonyManager.getDefault().getSimState() ==
TelephonyManager.SIM_STATE_ABSENT) ||
(TelephonyManager.getDefault().getSimState() ==
TelephonyManager.SIM_STATE_UNKNOWN)) {
root.findPreference(KEY_SIM_LOCK).setEnabled(false);
}
}
// Show password
mShowPassword = (CheckBoxPreference) root.findPreference(KEY_SHOW_PASSWORD);
// Credential storage
mResetCredentials = root.findPreference(KEY_RESET_CREDENTIALS);
mToggleAppInstallation = (CheckBoxPreference) findPreference(
KEY_TOGGLE_INSTALL_APPLICATIONS);
mToggleAppInstallation.setChecked(isNonMarketAppsAllowed());
// Package verification
mToggleVerifyApps = (CheckBoxPreference) findPreference(KEY_TOGGLE_VERIFY_APPLICATIONS);
if (isVerifierInstalled()) {
mToggleVerifyApps.setChecked(isVerifyAppsEnabled());
} else {
mToggleVerifyApps.setChecked(false);
mToggleVerifyApps.setEnabled(false);
}
mUserSelectedWidget = root.findPreference(KEY_CHOOSE_USER_SELECTED_LOCKSCREEN_WIDGET);
- AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getActivity());
- int appWidgetId = -1;
- String appWidgetIdString = Settings.Secure.getString(
- getContentResolver(), Settings.Secure.LOCK_SCREEN_USER_SELECTED_APPWIDGET_ID);
- if (appWidgetIdString != null) {;
- appWidgetId = (int) Integer.decode(appWidgetIdString);
- }
- if (appWidgetId == -1) {
- mUserSelectedWidget.setSummary(getResources().getString(R.string.widget_none));
- } else {
- AppWidgetProviderInfo appWidget = appWidgetManager.getAppWidgetInfo(appWidgetId);
- if (appWidget != null) {
- mUserSelectedWidget.setSummary(appWidget.label);
+ if (mUserSelectedWidget != null) {
+ AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getActivity());
+ int appWidgetId = -1;
+ String appWidgetIdString = Settings.Secure.getString(
+ getContentResolver(), Settings.Secure.LOCK_SCREEN_USER_SELECTED_APPWIDGET_ID);
+ if (appWidgetIdString != null) {;
+ appWidgetId = (int) Integer.decode(appWidgetIdString);
+ }
+ if (appWidgetId == -1) {
+ mUserSelectedWidget.setSummary(getResources().getString(R.string.widget_none));
+ } else {
+ AppWidgetProviderInfo appWidget = appWidgetManager.getAppWidgetInfo(appWidgetId);
+ if (appWidget != null) {
+ mUserSelectedWidget.setSummary(appWidget.label);
+ }
}
}
return root;
}
private boolean isNonMarketAppsAllowed() {
return Settings.Global.getInt(getContentResolver(),
Settings.Global.INSTALL_NON_MARKET_APPS, 0) > 0;
}
private void setNonMarketAppsAllowed(boolean enabled) {
// Change the system setting
Settings.Global.putInt(getContentResolver(), Settings.Global.INSTALL_NON_MARKET_APPS,
enabled ? 1 : 0);
}
private boolean isVerifyAppsEnabled() {
return Settings.Global.getInt(getContentResolver(),
Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) > 0;
}
private boolean isVerifierInstalled() {
final PackageManager pm = getPackageManager();
final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
verification.setType(PACKAGE_MIME_TYPE);
verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
final List<ResolveInfo> receivers = pm.queryBroadcastReceivers(verification, 0);
return (receivers.size() > 0) ? true : false;
}
private void warnAppInstallation() {
// TODO: DialogFragment?
mWarnInstallApps = new AlertDialog.Builder(getActivity()).setTitle(
getResources().getString(R.string.error_title))
.setIcon(com.android.internal.R.drawable.ic_dialog_alert)
.setMessage(getResources().getString(R.string.install_all_warning))
.setPositiveButton(android.R.string.yes, this)
.setNegativeButton(android.R.string.no, null)
.show();
}
public void onClick(DialogInterface dialog, int which) {
if (dialog == mWarnInstallApps && which == DialogInterface.BUTTON_POSITIVE) {
setNonMarketAppsAllowed(true);
if (mToggleAppInstallation != null) {
mToggleAppInstallation.setChecked(true);
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (mWarnInstallApps != null) {
mWarnInstallApps.dismiss();
}
}
private void setupLockAfterPreference() {
// Compatible with pre-Froyo
long currentTimeout = Settings.Secure.getLong(getContentResolver(),
Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT, 5000);
mLockAfter.setValue(String.valueOf(currentTimeout));
mLockAfter.setOnPreferenceChangeListener(this);
final long adminTimeout = (mDPM != null ? mDPM.getMaximumTimeToLock(null) : 0);
final long displayTimeout = Math.max(0,
Settings.System.getInt(getContentResolver(), SCREEN_OFF_TIMEOUT, 0));
if (adminTimeout > 0) {
// This setting is a slave to display timeout when a device policy is enforced.
// As such, maxLockTimeout = adminTimeout - displayTimeout.
// If there isn't enough time, shows "immediately" setting.
disableUnusableTimeouts(Math.max(0, adminTimeout - displayTimeout));
}
}
private void updateLockAfterPreferenceSummary() {
// Update summary message with current value
long currentTimeout = Settings.Secure.getLong(getContentResolver(),
Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT, 5000);
final CharSequence[] entries = mLockAfter.getEntries();
final CharSequence[] values = mLockAfter.getEntryValues();
int best = 0;
for (int i = 0; i < values.length; i++) {
long timeout = Long.valueOf(values[i].toString());
if (currentTimeout >= timeout) {
best = i;
}
}
mLockAfter.setSummary(getString(R.string.lock_after_timeout_summary, entries[best]));
}
private void disableUnusableTimeouts(long maxTimeout) {
final CharSequence[] entries = mLockAfter.getEntries();
final CharSequence[] values = mLockAfter.getEntryValues();
ArrayList<CharSequence> revisedEntries = new ArrayList<CharSequence>();
ArrayList<CharSequence> revisedValues = new ArrayList<CharSequence>();
for (int i = 0; i < values.length; i++) {
long timeout = Long.valueOf(values[i].toString());
if (timeout <= maxTimeout) {
revisedEntries.add(entries[i]);
revisedValues.add(values[i]);
}
}
if (revisedEntries.size() != entries.length || revisedValues.size() != values.length) {
mLockAfter.setEntries(
revisedEntries.toArray(new CharSequence[revisedEntries.size()]));
mLockAfter.setEntryValues(
revisedValues.toArray(new CharSequence[revisedValues.size()]));
final int userPreference = Integer.valueOf(mLockAfter.getValue());
if (userPreference <= maxTimeout) {
mLockAfter.setValue(String.valueOf(userPreference));
} else {
// There will be no highlighted selection since nothing in the list matches
// maxTimeout. The user can still select anything less than maxTimeout.
// TODO: maybe append maxTimeout to the list and mark selected.
}
}
mLockAfter.setEnabled(revisedEntries.size() > 0);
}
@Override
public void onResume() {
super.onResume();
// Make sure we reload the preference hierarchy since some of these settings
// depend on others...
createPreferenceHierarchy();
final LockPatternUtils lockPatternUtils = mChooseLockSettingsHelper.utils();
if (mBiometricWeakLiveliness != null) {
mBiometricWeakLiveliness.setChecked(
lockPatternUtils.isBiometricWeakLivelinessEnabled());
}
if (mVisiblePattern != null) {
mVisiblePattern.setChecked(lockPatternUtils.isVisiblePatternEnabled());
}
if (mTactileFeedback != null) {
mTactileFeedback.setChecked(lockPatternUtils.isTactileFeedbackEnabled());
}
if (mPowerButtonInstantlyLocks != null) {
mPowerButtonInstantlyLocks.setChecked(lockPatternUtils.getPowerButtonInstantlyLocks());
}
if (mShowPassword != null) {
mShowPassword.setChecked(Settings.System.getInt(getContentResolver(),
Settings.System.TEXT_SHOW_PASSWORD, 1) != 0);
}
KeyStore.State state = KeyStore.getInstance().state();
if (mResetCredentials != null) {
mResetCredentials.setEnabled(state != KeyStore.State.UNINITIALIZED);
}
}
void startActivityForResultSafely(Intent intent, int requestCode) {
try {
startActivityForResult(intent, requestCode);
} catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), R.string.activity_not_found, Toast.LENGTH_SHORT).show();
} catch (SecurityException e) {
Toast.makeText(getActivity(), R.string.activity_not_found, Toast.LENGTH_SHORT).show();
Log.e(TAG, "Settings does not have the permission to launch " + intent, e);
}
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
final String key = preference.getKey();
final LockPatternUtils lockPatternUtils = mChooseLockSettingsHelper.utils();
if (KEY_UNLOCK_SET_OR_CHANGE.equals(key)) {
startFragment(this, "com.android.settings.ChooseLockGeneric$ChooseLockGenericFragment",
SET_OR_CHANGE_LOCK_METHOD_REQUEST, null);
} else if (KEY_CHOOSE_USER_SELECTED_LOCKSCREEN_WIDGET.equals(key)) {
// Create intent to pick widget
Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
// Found in KeyguardHostView.java
final int KEYGUARD_HOST_ID = 0x4B455947;
int appWidgetId = AppWidgetHost.allocateAppWidgetIdForHost(
"com.android.internal.policy.impl.keyguard", KEYGUARD_HOST_ID);
if (appWidgetId != -1) {
pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
pickIntent.putExtra(AppWidgetManager.EXTRA_CUSTOM_SORT, false);
pickIntent.putExtra(AppWidgetManager.EXTRA_CATEGORY_FILTER,
AppWidgetProviderInfo.WIDGET_CATEGORY_KEYGUARD);
// Add an entry for "none" to let someone select no widget
AppWidgetProviderInfo noneInfo = new AppWidgetProviderInfo();
ArrayList<AppWidgetProviderInfo> extraInfos = new ArrayList<AppWidgetProviderInfo>();
noneInfo.label = getResources().getString(R.string.widget_none);
noneInfo.provider = new ComponentName("", "");
extraInfos.add(noneInfo);
ArrayList<Bundle> extraExtras = new ArrayList<Bundle>();
Bundle b = new Bundle();
b.putBoolean(EXTRA_NO_WIDGET, true);
extraExtras.add(b);
// Launch the widget picker
pickIntent.putExtra(AppWidgetManager.EXTRA_CUSTOM_INFO, extraInfos);
pickIntent.putExtra(AppWidgetManager.EXTRA_CUSTOM_EXTRAS, extraExtras);
startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET);
} else {
Log.e(TAG, "Unable to allocate an AppWidget id in lock screen");
}
} else if (KEY_BIOMETRIC_WEAK_IMPROVE_MATCHING.equals(key)) {
ChooseLockSettingsHelper helper =
new ChooseLockSettingsHelper(this.getActivity(), this);
if (!helper.launchConfirmationActivity(
CONFIRM_EXISTING_FOR_BIOMETRIC_WEAK_IMPROVE_REQUEST, null, null)) {
// If this returns false, it means no password confirmation is required, so
// go ahead and start improve.
// Note: currently a backup is required for biometric_weak so this code path
// can't be reached, but is here in case things change in the future
startBiometricWeakImprove();
}
} else if (KEY_BIOMETRIC_WEAK_LIVELINESS.equals(key)) {
if (isToggled(preference)) {
lockPatternUtils.setBiometricWeakLivelinessEnabled(true);
} else {
// In this case the user has just unchecked the checkbox, but this action requires
// them to confirm their password. We need to re-check the checkbox until
// they've confirmed their password
mBiometricWeakLiveliness.setChecked(true);
ChooseLockSettingsHelper helper =
new ChooseLockSettingsHelper(this.getActivity(), this);
if (!helper.launchConfirmationActivity(
CONFIRM_EXISTING_FOR_BIOMETRIC_WEAK_LIVELINESS_OFF, null, null)) {
// If this returns false, it means no password confirmation is required, so
// go ahead and uncheck it here.
// Note: currently a backup is required for biometric_weak so this code path
// can't be reached, but is here in case things change in the future
lockPatternUtils.setBiometricWeakLivelinessEnabled(false);
mBiometricWeakLiveliness.setChecked(false);
}
}
} else if (KEY_LOCK_ENABLED.equals(key)) {
lockPatternUtils.setLockPatternEnabled(isToggled(preference));
} else if (KEY_VISIBLE_PATTERN.equals(key)) {
lockPatternUtils.setVisiblePatternEnabled(isToggled(preference));
} else if (KEY_TACTILE_FEEDBACK_ENABLED.equals(key)) {
lockPatternUtils.setTactileFeedbackEnabled(isToggled(preference));
} else if (KEY_POWER_INSTANTLY_LOCKS.equals(key)) {
lockPatternUtils.setPowerButtonInstantlyLocks(isToggled(preference));
} else if (preference == mShowPassword) {
Settings.System.putInt(getContentResolver(), Settings.System.TEXT_SHOW_PASSWORD,
mShowPassword.isChecked() ? 1 : 0);
} else if (preference == mToggleAppInstallation) {
if (mToggleAppInstallation.isChecked()) {
mToggleAppInstallation.setChecked(false);
warnAppInstallation();
} else {
setNonMarketAppsAllowed(false);
}
} else if (KEY_TOGGLE_VERIFY_APPLICATIONS.equals(key)) {
Settings.Global.putInt(getContentResolver(), Settings.Global.PACKAGE_VERIFIER_ENABLE,
mToggleVerifyApps.isChecked() ? 1 : 0);
} else {
// If we didn't handle it, let preferences handle it.
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
return true;
}
private boolean isToggled(Preference pref) {
return ((CheckBoxPreference) pref).isChecked();
}
/**
* see confirmPatternThenDisableAndClear
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CONFIRM_EXISTING_FOR_BIOMETRIC_WEAK_IMPROVE_REQUEST &&
resultCode == Activity.RESULT_OK) {
startBiometricWeakImprove();
return;
} else if (requestCode == CONFIRM_EXISTING_FOR_BIOMETRIC_WEAK_LIVELINESS_OFF &&
resultCode == Activity.RESULT_OK) {
final LockPatternUtils lockPatternUtils = mChooseLockSettingsHelper.utils();
lockPatternUtils.setBiometricWeakLivelinessEnabled(false);
// Setting the mBiometricWeakLiveliness checked value to false is handled when onResume
// is called by grabbing the value from lockPatternUtils. We can't set it here
// because mBiometricWeakLiveliness could be null
return;
} else if (requestCode == REQUEST_PICK_APPWIDGET ||
requestCode == REQUEST_CREATE_APPWIDGET) {
int appWidgetId = (data == null) ? -1 : data.getIntExtra(
AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
if (requestCode == REQUEST_PICK_APPWIDGET && resultCode == Activity.RESULT_OK) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getActivity());
boolean noWidget = data.getBooleanExtra(EXTRA_NO_WIDGET, false);
AppWidgetProviderInfo appWidget = null;
if (!noWidget) {
appWidget = appWidgetManager.getAppWidgetInfo(appWidgetId);
}
if (!noWidget && appWidget.configure != null) {
// Launch over to configure widget, if needed
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
intent.setComponent(appWidget.configure);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
startActivityForResultSafely(intent, REQUEST_CREATE_APPWIDGET);
} else {
// Otherwise just add it
if (noWidget) {
data.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
}
onActivityResult(REQUEST_CREATE_APPWIDGET, Activity.RESULT_OK, data);
}
} else if (requestCode == REQUEST_CREATE_APPWIDGET && resultCode == Activity.RESULT_OK) {
Settings.Secure.putString(getContentResolver(),
Settings.Secure.LOCK_SCREEN_USER_SELECTED_APPWIDGET_ID,
Integer.toString(appWidgetId));
} else {
AppWidgetHost.deleteAppWidgetIdForHost(appWidgetId);
}
}
createPreferenceHierarchy();
}
public boolean onPreferenceChange(Preference preference, Object value) {
if (preference == mLockAfter) {
int timeout = Integer.parseInt((String) value);
try {
Settings.Secure.putInt(getContentResolver(),
Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT, timeout);
} catch (NumberFormatException e) {
Log.e("SecuritySettings", "could not persist lockAfter timeout setting", e);
}
updateLockAfterPreferenceSummary();
}
return true;
}
public void startBiometricWeakImprove(){
Intent intent = new Intent();
intent.setClassName("com.android.facelock", "com.android.facelock.AddToSetup");
startActivity(intent);
}
}
| true | true | private PreferenceScreen createPreferenceHierarchy() {
PreferenceScreen root = getPreferenceScreen();
if (root != null) {
root.removeAll();
}
addPreferencesFromResource(R.xml.security_settings);
root = getPreferenceScreen();
// Add options for lock/unlock screen
int resid = 0;
if (!mLockPatternUtils.isSecure()) {
if (mLockPatternUtils.isLockScreenDisabled()) {
resid = R.xml.security_settings_lockscreen;
} else {
resid = R.xml.security_settings_chooser;
}
} else if (mLockPatternUtils.usingBiometricWeak() &&
mLockPatternUtils.isBiometricWeakInstalled()) {
resid = R.xml.security_settings_biometric_weak;
} else {
switch (mLockPatternUtils.getKeyguardStoredPasswordQuality()) {
case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
resid = R.xml.security_settings_pattern;
break;
case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
resid = R.xml.security_settings_pin;
break;
case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
resid = R.xml.security_settings_password;
break;
}
}
addPreferencesFromResource(resid);
// Add options for device encryption
DevicePolicyManager dpm =
(DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
if (UserHandle.myUserId() == 0) {
switch (dpm.getStorageEncryptionStatus()) {
case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
// The device is currently encrypted.
addPreferencesFromResource(R.xml.security_settings_encrypted);
break;
case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
// This device supports encryption but isn't encrypted.
addPreferencesFromResource(R.xml.security_settings_unencrypted);
break;
}
}
// lock after preference
mLockAfter = (ListPreference) root.findPreference(KEY_LOCK_AFTER_TIMEOUT);
if (mLockAfter != null) {
setupLockAfterPreference();
updateLockAfterPreferenceSummary();
}
// biometric weak liveliness
mBiometricWeakLiveliness =
(CheckBoxPreference) root.findPreference(KEY_BIOMETRIC_WEAK_LIVELINESS);
// visible pattern
mVisiblePattern = (CheckBoxPreference) root.findPreference(KEY_VISIBLE_PATTERN);
// lock instantly on power key press
mPowerButtonInstantlyLocks = (CheckBoxPreference) root.findPreference(
KEY_POWER_INSTANTLY_LOCKS);
// don't display visible pattern if biometric and backup is not pattern
if (resid == R.xml.security_settings_biometric_weak &&
mLockPatternUtils.getKeyguardStoredPasswordQuality() !=
DevicePolicyManager.PASSWORD_QUALITY_SOMETHING) {
PreferenceGroup securityCategory = (PreferenceGroup)
root.findPreference(KEY_SECURITY_CATEGORY);
if (securityCategory != null && mVisiblePattern != null) {
securityCategory.removePreference(root.findPreference(KEY_VISIBLE_PATTERN));
}
}
// tactile feedback. Should be common to all unlock preference screens.
mTactileFeedback = (CheckBoxPreference) root.findPreference(KEY_TACTILE_FEEDBACK_ENABLED);
if (!((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).hasVibrator()) {
PreferenceGroup securityCategory = (PreferenceGroup)
root.findPreference(KEY_SECURITY_CATEGORY);
if (securityCategory != null && mTactileFeedback != null) {
securityCategory.removePreference(mTactileFeedback);
}
}
if (UserHandle.myUserId() > 0) {
return root;
}
// Rest are for primary user...
// Append the rest of the settings
addPreferencesFromResource(R.xml.security_settings_misc);
// Do not display SIM lock for devices without an Icc card
TelephonyManager tm = TelephonyManager.getDefault();
if (!tm.hasIccCard()) {
root.removePreference(root.findPreference(KEY_SIM_LOCK));
} else {
// Disable SIM lock if sim card is missing or unknown
if ((TelephonyManager.getDefault().getSimState() ==
TelephonyManager.SIM_STATE_ABSENT) ||
(TelephonyManager.getDefault().getSimState() ==
TelephonyManager.SIM_STATE_UNKNOWN)) {
root.findPreference(KEY_SIM_LOCK).setEnabled(false);
}
}
// Show password
mShowPassword = (CheckBoxPreference) root.findPreference(KEY_SHOW_PASSWORD);
// Credential storage
mResetCredentials = root.findPreference(KEY_RESET_CREDENTIALS);
mToggleAppInstallation = (CheckBoxPreference) findPreference(
KEY_TOGGLE_INSTALL_APPLICATIONS);
mToggleAppInstallation.setChecked(isNonMarketAppsAllowed());
// Package verification
mToggleVerifyApps = (CheckBoxPreference) findPreference(KEY_TOGGLE_VERIFY_APPLICATIONS);
if (isVerifierInstalled()) {
mToggleVerifyApps.setChecked(isVerifyAppsEnabled());
} else {
mToggleVerifyApps.setChecked(false);
mToggleVerifyApps.setEnabled(false);
}
mUserSelectedWidget = root.findPreference(KEY_CHOOSE_USER_SELECTED_LOCKSCREEN_WIDGET);
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getActivity());
int appWidgetId = -1;
String appWidgetIdString = Settings.Secure.getString(
getContentResolver(), Settings.Secure.LOCK_SCREEN_USER_SELECTED_APPWIDGET_ID);
if (appWidgetIdString != null) {;
appWidgetId = (int) Integer.decode(appWidgetIdString);
}
if (appWidgetId == -1) {
mUserSelectedWidget.setSummary(getResources().getString(R.string.widget_none));
} else {
AppWidgetProviderInfo appWidget = appWidgetManager.getAppWidgetInfo(appWidgetId);
if (appWidget != null) {
mUserSelectedWidget.setSummary(appWidget.label);
}
}
return root;
}
| private PreferenceScreen createPreferenceHierarchy() {
PreferenceScreen root = getPreferenceScreen();
if (root != null) {
root.removeAll();
}
addPreferencesFromResource(R.xml.security_settings);
root = getPreferenceScreen();
// Add options for lock/unlock screen
int resid = 0;
if (!mLockPatternUtils.isSecure()) {
if (mLockPatternUtils.isLockScreenDisabled()) {
resid = R.xml.security_settings_lockscreen;
} else {
resid = R.xml.security_settings_chooser;
}
} else if (mLockPatternUtils.usingBiometricWeak() &&
mLockPatternUtils.isBiometricWeakInstalled()) {
resid = R.xml.security_settings_biometric_weak;
} else {
switch (mLockPatternUtils.getKeyguardStoredPasswordQuality()) {
case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
resid = R.xml.security_settings_pattern;
break;
case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
resid = R.xml.security_settings_pin;
break;
case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
resid = R.xml.security_settings_password;
break;
}
}
addPreferencesFromResource(resid);
// Add options for device encryption
DevicePolicyManager dpm =
(DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
if (UserHandle.myUserId() == 0) {
switch (dpm.getStorageEncryptionStatus()) {
case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
// The device is currently encrypted.
addPreferencesFromResource(R.xml.security_settings_encrypted);
break;
case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
// This device supports encryption but isn't encrypted.
addPreferencesFromResource(R.xml.security_settings_unencrypted);
break;
}
}
// lock after preference
mLockAfter = (ListPreference) root.findPreference(KEY_LOCK_AFTER_TIMEOUT);
if (mLockAfter != null) {
setupLockAfterPreference();
updateLockAfterPreferenceSummary();
}
// biometric weak liveliness
mBiometricWeakLiveliness =
(CheckBoxPreference) root.findPreference(KEY_BIOMETRIC_WEAK_LIVELINESS);
// visible pattern
mVisiblePattern = (CheckBoxPreference) root.findPreference(KEY_VISIBLE_PATTERN);
// lock instantly on power key press
mPowerButtonInstantlyLocks = (CheckBoxPreference) root.findPreference(
KEY_POWER_INSTANTLY_LOCKS);
// don't display visible pattern if biometric and backup is not pattern
if (resid == R.xml.security_settings_biometric_weak &&
mLockPatternUtils.getKeyguardStoredPasswordQuality() !=
DevicePolicyManager.PASSWORD_QUALITY_SOMETHING) {
PreferenceGroup securityCategory = (PreferenceGroup)
root.findPreference(KEY_SECURITY_CATEGORY);
if (securityCategory != null && mVisiblePattern != null) {
securityCategory.removePreference(root.findPreference(KEY_VISIBLE_PATTERN));
}
}
// tactile feedback. Should be common to all unlock preference screens.
mTactileFeedback = (CheckBoxPreference) root.findPreference(KEY_TACTILE_FEEDBACK_ENABLED);
if (!((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).hasVibrator()) {
PreferenceGroup securityCategory = (PreferenceGroup)
root.findPreference(KEY_SECURITY_CATEGORY);
if (securityCategory != null && mTactileFeedback != null) {
securityCategory.removePreference(mTactileFeedback);
}
}
if (UserHandle.myUserId() > 0) {
return root;
}
// Rest are for primary user...
// Append the rest of the settings
addPreferencesFromResource(R.xml.security_settings_misc);
// Do not display SIM lock for devices without an Icc card
TelephonyManager tm = TelephonyManager.getDefault();
if (!tm.hasIccCard()) {
root.removePreference(root.findPreference(KEY_SIM_LOCK));
} else {
// Disable SIM lock if sim card is missing or unknown
if ((TelephonyManager.getDefault().getSimState() ==
TelephonyManager.SIM_STATE_ABSENT) ||
(TelephonyManager.getDefault().getSimState() ==
TelephonyManager.SIM_STATE_UNKNOWN)) {
root.findPreference(KEY_SIM_LOCK).setEnabled(false);
}
}
// Show password
mShowPassword = (CheckBoxPreference) root.findPreference(KEY_SHOW_PASSWORD);
// Credential storage
mResetCredentials = root.findPreference(KEY_RESET_CREDENTIALS);
mToggleAppInstallation = (CheckBoxPreference) findPreference(
KEY_TOGGLE_INSTALL_APPLICATIONS);
mToggleAppInstallation.setChecked(isNonMarketAppsAllowed());
// Package verification
mToggleVerifyApps = (CheckBoxPreference) findPreference(KEY_TOGGLE_VERIFY_APPLICATIONS);
if (isVerifierInstalled()) {
mToggleVerifyApps.setChecked(isVerifyAppsEnabled());
} else {
mToggleVerifyApps.setChecked(false);
mToggleVerifyApps.setEnabled(false);
}
mUserSelectedWidget = root.findPreference(KEY_CHOOSE_USER_SELECTED_LOCKSCREEN_WIDGET);
if (mUserSelectedWidget != null) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getActivity());
int appWidgetId = -1;
String appWidgetIdString = Settings.Secure.getString(
getContentResolver(), Settings.Secure.LOCK_SCREEN_USER_SELECTED_APPWIDGET_ID);
if (appWidgetIdString != null) {;
appWidgetId = (int) Integer.decode(appWidgetIdString);
}
if (appWidgetId == -1) {
mUserSelectedWidget.setSummary(getResources().getString(R.string.widget_none));
} else {
AppWidgetProviderInfo appWidget = appWidgetManager.getAppWidgetInfo(appWidgetId);
if (appWidget != null) {
mUserSelectedWidget.setSummary(appWidget.label);
}
}
}
return root;
}
|
diff --git a/core/src/visad/trunk/data/mcidas/PointDataAdapter.java b/core/src/visad/trunk/data/mcidas/PointDataAdapter.java
index 9a6fbc7b0..02da3f9a2 100644
--- a/core/src/visad/trunk/data/mcidas/PointDataAdapter.java
+++ b/core/src/visad/trunk/data/mcidas/PointDataAdapter.java
@@ -1,218 +1,221 @@
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 2001 Bill Hibbard, Curtis Rueden, Tom
Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and
Tommy Jasmin.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA
*/
package visad.data.mcidas;
import edu.wisc.ssec.mcidas.*;
import edu.wisc.ssec.mcidas.adde.*;
import visad.*;
import visad.data.units.*;
import visad.jmet.MetUnits;
/**
* A class for adapting the results of an ADDE point data request into a
* VisAD Data object.
*
* @author Don Murray, Unidata
*/
public class PointDataAdapter
{
AddePointDataReader reader;
FieldImpl field = null;
long millies;
long elapsed;
/**
* Construct a PointDataAdapter using the adde request passed as a string.
*
* @param addePointRequest - string representing the ADDE request
* @throws VisADException bad request, no data available, VisAD error
*/
public PointDataAdapter(String addePointRequest)
throws VisADException
{
try
{
reader = new AddePointDataReader(addePointRequest);
}
catch (AddeException excp)
{
throw new VisADException("Problem accessing data");
}
makeField();
}
// out of this will either come a FieldImpl, a ObservationDBImpl,
// or a StationObDBImpl
private void makeField()
throws VisADException
{
// First, let's make a generic FieldImpl from the data
// the structure will be index -> parameter tuple
// get all the stuff from the reader
int[][] data;
String[] units;
String[] params;
int[] scalingFactors;
try
{
data = reader.getData();
units = reader.getUnits();
params = reader.getParams();
scalingFactors = reader.getScales();
}
catch (AddeException ae)
{
throw new VisADException("Error retrieving data info");
}
int numObs = data[0].length;
System.out.println("number of obs = " + numObs);
if (numObs == 0)
throw new VisADException("No data available");
- RealType domainType = new RealType("index");
+ RealType domainType = RealType.getRealType("index");
Integer1DSet domain = new Integer1DSet(domainType, numObs);
// now make range (Tuple) type
MetUnits unitTranslator = new MetUnits();
int numParams = params.length;
ScalarType[] types = new ScalarType[numParams];
boolean noText = true;
for (int i = 0; i < numParams; i++)
{
// get the name
String name = params[i];
// make the unit
Unit unit = null;
try
{
unit = Parser.parse(unitTranslator.makeSymbol(units[i]));
}
catch (NoSuchUnitException ne) {
System.out.println("Unknown unit: " + units[i] + " for " + name);
}
catch (ParseException pe) {;}
if (units[i].equalsIgnoreCase("CHAR"))
{
noText = false;
types[i] = TextType.getTextType(params[i]);
}
else
{
types[i] = RealType.getRealType(params[i], unit, (Set) null);
}
}
TupleType rangeType;
if (noText) // all reals
{
RealType[] newTypes = new RealType[types.length];
for (int i = 0; i < types.length; i++)
newTypes[i] = (RealType) types[i];
rangeType = new RealTupleType(newTypes);
}
else
{
rangeType = new TupleType(types);
}
FunctionType functionType =
new FunctionType(domainType, rangeType);
field = new FieldImpl(functionType, domain);
// now, fill in the data
for (int i = 0; i < numObs; i++)
{
- Scalar[] scalars = new Scalar[numParams];
+ Scalar[] scalars = (noText == true) ? new Real[numParams]
+ : new Scalar[numParams];
for (int j = 0; j < numParams; j++)
{
try
{
if (types[j] instanceof TextType)
{
scalars[j] =
new Text( (TextType) types[j],
McIDASUtil.intBitsToString(data[j][i]));
}
else
{
double value =
data[j][i] == McIDASUtil.MCMISSING
? Double.NaN
: data[j][i]/Math.pow(10.0,
(double) scalingFactors[j] );
scalars[j] =
new Real((RealType) types[j], value);
}
}
catch (Exception e) {;}
}
try
{
- field.setSample(i, new Tuple(scalars));
+ field.setSample(i, (noText == true)
+ ? new RealTuple((Real[]) scalars)
+ : new Tuple(scalars));
}
catch (java.rmi.RemoteException e) {;}
}
}
/**
* Get the VisAD Data object that represents the output from the
* request.
*
* @return requested data
*/
public Data getData()
{
return field;
}
/**
* test with 'java visad.data.mcidas.PointDataAdapter args'
* @param args ADDE point data request
*/
public static void main(String[] args)
throws Exception
{
if (args.length == 0)
{
System.out.println("You must specify an ADDE Point Data URL");
System.exit(-1);
}
try
{
PointDataAdapter pda = new PointDataAdapter(args[0]);
Field data = (Field) pda.getData();
System.out.println(data.getType());
/*
int length = data.getDomainSet().getLength() - 1;
System.out.println(
"Sample "+ length + " = " + data.getSample(length));
*/
}
catch (VisADException ve)
{
System.out.println("Error reading data");
}
}
}
| false | true | private void makeField()
throws VisADException
{
// First, let's make a generic FieldImpl from the data
// the structure will be index -> parameter tuple
// get all the stuff from the reader
int[][] data;
String[] units;
String[] params;
int[] scalingFactors;
try
{
data = reader.getData();
units = reader.getUnits();
params = reader.getParams();
scalingFactors = reader.getScales();
}
catch (AddeException ae)
{
throw new VisADException("Error retrieving data info");
}
int numObs = data[0].length;
System.out.println("number of obs = " + numObs);
if (numObs == 0)
throw new VisADException("No data available");
RealType domainType = new RealType("index");
Integer1DSet domain = new Integer1DSet(domainType, numObs);
// now make range (Tuple) type
MetUnits unitTranslator = new MetUnits();
int numParams = params.length;
ScalarType[] types = new ScalarType[numParams];
boolean noText = true;
for (int i = 0; i < numParams; i++)
{
// get the name
String name = params[i];
// make the unit
Unit unit = null;
try
{
unit = Parser.parse(unitTranslator.makeSymbol(units[i]));
}
catch (NoSuchUnitException ne) {
System.out.println("Unknown unit: " + units[i] + " for " + name);
}
catch (ParseException pe) {;}
if (units[i].equalsIgnoreCase("CHAR"))
{
noText = false;
types[i] = TextType.getTextType(params[i]);
}
else
{
types[i] = RealType.getRealType(params[i], unit, (Set) null);
}
}
TupleType rangeType;
if (noText) // all reals
{
RealType[] newTypes = new RealType[types.length];
for (int i = 0; i < types.length; i++)
newTypes[i] = (RealType) types[i];
rangeType = new RealTupleType(newTypes);
}
else
{
rangeType = new TupleType(types);
}
FunctionType functionType =
new FunctionType(domainType, rangeType);
field = new FieldImpl(functionType, domain);
// now, fill in the data
for (int i = 0; i < numObs; i++)
{
Scalar[] scalars = new Scalar[numParams];
for (int j = 0; j < numParams; j++)
{
try
{
if (types[j] instanceof TextType)
{
scalars[j] =
new Text( (TextType) types[j],
McIDASUtil.intBitsToString(data[j][i]));
}
else
{
double value =
data[j][i] == McIDASUtil.MCMISSING
? Double.NaN
: data[j][i]/Math.pow(10.0,
(double) scalingFactors[j] );
scalars[j] =
new Real((RealType) types[j], value);
}
}
catch (Exception e) {;}
}
try
{
field.setSample(i, new Tuple(scalars));
}
catch (java.rmi.RemoteException e) {;}
}
}
| private void makeField()
throws VisADException
{
// First, let's make a generic FieldImpl from the data
// the structure will be index -> parameter tuple
// get all the stuff from the reader
int[][] data;
String[] units;
String[] params;
int[] scalingFactors;
try
{
data = reader.getData();
units = reader.getUnits();
params = reader.getParams();
scalingFactors = reader.getScales();
}
catch (AddeException ae)
{
throw new VisADException("Error retrieving data info");
}
int numObs = data[0].length;
System.out.println("number of obs = " + numObs);
if (numObs == 0)
throw new VisADException("No data available");
RealType domainType = RealType.getRealType("index");
Integer1DSet domain = new Integer1DSet(domainType, numObs);
// now make range (Tuple) type
MetUnits unitTranslator = new MetUnits();
int numParams = params.length;
ScalarType[] types = new ScalarType[numParams];
boolean noText = true;
for (int i = 0; i < numParams; i++)
{
// get the name
String name = params[i];
// make the unit
Unit unit = null;
try
{
unit = Parser.parse(unitTranslator.makeSymbol(units[i]));
}
catch (NoSuchUnitException ne) {
System.out.println("Unknown unit: " + units[i] + " for " + name);
}
catch (ParseException pe) {;}
if (units[i].equalsIgnoreCase("CHAR"))
{
noText = false;
types[i] = TextType.getTextType(params[i]);
}
else
{
types[i] = RealType.getRealType(params[i], unit, (Set) null);
}
}
TupleType rangeType;
if (noText) // all reals
{
RealType[] newTypes = new RealType[types.length];
for (int i = 0; i < types.length; i++)
newTypes[i] = (RealType) types[i];
rangeType = new RealTupleType(newTypes);
}
else
{
rangeType = new TupleType(types);
}
FunctionType functionType =
new FunctionType(domainType, rangeType);
field = new FieldImpl(functionType, domain);
// now, fill in the data
for (int i = 0; i < numObs; i++)
{
Scalar[] scalars = (noText == true) ? new Real[numParams]
: new Scalar[numParams];
for (int j = 0; j < numParams; j++)
{
try
{
if (types[j] instanceof TextType)
{
scalars[j] =
new Text( (TextType) types[j],
McIDASUtil.intBitsToString(data[j][i]));
}
else
{
double value =
data[j][i] == McIDASUtil.MCMISSING
? Double.NaN
: data[j][i]/Math.pow(10.0,
(double) scalingFactors[j] );
scalars[j] =
new Real((RealType) types[j], value);
}
}
catch (Exception e) {;}
}
try
{
field.setSample(i, (noText == true)
? new RealTuple((Real[]) scalars)
: new Tuple(scalars));
}
catch (java.rmi.RemoteException e) {;}
}
}
|
diff --git a/java/modules/core/src/main/java/org/apache/synapse/config/xml/MessageStoreFactory.java b/java/modules/core/src/main/java/org/apache/synapse/config/xml/MessageStoreFactory.java
index a20442635..77cbebb75 100644
--- a/java/modules/core/src/main/java/org/apache/synapse/config/xml/MessageStoreFactory.java
+++ b/java/modules/core/src/main/java/org/apache/synapse/config/xml/MessageStoreFactory.java
@@ -1,138 +1,138 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.synapse.config.xml;
import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMElement;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.SynapseException;
import org.apache.synapse.SynapseConstants;
import org.apache.synapse.message.processors.MessageProcessor;
import org.apache.synapse.message.store.InMemoryMessageStore;
import org.apache.synapse.message.store.MessageStore;
import org.apache.axis2.util.JavaUtils;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;
import java.util.Properties;
/**
* Create an instance of the given Message Store, and sets properties on it.
* <p/>
* <messageStore name="string" class="classname" [sequence = "string" ]>
* <parameter name="string">"string" <parameter>
* <parameter name="string">"string" <parameter>
* <parameter name="string">"string" <parameter>
* .
* .
* </messageStore>
*/
public class MessageStoreFactory {
private static final Log log = LogFactory.getLog(MessageStoreFactory.class);
public static final QName CLASS_Q = new QName(XMLConfigConstants.NULL_NAMESPACE, "class");
public static final QName NAME_Q = new QName(XMLConfigConstants.NULL_NAMESPACE, "name");
public static final QName SEQUENCE_Q = new QName(XMLConfigConstants.NULL_NAMESPACE, "sequence");
public static final QName PARAMETER_Q = new QName(XMLConfigConstants.SYNAPSE_NAMESPACE,
"parameter");
private static final QName DESCRIPTION_Q
= new QName(SynapseConstants.SYNAPSE_NAMESPACE, "description");
@SuppressWarnings({"UnusedDeclaration"})
public static MessageStore createMessageStore(OMElement elem, Properties properties) {
OMAttribute clss = elem.getAttribute(CLASS_Q);
MessageStore messageStore;
if (clss != null) {
try {
Class cls = Class.forName(clss.getAttributeValue());
messageStore = (MessageStore) cls.newInstance();
} catch (Exception e) {
handleException("Error while instantiating the message store", e);
return null;
}
} else {
messageStore = new InMemoryMessageStore();
}
OMAttribute nameAtt = elem.getAttribute(NAME_Q);
if (nameAtt != null) {
messageStore.setName(nameAtt.getAttributeValue());
} else {
handleException("Message Store name not specified");
}
OMElement descriptionElem = elem.getFirstChildWithName(DESCRIPTION_Q);
if (descriptionElem != null) {
messageStore.setDescription(descriptionElem.getText());
}
messageStore.setParameters(getParameters(elem));
- log.info("Successfully created Message Store" + nameAtt.getAttributeValue());
+ log.info("Successfully created Message Store: " + nameAtt.getAttributeValue());
return messageStore;
}
private static Map<String, Object> getParameters(OMElement elem) {
Iterator params = elem.getChildrenWithName(PARAMETER_Q);
Map<String, Object> parameters = new HashMap<String, Object>();
while (params.hasNext()) {
Object o = params.next();
if (o instanceof OMElement) {
OMElement prop = (OMElement) o;
OMAttribute paramName = prop.getAttribute(NAME_Q);
String paramValue = prop.getText();
if (paramName != null) {
if (paramValue != null) {
parameters.put(paramName.getAttributeValue(), paramValue);
}
} else {
handleException("Invalid MessageStore parameter - Parameter must have a name ");
}
}
}
return parameters;
}
private static void handleException(String msg) {
log.error(msg);
throw new SynapseException(msg);
}
private static void handleException(String msg, Exception e) {
log.error(msg, e);
throw new SynapseException(msg, e);
}
}
| true | true | public static MessageStore createMessageStore(OMElement elem, Properties properties) {
OMAttribute clss = elem.getAttribute(CLASS_Q);
MessageStore messageStore;
if (clss != null) {
try {
Class cls = Class.forName(clss.getAttributeValue());
messageStore = (MessageStore) cls.newInstance();
} catch (Exception e) {
handleException("Error while instantiating the message store", e);
return null;
}
} else {
messageStore = new InMemoryMessageStore();
}
OMAttribute nameAtt = elem.getAttribute(NAME_Q);
if (nameAtt != null) {
messageStore.setName(nameAtt.getAttributeValue());
} else {
handleException("Message Store name not specified");
}
OMElement descriptionElem = elem.getFirstChildWithName(DESCRIPTION_Q);
if (descriptionElem != null) {
messageStore.setDescription(descriptionElem.getText());
}
messageStore.setParameters(getParameters(elem));
log.info("Successfully created Message Store" + nameAtt.getAttributeValue());
return messageStore;
}
| public static MessageStore createMessageStore(OMElement elem, Properties properties) {
OMAttribute clss = elem.getAttribute(CLASS_Q);
MessageStore messageStore;
if (clss != null) {
try {
Class cls = Class.forName(clss.getAttributeValue());
messageStore = (MessageStore) cls.newInstance();
} catch (Exception e) {
handleException("Error while instantiating the message store", e);
return null;
}
} else {
messageStore = new InMemoryMessageStore();
}
OMAttribute nameAtt = elem.getAttribute(NAME_Q);
if (nameAtt != null) {
messageStore.setName(nameAtt.getAttributeValue());
} else {
handleException("Message Store name not specified");
}
OMElement descriptionElem = elem.getFirstChildWithName(DESCRIPTION_Q);
if (descriptionElem != null) {
messageStore.setDescription(descriptionElem.getText());
}
messageStore.setParameters(getParameters(elem));
log.info("Successfully created Message Store: " + nameAtt.getAttributeValue());
return messageStore;
}
|
diff --git a/src/main/java/jline/UnixTerminal.java b/src/main/java/jline/UnixTerminal.java
index 7e7c553..bd4b18a 100644
--- a/src/main/java/jline/UnixTerminal.java
+++ b/src/main/java/jline/UnixTerminal.java
@@ -1,421 +1,428 @@
/*
* Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
*
* This software is distributable under the BSD license. See the terms of the
* BSD license in the documentation provided with this software.
*/
package jline;
import java.io.*;
import java.util.*;
/**
* <p>
* Terminal that is used for unix platforms. Terminal initialization
* is handled by issuing the <em>stty</em> command against the
* <em>/dev/tty</em> file to disable character echoing and enable
* character input. All known unix systems (including
* Linux and Macintosh OS X) support the <em>stty</em>), so this
* implementation should work for an reasonable POSIX system.
* </p>
*
* @author <a href="mailto:[email protected]">Marc Prud'hommeaux</a>
* @author Updates <a href="mailto:[email protected]">Dale Kemp</a> 2005-12-03
*/
public class UnixTerminal extends Terminal {
public static final short ARROW_START = 27;
public static final short ARROW_PREFIX = 91;
public static final short ARROW_LEFT = 68;
public static final short ARROW_RIGHT = 67;
public static final short ARROW_UP = 65;
public static final short ARROW_DOWN = 66;
public static final short O_PREFIX = 79;
public static final short HOME_CODE = 72;
public static final short END_CODE = 70;
public static final short DEL_THIRD = 51;
public static final short DEL_SECOND = 126;
private Map terminfo;
private boolean echoEnabled;
private String ttyConfig;
private boolean backspaceDeleteSwitched = false;
private static String sttyCommand =
System.getProperty("jline.sttyCommand", "stty");
String encoding = System.getProperty("input.encoding", "UTF-8");
ReplayPrefixOneCharInputStream replayStream = new ReplayPrefixOneCharInputStream(encoding);
InputStreamReader replayReader;
public UnixTerminal() {
try {
replayReader = new InputStreamReader(replayStream, encoding);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected void checkBackspace(){
String[] ttyConfigSplit = ttyConfig.split(":|=");
if (ttyConfigSplit.length < 7)
return;
if (ttyConfigSplit[6] == null)
return;
backspaceDeleteSwitched = ttyConfigSplit[6].equals("7f");
}
/**
* Remove line-buffered input by invoking "stty -icanon min 1"
* against the current terminal.
*/
public void initializeTerminal() throws IOException, InterruptedException {
// save the initial tty configuration
ttyConfig = stty("-g");
// sanity check
if ((ttyConfig.length() == 0)
|| ((ttyConfig.indexOf("=") == -1)
&& (ttyConfig.indexOf(":") == -1))) {
throw new IOException("Unrecognized stty code: " + ttyConfig);
}
checkBackspace();
// set the console to be character-buffered instead of line-buffered
stty("-icanon min 1");
// disable character echoing
stty("-echo");
echoEnabled = false;
// at exit, restore the original tty configuration (for JDK 1.3+)
try {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void start() {
try {
restoreTerminal();
} catch (Exception e) {
consumeException(e);
}
}
});
} catch (AbstractMethodError ame) {
// JDK 1.3+ only method. Bummer.
consumeException(ame);
}
}
/**
* Restore the original terminal configuration, which can be used when
* shutting down the console reader. The ConsoleReader cannot be
* used after calling this method.
*/
public void restoreTerminal() throws Exception {
if (ttyConfig != null) {
stty(ttyConfig);
ttyConfig = null;
}
resetTerminal();
}
public int readVirtualKey(InputStream in) throws IOException {
int c = readCharacter(in);
if (backspaceDeleteSwitched)
if (c == DELETE)
c = '\b';
else if (c == '\b')
c = DELETE;
// in Unix terminals, arrow keys are represented by
// a sequence of 3 characters. E.g., the up arrow
// key yields 27, 91, 68
if (c == ARROW_START) {
- c = readCharacter(in);
+ //also the escape key is 27
+ //thats why we read until we
+ //have something different than 27
+ //this is a bugfix, because otherwise
+ //pressing escape and than an arrow key
+ //was an undefined state
+ while (c == ARROW_START)
+ c = readCharacter(in);
if (c == ARROW_PREFIX || c == O_PREFIX) {
c = readCharacter(in);
if (c == ARROW_UP) {
return CTRL_P;
} else if (c == ARROW_DOWN) {
return CTRL_N;
} else if (c == ARROW_LEFT) {
return CTRL_B;
} else if (c == ARROW_RIGHT) {
return CTRL_F;
} else if (c == HOME_CODE) {
return CTRL_A;
} else if (c == END_CODE) {
return CTRL_E;
} else if (c == DEL_THIRD) {
c = readCharacter(in); // read 4th
return DELETE;
}
}
}
// handle unicode characters, thanks for a patch from [email protected]
if (c > 128) {
// handle unicode characters longer than 2 bytes,
// thanks to [email protected]
replayStream.setInput(c, in);
// replayReader = new InputStreamReader(replayStream, encoding);
c = replayReader.read();
}
return c;
}
/**
* No-op for exceptions we want to silently consume.
*/
private void consumeException(Throwable e) {
}
public boolean isSupported() {
return true;
}
public boolean getEcho() {
return false;
}
/**
* Returns the value of "stty size" width param.
*
* <strong>Note</strong>: this method caches the value from the
* first time it is called in order to increase speed, which means
* that changing to size of the terminal will not be reflected
* in the console.
*/
public int getTerminalWidth() {
int val = -1;
try {
val = getTerminalProperty("columns");
} catch (Exception e) {
}
if (val == -1) {
val = 80;
}
return val;
}
/**
* Returns the value of "stty size" height param.
*
* <strong>Note</strong>: this method caches the value from the
* first time it is called in order to increase speed, which means
* that changing to size of the terminal will not be reflected
* in the console.
*/
public int getTerminalHeight() {
int val = -1;
try {
val = getTerminalProperty("rows");
} catch (Exception e) {
}
if (val == -1) {
val = 24;
}
return val;
}
private static int getTerminalProperty(String prop)
throws IOException, InterruptedException {
// need to be able handle both output formats:
// speed 9600 baud; 24 rows; 140 columns;
// and:
// speed 38400 baud; rows = 49; columns = 111; ypixels = 0; xpixels = 0;
String props = stty("-a");
for (StringTokenizer tok = new StringTokenizer(props, ";\n");
tok.hasMoreTokens();) {
String str = tok.nextToken().trim();
if (str.startsWith(prop)) {
int index = str.lastIndexOf(" ");
return Integer.parseInt(str.substring(index).trim());
} else if (str.endsWith(prop)) {
int index = str.indexOf(" ");
return Integer.parseInt(str.substring(0, index).trim());
}
}
return -1;
}
/**
* Execute the stty command with the specified arguments
* against the current active terminal.
*/
private static String stty(final String args)
throws IOException, InterruptedException {
return exec("stty " + args + " < /dev/tty").trim();
}
/**
* Execute the specified command and return the output
* (both stdout and stderr).
*/
private static String exec(final String cmd)
throws IOException, InterruptedException {
return exec(new String[] {
"sh",
"-c",
cmd
});
}
/**
* Execute the specified command and return the output
* (both stdout and stderr).
*/
private static String exec(final String[] cmd)
throws IOException, InterruptedException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
Process p = Runtime.getRuntime().exec(cmd);
int c;
InputStream in;
in = p.getInputStream();
while ((c = in.read()) != -1) {
bout.write(c);
}
in = p.getErrorStream();
while ((c = in.read()) != -1) {
bout.write(c);
}
p.waitFor();
String result = new String(bout.toByteArray());
return result;
}
/**
* The command to use to set the terminal options. Defaults
* to "stty", or the value of the system property "jline.sttyCommand".
*/
public static void setSttyCommand(String cmd) {
sttyCommand = cmd;
}
/**
* The command to use to set the terminal options. Defaults
* to "stty", or the value of the system property "jline.sttyCommand".
*/
public static String getSttyCommand() {
return sttyCommand;
}
public synchronized boolean isEchoEnabled() {
return echoEnabled;
}
public synchronized void enableEcho() {
try {
stty("echo");
echoEnabled = true;
} catch (Exception e) {
consumeException(e);
}
}
public synchronized void disableEcho() {
try {
stty("-echo");
echoEnabled = false;
} catch (Exception e) {
consumeException(e);
}
}
/**
* This is awkward and inefficient, but probably the minimal way to add
* UTF-8 support to JLine
*
* @author <a href="mailto:[email protected]">Marc Herbert</a>
*/
static class ReplayPrefixOneCharInputStream extends InputStream {
byte firstByte;
int byteLength;
InputStream wrappedStream;
int byteRead;
final String encoding;
public ReplayPrefixOneCharInputStream(String encoding) {
this.encoding = encoding;
}
public void setInput(int recorded, InputStream wrapped) throws IOException {
this.byteRead = 0;
this.firstByte = (byte) recorded;
this.wrappedStream = wrapped;
byteLength = 1;
if (encoding.equalsIgnoreCase("UTF-8"))
setInputUTF8(recorded, wrapped);
else if (encoding.equalsIgnoreCase("UTF-16"))
byteLength = 2;
else if (encoding.equalsIgnoreCase("UTF-32"))
byteLength = 4;
}
public void setInputUTF8(int recorded, InputStream wrapped) throws IOException {
// 110yyyyy 10zzzzzz
if ((firstByte & (byte) 0xE0) == (byte) 0xC0)
this.byteLength = 2;
// 1110xxxx 10yyyyyy 10zzzzzz
else if ((firstByte & (byte) 0xF0) == (byte) 0xE0)
this.byteLength = 3;
// 11110www 10xxxxxx 10yyyyyy 10zzzzzz
else if ((firstByte & (byte) 0xF8) == (byte) 0xF0)
this.byteLength = 4;
else
throw new IOException("invalid UTF-8 first byte: " + firstByte);
}
public int read() throws IOException {
if (available() == 0)
return -1;
byteRead++;
if (byteRead == 1)
return firstByte;
return wrappedStream.read();
}
/**
* InputStreamReader is greedy and will try to read bytes in advance. We
* do NOT want this to happen since we use a temporary/"losing bytes"
* InputStreamReader above, that's why we hide the real
* wrappedStream.available() here.
*/
public int available() {
return byteLength - byteRead;
}
}
}
| true | true | public int readVirtualKey(InputStream in) throws IOException {
int c = readCharacter(in);
if (backspaceDeleteSwitched)
if (c == DELETE)
c = '\b';
else if (c == '\b')
c = DELETE;
// in Unix terminals, arrow keys are represented by
// a sequence of 3 characters. E.g., the up arrow
// key yields 27, 91, 68
if (c == ARROW_START) {
c = readCharacter(in);
if (c == ARROW_PREFIX || c == O_PREFIX) {
c = readCharacter(in);
if (c == ARROW_UP) {
return CTRL_P;
} else if (c == ARROW_DOWN) {
return CTRL_N;
} else if (c == ARROW_LEFT) {
return CTRL_B;
} else if (c == ARROW_RIGHT) {
return CTRL_F;
} else if (c == HOME_CODE) {
return CTRL_A;
} else if (c == END_CODE) {
return CTRL_E;
} else if (c == DEL_THIRD) {
c = readCharacter(in); // read 4th
return DELETE;
}
}
}
// handle unicode characters, thanks for a patch from [email protected]
if (c > 128) {
// handle unicode characters longer than 2 bytes,
// thanks to [email protected]
replayStream.setInput(c, in);
// replayReader = new InputStreamReader(replayStream, encoding);
c = replayReader.read();
}
return c;
}
| public int readVirtualKey(InputStream in) throws IOException {
int c = readCharacter(in);
if (backspaceDeleteSwitched)
if (c == DELETE)
c = '\b';
else if (c == '\b')
c = DELETE;
// in Unix terminals, arrow keys are represented by
// a sequence of 3 characters. E.g., the up arrow
// key yields 27, 91, 68
if (c == ARROW_START) {
//also the escape key is 27
//thats why we read until we
//have something different than 27
//this is a bugfix, because otherwise
//pressing escape and than an arrow key
//was an undefined state
while (c == ARROW_START)
c = readCharacter(in);
if (c == ARROW_PREFIX || c == O_PREFIX) {
c = readCharacter(in);
if (c == ARROW_UP) {
return CTRL_P;
} else if (c == ARROW_DOWN) {
return CTRL_N;
} else if (c == ARROW_LEFT) {
return CTRL_B;
} else if (c == ARROW_RIGHT) {
return CTRL_F;
} else if (c == HOME_CODE) {
return CTRL_A;
} else if (c == END_CODE) {
return CTRL_E;
} else if (c == DEL_THIRD) {
c = readCharacter(in); // read 4th
return DELETE;
}
}
}
// handle unicode characters, thanks for a patch from [email protected]
if (c > 128) {
// handle unicode characters longer than 2 bytes,
// thanks to [email protected]
replayStream.setInput(c, in);
// replayReader = new InputStreamReader(replayStream, encoding);
c = replayReader.read();
}
return c;
}
|
diff --git a/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/EMAListener.java b/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/EMAListener.java
index b140c05..f2304e2 100644
--- a/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/EMAListener.java
+++ b/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/EMAListener.java
@@ -1,56 +1,56 @@
package com.runetooncraft.plugins.EasyMobArmory;
import net.minecraft.server.v1_6_R2.TileEntityChest;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_6_R2.inventory.CraftInventory;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.entity.Zombie;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.inventory.DoubleChestInventory;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import com.runetooncraft.plugins.EasyMobArmory.core.Config;
import com.runetooncraft.plugins.EasyMobArmory.core.InventorySerializer;
public class EMAListener implements Listener {
Config config;
public EMAListener(Config config) {
this.config = config;
}
@EventHandler
public void OnPlayerEntityInteract(PlayerInteractEntityEvent event) {
Entity e = event.getRightClicked();
Player p = event.getPlayer();
if(e.getType().equals(EntityType.ZOMBIE)) {
ItemStack i = p.getItemInHand();
Zombie z = (Zombie) e;
if(EMA.Helmets.contains(i)) {
z.getEquipment().setHelmet(i);
}else if(EMA.Chestplates.contains(i)) {
z.getEquipment().setChestplate(i);
}else if(EMA.Leggings.contains(i)) {
z.getEquipment().setLeggings(i);
}else if(EMA.Boots.contains(i)) {
z.getEquipment().setBoots(i);
}else if(i.getType().equals(Material.BONE)){
- Inventory inv = Bukkit.createInventory(p, 5, "zombieinv");
+ Inventory inv = Bukkit.createInventory(p, 9, "zombieinv");
ItemStack[] zombieinv = z.getEquipment().getArmorContents();
inv.setContents(zombieinv);
inv.addItem(z.getEquipment().getItemInHand());
p.openInventory(inv);
}else{
z.getEquipment().setItemInHand(i);
}
}
}
}
| true | true | public void OnPlayerEntityInteract(PlayerInteractEntityEvent event) {
Entity e = event.getRightClicked();
Player p = event.getPlayer();
if(e.getType().equals(EntityType.ZOMBIE)) {
ItemStack i = p.getItemInHand();
Zombie z = (Zombie) e;
if(EMA.Helmets.contains(i)) {
z.getEquipment().setHelmet(i);
}else if(EMA.Chestplates.contains(i)) {
z.getEquipment().setChestplate(i);
}else if(EMA.Leggings.contains(i)) {
z.getEquipment().setLeggings(i);
}else if(EMA.Boots.contains(i)) {
z.getEquipment().setBoots(i);
}else if(i.getType().equals(Material.BONE)){
Inventory inv = Bukkit.createInventory(p, 5, "zombieinv");
ItemStack[] zombieinv = z.getEquipment().getArmorContents();
inv.setContents(zombieinv);
inv.addItem(z.getEquipment().getItemInHand());
p.openInventory(inv);
}else{
z.getEquipment().setItemInHand(i);
}
}
}
| public void OnPlayerEntityInteract(PlayerInteractEntityEvent event) {
Entity e = event.getRightClicked();
Player p = event.getPlayer();
if(e.getType().equals(EntityType.ZOMBIE)) {
ItemStack i = p.getItemInHand();
Zombie z = (Zombie) e;
if(EMA.Helmets.contains(i)) {
z.getEquipment().setHelmet(i);
}else if(EMA.Chestplates.contains(i)) {
z.getEquipment().setChestplate(i);
}else if(EMA.Leggings.contains(i)) {
z.getEquipment().setLeggings(i);
}else if(EMA.Boots.contains(i)) {
z.getEquipment().setBoots(i);
}else if(i.getType().equals(Material.BONE)){
Inventory inv = Bukkit.createInventory(p, 9, "zombieinv");
ItemStack[] zombieinv = z.getEquipment().getArmorContents();
inv.setContents(zombieinv);
inv.addItem(z.getEquipment().getItemInHand());
p.openInventory(inv);
}else{
z.getEquipment().setItemInHand(i);
}
}
}
|
diff --git a/src/smartest/RelationalOperatorNode.java b/src/smartest/RelationalOperatorNode.java
index 888030c..31b5460 100644
--- a/src/smartest/RelationalOperatorNode.java
+++ b/src/smartest/RelationalOperatorNode.java
@@ -1,99 +1,99 @@
package smartest;
/*
* Implements Semantic checking and code output generation for
* EqualityOperands
*
* Example - a LT 3
* b LT 5
*/
/**
* The Class RelationalOperatorNode.
*@author Parth
*/
class RelationalOperatorNode extends ASTNode {
/** The operator. */
private String operator;
/*
* Instantiates EqualityOperator invoked by this grammar:
* equality_operand LT relational_operand
* equality_operand GT relational_operand
*
*
* @param op specifies the type of operator
* @param lcNode,rcNode represents nodes of operand
* @param yyline,yycolumn represents nodes line number and column number
*/
/**
* Instantiates a new relational operator node.
*
* @param op the op
* @param lcNode the lc node
* @param rcNode the rc node
* @param yyline the yyline
* @param yycolumn the yycolumn
*/
public RelationalOperatorNode(String op, ASTNode lcNode, ASTNode rcNode,
int yyline, int yycolumn) {
super(yyline, yycolumn);
this.addChild(lcNode);
this.addChild(rcNode);
this.operator = op;
}
/*
* symnatic check
*
*/
/* (non-Javadoc)
* @see ASTNode#checkSemantics()
*/
@Override
public void checkSemantics() throws Exception{
//symantic check for children
this.getChildAt(0).checkSemantics();
this.getChildAt(1).checkSemantics();
if(!((this.getChildAt(0).getType().equals("float") || this.getChildAt(0).getType().equals("int"))
&& (this.getChildAt(1).getType().equals("float") || this.getChildAt(1).getType().equals("int"))))
{
throw new Exception("Cannot do Relational operation on "+this.getChildAt(0).getType()+ " & " +
this.getChildAt(1).getType()+" on line "+ this.getYyline() + ":" +
this.getYycolumn());
}
this.setType("boolean");
return;
}
/* (non-Javadoc)
* @see ASTNode#generateCode()
*/
@Override
public StringBuffer generateCode() {
// TODO Auto-generated method stub
StringBuffer output = new StringBuffer();
output.append(this.getChildAt(0).generateCode());
if ("LT".equalsIgnoreCase(operator))
{
output.append(" < ");
}
else if ("LE".equalsIgnoreCase(operator))
{
output.append(" <= ");
}
else if ("GT".equalsIgnoreCase(operator))
{
output.append(" > ");
}
else if ("GE".equalsIgnoreCase(operator))
{
- output.append(" <= ");
+ output.append(" >= ");
}
output.append(this.getChildAt(1).generateCode());
return output;
}
}
| true | true | public StringBuffer generateCode() {
// TODO Auto-generated method stub
StringBuffer output = new StringBuffer();
output.append(this.getChildAt(0).generateCode());
if ("LT".equalsIgnoreCase(operator))
{
output.append(" < ");
}
else if ("LE".equalsIgnoreCase(operator))
{
output.append(" <= ");
}
else if ("GT".equalsIgnoreCase(operator))
{
output.append(" > ");
}
else if ("GE".equalsIgnoreCase(operator))
{
output.append(" <= ");
}
output.append(this.getChildAt(1).generateCode());
return output;
}
| public StringBuffer generateCode() {
// TODO Auto-generated method stub
StringBuffer output = new StringBuffer();
output.append(this.getChildAt(0).generateCode());
if ("LT".equalsIgnoreCase(operator))
{
output.append(" < ");
}
else if ("LE".equalsIgnoreCase(operator))
{
output.append(" <= ");
}
else if ("GT".equalsIgnoreCase(operator))
{
output.append(" > ");
}
else if ("GE".equalsIgnoreCase(operator))
{
output.append(" >= ");
}
output.append(this.getChildAt(1).generateCode());
return output;
}
|
diff --git a/tools/svn/src/java/org/apache/lenya/svn/SitetreeUpdater.java b/tools/svn/src/java/org/apache/lenya/svn/SitetreeUpdater.java
index f41a2dd8..2460f701 100755
--- a/tools/svn/src/java/org/apache/lenya/svn/SitetreeUpdater.java
+++ b/tools/svn/src/java/org/apache/lenya/svn/SitetreeUpdater.java
@@ -1,183 +1,183 @@
package org.apache.lenya.svn;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.ListIterator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.tmatesoft.svn.core.SVNErrorCode;
import org.tmatesoft.svn.core.SVNErrorMessage;
import org.tmatesoft.svn.core.SVNException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/** updates sitetree.xml nodes with local svn changes **/
public class SitetreeUpdater {
static Document document;
static boolean debug;
/** receive sitetree.xml location, path of new file, title of new file updateSitetree
* @throws SVNException */
public static void updateSitetree (String pathToSitetree, ArrayList newNodes, boolean debug_) throws SVNException
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
debug = debug_;
try {
File sitetree = new File(pathToSitetree);
if (!sitetree.exists()) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNKNOWN,
- "Could not find sitetree.xml, make sure your repositories point" +
- "to the authoring of a Lenya repository");
+ "Could not find sitetree.xml, make sure your repository " +
+ "(urlRep and localRep) point to the authoring/live dir of a Lenya repository");
throw new SVNException(err);
}
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(sitetree);
// sort by lowest depth first
Collections.sort(newNodes, new DepthComparator());
ListIterator it = newNodes.listIterator();
while (it.hasNext()) {
addNode((String)it.next());
}
writeSitetree(document, pathToSitetree);
} catch (SAXException sxe) {
// Error generated during parsing
Exception x = sxe;
if (sxe.getException() != null)
x = sxe.getException();
x.printStackTrace();
System.exit(1);
} catch (ParserConfigurationException pce) {
// Parser with specified options can't be built
pce.printStackTrace();
System.exit(1);
} catch (IOException ioe) {
// I/O error
ioe.printStackTrace();
System.exit(1);
}
}
static class DepthComparator implements Comparator {
public int compare(Object o1, Object o2) {
String s1 = (String) o1;
String s2 = (String) o2;
String [] depth1 = s1.split("/");
String [] depth2 = s2.split("/");
return (depth1.length - depth2.length);
}
}
/**
* @param newNode
*/
private static void addNode(String newNode) {
String [] nodePath = newNode.split("/");
String newNodeName = nodePath[nodePath.length - 2];
if (debug) {
System.err.println("\naddNode(), newNode: " + newNode);
System.err.println("newNodeName " + newNodeName);
System.err.println("nodepathlengti " + nodePath.length);
}
Element current = document.getDocumentElement(); //start with root
// iterate through all nodePath elements, mind the init and start values !
for (int i=1; i< nodePath.length -2; i++) {
if (debug) {
System.err.println("i " + i + ", nodePath " + nodePath[i]);
}
NodeList children = current.getElementsByTagName("node");
for (int j = 0; j < children.getLength(); j++){
// one child <node>
Element currentChild = (Element)children.item(j);
if (debug) {
System.err.println("j " + j + ", currentChild " + currentChild);
System.err.println("currentChildid " + currentChild.getAttributeNode("id").getValue());
}
// <node> id ?= path id
if (currentChild.getAttributeNode("id").getValue().equals(nodePath[i])){
// this is the child on the nodePath, use it for next iteration
current = currentChild;
}
}
}
// now we are at the parent of the new node to add, so add it.
createNode(current, newNodeName);
}
private static void createNode(Element parent, String newNodeName) {
if (debug) {
System.err.println("**** createNode ");
System.err.println("newNodeName " + newNodeName);
System.err.println("parent " + parent + ", id: " + parent.getAttributeNode("id").getValue() );
}
Element newNode = document.createElement("node");
newNode.setAttribute("id", newNodeName);
parent.appendChild(newNode);
Element newNodeLabel = document.createElement("label");
newNodeLabel.setAttribute("xml:lang", "en");
newNodeLabel.appendChild(document.createTextNode(newNodeName));
newNode.appendChild(newNodeLabel);
}
//This method writes a DOM document to a file
private static void writeSitetree(Document doc, String filename) {
try {
// Prepare the DOM document for writing
Source source = new DOMSource(doc);
// Prepare the output file
File file = new File(filename);
Result result = new StreamResult(file);
// Write the DOM document to the file
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, result);
} catch (TransformerConfigurationException e) {
System.err.println("Could not write to sitetree.xml");
System.exit(1);
} catch (TransformerException e) {
System.err.println("Could not write to sitetree.xml");
System.exit(1);
}
}
}
| true | true | public static void updateSitetree (String pathToSitetree, ArrayList newNodes, boolean debug_) throws SVNException
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
debug = debug_;
try {
File sitetree = new File(pathToSitetree);
if (!sitetree.exists()) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNKNOWN,
"Could not find sitetree.xml, make sure your repositories point" +
"to the authoring of a Lenya repository");
throw new SVNException(err);
}
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(sitetree);
// sort by lowest depth first
Collections.sort(newNodes, new DepthComparator());
ListIterator it = newNodes.listIterator();
while (it.hasNext()) {
addNode((String)it.next());
}
writeSitetree(document, pathToSitetree);
} catch (SAXException sxe) {
// Error generated during parsing
Exception x = sxe;
if (sxe.getException() != null)
x = sxe.getException();
x.printStackTrace();
System.exit(1);
} catch (ParserConfigurationException pce) {
// Parser with specified options can't be built
pce.printStackTrace();
System.exit(1);
} catch (IOException ioe) {
// I/O error
ioe.printStackTrace();
System.exit(1);
}
}
| public static void updateSitetree (String pathToSitetree, ArrayList newNodes, boolean debug_) throws SVNException
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
debug = debug_;
try {
File sitetree = new File(pathToSitetree);
if (!sitetree.exists()) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNKNOWN,
"Could not find sitetree.xml, make sure your repository " +
"(urlRep and localRep) point to the authoring/live dir of a Lenya repository");
throw new SVNException(err);
}
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(sitetree);
// sort by lowest depth first
Collections.sort(newNodes, new DepthComparator());
ListIterator it = newNodes.listIterator();
while (it.hasNext()) {
addNode((String)it.next());
}
writeSitetree(document, pathToSitetree);
} catch (SAXException sxe) {
// Error generated during parsing
Exception x = sxe;
if (sxe.getException() != null)
x = sxe.getException();
x.printStackTrace();
System.exit(1);
} catch (ParserConfigurationException pce) {
// Parser with specified options can't be built
pce.printStackTrace();
System.exit(1);
} catch (IOException ioe) {
// I/O error
ioe.printStackTrace();
System.exit(1);
}
}
|
diff --git a/car.ioMockup/src/car/io/application/ECApplication.java b/car.ioMockup/src/car/io/application/ECApplication.java
index 386a75ee..6406a574 100644
--- a/car.ioMockup/src/car/io/application/ECApplication.java
+++ b/car.ioMockup/src/car/io/application/ECApplication.java
@@ -1,788 +1,788 @@
package car.io.application;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Locale;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import android.app.Application;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ParseException;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
import car.io.adapter.DbAdapter;
import car.io.adapter.DbAdapterLocal;
import car.io.adapter.DbAdapterRemote;
import car.io.adapter.Measurement;
import car.io.adapter.Track;
import car.io.commands.CommonCommand;
import car.io.commands.MAF;
import car.io.commands.Speed;
import car.io.exception.FuelConsumptionException;
import car.io.exception.LocationInvalidException;
import car.io.exception.MeasurementsException;
import car.io.exception.TracksException;
import car.io.obd.BackgroundService;
import car.io.obd.Listener;
import car.io.obd.ServiceConnector;
public class ECApplication extends Application implements LocationListener {
public static final String BASE_URL = "https://giv-car.uni-muenster.de/stable/rest";
public static final String PREF_KEY_CAR_MODEL = "carmodel";
public static final String PREF_KEY_CAR_MANUFACTURER = "manufacturer";
public static final String PREF_KEY_CAR_CONSTRUCTION_YEAR = "constructionyear";
public static final String PREF_KEY_FUEL_TYPE = "fueltype";
public static final String PREF_KEY_SENSOR_ID = "sensorid";
private SharedPreferences preferences = null;
private DbAdapter dbAdapterLocal;
private DbAdapter dbAdapterRemote;
private final ScheduledExecutorService scheduleTaskExecutor = Executors
.newScheduledThreadPool(1);
// get the default Bluetooth adapter
private final BluetoothAdapter bluetoothAdapter = BluetoothAdapter
.getDefaultAdapter();
private ServiceConnector serviceConnector = null;
private Intent backgroundService = null;
private Handler handler = new Handler();
private Listener listener = null;
private LocationManager locationManager;
private float locationLatitude;
private float locationLongitude;
private int speedMeasurement = 0;
private double co2Measurement = 0.0;
private double mafMeasurement;
private Measurement measurement = null;
private long lastInsertTime = 0;
private Track track;
private boolean requirementsFulfilled = true;
private static User user;
public ServiceConnector getServiceConnector() {
return serviceConnector;
}
public boolean requirementsFulfilled() {
return requirementsFulfilled;
}
public void updateCurrentSensor(String sensorid, String carManufacturer, String carModel, String fuelType, int year){
Editor e = preferences.edit();
e.putString(PREF_KEY_SENSOR_ID, sensorid);
e.putString(PREF_KEY_CAR_MANUFACTURER, carManufacturer);
e.putString(PREF_KEY_CAR_MODEL, carModel);
e.putString(PREF_KEY_FUEL_TYPE, fuelType);
e.putString(PREF_KEY_CAR_CONSTRUCTION_YEAR,year+"");
e.commit();
}
@Override
public void onCreate() {
super.onCreate();
// TODO: Create something like a first-start method that determines the
// BT-Adapter, VIN etc. ... something like a setup method
initDbAdapter();
initBluetooth();
initLocationManager();
// AutoConnect checkbox and service
// TODO settings -> automatic connection to bt adapter
// startServiceConnector();
// Make a new listener to interpret the measurement values that are
// returned
Log.e("obd2", "init listener");
startListener();
// If everything is available, start the service connector and listener
startBackgroundService();
// createNewTrackIfNecessary();
try {
measurement = new Measurement(locationLatitude, locationLongitude);
} catch (LocationInvalidException e) {
e.printStackTrace();
}
preferences = PreferenceManager.getDefaultSharedPreferences(this);
user = getUserFromSharedPreferences();
}
/**
* This method determines whether it is necessary to create a new track or
* of the current/last used track should be reused
*/
// TODO call this method at some other positions in the code aswell... at
// some places, it might make sense to do so
private void createNewTrackIfNecessary() {
// TODO decode vin or read from shared preferences...
// setting undefined, will hopefully prevent correct uploading.
// but this shouldn't be possible to record tracks without these values
String fuelType = preferences
.getString(PREF_KEY_FUEL_TYPE, "undefined");
String carManufacturer = preferences.getString(
PREF_KEY_CAR_MANUFACTURER, "undefined");
String carModel = preferences
.getString(PREF_KEY_CAR_MODEL, "undefined");
String sensorId = preferences
.getString(PREF_KEY_SENSOR_ID, "undefined");
// if track is null, create a new one or take the last one from the
// database
if (track == null) {
Log.e("obd2", "The track was null");
Track lastUsedTrack;
try {
lastUsedTrack = dbAdapterLocal.getLastUsedTrack();
try {
// New track if last measurement is more than 60 minutes
// ago
if ((System.currentTimeMillis() - lastUsedTrack
- .getLastMeasurement().getMeasurementTime()) > 360000) {
+ .getLastMeasurement().getMeasurementTime()) > 3600000) {
// TODO: make parameters dynamic
Log.e("obd2",
"I create a new track because the last measurement is more than 60 mins ago");
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Trackname");
track.commitTrackToDatabase();
return;
}
// new track if last position is significantly different
// from the current position (more than 3 km)
if (getDistance(lastUsedTrack.getLastMeasurement(),
locationLatitude, locationLongitude) > 3.0) {
Log.e("obd2",
"The last measurement's position is more than 3 km away. I will create a new track");
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal); // TODO
track.setName("Trackname");
track.commitTrackToDatabase();
return;
}
// TODO: New track if user clicks on create new track button
// TODO: new track if VIN changed
else {
Log.e("obd2",
"The last measurement is less than 3 km away. I will append the measurement to this track");
track = lastUsedTrack;
return;
}
} catch (MeasurementsException e) {
Log.e("obd", "Track is empty, so I take the last track.");
track = lastUsedTrack;
e.printStackTrace();
}
} catch (TracksException e) {
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal); // TODO:
track.setName("Trackname");
track.commitTrackToDatabase();
e.printStackTrace();
Log.e("obd2",
"There was no track in the database so I created a new one");
}
return;
}
// if track is not null, determine whether it is useful to create a new
// track and store the current one //TODO: is it necessary to store
// this? normally, this is already in the database
if (track != null) {
Log.e("obd2", "the track was not null");
Track currentTrack = track;
try {
// New track if last measurement is more than 60 minutes
// ago
if ((System.currentTimeMillis() - currentTrack
- .getLastMeasurement().getMeasurementTime()) > 360000) {
+ .getLastMeasurement().getMeasurementTime()) > 3600000) {
// TODO: make parameters dynamic
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Trackname");
track.commitTrackToDatabase();
Log.e("obd2",
"I create a new track because the last measurement is more than 60 mins ago");
return;
}
// TODO: New track if user clicks on create new track button
// new track if last position is significantly different from
// the
// current position (more than 3 km)
if (getDistance(currentTrack.getLastMeasurement(),
locationLatitude, locationLongitude) > 3.0) {
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal); // TODO
track.setName("Trackname");
track.commitTrackToDatabase();
Log.e("obd2",
"The last measurement's position is more than 3 km away. I will create a new track");
return;
}
// TODO: new track if VIN changed
else {
Log.e("obd2",
"I will append to the last track because that still makes sense");
return;
}
} catch (MeasurementsException e) {
Log.e("obd2", "The track was empty so I will use this track");
e.printStackTrace();
}
}
}
/**
* Returns the distance between a measurement and a coordinate in kilometers
*
* @param m1
* Measurement
* @param lat2
* Latitude of coordinate
* @param lng2
* Longitude of coordinate
* @return
*/
public double getDistance(Measurement m1, double lat2, double lng2) {
double lat1 = m1.getLatitude();
double lng1 = m1.getLongitude();
double earthRadius = 6369;
double dLat = Math.toRadians(lat2 - lat1);
double dLng = Math.toRadians(lng2 - lng1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2)
* Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double dist = earthRadius * c;
return dist;
}
private void initDbAdapter() {
if (dbAdapterLocal == null) {
dbAdapterLocal = new DbAdapterLocal(this.getApplicationContext());
dbAdapterLocal.open();
} else {
if (!dbAdapterLocal.isOpen())
dbAdapterLocal.open();
}
if (dbAdapterRemote == null) {
dbAdapterRemote = new DbAdapterRemote(this.getApplicationContext());
dbAdapterRemote.open();
} else {
if (!dbAdapterRemote.isOpen())
dbAdapterRemote.open();
}
}
private void initBluetooth() {
if (bluetoothAdapter == null) {
requirementsFulfilled = false;
} else {
if (!bluetoothAdapter.isEnabled()) {
requirementsFulfilled = false;
}
}
}
/**
* Checks if a track with specific index is already present in the
* dbAdapterRemote
*
* @param index
* @return true if track already stored, false if track is new
*/
public boolean trackAlreadyInDB(String index) {
boolean matchFound = false;
ArrayList<Track> allStoredTracks = dbAdapterRemote.getAllTracks();
for (Track trackCompare : allStoredTracks) {
Log.i("obd2", "comparing: " + index + "");
Log.i("obd2", "to: " + trackCompare.getId() + "");
if (trackCompare.getId().equals(index)) {
Log.i("obd2", "match found");
matchFound = true;
return matchFound;
}
}
return matchFound;
}
private User getUserFromSharedPreferences() {
if (preferences.contains("username") && preferences.contains("token")) {
return new User(preferences.getString("username", "anonymous"),
preferences.getString("token", "anon"));
}
return null;
}
public void setUser(User user) {
ECApplication.user = user;
Editor e = preferences.edit();
e.putString("username", user.getUsername());
e.putString("token", user.getToken());
e.apply();
}
public User getUser() {
return user;
}
public boolean isLoggedIn() {
return user != null;
}
public void logOut() {
if (preferences.contains("username"))
preferences.edit().remove("username");
if (preferences.contains("token"))
preferences.edit().remove("token");
preferences.edit().apply();
user = null;
}
public DbAdapter getDbAdapterLocal() {
initDbAdapter();
return dbAdapterLocal;
}
public DbAdapter getDbAdapterRemote() {
initDbAdapter();
return dbAdapterRemote;
}
/**
* Starts the location manager again after an resume.
*/
public void startLocationManager() {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
}
/**
* Stops the location manager (removeUpdates) for pause.
*/
public void stopLocating() {
locationManager.removeUpdates(this);
}
public void startBackgroundService() {
if (requirementsFulfilled) {
Log.e("obd2", "requirements met");
backgroundService = new Intent(this, BackgroundService.class);
serviceConnector = new ServiceConnector();
serviceConnector.setServiceListener(listener);
bindService(backgroundService, serviceConnector,
Context.BIND_AUTO_CREATE);
} else {
Log.e("obd2", "requirements not met");
}
}
public void startServiceConnector() {
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
if (requirementsFulfilled) {
if (!serviceConnector.isRunning()) {
startConnection();
} else {
Log.e("obd2", "serviceConnector not running");
}
} else {
Log.e("obd2", "requirementsFulfilled was false!");
}
}
}, 0, 1, TimeUnit.MINUTES);
}
public void startListener() {
listener = new Listener() {
public void receiveUpdate(CommonCommand job) {
Log.e("obd2", "update received");
// Get the name and the result of the Command
String commandName = job.getCommandName();
String commandResult = job.getResult();
Log.i("btlogger", commandName + " " + commandResult);
if (commandResult.equals("NODATA"))
return;
// Get the fuel type from the preferences
// TextView fuelTypeTextView = (TextView)
// findViewById(R.id.fueltypeText);
// fuelTypeTextView.setText(preferences.getString(PREF_FUEL_TPYE,
// "Gasoline"));
/*
* Check which measurent is returned and save the value in the
* previously created measurement
*/
// Speed
if (commandName.equals("Vehicle Speed")) {
// TextView speedTextView = (TextView)
// findViewById(R.id.spd_text);
// speedTextView.setText(commandResult + " km/h");
try {
speedMeasurement = Integer.valueOf(commandResult);
} catch (NumberFormatException e) {
Log.e("obd2", "speed parse exception");
e.printStackTrace();
}
}
// MAF
if (commandName.equals("Mass Air Flow")) {
// TextView mafTextView = (TextView)
// findViewById(R.id.mafText);
String maf = commandResult;
// mafTextView.setText("MAF: " + maf + " g/s");
try {
NumberFormat format = NumberFormat
.getInstance(Locale.GERMAN);
Number number;
number = format.parse(maf);
mafMeasurement = number.doubleValue();
// Dashboard Co2 current value preparation
double consumption = 0.0;
if (mafMeasurement != -1.0) {
if (preferences.getString(PREF_KEY_FUEL_TYPE,
"gasoline").equals("gasoline")) {
consumption = (mafMeasurement / 14.7) / 747;
} else if (preferences.getString(
PREF_KEY_FUEL_TYPE, "gasoline").equals(
"diesel")) {
consumption = (mafMeasurement / 14.5) / 832;
}
}
if (preferences.getString(PREF_KEY_FUEL_TYPE,
"gasoline").equals("gasoline")) {
co2Measurement = consumption * 2.35;
} else if (preferences.getString(PREF_KEY_FUEL_TYPE,
"gasoline").equals("diesel")) {
co2Measurement = consumption * 2.65;
}
} catch (ParseException e) {
Log.e("obd", "parse exception maf");
e.printStackTrace();
} catch (java.text.ParseException e) {
Log.e("obd", "parse exception maf");
e.printStackTrace();
}
}
// Update and insert the measurement
updateMeasurement();
}
};
}
public void stopServiceConnector() {
scheduleTaskExecutor.shutdown();
}
/**
* Connects to the Bluetooth Adapter and starts the execution of the
* commands
*/
public void startConnection() {
openDb();
startLocationManager();
createNewTrackIfNecessary();
if (!serviceConnector.isRunning()) {
Log.e("obd2", "service start");
startService(backgroundService);
bindService(backgroundService, serviceConnector,
Context.BIND_AUTO_CREATE);
}
handler.post(waitingListRunnable);
}
/**
* Ends the connection with the Bluetooth Adapter
*/
public void stopConnection() {
closeDb();
stopLocating();
if (serviceConnector.isRunning()) {
stopService(backgroundService);
unbindService(serviceConnector);
}
handler.removeCallbacks(waitingListRunnable);
}
/**
* Handles the waiting-list
*/
private Runnable waitingListRunnable = new Runnable() {
public void run() {
if (serviceConnector.isRunning())
addCommandstoWaitinglist();
handler.postDelayed(waitingListRunnable, 2000);
}
};
/**
* Helper method that adds the desired commands to the waiting list where
* all commands are executed
*/
private void addCommandstoWaitinglist() {
final CommonCommand speed = new Speed();
final CommonCommand maf = new MAF();
serviceConnector.addJobToWaitingList(speed);
serviceConnector.addJobToWaitingList(maf);
}
/**
* Helper Command that updates the current measurement with the last
* measurement data and inserts it into the database if the measurements is
* young enough
*/
public void updateMeasurement() {
// Create track new measurement if necessary
if (measurement == null) {
try {
measurement = new Measurement(locationLatitude,
locationLongitude);
} catch (LocationInvalidException e) {
e.printStackTrace();
}
}
// Insert the values if the measurement (with the coordinates) is young
// enough (5000ms) or create track new one if it is too old
if (measurement != null) {
if (Math.abs(measurement.getMeasurementTime()
- System.currentTimeMillis()) < 5000) {
measurement.setSpeed(speedMeasurement);
measurement.setMaf(mafMeasurement);
Log.e("obd2", "new measurement");
Log.e("obd2",
measurement.getLatitude() + " "
+ measurement.getLongitude());
Log.e("obd2", measurement.toString());
insertMeasurement(measurement);
} else {
try {
measurement = new Measurement(locationLatitude,
locationLongitude);
} catch (LocationInvalidException e) {
e.printStackTrace();
}
}
}
}
/**
* Helper method to insert track measurement into the database (ensures that
* track measurement is only stored every 5 seconds and not faster...)
*
* @param measurement2
* The measurement you want to insert
*/
private void insertMeasurement(Measurement measurement2) {
// TODO: This has to be added with the following conditions:
/*
* 1)New measurement if more than 50 meters away 2)New measurement if
* last measurement more than 1 minute ago 3)New measurement if MAF
* value changed significantly (whatever this means... we will have to
* investigate on that. also it is not clear whether we should use this
* condition because we are vulnerable to noise from the sensor.
* therefore, we should include a minimum time between measurements (1
* sec) as well.)
*/
if (Math.abs(lastInsertTime - measurement2.getMeasurementTime()) > 5000) {
lastInsertTime = measurement2.getMeasurementTime();
track.addMeasurement(measurement2);
Log.i("obd2", measurement2.toString());
Toast.makeText(getApplicationContext(), measurement2.toString(),
Toast.LENGTH_SHORT).show();
}
}
/**
* Init the location Manager
*/
private void initLocationManager() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
// 0,
// 0, this);
}
public void destroyStuff() {
stopLocating();
locationManager = null;
backgroundService = null;
serviceConnector = null;
listener = null;
handler = null;
}
@Override
public void onLocationChanged(Location location) {
locationLatitude = (float) location.getLatitude();
locationLongitude = (float) location.getLongitude();
// speedMeasurement = (int) (location.getSpeed() * 3.6);
}
@Override
public void onProviderDisabled(String arg0) {
}
@Override
public void onProviderEnabled(String arg0) {
}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
public void openDb() {
initDbAdapter();
}
public void closeDb() {
if (dbAdapterLocal != null) {
dbAdapterLocal.close();
dbAdapterLocal = null;
}
if (dbAdapterRemote != null) {
dbAdapterRemote.close();
dbAdapterRemote = null;
}
}
/**
* @return the speedMeasurement
*/
public int getSpeedMeasurement() {
return speedMeasurement;
}
/**
* @return the track
*/
public Track getTrack() {
return track;
}
/**
* @param track
* the track to set
*/
public void setTrack(Track track) {
this.track = track;
}
/**
*
* @return the current co2 value
*/
public double getCo2Measurement() {
return co2Measurement;
}
}
| false | true | private void createNewTrackIfNecessary() {
// TODO decode vin or read from shared preferences...
// setting undefined, will hopefully prevent correct uploading.
// but this shouldn't be possible to record tracks without these values
String fuelType = preferences
.getString(PREF_KEY_FUEL_TYPE, "undefined");
String carManufacturer = preferences.getString(
PREF_KEY_CAR_MANUFACTURER, "undefined");
String carModel = preferences
.getString(PREF_KEY_CAR_MODEL, "undefined");
String sensorId = preferences
.getString(PREF_KEY_SENSOR_ID, "undefined");
// if track is null, create a new one or take the last one from the
// database
if (track == null) {
Log.e("obd2", "The track was null");
Track lastUsedTrack;
try {
lastUsedTrack = dbAdapterLocal.getLastUsedTrack();
try {
// New track if last measurement is more than 60 minutes
// ago
if ((System.currentTimeMillis() - lastUsedTrack
.getLastMeasurement().getMeasurementTime()) > 360000) {
// TODO: make parameters dynamic
Log.e("obd2",
"I create a new track because the last measurement is more than 60 mins ago");
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Trackname");
track.commitTrackToDatabase();
return;
}
// new track if last position is significantly different
// from the current position (more than 3 km)
if (getDistance(lastUsedTrack.getLastMeasurement(),
locationLatitude, locationLongitude) > 3.0) {
Log.e("obd2",
"The last measurement's position is more than 3 km away. I will create a new track");
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal); // TODO
track.setName("Trackname");
track.commitTrackToDatabase();
return;
}
// TODO: New track if user clicks on create new track button
// TODO: new track if VIN changed
else {
Log.e("obd2",
"The last measurement is less than 3 km away. I will append the measurement to this track");
track = lastUsedTrack;
return;
}
} catch (MeasurementsException e) {
Log.e("obd", "Track is empty, so I take the last track.");
track = lastUsedTrack;
e.printStackTrace();
}
} catch (TracksException e) {
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal); // TODO:
track.setName("Trackname");
track.commitTrackToDatabase();
e.printStackTrace();
Log.e("obd2",
"There was no track in the database so I created a new one");
}
return;
}
// if track is not null, determine whether it is useful to create a new
// track and store the current one //TODO: is it necessary to store
// this? normally, this is already in the database
if (track != null) {
Log.e("obd2", "the track was not null");
Track currentTrack = track;
try {
// New track if last measurement is more than 60 minutes
// ago
if ((System.currentTimeMillis() - currentTrack
.getLastMeasurement().getMeasurementTime()) > 360000) {
// TODO: make parameters dynamic
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Trackname");
track.commitTrackToDatabase();
Log.e("obd2",
"I create a new track because the last measurement is more than 60 mins ago");
return;
}
// TODO: New track if user clicks on create new track button
// new track if last position is significantly different from
// the
// current position (more than 3 km)
if (getDistance(currentTrack.getLastMeasurement(),
locationLatitude, locationLongitude) > 3.0) {
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal); // TODO
track.setName("Trackname");
track.commitTrackToDatabase();
Log.e("obd2",
"The last measurement's position is more than 3 km away. I will create a new track");
return;
}
// TODO: new track if VIN changed
else {
Log.e("obd2",
"I will append to the last track because that still makes sense");
return;
}
} catch (MeasurementsException e) {
Log.e("obd2", "The track was empty so I will use this track");
e.printStackTrace();
}
}
}
| private void createNewTrackIfNecessary() {
// TODO decode vin or read from shared preferences...
// setting undefined, will hopefully prevent correct uploading.
// but this shouldn't be possible to record tracks without these values
String fuelType = preferences
.getString(PREF_KEY_FUEL_TYPE, "undefined");
String carManufacturer = preferences.getString(
PREF_KEY_CAR_MANUFACTURER, "undefined");
String carModel = preferences
.getString(PREF_KEY_CAR_MODEL, "undefined");
String sensorId = preferences
.getString(PREF_KEY_SENSOR_ID, "undefined");
// if track is null, create a new one or take the last one from the
// database
if (track == null) {
Log.e("obd2", "The track was null");
Track lastUsedTrack;
try {
lastUsedTrack = dbAdapterLocal.getLastUsedTrack();
try {
// New track if last measurement is more than 60 minutes
// ago
if ((System.currentTimeMillis() - lastUsedTrack
.getLastMeasurement().getMeasurementTime()) > 3600000) {
// TODO: make parameters dynamic
Log.e("obd2",
"I create a new track because the last measurement is more than 60 mins ago");
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Trackname");
track.commitTrackToDatabase();
return;
}
// new track if last position is significantly different
// from the current position (more than 3 km)
if (getDistance(lastUsedTrack.getLastMeasurement(),
locationLatitude, locationLongitude) > 3.0) {
Log.e("obd2",
"The last measurement's position is more than 3 km away. I will create a new track");
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal); // TODO
track.setName("Trackname");
track.commitTrackToDatabase();
return;
}
// TODO: New track if user clicks on create new track button
// TODO: new track if VIN changed
else {
Log.e("obd2",
"The last measurement is less than 3 km away. I will append the measurement to this track");
track = lastUsedTrack;
return;
}
} catch (MeasurementsException e) {
Log.e("obd", "Track is empty, so I take the last track.");
track = lastUsedTrack;
e.printStackTrace();
}
} catch (TracksException e) {
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal); // TODO:
track.setName("Trackname");
track.commitTrackToDatabase();
e.printStackTrace();
Log.e("obd2",
"There was no track in the database so I created a new one");
}
return;
}
// if track is not null, determine whether it is useful to create a new
// track and store the current one //TODO: is it necessary to store
// this? normally, this is already in the database
if (track != null) {
Log.e("obd2", "the track was not null");
Track currentTrack = track;
try {
// New track if last measurement is more than 60 minutes
// ago
if ((System.currentTimeMillis() - currentTrack
.getLastMeasurement().getMeasurementTime()) > 3600000) {
// TODO: make parameters dynamic
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Trackname");
track.commitTrackToDatabase();
Log.e("obd2",
"I create a new track because the last measurement is more than 60 mins ago");
return;
}
// TODO: New track if user clicks on create new track button
// new track if last position is significantly different from
// the
// current position (more than 3 km)
if (getDistance(currentTrack.getLastMeasurement(),
locationLatitude, locationLongitude) > 3.0) {
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal); // TODO
track.setName("Trackname");
track.commitTrackToDatabase();
Log.e("obd2",
"The last measurement's position is more than 3 km away. I will create a new track");
return;
}
// TODO: new track if VIN changed
else {
Log.e("obd2",
"I will append to the last track because that still makes sense");
return;
}
} catch (MeasurementsException e) {
Log.e("obd2", "The track was empty so I will use this track");
e.printStackTrace();
}
}
}
|
diff --git a/src/test/java/com/google/code/nanorm/test/common/MapperTestBase.java b/src/test/java/com/google/code/nanorm/test/common/MapperTestBase.java
index f013078..ff8c5ab 100644
--- a/src/test/java/com/google/code/nanorm/test/common/MapperTestBase.java
+++ b/src/test/java/com/google/code/nanorm/test/common/MapperTestBase.java
@@ -1,158 +1,158 @@
/**
* Copyright (C) 2008 Ivan S. Dubrov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.code.nanorm.test.common;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.TimeZone;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import com.google.code.nanorm.NanormFactory;
import com.google.code.nanorm.Session;
import com.google.code.nanorm.config.NanormConfiguration;
/**
*
* @author Ivan Dubrov
* @version 1.0 29.05.2008
*/
public class MapperTestBase {
/**
* Connection.
*/
protected static Connection conn;
/**
* Nanorm factory.
*/
protected static NanormFactory factory;
/**
* Current transaction.
*/
protected static Session transaction;
/**
* Loads the test data.
*
* @throws Exception any error
*/
@BeforeClass
public static void beforeClass() throws Exception {
- TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
+ TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Class.forName("org.h2.Driver");
conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
// Tables for primitive values
execute("CREATE TABLE CORE(id INTEGER, primByte TINYINT, wrapByte TINYINT, "
+ "primShort SMALLINT, wrapShort SMALLINT, primInt INT, wrapInt INT,"
+ "primLong BIGINT, wrapLong BIGINT, primBoolean BOOL, wrapBoolean BOOL,"
+ "primChar CHAR(1), wrapChar CHAR(1), primFloat REAL, wrapFloat REAL,"
+ "primDouble DOUBLE, wrapDouble DOUBLE, string VARCHAR(50), "
+ "date TIMESTAMP, sqldate DATE, sqltime TIME, sqltimestamp TIMESTAMP,"
+ "bytearr BLOB, locale VARCHAR(10))");
execute("INSERT INTO CORE(id, primByte, wrapByte, primShort, wrapShort, "
+ "primInt, wrapInt, primLong, wrapLong, primBoolean, wrapBoolean, "
+ "primChar, wrapChar, primFloat, wrapFloat, primDouble, wrapDouble, string, "
+ "date, sqldate, sqltime, sqltimestamp, bytearr, locale) VALUES("
+ "1, 37, -23, 8723, -6532, "
+ "824756237, -123809163, 282347987987234987, -23429879871239879, TRUE, FALSE,"
+ "'a', 'H', 34.5, -25.25, "
+ "44.5, -47.125, 'Hello, H2!', "
+ "'2009-06-07 15:23:34', '2006-12-11', '16:32:01', '2008-07-08 18:08:11',"
+ "'1A5C6F', 'ru_RU')");
// Create some categories
execute("CREATE TABLE CATEGORIES(id INTEGER, title VARCHAR(50), year INTEGER)");
execute("INSERT INTO CATEGORIES(id, title, year) VALUES (1, 'World', 2006)");
execute("INSERT INTO CATEGORIES(id, title, year) VALUES (2, 'Science', 2004)");
// Create some articles
execute("CREATE TABLE ARTICLES(id INTEGER, category_id INTEGER, subject VARCHAR(50), body VARCHAR(200), year INTEGER)");
execute("INSERT INTO ARTICLES(id, category_id, subject, body, year) VALUES (1, 1, 'World Domination', 'Everybody thinks of world domination.', 2007)");
execute("INSERT INTO ARTICLES(id, category_id, subject, body, year) VALUES (2, 1, 'Saving the Earth', 'To save the earth you need...', 2008)");
// Create some publications
execute("CREATE TABLE PUBLICATIONS(id INTEGER, article_id INTEGER, title VARCHAR(50), year INTEGER)");
execute("INSERT INTO PUBLICATIONS(id, article_id, title, year) VALUES (543, 1, 'Best Way to World Dominate!', 2008)");
// Create some labels
execute("CREATE TABLE LABELS(id INTEGER, article_id INTEGER, label VARCHAR(50))");
execute("INSERT INTO LABELS(id, article_id, label) VALUES (1231, 1, 'World')");
execute("INSERT INTO LABELS(id, article_id, label) VALUES (1232, 1, 'Dominate')");
// Create some comments
execute("CREATE TABLE COMMENTS(id INTEGER, article_id INTEGER, comment VARCHAR(200), year INTEGER)");
execute("INSERT INTO COMMENTS(id, article_id, comment, year) VALUES (101, 1, 'Great!', 2006)");
execute("INSERT INTO COMMENTS(id, article_id, comment, year) VALUES (102, 1, 'Always wanted to world-dominate!', 2007)");
// Sequence for ids
execute("CREATE SEQUENCE ids START WITH 123 INCREMENT BY 1");
// Some functions to invoke
execute("CREATE ALIAS myConcat FOR \"com.google.code.nanorm.test.common.Funcs.concat\"");
execute("CREATE ALIAS myConcat2 FOR \"com.google.code.nanorm.test.common.Funcs.concat2\"");
conn.commit();
factory = new NanormConfiguration().buildFactory();
transaction = factory.openSession(conn);
}
/**
* Execute the statement.
*
* @param sql sql statement to execute
* @throws SQLException any SQL error
*/
protected static void execute(String sql) throws SQLException {
Statement st = conn.createStatement();
try {
st.execute(sql);
} finally {
st.close();
}
}
/**
* Rollback the transaction and close the connection.
*
* @throws SQLException any SQL exception
*/
@AfterClass
public static void afterClass() throws SQLException {
if (transaction != null) {
transaction.rollback();
transaction.end();
}
if (conn != null) {
conn.close();
}
}
}
| true | true | public static void beforeClass() throws Exception {
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
Class.forName("org.h2.Driver");
conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
// Tables for primitive values
execute("CREATE TABLE CORE(id INTEGER, primByte TINYINT, wrapByte TINYINT, "
+ "primShort SMALLINT, wrapShort SMALLINT, primInt INT, wrapInt INT,"
+ "primLong BIGINT, wrapLong BIGINT, primBoolean BOOL, wrapBoolean BOOL,"
+ "primChar CHAR(1), wrapChar CHAR(1), primFloat REAL, wrapFloat REAL,"
+ "primDouble DOUBLE, wrapDouble DOUBLE, string VARCHAR(50), "
+ "date TIMESTAMP, sqldate DATE, sqltime TIME, sqltimestamp TIMESTAMP,"
+ "bytearr BLOB, locale VARCHAR(10))");
execute("INSERT INTO CORE(id, primByte, wrapByte, primShort, wrapShort, "
+ "primInt, wrapInt, primLong, wrapLong, primBoolean, wrapBoolean, "
+ "primChar, wrapChar, primFloat, wrapFloat, primDouble, wrapDouble, string, "
+ "date, sqldate, sqltime, sqltimestamp, bytearr, locale) VALUES("
+ "1, 37, -23, 8723, -6532, "
+ "824756237, -123809163, 282347987987234987, -23429879871239879, TRUE, FALSE,"
+ "'a', 'H', 34.5, -25.25, "
+ "44.5, -47.125, 'Hello, H2!', "
+ "'2009-06-07 15:23:34', '2006-12-11', '16:32:01', '2008-07-08 18:08:11',"
+ "'1A5C6F', 'ru_RU')");
// Create some categories
execute("CREATE TABLE CATEGORIES(id INTEGER, title VARCHAR(50), year INTEGER)");
execute("INSERT INTO CATEGORIES(id, title, year) VALUES (1, 'World', 2006)");
execute("INSERT INTO CATEGORIES(id, title, year) VALUES (2, 'Science', 2004)");
// Create some articles
execute("CREATE TABLE ARTICLES(id INTEGER, category_id INTEGER, subject VARCHAR(50), body VARCHAR(200), year INTEGER)");
execute("INSERT INTO ARTICLES(id, category_id, subject, body, year) VALUES (1, 1, 'World Domination', 'Everybody thinks of world domination.', 2007)");
execute("INSERT INTO ARTICLES(id, category_id, subject, body, year) VALUES (2, 1, 'Saving the Earth', 'To save the earth you need...', 2008)");
// Create some publications
execute("CREATE TABLE PUBLICATIONS(id INTEGER, article_id INTEGER, title VARCHAR(50), year INTEGER)");
execute("INSERT INTO PUBLICATIONS(id, article_id, title, year) VALUES (543, 1, 'Best Way to World Dominate!', 2008)");
// Create some labels
execute("CREATE TABLE LABELS(id INTEGER, article_id INTEGER, label VARCHAR(50))");
execute("INSERT INTO LABELS(id, article_id, label) VALUES (1231, 1, 'World')");
execute("INSERT INTO LABELS(id, article_id, label) VALUES (1232, 1, 'Dominate')");
// Create some comments
execute("CREATE TABLE COMMENTS(id INTEGER, article_id INTEGER, comment VARCHAR(200), year INTEGER)");
execute("INSERT INTO COMMENTS(id, article_id, comment, year) VALUES (101, 1, 'Great!', 2006)");
execute("INSERT INTO COMMENTS(id, article_id, comment, year) VALUES (102, 1, 'Always wanted to world-dominate!', 2007)");
// Sequence for ids
execute("CREATE SEQUENCE ids START WITH 123 INCREMENT BY 1");
// Some functions to invoke
execute("CREATE ALIAS myConcat FOR \"com.google.code.nanorm.test.common.Funcs.concat\"");
execute("CREATE ALIAS myConcat2 FOR \"com.google.code.nanorm.test.common.Funcs.concat2\"");
conn.commit();
factory = new NanormConfiguration().buildFactory();
transaction = factory.openSession(conn);
}
| public static void beforeClass() throws Exception {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Class.forName("org.h2.Driver");
conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
// Tables for primitive values
execute("CREATE TABLE CORE(id INTEGER, primByte TINYINT, wrapByte TINYINT, "
+ "primShort SMALLINT, wrapShort SMALLINT, primInt INT, wrapInt INT,"
+ "primLong BIGINT, wrapLong BIGINT, primBoolean BOOL, wrapBoolean BOOL,"
+ "primChar CHAR(1), wrapChar CHAR(1), primFloat REAL, wrapFloat REAL,"
+ "primDouble DOUBLE, wrapDouble DOUBLE, string VARCHAR(50), "
+ "date TIMESTAMP, sqldate DATE, sqltime TIME, sqltimestamp TIMESTAMP,"
+ "bytearr BLOB, locale VARCHAR(10))");
execute("INSERT INTO CORE(id, primByte, wrapByte, primShort, wrapShort, "
+ "primInt, wrapInt, primLong, wrapLong, primBoolean, wrapBoolean, "
+ "primChar, wrapChar, primFloat, wrapFloat, primDouble, wrapDouble, string, "
+ "date, sqldate, sqltime, sqltimestamp, bytearr, locale) VALUES("
+ "1, 37, -23, 8723, -6532, "
+ "824756237, -123809163, 282347987987234987, -23429879871239879, TRUE, FALSE,"
+ "'a', 'H', 34.5, -25.25, "
+ "44.5, -47.125, 'Hello, H2!', "
+ "'2009-06-07 15:23:34', '2006-12-11', '16:32:01', '2008-07-08 18:08:11',"
+ "'1A5C6F', 'ru_RU')");
// Create some categories
execute("CREATE TABLE CATEGORIES(id INTEGER, title VARCHAR(50), year INTEGER)");
execute("INSERT INTO CATEGORIES(id, title, year) VALUES (1, 'World', 2006)");
execute("INSERT INTO CATEGORIES(id, title, year) VALUES (2, 'Science', 2004)");
// Create some articles
execute("CREATE TABLE ARTICLES(id INTEGER, category_id INTEGER, subject VARCHAR(50), body VARCHAR(200), year INTEGER)");
execute("INSERT INTO ARTICLES(id, category_id, subject, body, year) VALUES (1, 1, 'World Domination', 'Everybody thinks of world domination.', 2007)");
execute("INSERT INTO ARTICLES(id, category_id, subject, body, year) VALUES (2, 1, 'Saving the Earth', 'To save the earth you need...', 2008)");
// Create some publications
execute("CREATE TABLE PUBLICATIONS(id INTEGER, article_id INTEGER, title VARCHAR(50), year INTEGER)");
execute("INSERT INTO PUBLICATIONS(id, article_id, title, year) VALUES (543, 1, 'Best Way to World Dominate!', 2008)");
// Create some labels
execute("CREATE TABLE LABELS(id INTEGER, article_id INTEGER, label VARCHAR(50))");
execute("INSERT INTO LABELS(id, article_id, label) VALUES (1231, 1, 'World')");
execute("INSERT INTO LABELS(id, article_id, label) VALUES (1232, 1, 'Dominate')");
// Create some comments
execute("CREATE TABLE COMMENTS(id INTEGER, article_id INTEGER, comment VARCHAR(200), year INTEGER)");
execute("INSERT INTO COMMENTS(id, article_id, comment, year) VALUES (101, 1, 'Great!', 2006)");
execute("INSERT INTO COMMENTS(id, article_id, comment, year) VALUES (102, 1, 'Always wanted to world-dominate!', 2007)");
// Sequence for ids
execute("CREATE SEQUENCE ids START WITH 123 INCREMENT BY 1");
// Some functions to invoke
execute("CREATE ALIAS myConcat FOR \"com.google.code.nanorm.test.common.Funcs.concat\"");
execute("CREATE ALIAS myConcat2 FOR \"com.google.code.nanorm.test.common.Funcs.concat2\"");
conn.commit();
factory = new NanormConfiguration().buildFactory();
transaction = factory.openSession(conn);
}
|
diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebappRegistrationHelper.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebappRegistrationHelper.java
index 32507b49..b3b04f7a 100644
--- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebappRegistrationHelper.java
+++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebappRegistrationHelper.java
@@ -1,1005 +1,1005 @@
// ========================================================================
// Copyright (c) 2009 Intalio, Inc.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// Contributors:
// Hugues Malphettes - initial API and implementation
// ========================================================================
package org.eclipse.jetty.osgi.boot.internal.webapp;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import org.eclipse.jetty.deploy.AppProvider;
import org.eclipse.jetty.deploy.ContextDeployer;
import org.eclipse.jetty.deploy.DeploymentManager;
import org.eclipse.jetty.deploy.WebAppDeployer;
import org.eclipse.jetty.osgi.boot.JettyBootstrapActivator;
import org.eclipse.jetty.osgi.boot.OSGiAppProvider;
import org.eclipse.jetty.osgi.boot.OSGiWebappConstants;
import org.eclipse.jetty.osgi.boot.internal.jsp.TldLocatableURLClassloader;
import org.eclipse.jetty.osgi.boot.utils.BundleClassLoaderHelper;
import org.eclipse.jetty.osgi.boot.utils.BundleFileLocatorHelper;
import org.eclipse.jetty.osgi.boot.utils.WebappRegistrationCustomizer;
import org.eclipse.jetty.osgi.boot.utils.internal.DefaultBundleClassLoaderHelper;
import org.eclipse.jetty.osgi.boot.utils.internal.DefaultFileLocatorHelper;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.handler.RequestLogHandler;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.xml.XmlConfiguration;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/**
* Bridges the jetty deployers with the OSGi lifecycle where applications are
* managed inside OSGi-bundles.
* <p>
* This class should be called as a consequence of the activation of a new
* service that is a ContextHandler.<br/>
* This way the new webapps are exposed as OSGi services.
* </p>
* <p>
* Helper methods to register a bundle that is a web-application or a context.
* </p>
* Limitations:
* <ul>
* <li>support for jarred webapps is somewhat limited.</li>
* </ul>
*/
public class WebappRegistrationHelper
{
private static Logger __logger = Log.getLogger(WebappRegistrationHelper.class.getName());
private static boolean INITIALIZED = false;
/**
* By default set to: {@link DefaultBundleClassLoaderHelper}. It supports
* equinox and apache-felix fragment bundles that are specific to an OSGi
* implementation should set a different implementation.
*/
public static BundleClassLoaderHelper BUNDLE_CLASS_LOADER_HELPER = null;
/**
* By default set to: {@link DefaultBundleClassLoaderHelper}. It supports
* equinox and apache-felix fragment bundles that are specific to an OSGi
* implementation should set a different implementation.
*/
public static BundleFileLocatorHelper BUNDLE_FILE_LOCATOR_HELPER = null;
/**
* By default set to: {@link DefaultBundleClassLoaderHelper}. It supports
* equinox and apache-felix fragment bundles that are specific to an OSGi
* implementation should set a different implementation.
* <p>
* Several of those objects can be added here: For example we could have an optional fragment that setups
* a specific implementation of JSF for the whole of jetty-osgi.
* </p>
*/
public static Collection<WebappRegistrationCustomizer> JSP_REGISTRATION_HELPERS = new ArrayList<WebappRegistrationCustomizer>();
private Server _server;
private ContextHandlerCollection _ctxtHandler;
/**
* this class loader loads the jars inside {$jetty.home}/lib/ext it is meant
* as a migration path and for jars that are not OSGi ready. also gives
* access to the jsp jars.
*/
// private URLClassLoader _libExtClassLoader;
/**
* This is the class loader that should be the parent classloader of any
* webapp classloader. It is in fact the _libExtClassLoader with a trick to
* let the TldScanner find the jars where the tld files are.
*/
private URLClassLoader _commonParentClassLoaderForWebapps;
private DeploymentManager _deploymentManager;
private OSGiAppProvider _provider;
public WebappRegistrationHelper(Server server)
{
_server = server;
staticInit();
}
// Inject the customizing classes that might be defined in fragment bundles.
private static synchronized void staticInit()
{
if (!INITIALIZED)
{
INITIALIZED = true;
// setup the custom BundleClassLoaderHelper
try
{
BUNDLE_CLASS_LOADER_HELPER = (BundleClassLoaderHelper)Class.forName(BundleClassLoaderHelper.CLASS_NAME).newInstance();
}
catch (Throwable t)
{
// System.err.println("support for equinox and felix");
BUNDLE_CLASS_LOADER_HELPER = new DefaultBundleClassLoaderHelper();
}
// setup the custom FileLocatorHelper
try
{
BUNDLE_FILE_LOCATOR_HELPER = (BundleFileLocatorHelper)Class.forName(BundleFileLocatorHelper.CLASS_NAME).newInstance();
}
catch (Throwable t)
{
// System.err.println("no jsp/jasper support");
BUNDLE_FILE_LOCATOR_HELPER = new DefaultFileLocatorHelper();
}
}
}
/**
* Removes quotes around system property values before we try to make them
* into file pathes.
*/
public static String stripQuotesIfPresent(String filePath)
{
if (filePath == null)
return null;
if ((filePath.startsWith("\"") || filePath.startsWith("'")) && (filePath.endsWith("\"") || filePath.endsWith("'")))
return filePath.substring(1,filePath.length() - 1);
return filePath;
}
/**
* Look for the home directory of jetty as defined by the system property
* 'jetty.home'. If undefined, look at the current bundle and uses its own
* jettyhome folder for this feature.
* <p>
* Special case: inside eclipse-SDK:<br/>
* If the bundle is jarred, see if we are inside eclipse-PDE itself. In that
* case, look for the installation directory of eclipse-PDE, try to create a
* jettyhome folder there and install the sample jettyhome folder at that
* location. This makes the installation in eclipse-SDK easier. <br/>
* This is a bit redundant with the work done by the jetty configuration
* launcher.
* </p>
*
* @param context
* @throws Exception
*/
public void setup(BundleContext context, Map<String, String> configProperties) throws Exception
{
Enumeration<?> enUrls = context.getBundle().findEntries("/etc", "jetty.xml", false);System.err.println();
- if (enUrls.hasMoreElements())
+ if (enUrls != null && enUrls.hasMoreElements())
{
URL url = (URL) enUrls.nextElement();
if (url != null)
{
//bug 317231: there is a fragment that defines the jetty configuration file.
//let's use that as the jetty home.
url = DefaultFileLocatorHelper.getLocalURL(url);
if (url.getProtocol().equals("file"))
{
//ok good.
File jettyxml = new File(url.toURI());
File jettyhome = jettyxml.getParentFile().getParentFile();
System.setProperty("jetty.home", jettyhome.getAbsolutePath());
}
}
}
File _installLocation = BUNDLE_FILE_LOCATOR_HELPER.getBundleInstallLocation(context.getBundle());
// debug:
// new File("~/proj/eclipse-install/eclipse-3.5.1-SDK-jetty7/" +
// "dropins/jetty7/plugins/org.eclipse.jetty.osgi.boot_0.0.1.001-SNAPSHOT.jar");
boolean bootBundleCanBeJarred = true;
String jettyHome = stripQuotesIfPresent(System.getProperty("jetty.home"));
if (jettyHome == null || jettyHome.length() == 0)
{
if (_installLocation.getName().endsWith(".jar"))
{
jettyHome = JettyHomeHelper.setupJettyHomeInEclipsePDE(_installLocation);
}
if (jettyHome == null)
{
jettyHome = _installLocation.getAbsolutePath() + "/jettyhome";
bootBundleCanBeJarred = false;
}
}
// in case we stripped the quotes.
System.setProperty("jetty.home",jettyHome);
String jettyLogs = stripQuotesIfPresent(System.getProperty("jetty.logs"));
if (jettyLogs == null || jettyLogs.length() == 0)
{
System.setProperty("jetty.logs",jettyHome + "/logs");
}
if (!bootBundleCanBeJarred && !_installLocation.isDirectory())
{
String install = _installLocation != null?_installLocation.getCanonicalPath():" unresolved_install_location";
throw new IllegalArgumentException("The system property -Djetty.home" + " must be set to a directory or the bundle "
+ context.getBundle().getSymbolicName() + " installed here " + install + " must be unjarred.");
}
try
{
System.err.println("JETTY_HOME set to " + new File(jettyHome).getCanonicalPath());
}
catch (Throwable t)
{
System.err.println("JETTY_HOME _set to " + new File(jettyHome).getAbsolutePath());
}
ClassLoader contextCl = Thread.currentThread().getContextClassLoader();
try
{
// passing this bundle's classloader as the context classlaoder
// makes sure there is access to all the jetty's bundles
File jettyHomeF = new File(jettyHome);
URLClassLoader libExtClassLoader = null;
try
{
libExtClassLoader = LibExtClassLoaderHelper.createLibEtcClassLoaderHelper(jettyHomeF,_server,
JettyBootstrapActivator.class.getClassLoader());
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
Thread.currentThread().setContextClassLoader(libExtClassLoader);
String jettyetc = System.getProperty(OSGiWebappConstants.SYS_PROP_JETTY_ETC_FILES,"etc/jetty.xml");
StringTokenizer tokenizer = new StringTokenizer(jettyetc,";,");
Map<Object,Object> id_map = new HashMap<Object,Object>();
id_map.put("Server",_server);
Map<Object,Object> properties = new HashMap<Object,Object>();
properties.put("jetty.home",jettyHome);
properties.put("jetty.host",System.getProperty("jetty.host",""));
properties.put("jetty.port",System.getProperty("jetty.port","8080"));
properties.put("jetty.port.ssl",System.getProperty("jetty.port.ssl","8443"));
while (tokenizer.hasMoreTokens())
{
String etcFile = tokenizer.nextToken().trim();
File conffile = etcFile.startsWith("/")?new File(etcFile):new File(jettyHomeF,etcFile);
if (!conffile.exists())
{
__logger.warn("Unable to resolve the jetty/etc file " + etcFile);
if ("etc/jetty.xml".equals(etcFile))
{
// Missing jetty.xml file, so create a minimal Jetty configuration
__logger.info("Configuring default server on 8080");
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(8080);
_server.addConnector(connector);
HandlerCollection handlers = new HandlerCollection();
ContextHandlerCollection contexts = new ContextHandlerCollection();
RequestLogHandler requestLogHandler = new RequestLogHandler();
handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
_server.setHandler(handlers);
}
}
else
{
try
{
// Execute a Jetty configuration file
XmlConfiguration config = new XmlConfiguration(new FileInputStream(conffile));
config.setIdMap(id_map);
config.setProperties(properties);
config.configure();
id_map=config.getIdMap();
}
catch (SAXParseException saxparse)
{
Log.getLogger(WebappRegistrationHelper.class.getName()).warn("Unable to configure the jetty/etc file " + etcFile,saxparse);
throw saxparse;
}
}
}
init();
//now that we have an app provider we can call the registration customizer.
try
{
URL[] jarsWithTlds = getJarsWithTlds();
_commonParentClassLoaderForWebapps = jarsWithTlds == null?libExtClassLoader:new TldLocatableURLClassloader(libExtClassLoader,getJarsWithTlds());
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
_server.start();
}
catch (Throwable t)
{
t.printStackTrace();
}
finally
{
Thread.currentThread().setContextClassLoader(contextCl);
}
}
/**
* Must be called after the server is configured.
*
* Locate the actual instance of the ContextDeployer and WebAppDeployer that
* was created when configuring the server through jetty.xml. If there is no
* such thing it won't be possible to deploy webapps from a context and we
* throw IllegalStateExceptions.
*/
private void init()
{
// Get the context handler
_ctxtHandler = (ContextHandlerCollection)_server.getChildHandlerByClass(ContextHandlerCollection.class);
// get a deployerManager
List<DeploymentManager> deployers = _server.getBeans(DeploymentManager.class);
if (deployers != null && !deployers.isEmpty())
{
_deploymentManager = deployers.get(0);
for (AppProvider provider : _deploymentManager.getAppProviders())
{
if (provider instanceof OSGiAppProvider)
{
_provider=(OSGiAppProvider)provider;
break;
}
}
if (_provider == null)
{
//create it on the fly with reasonable default values.
try
{
_provider = new OSGiAppProvider();
_provider.setMonitoredDir(
Resource.newResource(getDefaultOSGiContextsHome(
new File(System.getProperty("jetty.home"))).toURI()));
} catch (IOException e) {
e.printStackTrace();
}
_deploymentManager.addAppProvider(_provider);
}
}
if (_ctxtHandler == null || _provider==null)
throw new IllegalStateException("ERROR: No ContextHandlerCollection or OSGiAppProvider configured");
}
/**
* Deploy a new web application on the jetty server.
*
* @param bundle
* The bundle
* @param webappFolderPath
* The path to the root of the webapp. Must be a path relative to
* bundle; either an absolute path.
* @param contextPath
* The context path. Must start with "/"
* @param extraClasspath
* @param overrideBundleInstallLocation
* @param webXmlPath
* @param defaultWebXmlPath
* TODO: parameter description
* @return The contexthandler created and started
* @throws Exception
*/
public ContextHandler registerWebapplication(Bundle bundle, String webappFolderPath, String contextPath, String extraClasspath,
String overrideBundleInstallLocation, String webXmlPath, String defaultWebXmlPath) throws Exception
{
File bundleInstall = overrideBundleInstallLocation == null?BUNDLE_FILE_LOCATOR_HELPER.getBundleInstallLocation(bundle):new File(
overrideBundleInstallLocation);
File webapp = null;
if (webappFolderPath != null && webappFolderPath.length() != 0 && !webappFolderPath.equals("."))
{
if (webappFolderPath.startsWith("/") || webappFolderPath.startsWith("file:/"))
{
webapp = new File(webappFolderPath);
}
else
{
webapp = new File(bundleInstall,webappFolderPath);
}
}
else
{
webapp = bundleInstall;
}
if (!webapp.exists())
{
throw new IllegalArgumentException("Unable to locate " + webappFolderPath + " inside "
+ (bundleInstall != null?bundleInstall.getAbsolutePath():"unlocated bundle '" + bundle.getSymbolicName() + "'"));
}
return registerWebapplication(bundle,webapp,contextPath,extraClasspath,bundleInstall,webXmlPath,defaultWebXmlPath);
}
/**
* TODO: refactor this into the createContext method of OSGiAppProvider.
* @see WebAppDeployer#scan()
* @param contributor
* @param webapp
* @param contextPath
* @param extraClasspath
* @param bundleInstall
* @param webXmlPath
* @param defaultWebXmlPath
* @return The contexthandler created and started
* @throws Exception
*/
public ContextHandler registerWebapplication(Bundle contributor, File webapp, String contextPath, String extraClasspath, File bundleInstall,
String webXmlPath, String defaultWebXmlPath) throws Exception
{
ClassLoader contextCl = Thread.currentThread().getContextClassLoader();
String[] oldServerClasses = null;
WebAppContext context = null;
try
{
// make sure we provide access to all the jetty bundles by going
// through this bundle.
OSGiWebappClassLoader composite = createWebappClassLoader(contributor);
// configure with access to all jetty classes and also all the classes
// that the contributor gives access to.
Thread.currentThread().setContextClassLoader(composite);
context = new WebAppContext(webapp.getAbsolutePath(),contextPath);
context.setExtraClasspath(extraClasspath);
if (webXmlPath != null && webXmlPath.length() != 0)
{
File webXml = null;
if (webXmlPath.startsWith("/") || webXmlPath.startsWith("file:/"))
{
webXml = new File(webXmlPath);
}
else
{
webXml = new File(bundleInstall,webXmlPath);
}
if (webXml.exists())
{
context.setDescriptor(webXml.getAbsolutePath());
}
}
if (defaultWebXmlPath == null || defaultWebXmlPath.length() == 0)
{
//use the one defined by the OSGiAppProvider.
defaultWebXmlPath = _provider.getDefaultsDescriptor();
}
if (defaultWebXmlPath != null && defaultWebXmlPath.length() != 0)
{
File defaultWebXml = null;
if (defaultWebXmlPath.startsWith("/") || defaultWebXmlPath.startsWith("file:/"))
{
defaultWebXml = new File(webXmlPath);
}
else
{
defaultWebXml = new File(bundleInstall,defaultWebXmlPath);
}
if (defaultWebXml.exists())
{
context.setDefaultsDescriptor(defaultWebXml.getAbsolutePath());
}
}
//other parameters that might be defines on the OSGiAppProvider:
context.setParentLoaderPriority(_provider.isParentLoaderPriority());
configureWebAppContext(context,contributor);
configureWebappClassLoader(contributor,context,composite);
// @see
// org.eclipse.jetty.webapp.JettyWebXmlConfiguration#configure(WebAppContext)
// during initialization of the webapp all the jetty packages are
// visible
// through the webapp classloader.
oldServerClasses = context.getServerClasses();
context.setServerClasses(null);
_provider.addContext(context);
return context;
}
finally
{
if (context != null && oldServerClasses != null)
{
context.setServerClasses(oldServerClasses);
}
Thread.currentThread().setContextClassLoader(contextCl);
}
}
/**
* Stop a ContextHandler and remove it from the collection.
*
* @see ContextDeployer#undeploy
* @param contextHandler
* @throws Exception
*/
public void unregister(ContextHandler contextHandler) throws Exception
{
contextHandler.stop();
_ctxtHandler.removeHandler(contextHandler);
}
/**
* @return The default folder in which the context files of the osgi bundles
* are located and watched. Or null when the system property
* "jetty.osgi.contexts.home" is not defined.
* If the configuration file defines the OSGiAppProvider's context.
* This will not be taken into account.
*/
File getDefaultOSGiContextsHome(File jettyHome)
{
String jettyContextsHome = System.getProperty("jetty.osgi.contexts.home");
if (jettyContextsHome != null)
{
File contextsHome = new File(jettyContextsHome);
if (!contextsHome.exists() || !contextsHome.isDirectory())
{
throw new IllegalArgumentException("the ${jetty.osgi.contexts.home} '" + jettyContextsHome + " must exist and be a folder");
}
return contextsHome;
}
return new File(jettyHome, "/contexts");
}
File getOSGiContextsHome()
{
return _provider.getContextXmlDirAsFile();
}
/**
* This type of registration relies on jetty's complete context xml file.
* Context encompasses jndi and all other things. This makes the definition
* of the webapp a lot more self-contained.
*
* @param contributor
* @param contextFileRelativePath
* @param extraClasspath
* @param overrideBundleInstallLocation
* @return The contexthandler created and started
* @throws Exception
*/
public ContextHandler registerContext(Bundle contributor, String contextFileRelativePath, String extraClasspath, String overrideBundleInstallLocation)
throws Exception
{
File contextsHome = _provider.getContextXmlDirAsFile();
if (contextsHome != null)
{
File prodContextFile = new File(contextsHome,contributor.getSymbolicName() + "/" + contextFileRelativePath);
if (prodContextFile.exists())
{
return registerContext(contributor,prodContextFile,extraClasspath,overrideBundleInstallLocation);
}
}
File contextFile = overrideBundleInstallLocation != null?new File(overrideBundleInstallLocation,contextFileRelativePath):new File(
BUNDLE_FILE_LOCATOR_HELPER.getBundleInstallLocation(contributor),contextFileRelativePath);
if (contextFile.exists())
{
return registerContext(contributor,contextFile,extraClasspath,overrideBundleInstallLocation);
}
else
{
if (contextFileRelativePath.startsWith("./"))
{
contextFileRelativePath = contextFileRelativePath.substring(1);
}
if (!contextFileRelativePath.startsWith("/"))
{
contextFileRelativePath = "/" + contextFileRelativePath;
}
if (overrideBundleInstallLocation == null)
{
URL contextURL = contributor.getEntry(contextFileRelativePath);
if (contextURL != null)
{
return registerContext(contributor,contextURL.openStream(),extraClasspath,overrideBundleInstallLocation);
}
}
else
{
JarFile zipFile = null;
try
{
zipFile = new JarFile(overrideBundleInstallLocation);
ZipEntry entry = zipFile.getEntry(contextFileRelativePath.substring(1));
return registerContext(contributor,zipFile.getInputStream(entry),extraClasspath,overrideBundleInstallLocation);
}
catch (Throwable t)
{
}
finally
{
if (zipFile != null)
try
{
zipFile.close();
}
catch (IOException ioe)
{
}
}
}
throw new IllegalArgumentException("Could not find the context " + "file " + contextFileRelativePath + " for the bundle "
+ contributor.getSymbolicName() + (overrideBundleInstallLocation != null?" using the install location " + overrideBundleInstallLocation:""));
}
}
/**
* This type of registration relies on jetty's complete context xml file.
* Context encompasses jndi and all other things. This makes the definition
* of the webapp a lot more self-contained.
*
* @param webapp
* @param contextPath
* @param classInBundle
* @throws Exception
*/
private ContextHandler registerContext(Bundle contributor, File contextFile, String extraClasspath, String overrideBundleInstallLocation) throws Exception
{
InputStream contextFileInputStream = null;
try
{
contextFileInputStream = new BufferedInputStream(new FileInputStream(contextFile));
return registerContext(contributor,contextFileInputStream,extraClasspath,overrideBundleInstallLocation);
}
finally
{
if (contextFileInputStream != null)
try
{
contextFileInputStream.close();
}
catch (IOException ioe)
{
}
}
}
/**
* @param contributor
* @param contextFileInputStream
* @return The ContextHandler created and registered or null if it did not
* happen.
* @throws Exception
*/
private ContextHandler registerContext(Bundle contributor, InputStream contextFileInputStream, String extraClasspath, String overrideBundleInstallLocation)
throws Exception
{
ClassLoader contextCl = Thread.currentThread().getContextClassLoader();
String[] oldServerClasses = null;
WebAppContext webAppContext = null;
try
{
// make sure we provide access to all the jetty bundles by going
// through this bundle.
OSGiWebappClassLoader composite = createWebappClassLoader(contributor);
// configure with access to all jetty classes and also all the
// classes
// that the contributor gives access to.
Thread.currentThread().setContextClassLoader(composite);
ContextHandler context = createContextHandler(contributor,contextFileInputStream,extraClasspath,overrideBundleInstallLocation);
if (context == null)
{
return null;// did not happen
}
// ok now register this webapp. we checked when we started jetty
// that there
// was at least one such handler for webapps.
//the actual registration must happen via the new Deployment API.
// _ctxtHandler.addHandler(context);
configureWebappClassLoader(contributor,context,composite);
if (context instanceof WebAppContext)
{
webAppContext = (WebAppContext)context;
// @see
// org.eclipse.jetty.webapp.JettyWebXmlConfiguration#configure(WebAppContext)
oldServerClasses = webAppContext.getServerClasses();
webAppContext.setServerClasses(null);
}
_provider.addContext(context);
return context;
}
finally
{
if (webAppContext != null)
{
webAppContext.setServerClasses(oldServerClasses);
}
Thread.currentThread().setContextClassLoader(contextCl);
}
}
/**
* TODO: right now only the jetty-jsp bundle is scanned for common taglibs.
* Should support a way to plug more bundles that contain taglibs.
*
* The jasper TldScanner expects a URLClassloader to parse a jar for the
* /META-INF/*.tld it may contain. We place the bundles that we know contain
* such tag-libraries. Please note that it will work if and only if the
* bundle is a jar (!) Currently we just hardcode the bundle that contains
* the jstl implemenation.
*
* A workaround when the tld cannot be parsed with this method is to copy
* and paste it inside the WEB-INF of the webapplication where it is used.
*
* Support only 2 types of packaging for the bundle: - the bundle is a jar
* (recommended for runtime.) - the bundle is a folder and contain jars in
* the root and/or in the lib folder (nice for PDE developement situations)
* Unsupported: the bundle is a jar that embeds more jars.
*
* @return
* @throws Exception
*/
private URL[] getJarsWithTlds() throws Exception
{
ArrayList<URL> res = new ArrayList<URL>();
for (WebappRegistrationCustomizer regCustomizer : JSP_REGISTRATION_HELPERS)
{
URL[] urls = regCustomizer.getJarsWithTlds(_provider, BUNDLE_FILE_LOCATOR_HELPER);
for (URL url : urls)
{
if (!res.contains(url))
res.add(url);
}
}
if (!res.isEmpty())
return res.toArray(new URL[res.size()]);
else
return null;
}
/**
* Applies the properties of WebAppDeployer as defined in jetty.xml.
*
* @see {WebAppDeployer#scan} around the comment
* <code>// configure it</code>
*/
protected void configureWebAppContext(WebAppContext wah, Bundle contributor)
{
// rfc66
wah.setAttribute(OSGiWebappConstants.RFC66_OSGI_BUNDLE_CONTEXT,contributor.getBundleContext());
//spring-dm-1.2.1 looks for the BundleContext as a different attribute.
//not a spec... but if we want to support
//org.springframework.osgi.web.context.support.OsgiBundleXmlWebApplicationContext
//then we need to do this to:
wah.setAttribute("org.springframework.osgi.web." + BundleContext.class.getName(),
contributor.getBundleContext());
}
/**
* @See {@link ContextDeployer#scan}
* @param contextFile
* @return
*/
protected ContextHandler createContextHandler(Bundle bundle, File contextFile, String extraClasspath, String overrideBundleInstallLocation)
{
try
{
return createContextHandler(bundle,new BufferedInputStream(new FileInputStream(contextFile)),extraClasspath,overrideBundleInstallLocation);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
return null;
}
/**
* @See {@link ContextDeployer#scan}
* @param contextFile
* @return
*/
@SuppressWarnings("unchecked")
protected ContextHandler createContextHandler(Bundle bundle, InputStream contextInputStream, String extraClasspath, String overrideBundleInstallLocation)
{
/*
* Do something identical to what the ContextProvider would have done:
* XmlConfiguration xmlConfiguration=new
* XmlConfiguration(resource.getURL()); HashMap properties = new
* HashMap(); properties.put("Server", _contexts.getServer()); if
* (_configMgr!=null) properties.putAll(_configMgr.getProperties());
*
* xmlConfiguration.setProperties(properties); ContextHandler
* context=(ContextHandler)xmlConfiguration.configure();
* context.setAttributes(new AttributesMap(_contextAttributes));
*/
try
{
XmlConfiguration xmlConfiguration = new XmlConfiguration(contextInputStream);
HashMap properties = new HashMap();
properties.put("Server",_server);
// insert the bundle's location as a property.
setThisBundleHomeProperty(bundle,properties,overrideBundleInstallLocation);
xmlConfiguration.setProperties(properties);
ContextHandler context = (ContextHandler)xmlConfiguration.configure();
if (context instanceof WebAppContext)
{
((WebAppContext)context).setExtraClasspath(extraClasspath);
((WebAppContext)context).setParentLoaderPriority(_provider.isParentLoaderPriority());
if (_provider.getDefaultsDescriptor() != null && _provider.getDefaultsDescriptor().length() != 0)
{
((WebAppContext)context).setDefaultsDescriptor(_provider.getDefaultsDescriptor());
}
}
// rfc-66:
context.setAttribute(OSGiWebappConstants.RFC66_OSGI_BUNDLE_CONTEXT,bundle.getBundleContext());
//spring-dm-1.2.1 looks for the BundleContext as a different attribute.
//not a spec... but if we want to support
//org.springframework.osgi.web.context.support.OsgiBundleXmlWebApplicationContext
//then we need to do this to:
context.setAttribute("org.springframework.osgi.web." + BundleContext.class.getName(),
bundle.getBundleContext());
return context;
}
catch (FileNotFoundException e)
{
return null;
}
catch (SAXException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Throwable e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
if (contextInputStream != null)
try
{
contextInputStream.close();
}
catch (IOException ioe)
{
}
}
return null;
}
/**
* Configure a classloader onto the context. If the context is a
* WebAppContext, build a WebAppClassLoader that has access to all the jetty
* classes thanks to the classloader of the JettyBootStrapper bundle and
* also has access to the classloader of the bundle that defines this
* context.
* <p>
* If the context is not a WebAppContext, same but with a simpler
* URLClassLoader. Note that the URLClassLoader is pretty much fake: it
* delegate all actual classloading to the parent classloaders.
* </p>
* <p>
* The URL[] returned by the URLClassLoader create contained specifically
* the jars that some j2ee tools expect and look into. For example the jars
* that contain tld files for jasper's jstl support.
* </p>
* <p>
* Also as the jars in the lib folder and the classes in the classes folder
* might already be in the OSGi classloader we filter them out of the
* WebAppClassLoader
* </p>
*
* @param context
* @param contributor
* @param webapp
* @param contextPath
* @param classInBundle
* @throws Exception
*/
protected void configureWebappClassLoader(Bundle contributor, ContextHandler context, OSGiWebappClassLoader webappClassLoader) throws Exception
{
if (context instanceof WebAppContext)
{
WebAppContext webappCtxt = (WebAppContext)context;
context.setClassLoader(webappClassLoader);
webappClassLoader.setWebappContext(webappCtxt);
}
else
{
context.setClassLoader(webappClassLoader);
}
}
/**
* No matter what the type of webapp, we create a WebappClassLoader.
*/
protected OSGiWebappClassLoader createWebappClassLoader(Bundle contributor) throws Exception
{
// we use a temporary WebAppContext object.
// if this is a real webapp we will set it on it a bit later: once we
// know.
OSGiWebappClassLoader webappClassLoader = new OSGiWebappClassLoader(_commonParentClassLoaderForWebapps,new WebAppContext(),contributor);
return webappClassLoader;
}
/**
* Set the property "this.bundle.install" to point to the location
* of the bundle. Useful when <SystemProperty name="this.bundle.home"/> is
* used.
*/
private void setThisBundleHomeProperty(Bundle bundle, HashMap<String, Object> properties, String overrideBundleInstallLocation)
{
try
{
File location = overrideBundleInstallLocation != null?new File(overrideBundleInstallLocation):BUNDLE_FILE_LOCATOR_HELPER
.getBundleInstallLocation(bundle);
properties.put("this.bundle.install",location.getCanonicalPath());
}
catch (Throwable t)
{
System.err.println("Unable to set 'this.bundle.install' " + " for the bundle " + bundle.getSymbolicName());
t.printStackTrace();
}
}
}
| true | true | public void setup(BundleContext context, Map<String, String> configProperties) throws Exception
{
Enumeration<?> enUrls = context.getBundle().findEntries("/etc", "jetty.xml", false);System.err.println();
if (enUrls.hasMoreElements())
{
URL url = (URL) enUrls.nextElement();
if (url != null)
{
//bug 317231: there is a fragment that defines the jetty configuration file.
//let's use that as the jetty home.
url = DefaultFileLocatorHelper.getLocalURL(url);
if (url.getProtocol().equals("file"))
{
//ok good.
File jettyxml = new File(url.toURI());
File jettyhome = jettyxml.getParentFile().getParentFile();
System.setProperty("jetty.home", jettyhome.getAbsolutePath());
}
}
}
File _installLocation = BUNDLE_FILE_LOCATOR_HELPER.getBundleInstallLocation(context.getBundle());
// debug:
// new File("~/proj/eclipse-install/eclipse-3.5.1-SDK-jetty7/" +
// "dropins/jetty7/plugins/org.eclipse.jetty.osgi.boot_0.0.1.001-SNAPSHOT.jar");
boolean bootBundleCanBeJarred = true;
String jettyHome = stripQuotesIfPresent(System.getProperty("jetty.home"));
if (jettyHome == null || jettyHome.length() == 0)
{
if (_installLocation.getName().endsWith(".jar"))
{
jettyHome = JettyHomeHelper.setupJettyHomeInEclipsePDE(_installLocation);
}
if (jettyHome == null)
{
jettyHome = _installLocation.getAbsolutePath() + "/jettyhome";
bootBundleCanBeJarred = false;
}
}
// in case we stripped the quotes.
System.setProperty("jetty.home",jettyHome);
String jettyLogs = stripQuotesIfPresent(System.getProperty("jetty.logs"));
if (jettyLogs == null || jettyLogs.length() == 0)
{
System.setProperty("jetty.logs",jettyHome + "/logs");
}
if (!bootBundleCanBeJarred && !_installLocation.isDirectory())
{
String install = _installLocation != null?_installLocation.getCanonicalPath():" unresolved_install_location";
throw new IllegalArgumentException("The system property -Djetty.home" + " must be set to a directory or the bundle "
+ context.getBundle().getSymbolicName() + " installed here " + install + " must be unjarred.");
}
try
{
System.err.println("JETTY_HOME set to " + new File(jettyHome).getCanonicalPath());
}
catch (Throwable t)
{
System.err.println("JETTY_HOME _set to " + new File(jettyHome).getAbsolutePath());
}
ClassLoader contextCl = Thread.currentThread().getContextClassLoader();
try
{
// passing this bundle's classloader as the context classlaoder
// makes sure there is access to all the jetty's bundles
File jettyHomeF = new File(jettyHome);
URLClassLoader libExtClassLoader = null;
try
{
libExtClassLoader = LibExtClassLoaderHelper.createLibEtcClassLoaderHelper(jettyHomeF,_server,
JettyBootstrapActivator.class.getClassLoader());
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
Thread.currentThread().setContextClassLoader(libExtClassLoader);
String jettyetc = System.getProperty(OSGiWebappConstants.SYS_PROP_JETTY_ETC_FILES,"etc/jetty.xml");
StringTokenizer tokenizer = new StringTokenizer(jettyetc,";,");
Map<Object,Object> id_map = new HashMap<Object,Object>();
id_map.put("Server",_server);
Map<Object,Object> properties = new HashMap<Object,Object>();
properties.put("jetty.home",jettyHome);
properties.put("jetty.host",System.getProperty("jetty.host",""));
properties.put("jetty.port",System.getProperty("jetty.port","8080"));
properties.put("jetty.port.ssl",System.getProperty("jetty.port.ssl","8443"));
while (tokenizer.hasMoreTokens())
{
String etcFile = tokenizer.nextToken().trim();
File conffile = etcFile.startsWith("/")?new File(etcFile):new File(jettyHomeF,etcFile);
if (!conffile.exists())
{
__logger.warn("Unable to resolve the jetty/etc file " + etcFile);
if ("etc/jetty.xml".equals(etcFile))
{
// Missing jetty.xml file, so create a minimal Jetty configuration
__logger.info("Configuring default server on 8080");
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(8080);
_server.addConnector(connector);
HandlerCollection handlers = new HandlerCollection();
ContextHandlerCollection contexts = new ContextHandlerCollection();
RequestLogHandler requestLogHandler = new RequestLogHandler();
handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
_server.setHandler(handlers);
}
}
else
{
try
{
// Execute a Jetty configuration file
XmlConfiguration config = new XmlConfiguration(new FileInputStream(conffile));
config.setIdMap(id_map);
config.setProperties(properties);
config.configure();
id_map=config.getIdMap();
}
catch (SAXParseException saxparse)
{
Log.getLogger(WebappRegistrationHelper.class.getName()).warn("Unable to configure the jetty/etc file " + etcFile,saxparse);
throw saxparse;
}
}
}
init();
//now that we have an app provider we can call the registration customizer.
try
{
URL[] jarsWithTlds = getJarsWithTlds();
_commonParentClassLoaderForWebapps = jarsWithTlds == null?libExtClassLoader:new TldLocatableURLClassloader(libExtClassLoader,getJarsWithTlds());
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
_server.start();
}
catch (Throwable t)
{
t.printStackTrace();
}
finally
{
Thread.currentThread().setContextClassLoader(contextCl);
}
}
| public void setup(BundleContext context, Map<String, String> configProperties) throws Exception
{
Enumeration<?> enUrls = context.getBundle().findEntries("/etc", "jetty.xml", false);System.err.println();
if (enUrls != null && enUrls.hasMoreElements())
{
URL url = (URL) enUrls.nextElement();
if (url != null)
{
//bug 317231: there is a fragment that defines the jetty configuration file.
//let's use that as the jetty home.
url = DefaultFileLocatorHelper.getLocalURL(url);
if (url.getProtocol().equals("file"))
{
//ok good.
File jettyxml = new File(url.toURI());
File jettyhome = jettyxml.getParentFile().getParentFile();
System.setProperty("jetty.home", jettyhome.getAbsolutePath());
}
}
}
File _installLocation = BUNDLE_FILE_LOCATOR_HELPER.getBundleInstallLocation(context.getBundle());
// debug:
// new File("~/proj/eclipse-install/eclipse-3.5.1-SDK-jetty7/" +
// "dropins/jetty7/plugins/org.eclipse.jetty.osgi.boot_0.0.1.001-SNAPSHOT.jar");
boolean bootBundleCanBeJarred = true;
String jettyHome = stripQuotesIfPresent(System.getProperty("jetty.home"));
if (jettyHome == null || jettyHome.length() == 0)
{
if (_installLocation.getName().endsWith(".jar"))
{
jettyHome = JettyHomeHelper.setupJettyHomeInEclipsePDE(_installLocation);
}
if (jettyHome == null)
{
jettyHome = _installLocation.getAbsolutePath() + "/jettyhome";
bootBundleCanBeJarred = false;
}
}
// in case we stripped the quotes.
System.setProperty("jetty.home",jettyHome);
String jettyLogs = stripQuotesIfPresent(System.getProperty("jetty.logs"));
if (jettyLogs == null || jettyLogs.length() == 0)
{
System.setProperty("jetty.logs",jettyHome + "/logs");
}
if (!bootBundleCanBeJarred && !_installLocation.isDirectory())
{
String install = _installLocation != null?_installLocation.getCanonicalPath():" unresolved_install_location";
throw new IllegalArgumentException("The system property -Djetty.home" + " must be set to a directory or the bundle "
+ context.getBundle().getSymbolicName() + " installed here " + install + " must be unjarred.");
}
try
{
System.err.println("JETTY_HOME set to " + new File(jettyHome).getCanonicalPath());
}
catch (Throwable t)
{
System.err.println("JETTY_HOME _set to " + new File(jettyHome).getAbsolutePath());
}
ClassLoader contextCl = Thread.currentThread().getContextClassLoader();
try
{
// passing this bundle's classloader as the context classlaoder
// makes sure there is access to all the jetty's bundles
File jettyHomeF = new File(jettyHome);
URLClassLoader libExtClassLoader = null;
try
{
libExtClassLoader = LibExtClassLoaderHelper.createLibEtcClassLoaderHelper(jettyHomeF,_server,
JettyBootstrapActivator.class.getClassLoader());
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
Thread.currentThread().setContextClassLoader(libExtClassLoader);
String jettyetc = System.getProperty(OSGiWebappConstants.SYS_PROP_JETTY_ETC_FILES,"etc/jetty.xml");
StringTokenizer tokenizer = new StringTokenizer(jettyetc,";,");
Map<Object,Object> id_map = new HashMap<Object,Object>();
id_map.put("Server",_server);
Map<Object,Object> properties = new HashMap<Object,Object>();
properties.put("jetty.home",jettyHome);
properties.put("jetty.host",System.getProperty("jetty.host",""));
properties.put("jetty.port",System.getProperty("jetty.port","8080"));
properties.put("jetty.port.ssl",System.getProperty("jetty.port.ssl","8443"));
while (tokenizer.hasMoreTokens())
{
String etcFile = tokenizer.nextToken().trim();
File conffile = etcFile.startsWith("/")?new File(etcFile):new File(jettyHomeF,etcFile);
if (!conffile.exists())
{
__logger.warn("Unable to resolve the jetty/etc file " + etcFile);
if ("etc/jetty.xml".equals(etcFile))
{
// Missing jetty.xml file, so create a minimal Jetty configuration
__logger.info("Configuring default server on 8080");
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(8080);
_server.addConnector(connector);
HandlerCollection handlers = new HandlerCollection();
ContextHandlerCollection contexts = new ContextHandlerCollection();
RequestLogHandler requestLogHandler = new RequestLogHandler();
handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
_server.setHandler(handlers);
}
}
else
{
try
{
// Execute a Jetty configuration file
XmlConfiguration config = new XmlConfiguration(new FileInputStream(conffile));
config.setIdMap(id_map);
config.setProperties(properties);
config.configure();
id_map=config.getIdMap();
}
catch (SAXParseException saxparse)
{
Log.getLogger(WebappRegistrationHelper.class.getName()).warn("Unable to configure the jetty/etc file " + etcFile,saxparse);
throw saxparse;
}
}
}
init();
//now that we have an app provider we can call the registration customizer.
try
{
URL[] jarsWithTlds = getJarsWithTlds();
_commonParentClassLoaderForWebapps = jarsWithTlds == null?libExtClassLoader:new TldLocatableURLClassloader(libExtClassLoader,getJarsWithTlds());
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
_server.start();
}
catch (Throwable t)
{
t.printStackTrace();
}
finally
{
Thread.currentThread().setContextClassLoader(contextCl);
}
}
|
diff --git a/src/org/ohmage/reporting/AuditReporter.java b/src/org/ohmage/reporting/AuditReporter.java
index a2466962..d8d1e5a2 100644
--- a/src/org/ohmage/reporting/AuditReporter.java
+++ b/src/org/ohmage/reporting/AuditReporter.java
@@ -1,321 +1,324 @@
/*******************************************************************************
* Copyright 2012 The Regents of the University of California
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.ohmage.reporting;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.json.JSONException;
import org.json.JSONObject;
import org.ohmage.cache.PreferenceCache;
import org.ohmage.domain.Audit;
import org.ohmage.exception.CacheMissException;
import org.ohmage.exception.ServiceException;
import org.ohmage.request.InputKeys;
import org.ohmage.request.RequestBuilder;
import org.ohmage.service.AuditServices;
import org.ohmage.util.DateTimeUtils;
/**
* Begins on server startup and creates a daily snapshot of some information
* from the audit table.
*
* @author John Jenkins
*/
public final class AuditReporter {
private static final Logger LOGGER = Logger.getLogger(AuditReporter.class);
// Used by the timer.
private static final int MILLIS_IN_A_DAY = 1000 * 60 * 60 * 24;
// The number of idle threads ready to generate the report. Two reports
// should never be generated at the same time, so we only need one thread
// to handle this.
private static final int THREAD_POOL_SIZE = 1;
// Where we will save the audit reports.
private static String saveLocation;
/**
* The class that runs as its own thread to generate the report.
*
* @author John Jenkins
*/
private final class GenerateReport implements Runnable {
/**
* Generates a report for the previous day.
*/
@Override
public void run() {
DateTime currentDate = new DateTime();
DateTime endDate =
new DateTime(
currentDate.getYear(),
currentDate.getMonthOfYear(),
currentDate.getDayOfMonth(),
0,
0);
DateTime startDate = endDate.minusDays(1);
// Use the service to aggregate the results.
List<Audit> audits;
try {
audits = AuditServices.instance().getAuditInformation(
null,
null,
null,
null,
null,
null,
startDate,
endDate);
}
catch(ServiceException e) {
- LOGGER.error("There was an error generating the audit inforamtion.", e);
+ LOGGER
+ .error(
+ "There was an error generating the audit information.",
+ e);
return;
}
long numberOfValidRequests = 0;
long numberOfInvalidRequests = 0;
long numberOfSuccessfulValidRequests = 0;
long numberOfFailedValidRequests = 0;
long timeToProcessValidRequests = 0;
Map<String, Integer> numberUriRequests = new HashMap<String, Integer>();
Map<String, Integer> numberCampaignReads = new HashMap<String, Integer>();
Map<String, Integer> numberClassReads = new HashMap<String, Integer>();
// Cycle through all of the audit entries.
for(Audit audit : audits) {
// First, get the URI and determine if the request is even
// valid.
String uri = audit.getUri();
// Either way, make a note of it in the list of URIs.
Integer uriCount = numberUriRequests.get(uri);
if(uriCount == null) {
numberUriRequests.put(uri, 1);
}
else {
numberUriRequests.put(uri, uriCount + 1);
}
// If the request is known, note it and continue processing.
if(RequestBuilder.getInstance().knownUri(uri)) {
numberOfValidRequests++;
// Calculate the time it took to process the request.
timeToProcessValidRequests += audit.getRespondedMillis() - audit.getReceivedMillis();
// Get the audit's response. If there is an issue parsing
// the response, note it and continue to the next audit.
JSONObject response = audit.getResponse();
String result;
try {
result = response.getString("result");
}
catch(JSONException e) {
LOGGER.error("Error reading an audit's response.");
continue;
}
// If the request was successful, continue evaluating the
// audit to see if any other substantial data was returned.
if("success".equals(result)) {
numberOfSuccessfulValidRequests++;
// Check if it's a class read request.
if(RequestBuilder.getInstance().getApiClassRead().equals(uri) ||
RequestBuilder.getInstance().getApiClassRosterRead().equals(uri)) {
// Get the class ID parameter if it exists.
Collection<String> classIdCollection = audit.getExtras(InputKeys.CLASS_URN);
if(classIdCollection != null) {
for(String classId : classIdCollection) {
Integer count = numberClassReads.get(classId);
if(count == null) {
numberClassReads.put(classId, 1);
}
else {
numberClassReads.put(classId, count + 1);
}
}
}
}
// Check if it's a campaign read request.
else if(RequestBuilder.getInstance().getApiCampaignRead().equals(uri)) {
Collection<String> campaignIdCollection = audit.getExtras(InputKeys.CAMPAIGN_URN);
if(campaignIdCollection != null) {
for(String campaignId : campaignIdCollection) {
Integer count = numberCampaignReads.get(campaignId);
if(count == null) {
numberCampaignReads.put(campaignId, 1);
}
else {
numberCampaignReads.put(campaignId, count + 1);
}
}
}
}
}
// If the request was unsuccessful, note it and move on to
// the next request.
else {
numberOfFailedValidRequests++;
}
}
// If the request is unknown, note it and move on to the next
// request.
else {
numberOfInvalidRequests++;
}
}
try {
// Retrieve the output file to write the results.
FileWriter fileWriter = new FileWriter(saveLocation + "/" + DateTimeUtils.getIso8601DateString(startDate, false));
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("invalid_requests=");
bufferedWriter.write(Long.toString(numberOfInvalidRequests));
bufferedWriter.write('\n');
bufferedWriter.write("valid_requests=");
bufferedWriter.write(Long.toString(numberOfValidRequests));
bufferedWriter.write('\n');
bufferedWriter.write("successful_valid_requests=");
bufferedWriter.write(Long.toString(numberOfSuccessfulValidRequests));
bufferedWriter.write('\n');
bufferedWriter.write("failed_valid_requests=");
bufferedWriter.write(Long.toString(numberOfFailedValidRequests));
bufferedWriter.write('\n');
bufferedWriter.write("average_request_time=");
if(numberOfValidRequests == 0) {
bufferedWriter.write('0');
}
else {
bufferedWriter.write(Long.toString(timeToProcessValidRequests / numberOfValidRequests));
}
bufferedWriter.write('\n');
bufferedWriter.write("number of requests per uri\n");
for(String uri : numberUriRequests.keySet()) {
bufferedWriter.write(uri);
bufferedWriter.write('=');
bufferedWriter.write(numberUriRequests.get(uri).toString());
bufferedWriter.write('\n');
}
bufferedWriter.write("number of reads per campaign ID\n");
for(String campaignId : numberCampaignReads.keySet()) {
bufferedWriter.write(campaignId);
bufferedWriter.write('=');
bufferedWriter.write(numberCampaignReads.get(campaignId).toString());
bufferedWriter.write('\n');
}
bufferedWriter.write("number of reads per class ID\n");
for(String classId : numberClassReads.keySet()) {
bufferedWriter.write(classId);
bufferedWriter.write('=');
bufferedWriter.write(numberClassReads.get(classId).toString());
bufferedWriter.write('\n');
}
bufferedWriter.flush();
bufferedWriter.close();
fileWriter.close();
}
catch(IOException e) {
LOGGER.error("Error while writing the audit information.", e);
}
}
}
/**
* Starts a timer task to generate a report at the beginning of every day.
*/
private AuditReporter() {
try {
// Get the location to save the audit logs.
saveLocation =
PreferenceCache.instance().lookup(
PreferenceCache.KEY_AUDIT_LOG_LOCATION);
}
catch(CacheMissException e) {
throw new IllegalStateException(
"The audit log location is missing: " +
PreferenceCache.KEY_AUDIT_LOG_LOCATION,
e);
}
try {
// If it doesn't exist, create it. If it does exist, make sure it's a
// directory.
File saveFolder = new File(saveLocation);
if(! saveFolder.exists()) {
saveFolder.mkdir();
}
else if(! saveFolder.isDirectory()) {
throw new IllegalStateException(
"The directory that is to be used for saving the audit reports exists but isn't a directory: " +
saveLocation);
}
}
catch(SecurityException e) {
throw new IllegalStateException(
"We are not allowed to read or write in the specified directory.",
e);
}
// Generate the number of milliseconds until the first run.
Calendar firstRun = Calendar.getInstance();
// Fast-forward to the beginning of the next day.
firstRun.add(Calendar.DAY_OF_YEAR, 1);
// Reset the hours, minutes, seconds, and milliseconds.
firstRun.set(Calendar.HOUR_OF_DAY, 0);
firstRun.set(Calendar.MINUTE, 0);
firstRun.set(Calendar.SECOND, 0);
firstRun.set(Calendar.MILLISECOND, 0);
// Calculate the time between now and when the task should first run.
long initialDelay =
firstRun.getTimeInMillis() -
Calendar.getInstance().getTimeInMillis();
// Begin the task.
Executors.newScheduledThreadPool(THREAD_POOL_SIZE).scheduleAtFixedRate(
new GenerateReport(),
initialDelay,
MILLIS_IN_A_DAY,
TimeUnit.MILLISECONDS);
}
}
| true | true | public void run() {
DateTime currentDate = new DateTime();
DateTime endDate =
new DateTime(
currentDate.getYear(),
currentDate.getMonthOfYear(),
currentDate.getDayOfMonth(),
0,
0);
DateTime startDate = endDate.minusDays(1);
// Use the service to aggregate the results.
List<Audit> audits;
try {
audits = AuditServices.instance().getAuditInformation(
null,
null,
null,
null,
null,
null,
startDate,
endDate);
}
catch(ServiceException e) {
LOGGER.error("There was an error generating the audit inforamtion.", e);
return;
}
long numberOfValidRequests = 0;
long numberOfInvalidRequests = 0;
long numberOfSuccessfulValidRequests = 0;
long numberOfFailedValidRequests = 0;
long timeToProcessValidRequests = 0;
Map<String, Integer> numberUriRequests = new HashMap<String, Integer>();
Map<String, Integer> numberCampaignReads = new HashMap<String, Integer>();
Map<String, Integer> numberClassReads = new HashMap<String, Integer>();
// Cycle through all of the audit entries.
for(Audit audit : audits) {
// First, get the URI and determine if the request is even
// valid.
String uri = audit.getUri();
// Either way, make a note of it in the list of URIs.
Integer uriCount = numberUriRequests.get(uri);
if(uriCount == null) {
numberUriRequests.put(uri, 1);
}
else {
numberUriRequests.put(uri, uriCount + 1);
}
// If the request is known, note it and continue processing.
if(RequestBuilder.getInstance().knownUri(uri)) {
numberOfValidRequests++;
// Calculate the time it took to process the request.
timeToProcessValidRequests += audit.getRespondedMillis() - audit.getReceivedMillis();
// Get the audit's response. If there is an issue parsing
// the response, note it and continue to the next audit.
JSONObject response = audit.getResponse();
String result;
try {
result = response.getString("result");
}
catch(JSONException e) {
LOGGER.error("Error reading an audit's response.");
continue;
}
// If the request was successful, continue evaluating the
// audit to see if any other substantial data was returned.
if("success".equals(result)) {
numberOfSuccessfulValidRequests++;
// Check if it's a class read request.
if(RequestBuilder.getInstance().getApiClassRead().equals(uri) ||
RequestBuilder.getInstance().getApiClassRosterRead().equals(uri)) {
// Get the class ID parameter if it exists.
Collection<String> classIdCollection = audit.getExtras(InputKeys.CLASS_URN);
if(classIdCollection != null) {
for(String classId : classIdCollection) {
Integer count = numberClassReads.get(classId);
if(count == null) {
numberClassReads.put(classId, 1);
}
else {
numberClassReads.put(classId, count + 1);
}
}
}
}
// Check if it's a campaign read request.
else if(RequestBuilder.getInstance().getApiCampaignRead().equals(uri)) {
Collection<String> campaignIdCollection = audit.getExtras(InputKeys.CAMPAIGN_URN);
if(campaignIdCollection != null) {
for(String campaignId : campaignIdCollection) {
Integer count = numberCampaignReads.get(campaignId);
if(count == null) {
numberCampaignReads.put(campaignId, 1);
}
else {
numberCampaignReads.put(campaignId, count + 1);
}
}
}
}
}
// If the request was unsuccessful, note it and move on to
// the next request.
else {
numberOfFailedValidRequests++;
}
}
// If the request is unknown, note it and move on to the next
// request.
else {
numberOfInvalidRequests++;
}
}
try {
// Retrieve the output file to write the results.
FileWriter fileWriter = new FileWriter(saveLocation + "/" + DateTimeUtils.getIso8601DateString(startDate, false));
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("invalid_requests=");
bufferedWriter.write(Long.toString(numberOfInvalidRequests));
bufferedWriter.write('\n');
bufferedWriter.write("valid_requests=");
bufferedWriter.write(Long.toString(numberOfValidRequests));
bufferedWriter.write('\n');
bufferedWriter.write("successful_valid_requests=");
bufferedWriter.write(Long.toString(numberOfSuccessfulValidRequests));
bufferedWriter.write('\n');
bufferedWriter.write("failed_valid_requests=");
bufferedWriter.write(Long.toString(numberOfFailedValidRequests));
bufferedWriter.write('\n');
bufferedWriter.write("average_request_time=");
if(numberOfValidRequests == 0) {
bufferedWriter.write('0');
}
else {
bufferedWriter.write(Long.toString(timeToProcessValidRequests / numberOfValidRequests));
}
bufferedWriter.write('\n');
bufferedWriter.write("number of requests per uri\n");
for(String uri : numberUriRequests.keySet()) {
bufferedWriter.write(uri);
bufferedWriter.write('=');
bufferedWriter.write(numberUriRequests.get(uri).toString());
bufferedWriter.write('\n');
}
bufferedWriter.write("number of reads per campaign ID\n");
for(String campaignId : numberCampaignReads.keySet()) {
bufferedWriter.write(campaignId);
bufferedWriter.write('=');
bufferedWriter.write(numberCampaignReads.get(campaignId).toString());
bufferedWriter.write('\n');
}
bufferedWriter.write("number of reads per class ID\n");
for(String classId : numberClassReads.keySet()) {
bufferedWriter.write(classId);
bufferedWriter.write('=');
bufferedWriter.write(numberClassReads.get(classId).toString());
bufferedWriter.write('\n');
}
bufferedWriter.flush();
bufferedWriter.close();
fileWriter.close();
}
catch(IOException e) {
LOGGER.error("Error while writing the audit information.", e);
}
}
| public void run() {
DateTime currentDate = new DateTime();
DateTime endDate =
new DateTime(
currentDate.getYear(),
currentDate.getMonthOfYear(),
currentDate.getDayOfMonth(),
0,
0);
DateTime startDate = endDate.minusDays(1);
// Use the service to aggregate the results.
List<Audit> audits;
try {
audits = AuditServices.instance().getAuditInformation(
null,
null,
null,
null,
null,
null,
startDate,
endDate);
}
catch(ServiceException e) {
LOGGER
.error(
"There was an error generating the audit information.",
e);
return;
}
long numberOfValidRequests = 0;
long numberOfInvalidRequests = 0;
long numberOfSuccessfulValidRequests = 0;
long numberOfFailedValidRequests = 0;
long timeToProcessValidRequests = 0;
Map<String, Integer> numberUriRequests = new HashMap<String, Integer>();
Map<String, Integer> numberCampaignReads = new HashMap<String, Integer>();
Map<String, Integer> numberClassReads = new HashMap<String, Integer>();
// Cycle through all of the audit entries.
for(Audit audit : audits) {
// First, get the URI and determine if the request is even
// valid.
String uri = audit.getUri();
// Either way, make a note of it in the list of URIs.
Integer uriCount = numberUriRequests.get(uri);
if(uriCount == null) {
numberUriRequests.put(uri, 1);
}
else {
numberUriRequests.put(uri, uriCount + 1);
}
// If the request is known, note it and continue processing.
if(RequestBuilder.getInstance().knownUri(uri)) {
numberOfValidRequests++;
// Calculate the time it took to process the request.
timeToProcessValidRequests += audit.getRespondedMillis() - audit.getReceivedMillis();
// Get the audit's response. If there is an issue parsing
// the response, note it and continue to the next audit.
JSONObject response = audit.getResponse();
String result;
try {
result = response.getString("result");
}
catch(JSONException e) {
LOGGER.error("Error reading an audit's response.");
continue;
}
// If the request was successful, continue evaluating the
// audit to see if any other substantial data was returned.
if("success".equals(result)) {
numberOfSuccessfulValidRequests++;
// Check if it's a class read request.
if(RequestBuilder.getInstance().getApiClassRead().equals(uri) ||
RequestBuilder.getInstance().getApiClassRosterRead().equals(uri)) {
// Get the class ID parameter if it exists.
Collection<String> classIdCollection = audit.getExtras(InputKeys.CLASS_URN);
if(classIdCollection != null) {
for(String classId : classIdCollection) {
Integer count = numberClassReads.get(classId);
if(count == null) {
numberClassReads.put(classId, 1);
}
else {
numberClassReads.put(classId, count + 1);
}
}
}
}
// Check if it's a campaign read request.
else if(RequestBuilder.getInstance().getApiCampaignRead().equals(uri)) {
Collection<String> campaignIdCollection = audit.getExtras(InputKeys.CAMPAIGN_URN);
if(campaignIdCollection != null) {
for(String campaignId : campaignIdCollection) {
Integer count = numberCampaignReads.get(campaignId);
if(count == null) {
numberCampaignReads.put(campaignId, 1);
}
else {
numberCampaignReads.put(campaignId, count + 1);
}
}
}
}
}
// If the request was unsuccessful, note it and move on to
// the next request.
else {
numberOfFailedValidRequests++;
}
}
// If the request is unknown, note it and move on to the next
// request.
else {
numberOfInvalidRequests++;
}
}
try {
// Retrieve the output file to write the results.
FileWriter fileWriter = new FileWriter(saveLocation + "/" + DateTimeUtils.getIso8601DateString(startDate, false));
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("invalid_requests=");
bufferedWriter.write(Long.toString(numberOfInvalidRequests));
bufferedWriter.write('\n');
bufferedWriter.write("valid_requests=");
bufferedWriter.write(Long.toString(numberOfValidRequests));
bufferedWriter.write('\n');
bufferedWriter.write("successful_valid_requests=");
bufferedWriter.write(Long.toString(numberOfSuccessfulValidRequests));
bufferedWriter.write('\n');
bufferedWriter.write("failed_valid_requests=");
bufferedWriter.write(Long.toString(numberOfFailedValidRequests));
bufferedWriter.write('\n');
bufferedWriter.write("average_request_time=");
if(numberOfValidRequests == 0) {
bufferedWriter.write('0');
}
else {
bufferedWriter.write(Long.toString(timeToProcessValidRequests / numberOfValidRequests));
}
bufferedWriter.write('\n');
bufferedWriter.write("number of requests per uri\n");
for(String uri : numberUriRequests.keySet()) {
bufferedWriter.write(uri);
bufferedWriter.write('=');
bufferedWriter.write(numberUriRequests.get(uri).toString());
bufferedWriter.write('\n');
}
bufferedWriter.write("number of reads per campaign ID\n");
for(String campaignId : numberCampaignReads.keySet()) {
bufferedWriter.write(campaignId);
bufferedWriter.write('=');
bufferedWriter.write(numberCampaignReads.get(campaignId).toString());
bufferedWriter.write('\n');
}
bufferedWriter.write("number of reads per class ID\n");
for(String classId : numberClassReads.keySet()) {
bufferedWriter.write(classId);
bufferedWriter.write('=');
bufferedWriter.write(numberClassReads.get(classId).toString());
bufferedWriter.write('\n');
}
bufferedWriter.flush();
bufferedWriter.close();
fileWriter.close();
}
catch(IOException e) {
LOGGER.error("Error while writing the audit information.", e);
}
}
|
diff --git a/test/api/org/openmrs/test/logic/LogicServiceTest.java b/test/api/org/openmrs/test/logic/LogicServiceTest.java
index fdb3816a..5cbb8611 100644
--- a/test/api/org/openmrs/test/logic/LogicServiceTest.java
+++ b/test/api/org/openmrs/test/logic/LogicServiceTest.java
@@ -1,366 +1,366 @@
package org.openmrs.test.logic;
import java.util.Calendar;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Cohort;
import org.openmrs.Patient;
import org.openmrs.api.context.Context;
import org.openmrs.logic.Duration;
import org.openmrs.logic.LogicCriteria;
import org.openmrs.logic.LogicException;
import org.openmrs.logic.LogicService;
import org.openmrs.logic.result.Result;
import org.openmrs.test.BaseContextSensitiveTest;
/**
* TODO: add more tests to this test case
*/
public class LogicServiceTest extends BaseContextSensitiveTest {
private Log log = LogFactory.getLog(this.getClass());
/**
* @see org.springframework.test.AbstractTransactionalSpringContextTests#onSetUpInTransaction()
*/
@Override
protected void onSetUpInTransaction() throws Exception {
initializeInMemoryDatabase();
executeDataSet("org/openmrs/test/logic/include/LogicTests-patients.xml");
executeDataSet("org/openmrs/test/logic/include/LogicBasicTest.concepts.xml");
authenticate();
}
/**
* TODO make this test use assert statements instead of printing to stdout
*
*/
public void testObservationRule() {
LogicService logicService = Context.getLogicService();
Cohort patients = new Cohort();
Map<Integer, Result> result = null;
patients.addMember(2);
try {
log.error("Evaluating CD4 COUNT"); // for a single patient
Result r = logicService.eval(new Patient(2), "CD4 COUNT");
log.error("PatientID: 2 " + r);
log.error("Evaluating CD4 COUNT");
result = logicService.eval(patients, "CD4 COUNT");
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT < 170");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.lt(170));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT > 185");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.gt(185));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT EQUALS 190");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.equalTo(190));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT BEFORE 2006-04-11");
Calendar cal = Calendar.getInstance();
cal.set(2006, 3, 11);
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.before(cal.getTime()));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT < 190 BEFORE 2006-04-11");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.lt(190).before(cal.getTime()));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT AFTER 2006-04-11");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.after(cal.getTime()));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating LAST CD4 COUNT");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.last());
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating LAST CD4 COUNT BEFORE 2006-4-11");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.last().before(cal.getTime()));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating NOT CD4 COUNT < 150");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.not().lt(150));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating NOT NOT CD4 COUNT < 150");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.not().not().lt(150));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT < 200");
- patients.addMember(2994);
- patients.addMember(2004);
+ patients.addMember(2);
+ patients.addMember(3);
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.lt(200));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
patients.addMember(39);
log
.error("Evaluating PROBLEM ADDED ASNWERED BY HUMAN IMMUNODEFICIENCY VIRUS");
result = logicService.eval(patients, new LogicCriteria(
"PROBLEM ADDED").contains("HUMAN IMMUNODEFICIENCY VIRUS"));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
// test the index date functionality
// Calendar index = Calendar.getInstance();
// index.set(2006, 3, 1);
// logicService.setIndexDate(index.getTime());
log.error("Evaluating CD4 COUNT AS OF 2006-04-01");
result = logicService.eval(patients, "CD4 COUNT");
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT AS OF 2006-04-01, WITHIN 1 MONTH");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.within(Duration.months(1)));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
// set it back to today
// logicService.resetIndexDate();
} catch (LogicException e) {
log.error("testObservationRule: Error generated", e);
}
}
/**
* TODO make this test use assert statements instead of printing to stdout
*
*/
public void testDemographicsRule() {
LogicService logicService = Context.getLogicService();
Cohort patients = new Cohort();
Map<Integer, Result> result;
patients.addMember(2);
//patients.addMember(9342);
//patients.addMember(9170);
//patients.addMember(39);
try {
log.error("Evaluating BIRTHDATE");
result = logicService.eval(patients, "BIRTHDATE");
for (Integer id : result.keySet())
log.error("Patient ID: " + id + " " + result.get(id));
log.error("Evaluating AGE");
result = logicService.eval(patients, "AGE");
for (Integer id : result.keySet())
log.error("Patient ID: " + id + " " + result.get(id));
log.error("Evaluating AGE > 10");
result = logicService.eval(patients, new LogicCriteria("AGE")
.gt(10));
for (Integer id : result.keySet())
log.error("Patient ID: " + id + " " + result.get(id));
log.error("Evaluating BIRTHDATE AFTER 2000");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2000);
result = logicService.eval(patients, new LogicCriteria("BIRTHDATE")
.after(cal.getTime()));
for (Integer id : result.keySet())
log.error("Patient ID: " + id + " " + result.get(id));
log.error("Evaluating BIRTHDATE BEFORE 2000");
result = logicService.eval(patients, new LogicCriteria("BIRTHDATE")
.before(cal.getTime()));
for (Integer id : result.keySet())
log.error("Patient ID: " + id + " " + result.get(id));
// test the index date functionality
Calendar index = Calendar.getInstance();
index.set(1970, 0, 1);
// logicService.setIndexDate(index.getTime());
log.error("Evaluating BIRTHDATE AS OF 1970-01-01");
result = logicService.eval(patients, "BIRTHDATE");
for (Integer id : result.keySet())
log.error("Patient ID: " + id + " " + result.get(id));
log.error("Evaluating BIRTHDATE AS OF 1970-01-01, WITHIN 5 YEARS");
result = logicService.eval(patients, new LogicCriteria("BIRTHDATE")
.within(Duration.years(5)));
for (Integer id : result.keySet())
log.error("Patient ID: " + id + " " + result.get(id));
// set it back to today
// logicService.resetIndexDate();
} catch (LogicException e) {
log.error("testDemographicsRule: Error generated", e);
}
}
/**
* TODO make this test use assert statements instead of printing to stdout
*
*/
public void testHIVPositiveRule() {
LogicService logicService = Context.getLogicService();
Cohort patients = new Cohort();
Map<Integer, Result> result = null;
patients.addMember(2);
//patients.addMember(9342);
//patients.addMember(9170);
//patients.addMember(39);
try {
log.error("Evaluating FIRST HUMAN IMMUNODEFICIENCY VIRUS");
result = logicService.eval(patients, new LogicCriteria(
"PROBLEM ADDED").contains("HUMAN IMMUNODEFICIENCY VIRUS")
.first());
for (Integer id : result.keySet()) {
log.error("Patient ID: " + id + " " + result.get(id));
}
log.error("Evaluating FIRST HIV INFECTED");
result = logicService.eval(patients, new LogicCriteria(
"PROBLEM ADDED").contains("HIV INFECTED").first());
for (Integer id : result.keySet()) {
log.error("Patient ID: " + id + " " + result.get(id));
}
log.error("Evaluating FIRST ASYMPTOMATIC HIV INFECTION");
result = logicService.eval(patients, new LogicCriteria(
"PROBLEM ADDED").contains("ASYMPTOMATIC HIV INFECTION")
.first());
for (Integer id : result.keySet()) {
log.error("Patient ID: " + id + " " + result.get(id));
}
log.error("Evaluating FIRST HIV VIRAL LOAD");
result = logicService.eval(patients, new LogicCriteria(
"HIV VIRAL LOAD").first());
for (Integer id : result.keySet()) {
log.error("Patient ID: " + id + " " + result.get(id));
}
log.error("Evaluating FIRST HIV VIRAL LOAD, QUALITATIVE");
result = logicService.eval(patients, new LogicCriteria(
"HIV VIRAL LOAD, QUALITATIVE").first());
for (Integer id : result.keySet()) {
log.error("Patient ID: " + id + " " + result.get(id));
}
log.error("Evaluating FIRST CD4 COUNT < 200");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.lt(200).first());
for (Integer id : result.keySet()) {
log.error("Patient ID: " + id + " " + result.get(id));
}
log.error("Evaluating HIV POSITIVE");
result = logicService.eval(patients, "HIV POSITIVE");
for (Integer id : result.keySet()) {
log.error("Patient ID: " + id + " " + result.get(id));
}
} catch (LogicException e) {
log.error("Error generated", e);
}
}
/**
* TODO make this test use assert statements instead of printing to stdout
*
*/
public void testReferenceRule() {
LogicService logicService = Context.getLogicService();
Cohort patients = new Cohort();
Map<Integer, Result> result = null;
patients.addMember(2);
//patients.addMember(9342);
//patients.addMember(9170);
//patients.addMember(39);
try {
log.error("Evaluating ${OBS::CD4 COUNT}");
result = logicService.eval(patients, "${OBS::CD4 COUNT}");
for (Integer id : result.keySet()) {
log.error("Patient ID: " + id + " " + result.get(id));
}
log.error("Evaluating FIRST ${OBS::CD4 COUNT}");
result = logicService.eval(patients, new LogicCriteria(
"${OBS::CD4 COUNT}").first());
for (Integer id : result.keySet()) {
log.error("Patient ID: " + id + " " + result.get(id));
}
log.error("Evaluating ${PERSON::BIRTHDATE}");
result = logicService.eval(patients, "${PERSON::BIRTHDATE}");
for (Integer id : result.keySet()) {
log.error("Patient ID: " + id + " " + result.get(id));
}
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1980);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
log.error("Evaluating ${PERSON::BIRTHDATE} BEFORE 1980-01-01");
result = logicService.eval(patients, new LogicCriteria(
"${PERSON::BIRTHDATE}").before(cal.getTime()));
for (Integer id : result.keySet()) {
log.error("Patient ID: " + id + " " + result.get(id));
}
} catch (LogicException e) {
log.error("Error generated", e);
}
}
}
| true | true | public void testObservationRule() {
LogicService logicService = Context.getLogicService();
Cohort patients = new Cohort();
Map<Integer, Result> result = null;
patients.addMember(2);
try {
log.error("Evaluating CD4 COUNT"); // for a single patient
Result r = logicService.eval(new Patient(2), "CD4 COUNT");
log.error("PatientID: 2 " + r);
log.error("Evaluating CD4 COUNT");
result = logicService.eval(patients, "CD4 COUNT");
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT < 170");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.lt(170));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT > 185");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.gt(185));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT EQUALS 190");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.equalTo(190));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT BEFORE 2006-04-11");
Calendar cal = Calendar.getInstance();
cal.set(2006, 3, 11);
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.before(cal.getTime()));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT < 190 BEFORE 2006-04-11");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.lt(190).before(cal.getTime()));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT AFTER 2006-04-11");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.after(cal.getTime()));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating LAST CD4 COUNT");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.last());
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating LAST CD4 COUNT BEFORE 2006-4-11");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.last().before(cal.getTime()));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating NOT CD4 COUNT < 150");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.not().lt(150));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating NOT NOT CD4 COUNT < 150");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.not().not().lt(150));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT < 200");
patients.addMember(2994);
patients.addMember(2004);
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.lt(200));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
patients.addMember(39);
log
.error("Evaluating PROBLEM ADDED ASNWERED BY HUMAN IMMUNODEFICIENCY VIRUS");
result = logicService.eval(patients, new LogicCriteria(
"PROBLEM ADDED").contains("HUMAN IMMUNODEFICIENCY VIRUS"));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
// test the index date functionality
// Calendar index = Calendar.getInstance();
// index.set(2006, 3, 1);
// logicService.setIndexDate(index.getTime());
log.error("Evaluating CD4 COUNT AS OF 2006-04-01");
result = logicService.eval(patients, "CD4 COUNT");
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT AS OF 2006-04-01, WITHIN 1 MONTH");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.within(Duration.months(1)));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
// set it back to today
// logicService.resetIndexDate();
} catch (LogicException e) {
log.error("testObservationRule: Error generated", e);
}
}
| public void testObservationRule() {
LogicService logicService = Context.getLogicService();
Cohort patients = new Cohort();
Map<Integer, Result> result = null;
patients.addMember(2);
try {
log.error("Evaluating CD4 COUNT"); // for a single patient
Result r = logicService.eval(new Patient(2), "CD4 COUNT");
log.error("PatientID: 2 " + r);
log.error("Evaluating CD4 COUNT");
result = logicService.eval(patients, "CD4 COUNT");
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT < 170");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.lt(170));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT > 185");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.gt(185));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT EQUALS 190");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.equalTo(190));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT BEFORE 2006-04-11");
Calendar cal = Calendar.getInstance();
cal.set(2006, 3, 11);
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.before(cal.getTime()));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT < 190 BEFORE 2006-04-11");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.lt(190).before(cal.getTime()));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT AFTER 2006-04-11");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.after(cal.getTime()));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating LAST CD4 COUNT");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.last());
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating LAST CD4 COUNT BEFORE 2006-4-11");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.last().before(cal.getTime()));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating NOT CD4 COUNT < 150");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.not().lt(150));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating NOT NOT CD4 COUNT < 150");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.not().not().lt(150));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT < 200");
patients.addMember(2);
patients.addMember(3);
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.lt(200));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
patients.addMember(39);
log
.error("Evaluating PROBLEM ADDED ASNWERED BY HUMAN IMMUNODEFICIENCY VIRUS");
result = logicService.eval(patients, new LogicCriteria(
"PROBLEM ADDED").contains("HUMAN IMMUNODEFICIENCY VIRUS"));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
// test the index date functionality
// Calendar index = Calendar.getInstance();
// index.set(2006, 3, 1);
// logicService.setIndexDate(index.getTime());
log.error("Evaluating CD4 COUNT AS OF 2006-04-01");
result = logicService.eval(patients, "CD4 COUNT");
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
log.error("Evaluating CD4 COUNT AS OF 2006-04-01, WITHIN 1 MONTH");
result = logicService.eval(patients, new LogicCriteria("CD4 COUNT")
.within(Duration.months(1)));
for (Integer id : result.keySet()) {
log.error("PatientID: " + id + " " + result.get(id));
}
// set it back to today
// logicService.resetIndexDate();
} catch (LogicException e) {
log.error("testObservationRule: Error generated", e);
}
}
|
diff --git a/org.osate.aadl2.errormodel.analysis/src/org/osate/aadl2/errormodel/analysis/PropagateErrorSources.java b/org.osate.aadl2.errormodel.analysis/src/org/osate/aadl2/errormodel/analysis/PropagateErrorSources.java
index cfa1a7d0..296f8b83 100644
--- a/org.osate.aadl2.errormodel.analysis/src/org/osate/aadl2/errormodel/analysis/PropagateErrorSources.java
+++ b/org.osate.aadl2.errormodel.analysis/src/org/osate/aadl2/errormodel/analysis/PropagateErrorSources.java
@@ -1,574 +1,577 @@
/*
* <copyright>
* Copyright 2012 by Carnegie Mellon University, all rights reserved.
*
* Use of the Open Source AADL Tool Environment (OSATE) is subject to the terms of the license set forth
* at http://www.eclipse.org/org/documents/epl-v10.html.
*
* NO WARRANTY
*
* ANY INFORMATION, MATERIALS, SERVICES, INTELLECTUAL PROPERTY OR OTHER PROPERTY OR RIGHTS GRANTED OR PROVIDED BY
* CARNEGIE MELLON UNIVERSITY PURSUANT TO THIS LICENSE (HEREINAFTER THE "DELIVERABLES") ARE ON AN "AS-IS" BASIS.
* CARNEGIE MELLON UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED AS TO ANY MATTER INCLUDING,
* BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, INFORMATIONAL CONTENT,
* NONINFRINGEMENT, OR ERROR-FREE OPERATION. CARNEGIE MELLON UNIVERSITY SHALL NOT BE LIABLE FOR INDIRECT, SPECIAL OR
* CONSEQUENTIAL DAMAGES, SUCH AS LOSS OF PROFITS OR INABILITY TO USE SAID INTELLECTUAL PROPERTY, UNDER THIS LICENSE,
* REGARDLESS OF WHETHER SUCH PARTY WAS AWARE OF THE POSSIBILITY OF SUCH DAMAGES. LICENSEE AGREES THAT IT WILL NOT
* MAKE ANY WARRANTY ON BEHALF OF CARNEGIE MELLON UNIVERSITY, EXPRESS OR IMPLIED, TO ANY PERSON CONCERNING THE
* APPLICATION OF OR THE RESULTS TO BE OBTAINED WITH THE DELIVERABLES UNDER THIS LICENSE.
*
* Licensee hereby agrees to defend, indemnify, and hold harmless Carnegie Mellon University, its trustees, officers,
* employees, and agents from all claims or demands made against them (and any related losses, expenses, or
* attorney's fees) arising out of, or relating to Licensee's and/or its sub licensees' negligent use or willful
* misuse of or negligent conduct or willful misconduct regarding the Software, facilities, or other rights or
* assistance granted by Carnegie Mellon University under this License, including, but not limited to, any claims of
* product liability, personal injury, death, damage to property, or violation of any laws or regulations.
*
* Carnegie Mellon Carnegie Mellon University Software Engineering Institute authored documents are sponsored by the U.S. Department
* of Defense under Contract F19628-00-C-0003. Carnegie Mellon University retains copyrights in all material produced
* under this contract. The U.S. Government retains a non-exclusive, royalty-free license to publish or reproduce these
* documents, or allow others to do so, for U.S. Government purposes only pursuant to the copyright license
* under the contract clause at 252.227.7013.
* </copyright>
*/
package org.osate.aadl2.errormodel.analysis;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.UniqueEList;
import org.eclipse.emf.ecore.EObject;
import org.osate.aadl2.instance.ComponentInstance;
import org.osate.aadl2.instance.ConnectionInstanceEnd;
import org.osate.aadl2.instance.FeatureInstance;
import org.osate.aadl2.instance.FlowSpecificationInstance;
import org.osate.aadl2.instance.InstanceObject;
import org.osate.aadl2.modelsupport.WriteToFile;
import org.osate.xtext.aadl2.errormodel.errorModel.ConditionElement;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorBehaviorEvent;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorBehaviorState;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorBehaviorStateOrTypeSet;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorBehaviorTransition;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorFlow;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorPath;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorPropagation;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorSink;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorSource;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorType;
import org.osate.xtext.aadl2.errormodel.errorModel.OutgoingPropagationCondition;
import org.osate.xtext.aadl2.errormodel.errorModel.TypeSet;
import org.osate.xtext.aadl2.errormodel.errorModel.TypeToken;
import org.osate.xtext.aadl2.errormodel.util.AnalysisModel;
import org.osate.xtext.aadl2.errormodel.util.EM2TypeSetUtil;
import org.osate.xtext.aadl2.errormodel.util.EMV2Util;
import org.osate.xtext.aadl2.errormodel.util.ErrorModelState;
import org.osate.xtext.aadl2.errormodel.util.ErrorModelStateAdapterFactory;
import org.osate.xtext.aadl2.errormodel.util.PropagationPath;
/**
* @author phf
*/
public class PropagateErrorSources {
protected WriteToFile report ;
protected AnalysisModel faultModel ;
protected EList<EObject> visited ;
protected int maxLevel = 7;
private Map<ComponentInstance,List<String>> alreadyTreated;
public PropagateErrorSources(String reportType, ComponentInstance root){
report = new WriteToFile(reportType, root);
faultModel = new AnalysisModel(root);
visited = new UniqueEList<EObject>();
alreadyTreated = new HashMap<ComponentInstance,List<String>>();
}
public PropagateErrorSources(String reportType, ComponentInstance root, int maxLevel){
this (reportType,root);
this.maxLevel = maxLevel;
}
public void setMaxDepth(int maxLevel){
this.maxLevel = maxLevel;
}
public EList<ComponentInstance> getSubcomponents() {
return faultModel.getSubcomponents();
}
public void addText(String text){
if (report != null)
report.addOutput(text);
}
public int getMaxLevel(){
return this.maxLevel;
}
public void addTextNewline(String text){
if (report != null)
report.addOutputNewline(text);
}
public void addNewline(){
if (report != null)
report.addOutputNewline("");
}
public void saveReport(){
report.saveToFile();
}
public void reportHeading( ){
report.addOutput("Component, Initial Failure Mode, 1st Level Effect");
for (int i = 2; i <= this.maxLevel; i++) {
report.addOutput(", Failure Mode, "+(i==2?"second":i==3?"third":Integer.toString(i)+"th")+" Level Effect");
}
report.addOutputNewline(", More");
}
/**
* Put an entry into the report based on the prefix, entryText and any postfix processing based on level
* @param entryText String assumed to provide any comma before each entry
* @param curLevel last level reported
*/
public void reportEntry(String entryText,int curLevel){
report.addOutputNewline(entryText);
// for (int i = curLevel; i < maxLevel; i++) {
// report.addOutput(", , ");
// }
// report.addOutputNewline(", "+"Severe");
}
/**
* traverse error flow if the component instance is an error source
* @param ci component instance
*/
public void startErrorFlows(ComponentInstance ci)
{
Collection<ErrorSource> eslist = EMV2Util.getAllErrorSources(ci.getComponentClassifier());
String componentText = generateItemText(ci);
List<ErrorType> handledTypes = new ArrayList<ErrorType>();
for (ErrorBehaviorEvent event : EMV2Util.getAllErrorBehaviorEvents(ci))
{
List<ErrorBehaviorState> states = new ArrayList<ErrorBehaviorState> ();
for (ErrorBehaviorTransition trans : EMV2Util.getAllErrorBehaviorTransitions(ci))
{
if (trans.getCondition() instanceof ConditionElement)
{
ConditionElement conditionElement = (ConditionElement) trans.getCondition();
if (conditionElement.getIncoming() instanceof ErrorPropagation)
{
continue;
}
if (conditionElement.getIncoming().getName().equalsIgnoreCase(event.getName()))
{
states.add (trans.getTarget());
}
}
}
for (OutgoingPropagationCondition opc : EMV2Util.getAllOutgoingPropagationConditions(ci))
{
if (opc.getTypeToken().isNoError())
{
continue;
}
boolean used = false;
for (ErrorBehaviorState s : states)
{
if (s.getName().equalsIgnoreCase(opc.getState().getName()))
{
used = true;
}
}
if (used)
{
ErrorPropagation ep = opc.getOutgoing();
TypeSet ts = opc.getTypeTokenConstraint();
if (ts == null)
{
ts = ep.getTypeSet();
}
ErrorBehaviorState failureMode = null;
EList<TypeToken> result = EM2TypeSetUtil.generateAllLeafTypeTokens(ts, EMV2Util.getContainingTypeUseContext(ep));
for (TypeToken typeToken : result)
{
for (int i = 0 ; i < typeToken.getType().size() ; i++)
{
handledTypes.add (typeToken.getType().get(i));
}
String failuremodeText = generateOriginalFailureModeText(failureMode!=null?failureMode:typeToken);
traceErrorPaths(ci,ep,typeToken,2,componentText+", "+ "internal event " + event.getName());
}
//OsateDebug.osateDebug("event=" + event.getName() + "state=" + opc.getState().getName() + "|outgoing=" + opc.getOutgoing());
}
}
}
for (ErrorSource errorSource : eslist)
{
Collection<ErrorPropagation> eplist = EMV2Util.getOutgoingPropagationOrAll(errorSource);
TypeSet ts = errorSource.getTypeTokenConstraint();
ErrorBehaviorStateOrTypeSet fmr = errorSource.getFailureModeReference();
ErrorBehaviorState failureMode = null;
if (fmr instanceof ErrorBehaviorState){
// XXX TODO how about the other case
failureMode = (ErrorBehaviorState) fmr;
}
for (ErrorPropagation ep : eplist){
TypeSet tsep = ep.getTypeSet();
EList<TypeToken> result = ts!=null?ts.getTypeTokens():tsep.getTypeTokens();
//EM2TypeSetUtil.generateAllLeafTypeTokens(ts,EMV2Util.getContainingTypeUseContext(errorSource));
for (TypeToken typeToken : result)
{
String failuremodeText = generateOriginalFailureModeText(failureMode!=null?failureMode:typeToken);
if (failureMode == null)
{
for (int i = 0 ; i < typeToken.getType().size() ; i++)
{
if (! handledTypes.contains (typeToken.getType().get(i)))
{
traceErrorPaths(ci,ep,typeToken,2,componentText+", "+failuremodeText);
}
}
}
else
{
traceErrorPaths(ci,ep,typeToken,2,componentText+", "+failuremodeText);
}
}
}
}
}
/**
* get the text to be used for the item (Component or feature)
* that is the source of a failure mode
* @param ci component instance
* @return String
*/
public String generateItemText(ConnectionInstanceEnd io)
{
String result;
if (io instanceof FeatureInstance)
{
FeatureInstance fi = (FeatureInstance)io;
ComponentInstance ci = fi.getContainingComponentInstance();
result = ci.getQualifiedName()+"."+fi.getName();
}
else if (io instanceof ComponentInstance)
{
ComponentInstance ci = (ComponentInstance)io;
if ((ci.getContainingComponentInstance() != null) && (ci.getContainingComponentInstance() != ci.getSystemInstance()))
{
result = ci.getContainingComponentInstance().getName() + "/" + ci.getName();
}
else
{
result = ci.getQualifiedName();
}
}
else
{
result = io.getName();
}
return result;
}
/**
* get the text for the failure mode
* @param io Error State or Type token
* @return String
*/
public String generateOriginalFailureModeText(EObject io){
if (io instanceof ErrorBehaviorState){
ErrorBehaviorState ev = (ErrorBehaviorState)io;
return ev.getName();
} else if (io instanceof TypeToken){
return EMV2Util.getPrintName((TypeToken) io);
} else if (io instanceof TypeSet){
return EMV2Util.getTableName((TypeSet)io);
} else {
return "NoError";
}
}
/**
* report on io object with optional error propagation.
* report on attached ErrorModelState if present
* note: error propagation ep can be null.
* @param io Instance Object
* @param ep Error Propagation
*/
public String generatePropagationPointText(ComponentInstance io, ErrorPropagation ep){
return(generateItemText(io)+
(ep!=null?"."+EMV2Util.getPrintName(ep):""));
}
/**
* report on io object with optional error propagation.
* report on attached ErrorModelState if present
* note: error propagation ep can be null.
* @param io Instance Object
* @param ep Error Propagation
*/
public String generateErrorPropText( ErrorPropagation ep, TypeToken tt){
return(
(ep!=null?EMV2Util.getPrintName(ep):"")+
(tt!=null?" "+EMV2Util.getPrintName(tt):""));
}
/**
* report on Failure mode.
* note: error propagation ep can be null.
* @param io Instance Object
* @param ep Error Propagation
*/
public String generateFailureModeText( ComponentInstance ci,ErrorPropagation ep, TypeToken tt){
return generateComponentErrorPropText(ci,ep,tt);//generateErrorPropText(ep, tt);
}
/**
* report on ci object with optional error propagation.
* note: error propagation ep can be null.
* @param io Instance Object
* @param ep Error Propagation
*/
public String generateComponentErrorPropText( ComponentInstance ci,ErrorPropagation ep, TypeToken tt){
return generateItemText(ci)+"."+
generateErrorPropText(ep, tt);
}
/**
* traverse through the destination of the connection instance
* @param conni
*/
protected void traceErrorPaths(ComponentInstance ci, ErrorPropagation ep, TypeToken tt, int depth, String entryText){
// TODO this is the place where we can limit the depth of propagation path generation
// if (depth > maxLevel){
// reportEntry(entryText+" <more>,,", depth);
// return;
// }
FeatureInstance fi = EMV2Util.findFeatureInstance(ep, ci);
ErrorModelState st=null;
if (fi != null){
st = (ErrorModelState) ErrorModelStateAdapterFactory.INSTANCE.adapt(fi, ErrorModelState.class);
} else {
st = (ErrorModelState) ErrorModelStateAdapterFactory.INSTANCE.adapt(ci, ErrorModelState.class);
}
if (st.visited(tt)){
// we were there before.
String effectText = ", "+generateErrorPropText(ep,tt);
reportEntry(entryText+effectText+" -> <Cycle>,,", depth);
return;
} else {
st.setVisitToken(tt);
}
EList<PropagationPath> paths = faultModel.getAllPropagationPaths(ci, ep);
String effectText = ", "+generateErrorPropText(ep,tt);
if (paths.isEmpty()){
reportEntry(entryText+effectText+" -> <no paths>,,", depth);
} else {
for (PropagationPath path : paths) {
ComponentInstance destci = path.getDstCI();
ErrorPropagation destEP = path.getPathDst().getErrorPropagation();
// we go to the end of the connection instance, not an enclosing component that may have an error model abstraction
String connText=" -> "+generateItemText(destci);
traceErrorFlows(destci, destEP, tt, depth, entryText+effectText+connText);
}
}
st.removeVisitedToken( tt);
}
/**
* traverse through the destination of the connection instance
* @param conni
*/
protected void traceErrorFlows(ComponentInstance ci, ErrorPropagation ep, TypeToken tt, int depth, String entryText)
{
if (ci == null)
{
return;
}
/**
* With alreadyTreated, we have a cache that keep track of existing report
* text for each component. For each component, we maintain a list of existing
* entryText already reported. So, we do not duplicate the error report for each component
* and make sure to report each entry only once.
*/
if (! alreadyTreated.containsKey(ci))
{
alreadyTreated.put(ci, new ArrayList<String>());
}
if (alreadyTreated.get(ci).contains(entryText))
{
return;
}
alreadyTreated.get(ci).add(entryText);
List<ErrorPropagation> treated = new ArrayList<ErrorPropagation>();
boolean handled = false;
Collection<ErrorFlow> outefs=EMV2Util.findErrorFlowFromComponentInstance(ci, ep);
for (ErrorFlow ef : outefs) {
if (ef instanceof ErrorSink)
{
//OsateDebug.osateDebug("error sink" + ef.getName());
/**
* We try to find additional error propagation for this error sink.
* For example, if the error sink triggers to switch to
* another behavior state and that states is used to propagate
* an error through an error source. Then, we do not consider
* it as an error sink but as an error path and continue
* to trace the flow using this additional error propagation.
*/
EList<OutgoingPropagationCondition> additionalPropagations = EMV2Util.getAdditionalOutgoingPropagation (ci, ep);
// process should have returned false, but for safety we check again
if(additionalPropagations.size() == 0)
{
/**
* Here, we do not have any additional error propagation, we mark it as a sink.
*/
if (EM2TypeSetUtil.contains(ef.getTypeTokenConstraint(), tt)){
String maskText = ", "+generateFailureModeText(ci,ep,tt)+" [Masked],";
reportEntry(entryText+maskText, depth);
handled = true;
} else {
Collection<TypeToken> intersection = EM2TypeSetUtil.getConstrainedTypeTokens(ef.getTypeTokenConstraint(), tt);
for (TypeToken typeToken : intersection) {
String maskText = ", "+generateFailureModeText(ci,ep,typeToken)+" [Masked],";
reportEntry(entryText+maskText, depth);
handled = true;
}
}
}
else
{
/**
* We continue to trace the propagation flows
* based on the additional errors propagated.
*/
for (OutgoingPropagationCondition opc : additionalPropagations)
{
ErrorPropagation outp = opc.getOutgoing();
/**
* We try to address all potential error propagation cases.
*/
if (! treated.contains(opc))
{
TypeToken newtt = EMV2Util.mapToken(outp.getTypeSet().getTypeTokens().get(0),ef);
treated.add(outp);
traceErrorPaths(ci,outp,newtt,depth+1,entryText+", from state " + opc.getState().getName() +" " +generateFailureModeText(ci,ep,tt));
}
}
handled = true;
}
}
else if (ef instanceof ErrorPath){ // error path
Collection<ErrorPropagation> eplist = EMV2Util.getOutgoingPropagationOrAll((ErrorPath)ef);
- if (EM2TypeSetUtil.contains(ef.getTypeTokenConstraint(), tt)){
+ ErrorPropagation inep = ((ErrorPath)ef).getIncoming();
+ if ((ef.getTypeTokenConstraint()!=null&&EM2TypeSetUtil.contains(ef.getTypeTokenConstraint(), tt))
+ || (inep != null && EM2TypeSetUtil.contains(inep.getTypeSet(), tt))
+ || ((ErrorPath)ef).isAllIncoming()){
TypeToken newtt = EMV2Util.mapToken(tt,ef);
for (ErrorPropagation outp : eplist) {
traceErrorPaths(ci,outp,newtt,depth+1,entryText+", "+generateFailureModeText(ci, ep,tt));
handled = true;
}
} else {
Collection<TypeToken> intersection = EM2TypeSetUtil.getConstrainedTypeTokens(ef.getTypeTokenConstraint(), tt);
for (TypeToken typeToken : intersection) {
TypeToken newtt = EMV2Util.mapToken(typeToken,ef);
for (ErrorPropagation outp : eplist) {
traceErrorPaths(ci,outp,newtt,depth+1,entryText+", "+generateFailureModeText(ci, ep,typeToken));
handled = true;
}
}
}
}
}
if (!handled){
// no error flows:. and no flows condition
// try flows or propagate to all outgoing error propagations
EList<FlowSpecificationInstance> flowlist = ci.getFlowSpecifications();
if (!flowlist.isEmpty()){
for (FlowSpecificationInstance flowSpecificationInstance : flowlist) {
if (flowSpecificationInstance.getSource() != null&&
flowSpecificationInstance.getSource().getFeature() == EMV2Util.getErrorPropagationFeature(ep, ci)){
FeatureInstance outfi = flowSpecificationInstance.getDestination();
if (outfi != null){
ErrorPropagation outp = EMV2Util.getOutgoingErrorPropagation(outfi);
if (outp != null){
TypeToken newtt = EMV2Util.mapToken(tt,flowSpecificationInstance);
if (EM2TypeSetUtil.contains(outp.getTypeSet(), newtt)){
traceErrorPaths(ci,outp,newtt,depth+1,entryText+", "+generateFailureModeText(ci, ep,tt)+" [FlowPath]");
} else {
Collection<TypeToken> intersection = EM2TypeSetUtil.getConstrainedTypeTokens(outp.getTypeSet(), newtt);
for (TypeToken typeToken : intersection) {
traceErrorPaths(ci,outp,typeToken,depth+1,entryText+", "+generateFailureModeText(ci, ep,tt)+" [FlowPath]");
}
}
}
} else {
// do all since we have a flow sink
EList<FeatureInstance> filist = ci.getFeatureInstances();
doAllFeatures(ci, filist, ep, tt, depth, entryText);
}
}
}
} else {
// now all outgoing connections since we did not find flows
EList<FeatureInstance> filist = ci.getFeatureInstances();
doAllFeatures(ci, filist, ep, tt, depth, entryText);
}
}
}
protected void doAllFeatures(ComponentInstance ci, EList<FeatureInstance> filist,ErrorPropagation ep, TypeToken tt, int depth, String entryText){
for (FeatureInstance fi : filist) {
if (fi.getDirection().outgoing()){
ErrorPropagation outp = EMV2Util.getOutgoingErrorPropagation(fi);
if (outp!=null){
TypeToken newtt = EMV2Util.mapToken(tt,null);
traceErrorPaths(ci,outp,newtt,depth+1,entryText+","+generateFailureModeText(ci,ep,tt)+" [AllOut]");
if (EM2TypeSetUtil.contains(outp.getTypeSet(), newtt)){
traceErrorPaths(ci,outp,newtt,depth+1,entryText+","+generateFailureModeText(ci,ep,tt)+" [AllOut]");
} else {
Collection<TypeToken> intersection = EM2TypeSetUtil.getConstrainedTypeTokens(outp.getTypeSet(), newtt);
for (TypeToken typeToken : intersection) {
traceErrorPaths(ci,outp,typeToken,depth+1,entryText+","+generateFailureModeText(ci,ep,tt)+" [AllOut]");
}
}
} else {
if (!fi.getFeatureInstances().isEmpty()){
doAllFeatures(ci, fi.getFeatureInstances(), ep, tt, depth, entryText);
}
}
}
}
}
}
| true | true | protected void traceErrorFlows(ComponentInstance ci, ErrorPropagation ep, TypeToken tt, int depth, String entryText)
{
if (ci == null)
{
return;
}
/**
* With alreadyTreated, we have a cache that keep track of existing report
* text for each component. For each component, we maintain a list of existing
* entryText already reported. So, we do not duplicate the error report for each component
* and make sure to report each entry only once.
*/
if (! alreadyTreated.containsKey(ci))
{
alreadyTreated.put(ci, new ArrayList<String>());
}
if (alreadyTreated.get(ci).contains(entryText))
{
return;
}
alreadyTreated.get(ci).add(entryText);
List<ErrorPropagation> treated = new ArrayList<ErrorPropagation>();
boolean handled = false;
Collection<ErrorFlow> outefs=EMV2Util.findErrorFlowFromComponentInstance(ci, ep);
for (ErrorFlow ef : outefs) {
if (ef instanceof ErrorSink)
{
//OsateDebug.osateDebug("error sink" + ef.getName());
/**
* We try to find additional error propagation for this error sink.
* For example, if the error sink triggers to switch to
* another behavior state and that states is used to propagate
* an error through an error source. Then, we do not consider
* it as an error sink but as an error path and continue
* to trace the flow using this additional error propagation.
*/
EList<OutgoingPropagationCondition> additionalPropagations = EMV2Util.getAdditionalOutgoingPropagation (ci, ep);
// process should have returned false, but for safety we check again
if(additionalPropagations.size() == 0)
{
/**
* Here, we do not have any additional error propagation, we mark it as a sink.
*/
if (EM2TypeSetUtil.contains(ef.getTypeTokenConstraint(), tt)){
String maskText = ", "+generateFailureModeText(ci,ep,tt)+" [Masked],";
reportEntry(entryText+maskText, depth);
handled = true;
} else {
Collection<TypeToken> intersection = EM2TypeSetUtil.getConstrainedTypeTokens(ef.getTypeTokenConstraint(), tt);
for (TypeToken typeToken : intersection) {
String maskText = ", "+generateFailureModeText(ci,ep,typeToken)+" [Masked],";
reportEntry(entryText+maskText, depth);
handled = true;
}
}
}
else
{
/**
* We continue to trace the propagation flows
* based on the additional errors propagated.
*/
for (OutgoingPropagationCondition opc : additionalPropagations)
{
ErrorPropagation outp = opc.getOutgoing();
/**
* We try to address all potential error propagation cases.
*/
if (! treated.contains(opc))
{
TypeToken newtt = EMV2Util.mapToken(outp.getTypeSet().getTypeTokens().get(0),ef);
treated.add(outp);
traceErrorPaths(ci,outp,newtt,depth+1,entryText+", from state " + opc.getState().getName() +" " +generateFailureModeText(ci,ep,tt));
}
}
handled = true;
}
}
else if (ef instanceof ErrorPath){ // error path
Collection<ErrorPropagation> eplist = EMV2Util.getOutgoingPropagationOrAll((ErrorPath)ef);
if (EM2TypeSetUtil.contains(ef.getTypeTokenConstraint(), tt)){
TypeToken newtt = EMV2Util.mapToken(tt,ef);
for (ErrorPropagation outp : eplist) {
traceErrorPaths(ci,outp,newtt,depth+1,entryText+", "+generateFailureModeText(ci, ep,tt));
handled = true;
}
} else {
Collection<TypeToken> intersection = EM2TypeSetUtil.getConstrainedTypeTokens(ef.getTypeTokenConstraint(), tt);
for (TypeToken typeToken : intersection) {
TypeToken newtt = EMV2Util.mapToken(typeToken,ef);
for (ErrorPropagation outp : eplist) {
traceErrorPaths(ci,outp,newtt,depth+1,entryText+", "+generateFailureModeText(ci, ep,typeToken));
handled = true;
}
}
}
}
}
if (!handled){
// no error flows:. and no flows condition
// try flows or propagate to all outgoing error propagations
EList<FlowSpecificationInstance> flowlist = ci.getFlowSpecifications();
if (!flowlist.isEmpty()){
for (FlowSpecificationInstance flowSpecificationInstance : flowlist) {
if (flowSpecificationInstance.getSource() != null&&
flowSpecificationInstance.getSource().getFeature() == EMV2Util.getErrorPropagationFeature(ep, ci)){
FeatureInstance outfi = flowSpecificationInstance.getDestination();
if (outfi != null){
ErrorPropagation outp = EMV2Util.getOutgoingErrorPropagation(outfi);
if (outp != null){
TypeToken newtt = EMV2Util.mapToken(tt,flowSpecificationInstance);
if (EM2TypeSetUtil.contains(outp.getTypeSet(), newtt)){
traceErrorPaths(ci,outp,newtt,depth+1,entryText+", "+generateFailureModeText(ci, ep,tt)+" [FlowPath]");
} else {
Collection<TypeToken> intersection = EM2TypeSetUtil.getConstrainedTypeTokens(outp.getTypeSet(), newtt);
for (TypeToken typeToken : intersection) {
traceErrorPaths(ci,outp,typeToken,depth+1,entryText+", "+generateFailureModeText(ci, ep,tt)+" [FlowPath]");
}
}
}
} else {
// do all since we have a flow sink
EList<FeatureInstance> filist = ci.getFeatureInstances();
doAllFeatures(ci, filist, ep, tt, depth, entryText);
}
}
}
} else {
// now all outgoing connections since we did not find flows
EList<FeatureInstance> filist = ci.getFeatureInstances();
doAllFeatures(ci, filist, ep, tt, depth, entryText);
}
}
}
| protected void traceErrorFlows(ComponentInstance ci, ErrorPropagation ep, TypeToken tt, int depth, String entryText)
{
if (ci == null)
{
return;
}
/**
* With alreadyTreated, we have a cache that keep track of existing report
* text for each component. For each component, we maintain a list of existing
* entryText already reported. So, we do not duplicate the error report for each component
* and make sure to report each entry only once.
*/
if (! alreadyTreated.containsKey(ci))
{
alreadyTreated.put(ci, new ArrayList<String>());
}
if (alreadyTreated.get(ci).contains(entryText))
{
return;
}
alreadyTreated.get(ci).add(entryText);
List<ErrorPropagation> treated = new ArrayList<ErrorPropagation>();
boolean handled = false;
Collection<ErrorFlow> outefs=EMV2Util.findErrorFlowFromComponentInstance(ci, ep);
for (ErrorFlow ef : outefs) {
if (ef instanceof ErrorSink)
{
//OsateDebug.osateDebug("error sink" + ef.getName());
/**
* We try to find additional error propagation for this error sink.
* For example, if the error sink triggers to switch to
* another behavior state and that states is used to propagate
* an error through an error source. Then, we do not consider
* it as an error sink but as an error path and continue
* to trace the flow using this additional error propagation.
*/
EList<OutgoingPropagationCondition> additionalPropagations = EMV2Util.getAdditionalOutgoingPropagation (ci, ep);
// process should have returned false, but for safety we check again
if(additionalPropagations.size() == 0)
{
/**
* Here, we do not have any additional error propagation, we mark it as a sink.
*/
if (EM2TypeSetUtil.contains(ef.getTypeTokenConstraint(), tt)){
String maskText = ", "+generateFailureModeText(ci,ep,tt)+" [Masked],";
reportEntry(entryText+maskText, depth);
handled = true;
} else {
Collection<TypeToken> intersection = EM2TypeSetUtil.getConstrainedTypeTokens(ef.getTypeTokenConstraint(), tt);
for (TypeToken typeToken : intersection) {
String maskText = ", "+generateFailureModeText(ci,ep,typeToken)+" [Masked],";
reportEntry(entryText+maskText, depth);
handled = true;
}
}
}
else
{
/**
* We continue to trace the propagation flows
* based on the additional errors propagated.
*/
for (OutgoingPropagationCondition opc : additionalPropagations)
{
ErrorPropagation outp = opc.getOutgoing();
/**
* We try to address all potential error propagation cases.
*/
if (! treated.contains(opc))
{
TypeToken newtt = EMV2Util.mapToken(outp.getTypeSet().getTypeTokens().get(0),ef);
treated.add(outp);
traceErrorPaths(ci,outp,newtt,depth+1,entryText+", from state " + opc.getState().getName() +" " +generateFailureModeText(ci,ep,tt));
}
}
handled = true;
}
}
else if (ef instanceof ErrorPath){ // error path
Collection<ErrorPropagation> eplist = EMV2Util.getOutgoingPropagationOrAll((ErrorPath)ef);
ErrorPropagation inep = ((ErrorPath)ef).getIncoming();
if ((ef.getTypeTokenConstraint()!=null&&EM2TypeSetUtil.contains(ef.getTypeTokenConstraint(), tt))
|| (inep != null && EM2TypeSetUtil.contains(inep.getTypeSet(), tt))
|| ((ErrorPath)ef).isAllIncoming()){
TypeToken newtt = EMV2Util.mapToken(tt,ef);
for (ErrorPropagation outp : eplist) {
traceErrorPaths(ci,outp,newtt,depth+1,entryText+", "+generateFailureModeText(ci, ep,tt));
handled = true;
}
} else {
Collection<TypeToken> intersection = EM2TypeSetUtil.getConstrainedTypeTokens(ef.getTypeTokenConstraint(), tt);
for (TypeToken typeToken : intersection) {
TypeToken newtt = EMV2Util.mapToken(typeToken,ef);
for (ErrorPropagation outp : eplist) {
traceErrorPaths(ci,outp,newtt,depth+1,entryText+", "+generateFailureModeText(ci, ep,typeToken));
handled = true;
}
}
}
}
}
if (!handled){
// no error flows:. and no flows condition
// try flows or propagate to all outgoing error propagations
EList<FlowSpecificationInstance> flowlist = ci.getFlowSpecifications();
if (!flowlist.isEmpty()){
for (FlowSpecificationInstance flowSpecificationInstance : flowlist) {
if (flowSpecificationInstance.getSource() != null&&
flowSpecificationInstance.getSource().getFeature() == EMV2Util.getErrorPropagationFeature(ep, ci)){
FeatureInstance outfi = flowSpecificationInstance.getDestination();
if (outfi != null){
ErrorPropagation outp = EMV2Util.getOutgoingErrorPropagation(outfi);
if (outp != null){
TypeToken newtt = EMV2Util.mapToken(tt,flowSpecificationInstance);
if (EM2TypeSetUtil.contains(outp.getTypeSet(), newtt)){
traceErrorPaths(ci,outp,newtt,depth+1,entryText+", "+generateFailureModeText(ci, ep,tt)+" [FlowPath]");
} else {
Collection<TypeToken> intersection = EM2TypeSetUtil.getConstrainedTypeTokens(outp.getTypeSet(), newtt);
for (TypeToken typeToken : intersection) {
traceErrorPaths(ci,outp,typeToken,depth+1,entryText+", "+generateFailureModeText(ci, ep,tt)+" [FlowPath]");
}
}
}
} else {
// do all since we have a flow sink
EList<FeatureInstance> filist = ci.getFeatureInstances();
doAllFeatures(ci, filist, ep, tt, depth, entryText);
}
}
}
} else {
// now all outgoing connections since we did not find flows
EList<FeatureInstance> filist = ci.getFeatureInstances();
doAllFeatures(ci, filist, ep, tt, depth, entryText);
}
}
}
|
diff --git a/Slick/tools/org/newdawn/slick/tools/peditor/ParticleGame.java b/Slick/tools/org/newdawn/slick/tools/peditor/ParticleGame.java
index a580d35..8ad2857 100644
--- a/Slick/tools/org/newdawn/slick/tools/peditor/ParticleGame.java
+++ b/Slick/tools/org/newdawn/slick/tools/peditor/ParticleGame.java
@@ -1,306 +1,306 @@
package org.newdawn.slick.tools.peditor;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.Color;
import org.newdawn.slick.Font;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.InputListener;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.particles.ConfigurableEmitter;
import org.newdawn.slick.particles.ParticleEmitter;
import org.newdawn.slick.particles.ParticleSystem;
import org.newdawn.slick.util.Log;
/**
* A LWJGL canvas displaying a particle system
*
* @author kevin
*/
public class ParticleGame extends BasicGame {
/** Emitters waiting to be added once the system is created */
private ArrayList waiting = new ArrayList();
/** The particle system being displayed on the panel */
private ParticleSystem system;
/** The font used to display info on the canvas */
private Font defaultFont;
/** The list of emitters being displayed in the system */
private ArrayList emitters = new ArrayList();
/** The maximum number of particles in use */
private int max;
/** True if the hud should be displayed */
private boolean hudOn = true;
/** True if the rendering is paused */
private boolean paused;
/** The amount the system moves */
private int systemMove;
/** The y position of the system */
private float ypos;
/** The background image file to load */
private File backgroundImage;
/** The background image being rendered */
private Image background;
/** An input listener to be added on init */
private InputListener listener;
/**
* Create a new canvas
*
* @param editor
* The editor which this canvas is part of
* @throws LWJGLException
* Indicates a failure to create the OpenGL context
*/
public ParticleGame(ParticleEditor editor) throws LWJGLException {
super("Particle Game");
}
/**
* Set the input listener to be added on init
*
* @param listener The listener to be added on init
*/
public void setListener(InputListener listener) {
this.listener = listener;
}
/**
* Set the image to display behind the particle system
*
* @param file
* The file to load for the background image
*/
public void setBackgroundImage(File file) {
backgroundImage = file;
background = null;
}
/**
* Set how much the system should move
*
* @param move
* The amount of the system should move
* @param reset
* True if the position should be reset
*/
public void setSystemMove(int move, boolean reset) {
this.systemMove = move;
if (reset) {
ypos = 0;
}
}
/**
* Indicate if this canvas should pause
*
* @param paused
* True if the rendering should pause
*/
public void setPaused(boolean paused) {
this.paused = paused;
}
/**
* Check if the canvas is paused
*
* @return True if the canvas is paused
*/
public boolean isPaused() {
return paused;
}
/**
* Check if this hud is being displayed
*
* @return True if this hud is being displayed
*/
public boolean isHudOn() {
return hudOn;
}
/**
* Indicate if the HUD should be drawn
*
* @param hud
* True if the HUD should be drawn
*/
public void setHud(boolean hud) {
this.hudOn = hud;
}
/**
* Add an emitter to the particle system held here
*
* @param emitter
* The emitter to add
*/
public void addEmitter(ConfigurableEmitter emitter) {
emitters.add(emitter);
if (system == null) {
waiting.add(emitter);
} else {
system.addEmitter(emitter);
}
}
/**
* Remove an emitter from the system held here
*
* @param emitter
* The emitter to be removed
*/
public void removeEmitter(ConfigurableEmitter emitter) {
emitters.remove(emitter);
system.removeEmitter(emitter);
}
/**
* Clear the particle system held in this canvas
*
* @param additive
* True if the particle system should be set to additive
*/
public void clearSystem(boolean additive) {
system = new ParticleSystem("org/newdawn/slick/data/particle.tga", 2000);
if (additive) {
system.setBlendingMode(ParticleSystem.BLEND_ADDITIVE);
}
system.setRemoveCompletedEmitters(false);
}
/**
* Set the particle system to be displayed
*
* @param system
* The system to be displayed
*/
public void setSystem(ParticleSystem system) {
this.system = system;
emitters.clear();
system.setRemoveCompletedEmitters(false);
for (int i = 0; i < system.getEmitterCount(); i++) {
emitters.add(system.getEmitter(i));
}
}
/**
* Reset the counts held in this canvas (maximum particles for instance)
*/
public void resetCounts() {
max = 0;
}
/**
* Get the particle system being displayed
*
* @return The system being displayed
*/
public ParticleSystem getSystem() {
return system;
}
public void init(GameContainer container) throws SlickException {
container.getInput().addListener(listener);
container.setShowFPS(false);
system = new ParticleSystem("org/newdawn/slick/data/particle.tga", 2000);
system.setBlendingMode(ParticleSystem.BLEND_ADDITIVE);
system.setRemoveCompletedEmitters(false);
for (int i = 0; i < waiting.size(); i++) {
system.addEmitter((ParticleEmitter) waiting.get(i));
}
waiting.clear();
}
public void update(GameContainer container, int delta)
throws SlickException {
if (!paused) {
ypos += delta * 0.002 * systemMove;
if (ypos > 300) {
ypos = -300;
}
if (ypos < -300) {
ypos = 300;
}
for (int i = 0; i < emitters.size(); i++) {
((ConfigurableEmitter) emitters.get(i)).replayCheck();
}
for (int i = 0; i < delta; i++) {
system.update(1);
}
}
Display.sync(100);
}
public void render(GameContainer container, Graphics g)
throws SlickException {
try {
if (backgroundImage != null) {
if (background == null) {
background = new Image(
new FileInputStream(backgroundImage),
backgroundImage.getAbsolutePath(), false);
}
}
} catch (Exception e) {
Log.error("Failed to load backgroundImage: " + backgroundImage);
Log.error(e);
backgroundImage = null;
background = null;
}
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
GL11.glLoadIdentity();
if (background != null) {
g.fillRect(0, 0, container.getWidth(), container.getHeight(), background, 0, 0);
}
max = Math.max(max, system.getParticleCount());
if (hudOn) {
g.setColor(Color.white);
g.drawString("FPS: " + container.getFPS(), 10, 10);
g.drawString("Particles: " + system.getParticleCount(), 10,
25);
g.drawString("Max: " + max, 10, 40);
g.drawString(
- "LMB: Position Emitter RMB: Default Position", 90,
+ "LMB: Position Emitter RMB: Default Position", 20,
527);
}
GL11.glTranslatef(250, 300, 0);
for (int i = 0; i < emitters.size(); i++) {
((ConfigurableEmitter) emitters.get(i)).setPosition(0, ypos);
}
system.render();
g.setColor(new Color(0, 0, 0, 0.5f));
g.fillRect(-1, -5, 2, 10);
g.fillRect(-5, -1, 10, 2);
}
}
| true | true | public void render(GameContainer container, Graphics g)
throws SlickException {
try {
if (backgroundImage != null) {
if (background == null) {
background = new Image(
new FileInputStream(backgroundImage),
backgroundImage.getAbsolutePath(), false);
}
}
} catch (Exception e) {
Log.error("Failed to load backgroundImage: " + backgroundImage);
Log.error(e);
backgroundImage = null;
background = null;
}
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
GL11.glLoadIdentity();
if (background != null) {
g.fillRect(0, 0, container.getWidth(), container.getHeight(), background, 0, 0);
}
max = Math.max(max, system.getParticleCount());
if (hudOn) {
g.setColor(Color.white);
g.drawString("FPS: " + container.getFPS(), 10, 10);
g.drawString("Particles: " + system.getParticleCount(), 10,
25);
g.drawString("Max: " + max, 10, 40);
g.drawString(
"LMB: Position Emitter RMB: Default Position", 90,
527);
}
GL11.glTranslatef(250, 300, 0);
for (int i = 0; i < emitters.size(); i++) {
((ConfigurableEmitter) emitters.get(i)).setPosition(0, ypos);
}
system.render();
g.setColor(new Color(0, 0, 0, 0.5f));
g.fillRect(-1, -5, 2, 10);
g.fillRect(-5, -1, 10, 2);
}
| public void render(GameContainer container, Graphics g)
throws SlickException {
try {
if (backgroundImage != null) {
if (background == null) {
background = new Image(
new FileInputStream(backgroundImage),
backgroundImage.getAbsolutePath(), false);
}
}
} catch (Exception e) {
Log.error("Failed to load backgroundImage: " + backgroundImage);
Log.error(e);
backgroundImage = null;
background = null;
}
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
GL11.glLoadIdentity();
if (background != null) {
g.fillRect(0, 0, container.getWidth(), container.getHeight(), background, 0, 0);
}
max = Math.max(max, system.getParticleCount());
if (hudOn) {
g.setColor(Color.white);
g.drawString("FPS: " + container.getFPS(), 10, 10);
g.drawString("Particles: " + system.getParticleCount(), 10,
25);
g.drawString("Max: " + max, 10, 40);
g.drawString(
"LMB: Position Emitter RMB: Default Position", 20,
527);
}
GL11.glTranslatef(250, 300, 0);
for (int i = 0; i < emitters.size(); i++) {
((ConfigurableEmitter) emitters.get(i)).setPosition(0, ypos);
}
system.render();
g.setColor(new Color(0, 0, 0, 0.5f));
g.fillRect(-1, -5, 2, 10);
g.fillRect(-5, -1, 10, 2);
}
|
diff --git a/src/ru/artyomkomarov/MainApp.java b/src/ru/artyomkomarov/MainApp.java
index aeead67..6b360bb 100644
--- a/src/ru/artyomkomarov/MainApp.java
+++ b/src/ru/artyomkomarov/MainApp.java
@@ -1,40 +1,40 @@
package ru.artyomkomarov;
import java.io.File;
public class MainApp {
static long ans = 0;
public static void main(String[] args) {
- args = new String[2];
+ /*args = new String[2];
args[0] = "C:\\Users\\1\\Desktop\\����������";
- args[1] = "false";
+ args[1] = "false";*/
String name = "";
String mark = "false";
for(int i = 0; i < args.length - 1; i++) {
if(i == 0)name = args[i];
else name = name + " " + args[i];
}
mark = args[args.length - 1];
long startTime = System.currentTimeMillis();
if(mark.equals("true")) {
ThreadClass th = new ThreadClass(args[0]);
Thread newTh = new Thread(th);
newTh.start();
try {
newTh.join();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(th.res);
} else {
File[] files = new File(name).listFiles();
for(int i = 0; i < files.length; i++) {
if(files[i].isFile())ans += files[i].length();
}
System.out.println(ans);
}
long finishTime = System.currentTimeMillis();
System.out.println("Time mills: " + (finishTime - startTime));
}
}
| false | true | public static void main(String[] args) {
args = new String[2];
args[0] = "C:\\Users\\1\\Desktop\\����������";
args[1] = "false";
String name = "";
String mark = "false";
for(int i = 0; i < args.length - 1; i++) {
if(i == 0)name = args[i];
else name = name + " " + args[i];
}
mark = args[args.length - 1];
long startTime = System.currentTimeMillis();
if(mark.equals("true")) {
ThreadClass th = new ThreadClass(args[0]);
Thread newTh = new Thread(th);
newTh.start();
try {
newTh.join();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(th.res);
} else {
File[] files = new File(name).listFiles();
for(int i = 0; i < files.length; i++) {
if(files[i].isFile())ans += files[i].length();
}
System.out.println(ans);
}
long finishTime = System.currentTimeMillis();
System.out.println("Time mills: " + (finishTime - startTime));
}
| public static void main(String[] args) {
/*args = new String[2];
args[0] = "C:\\Users\\1\\Desktop\\����������";
args[1] = "false";*/
String name = "";
String mark = "false";
for(int i = 0; i < args.length - 1; i++) {
if(i == 0)name = args[i];
else name = name + " " + args[i];
}
mark = args[args.length - 1];
long startTime = System.currentTimeMillis();
if(mark.equals("true")) {
ThreadClass th = new ThreadClass(args[0]);
Thread newTh = new Thread(th);
newTh.start();
try {
newTh.join();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(th.res);
} else {
File[] files = new File(name).listFiles();
for(int i = 0; i < files.length; i++) {
if(files[i].isFile())ans += files[i].length();
}
System.out.println(ans);
}
long finishTime = System.currentTimeMillis();
System.out.println("Time mills: " + (finishTime - startTime));
}
|
diff --git a/src/com/ichi2/libanki/sync/Syncer.java b/src/com/ichi2/libanki/sync/Syncer.java
index b3520fbe..4e697b5e 100644
--- a/src/com/ichi2/libanki/sync/Syncer.java
+++ b/src/com/ichi2/libanki/sync/Syncer.java
@@ -1,698 +1,702 @@
/***************************************************************************************
* Copyright (c) 2011 Norbert Nagold <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.libanki.sync;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.database.Cursor;
import android.database.SQLException;
import com.ichi2.anki2.R;
import com.ichi2.async.Connection;
import com.ichi2.libanki.Collection;
import com.ichi2.libanki.Sched;
import com.ichi2.libanki.Utils;
import com.ichi2.utils.ConvUtils;
public class Syncer {
Collection mCol;
HttpSyncer mServer;
long mRMod;
long mRScm;
int mMaxUsn;
int mMediaUsn;
long mLMod;
long mLScm;
int mMinUsn;
boolean mLNewer;
JSONObject mRChg;
private LinkedList<String> mTablesLeft;
private Cursor mCursor;
public Syncer (Collection col, HttpSyncer server) {
mCol = col;
mServer = server;
}
/** Returns 'noChanges', 'fullSync', or 'success'. */
public Object[] sync(Connection con) {
// if the deck has any pending changes, flush them first and bump mod time
mCol.save();
// step 1: login & metadata
HttpResponse ret = mServer.meta();
if (ret == null) {
return null;
}
int returntype = ret.getStatusLine().getStatusCode();
if (returntype == 403){
return new Object[] {"badAuth"};
} else if (returntype != 200) {
return new Object[] {"error", returntype, ret.getStatusLine().getReasonPhrase()};
}
long rts;
long lts;
try {
JSONArray ra = new JSONArray(mServer.stream2String(ret.getEntity().getContent()));
mRMod = ra.getLong(0);
mRScm = ra.getLong(1);
mMaxUsn = ra.getInt(2);
rts = ra.getLong(3);
mMediaUsn = ra.getInt(4);
JSONArray la = meta();
mLMod = la.getLong(0);
mLScm = la.getLong(1);
mMinUsn = la.getInt(2);
lts = la.getLong(3);
long diff = Math.abs(rts - lts);
if (diff > 300) {
return new Object[]{"clockOff", diff};
}
if (mLMod == mRMod) {
return new Object[]{"noChanges"};
} else if (mLScm != mRScm) {
return new Object[]{"fullSync"};
}
mLNewer = mLMod > mRMod;
// step 2: deletions
con.publishProgress(R.string.sync_deletions_message);
JSONObject lrem = removed();
JSONObject o = new JSONObject();
o.put("minUsn", mMinUsn);
o.put("lnewer", mLNewer);
o.put("graves", lrem);
JSONObject rrem = mServer.start(o);
if (rrem == null) {
return null;
}
if (rrem.has("errorType")) {
return new Object[]{"error", rrem.get("errorType"), rrem.get("errorReason")};
}
remove(rrem);
// ... and small objects
con.publishProgress(R.string.sync_small_objects_message);
JSONObject lchg = changes();
JSONObject sch = new JSONObject();
sch.put("changes", lchg);
JSONObject rchg = mServer.applyChanges(sch);
if (rchg == null) {
return null;
}
if (rchg.has("errorType")) {
return new Object[]{"error", rchg.get("errorType"), rchg.get("errorReason")};
}
mergeChanges(lchg, rchg);
// step 3: stream large tables from server
con.publishProgress(R.string.sync_download_chunk);
while (true) {
JSONObject chunk = mServer.chunk();
if (chunk == null) {
return null;
}
if (chunk.has("errorType")) {
return new Object[]{"error", chunk.get("errorType"), chunk.get("errorReason")};
}
applyChunk(chunk);
if (chunk.getBoolean("done")) {
break;
}
}
// step 4: stream to server
con.publishProgress(R.string.sync_upload_chunk);
while (true) {
JSONObject chunk = chunk();
JSONObject sech = new JSONObject();
sech.put("chunk", chunk);
mServer.applyChunk(sech);
if (chunk.getBoolean("done")) {
break;
}
}
// step 5: sanity check during beta testing
JSONArray c = sanityCheck();
JSONArray s = mServer.sanityCheck();
if (s.getString(0).equals("error")) {
return new Object[]{"error", 200, "sanity check error on server"};
}
+ boolean error = false;
for (int i = 0; i < s.getJSONArray(0).length(); i++) {
if (c.getJSONArray(0).getLong(i) != s.getJSONArray(0).getLong(i)) {
- return new Object[]{"error", 200, "sanity check failed: 1/" + i};
+ error = true;
}
}
for (int i = 1; i < s.length(); i++) {
if (c.getLong(i) != s.getLong(i)) {
- return new Object[]{"error", 200, "sanity check failed: " + i};
+ error = true;
}
}
+ if (error) {
+ return new Object[]{"error", 200, "sanity check failed:\nl: " + c.toString() + "\nr: " + l.toString()};
+ }
} catch (JSONException e) {
throw new RuntimeException(e);
} catch (IllegalStateException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
// finalize
con.publishProgress(R.string.sync_finish_message);
long mod = mServer.finish();
if (mod == 0) {
return new Object[]{"finishError"};
}
finish(mod);
return new Object[]{"success"};
}
private JSONArray meta() {
JSONArray o = new JSONArray();
o.put(mCol.getMod());
o.put(mCol.getScm());
o.put(mCol.getUsnForSync());
o.put(Utils.intNow());
return o;
}
/** Bundle up small objects. */
private JSONObject changes() {
JSONObject o = new JSONObject();
try {
o.put("models",getModels());
o.put("decks", getDecks());
o.put("tags", getTags());
if (mLNewer) {
o.put("conf", getConf());
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
return o;
}
private JSONObject applyChanges(JSONObject changes) {
mRChg = changes;
JSONObject lchg = changes();
// merge our side before returning
mergeChanges(lchg, mRChg);
return lchg;
}
private void mergeChanges(JSONObject lchg, JSONObject rchg) {
try {
// then the other objects
mergeModels(rchg.getJSONArray("models"));
mergeDecks(rchg.getJSONArray("decks"));
mergeTags(rchg.getJSONArray("tags"));
if (rchg.has("conf")) {
mergeConf(rchg.getJSONObject("conf"));
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
prepareToChunk();
}
private JSONArray sanityCheck() {
boolean ok = true;
ok = ok && mCol.getDb().queryScalar("SELECT count() FROM cards WHERE nid NOT IN (SELECT id FROM notes)", false) == 0;
ok = ok && mCol.getDb().queryScalar("SELECT count() FROM notes WHERE id NOT IN (SELECT DISTINCT nid FROM cards)", false) == 0;
ok = ok && mCol.getDb().queryScalar("SELECT count() FROM cards WHERE usn = -1", false) == 0;
ok = ok && mCol.getDb().queryScalar("SELECT count() FROM notes WHERE usn = -1", false) == 0;
ok = ok && mCol.getDb().queryScalar("SELECT count() FROM revlog WHERE usn = -1", false) == 0;
ok = ok && mCol.getDb().queryScalar("SELECT count() FROM graves WHERE usn = -1", false) == 0;
try {
for (JSONObject g : mCol.getDecks().all()) {
ok = ok && g.getInt("usn") != -1;
}
for (Integer usn : mCol.getTags().allItems().values()) {
ok = ok && usn != -1;
}
for (JSONObject m : mCol.getModels().all()) {
ok = ok && m.getInt("usn") != -1;
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
if (!ok) {
return null;
}
mCol.getSched().reset();
JSONArray ja = new JSONArray();
JSONArray sa = new JSONArray();
for (int c : mCol.getSched().counts()) {
sa.put(c);
}
ja.put(sa);
ja.put(mCol.getDb().queryScalar("SELECT count() FROM cards"));
ja.put(mCol.getDb().queryScalar("SELECT count() FROM notes"));
ja.put(mCol.getDb().queryScalar("SELECT count() FROM revlog"));
ja.put(mCol.getDb().queryScalar("SELECT count() FROM graves"));
ja.put(mCol.getModels().all().size());
ja.put(mCol.getDecks().all().size());
ja.put(mCol.getDecks().allConf().size());
return ja;
}
private String usnLim() {
if (mCol.getServer()) {
return "usn >= " + mMinUsn;
} else {
return "usn = -1";
}
}
private long finish() {
return finish(0);
}
private long finish(long mod) {
if (mod == 0) {
// server side; we decide new mod time
mod = Utils.intNow(1000);
}
mCol.setLs(mod);
mCol.setUsnAfterSync(mMaxUsn + 1);
mCol.save(null, mod);
return mod;
}
/** Chunked syncing
* ********************************************************************
*/
private void prepareToChunk() {
mTablesLeft = new LinkedList<String>();
mTablesLeft.add("revlog");
mTablesLeft.add("cards");
mTablesLeft.add("notes");
mCursor = null;
}
private Cursor cursorForTable(String table) {
String lim = usnLim();
if (table.equals("revlog")) {
return mCol.getDb().getDatabase().rawQuery(String.format("SELECT id, cid, %d, ease, ivl, lastIvl, factor, time, type FROM revlog WHERE %s", mMaxUsn, lim), null);
} else if (table.equals("cards")) {
return mCol.getDb().getDatabase().rawQuery(String.format("SELECT id, nid, did, ord, mod, %d, type, queue, due, ivl, factor, reps, lapses, left, edue, flags, data FROM cards WHERE %s", mMaxUsn, lim), null);
} else {
return mCol.getDb().getDatabase().rawQuery(String.format("SELECT id, guid, mid, did, mod, %d, tags, flds, '', '', flags, data FROM notes WHERE %s", mMaxUsn, lim), null);
}
}
private JSONObject chunk() {
JSONObject buf = new JSONObject();
try {
buf.put("done", false);
int lim = 2500;
while (!mTablesLeft.isEmpty() && lim > 0) {
String curTable = mTablesLeft.getFirst();
if (mCursor == null) {
mCursor = cursorForTable(curTable);
}
JSONArray rows = new JSONArray();
while (mCursor.moveToNext() && mCursor.getPosition() <= lim) {
JSONArray r = new JSONArray();
int count = mCursor.getColumnCount();
for (int i = 0; i < count; i++) {
switch (mCursor.getType(i)) {
case Cursor.FIELD_TYPE_STRING:
r.put(mCursor.getString(i));
break;
case Cursor.FIELD_TYPE_FLOAT:
r.put(mCursor.getDouble(i));
break;
case Cursor.FIELD_TYPE_INTEGER:
r.put(mCursor.getLong(i));
break;
}
}
rows.put(r);
}
int fetched = rows.length();
if (fetched != lim) {
// table is empty
mTablesLeft.removeFirst();
mCursor.close();
mCursor = null;
// if we're the client, mark the objects as having been sent
if (!mCol.getServer()) {
mCol.getDb().execute("UPDATE " + curTable + " SET usn=" + mMaxUsn + " WHERE usn=-1");
}
}
buf.put(curTable, rows);
lim -= fetched;
}
if (mTablesLeft.isEmpty()) {
buf.put("done", true);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
return buf;
}
private void applyChunk(JSONObject chunk) {
try {
if (chunk.has("revlog")) {
mergeRevlog(chunk.getJSONArray("revlog"));
}
if (chunk.has("cards")) {
mergeCards(chunk.getJSONArray("cards"));
}
if (chunk.has("notes")) {
mergeNotes(chunk.getJSONArray("notes"));
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
/** Deletions
* ********************************************************************
*/
private JSONObject removed() {
JSONArray cards = new JSONArray();
JSONArray notes = new JSONArray();
JSONArray decks = new JSONArray();
Cursor cur = null;
try {
cur = mCol.getDb().getDatabase().rawQuery("SELECT oid, type FROM graves WHERE usn" + (mCol.getServer() ? (" >= " + mMinUsn) : (" = -1")), null);
while (cur.moveToNext()) {
int type = cur.getInt(1);
switch (type) {
case Sched.REM_CARD:
cards.put(cur.getLong(0));
break;
case Sched.REM_NOTE:
notes.put(cur.getLong(0));
break;
case Sched.REM_DECK:
decks.put(cur.getLong(0));
break;
}
}
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
if (!mCol.getServer()) {
mCol.getDb().execute("UPDATE graves SET usn=" + mMaxUsn + " WHERE usn=-1");
}
JSONObject o = new JSONObject();
try {
o.put("cards", cards);
o.put("notes", notes);
o.put("decks", decks);
} catch (JSONException e) {
throw new RuntimeException(e);
}
return o;
}
private JSONObject start(int minUsn, boolean lnewer, JSONObject graves) {
mMaxUsn = mCol.getUsnForSync();
mMinUsn = minUsn;
mLNewer = !lnewer;
JSONObject lgraves = removed();
remove(graves);
return lgraves;
}
private void remove(JSONObject graves) {
// pretend to be the server so we don't set usn = -1
boolean wasServer = mCol.getServer();
mCol.setServer(true);
try {
// notes first, so we don't end up with duplicate graves
mCol._remNotes(Utils.jsonArrayToLongArray(graves.getJSONArray("notes")));
// then cards
mCol.remCards(Utils.jsonArrayToLongArray(graves.getJSONArray("cards")));
// and deck
JSONArray decks = graves.getJSONArray("decks");
for (int i = 0; i < decks.length(); i++) {
mCol.getDecks().rem(decks.getLong(i));
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
mCol.setServer(wasServer);
}
/** Models
* ********************************************************************
*/
private JSONArray getModels() {
JSONArray result = new JSONArray();
try {
if (mCol.getServer()) {
for (JSONObject m : mCol.getModels().all()) {
if (m.getInt("usn") >= mMinUsn) {
result.put(m);
}
}
} else {
for (JSONObject m : mCol.getModels().all()) {
if (m.getInt("usn") == -1) {
m.put("usn", mMaxUsn);
result.put(m);
}
}
mCol.getModels().save();
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
return result;
}
private void mergeModels(JSONArray rchg) {
for (int i = 0; i < rchg.length(); i++) {
try {
JSONObject r = rchg.getJSONObject(i);
JSONObject l;
l = mCol.getModels().get(r.getLong("id"));
// if missing locally or server is newer, update
if (l == null || r.getLong("mod") > l.getLong("mod")) {
mCol.getModels().update(r);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
}
/** Decks
* ********************************************************************
*/
private JSONArray getDecks() {
JSONArray result = new JSONArray();
try {
if (mCol.getServer()) {
JSONArray decks = new JSONArray();
for (JSONObject g : mCol.getDecks().all()) {
if (g.getInt("usn") >= mMinUsn) {
decks.put(g);
}
}
JSONArray dconfs = new JSONArray();
for (JSONObject g : mCol.getDecks().allConf()) {
if (g.getInt("usn") >= mMinUsn) {
dconfs.put(g);
}
}
result.put(decks);
result.put(dconfs);
} else {
JSONArray decks = new JSONArray();
for (JSONObject g : mCol.getDecks().all()) {
if (g.getInt("usn") == -1) {
g.put("usn", mMaxUsn);
decks.put(g);
}
}
JSONArray dconfs = new JSONArray();
for (JSONObject g : mCol.getDecks().allConf()) {
if (g.getInt("usn") == -1) {
g.put("usn", mMaxUsn);
dconfs.put(g);
}
}
mCol.getDecks().save();
result.put(decks);
result.put(dconfs);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
return result;
}
private void mergeDecks(JSONArray rchg) {
try {
JSONArray decks = rchg.getJSONArray(0);
for (int i = 0; i < decks.length(); i++) {
JSONObject r = decks.getJSONObject(i);
JSONObject l = mCol.getDecks().get(r.getLong("id"), false);
// if missing locally or server is newer, update
if (l == null || r.getLong("mod") > l.getLong("mod")) {
mCol.getDecks().update(r);
}
}
JSONArray confs = rchg.getJSONArray(1);
for (int i = 0; i < confs.length(); i++) {
JSONObject r = confs.getJSONObject(i);
JSONObject l = mCol.getDecks().getConf(r.getLong("id"));
// if missing locally or server is newer, update
if (l == null || r.getLong("mod") > l.getLong("mod")) {
mCol.getDecks().updateConf(r);
}
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
/** Tags
* ********************************************************************
*/
private JSONArray getTags() {
JSONArray result = new JSONArray();
if (mCol.getServer()) {
for (Map.Entry<String, Integer> t : mCol.getTags().allItems().entrySet()) {
if (t.getValue() >= mMinUsn) {
JSONArray ta = new JSONArray();
ta.put(t.getKey());
ta.put(t.getValue());
result.put(ta);
}
}
} else {
for (Map.Entry<String, Integer> t : mCol.getTags().allItems().entrySet()) {
if (t.getValue() == -1) {
ArrayList<String> tag = new ArrayList<String>();
tag.add(t.getKey());
mCol.getTags().register(tag, mMaxUsn);
JSONArray ta = new JSONArray();
ta.put(t.getKey());
ta.put(t.getValue());
result.put(ta);
}
}
mCol.getTags().save();
}
return result;
}
private void mergeTags(JSONArray tags) {
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < tags.length(); i++) {
try {
list.add(tags.getString(i));
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
mCol.getTags().register(list, mMaxUsn);
}
/** Cards/notes/revlog
* ********************************************************************
*/
private void mergeRevlog(JSONArray logs) {
for (int i = 0; i < logs.length(); i++) {
try {
mCol.getDb().execute("INSERT OR IGNORE INTO revlog VALUES (?,?,?,?,?,?,?,?,?)", ConvUtils.jsonArray2Objects(logs.getJSONArray(i)));
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
}
private ArrayList<Object[]> newerRows(JSONArray data, String table, int modIdx) {
long[] ids = new long[data.length()];
try {
for (int i = 0; i < data.length(); i++) {
ids[i] = data.getJSONArray(i).getLong(0);
}
HashMap<Long, Long> lmods = new HashMap<Long, Long>();
Cursor cur = null;
try {
cur = mCol.getDb().getDatabase().rawQuery("SELECT id, mod FROM " + table + " WHERE id IN " + Utils.ids2str(ids) + " AND " + usnLim(), null);
while (cur.moveToNext()) {
lmods.put(cur.getLong(0), cur.getLong(1));
}
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
ArrayList<Object[]> update = new ArrayList<Object[]>();
for (int i = 0; i < data.length(); i++) {
JSONArray r = data.getJSONArray(i);
if (!lmods.containsKey(r.getLong(0)) || lmods.get(r.getLong(0)) < r.getLong(modIdx)) {
update.add(ConvUtils.jsonArray2Objects(r));
}
}
return update;
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
private void mergeCards(JSONArray cards) {
for (Object[] r : newerRows(cards, "cards", 4)) {
mCol.getDb().execute("INSERT OR REPLACE INTO cards VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", r);
}
}
private void mergeNotes(JSONArray notes) {
for (Object[] n : newerRows(notes, "notes", 4)) {
mCol.getDb().execute("INSERT OR REPLACE INTO notes VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", n);
mCol.updateFieldCache(new long[]{(Long) n[0]});
}
}
/** Col config
* ********************************************************************
*/
private JSONObject getConf() {
return mCol.getConf();
}
private void mergeConf(JSONObject conf) {
mCol.setConf(conf);
}
}
| false | true | public Object[] sync(Connection con) {
// if the deck has any pending changes, flush them first and bump mod time
mCol.save();
// step 1: login & metadata
HttpResponse ret = mServer.meta();
if (ret == null) {
return null;
}
int returntype = ret.getStatusLine().getStatusCode();
if (returntype == 403){
return new Object[] {"badAuth"};
} else if (returntype != 200) {
return new Object[] {"error", returntype, ret.getStatusLine().getReasonPhrase()};
}
long rts;
long lts;
try {
JSONArray ra = new JSONArray(mServer.stream2String(ret.getEntity().getContent()));
mRMod = ra.getLong(0);
mRScm = ra.getLong(1);
mMaxUsn = ra.getInt(2);
rts = ra.getLong(3);
mMediaUsn = ra.getInt(4);
JSONArray la = meta();
mLMod = la.getLong(0);
mLScm = la.getLong(1);
mMinUsn = la.getInt(2);
lts = la.getLong(3);
long diff = Math.abs(rts - lts);
if (diff > 300) {
return new Object[]{"clockOff", diff};
}
if (mLMod == mRMod) {
return new Object[]{"noChanges"};
} else if (mLScm != mRScm) {
return new Object[]{"fullSync"};
}
mLNewer = mLMod > mRMod;
// step 2: deletions
con.publishProgress(R.string.sync_deletions_message);
JSONObject lrem = removed();
JSONObject o = new JSONObject();
o.put("minUsn", mMinUsn);
o.put("lnewer", mLNewer);
o.put("graves", lrem);
JSONObject rrem = mServer.start(o);
if (rrem == null) {
return null;
}
if (rrem.has("errorType")) {
return new Object[]{"error", rrem.get("errorType"), rrem.get("errorReason")};
}
remove(rrem);
// ... and small objects
con.publishProgress(R.string.sync_small_objects_message);
JSONObject lchg = changes();
JSONObject sch = new JSONObject();
sch.put("changes", lchg);
JSONObject rchg = mServer.applyChanges(sch);
if (rchg == null) {
return null;
}
if (rchg.has("errorType")) {
return new Object[]{"error", rchg.get("errorType"), rchg.get("errorReason")};
}
mergeChanges(lchg, rchg);
// step 3: stream large tables from server
con.publishProgress(R.string.sync_download_chunk);
while (true) {
JSONObject chunk = mServer.chunk();
if (chunk == null) {
return null;
}
if (chunk.has("errorType")) {
return new Object[]{"error", chunk.get("errorType"), chunk.get("errorReason")};
}
applyChunk(chunk);
if (chunk.getBoolean("done")) {
break;
}
}
// step 4: stream to server
con.publishProgress(R.string.sync_upload_chunk);
while (true) {
JSONObject chunk = chunk();
JSONObject sech = new JSONObject();
sech.put("chunk", chunk);
mServer.applyChunk(sech);
if (chunk.getBoolean("done")) {
break;
}
}
// step 5: sanity check during beta testing
JSONArray c = sanityCheck();
JSONArray s = mServer.sanityCheck();
if (s.getString(0).equals("error")) {
return new Object[]{"error", 200, "sanity check error on server"};
}
for (int i = 0; i < s.getJSONArray(0).length(); i++) {
if (c.getJSONArray(0).getLong(i) != s.getJSONArray(0).getLong(i)) {
return new Object[]{"error", 200, "sanity check failed: 1/" + i};
}
}
for (int i = 1; i < s.length(); i++) {
if (c.getLong(i) != s.getLong(i)) {
return new Object[]{"error", 200, "sanity check failed: " + i};
}
}
} catch (JSONException e) {
throw new RuntimeException(e);
} catch (IllegalStateException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
// finalize
con.publishProgress(R.string.sync_finish_message);
long mod = mServer.finish();
if (mod == 0) {
return new Object[]{"finishError"};
}
finish(mod);
return new Object[]{"success"};
}
| public Object[] sync(Connection con) {
// if the deck has any pending changes, flush them first and bump mod time
mCol.save();
// step 1: login & metadata
HttpResponse ret = mServer.meta();
if (ret == null) {
return null;
}
int returntype = ret.getStatusLine().getStatusCode();
if (returntype == 403){
return new Object[] {"badAuth"};
} else if (returntype != 200) {
return new Object[] {"error", returntype, ret.getStatusLine().getReasonPhrase()};
}
long rts;
long lts;
try {
JSONArray ra = new JSONArray(mServer.stream2String(ret.getEntity().getContent()));
mRMod = ra.getLong(0);
mRScm = ra.getLong(1);
mMaxUsn = ra.getInt(2);
rts = ra.getLong(3);
mMediaUsn = ra.getInt(4);
JSONArray la = meta();
mLMod = la.getLong(0);
mLScm = la.getLong(1);
mMinUsn = la.getInt(2);
lts = la.getLong(3);
long diff = Math.abs(rts - lts);
if (diff > 300) {
return new Object[]{"clockOff", diff};
}
if (mLMod == mRMod) {
return new Object[]{"noChanges"};
} else if (mLScm != mRScm) {
return new Object[]{"fullSync"};
}
mLNewer = mLMod > mRMod;
// step 2: deletions
con.publishProgress(R.string.sync_deletions_message);
JSONObject lrem = removed();
JSONObject o = new JSONObject();
o.put("minUsn", mMinUsn);
o.put("lnewer", mLNewer);
o.put("graves", lrem);
JSONObject rrem = mServer.start(o);
if (rrem == null) {
return null;
}
if (rrem.has("errorType")) {
return new Object[]{"error", rrem.get("errorType"), rrem.get("errorReason")};
}
remove(rrem);
// ... and small objects
con.publishProgress(R.string.sync_small_objects_message);
JSONObject lchg = changes();
JSONObject sch = new JSONObject();
sch.put("changes", lchg);
JSONObject rchg = mServer.applyChanges(sch);
if (rchg == null) {
return null;
}
if (rchg.has("errorType")) {
return new Object[]{"error", rchg.get("errorType"), rchg.get("errorReason")};
}
mergeChanges(lchg, rchg);
// step 3: stream large tables from server
con.publishProgress(R.string.sync_download_chunk);
while (true) {
JSONObject chunk = mServer.chunk();
if (chunk == null) {
return null;
}
if (chunk.has("errorType")) {
return new Object[]{"error", chunk.get("errorType"), chunk.get("errorReason")};
}
applyChunk(chunk);
if (chunk.getBoolean("done")) {
break;
}
}
// step 4: stream to server
con.publishProgress(R.string.sync_upload_chunk);
while (true) {
JSONObject chunk = chunk();
JSONObject sech = new JSONObject();
sech.put("chunk", chunk);
mServer.applyChunk(sech);
if (chunk.getBoolean("done")) {
break;
}
}
// step 5: sanity check during beta testing
JSONArray c = sanityCheck();
JSONArray s = mServer.sanityCheck();
if (s.getString(0).equals("error")) {
return new Object[]{"error", 200, "sanity check error on server"};
}
boolean error = false;
for (int i = 0; i < s.getJSONArray(0).length(); i++) {
if (c.getJSONArray(0).getLong(i) != s.getJSONArray(0).getLong(i)) {
error = true;
}
}
for (int i = 1; i < s.length(); i++) {
if (c.getLong(i) != s.getLong(i)) {
error = true;
}
}
if (error) {
return new Object[]{"error", 200, "sanity check failed:\nl: " + c.toString() + "\nr: " + l.toString()};
}
} catch (JSONException e) {
throw new RuntimeException(e);
} catch (IllegalStateException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
// finalize
con.publishProgress(R.string.sync_finish_message);
long mod = mServer.finish();
if (mod == 0) {
return new Object[]{"finishError"};
}
finish(mod);
return new Object[]{"success"};
}
|
diff --git a/src/com/irccloud/android/MessageActivity.java b/src/com/irccloud/android/MessageActivity.java
index 7e3124df..0cddf259 100644
--- a/src/com/irccloud/android/MessageActivity.java
+++ b/src/com/irccloud/android/MessageActivity.java
@@ -1,2068 +1,2070 @@
package com.irccloud.android;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.google.android.gcm.GCMRegistrar;
import com.irccloud.android.BanListFragment.AddClickListener;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.UnderlineSpan;
import android.text.util.Linkify;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.OnEditorActionListener;
public class MessageActivity extends BaseActivity implements UsersListFragment.OnUserSelectedListener, BuffersListFragment.OnBufferSelectedListener, MessageViewFragment.MessageViewListener {
int cid = -1;
int bid = -1;
String name;
String type;
ActionEditText messageTxt;
View sendBtn;
int joined;
int archived;
String status;
UsersDataSource.User selected_user;
View userListView;
View buffersListView;
TextView title;
TextView subtitle;
ImageView key;
LinearLayout messageContainer;
HorizontalScrollView scrollView;
NetworkConnection conn;
private boolean shouldFadeIn = false;
ImageView upView;
private RefreshUpIndicatorTask refreshUpIndicatorTask = null;
private ShowNotificationsTask showNotificationsTask = null;
private ArrayList<Integer> backStack = new ArrayList<Integer>();
PowerManager.WakeLock screenLock = null;
private int launchBid = -1;
private Uri launchURI = null;
private AlertDialog channelsListDialog;
private HashMap<Integer, EventsDataSource.Event> pendingEvents = new HashMap<Integer, EventsDataSource.Event>();
@SuppressLint("NewApi")
@SuppressWarnings({ "deprecation", "unchecked" })
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setBackgroundDrawable(null);
setContentView(R.layout.activity_message);
buffersListView = findViewById(R.id.BuffersList);
messageContainer = (LinearLayout)findViewById(R.id.messageContainer);
scrollView = (HorizontalScrollView)findViewById(R.id.scroll);
if(scrollView != null) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)messageContainer.getLayoutParams();
params.width = getWindowManager().getDefaultDisplay().getWidth();
messageContainer.setLayoutParams(params);
}
messageTxt = (ActionEditText)findViewById(R.id.messageTxt);
messageTxt.setEnabled(false);
messageTxt.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && messageTxt.getText() != null && messageTxt.getText().length() > 0) {
new SendTask().execute((Void)null);
}
return false;
}
});
messageTxt.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(scrollView != null && v == messageTxt && hasFocus) {
scrollView.scrollTo((int)getResources().getDimension(R.dimen.drawer_width), 0);
upView.setVisibility(View.VISIBLE);
}
}
});
messageTxt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(scrollView != null) {
scrollView.scrollTo((int)getResources().getDimension(R.dimen.drawer_width), 0);
upView.setVisibility(View.VISIBLE);
}
}
});
messageTxt.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEND && messageTxt.getText() != null && messageTxt.getText().length() > 0) {
new SendTask().execute((Void)null);
}
return true;
}
});
messageTxt.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
Object[] spans = s.getSpans(0, s.length(), Object.class);
for(Object o : spans) {
if(((s.getSpanFlags(o) & Spanned.SPAN_COMPOSING) != Spanned.SPAN_COMPOSING) && (o.getClass() == StyleSpan.class || o.getClass() == ForegroundColorSpan.class || o.getClass() == BackgroundColorSpan.class || o.getClass() == UnderlineSpan.class)) {
s.removeSpan(o);
}
}
if(s.length() > 0) {
sendBtn.setEnabled(true);
if(Build.VERSION.SDK_INT >= 11)
sendBtn.setAlpha(1);
} else {
sendBtn.setEnabled(false);
if(Build.VERSION.SDK_INT >= 11)
sendBtn.setAlpha(0.5f);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
sendBtn = findViewById(R.id.sendBtn);
sendBtn.setFocusable(false);
sendBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new SendTask().execute((Void)null);
}
});
userListView = findViewById(R.id.usersListFragment);
getSupportActionBar().setLogo(R.drawable.logo);
getSupportActionBar().setHomeButtonEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
View v = getLayoutInflater().inflate(R.layout.actionbar_messageview, null);
v.findViewById(R.id.actionTitleArea).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(bid);
if(c != null) {
AlertDialog.Builder builder = new AlertDialog.Builder(MessageActivity.this);
builder.setTitle("Channel Topic");
if(c.topic_text.length() > 0) {
builder.setMessage(ColorFormatter.html_to_spanned(TextUtils.htmlEncode(c.topic_text), true, ServersDataSource.getInstance().getServer(cid)));
} else
builder.setMessage("No topic set.");
builder.setPositiveButton("Close", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
boolean canEditTopic;
if(c.mode.contains("t")) {
UsersDataSource.User self_user = UsersDataSource.getInstance().getUser(cid, name, ServersDataSource.getInstance().getServer(cid).nick);
if(self_user != null && (self_user.mode.contains("q") || self_user.mode.contains("a") || self_user.mode.contains("o"))) {
canEditTopic = true;
} else {
canEditTopic = false;
}
} else {
canEditTopic = true;
}
if(canEditTopic) {
builder.setNeutralButton("Edit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
editTopic();
}
});
}
final AlertDialog dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.show();
((TextView)dialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
((TextView)dialog.findViewById(android.R.id.message)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
} else if(archived == 0 && subtitle.getText().length() > 0){
AlertDialog.Builder builder = new AlertDialog.Builder(MessageActivity.this);
builder.setTitle(title.getText().toString());
final SpannableString s = new SpannableString(subtitle.getText().toString());
Linkify.addLinks(s, Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES);
builder.setMessage(s);
builder.setPositiveButton("Close", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.show();
((TextView)dialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
}
}
});
upView = (ImageView)v.findViewById(R.id.upIndicator);
if(scrollView != null) {
upView.setVisibility(View.VISIBLE);
upView.setOnClickListener(upClickListener);
ImageView icon = (ImageView)v.findViewById(R.id.upIcon);
icon.setOnClickListener(upClickListener);
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
} else {
upView.setVisibility(View.INVISIBLE);
}
messageTxt.setScrollView(scrollView, upView);
title = (TextView)v.findViewById(R.id.title);
subtitle = (TextView)v.findViewById(R.id.subtitle);
key = (ImageView)v.findViewById(R.id.key);
getSupportActionBar().setCustomView(v);
if(savedInstanceState != null && savedInstanceState.containsKey("cid")) {
cid = savedInstanceState.getInt("cid");
bid = savedInstanceState.getInt("bid");
name = savedInstanceState.getString("name");
type = savedInstanceState.getString("type");
joined = savedInstanceState.getInt("joined");
archived = savedInstanceState.getInt("archived");
status = savedInstanceState.getString("status");
backStack = (ArrayList<Integer>) savedInstanceState.getSerializable("backStack");
}
try {
if(getSharedPreferences("prefs", 0).contains("session_key")) {
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
GCMRegistrar.register(this, GCMIntentService.GCM_ID);
} else {
if(!getSharedPreferences("prefs", 0).contains("gcm_registered"))
GCMIntentService.scheduleRegisterTimer(30000);
}
}
} catch (Exception e) {
//GCM might not be available on the device
}
}
@Override
public void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putInt("cid", cid);
state.putInt("bid", bid);
state.putString("name", name);
state.putString("type", type);
state.putInt("joined", joined);
state.putInt("archived", archived);
state.putString("status", status);
state.putSerializable("backStack", backStack);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) { //Back key pressed
if(scrollView != null && (scrollView.getScrollX() >= buffersListView.getWidth() + userListView.getWidth() || scrollView.getScrollX() < buffersListView.getWidth())) {
scrollView.smoothScrollTo(buffersListView.getWidth(), 0);
upView.setVisibility(View.VISIBLE);
return true;
} else if(backStack != null && backStack.size() > 0) {
Integer bid = backStack.get(0);
backStack.remove(0);
BuffersDataSource.Buffer buffer = BuffersDataSource.getInstance().getBuffer(bid);
if(buffer != null) {
ServersDataSource.Server s = ServersDataSource.getInstance().getServer(buffer.cid);
if(s != null)
status = s.status;
String name = buffer.name;
if(buffer.type.equalsIgnoreCase("console")) {
if(s != null) {
if(s.name != null && s.name.length() > 0)
name = s.name;
else
name = s.hostname;
}
}
onBufferSelected(buffer.cid, buffer.bid, name, buffer.last_seen_eid, buffer.min_eid,
buffer.type, 1, buffer.archived, status);
if(backStack.size() > 0)
backStack.remove(0);
} else {
return super.onKeyDown(keyCode, event);
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
private class SendTask extends AsyncTaskEx<Void, Void, Void> {
EventsDataSource.Event e = null;
@Override
protected void onPreExecute() {
MessageViewFragment mvf = (MessageViewFragment)getSupportFragmentManager().findFragmentById(R.id.messageViewFragment);
if(mvf != null && mvf.bid != bid) {
Log.w("IRCCloud", "MessageViewFragment's bid differs from MessageActivity's, switching buffers again");
open_bid(mvf.bid);
}
if(conn.getState() == NetworkConnection.STATE_CONNECTED && messageTxt.getText() != null && messageTxt.getText().length() > 0) {
ServersDataSource.Server s = ServersDataSource.getInstance().getServer(cid);
if(s != null) {
sendBtn.setEnabled(false);
UsersDataSource.User u = UsersDataSource.getInstance().getUser(cid, name, s.nick);
e = EventsDataSource.getInstance().new Event();
e.cid = cid;
e.bid = bid;
e.eid = (System.currentTimeMillis() + conn.clockOffset + 5000) * 1000L;
e.self = true;
e.from = s.nick;
e.nick = s.nick;
if(u != null)
e.from_mode = u.mode;
String msg = messageTxt.getText().toString();
if(msg.startsWith("//"))
msg = msg.substring(1);
else if(msg.startsWith("/") && !msg.startsWith("/me "))
msg = null;
e.msg = msg;
if(msg != null && msg.toLowerCase().startsWith("/me ")) {
e.type = "buffer_me_msg";
e.msg = msg.substring(4);
} else {
e.type = "buffer_msg";
}
e.color = R.color.timestamp;
if(name.equals(s.nick))
e.bg_color = R.color.message_bg;
else
e.bg_color = R.color.self;
e.row_type = 0;
e.html = null;
e.group_msg = null;
e.linkify = true;
e.target_mode = null;
e.highlight = false;
e.reqid = -1;
e.pending = true;
if(e.msg != null) {
e.msg = TextUtils.htmlEncode(e.msg);
EventsDataSource.getInstance().addEvent(e);
conn.notifyHandlers(NetworkConnection.EVENT_BUFFERMSG, e, mHandler);
}
}
}
}
@Override
protected Void doInBackground(Void... arg0) {
if(e != null && conn.getState() == NetworkConnection.STATE_CONNECTED && messageTxt.getText() != null && messageTxt.getText().length() > 0) {
e.reqid = conn.say(cid, name, messageTxt.getText().toString());
if(e.msg != null)
pendingEvents.put(e.reqid, e);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if(e != null && e.reqid != -1) {
messageTxt.setText("");
}
sendBtn.setEnabled(true);
}
}
private class RefreshUpIndicatorTask extends AsyncTaskEx<Void, Void, Void> {
int unread = 0;
int highlights = 0;
@Override
protected Void doInBackground(Void... arg0) {
ArrayList<ServersDataSource.Server> servers = ServersDataSource.getInstance().getServers();
JSONObject channelDisabledMap = null;
JSONObject bufferDisabledMap = null;
if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) {
try {
if(conn.getUserInfo().prefs.has("channel-disableTrackUnread"))
channelDisabledMap = conn.getUserInfo().prefs.getJSONObject("channel-disableTrackUnread");
if(conn.getUserInfo().prefs.has("buffer-disableTrackUnread"))
bufferDisabledMap = conn.getUserInfo().prefs.getJSONObject("buffer-disableTrackUnread");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int i = 0; i < servers.size(); i++) {
ServersDataSource.Server s = servers.get(i);
ArrayList<BuffersDataSource.Buffer> buffers = BuffersDataSource.getInstance().getBuffersForServer(s.cid);
for(int j = 0; j < buffers.size(); j++) {
BuffersDataSource.Buffer b = buffers.get(j);
if(b.bid != bid) {
if(unread == 0) {
int u = 0;
try {
u = EventsDataSource.getInstance().getUnreadCountForBuffer(b.bid, b.last_seen_eid, b.type);
if(b.type.equalsIgnoreCase("channel") && channelDisabledMap != null && channelDisabledMap.has(String.valueOf(b.bid)) && channelDisabledMap.getBoolean(String.valueOf(b.bid)))
u = 0;
else if(bufferDisabledMap != null && bufferDisabledMap.has(String.valueOf(b.bid)) && bufferDisabledMap.getBoolean(String.valueOf(b.bid)))
u = 0;
} catch (JSONException e) {
e.printStackTrace();
}
unread += u;
}
if(highlights == 0) {
try {
if(!b.type.equalsIgnoreCase("conversation") || bufferDisabledMap == null || !bufferDisabledMap.has(String.valueOf(b.bid)) || !bufferDisabledMap.getBoolean(String.valueOf(b.bid)))
highlights += EventsDataSource.getInstance().getHighlightCountForBuffer(b.bid, b.last_seen_eid, b.type);
} catch (JSONException e) {
}
}
}
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if(!isCancelled()) {
if(highlights > 0) {
upView.setImageResource(R.drawable.up_highlight);
} else if(unread > 0) {
upView.setImageResource(R.drawable.up_unread);
} else {
upView.setImageResource(R.drawable.up);
}
refreshUpIndicatorTask = null;
}
}
}
private class ShowNotificationsTask extends AsyncTaskEx<Integer, Void, Void> {
@Override
protected Void doInBackground(Integer... params) {
Notifications.getInstance().excludeBid(params[0]);
if(params[0] > 0)
Notifications.getInstance().showNotifications(null);
showNotificationsTask = null;
return null;
}
}
private void setFromIntent(Intent intent) {
long min_eid = 0;
long last_seen_eid = 0;
launchBid = -1;
launchURI = null;
if(intent.hasExtra("bid")) {
int new_bid = intent.getIntExtra("bid", 0);
if(NetworkConnection.getInstance().ready && BuffersDataSource.getInstance().getBuffer(new_bid) == null) {
Log.w("IRCCloud", "Invalid bid requested by launch intent: " + new_bid);
Notifications.getInstance().deleteNotificationsForBid(new_bid);
if(showNotificationsTask != null)
showNotificationsTask.cancel(true);
showNotificationsTask = new ShowNotificationsTask();
showNotificationsTask.execute(bid);
return;
} else {
if(bid >= 0)
backStack.add(0, bid);
bid = new_bid;
}
}
if(intent.getData() != null && intent.getData().getScheme().startsWith("irc")) {
if(open_uri(intent.getData()))
return;
launchURI = intent.getData();
} else if(intent.hasExtra("cid")) {
cid = intent.getIntExtra("cid", 0);
name = intent.getStringExtra("name");
type = intent.getStringExtra("type");
joined = intent.getIntExtra("joined", 0);
archived = intent.getIntExtra("archived", 0);
status = intent.getStringExtra("status");
min_eid = intent.getLongExtra("min_eid", 0);
last_seen_eid = intent.getLongExtra("last_seen_eid", 0);
if(bid == -1) {
BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(cid, name);
if(b != null) {
bid = b.bid;
last_seen_eid = b.last_seen_eid;
min_eid = b.min_eid;
archived = b.archived;
}
}
} else if(bid != -1) {
BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBuffer(bid);
if(b != null) {
ServersDataSource.Server s = ServersDataSource.getInstance().getServer(b.cid);
joined = 1;
if(b.type.equalsIgnoreCase("channel")) {
ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(b.bid);
if(c == null)
joined = 0;
}
if(b.type.equalsIgnoreCase("console"))
b.name = s.name;
cid = b.cid;
name = b.name;
type = b.type;
archived = b.archived;
min_eid = b.min_eid;
last_seen_eid = b.last_seen_eid;
status = s.status;
} else {
cid = -1;
}
}
if(cid == -1) {
launchBid = bid;
} else {
UsersListFragment ulf = (UsersListFragment)getSupportFragmentManager().findFragmentById(R.id.usersListFragment);
MessageViewFragment mvf = (MessageViewFragment)getSupportFragmentManager().findFragmentById(R.id.messageViewFragment);
Bundle b = new Bundle();
b.putInt("cid", cid);
b.putInt("bid", bid);
b.putLong("last_seen_eid", last_seen_eid);
b.putLong("min_eid", min_eid);
b.putString("name", name);
b.putString("type", type);
ulf.setArguments(b);
mvf.setArguments(b);
messageTxt.setEnabled(true);
}
}
@Override
protected void onNewIntent(Intent intent) {
if(intent != null) {
setFromIntent(intent);
}
}
@SuppressLint("NewApi")
@Override
public void onResume() {
conn = NetworkConnection.getInstance();
if(!conn.ready) {
super.onResume();
Intent i = new Intent(this, MainActivity.class);
if(getIntent() != null) {
if(getIntent().getData() != null)
i.setData(getIntent().getData());
if(getIntent().getExtras() != null)
i.putExtras(getIntent().getExtras());
}
startActivity(i);
finish();
return;
}
conn.addHandler(mHandler);
super.onResume();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(prefs.getBoolean("screenlock", false)) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
if(conn.getState() != NetworkConnection.STATE_CONNECTED) {
if(scrollView != null && !NetworkConnection.getInstance().ready) {
scrollView.setEnabled(false);
upView.setVisibility(View.INVISIBLE);
}
messageTxt.setEnabled(false);
} else {
if(scrollView != null) {
scrollView.setEnabled(true);
scrollView.scrollTo((int)getResources().getDimension(R.dimen.drawer_width), 0);
upView.setVisibility(View.VISIBLE);
}
messageTxt.setEnabled(true);
}
if(cid == -1) {
if(getIntent() != null && (getIntent().hasExtra("bid") || getIntent().getData() != null)) {
setFromIntent(getIntent());
} else if(conn.getState() == NetworkConnection.STATE_CONNECTED && conn.getUserInfo() != null && NetworkConnection.getInstance().ready) {
if(!open_bid(conn.getUserInfo().last_selected_bid)) {
if(!open_bid(BuffersDataSource.getInstance().firstBid())) {
if(scrollView != null && NetworkConnection.getInstance().ready)
scrollView.scrollTo(0,0);
}
}
}
}
updateUsersListFragmentVisibility();
title.setText(name);
getSupportActionBar().setTitle(name);
update_subtitle();
if(getSupportFragmentManager().findFragmentById(R.id.BuffersList) != null)
((BuffersListFragment)getSupportFragmentManager().findFragmentById(R.id.BuffersList)).setSelectedBid(bid);
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
invalidateOptionsMenu();
if(NetworkConnection.getInstance().ready) {
if(showNotificationsTask != null)
showNotificationsTask.cancel(true);
showNotificationsTask = new ShowNotificationsTask();
showNotificationsTask.execute(bid);
}
sendBtn.setEnabled(messageTxt.getText().length() > 0);
if(Build.VERSION.SDK_INT >= 11 && messageTxt.getText().length() == 0)
sendBtn.setAlpha(0.5f);
}
@Override
public void onPause() {
super.onPause();
if(showNotificationsTask != null)
showNotificationsTask.cancel(true);
showNotificationsTask = new ShowNotificationsTask();
showNotificationsTask.execute(-1);
if(channelsListDialog != null)
channelsListDialog.dismiss();
if(conn != null)
conn.removeHandler(mHandler);
}
private boolean open_uri(Uri uri) {
if(uri != null && NetworkConnection.getInstance().ready) {
ServersDataSource.Server s = null;
if(uri.getPort() > 0)
s = ServersDataSource.getInstance().getServer(uri.getHost(), uri.getPort());
else if(uri.getScheme().equalsIgnoreCase("ircs"))
s = ServersDataSource.getInstance().getServer(uri.getHost(), true);
else
s = ServersDataSource.getInstance().getServer(uri.getHost());
if(s != null) {
if(uri.getPath().length() > 1) {
String key = null;
String channel = uri.getPath().substring(1);
if(channel.contains(",")) {
key = channel.substring(channel.indexOf(",") + 1);
channel = channel.substring(0, channel.indexOf(","));
}
BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(s.cid, channel);
if(b != null)
return open_bid(b.bid);
else
conn.join(s.cid, channel, key);
return true;
} else {
BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(s.cid, "*");
if(b != null)
return open_bid(b.bid);
}
} else {
EditConnectionFragment connFragment = new EditConnectionFragment();
connFragment.default_hostname = uri.getHost();
if(uri.getPort() > 0)
connFragment.default_port = uri.getPort();
else if(uri.getScheme().equalsIgnoreCase("ircs"))
connFragment.default_port = 6697;
if(uri.getPath().length() > 1)
connFragment.default_channels = uri.getPath().substring(1).replace(",", " ");
connFragment.show(getSupportFragmentManager(), "addnetwork");
return true;
}
}
return false;
}
private boolean open_bid(int bid) {
BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBuffer(bid);
if(b != null) {
ServersDataSource.Server s = ServersDataSource.getInstance().getServer(b.cid);
int joined = 1;
if(b.type.equalsIgnoreCase("channel")) {
ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(b.bid);
if(c == null)
joined = 0;
}
String name = b.name;
if(b.type.equalsIgnoreCase("console")) {
if(s.name != null && s.name.length() > 0)
name = s.name;
else
name = s.hostname;
}
onBufferSelected(b.cid, b.bid, name, b.last_seen_eid, b.min_eid, b.type, joined, b.archived, s.status);
return true;
}
Log.w("IRCCloud", "Requested BID not found");
return false;
}
private void update_subtitle() {
if(cid == -1 || !NetworkConnection.getInstance().ready) {
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowCustomEnabled(false);
} else {
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setDisplayShowCustomEnabled(true);
if(archived > 0 && !type.equalsIgnoreCase("console")) {
subtitle.setVisibility(View.VISIBLE);
subtitle.setText("(archived)");
} else {
if(type == null) {
subtitle.setVisibility(View.GONE);
} else if(type.equalsIgnoreCase("conversation")) {
UsersDataSource.User user = UsersDataSource.getInstance().getUser(cid, name);
BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBuffer(bid);
if(user != null && user.away > 0) {
subtitle.setVisibility(View.VISIBLE);
if(user.away_msg != null && user.away_msg.length() > 0) {
subtitle.setText("Away: " + user.away_msg);
} else if(b != null && b.away_msg != null && b.away_msg.length() > 0) {
subtitle.setText("Away: " + b.away_msg);
} else {
subtitle.setText("Away");
}
} else {
subtitle.setVisibility(View.GONE);
}
key.setVisibility(View.GONE);
} else if(type.equalsIgnoreCase("channel")) {
ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(bid);
if(c != null && c.topic_text.length() > 0) {
subtitle.setVisibility(View.VISIBLE);
subtitle.setText(c.topic_text);
} else {
subtitle.setVisibility(View.GONE);
}
if(c != null && c.mode.contains("k")) {
key.setVisibility(View.VISIBLE);
} else {
key.setVisibility(View.GONE);
}
} else if(type.equalsIgnoreCase("console")) {
ServersDataSource.Server s = ServersDataSource.getInstance().getServer(cid);
if(s != null) {
subtitle.setVisibility(View.VISIBLE);
subtitle.setText(s.hostname + ":" + s.port);
} else {
subtitle.setVisibility(View.GONE);
}
key.setVisibility(View.GONE);
}
}
}
invalidateOptionsMenu();
}
private void updateUsersListFragmentVisibility() {
boolean hide = false;
if(userListView != null) {
try {
if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) {
JSONObject hiddenMap = conn.getUserInfo().prefs.getJSONObject("channel-hiddenMembers");
if(hiddenMap.has(String.valueOf(bid)) && hiddenMap.getBoolean(String.valueOf(bid)))
hide = true;
}
} catch (Exception e) {
e.printStackTrace();
}
if(hide || type == null || !type.equalsIgnoreCase("channel") || joined == 0)
userListView.setVisibility(View.GONE);
else
userListView.setVisibility(View.VISIBLE);
}
}
@SuppressLint("HandlerLeak")
private final Handler mHandler = new Handler() {
String bufferToOpen = null;
int cidToOpen = -1;
public void handleMessage(Message msg) {
Integer event_bid = 0;
IRCCloudJSONObject event = null;
Bundle args = null;
switch (msg.what) {
case NetworkConnection.EVENT_LINKCHANNEL:
event = (IRCCloudJSONObject)msg.obj;
if(cidToOpen == event.cid() && event.getString("invalid_chan").equalsIgnoreCase(bufferToOpen)) {
bufferToOpen = event.getString("valid_chan");
msg.obj = BuffersDataSource.getInstance().getBuffer(event.bid());
+ } else {
+ return;
}
case NetworkConnection.EVENT_MAKEBUFFER:
BuffersDataSource.Buffer b = (BuffersDataSource.Buffer)msg.obj;
if(cidToOpen == b.cid && b.name.equalsIgnoreCase(bufferToOpen) && !bufferToOpen.equalsIgnoreCase(name)) {
onBufferSelected(b.cid, b.bid, b.name, b.last_seen_eid, b.min_eid, b.type, 1, 0, "connected_ready");
bufferToOpen = null;
cidToOpen = -1;
} else if(bid == -1 && b.cid == cid && b.name.equalsIgnoreCase(name)) {
bid = b.bid;
if(getSupportFragmentManager().findFragmentById(R.id.BuffersList) != null)
((BuffersListFragment)getSupportFragmentManager().findFragmentById(R.id.BuffersList)).setSelectedBid(bid);
if(showNotificationsTask != null)
showNotificationsTask.cancel(true);
showNotificationsTask = new ShowNotificationsTask();
showNotificationsTask.execute(bid);
}
break;
case NetworkConnection.EVENT_OPENBUFFER:
event = (IRCCloudJSONObject)msg.obj;
try {
bufferToOpen = event.getString("name");
cidToOpen = event.cid();
b = BuffersDataSource.getInstance().getBufferByName(cidToOpen, bufferToOpen);
if(b != null && !bufferToOpen.equalsIgnoreCase(name)) {
onBufferSelected(b.cid, b.bid, b.name, b.last_seen_eid, b.min_eid, b.type, 1, 0, "connected_ready");
bufferToOpen = null;
cidToOpen = -1;
}
} catch (Exception e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
break;
case NetworkConnection.EVENT_CONNECTIVITY:
if(conn.getState() == NetworkConnection.STATE_CONNECTED) {
for(EventsDataSource.Event e : pendingEvents.values()) {
EventsDataSource.getInstance().deleteEvent(e.eid, e.bid);
}
pendingEvents.clear();
if(scrollView != null && NetworkConnection.getInstance().ready) {
scrollView.setEnabled(true);
if(scrollView.getScrollX() > 0)
upView.setVisibility(View.VISIBLE);
}
if(cid != -1)
messageTxt.setEnabled(true);
} else {
if(scrollView != null && NetworkConnection.getInstance().ready) {
scrollView.setEnabled(false);
scrollView.smoothScrollTo((int)getResources().getDimension(R.dimen.drawer_width), 0);
upView.setVisibility(View.VISIBLE);
}
messageTxt.setEnabled(false);
}
break;
case NetworkConnection.EVENT_BANLIST:
event = (IRCCloudJSONObject)msg.obj;
if(event.getString("channel").equalsIgnoreCase(name)) {
args = new Bundle();
args.putInt("cid", cid);
args.putInt("bid", bid);
args.putString("event", event.toString());
BanListFragment banList = (BanListFragment)getSupportFragmentManager().findFragmentByTag("banlist");
if(banList == null) {
banList = new BanListFragment();
banList.setArguments(args);
banList.show(getSupportFragmentManager(), "banlist");
} else {
banList.setArguments(args);
}
}
break;
case NetworkConnection.EVENT_ACCEPTLIST:
event = (IRCCloudJSONObject)msg.obj;
if(event.cid() == cid) {
args = new Bundle();
args.putInt("cid", cid);
args.putString("event", event.toString());
AcceptListFragment acceptList = (AcceptListFragment)getSupportFragmentManager().findFragmentByTag("acceptlist");
if(acceptList == null) {
acceptList = new AcceptListFragment();
acceptList.setArguments(args);
acceptList.show(getSupportFragmentManager(), "acceptlist");
} else {
acceptList.setArguments(args);
}
}
break;
case NetworkConnection.EVENT_WHOLIST:
event = (IRCCloudJSONObject)msg.obj;
args = new Bundle();
args.putString("event", event.toString());
WhoListFragment whoList = (WhoListFragment)getSupportFragmentManager().findFragmentByTag("wholist");
if(whoList == null) {
whoList = new WhoListFragment();
whoList.setArguments(args);
whoList.show(getSupportFragmentManager(), "wholist");
} else {
whoList.setArguments(args);
}
break;
case NetworkConnection.EVENT_WHOIS:
event = (IRCCloudJSONObject)msg.obj;
args = new Bundle();
args.putString("event", event.toString());
WhoisFragment whois = (WhoisFragment)getSupportFragmentManager().findFragmentByTag("whois");
if(whois == null) {
whois = new WhoisFragment();
whois.setArguments(args);
whois.show(getSupportFragmentManager(), "whois");
} else {
whois.setArguments(args);
}
break;
case NetworkConnection.EVENT_LISTRESPONSEFETCHING:
event = (IRCCloudJSONObject)msg.obj;
String dialogtitle = "List of channels on " + ServersDataSource.getInstance().getServer(event.cid()).hostname;
if(channelsListDialog == null) {
Context ctx = MessageActivity.this;
if(Build.VERSION.SDK_INT < 11)
ctx = new ContextThemeWrapper(ctx, android.R.style.Theme_Dialog);
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setView(getLayoutInflater().inflate(R.layout.dialog_channelslist, null));
builder.setTitle(dialogtitle);
builder.setNegativeButton("Close", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
channelsListDialog = builder.create();
channelsListDialog.setOwnerActivity(MessageActivity.this);
} else {
channelsListDialog.setTitle(dialogtitle);
}
channelsListDialog.show();
ChannelListFragment channels = (ChannelListFragment)getSupportFragmentManager().findFragmentById(R.id.channelListFragment);
args = new Bundle();
args.putInt("cid", event.cid());
channels.setArguments(args);
break;
case NetworkConnection.EVENT_BACKLOG_END:
if(scrollView != null) {
scrollView.setEnabled(true);
if(scrollView.getScrollX() > 0)
upView.setVisibility(View.VISIBLE);
}
if(cid == -1) {
if(launchURI == null || !open_uri(launchURI)) {
if(launchBid == -1 || !open_bid(launchBid)) {
if(conn.getUserInfo() == null || !open_bid(conn.getUserInfo().last_selected_bid)) {
if(!open_bid(BuffersDataSource.getInstance().firstBid())) {
if(scrollView != null && NetworkConnection.getInstance().ready) {
scrollView.scrollTo(0, 0);
}
}
}
}
}
}
update_subtitle();
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
break;
case NetworkConnection.EVENT_USERINFO:
updateUsersListFragmentVisibility();
invalidateOptionsMenu();
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
if(launchBid == -1 && cid == -1)
launchBid = conn.getUserInfo().last_selected_bid;
break;
case NetworkConnection.EVENT_STATUSCHANGED:
try {
event = (IRCCloudJSONObject)msg.obj;
if(event.cid() == cid) {
status = event.getString("new_status");
invalidateOptionsMenu();
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;
case NetworkConnection.EVENT_MAKESERVER:
ServersDataSource.Server server = (ServersDataSource.Server)msg.obj;
if(server.cid == cid) {
status = server.status;
invalidateOptionsMenu();
}
break;
case NetworkConnection.EVENT_BUFFERARCHIVED:
event_bid = (Integer)msg.obj;
if(event_bid == bid) {
archived = 1;
invalidateOptionsMenu();
subtitle.setVisibility(View.VISIBLE);
subtitle.setText("(archived)");
}
break;
case NetworkConnection.EVENT_BUFFERUNARCHIVED:
event_bid = (Integer)msg.obj;
if(event_bid == bid) {
archived = 0;
invalidateOptionsMenu();
subtitle.setVisibility(View.GONE);
}
break;
case NetworkConnection.EVENT_JOIN:
event = (IRCCloudJSONObject)msg.obj;
if(event.bid() == bid && event.type().equalsIgnoreCase("you_joined_channel")) {
joined = 1;
invalidateOptionsMenu();
updateUsersListFragmentVisibility();
}
break;
case NetworkConnection.EVENT_PART:
event = (IRCCloudJSONObject)msg.obj;
if(event.bid() == bid && event.type().equalsIgnoreCase("you_parted_channel")) {
joined = 0;
invalidateOptionsMenu();
updateUsersListFragmentVisibility();
}
break;
case NetworkConnection.EVENT_CHANNELINIT:
ChannelsDataSource.Channel channel = (ChannelsDataSource.Channel)msg.obj;
if(channel.bid == bid) {
joined = 1;
archived = 0;
update_subtitle();
invalidateOptionsMenu();
updateUsersListFragmentVisibility();
}
break;
case NetworkConnection.EVENT_CONNECTIONDELETED:
case NetworkConnection.EVENT_DELETEBUFFER:
Integer id = (Integer)msg.obj;
if(msg.what==NetworkConnection.EVENT_DELETEBUFFER) {
for(int i = 0; i < backStack.size(); i++) {
if(backStack.get(i).equals(id)) {
backStack.remove(i);
i--;
}
}
}
if(id == ((msg.what==NetworkConnection.EVENT_CONNECTIONDELETED)?cid:bid)) {
if(backStack != null && backStack.size() > 0) {
Integer bid = backStack.get(0);
backStack.remove(0);
BuffersDataSource.Buffer buffer = BuffersDataSource.getInstance().getBuffer(bid);
if(buffer != null) {
ServersDataSource.Server s = ServersDataSource.getInstance().getServer(buffer.cid);
if(s != null)
status = s.status;
String name = buffer.name;
if(buffer.type.equalsIgnoreCase("console")) {
if(s != null) {
if(s.name != null && s.name.length() > 0)
name = s.name;
else
name = s.hostname;
}
}
onBufferSelected(buffer.cid, buffer.bid, name, buffer.last_seen_eid, buffer.min_eid,
buffer.type, 1, buffer.archived, status);
backStack.remove(0);
} else {
finish();
}
} else {
if(!open_bid(BuffersDataSource.getInstance().firstBid()))
finish();
}
}
break;
case NetworkConnection.EVENT_CHANNELTOPIC:
event = (IRCCloudJSONObject)msg.obj;
if(event.bid() == bid) {
try {
if(event.getString("topic").length() > 0) {
subtitle.setVisibility(View.VISIBLE);
subtitle.setText(event.getString("topic"));
} else {
subtitle.setVisibility(View.GONE);
}
} catch (Exception e1) {
subtitle.setVisibility(View.GONE);
e1.printStackTrace();
}
}
break;
case NetworkConnection.EVENT_SELFBACK:
try {
event = (IRCCloudJSONObject)msg.obj;
if(event.cid() == cid && event.getString("nick").equalsIgnoreCase(name)) {
subtitle.setVisibility(View.GONE);
subtitle.setText("");
}
} catch (Exception e1) {
e1.printStackTrace();
}
break;
case NetworkConnection.EVENT_AWAY:
try {
event = (IRCCloudJSONObject)msg.obj;
if((event.bid() == bid || (event.type().equalsIgnoreCase("self_away") && event.cid() == cid)) && event.getString("nick").equalsIgnoreCase(name)) {
subtitle.setVisibility(View.VISIBLE);
if(event.has("away_msg"))
subtitle.setText("Away: " + event.getString("away_msg"));
else
subtitle.setText("Away: " + event.getString("msg"));
}
} catch (Exception e1) {
e1.printStackTrace();
}
break;
case NetworkConnection.EVENT_HEARTBEATECHO:
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
break;
case NetworkConnection.EVENT_FAILURE_MSG:
event = (IRCCloudJSONObject)msg.obj;
if(event.has("_reqid")) {
int reqid = event.getInt("_reqid");
if(pendingEvents.containsKey(reqid)) {
EventsDataSource.Event e = pendingEvents.get(reqid);
EventsDataSource.getInstance().deleteEvent(e.eid, e.bid);
pendingEvents.remove(event.getInt("_reqid"));
e.msg = ColorFormatter.irc_to_html(e.msg + " \u00034(FAILED)\u000f");
conn.notifyHandlers(NetworkConnection.EVENT_BUFFERMSG, e);
}
}
break;
case NetworkConnection.EVENT_BUFFERMSG:
try {
EventsDataSource.Event e = (EventsDataSource.Event)msg.obj;
if(e.bid != bid && upView != null) {
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
}
if(e.from.equalsIgnoreCase(name)) {
for(EventsDataSource.Event e1 : pendingEvents.values()) {
EventsDataSource.getInstance().deleteEvent(e1.eid, e1.bid);
}
pendingEvents.clear();
} else if(pendingEvents.containsKey(e.reqid)) {
e = pendingEvents.get(e.reqid);
EventsDataSource.getInstance().deleteEvent(e.eid, e.bid);
pendingEvents.remove(e.reqid);
}
} catch (Exception e1) {
}
break;
}
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if(type != null && NetworkConnection.getInstance().ready) {
if(type.equalsIgnoreCase("channel")) {
getSupportMenuInflater().inflate(R.menu.activity_message_channel_userlist, menu);
getSupportMenuInflater().inflate(R.menu.activity_message_channel, menu);
} else if(type.equalsIgnoreCase("conversation"))
getSupportMenuInflater().inflate(R.menu.activity_message_conversation, menu);
else if(type.equalsIgnoreCase("console"))
getSupportMenuInflater().inflate(R.menu.activity_message_console, menu);
getSupportMenuInflater().inflate(R.menu.activity_message_archive, menu);
}
getSupportMenuInflater().inflate(R.menu.activity_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu (Menu menu) {
if(type != null && NetworkConnection.getInstance().ready) {
if(archived == 0) {
menu.findItem(R.id.menu_archive).setTitle(R.string.menu_archive);
} else {
menu.findItem(R.id.menu_archive).setTitle(R.string.menu_unarchive);
}
if(type.equalsIgnoreCase("channel")) {
if(joined == 0) {
menu.findItem(R.id.menu_leave).setTitle(R.string.menu_rejoin);
menu.findItem(R.id.menu_archive).setVisible(true);
menu.findItem(R.id.menu_archive).setEnabled(true);
menu.findItem(R.id.menu_delete).setVisible(true);
menu.findItem(R.id.menu_delete).setEnabled(true);
if(menu.findItem(R.id.menu_userlist) != null) {
menu.findItem(R.id.menu_userlist).setEnabled(false);
menu.findItem(R.id.menu_userlist).setVisible(false);
}
menu.findItem(R.id.menu_ban_list).setVisible(false);
menu.findItem(R.id.menu_ban_list).setEnabled(false);
} else {
menu.findItem(R.id.menu_leave).setTitle(R.string.menu_leave);
menu.findItem(R.id.menu_archive).setVisible(false);
menu.findItem(R.id.menu_archive).setEnabled(false);
menu.findItem(R.id.menu_delete).setVisible(false);
menu.findItem(R.id.menu_delete).setEnabled(false);
menu.findItem(R.id.menu_ban_list).setVisible(true);
menu.findItem(R.id.menu_ban_list).setEnabled(true);
if(menu.findItem(R.id.menu_userlist) != null) {
boolean hide = false;
try {
if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) {
JSONObject hiddenMap = conn.getUserInfo().prefs.getJSONObject("channel-hiddenMembers");
if(hiddenMap.has(String.valueOf(bid)) && hiddenMap.getBoolean(String.valueOf(bid)))
hide = true;
}
} catch (JSONException e) {
}
if(hide) {
menu.findItem(R.id.menu_userlist).setEnabled(false);
menu.findItem(R.id.menu_userlist).setVisible(false);
} else {
menu.findItem(R.id.menu_userlist).setEnabled(true);
menu.findItem(R.id.menu_userlist).setVisible(true);
}
}
}
} else if(type.equalsIgnoreCase("console")) {
menu.findItem(R.id.menu_archive).setVisible(false);
menu.findItem(R.id.menu_archive).setEnabled(false);
if(status != null && status.contains("connected") && !status.startsWith("dis")) {
menu.findItem(R.id.menu_disconnect).setTitle(R.string.menu_disconnect);
menu.findItem(R.id.menu_delete).setVisible(false);
menu.findItem(R.id.menu_delete).setEnabled(false);
} else {
menu.findItem(R.id.menu_disconnect).setTitle(R.string.menu_reconnect);
menu.findItem(R.id.menu_delete).setVisible(true);
menu.findItem(R.id.menu_delete).setEnabled(true);
}
}
}
return super.onPrepareOptionsMenu(menu);
}
private OnClickListener upClickListener = new OnClickListener() {
@Override
public void onClick(View arg0) {
if(scrollView != null) {
if(scrollView.getScrollX() < buffersListView.getWidth() / 4) {
scrollView.smoothScrollTo(buffersListView.getWidth(), 0);
upView.setVisibility(View.VISIBLE);
} else {
scrollView.smoothScrollTo(0, 0);
upView.setVisibility(View.INVISIBLE);
}
if(!getSharedPreferences("prefs", 0).getBoolean("bufferSwipeTip", false)) {
Toast.makeText(MessageActivity.this, "Swipe right and left to quickly open and close channels and conversations list", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = getSharedPreferences("prefs", 0).edit();
editor.putBoolean("bufferSwipeTip", true);
editor.commit();
}
}
}
};
@Override
public boolean onOptionsItemSelected(MenuItem item) {
AlertDialog.Builder builder;
AlertDialog dialog;
switch (item.getItemId()) {
case R.id.menu_whois:
conn.whois(cid, name, null);
break;
case R.id.menu_identify:
NickservFragment nsFragment = new NickservFragment();
nsFragment.setCid(cid);
nsFragment.show(getSupportFragmentManager(), "nickserv");
break;
case R.id.menu_add_network:
if(getWindowManager().getDefaultDisplay().getWidth() < 800) {
Intent i = new Intent(this, EditConnectionActivity.class);
startActivity(i);
} else {
EditConnectionFragment connFragment = new EditConnectionFragment();
connFragment.show(getSupportFragmentManager(), "addnetwork");
}
break;
case R.id.menu_channel_options:
ChannelOptionsFragment newFragment = new ChannelOptionsFragment(cid, bid);
newFragment.show(getSupportFragmentManager(), "channeloptions");
break;
case R.id.menu_buffer_options:
BufferOptionsFragment bufferFragment = new BufferOptionsFragment(cid, bid, type);
bufferFragment.show(getSupportFragmentManager(), "bufferoptions");
break;
case R.id.menu_userlist:
if(scrollView != null) {
if(scrollView.getScrollX() > buffersListView.getWidth()) {
scrollView.smoothScrollTo(buffersListView.getWidth(), 0);
} else {
scrollView.smoothScrollTo(buffersListView.getWidth() + userListView.getWidth(), 0);
}
upView.setVisibility(View.VISIBLE);
if(!getSharedPreferences("prefs", 0).getBoolean("userSwipeTip", false)) {
Toast.makeText(this, "Swipe left and right to quickly open and close the user list", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = getSharedPreferences("prefs", 0).edit();
editor.putBoolean("userSwipeTip", true);
editor.commit();
}
}
return true;
case R.id.menu_ignore_list:
Bundle args = new Bundle();
args.putInt("cid", cid);
IgnoreListFragment ignoreList = new IgnoreListFragment();
ignoreList.setArguments(args);
ignoreList.show(getSupportFragmentManager(), "ignorelist");
return true;
case R.id.menu_ban_list:
conn.mode(cid, name, "b");
return true;
case R.id.menu_leave:
if(joined == 0)
conn.join(cid, name, null);
else
conn.part(cid, name, null);
return true;
case R.id.menu_archive:
if(archived == 0)
conn.archiveBuffer(cid, bid);
else
conn.unarchiveBuffer(cid, bid);
return true;
case R.id.menu_delete:
builder = new AlertDialog.Builder(MessageActivity.this);
if(type.equalsIgnoreCase("console"))
builder.setTitle("Delete Connection");
else
builder.setTitle("Delete History");
if(type.equalsIgnoreCase("console"))
builder.setMessage("Are you sure you want to remove this connection?");
else if(type.equalsIgnoreCase("channel"))
builder.setMessage("Are you sure you want to clear your history in " + name + "?");
else
builder.setMessage("Are you sure you want to clear your history with " + name + "?");
builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setNeutralButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(type.equalsIgnoreCase("console")) {
conn.deleteServer(cid);
} else {
conn.deleteBuffer(cid, bid);
}
dialog.dismiss();
}
});
dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.show();
return true;
case R.id.menu_editconnection:
if(getWindowManager().getDefaultDisplay().getWidth() < 800) {
Intent i = new Intent(this, EditConnectionActivity.class);
i.putExtra("cid", cid);
startActivity(i);
} else {
EditConnectionFragment editFragment = new EditConnectionFragment();
editFragment.setCid(cid);
editFragment.show(getSupportFragmentManager(), "editconnection");
}
return true;
case R.id.menu_disconnect:
if(status != null && status.contains("connected") && !status.startsWith("dis")) {
conn.disconnect(cid, null);
} else {
conn.reconnect(cid);
}
return true;
}
return super.onOptionsItemSelected(item);
}
void editTopic() {
ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(bid);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_textprompt,null);
TextView prompt = (TextView)view.findViewById(R.id.prompt);
final EditText input = (EditText)view.findViewById(R.id.textInput);
input.setText(c.topic_text);
prompt.setVisibility(View.GONE);
builder.setTitle("Channel Topic");
builder.setView(view);
builder.setPositiveButton("Set Topic", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
conn.topic(cid, name, input.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(this);
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
}
@Override
public void onMessageDoubleClicked(EventsDataSource.Event event) {
if(event == null)
return;
String from = event.from;
if(from == null || from.length() == 0)
from = event.nick;
onUserDoubleClicked(from);
}
@Override
public void onUserDoubleClicked(String from) {
if(messageTxt == null || from == null || from.length() == 0)
return;
if(!getSharedPreferences("prefs", 0).getBoolean("mentionTip", false)) {
SharedPreferences.Editor editor = getSharedPreferences("prefs", 0).edit();
editor.putBoolean("mentionTip", true);
editor.commit();
}
if(scrollView != null)
scrollView.scrollTo((int)getResources().getDimension(R.dimen.drawer_width), 0);
if(messageTxt.getText().length() == 0) {
messageTxt.append(from + ": ");
} else {
int oldPosition = messageTxt.getSelectionStart();
String text = messageTxt.getText().toString();
int start = oldPosition - 1;
if(start > 0 && text.charAt(start) == ' ')
start--;
while(start > 0 && text.charAt(start) != ' ')
start--;
int match = text.indexOf(from, start);
int end = oldPosition + from.length();
if(end > text.length() - 1)
end = text.length() - 1;
if(match >= 0 && match < end) {
String newtext = "";
if(match > 1 && text.charAt(match - 1) == ' ')
newtext = text.substring(0, match - 1);
else
newtext = text.substring(0, match);
if(match+from.length() < text.length() && text.charAt(match+from.length()) == ':' &&
match+from.length()+1 < text.length() && text.charAt(match+from.length()+1) == ' ') {
if(match+from.length()+2 < text.length())
newtext += text.substring(match+from.length()+2, text.length());
} else if(match+from.length() < text.length()) {
newtext += text.substring(match+from.length(), text.length());
}
if(newtext.endsWith(" "))
newtext = newtext.substring(0, newtext.length() - 1);
if(newtext.equals(":"))
newtext = "";
messageTxt.setText(newtext);
if(match < newtext.length())
messageTxt.setSelection(match);
else
messageTxt.setSelection(newtext.length());
} else {
if(oldPosition == text.length() - 1) {
text += " " + from;
} else {
String newtext = text.substring(0, oldPosition);
if(!newtext.endsWith(" "))
from = " " + from;
if(!text.substring(oldPosition, text.length()).startsWith(" "))
from += " ";
newtext += from;
newtext += text.substring(oldPosition, text.length());
if(newtext.endsWith(" "))
newtext = newtext.substring(0, newtext.length() - 1);
text = newtext;
}
messageTxt.setText(text);
if(text.length() > 0) {
if(oldPosition + from.length() + 2 < text.length())
messageTxt.setSelection(oldPosition + from.length());
else
messageTxt.setSelection(text.length());
}
}
}
messageTxt.requestFocus();
InputMethodManager keyboard = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.showSoftInput(messageTxt, 0);
}
@Override
public boolean onBufferLongClicked(BuffersDataSource.Buffer b) {
if(b == null)
return false;
ArrayList<String> itemList = new ArrayList<String>();
final String[] items;
final BuffersDataSource.Buffer buffer = b;
ServersDataSource.Server s = ServersDataSource.getInstance().getServer(buffer.cid);
if(buffer.bid != bid)
itemList.add("Open");
if(ChannelsDataSource.getInstance().getChannelForBuffer(b.bid) != null) {
itemList.add("Leave");
itemList.add("Channel Options�");
} else {
if(b.type.equalsIgnoreCase("channel"))
itemList.add("Join");
else if(b.type.equalsIgnoreCase("console")) {
if(s.status.contains("connected") && !s.status.startsWith("dis")) {
itemList.add("Disconnect");
} else {
itemList.add("Connect");
itemList.add("Delete");
}
itemList.add("Edit Connection�");
}
if(!b.type.equalsIgnoreCase("console")) {
if(b.archived == 0)
itemList.add("Archive");
else
itemList.add("Unarchive");
itemList.add("Delete");
}
if(!b.type.equalsIgnoreCase("channel")) {
itemList.add("Buffer Options�");
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
if(b.type.equalsIgnoreCase("console"))
builder.setTitle(s.name);
else
builder.setTitle(b.name);
items = itemList.toArray(new String[itemList.size()]);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
AlertDialog.Builder builder = new AlertDialog.Builder(MessageActivity.this);
AlertDialog dialog;
if(items[item].equals("Open")) {
ServersDataSource.Server s = ServersDataSource.getInstance().getServer(buffer.cid);
if(buffer.type.equalsIgnoreCase("console")) {
onBufferSelected(buffer.cid, buffer.bid, s.name, buffer.last_seen_eid, buffer.min_eid,
buffer.type, 1, buffer.archived, s.status);
} else {
onBufferSelected(buffer.cid, buffer.bid, buffer.name, buffer.last_seen_eid, buffer.min_eid,
buffer.type, 1, buffer.archived, s.status);
}
} else if(items[item].equals("Join")) {
conn.join(buffer.cid, buffer.name, null);
} else if(items[item].equals("Leave")) {
conn.part(buffer.cid, buffer.name, null);
} else if(items[item].equals("Archive")) {
conn.archiveBuffer(buffer.cid, buffer.bid);
} else if(items[item].equals("Unarchive")) {
conn.unarchiveBuffer(buffer.cid, buffer.bid);
} else if(items[item].equals("Connect")) {
conn.reconnect(buffer.cid);
} else if(items[item].equals("Disconnect")) {
conn.disconnect(buffer.cid, null);
} else if(items[item].equals("Channel Options�")) {
ChannelOptionsFragment newFragment = new ChannelOptionsFragment(buffer.cid, buffer.bid);
newFragment.show(getSupportFragmentManager(), "channeloptions");
} else if(items[item].equals("Buffer Options�")) {
BufferOptionsFragment newFragment = new BufferOptionsFragment(buffer.cid, buffer.bid, buffer.type);
newFragment.show(getSupportFragmentManager(), "bufferoptions");
} else if(items[item].equals("Edit Connection�")) {
EditConnectionFragment editFragment = new EditConnectionFragment();
editFragment.setCid(buffer.cid);
editFragment.show(getSupportFragmentManager(), "editconnection");
} else if(items[item].equals("Delete")) {
builder = new AlertDialog.Builder(MessageActivity.this);
if(buffer.type.equalsIgnoreCase("console"))
builder.setTitle("Delete Connection");
else
builder.setTitle("Delete History");
if(buffer.type.equalsIgnoreCase("console"))
builder.setMessage("Are you sure you want to remove this connection?");
else if(buffer.type.equalsIgnoreCase("channel"))
builder.setMessage("Are you sure you want to clear your history in " + buffer.name + "?");
else
builder.setMessage("Are you sure you want to clear your history with " + buffer.name + "?");
builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setNeutralButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(type.equalsIgnoreCase("console")) {
conn.deleteServer(buffer.cid);
} else {
conn.deleteBuffer(buffer.cid, buffer.bid);
}
dialog.dismiss();
}
});
dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.show();
}
}
});
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(this);
dialog.show();
return true;
}
@Override
public boolean onMessageLongClicked(EventsDataSource.Event event) {
String from = event.from;
if(from == null || from.length() == 0)
from = event.nick;
UsersDataSource.User user;
if(type.equals("channel"))
user = UsersDataSource.getInstance().getUser(cid, name, from);
else
user = UsersDataSource.getInstance().getUser(cid, from);
if(user == null && from != null && event.hostmask != null) {
user = UsersDataSource.getInstance().new User();
user.nick = from;
user.hostmask = event.hostmask;
user.mode = "";
}
if(user == null && event.html == null)
return false;
if(event.html != null)
showUserPopup(user, ColorFormatter.html_to_spanned(event.html));
else
showUserPopup(user, null);
return true;
}
@Override
public void onUserSelected(int c, String chan, String nick) {
UsersDataSource u = UsersDataSource.getInstance();
if(type.equals("channel"))
showUserPopup(u.getUser(cid, name, nick), null);
else
showUserPopup(u.getUser(cid, nick), null);
}
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private void showUserPopup(UsersDataSource.User user, Spanned message) {
ArrayList<String> itemList = new ArrayList<String>();
final String[] items;
final Spanned text_to_copy = message;
selected_user = user;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
if(message != null)
itemList.add("Copy Message");
if(selected_user != null) {
itemList.add("Whois�");
itemList.add("Send a message");
itemList.add("Mention");
itemList.add("Invite to a channel�");
itemList.add("Ignore");
if(type.equalsIgnoreCase("channel")) {
UsersDataSource.User self_user = UsersDataSource.getInstance().getUser(cid, name, ServersDataSource.getInstance().getServer(cid).nick);
if(self_user != null && self_user.mode != null) {
if(self_user.mode.contains("q") || self_user.mode.contains("a") || self_user.mode.contains("o")) {
if(selected_user.mode.contains("o"))
itemList.add("Deop");
else
itemList.add("Op");
}
if(self_user.mode.contains("q") || self_user.mode.contains("a") || self_user.mode.contains("o") || self_user.mode.contains("h")) {
itemList.add("Kick�");
itemList.add("Ban�");
}
}
}
}
items = itemList.toArray(new String[itemList.size()]);
if(selected_user != null)
builder.setTitle(selected_user.nick + "\n(" + selected_user.hostmask + ")");
else
builder.setTitle("Message");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
AlertDialog.Builder builder = new AlertDialog.Builder(MessageActivity.this);
LayoutInflater inflater = getLayoutInflater();
ServersDataSource s = ServersDataSource.getInstance();
ServersDataSource.Server server = s.getServer(cid);
View view;
final TextView prompt;
final EditText input;
AlertDialog dialog;
if(items[item].equals("Copy Message")) {
if(Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(text_to_copy);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("IRCCloud Message",text_to_copy);
clipboard.setPrimaryClip(clip);
}
} else if(items[item].equals("Whois�")) {
conn.whois(cid, selected_user.nick, null);
} else if(items[item].equals("Send a message")) {
BuffersDataSource b = BuffersDataSource.getInstance();
BuffersDataSource.Buffer buffer = b.getBufferByName(cid, selected_user.nick);
if(getSupportFragmentManager().findFragmentById(R.id.BuffersList) != null) {
if(buffer != null) {
onBufferSelected(buffer.cid, buffer.bid, buffer.name, buffer.last_seen_eid, buffer.min_eid,
buffer.type, 1, buffer.archived, status);
} else {
onBufferSelected(cid, -1, selected_user.nick, 0, 0, "conversation", 1, 0, status);
}
} else {
Intent i = new Intent(MessageActivity.this, MessageActivity.class);
if(buffer != null) {
i.putExtra("cid", buffer.cid);
i.putExtra("bid", buffer.bid);
i.putExtra("name", buffer.name);
i.putExtra("last_seen_eid", buffer.last_seen_eid);
i.putExtra("min_eid", buffer.min_eid);
i.putExtra("type", buffer.type);
i.putExtra("joined", 1);
i.putExtra("archived", buffer.archived);
i.putExtra("status", status);
} else {
i.putExtra("cid", cid);
i.putExtra("bid", -1);
i.putExtra("name", selected_user.nick);
i.putExtra("last_seen_eid", 0L);
i.putExtra("min_eid", 0L);
i.putExtra("type", "conversation");
i.putExtra("joined", 1);
i.putExtra("archived", 0);
i.putExtra("status", status);
}
startActivity(i);
}
} else if(items[item].equals("Mention")) {
if(!getSharedPreferences("prefs", 0).getBoolean("mentionTip", false)) {
Toast.makeText(MessageActivity.this, "Double-tap a message to quickly reply to the sender", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = getSharedPreferences("prefs", 0).edit();
editor.putBoolean("mentionTip", true);
editor.commit();
}
onUserDoubleClicked(selected_user.nick);
} else if(items[item].equals("Invite to a channel�")) {
view = inflater.inflate(R.layout.dialog_textprompt,null);
prompt = (TextView)view.findViewById(R.id.prompt);
input = (EditText)view.findViewById(R.id.textInput);
prompt.setText("Invite " + selected_user.nick + " to a channel");
builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
builder.setView(view);
builder.setPositiveButton("Invite", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
conn.invite(cid, input.getText().toString(), selected_user.nick);
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
} else if(items[item].equals("Ignore")) {
view = inflater.inflate(R.layout.dialog_textprompt,null);
prompt = (TextView)view.findViewById(R.id.prompt);
input = (EditText)view.findViewById(R.id.textInput);
input.setText("*!"+selected_user.hostmask);
prompt.setText("Ignore messages for " + selected_user.nick + " at this hostmask");
builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
builder.setView(view);
builder.setPositiveButton("Ignore", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
conn.ignore(cid, input.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
} else if(items[item].equals("Op")) {
conn.mode(cid, name, "+o " + selected_user.nick);
} else if(items[item].equals("Deop")) {
conn.mode(cid, name, "-o " + selected_user.nick);
} else if(items[item].equals("Kick�")) {
view = inflater.inflate(R.layout.dialog_textprompt,null);
prompt = (TextView)view.findViewById(R.id.prompt);
input = (EditText)view.findViewById(R.id.textInput);
prompt.setText("Give a reason for kicking");
builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
builder.setView(view);
builder.setPositiveButton("Kick", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
conn.kick(cid, name, selected_user.nick, input.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
} else if(items[item].equals("Ban�")) {
view = inflater.inflate(R.layout.dialog_textprompt,null);
prompt = (TextView)view.findViewById(R.id.prompt);
input = (EditText)view.findViewById(R.id.textInput);
input.setText("*!"+selected_user.hostmask);
prompt.setText("Add a banmask for " + selected_user.nick);
builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
builder.setView(view);
builder.setPositiveButton("Ban", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
conn.mode(cid, name, "+b " + input.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
}
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(this);
dialog.show();
}
@Override
public void onBufferSelected(int cid, int bid, String name,
long last_seen_eid, long min_eid, String type, int joined,
int archived, String status) {
if(scrollView != null) {
if(buffersListView.getWidth() > 0)
scrollView.smoothScrollTo(buffersListView.getWidth(), 0);
upView.setVisibility(View.VISIBLE);
}
if(bid != this.bid || this.cid == -1) {
if(bid != -1 && conn != null && conn.getUserInfo() != null)
conn.getUserInfo().last_selected_bid = bid;
for(int i = 0; i < backStack.size(); i++) {
if(backStack.get(i) == this.bid)
backStack.remove(i);
}
if(this.bid >= 0)
backStack.add(0, this.bid);
this.cid = cid;
this.bid = bid;
this.name = name;
this.type = type;
this.joined = joined;
this.archived = archived;
this.status = status;
title.setText(name);
getSupportActionBar().setTitle(name);
update_subtitle();
Bundle b = new Bundle();
b.putInt("cid", cid);
b.putInt("bid", bid);
b.putLong("last_seen_eid", last_seen_eid);
b.putLong("min_eid", min_eid);
b.putString("name", name);
b.putString("type", type);
BuffersListFragment blf = (BuffersListFragment)getSupportFragmentManager().findFragmentById(R.id.BuffersList);
MessageViewFragment mvf = (MessageViewFragment)getSupportFragmentManager().findFragmentById(R.id.messageViewFragment);
UsersListFragment ulf = (UsersListFragment)getSupportFragmentManager().findFragmentById(R.id.usersListFragment);
if(blf != null)
blf.setSelectedBid(bid);
if(mvf != null)
mvf.setArguments(b);
if(ulf != null)
ulf.setArguments(b);
AlphaAnimation anim = new AlphaAnimation(1, 0);
anim.setDuration(200);
anim.setFillAfter(true);
mvf.getListView().startAnimation(anim);
ulf.getListView().startAnimation(anim);
shouldFadeIn = true;
updateUsersListFragmentVisibility();
invalidateOptionsMenu();
if(showNotificationsTask != null)
showNotificationsTask.cancel(true);
showNotificationsTask = new ShowNotificationsTask();
showNotificationsTask.execute(bid);
if(upView != null)
new RefreshUpIndicatorTask().execute((Void)null);
}
if(cid != -1) {
if(scrollView != null)
scrollView.setEnabled(true);
messageTxt.setEnabled(true);
}
}
public void showUpButton(boolean show) {
if(upView != null) {
if(show) {
upView.setVisibility(View.VISIBLE);
} else {
upView.setVisibility(View.INVISIBLE);
}
}
}
@Override
public void onMessageViewReady() {
if(shouldFadeIn) {
MessageViewFragment mvf = (MessageViewFragment)getSupportFragmentManager().findFragmentById(R.id.messageViewFragment);
UsersListFragment ulf = (UsersListFragment)getSupportFragmentManager().findFragmentById(R.id.usersListFragment);
AlphaAnimation anim = new AlphaAnimation(0, 1);
anim.setDuration(200);
anim.setFillAfter(true);
mvf.getListView().startAnimation(anim);
ulf.getListView().startAnimation(anim);
shouldFadeIn = false;
}
}
@Override
public void addButtonPressed(int cid) {
if(scrollView != null)
scrollView.scrollTo(0,0);
}
}
| true | true | public void handleMessage(Message msg) {
Integer event_bid = 0;
IRCCloudJSONObject event = null;
Bundle args = null;
switch (msg.what) {
case NetworkConnection.EVENT_LINKCHANNEL:
event = (IRCCloudJSONObject)msg.obj;
if(cidToOpen == event.cid() && event.getString("invalid_chan").equalsIgnoreCase(bufferToOpen)) {
bufferToOpen = event.getString("valid_chan");
msg.obj = BuffersDataSource.getInstance().getBuffer(event.bid());
}
case NetworkConnection.EVENT_MAKEBUFFER:
BuffersDataSource.Buffer b = (BuffersDataSource.Buffer)msg.obj;
if(cidToOpen == b.cid && b.name.equalsIgnoreCase(bufferToOpen) && !bufferToOpen.equalsIgnoreCase(name)) {
onBufferSelected(b.cid, b.bid, b.name, b.last_seen_eid, b.min_eid, b.type, 1, 0, "connected_ready");
bufferToOpen = null;
cidToOpen = -1;
} else if(bid == -1 && b.cid == cid && b.name.equalsIgnoreCase(name)) {
bid = b.bid;
if(getSupportFragmentManager().findFragmentById(R.id.BuffersList) != null)
((BuffersListFragment)getSupportFragmentManager().findFragmentById(R.id.BuffersList)).setSelectedBid(bid);
if(showNotificationsTask != null)
showNotificationsTask.cancel(true);
showNotificationsTask = new ShowNotificationsTask();
showNotificationsTask.execute(bid);
}
break;
case NetworkConnection.EVENT_OPENBUFFER:
event = (IRCCloudJSONObject)msg.obj;
try {
bufferToOpen = event.getString("name");
cidToOpen = event.cid();
b = BuffersDataSource.getInstance().getBufferByName(cidToOpen, bufferToOpen);
if(b != null && !bufferToOpen.equalsIgnoreCase(name)) {
onBufferSelected(b.cid, b.bid, b.name, b.last_seen_eid, b.min_eid, b.type, 1, 0, "connected_ready");
bufferToOpen = null;
cidToOpen = -1;
}
} catch (Exception e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
break;
case NetworkConnection.EVENT_CONNECTIVITY:
if(conn.getState() == NetworkConnection.STATE_CONNECTED) {
for(EventsDataSource.Event e : pendingEvents.values()) {
EventsDataSource.getInstance().deleteEvent(e.eid, e.bid);
}
pendingEvents.clear();
if(scrollView != null && NetworkConnection.getInstance().ready) {
scrollView.setEnabled(true);
if(scrollView.getScrollX() > 0)
upView.setVisibility(View.VISIBLE);
}
if(cid != -1)
messageTxt.setEnabled(true);
} else {
if(scrollView != null && NetworkConnection.getInstance().ready) {
scrollView.setEnabled(false);
scrollView.smoothScrollTo((int)getResources().getDimension(R.dimen.drawer_width), 0);
upView.setVisibility(View.VISIBLE);
}
messageTxt.setEnabled(false);
}
break;
case NetworkConnection.EVENT_BANLIST:
event = (IRCCloudJSONObject)msg.obj;
if(event.getString("channel").equalsIgnoreCase(name)) {
args = new Bundle();
args.putInt("cid", cid);
args.putInt("bid", bid);
args.putString("event", event.toString());
BanListFragment banList = (BanListFragment)getSupportFragmentManager().findFragmentByTag("banlist");
if(banList == null) {
banList = new BanListFragment();
banList.setArguments(args);
banList.show(getSupportFragmentManager(), "banlist");
} else {
banList.setArguments(args);
}
}
break;
case NetworkConnection.EVENT_ACCEPTLIST:
event = (IRCCloudJSONObject)msg.obj;
if(event.cid() == cid) {
args = new Bundle();
args.putInt("cid", cid);
args.putString("event", event.toString());
AcceptListFragment acceptList = (AcceptListFragment)getSupportFragmentManager().findFragmentByTag("acceptlist");
if(acceptList == null) {
acceptList = new AcceptListFragment();
acceptList.setArguments(args);
acceptList.show(getSupportFragmentManager(), "acceptlist");
} else {
acceptList.setArguments(args);
}
}
break;
case NetworkConnection.EVENT_WHOLIST:
event = (IRCCloudJSONObject)msg.obj;
args = new Bundle();
args.putString("event", event.toString());
WhoListFragment whoList = (WhoListFragment)getSupportFragmentManager().findFragmentByTag("wholist");
if(whoList == null) {
whoList = new WhoListFragment();
whoList.setArguments(args);
whoList.show(getSupportFragmentManager(), "wholist");
} else {
whoList.setArguments(args);
}
break;
case NetworkConnection.EVENT_WHOIS:
event = (IRCCloudJSONObject)msg.obj;
args = new Bundle();
args.putString("event", event.toString());
WhoisFragment whois = (WhoisFragment)getSupportFragmentManager().findFragmentByTag("whois");
if(whois == null) {
whois = new WhoisFragment();
whois.setArguments(args);
whois.show(getSupportFragmentManager(), "whois");
} else {
whois.setArguments(args);
}
break;
case NetworkConnection.EVENT_LISTRESPONSEFETCHING:
event = (IRCCloudJSONObject)msg.obj;
String dialogtitle = "List of channels on " + ServersDataSource.getInstance().getServer(event.cid()).hostname;
if(channelsListDialog == null) {
Context ctx = MessageActivity.this;
if(Build.VERSION.SDK_INT < 11)
ctx = new ContextThemeWrapper(ctx, android.R.style.Theme_Dialog);
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setView(getLayoutInflater().inflate(R.layout.dialog_channelslist, null));
builder.setTitle(dialogtitle);
builder.setNegativeButton("Close", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
channelsListDialog = builder.create();
channelsListDialog.setOwnerActivity(MessageActivity.this);
} else {
channelsListDialog.setTitle(dialogtitle);
}
channelsListDialog.show();
ChannelListFragment channels = (ChannelListFragment)getSupportFragmentManager().findFragmentById(R.id.channelListFragment);
args = new Bundle();
args.putInt("cid", event.cid());
channels.setArguments(args);
break;
case NetworkConnection.EVENT_BACKLOG_END:
if(scrollView != null) {
scrollView.setEnabled(true);
if(scrollView.getScrollX() > 0)
upView.setVisibility(View.VISIBLE);
}
if(cid == -1) {
if(launchURI == null || !open_uri(launchURI)) {
if(launchBid == -1 || !open_bid(launchBid)) {
if(conn.getUserInfo() == null || !open_bid(conn.getUserInfo().last_selected_bid)) {
if(!open_bid(BuffersDataSource.getInstance().firstBid())) {
if(scrollView != null && NetworkConnection.getInstance().ready) {
scrollView.scrollTo(0, 0);
}
}
}
}
}
}
update_subtitle();
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
break;
case NetworkConnection.EVENT_USERINFO:
updateUsersListFragmentVisibility();
invalidateOptionsMenu();
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
if(launchBid == -1 && cid == -1)
launchBid = conn.getUserInfo().last_selected_bid;
break;
case NetworkConnection.EVENT_STATUSCHANGED:
try {
event = (IRCCloudJSONObject)msg.obj;
if(event.cid() == cid) {
status = event.getString("new_status");
invalidateOptionsMenu();
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;
case NetworkConnection.EVENT_MAKESERVER:
ServersDataSource.Server server = (ServersDataSource.Server)msg.obj;
if(server.cid == cid) {
status = server.status;
invalidateOptionsMenu();
}
break;
case NetworkConnection.EVENT_BUFFERARCHIVED:
event_bid = (Integer)msg.obj;
if(event_bid == bid) {
archived = 1;
invalidateOptionsMenu();
subtitle.setVisibility(View.VISIBLE);
subtitle.setText("(archived)");
}
break;
case NetworkConnection.EVENT_BUFFERUNARCHIVED:
event_bid = (Integer)msg.obj;
if(event_bid == bid) {
archived = 0;
invalidateOptionsMenu();
subtitle.setVisibility(View.GONE);
}
break;
case NetworkConnection.EVENT_JOIN:
event = (IRCCloudJSONObject)msg.obj;
if(event.bid() == bid && event.type().equalsIgnoreCase("you_joined_channel")) {
joined = 1;
invalidateOptionsMenu();
updateUsersListFragmentVisibility();
}
break;
case NetworkConnection.EVENT_PART:
event = (IRCCloudJSONObject)msg.obj;
if(event.bid() == bid && event.type().equalsIgnoreCase("you_parted_channel")) {
joined = 0;
invalidateOptionsMenu();
updateUsersListFragmentVisibility();
}
break;
case NetworkConnection.EVENT_CHANNELINIT:
ChannelsDataSource.Channel channel = (ChannelsDataSource.Channel)msg.obj;
if(channel.bid == bid) {
joined = 1;
archived = 0;
update_subtitle();
invalidateOptionsMenu();
updateUsersListFragmentVisibility();
}
break;
case NetworkConnection.EVENT_CONNECTIONDELETED:
case NetworkConnection.EVENT_DELETEBUFFER:
Integer id = (Integer)msg.obj;
if(msg.what==NetworkConnection.EVENT_DELETEBUFFER) {
for(int i = 0; i < backStack.size(); i++) {
if(backStack.get(i).equals(id)) {
backStack.remove(i);
i--;
}
}
}
if(id == ((msg.what==NetworkConnection.EVENT_CONNECTIONDELETED)?cid:bid)) {
if(backStack != null && backStack.size() > 0) {
Integer bid = backStack.get(0);
backStack.remove(0);
BuffersDataSource.Buffer buffer = BuffersDataSource.getInstance().getBuffer(bid);
if(buffer != null) {
ServersDataSource.Server s = ServersDataSource.getInstance().getServer(buffer.cid);
if(s != null)
status = s.status;
String name = buffer.name;
if(buffer.type.equalsIgnoreCase("console")) {
if(s != null) {
if(s.name != null && s.name.length() > 0)
name = s.name;
else
name = s.hostname;
}
}
onBufferSelected(buffer.cid, buffer.bid, name, buffer.last_seen_eid, buffer.min_eid,
buffer.type, 1, buffer.archived, status);
backStack.remove(0);
} else {
finish();
}
} else {
if(!open_bid(BuffersDataSource.getInstance().firstBid()))
finish();
}
}
break;
case NetworkConnection.EVENT_CHANNELTOPIC:
event = (IRCCloudJSONObject)msg.obj;
if(event.bid() == bid) {
try {
if(event.getString("topic").length() > 0) {
subtitle.setVisibility(View.VISIBLE);
subtitle.setText(event.getString("topic"));
} else {
subtitle.setVisibility(View.GONE);
}
} catch (Exception e1) {
subtitle.setVisibility(View.GONE);
e1.printStackTrace();
}
}
break;
case NetworkConnection.EVENT_SELFBACK:
try {
event = (IRCCloudJSONObject)msg.obj;
if(event.cid() == cid && event.getString("nick").equalsIgnoreCase(name)) {
subtitle.setVisibility(View.GONE);
subtitle.setText("");
}
} catch (Exception e1) {
e1.printStackTrace();
}
break;
case NetworkConnection.EVENT_AWAY:
try {
event = (IRCCloudJSONObject)msg.obj;
if((event.bid() == bid || (event.type().equalsIgnoreCase("self_away") && event.cid() == cid)) && event.getString("nick").equalsIgnoreCase(name)) {
subtitle.setVisibility(View.VISIBLE);
if(event.has("away_msg"))
subtitle.setText("Away: " + event.getString("away_msg"));
else
subtitle.setText("Away: " + event.getString("msg"));
}
} catch (Exception e1) {
e1.printStackTrace();
}
break;
case NetworkConnection.EVENT_HEARTBEATECHO:
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
break;
case NetworkConnection.EVENT_FAILURE_MSG:
event = (IRCCloudJSONObject)msg.obj;
if(event.has("_reqid")) {
int reqid = event.getInt("_reqid");
if(pendingEvents.containsKey(reqid)) {
EventsDataSource.Event e = pendingEvents.get(reqid);
EventsDataSource.getInstance().deleteEvent(e.eid, e.bid);
pendingEvents.remove(event.getInt("_reqid"));
e.msg = ColorFormatter.irc_to_html(e.msg + " \u00034(FAILED)\u000f");
conn.notifyHandlers(NetworkConnection.EVENT_BUFFERMSG, e);
}
}
break;
case NetworkConnection.EVENT_BUFFERMSG:
try {
EventsDataSource.Event e = (EventsDataSource.Event)msg.obj;
if(e.bid != bid && upView != null) {
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
}
if(e.from.equalsIgnoreCase(name)) {
for(EventsDataSource.Event e1 : pendingEvents.values()) {
EventsDataSource.getInstance().deleteEvent(e1.eid, e1.bid);
}
pendingEvents.clear();
} else if(pendingEvents.containsKey(e.reqid)) {
e = pendingEvents.get(e.reqid);
EventsDataSource.getInstance().deleteEvent(e.eid, e.bid);
pendingEvents.remove(e.reqid);
}
} catch (Exception e1) {
}
break;
}
}
| public void handleMessage(Message msg) {
Integer event_bid = 0;
IRCCloudJSONObject event = null;
Bundle args = null;
switch (msg.what) {
case NetworkConnection.EVENT_LINKCHANNEL:
event = (IRCCloudJSONObject)msg.obj;
if(cidToOpen == event.cid() && event.getString("invalid_chan").equalsIgnoreCase(bufferToOpen)) {
bufferToOpen = event.getString("valid_chan");
msg.obj = BuffersDataSource.getInstance().getBuffer(event.bid());
} else {
return;
}
case NetworkConnection.EVENT_MAKEBUFFER:
BuffersDataSource.Buffer b = (BuffersDataSource.Buffer)msg.obj;
if(cidToOpen == b.cid && b.name.equalsIgnoreCase(bufferToOpen) && !bufferToOpen.equalsIgnoreCase(name)) {
onBufferSelected(b.cid, b.bid, b.name, b.last_seen_eid, b.min_eid, b.type, 1, 0, "connected_ready");
bufferToOpen = null;
cidToOpen = -1;
} else if(bid == -1 && b.cid == cid && b.name.equalsIgnoreCase(name)) {
bid = b.bid;
if(getSupportFragmentManager().findFragmentById(R.id.BuffersList) != null)
((BuffersListFragment)getSupportFragmentManager().findFragmentById(R.id.BuffersList)).setSelectedBid(bid);
if(showNotificationsTask != null)
showNotificationsTask.cancel(true);
showNotificationsTask = new ShowNotificationsTask();
showNotificationsTask.execute(bid);
}
break;
case NetworkConnection.EVENT_OPENBUFFER:
event = (IRCCloudJSONObject)msg.obj;
try {
bufferToOpen = event.getString("name");
cidToOpen = event.cid();
b = BuffersDataSource.getInstance().getBufferByName(cidToOpen, bufferToOpen);
if(b != null && !bufferToOpen.equalsIgnoreCase(name)) {
onBufferSelected(b.cid, b.bid, b.name, b.last_seen_eid, b.min_eid, b.type, 1, 0, "connected_ready");
bufferToOpen = null;
cidToOpen = -1;
}
} catch (Exception e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
break;
case NetworkConnection.EVENT_CONNECTIVITY:
if(conn.getState() == NetworkConnection.STATE_CONNECTED) {
for(EventsDataSource.Event e : pendingEvents.values()) {
EventsDataSource.getInstance().deleteEvent(e.eid, e.bid);
}
pendingEvents.clear();
if(scrollView != null && NetworkConnection.getInstance().ready) {
scrollView.setEnabled(true);
if(scrollView.getScrollX() > 0)
upView.setVisibility(View.VISIBLE);
}
if(cid != -1)
messageTxt.setEnabled(true);
} else {
if(scrollView != null && NetworkConnection.getInstance().ready) {
scrollView.setEnabled(false);
scrollView.smoothScrollTo((int)getResources().getDimension(R.dimen.drawer_width), 0);
upView.setVisibility(View.VISIBLE);
}
messageTxt.setEnabled(false);
}
break;
case NetworkConnection.EVENT_BANLIST:
event = (IRCCloudJSONObject)msg.obj;
if(event.getString("channel").equalsIgnoreCase(name)) {
args = new Bundle();
args.putInt("cid", cid);
args.putInt("bid", bid);
args.putString("event", event.toString());
BanListFragment banList = (BanListFragment)getSupportFragmentManager().findFragmentByTag("banlist");
if(banList == null) {
banList = new BanListFragment();
banList.setArguments(args);
banList.show(getSupportFragmentManager(), "banlist");
} else {
banList.setArguments(args);
}
}
break;
case NetworkConnection.EVENT_ACCEPTLIST:
event = (IRCCloudJSONObject)msg.obj;
if(event.cid() == cid) {
args = new Bundle();
args.putInt("cid", cid);
args.putString("event", event.toString());
AcceptListFragment acceptList = (AcceptListFragment)getSupportFragmentManager().findFragmentByTag("acceptlist");
if(acceptList == null) {
acceptList = new AcceptListFragment();
acceptList.setArguments(args);
acceptList.show(getSupportFragmentManager(), "acceptlist");
} else {
acceptList.setArguments(args);
}
}
break;
case NetworkConnection.EVENT_WHOLIST:
event = (IRCCloudJSONObject)msg.obj;
args = new Bundle();
args.putString("event", event.toString());
WhoListFragment whoList = (WhoListFragment)getSupportFragmentManager().findFragmentByTag("wholist");
if(whoList == null) {
whoList = new WhoListFragment();
whoList.setArguments(args);
whoList.show(getSupportFragmentManager(), "wholist");
} else {
whoList.setArguments(args);
}
break;
case NetworkConnection.EVENT_WHOIS:
event = (IRCCloudJSONObject)msg.obj;
args = new Bundle();
args.putString("event", event.toString());
WhoisFragment whois = (WhoisFragment)getSupportFragmentManager().findFragmentByTag("whois");
if(whois == null) {
whois = new WhoisFragment();
whois.setArguments(args);
whois.show(getSupportFragmentManager(), "whois");
} else {
whois.setArguments(args);
}
break;
case NetworkConnection.EVENT_LISTRESPONSEFETCHING:
event = (IRCCloudJSONObject)msg.obj;
String dialogtitle = "List of channels on " + ServersDataSource.getInstance().getServer(event.cid()).hostname;
if(channelsListDialog == null) {
Context ctx = MessageActivity.this;
if(Build.VERSION.SDK_INT < 11)
ctx = new ContextThemeWrapper(ctx, android.R.style.Theme_Dialog);
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setView(getLayoutInflater().inflate(R.layout.dialog_channelslist, null));
builder.setTitle(dialogtitle);
builder.setNegativeButton("Close", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
channelsListDialog = builder.create();
channelsListDialog.setOwnerActivity(MessageActivity.this);
} else {
channelsListDialog.setTitle(dialogtitle);
}
channelsListDialog.show();
ChannelListFragment channels = (ChannelListFragment)getSupportFragmentManager().findFragmentById(R.id.channelListFragment);
args = new Bundle();
args.putInt("cid", event.cid());
channels.setArguments(args);
break;
case NetworkConnection.EVENT_BACKLOG_END:
if(scrollView != null) {
scrollView.setEnabled(true);
if(scrollView.getScrollX() > 0)
upView.setVisibility(View.VISIBLE);
}
if(cid == -1) {
if(launchURI == null || !open_uri(launchURI)) {
if(launchBid == -1 || !open_bid(launchBid)) {
if(conn.getUserInfo() == null || !open_bid(conn.getUserInfo().last_selected_bid)) {
if(!open_bid(BuffersDataSource.getInstance().firstBid())) {
if(scrollView != null && NetworkConnection.getInstance().ready) {
scrollView.scrollTo(0, 0);
}
}
}
}
}
}
update_subtitle();
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
break;
case NetworkConnection.EVENT_USERINFO:
updateUsersListFragmentVisibility();
invalidateOptionsMenu();
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
if(launchBid == -1 && cid == -1)
launchBid = conn.getUserInfo().last_selected_bid;
break;
case NetworkConnection.EVENT_STATUSCHANGED:
try {
event = (IRCCloudJSONObject)msg.obj;
if(event.cid() == cid) {
status = event.getString("new_status");
invalidateOptionsMenu();
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;
case NetworkConnection.EVENT_MAKESERVER:
ServersDataSource.Server server = (ServersDataSource.Server)msg.obj;
if(server.cid == cid) {
status = server.status;
invalidateOptionsMenu();
}
break;
case NetworkConnection.EVENT_BUFFERARCHIVED:
event_bid = (Integer)msg.obj;
if(event_bid == bid) {
archived = 1;
invalidateOptionsMenu();
subtitle.setVisibility(View.VISIBLE);
subtitle.setText("(archived)");
}
break;
case NetworkConnection.EVENT_BUFFERUNARCHIVED:
event_bid = (Integer)msg.obj;
if(event_bid == bid) {
archived = 0;
invalidateOptionsMenu();
subtitle.setVisibility(View.GONE);
}
break;
case NetworkConnection.EVENT_JOIN:
event = (IRCCloudJSONObject)msg.obj;
if(event.bid() == bid && event.type().equalsIgnoreCase("you_joined_channel")) {
joined = 1;
invalidateOptionsMenu();
updateUsersListFragmentVisibility();
}
break;
case NetworkConnection.EVENT_PART:
event = (IRCCloudJSONObject)msg.obj;
if(event.bid() == bid && event.type().equalsIgnoreCase("you_parted_channel")) {
joined = 0;
invalidateOptionsMenu();
updateUsersListFragmentVisibility();
}
break;
case NetworkConnection.EVENT_CHANNELINIT:
ChannelsDataSource.Channel channel = (ChannelsDataSource.Channel)msg.obj;
if(channel.bid == bid) {
joined = 1;
archived = 0;
update_subtitle();
invalidateOptionsMenu();
updateUsersListFragmentVisibility();
}
break;
case NetworkConnection.EVENT_CONNECTIONDELETED:
case NetworkConnection.EVENT_DELETEBUFFER:
Integer id = (Integer)msg.obj;
if(msg.what==NetworkConnection.EVENT_DELETEBUFFER) {
for(int i = 0; i < backStack.size(); i++) {
if(backStack.get(i).equals(id)) {
backStack.remove(i);
i--;
}
}
}
if(id == ((msg.what==NetworkConnection.EVENT_CONNECTIONDELETED)?cid:bid)) {
if(backStack != null && backStack.size() > 0) {
Integer bid = backStack.get(0);
backStack.remove(0);
BuffersDataSource.Buffer buffer = BuffersDataSource.getInstance().getBuffer(bid);
if(buffer != null) {
ServersDataSource.Server s = ServersDataSource.getInstance().getServer(buffer.cid);
if(s != null)
status = s.status;
String name = buffer.name;
if(buffer.type.equalsIgnoreCase("console")) {
if(s != null) {
if(s.name != null && s.name.length() > 0)
name = s.name;
else
name = s.hostname;
}
}
onBufferSelected(buffer.cid, buffer.bid, name, buffer.last_seen_eid, buffer.min_eid,
buffer.type, 1, buffer.archived, status);
backStack.remove(0);
} else {
finish();
}
} else {
if(!open_bid(BuffersDataSource.getInstance().firstBid()))
finish();
}
}
break;
case NetworkConnection.EVENT_CHANNELTOPIC:
event = (IRCCloudJSONObject)msg.obj;
if(event.bid() == bid) {
try {
if(event.getString("topic").length() > 0) {
subtitle.setVisibility(View.VISIBLE);
subtitle.setText(event.getString("topic"));
} else {
subtitle.setVisibility(View.GONE);
}
} catch (Exception e1) {
subtitle.setVisibility(View.GONE);
e1.printStackTrace();
}
}
break;
case NetworkConnection.EVENT_SELFBACK:
try {
event = (IRCCloudJSONObject)msg.obj;
if(event.cid() == cid && event.getString("nick").equalsIgnoreCase(name)) {
subtitle.setVisibility(View.GONE);
subtitle.setText("");
}
} catch (Exception e1) {
e1.printStackTrace();
}
break;
case NetworkConnection.EVENT_AWAY:
try {
event = (IRCCloudJSONObject)msg.obj;
if((event.bid() == bid || (event.type().equalsIgnoreCase("self_away") && event.cid() == cid)) && event.getString("nick").equalsIgnoreCase(name)) {
subtitle.setVisibility(View.VISIBLE);
if(event.has("away_msg"))
subtitle.setText("Away: " + event.getString("away_msg"));
else
subtitle.setText("Away: " + event.getString("msg"));
}
} catch (Exception e1) {
e1.printStackTrace();
}
break;
case NetworkConnection.EVENT_HEARTBEATECHO:
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
break;
case NetworkConnection.EVENT_FAILURE_MSG:
event = (IRCCloudJSONObject)msg.obj;
if(event.has("_reqid")) {
int reqid = event.getInt("_reqid");
if(pendingEvents.containsKey(reqid)) {
EventsDataSource.Event e = pendingEvents.get(reqid);
EventsDataSource.getInstance().deleteEvent(e.eid, e.bid);
pendingEvents.remove(event.getInt("_reqid"));
e.msg = ColorFormatter.irc_to_html(e.msg + " \u00034(FAILED)\u000f");
conn.notifyHandlers(NetworkConnection.EVENT_BUFFERMSG, e);
}
}
break;
case NetworkConnection.EVENT_BUFFERMSG:
try {
EventsDataSource.Event e = (EventsDataSource.Event)msg.obj;
if(e.bid != bid && upView != null) {
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
}
if(e.from.equalsIgnoreCase(name)) {
for(EventsDataSource.Event e1 : pendingEvents.values()) {
EventsDataSource.getInstance().deleteEvent(e1.eid, e1.bid);
}
pendingEvents.clear();
} else if(pendingEvents.containsKey(e.reqid)) {
e = pendingEvents.get(e.reqid);
EventsDataSource.getInstance().deleteEvent(e.eid, e.bid);
pendingEvents.remove(e.reqid);
}
} catch (Exception e1) {
}
break;
}
}
|
diff --git a/src/main/java/fr/aumgn/tobenamed/command/GeneralCommands.java b/src/main/java/fr/aumgn/tobenamed/command/GeneralCommands.java
index d5fd70a..05561ea 100644
--- a/src/main/java/fr/aumgn/tobenamed/command/GeneralCommands.java
+++ b/src/main/java/fr/aumgn/tobenamed/command/GeneralCommands.java
@@ -1,20 +1,20 @@
package fr.aumgn.tobenamed.command;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import fr.aumgn.bukkit.command.Command;
import fr.aumgn.bukkit.command.CommandArgs;
import fr.aumgn.bukkit.command.Commands;
import fr.aumgn.tobenamed.TBN;
import fr.aumgn.tobenamed.stage.Stage;
public class GeneralCommands extends Commands {
@Command(name = "stop-game", max = 0)
public void stopGame(CommandSender sender, CommandArgs args) {
Stage stage = TBN.getStage();
- TBN.nextStage(null);
+ TBN.forceStop();
stage.getGame().sendMessage(ChatColor.RED + "La partie a été arreté.");
}
}
| true | true | public void stopGame(CommandSender sender, CommandArgs args) {
Stage stage = TBN.getStage();
TBN.nextStage(null);
stage.getGame().sendMessage(ChatColor.RED + "La partie a été arreté.");
}
| public void stopGame(CommandSender sender, CommandArgs args) {
Stage stage = TBN.getStage();
TBN.forceStop();
stage.getGame().sendMessage(ChatColor.RED + "La partie a été arreté.");
}
|
diff --git a/battleships-presentation/src/main/java/com/jostrobin/battleships/view/panels/ShipsPanel.java b/battleships-presentation/src/main/java/com/jostrobin/battleships/view/panels/ShipsPanel.java
index d7286a0..2675c9c 100644
--- a/battleships-presentation/src/main/java/com/jostrobin/battleships/view/panels/ShipsPanel.java
+++ b/battleships-presentation/src/main/java/com/jostrobin/battleships/view/panels/ShipsPanel.java
@@ -1,138 +1,138 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jostrobin.battleships.view.panels;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.*;
import com.jostrobin.battleships.data.Ship;
import com.jostrobin.battleships.view.components.CellComponent;
import com.jostrobin.battleships.view.listeners.SelectionListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author rowyss
* Date: 05.11.11 Time: 18:52
*/
public class ShipsPanel extends JPanel implements ActionListener
{
private JButton rotate;
private JButton rotateRightButton;
private int y;
private List<SelectionListener<Ship>> selectionListeners = new ArrayList<SelectionListener<Ship>>();
private Map<Ship, JPanel> shipPanels = new HashMap<Ship, JPanel>();
private static final Logger LOG = LoggerFactory.getLogger(ShipsPanel.class);
public ShipsPanel()
{
initUi();
}
private void initUi()
{
setLayout(new GridBagLayout());
rotate = new JButton("Rotate left");
GridBagConstraints leftButtonConstraints = new GridBagConstraints();
leftButtonConstraints.gridy = y++;
leftButtonConstraints.anchor = GridBagConstraints.ABOVE_BASELINE;
add(rotate, leftButtonConstraints);
}
public void updateShips(List<Ship> ships)
{
removeAllShips();
MouseListener mouseListener = new MouseListener();
for (Ship ship : ships)
{
if (ship.isPlaced())
{
continue;
}
JPanel shipPanel = new JPanel();
shipPanel.setLayout(new GridLayout(1, ship.getSize()));
shipPanel.setPreferredSize(new Dimension(ship.getSize() * CellComponent.CELL_SIZE, CellComponent.CELL_SIZE));
for (int i = 0; i < ship.getSize(); i++)
{
CellComponent cell = new CellComponent(1, i);
// cell.setHighlight(false);
cell.setShip(ship);
cell.addMouseListener(mouseListener);
ship.addCell(cell);
shipPanel.add(cell);
}
GridBagConstraints shipConstraints = new GridBagConstraints();
shipConstraints.gridy = y++;
shipConstraints.anchor = GridBagConstraints.BASELINE;
shipConstraints.insets = new Insets(2, 2, 2, 2);
shipPanels.put(ship, shipPanel);
add(shipPanel, shipConstraints);
}
- repaint();
+ revalidate();
}
private void removeAllShips()
{
for (JPanel shipPanel : shipPanels.values())
{
remove(shipPanel);
y--;
}
shipPanels.clear();
}
public void addSelectionListener(SelectionListener<Ship> selectionListener)
{
selectionListeners.add(selectionListener);
}
@Override
public void actionPerformed(ActionEvent actionEvent)
{
//To change body of implemented methods use File | Settings | File Templates.
}
private class MouseListener extends MouseAdapter
{
@Override
public void mouseClicked(MouseEvent mouseEvent)
{
if (mouseEvent.getSource() instanceof CellComponent)
{
CellComponent cell = (CellComponent) mouseEvent.getSource();
cell.setSelected(true);
Ship ship = cell.getShip();
LOG.debug("Ship with size {} was selected", ship.getSize());
for (SelectionListener<Ship> selectionListener : selectionListeners)
{
selectionListener.selected(ship);
}
}
}
}
}
| true | true | public void updateShips(List<Ship> ships)
{
removeAllShips();
MouseListener mouseListener = new MouseListener();
for (Ship ship : ships)
{
if (ship.isPlaced())
{
continue;
}
JPanel shipPanel = new JPanel();
shipPanel.setLayout(new GridLayout(1, ship.getSize()));
shipPanel.setPreferredSize(new Dimension(ship.getSize() * CellComponent.CELL_SIZE, CellComponent.CELL_SIZE));
for (int i = 0; i < ship.getSize(); i++)
{
CellComponent cell = new CellComponent(1, i);
// cell.setHighlight(false);
cell.setShip(ship);
cell.addMouseListener(mouseListener);
ship.addCell(cell);
shipPanel.add(cell);
}
GridBagConstraints shipConstraints = new GridBagConstraints();
shipConstraints.gridy = y++;
shipConstraints.anchor = GridBagConstraints.BASELINE;
shipConstraints.insets = new Insets(2, 2, 2, 2);
shipPanels.put(ship, shipPanel);
add(shipPanel, shipConstraints);
}
repaint();
}
| public void updateShips(List<Ship> ships)
{
removeAllShips();
MouseListener mouseListener = new MouseListener();
for (Ship ship : ships)
{
if (ship.isPlaced())
{
continue;
}
JPanel shipPanel = new JPanel();
shipPanel.setLayout(new GridLayout(1, ship.getSize()));
shipPanel.setPreferredSize(new Dimension(ship.getSize() * CellComponent.CELL_SIZE, CellComponent.CELL_SIZE));
for (int i = 0; i < ship.getSize(); i++)
{
CellComponent cell = new CellComponent(1, i);
// cell.setHighlight(false);
cell.setShip(ship);
cell.addMouseListener(mouseListener);
ship.addCell(cell);
shipPanel.add(cell);
}
GridBagConstraints shipConstraints = new GridBagConstraints();
shipConstraints.gridy = y++;
shipConstraints.anchor = GridBagConstraints.BASELINE;
shipConstraints.insets = new Insets(2, 2, 2, 2);
shipPanels.put(ship, shipPanel);
add(shipPanel, shipConstraints);
}
revalidate();
}
|
diff --git a/motech-mobileforms-api/src/test/java/org/motechproject/mobileforms/api/web/FormUploadServletIT.java b/motech-mobileforms-api/src/test/java/org/motechproject/mobileforms/api/web/FormUploadServletIT.java
index 620c3b60e..6edda6128 100644
--- a/motech-mobileforms-api/src/test/java/org/motechproject/mobileforms/api/web/FormUploadServletIT.java
+++ b/motech-mobileforms-api/src/test/java/org/motechproject/mobileforms/api/web/FormUploadServletIT.java
@@ -1,117 +1,117 @@
package org.motechproject.mobileforms.api.web;
import com.jcraft.jzlib.ZInputStream;
import org.fcitmuk.epihandy.EpihandyXformSerializer;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.motechproject.mobileforms.api.callbacks.FormProcessor;
import org.motechproject.mobileforms.api.callbacks.FormPublisher;
import org.motechproject.mobileforms.api.domain.FormBean;
import org.motechproject.mobileforms.api.validator.TestFormBean;
import org.motechproject.mobileforms.api.validator.TestFormValidator;
import org.motechproject.mobileforms.api.vo.Study;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.util.ReflectionTestUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static junit.framework.Assert.assertFalse;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
public class FormUploadServletIT {
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private MockServletContext servletContext;
@Mock
FormPublisher formPublisher;
@Mock
private FormProcessor formProcessor;
@Before
public void setUp() {
initMocks(this);
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
servletContext = new MockServletContext();
}
@Test
public void shouldProcessUploadedFormAndReturnValidationErrorsIfErrorsAreFound() throws Exception {
FormUploadServlet formUploadServlet = new FormUploadServlet();
- ReflectionTestUtils.setField(formUploadServlet, "formProcessor", formProcessor);
ReflectionTestUtils.setField(formUploadServlet, "formPublisher", formPublisher);
FormUploadServlet servlet = spy(formUploadServlet);
+ doReturn(formProcessor).when(servlet).createFormProcessor();
List<FormBean> formBeans = new ArrayList<FormBean>();
TestFormBean formBeanWithOutValidationErrors = new TestFormBean();
formBeanWithOutValidationErrors.setValidator(TestFormValidator.class.getName());
formBeanWithOutValidationErrors.setFirstName("Abc");
TestFormBean formBeanWithValidationErrors = new TestFormBean();
formBeanWithValidationErrors.setValidator(TestFormValidator.class.getName());
formBeanWithValidationErrors.setFirstName("1Abc");
formBeans.add(formBeanWithOutValidationErrors);
formBeans.add(formBeanWithValidationErrors);
Study study = new Study("study_name", formBeans);
List<Study> studies = Arrays.asList(study);
when(formProcessor.getStudies()).thenReturn(studies);
EpihandyXformSerializer epihandyXformSerializer = spy(new EpihandyXformSerializer());
doNothing().when(epihandyXformSerializer).deserializeStudiesWithEvents(any(DataInputStream.class), anyObject());
doReturn(epihandyXformSerializer).when(servlet).serializer();
TestFormValidator testFormValidator = new TestFormValidator();
servletContext.setAttribute(TestFormValidator.class.getName(), testFormValidator);
doReturn(servletContext).when(servlet).getServletContext();
try {
setupRequestWithActionAndOtherRequestParameters(request, "username", "password", FormDownloadServlet.ACTION_DOWNLOAD_STUDY_LIST);
servlet.doPost(request, response);
DataInputStream responseSentToMobile = readResponse(response);
int expectedNoOfSuccessfullyUploadedForms = 1;
int expectedNoOfFailedForms = 1;
int expectedStudyIndex = 0;
int expectedFormIndex = 1;
assertThat(responseSentToMobile.readByte(), is(equalTo(FormDownloadServlet.RESPONSE_SUCCESS)));
assertThat(responseSentToMobile.readInt(), is(equalTo(expectedNoOfSuccessfullyUploadedForms)));
assertThat(responseSentToMobile.readInt(), is(equalTo(expectedNoOfFailedForms)));
assertThat(responseSentToMobile.readByte(), is(equalTo((byte) expectedStudyIndex)));
assertThat(responseSentToMobile.readShort(), is(equalTo((short) expectedFormIndex)));
assertThat(responseSentToMobile.readUTF(), is(equalTo("Errors:firstName=wrong format")));
} catch (Exception e) {
assertFalse(true);
}
verify(formPublisher).publish(formBeanWithOutValidationErrors);
}
private DataInputStream readResponse(MockHttpServletResponse response) {
return new DataInputStream(new ZInputStream(new ByteArrayInputStream(response.getContentAsByteArray())));
}
private void setupRequestWithActionAndOtherRequestParameters(MockHttpServletRequest request, String userName, String password, byte actionCode) throws Exception {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
dataOutputStream.writeUTF(userName);
dataOutputStream.writeUTF(password);
dataOutputStream.writeUTF("epihandyser");
dataOutputStream.writeUTF("en");
dataOutputStream.writeByte(actionCode);
request.setContent(byteArrayOutputStream.toByteArray());
}
}
| false | true | public void shouldProcessUploadedFormAndReturnValidationErrorsIfErrorsAreFound() throws Exception {
FormUploadServlet formUploadServlet = new FormUploadServlet();
ReflectionTestUtils.setField(formUploadServlet, "formProcessor", formProcessor);
ReflectionTestUtils.setField(formUploadServlet, "formPublisher", formPublisher);
FormUploadServlet servlet = spy(formUploadServlet);
List<FormBean> formBeans = new ArrayList<FormBean>();
TestFormBean formBeanWithOutValidationErrors = new TestFormBean();
formBeanWithOutValidationErrors.setValidator(TestFormValidator.class.getName());
formBeanWithOutValidationErrors.setFirstName("Abc");
TestFormBean formBeanWithValidationErrors = new TestFormBean();
formBeanWithValidationErrors.setValidator(TestFormValidator.class.getName());
formBeanWithValidationErrors.setFirstName("1Abc");
formBeans.add(formBeanWithOutValidationErrors);
formBeans.add(formBeanWithValidationErrors);
Study study = new Study("study_name", formBeans);
List<Study> studies = Arrays.asList(study);
when(formProcessor.getStudies()).thenReturn(studies);
EpihandyXformSerializer epihandyXformSerializer = spy(new EpihandyXformSerializer());
doNothing().when(epihandyXformSerializer).deserializeStudiesWithEvents(any(DataInputStream.class), anyObject());
doReturn(epihandyXformSerializer).when(servlet).serializer();
TestFormValidator testFormValidator = new TestFormValidator();
servletContext.setAttribute(TestFormValidator.class.getName(), testFormValidator);
doReturn(servletContext).when(servlet).getServletContext();
try {
setupRequestWithActionAndOtherRequestParameters(request, "username", "password", FormDownloadServlet.ACTION_DOWNLOAD_STUDY_LIST);
servlet.doPost(request, response);
DataInputStream responseSentToMobile = readResponse(response);
int expectedNoOfSuccessfullyUploadedForms = 1;
int expectedNoOfFailedForms = 1;
int expectedStudyIndex = 0;
int expectedFormIndex = 1;
assertThat(responseSentToMobile.readByte(), is(equalTo(FormDownloadServlet.RESPONSE_SUCCESS)));
assertThat(responseSentToMobile.readInt(), is(equalTo(expectedNoOfSuccessfullyUploadedForms)));
assertThat(responseSentToMobile.readInt(), is(equalTo(expectedNoOfFailedForms)));
assertThat(responseSentToMobile.readByte(), is(equalTo((byte) expectedStudyIndex)));
assertThat(responseSentToMobile.readShort(), is(equalTo((short) expectedFormIndex)));
assertThat(responseSentToMobile.readUTF(), is(equalTo("Errors:firstName=wrong format")));
} catch (Exception e) {
assertFalse(true);
}
verify(formPublisher).publish(formBeanWithOutValidationErrors);
}
| public void shouldProcessUploadedFormAndReturnValidationErrorsIfErrorsAreFound() throws Exception {
FormUploadServlet formUploadServlet = new FormUploadServlet();
ReflectionTestUtils.setField(formUploadServlet, "formPublisher", formPublisher);
FormUploadServlet servlet = spy(formUploadServlet);
doReturn(formProcessor).when(servlet).createFormProcessor();
List<FormBean> formBeans = new ArrayList<FormBean>();
TestFormBean formBeanWithOutValidationErrors = new TestFormBean();
formBeanWithOutValidationErrors.setValidator(TestFormValidator.class.getName());
formBeanWithOutValidationErrors.setFirstName("Abc");
TestFormBean formBeanWithValidationErrors = new TestFormBean();
formBeanWithValidationErrors.setValidator(TestFormValidator.class.getName());
formBeanWithValidationErrors.setFirstName("1Abc");
formBeans.add(formBeanWithOutValidationErrors);
formBeans.add(formBeanWithValidationErrors);
Study study = new Study("study_name", formBeans);
List<Study> studies = Arrays.asList(study);
when(formProcessor.getStudies()).thenReturn(studies);
EpihandyXformSerializer epihandyXformSerializer = spy(new EpihandyXformSerializer());
doNothing().when(epihandyXformSerializer).deserializeStudiesWithEvents(any(DataInputStream.class), anyObject());
doReturn(epihandyXformSerializer).when(servlet).serializer();
TestFormValidator testFormValidator = new TestFormValidator();
servletContext.setAttribute(TestFormValidator.class.getName(), testFormValidator);
doReturn(servletContext).when(servlet).getServletContext();
try {
setupRequestWithActionAndOtherRequestParameters(request, "username", "password", FormDownloadServlet.ACTION_DOWNLOAD_STUDY_LIST);
servlet.doPost(request, response);
DataInputStream responseSentToMobile = readResponse(response);
int expectedNoOfSuccessfullyUploadedForms = 1;
int expectedNoOfFailedForms = 1;
int expectedStudyIndex = 0;
int expectedFormIndex = 1;
assertThat(responseSentToMobile.readByte(), is(equalTo(FormDownloadServlet.RESPONSE_SUCCESS)));
assertThat(responseSentToMobile.readInt(), is(equalTo(expectedNoOfSuccessfullyUploadedForms)));
assertThat(responseSentToMobile.readInt(), is(equalTo(expectedNoOfFailedForms)));
assertThat(responseSentToMobile.readByte(), is(equalTo((byte) expectedStudyIndex)));
assertThat(responseSentToMobile.readShort(), is(equalTo((short) expectedFormIndex)));
assertThat(responseSentToMobile.readUTF(), is(equalTo("Errors:firstName=wrong format")));
} catch (Exception e) {
assertFalse(true);
}
verify(formPublisher).publish(formBeanWithOutValidationErrors);
}
|
diff --git a/test/test-generation/src/main/java/org/umlg/test/generation/GenerateTestProjects.java b/test/test-generation/src/main/java/org/umlg/test/generation/GenerateTestProjects.java
index 29d0fe1c..b25d8507 100644
--- a/test/test-generation/src/main/java/org/umlg/test/generation/GenerateTestProjects.java
+++ b/test/test-generation/src/main/java/org/umlg/test/generation/GenerateTestProjects.java
@@ -1,29 +1,29 @@
package org.umlg.test.generation;
import java.io.File;
import java.net.URISyntaxException;
import org.umlg.generation.JavaGenerator;
import org.umlg.javageneration.DefaultVisitors;
import org.umlg.restlet.generation.RestletVisitors;
public class GenerateTestProjects {
public static void main(String[] args) throws URISyntaxException {
if (args.length == 0) {
args = new String[]{"."};
}
JavaGenerator javaGenerator = new JavaGenerator();
- javaGenerator.generate(new File(args[0] + "/test/blueprints/umlg-test-blueprints/src/main/model/umlg-test.uml"), new File(args[0] + "/test/blueprints/umlg-test-blueprints/"), DefaultVisitors.getDefaultJavaVisitors());
- javaGenerator = new JavaGenerator();
+// javaGenerator.generate(new File(args[0] + "/test/blueprints/umlg-test-blueprints/src/main/model/umlg-test.uml"), new File(args[0] + "/test/blueprints/umlg-test-blueprints/"), DefaultVisitors.getDefaultJavaVisitors());
+// javaGenerator = new JavaGenerator();
javaGenerator.generate(new File(args[0] + "/test/test-restlet/src/main/model/restAndJson.uml"), new File(args[0] + "/test/test-restlet/"), RestletVisitors.getDefaultJavaVisitors());
- javaGenerator = new JavaGenerator();
- javaGenerator.generate(new File(args[0] + "/test/umlg-test-basic/src/main/model/umlg-test-basic.uml"), new File(args[0] + "/test/umlg-test-basic/"), DefaultVisitors.getDefaultJavaVisitors());
- javaGenerator = new JavaGenerator();
- javaGenerator.generate(new File(args[0] + "/test/umlg-test-ocl/src/main/model/test-ocl.uml"), new File(args[0] + "/test/umlg-test-ocl/"), DefaultVisitors.getDefaultJavaVisitors());
- javaGenerator = new JavaGenerator();
- javaGenerator.generate(new File(args[0] + "/test/test-restlet-minimal/src/main/model/test-restlet-minimal.uml"), new File(args[0] + "/test/test-restlet-minimal/"), RestletVisitors.getDefaultJavaVisitors());
- javaGenerator = new JavaGenerator();
- javaGenerator.generate(new File(args[0] + "/test/umlg-test-tinkergraph/src/main/model/tinkergraph.uml"), new File(args[0] + "/test/umlg-test-tinkergraph/"), DefaultVisitors.getDefaultJavaVisitors());
+// javaGenerator = new JavaGenerator();
+// javaGenerator.generate(new File(args[0] + "/test/umlg-test-basic/src/main/model/umlg-test-basic.uml"), new File(args[0] + "/test/umlg-test-basic/"), DefaultVisitors.getDefaultJavaVisitors());
+// javaGenerator = new JavaGenerator();
+// javaGenerator.generate(new File(args[0] + "/test/umlg-test-ocl/src/main/model/test-ocl.uml"), new File(args[0] + "/test/umlg-test-ocl/"), DefaultVisitors.getDefaultJavaVisitors());
+// javaGenerator = new JavaGenerator();
+// javaGenerator.generate(new File(args[0] + "/test/test-restlet-minimal/src/main/model/test-restlet-minimal.uml"), new File(args[0] + "/test/test-restlet-minimal/"), RestletVisitors.getDefaultJavaVisitors());
+// javaGenerator = new JavaGenerator();
+// javaGenerator.generate(new File(args[0] + "/test/umlg-test-tinkergraph/src/main/model/tinkergraph.uml"), new File(args[0] + "/test/umlg-test-tinkergraph/"), DefaultVisitors.getDefaultJavaVisitors());
}
}
| false | true | public static void main(String[] args) throws URISyntaxException {
if (args.length == 0) {
args = new String[]{"."};
}
JavaGenerator javaGenerator = new JavaGenerator();
javaGenerator.generate(new File(args[0] + "/test/blueprints/umlg-test-blueprints/src/main/model/umlg-test.uml"), new File(args[0] + "/test/blueprints/umlg-test-blueprints/"), DefaultVisitors.getDefaultJavaVisitors());
javaGenerator = new JavaGenerator();
javaGenerator.generate(new File(args[0] + "/test/test-restlet/src/main/model/restAndJson.uml"), new File(args[0] + "/test/test-restlet/"), RestletVisitors.getDefaultJavaVisitors());
javaGenerator = new JavaGenerator();
javaGenerator.generate(new File(args[0] + "/test/umlg-test-basic/src/main/model/umlg-test-basic.uml"), new File(args[0] + "/test/umlg-test-basic/"), DefaultVisitors.getDefaultJavaVisitors());
javaGenerator = new JavaGenerator();
javaGenerator.generate(new File(args[0] + "/test/umlg-test-ocl/src/main/model/test-ocl.uml"), new File(args[0] + "/test/umlg-test-ocl/"), DefaultVisitors.getDefaultJavaVisitors());
javaGenerator = new JavaGenerator();
javaGenerator.generate(new File(args[0] + "/test/test-restlet-minimal/src/main/model/test-restlet-minimal.uml"), new File(args[0] + "/test/test-restlet-minimal/"), RestletVisitors.getDefaultJavaVisitors());
javaGenerator = new JavaGenerator();
javaGenerator.generate(new File(args[0] + "/test/umlg-test-tinkergraph/src/main/model/tinkergraph.uml"), new File(args[0] + "/test/umlg-test-tinkergraph/"), DefaultVisitors.getDefaultJavaVisitors());
}
| public static void main(String[] args) throws URISyntaxException {
if (args.length == 0) {
args = new String[]{"."};
}
JavaGenerator javaGenerator = new JavaGenerator();
// javaGenerator.generate(new File(args[0] + "/test/blueprints/umlg-test-blueprints/src/main/model/umlg-test.uml"), new File(args[0] + "/test/blueprints/umlg-test-blueprints/"), DefaultVisitors.getDefaultJavaVisitors());
// javaGenerator = new JavaGenerator();
javaGenerator.generate(new File(args[0] + "/test/test-restlet/src/main/model/restAndJson.uml"), new File(args[0] + "/test/test-restlet/"), RestletVisitors.getDefaultJavaVisitors());
// javaGenerator = new JavaGenerator();
// javaGenerator.generate(new File(args[0] + "/test/umlg-test-basic/src/main/model/umlg-test-basic.uml"), new File(args[0] + "/test/umlg-test-basic/"), DefaultVisitors.getDefaultJavaVisitors());
// javaGenerator = new JavaGenerator();
// javaGenerator.generate(new File(args[0] + "/test/umlg-test-ocl/src/main/model/test-ocl.uml"), new File(args[0] + "/test/umlg-test-ocl/"), DefaultVisitors.getDefaultJavaVisitors());
// javaGenerator = new JavaGenerator();
// javaGenerator.generate(new File(args[0] + "/test/test-restlet-minimal/src/main/model/test-restlet-minimal.uml"), new File(args[0] + "/test/test-restlet-minimal/"), RestletVisitors.getDefaultJavaVisitors());
// javaGenerator = new JavaGenerator();
// javaGenerator.generate(new File(args[0] + "/test/umlg-test-tinkergraph/src/main/model/tinkergraph.uml"), new File(args[0] + "/test/umlg-test-tinkergraph/"), DefaultVisitors.getDefaultJavaVisitors());
}
|
diff --git a/flexodesktop/GUI/flexographicalengine/src/main/java/org/openflexo/fge/view/listener/FGEViewMouseListener.java b/flexodesktop/GUI/flexographicalengine/src/main/java/org/openflexo/fge/view/listener/FGEViewMouseListener.java
index 2e5fd46ba..9f575dac6 100644
--- a/flexodesktop/GUI/flexographicalengine/src/main/java/org/openflexo/fge/view/listener/FGEViewMouseListener.java
+++ b/flexodesktop/GUI/flexographicalengine/src/main/java/org/openflexo/fge/view/listener/FGEViewMouseListener.java
@@ -1,633 +1,630 @@
/*
* (c) Copyright 2010-2011 AgileBirds
*
* This file is part of OpenFlexo.
*
* OpenFlexo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenFlexo is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenFlexo. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.openflexo.fge.view.listener;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingUtilities;
import org.openflexo.fge.ConnectorGraphicalRepresentation;
import org.openflexo.fge.GraphicalRepresentation;
import org.openflexo.fge.ShapeGraphicalRepresentation;
import org.openflexo.fge.controller.DrawingController;
import org.openflexo.fge.controller.DrawingController.EditorTool;
import org.openflexo.fge.controller.MouseClickControl;
import org.openflexo.fge.controller.MouseDragControl;
import org.openflexo.fge.cp.ControlArea;
import org.openflexo.fge.geom.FGEPoint;
import org.openflexo.fge.view.FGEPaintManager;
import org.openflexo.fge.view.FGEView;
import org.openflexo.fge.view.LabelView;
import org.openflexo.toolbox.ToolBox;
public class FGEViewMouseListener implements MouseListener, MouseMotionListener {
private static final Logger logger = Logger.getLogger(FGEViewMouseListener.class.getPackage().getName());
private GraphicalRepresentation<?> graphicalRepresentation;
protected FGEView<?> view;
public FGEViewMouseListener(GraphicalRepresentation<?> aGraphicalRepresentation, FGEView<?> aView) {
graphicalRepresentation = aGraphicalRepresentation;
view = aView;
}
private MouseEvent previousEvent;
@Override
public void mouseClicked(MouseEvent e) {
if (view.isDeleted()) {
return;
}
if (ToolBox.getPLATFORM() == ToolBox.MACOS) {
if (e.getClickCount() == 2 && previousEvent != null) {
if (previousEvent.getClickCount() == 1 && previousEvent.getComponent() == e.getComponent()
&& previousEvent.getButton() != e.getButton()) {
e = new MouseEvent(e.getComponent(), e.getID(), e.getWhen(), e.getModifiers(), e.getX(), e.getY(), 1,
e.isPopupTrigger());
}
}
}
previousEvent = e;
boolean editable = getController().getDrawing().isEditable();
switch (getController().getCurrentTool()) {
case SelectionTool:
GraphicalRepresentation<?> focusedObject = getFocusRetriever().getFocusedObject(e);
- if (focusedObject == null) {
- focusedObject = getController().getDrawingGraphicalRepresentation();
- }
- editable &= !focusedObject.getIsReadOnly();
+ editable &= focusedObject != null && !focusedObject.getIsReadOnly();
if (editable) {
if (getController().hasEditedLabel()) {
if (handleEventForEditedLabel(e, focusedObject)) {
return;
// return;
}
}
if (focusedObject != null && getFocusRetriever().focusOnFloatingLabel(focusedObject, e) && getController().hasEditedLabel()
&& getController().getEditedLabel().getGraphicalRepresentation() == focusedObject) {
// Special case, do nothing, since we let the label live its life !!!
e.consume();
return;
}
if (focusedObject != null && e.getClickCount() == 2 && getFocusRetriever().focusOnFloatingLabel(focusedObject, e)) {
if (focusedObject instanceof ShapeGraphicalRepresentation) {
view.getDrawingView().shapeViewForObject((ShapeGraphicalRepresentation<?>) focusedObject).getLabelView()
.startEdition();
e.consume();
return;
} else if (focusedObject instanceof ConnectorGraphicalRepresentation) {
view.getDrawingView().connectorViewForObject((ConnectorGraphicalRepresentation<?>) focusedObject).getLabelView()
.startEdition();
e.consume();
return;
}
}
if (focusedObject != null) {
ControlArea<?> ca = getFocusRetriever().getFocusedControlAreaForDrawable(focusedObject, e);
if (ca != null && ca.isClickable()) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("Click on control area " + ca);
}
Point clickedLocationInDrawingView = SwingUtilities.convertPoint((Component) e.getSource(), e.getPoint(),
view.getDrawingView());
FGEPoint clickedPoint = ca.getGraphicalRepresentation().convertRemoteViewCoordinatesToLocalNormalizedPoint(
clickedLocationInDrawingView, view.getDrawingView().getGraphicalRepresentation(),
view.getDrawingView().getScale());
if (ca.clickOnPoint(clickedPoint, e.getClickCount())) {
// Event was successfully handled
e.consume();
return;
}
}
}
}
if (focusedObject == null) {
focusedObject = graphicalRepresentation.getDrawing().getDrawingGraphicalRepresentation();
}
if (view.isDeleted()) {
return;
}
// We have now performed all low-level possible actions, let's go for the registered mouse controls
for (MouseClickControl mouseClickControl : focusedObject.getMouseClickControls()) {
if ((editable || !mouseClickControl.isModelEditionAction())
&& mouseClickControl.isApplicable(focusedObject, getController(), e)) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("Applying " + mouseClickControl);
}
mouseClickControl.handleClick(focusedObject, getController(), e);
} else {
if (logger.isLoggable(Level.FINE)) {
logger.fine("Ignoring " + mouseClickControl);
}
}
}
break;
case DrawShapeTool:
if (editable) {
getController().getDrawShapeToolController().mouseClicked(e);
}
default:
break;
}
}
@Override
public void mouseEntered(MouseEvent e) {
if (view.isDeleted()) {
return;
}
// SGU: I dont think that JTextComponent react to these event, but in case of, uncomment this
// GPO: Actually this is not the case because a mouse enter/exited event in one component does
// not make sense for another one. If we want to emulate those event, it should be done
// in the mouse moved event.
/*if (getController().hasEditedLabel()) {
GraphicalRepresentation<?> focusedObject = getFocusRetriever().getFocusedObject(e);
handleEventForEditedLabel(e, focusedObject);
}*/
}
@Override
public void mouseExited(MouseEvent e) {
if (view.isDeleted()) {
return;
}
// SGU: I dont think that JTextComponent react to these event, but in case of, uncomment this
// GPO: Actually this is not the case because a mouse enter/exited event in one component does
// not make sense for another one. If we want to emulate those event, it should be done
// in the mouse moved event.
/*if (getController().hasEditedLabel()) {
GraphicalRepresentation<?> focusedObject = getFocusRetriever().getFocusedObject(e);
handleEventForEditedLabel(e, focusedObject);
}*/
}
private ControlAreaDrag currentControlAreaDrag = null;
private class ControlAreaDrag {
private Point startMovingLocationInDrawingView;
private FGEPoint startMovingPoint;
private ControlArea<?> controlArea;
private double initialWidth;
private double initialHeight;
private ControlAreaDrag(ControlArea<?> aControlArea, MouseEvent e) {
controlArea = aControlArea;
startMovingLocationInDrawingView = SwingUtilities.convertPoint((Component) e.getSource(), e.getPoint(), view.getDrawingView());
logger.fine("ControlPointDrag: start pt = " + startMovingLocationInDrawingView);
FGEPoint relativeStartMovingPoint = controlArea.getGraphicalRepresentation()
.convertRemoteViewCoordinatesToLocalNormalizedPoint(startMovingLocationInDrawingView,
view.getDrawingView().getGraphicalRepresentation(), view.getDrawingView().getScale());
startMovingPoint = aControlArea.getArea().getNearestPoint(relativeStartMovingPoint);
Point clickedLocationInDrawingView = SwingUtilities
.convertPoint((Component) e.getSource(), e.getPoint(), view.getDrawingView());
aControlArea.startDragging(
getController(),
aControlArea.getGraphicalRepresentation().convertRemoteViewCoordinatesToLocalNormalizedPoint(
clickedLocationInDrawingView, view.getDrawingView().getGraphicalRepresentation(),
view.getDrawingView().getScale()));
if (controlArea.getGraphicalRepresentation().isConnectedToDrawing()) {
initialWidth = controlArea.getGraphicalRepresentation().getViewWidth(view.getScale());
initialHeight = controlArea.getGraphicalRepresentation().getViewHeight(view.getScale());
} else {
// System.out.println("Not connected to drawing");
initialWidth = 0;
initialHeight = 0;
}
}
private boolean moveTo(Point newLocationInDrawingView, MouseEvent e) {
FGEPoint newAbsoluteLocation = new FGEPoint(startMovingPoint.x
+ (newLocationInDrawingView.x - startMovingLocationInDrawingView.x) / view.getScale(), startMovingPoint.y
+ (newLocationInDrawingView.y - startMovingLocationInDrawingView.y) / view.getScale());
FGEPoint newRelativeLocation = getGraphicalRepresentation().getDrawingGraphicalRepresentation()
.convertLocalViewCoordinatesToRemoteNormalizedPoint(newLocationInDrawingView, controlArea.getGraphicalRepresentation(),
view.getScale());
FGEPoint pointRelativeToInitialConfiguration = new FGEPoint(startMovingPoint.x
+ (newLocationInDrawingView.x - startMovingLocationInDrawingView.x) / initialWidth/* *view.getScale()*/,
startMovingPoint.y + (newLocationInDrawingView.y - startMovingLocationInDrawingView.y) / initialHeight/* *view.getScale()*/);
return controlArea.dragToPoint(newRelativeLocation, pointRelativeToInitialConfiguration, newAbsoluteLocation, startMovingPoint,
e);
}
private void stopDragging(GraphicalRepresentation<?> focusedGR) {
controlArea.stopDragging(getController(), focusedGR);
}
}
private FloatingLabelDrag currentFloatingLabelDrag = null;
private class FloatingLabelDrag {
private GraphicalRepresentation<?> graphicalRepresentation;
private Point startMovingLocationInDrawingView;
private Point startLabelPoint;
private boolean started = false;
private FloatingLabelDrag(GraphicalRepresentation<?> aGraphicalRepresentation, Point startMovingLocationInDrawingView) {
graphicalRepresentation = aGraphicalRepresentation;
this.startMovingLocationInDrawingView = startMovingLocationInDrawingView;
logger.fine("FloatingLabelDrag: start pt = " + startMovingLocationInDrawingView);
startLabelPoint = graphicalRepresentation.getLabelLocation(view.getScale());
}
private void startDragging() {
graphicalRepresentation.notifyLabelWillMove();
}
private void moveTo(Point newLocationInDrawingView) {
if (!started) {
startDragging();
started = true;
}
Point newLabelCenterPoint = new Point(startLabelPoint.x + newLocationInDrawingView.x - startMovingLocationInDrawingView.x,
startLabelPoint.y + newLocationInDrawingView.y - startMovingLocationInDrawingView.y);
graphicalRepresentation.setLabelLocation(newLabelCenterPoint, view.getScale());
/*if (graphicalRepresentation instanceof ShapeGraphicalRepresentation
&& ((ShapeGraphicalRepresentation)graphicalRepresentation).isParentLayoutedAsContainer()) {
Point resultingLocation = graphicalRepresentation.getLabelViewCenter(view.getScale());
if (!resultingLocation.equals(newLabelCenterPoint)) {
int dx = resultingLocation.x-newLabelCenterPoint.x;
int dy = resultingLocation.y-newLabelCenterPoint.y;
startLabelCenterPoint.x = startLabelCenterPoint.x+dx;
startLabelCenterPoint.y = startLabelCenterPoint.y+dy;
}
}*/
}
private void stopDragging() {
if (getPaintManager().isPaintingCacheEnabled()) {
getPaintManager().removeFromTemporaryObjects(graphicalRepresentation);
getPaintManager().invalidate(graphicalRepresentation);
getPaintManager().repaint(view.getDrawingView());
}
}
}
@Override
public void mousePressed(MouseEvent e) {
if (view.isDeleted()) {
return;
}
boolean editable = getController().getDrawing().isEditable();
GraphicalRepresentation<?> focusedObject = getFocusRetriever().getFocusedObject(e);
if (focusedObject == null) {
focusedObject = graphicalRepresentation.getDrawing().getDrawingGraphicalRepresentation();
}
editable &= !focusedObject.getIsReadOnly();
if (editable) {
if (getController().hasEditedLabel()) {
if (handleEventForEditedLabel(e, focusedObject)) {
// Special case, do nothing, since we let the label live its life !!!
return;
}
}
getController().stopEditionOfEditedLabelIfAny();
if (focusedObject.hasFloatingLabel() && getFocusRetriever().focusOnFloatingLabel(focusedObject, e)) {
currentFloatingLabelDrag = new FloatingLabelDrag(focusedObject, SwingUtilities.convertPoint((Component) e.getSource(),
e.getPoint(), view.getDrawingView()));
e.consume();
return;
} else {
ControlArea<?> ca = getFocusRetriever().getFocusedControlAreaForDrawable(focusedObject, e);
if (ca != null && ca.isDraggable()) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("Starting drag of control point " + ca);
}
currentControlAreaDrag = new ControlAreaDrag(ca, e);
e.consume();
return;
}
}
}
// We have now performed all low-level possible actions, let's go for the registered mouse controls
List<MouseDragControl> applicableMouseDragControls = new ArrayList<MouseDragControl>();
for (MouseDragControl mouseDragControl : focusedObject.getMouseDragControls()) {
if ((editable || !mouseDragControl.isModelEditionAction()) && mouseDragControl.isApplicable(focusedObject, getController(), e)) {
applicableMouseDragControls.add(mouseDragControl);
if (logger.isLoggable(Level.FINE)) {
logger.fine("Found applicable " + mouseDragControl);
}
} else {
if (logger.isLoggable(Level.FINE)) {
logger.fine("Ignoring " + mouseDragControl);
}
}
}
if (applicableMouseDragControls.size() == 0) {
// No applicable mouse drag
return;
}
if (applicableMouseDragControls.size() > 1) {
logger.warning("More than one applicable MouseDragControl for graphical representation: " + focusedObject
+ " Applying first and forgetting others...");
}
// Apply applicable mouse drag control
MouseDragControl currentMouseDrag = applicableMouseDragControls.get(0);
if (logger.isLoggable(Level.FINE)) {
logger.fine("Applying " + currentMouseDrag);
}
if (currentMouseDrag.handleMousePressed(focusedObject, getController(), e)) {
// Everything OK
if (getController() != null) {
getController().setCurrentMouseDrag(currentMouseDrag);
}
} else {
// Something failed, abort this drag
if (getController() != null) {
getController().setCurrentMouseDrag(null);
}
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (view.isDeleted()) {
return;
}
if (getController().hasEditedLabel()) {
GraphicalRepresentation<?> focusedObject = getFocusRetriever().getFocusedObject(e);
if (handleEventForEditedLabel(e, focusedObject)) {
return;
}
// Special case, do nothing, since we let the label live its life !!!
e.consume();
return;
}
/*if (getController().hasEditedLabel()) {
// Special case, do nothing, since we let the label live its life !!!
e.consume();
return;
}*/
if (currentFloatingLabelDrag != null) {
currentFloatingLabelDrag.stopDragging();
currentFloatingLabelDrag = null;
e.consume();
}
if (currentControlAreaDrag != null) {
GraphicalRepresentation<?> focusedGR = getFocusRetriever().getFocusedObject(e);
// logger.info("Stop dragging, focused on " + focusedGR.getDrawable());
currentControlAreaDrag.stopDragging(focusedGR);
currentControlAreaDrag = null;
e.consume();
}
if (view.isDeleted()) {
return;
}
// We have now performed all low-level possible actions, let's go for the registered mouse controls
if (getController().getCurrentMouseDrag() != null) {
DrawingController<?> controller = getController();
controller.getCurrentMouseDrag().handleMouseReleased(getController(), e);
controller.setCurrentMouseDrag(null);
}
}
@Override
public void mouseDragged(MouseEvent e) {
if (view.isDeleted()) {
return;
}
boolean editable = getController().getDrawing().isEditable();
if (editable) {
if (getController().hasEditedLabel()) {
GraphicalRepresentation<?> focusedObject = getFocusRetriever().getFocusedObject(e);
if (handleEventForEditedLabel(e, focusedObject)) {
return;
}
// Special case, do nothing, since we let the label live its life !!!
e.consume();
return;
}
/*if (getController().hasEditedLabel()) {
// Special case, do nothing, since we let the label live its life !!!
e.consume();
return;
}*/
if (currentFloatingLabelDrag != null) {
Point newPointLocation = SwingUtilities.convertPoint((Component) e.getSource(), e.getPoint(), view.getDrawingView());
currentFloatingLabelDrag.moveTo(newPointLocation);
e.consume();
}
if (currentControlAreaDrag != null) {
Point newPointLocation = SwingUtilities.convertPoint((Component) e.getSource(), e.getPoint(), view.getDrawingView());
boolean continueDragging = currentControlAreaDrag.moveTo(newPointLocation, e);
e.consume();
if (!continueDragging) {
GraphicalRepresentation focusedGR = getFocusRetriever().getFocusedObject(e);
// logger.info("Stop dragging, focused on " + focusedGR.getDrawable());
currentControlAreaDrag.stopDragging(focusedGR);
logger.fine("OK, stopping dragging point");
currentControlAreaDrag = null;
}
}
}
// We have now performed all low-level possible actions, let's go for the registered mouse controls
getFocusRetriever().handleMouseMove(e);
if (getController().getCurrentMouseDrag() != null) {
getController().getCurrentMouseDrag().handleMouseDragged(getController(), e);
}
}
@Override
public void mouseMoved(MouseEvent e) {
if (view.isDeleted()) {
return;
}
if (getController().hasEditedLabel()) {
GraphicalRepresentation<?> focusedObject = getFocusRetriever().getFocusedObject(e);
if (handleEventForEditedLabel(e, focusedObject)) {
return;
// Special case, do nothing, since we let the label live its life !!!
/*e.consume();
return;*/
}
}
/*if (getController().hasEditedLabel()) {
// Special case, do nothing, since we let the label live its life !!!
e.consume();
return;
}*/
// We have now performed all low-level possible actions, let's go for the registered mouse controls
if (getController().getCurrentMouseDrag() != null) {
getController().getCurrentMouseDrag().handleMouseDragged(getController(), e);
}
getFocusRetriever().handleMouseMove(e);
if (getController().getCurrentTool() == EditorTool.DrawShapeTool) {
getController().getDrawShapeToolController().mouseMoved(e);
}
}
private Stack<MouseEvent> eventStack;
/**
* What happen here ? (SGU)
*
* Well, it's a long and difficult story. We have here a totally different view paradigm from Swing (where all view are rectangle).
* Here, we manage transparency, layers and complex shapes. That means that the mouse listener is sometimes not belonging to the view
* displayed accessed object.
*
* But we use swing in the context of text edition. Sometimes, we receive mouse events regarding JTextComponent management on some views
* that have nothing to do with the label this JTextComponent is representing. (focusedObject is not necessary object represented by the
* view)
*
* So, we have here to implement a re-targeting scheme for those events, for swing to correctly handle those events.
*
* @param e
* @param focusedObject
* @return
*/
private boolean handleEventForEditedLabel(MouseEvent e, GraphicalRepresentation<?> focusedObject) {
if (focusedObject == null || !focusedObject.getDrawing().isEditable()) {
return false;
}
LabelView<?> labelView = getController().getEditedLabel();
Point pointRelativeToTextComponent = SwingUtilities.convertPoint((Component) view, e.getPoint(), labelView);
if (labelView.getGraphicalRepresentation() == focusedObject) {
// Label being edited matches focused object:
// We potentially need to redispatch this event
if (labelView.contains(pointRelativeToTextComponent)) {
if (!labelView.isMouseInsideLabel()) {
MouseEvent newEvent = new MouseEvent(labelView.getTextComponent(), MouseEvent.MOUSE_ENTERED, e.getWhen(),
e.getModifiers(), pointRelativeToTextComponent.x, pointRelativeToTextComponent.y, e.getClickCount(),
e.isPopupTrigger());
labelView.getTextComponent().dispatchEvent(newEvent);
}
if (labelView.isEditing()) {
if (eventStack == null || eventStack.isEmpty() || eventStack.peek() != e) {
// This event effectively concerns related text component
// I will retarget it !
MouseEvent newEvent = new MouseEvent(labelView.getTextComponent(), e.getID(), e.getWhen(), e.getModifiers(),
pointRelativeToTextComponent.x, pointRelativeToTextComponent.y, e.getClickCount(), e.isPopupTrigger());
if (eventStack == null) {
eventStack = new Stack<MouseEvent>();
}
eventStack.add(newEvent);
labelView.getTextComponent().dispatchEvent(newEvent);
eventStack.pop();
if (eventStack.isEmpty()) {
eventStack = null;
}
e.consume();
return true;
}
}
} else {
triggerMouseExitedIfNeeded(e, labelView, pointRelativeToTextComponent);
}
return false;
} else {
triggerMouseExitedIfNeeded(e, labelView, pointRelativeToTextComponent);
}
return false;
}
private void triggerMouseExitedIfNeeded(MouseEvent e, LabelView<?> labelView, Point pointRelativeToTextComponent) {
if (labelView.isMouseInsideLabel()) {
MouseEvent newEvent = new MouseEvent(labelView.getTextComponent(), MouseEvent.MOUSE_EXITED, e.getWhen(), e.getModifiers(),
pointRelativeToTextComponent.x, pointRelativeToTextComponent.y, e.getClickCount(), e.isPopupTrigger());
labelView.getTextComponent().dispatchEvent(newEvent);
}
}
public DrawingController<?> getController() {
return view.getController();
}
public FocusRetriever getFocusRetriever() {
return view.getDrawingView().getFocusRetriever();
}
public Object getDrawable() {
return getGraphicalRepresentation().getDrawable();
}
public FGEView<?> getView() {
return view;
}
public GraphicalRepresentation<?> getGraphicalRepresentation() {
return graphicalRepresentation;
}
public FGEPaintManager getPaintManager() {
return view.getPaintManager();
}
}
| true | true | public void mouseClicked(MouseEvent e) {
if (view.isDeleted()) {
return;
}
if (ToolBox.getPLATFORM() == ToolBox.MACOS) {
if (e.getClickCount() == 2 && previousEvent != null) {
if (previousEvent.getClickCount() == 1 && previousEvent.getComponent() == e.getComponent()
&& previousEvent.getButton() != e.getButton()) {
e = new MouseEvent(e.getComponent(), e.getID(), e.getWhen(), e.getModifiers(), e.getX(), e.getY(), 1,
e.isPopupTrigger());
}
}
}
previousEvent = e;
boolean editable = getController().getDrawing().isEditable();
switch (getController().getCurrentTool()) {
case SelectionTool:
GraphicalRepresentation<?> focusedObject = getFocusRetriever().getFocusedObject(e);
if (focusedObject == null) {
focusedObject = getController().getDrawingGraphicalRepresentation();
}
editable &= !focusedObject.getIsReadOnly();
if (editable) {
if (getController().hasEditedLabel()) {
if (handleEventForEditedLabel(e, focusedObject)) {
return;
// return;
}
}
if (focusedObject != null && getFocusRetriever().focusOnFloatingLabel(focusedObject, e) && getController().hasEditedLabel()
&& getController().getEditedLabel().getGraphicalRepresentation() == focusedObject) {
// Special case, do nothing, since we let the label live its life !!!
e.consume();
return;
}
if (focusedObject != null && e.getClickCount() == 2 && getFocusRetriever().focusOnFloatingLabel(focusedObject, e)) {
if (focusedObject instanceof ShapeGraphicalRepresentation) {
view.getDrawingView().shapeViewForObject((ShapeGraphicalRepresentation<?>) focusedObject).getLabelView()
.startEdition();
e.consume();
return;
} else if (focusedObject instanceof ConnectorGraphicalRepresentation) {
view.getDrawingView().connectorViewForObject((ConnectorGraphicalRepresentation<?>) focusedObject).getLabelView()
.startEdition();
e.consume();
return;
}
}
if (focusedObject != null) {
ControlArea<?> ca = getFocusRetriever().getFocusedControlAreaForDrawable(focusedObject, e);
if (ca != null && ca.isClickable()) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("Click on control area " + ca);
}
Point clickedLocationInDrawingView = SwingUtilities.convertPoint((Component) e.getSource(), e.getPoint(),
view.getDrawingView());
FGEPoint clickedPoint = ca.getGraphicalRepresentation().convertRemoteViewCoordinatesToLocalNormalizedPoint(
clickedLocationInDrawingView, view.getDrawingView().getGraphicalRepresentation(),
view.getDrawingView().getScale());
if (ca.clickOnPoint(clickedPoint, e.getClickCount())) {
// Event was successfully handled
e.consume();
return;
}
}
}
}
if (focusedObject == null) {
focusedObject = graphicalRepresentation.getDrawing().getDrawingGraphicalRepresentation();
}
if (view.isDeleted()) {
return;
}
// We have now performed all low-level possible actions, let's go for the registered mouse controls
for (MouseClickControl mouseClickControl : focusedObject.getMouseClickControls()) {
if ((editable || !mouseClickControl.isModelEditionAction())
&& mouseClickControl.isApplicable(focusedObject, getController(), e)) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("Applying " + mouseClickControl);
}
mouseClickControl.handleClick(focusedObject, getController(), e);
} else {
if (logger.isLoggable(Level.FINE)) {
logger.fine("Ignoring " + mouseClickControl);
}
}
}
break;
case DrawShapeTool:
if (editable) {
getController().getDrawShapeToolController().mouseClicked(e);
}
default:
break;
}
}
| public void mouseClicked(MouseEvent e) {
if (view.isDeleted()) {
return;
}
if (ToolBox.getPLATFORM() == ToolBox.MACOS) {
if (e.getClickCount() == 2 && previousEvent != null) {
if (previousEvent.getClickCount() == 1 && previousEvent.getComponent() == e.getComponent()
&& previousEvent.getButton() != e.getButton()) {
e = new MouseEvent(e.getComponent(), e.getID(), e.getWhen(), e.getModifiers(), e.getX(), e.getY(), 1,
e.isPopupTrigger());
}
}
}
previousEvent = e;
boolean editable = getController().getDrawing().isEditable();
switch (getController().getCurrentTool()) {
case SelectionTool:
GraphicalRepresentation<?> focusedObject = getFocusRetriever().getFocusedObject(e);
editable &= focusedObject != null && !focusedObject.getIsReadOnly();
if (editable) {
if (getController().hasEditedLabel()) {
if (handleEventForEditedLabel(e, focusedObject)) {
return;
// return;
}
}
if (focusedObject != null && getFocusRetriever().focusOnFloatingLabel(focusedObject, e) && getController().hasEditedLabel()
&& getController().getEditedLabel().getGraphicalRepresentation() == focusedObject) {
// Special case, do nothing, since we let the label live its life !!!
e.consume();
return;
}
if (focusedObject != null && e.getClickCount() == 2 && getFocusRetriever().focusOnFloatingLabel(focusedObject, e)) {
if (focusedObject instanceof ShapeGraphicalRepresentation) {
view.getDrawingView().shapeViewForObject((ShapeGraphicalRepresentation<?>) focusedObject).getLabelView()
.startEdition();
e.consume();
return;
} else if (focusedObject instanceof ConnectorGraphicalRepresentation) {
view.getDrawingView().connectorViewForObject((ConnectorGraphicalRepresentation<?>) focusedObject).getLabelView()
.startEdition();
e.consume();
return;
}
}
if (focusedObject != null) {
ControlArea<?> ca = getFocusRetriever().getFocusedControlAreaForDrawable(focusedObject, e);
if (ca != null && ca.isClickable()) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("Click on control area " + ca);
}
Point clickedLocationInDrawingView = SwingUtilities.convertPoint((Component) e.getSource(), e.getPoint(),
view.getDrawingView());
FGEPoint clickedPoint = ca.getGraphicalRepresentation().convertRemoteViewCoordinatesToLocalNormalizedPoint(
clickedLocationInDrawingView, view.getDrawingView().getGraphicalRepresentation(),
view.getDrawingView().getScale());
if (ca.clickOnPoint(clickedPoint, e.getClickCount())) {
// Event was successfully handled
e.consume();
return;
}
}
}
}
if (focusedObject == null) {
focusedObject = graphicalRepresentation.getDrawing().getDrawingGraphicalRepresentation();
}
if (view.isDeleted()) {
return;
}
// We have now performed all low-level possible actions, let's go for the registered mouse controls
for (MouseClickControl mouseClickControl : focusedObject.getMouseClickControls()) {
if ((editable || !mouseClickControl.isModelEditionAction())
&& mouseClickControl.isApplicable(focusedObject, getController(), e)) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("Applying " + mouseClickControl);
}
mouseClickControl.handleClick(focusedObject, getController(), e);
} else {
if (logger.isLoggable(Level.FINE)) {
logger.fine("Ignoring " + mouseClickControl);
}
}
}
break;
case DrawShapeTool:
if (editable) {
getController().getDrawShapeToolController().mouseClicked(e);
}
default:
break;
}
}
|
diff --git a/src/test/java/no/niths/infrastructure/StudentRepositoryTest.java b/src/test/java/no/niths/infrastructure/StudentRepositoryTest.java
index de0db4b0..fdc19671 100644
--- a/src/test/java/no/niths/infrastructure/StudentRepositoryTest.java
+++ b/src/test/java/no/niths/infrastructure/StudentRepositoryTest.java
@@ -1,196 +1,197 @@
package no.niths.infrastructure;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import no.niths.common.config.HibernateConfig;
import no.niths.common.config.TestAppConfig;
import no.niths.domain.Committee;
import no.niths.domain.Course;
import no.niths.domain.StudentOrientationGroup;
import no.niths.domain.Student;
import no.niths.infrastructure.interfaces.CommitteeRepositorty;
import no.niths.infrastructure.interfaces.CourseRepository;
import no.niths.infrastructure.interfaces.StudentRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { TestAppConfig.class, HibernateConfig.class })
@Transactional
@TransactionConfiguration(transactionManager = "transactionManager")
public class StudentRepositoryTest {
private static final Logger logger = LoggerFactory
.getLogger(StudentRepositoryTest.class); // Replace with test class
@Autowired
private StudentRepository studentRepo;
@Autowired
private CourseRepository courseRepo;
@Autowired
private CommitteeRepositorty comRepo;
/**
* Testing of basic CRUD functions
*/
@Test
public void testCRUD() {
int size = studentRepo.getAll(null).size();
Student stud = new Student("John", "Doe");
studentRepo.create(stud);
assertEquals(stud, studentRepo.getById(stud.getId()));
assertEquals(size + 1, studentRepo.getAll(null).size());
stud.setFirstName("Jane");
studentRepo.update(stud);
assertEquals("Jane", studentRepo.getById(stud.getId()).getFirstName());
studentRepo.delete(stud.getId());
// assertEquals(null, studentRepo.getById(stud.getId()));
assertEquals(size, studentRepo.getAll(null).size());
}
/**
* Tests the course association
*/
@Test
public void testStudentWithCourses() {
int cSize = courseRepo.getAll(null).size();
int sSize = studentRepo.getAll(null).size();
+ int comSize = comRepo.getAll(null).size();
Course c1 = new Course("PROG", "casd1");
Course c2 = new Course("DESIGN", "cdda2");
courseRepo.create(c1);
courseRepo.create(c2);
// Courses should be persisted
assertEquals(cSize + 2, courseRepo.getAll(null).size());
Student stud = new Student("John", "Doe");
stud.getCourses().add(c1);
stud.getCourses().add(c2);
studentRepo.create(stud);
assertEquals(stud, studentRepo.getById(stud.getId()));
// Test if student has courses
assertEquals(2, studentRepo.getById(stud.getId()).getCourses().size());
studentRepo.getById(stud.getId()).getCourses().remove(1);
assertEquals(1, studentRepo.getById(stud.getId()).getCourses().size());
assertEquals(cSize + 2, courseRepo.getAll(null).size());
Committee c = new Committee("Utvalg", "desc");
comRepo.create(c);
- assertEquals(cSize + 1, comRepo.getAll(null).size());
+ assertEquals(comSize + 1, comRepo.getAll(null).size());
stud = studentRepo.getById(stud.getId());
stud.getCommittees().add(c);
studentRepo.update(stud);
assertEquals(1, studentRepo.getById(stud.getId()).getCommittees()
.size());
}
@Test
public void testGetAllStudentsWithParameter_shouldReturnListOfStudentsMatching() {
int size = studentRepo.getAll(null).size();
createStudentHelper();
assertEquals(size + 4, studentRepo.getAll(null).size());
Student toFind = new Student("John", "Doe");
assertEquals(2, studentRepo.getAll(toFind).size());
toFind = new Student("Jane", "Doe");
assertEquals(1, studentRepo.getAll(toFind).size());
toFind = new Student("XXX", "Doe");
assertEquals(0, studentRepo.getAll(toFind).size());
}
@Test
public void testGetStudentsWithNamedCourse(){
int size = studentRepo.getAll(null).size();
List<Student> students =createStudentHelper();
assertEquals(size + 4, studentRepo.getAll(null).size());
String name ="prog";
Course c = new Course(name, "ProgProg");
courseRepo.create(c);
ArrayList<Course> cs = new ArrayList<Course>();
cs.add(c);
for (int i = 0; i < students.size()-1; i++) {
students.get(i).setCourses(cs);
studentRepo.update(students.get(i));
}
students.clear();
students = studentRepo.getStudentsWithNamedCourse(name);
assertEquals(3, students.size());
}
@Test
public void testGetAllStudentMentors(){
List<Student> studs = createStudentHelper();
studs.get(0).getOrientationGroup().add(new StudentOrientationGroup(1));
studs.get(0).getOrientationGroup().add(new StudentOrientationGroup(2));
studs.get(0).getOrientationGroup().add(new StudentOrientationGroup(3));
studs.get(1).getOrientationGroup().add(new StudentOrientationGroup(2));
studentRepo.update(studs.get(0));
studentRepo.update(studs.get(1));
List<Student> students = studentRepo.getAllMentors();
assertEquals(2, students.size());
assertEquals(3,students.get(0).getOrientationGroup().size());
System.out.println(students.get(0).getFirstName());
students = studentRepo.getMentorsByGroupe(2);
assertEquals(2, students.size());
}
private ArrayList<Student>createStudentHelper(){
ArrayList<Student> students = new ArrayList<Student>();
String [] firstName = {"John","John","Jane","Foo"};
String [] lastName = {"Doe","Doe","Doe","Bar"};
for (int i = 0; i < lastName.length; i++) {
Student s1 = new Student(firstName[i],lastName[i]);
studentRepo.create(s1);
students.add(s1);
}
return students;
}
}
| false | true | public void testStudentWithCourses() {
int cSize = courseRepo.getAll(null).size();
int sSize = studentRepo.getAll(null).size();
Course c1 = new Course("PROG", "casd1");
Course c2 = new Course("DESIGN", "cdda2");
courseRepo.create(c1);
courseRepo.create(c2);
// Courses should be persisted
assertEquals(cSize + 2, courseRepo.getAll(null).size());
Student stud = new Student("John", "Doe");
stud.getCourses().add(c1);
stud.getCourses().add(c2);
studentRepo.create(stud);
assertEquals(stud, studentRepo.getById(stud.getId()));
// Test if student has courses
assertEquals(2, studentRepo.getById(stud.getId()).getCourses().size());
studentRepo.getById(stud.getId()).getCourses().remove(1);
assertEquals(1, studentRepo.getById(stud.getId()).getCourses().size());
assertEquals(cSize + 2, courseRepo.getAll(null).size());
Committee c = new Committee("Utvalg", "desc");
comRepo.create(c);
assertEquals(cSize + 1, comRepo.getAll(null).size());
stud = studentRepo.getById(stud.getId());
stud.getCommittees().add(c);
studentRepo.update(stud);
assertEquals(1, studentRepo.getById(stud.getId()).getCommittees()
.size());
}
| public void testStudentWithCourses() {
int cSize = courseRepo.getAll(null).size();
int sSize = studentRepo.getAll(null).size();
int comSize = comRepo.getAll(null).size();
Course c1 = new Course("PROG", "casd1");
Course c2 = new Course("DESIGN", "cdda2");
courseRepo.create(c1);
courseRepo.create(c2);
// Courses should be persisted
assertEquals(cSize + 2, courseRepo.getAll(null).size());
Student stud = new Student("John", "Doe");
stud.getCourses().add(c1);
stud.getCourses().add(c2);
studentRepo.create(stud);
assertEquals(stud, studentRepo.getById(stud.getId()));
// Test if student has courses
assertEquals(2, studentRepo.getById(stud.getId()).getCourses().size());
studentRepo.getById(stud.getId()).getCourses().remove(1);
assertEquals(1, studentRepo.getById(stud.getId()).getCourses().size());
assertEquals(cSize + 2, courseRepo.getAll(null).size());
Committee c = new Committee("Utvalg", "desc");
comRepo.create(c);
assertEquals(comSize + 1, comRepo.getAll(null).size());
stud = studentRepo.getById(stud.getId());
stud.getCommittees().add(c);
studentRepo.update(stud);
assertEquals(1, studentRepo.getById(stud.getId()).getCommittees()
.size());
}
|
diff --git a/src/Graph.java b/src/Graph.java
index 6c52df2..1442e6f 100644
--- a/src/Graph.java
+++ b/src/Graph.java
@@ -1,396 +1,401 @@
/*
* LICENSE to be determined
*/
package srma;
import net.sf.picard.reference.ReferenceSequence;
import net.sf.samtools.*;
import java.util.*;
import java.io.*;
import srma.Node;
public class Graph {
int contig; // one based
int position_start; // one based
int position_end; // one based
List<PriorityQueue<Node>> nodes; // zero based
List<Integer> coverage; // does not count insertions with offset > 0
SAMFileHeader header;
NodeComparator nodeComparator;
private boolean isEmpty;
public Graph(SAMFileHeader header)
{
this.header = header;
this.contig = 1;
this.position_start = 1;
this.position_end = 1;
this.nodes = new ArrayList<PriorityQueue<Node>>();
this.coverage = new ArrayList<Integer>();
this.nodeComparator = new NodeComparator();
// Add two initial dummy elements
this.nodes.add(new PriorityQueue<Node>(1, this.nodeComparator));
this.coverage.add(new Integer(0));
this.isEmpty = true;
}
// Returns start/end node in the alignment graph with respect to strand
public Node addSAMRecord(SAMRecord record, ReferenceSequence sequence) throws Exception
{
Alignment alignment;
PriorityQueue<Node> nodeQueue = null;
int i, ref_i, offset, node_type, alignment_start, alignment_reference_index;
Node prev=null, cur=null, ret=null;
boolean strand = false;
alignment_start = record.getAlignmentStart();
alignment_reference_index = record.getReferenceIndex();
if(alignment_reference_index != sequence.getContigIndex()) {
throw new Exception("SAMRecord contig does not match the current reference sequence contig");
}
// Get the alignment
alignment = new Alignment(record, sequence);
strand = record.getReadNegativeStrandFlag();
synchronized (this) {
+ //System.err.println("HERE " + alignment_start + " " + this.position_start + ":" + this.position_end);
if(alignment_start < this.position_start) {
- // possible race condition otherwise.
- throw new Exception("Unsynchronized addition");
+ for(i=alignment_start;i<this.position_start;i++) {
+ this.nodes.add(0, new PriorityQueue<Node>(1, this.nodeComparator));
+ this.coverage.add(0, new Integer(0));
+ }
+ this.position_start = alignment_start;
}
// Reset if there are no nodes
if(this.isEmpty) {
this.position_start = alignment_start;
if(Alignment.GAP == alignment.reference[0]) { // insertion
this.position_start--;
}
// TODO: could be insertions then deletions at the start, which will cause errors, not implemented yet
this.position_end = this.position_start;
this.contig = alignment_reference_index + 1;
this.nodes.clear();
this.coverage.clear();
this.nodes.add(new PriorityQueue<Node>(1, this.nodeComparator));
this.coverage.add(new Integer(0));
+ this.isEmpty = false;
}
}
/* Reminders:
i - index from 0 to 'alignment.length'
ref_i - index within 'alignment.reference'
*/
for(i=0,ref_i=-1;i<alignment.length;i++,prev=cur)
{ // go through the alignment
// Skip over a deletion
while(Alignment.GAP == alignment.read[i]) {
i++;
ref_i++;
}
// Get the node type
if(alignment.read[i] == alignment.reference[i]) { // match
node_type = Node.MATCH;
}
else if(alignment.reference[i] == Alignment.GAP) { // insertion
node_type = Node.INSERTION;
}
else { // mismatch
node_type = Node.MISMATCH;
}
if(null == prev || Node.INSERTION != prev.type) { // previous was an insertion, already on the position
ref_i++;
}
// Create the node
cur = this.addNode(new Node((char)alignment.read[i],
node_type,
alignment_reference_index + 1,
alignment_start + ref_i,
prev,
this.nodeComparator),
prev);
// save return node
if(null == prev && !strand) { // first node and forward strand
ret = cur;
}
}
if(strand) { // negative strand
ret = cur;
}
return ret;
}
/*
* Adds the node to the graph. Merges if the graph already
* contains a similar node.
* */
private synchronized Node addNode(Node node, Node prev)
throws Exception
{
Node curNode = null;
int i;
// Check if such a node exists
// - if such a node exists, return it
// - else insert it
curNode = this.contains(node);
if(null == curNode) { // new node, "how exciting!"
if(node.contig != this.contig) { // same contig
throw new Exception("NOT IMPLEMENTED");
}
// Add new queues if necessary
for(i=this.position_end;i<node.position;i++) {
this.nodes.add(new PriorityQueue<Node>(1, this.nodeComparator));
this.coverage.add(new Integer(0));
}
// Get the proper queue and add
this.nodes.get(node.position - this.position_start).add(node);
// do not include insertions that extend an insertion
if(Node.INSERTION != node.type || 0 != node.offset) {
this.coverage.set(node.position - this.position_start, node.coverage + this.coverage.get(node.position - this.position_start)); // set coverage
}
if(this.position_end < node.position) {
this.position_end = node.position;
}
curNode = node;
this.isEmpty = false;
}
else { // already contains
curNode.coverage++;
// do not include insertions that extend an insertion
if(Node.INSERTION != curNode.type || 0 != curNode.offset) {
// increment coverage
this.coverage.set(curNode.position - this.position_start, 1 + this.coverage.get(curNode.position - this.position_start));
}
}
// Update edges
if(null != prev) {
curNode.addToPrev(prev, this.nodeComparator);
prev.addToNext(curNode, this.nodeComparator);
}
return curNode;
}
/*
* Returns the Node in the graph if already exists,
* null otherwise
* */
private Node contains(Node node)
throws Exception
{
PriorityQueue<Node> nodeQueue = null;
Iterator<Node> nodeQueueIter = null;
Node curNode = null;
// See if there are any nodes at this position
if(node.position - this.position_start < 0 || this.nodes.size() <= node.position - this.position_start) {
return null;
}
nodeQueue = this.nodes.get(node.position - this.position_start);
// Go through all nodes at this position etc.
nodeQueueIter = nodeQueue.iterator();
while(nodeQueueIter.hasNext()) {
curNode = nodeQueueIter.next();
if(this.nodeComparator.equals(curNode, node)) {
return curNode;
}
}
return null;
}
public int getPriorityQueueIndexAtPosition(int position)
{
PriorityQueue<Node> nodeQueue = null;
if(position < this.position_start || this.position_end < position) {
return 0;
}
nodeQueue = this.nodes.get(position - this.position_start);
if(0 < nodeQueue.size()) {
return position;
}
return 0;
}
public int getPriorityQueueIndexAtPositionOrGreater(int position)
throws Exception
{
PriorityQueue<Node> nodeQueue = null;
if(position < this.position_start) {
position = this.position_start;
}
while(position <= this.position_end) {
nodeQueue = this.nodes.get(position - this.position_start);
if(0 < nodeQueue.size()) {
return position;
}
position++;
}
return 0;
}
public int getPriorityQueueIndexAtPositionOrBefore(int position)
throws Exception
{
PriorityQueue<Node> nodeQueue = null;
if(this.position_end < position) {
position = this.position_end;
}
while(this.position_start <= position) {
nodeQueue = this.nodes.get(position - this.position_start);
if(0 < nodeQueue.size()) {
return position;
}
position--;
}
return 0;
}
public PriorityQueue<Node> getPriorityQueue(int position)
{
try {
return this.nodes.get(position - this.position_start);
} catch (IndexOutOfBoundsException e) {
return null;
}
}
public int getCoverage(int position)
{
try {
return this.coverage.get(position - this.position_start);
} catch (IndexOutOfBoundsException e) {
return 0;
}
}
public synchronized void prune(int referenceIndex, int alignmentStart, int offset)
throws Exception
{
boolean shouldClear = false;
if(this.contig != referenceIndex+1) {
shouldClear = true;
}
else {
if(this.position_start < alignmentStart - offset) { // unreachable nodes at the start
if(this.position_end < alignmentStart - offset) { // all are unreachable
shouldClear = true;
}
else {
this.nodes = this.nodes.subList(alignmentStart - offset - this.position_start, this.nodes.size());
this.coverage = this.coverage.subList(alignmentStart - offset - this.position_start, this.coverage.size());
this.position_start = alignmentStart - offset;
}
}
}
if(shouldClear) {
this.nodes.clear();
this.coverage.clear();
this.contig = referenceIndex + 1;
this.position_start = this.position_end = alignmentStart;
this.nodes.add(new PriorityQueue<Node>(1, this.nodeComparator));
this.coverage.add(new Integer(0));
this.isEmpty = true;
}
}
public void print()
throws Exception
{
this.print(System.out);
}
public void print(PrintStream out)
throws Exception
{
int i;
PriorityQueue<Node> queue;
Iterator<Node> iter;
out.println((1+contig)+":"+position_start+"-"+position_end);
for(i=0;i<this.nodes.size();i++) {
queue = this.nodes.get(i);
iter = queue.iterator();
while(iter.hasNext()) {
iter.next().print(out);
}
}
}
// Debugging function
public void check()
throws Exception
{
if(0 < this.nodes.size()) {
int i;
for(i=this.position_start;i<=this.position_end;i++) {
PriorityQueue<Node> q = this.nodes.get(i - this.position_start);
Iterator<Node> iter = q.iterator();
while(iter.hasNext()) {
Node n = iter.next();
if(i != n.position) {
System.err.println("i="+i+"\tn.position="+n.position);
throw new Exception("Inconsistent graph");
}
}
}
}
}
// Debugging function
public void printDebug()
throws Exception
{
int i;
System.err.println(this.contig + ":" + this.position_start + "-" + this.position_end + " " + this.nodes.size() + " " + this.coverage.size());
for(i=0;i<this.coverage.size();i++) {
Node prev = null;
PriorityQueue<Node> q1 = this.nodes.get(i);
// copy queue
PriorityQueue<Node> q2 = new PriorityQueue<Node>(1, new NodeComparator());
Iterator<Node> iter = q1.iterator();
while(iter.hasNext()) {
q2.add(iter.next());
}
System.err.println((i+1)+" "+this.coverage.get(i)+" ");
while(0 != q2.size()) {
Node n = q2.poll();
n.print(System.err);
n.checkList(n.prev.listIterator(), this.nodeComparator);
n.checkList(n.next.listIterator(), this.nodeComparator);
if(null != prev) {
int c = this.nodeComparator.compare(prev, n);
if(0 < c) {
throw new Exception("OUT OF ORDER");
}
//System.err.println("comparison="+c);
}
prev = n;
}
}
}
}
| false | true | public Node addSAMRecord(SAMRecord record, ReferenceSequence sequence) throws Exception
{
Alignment alignment;
PriorityQueue<Node> nodeQueue = null;
int i, ref_i, offset, node_type, alignment_start, alignment_reference_index;
Node prev=null, cur=null, ret=null;
boolean strand = false;
alignment_start = record.getAlignmentStart();
alignment_reference_index = record.getReferenceIndex();
if(alignment_reference_index != sequence.getContigIndex()) {
throw new Exception("SAMRecord contig does not match the current reference sequence contig");
}
// Get the alignment
alignment = new Alignment(record, sequence);
strand = record.getReadNegativeStrandFlag();
synchronized (this) {
if(alignment_start < this.position_start) {
// possible race condition otherwise.
throw new Exception("Unsynchronized addition");
}
// Reset if there are no nodes
if(this.isEmpty) {
this.position_start = alignment_start;
if(Alignment.GAP == alignment.reference[0]) { // insertion
this.position_start--;
}
// TODO: could be insertions then deletions at the start, which will cause errors, not implemented yet
this.position_end = this.position_start;
this.contig = alignment_reference_index + 1;
this.nodes.clear();
this.coverage.clear();
this.nodes.add(new PriorityQueue<Node>(1, this.nodeComparator));
this.coverage.add(new Integer(0));
}
}
/* Reminders:
i - index from 0 to 'alignment.length'
ref_i - index within 'alignment.reference'
*/
for(i=0,ref_i=-1;i<alignment.length;i++,prev=cur)
{ // go through the alignment
// Skip over a deletion
while(Alignment.GAP == alignment.read[i]) {
i++;
ref_i++;
}
// Get the node type
if(alignment.read[i] == alignment.reference[i]) { // match
node_type = Node.MATCH;
}
else if(alignment.reference[i] == Alignment.GAP) { // insertion
node_type = Node.INSERTION;
}
else { // mismatch
node_type = Node.MISMATCH;
}
if(null == prev || Node.INSERTION != prev.type) { // previous was an insertion, already on the position
ref_i++;
}
// Create the node
cur = this.addNode(new Node((char)alignment.read[i],
node_type,
alignment_reference_index + 1,
alignment_start + ref_i,
prev,
this.nodeComparator),
prev);
// save return node
if(null == prev && !strand) { // first node and forward strand
ret = cur;
}
}
if(strand) { // negative strand
ret = cur;
}
return ret;
}
| public Node addSAMRecord(SAMRecord record, ReferenceSequence sequence) throws Exception
{
Alignment alignment;
PriorityQueue<Node> nodeQueue = null;
int i, ref_i, offset, node_type, alignment_start, alignment_reference_index;
Node prev=null, cur=null, ret=null;
boolean strand = false;
alignment_start = record.getAlignmentStart();
alignment_reference_index = record.getReferenceIndex();
if(alignment_reference_index != sequence.getContigIndex()) {
throw new Exception("SAMRecord contig does not match the current reference sequence contig");
}
// Get the alignment
alignment = new Alignment(record, sequence);
strand = record.getReadNegativeStrandFlag();
synchronized (this) {
//System.err.println("HERE " + alignment_start + " " + this.position_start + ":" + this.position_end);
if(alignment_start < this.position_start) {
for(i=alignment_start;i<this.position_start;i++) {
this.nodes.add(0, new PriorityQueue<Node>(1, this.nodeComparator));
this.coverage.add(0, new Integer(0));
}
this.position_start = alignment_start;
}
// Reset if there are no nodes
if(this.isEmpty) {
this.position_start = alignment_start;
if(Alignment.GAP == alignment.reference[0]) { // insertion
this.position_start--;
}
// TODO: could be insertions then deletions at the start, which will cause errors, not implemented yet
this.position_end = this.position_start;
this.contig = alignment_reference_index + 1;
this.nodes.clear();
this.coverage.clear();
this.nodes.add(new PriorityQueue<Node>(1, this.nodeComparator));
this.coverage.add(new Integer(0));
this.isEmpty = false;
}
}
/* Reminders:
i - index from 0 to 'alignment.length'
ref_i - index within 'alignment.reference'
*/
for(i=0,ref_i=-1;i<alignment.length;i++,prev=cur)
{ // go through the alignment
// Skip over a deletion
while(Alignment.GAP == alignment.read[i]) {
i++;
ref_i++;
}
// Get the node type
if(alignment.read[i] == alignment.reference[i]) { // match
node_type = Node.MATCH;
}
else if(alignment.reference[i] == Alignment.GAP) { // insertion
node_type = Node.INSERTION;
}
else { // mismatch
node_type = Node.MISMATCH;
}
if(null == prev || Node.INSERTION != prev.type) { // previous was an insertion, already on the position
ref_i++;
}
// Create the node
cur = this.addNode(new Node((char)alignment.read[i],
node_type,
alignment_reference_index + 1,
alignment_start + ref_i,
prev,
this.nodeComparator),
prev);
// save return node
if(null == prev && !strand) { // first node and forward strand
ret = cur;
}
}
if(strand) { // negative strand
ret = cur;
}
return ret;
}
|
diff --git a/src/main/java/org/mael/chan4j/FourChanPage.java b/src/main/java/org/mael/chan4j/FourChanPage.java
index 98eeba9..7b5e2ab 100644
--- a/src/main/java/org/mael/chan4j/FourChanPage.java
+++ b/src/main/java/org/mael/chan4j/FourChanPage.java
@@ -1,94 +1,94 @@
package org.mael.chan4j;
import java.io.IOException;
import java.util.List;
import org.mael.chan4j.utils.HttpUtils;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class FourChanPage {
private int pageNumber;
private FourChanBoard board;
@Expose
@SerializedName("threads")
private List<FourChanPreviewThread> threads;
public FourChanPage(FourChanBoard fourChanBoard, int pageNumber) {
this.board = fourChanBoard;
this.pageNumber = pageNumber;
}
public int getPageNumber() {
return pageNumber;
}
public void setPageNumber(int pageNumber) {
this.pageNumber = pageNumber;
}
public FourChanBoard getBoard() {
return board;
}
public void setBoard(FourChanBoard board) {
this.board = board;
}
public List<FourChanPreviewThread> allThreads() {
return this.allThreads(false);
}
public List<FourChanPreviewThread> allThreads(boolean useHttps) {
String json = null;
try {
- json = HttpUtils.getContentFromUrl(buildPageUrl(false));
+ json = HttpUtils.getContentFromUrl(buildPageUrl(useHttps));
} catch (IOException e) {
throw new FourChanException("Cannot get JSON request", e);
}
FourChanPage page = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation().create()
.fromJson(json, FourChanPage.class);
for (FourChanPreviewThread thread : page.getThreads()) {
thread.setPage(this);
}
return page.getThreads();
}
public String buildPageUrl(boolean useHttps) {
String protocol = "http";
if (useHttps) {
protocol = "https";
}
return protocol + "://api.4chan.org/" + this.board.getName() + "/"
+ pageNumber + ".json";
}
public List<FourChanPreviewThread> getThreads() {
return threads;
}
public void setThreads(List<FourChanPreviewThread> threads) {
this.threads = threads;
}
}
| true | true | public List<FourChanPreviewThread> allThreads(boolean useHttps) {
String json = null;
try {
json = HttpUtils.getContentFromUrl(buildPageUrl(false));
} catch (IOException e) {
throw new FourChanException("Cannot get JSON request", e);
}
FourChanPage page = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation().create()
.fromJson(json, FourChanPage.class);
for (FourChanPreviewThread thread : page.getThreads()) {
thread.setPage(this);
}
return page.getThreads();
}
| public List<FourChanPreviewThread> allThreads(boolean useHttps) {
String json = null;
try {
json = HttpUtils.getContentFromUrl(buildPageUrl(useHttps));
} catch (IOException e) {
throw new FourChanException("Cannot get JSON request", e);
}
FourChanPage page = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation().create()
.fromJson(json, FourChanPage.class);
for (FourChanPreviewThread thread : page.getThreads()) {
thread.setPage(this);
}
return page.getThreads();
}
|
diff --git a/ui/isometric/mock/IsoTestDataSource.java b/ui/isometric/mock/IsoTestDataSource.java
index 3cc6625..03ec962 100644
--- a/ui/isometric/mock/IsoTestDataSource.java
+++ b/ui/isometric/mock/IsoTestDataSource.java
@@ -1,114 +1,114 @@
package ui.isometric.mock;
import java.awt.Point;
import ui.isometric.IsoDataSource;
import ui.isometric.IsoImage;
import ui.isometric.IsoSquare;
import ui.isometric.IsoTransform;
import util.Area;
import util.Direction;
import util.Position;
/**
*
* A test implementation of IsoDataSource so that IsoCanvas can be tested
*
* @author melby
*
*/
public class IsoTestDataSource implements IsoDataSource {
private IsoImage floor = new IsoImage("/resources/isotiles/test/floor.png", null);
private IsoImage floorpool = new IsoImage("/resources/isotiles/test/floorpool.png", null);
private IsoImage floorpost = new IsoImage("/resources/isotiles/test/floorpost.png", null);
private IsoImage floorstone = new IsoImage("/resources/isotiles/test/floorstone.png", null);
private IsoImage floortree = new IsoImage("/resources/isotiles/test/floortree.png", null);
private IsoImage wally = new IsoImage("/resources/isotiles/test/wally.png", null);
private IsoImage wallx = new IsoImage("/resources/isotiles/test/wallx.png", null);
private IsoImage wallcross = new IsoImage("/resources/isotiles/test/wallcross.png", null);
/**
* Dummy transform class that doesn't do anything
* @author melby
*
*/
private class IsoTransformDummy implements IsoTransform {
@Override
public Area querryArea() {
return new Area(0, 0, 100, 100);
}
@Override
public Position transformMapPosition(Position pos) {
return pos;
}
@Override
public Point transformRelitivePoint(Point p) {
return p;
}
@Override
public Point smoothOrigin(Point origin) {
return new Point(0, 0);
}
}
@Override
public IsoSquare squareAt(int x, int y) {
IsoSquare s = new IsoSquare();
if(x % 6 == 0 && y % 6 == 0) {
s.addImageForLevel(floor, IsoSquare.FLOOR);
s.addImageForLevel(wallcross, IsoSquare.WALL);
}
else if(x % 6 == 0) {
s.addImageForLevel(floor, IsoSquare.FLOOR);
- s.addImageForLevel(wallx, IsoSquare.WALL);
+ s.addImageForLevel(wally, IsoSquare.WALL);
}
else if(y % 6 == 0) {
s.addImageForLevel(floor, IsoSquare.FLOOR);
- s.addImageForLevel(wally, IsoSquare.WALL);
+ s.addImageForLevel(wallx, IsoSquare.WALL);
}
else {
int n = (int) (Math.random() * 5);
switch(n) {
case 0:
s.addImageForLevel(floor, IsoSquare.FLOOR);
s.addImageForLevel(floortree, IsoSquare.FLOOR);
break;
case 1:
s.addImageForLevel(floor, IsoSquare.FLOOR);
break;
case 2:
s.addImageForLevel(floorpool, IsoSquare.FLOOR);
break;
case 3:
s.addImageForLevel(floor, IsoSquare.FLOOR);
s.addImageForLevel(floorpost, IsoSquare.FLOOR);
break;
case 4:
s.addImageForLevel(floorstone, IsoSquare.FLOOR);
break;
}
}
return s;
}
@Override
public void setViewableRect(int x, int y, int w, int h, Direction viewDirection) {
// Don't need this info atm
}
@Override
public void update() {
// Don't need to do anything
}
@Override
public IsoTransform transform() {
return new IsoTransformDummy();
}
}
| false | true | public IsoSquare squareAt(int x, int y) {
IsoSquare s = new IsoSquare();
if(x % 6 == 0 && y % 6 == 0) {
s.addImageForLevel(floor, IsoSquare.FLOOR);
s.addImageForLevel(wallcross, IsoSquare.WALL);
}
else if(x % 6 == 0) {
s.addImageForLevel(floor, IsoSquare.FLOOR);
s.addImageForLevel(wallx, IsoSquare.WALL);
}
else if(y % 6 == 0) {
s.addImageForLevel(floor, IsoSquare.FLOOR);
s.addImageForLevel(wally, IsoSquare.WALL);
}
else {
int n = (int) (Math.random() * 5);
switch(n) {
case 0:
s.addImageForLevel(floor, IsoSquare.FLOOR);
s.addImageForLevel(floortree, IsoSquare.FLOOR);
break;
case 1:
s.addImageForLevel(floor, IsoSquare.FLOOR);
break;
case 2:
s.addImageForLevel(floorpool, IsoSquare.FLOOR);
break;
case 3:
s.addImageForLevel(floor, IsoSquare.FLOOR);
s.addImageForLevel(floorpost, IsoSquare.FLOOR);
break;
case 4:
s.addImageForLevel(floorstone, IsoSquare.FLOOR);
break;
}
}
return s;
}
| public IsoSquare squareAt(int x, int y) {
IsoSquare s = new IsoSquare();
if(x % 6 == 0 && y % 6 == 0) {
s.addImageForLevel(floor, IsoSquare.FLOOR);
s.addImageForLevel(wallcross, IsoSquare.WALL);
}
else if(x % 6 == 0) {
s.addImageForLevel(floor, IsoSquare.FLOOR);
s.addImageForLevel(wally, IsoSquare.WALL);
}
else if(y % 6 == 0) {
s.addImageForLevel(floor, IsoSquare.FLOOR);
s.addImageForLevel(wallx, IsoSquare.WALL);
}
else {
int n = (int) (Math.random() * 5);
switch(n) {
case 0:
s.addImageForLevel(floor, IsoSquare.FLOOR);
s.addImageForLevel(floortree, IsoSquare.FLOOR);
break;
case 1:
s.addImageForLevel(floor, IsoSquare.FLOOR);
break;
case 2:
s.addImageForLevel(floorpool, IsoSquare.FLOOR);
break;
case 3:
s.addImageForLevel(floor, IsoSquare.FLOOR);
s.addImageForLevel(floorpost, IsoSquare.FLOOR);
break;
case 4:
s.addImageForLevel(floorstone, IsoSquare.FLOOR);
break;
}
}
return s;
}
|
diff --git a/cinta/src/main/java/common/ci/cinta/autotests/CommonUtilsTest.java b/cinta/src/main/java/common/ci/cinta/autotests/CommonUtilsTest.java
index 4c0bec9..42b0734 100644
--- a/cinta/src/main/java/common/ci/cinta/autotests/CommonUtilsTest.java
+++ b/cinta/src/main/java/common/ci/cinta/autotests/CommonUtilsTest.java
@@ -1,46 +1,46 @@
package common.ci.cinta.autotests;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.assertNull;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import common.ci.cinta.utils.CommonUtils;
public class CommonUtilsTest {
@SuppressWarnings("unused")
@DataProvider(name = "digitCandidates")
private Object[][] dpCandidates() {
return new Object[][] {
{"123fdfdfd", "123"},
{"1fdfdfd", "1"},
{"fdfdfd1", ""},
{"f1dfdfd1", ""},
{"232223232323fdfdfd1", "232223232323"},
{"555f555f555", "555"},
- {"f555f555", "555"},
+// {"f555f555", "555"},
};
}
@Test(dataProvider = "digitCandidates")
public void getLeadingDigitsTest(String candidate, String expectedDigit) {
String input = String.format("input: %-30s expectedDigit: %-30s", candidate, expectedDigit);
String result = CommonUtils.getLeadingDigits(candidate);
System.out.println(String.format("%-60s result: %-15s", input, result));
assertTrue(result.equals(expectedDigit));
}
@Test
public void checkForNullTest() {
String input = String.format("input: %-30s expectedDigit: %-30s", null, null);
String result = CommonUtils.getLeadingDigits(null);
System.out.println(String.format("%-60s result: %-15s", input, result));
assertNull(result);
}
}
| true | true | private Object[][] dpCandidates() {
return new Object[][] {
{"123fdfdfd", "123"},
{"1fdfdfd", "1"},
{"fdfdfd1", ""},
{"f1dfdfd1", ""},
{"232223232323fdfdfd1", "232223232323"},
{"555f555f555", "555"},
{"f555f555", "555"},
};
}
| private Object[][] dpCandidates() {
return new Object[][] {
{"123fdfdfd", "123"},
{"1fdfdfd", "1"},
{"fdfdfd1", ""},
{"f1dfdfd1", ""},
{"232223232323fdfdfd1", "232223232323"},
{"555f555f555", "555"},
// {"f555f555", "555"},
};
}
|
diff --git a/alitheia/core/src/eu/sqooss/impl/service/webadmin/AdminServlet.java b/alitheia/core/src/eu/sqooss/impl/service/webadmin/AdminServlet.java
index ecdb0358..70a3e876 100644
--- a/alitheia/core/src/eu/sqooss/impl/service/webadmin/AdminServlet.java
+++ b/alitheia/core/src/eu/sqooss/impl/service/webadmin/AdminServlet.java
@@ -1,293 +1,293 @@
/*
* This file is part of the Alitheia system, developed by the SQO-OSS
* consortium as part of the IST FP6 SQO-OSS project, number 033331.
*
* Copyright 2007-2008 by the SQO-OSS consortium members <[email protected]>
* Copyright 2007-2008 by Adriaan de Groot <[email protected]>
* Copyright 2008 by Paul J. Adams <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package eu.sqooss.impl.service.webadmin;
import eu.sqooss.impl.service.webadmin.WebAdminRenderer;
import eu.sqooss.service.logging.Logger;
import eu.sqooss.service.util.Pair;
import eu.sqooss.service.pa.PluginAdmin;
import eu.sqooss.service.scheduler.Scheduler;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Hashtable;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
public class AdminServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// Content tables
private Hashtable<String, String> dynamicContentMap = null;
private Hashtable<String, Pair<String, String>> staticContentMap = null;
// Dynamic substitutions
VelocityContext vc = null;
VelocityEngine ve = null;
// Renderer of content
WebAdminRenderer render = null;
public AdminServlet(BundleContext bc) {
// Create the static content map
staticContentMap = new Hashtable<String, Pair<String, String>>();
addStaticContent("/screen.css", "text/css");
addStaticContent("/sqo-oss.png", "image/x-png");
addStaticContent("/queue.png", "image/x-png");
addStaticContent("/uptime.png", "image/x-png");
addStaticContent("/greyBack.jpg", "image/x-jpg");
addStaticContent("/projects.png", "image/x-png");
addStaticContent("/logs.png", "image/x-png");
addStaticContent("/metrics.png", "image/x-png");
addStaticContent("/gear.png", "image/x-png");
addStaticContent("/header-repeat.png", "image/x-png");
addStaticContent("/add_user.png", "image/x-png");
// Create the dynamic content map
dynamicContentMap = new Hashtable<String, String>();
dynamicContentMap.put("/", "index.html");
dynamicContentMap.put("/index", "index.html");
dynamicContentMap.put("/projects", "projects.html");
dynamicContentMap.put("/logs", "logs.html");
dynamicContentMap.put("/jobs", "jobs.html");
dynamicContentMap.put("/alljobs", "alljobs.html");
dynamicContentMap.put("/users", "users.html");
// Now the dynamic substitutions and renderer
vc = new VelocityContext();
render = new WebAdminRenderer(bc, vc);
createSubstitutions(true);
try {
ve = new VelocityEngine();
ve.setProperty("runtime.log.logsystem.class",
"org.apache.velocity.runtime.log.SimpleLog4JLogSystem");
ve.setProperty("runtime.log.logsystem.log4j.category",
Logger.NAME_SQOOSS_WEBADMIN);
ve.setProperty("resource.loader","bundle");
ve.setProperty("bundle.resource.loader.description",
"Loader from the bundle.");
ve.setProperty("bundle.resource.loader.class",
"org.apache.velocity.runtime.resource.loader.JarResourceLoader");
ve.setProperty("bundle.resource.loader.path",
"jar:file:eu.sqooss.alitheia.core-0.0.1.jar");
}
catch (Exception e) {
System.out.println(e);
}
}
/**
* Add content to the static map
*/
private void addStaticContent(String path, String type) {
Pair<String, String> p = new Pair<String, String> (path,type);
staticContentMap.put(path, p);
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
try {
String query = request.getPathInfo();
// This is static content
if ((query != null) && (staticContentMap.containsKey(query))) {
sendResource(response, staticContentMap.get(query));
}
else if ((query != null) && (dynamicContentMap.containsKey(query))) {
sendPage(response, dynamicContentMap.get(query));
}
}
catch (Exception e) {
System.out.println(e);
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
try {
String query = request.getPathInfo();
if (query.startsWith("/addproject")) {
render.addProject(request);
//dynamicSubstitutions.put("@@ACTIVE","class=\"section-3\"");
sendPage(response, "/results.html");
} else {
doGet(request,response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sends a resource (stored in the jar file) as a response. The mime-type
* is set to @p mimeType . The @p path to the resource should start
* with a / .
*
* Test cases:
* - null mimetype, null path, bad path, relative path, path not found,
* - null response
*
* TODO: How to simulate conditions that will cause IOException
*/
protected void sendResource(HttpServletResponse response, Pair<String,String> source)
throws ServletException, IOException {
InputStream istream = getClass().getResourceAsStream(source.first);
if ( istream == null ) {
throw new IOException("Path not found: " + source.first);
}
byte[] buffer = new byte[1024];
int bytesRead = 0;
int totalBytes = 0;
response.setContentType(source.second);
ServletOutputStream ostream = response.getOutputStream();
while ((bytesRead = istream.read(buffer)) > 0) {
ostream.write(buffer,0,bytesRead);
totalBytes += bytesRead;
}
}
protected void sendPage(HttpServletResponse response, String path)
throws ServletException, IOException, Exception {
Template t = ve.getTemplate( path );
StringWriter writer = new StringWriter();
PrintWriter print = response.getWriter();
// Do any substitutions that may be required
createSubstitutions(false);
response.setContentType("text/html");
t.merge(vc, writer);
print.print(writer.toString());
}
private void createSubstitutions(boolean initialRun) {
if (initialRun) {
// Simple string substitutions
vc.put("COPYRIGHT", "Copyright 2007-2008 <a href=\"http://www.sqo-oss.eu/about/\">SQO-OSS Consortium Members</a>");
vc.put("LOGO", "<img src='/logo' id='logo' alt='Logo' />");
vc.put("MENU",
"<ul id=\"menu\">" +
"<li id=\"nav-1\"><a href=\"/index\">Metrics</a></li>" +
"<li id=\"nav-3\"><a href=\"/projects\">Projects</a></li>" +
"<li id=\"nav-6\"><a href=\"/users\">Users</a></li>" +
"<li id=\"nav-2\"><a href=\"/logs\">Logs</a></li>" +
"<li id=\"nav-4\"><a href=\"/jobs\">Jobs</a></li>" +
"</ul>");
vc.put("OPTIONS","<fieldset id=\"options\">" +
"<legend>Options</legend>" +
- "<form id=\"motd\" method=\"post\" acrion=\"motd\">" +
+ "<form id=\"motd\" method=\"post\" action=\"motd\">" +
"<p>Message of the day:</p><br/>"+
"<input id=\"motdinput\" type=\"text\" name=\"motdtext\" class=\"form\"/>" +
"<br/><input type=\"submit\" value=\"Set\" id=\"motdbutton\" /></form>" +
"<form id=\"start\" method=\"post\" action=\"restart\">" +
"<p><input type=\"submit\" value=\"Restart\" /></p>" +
"</form>" +
"<form id=\"stop\" method=\"post\" action=\"stop\">" +
"<p><input type=\"submit\" value=\"Stop\" /></p>" +
"</form></fieldset>");
}
// Function-based substitutions
//vc.put("STATUS", someFunction); FIXME
vc.put("GETLOGS", render.renderLogs());
vc.put("PROJECTS", render.renderProjects());
vc.put("UPTIME", render.getUptime());
vc.put("QUEUE_LENGTH", render.getSchedulerDetails("WAITING"));
vc.put("JOB_EXEC", render.getSchedulerDetails("RUNNING"));
vc.put("JOB_WAIT", render.getSchedulerDetails("WAITING"));
vc.put("JOB_WORKTHR", render.getSchedulerDetails("WORKER"));
vc.put("JOB_FAILED", render.getSchedulerDetails("FAILED"));
vc.put("JOB_TOTAL", render.getSchedulerDetails("TOTAL"));
vc.put("WAITJOBS", render.renderWaitJobs());
vc.put("FAILJOBS", render.renderFailedJobs());
vc.put("JOBFAILSTATS", render.renderJobFailStats());
vc.put("METRICS", render.renderMetrics());
vc.put("USERS", render.renderUsers());
// These are composite substitutions
vc.put("STATUS_CORE","<fieldset id=\"status\">" +
"<legend>Status</legend>" +
"<ul>" +
"<li class=\"uptime\">Uptime: " +
vc.get("UPTIME") +
"</li>" +
"<li class=\"queue\">Job Queue Length: " +
vc.get("QUEUE_LENGTH") +
"</li></ul></fieldset>");
vc.put("STATUS_JOBS","<fieldset id=\"jobs\">" +
"<legend>Job Info</legend>" +
"<table width='100%' cellspacing=0 cellpadding=3>" +
"<tr><td>Executing:</td><td class=\"number\">" +
vc.get("JOB_EXEC") +
"</td></tr>" +
"<tr><td>Waiting:</td><td class=\"number\">" +
vc.get("JOB_WAIT") +
"</td></tr>" +
"<tr><td>Failed:</td><td class=\"number\">" +
vc.get("JOB_FAILED") +
"</td></tr>" +
"<tr><td>Total:</td><td class=\"number\">" +
vc.get("JOB_TOTAL") +
"</td></tr>" +
"<tr class=\"newgroup\"><td>Workers:</td><td class=\"number\">" +
vc.get("JOB_WORKTHR") +
"</td></tr></table></fieldset>");
}
}
// vi: ai nosi sw=4 ts=4 expandtab
| true | true | private void createSubstitutions(boolean initialRun) {
if (initialRun) {
// Simple string substitutions
vc.put("COPYRIGHT", "Copyright 2007-2008 <a href=\"http://www.sqo-oss.eu/about/\">SQO-OSS Consortium Members</a>");
vc.put("LOGO", "<img src='/logo' id='logo' alt='Logo' />");
vc.put("MENU",
"<ul id=\"menu\">" +
"<li id=\"nav-1\"><a href=\"/index\">Metrics</a></li>" +
"<li id=\"nav-3\"><a href=\"/projects\">Projects</a></li>" +
"<li id=\"nav-6\"><a href=\"/users\">Users</a></li>" +
"<li id=\"nav-2\"><a href=\"/logs\">Logs</a></li>" +
"<li id=\"nav-4\"><a href=\"/jobs\">Jobs</a></li>" +
"</ul>");
vc.put("OPTIONS","<fieldset id=\"options\">" +
"<legend>Options</legend>" +
"<form id=\"motd\" method=\"post\" acrion=\"motd\">" +
"<p>Message of the day:</p><br/>"+
"<input id=\"motdinput\" type=\"text\" name=\"motdtext\" class=\"form\"/>" +
"<br/><input type=\"submit\" value=\"Set\" id=\"motdbutton\" /></form>" +
"<form id=\"start\" method=\"post\" action=\"restart\">" +
"<p><input type=\"submit\" value=\"Restart\" /></p>" +
"</form>" +
"<form id=\"stop\" method=\"post\" action=\"stop\">" +
"<p><input type=\"submit\" value=\"Stop\" /></p>" +
"</form></fieldset>");
}
// Function-based substitutions
//vc.put("STATUS", someFunction); FIXME
vc.put("GETLOGS", render.renderLogs());
vc.put("PROJECTS", render.renderProjects());
vc.put("UPTIME", render.getUptime());
vc.put("QUEUE_LENGTH", render.getSchedulerDetails("WAITING"));
vc.put("JOB_EXEC", render.getSchedulerDetails("RUNNING"));
vc.put("JOB_WAIT", render.getSchedulerDetails("WAITING"));
vc.put("JOB_WORKTHR", render.getSchedulerDetails("WORKER"));
vc.put("JOB_FAILED", render.getSchedulerDetails("FAILED"));
vc.put("JOB_TOTAL", render.getSchedulerDetails("TOTAL"));
vc.put("WAITJOBS", render.renderWaitJobs());
vc.put("FAILJOBS", render.renderFailedJobs());
vc.put("JOBFAILSTATS", render.renderJobFailStats());
vc.put("METRICS", render.renderMetrics());
vc.put("USERS", render.renderUsers());
// These are composite substitutions
vc.put("STATUS_CORE","<fieldset id=\"status\">" +
"<legend>Status</legend>" +
"<ul>" +
"<li class=\"uptime\">Uptime: " +
vc.get("UPTIME") +
"</li>" +
"<li class=\"queue\">Job Queue Length: " +
vc.get("QUEUE_LENGTH") +
"</li></ul></fieldset>");
vc.put("STATUS_JOBS","<fieldset id=\"jobs\">" +
"<legend>Job Info</legend>" +
"<table width='100%' cellspacing=0 cellpadding=3>" +
"<tr><td>Executing:</td><td class=\"number\">" +
vc.get("JOB_EXEC") +
"</td></tr>" +
"<tr><td>Waiting:</td><td class=\"number\">" +
vc.get("JOB_WAIT") +
"</td></tr>" +
"<tr><td>Failed:</td><td class=\"number\">" +
vc.get("JOB_FAILED") +
"</td></tr>" +
"<tr><td>Total:</td><td class=\"number\">" +
vc.get("JOB_TOTAL") +
"</td></tr>" +
"<tr class=\"newgroup\"><td>Workers:</td><td class=\"number\">" +
vc.get("JOB_WORKTHR") +
"</td></tr></table></fieldset>");
}
| private void createSubstitutions(boolean initialRun) {
if (initialRun) {
// Simple string substitutions
vc.put("COPYRIGHT", "Copyright 2007-2008 <a href=\"http://www.sqo-oss.eu/about/\">SQO-OSS Consortium Members</a>");
vc.put("LOGO", "<img src='/logo' id='logo' alt='Logo' />");
vc.put("MENU",
"<ul id=\"menu\">" +
"<li id=\"nav-1\"><a href=\"/index\">Metrics</a></li>" +
"<li id=\"nav-3\"><a href=\"/projects\">Projects</a></li>" +
"<li id=\"nav-6\"><a href=\"/users\">Users</a></li>" +
"<li id=\"nav-2\"><a href=\"/logs\">Logs</a></li>" +
"<li id=\"nav-4\"><a href=\"/jobs\">Jobs</a></li>" +
"</ul>");
vc.put("OPTIONS","<fieldset id=\"options\">" +
"<legend>Options</legend>" +
"<form id=\"motd\" method=\"post\" action=\"motd\">" +
"<p>Message of the day:</p><br/>"+
"<input id=\"motdinput\" type=\"text\" name=\"motdtext\" class=\"form\"/>" +
"<br/><input type=\"submit\" value=\"Set\" id=\"motdbutton\" /></form>" +
"<form id=\"start\" method=\"post\" action=\"restart\">" +
"<p><input type=\"submit\" value=\"Restart\" /></p>" +
"</form>" +
"<form id=\"stop\" method=\"post\" action=\"stop\">" +
"<p><input type=\"submit\" value=\"Stop\" /></p>" +
"</form></fieldset>");
}
// Function-based substitutions
//vc.put("STATUS", someFunction); FIXME
vc.put("GETLOGS", render.renderLogs());
vc.put("PROJECTS", render.renderProjects());
vc.put("UPTIME", render.getUptime());
vc.put("QUEUE_LENGTH", render.getSchedulerDetails("WAITING"));
vc.put("JOB_EXEC", render.getSchedulerDetails("RUNNING"));
vc.put("JOB_WAIT", render.getSchedulerDetails("WAITING"));
vc.put("JOB_WORKTHR", render.getSchedulerDetails("WORKER"));
vc.put("JOB_FAILED", render.getSchedulerDetails("FAILED"));
vc.put("JOB_TOTAL", render.getSchedulerDetails("TOTAL"));
vc.put("WAITJOBS", render.renderWaitJobs());
vc.put("FAILJOBS", render.renderFailedJobs());
vc.put("JOBFAILSTATS", render.renderJobFailStats());
vc.put("METRICS", render.renderMetrics());
vc.put("USERS", render.renderUsers());
// These are composite substitutions
vc.put("STATUS_CORE","<fieldset id=\"status\">" +
"<legend>Status</legend>" +
"<ul>" +
"<li class=\"uptime\">Uptime: " +
vc.get("UPTIME") +
"</li>" +
"<li class=\"queue\">Job Queue Length: " +
vc.get("QUEUE_LENGTH") +
"</li></ul></fieldset>");
vc.put("STATUS_JOBS","<fieldset id=\"jobs\">" +
"<legend>Job Info</legend>" +
"<table width='100%' cellspacing=0 cellpadding=3>" +
"<tr><td>Executing:</td><td class=\"number\">" +
vc.get("JOB_EXEC") +
"</td></tr>" +
"<tr><td>Waiting:</td><td class=\"number\">" +
vc.get("JOB_WAIT") +
"</td></tr>" +
"<tr><td>Failed:</td><td class=\"number\">" +
vc.get("JOB_FAILED") +
"</td></tr>" +
"<tr><td>Total:</td><td class=\"number\">" +
vc.get("JOB_TOTAL") +
"</td></tr>" +
"<tr class=\"newgroup\"><td>Workers:</td><td class=\"number\">" +
vc.get("JOB_WORKTHR") +
"</td></tr></table></fieldset>");
}
|
diff --git a/src/main/java/com/espirit/moddev/basicworkflows/release/WorkflowObject.java b/src/main/java/com/espirit/moddev/basicworkflows/release/WorkflowObject.java
index 7755343..40ac9a6 100644
--- a/src/main/java/com/espirit/moddev/basicworkflows/release/WorkflowObject.java
+++ b/src/main/java/com/espirit/moddev/basicworkflows/release/WorkflowObject.java
@@ -1,366 +1,366 @@
/*
* **********************************************************************
* basicworkflows
* %%
* Copyright (C) 2012 - 2013 e-Spirit AG
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* **********************************************************************
*/
package com.espirit.moddev.basicworkflows.release;
import com.espirit.moddev.basicworkflows.util.FsException;
import com.espirit.moddev.basicworkflows.util.FsLocale;
import com.espirit.moddev.basicworkflows.util.ReferenceResult;
import com.espirit.moddev.basicworkflows.util.WorkflowConstants;
import de.espirit.common.base.Logging;
import de.espirit.firstspirit.access.ReferenceEntry;
import de.espirit.firstspirit.access.store.IDProvider;
import de.espirit.firstspirit.access.store.StoreElement;
import de.espirit.firstspirit.access.store.contentstore.Content2;
import de.espirit.firstspirit.access.store.contentstore.ContentFolder;
import de.espirit.firstspirit.access.store.contentstore.ContentWorkflowable;
import de.espirit.firstspirit.access.store.globalstore.GCAFolder;
import de.espirit.firstspirit.access.store.globalstore.GCAPage;
import de.espirit.firstspirit.access.store.globalstore.ProjectProperties;
import de.espirit.firstspirit.access.store.mediastore.Media;
import de.espirit.firstspirit.access.store.mediastore.MediaFolder;
import de.espirit.firstspirit.access.store.pagestore.*;
import de.espirit.firstspirit.access.store.sitestore.DocumentGroup;
import de.espirit.firstspirit.access.store.sitestore.PageRef;
import de.espirit.firstspirit.access.store.sitestore.PageRefFolder;
import de.espirit.firstspirit.access.store.templatestore.TemplateStoreElement;
import de.espirit.firstspirit.access.store.templatestore.WorkflowScriptContext;
import de.espirit.or.schema.Entity;
import java.util.*;
/**
* This class provides methods to get the references of the workflow object and store them in the session.
*
* @author stephan
* @since 1.0
*/
public class WorkflowObject {
/** The storeElement to use. */
private StoreElement storeElement;
/** The workflowScriptContext from the workflow. */
private WorkflowScriptContext workflowScriptContext;
/** The content2 object from the workflow. */
private Content2 content2;
/** The Entity to use. */
private Entity entity;
/** The ResourceBundle that contains language specific labels. */
private ResourceBundle bundle;
/** The logging class to use. */
public static final Class<?> LOGGER = WorkflowObject.class;
/**
* Constructor for WorkflowObject.
*
* @param workflowScriptContext The workflowScriptContext from the workflow.
*/
public WorkflowObject(WorkflowScriptContext workflowScriptContext) {
this.workflowScriptContext = workflowScriptContext;
ResourceBundle.clearCache();
bundle = ResourceBundle.getBundle(WorkflowConstants.MESSAGES, new FsLocale(workflowScriptContext).get());
if(workflowScriptContext.getWorkflowable() instanceof ContentWorkflowable) {
content2 = ((ContentWorkflowable) workflowScriptContext.getWorkflowable()).getContent();
entity = ((ContentWorkflowable) workflowScriptContext.getWorkflowable()).getEntity();
} else {
storeElement = (StoreElement) workflowScriptContext.getWorkflowable();
}
}
/**
* This method gets the referenced objects from the workflow object (StoreElement) that prevent the release.
*
* @param releaseWithMedia Determines if media references should also be checked
* @return a list of elements that reference the workflow object.
*/
public List<Object> getRefObjectsFromStoreElement(boolean releaseWithMedia) {
ArrayList<Object>referencedObjects = new ArrayList<Object>();
if (storeElement instanceof PageRef) {
// add outgoing references
referencedObjects.addAll(getReferences(storeElement, releaseWithMedia));
// add outgoing references of referenced page if it is not released
final Page page = ((PageRef) storeElement).getPage();
if (page.getReleaseStatus() != Page.RELEASED) {
// add results
for(ReferenceEntry referenceEntry : page.getOutgoingReferences()) {
if(!releaseWithMedia) {
if(!referenceEntry.isType(ReferenceEntry.MEDIA_STORE_REFERENCE)) {
referencedObjects.add(referenceEntry);
}
} else {
referencedObjects.add(referenceEntry);
}
}
referencedObjects.addAll(getRefObjectsFromSection(page, releaseWithMedia));
}
} else if (storeElement instanceof PageRefFolder) {
// add outgoing references
referencedObjects.addAll(getReferences(storeElement, releaseWithMedia));
} else if (storeElement instanceof GCAPage) {
// add outgoing references
referencedObjects.addAll(getReferences(storeElement, releaseWithMedia));
} else if (storeElement instanceof Page) {
// add outgoing references
referencedObjects.addAll(getReferences(storeElement, releaseWithMedia));
referencedObjects.addAll(getRefObjectsFromSection(storeElement, releaseWithMedia));
} else if (storeElement instanceof PageFolder) {
// add outgoing references
referencedObjects.addAll(getReferences(storeElement, releaseWithMedia));
} else if (storeElement instanceof DocumentGroup) {
// add outgoing references
referencedObjects.addAll(getReferences(storeElement, releaseWithMedia));
} else if (storeElement instanceof Media) {
// add outgoing references
referencedObjects.addAll(getReferences(storeElement, releaseWithMedia));
} else if (storeElement instanceof MediaFolder) {
// add outgoing references
referencedObjects.addAll(getReferences(storeElement, releaseWithMedia));
} else if (storeElement instanceof GCAFolder) {
// add outgoing references
referencedObjects.addAll(getReferences(storeElement, releaseWithMedia));
} else if (storeElement instanceof ProjectProperties) {
// add outgoing references
referencedObjects.addAll(getReferences(storeElement, releaseWithMedia));
} else if (storeElement instanceof Content2) {
//Element is a content2 object -> aborting"
workflowScriptContext.gotoErrorState(bundle.getString("releaseC2notPossible"), new FsException());
} else if (storeElement instanceof ContentFolder) {
//Element is a content folder object -> aborting"
workflowScriptContext.gotoErrorState(bundle.getString("releaseCFnotPossible"), new FsException());
}
return referencedObjects;
}
/**
* This method gets the referenced objects from sections of a page that prevent the release.
*
* @param page The page where to check the sections
* @param releaseWithMedia Determines if media references should also be checked
* @return a list of elements that reference the workflow object.
*/
public List<Object> getRefObjectsFromSection(StoreElement page, boolean releaseWithMedia) {
ArrayList<Object>referencedObjects = new ArrayList<Object>();
// add outgoing references of page sections
for (Section section : page.getChildren(Section.class, true)) {
/** documentation example - begin **/
if (!(section instanceof Content2Section)) {
/** documentation example - end **/
for(ReferenceEntry referenceEntry : section.getOutgoingReferences()) {
if(!releaseWithMedia) {
if(!referenceEntry.isType(ReferenceEntry.MEDIA_STORE_REFERENCE)) {
referencedObjects.add(referenceEntry);
}
} else {
referencedObjects.add(referenceEntry);
}
}
}
}
return referencedObjects;
}
/**
* This method gets the referenced objects from the workflow object (Entity) that prevent the release.
*
* @param includeMedia Determines if media references should also be checked
* @return a list of elements that reference the workflow object.
*/
public List<Object> getRefObjectsFromEntity(boolean includeMedia) {
ArrayList<Object> referencedObjects= new ArrayList<Object>();
for(ReferenceEntry referenceEntry : content2.getSchema().getOutgoingReferences(entity)) {
if(!includeMedia) {
if(!referenceEntry.isType(ReferenceEntry.MEDIA_STORE_REFERENCE)) {
referencedObjects.add(referenceEntry);
}
} else {
referencedObjects.add(referenceEntry);
}
}
return referencedObjects;
}
/**
* Convenience method to check if element can be released according to defined rules.
*
* @param releaseObjects The list of objects to check.
* @param releaseWithMedia Determines if media elements should be implicitly released.
* @return true if successfull
*/
@SuppressWarnings("unchecked")
public boolean checkReferences(List<Object> releaseObjects, boolean releaseWithMedia) {
boolean result = false;
HashMap<String, IDProvider.UidType> notReleasedElements = new HashMap<String, IDProvider.UidType>();
// object to store if elements can be released
ReferenceResult referenceResult = new ReferenceResult();
// itereate over references and check release rules
for(Object object : releaseObjects) {
if(object instanceof Entity || object instanceof ReferenceEntry && ((ReferenceEntry) object).getReferencedObject() instanceof Entity) {
Entity ent;
if(object instanceof Entity) {
ent = (Entity) object;
} else {
ent = (Entity) ((ReferenceEntry) object).getReferencedObject();
}
referenceResult.setOnlyMedia(false);
// check if is no media and released
if(!ent.isReleased()) {
Logging.logWarning("No media and not released:" + ent.getIdentifier() + "#" + ent.get("fs_id"), LOGGER);
referenceResult.setNotMediaReleased(false);
referenceResult.setAllObjectsReleased(false);
notReleasedElements.put(ent.getIdentifier().getEntityTypeName() + " (" + ent.getIdentifier().getEntityTypeName() + ", ID#" + ent.get("fs_id") + ")", IDProvider.UidType.CONTENTSTORE_DATA);
}
} else {
IDProvider idProvider;
if (object instanceof IDProvider) {
idProvider = (IDProvider) object;
} else {
idProvider = (IDProvider) ((ReferenceEntry) object).getReferencedObject();
}
/** documentation example - begin **/
if(idProvider instanceof Section) {
idProvider = idProvider.getParent().getParent();
}
/** documentation example - end **/
// check if current PAGE within PAGEREF-Release
boolean isCurrentPage = false;
if(idProvider instanceof Page && storeElement instanceof PageRef) {
Page page = (Page) idProvider;
Page curPage = ((PageRef) storeElement).getPage();
if(page.getId() == curPage.getId()) {
isCurrentPage = true;
}
}
// if not current PAGE within PAGEREF-Release or media and release with media is not checked
- if(!isCurrentPage || (idProvider instanceof Media && !releaseWithMedia)) {
+ if(!isCurrentPage && idProvider != null || (idProvider instanceof Media && !releaseWithMedia )) {
idProvider.refresh();
// check if only media is referenced except templates
if(!(idProvider instanceof Media) && !(idProvider instanceof TemplateStoreElement) && !(idProvider instanceof Content2)) {
Logging.logWarning("No media:" + idProvider.getUid(), LOGGER);
referenceResult.setOnlyMedia(false);
// check if is no media and not released
if(idProvider.getReleaseStatus() == IDProvider.NEVER_RELEASED) {
Logging.logWarning("No media, but never released:" + idProvider.getUid(), LOGGER);
referenceResult.setNotMediaReleased(false);
notReleasedElements.put(idProvider.getDisplayName(new FsLocale(workflowScriptContext).getLanguage()) + " (" + idProvider.getUid() + ", " + idProvider.getId() + ")", idProvider.getUidType());
}
}
// check if all references are released
if(!(idProvider instanceof TemplateStoreElement) && !(idProvider instanceof Content2) && idProvider.getReleaseStatus() == IDProvider.NEVER_RELEASED) {
Logging.logWarning("Never released:" + idProvider.getUid(), LOGGER);
referenceResult.setAllObjectsReleased(false);
notReleasedElements.put(idProvider.getDisplayName(new FsLocale(workflowScriptContext).getLanguage()) + " (" + idProvider.getUid() + ", " + idProvider.getId() + ")", idProvider.getUidType());
}
}
}
}
// check result if can be released
if(referenceResult.isOnlyMedia() && releaseWithMedia) {
Logging.logWarning("Is only media and checked", LOGGER);
result = true;
} else if (referenceResult.isNotMediaReleased() && releaseWithMedia) {
Logging.logWarning("All non media released and checked", LOGGER);
result = true;
} else if (referenceResult.isAllObjectsReleased() && !releaseWithMedia) {
Logging.logWarning("Everything released and not checked", LOGGER);
result = true;
}
// put not released elements to session for further use
workflowScriptContext.getSession().put("wfNotReleasedElements", notReleasedElements);
return result;
}
/**
* Convenience method to get referenced objects of storeElement and its parents.
*
* @param storeEl The StoreElement to get references from.
* @param releaseWithMedia Determines if media references should also be checked.
* @return the list of referenced objects.
*/
public List<Object> getReferences(StoreElement storeEl, boolean releaseWithMedia) {
ArrayList<Object> references = new ArrayList<Object>();
StoreElement storeElem = storeEl;
// add outgoing references
for(ReferenceEntry referenceEntry : storeElem.getOutgoingReferences()) {
if(!releaseWithMedia) {
if(!referenceEntry.isType(ReferenceEntry.MEDIA_STORE_REFERENCE)) {
references.add(referenceEntry);
}
} else {
references.add(referenceEntry);
}
}
// add outgoing references of parent objects if element was never released before
if(((IDProvider) storeElem).getReleaseStatus() == IDProvider.NEVER_RELEASED) {
while(storeElem.getParent() != null) {
for(ReferenceEntry referenceEntry : storeElem.getOutgoingReferences()) {
if(!releaseWithMedia) {
if(!referenceEntry.isType(ReferenceEntry.MEDIA_STORE_REFERENCE)) {
references.add(referenceEntry);
}
} else {
references.add(referenceEntry);
}
}
storeElem = storeElem.getParent();
}
}
return references;
}
/**
* Convenience method to get an ID from an entity/storeElement.
*
* @return the ID.
*/
public String getId() {
if(storeElement != null) {
return storeElement.getName();
} else {
return entity.getKeyValue().toString();
}
}
}
| true | true | public boolean checkReferences(List<Object> releaseObjects, boolean releaseWithMedia) {
boolean result = false;
HashMap<String, IDProvider.UidType> notReleasedElements = new HashMap<String, IDProvider.UidType>();
// object to store if elements can be released
ReferenceResult referenceResult = new ReferenceResult();
// itereate over references and check release rules
for(Object object : releaseObjects) {
if(object instanceof Entity || object instanceof ReferenceEntry && ((ReferenceEntry) object).getReferencedObject() instanceof Entity) {
Entity ent;
if(object instanceof Entity) {
ent = (Entity) object;
} else {
ent = (Entity) ((ReferenceEntry) object).getReferencedObject();
}
referenceResult.setOnlyMedia(false);
// check if is no media and released
if(!ent.isReleased()) {
Logging.logWarning("No media and not released:" + ent.getIdentifier() + "#" + ent.get("fs_id"), LOGGER);
referenceResult.setNotMediaReleased(false);
referenceResult.setAllObjectsReleased(false);
notReleasedElements.put(ent.getIdentifier().getEntityTypeName() + " (" + ent.getIdentifier().getEntityTypeName() + ", ID#" + ent.get("fs_id") + ")", IDProvider.UidType.CONTENTSTORE_DATA);
}
} else {
IDProvider idProvider;
if (object instanceof IDProvider) {
idProvider = (IDProvider) object;
} else {
idProvider = (IDProvider) ((ReferenceEntry) object).getReferencedObject();
}
/** documentation example - begin **/
if(idProvider instanceof Section) {
idProvider = idProvider.getParent().getParent();
}
/** documentation example - end **/
// check if current PAGE within PAGEREF-Release
boolean isCurrentPage = false;
if(idProvider instanceof Page && storeElement instanceof PageRef) {
Page page = (Page) idProvider;
Page curPage = ((PageRef) storeElement).getPage();
if(page.getId() == curPage.getId()) {
isCurrentPage = true;
}
}
// if not current PAGE within PAGEREF-Release or media and release with media is not checked
if(!isCurrentPage || (idProvider instanceof Media && !releaseWithMedia)) {
idProvider.refresh();
// check if only media is referenced except templates
if(!(idProvider instanceof Media) && !(idProvider instanceof TemplateStoreElement) && !(idProvider instanceof Content2)) {
Logging.logWarning("No media:" + idProvider.getUid(), LOGGER);
referenceResult.setOnlyMedia(false);
// check if is no media and not released
if(idProvider.getReleaseStatus() == IDProvider.NEVER_RELEASED) {
Logging.logWarning("No media, but never released:" + idProvider.getUid(), LOGGER);
referenceResult.setNotMediaReleased(false);
notReleasedElements.put(idProvider.getDisplayName(new FsLocale(workflowScriptContext).getLanguage()) + " (" + idProvider.getUid() + ", " + idProvider.getId() + ")", idProvider.getUidType());
}
}
// check if all references are released
if(!(idProvider instanceof TemplateStoreElement) && !(idProvider instanceof Content2) && idProvider.getReleaseStatus() == IDProvider.NEVER_RELEASED) {
Logging.logWarning("Never released:" + idProvider.getUid(), LOGGER);
referenceResult.setAllObjectsReleased(false);
notReleasedElements.put(idProvider.getDisplayName(new FsLocale(workflowScriptContext).getLanguage()) + " (" + idProvider.getUid() + ", " + idProvider.getId() + ")", idProvider.getUidType());
}
}
}
}
// check result if can be released
if(referenceResult.isOnlyMedia() && releaseWithMedia) {
Logging.logWarning("Is only media and checked", LOGGER);
result = true;
} else if (referenceResult.isNotMediaReleased() && releaseWithMedia) {
Logging.logWarning("All non media released and checked", LOGGER);
result = true;
} else if (referenceResult.isAllObjectsReleased() && !releaseWithMedia) {
Logging.logWarning("Everything released and not checked", LOGGER);
result = true;
}
// put not released elements to session for further use
workflowScriptContext.getSession().put("wfNotReleasedElements", notReleasedElements);
return result;
}
| public boolean checkReferences(List<Object> releaseObjects, boolean releaseWithMedia) {
boolean result = false;
HashMap<String, IDProvider.UidType> notReleasedElements = new HashMap<String, IDProvider.UidType>();
// object to store if elements can be released
ReferenceResult referenceResult = new ReferenceResult();
// itereate over references and check release rules
for(Object object : releaseObjects) {
if(object instanceof Entity || object instanceof ReferenceEntry && ((ReferenceEntry) object).getReferencedObject() instanceof Entity) {
Entity ent;
if(object instanceof Entity) {
ent = (Entity) object;
} else {
ent = (Entity) ((ReferenceEntry) object).getReferencedObject();
}
referenceResult.setOnlyMedia(false);
// check if is no media and released
if(!ent.isReleased()) {
Logging.logWarning("No media and not released:" + ent.getIdentifier() + "#" + ent.get("fs_id"), LOGGER);
referenceResult.setNotMediaReleased(false);
referenceResult.setAllObjectsReleased(false);
notReleasedElements.put(ent.getIdentifier().getEntityTypeName() + " (" + ent.getIdentifier().getEntityTypeName() + ", ID#" + ent.get("fs_id") + ")", IDProvider.UidType.CONTENTSTORE_DATA);
}
} else {
IDProvider idProvider;
if (object instanceof IDProvider) {
idProvider = (IDProvider) object;
} else {
idProvider = (IDProvider) ((ReferenceEntry) object).getReferencedObject();
}
/** documentation example - begin **/
if(idProvider instanceof Section) {
idProvider = idProvider.getParent().getParent();
}
/** documentation example - end **/
// check if current PAGE within PAGEREF-Release
boolean isCurrentPage = false;
if(idProvider instanceof Page && storeElement instanceof PageRef) {
Page page = (Page) idProvider;
Page curPage = ((PageRef) storeElement).getPage();
if(page.getId() == curPage.getId()) {
isCurrentPage = true;
}
}
// if not current PAGE within PAGEREF-Release or media and release with media is not checked
if(!isCurrentPage && idProvider != null || (idProvider instanceof Media && !releaseWithMedia )) {
idProvider.refresh();
// check if only media is referenced except templates
if(!(idProvider instanceof Media) && !(idProvider instanceof TemplateStoreElement) && !(idProvider instanceof Content2)) {
Logging.logWarning("No media:" + idProvider.getUid(), LOGGER);
referenceResult.setOnlyMedia(false);
// check if is no media and not released
if(idProvider.getReleaseStatus() == IDProvider.NEVER_RELEASED) {
Logging.logWarning("No media, but never released:" + idProvider.getUid(), LOGGER);
referenceResult.setNotMediaReleased(false);
notReleasedElements.put(idProvider.getDisplayName(new FsLocale(workflowScriptContext).getLanguage()) + " (" + idProvider.getUid() + ", " + idProvider.getId() + ")", idProvider.getUidType());
}
}
// check if all references are released
if(!(idProvider instanceof TemplateStoreElement) && !(idProvider instanceof Content2) && idProvider.getReleaseStatus() == IDProvider.NEVER_RELEASED) {
Logging.logWarning("Never released:" + idProvider.getUid(), LOGGER);
referenceResult.setAllObjectsReleased(false);
notReleasedElements.put(idProvider.getDisplayName(new FsLocale(workflowScriptContext).getLanguage()) + " (" + idProvider.getUid() + ", " + idProvider.getId() + ")", idProvider.getUidType());
}
}
}
}
// check result if can be released
if(referenceResult.isOnlyMedia() && releaseWithMedia) {
Logging.logWarning("Is only media and checked", LOGGER);
result = true;
} else if (referenceResult.isNotMediaReleased() && releaseWithMedia) {
Logging.logWarning("All non media released and checked", LOGGER);
result = true;
} else if (referenceResult.isAllObjectsReleased() && !releaseWithMedia) {
Logging.logWarning("Everything released and not checked", LOGGER);
result = true;
}
// put not released elements to session for further use
workflowScriptContext.getSession().put("wfNotReleasedElements", notReleasedElements);
return result;
}
|
diff --git a/src/com/teamtyro/src/DataAnalyzer.java b/src/com/teamtyro/src/DataAnalyzer.java
index 9907cfb..a66eb66 100644
--- a/src/com/teamtyro/src/DataAnalyzer.java
+++ b/src/com/teamtyro/src/DataAnalyzer.java
@@ -1,347 +1,347 @@
package com.teamtyro.src;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import com.teamtyro.etc.BetterConstants;
import com.teamtyro.etc.Constants;
import com.teamtyro.etc.MazeMap;
public class DataAnalyzer {
private static TestSubject subjects[];
private static int map[][];
private static MazeMap maze;
private static int whoToDisplay = 0; //0 = human results. 1 = Genetic Algorithm results. 2 = Neural Network Results
private static int[][][] mapPercent;
private static int maxDensity;
private static int camX, camY;
private static DrawText dText;
private static boolean [] keyPressed;
private static boolean numbers;
private static ReadSolutions r;
public static void main(String[] args) {
r = new ReadSolutions("humanSolutions.txt", "geneticSolutions.txt", "neuralSolutions.txt");
switch(whoToDisplay){
case 0:
mapPercent = r.getMapPercent(r.humanSolutions);
case 1:
mapPercent = r.getMapPercent(r.geneticSolutions);
case 2:
mapPercent = r.getMapPercent(r.neuralSolutions);
}
for(int x = 0; x < Constants.MAP_WIDTH; x++){
for(int y = 0; y < Constants.MAP_HEIGHT; y++){
System.out.println("x: "+x+" y: "+y);
System.out.println(mapPercent[x][y][0]);
System.out.println(mapPercent[x][y][1]);
System.out.println(mapPercent[x][y][2]);
System.out.println(mapPercent[x][y][3]);
}
}
System.out.printf("DataAnalyzer V 0.0.1\n");
subjects = new TestSubject [50];
parseTextyText("game_first_run.txt");
map = new int[16][16];
maze = new MazeMap();
maze.loadConstMap("cbbbccccccccbbbbcccccbbbbbbcbbbbcbbbcbsbccbcbbbbcccbccc" +
"bccccbbbbcbcbbbcbbbcbbbbbcbcbbbcbcccbbbbbcccccccccbbbbbbbcbbbbbbb" +
"bbbcbbbbccccccccccbcbbbbbbbbbcbbbcccbbbbcccbbcccccccbbbbcbccccbcc" +
"cbcbbbbcbbbbbbcbcbcbbbbcbwcccbcbcbcbbbbcbbbbcbbbcbcbbbbcccccccccc" +
"ccbbbb");
for(int i=0; i<10; i++) {
maze.loadDensity(subjects[i]);
}
for(int x=0; x<Constants.MAP_WIDTH; x++) {
for(int y=0; y<Constants.MAP_HEIGHT; y++) {
map[x][y] = maze.getSpace(x,y);
}
}
keyPressed = new boolean [256];
for(int i=0; i<256; i++) {
keyPressed[i] = false;
}
numbers = true;
printMaze(map);
begin();
}
private static void parseTextyText(String filename) {
BufferedReader textFile;
try {
textFile = new BufferedReader(new FileReader(filename));
} catch(FileNotFoundException ex) {
System.out.printf("ERROR: Cannot load Texty Text\n");
return;
}
String line;
try {
line = textFile.readLine();
} catch(IOException ex) { return; }
int charsRead = 1;
for(int j=0; j<50; j++) {
String input[] = new String [10];
for(int i=0; i<10; i++) {
input[i] = "";
while(line.charAt(charsRead) != '|' && charsRead < line.length()-1) {
input[i] = input[i] + line.charAt(charsRead);
charsRead++;
}
charsRead++;
}
try { line = textFile.readLine(); } catch (IOException ex) { return; }
System.out.printf("%s\n%s\n%s\n%s\n\n", input[7], input[6], input[5], input[9]);
subjects[j] = new TestSubject(input[7], input[6], input[5], input[9], 1);
System.out.printf("%d\n%d\n%d\n\n", subjects[j].getGender(), subjects[j].getAge(), subjects[j].getEthnicity());
charsRead = 1;
}
try {
textFile.close();
} catch(IOException ex) {}
}
private static void begin() {
int size = Constants.MAP_WIDTH*32;
try {
Display.setDisplayMode(new DisplayMode(size,size));
Display.create();
} catch (LWJGLException e) {
e.printStackTrace();
System.exit(0);
}
// Init OpenGL
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(-1, (float)size-1, 0, (float)size, 1, -1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
maxDensity = maze.getMaxDensity();
System.out.printf("VALUE: %d\n", maxDensity);
// Start main loop
while(!Display.isCloseRequested()) {
// Clears screen and depth buffer
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
GL11.glLoadIdentity();
GL11.glTranslated(camX, camY, 0);
// Rendering
render();
checkKeys();
Display.update();
}
Display.destroy();
}
private static int getPercent(int x, int y, int dir) {
return mapPercent[x][y][dir];
}
private static void drawRect(double x, double y, double w, double h) {
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2d(x ,y );
GL11.glVertex2d(x+w,y );
GL11.glVertex2d(x+w,y+h);
GL11.glVertex2d(x ,y+h);
GL11.glEnd();
}
private static void drawEmptyRect(double x, double y, double w, double h) {
GL11.glColor3f(1, 1, 1);
GL11.glBegin(GL11.GL_LINE_LOOP);
GL11.glVertex2d(x ,y );
GL11.glVertex2d(x+w,y );
GL11.glVertex2d(x+w,y+h);
GL11.glVertex2d(x ,y+h);
GL11.glEnd();
}
private static void render() {
float bs = Constants.BLOCK_SIZE;
for(int y=0; y<Constants.MAP_HEIGHT; y++) {
for(int x=0; x<Constants.MAP_WIDTH; x++) {
switch(map[x][y]) {
case Constants.MAP_BLOCK:
GL11.glColor3f(1, 0, 0);
drawRect(x*bs, ( (Constants.MAP_HEIGHT-1)*bs)-(y*bs), bs, bs);
break;
case Constants.MAP_START:
GL11.glColor3f(1, 1, 0);
drawRect(x*bs, ( (Constants.MAP_HEIGHT-1)*bs)-(y*bs), bs, bs);
break;
case Constants.MAP_WIN:
GL11.glColor3f(0, 1, 0);
drawRect(x*bs, ( (Constants.MAP_HEIGHT-1)*bs)-(y*bs), bs, bs);
break;
case Constants.MAP_SPACE:
GL11.glColor3f(0, 0, (float)maze.getDensity(x,y)/(float)maxDensity);
drawRect(x*bs, ( (Constants.MAP_HEIGHT-1)*bs)-(y*bs), bs, bs);
if(!numbers) {
break;
}
- double txtSize = bs/5;
- double txtW = (1+0.4)*txtSize;
+ double txtSize = bs/4;
+ double txtW = (1.4)*txtSize;
double txtH = txtSize;
GL11.glColor3f(1, 1, 1);
for(int i=0; i<4; i++) {
if(getPercent(x,y,i) != 0) {
GL11.glPushMatrix();
switch(i) {
case 0:
GL11.glTranslated((x*bs)+(bs-txtW)/2, ((Constants.MAP_HEIGHT)*bs)-(y*bs) , 0);
break;
case 1:
GL11.glTranslated((x*bs)+(bs-txtW)/2, ((Constants.MAP_HEIGHT)*bs)-((y*bs)+(bs-txtH)) , 0);
break;
case 2:
GL11.glTranslated((x*bs) , ((Constants.MAP_HEIGHT)*bs)-((y*bs)+(bs-txtH)/2), 0);
break;
case 3:
GL11.glTranslated((x*bs)+(bs-txtW) , ((Constants.MAP_HEIGHT)*bs)-((y*bs)+(bs-txtH)/2), 0);
break;
}
GL11.glTranslated(0,-txtH, 0);
GL11.glScaled(txtSize-1, txtSize-1, 0);
switch(i) {
case 0:
dText = new DrawText(Integer.toString(getPercent(x,y,i)));
break;
case 1:
dText = new DrawText(Integer.toString(getPercent(x,y,i)));
break;
case 2:
dText = new DrawText(Integer.toString(getPercent(x,y,i)));
break;
case 3:
dText = new DrawText(Integer.toString(getPercent(x,y,i)));
break;
}
dText.draw();
GL11.glPopMatrix();
}
}
break;
}
drawEmptyRect(x*bs, ( (Constants.MAP_HEIGHT-1)*bs)-(y*bs), bs, bs);
}
}
}
private static void checkKeys() {
if(Keyboard.isKeyDown(Keyboard.KEY_1)) {
if(maxDensity > 0) {
maxDensity--;
}
} else if(Keyboard.isKeyDown(Keyboard.KEY_2)) {
if(maxDensity < maze.getMaxDensity()) {
maxDensity++;
}
}
if(Keyboard.isKeyDown(Keyboard.KEY_N) && !keyPressed[10]) {
numbers = !numbers;
keyPressed[10] = true;
} else if(!Keyboard.isKeyDown(Keyboard.KEY_N)) {
keyPressed[10] = false;
}
if(Keyboard.isKeyDown(Keyboard.KEY_LEFT) && !keyPressed[Constants.DIR_LEFT]) {
camX+=Constants.BLOCK_SIZE;
keyPressed[Constants.DIR_LEFT] = true;
} else if(!Keyboard.isKeyDown(Keyboard.KEY_LEFT)) {
keyPressed[Constants.DIR_LEFT] = false;
}
if(Keyboard.isKeyDown(Keyboard.KEY_RIGHT) && !keyPressed[Constants.DIR_RIGHT]) {
camX-=Constants.BLOCK_SIZE;
keyPressed[Constants.DIR_RIGHT] = true;
} else if(!Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) {
keyPressed[Constants.DIR_RIGHT] = false;
}
if(Keyboard.isKeyDown(Keyboard.KEY_UP) && !keyPressed[Constants.DIR_UP]) {
camY-=Constants.BLOCK_SIZE;
keyPressed[Constants.DIR_UP] = true;
} else if(!Keyboard.isKeyDown(Keyboard.KEY_UP)) {
keyPressed[Constants.DIR_UP] = false;
}
if(Keyboard.isKeyDown(Keyboard.KEY_DOWN) && !keyPressed[Constants.DIR_DOWN]) {
camY+=Constants.BLOCK_SIZE;
keyPressed[Constants.DIR_DOWN] = true;
} else if(!Keyboard.isKeyDown(Keyboard.KEY_DOWN)) {
keyPressed[Constants.DIR_DOWN] = false;
}
}
private static void printMaze(int[][] tmap) {
for(int x=0; x<Constants.MAP_WIDTH+2; x++) {
System.out.printf("[-]");
}
System.out.println("");
for (int y = 0; y < Constants.MAP_WIDTH; y++) {
System.out.printf("[|]");
for (int x = 0; x < Constants.MAP_HEIGHT; x++) {
switch (tmap[x][y]) {
case Constants.MAP_START:
System.out.printf(" s ");
case Constants.MAP_BLOCK:
System.out.printf("[ ]");
break;
case Constants.MAP_SPACE:
System.out.printf(" ");
break;
case Constants.MAP_WIN:
System.out.printf(" w ");
}
}
System.out.printf("[|]");
System.out.println("");
}
for(int x=0; x<Constants.MAP_WIDTH+2; x++) {
System.out.printf("[-]");
}
System.out.printf("\n");
}
}
| true | true | private static void render() {
float bs = Constants.BLOCK_SIZE;
for(int y=0; y<Constants.MAP_HEIGHT; y++) {
for(int x=0; x<Constants.MAP_WIDTH; x++) {
switch(map[x][y]) {
case Constants.MAP_BLOCK:
GL11.glColor3f(1, 0, 0);
drawRect(x*bs, ( (Constants.MAP_HEIGHT-1)*bs)-(y*bs), bs, bs);
break;
case Constants.MAP_START:
GL11.glColor3f(1, 1, 0);
drawRect(x*bs, ( (Constants.MAP_HEIGHT-1)*bs)-(y*bs), bs, bs);
break;
case Constants.MAP_WIN:
GL11.glColor3f(0, 1, 0);
drawRect(x*bs, ( (Constants.MAP_HEIGHT-1)*bs)-(y*bs), bs, bs);
break;
case Constants.MAP_SPACE:
GL11.glColor3f(0, 0, (float)maze.getDensity(x,y)/(float)maxDensity);
drawRect(x*bs, ( (Constants.MAP_HEIGHT-1)*bs)-(y*bs), bs, bs);
if(!numbers) {
break;
}
double txtSize = bs/5;
double txtW = (1+0.4)*txtSize;
double txtH = txtSize;
GL11.glColor3f(1, 1, 1);
for(int i=0; i<4; i++) {
if(getPercent(x,y,i) != 0) {
GL11.glPushMatrix();
switch(i) {
case 0:
GL11.glTranslated((x*bs)+(bs-txtW)/2, ((Constants.MAP_HEIGHT)*bs)-(y*bs) , 0);
break;
case 1:
GL11.glTranslated((x*bs)+(bs-txtW)/2, ((Constants.MAP_HEIGHT)*bs)-((y*bs)+(bs-txtH)) , 0);
break;
case 2:
GL11.glTranslated((x*bs) , ((Constants.MAP_HEIGHT)*bs)-((y*bs)+(bs-txtH)/2), 0);
break;
case 3:
GL11.glTranslated((x*bs)+(bs-txtW) , ((Constants.MAP_HEIGHT)*bs)-((y*bs)+(bs-txtH)/2), 0);
break;
}
GL11.glTranslated(0,-txtH, 0);
GL11.glScaled(txtSize-1, txtSize-1, 0);
switch(i) {
case 0:
dText = new DrawText(Integer.toString(getPercent(x,y,i)));
break;
case 1:
dText = new DrawText(Integer.toString(getPercent(x,y,i)));
break;
case 2:
dText = new DrawText(Integer.toString(getPercent(x,y,i)));
break;
case 3:
dText = new DrawText(Integer.toString(getPercent(x,y,i)));
break;
}
dText.draw();
GL11.glPopMatrix();
}
}
break;
}
drawEmptyRect(x*bs, ( (Constants.MAP_HEIGHT-1)*bs)-(y*bs), bs, bs);
}
}
}
| private static void render() {
float bs = Constants.BLOCK_SIZE;
for(int y=0; y<Constants.MAP_HEIGHT; y++) {
for(int x=0; x<Constants.MAP_WIDTH; x++) {
switch(map[x][y]) {
case Constants.MAP_BLOCK:
GL11.glColor3f(1, 0, 0);
drawRect(x*bs, ( (Constants.MAP_HEIGHT-1)*bs)-(y*bs), bs, bs);
break;
case Constants.MAP_START:
GL11.glColor3f(1, 1, 0);
drawRect(x*bs, ( (Constants.MAP_HEIGHT-1)*bs)-(y*bs), bs, bs);
break;
case Constants.MAP_WIN:
GL11.glColor3f(0, 1, 0);
drawRect(x*bs, ( (Constants.MAP_HEIGHT-1)*bs)-(y*bs), bs, bs);
break;
case Constants.MAP_SPACE:
GL11.glColor3f(0, 0, (float)maze.getDensity(x,y)/(float)maxDensity);
drawRect(x*bs, ( (Constants.MAP_HEIGHT-1)*bs)-(y*bs), bs, bs);
if(!numbers) {
break;
}
double txtSize = bs/4;
double txtW = (1.4)*txtSize;
double txtH = txtSize;
GL11.glColor3f(1, 1, 1);
for(int i=0; i<4; i++) {
if(getPercent(x,y,i) != 0) {
GL11.glPushMatrix();
switch(i) {
case 0:
GL11.glTranslated((x*bs)+(bs-txtW)/2, ((Constants.MAP_HEIGHT)*bs)-(y*bs) , 0);
break;
case 1:
GL11.glTranslated((x*bs)+(bs-txtW)/2, ((Constants.MAP_HEIGHT)*bs)-((y*bs)+(bs-txtH)) , 0);
break;
case 2:
GL11.glTranslated((x*bs) , ((Constants.MAP_HEIGHT)*bs)-((y*bs)+(bs-txtH)/2), 0);
break;
case 3:
GL11.glTranslated((x*bs)+(bs-txtW) , ((Constants.MAP_HEIGHT)*bs)-((y*bs)+(bs-txtH)/2), 0);
break;
}
GL11.glTranslated(0,-txtH, 0);
GL11.glScaled(txtSize-1, txtSize-1, 0);
switch(i) {
case 0:
dText = new DrawText(Integer.toString(getPercent(x,y,i)));
break;
case 1:
dText = new DrawText(Integer.toString(getPercent(x,y,i)));
break;
case 2:
dText = new DrawText(Integer.toString(getPercent(x,y,i)));
break;
case 3:
dText = new DrawText(Integer.toString(getPercent(x,y,i)));
break;
}
dText.draw();
GL11.glPopMatrix();
}
}
break;
}
drawEmptyRect(x*bs, ( (Constants.MAP_HEIGHT-1)*bs)-(y*bs), bs, bs);
}
}
}
|
diff --git a/bundles/org.eclipse.equinox.frameworkadmin.equinox/src/org/eclipse/equinox/internal/frameworkadmin/equinox/EquinoxFwConfigFileParser.java b/bundles/org.eclipse.equinox.frameworkadmin.equinox/src/org/eclipse/equinox/internal/frameworkadmin/equinox/EquinoxFwConfigFileParser.java
index aa14afea5..36a9e163e 100644
--- a/bundles/org.eclipse.equinox.frameworkadmin.equinox/src/org/eclipse/equinox/internal/frameworkadmin/equinox/EquinoxFwConfigFileParser.java
+++ b/bundles/org.eclipse.equinox.frameworkadmin.equinox/src/org/eclipse/equinox/internal/frameworkadmin/equinox/EquinoxFwConfigFileParser.java
@@ -1,585 +1,585 @@
/*******************************************************************************
* Copyright (c) 2007, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.equinox.internal.frameworkadmin.equinox;
import java.io.*;
import java.net.*;
import java.util.*;
import org.eclipse.core.runtime.URIUtil;
import org.eclipse.equinox.internal.frameworkadmin.equinox.utils.FileUtils;
import org.eclipse.equinox.internal.frameworkadmin.utils.Utils;
import org.eclipse.equinox.internal.provisional.frameworkadmin.*;
import org.eclipse.osgi.util.NLS;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.service.log.LogService;
public class EquinoxFwConfigFileParser {
private static final Set KNOWN_PROPERTIES = new HashSet(Arrays.asList(new String[] {EquinoxConstants.PROP_BUNDLES, EquinoxConstants.PROP_FW_EXTENSIONS, EquinoxConstants.PROP_INITIAL_STARTLEVEL, EquinoxConstants.PROP_BUNDLES_STARTLEVEL}));
private static final String CONFIG_DIR = "@config.dir/"; //$NON-NLS-1$
private static final String KEY_ECLIPSE_PROV_DATA_AREA = "eclipse.p2.data.area"; //$NON-NLS-1$
private static final String KEY_ORG_ECLIPSE_EQUINOX_SIMPLECONFIGURATOR_CONFIGURL = "org.eclipse.equinox.simpleconfigurator.configUrl"; //$NON-NLS-1$
private static final String REFERENCE_SCHEME = "reference:"; //$NON-NLS-1$
private static final String FILE_PROTOCOL = "file:"; //$NON-NLS-1$
private static boolean DEBUG = false;
public EquinoxFwConfigFileParser(BundleContext context) {
//Empty
}
private static StringBuffer toOSGiBundleListForm(BundleInfo bundleInfo, URI location) {
StringBuffer locationString = new StringBuffer(REFERENCE_SCHEME);
if (URIUtil.isFileURI(location))
locationString.append(URIUtil.toUnencodedString(location));
else if (location.getScheme() == null)
locationString.append(FILE_PROTOCOL).append(URIUtil.toUnencodedString(location));
else
locationString = new StringBuffer(URIUtil.toUnencodedString(location));
int startLevel = bundleInfo.getStartLevel();
boolean toBeStarted = bundleInfo.isMarkedAsStarted();
StringBuffer sb = new StringBuffer();
sb.append(locationString);
if (startLevel == BundleInfo.NO_LEVEL && !toBeStarted)
return sb;
sb.append('@');
if (startLevel != BundleInfo.NO_LEVEL)
sb.append(startLevel);
if (toBeStarted)
sb.append(":start"); //$NON-NLS-1$
return sb;
}
private static boolean getMarkedAsStartedFormat(String startInfo) {
if (startInfo == null)
return false;
startInfo = startInfo.trim();
int colon = startInfo.indexOf(':');
if (colon > -1) {
return startInfo.substring(colon + 1).equals("start"); //$NON-NLS-1$
}
return startInfo.equals("start"); //$NON-NLS-1$
}
private static int getStartLevel(String startInfo) {
if (startInfo == null)
return BundleInfo.NO_LEVEL;
startInfo = startInfo.trim();
int colon = startInfo.indexOf(":"); //$NON-NLS-1$
if (colon > 0) {
try {
return Integer.parseInt(startInfo.substring(0, colon));
} catch (NumberFormatException e) {
return BundleInfo.NO_LEVEL;
}
}
return BundleInfo.NO_LEVEL;
}
private void readBundlesList(Manipulator manipulator, URI osgiInstallArea, Properties props) throws NumberFormatException {
ConfigData configData = manipulator.getConfigData();
BundleInfo[] fwExtensions = parseBundleList(manipulator, props.getProperty(EquinoxConstants.PROP_FW_EXTENSIONS));
if (fwExtensions != null) {
for (int i = 0; i < fwExtensions.length; i++) {
fwExtensions[i].setFragmentHost(Constants.SYSTEM_BUNDLE_SYMBOLICNAME);
configData.addBundle(fwExtensions[i]);
}
}
BundleInfo[] bundles = parseBundleList(manipulator, props.getProperty(EquinoxConstants.PROP_BUNDLES));
if (bundles != null) {
for (int i = 0; i < bundles.length; i++) {
configData.addBundle(bundles[i]);
}
}
}
private BundleInfo[] parseBundleList(Manipulator manipulator, String value) {
if (value == null || value.length() == 0)
return null;
List bundles = new ArrayList();
String[] bInfoStrings = Utils.getTokens(value, ","); //$NON-NLS-1$
for (int i = 0; i < bInfoStrings.length; i++) {
String entry = bInfoStrings[i].trim();
entry = FileUtils.removeEquinoxSpecificProtocols(entry);
int indexStartInfo = entry.indexOf('@');
String location = (indexStartInfo == -1) ? entry : entry.substring(0, indexStartInfo);
URI realLocation = null;
if (manipulator.getLauncherData().getFwJar() != null) {
File parentFile = manipulator.getLauncherData().getFwJar().getParentFile();
try {
realLocation = URIUtil.makeAbsolute(FileUtils.fromFileURL(location), parentFile.toURI());
} catch (URISyntaxException e) {
// try searching as a simple location
realLocation = FileUtils.getEclipsePluginFullLocation(location, parentFile);
}
}
String slAndFlag = (indexStartInfo > -1) ? entry.substring(indexStartInfo + 1) : null;
boolean markedAsStarted = getMarkedAsStartedFormat(slAndFlag);
int startLevel = getStartLevel(slAndFlag);
if (realLocation != null) {
bundles.add(new BundleInfo(realLocation, startLevel, markedAsStarted));
continue;
}
if (location != null && location.startsWith(FILE_PROTOCOL))
try {
bundles.add(new BundleInfo(FileUtils.fromFileURL(location), startLevel, markedAsStarted));
continue;
} catch (URISyntaxException e) {
//Ignore
}
//Fallback case, we use the location as a string
bundles.add(new BundleInfo(location, null, null, startLevel, markedAsStarted));
}
return (BundleInfo[]) bundles.toArray(new BundleInfo[bundles.size()]);
}
private void writeBundlesList(File fwJar, Properties props, URI base, BundleInfo[] bundles) {
StringBuffer osgiBundlesList = new StringBuffer();
StringBuffer osgiFrameworkExtensionsList = new StringBuffer();
for (int j = 0; j < bundles.length; j++) {
BundleInfo bundle = bundles[j];
//framework jar does not get stored on the bundle list, figure out who that is.
if (fwJar != null) {
if (URIUtil.sameURI(fwJar.toURI(), bundle.getLocation()))
continue;
} else if (EquinoxConstants.FW_SYMBOLIC_NAME.equals(bundle.getSymbolicName()))
continue;
URI location = fwJar != null ? URIUtil.makeRelative(bundle.getLocation(), fwJar.getParentFile().toURI()) : bundle.getLocation();
String fragmentHost = bundle.getFragmentHost();
boolean isFrameworkExtension = fragmentHost != null && (fragmentHost.startsWith(EquinoxConstants.FW_SYMBOLIC_NAME) || fragmentHost.startsWith(Constants.SYSTEM_BUNDLE_SYMBOLICNAME));
if (isFrameworkExtension) {
bundle.setStartLevel(BundleInfo.NO_LEVEL);
bundle.setMarkedAsStarted(false);
osgiFrameworkExtensionsList.append(toOSGiBundleListForm(bundle, location));
osgiFrameworkExtensionsList.append(',');
} else {
osgiBundlesList.append(toOSGiBundleListForm(bundle, location));
osgiBundlesList.append(',');
}
}
if (osgiFrameworkExtensionsList.length() > 0)
osgiFrameworkExtensionsList.deleteCharAt(osgiFrameworkExtensionsList.length() - 1);
props.setProperty(EquinoxConstants.PROP_FW_EXTENSIONS, osgiFrameworkExtensionsList.toString());
if (osgiBundlesList.length() > 0)
osgiBundlesList.deleteCharAt(osgiBundlesList.length() - 1);
props.setProperty(EquinoxConstants.PROP_BUNDLES, osgiBundlesList.toString());
}
/**
* inputFile must be not a directory but a file.
*
* @param manipulator
* @param inputFile
* @throws IOException
*/
public void readFwConfig(Manipulator manipulator, File inputFile) throws IOException, URISyntaxException {
if (inputFile.isDirectory())
throw new IllegalArgumentException(NLS.bind(Messages.exception_inputFileIsDirectory, inputFile));
//Initialize data structures
ConfigData configData = manipulator.getConfigData();
LauncherData launcherData = manipulator.getLauncherData();
configData.initialize();
configData.setBundles(null);
String launcherName = null;
String launcherPath = null;
// load configuration properties
Properties props = loadProperties(inputFile);
// load shared configuration properties
Properties sharedConfigProperties = getSharedConfiguration(props.getProperty(EquinoxConstants.PROP_SHARED_CONFIGURATION_AREA), ParserUtils.getOSGiInstallArea(Arrays.asList(manipulator.getLauncherData().getProgramArgs()), props, manipulator.getLauncherData()));
if (sharedConfigProperties != null) {
sharedConfigProperties.putAll(props);
props = sharedConfigProperties;
}
//Start figuring out stuffs
URI rootURI = launcherData.getLauncher() != null ? launcherData.getLauncher().getParentFile().toURI() : null;
readFwJarLocation(configData, launcherData, props);
URI configArea = inputFile.getParentFile().toURI();
readLauncherPath(props, rootURI);
readp2DataArea(props, configArea);
readSimpleConfiguratorURL(props, configArea);
readBundlesList(manipulator, ParserUtils.getOSGiInstallArea(Arrays.asList(launcherData.getProgramArgs()), props, launcherData).toURI(), props);
readInitialStartLeve(configData, props);
readDefaultStartLevel(configData, props);
for (Enumeration enumeration = props.keys(); enumeration.hasMoreElements();) {
String key = (String) enumeration.nextElement();
if (KNOWN_PROPERTIES.contains(key))
continue;
String value = props.getProperty(key);
configData.setProperty(key, value);
}
if (launcherName != null && launcherPath != null) {
launcherData.setLauncher(new File(launcherPath, launcherName + EquinoxConstants.EXE_EXTENSION));
}
Log.log(LogService.LOG_INFO, NLS.bind(Messages.log_configFile, inputFile.getAbsolutePath()));
}
private void readDefaultStartLevel(ConfigData configData, Properties props) {
if (props.getProperty(EquinoxConstants.PROP_BUNDLES_STARTLEVEL) != null)
configData.setInitialBundleStartLevel(Integer.parseInt(props.getProperty(EquinoxConstants.PROP_BUNDLES_STARTLEVEL)));
}
private void writeDefaultStartLevel(ConfigData configData, Properties props) {
if (configData.getInitialBundleStartLevel() != BundleInfo.NO_LEVEL)
props.setProperty(EquinoxConstants.PROP_BUNDLES_STARTLEVEL, Integer.toString(configData.getInitialBundleStartLevel()));
}
private void readInitialStartLeve(ConfigData configData, Properties props) {
if (props.getProperty(EquinoxConstants.PROP_INITIAL_STARTLEVEL) != null)
configData.setBeginningFwStartLevel(Integer.parseInt(props.getProperty(EquinoxConstants.PROP_INITIAL_STARTLEVEL)));
}
private void writeInitialStartLevel(ConfigData configData, Properties props) {
if (configData.getBeginingFwStartLevel() != BundleInfo.NO_LEVEL)
props.setProperty(EquinoxConstants.PROP_INITIAL_STARTLEVEL, Integer.toString(configData.getBeginingFwStartLevel()));
}
private File readFwJarLocation(ConfigData configData, LauncherData launcherData, Properties props) throws URISyntaxException {
File fwJar = null;
if (props.getProperty(EquinoxConstants.PROP_OSGI_FW) != null) {
URI absoluteFwJar = null;
absoluteFwJar = URIUtil.makeAbsolute(FileUtils.fromFileURL(props.getProperty(EquinoxConstants.PROP_OSGI_FW)), ParserUtils.getOSGiInstallArea(Arrays.asList(launcherData.getProgramArgs()), configData.getProperties(), launcherData).toURI());
props.setProperty(EquinoxConstants.PROP_OSGI_FW, absoluteFwJar.toString());
String fwJarString = props.getProperty(EquinoxConstants.PROP_OSGI_FW);
if (fwJarString != null) {
fwJar = URIUtil.toFile(absoluteFwJar);
if (fwJar == null)
throw new IllegalStateException(Messages.exception_noFrameworkLocation);
//Here we overwrite the value read from eclipse.ini, because the value of osgi.framework always takes precedence.
launcherData.setFwJar(fwJar);
} else {
throw new IllegalStateException(Messages.exception_noFrameworkLocation);
}
}
if (launcherData.getFwJar() != null)
configData.addBundle(new BundleInfo(launcherData.getFwJar().toURI()));
return launcherData.getFwJar();
}
private void writeFwJarLocation(ConfigData configData, LauncherData launcherData, Properties props) {
if (launcherData.getFwJar() == null)
return;
props.setProperty(EquinoxConstants.PROP_OSGI_FW, FileUtils.toFileURL(URIUtil.makeRelative(launcherData.getFwJar().toURI(), ParserUtils.getOSGiInstallArea(Arrays.asList(launcherData.getProgramArgs()), configData.getProperties(), launcherData).toURI())));
}
private static Properties loadProperties(File inputFile) throws FileNotFoundException, IOException {
Properties props = new Properties();
InputStream is = null;
try {
is = new FileInputStream(inputFile);
props.load(is);
} finally {
try {
is.close();
} catch (IOException e) {
Log.log(LogService.LOG_WARNING, NLS.bind(Messages.log_failed_reading_properties, inputFile));
}
is = null;
}
return props;
}
private File findSharedConfigIniFile(URL rootURL, String sharedConfigurationArea) {
URL sharedConfigurationURL = null;
try {
sharedConfigurationURL = new URL(sharedConfigurationArea);
} catch (MalformedURLException e) {
// unexpected since this was written by the framework
Log.log(LogService.LOG_WARNING, NLS.bind(Messages.log_shared_config_url, sharedConfigurationArea));
return null;
}
// check for a relative URL
if (!sharedConfigurationURL.getPath().startsWith("/")) { //$NON-NLS-1$
if (!rootURL.getProtocol().equals(sharedConfigurationURL.getProtocol())) {
Log.log(LogService.LOG_WARNING, NLS.bind(Messages.log_shared_config_relative_url, rootURL.toExternalForm(), sharedConfigurationArea));
return null;
}
try {
sharedConfigurationURL = new URL(rootURL, sharedConfigurationArea);
} catch (MalformedURLException e) {
// unexpected since this was written by the framework
Log.log(LogService.LOG_WARNING, NLS.bind(Messages.log_shared_config_relative_url, rootURL.toExternalForm(), sharedConfigurationArea));
return null;
}
}
File sharedConfigurationFolder = new File(sharedConfigurationURL.getPath());
if (!sharedConfigurationFolder.isDirectory()) {
Log.log(LogService.LOG_WARNING, NLS.bind(Messages.log_shared_config_file_missing, sharedConfigurationFolder));
return null;
}
File sharedConfigIni = new File(sharedConfigurationFolder, EquinoxConstants.CONFIG_INI);
if (!sharedConfigIni.exists()) {
Log.log(LogService.LOG_WARNING, NLS.bind(Messages.log_shared_config_file_missing, sharedConfigIni));
return null;
}
return sharedConfigIni;
}
private void readp2DataArea(Properties props, URI configArea) throws URISyntaxException {
if (props.getProperty(KEY_ECLIPSE_PROV_DATA_AREA) != null) {
String url = props.getProperty(KEY_ECLIPSE_PROV_DATA_AREA);
if (url != null) {
if (url.startsWith(CONFIG_DIR))
url = "file:" + url.substring(CONFIG_DIR.length()); //$NON-NLS-1$
props.setProperty(KEY_ECLIPSE_PROV_DATA_AREA, URIUtil.makeAbsolute(FileUtils.fromFileURL(url), configArea).toString());
}
}
}
private void writep2DataArea(ConfigData configData, Properties props, URI configArea) throws URISyntaxException {
String dataArea = getFwProperty(configData, KEY_ECLIPSE_PROV_DATA_AREA);
if (dataArea != null) {
if (dataArea.startsWith(CONFIG_DIR)) {
props.setProperty(KEY_ECLIPSE_PROV_DATA_AREA, dataArea);
return;
}
URI dataAreaURI = new URI(dataArea);
URI relative = URIUtil.makeRelative(dataAreaURI, configArea);
if (dataAreaURI.equals(relative)) {
props.setProperty(KEY_ECLIPSE_PROV_DATA_AREA, FileUtils.toFileURL(dataAreaURI));
return;
}
String result = URIUtil.toUnencodedString(relative);
//We only relativize up to the level where the p2 and config folder are siblings (e.g. foo/p2 and foo/config)
if (result.startsWith("../..")) //$NON-NLS-1$
result = dataArea;
else if (!result.equals(dataArea)) {
props.setProperty(KEY_ECLIPSE_PROV_DATA_AREA, CONFIG_DIR + result);
return;
}
props.setProperty(KEY_ECLIPSE_PROV_DATA_AREA, FileUtils.toFileURL(new URI(result)));
}
}
private void readLauncherPath(Properties props, URI root) throws URISyntaxException {
if (props.getProperty(EquinoxConstants.PROP_LAUNCHER_PATH) != null)
props.setProperty(EquinoxConstants.PROP_LAUNCHER_PATH, URIUtil.makeAbsolute(URIUtil.fromString(props.getProperty(EquinoxConstants.PROP_LAUNCHER_PATH)), root).toString());
}
private void writeLauncherPath(ConfigData configData, Properties props, URI root) throws URISyntaxException {
String value = getFwProperty(configData, EquinoxConstants.PROP_LAUNCHER_PATH);
if (value != null) {
URI launcherPathURI = FileUtils.fromPath(value);
String launcherPath = URIUtil.toUnencodedString(URIUtil.makeRelative(launcherPathURI, root));
if ("/".equals(launcherPath) || "".equals(launcherPath)) //$NON-NLS-1$ //$NON-NLS-2$
launcherPath = "."; //$NON-NLS-1$
props.setProperty(EquinoxConstants.PROP_LAUNCHER_PATH, launcherPath);
}
}
private void readSimpleConfiguratorURL(Properties props, URI configArea) throws URISyntaxException {
if (props.getProperty(KEY_ORG_ECLIPSE_EQUINOX_SIMPLECONFIGURATOR_CONFIGURL) != null)
props.setProperty(KEY_ORG_ECLIPSE_EQUINOX_SIMPLECONFIGURATOR_CONFIGURL, URIUtil.makeAbsolute(FileUtils.fromFileURL(props.getProperty(KEY_ORG_ECLIPSE_EQUINOX_SIMPLECONFIGURATOR_CONFIGURL)), configArea).toString());
}
private void writeSimpleConfiguratorURL(ConfigData configData, Properties props, URI configArea) throws URISyntaxException {
//FIXME How would someone set such a value.....
String value = getFwProperty(configData, KEY_ORG_ECLIPSE_EQUINOX_SIMPLECONFIGURATOR_CONFIGURL);
if (value != null)
props.setProperty(KEY_ORG_ECLIPSE_EQUINOX_SIMPLECONFIGURATOR_CONFIGURL, FileUtils.toFileURL(URIUtil.makeRelative(URIUtil.fromString(value), configArea)));
}
private String getFwProperty(ConfigData data, String key) {
return data.getProperty(key);
}
public void saveFwConfig(BundleInfo[] bInfos, Manipulator manipulator, boolean backup, boolean relative) throws IOException {//{
ConfigData configData = manipulator.getConfigData();
LauncherData launcherData = manipulator.getLauncherData();
//Get the OSGi jar from the bundle.info
File fwJar = EquinoxBundlesState.getSystemBundleFromBundleInfos(configData);
launcherData.setFwJar(fwJar);
File outputFile = launcherData.getFwConfigLocation();
if (outputFile.exists()) {
if (outputFile.isFile()) {
if (!outputFile.getName().equals(EquinoxConstants.CONFIG_INI))
throw new IllegalStateException(NLS.bind(Messages.exception_fwConfigLocationName, outputFile.getAbsolutePath(), EquinoxConstants.CONFIG_INI));
} else { // Directory
outputFile = new File(outputFile, EquinoxConstants.CONFIG_INI);
}
} else {
if (!outputFile.getName().equals(EquinoxConstants.CONFIG_INI)) {
if (!outputFile.mkdir())
throw new IOException(NLS.bind(Messages.exception_failedToCreateDir, outputFile));
outputFile = new File(outputFile, EquinoxConstants.CONFIG_INI);
}
}
String header = "This configuration file was written by: " + this.getClass().getName(); //$NON-NLS-1$
Properties configProps = new Properties();
URI rootURI = launcherData.getLauncher() != null ? launcherData.getLauncher().getParentFile().toURI() : null;
writeFwJarLocation(configData, launcherData, configProps);
try {
writeLauncherPath(configData, configProps, rootURI);
URI configArea = manipulator.getLauncherData().getFwConfigLocation().toURI();
writep2DataArea(configData, configProps, configArea);
writeSimpleConfiguratorURL(configData, configProps, configArea);
writeBundlesList(launcherData.getFwJar(), configProps, ParserUtils.getOSGiInstallArea(Arrays.asList(launcherData.getProgramArgs()), configProps, launcherData).toURI(), bInfos);
writeInitialStartLevel(configData, configProps);
writeDefaultStartLevel(configData, configProps);
} catch (URISyntaxException e) {
throw new FrameworkAdminRuntimeException(e, Messages.exception_errorSavingConfigIni);
}
Properties original = configData.getProperties();
original.putAll(configProps);
configProps = original;
//Deal with the fw jar and ensure it is not set.
//TODO This can't be done before because of the previous calls to appendProperties
if (configProps == null || configProps.size() == 0) {
Log.log(LogService.LOG_WARNING, this, "saveFwConfig() ", Messages.log_configProps); //$NON-NLS-1$
return;
}
if (!Utils.createParentDir(outputFile)) {
- throw new IllegalStateException(Messages.exception_failedToCreateDir);
+ throw new IllegalStateException(NLS.bind(Messages.exception_failedToCreateDir, outputFile.getParent()));
}
if (DEBUG)
Utils.printoutProperties(System.out, "configProps", configProps); //$NON-NLS-1$
if (backup)
if (outputFile.exists()) {
File dest = Utils.getSimpleDataFormattedFile(outputFile);
if (!outputFile.renameTo(dest))
throw new IOException(NLS.bind(Messages.exception_failedToRename, outputFile, dest));
Log.log(LogService.LOG_INFO, this, "saveFwConfig()", NLS.bind(Messages.log_renameSuccessful, outputFile, dest)); //$NON-NLS-1$
}
FileOutputStream out = null;
try {
out = new FileOutputStream(outputFile);
// configProps = makeRelative(configProps, launcherData.getLauncher().getParentFile().toURI(), fwJar, outputFile.getParentFile(), getOSGiInstallArea(manipulator.getLauncherData()));
filterPropertiesFromSharedArea(configProps, manipulator);
configProps.store(out, header);
Log.log(LogService.LOG_INFO, NLS.bind(Messages.log_fwConfigSave, outputFile));
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
out = null;
}
}
private void filterPropertiesFromSharedArea(Properties configProps, Manipulator manipulator) {
LauncherData launcherData = manipulator.getLauncherData();
//Remove from the config file that we are about to write the properties that are unchanged compared to what is in the base
Properties sharedConfigProperties = getSharedConfiguration(configProps.getProperty(EquinoxConstants.PROP_SHARED_CONFIGURATION_AREA), ParserUtils.getOSGiInstallArea(Arrays.asList(launcherData.getProgramArgs()), configProps, launcherData));
if (sharedConfigProperties == null)
return;
Enumeration keys = configProps.propertyNames();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
String sharedValue = sharedConfigProperties.getProperty(key);
if (sharedValue == null)
continue;
String value = configProps.getProperty(key);
if (equalsIgnoringSeparators(sharedValue, value)) {
configProps.remove(key);
continue;
}
if (key.equals(EquinoxConstants.PROP_BUNDLES) && equalBundleLists(manipulator, value, sharedValue)) {
configProps.remove(key);
continue;
}
if (key.equals(EquinoxConstants.PROP_FW_EXTENSIONS) && equalBundleLists(manipulator, value, sharedValue)) {
configProps.remove(key);
continue;
}
}
}
private boolean equalBundleLists(Manipulator manipulator, String value, String sharedValue) {
BundleInfo[] bundles = parseBundleList(manipulator, value);
BundleInfo[] sharedBundles = parseBundleList(manipulator, sharedValue);
if (bundles == null || sharedBundles == null || bundles.length != sharedBundles.length)
return false;
List compareList = new ArrayList(Arrays.asList(bundles));
compareList.removeAll(Arrays.asList(sharedBundles));
return compareList.isEmpty();
}
private boolean equalsIgnoringSeparators(String s1, String s2) {
if (s1 == null && s2 == null)
return true;
if (s1 == null || s2 == null)
return false;
StringBuffer sb1 = new StringBuffer(s1);
StringBuffer sb2 = new StringBuffer(s2);
canonicalizePathsForComparison(sb1);
canonicalizePathsForComparison(sb2);
return sb1.toString().equals(sb2.toString());
}
private void canonicalizePathsForComparison(StringBuffer s) {
final String[] tokens = new String[] {"\\\\", "\\", "//", "/"}; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
for (int t = 0; t < tokens.length; t++) {
int idx = s.length();
for (int i = s.length(); i != 0 && idx != -1; i--) {
idx = s.toString().lastIndexOf(tokens[t], idx);
if (idx != -1)
s.replace(idx, idx + tokens[t].length(), "^"); //$NON-NLS-1$
}
}
}
private Properties getSharedConfiguration(String sharedConfigurationArea, File baseFile) {
if (sharedConfigurationArea == null)
return null;
File sharedConfigIni;
try {
sharedConfigIni = findSharedConfigIniFile(baseFile.toURL(), sharedConfigurationArea);
} catch (MalformedURLException e) {
return null;
}
if (sharedConfigIni != null && sharedConfigIni.exists())
try {
return loadProperties(sharedConfigIni);
} catch (FileNotFoundException e) {
return null;
} catch (IOException e) {
return null;
}
return null;
}
}
| true | true | public void saveFwConfig(BundleInfo[] bInfos, Manipulator manipulator, boolean backup, boolean relative) throws IOException {//{
ConfigData configData = manipulator.getConfigData();
LauncherData launcherData = manipulator.getLauncherData();
//Get the OSGi jar from the bundle.info
File fwJar = EquinoxBundlesState.getSystemBundleFromBundleInfos(configData);
launcherData.setFwJar(fwJar);
File outputFile = launcherData.getFwConfigLocation();
if (outputFile.exists()) {
if (outputFile.isFile()) {
if (!outputFile.getName().equals(EquinoxConstants.CONFIG_INI))
throw new IllegalStateException(NLS.bind(Messages.exception_fwConfigLocationName, outputFile.getAbsolutePath(), EquinoxConstants.CONFIG_INI));
} else { // Directory
outputFile = new File(outputFile, EquinoxConstants.CONFIG_INI);
}
} else {
if (!outputFile.getName().equals(EquinoxConstants.CONFIG_INI)) {
if (!outputFile.mkdir())
throw new IOException(NLS.bind(Messages.exception_failedToCreateDir, outputFile));
outputFile = new File(outputFile, EquinoxConstants.CONFIG_INI);
}
}
String header = "This configuration file was written by: " + this.getClass().getName(); //$NON-NLS-1$
Properties configProps = new Properties();
URI rootURI = launcherData.getLauncher() != null ? launcherData.getLauncher().getParentFile().toURI() : null;
writeFwJarLocation(configData, launcherData, configProps);
try {
writeLauncherPath(configData, configProps, rootURI);
URI configArea = manipulator.getLauncherData().getFwConfigLocation().toURI();
writep2DataArea(configData, configProps, configArea);
writeSimpleConfiguratorURL(configData, configProps, configArea);
writeBundlesList(launcherData.getFwJar(), configProps, ParserUtils.getOSGiInstallArea(Arrays.asList(launcherData.getProgramArgs()), configProps, launcherData).toURI(), bInfos);
writeInitialStartLevel(configData, configProps);
writeDefaultStartLevel(configData, configProps);
} catch (URISyntaxException e) {
throw new FrameworkAdminRuntimeException(e, Messages.exception_errorSavingConfigIni);
}
Properties original = configData.getProperties();
original.putAll(configProps);
configProps = original;
//Deal with the fw jar and ensure it is not set.
//TODO This can't be done before because of the previous calls to appendProperties
if (configProps == null || configProps.size() == 0) {
Log.log(LogService.LOG_WARNING, this, "saveFwConfig() ", Messages.log_configProps); //$NON-NLS-1$
return;
}
if (!Utils.createParentDir(outputFile)) {
throw new IllegalStateException(Messages.exception_failedToCreateDir);
}
if (DEBUG)
Utils.printoutProperties(System.out, "configProps", configProps); //$NON-NLS-1$
if (backup)
if (outputFile.exists()) {
File dest = Utils.getSimpleDataFormattedFile(outputFile);
if (!outputFile.renameTo(dest))
throw new IOException(NLS.bind(Messages.exception_failedToRename, outputFile, dest));
Log.log(LogService.LOG_INFO, this, "saveFwConfig()", NLS.bind(Messages.log_renameSuccessful, outputFile, dest)); //$NON-NLS-1$
}
FileOutputStream out = null;
try {
out = new FileOutputStream(outputFile);
// configProps = makeRelative(configProps, launcherData.getLauncher().getParentFile().toURI(), fwJar, outputFile.getParentFile(), getOSGiInstallArea(manipulator.getLauncherData()));
filterPropertiesFromSharedArea(configProps, manipulator);
configProps.store(out, header);
Log.log(LogService.LOG_INFO, NLS.bind(Messages.log_fwConfigSave, outputFile));
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
out = null;
}
}
private void filterPropertiesFromSharedArea(Properties configProps, Manipulator manipulator) {
LauncherData launcherData = manipulator.getLauncherData();
//Remove from the config file that we are about to write the properties that are unchanged compared to what is in the base
Properties sharedConfigProperties = getSharedConfiguration(configProps.getProperty(EquinoxConstants.PROP_SHARED_CONFIGURATION_AREA), ParserUtils.getOSGiInstallArea(Arrays.asList(launcherData.getProgramArgs()), configProps, launcherData));
if (sharedConfigProperties == null)
return;
Enumeration keys = configProps.propertyNames();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
String sharedValue = sharedConfigProperties.getProperty(key);
if (sharedValue == null)
continue;
String value = configProps.getProperty(key);
if (equalsIgnoringSeparators(sharedValue, value)) {
configProps.remove(key);
continue;
}
if (key.equals(EquinoxConstants.PROP_BUNDLES) && equalBundleLists(manipulator, value, sharedValue)) {
configProps.remove(key);
continue;
}
if (key.equals(EquinoxConstants.PROP_FW_EXTENSIONS) && equalBundleLists(manipulator, value, sharedValue)) {
configProps.remove(key);
continue;
}
}
}
private boolean equalBundleLists(Manipulator manipulator, String value, String sharedValue) {
BundleInfo[] bundles = parseBundleList(manipulator, value);
BundleInfo[] sharedBundles = parseBundleList(manipulator, sharedValue);
if (bundles == null || sharedBundles == null || bundles.length != sharedBundles.length)
return false;
List compareList = new ArrayList(Arrays.asList(bundles));
compareList.removeAll(Arrays.asList(sharedBundles));
return compareList.isEmpty();
}
private boolean equalsIgnoringSeparators(String s1, String s2) {
if (s1 == null && s2 == null)
return true;
if (s1 == null || s2 == null)
return false;
StringBuffer sb1 = new StringBuffer(s1);
StringBuffer sb2 = new StringBuffer(s2);
canonicalizePathsForComparison(sb1);
canonicalizePathsForComparison(sb2);
return sb1.toString().equals(sb2.toString());
}
private void canonicalizePathsForComparison(StringBuffer s) {
final String[] tokens = new String[] {"\\\\", "\\", "//", "/"}; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
for (int t = 0; t < tokens.length; t++) {
int idx = s.length();
for (int i = s.length(); i != 0 && idx != -1; i--) {
idx = s.toString().lastIndexOf(tokens[t], idx);
if (idx != -1)
s.replace(idx, idx + tokens[t].length(), "^"); //$NON-NLS-1$
}
}
}
private Properties getSharedConfiguration(String sharedConfigurationArea, File baseFile) {
if (sharedConfigurationArea == null)
return null;
File sharedConfigIni;
try {
sharedConfigIni = findSharedConfigIniFile(baseFile.toURL(), sharedConfigurationArea);
} catch (MalformedURLException e) {
return null;
}
if (sharedConfigIni != null && sharedConfigIni.exists())
try {
return loadProperties(sharedConfigIni);
} catch (FileNotFoundException e) {
return null;
} catch (IOException e) {
return null;
}
return null;
}
}
| public void saveFwConfig(BundleInfo[] bInfos, Manipulator manipulator, boolean backup, boolean relative) throws IOException {//{
ConfigData configData = manipulator.getConfigData();
LauncherData launcherData = manipulator.getLauncherData();
//Get the OSGi jar from the bundle.info
File fwJar = EquinoxBundlesState.getSystemBundleFromBundleInfos(configData);
launcherData.setFwJar(fwJar);
File outputFile = launcherData.getFwConfigLocation();
if (outputFile.exists()) {
if (outputFile.isFile()) {
if (!outputFile.getName().equals(EquinoxConstants.CONFIG_INI))
throw new IllegalStateException(NLS.bind(Messages.exception_fwConfigLocationName, outputFile.getAbsolutePath(), EquinoxConstants.CONFIG_INI));
} else { // Directory
outputFile = new File(outputFile, EquinoxConstants.CONFIG_INI);
}
} else {
if (!outputFile.getName().equals(EquinoxConstants.CONFIG_INI)) {
if (!outputFile.mkdir())
throw new IOException(NLS.bind(Messages.exception_failedToCreateDir, outputFile));
outputFile = new File(outputFile, EquinoxConstants.CONFIG_INI);
}
}
String header = "This configuration file was written by: " + this.getClass().getName(); //$NON-NLS-1$
Properties configProps = new Properties();
URI rootURI = launcherData.getLauncher() != null ? launcherData.getLauncher().getParentFile().toURI() : null;
writeFwJarLocation(configData, launcherData, configProps);
try {
writeLauncherPath(configData, configProps, rootURI);
URI configArea = manipulator.getLauncherData().getFwConfigLocation().toURI();
writep2DataArea(configData, configProps, configArea);
writeSimpleConfiguratorURL(configData, configProps, configArea);
writeBundlesList(launcherData.getFwJar(), configProps, ParserUtils.getOSGiInstallArea(Arrays.asList(launcherData.getProgramArgs()), configProps, launcherData).toURI(), bInfos);
writeInitialStartLevel(configData, configProps);
writeDefaultStartLevel(configData, configProps);
} catch (URISyntaxException e) {
throw new FrameworkAdminRuntimeException(e, Messages.exception_errorSavingConfigIni);
}
Properties original = configData.getProperties();
original.putAll(configProps);
configProps = original;
//Deal with the fw jar and ensure it is not set.
//TODO This can't be done before because of the previous calls to appendProperties
if (configProps == null || configProps.size() == 0) {
Log.log(LogService.LOG_WARNING, this, "saveFwConfig() ", Messages.log_configProps); //$NON-NLS-1$
return;
}
if (!Utils.createParentDir(outputFile)) {
throw new IllegalStateException(NLS.bind(Messages.exception_failedToCreateDir, outputFile.getParent()));
}
if (DEBUG)
Utils.printoutProperties(System.out, "configProps", configProps); //$NON-NLS-1$
if (backup)
if (outputFile.exists()) {
File dest = Utils.getSimpleDataFormattedFile(outputFile);
if (!outputFile.renameTo(dest))
throw new IOException(NLS.bind(Messages.exception_failedToRename, outputFile, dest));
Log.log(LogService.LOG_INFO, this, "saveFwConfig()", NLS.bind(Messages.log_renameSuccessful, outputFile, dest)); //$NON-NLS-1$
}
FileOutputStream out = null;
try {
out = new FileOutputStream(outputFile);
// configProps = makeRelative(configProps, launcherData.getLauncher().getParentFile().toURI(), fwJar, outputFile.getParentFile(), getOSGiInstallArea(manipulator.getLauncherData()));
filterPropertiesFromSharedArea(configProps, manipulator);
configProps.store(out, header);
Log.log(LogService.LOG_INFO, NLS.bind(Messages.log_fwConfigSave, outputFile));
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
out = null;
}
}
private void filterPropertiesFromSharedArea(Properties configProps, Manipulator manipulator) {
LauncherData launcherData = manipulator.getLauncherData();
//Remove from the config file that we are about to write the properties that are unchanged compared to what is in the base
Properties sharedConfigProperties = getSharedConfiguration(configProps.getProperty(EquinoxConstants.PROP_SHARED_CONFIGURATION_AREA), ParserUtils.getOSGiInstallArea(Arrays.asList(launcherData.getProgramArgs()), configProps, launcherData));
if (sharedConfigProperties == null)
return;
Enumeration keys = configProps.propertyNames();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
String sharedValue = sharedConfigProperties.getProperty(key);
if (sharedValue == null)
continue;
String value = configProps.getProperty(key);
if (equalsIgnoringSeparators(sharedValue, value)) {
configProps.remove(key);
continue;
}
if (key.equals(EquinoxConstants.PROP_BUNDLES) && equalBundleLists(manipulator, value, sharedValue)) {
configProps.remove(key);
continue;
}
if (key.equals(EquinoxConstants.PROP_FW_EXTENSIONS) && equalBundleLists(manipulator, value, sharedValue)) {
configProps.remove(key);
continue;
}
}
}
private boolean equalBundleLists(Manipulator manipulator, String value, String sharedValue) {
BundleInfo[] bundles = parseBundleList(manipulator, value);
BundleInfo[] sharedBundles = parseBundleList(manipulator, sharedValue);
if (bundles == null || sharedBundles == null || bundles.length != sharedBundles.length)
return false;
List compareList = new ArrayList(Arrays.asList(bundles));
compareList.removeAll(Arrays.asList(sharedBundles));
return compareList.isEmpty();
}
private boolean equalsIgnoringSeparators(String s1, String s2) {
if (s1 == null && s2 == null)
return true;
if (s1 == null || s2 == null)
return false;
StringBuffer sb1 = new StringBuffer(s1);
StringBuffer sb2 = new StringBuffer(s2);
canonicalizePathsForComparison(sb1);
canonicalizePathsForComparison(sb2);
return sb1.toString().equals(sb2.toString());
}
private void canonicalizePathsForComparison(StringBuffer s) {
final String[] tokens = new String[] {"\\\\", "\\", "//", "/"}; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
for (int t = 0; t < tokens.length; t++) {
int idx = s.length();
for (int i = s.length(); i != 0 && idx != -1; i--) {
idx = s.toString().lastIndexOf(tokens[t], idx);
if (idx != -1)
s.replace(idx, idx + tokens[t].length(), "^"); //$NON-NLS-1$
}
}
}
private Properties getSharedConfiguration(String sharedConfigurationArea, File baseFile) {
if (sharedConfigurationArea == null)
return null;
File sharedConfigIni;
try {
sharedConfigIni = findSharedConfigIniFile(baseFile.toURL(), sharedConfigurationArea);
} catch (MalformedURLException e) {
return null;
}
if (sharedConfigIni != null && sharedConfigIni.exists())
try {
return loadProperties(sharedConfigIni);
} catch (FileNotFoundException e) {
return null;
} catch (IOException e) {
return null;
}
return null;
}
}
|
diff --git a/acs/tabbychat/core/GuiChatTC.java b/acs/tabbychat/core/GuiChatTC.java
index 245ca66..7b4d4ea 100755
--- a/acs/tabbychat/core/GuiChatTC.java
+++ b/acs/tabbychat/core/GuiChatTC.java
@@ -1,699 +1,699 @@
package acs.tabbychat.core;
import java.awt.Rectangle;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
import acs.tabbychat.compat.EmoticonsCompat;
import acs.tabbychat.compat.MacroKeybindCompat;
import acs.tabbychat.gui.ChatBox;
import acs.tabbychat.gui.ChatButton;
import acs.tabbychat.gui.ChatChannelGUI;
import acs.tabbychat.gui.ChatScrollBar;
import acs.tabbychat.gui.PrefsButton;
import acs.tabbychat.util.TabbyChatUtils;
import net.minecraft.src.Minecraft;
import net.minecraft.src.ChatClickData;
import net.minecraft.src.GuiButton;
import net.minecraft.src.GuiChat;
import net.minecraft.src.GuiConfirmOpenLink;
import net.minecraft.src.GuiScreen;
import net.minecraft.src.GuiTextField;
import net.minecraft.src.NetClientHandler;
import net.minecraft.src.Packet19EntityAction;
import net.minecraft.src.Packet203AutoComplete;
import net.minecraft.src.ScaledResolution;
import net.minecraft.src.StatCollector;
import net.minecraft.src.StringTranslate;
public class GuiChatTC extends GuiChat {
public String historyBuffer = "";
public String defaultInputFieldText = "";
public int sentHistoryCursor2 = -1;
private boolean playerNamesFound = false;
private boolean waitingOnPlayerNames = false;
private int playerNameIndex = 0;
private List foundPlayerNames = new ArrayList();
private URI clickedURI2 = null;
public GuiTextField inputField2;
public List<GuiTextField> inputList = new ArrayList<GuiTextField>(3);
public ChatScrollBar scrollBar;
public GuiButton selectedButton2 = null;
public int eventButton2 = 0;
public long field_85043_c2 = 0L;
public int field_92018_d2 = 0;
public float zLevel2 = 0.0F;
private static ScaledResolution sr;
public TabbyChat tc;
public GuiNewChatTC gnc;
public GuiChatTC() {
super();
this.mc = Minecraft.getMinecraft();
sr = new ScaledResolution(mc.gameSettings, mc.displayWidth, mc.displayHeight);
this.fontRenderer = this.mc.fontRenderer;
this.gnc = GuiNewChatTC.getInstance();
this.tc = this.gnc.tc;
EmoticonsCompat.load();
MacroKeybindCompat.load();
}
public GuiChatTC(String par1Str) {
this();
this.defaultInputFieldText = par1Str;
}
public void actionPerformed(GuiButton par1GuiButton) {
// Attempt Emoticons actionPerformed if present
EmoticonsCompat.actionPerformed(par1GuiButton, this.buttonList, this.inputField2);
if(par1GuiButton instanceof PrefsButton && par1GuiButton.id == 1) this.playerWakeUp();
if(!ChatButton.class.isInstance(par1GuiButton)) return;
ChatButton _button = (ChatButton)par1GuiButton;
if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) && tc.channelMap.get("*") == _button.channel) {
this.mc.displayGuiScreen(TabbyChat.generalSettings);
return;
}
if (!this.tc.enabled()) return;
if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
this.buttonList.remove(_button);
this.tc.channelMap.remove(_button.channel.getTitle());
} else if (Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)) {
if (!_button.channel.active) {
this.gnc.mergeChatLines(_button.channel);
_button.channel.unread = false;
}
_button.channel.active = !_button.channel.active;
if (!_button.channel.active)
this.tc.resetDisplayedChat();
} else {
List<String> preActiveTabs = this.tc.getActive();
for (ChatChannel chan : this.tc.channelMap.values()) {
if (!_button.equals(chan.tab))
chan.active = false;
}
if (!_button.channel.active) {
this.scrollBar.scrollBarMouseWheel();
if(preActiveTabs.size() == 1) {
this.checkCommandPrefixChange(this.tc.channelMap.get(preActiveTabs.get(0)), _button.channel);
} else {
_button.channel.active = true;
_button.channel.unread = false;
}
}
this.tc.resetDisplayedChat();
}
}
public void checkCommandPrefixChange(ChatChannel oldChan, ChatChannel newChan) {
String oldPrefix = oldChan.cmdPrefix.trim();
if(this.inputField2.getText().trim().equals(oldPrefix)) {
String newPrefix = newChan.cmdPrefix.trim();
if(newPrefix.length() > 0) this.inputField2.setText(newPrefix + " ");
else this.inputField2.setText("");
}
oldChan.active = false;
newChan.active = true;
newChan.unread = false;
}
public @Override void completePlayerName() {
String textBuffer;
if(this.playerNamesFound) {
this.inputField2.deleteFromCursor(this.inputField2.func_73798_a(-1, this.inputField2.getCursorPosition(), false) - this.inputField2.getCursorPosition());
if(this.playerNameIndex >= this.foundPlayerNames.size()) {
this.playerNameIndex = 0;
}
} else {
int prevWordIndex = this.inputField2.func_73798_a(-1, this.inputField2.getCursorPosition(), false);
this.foundPlayerNames.clear();
this.playerNameIndex = 0;
String nameStart = this.inputField2.getText().substring(prevWordIndex).toLowerCase();
textBuffer = this.inputField2.getText().substring(0, this.inputField2.getCursorPosition());
this.func_73893_a(textBuffer, nameStart);
if(this.foundPlayerNames.isEmpty()) {
return;
}
this.playerNamesFound = true;
this.inputField2.deleteFromCursor(prevWordIndex - this.inputField2.getCursorPosition());
}
if(this.foundPlayerNames.size() > 1) {
StringBuilder _sb = new StringBuilder();
for(Iterator _iter = this.foundPlayerNames.iterator(); _iter.hasNext(); _sb.append(textBuffer)) {
textBuffer = (String)_iter.next();
if(_sb.length() > 0) {
_sb.append(", ");
}
}
this.mc.ingameGUI.getChatGUI().printChatMessageWithOptionalDeletion(_sb.toString(), 1);
}
this.inputField2.writeText((String)this.foundPlayerNames.get(this.playerNameIndex++));
}
public @Override void confirmClicked(boolean zeroId, int worldNum) {
if(worldNum == 0) {
if(zeroId) this.func_73896_a(this.clickedURI2);
this.clickedURI2 = null;
this.mc.displayGuiScreen(this);
}
}
public @Override void drawScreen(int cursorX, int cursorY, float pointless) {
if (this.tc.enabled() && TabbyChat.advancedSettings.forceUnicode.getValue()) this.fontRenderer.setUnicodeFlag(true);
sr = new ScaledResolution(mc.gameSettings, mc.displayWidth, mc.displayHeight);
this.width = sr.getScaledWidth();
this.height = sr.getScaledHeight();
// Calculate positions of currently-visible input fields
int inputHeight = 0;
for(int i=0; i<this.inputList.size(); i++) {
if(this.inputList.get(i).getVisible()) inputHeight += 12;
}
// Draw text fields and background
int bgWidth = (MacroKeybindCompat.present) ? this.width - 24 : this.width - 2;
drawRect(2, this.height-2-inputHeight, bgWidth, this.height-2, Integer.MIN_VALUE);
for(GuiTextField field : this.inputList) {
if(field.getVisible()) field.drawTextBox();
}
// Draw current message length indicator
if(this.tc.enabled()) {
String requiredSends = ((Integer)this.getCurrentSends()).toString();
int sendsX = sr.getScaledWidth() - 12;
if(MacroKeybindCompat.present) sendsX -= 22;
this.fontRenderer.drawStringWithShadow(requiredSends, sendsX, this.height-inputHeight, 0x707070);
}
// Update chat tabs (add to buttonlist)
ChatBox.updateTabs(this.tc.channelMap);
// Determine appropriate scaling for chat tab size and location
float scaleSetting = this.gnc.getScaleSetting();
GL11.glPushMatrix();
float scaleOffsetX = ChatBox.current.x * (1.0f - scaleSetting);
float scaleOffsetY = (this.gnc.sr.getScaledHeight() + ChatBox.current.y) * (1.0f - scaleSetting);
GL11.glTranslatef(scaleOffsetX, scaleOffsetY, 1.0f);
GL11.glScalef(scaleSetting, scaleSetting, 1.0f);
// Draw chat tabs
GuiButton _button;
for(int i=0; i<this.buttonList.size(); i++) {
_button = (GuiButton)this.buttonList.get(i);
if(_button instanceof PrefsButton && _button.id == 1) {
if(mc.thePlayer != null && !mc.thePlayer.isPlayerSleeping()) {
this.buttonList.remove(_button);
continue;
}
}
_button.drawButton(this.mc, cursorX, cursorY);
}
GL11.glPopMatrix();
this.fontRenderer.setUnicodeFlag(TabbyChat.defaultUnicode);
// Attempt Macro/Keybind drawScreen if present
MacroKeybindCompat.drawScreen(cursorX, cursorY, this);
// Attempt Emoticons drawScreen if present
EmoticonsCompat.drawScreen(cursorX, cursorY, pointless, this, this.buttonList);
}
public void func_73893_a(String nameStart, String buffer) {
if(nameStart.length() >= 1) {
this.mc.thePlayer.sendQueue.addToSendQueue(new Packet203AutoComplete(nameStart));
this.waitingOnPlayerNames = true;
}
}
public @Override void func_73894_a(String[] par1ArrayOfStr) {
if(this.waitingOnPlayerNames) {
this.foundPlayerNames.clear();
String[] _copy = par1ArrayOfStr;
int _len = par1ArrayOfStr.length;
for(int i=0; i<_len; ++i) {
String name = _copy[i];
if(name.length() > 0) this.foundPlayerNames.add(name);
}
if(this.foundPlayerNames.size() > 0) {
this.playerNamesFound = true;
this.completePlayerName();
}
}
}
public void func_73896_a(URI _uri) {
try {
Class desktop = Class.forName("java.awt.Desktop");
Object theDesktop = desktop.getMethod("getDesktop", new Class[0]).invoke((Object)null, new Object[0]);
desktop.getMethod("browse", new Class[]{URI.class}).invoke(theDesktop, new Object[]{_uri});
} catch (Throwable t) {
t.printStackTrace();
}
}
public int getCurrentSends() {
int lng = 0;
int _s = this.inputList.size() - 1;
for (int i=_s; i>=0; i-=1) {
lng += this.inputList.get(i).getText().length();
}
if (lng == 0)
return 0;
else
return (lng + 100 - 1) / 100;
}
public int getFocusedFieldInd() {
int _s = this.inputList.size();
for (int i=0; i<_s; i++) {
if (this.inputList.get(i).isFocused() && this.inputList.get(i).getVisible())
return i;
}
return 0;
}
public @Override void getSentHistory(int _dir) {
int loc = this.sentHistoryCursor2 + _dir;
int historyLength = this.gnc.getSentMessages().size();
loc = Math.max(0, loc);
loc = Math.min(historyLength, loc);
if(loc == this.sentHistoryCursor2) return;
if(loc == historyLength) {
this.sentHistoryCursor2 = historyLength;
this.setText(new StringBuilder(""), 1);
} else {
if(this.sentHistoryCursor2 == historyLength) this.historyBuffer = this.inputField2.getText();
StringBuilder _sb = new StringBuilder((String)this.gnc.getSentMessages().get(loc));
this.setText(_sb, _sb.length());
this.sentHistoryCursor2 = loc;
}
}
public @Override void handleMouseInput() {
// Allow chatbox dragging
if(ChatBox.resizing) {
if(!Mouse.isButtonDown(0)) ChatBox.resizing = false;
else ChatBox.handleMouseResize(Mouse.getEventX(), Mouse.getEventY());
return;
} else if(ChatBox.dragging) {
if(!Mouse.isButtonDown(0)) ChatBox.dragging = false;
else ChatBox.handleMouseDrag(Mouse.getEventX(), Mouse.getEventY());
return;
}
if(Mouse.getEventButton() == 0 && Mouse.isButtonDown(0)) {
if(ChatBox.resizeHovered() && !ChatBox.dragging) {
ChatBox.startResizing(Mouse.getEventX(), Mouse.getEventY());
} else if(ChatBox.tabTrayHovered(Mouse.getEventX(), Mouse.getEventY()) && !ChatBox.resizing) {
ChatBox.startDragging(Mouse.getEventX(), Mouse.getEventY());
}
}
int wheelDelta = Mouse.getEventDWheel();
if(wheelDelta != 0) {
wheelDelta = Math.min(1, wheelDelta);
wheelDelta = Math.max(-1, wheelDelta);
if(!isShiftKeyDown()) wheelDelta *= 7;
if(ChatBox.anchoredTop) this.gnc.scroll(-wheelDelta);
else this.gnc.scroll(wheelDelta);
if(this.tc.enabled()) this.scrollBar.scrollBarMouseWheel();
} else if(this.tc.enabled()) this.scrollBar.handleMouse();
if(mc.currentScreen.getClass() != GuiChat.class) super.handleMouseInput();
}
public @Override void initGui() {
Keyboard.enableRepeatEvents(true);
this.buttonList.clear();
this.inputList.clear();
sr = new ScaledResolution(mc.gameSettings, mc.displayWidth, mc.displayHeight);
this.width = sr.getScaledWidth();
this.height = sr.getScaledHeight();
this.tc.checkServer();
if(this.tc.enabled()) {
if(this.scrollBar == null) this.scrollBar = new ChatScrollBar();
for(ChatChannel chan : this.tc.channelMap.values()) {
this.buttonList.add(chan.tab);
}
} else {
this.buttonList.add(this.tc.channelMap.get("*").tab);
}
this.sentHistoryCursor2 = this.gnc.getSentMessages().size();
int textFieldWidth = (MacroKeybindCompat.present) ? this.width - 26 : this.width - 4;
this.inputField2 = new GuiTextField(this.fontRenderer, 4, this.height - 12, textFieldWidth, 12);
this.inputField2.setMaxStringLength(500);
this.inputField2.setEnableBackgroundDrawing(false);
this.inputField2.setFocused(true);
this.inputField2.setText(this.defaultInputFieldText);
this.inputField2.setCanLoseFocus(true);
this.inputList.add(0, this.inputField2);
if(!tc.enabled()) return;
GuiTextField placeholder;
for(int i=1; i<3; i++) {
placeholder = new GuiTextField(this.fontRenderer, 4, this.height - 12*(i+1), textFieldWidth, 12);
placeholder.setMaxStringLength(500);
placeholder.setEnableBackgroundDrawing(false);
placeholder.setFocused(false);
placeholder.setText("");
placeholder.setCanLoseFocus(true);
placeholder.setVisible(false);
this.inputList.add(i,placeholder);
}
if(this.tc.enabled()) {
List<String> activeTabs = this.tc.getActive();
if(activeTabs.size() != 1) {
this.inputField2.setText("");
} else {
String thePrefix = this.tc.channelMap.get(activeTabs.get(0)).cmdPrefix.trim();
boolean prefixHidden = this.tc.channelMap.get(activeTabs.get(0)).hidePrefix;
if(thePrefix.length() > 0 && !prefixHidden) this.inputField2.setText(this.tc.channelMap.get(activeTabs.get(0)).cmdPrefix.trim() + " ");
}
ChatBox.enforceScreenBoundary(ChatBox.current);
}
if(mc.thePlayer != null && mc.theWorld != null && mc.thePlayer.isPlayerSleeping()) {
PrefsButton leaveBed = new PrefsButton(1, this.width/2 - 100, this.height - 50, 200, 14, StatCollector.translateToLocal("multiplayer.stopSleeping"), 0x55ffffff);
this.buttonList.add(leaveBed);
}
// Initialize Emoticons screen if present
EmoticonsCompat.initGui(this.buttonList);
}
public void insertCharsAtCursor(String _chars) {
StringBuilder msg = new StringBuilder();
int cPos = 0;
boolean cFound = false;
for (int i=this.inputList.size()-1; i>=0; i--) {
msg.append(this.inputList.get(i).getText());
if (this.inputList.get(i).isFocused()) {
cPos += this.inputList.get(i).getCursorPosition();
cFound = true;
} else if (!cFound) {
cPos += this.inputList.get(i).getText().length();
}
}
if (this.fontRenderer.getStringWidth(msg.toString()) + this.fontRenderer.getStringWidth(_chars) < (sr.getScaledWidth()-20)*this.inputList.size()) {
msg.insert(cPos, _chars);
this.setText(msg, cPos+_chars.length());
}
}
public @Override void keyTyped(char _char, int _code) {
this.waitingOnPlayerNames = false;
if(_code != Keyboard.KEY_TAB) this.playerNamesFound = false;
switch (_code) {
// TAB: execute vanilla name completion
case Keyboard.KEY_TAB:
if(GuiScreen.isCtrlKeyDown()) {
// CTRL+SHIFT+TAB: switch active tab to previous
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
tc.activatePrev();
// CTRL+TAB: switch active tab to next
} else tc.activateNext();
break;
}
this.completePlayerName();
break;
// ESCAPE: close the chat interface
case Keyboard.KEY_ESCAPE:
this.mc.displayGuiScreen((GuiScreen)null);
break;
// RETURN: send chat to server
case Keyboard.KEY_RETURN:
StringBuilder _msg = new StringBuilder(1500);
for(int i=this.inputList.size()-1; i>=0; i--) _msg.append(this.inputList.get(i).getText());
if(_msg.toString().length() > 0) {
List<String> activeTabs = this.tc.getActive();
boolean prefixHidden = this.tc.channelMap.get(activeTabs.get(0)).hidePrefix;
- String thePrefix = this.tc.channelMap.get(activeTabs.get(0)).cmdPrefix.trim();
+ String thePrefix = this.tc.channelMap.get(activeTabs.get(0)).cmdPrefix;
if(!thePrefix.equals("") && prefixHidden && !_msg.substring(0,1).equals("/")) {
_msg.insert(0, thePrefix);
}
TabbyChatUtils.writeLargeChat(_msg.toString());
for(int i=1; i<this.inputList.size(); i++) {
this.inputList.get(i).setText("");
this.inputList.get(i).setVisible(false);
}
}
this.mc.displayGuiScreen((GuiScreen)null);
break;
// UP: if currently in multi-line chat, move into the above textbox. Otherwise, go back one in the sent history (forced by Ctrl)
case Keyboard.KEY_UP:
if(GuiScreen.isCtrlKeyDown()) this.getSentHistory(-1);
else {
int foc = this.getFocusedFieldInd();
if(foc+1 < this.inputList.size() && this.inputList.get(foc+1).getVisible()) {
int gcp = this.inputList.get(foc).getCursorPosition();
int lng = this.inputList.get(foc+1).getText().length();
int newPos = Math.min(gcp, lng);
this.inputList.get(foc).setFocused(false);
this.inputList.get(foc+1).setFocused(true);
this.inputList.get(foc+1).setCursorPosition(newPos);
} else this.getSentHistory(-1);
}
break;
// DOWN: if currently in multi-line chat, move into the below textbox. Otherwise, go forward one in the sent history (force by Ctrl)
case Keyboard.KEY_DOWN:
if(GuiScreen.isCtrlKeyDown()) this.getSentHistory(1);
else {
int foc = this.getFocusedFieldInd();
if(foc-1 >= 0 && this.inputList.get(foc-1).getVisible()) {
int gcp = this.inputList.get(foc).getCursorPosition();
int lng = this.inputList.get(foc-1).getText().length();
int newPos = Math.min(gcp, lng);
this.inputList.get(foc).setFocused(false);
this.inputList.get(foc-1).setFocused(true);
this.inputList.get(foc-1).setCursorPosition(newPos);
} else this.getSentHistory(1);
}
break;
// PAGE UP: scroll up through chat
case Keyboard.KEY_PRIOR:
this.gnc.scroll(19);
if(this.tc.enabled()) this.scrollBar.scrollBarMouseWheel();
break;
// PAGE DOWN: scroll down through chat
case Keyboard.KEY_NEXT:
this.gnc.scroll(-19);
if(this.tc.enabled()) this.scrollBar.scrollBarMouseWheel();
break;
// BACKSPACE: delete previous character, minding potential contents of other input fields
case Keyboard.KEY_BACK:
if(this.inputField2.isFocused() && this.inputField2.getCursorPosition() > 0) this.inputField2.textboxKeyTyped(_char, _code);
else this.removeCharsAtCursor(-1);
break;
// DELETE: delete next character, minding potential contents of other input fields
case Keyboard.KEY_DELETE:
if(this.inputField2.isFocused()) this.inputField2.textboxKeyTyped(_char, _code);
else this.removeCharsAtCursor(1);
break;
// LEFT/RIGHT: move the cursor
case Keyboard.KEY_LEFT:
case Keyboard.KEY_RIGHT:
this.inputList.get(this.getFocusedFieldInd()).textboxKeyTyped(_char, _code);
break;
default:
// CTRL + NUM1-9: Make the numbered tab active
if(GuiScreen.isCtrlKeyDown() && !Keyboard.isKeyDown(Keyboard.KEY_LMENU) && !Keyboard.isKeyDown(Keyboard.KEY_RMENU)) {
if(_code > 1 && _code < 12) {
tc.activateIndex(_code-1);
// CTRL+O: open options
} else if(_code == Keyboard.KEY_O) {
this.mc.displayGuiScreen(this.tc.generalSettings);
} else {
this.inputField2.textboxKeyTyped(_char, _code);
}
// Keypress will not trigger overflow, send to default input field
} else if(this.inputField2.isFocused() && this.fontRenderer.getStringWidth(this.inputField2.getText()) < sr.getScaledWidth()-20) {
this.inputField2.textboxKeyTyped(_char, _code);
// Keypress will trigger overflow, send through helper function
} else {
this.insertCharsAtCursor(Character.toString(_char));
}
}
}
public @Override void mouseClicked(int _x, int _y, int _button) {
if(_button == 0 && this.mc.gameSettings.chatLinks) {
ChatClickData ccd = this.gnc.func_73766_a(Mouse.getX(), Mouse.getY());
if(ccd != null) {
URI url = ccd.getURI();
if(url != null) {
if(this.mc.gameSettings.chatLinksPrompt) {
this.clickedURI2 = url;
this.mc.displayGuiScreen(new GuiConfirmOpenLink(this, ccd.getClickedUrl(), 0, false));
} else this.func_73896_a(url);
return;
}
}
}
for(int i=0; i<this.inputList.size(); i++) {
if(_y>=this.height-12*(i+1) && this.inputList.get(i).getVisible()) {
this.inputList.get(i).setFocused(true);
for(GuiTextField field : this.inputList) {
if(field != this.inputList.get(i)) field.setFocused(false);
}
this.inputList.get(i).mouseClicked(_x, _y, _button);
break;
}
}
// Pass click info to Macro/Keybind mod if present
if(MacroKeybindCompat.controlClicked(_x, _y, _button, this)) return;
// Replicating GuiScreen's mouseClicked method since 'super' won't work
for(GuiButton _guibutton : (List<GuiButton>)this.buttonList) {
if(ChatButton.class.isInstance(_guibutton) || _guibutton.id <= 2) {
if(_guibutton.mousePressed(this.mc, _x, _y)) {
if(_button == 0) {
this.selectedButton2 = _guibutton;
this.mc.sndManager.playSoundFX("random.click", 1.0F, 1.0F);
this.actionPerformed(_guibutton);
return;
} else if (_button == 1) {
ChatButton _cb = (ChatButton)_guibutton;
if(_cb.channel == this.tc.channelMap.get("*")) return;
this.mc.displayGuiScreen(new ChatChannelGUI(_cb.channel));
return;
}
}
} else {
if(_guibutton.mousePressed(this.mc, _x-EmoticonsCompat.emoteOffsetX, _y) && _button == 0) {
this.selectedButton2 = _guibutton;
this.mc.sndManager.playSoundFX("random.click", 1.0F, 1.0F);
this.actionPerformed(_guibutton);
return;
}
}
}
}
public @Override void mouseMovedOrUp(int _x, int _y, int _button)
{
if (this.selectedButton2 != null && _button == 0)
{
this.selectedButton2.mouseReleased(_x, _y);
this.selectedButton2 = null;
}
}
public @Override void onGuiClosed() {
ChatBox.dragging = false;
}
private void playerWakeUp() {
NetClientHandler var1 = this.mc.thePlayer.sendQueue;
var1.addToSendQueue(new Packet19EntityAction(this.mc.thePlayer, 3));
}
public void removeCharsAtCursor(int _del) {
StringBuilder msg = new StringBuilder();
int cPos = 0;
boolean cFound = false;
for (int i=this.inputList.size()-1; i>=0; i--) {
msg.append(this.inputList.get(i).getText());
if (this.inputList.get(i).isFocused()) {
cPos += this.inputList.get(i).getCursorPosition();
cFound = true;
} else if (!cFound) {
cPos += this.inputList.get(i).getText().length();
}
}
int other = cPos + _del;
other = Math.min(msg.length()-1, other);
other = Math.max(0, other);
if (other < cPos) {
msg.replace(other, cPos, "");
this.setText(msg, other);
} else if (other > cPos) {
msg.replace(cPos, other, "");
this.setText(msg, cPos);
} else
return;
}
public void setText(StringBuilder txt, int pos) {
List<String> txtList = this.stringListByWidth(txt, sr.getScaledWidth()-20);
int strings = Math.min(txtList.size()-1, this.inputList.size()-1);
for (int i=strings; i>=0; i--) {
this.inputList.get(i).setText(txtList.get(strings-i));
if (pos > txtList.get(strings-i).length()) {
pos -= txtList.get(strings-i).length();
this.inputList.get(i).setVisible(true);
this.inputList.get(i).setFocused(false);
} else if (pos >= 0) {
this.inputList.get(i).setFocused(true);
this.inputList.get(i).setVisible(true);
this.inputList.get(i).setCursorPosition(pos);
pos = -1;
} else {
this.inputList.get(i).setVisible(true);
this.inputList.get(i).setFocused(false);
}
}
if (pos > 0) {
this.inputField2.setCursorPositionEnd();
}
if (this.inputList.size() > txtList.size()) {
for (int j=txtList.size(); j<this.inputList.size(); j++) {
this.inputList.get(j).setText("");
this.inputList.get(j).setFocused(false);
this.inputList.get(j).setVisible(false);
}
}
if (!this.inputField2.getVisible()) {
this.inputField2.setVisible(true);
this.inputField2.setFocused(true);
}
}
public List<String> stringListByWidth(StringBuilder _sb, int _w) {
List<String> result = new ArrayList<String>(5);
int _len = 0;
int _cw;
StringBuilder bucket = new StringBuilder(_sb.length());
for (int ind=0; ind<_sb.length(); ind++) {
_cw = this.fontRenderer.getCharWidth(_sb.charAt(ind));
if (_len + _cw > _w) {
result.add(bucket.toString());
bucket = new StringBuilder(_sb.length());
_len = 0;
}
_len += _cw;
bucket.append(_sb.charAt(ind));
}
if (bucket.length() > 0)
result.add(bucket.toString());
return result;
}
public @Override void updateScreen() {
this.inputField2.updateCursorCounter();
}
}
| true | true | public @Override void keyTyped(char _char, int _code) {
this.waitingOnPlayerNames = false;
if(_code != Keyboard.KEY_TAB) this.playerNamesFound = false;
switch (_code) {
// TAB: execute vanilla name completion
case Keyboard.KEY_TAB:
if(GuiScreen.isCtrlKeyDown()) {
// CTRL+SHIFT+TAB: switch active tab to previous
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
tc.activatePrev();
// CTRL+TAB: switch active tab to next
} else tc.activateNext();
break;
}
this.completePlayerName();
break;
// ESCAPE: close the chat interface
case Keyboard.KEY_ESCAPE:
this.mc.displayGuiScreen((GuiScreen)null);
break;
// RETURN: send chat to server
case Keyboard.KEY_RETURN:
StringBuilder _msg = new StringBuilder(1500);
for(int i=this.inputList.size()-1; i>=0; i--) _msg.append(this.inputList.get(i).getText());
if(_msg.toString().length() > 0) {
List<String> activeTabs = this.tc.getActive();
boolean prefixHidden = this.tc.channelMap.get(activeTabs.get(0)).hidePrefix;
String thePrefix = this.tc.channelMap.get(activeTabs.get(0)).cmdPrefix.trim();
if(!thePrefix.equals("") && prefixHidden && !_msg.substring(0,1).equals("/")) {
_msg.insert(0, thePrefix);
}
TabbyChatUtils.writeLargeChat(_msg.toString());
for(int i=1; i<this.inputList.size(); i++) {
this.inputList.get(i).setText("");
this.inputList.get(i).setVisible(false);
}
}
this.mc.displayGuiScreen((GuiScreen)null);
break;
// UP: if currently in multi-line chat, move into the above textbox. Otherwise, go back one in the sent history (forced by Ctrl)
case Keyboard.KEY_UP:
if(GuiScreen.isCtrlKeyDown()) this.getSentHistory(-1);
else {
int foc = this.getFocusedFieldInd();
if(foc+1 < this.inputList.size() && this.inputList.get(foc+1).getVisible()) {
int gcp = this.inputList.get(foc).getCursorPosition();
int lng = this.inputList.get(foc+1).getText().length();
int newPos = Math.min(gcp, lng);
this.inputList.get(foc).setFocused(false);
this.inputList.get(foc+1).setFocused(true);
this.inputList.get(foc+1).setCursorPosition(newPos);
} else this.getSentHistory(-1);
}
break;
// DOWN: if currently in multi-line chat, move into the below textbox. Otherwise, go forward one in the sent history (force by Ctrl)
case Keyboard.KEY_DOWN:
if(GuiScreen.isCtrlKeyDown()) this.getSentHistory(1);
else {
int foc = this.getFocusedFieldInd();
if(foc-1 >= 0 && this.inputList.get(foc-1).getVisible()) {
int gcp = this.inputList.get(foc).getCursorPosition();
int lng = this.inputList.get(foc-1).getText().length();
int newPos = Math.min(gcp, lng);
this.inputList.get(foc).setFocused(false);
this.inputList.get(foc-1).setFocused(true);
this.inputList.get(foc-1).setCursorPosition(newPos);
} else this.getSentHistory(1);
}
break;
// PAGE UP: scroll up through chat
case Keyboard.KEY_PRIOR:
this.gnc.scroll(19);
if(this.tc.enabled()) this.scrollBar.scrollBarMouseWheel();
break;
// PAGE DOWN: scroll down through chat
case Keyboard.KEY_NEXT:
this.gnc.scroll(-19);
if(this.tc.enabled()) this.scrollBar.scrollBarMouseWheel();
break;
// BACKSPACE: delete previous character, minding potential contents of other input fields
case Keyboard.KEY_BACK:
if(this.inputField2.isFocused() && this.inputField2.getCursorPosition() > 0) this.inputField2.textboxKeyTyped(_char, _code);
else this.removeCharsAtCursor(-1);
break;
// DELETE: delete next character, minding potential contents of other input fields
case Keyboard.KEY_DELETE:
if(this.inputField2.isFocused()) this.inputField2.textboxKeyTyped(_char, _code);
else this.removeCharsAtCursor(1);
break;
// LEFT/RIGHT: move the cursor
case Keyboard.KEY_LEFT:
case Keyboard.KEY_RIGHT:
this.inputList.get(this.getFocusedFieldInd()).textboxKeyTyped(_char, _code);
break;
default:
// CTRL + NUM1-9: Make the numbered tab active
if(GuiScreen.isCtrlKeyDown() && !Keyboard.isKeyDown(Keyboard.KEY_LMENU) && !Keyboard.isKeyDown(Keyboard.KEY_RMENU)) {
if(_code > 1 && _code < 12) {
tc.activateIndex(_code-1);
// CTRL+O: open options
} else if(_code == Keyboard.KEY_O) {
this.mc.displayGuiScreen(this.tc.generalSettings);
} else {
this.inputField2.textboxKeyTyped(_char, _code);
}
// Keypress will not trigger overflow, send to default input field
} else if(this.inputField2.isFocused() && this.fontRenderer.getStringWidth(this.inputField2.getText()) < sr.getScaledWidth()-20) {
this.inputField2.textboxKeyTyped(_char, _code);
// Keypress will trigger overflow, send through helper function
} else {
this.insertCharsAtCursor(Character.toString(_char));
}
}
}
| public @Override void keyTyped(char _char, int _code) {
this.waitingOnPlayerNames = false;
if(_code != Keyboard.KEY_TAB) this.playerNamesFound = false;
switch (_code) {
// TAB: execute vanilla name completion
case Keyboard.KEY_TAB:
if(GuiScreen.isCtrlKeyDown()) {
// CTRL+SHIFT+TAB: switch active tab to previous
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
tc.activatePrev();
// CTRL+TAB: switch active tab to next
} else tc.activateNext();
break;
}
this.completePlayerName();
break;
// ESCAPE: close the chat interface
case Keyboard.KEY_ESCAPE:
this.mc.displayGuiScreen((GuiScreen)null);
break;
// RETURN: send chat to server
case Keyboard.KEY_RETURN:
StringBuilder _msg = new StringBuilder(1500);
for(int i=this.inputList.size()-1; i>=0; i--) _msg.append(this.inputList.get(i).getText());
if(_msg.toString().length() > 0) {
List<String> activeTabs = this.tc.getActive();
boolean prefixHidden = this.tc.channelMap.get(activeTabs.get(0)).hidePrefix;
String thePrefix = this.tc.channelMap.get(activeTabs.get(0)).cmdPrefix;
if(!thePrefix.equals("") && prefixHidden && !_msg.substring(0,1).equals("/")) {
_msg.insert(0, thePrefix);
}
TabbyChatUtils.writeLargeChat(_msg.toString());
for(int i=1; i<this.inputList.size(); i++) {
this.inputList.get(i).setText("");
this.inputList.get(i).setVisible(false);
}
}
this.mc.displayGuiScreen((GuiScreen)null);
break;
// UP: if currently in multi-line chat, move into the above textbox. Otherwise, go back one in the sent history (forced by Ctrl)
case Keyboard.KEY_UP:
if(GuiScreen.isCtrlKeyDown()) this.getSentHistory(-1);
else {
int foc = this.getFocusedFieldInd();
if(foc+1 < this.inputList.size() && this.inputList.get(foc+1).getVisible()) {
int gcp = this.inputList.get(foc).getCursorPosition();
int lng = this.inputList.get(foc+1).getText().length();
int newPos = Math.min(gcp, lng);
this.inputList.get(foc).setFocused(false);
this.inputList.get(foc+1).setFocused(true);
this.inputList.get(foc+1).setCursorPosition(newPos);
} else this.getSentHistory(-1);
}
break;
// DOWN: if currently in multi-line chat, move into the below textbox. Otherwise, go forward one in the sent history (force by Ctrl)
case Keyboard.KEY_DOWN:
if(GuiScreen.isCtrlKeyDown()) this.getSentHistory(1);
else {
int foc = this.getFocusedFieldInd();
if(foc-1 >= 0 && this.inputList.get(foc-1).getVisible()) {
int gcp = this.inputList.get(foc).getCursorPosition();
int lng = this.inputList.get(foc-1).getText().length();
int newPos = Math.min(gcp, lng);
this.inputList.get(foc).setFocused(false);
this.inputList.get(foc-1).setFocused(true);
this.inputList.get(foc-1).setCursorPosition(newPos);
} else this.getSentHistory(1);
}
break;
// PAGE UP: scroll up through chat
case Keyboard.KEY_PRIOR:
this.gnc.scroll(19);
if(this.tc.enabled()) this.scrollBar.scrollBarMouseWheel();
break;
// PAGE DOWN: scroll down through chat
case Keyboard.KEY_NEXT:
this.gnc.scroll(-19);
if(this.tc.enabled()) this.scrollBar.scrollBarMouseWheel();
break;
// BACKSPACE: delete previous character, minding potential contents of other input fields
case Keyboard.KEY_BACK:
if(this.inputField2.isFocused() && this.inputField2.getCursorPosition() > 0) this.inputField2.textboxKeyTyped(_char, _code);
else this.removeCharsAtCursor(-1);
break;
// DELETE: delete next character, minding potential contents of other input fields
case Keyboard.KEY_DELETE:
if(this.inputField2.isFocused()) this.inputField2.textboxKeyTyped(_char, _code);
else this.removeCharsAtCursor(1);
break;
// LEFT/RIGHT: move the cursor
case Keyboard.KEY_LEFT:
case Keyboard.KEY_RIGHT:
this.inputList.get(this.getFocusedFieldInd()).textboxKeyTyped(_char, _code);
break;
default:
// CTRL + NUM1-9: Make the numbered tab active
if(GuiScreen.isCtrlKeyDown() && !Keyboard.isKeyDown(Keyboard.KEY_LMENU) && !Keyboard.isKeyDown(Keyboard.KEY_RMENU)) {
if(_code > 1 && _code < 12) {
tc.activateIndex(_code-1);
// CTRL+O: open options
} else if(_code == Keyboard.KEY_O) {
this.mc.displayGuiScreen(this.tc.generalSettings);
} else {
this.inputField2.textboxKeyTyped(_char, _code);
}
// Keypress will not trigger overflow, send to default input field
} else if(this.inputField2.isFocused() && this.fontRenderer.getStringWidth(this.inputField2.getText()) < sr.getScaledWidth()-20) {
this.inputField2.textboxKeyTyped(_char, _code);
// Keypress will trigger overflow, send through helper function
} else {
this.insertCharsAtCursor(Character.toString(_char));
}
}
}
|
diff --git a/Android/SpaceMerchant/src/edu/gatech/cs2340/group29/spacemerchant/util/GameDataSource.java b/Android/SpaceMerchant/src/edu/gatech/cs2340/group29/spacemerchant/util/GameDataSource.java
index 38527d5..64bed04 100644
--- a/Android/SpaceMerchant/src/edu/gatech/cs2340/group29/spacemerchant/util/GameDataSource.java
+++ b/Android/SpaceMerchant/src/edu/gatech/cs2340/group29/spacemerchant/util/GameDataSource.java
@@ -1,304 +1,304 @@
/**
* @author MetaGalactic Merchants
* @version 1.0
*
*/
package edu.gatech.cs2340.group29.spacemerchant.util;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import edu.gatech.cs2340.group29.spacemerchant.model.Game;
import edu.gatech.cs2340.group29.spacemerchant.model.Planet;
import edu.gatech.cs2340.group29.spacemerchant.model.Player;
import edu.gatech.cs2340.group29.spacemerchant.model.Universe;
/**
* The Class GameDataSource.
*/
public class GameDataSource
{
private static String[] ALL_COLUMNS = { "game", "difficulty", "player" };
private static String[] ALL_PLANET_COLUMNS = { "planet", "game", "techLevel",
"resourceType", "name", "x_coord" ,
"y_coord"
};
private SQLiteDatabase database;
private DatabaseHelper databaseHelper;
private Context context;
/**
* Instantiates a new game data source.
*
* @param context the Context
*/
public GameDataSource( Context context )
{
this.context = context;
databaseHelper = new DatabaseHelper( context );
}
/**
* Open.
*
* @throws SQLiteException the sQ lite exception
*/
public void open() throws SQLiteException
{
database = databaseHelper.getWritableDatabase();
}
/**
* Close.
*/
public void close()
{
databaseHelper.close();
}
/**
* Creates the game.
*
* @param game the Game
* @return the long
*/
public long createGame( Game game )
{
Planet currentPlanet = game.getPlanet();
Universe universe = game.getUniverse();
int difficulty = game.getDifficulty();
Player player = game.getPlayer();
// insert planet into database
ContentValues values = new ContentValues();
int techLevel = currentPlanet.getTechLevel();
int resourceType = currentPlanet.getResourceType();
String name = currentPlanet.getName();
int x_coord = currentPlanet.getX();
int y_coord = currentPlanet.getY();
values.put("techLevel", techLevel);
values.put("resourceType", resourceType);
values.put("name", name);
values.put("x_coord", x_coord);
values.put("y_coord", y_coord);
long currentPlanetID = database.insert( "tb_planet", null, values );
//insert player into database
PlayerDataSource playerDataSource = new PlayerDataSource( context );
playerDataSource.open();
long playerID = playerDataSource.createPlayer( player );
playerDataSource.close();
//insert game into database
values = new ContentValues();
values.put( "player", playerID );
values.put( "difficulty", difficulty );
values.put( "planet", currentPlanetID );
long gameID = database.insert( "tb_game", null, values );
game.setID( gameID );
//insert universe into database
ArrayList<Planet> universePlanets = universe.getUniverse();
for( Planet universePlanet: universePlanets )
{
values = new ContentValues();
- values.put("game", gameID);
+ values.put("game", (int)gameID);
values.put("techLevel", universePlanet.getTechLevel());
values.put("resourceType", universePlanet.getResourceType());
values.put("name", universePlanet.getName());
values.put("x_coord", universePlanet.getX());
values.put("y_coord", universePlanet.getY());
database.insert( "tb_planet", null, values );
}
return gameID;
}
/**
* Delete game.
*
* @param game the Game
*/
public void deleteGame( Game game )
{
long gameID = game.getID();
database.delete( "tb_game", "game=" + gameID, null );
}
/**
* Gets the game list.
*
* @return the game list
*/
public List<Game> getGameList()
{
List<Game> games = new ArrayList<Game>();
Cursor cursor = database.query( "tb_game", ALL_COLUMNS, null, null, null, null, null );
cursor.moveToFirst();
while ( !cursor.isAfterLast() )
{
Game game = cursorToGame( cursor );
games.add( game );
cursor.moveToNext();
}
cursor.close();
return games;
}
/**
* Gets the game by id.
*
* @param gameID the long
* @return the game by id
*/
public Game getGameByID( long gameID )
{
Cursor cursor = database.query( "tb_game", ALL_COLUMNS, "game=" + gameID, null, null, null, null );
cursor.moveToFirst();
Game game = cursorToGame( cursor );
cursor.close();
return game;
}
/**
* Gets the planet by id.
*
* @param planetID the long
* @return the planet by id
*/
public Planet getPlanetByID( long planetID )
{
Cursor cursor = database.query( "tb_planet", ALL_PLANET_COLUMNS, "planet=" + planetID, null, null, null, null );
cursor.moveToFirst();
Planet planet = cursorToPlanet( cursor );
cursor.close();
return planet;
}
/**
* Gets the planets by game id.
*
* @param gameID the long
* @return the planets by game id
*/
public ArrayList<Planet> getPlanetsByGameID( long gameID )
{
ArrayList<Planet> planets = new ArrayList<Planet>();
Cursor cursor = database.query( "tb_planet", ALL_PLANET_COLUMNS, "game=" + gameID,
null, null, null, null );
cursor.moveToFirst();
while ( !cursor.isAfterLast() )
{
Planet planet = cursorToPlanet( cursor );
planets.add( planet );
cursor.moveToNext();
}
cursor.close();
return planets;
}
/**
* Cursor to game.
*
* @param cursor the Cursor
* @return the game
*/
public Game cursorToGame( Cursor cursor )
{
int gameID = cursor.getInt(0);
int difficulty = cursor.getInt(1);
long playerID = cursor.getInt(2);
long currentPlanetID = cursor.getInt(3);
Planet currentPlanet = getPlanetByID(currentPlanetID);
Universe universe = new Universe(difficulty, context);
ArrayList<Planet> planets = getPlanetsByGameID( gameID );
universe.setUniverse(planets);
PlayerDataSource dataSource = new PlayerDataSource( context );
dataSource.open();
Player player = dataSource.getPlayerByID( playerID );
dataSource.close();
Game game = new Game( context );
game.setID( gameID );
game.setDifficulty( difficulty );
game.setPlayer( player );
game.setPlanet( currentPlanet );
game.setUniverse( universe );
return game;
}
/**
* Cursor to planet.
*
* @param cursor the Cursor
* @return the planet
*/
public Planet cursorToPlanet( Cursor cursor )
{
Planet planet = new Planet(cursor.getString(4), cursor.getInt(5), cursor.getInt(6) );
planet.setTechLevel( cursor.getInt(2) );
planet.setResourceType( cursor.getInt(3) );
return planet;
}
}
| true | true | public long createGame( Game game )
{
Planet currentPlanet = game.getPlanet();
Universe universe = game.getUniverse();
int difficulty = game.getDifficulty();
Player player = game.getPlayer();
// insert planet into database
ContentValues values = new ContentValues();
int techLevel = currentPlanet.getTechLevel();
int resourceType = currentPlanet.getResourceType();
String name = currentPlanet.getName();
int x_coord = currentPlanet.getX();
int y_coord = currentPlanet.getY();
values.put("techLevel", techLevel);
values.put("resourceType", resourceType);
values.put("name", name);
values.put("x_coord", x_coord);
values.put("y_coord", y_coord);
long currentPlanetID = database.insert( "tb_planet", null, values );
//insert player into database
PlayerDataSource playerDataSource = new PlayerDataSource( context );
playerDataSource.open();
long playerID = playerDataSource.createPlayer( player );
playerDataSource.close();
//insert game into database
values = new ContentValues();
values.put( "player", playerID );
values.put( "difficulty", difficulty );
values.put( "planet", currentPlanetID );
long gameID = database.insert( "tb_game", null, values );
game.setID( gameID );
//insert universe into database
ArrayList<Planet> universePlanets = universe.getUniverse();
for( Planet universePlanet: universePlanets )
{
values = new ContentValues();
values.put("game", gameID);
values.put("techLevel", universePlanet.getTechLevel());
values.put("resourceType", universePlanet.getResourceType());
values.put("name", universePlanet.getName());
values.put("x_coord", universePlanet.getX());
values.put("y_coord", universePlanet.getY());
database.insert( "tb_planet", null, values );
}
return gameID;
}
| public long createGame( Game game )
{
Planet currentPlanet = game.getPlanet();
Universe universe = game.getUniverse();
int difficulty = game.getDifficulty();
Player player = game.getPlayer();
// insert planet into database
ContentValues values = new ContentValues();
int techLevel = currentPlanet.getTechLevel();
int resourceType = currentPlanet.getResourceType();
String name = currentPlanet.getName();
int x_coord = currentPlanet.getX();
int y_coord = currentPlanet.getY();
values.put("techLevel", techLevel);
values.put("resourceType", resourceType);
values.put("name", name);
values.put("x_coord", x_coord);
values.put("y_coord", y_coord);
long currentPlanetID = database.insert( "tb_planet", null, values );
//insert player into database
PlayerDataSource playerDataSource = new PlayerDataSource( context );
playerDataSource.open();
long playerID = playerDataSource.createPlayer( player );
playerDataSource.close();
//insert game into database
values = new ContentValues();
values.put( "player", playerID );
values.put( "difficulty", difficulty );
values.put( "planet", currentPlanetID );
long gameID = database.insert( "tb_game", null, values );
game.setID( gameID );
//insert universe into database
ArrayList<Planet> universePlanets = universe.getUniverse();
for( Planet universePlanet: universePlanets )
{
values = new ContentValues();
values.put("game", (int)gameID);
values.put("techLevel", universePlanet.getTechLevel());
values.put("resourceType", universePlanet.getResourceType());
values.put("name", universePlanet.getName());
values.put("x_coord", universePlanet.getX());
values.put("y_coord", universePlanet.getY());
database.insert( "tb_planet", null, values );
}
return gameID;
}
|
diff --git a/projects/lucene/src/test/org/springmodules/lucene/index/support/handler/database/SqlDocumentHandlerTests.java b/projects/lucene/src/test/org/springmodules/lucene/index/support/handler/database/SqlDocumentHandlerTests.java
index 9b41333d..5564cb2c 100644
--- a/projects/lucene/src/test/org/springmodules/lucene/index/support/handler/database/SqlDocumentHandlerTests.java
+++ b/projects/lucene/src/test/org/springmodules/lucene/index/support/handler/database/SqlDocumentHandlerTests.java
@@ -1,91 +1,91 @@
package org.springmodules.lucene.index.support.handler.database;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
import junit.framework.TestCase;
import org.apache.lucene.document.Document;
import org.springmodules.lucene.index.DocumentHandlerException;
import org.springmodules.lucene.index.support.handler.DocumentHandler;
public class SqlDocumentHandlerTests extends TestCase {
public void testSupport() throws Exception {
DocumentHandler documentHandler=new SqlDocumentHandler() {
public Document getDocument(SqlRequest request, ResultSet rs) throws SQLException {
return null;
}
};
Map description=new HashMap();
description.put(SqlRequest.SQL_REQUEST,"sql");
documentHandler.getDocument(description,new MockResultSet());
}
public void testNotSupport() throws Exception {
DocumentHandler documentHandler=new SqlDocumentHandler() {
public Document getDocument(SqlRequest request, ResultSet rs) throws SQLException {
return null;
}
};
Map description=new HashMap();
description.put(SqlRequest.SQL_REQUEST,"sql");
try {
documentHandler.getDocument(description,"test");
fail();
} catch (DocumentHandlerException ex) {
}
}
public void testDescription() throws Exception {
DocumentHandler documentHandler=new SqlDocumentHandler() {
public Document getDocument(SqlRequest request, ResultSet rs) throws SQLException {
return null;
}
};
Map description=new HashMap();
description.put(SqlRequest.SQL_REQUEST,"sql");
try {
documentHandler.getDocument(description,"test");
fail();
} catch (DocumentHandlerException ex) {
}
description.put(SqlRequest.SQL_REQUEST,"sql");
documentHandler.getDocument(description,new MockResultSet());
}
public void testGetDocument() throws Exception {
String sql="sql";
- Object[] params=new Object[] { "param1",12};
+ Object[] params=new Object[] { "param1",new Integer(12)};
int[] paramTypes=new int[] { Types.VARCHAR,Types.INTEGER};
final boolean[] called={false};
final SqlRequest[] sqlRequests={null};
DocumentHandler documentHandler=new SqlDocumentHandler() {
public Document getDocument(SqlRequest request, ResultSet rs) throws SQLException {
called[0]=true;
sqlRequests[0]=request;
return null;
}
};
Map description=new HashMap();
description.put(SqlRequest.SQL_REQUEST,sql);
description.put(SqlRequest.REQUEST_PARAMETERS,params);
description.put(SqlRequest.REQUEST_PARAMETER_TYPES,paramTypes);
documentHandler.getDocument(description,new MockResultSet());
assertTrue(called[0]);
assertEquals(sqlRequests[0].getSql(),sql);
assertEquals(sqlRequests[0].getParams()[0],params[0]);
assertEquals(sqlRequests[0].getParams()[1],params[1]);
assertEquals(sqlRequests[0].getTypes()[0],paramTypes[0]);
assertEquals(sqlRequests[0].getTypes()[1],paramTypes[1]);
}
}
| true | true | public void testGetDocument() throws Exception {
String sql="sql";
Object[] params=new Object[] { "param1",12};
int[] paramTypes=new int[] { Types.VARCHAR,Types.INTEGER};
final boolean[] called={false};
final SqlRequest[] sqlRequests={null};
DocumentHandler documentHandler=new SqlDocumentHandler() {
public Document getDocument(SqlRequest request, ResultSet rs) throws SQLException {
called[0]=true;
sqlRequests[0]=request;
return null;
}
};
Map description=new HashMap();
description.put(SqlRequest.SQL_REQUEST,sql);
description.put(SqlRequest.REQUEST_PARAMETERS,params);
description.put(SqlRequest.REQUEST_PARAMETER_TYPES,paramTypes);
documentHandler.getDocument(description,new MockResultSet());
assertTrue(called[0]);
assertEquals(sqlRequests[0].getSql(),sql);
assertEquals(sqlRequests[0].getParams()[0],params[0]);
assertEquals(sqlRequests[0].getParams()[1],params[1]);
assertEquals(sqlRequests[0].getTypes()[0],paramTypes[0]);
assertEquals(sqlRequests[0].getTypes()[1],paramTypes[1]);
}
| public void testGetDocument() throws Exception {
String sql="sql";
Object[] params=new Object[] { "param1",new Integer(12)};
int[] paramTypes=new int[] { Types.VARCHAR,Types.INTEGER};
final boolean[] called={false};
final SqlRequest[] sqlRequests={null};
DocumentHandler documentHandler=new SqlDocumentHandler() {
public Document getDocument(SqlRequest request, ResultSet rs) throws SQLException {
called[0]=true;
sqlRequests[0]=request;
return null;
}
};
Map description=new HashMap();
description.put(SqlRequest.SQL_REQUEST,sql);
description.put(SqlRequest.REQUEST_PARAMETERS,params);
description.put(SqlRequest.REQUEST_PARAMETER_TYPES,paramTypes);
documentHandler.getDocument(description,new MockResultSet());
assertTrue(called[0]);
assertEquals(sqlRequests[0].getSql(),sql);
assertEquals(sqlRequests[0].getParams()[0],params[0]);
assertEquals(sqlRequests[0].getParams()[1],params[1]);
assertEquals(sqlRequests[0].getTypes()[0],paramTypes[0]);
assertEquals(sqlRequests[0].getTypes()[1],paramTypes[1]);
}
|
diff --git a/preflight/src/main/java/org/apache/pdfbox/preflight/font/Type0FontValidator.java b/preflight/src/main/java/org/apache/pdfbox/preflight/font/Type0FontValidator.java
index bbb27d7..c00b66f 100644
--- a/preflight/src/main/java/org/apache/pdfbox/preflight/font/Type0FontValidator.java
+++ b/preflight/src/main/java/org/apache/pdfbox/preflight/font/Type0FontValidator.java
@@ -1,350 +1,350 @@
/*****************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
package org.apache.pdfbox.preflight.font;
import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_FONTS_CIDKEYED_CMAP_INVALID_OR_MISSING;
import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_FONTS_CIDKEYED_INVALID;
import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_FONTS_CIDKEYED_SYSINFO;
import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_FONTS_CID_CMAP_DAMAGED;
import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_FONTS_DICTIONARY_INVALID;
import static org.apache.pdfbox.preflight.PreflightConstants.FONT_DICTIONARY_DEFAULT_CMAP_WMODE;
import static org.apache.pdfbox.preflight.PreflightConstants.FONT_DICTIONARY_KEY_CMAP_NAME;
import static org.apache.pdfbox.preflight.PreflightConstants.FONT_DICTIONARY_KEY_CMAP_USECMAP;
import static org.apache.pdfbox.preflight.PreflightConstants.FONT_DICTIONARY_KEY_CMAP_WMODE;
import static org.apache.pdfbox.preflight.PreflightConstants.FONT_DICTIONARY_VALUE_CMAP_IDENTITY_H;
import static org.apache.pdfbox.preflight.PreflightConstants.FONT_DICTIONARY_VALUE_CMAP_IDENTITY_V;
import static org.apache.pdfbox.preflight.PreflightConstants.FONT_DICTIONARY_VALUE_TYPE0;
import static org.apache.pdfbox.preflight.PreflightConstants.FONT_DICTIONARY_VALUE_TYPE2;
import static org.apache.pdfbox.preflight.PreflightConstants.FONT_DICTIONARY_VALUE_TYPE_CMAP;
import java.io.IOException;
import org.apache.fontbox.cmap.CMap;
import org.apache.fontbox.cmap.CMapParser;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSStream;
import org.apache.pdfbox.pdmodel.font.PDCIDFontType0Font;
import org.apache.pdfbox.pdmodel.font.PDCIDFontType2Font;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.preflight.PreflightContext;
import org.apache.pdfbox.preflight.ValidationResult.ValidationError;
import org.apache.pdfbox.preflight.exception.ValidationException;
import org.apache.pdfbox.preflight.font.container.FontContainer;
import org.apache.pdfbox.preflight.font.container.Type0Container;
import org.apache.pdfbox.preflight.utils.COSUtils;
public class Type0FontValidator extends FontValidator<Type0Container>
{
protected COSDocument cosDocument = null;
public Type0FontValidator(PreflightContext context, PDFont font)
{
super(context, font, new Type0Container(font));
cosDocument = this.context.getDocument().getDocument();
}
@Override
public void validate() throws ValidationException
{
checkMandatoryFields();
processDescendantFont();
checkEncoding();
checkToUnicode();
}
/**
* This methods extracts from the Font dictionary all mandatory fields. If a mandatory field is missing, the list of
* ValidationError in the FontContainer is updated.
*/
protected void checkMandatoryFields()
{
COSDictionary fontDictionary = (COSDictionary) font.getCOSObject();
boolean areFieldsPResent = fontDictionary.containsKey(COSName.TYPE);
areFieldsPResent &= fontDictionary.containsKey(COSName.SUBTYPE);
areFieldsPResent &= fontDictionary.containsKey(COSName.BASE_FONT);
areFieldsPResent &= fontDictionary.containsKey(COSName.DESCENDANT_FONTS);
areFieldsPResent &= fontDictionary.containsKey(COSName.ENCODING);
if (!areFieldsPResent)
{
this.fontContainer.push(new ValidationError(ERROR_FONTS_DICTIONARY_INVALID,
"Some keys are missing from composite font dictionary"));
}
}
/**
* Extract the single CIDFont from the Descendant array. Create a FontValidator for this CODFont and launch its
* validation.
*/
protected void processDescendantFont() throws ValidationException
{
COSDictionary fontDictionary = (COSDictionary) font.getCOSObject();
// a CIDFont is contained in the DescendantFonts array
COSArray array = COSUtils.getAsArray(fontDictionary.getItem(COSName.DESCENDANT_FONTS), cosDocument);
if (array == null || array.size() != 1)
{
/*
* in PDF 1.4, this array must contain only one element, because of a PDF/A should be a PDF 1.4, this method
* returns an error if the array has more than one element.
*/
this.fontContainer.push(new ValidationError(ERROR_FONTS_CIDKEYED_INVALID,
"CIDFont is missing from the DescendantFonts array or the size of array is greater than 1"));
return;
}
COSDictionary cidFont = COSUtils.getAsDictionary(array.get(0), cosDocument);
if (cidFont == null)
{
this.fontContainer.push(new ValidationError(ERROR_FONTS_CIDKEYED_INVALID,
"The DescendantFonts array should have one element with is a dictionary."));
return;
}
FontValidator<? extends FontContainer> cidFontValidator = createDescendantValidator(cidFont);
if (cidFontValidator != null)
{
this.fontContainer.setDelegateFontContainer(cidFontValidator.getFontContainer());
cidFontValidator.validate();
}
}
protected FontValidator<? extends FontContainer> createDescendantValidator(COSDictionary cidFont)
{
String subtype = cidFont.getNameAsString(COSName.SUBTYPE);
FontValidator<? extends FontContainer> cidFontValidator = null;
if (FONT_DICTIONARY_VALUE_TYPE0.equals(subtype))
{
cidFontValidator = createCIDType0FontValidator(cidFont);
}
else if (FONT_DICTIONARY_VALUE_TYPE2.equals(subtype))
{
cidFontValidator = createCIDType2FontValidator(cidFont);
}
else
{
this.fontContainer.push(new ValidationError(ERROR_FONTS_DICTIONARY_INVALID,
"Type and/or Subtype keys are missing"));
}
return cidFontValidator;
}
/**
* Create the validation object for CIDType0 Font
*
* @return
*/
protected FontValidator<? extends FontContainer> createCIDType0FontValidator(COSDictionary fDict)
{
return new CIDType0FontValidator(context, new PDCIDFontType0Font(fDict));
}
/**
* Create the validation object for CIDType2 Font
*
* @return
*/
protected FontValidator<? extends FontContainer> createCIDType2FontValidator(COSDictionary fDict)
{
return new CIDType2FontValidator(context, new PDCIDFontType2Font(fDict));
}
/**
* Check the CMap entry.
*
* The CMap entry must be a dictionary in a PDF/A. This entry can be a String only if the String value is Identity-H
* or Identity-V
*
* @param encoding
*/
protected void checkEncoding()
{
COSBase encoding = ((COSDictionary) font.getCOSObject()).getItem(COSName.ENCODING);
checkCMapEncoding(encoding);
}
protected void checkCMapEncoding(COSBase encoding)
{
if (COSUtils.isString(encoding, cosDocument))
{
// if encoding is a string, only 2 values are allowed
String str = COSUtils.getAsString(encoding, cosDocument);
if (!(FONT_DICTIONARY_VALUE_CMAP_IDENTITY_V.equals(str) || FONT_DICTIONARY_VALUE_CMAP_IDENTITY_H
.equals(str)))
{
this.fontContainer.push(new ValidationError(ERROR_FONTS_CIDKEYED_INVALID,
"The CMap is a string but it isn't an Identity-H/V"));
return;
}
}
else if (COSUtils.isStream(encoding, cosDocument))
{
/*
* If the CMap is a stream, some fields are mandatory and the CIDSytemInfo must be compared with the
* CIDSystemInfo entry of the CIDFont.
*/
processCMapAsStream(COSUtils.getAsStream(encoding, cosDocument));
}
else
{
// CMap type is invalid
this.fontContainer.push(new ValidationError(ERROR_FONTS_CIDKEYED_CMAP_INVALID_OR_MISSING,
"The CMap type is invalid"));
}
}
/**
* Standard information of a stream element will be checked by the StreamValidationProcess.
*
* This method checks mandatory fields of the CMap stream. This method checks too if the CMap stream is damaged
* using the CMapParser of the fontbox api.
*
* @param aCMap
* @return
*/
private void processCMapAsStream(COSStream aCMap)
{
COSBase sysinfo = aCMap.getItem(COSName.CIDSYSTEMINFO);
checkCIDSystemInfo(sysinfo);
try
{
// extract information from the CMap stream
CMap fontboxCMap = new CMapParser().parse(null, aCMap.getUnfilteredStream());
int wmValue = fontboxCMap.getWMode();
String cmnValue = fontboxCMap.getName();
/*
* According to the getInt javadoc, -1 is returned if there are no result. In the PDF Reference v1.7 p449,
* we can read that Default value is 0.
*/
int wmode = aCMap.getInt(COSName.getPDFName(FONT_DICTIONARY_KEY_CMAP_WMODE),
FONT_DICTIONARY_DEFAULT_CMAP_WMODE);
String type = aCMap.getNameAsString(COSName.TYPE);
String cmapName = aCMap.getNameAsString(COSName.getPDFName(FONT_DICTIONARY_KEY_CMAP_NAME));
if (cmapName == null || "".equals(cmapName) || wmode > 1)
{
this.fontContainer.push(new ValidationError(ERROR_FONTS_CIDKEYED_CMAP_INVALID_OR_MISSING,
"Some elements in the CMap dictionary are missing or invalid"));
}
- else if (!(wmValue == wmode && cmnValue.equals(cmapName)))
+ else if (!(wmValue == wmode && cmapName.equals(cmnValue)))
{
this.fontContainer.push(new ValidationError(ERROR_FONTS_CIDKEYED_CMAP_INVALID_OR_MISSING,
"CMapName or WMode is inconsistent"));
}
else if (!FONT_DICTIONARY_VALUE_TYPE_CMAP.equals(type))
{
this.fontContainer.push(new ValidationError(ERROR_FONTS_CIDKEYED_CMAP_INVALID_OR_MISSING,
"The CMap type is invalid"));
}
}
catch (IOException e)
{
this.fontContainer.push(new ValidationError(ERROR_FONTS_CID_CMAP_DAMAGED, "The CMap type is damaged"));
}
COSDictionary cmapUsed = (COSDictionary) aCMap.getDictionaryObject(COSName
.getPDFName(FONT_DICTIONARY_KEY_CMAP_USECMAP));
if (cmapUsed != null)
{
checkCMapEncoding(cmapUsed);
}
compareCIDSystemInfo(aCMap);
}
/**
* Check the content of the CIDSystemInfo dictionary. A CIDSystemInfo dictionary must contain :
* <UL>
* <li>a Name - Registry
* <li>a Name - Ordering
* <li>a Integer - Supplement
* </UL>
*
* @param sysinfo
* @return
*/
protected boolean checkCIDSystemInfo(COSBase sysinfo)
{
boolean result = true;
COSDictionary cidSysInfo = COSUtils.getAsDictionary(sysinfo, cosDocument);
if (cidSysInfo != null)
{
COSBase reg = cidSysInfo.getItem(COSName.REGISTRY);
COSBase ord = cidSysInfo.getItem(COSName.ORDERING);
COSBase sup = cidSysInfo.getItem(COSName.SUPPLEMENT);
if (!(COSUtils.isString(reg, cosDocument) && COSUtils.isString(ord, cosDocument) && COSUtils.isInteger(sup,
cosDocument)))
{
this.fontContainer.push(new ValidationError(ERROR_FONTS_CIDKEYED_SYSINFO));
result = false;
}
}
else
{
this.fontContainer.push(new ValidationError(ERROR_FONTS_CIDKEYED_SYSINFO));
result = false;
}
return result;
}
/**
* The CIDSystemInfo must have the same Registry and Ordering for CMap and CIDFont. This control is useless if CMap
* is Identity-H or Identity-V so this method is called by the checkCMap method.
*
* @param cmap
* @return
*/
private void compareCIDSystemInfo(COSDictionary cmap)
{
COSDictionary fontDictionary = (COSDictionary) font.getCOSObject();
COSArray array = COSUtils.getAsArray(fontDictionary.getItem(COSName.DESCENDANT_FONTS), cosDocument);
if (array != null && array.size() > 0)
{
COSDictionary cidFont = COSUtils.getAsDictionary(array.get(0), cosDocument);
COSDictionary cmsi = COSUtils.getAsDictionary(cmap.getItem(COSName.CIDSYSTEMINFO), cosDocument);
COSDictionary cfsi = COSUtils.getAsDictionary(cidFont.getItem(COSName.CIDSYSTEMINFO), cosDocument);
String regCM = COSUtils.getAsString(cmsi.getItem(COSName.REGISTRY), cosDocument);
String ordCM = COSUtils.getAsString(cmsi.getItem(COSName.ORDERING), cosDocument);
String regCF = COSUtils.getAsString(cfsi.getItem(COSName.REGISTRY), cosDocument);
String ordCF = COSUtils.getAsString(cfsi.getItem(COSName.ORDERING), cosDocument);
if (!regCF.equals(regCM) || !ordCF.equals(ordCM))
{
this.fontContainer.push(new ValidationError(ERROR_FONTS_CIDKEYED_SYSINFO,
"The CIDSystemInfo is inconsistent"));
}
}
}
}
| true | true | private void processCMapAsStream(COSStream aCMap)
{
COSBase sysinfo = aCMap.getItem(COSName.CIDSYSTEMINFO);
checkCIDSystemInfo(sysinfo);
try
{
// extract information from the CMap stream
CMap fontboxCMap = new CMapParser().parse(null, aCMap.getUnfilteredStream());
int wmValue = fontboxCMap.getWMode();
String cmnValue = fontboxCMap.getName();
/*
* According to the getInt javadoc, -1 is returned if there are no result. In the PDF Reference v1.7 p449,
* we can read that Default value is 0.
*/
int wmode = aCMap.getInt(COSName.getPDFName(FONT_DICTIONARY_KEY_CMAP_WMODE),
FONT_DICTIONARY_DEFAULT_CMAP_WMODE);
String type = aCMap.getNameAsString(COSName.TYPE);
String cmapName = aCMap.getNameAsString(COSName.getPDFName(FONT_DICTIONARY_KEY_CMAP_NAME));
if (cmapName == null || "".equals(cmapName) || wmode > 1)
{
this.fontContainer.push(new ValidationError(ERROR_FONTS_CIDKEYED_CMAP_INVALID_OR_MISSING,
"Some elements in the CMap dictionary are missing or invalid"));
}
else if (!(wmValue == wmode && cmnValue.equals(cmapName)))
{
this.fontContainer.push(new ValidationError(ERROR_FONTS_CIDKEYED_CMAP_INVALID_OR_MISSING,
"CMapName or WMode is inconsistent"));
}
else if (!FONT_DICTIONARY_VALUE_TYPE_CMAP.equals(type))
{
this.fontContainer.push(new ValidationError(ERROR_FONTS_CIDKEYED_CMAP_INVALID_OR_MISSING,
"The CMap type is invalid"));
}
}
catch (IOException e)
{
this.fontContainer.push(new ValidationError(ERROR_FONTS_CID_CMAP_DAMAGED, "The CMap type is damaged"));
}
COSDictionary cmapUsed = (COSDictionary) aCMap.getDictionaryObject(COSName
.getPDFName(FONT_DICTIONARY_KEY_CMAP_USECMAP));
if (cmapUsed != null)
{
checkCMapEncoding(cmapUsed);
}
compareCIDSystemInfo(aCMap);
}
| private void processCMapAsStream(COSStream aCMap)
{
COSBase sysinfo = aCMap.getItem(COSName.CIDSYSTEMINFO);
checkCIDSystemInfo(sysinfo);
try
{
// extract information from the CMap stream
CMap fontboxCMap = new CMapParser().parse(null, aCMap.getUnfilteredStream());
int wmValue = fontboxCMap.getWMode();
String cmnValue = fontboxCMap.getName();
/*
* According to the getInt javadoc, -1 is returned if there are no result. In the PDF Reference v1.7 p449,
* we can read that Default value is 0.
*/
int wmode = aCMap.getInt(COSName.getPDFName(FONT_DICTIONARY_KEY_CMAP_WMODE),
FONT_DICTIONARY_DEFAULT_CMAP_WMODE);
String type = aCMap.getNameAsString(COSName.TYPE);
String cmapName = aCMap.getNameAsString(COSName.getPDFName(FONT_DICTIONARY_KEY_CMAP_NAME));
if (cmapName == null || "".equals(cmapName) || wmode > 1)
{
this.fontContainer.push(new ValidationError(ERROR_FONTS_CIDKEYED_CMAP_INVALID_OR_MISSING,
"Some elements in the CMap dictionary are missing or invalid"));
}
else if (!(wmValue == wmode && cmapName.equals(cmnValue)))
{
this.fontContainer.push(new ValidationError(ERROR_FONTS_CIDKEYED_CMAP_INVALID_OR_MISSING,
"CMapName or WMode is inconsistent"));
}
else if (!FONT_DICTIONARY_VALUE_TYPE_CMAP.equals(type))
{
this.fontContainer.push(new ValidationError(ERROR_FONTS_CIDKEYED_CMAP_INVALID_OR_MISSING,
"The CMap type is invalid"));
}
}
catch (IOException e)
{
this.fontContainer.push(new ValidationError(ERROR_FONTS_CID_CMAP_DAMAGED, "The CMap type is damaged"));
}
COSDictionary cmapUsed = (COSDictionary) aCMap.getDictionaryObject(COSName
.getPDFName(FONT_DICTIONARY_KEY_CMAP_USECMAP));
if (cmapUsed != null)
{
checkCMapEncoding(cmapUsed);
}
compareCIDSystemInfo(aCMap);
}
|
diff --git a/Essentials/src/com/earth2me/essentials/EssentialsEcoBlockListener.java b/Essentials/src/com/earth2me/essentials/EssentialsEcoBlockListener.java
index aac9fef..3955292 100644
--- a/Essentials/src/com/earth2me/essentials/EssentialsEcoBlockListener.java
+++ b/Essentials/src/com/earth2me/essentials/EssentialsEcoBlockListener.java
@@ -1,250 +1,250 @@
package com.earth2me.essentials;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Material;
import org.bukkit.block.Sign;
import org.bukkit.craftbukkit.block.CraftSign;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockListener;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.inventory.ItemStack;
public class EssentialsEcoBlockListener extends BlockListener
{
Essentials ess;
private static final Logger logger = Logger.getLogger("Minecraft");
public EssentialsEcoBlockListener(Essentials ess)
{
this.ess = ess;
}
@Override
public void onBlockBreak(BlockBreakEvent event)
{
if (event.isCancelled())
{
return;
}
if (ess.getSettings().areSignsDisabled())
{
return;
}
User user = ess.getUser(event.getPlayer());
String username = user.getName().substring(0, user.getName().length() > 13 ? 13 : user.getName().length());
if (event.getBlock().getType() != Material.WALL_SIGN && event.getBlock().getType() != Material.SIGN_POST)
{
return;
}
Sign sign = new CraftSign(event.getBlock());
if (sign.getLine(0).equals("§1[Trade]"))
{
if (!sign.getLine(3).substring(2).equals(username))
{
if (!user.isOp())
{
event.setCancelled(true);
}
return;
}
try
{
String[] l1 = sign.getLines()[1].split("[ :-]+");
String[] l2 = sign.getLines()[2].split("[ :-]+");
boolean m1 = l1[0].matches("[^0-9][0-9]+(\\.[0-9]+)?");
boolean m2 = l2[0].matches("[^0-9][0-9]+(\\.[0-9]+)?");
double q1 = Double.parseDouble(m1 ? l1[0].substring(1) : l1[0]);
double q2 = Double.parseDouble(m2 ? l2[0].substring(1) : l2[0]);
double r1 = Double.parseDouble(l1[m1 ? 1 : 2]);
double r2 = Double.parseDouble(l2[m2 ? 1 : 2]);
if ((!m1 & q1 < 1) || (!m2 & q2 < 1))
{
throw new Exception(Util.i18n("moreThanZero"));
}
ItemStack i1 = m1 || r1 <= 0 ? null : ItemDb.get(l1[1], (int)r1);
ItemStack i2 = m2 || r2 <= 0 ? null : ItemDb.get(l2[1], (int)r2);
if (m1)
{
user.giveMoney(r1);
}
else if (i1 != null)
{
Map<Integer, ItemStack> leftOver = user.getInventory().addItem(i1);
for (ItemStack itemStack : leftOver.values())
{
InventoryWorkaround.dropItem(user.getLocation(), itemStack);
}
}
if (m2)
{
user.giveMoney(r2);
}
else if (i2 != null)
{
Map<Integer, ItemStack> leftOver = user.getInventory().addItem(i2);
for (ItemStack itemStack : leftOver.values())
{
InventoryWorkaround.dropItem(user.getLocation(), itemStack);
}
}
user.updateInventory();
sign.setType(Material.AIR);
}
catch (Throwable ex)
{
user.sendMessage(Util.format("errorWithMessage", ex.getMessage()));
if (ess.getSettings().isDebug())
{
logger.log(Level.WARNING, ex.getMessage(), ex);
}
}
return;
}
}
@Override
public void onSignChange(SignChangeEvent event)
{
if (ess.getSettings().areSignsDisabled())
{
return;
}
User user = ess.getUser(event.getPlayer());
String username = user.getName().substring(0, user.getName().length() > 13 ? 13 : user.getName().length());
if ((event.getLine(0).equalsIgnoreCase("[Buy]") || event.getLine(0).equalsIgnoreCase("#1[Buy]")) && user.isAuthorized("essentials.signs.buy.create"))
{
try
{
event.setLine(0, "§1[Buy]");
event.setLine(1, "" + Math.abs(Integer.parseInt(event.getLine(1))));
ItemStack is = ItemDb.get(event.getLine(2));
if (is.getTypeId() == 0 || Math.abs(Integer.parseInt(event.getLine(1))) == 0)
{
throw new Exception("Don't sell air.");
}
double price = Double.parseDouble(event.getLine(3).replaceAll("[^0-9\\.]", ""));
event.setLine(3, Util.formatCurrency(price));
}
catch (Throwable ex)
{
user.sendMessage(Util.format("errorWithMessage", ex.getMessage()));
if (ess.getSettings().isDebug())
{
logger.log(Level.WARNING, ex.getMessage(), ex);
}
event.setLine(0, "§4[Buy]");
event.setLine(1, "#");
event.setLine(2, "Item");
event.setLine(3, "$Price");
}
return;
}
if ((event.getLine(0).equalsIgnoreCase("[Sell]") || event.getLine(0).equalsIgnoreCase("#1[Sell]")) && user.isAuthorized("essentials.signs.sell.create"))
{
try
{
event.setLine(0, "§1[Sell]");
event.setLine(1, "" + Math.abs(Integer.parseInt(event.getLine(1))));
ItemStack is = ItemDb.get(event.getLine(2));
if (is.getTypeId() == 0 || Math.abs(Integer.parseInt(event.getLine(1))) == 0)
{
throw new Exception("Can't buy air.");
}
double price = Double.parseDouble(event.getLine(3).replaceAll("[^0-9\\.]", ""));
event.setLine(3, Util.formatCurrency(price));
}
catch (Throwable ex)
{
user.sendMessage(Util.format("errorWithMessage", ex.getMessage()));
if (ess.getSettings().isDebug())
{
logger.log(Level.WARNING, ex.getMessage(), ex);
}
event.setLine(0, "§4[Sell]");
event.setLine(1, "#");
event.setLine(2, "Item");
event.setLine(3, "$Price");
}
return;
}
if ((event.getLine(0).equalsIgnoreCase("[Trade]") || event.getLine(0).equalsIgnoreCase("#1[Trade]")) && user.isAuthorized("essentials.signs.trade.create"))
{
try
{
String[] l1 = event.getLine(1).split("[ :-]+");
String[] l2 = event.getLine(2).split("[ :-]+");
boolean m1 = l1[0].matches("[^0-9][0-9]+(\\.[0-9]+)?");
boolean m2 = l2[0].matches("[^0-9][0-9]+(\\.[0-9]+)?");
double q1 = Double.parseDouble(m1 ? l1[0].substring(1) : l1[0]);
double q2 = Double.parseDouble(m2 ? l2[0].substring(1) : l2[0]);
- if (m1 ? l2.length != 1 : l2.length != 2)
+ if (m1 ? l1.length != 1 : l1.length != 2)
{
throw new Exception(Util.format("invalidSignLine", 2));
}
if (m2 ? l2.length != 2 : l2.length != 3)
{
throw new Exception(Util.format("invalidSignLine", 3));
}
double r2 = Double.parseDouble(l2[m2 ? 1 : 2]);
r2 = m2 ? r2 : r2 - r2 % q2;
if ((!m1 & q1 < 1) || (!m2 & q2 < 1) || r2 < 1)
{
throw new Exception(Util.i18n("moreThanZero"));
}
if (!m1)
{
ItemDb.get(l1[1]);
}
if (m2)
{
if (user.getMoney() < r2)
{
throw new Exception(Util.i18n("notEnoughMoney"));
}
user.takeMoney(r2);
//user.sendMessage("r2: " + r2 + " q2: " + q2);
}
else
{
ItemStack i2 = ItemDb.get(l2[1], (int)r2);
if (!InventoryWorkaround.containsItem(user.getInventory(), true, i2))
{
throw new Exception(Util.format("missingItems", (int)r2, l2[1]));
}
InventoryWorkaround.removeItem(user.getInventory(), true, i2);
user.updateInventory();
}
event.setLine(0, "§1[Trade]");
event.setLine(1, (m1 ? Util.formatCurrency(q1) : (int)q1 + " " + l1[1]) + ":0");
event.setLine(2, (m2 ? Util.formatCurrency(q2) : (int)q2 + " " + l2[1]) + ":" + (m2 ? Util.roundDouble(r2) : "" + (int)r2));
event.setLine(3, "§8" + username);
}
catch (Throwable ex)
{
user.sendMessage(Util.format("errorWithMessage", ex.getMessage()));
if (ess.getSettings().isDebug())
{
logger.log(Level.WARNING, ex.getMessage(), ex);
}
event.setLine(0, "§4[Trade]");
event.setLine(1, "# ItemOr" + ess.getSettings().getCurrencySymbol());
event.setLine(2, "# ItemOr" + ess.getSettings().getCurrencySymbol() + ":#");
event.setLine(3, "§8" + username);
}
return;
}
}
}
| true | true | public void onSignChange(SignChangeEvent event)
{
if (ess.getSettings().areSignsDisabled())
{
return;
}
User user = ess.getUser(event.getPlayer());
String username = user.getName().substring(0, user.getName().length() > 13 ? 13 : user.getName().length());
if ((event.getLine(0).equalsIgnoreCase("[Buy]") || event.getLine(0).equalsIgnoreCase("#1[Buy]")) && user.isAuthorized("essentials.signs.buy.create"))
{
try
{
event.setLine(0, "§1[Buy]");
event.setLine(1, "" + Math.abs(Integer.parseInt(event.getLine(1))));
ItemStack is = ItemDb.get(event.getLine(2));
if (is.getTypeId() == 0 || Math.abs(Integer.parseInt(event.getLine(1))) == 0)
{
throw new Exception("Don't sell air.");
}
double price = Double.parseDouble(event.getLine(3).replaceAll("[^0-9\\.]", ""));
event.setLine(3, Util.formatCurrency(price));
}
catch (Throwable ex)
{
user.sendMessage(Util.format("errorWithMessage", ex.getMessage()));
if (ess.getSettings().isDebug())
{
logger.log(Level.WARNING, ex.getMessage(), ex);
}
event.setLine(0, "§4[Buy]");
event.setLine(1, "#");
event.setLine(2, "Item");
event.setLine(3, "$Price");
}
return;
}
if ((event.getLine(0).equalsIgnoreCase("[Sell]") || event.getLine(0).equalsIgnoreCase("#1[Sell]")) && user.isAuthorized("essentials.signs.sell.create"))
{
try
{
event.setLine(0, "§1[Sell]");
event.setLine(1, "" + Math.abs(Integer.parseInt(event.getLine(1))));
ItemStack is = ItemDb.get(event.getLine(2));
if (is.getTypeId() == 0 || Math.abs(Integer.parseInt(event.getLine(1))) == 0)
{
throw new Exception("Can't buy air.");
}
double price = Double.parseDouble(event.getLine(3).replaceAll("[^0-9\\.]", ""));
event.setLine(3, Util.formatCurrency(price));
}
catch (Throwable ex)
{
user.sendMessage(Util.format("errorWithMessage", ex.getMessage()));
if (ess.getSettings().isDebug())
{
logger.log(Level.WARNING, ex.getMessage(), ex);
}
event.setLine(0, "§4[Sell]");
event.setLine(1, "#");
event.setLine(2, "Item");
event.setLine(3, "$Price");
}
return;
}
if ((event.getLine(0).equalsIgnoreCase("[Trade]") || event.getLine(0).equalsIgnoreCase("#1[Trade]")) && user.isAuthorized("essentials.signs.trade.create"))
{
try
{
String[] l1 = event.getLine(1).split("[ :-]+");
String[] l2 = event.getLine(2).split("[ :-]+");
boolean m1 = l1[0].matches("[^0-9][0-9]+(\\.[0-9]+)?");
boolean m2 = l2[0].matches("[^0-9][0-9]+(\\.[0-9]+)?");
double q1 = Double.parseDouble(m1 ? l1[0].substring(1) : l1[0]);
double q2 = Double.parseDouble(m2 ? l2[0].substring(1) : l2[0]);
if (m1 ? l2.length != 1 : l2.length != 2)
{
throw new Exception(Util.format("invalidSignLine", 2));
}
if (m2 ? l2.length != 2 : l2.length != 3)
{
throw new Exception(Util.format("invalidSignLine", 3));
}
double r2 = Double.parseDouble(l2[m2 ? 1 : 2]);
r2 = m2 ? r2 : r2 - r2 % q2;
if ((!m1 & q1 < 1) || (!m2 & q2 < 1) || r2 < 1)
{
throw new Exception(Util.i18n("moreThanZero"));
}
if (!m1)
{
ItemDb.get(l1[1]);
}
if (m2)
{
if (user.getMoney() < r2)
{
throw new Exception(Util.i18n("notEnoughMoney"));
}
user.takeMoney(r2);
//user.sendMessage("r2: " + r2 + " q2: " + q2);
}
else
{
ItemStack i2 = ItemDb.get(l2[1], (int)r2);
if (!InventoryWorkaround.containsItem(user.getInventory(), true, i2))
{
throw new Exception(Util.format("missingItems", (int)r2, l2[1]));
}
InventoryWorkaround.removeItem(user.getInventory(), true, i2);
user.updateInventory();
}
event.setLine(0, "§1[Trade]");
event.setLine(1, (m1 ? Util.formatCurrency(q1) : (int)q1 + " " + l1[1]) + ":0");
event.setLine(2, (m2 ? Util.formatCurrency(q2) : (int)q2 + " " + l2[1]) + ":" + (m2 ? Util.roundDouble(r2) : "" + (int)r2));
event.setLine(3, "§8" + username);
}
catch (Throwable ex)
{
user.sendMessage(Util.format("errorWithMessage", ex.getMessage()));
if (ess.getSettings().isDebug())
{
logger.log(Level.WARNING, ex.getMessage(), ex);
}
event.setLine(0, "§4[Trade]");
event.setLine(1, "# ItemOr" + ess.getSettings().getCurrencySymbol());
event.setLine(2, "# ItemOr" + ess.getSettings().getCurrencySymbol() + ":#");
event.setLine(3, "§8" + username);
}
return;
}
}
| public void onSignChange(SignChangeEvent event)
{
if (ess.getSettings().areSignsDisabled())
{
return;
}
User user = ess.getUser(event.getPlayer());
String username = user.getName().substring(0, user.getName().length() > 13 ? 13 : user.getName().length());
if ((event.getLine(0).equalsIgnoreCase("[Buy]") || event.getLine(0).equalsIgnoreCase("#1[Buy]")) && user.isAuthorized("essentials.signs.buy.create"))
{
try
{
event.setLine(0, "§1[Buy]");
event.setLine(1, "" + Math.abs(Integer.parseInt(event.getLine(1))));
ItemStack is = ItemDb.get(event.getLine(2));
if (is.getTypeId() == 0 || Math.abs(Integer.parseInt(event.getLine(1))) == 0)
{
throw new Exception("Don't sell air.");
}
double price = Double.parseDouble(event.getLine(3).replaceAll("[^0-9\\.]", ""));
event.setLine(3, Util.formatCurrency(price));
}
catch (Throwable ex)
{
user.sendMessage(Util.format("errorWithMessage", ex.getMessage()));
if (ess.getSettings().isDebug())
{
logger.log(Level.WARNING, ex.getMessage(), ex);
}
event.setLine(0, "§4[Buy]");
event.setLine(1, "#");
event.setLine(2, "Item");
event.setLine(3, "$Price");
}
return;
}
if ((event.getLine(0).equalsIgnoreCase("[Sell]") || event.getLine(0).equalsIgnoreCase("#1[Sell]")) && user.isAuthorized("essentials.signs.sell.create"))
{
try
{
event.setLine(0, "§1[Sell]");
event.setLine(1, "" + Math.abs(Integer.parseInt(event.getLine(1))));
ItemStack is = ItemDb.get(event.getLine(2));
if (is.getTypeId() == 0 || Math.abs(Integer.parseInt(event.getLine(1))) == 0)
{
throw new Exception("Can't buy air.");
}
double price = Double.parseDouble(event.getLine(3).replaceAll("[^0-9\\.]", ""));
event.setLine(3, Util.formatCurrency(price));
}
catch (Throwable ex)
{
user.sendMessage(Util.format("errorWithMessage", ex.getMessage()));
if (ess.getSettings().isDebug())
{
logger.log(Level.WARNING, ex.getMessage(), ex);
}
event.setLine(0, "§4[Sell]");
event.setLine(1, "#");
event.setLine(2, "Item");
event.setLine(3, "$Price");
}
return;
}
if ((event.getLine(0).equalsIgnoreCase("[Trade]") || event.getLine(0).equalsIgnoreCase("#1[Trade]")) && user.isAuthorized("essentials.signs.trade.create"))
{
try
{
String[] l1 = event.getLine(1).split("[ :-]+");
String[] l2 = event.getLine(2).split("[ :-]+");
boolean m1 = l1[0].matches("[^0-9][0-9]+(\\.[0-9]+)?");
boolean m2 = l2[0].matches("[^0-9][0-9]+(\\.[0-9]+)?");
double q1 = Double.parseDouble(m1 ? l1[0].substring(1) : l1[0]);
double q2 = Double.parseDouble(m2 ? l2[0].substring(1) : l2[0]);
if (m1 ? l1.length != 1 : l1.length != 2)
{
throw new Exception(Util.format("invalidSignLine", 2));
}
if (m2 ? l2.length != 2 : l2.length != 3)
{
throw new Exception(Util.format("invalidSignLine", 3));
}
double r2 = Double.parseDouble(l2[m2 ? 1 : 2]);
r2 = m2 ? r2 : r2 - r2 % q2;
if ((!m1 & q1 < 1) || (!m2 & q2 < 1) || r2 < 1)
{
throw new Exception(Util.i18n("moreThanZero"));
}
if (!m1)
{
ItemDb.get(l1[1]);
}
if (m2)
{
if (user.getMoney() < r2)
{
throw new Exception(Util.i18n("notEnoughMoney"));
}
user.takeMoney(r2);
//user.sendMessage("r2: " + r2 + " q2: " + q2);
}
else
{
ItemStack i2 = ItemDb.get(l2[1], (int)r2);
if (!InventoryWorkaround.containsItem(user.getInventory(), true, i2))
{
throw new Exception(Util.format("missingItems", (int)r2, l2[1]));
}
InventoryWorkaround.removeItem(user.getInventory(), true, i2);
user.updateInventory();
}
event.setLine(0, "§1[Trade]");
event.setLine(1, (m1 ? Util.formatCurrency(q1) : (int)q1 + " " + l1[1]) + ":0");
event.setLine(2, (m2 ? Util.formatCurrency(q2) : (int)q2 + " " + l2[1]) + ":" + (m2 ? Util.roundDouble(r2) : "" + (int)r2));
event.setLine(3, "§8" + username);
}
catch (Throwable ex)
{
user.sendMessage(Util.format("errorWithMessage", ex.getMessage()));
if (ess.getSettings().isDebug())
{
logger.log(Level.WARNING, ex.getMessage(), ex);
}
event.setLine(0, "§4[Trade]");
event.setLine(1, "# ItemOr" + ess.getSettings().getCurrencySymbol());
event.setLine(2, "# ItemOr" + ess.getSettings().getCurrencySymbol() + ":#");
event.setLine(3, "§8" + username);
}
return;
}
}
|
diff --git a/src/main/java/GiovanniDini/app/Main.java b/src/main/java/GiovanniDini/app/Main.java
index 435f6ff..49b8acb 100644
--- a/src/main/java/GiovanniDini/app/Main.java
+++ b/src/main/java/GiovanniDini/app/Main.java
@@ -1,215 +1,218 @@
package GiovanniDini.app;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public static void main(String[] args) {
/**
* Nasco.
*/
//System.out.println("Thread main partito.");
/**
* Ricevo l'URL iniziale e faccio partire il manager.
* Ricevo da input da tastiera l'URL iniziale, lo inserisco nella lista
* degli URL da visitare, istanzio il manager e gli passo le liste.
*/
System.out.println("Progetto di Ingegneria del Software\n");
System.out.println("Autore: Giovanni Dini");
System.out.println("Matricola: 232274");
System.out.println("Email: [email protected]\n");
System.out.println("Operazioni disponibili:");
System.out.println("- Inserire l'URL da cui cominciare l'analisi \n- Digitare \"file\" se ");
System.out.print("si desidera leggere la workload dal file apposito (workload.csv)");
System.out.println("- Digitare \"restart\" se si desidera riprendere una vecchia sessione :");
- System.out.println("(digitare \"help\" per istruzioni o \"exit\" per uscire):\n\n");
+ System.out.println("(digitare \"help\" per istruzioni o \"exit\" per uscire):");
Scanner user_input = new Scanner(System.in);
String first_url;
first_url = user_input.next();
while ("help".equals(first_url)) {
System.out.print("\n\n*----------*\n\nCosa è e a cosa serve questo software?");
System.out.print("\n\nQuesto software genera un sistema di crawler che girano per la rete, ");
System.out.print("raccogliendo indirizzi email e salvandoli per un successivo utilizzo.");
System.out.print("\n\n*----------*\n\nCome si utilizza?");
System.out.print("\n\nIl funzionamento è molto semplice: è sufficiente inserire un URL ");
System.out.print("(nel formato http://www.sito.com) e il programma lo analizzerà, raccogliendo ");
System.out.print("automaticamente gli indirizzi dei link che troverà e analizzando successivamente ");
System.out.print("anche quelli. Tutti gli indirizzi email trovati durante l'analisi sono salvati per ");
System.out.print("un successivo utilizzo. ");
System.out.print("\n\n*----------*\n\nQuale è l'utilità pratica di questo software?");
System.out.print("\n\nIn questa versione il software si limita a raccogliere indirizzi email ");
System.out.print("(si ricorda che lo spam non è una pratica legale), ma con poche e semplici ");
System.out.print("modifiche è possibile fargli raccogliere e analizzare praticamente tutto ciò che ");
System.out.print("può essere contenuto in una pagina web. Vista la natura di questo software ");
System.out.print("(realizzato per un progetto d'esame), è da considerarsi un puro esercizio, ma che ");
System.out.print("con poche modifiche può avere scopi decisamente più utili.");
System.out.print("\n\n*----------*\n\nQuali comode funzionalità offre questo programma?");
System.out.print("\n\n-Gli URL da visitare possono essere passati anche tramite file (workload.csv).");
System.out.print("\n-Gli URL già visitati sono salvati in un file di testo e riletti ogni volta che ");
System.out.print("il programma viene avviato, per evitare di ripetere lavoro già fatto in precedenza.");
System.out.print("\n-Stessa cosa viene fatta per gli indirizzi email.");
System.out.print("\n-I parametri di configurazione del programma sono contenuti in un semplice file di ");
System.out.print("testo e comprendono il numero massimo di thread crawlers che operano in contemporanea ");
System.out.print("e la profondità dell'analisi (espressa nel numero massimo di URL da analizzare.");
System.out.print("\n\n*----------*\n\nIl programma è coperto da copyright?");
System.out.print("\n\nLa licenza con cui viene fornito questo software è la Attribution-NonCommercial-ShareAlike ");
System.out.print("3.0 Unported (CC BY-NC-SA 3.0). E' possibile modificare questo software e ridistribuirlo ");
System.out.print("solo riportandone l'autore originale (Giovanni Dini). Non è possibile derivarne prodotti ");
System.out.print("commerciali. Ogni derivazione dovrà essere distribuita sotto la stessa licenza.\n");
System.out.println("\nInserire l'URL da cui cominciare l'analisi, oppure digitare \"file\" se ");
System.out.println("si desidera leggere la workload dal file apposito ");
- System.out.println("(digitare \"help\" per istruzioni o \"exit\" per uscire):\n\n");
+ System.out.println("(digitare \"help\" per istruzioni o \"exit\" per uscire):");
first_url = user_input.next();
}
//System.out.println("Hai inserito questo testo: "+first_url);
/**
* Genero le liste che saranno utilizzate.
*/
ArrayList workload = new ArrayList();
ArrayList visited = new ArrayList();
ArrayList emails = new ArrayList();
ArrayList param = new ArrayList();
if ("exit".equals(first_url)){
return;
}
if ("file".equals(first_url)) {
File workloadFile = new File ("workload.csv");
if(!workloadFile.exists()) {
try {
workloadFile.createNewFile();
System.out.println("\n\nIl file non esisteva. Aggiungere manualmente il primo URL da analizzare: ");
first_url = user_input.next();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.println("Devo leggere il file.");
Organizer.fileWorkload(workloadFile, workload);
first_url = (String) workload.get(0);
System.out.println("Devo analizzare questo: "+first_url);
}
if ("restart".equals(first_url)) {
File lastWorkload = new File ("nextWorkload.csv");
if(!lastWorkload.exists()) {
- System.out.println("\n\nIl file non esisteva. Aggiungere manualmente il primo URL da analizzare: ");
+ System.out.println("\nIl file nextWorkload.csv non esiste. Aggiungere manualmente il primo URL da analizzare:");
first_url = user_input.next();
- }
+ } else {
System.out.println("Riprendo il lavoro dall'ultima sessione.");
Organizer.fileWorkload(lastWorkload, workload);
+ first_url = (String) workload.get(0);
+ System.out.println("Devo analizzare questo: "+first_url);
+ }
}
File emailsFile = new File("emails.csv");
File visitedFile = new File ("visited.csv");
if(!emailsFile.exists()) {
try {
emailsFile.createNewFile();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(!visitedFile.exists()) {
try {
visitedFile.createNewFile();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
Organizer.fileEmails(emailsFile, emails);
Organizer.fileVisited(visitedFile, visited);
workload.add(first_url);
/**
* Genero il manager.
*/
int numCrawlers;
int maxURLS;
File paramFile = new File ("preferences.cfg");
if(!paramFile.exists()) {
System.out.println("Il file di configurazione non esiste. Saranno utilizzati i parametri di default: ");
System.out.println("Numero di crawlers in contemporanea: 5.\nProfondità dell'analisi: 30 URLs.");
numCrawlers = 5;
maxURLS = 30;
} else {
Organizer.fileParam(paramFile, param);
numCrawlers = (Integer) param.get(0);
maxURLS = (Integer) param.get(1);
System.out.println("\nTrovato file di configurazione. Il programma avrà questi parametri: ");
System.out.println("-Numero di crawlers in contemporanea: "+numCrawlers);
System.out.println("-Profondità dell'analisi: "+maxURLS+" URLS\n");
}
Runnable manager = new Manager(workload, visited, emails, numCrawlers, maxURLS);
Thread m = new Thread(manager);
m.start();
m.setName("Manager");
try {
m.join();
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
/**
* Genero l'organizer.
*/
Runnable organizer = new Organizer(visited, emails);
Thread o = new Thread(organizer);
o.start();
o.setName("Organizer");
try {
o.join();
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("L'analisi è stata completata. ");
System.out.println("Ci sono ancora "+workload.size()+" URL nella workload.");
System.out.println("Vuoi che siano scritti in un file in modo da poter proseguire l'analisi successivamente? si/no");
String answer = user_input.next();
if ("si".equals(answer)){
File finalWorkload = new File("nextWorkload.csv");
Organizer.finalWorkload(finalWorkload, workload);
}
/**
* Muoio.
*/
/*if(m.isAlive() == true){
System.out.println("*--------*");
System.out.println("Il manager è vivo");
} else {
System.out.println("*--------*");
System.out.println("Il manager è morto");
}
if(o.isAlive() == true){
System.out.println("*--------*");
System.out.println("L'organizer è vivo");
} else {
System.out.println("*--------*");
System.out.println("L'organizer è morto");
}*/
/*System.out.println("*--------*");
System.out.println("Lista degli URL visitati: ");
Manager.printList(visited);
System.out.println("*--------*");
System.out.println("Lista delle email trovate: ");
Manager.printList(emails);*/
//System.out.println("\n\nMain in attesa di terminazione.");
}
}
| false | true | public static void main(String[] args) {
/**
* Nasco.
*/
//System.out.println("Thread main partito.");
/**
* Ricevo l'URL iniziale e faccio partire il manager.
* Ricevo da input da tastiera l'URL iniziale, lo inserisco nella lista
* degli URL da visitare, istanzio il manager e gli passo le liste.
*/
System.out.println("Progetto di Ingegneria del Software\n");
System.out.println("Autore: Giovanni Dini");
System.out.println("Matricola: 232274");
System.out.println("Email: [email protected]\n");
System.out.println("Operazioni disponibili:");
System.out.println("- Inserire l'URL da cui cominciare l'analisi \n- Digitare \"file\" se ");
System.out.print("si desidera leggere la workload dal file apposito (workload.csv)");
System.out.println("- Digitare \"restart\" se si desidera riprendere una vecchia sessione :");
System.out.println("(digitare \"help\" per istruzioni o \"exit\" per uscire):\n\n");
Scanner user_input = new Scanner(System.in);
String first_url;
first_url = user_input.next();
while ("help".equals(first_url)) {
System.out.print("\n\n*----------*\n\nCosa è e a cosa serve questo software?");
System.out.print("\n\nQuesto software genera un sistema di crawler che girano per la rete, ");
System.out.print("raccogliendo indirizzi email e salvandoli per un successivo utilizzo.");
System.out.print("\n\n*----------*\n\nCome si utilizza?");
System.out.print("\n\nIl funzionamento è molto semplice: è sufficiente inserire un URL ");
System.out.print("(nel formato http://www.sito.com) e il programma lo analizzerà, raccogliendo ");
System.out.print("automaticamente gli indirizzi dei link che troverà e analizzando successivamente ");
System.out.print("anche quelli. Tutti gli indirizzi email trovati durante l'analisi sono salvati per ");
System.out.print("un successivo utilizzo. ");
System.out.print("\n\n*----------*\n\nQuale è l'utilità pratica di questo software?");
System.out.print("\n\nIn questa versione il software si limita a raccogliere indirizzi email ");
System.out.print("(si ricorda che lo spam non è una pratica legale), ma con poche e semplici ");
System.out.print("modifiche è possibile fargli raccogliere e analizzare praticamente tutto ciò che ");
System.out.print("può essere contenuto in una pagina web. Vista la natura di questo software ");
System.out.print("(realizzato per un progetto d'esame), è da considerarsi un puro esercizio, ma che ");
System.out.print("con poche modifiche può avere scopi decisamente più utili.");
System.out.print("\n\n*----------*\n\nQuali comode funzionalità offre questo programma?");
System.out.print("\n\n-Gli URL da visitare possono essere passati anche tramite file (workload.csv).");
System.out.print("\n-Gli URL già visitati sono salvati in un file di testo e riletti ogni volta che ");
System.out.print("il programma viene avviato, per evitare di ripetere lavoro già fatto in precedenza.");
System.out.print("\n-Stessa cosa viene fatta per gli indirizzi email.");
System.out.print("\n-I parametri di configurazione del programma sono contenuti in un semplice file di ");
System.out.print("testo e comprendono il numero massimo di thread crawlers che operano in contemporanea ");
System.out.print("e la profondità dell'analisi (espressa nel numero massimo di URL da analizzare.");
System.out.print("\n\n*----------*\n\nIl programma è coperto da copyright?");
System.out.print("\n\nLa licenza con cui viene fornito questo software è la Attribution-NonCommercial-ShareAlike ");
System.out.print("3.0 Unported (CC BY-NC-SA 3.0). E' possibile modificare questo software e ridistribuirlo ");
System.out.print("solo riportandone l'autore originale (Giovanni Dini). Non è possibile derivarne prodotti ");
System.out.print("commerciali. Ogni derivazione dovrà essere distribuita sotto la stessa licenza.\n");
System.out.println("\nInserire l'URL da cui cominciare l'analisi, oppure digitare \"file\" se ");
System.out.println("si desidera leggere la workload dal file apposito ");
System.out.println("(digitare \"help\" per istruzioni o \"exit\" per uscire):\n\n");
first_url = user_input.next();
}
//System.out.println("Hai inserito questo testo: "+first_url);
/**
* Genero le liste che saranno utilizzate.
*/
ArrayList workload = new ArrayList();
ArrayList visited = new ArrayList();
ArrayList emails = new ArrayList();
ArrayList param = new ArrayList();
if ("exit".equals(first_url)){
return;
}
if ("file".equals(first_url)) {
File workloadFile = new File ("workload.csv");
if(!workloadFile.exists()) {
try {
workloadFile.createNewFile();
System.out.println("\n\nIl file non esisteva. Aggiungere manualmente il primo URL da analizzare: ");
first_url = user_input.next();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.println("Devo leggere il file.");
Organizer.fileWorkload(workloadFile, workload);
first_url = (String) workload.get(0);
System.out.println("Devo analizzare questo: "+first_url);
}
if ("restart".equals(first_url)) {
File lastWorkload = new File ("nextWorkload.csv");
if(!lastWorkload.exists()) {
System.out.println("\n\nIl file non esisteva. Aggiungere manualmente il primo URL da analizzare: ");
first_url = user_input.next();
}
System.out.println("Riprendo il lavoro dall'ultima sessione.");
Organizer.fileWorkload(lastWorkload, workload);
}
File emailsFile = new File("emails.csv");
File visitedFile = new File ("visited.csv");
if(!emailsFile.exists()) {
try {
emailsFile.createNewFile();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(!visitedFile.exists()) {
try {
visitedFile.createNewFile();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
Organizer.fileEmails(emailsFile, emails);
Organizer.fileVisited(visitedFile, visited);
workload.add(first_url);
/**
* Genero il manager.
*/
int numCrawlers;
int maxURLS;
File paramFile = new File ("preferences.cfg");
if(!paramFile.exists()) {
System.out.println("Il file di configurazione non esiste. Saranno utilizzati i parametri di default: ");
System.out.println("Numero di crawlers in contemporanea: 5.\nProfondità dell'analisi: 30 URLs.");
numCrawlers = 5;
maxURLS = 30;
} else {
Organizer.fileParam(paramFile, param);
numCrawlers = (Integer) param.get(0);
maxURLS = (Integer) param.get(1);
System.out.println("\nTrovato file di configurazione. Il programma avrà questi parametri: ");
System.out.println("-Numero di crawlers in contemporanea: "+numCrawlers);
System.out.println("-Profondità dell'analisi: "+maxURLS+" URLS\n");
}
Runnable manager = new Manager(workload, visited, emails, numCrawlers, maxURLS);
Thread m = new Thread(manager);
m.start();
m.setName("Manager");
try {
m.join();
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
/**
* Genero l'organizer.
*/
Runnable organizer = new Organizer(visited, emails);
Thread o = new Thread(organizer);
o.start();
o.setName("Organizer");
try {
o.join();
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("L'analisi è stata completata. ");
System.out.println("Ci sono ancora "+workload.size()+" URL nella workload.");
System.out.println("Vuoi che siano scritti in un file in modo da poter proseguire l'analisi successivamente? si/no");
String answer = user_input.next();
if ("si".equals(answer)){
File finalWorkload = new File("nextWorkload.csv");
Organizer.finalWorkload(finalWorkload, workload);
}
/**
* Muoio.
*/
/*if(m.isAlive() == true){
System.out.println("*--------*");
System.out.println("Il manager è vivo");
} else {
| public static void main(String[] args) {
/**
* Nasco.
*/
//System.out.println("Thread main partito.");
/**
* Ricevo l'URL iniziale e faccio partire il manager.
* Ricevo da input da tastiera l'URL iniziale, lo inserisco nella lista
* degli URL da visitare, istanzio il manager e gli passo le liste.
*/
System.out.println("Progetto di Ingegneria del Software\n");
System.out.println("Autore: Giovanni Dini");
System.out.println("Matricola: 232274");
System.out.println("Email: [email protected]\n");
System.out.println("Operazioni disponibili:");
System.out.println("- Inserire l'URL da cui cominciare l'analisi \n- Digitare \"file\" se ");
System.out.print("si desidera leggere la workload dal file apposito (workload.csv)");
System.out.println("- Digitare \"restart\" se si desidera riprendere una vecchia sessione :");
System.out.println("(digitare \"help\" per istruzioni o \"exit\" per uscire):");
Scanner user_input = new Scanner(System.in);
String first_url;
first_url = user_input.next();
while ("help".equals(first_url)) {
System.out.print("\n\n*----------*\n\nCosa è e a cosa serve questo software?");
System.out.print("\n\nQuesto software genera un sistema di crawler che girano per la rete, ");
System.out.print("raccogliendo indirizzi email e salvandoli per un successivo utilizzo.");
System.out.print("\n\n*----------*\n\nCome si utilizza?");
System.out.print("\n\nIl funzionamento è molto semplice: è sufficiente inserire un URL ");
System.out.print("(nel formato http://www.sito.com) e il programma lo analizzerà, raccogliendo ");
System.out.print("automaticamente gli indirizzi dei link che troverà e analizzando successivamente ");
System.out.print("anche quelli. Tutti gli indirizzi email trovati durante l'analisi sono salvati per ");
System.out.print("un successivo utilizzo. ");
System.out.print("\n\n*----------*\n\nQuale è l'utilità pratica di questo software?");
System.out.print("\n\nIn questa versione il software si limita a raccogliere indirizzi email ");
System.out.print("(si ricorda che lo spam non è una pratica legale), ma con poche e semplici ");
System.out.print("modifiche è possibile fargli raccogliere e analizzare praticamente tutto ciò che ");
System.out.print("può essere contenuto in una pagina web. Vista la natura di questo software ");
System.out.print("(realizzato per un progetto d'esame), è da considerarsi un puro esercizio, ma che ");
System.out.print("con poche modifiche può avere scopi decisamente più utili.");
System.out.print("\n\n*----------*\n\nQuali comode funzionalità offre questo programma?");
System.out.print("\n\n-Gli URL da visitare possono essere passati anche tramite file (workload.csv).");
System.out.print("\n-Gli URL già visitati sono salvati in un file di testo e riletti ogni volta che ");
System.out.print("il programma viene avviato, per evitare di ripetere lavoro già fatto in precedenza.");
System.out.print("\n-Stessa cosa viene fatta per gli indirizzi email.");
System.out.print("\n-I parametri di configurazione del programma sono contenuti in un semplice file di ");
System.out.print("testo e comprendono il numero massimo di thread crawlers che operano in contemporanea ");
System.out.print("e la profondità dell'analisi (espressa nel numero massimo di URL da analizzare.");
System.out.print("\n\n*----------*\n\nIl programma è coperto da copyright?");
System.out.print("\n\nLa licenza con cui viene fornito questo software è la Attribution-NonCommercial-ShareAlike ");
System.out.print("3.0 Unported (CC BY-NC-SA 3.0). E' possibile modificare questo software e ridistribuirlo ");
System.out.print("solo riportandone l'autore originale (Giovanni Dini). Non è possibile derivarne prodotti ");
System.out.print("commerciali. Ogni derivazione dovrà essere distribuita sotto la stessa licenza.\n");
System.out.println("\nInserire l'URL da cui cominciare l'analisi, oppure digitare \"file\" se ");
System.out.println("si desidera leggere la workload dal file apposito ");
System.out.println("(digitare \"help\" per istruzioni o \"exit\" per uscire):");
first_url = user_input.next();
}
//System.out.println("Hai inserito questo testo: "+first_url);
/**
* Genero le liste che saranno utilizzate.
*/
ArrayList workload = new ArrayList();
ArrayList visited = new ArrayList();
ArrayList emails = new ArrayList();
ArrayList param = new ArrayList();
if ("exit".equals(first_url)){
return;
}
if ("file".equals(first_url)) {
File workloadFile = new File ("workload.csv");
if(!workloadFile.exists()) {
try {
workloadFile.createNewFile();
System.out.println("\n\nIl file non esisteva. Aggiungere manualmente il primo URL da analizzare: ");
first_url = user_input.next();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.println("Devo leggere il file.");
Organizer.fileWorkload(workloadFile, workload);
first_url = (String) workload.get(0);
System.out.println("Devo analizzare questo: "+first_url);
}
if ("restart".equals(first_url)) {
File lastWorkload = new File ("nextWorkload.csv");
if(!lastWorkload.exists()) {
System.out.println("\nIl file nextWorkload.csv non esiste. Aggiungere manualmente il primo URL da analizzare:");
first_url = user_input.next();
} else {
System.out.println("Riprendo il lavoro dall'ultima sessione.");
Organizer.fileWorkload(lastWorkload, workload);
first_url = (String) workload.get(0);
System.out.println("Devo analizzare questo: "+first_url);
}
}
File emailsFile = new File("emails.csv");
File visitedFile = new File ("visited.csv");
if(!emailsFile.exists()) {
try {
emailsFile.createNewFile();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(!visitedFile.exists()) {
try {
visitedFile.createNewFile();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
Organizer.fileEmails(emailsFile, emails);
Organizer.fileVisited(visitedFile, visited);
workload.add(first_url);
/**
* Genero il manager.
*/
int numCrawlers;
int maxURLS;
File paramFile = new File ("preferences.cfg");
if(!paramFile.exists()) {
System.out.println("Il file di configurazione non esiste. Saranno utilizzati i parametri di default: ");
System.out.println("Numero di crawlers in contemporanea: 5.\nProfondità dell'analisi: 30 URLs.");
numCrawlers = 5;
maxURLS = 30;
} else {
Organizer.fileParam(paramFile, param);
numCrawlers = (Integer) param.get(0);
maxURLS = (Integer) param.get(1);
System.out.println("\nTrovato file di configurazione. Il programma avrà questi parametri: ");
System.out.println("-Numero di crawlers in contemporanea: "+numCrawlers);
System.out.println("-Profondità dell'analisi: "+maxURLS+" URLS\n");
}
Runnable manager = new Manager(workload, visited, emails, numCrawlers, maxURLS);
Thread m = new Thread(manager);
m.start();
m.setName("Manager");
try {
m.join();
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
/**
* Genero l'organizer.
*/
Runnable organizer = new Organizer(visited, emails);
Thread o = new Thread(organizer);
o.start();
o.setName("Organizer");
try {
o.join();
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("L'analisi è stata completata. ");
System.out.println("Ci sono ancora "+workload.size()+" URL nella workload.");
System.out.println("Vuoi che siano scritti in un file in modo da poter proseguire l'analisi successivamente? si/no");
String answer = user_input.next();
if ("si".equals(answer)){
File finalWorkload = new File("nextWorkload.csv");
Organizer.finalWorkload(finalWorkload, workload);
}
/**
* Muoio.
*/
/*if(m.isAlive() == true){
System.out.println("*--------*");
System.out.println("Il manager è vivo");
} else {
|
diff --git a/geogebra/geogebra3D/euclidian3D/DrawAxis3D.java b/geogebra/geogebra3D/euclidian3D/DrawAxis3D.java
index 76d2b0614..3ed2aeafc 100644
--- a/geogebra/geogebra3D/euclidian3D/DrawAxis3D.java
+++ b/geogebra/geogebra3D/euclidian3D/DrawAxis3D.java
@@ -1,142 +1,142 @@
package geogebra3D.euclidian3D;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import geogebra.main.Application;
import geogebra3D.Matrix.Ggb3DMatrix4x4;
import geogebra3D.Matrix.Ggb3DVector;
import geogebra3D.euclidian3D.opengl.Renderer;
import geogebra3D.kernel3D.GeoAxis3D;
import geogebra3D.kernel3D.GeoCoordSys1D;
import geogebra3D.kernel3D.GeoElement3D;
import geogebra3D.kernel3D.GeoElement3DInterface;
public class DrawAxis3D extends DrawLine3D {
public DrawAxis3D(EuclidianView3D a_view3D, GeoAxis3D axis3D){
super(a_view3D, axis3D);
}
public void drawGeometry(Renderer renderer) {
renderer.setArrowType(Renderer.ARROW_TYPE_SIMPLE);
renderer.setArrowLength(20);
renderer.setArrowWidth(10);
super.drawGeometry(renderer);
renderer.setArrowType(Renderer.ARROW_TYPE_NONE);
}
/**
* drawLabel is used here for ticks
*/
public void drawLabel(Renderer renderer){
if(!getGeoElement().isEuclidianVisible())
return;
if (!getGeoElement().isLabelVisible())
return;
renderer.setTextColor(getGeoElement().getObjectColor());
renderer.setColor(getGeoElement().getObjectColor(), 1);
renderer.setDash(Renderer.DASH_NONE);
double ticksSize = 5;
//gets the direction vector of the axis as it is drawn on screen
//TODO do this when updated
Ggb3DVector v = ((GeoCoordSys1D) getGeoElement()).getVx().copyVector();
getView3D().toScreenCoords3D(v);
v.set(3, 0); //set z-coord to 0
double vScale = v.norm(); //axis scale, used for ticks distance
//v.normalize();
//calc orthogonal offsets
int vx = (int) (v.get(1)*3*ticksSize/vScale);
int vy = (int) (v.get(2)*3*ticksSize/vScale);
int xOffset = -vy;
int yOffset = vx;
if (yOffset>0){
xOffset = -xOffset;
yOffset = -yOffset;
}
//interval between two ticks
//TODO merge with EuclidianView.setAxesIntervals(double scale, int axis)
//Application.debug("vscale : "+vScale);
double maxPix = 100; // only one tick is allowed per maxPix pixels
- double units = 100*maxPix / (getView3D().getScale()*vScale);
+ double units = maxPix / vScale;
int exp = (int) Math.floor(Math.log(units) / Math.log(10));
int maxFractionDigtis = Math.max(-exp, getView3D().getKernel().getPrintDecimals());
NumberFormat numberFormat = new DecimalFormat();
((DecimalFormat) numberFormat).applyPattern("###0.##");
numberFormat.setMaximumFractionDigits(maxFractionDigtis);
double pot = Math.pow(10, exp);
double n = units / pot;
double distance;
if (n > 5) {
distance = 5 * pot;
} else if (n > 2) {
distance = 2 * pot;
} else {
distance = pot;
}
//matrix for each number
Ggb3DMatrix4x4 numbersMatrix = Ggb3DMatrix4x4.Identity();
//matrix for each ticks
Ggb3DMatrix4x4 ticksMatrix = new Ggb3DMatrix4x4();
Ggb3DMatrix4x4 drawingMatrix = ((GeoElement3D) getGeoElement()).getDrawingMatrix();
double ticksThickness = 1/getView3D().getScale();
ticksMatrix.setVx(drawingMatrix.getVx().normalized());
ticksMatrix.setVy((Ggb3DVector) drawingMatrix.getVy().mul(ticksSize));
ticksMatrix.setVz((Ggb3DVector) drawingMatrix.getVz().mul(ticksSize));
//for(int i=(int) getDrawMin();i<=getDrawMax();i++){
for(int i=(int) (getDrawMin()/distance);i<=getDrawMax()/distance;i++){
double val = i*distance;
Ggb3DVector origin = ((GeoCoordSys1D) getGeoElement()).getPoint(val);
//draw numbers
String strNum = getView3D().getKernel().formatPiE(val,numberFormat);
numbersMatrix.setOrigin(origin);
renderer.setMatrix(numbersMatrix);
renderer.drawText(xOffset-4,yOffset-6, strNum,true); //TODO values 4 and 6 depend to label size
//draw ticks
ticksMatrix.setOrigin(origin);
renderer.setMatrix(ticksMatrix);
renderer.drawSegment(-ticksThickness, ticksThickness);
}
numbersMatrix.setOrigin(((GeoCoordSys1D) getGeoElement()).getPoint(getDrawMax()));
renderer.setMatrix(numbersMatrix);
renderer.drawText(-vx-xOffset-4,-vy-yOffset-6, ((GeoAxis3D) getGeoElement()).getAxisLabel(),true); //TODO values 4 and 6 depend to label size
}
}
| true | true | public void drawLabel(Renderer renderer){
if(!getGeoElement().isEuclidianVisible())
return;
if (!getGeoElement().isLabelVisible())
return;
renderer.setTextColor(getGeoElement().getObjectColor());
renderer.setColor(getGeoElement().getObjectColor(), 1);
renderer.setDash(Renderer.DASH_NONE);
double ticksSize = 5;
//gets the direction vector of the axis as it is drawn on screen
//TODO do this when updated
Ggb3DVector v = ((GeoCoordSys1D) getGeoElement()).getVx().copyVector();
getView3D().toScreenCoords3D(v);
v.set(3, 0); //set z-coord to 0
double vScale = v.norm(); //axis scale, used for ticks distance
//v.normalize();
//calc orthogonal offsets
int vx = (int) (v.get(1)*3*ticksSize/vScale);
int vy = (int) (v.get(2)*3*ticksSize/vScale);
int xOffset = -vy;
int yOffset = vx;
if (yOffset>0){
xOffset = -xOffset;
yOffset = -yOffset;
}
//interval between two ticks
//TODO merge with EuclidianView.setAxesIntervals(double scale, int axis)
//Application.debug("vscale : "+vScale);
double maxPix = 100; // only one tick is allowed per maxPix pixels
double units = 100*maxPix / (getView3D().getScale()*vScale);
int exp = (int) Math.floor(Math.log(units) / Math.log(10));
int maxFractionDigtis = Math.max(-exp, getView3D().getKernel().getPrintDecimals());
NumberFormat numberFormat = new DecimalFormat();
((DecimalFormat) numberFormat).applyPattern("###0.##");
numberFormat.setMaximumFractionDigits(maxFractionDigtis);
double pot = Math.pow(10, exp);
double n = units / pot;
double distance;
if (n > 5) {
distance = 5 * pot;
} else if (n > 2) {
distance = 2 * pot;
} else {
distance = pot;
}
//matrix for each number
Ggb3DMatrix4x4 numbersMatrix = Ggb3DMatrix4x4.Identity();
//matrix for each ticks
Ggb3DMatrix4x4 ticksMatrix = new Ggb3DMatrix4x4();
Ggb3DMatrix4x4 drawingMatrix = ((GeoElement3D) getGeoElement()).getDrawingMatrix();
double ticksThickness = 1/getView3D().getScale();
ticksMatrix.setVx(drawingMatrix.getVx().normalized());
ticksMatrix.setVy((Ggb3DVector) drawingMatrix.getVy().mul(ticksSize));
ticksMatrix.setVz((Ggb3DVector) drawingMatrix.getVz().mul(ticksSize));
//for(int i=(int) getDrawMin();i<=getDrawMax();i++){
for(int i=(int) (getDrawMin()/distance);i<=getDrawMax()/distance;i++){
double val = i*distance;
Ggb3DVector origin = ((GeoCoordSys1D) getGeoElement()).getPoint(val);
//draw numbers
String strNum = getView3D().getKernel().formatPiE(val,numberFormat);
numbersMatrix.setOrigin(origin);
renderer.setMatrix(numbersMatrix);
renderer.drawText(xOffset-4,yOffset-6, strNum,true); //TODO values 4 and 6 depend to label size
//draw ticks
ticksMatrix.setOrigin(origin);
renderer.setMatrix(ticksMatrix);
renderer.drawSegment(-ticksThickness, ticksThickness);
}
numbersMatrix.setOrigin(((GeoCoordSys1D) getGeoElement()).getPoint(getDrawMax()));
renderer.setMatrix(numbersMatrix);
renderer.drawText(-vx-xOffset-4,-vy-yOffset-6, ((GeoAxis3D) getGeoElement()).getAxisLabel(),true); //TODO values 4 and 6 depend to label size
}
| public void drawLabel(Renderer renderer){
if(!getGeoElement().isEuclidianVisible())
return;
if (!getGeoElement().isLabelVisible())
return;
renderer.setTextColor(getGeoElement().getObjectColor());
renderer.setColor(getGeoElement().getObjectColor(), 1);
renderer.setDash(Renderer.DASH_NONE);
double ticksSize = 5;
//gets the direction vector of the axis as it is drawn on screen
//TODO do this when updated
Ggb3DVector v = ((GeoCoordSys1D) getGeoElement()).getVx().copyVector();
getView3D().toScreenCoords3D(v);
v.set(3, 0); //set z-coord to 0
double vScale = v.norm(); //axis scale, used for ticks distance
//v.normalize();
//calc orthogonal offsets
int vx = (int) (v.get(1)*3*ticksSize/vScale);
int vy = (int) (v.get(2)*3*ticksSize/vScale);
int xOffset = -vy;
int yOffset = vx;
if (yOffset>0){
xOffset = -xOffset;
yOffset = -yOffset;
}
//interval between two ticks
//TODO merge with EuclidianView.setAxesIntervals(double scale, int axis)
//Application.debug("vscale : "+vScale);
double maxPix = 100; // only one tick is allowed per maxPix pixels
double units = maxPix / vScale;
int exp = (int) Math.floor(Math.log(units) / Math.log(10));
int maxFractionDigtis = Math.max(-exp, getView3D().getKernel().getPrintDecimals());
NumberFormat numberFormat = new DecimalFormat();
((DecimalFormat) numberFormat).applyPattern("###0.##");
numberFormat.setMaximumFractionDigits(maxFractionDigtis);
double pot = Math.pow(10, exp);
double n = units / pot;
double distance;
if (n > 5) {
distance = 5 * pot;
} else if (n > 2) {
distance = 2 * pot;
} else {
distance = pot;
}
//matrix for each number
Ggb3DMatrix4x4 numbersMatrix = Ggb3DMatrix4x4.Identity();
//matrix for each ticks
Ggb3DMatrix4x4 ticksMatrix = new Ggb3DMatrix4x4();
Ggb3DMatrix4x4 drawingMatrix = ((GeoElement3D) getGeoElement()).getDrawingMatrix();
double ticksThickness = 1/getView3D().getScale();
ticksMatrix.setVx(drawingMatrix.getVx().normalized());
ticksMatrix.setVy((Ggb3DVector) drawingMatrix.getVy().mul(ticksSize));
ticksMatrix.setVz((Ggb3DVector) drawingMatrix.getVz().mul(ticksSize));
//for(int i=(int) getDrawMin();i<=getDrawMax();i++){
for(int i=(int) (getDrawMin()/distance);i<=getDrawMax()/distance;i++){
double val = i*distance;
Ggb3DVector origin = ((GeoCoordSys1D) getGeoElement()).getPoint(val);
//draw numbers
String strNum = getView3D().getKernel().formatPiE(val,numberFormat);
numbersMatrix.setOrigin(origin);
renderer.setMatrix(numbersMatrix);
renderer.drawText(xOffset-4,yOffset-6, strNum,true); //TODO values 4 and 6 depend to label size
//draw ticks
ticksMatrix.setOrigin(origin);
renderer.setMatrix(ticksMatrix);
renderer.drawSegment(-ticksThickness, ticksThickness);
}
numbersMatrix.setOrigin(((GeoCoordSys1D) getGeoElement()).getPoint(getDrawMax()));
renderer.setMatrix(numbersMatrix);
renderer.drawText(-vx-xOffset-4,-vy-yOffset-6, ((GeoAxis3D) getGeoElement()).getAxisLabel(),true); //TODO values 4 and 6 depend to label size
}
|
diff --git a/src/ru/regenix/jphp/cli/CLI.java b/src/ru/regenix/jphp/cli/CLI.java
index cea2b543..c9ecd6f6 100644
--- a/src/ru/regenix/jphp/cli/CLI.java
+++ b/src/ru/regenix/jphp/cli/CLI.java
@@ -1,104 +1,106 @@
package ru.regenix.jphp.cli;
import com.beust.jcommander.JCommander;
import ru.regenix.jphp.Information;
import ru.regenix.jphp.compiler.AbstractCompiler;
import ru.regenix.jphp.compiler.CompileScope;
import ru.regenix.jphp.compiler.jvm.JvmCompiler;
import ru.regenix.jphp.runtime.env.Context;
import ru.regenix.jphp.runtime.env.Environment;
import ru.regenix.jphp.runtime.ext.*;
import ru.regenix.jphp.runtime.reflection.ModuleEntity;
import java.io.File;
import java.io.PrintStream;
public class CLI {
private final CompileScope compileScope = new CompileScope();
private final Arguments arguments;
private final PrintStream output;
private final JCommander commander;
{
compileScope.registerExtension(new CoreExtension());
compileScope.registerExtension(new BCMathExtension());
compileScope.registerExtension(new CTypeExtension());
compileScope.registerExtension(new DateExtension());
compileScope.registerExtension(new SPLExtension());
}
public CLI(JCommander commander, Arguments arguments, PrintStream output){
this.commander = commander;
this.output = output;
this.arguments = arguments;
}
public void echo(String str){
output.write(str.getBytes(), 0, str.length());
}
protected void showHelp(){
StringBuilder builder = new StringBuilder();
commander.usage(builder);
echo(builder.toString());
}
protected void showVersion(){
output.printf("%s %s like PHP %s",
Information.NAME, Information.CORE_VERSION, Information.LIKE_PHP_VERSION
);
output.println();
output.println("Copyright (c) " + Information.COPYRIGHT);
output.println("License: " + Information.LICENSE);
output.println();
}
protected void executeFile(String filename){
File file = new File(filename);
Environment environment = new Environment(compileScope, output);
try {
Context context = environment.createContext(file);
AbstractCompiler compiler = new JvmCompiler(environment, context);
ModuleEntity module = compiler.compile();
compileScope.loadModule(module);
environment.registerModule(module);
module.includeNoThrow(environment);
} catch (Exception e){
environment.catchUncaught(e);
+ } catch (Throwable throwable) {
+ throw new RuntimeException(throwable);
} finally {
try {
environment.doFinal();
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
}
}
public void process(){
long t = System.currentTimeMillis();
if (arguments.showHelp)
showHelp();
else if (arguments.showVersion){
showVersion();
} else if (arguments.file != null){
executeFile(arguments.file);
} else
showHelp();
if (arguments.showStat){
output.println();
output.println("---");
output.printf("Time: %s ms", System.currentTimeMillis() - t);
}
}
public static void main(String[] args){
Arguments arguments = new Arguments();
JCommander commander = new JCommander(arguments, args);
CLI cli = new CLI(commander, arguments, System.out);
cli.process();
}
}
| true | true | protected void executeFile(String filename){
File file = new File(filename);
Environment environment = new Environment(compileScope, output);
try {
Context context = environment.createContext(file);
AbstractCompiler compiler = new JvmCompiler(environment, context);
ModuleEntity module = compiler.compile();
compileScope.loadModule(module);
environment.registerModule(module);
module.includeNoThrow(environment);
} catch (Exception e){
environment.catchUncaught(e);
} finally {
try {
environment.doFinal();
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
}
}
| protected void executeFile(String filename){
File file = new File(filename);
Environment environment = new Environment(compileScope, output);
try {
Context context = environment.createContext(file);
AbstractCompiler compiler = new JvmCompiler(environment, context);
ModuleEntity module = compiler.compile();
compileScope.loadModule(module);
environment.registerModule(module);
module.includeNoThrow(environment);
} catch (Exception e){
environment.catchUncaught(e);
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
} finally {
try {
environment.doFinal();
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
}
}
|
diff --git a/src/main/java/com/github/rnewson/couchdb/lucene/Utils.java b/src/main/java/com/github/rnewson/couchdb/lucene/Utils.java
index d171a42..696965b 100644
--- a/src/main/java/com/github/rnewson/couchdb/lucene/Utils.java
+++ b/src/main/java/com/github/rnewson/couchdb/lucene/Utils.java
@@ -1,78 +1,80 @@
package com.github.rnewson.couchdb.lucene;
/**
* Copyright 2009 Robert Newson
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.PrintWriter;
import java.io.StringWriter;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.BooleanClause.Occur;
class Utils {
public static final Logger LOG = Logger.getLogger("couchdb-lucene");
public static String throwableToJSON(final Throwable t) {
return error(t.getMessage() == null ? "Unknown error" : String.format("%s: %s", t.getClass(), t.getMessage()));
}
public static String error(final String txt) {
return error(500, txt);
}
public static String digest(final String data) {
return DigestUtils.md5Hex(data);
}
public static String error(final int code, final Throwable t) {
final StringWriter writer = new StringWriter();
final PrintWriter printWriter = new PrintWriter(writer);
- if (t.getMessage() != null)
+ if (t.getMessage() != null) {
printWriter.append(t.getMessage());
+ printWriter.append("\n");
+ }
t.printStackTrace(printWriter);
- return new JSONObject().element("code", code).element("body", writer.toString()).toString();
+ return new JSONObject().element("code", code).element("body", "<pre>"+ writer + "</pre>").toString();
}
public static String error(final int code, final String txt) {
return new JSONObject().element("code", code).element("body", StringEscapeUtils.escapeHtml(txt)).toString();
}
public static Field text(final String name, final String value, final boolean store) {
return new Field(name, value, store ? Store.YES : Store.NO, Field.Index.ANALYZED);
}
public static Field token(final String name, final String value, final boolean store) {
return new Field(name, value, store ? Store.YES : Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS);
}
public static Query docQuery(final String dbname, final String id) {
BooleanQuery q = new BooleanQuery();
q.add(new TermQuery(new Term(Config.DB, dbname)), Occur.MUST);
q.add(new TermQuery(new Term(Config.ID, id)), Occur.MUST);
return q;
}
}
| false | true | public static String error(final int code, final Throwable t) {
final StringWriter writer = new StringWriter();
final PrintWriter printWriter = new PrintWriter(writer);
if (t.getMessage() != null)
printWriter.append(t.getMessage());
t.printStackTrace(printWriter);
return new JSONObject().element("code", code).element("body", writer.toString()).toString();
}
| public static String error(final int code, final Throwable t) {
final StringWriter writer = new StringWriter();
final PrintWriter printWriter = new PrintWriter(writer);
if (t.getMessage() != null) {
printWriter.append(t.getMessage());
printWriter.append("\n");
}
t.printStackTrace(printWriter);
return new JSONObject().element("code", code).element("body", "<pre>"+ writer + "</pre>").toString();
}
|
diff --git a/impl/src/java/org/sakaiproject/signup/logic/messages/SignupEmailBase.java b/impl/src/java/org/sakaiproject/signup/logic/messages/SignupEmailBase.java
index 0c54825..fa2bb72 100644
--- a/impl/src/java/org/sakaiproject/signup/logic/messages/SignupEmailBase.java
+++ b/impl/src/java/org/sakaiproject/signup/logic/messages/SignupEmailBase.java
@@ -1,224 +1,224 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2007, 2008, 2009 Yale University
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* See the LICENSE.txt distributed with this file.
*
**********************************************************************************/
package org.sakaiproject.signup.logic.messages;
import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import org.sakaiproject.signup.logic.SakaiFacade;
import org.sakaiproject.signup.model.MeetingTypes;
import org.sakaiproject.signup.model.SignupMeeting;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.util.ResourceLoader;
/**
* <p>
* This is a abstract base class for Signup Email. It provides some must-have or
* common used methods like getFooter()
* </P>
*/
abstract public class SignupEmailBase implements SignupEmailNotification, MeetingTypes {
private SakaiFacade sakaiFacade;
protected SignupMeeting meeting;
protected static ResourceLoader rb = new ResourceLoader("emailMessage");
public static final String newline = "<BR>\r\n"; // System.getProperty("line.separator");\r\n
public static final String space = " ";
/* footer for the email */
protected String getFooter(String newline) {
/* tag the message - HTML version */
if(this.meeting.getCurrentSiteId()==null)
return getFooterWithAccessUrl(newline);
else
return getFooterWithNoAccessUrl(newline);
}
/* footer for the email */
protected String getFooter(String newline, String targetSiteId) {
/* tag the message - HTML version */
Object[] params = new Object[] { getServiceName(),
"<a href=\"" + getSiteAccessUrl(targetSiteId) + "\">" + getSiteAccessUrl(targetSiteId) + "</a>",
getSiteTitle(targetSiteId), newline };
String rv = newline + rb.getString("separator") + newline
+ MessageFormat.format(rb.getString("body.footer.text"), params) + newline;
return rv;
}
/* footer for the email */
private String getFooterWithAccessUrl(String newline) {
/* tag the message - HTML version */
Object[] params = new Object[] { getServiceName(),
"<a href=\"" + getSiteAccessUrl() + "\">" + getSiteAccessUrl() + "</a>", getSiteTitle(), newline };
String rv = newline + rb.getString("separator") + newline
+ MessageFormat.format(rb.getString("body.footer.text"), params) + newline;
return rv;
}
/* footer for the email */
private String getFooterWithNoAccessUrl(String newline) {
/* tag the message - HTML version */
Object[] params = new Object[] { getServiceName(),
getSiteTitle(), newline };
String rv = newline + rb.getString("separator") + newline
+ MessageFormat.format(rb.getString("body.footer.text.no.access.link"), params) + newline;
return rv;
}
/**
* get the email Header, which contains destination email address, subject
* etc.
*/
abstract public List<String> getHeader();
/**
* get the main message for this email
*/
abstract public String getMessage();
/**
* get SakaiFacade object
*
* @return SakaiFacade object
*/
public SakaiFacade getSakaiFacade() {
return sakaiFacade;
}
/**
* this is a setter
*
* @param sakaiFacade
* SakaiFacade object
*/
public void setSakaiFacade(SakaiFacade sakaiFacade) {
this.sakaiFacade = sakaiFacade;
}
/**
* get current site Id
*
* @return the current site Id
*/
protected String getSiteId() {
String siteId = getSakaiFacade().getCurrentLocationId();
if(SakaiFacade.NO_LOCATION.equals(siteId)){
siteId =meeting.getCurrentSiteId()!=null? this.meeting.getCurrentSiteId() : SakaiFacade.NO_LOCATION;
}
return siteId;
}
/* get the site name */
protected String getSiteTitle() {
return getSakaiFacade().getLocationTitle(getSiteId());
}
/* get the site name */
protected String getSiteTitle(String targetSiteId) {
return getSakaiFacade().getLocationTitle(targetSiteId);
}
/* get the site name with a quotation mark */
protected String getSiteTitleWithQuote() {
return "\"" + getSiteTitle() + "\"";
}
/* get the site name with a quotation mark */
protected String getSiteTitleWithQuote(String targetSiteId) {
return "\"" + getSiteTitle(targetSiteId) + "\"";
}
/* get the link to access the current-site signup tool page in a site */
protected String getSiteAccessUrl() {
// TODO May have efficiency issue with getPageId
String siteUrl = getSakaiFacade().getServerConfigurationService().getPortalUrl() + "/site/" + getSiteId()
+ "/page/" + getSakaiFacade().getCurrentPageId();
return siteUrl;
}
/* get the link to access corresponding site - signup tool page in a site */
protected String getSiteAccessUrl(String targetSiteId) {
// TODO May have efficiency issue with getPageId
String siteUrl = getSakaiFacade().getServerConfigurationService().getPortalUrl() + "/site/" + targetSiteId
+ "/page/" + getSakaiFacade().getSiteSignupPageId(targetSiteId);
return siteUrl;
}
/**
* This will convert the Java date object to a Sakai's Time object, which
* provides all the useful methods for output.
*
* @param date
* a Java Date object.
* @return a Sakai's Time object.
*/
protected Time getTime(Date date) {
Time time = getSakaiFacade().getTimeService().newTime(date.getTime());
return time;
}
/**
* Make first letter of the string to Capital letter
*
* @param st
* a string value
* @return a string with a first capital letter
*/
protected String makeFirstCapLetter(String st) {
String temp = "";
if (st != null && st.length() > 0)
temp = st.substring(0, 1).toUpperCase() + st.substring(1);
return temp;
}
static private String myServiceName = null;
protected String getServiceName() {
/* first look at email bundle since it's not a Sakai core tool yet */
if (myServiceName == null) {
try {
myServiceName = rb.getString("ui.service");
- if (myServiceName.trim().length() < 1)
+ int index = myServiceName.indexOf("missing key");
+ if (index >=0)
myServiceName = getSakaiFacade().getServerConfigurationService().getString("ui.service",
"Sakai Service");
} catch (Exception e) {
myServiceName = getSakaiFacade().getServerConfigurationService().getString("ui.service",
"Sakai Service");
- ;
}
}
return myServiceName;
}
}
| false | true | protected String getServiceName() {
/* first look at email bundle since it's not a Sakai core tool yet */
if (myServiceName == null) {
try {
myServiceName = rb.getString("ui.service");
if (myServiceName.trim().length() < 1)
myServiceName = getSakaiFacade().getServerConfigurationService().getString("ui.service",
"Sakai Service");
} catch (Exception e) {
myServiceName = getSakaiFacade().getServerConfigurationService().getString("ui.service",
"Sakai Service");
;
}
}
return myServiceName;
}
| protected String getServiceName() {
/* first look at email bundle since it's not a Sakai core tool yet */
if (myServiceName == null) {
try {
myServiceName = rb.getString("ui.service");
int index = myServiceName.indexOf("missing key");
if (index >=0)
myServiceName = getSakaiFacade().getServerConfigurationService().getString("ui.service",
"Sakai Service");
} catch (Exception e) {
myServiceName = getSakaiFacade().getServerConfigurationService().getString("ui.service",
"Sakai Service");
}
}
return myServiceName;
}
|
diff --git a/src/no/runsafe/eventengine/engine/hooks/HookHandler.java b/src/no/runsafe/eventengine/engine/hooks/HookHandler.java
index 6727ec8..7a16105 100644
--- a/src/no/runsafe/eventengine/engine/hooks/HookHandler.java
+++ b/src/no/runsafe/eventengine/engine/hooks/HookHandler.java
@@ -1,289 +1,289 @@
package no.runsafe.eventengine.engine.hooks;
import no.runsafe.framework.api.ILocation;
import no.runsafe.framework.api.IScheduler;
import no.runsafe.framework.api.IWorld;
import no.runsafe.framework.api.block.IBlock;
import no.runsafe.framework.api.event.block.IBlockBreak;
import no.runsafe.framework.api.event.block.IBlockRedstone;
import no.runsafe.framework.api.event.player.*;
import no.runsafe.framework.api.log.IDebug;
import no.runsafe.framework.api.player.IPlayer;
import no.runsafe.framework.internal.extension.block.RunsafeBlock;
import no.runsafe.framework.minecraft.Item;
import no.runsafe.framework.minecraft.event.block.RunsafeBlockRedstoneEvent;
import no.runsafe.framework.minecraft.event.player.*;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HookHandler implements IPlayerChatEvent, IPlayerCustomEvent, IPlayerJoinEvent, IPlayerQuitEvent, IPlayerInteractEvent, IBlockRedstone, IBlockBreak, IPlayerLeftClickBlockEvent
{
public HookHandler(IScheduler scheduler, IDebug debug)
{
this.scheduler = scheduler;
this.debug = debug;
}
public static void registerHook(Hook hook)
{
HookType type = hook.getType();
if (!HookHandler.hooks.containsKey(type))
HookHandler.hooks.put(type, new ArrayList<Hook>());
HookHandler.hooks.get(type).add(hook);
}
private static List<Hook> getHooks(HookType type)
{
if (HookHandler.hooks.containsKey(type))
return HookHandler.hooks.get(type);
return null;
}
public static void clearHooks()
{
HookHandler.hooks.clear();
}
@Override
public void OnPlayerChatEvent(RunsafePlayerChatEvent event)
{
List<Hook> hooks = HookHandler.getHooks(HookType.CHAT_MESSAGE);
if (hooks != null)
{
for (Hook hook : hooks)
{
if (event.getMessage().equalsIgnoreCase((String) hook.getData()))
{
LuaTable table = new LuaTable();
table.set("player", LuaValue.valueOf(event.getPlayer().getName()));
hook.execute(table);
}
}
}
}
@SuppressWarnings("unchecked")
@Override
public void OnPlayerCustomEvent(RunsafeCustomEvent event)
{
HookType type = null;
String eventType = event.getEvent();
if (eventType.equals("region.enter"))
type = HookType.REGION_ENTER;
else if (eventType.equals("region.leave"))
type = HookType.REGION_LEAVE;
if (type != null)
{
List<Hook> hooks = HookHandler.getHooks(type);
if (hooks != null)
{
for (final Hook hook : hooks)
{
Map<String, String> data = (Map<String, String>) event.getData();
if (((String) hook.getData()).equalsIgnoreCase(String.format("%s-%s", data.get("world"), data.get("region"))))
{
final LuaTable table = new LuaTable();
table.set("player", LuaValue.valueOf(event.getPlayer().getName()));
scheduler.runNow(new Runnable()
{
@Override
public void run()
{
hook.execute(table);
}
});
}
}
}
}
}
@Override
public void OnPlayerJoinEvent(RunsafePlayerJoinEvent event)
{
this.playerLogEvent(event.getPlayer(), HookType.PLAYER_LOGIN);
}
@Override
public void OnPlayerQuit(RunsafePlayerQuitEvent event)
{
this.playerLogEvent(event.getPlayer(), HookType.PLAYER_LOGOUT);
}
private void playerLogEvent(IPlayer player, HookType type)
{
List<Hook> hooks = HookHandler.getHooks(type);
if (hooks != null)
for (Hook hook : hooks)
if (hook.getPlayerName().equalsIgnoreCase(player.getName()))
hook.execute();
}
@Override
public void OnPlayerInteractEvent(RunsafePlayerInteractEvent event)
{
debug.debugFine("Interact event detected");
List<Hook> hooks = HookHandler.getHooks(HookType.INTERACT);
if (hooks != null)
{
debug.debugFine("Hooks not null");
for (Hook hook : hooks)
{
debug.debugFine("Processing hook...");
IBlock block = event.getBlock();
if (hook.getData() != null)
if (block == null || block.getMaterial().getItemID() != (Integer) hook.getData())
- return;
+ continue;
debug.debugFine("Block is not null");
IWorld hookWorld = hook.getWorld();
ILocation location = block.getLocation();
if (hookWorld == null)
{
debug.debugFine("Hook world is null, using location");
if (location.getWorld().getName().equals(hook.getLocation().getWorld().getName()))
{
debug.debugFine("Correct world!");
if (location.distance(hook.getLocation()) < 1)
{
debug.debugFine("Distance is less than 1");
LuaTable table = new LuaTable();
if (event.getPlayer() != null)
table.set("player", LuaValue.valueOf(event.getPlayer().getName()));
table.set("x", LuaValue.valueOf(location.getBlockX()));
table.set("y", LuaValue.valueOf(location.getBlockY()));
table.set("z", LuaValue.valueOf(location.getBlockZ()));
table.set("blockID", LuaValue.valueOf(block.getMaterial().getItemID()));
table.set("blockData", LuaValue.valueOf((block).getData()));
hook.execute(table);
}
}
}
else if (hookWorld.getName().equals(block.getWorld().getName()))
{
debug.debugFine("Hook world is null, sending location data");
LuaTable table = new LuaTable();
if (event.getPlayer() != null)
table.set("player", LuaValue.valueOf(event.getPlayer().getName()));
table.set("x", LuaValue.valueOf(location.getBlockX()));
table.set("y", LuaValue.valueOf(location.getBlockY()));
table.set("z", LuaValue.valueOf(location.getBlockZ()));
table.set("blockID", LuaValue.valueOf(block.getMaterial().getItemID()));
table.set("blockData", LuaValue.valueOf((block).getData()));
hook.execute(table);
}
}
}
}
@Override
public void OnBlockRedstoneEvent(RunsafeBlockRedstoneEvent event)
{
if (event.getNewCurrent() > 0 && event.getOldCurrent() == 0)
{
List<Hook> hooks = HookHandler.getHooks(HookType.BLOCK_GAINS_CURRENT);
if (hooks != null)
{
for (Hook hook : hooks)
{
IBlock block = event.getBlock();
if (block != null)
{
ILocation location = block.getLocation();
if (location.getWorld().getName().equals(hook.getLocation().getWorld().getName()))
if (location.distance(hook.getLocation()) < 1)
hook.execute();
}
}
}
}
}
@Override
public boolean OnBlockBreak(IPlayer player, IBlock block)
{
List<Hook> hooks = HookHandler.getHooks(HookType.BLOCK_BREAK);
if (hooks != null)
{
ILocation blockLocation = block.getLocation();
String blockWorld = blockLocation.getWorld().getName();
for (Hook hook : hooks)
{
IWorld world = hook.getWorld();
if (world != null && !blockWorld.equals(world.getName()))
return true;
LuaTable table = new LuaTable();
if (player != null)
table.set("player", LuaValue.valueOf(player.getName()));
table.set("world", LuaValue.valueOf(blockWorld));
table.set("x", LuaValue.valueOf(blockLocation.getBlockX()));
table.set("y", LuaValue.valueOf(blockLocation.getBlockY()));
table.set("z", LuaValue.valueOf(blockLocation.getBlockZ()));
table.set("blockID", LuaValue.valueOf(block.getMaterial().getItemID()));
table.set("blockData", LuaValue.valueOf(((RunsafeBlock) block).getData()));
hook.execute(table);
}
}
return true;
}
@Override
public void OnPlayerLeftClick(RunsafePlayerClickEvent event)
{
List<Hook> hooks = HookHandler.getHooks(HookType.LEFT_CLICK_BLOCK);
if (hooks != null)
{
IBlock block = event.getBlock();
Item material = block.getMaterial();
ILocation blockLocation = block.getLocation();
String blockWorldName = blockLocation.getWorld().getName();
String playerName = event.getPlayer().getName();
for (Hook hook : hooks)
{
IWorld world = hook.getWorld();
if (world != null && !blockWorldName.equals(world.getName()))
return;
LuaTable table = new LuaTable();
table.set("player", LuaValue.valueOf(playerName));
table.set("world", LuaValue.valueOf(blockWorldName));
table.set("x", LuaValue.valueOf(blockLocation.getBlockX()));
table.set("y", LuaValue.valueOf(blockLocation.getBlockY()));
table.set("z", LuaValue.valueOf(blockLocation.getBlockZ()));
table.set("blockID", LuaValue.valueOf(material.getItemID()));
table.set("blockData", LuaValue.valueOf(material.getData()));
hook.execute(table);
}
}
}
private static final HashMap<HookType, List<Hook>> hooks = new HashMap<HookType, List<Hook>>();
private final IScheduler scheduler;
private final IDebug debug;
}
| true | true | public void OnPlayerInteractEvent(RunsafePlayerInteractEvent event)
{
debug.debugFine("Interact event detected");
List<Hook> hooks = HookHandler.getHooks(HookType.INTERACT);
if (hooks != null)
{
debug.debugFine("Hooks not null");
for (Hook hook : hooks)
{
debug.debugFine("Processing hook...");
IBlock block = event.getBlock();
if (hook.getData() != null)
if (block == null || block.getMaterial().getItemID() != (Integer) hook.getData())
return;
debug.debugFine("Block is not null");
IWorld hookWorld = hook.getWorld();
ILocation location = block.getLocation();
if (hookWorld == null)
{
debug.debugFine("Hook world is null, using location");
if (location.getWorld().getName().equals(hook.getLocation().getWorld().getName()))
{
debug.debugFine("Correct world!");
if (location.distance(hook.getLocation()) < 1)
{
debug.debugFine("Distance is less than 1");
LuaTable table = new LuaTable();
if (event.getPlayer() != null)
table.set("player", LuaValue.valueOf(event.getPlayer().getName()));
table.set("x", LuaValue.valueOf(location.getBlockX()));
table.set("y", LuaValue.valueOf(location.getBlockY()));
table.set("z", LuaValue.valueOf(location.getBlockZ()));
table.set("blockID", LuaValue.valueOf(block.getMaterial().getItemID()));
table.set("blockData", LuaValue.valueOf((block).getData()));
hook.execute(table);
}
}
}
else if (hookWorld.getName().equals(block.getWorld().getName()))
{
debug.debugFine("Hook world is null, sending location data");
LuaTable table = new LuaTable();
if (event.getPlayer() != null)
table.set("player", LuaValue.valueOf(event.getPlayer().getName()));
table.set("x", LuaValue.valueOf(location.getBlockX()));
table.set("y", LuaValue.valueOf(location.getBlockY()));
table.set("z", LuaValue.valueOf(location.getBlockZ()));
table.set("blockID", LuaValue.valueOf(block.getMaterial().getItemID()));
table.set("blockData", LuaValue.valueOf((block).getData()));
hook.execute(table);
}
}
}
}
| public void OnPlayerInteractEvent(RunsafePlayerInteractEvent event)
{
debug.debugFine("Interact event detected");
List<Hook> hooks = HookHandler.getHooks(HookType.INTERACT);
if (hooks != null)
{
debug.debugFine("Hooks not null");
for (Hook hook : hooks)
{
debug.debugFine("Processing hook...");
IBlock block = event.getBlock();
if (hook.getData() != null)
if (block == null || block.getMaterial().getItemID() != (Integer) hook.getData())
continue;
debug.debugFine("Block is not null");
IWorld hookWorld = hook.getWorld();
ILocation location = block.getLocation();
if (hookWorld == null)
{
debug.debugFine("Hook world is null, using location");
if (location.getWorld().getName().equals(hook.getLocation().getWorld().getName()))
{
debug.debugFine("Correct world!");
if (location.distance(hook.getLocation()) < 1)
{
debug.debugFine("Distance is less than 1");
LuaTable table = new LuaTable();
if (event.getPlayer() != null)
table.set("player", LuaValue.valueOf(event.getPlayer().getName()));
table.set("x", LuaValue.valueOf(location.getBlockX()));
table.set("y", LuaValue.valueOf(location.getBlockY()));
table.set("z", LuaValue.valueOf(location.getBlockZ()));
table.set("blockID", LuaValue.valueOf(block.getMaterial().getItemID()));
table.set("blockData", LuaValue.valueOf((block).getData()));
hook.execute(table);
}
}
}
else if (hookWorld.getName().equals(block.getWorld().getName()))
{
debug.debugFine("Hook world is null, sending location data");
LuaTable table = new LuaTable();
if (event.getPlayer() != null)
table.set("player", LuaValue.valueOf(event.getPlayer().getName()));
table.set("x", LuaValue.valueOf(location.getBlockX()));
table.set("y", LuaValue.valueOf(location.getBlockY()));
table.set("z", LuaValue.valueOf(location.getBlockZ()));
table.set("blockID", LuaValue.valueOf(block.getMaterial().getItemID()));
table.set("blockData", LuaValue.valueOf((block).getData()));
hook.execute(table);
}
}
}
}
|
diff --git a/src/main/java/com/github/ucchyocean/ct/command/CTPCommand.java b/src/main/java/com/github/ucchyocean/ct/command/CTPCommand.java
index 87896d1..60ae34a 100644
--- a/src/main/java/com/github/ucchyocean/ct/command/CTPCommand.java
+++ b/src/main/java/com/github/ucchyocean/ct/command/CTPCommand.java
@@ -1,393 +1,395 @@
/*
* @author ucchy
* @license LGPLv3
* @copyright Copyright ucchy 2013
*/
package com.github.ucchyocean.ct.command;
import java.util.ArrayList;
import java.util.HashMap;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.github.ucchyocean.ct.ColorTeaming;
import com.github.ucchyocean.ct.DelayedTeleportTask;
import com.github.ucchyocean.ct.config.RespawnConfiguration;
import com.github.ucchyocean.ct.config.TeamNameSetting;
/**
* colortp(ctp)コマンドの実行クラス
* @author ucchy
*/
public class CTPCommand implements CommandExecutor {
private static final String PREERR = ChatColor.RED.toString();
private static final String PREINFO = ChatColor.GRAY.toString();
private static final String PRE_LIST_MESSAGE =
PREINFO + "=== TP Points Information ===";
private ColorTeaming plugin;
public CTPCommand(ColorTeaming plugin) {
this.plugin = plugin;
}
/**
* @see org.bukkit.plugin.java.JavaPlugin#onCommand(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[])
*/
public boolean onCommand(
CommandSender sender, Command command, String label, String[] args) {
// 引数が一つもない場合は、ここで終了
if ( args.length == 0 ) {
return false;
}
if ( args[0].equalsIgnoreCase("list") ) {
// ctp list の実行
sender.sendMessage(PRE_LIST_MESSAGE);
ArrayList<String> list = plugin.getAPI().getTppointConfig().list();
for ( String l : list ) {
sender.sendMessage(PREINFO + l);
}
return true;
}
// ここ以降は引数が最低2つ必要なので、1つしかない場合はここで終了させておく
if ( args.length == 1 ) {
return false;
}
if ( args[0].equalsIgnoreCase("all") ) {
HashMap<String, ArrayList<Player>> members =
plugin.getAPI().getAllTeamMembers();
if ( args[1].equalsIgnoreCase("spawn") ) {
// ctp all spawn の実行
// テレポート実行
String respawnMapName = plugin.getAPI().getRespawnMapName();
RespawnConfiguration respawnConfig = plugin.getAPI().getRespawnConfig();
HashMap<Player, Location> map = new HashMap<Player, Location>();
for ( String team : members.keySet() ) {
TeamNameSetting tns = plugin.getAPI().getTeamNameFromID(team);
Location location = respawnConfig.get(team, respawnMapName);
if ( location == null ) {
sender.sendMessage(PREERR +
"チーム " + tns.getName() + " にリスポーンポイントが指定されていません。");
} else {
location = location.add(0.5, 0, 0.5);
for ( Player p : members.get(team) ) {
map.put(p, location);
}
sender.sendMessage(PREINFO +
"チーム " + tns.getName() + " のプレイヤーを全員テレポートします。");
}
}
if ( map.size() > 0 ) {
DelayedTeleportTask task = new DelayedTeleportTask(map,
plugin.getCTConfig().getTeleportDelay());
task.startTask();
}
} else {
// ctp all (point) の実行
String point = args[1];
Location location = plugin.getAPI().getTppointConfig().get(point);
// point が登録済みのポイントかどうかを確認する
if ( location == null ) {
sender.sendMessage(PREERR +
"ポイント " + point + " は登録されていません。");
return true;
}
// テレポート実行
HashMap<Player, Location> map = new HashMap<Player, Location>();
for ( String team : members.keySet() ) {
for ( Player p : members.get(team) ) {
map.put(p, location);
}
TeamNameSetting tns = plugin.getAPI().getTeamNameFromID(team);
sender.sendMessage(PREINFO +
"チーム " + tns.getName() + " のプレイヤーを全員テレポートします。");
}
if ( map.size() > 0 ) {
DelayedTeleportTask task = new DelayedTeleportTask(map,
plugin.getCTConfig().getTeleportDelay());
task.startTask();
}
}
return true;
} else if ( args[0].equalsIgnoreCase("set") ) {
String point = args[1];
// 引数が3個以下なら、ここで終了
if ( args.length < 3 ) {
return false;
}
Location location;
if ( args.length == 2 || args[2].equalsIgnoreCase("here") ) {
// ctp set (point) [here]
if ( sender instanceof Player ) {
location = ((Player)sender).getLocation();
} else {
sender.sendMessage(PREERR + "ctp set point [here] 指定は、" +
"コンソールやコマンドブロックからは実行できません。");
return true;
}
} else {
// ctp set (point) [world] (x) (y) (z)
location = checkAndGetLocation(sender, args, 2);
if ( location == null ) {
return true;
}
}
// ポイント登録の実行
plugin.getAPI().getTppointConfig().set(point, location);
String message = String.format(
PREINFO + "ポイント %s を (%d, %d, %d) に設定しました。",
point, location.getBlockX(), location.getBlockY(), location.getBlockZ());
sender.sendMessage(message);
return true;
} else if ( args[0].equalsIgnoreCase("remove") ) {
String point = args[1];
// point が登録済みのポイントかどうかを確認する、未登録なら終了
if ( plugin.getAPI().getTppointConfig().get(point) == null ) {
sender.sendMessage(PREERR +
"ポイント " + point + " は登録されていません。");
return true;
}
// ポイント削除の実行
plugin.getAPI().getTppointConfig().set(point, null);
String message = String.format(
PREINFO + "ポイント %s を削除しました。", point);
sender.sendMessage(message);
return true;
} else {
// ctp (group) ほにゃらら の実行
String target = args[0];
HashMap<String, ArrayList<Player>> members =
plugin.getAPI().getAllTeamMembers();
// 有効なチーム名またはプレイヤー名が指定されたか確認する
boolean isPlayer = false;
if ( members.containsKey(target) ) {
//isTeam = true;
} else if ( Bukkit.getPlayerExact(target) != null ) {
isPlayer = true;
} else {
sender.sendMessage(PREERR + "指定された " + target + " に一致する、チームもプレイヤーも存在しません。");
return true;
}
- Location location;
+ Location location = null;
if ( args[1].equalsIgnoreCase("here") ) {
// ctp (group) here
// コマンド実行者の場所を取得、コンソールなら終了
if ( sender instanceof Player ) {
location = ((Player)sender).getLocation();
} else if ( sender instanceof BlockCommandSender ) {
location = ((BlockCommandSender)sender).getBlock().getLocation().add(0.5, 1, 0.5);
} else {
sender.sendMessage(PREERR +
"ctp の here 指定は、コンソールからは実行できません。");
return true;
}
} else if ( args[1].equalsIgnoreCase("spawn") ) {
// ctp (group) spawn
// チームのリスポーンポイントを取得、登録されていなければ終了
String respawnMapName = plugin.getAPI().getRespawnMapName();
RespawnConfiguration respawnConfig = plugin.getAPI().getRespawnConfig();
if ( isPlayer ) {
Player player = Bukkit.getPlayerExact(target);
- String team = plugin.getAPI().getPlayerTeamName(player).getID();
- location = respawnConfig.get(team, respawnMapName);
+ TeamNameSetting tns = plugin.getAPI().getPlayerTeamName(player);
+ if ( tns != null ) {
+ location = respawnConfig.get(tns.getID(), respawnMapName);
+ }
if ( location == null ) {
location = player.getBedSpawnLocation();
if ( location == null ) {
location = player.getWorld().getSpawnLocation();
if ( location == null ) {
sender.sendMessage(PREERR +
"プレイヤー " + target + " のリスポーンポイントが取得できませんでした。");
return true;
}
}
}
} else {
location = respawnConfig.get(target, respawnMapName);
if ( location == null ) {
sender.sendMessage(PREERR +
"チーム " + target + " にリスポーンポイントが指定されていません。");
return true;
}
}
location = location.add(0.5, 0, 0.5);
} else if ( args.length <= 3 ) {
// ctp (group) (point)
// 登録ポイントの取得、ポイントがなければ終了
String point = args[1];
location = plugin.getAPI().getTppointConfig().get(point);
if ( location == null ) {
sender.sendMessage(PREERR +
"ポイント " + point + " は登録されていません。");
return true;
}
location = location.add(0.5, 0, 0.5);
} else {
// ctp (group) [world] (x) (y) (z)
// 指定された座標からlocationを取得、取得できなければ終了
location = checkAndGetLocation(sender, args, 1);
if ( location == null ) {
return true;
}
location = location.add(0.5, 0, 0.5);
}
// テレポートの実行
HashMap<Player, Location> map = new HashMap<Player, Location>();
if ( isPlayer ) {
Player player = Bukkit.getPlayerExact(target);
map.put(player, location);
sender.sendMessage(PREINFO + "プレイヤー " + target + " をテレポートします。");
} else {
for ( Player p : members.get(target) ) {
map.put(p, location);
}
sender.sendMessage(PREINFO + "チーム " + target + " のプレイヤーを全員テレポートします。");
}
if ( map.size() > 0 ) {
DelayedTeleportTask task = new DelayedTeleportTask(map,
plugin.getCTConfig().getTeleportDelay());
task.startTask();
}
return true;
}
}
/**
* Locationを作成できるかどうかチェックして、Locationを作成し、返すメソッド。
* @param sender コマンド実行者
* @param args コマンドの引数
* @param fromIndex コマンドの引数の、どのインデクスからチェックを開始するか
* @return 作成したLocation。ただし、作成に失敗した場合はnullになる。
*/
private Location checkAndGetLocation(CommandSender sender, String[] args, int fromIndex) {
String world = "world";
String x_str, y_str, z_str;
if ( args.length >= fromIndex + 4 ) {
world = args[fromIndex];
x_str = args[fromIndex + 1];
y_str = args[fromIndex + 2];
z_str = args[fromIndex + 3];
} else if ( args.length >= fromIndex + 3 ) {
x_str = args[fromIndex];
y_str = args[fromIndex + 1];
z_str = args[fromIndex + 2];
if ( sender instanceof BlockCommandSender ) {
BlockCommandSender block = (BlockCommandSender)sender;
world = block.getBlock().getWorld().getName();
} else if ( sender instanceof Player ) {
Player player = (Player)sender;
world = player.getWorld().getName();
}
} else {
sender.sendMessage(PREERR + "引数の指定が足りません。");
return null;
}
// 有効な座標が指定されたか確認する
if ( !checkXYZ(sender, x_str) ||
!checkXYZ(sender, y_str) ||
!checkXYZ(sender, z_str) ) {
return null;
}
// 有効なワールド名が指定されたか確認する
if ( Bukkit.getWorld(world) == null ) {
sender.sendMessage(PREERR + "ワールド " + world + " が存在しません。");
return null;
}
// Locationを作成して返す。
double x = Integer.parseInt(x_str) + 0.5;
double y = Integer.parseInt(y_str);
double z = Integer.parseInt(z_str) + 0.5;
return new Location(Bukkit.getWorld(world), x, y, z);
}
/**
* value が、座標の数値として適切な内容かどうかを確認する。
* @param sender エラー時のメッセージ送り先
* @param value 検査対象の文字列
* @return 座標の数値として適切かどうか
*/
private boolean checkXYZ (CommandSender sender, String value) {
// 数値かどうかをチェックする
if ( !value.matches("-?[0-9]+") ) {
sender.sendMessage(PREERR + value + " は数値ではありません。");
return false;
}
int v = Integer.parseInt(value);
// 大きすぎる値でないかどうかチェックする
if ( v < -30000000 || 30000000 < v ) {
sender.sendMessage(PREERR + value + " は遠すぎて指定できません。");
return false;
}
return true;
}
}
| false | true | public boolean onCommand(
CommandSender sender, Command command, String label, String[] args) {
// 引数が一つもない場合は、ここで終了
if ( args.length == 0 ) {
return false;
}
if ( args[0].equalsIgnoreCase("list") ) {
// ctp list の実行
sender.sendMessage(PRE_LIST_MESSAGE);
ArrayList<String> list = plugin.getAPI().getTppointConfig().list();
for ( String l : list ) {
sender.sendMessage(PREINFO + l);
}
return true;
}
// ここ以降は引数が最低2つ必要なので、1つしかない場合はここで終了させておく
if ( args.length == 1 ) {
return false;
}
if ( args[0].equalsIgnoreCase("all") ) {
HashMap<String, ArrayList<Player>> members =
plugin.getAPI().getAllTeamMembers();
if ( args[1].equalsIgnoreCase("spawn") ) {
// ctp all spawn の実行
// テレポート実行
String respawnMapName = plugin.getAPI().getRespawnMapName();
RespawnConfiguration respawnConfig = plugin.getAPI().getRespawnConfig();
HashMap<Player, Location> map = new HashMap<Player, Location>();
for ( String team : members.keySet() ) {
TeamNameSetting tns = plugin.getAPI().getTeamNameFromID(team);
Location location = respawnConfig.get(team, respawnMapName);
if ( location == null ) {
sender.sendMessage(PREERR +
"チーム " + tns.getName() + " にリスポーンポイントが指定されていません。");
} else {
location = location.add(0.5, 0, 0.5);
for ( Player p : members.get(team) ) {
map.put(p, location);
}
sender.sendMessage(PREINFO +
"チーム " + tns.getName() + " のプレイヤーを全員テレポートします。");
}
}
if ( map.size() > 0 ) {
DelayedTeleportTask task = new DelayedTeleportTask(map,
plugin.getCTConfig().getTeleportDelay());
task.startTask();
}
} else {
// ctp all (point) の実行
String point = args[1];
Location location = plugin.getAPI().getTppointConfig().get(point);
// point が登録済みのポイントかどうかを確認する
if ( location == null ) {
sender.sendMessage(PREERR +
"ポイント " + point + " は登録されていません。");
return true;
}
// テレポート実行
HashMap<Player, Location> map = new HashMap<Player, Location>();
for ( String team : members.keySet() ) {
for ( Player p : members.get(team) ) {
map.put(p, location);
}
TeamNameSetting tns = plugin.getAPI().getTeamNameFromID(team);
sender.sendMessage(PREINFO +
"チーム " + tns.getName() + " のプレイヤーを全員テレポートします。");
}
if ( map.size() > 0 ) {
DelayedTeleportTask task = new DelayedTeleportTask(map,
plugin.getCTConfig().getTeleportDelay());
task.startTask();
}
}
return true;
} else if ( args[0].equalsIgnoreCase("set") ) {
String point = args[1];
// 引数が3個以下なら、ここで終了
if ( args.length < 3 ) {
return false;
}
Location location;
if ( args.length == 2 || args[2].equalsIgnoreCase("here") ) {
// ctp set (point) [here]
if ( sender instanceof Player ) {
location = ((Player)sender).getLocation();
} else {
sender.sendMessage(PREERR + "ctp set point [here] 指定は、" +
"コンソールやコマンドブロックからは実行できません。");
return true;
}
} else {
// ctp set (point) [world] (x) (y) (z)
location = checkAndGetLocation(sender, args, 2);
if ( location == null ) {
return true;
}
}
// ポイント登録の実行
plugin.getAPI().getTppointConfig().set(point, location);
String message = String.format(
PREINFO + "ポイント %s を (%d, %d, %d) に設定しました。",
point, location.getBlockX(), location.getBlockY(), location.getBlockZ());
sender.sendMessage(message);
return true;
} else if ( args[0].equalsIgnoreCase("remove") ) {
String point = args[1];
// point が登録済みのポイントかどうかを確認する、未登録なら終了
if ( plugin.getAPI().getTppointConfig().get(point) == null ) {
sender.sendMessage(PREERR +
"ポイント " + point + " は登録されていません。");
return true;
}
// ポイント削除の実行
plugin.getAPI().getTppointConfig().set(point, null);
String message = String.format(
PREINFO + "ポイント %s を削除しました。", point);
sender.sendMessage(message);
return true;
} else {
// ctp (group) ほにゃらら の実行
String target = args[0];
HashMap<String, ArrayList<Player>> members =
plugin.getAPI().getAllTeamMembers();
// 有効なチーム名またはプレイヤー名が指定されたか確認する
boolean isPlayer = false;
if ( members.containsKey(target) ) {
//isTeam = true;
} else if ( Bukkit.getPlayerExact(target) != null ) {
isPlayer = true;
} else {
sender.sendMessage(PREERR + "指定された " + target + " に一致する、チームもプレイヤーも存在しません。");
return true;
}
Location location;
if ( args[1].equalsIgnoreCase("here") ) {
// ctp (group) here
// コマンド実行者の場所を取得、コンソールなら終了
if ( sender instanceof Player ) {
location = ((Player)sender).getLocation();
} else if ( sender instanceof BlockCommandSender ) {
location = ((BlockCommandSender)sender).getBlock().getLocation().add(0.5, 1, 0.5);
} else {
sender.sendMessage(PREERR +
"ctp の here 指定は、コンソールからは実行できません。");
return true;
}
} else if ( args[1].equalsIgnoreCase("spawn") ) {
// ctp (group) spawn
// チームのリスポーンポイントを取得、登録されていなければ終了
String respawnMapName = plugin.getAPI().getRespawnMapName();
RespawnConfiguration respawnConfig = plugin.getAPI().getRespawnConfig();
if ( isPlayer ) {
Player player = Bukkit.getPlayerExact(target);
String team = plugin.getAPI().getPlayerTeamName(player).getID();
location = respawnConfig.get(team, respawnMapName);
if ( location == null ) {
location = player.getBedSpawnLocation();
if ( location == null ) {
location = player.getWorld().getSpawnLocation();
if ( location == null ) {
sender.sendMessage(PREERR +
"プレイヤー " + target + " のリスポーンポイントが取得できませんでした。");
return true;
}
}
}
} else {
location = respawnConfig.get(target, respawnMapName);
if ( location == null ) {
sender.sendMessage(PREERR +
"チーム " + target + " にリスポーンポイントが指定されていません。");
return true;
}
}
location = location.add(0.5, 0, 0.5);
} else if ( args.length <= 3 ) {
// ctp (group) (point)
// 登録ポイントの取得、ポイントがなければ終了
String point = args[1];
location = plugin.getAPI().getTppointConfig().get(point);
if ( location == null ) {
sender.sendMessage(PREERR +
"ポイント " + point + " は登録されていません。");
return true;
}
location = location.add(0.5, 0, 0.5);
} else {
// ctp (group) [world] (x) (y) (z)
// 指定された座標からlocationを取得、取得できなければ終了
location = checkAndGetLocation(sender, args, 1);
if ( location == null ) {
return true;
}
location = location.add(0.5, 0, 0.5);
}
// テレポートの実行
HashMap<Player, Location> map = new HashMap<Player, Location>();
if ( isPlayer ) {
Player player = Bukkit.getPlayerExact(target);
map.put(player, location);
sender.sendMessage(PREINFO + "プレイヤー " + target + " をテレポートします。");
} else {
for ( Player p : members.get(target) ) {
map.put(p, location);
}
sender.sendMessage(PREINFO + "チーム " + target + " のプレイヤーを全員テレポートします。");
}
if ( map.size() > 0 ) {
DelayedTeleportTask task = new DelayedTeleportTask(map,
plugin.getCTConfig().getTeleportDelay());
task.startTask();
}
return true;
}
}
| public boolean onCommand(
CommandSender sender, Command command, String label, String[] args) {
// 引数が一つもない場合は、ここで終了
if ( args.length == 0 ) {
return false;
}
if ( args[0].equalsIgnoreCase("list") ) {
// ctp list の実行
sender.sendMessage(PRE_LIST_MESSAGE);
ArrayList<String> list = plugin.getAPI().getTppointConfig().list();
for ( String l : list ) {
sender.sendMessage(PREINFO + l);
}
return true;
}
// ここ以降は引数が最低2つ必要なので、1つしかない場合はここで終了させておく
if ( args.length == 1 ) {
return false;
}
if ( args[0].equalsIgnoreCase("all") ) {
HashMap<String, ArrayList<Player>> members =
plugin.getAPI().getAllTeamMembers();
if ( args[1].equalsIgnoreCase("spawn") ) {
// ctp all spawn の実行
// テレポート実行
String respawnMapName = plugin.getAPI().getRespawnMapName();
RespawnConfiguration respawnConfig = plugin.getAPI().getRespawnConfig();
HashMap<Player, Location> map = new HashMap<Player, Location>();
for ( String team : members.keySet() ) {
TeamNameSetting tns = plugin.getAPI().getTeamNameFromID(team);
Location location = respawnConfig.get(team, respawnMapName);
if ( location == null ) {
sender.sendMessage(PREERR +
"チーム " + tns.getName() + " にリスポーンポイントが指定されていません。");
} else {
location = location.add(0.5, 0, 0.5);
for ( Player p : members.get(team) ) {
map.put(p, location);
}
sender.sendMessage(PREINFO +
"チーム " + tns.getName() + " のプレイヤーを全員テレポートします。");
}
}
if ( map.size() > 0 ) {
DelayedTeleportTask task = new DelayedTeleportTask(map,
plugin.getCTConfig().getTeleportDelay());
task.startTask();
}
} else {
// ctp all (point) の実行
String point = args[1];
Location location = plugin.getAPI().getTppointConfig().get(point);
// point が登録済みのポイントかどうかを確認する
if ( location == null ) {
sender.sendMessage(PREERR +
"ポイント " + point + " は登録されていません。");
return true;
}
// テレポート実行
HashMap<Player, Location> map = new HashMap<Player, Location>();
for ( String team : members.keySet() ) {
for ( Player p : members.get(team) ) {
map.put(p, location);
}
TeamNameSetting tns = plugin.getAPI().getTeamNameFromID(team);
sender.sendMessage(PREINFO +
"チーム " + tns.getName() + " のプレイヤーを全員テレポートします。");
}
if ( map.size() > 0 ) {
DelayedTeleportTask task = new DelayedTeleportTask(map,
plugin.getCTConfig().getTeleportDelay());
task.startTask();
}
}
return true;
} else if ( args[0].equalsIgnoreCase("set") ) {
String point = args[1];
// 引数が3個以下なら、ここで終了
if ( args.length < 3 ) {
return false;
}
Location location;
if ( args.length == 2 || args[2].equalsIgnoreCase("here") ) {
// ctp set (point) [here]
if ( sender instanceof Player ) {
location = ((Player)sender).getLocation();
} else {
sender.sendMessage(PREERR + "ctp set point [here] 指定は、" +
"コンソールやコマンドブロックからは実行できません。");
return true;
}
} else {
// ctp set (point) [world] (x) (y) (z)
location = checkAndGetLocation(sender, args, 2);
if ( location == null ) {
return true;
}
}
// ポイント登録の実行
plugin.getAPI().getTppointConfig().set(point, location);
String message = String.format(
PREINFO + "ポイント %s を (%d, %d, %d) に設定しました。",
point, location.getBlockX(), location.getBlockY(), location.getBlockZ());
sender.sendMessage(message);
return true;
} else if ( args[0].equalsIgnoreCase("remove") ) {
String point = args[1];
// point が登録済みのポイントかどうかを確認する、未登録なら終了
if ( plugin.getAPI().getTppointConfig().get(point) == null ) {
sender.sendMessage(PREERR +
"ポイント " + point + " は登録されていません。");
return true;
}
// ポイント削除の実行
plugin.getAPI().getTppointConfig().set(point, null);
String message = String.format(
PREINFO + "ポイント %s を削除しました。", point);
sender.sendMessage(message);
return true;
} else {
// ctp (group) ほにゃらら の実行
String target = args[0];
HashMap<String, ArrayList<Player>> members =
plugin.getAPI().getAllTeamMembers();
// 有効なチーム名またはプレイヤー名が指定されたか確認する
boolean isPlayer = false;
if ( members.containsKey(target) ) {
//isTeam = true;
} else if ( Bukkit.getPlayerExact(target) != null ) {
isPlayer = true;
} else {
sender.sendMessage(PREERR + "指定された " + target + " に一致する、チームもプレイヤーも存在しません。");
return true;
}
Location location = null;
if ( args[1].equalsIgnoreCase("here") ) {
// ctp (group) here
// コマンド実行者の場所を取得、コンソールなら終了
if ( sender instanceof Player ) {
location = ((Player)sender).getLocation();
} else if ( sender instanceof BlockCommandSender ) {
location = ((BlockCommandSender)sender).getBlock().getLocation().add(0.5, 1, 0.5);
} else {
sender.sendMessage(PREERR +
"ctp の here 指定は、コンソールからは実行できません。");
return true;
}
} else if ( args[1].equalsIgnoreCase("spawn") ) {
// ctp (group) spawn
// チームのリスポーンポイントを取得、登録されていなければ終了
String respawnMapName = plugin.getAPI().getRespawnMapName();
RespawnConfiguration respawnConfig = plugin.getAPI().getRespawnConfig();
if ( isPlayer ) {
Player player = Bukkit.getPlayerExact(target);
TeamNameSetting tns = plugin.getAPI().getPlayerTeamName(player);
if ( tns != null ) {
location = respawnConfig.get(tns.getID(), respawnMapName);
}
if ( location == null ) {
location = player.getBedSpawnLocation();
if ( location == null ) {
location = player.getWorld().getSpawnLocation();
if ( location == null ) {
sender.sendMessage(PREERR +
"プレイヤー " + target + " のリスポーンポイントが取得できませんでした。");
return true;
}
}
}
} else {
location = respawnConfig.get(target, respawnMapName);
if ( location == null ) {
sender.sendMessage(PREERR +
"チーム " + target + " にリスポーンポイントが指定されていません。");
return true;
}
}
location = location.add(0.5, 0, 0.5);
} else if ( args.length <= 3 ) {
// ctp (group) (point)
// 登録ポイントの取得、ポイントがなければ終了
String point = args[1];
location = plugin.getAPI().getTppointConfig().get(point);
if ( location == null ) {
sender.sendMessage(PREERR +
"ポイント " + point + " は登録されていません。");
return true;
}
location = location.add(0.5, 0, 0.5);
} else {
// ctp (group) [world] (x) (y) (z)
// 指定された座標からlocationを取得、取得できなければ終了
location = checkAndGetLocation(sender, args, 1);
if ( location == null ) {
return true;
}
location = location.add(0.5, 0, 0.5);
}
// テレポートの実行
HashMap<Player, Location> map = new HashMap<Player, Location>();
if ( isPlayer ) {
Player player = Bukkit.getPlayerExact(target);
map.put(player, location);
sender.sendMessage(PREINFO + "プレイヤー " + target + " をテレポートします。");
} else {
for ( Player p : members.get(target) ) {
map.put(p, location);
}
sender.sendMessage(PREINFO + "チーム " + target + " のプレイヤーを全員テレポートします。");
}
if ( map.size() > 0 ) {
DelayedTeleportTask task = new DelayedTeleportTask(map,
plugin.getCTConfig().getTeleportDelay());
task.startTask();
}
return true;
}
}
|
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheck.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheck.java
index 9d12ebb4e..bacfec9de 100644
--- a/src/checkstyle/com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheck.java
+++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheck.java
@@ -1,98 +1,98 @@
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2002 Oliver Burn
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.api;
import java.util.Set;
import java.util.HashSet;
import java.io.File;
import com.puppycrawl.tools.checkstyle.PackageNamesLoader;
/**
* Provides common functionality for many FileSetChecks.
*
* @author lkuehne
*/
public abstract class AbstractFileSetCheck
extends AutomaticBean implements FileSetCheck
{
/** The dispatcher errors are fired to. */
private MessageDispatcher mDispatcher = null;
/** List of package names for object instantiation */
private String[] mPackageNames;
/**
* Does nothing.
* @see com.puppycrawl.tools.checkstyle.api.FileSetCheck
*/
public void destroy()
{
}
/**
* Returns the set of directories for a set of files.
* @param aFiles s set of files
* @return the set of parent directories of the given files
*/
protected Set getParentDirs(File[] aFiles)
{
Set directories = new HashSet();
for (int i = 0; i < aFiles.length; i++) {
- File file = aFiles[i];
+ File file = aFiles[i].getAbsoluteFile();
if (file.getName().endsWith(".java")) {
File dir = file.getParentFile();
directories.add(dir); // duplicates are handled automatically
}
}
return directories;
}
/** @see com.puppycrawl.tools.checkstyle.api.FileSetCheck */
public void setMessageDispatcher(MessageDispatcher aDispatcher)
{
mDispatcher = aDispatcher;
}
/** @return the current MessageDispatcher. */
protected MessageDispatcher getMessageDispatcher()
{
return mDispatcher;
}
/** @see com.puppycrawl.tools.checkstyle.api.PackageNamesBean */
public void setPackageNames(String[] aPackageNames)
{
mPackageNames = aPackageNames;
}
/** @see com.puppycrawl.tools.checkstyle.api.PackageNamesBean */
public String[] getPackageNames()
throws CheckstyleException
{
if (mPackageNames == null) {
mPackageNames = PackageNamesLoader.loadPackageNames(
this.getClass().getClassLoader());
}
return mPackageNames;
}
}
| true | true | protected Set getParentDirs(File[] aFiles)
{
Set directories = new HashSet();
for (int i = 0; i < aFiles.length; i++) {
File file = aFiles[i];
if (file.getName().endsWith(".java")) {
File dir = file.getParentFile();
directories.add(dir); // duplicates are handled automatically
}
}
return directories;
}
| protected Set getParentDirs(File[] aFiles)
{
Set directories = new HashSet();
for (int i = 0; i < aFiles.length; i++) {
File file = aFiles[i].getAbsoluteFile();
if (file.getName().endsWith(".java")) {
File dir = file.getParentFile();
directories.add(dir); // duplicates are handled automatically
}
}
return directories;
}
|
diff --git a/src/org/jacorb/orb/portableInterceptor/ClientRequestInfoImpl.java b/src/org/jacorb/orb/portableInterceptor/ClientRequestInfoImpl.java
index fa47fa065..f5fc6843c 100644
--- a/src/org/jacorb/orb/portableInterceptor/ClientRequestInfoImpl.java
+++ b/src/org/jacorb/orb/portableInterceptor/ClientRequestInfoImpl.java
@@ -1,368 +1,368 @@
/*
* JacORB - a free Java ORB
*
* Copyright (C) 1999-2004 Gerald Brose
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
package org.jacorb.orb.portableInterceptor;
import org.omg.IOP.*;
import org.omg.CORBA.*;
import org.omg.PortableInterceptor.*;
import org.omg.Dynamic.Parameter;
import org.omg.ETF.*;
import org.apache.avalon.framework.logger.*;
import java.util.*;
import org.jacorb.orb.iiop.IIOPProfile;
/**
* This class represents the type of info object,
* that will be passed to the ClientRequestInterceptors. <br>
* See PI Spec p.5-46ff
*
* @author Nicolas Noffke
* @version $Id$
*/
public class ClientRequestInfoImpl
extends RequestInfoImpl
implements ClientRequestInfo
{
private Logger logger;
//from ClientRequestInfo
public org.omg.CORBA.Object target = null;
public org.omg.CORBA.Object effective_target = null;
public TaggedProfile effective_profile = null;
public Any received_exception = null;
public String received_exception_id = null;
public TaggedComponent[] effective_components = null;
public org.jacorb.orb.Delegate delegate = null;
public org.jacorb.orb.ORB orb = null;
public org.jacorb.orb.giop.RequestOutputStream request_os = null;
public org.jacorb.orb.giop.ReplyInputStream reply_is = null;
public org.jacorb.orb.giop.ClientConnection connection = null;
public ClientRequestInfoImpl
( org.jacorb.orb.ORB orb,
org.jacorb.orb.giop.RequestOutputStream ros,
org.omg.CORBA.Object self,
org.jacorb.orb.Delegate delegate,
org.jacorb.orb.ParsedIOR piorOriginal,
org.jacorb.orb.giop.ClientConnection connection )
{
this.orb = orb;
logger = orb.getConfiguration().getNamedLogger("jacorb.orb.interceptors");
this.operation = ros.operation();
this.response_expected = ros.response_expected();
this.received_exception = orb.create_any();
if ( ros.getRequest() != null )
this.setRequest( ros.getRequest() );
this.effective_target = self;
org.jacorb.orb.ParsedIOR pior = delegate.getParsedIOR();
if ( piorOriginal != null )
- this.target = orb._getObject( piorOriginal );
+ this.target = orb._getObject( pior );
else
this.target = self;
Profile profile = pior.getEffectiveProfile();
if (profile instanceof org.jacorb.orb.etf.ProfileBase)
{
this.effective_profile = ((org.jacorb.orb.etf.ProfileBase)profile).asTaggedProfile();
this.effective_components = ((org.jacorb.orb.etf.ProfileBase)profile).getComponents().asArray();
}
if ( this.effective_components == null )
{
this.effective_components = new org.omg.IOP.TaggedComponent[ 0 ];
}
this.delegate = delegate;
this.request_id = ros.requestId();
InterceptorManager manager = orb.getInterceptorManager();
this.current = manager.getCurrent();
//allow interceptors access to request output stream
this.request_os = ros;
//allow (BiDir) interceptor to inspect the connection
this.connection = connection;
}
public void setRequest(org.jacorb.orb.dii.Request request)
{
arguments = new org.omg.Dynamic.Parameter[request.arguments.count()];
for (int i = 0; i < arguments.length; i++)
{
try
{
NamedValue value = request.arguments.item(i);
ParameterMode mode = null;
if (value.flags() == ARG_IN.value)
mode = ParameterMode.PARAM_IN;
else if (value.flags() == ARG_OUT.value)
mode = ParameterMode.PARAM_OUT;
else if (value.flags() == ARG_INOUT.value)
mode = ParameterMode.PARAM_INOUT;
arguments[i] = new org.omg.Dynamic.Parameter(value.value(), mode);
}
catch (Exception e)
{
if( logger.isDebugEnabled() )
{
logger.debug(e.getMessage());
}
}
}
//exceptions will be set when available
}
/**
* This method builds an array of ServiceContexts.
* The last ServiceContext is a dummy object for
* data aligning purposes.
*/
public Enumeration getRequestServiceContexts()
{
return request_ctx.elements();
}
// implementation of
// org.omg.PortableInterceptor.RequestInfoOperations interface
public Parameter[] arguments()
{
if (! (caller_op == ClientInterceptorIterator.SEND_REQUEST) &&
! (caller_op == ClientInterceptorIterator.RECEIVE_REPLY))
throw new BAD_INV_ORDER("The attribute \"arguments\" is currently invalid!",
10, CompletionStatus.COMPLETED_MAYBE);
if (arguments == null)
throw new NO_RESOURCES("Stream-based skeletons/stubs do not support this op",
1, CompletionStatus.COMPLETED_MAYBE);
else
return arguments;
}
public TypeCode[] exceptions()
{
if (caller_op == ClientInterceptorIterator.SEND_POLL)
throw new BAD_INV_ORDER("The attribute \"exceptions\" is currently invalid!",
10, CompletionStatus.COMPLETED_MAYBE);
if (exceptions == null)
throw new NO_RESOURCES("Stream-based skeletons/stubs do not support this op",
1, CompletionStatus.COMPLETED_MAYBE);
else
return exceptions;
}
public Any result()
{
if (caller_op != ClientInterceptorIterator.RECEIVE_REPLY)
throw new BAD_INV_ORDER("The attribute \"result\" is currently invalid!",
10, CompletionStatus.COMPLETED_MAYBE);
if (result == null)
throw new NO_RESOURCES("Stream-based skeletons/stubs do not support this op",
1, CompletionStatus.COMPLETED_MAYBE);
else
return result;
}
public short sync_scope()
{
if (caller_op == ClientInterceptorIterator.SEND_POLL)
throw new BAD_INV_ORDER("The attribute \"sync_scope\" is currently invalid!",
10, CompletionStatus.COMPLETED_MAYBE);
return org.omg.Messaging.SYNC_WITH_TRANSPORT.value;
}
public short reply_status()
{
if ((caller_op == ClientInterceptorIterator.SEND_REQUEST) ||
(caller_op == ClientInterceptorIterator.SEND_POLL))
throw new BAD_INV_ORDER("The attribute \"reply_status\" is currently invalid!",
10, CompletionStatus.COMPLETED_MAYBE);
return reply_status;
}
public org.omg.CORBA.Object forward_reference()
{
if( (caller_op != ClientInterceptorIterator.RECEIVE_OTHER) ||
(reply_status != LOCATION_FORWARD.value) )
throw new BAD_INV_ORDER("The attribute \"forward_reference\" is currently " +
"invalid!", 10, CompletionStatus.COMPLETED_MAYBE);
return forward_reference;
}
public ServiceContext get_request_service_context(int id)
{
if (caller_op == ClientInterceptorIterator.SEND_POLL)
throw new BAD_INV_ORDER("The attribute \"operation_context\" is currently " +
"invalid!", 10, CompletionStatus.COMPLETED_MAYBE);
return super.get_request_service_context(id);
}
public ServiceContext get_reply_service_context(int id)
{
if ((caller_op == ClientInterceptorIterator.SEND_REQUEST) ||
(caller_op == ClientInterceptorIterator.SEND_POLL))
throw new BAD_INV_ORDER("The attribute \"reply_status\" is currently invalid!",
10, CompletionStatus.COMPLETED_MAYBE);
return super.get_reply_service_context(id);
}
// implementation of ClientRequestInfoOperations interface
public org.omg.CORBA.Object target()
{
return target;
}
public org.omg.CORBA.Object effective_target()
{
return effective_target;
}
public TaggedProfile effective_profile() {
return effective_profile;
}
public Any received_exception()
{
if (caller_op != ClientInterceptorIterator.RECEIVE_EXCEPTION)
throw new BAD_INV_ORDER("The attribute \"received_exception\" is currently " +
"invalid!", 10, CompletionStatus.COMPLETED_MAYBE);
return received_exception;
}
public String received_exception_id()
{
if (caller_op != ClientInterceptorIterator.RECEIVE_EXCEPTION)
throw new BAD_INV_ORDER("The attribute \"received_exception_id\" is " +
"currently invalid!", 10,
CompletionStatus.COMPLETED_MAYBE);
return received_exception_id;
}
public TaggedComponent get_effective_component(int id)
{
if (caller_op == ClientInterceptorIterator.SEND_POLL)
throw new BAD_INV_ORDER("The operation \"get_effective_component\" is " +
"currently invalid!", 10,
CompletionStatus.COMPLETED_MAYBE);
for(int _i = 0; _i < effective_components.length; _i++)
if (effective_components[_i].tag == id)
return effective_components[_i];
throw new BAD_PARAM("No TaggedComponent with id " + id + " found",
25, CompletionStatus.COMPLETED_MAYBE);
}
public TaggedComponent[] get_effective_components(int id)
{
if (caller_op == ClientInterceptorIterator.SEND_POLL)
throw new BAD_INV_ORDER("The operation \"get_effective_components\" is " +
"currently invalid!", 10,
CompletionStatus.COMPLETED_MAYBE);
Vector _store = new Vector();
for(int _i = 0; _i < effective_components.length; _i++)
if (effective_components[_i].tag == id)
_store.addElement(effective_components[_i]);
if (_store.size() == 0)
throw new BAD_PARAM("No TaggedComponents with id " + id + " found",
25, CompletionStatus.COMPLETED_MAYBE);
else
{
TaggedComponent[] _result = new TaggedComponent[_store.size()];
for (int _i = 0; _i < _result.length; _i++)
_result[_i] = (TaggedComponent) _store.elementAt(_i);
return _result;
}
}
/**
* WARNING: This method relies on the DomainService to be available.
* Make shure that the DS is running, if you want to call this method.
*/
public Policy get_request_policy(int type)
{
if (caller_op == ClientInterceptorIterator.SEND_POLL)
throw new BAD_INV_ORDER("The operation \"get_request_policy\" is currently " +
"invalid!", 10, CompletionStatus.COMPLETED_MAYBE);
if (! orb.hasPolicyFactoryForType(type))
throw new INV_POLICY("No PolicyFactory for type " + type +
" has been registered!", 1,
CompletionStatus.COMPLETED_MAYBE);
try
{
return delegate.get_policy (target, type);
}
catch(INV_POLICY _e)
{
_e.minor = 1;
throw _e;
}
}
public void add_request_service_context(ServiceContext service_context,
boolean replace)
{
if (caller_op != ClientInterceptorIterator.SEND_REQUEST)
throw new BAD_INV_ORDER("The operation \"add_request_service_context\" is " +
"currently invalid!", 10,
CompletionStatus.COMPLETED_MAYBE);
Integer _id = new Integer(service_context.context_id);
if (! replace && request_ctx.containsKey(_id))
throw new BAD_INV_ORDER("The ServiceContext with id " + _id.toString()
+ " has already been set!", 11,
CompletionStatus.COMPLETED_MAYBE);
request_ctx.put(_id, service_context);
}
} // ClientRequestInfoImpl
| true | true | public ClientRequestInfoImpl
( org.jacorb.orb.ORB orb,
org.jacorb.orb.giop.RequestOutputStream ros,
org.omg.CORBA.Object self,
org.jacorb.orb.Delegate delegate,
org.jacorb.orb.ParsedIOR piorOriginal,
org.jacorb.orb.giop.ClientConnection connection )
{
this.orb = orb;
logger = orb.getConfiguration().getNamedLogger("jacorb.orb.interceptors");
this.operation = ros.operation();
this.response_expected = ros.response_expected();
this.received_exception = orb.create_any();
if ( ros.getRequest() != null )
this.setRequest( ros.getRequest() );
this.effective_target = self;
org.jacorb.orb.ParsedIOR pior = delegate.getParsedIOR();
if ( piorOriginal != null )
this.target = orb._getObject( piorOriginal );
else
this.target = self;
Profile profile = pior.getEffectiveProfile();
if (profile instanceof org.jacorb.orb.etf.ProfileBase)
{
this.effective_profile = ((org.jacorb.orb.etf.ProfileBase)profile).asTaggedProfile();
this.effective_components = ((org.jacorb.orb.etf.ProfileBase)profile).getComponents().asArray();
}
if ( this.effective_components == null )
{
this.effective_components = new org.omg.IOP.TaggedComponent[ 0 ];
}
this.delegate = delegate;
this.request_id = ros.requestId();
InterceptorManager manager = orb.getInterceptorManager();
this.current = manager.getCurrent();
//allow interceptors access to request output stream
this.request_os = ros;
//allow (BiDir) interceptor to inspect the connection
this.connection = connection;
}
| public ClientRequestInfoImpl
( org.jacorb.orb.ORB orb,
org.jacorb.orb.giop.RequestOutputStream ros,
org.omg.CORBA.Object self,
org.jacorb.orb.Delegate delegate,
org.jacorb.orb.ParsedIOR piorOriginal,
org.jacorb.orb.giop.ClientConnection connection )
{
this.orb = orb;
logger = orb.getConfiguration().getNamedLogger("jacorb.orb.interceptors");
this.operation = ros.operation();
this.response_expected = ros.response_expected();
this.received_exception = orb.create_any();
if ( ros.getRequest() != null )
this.setRequest( ros.getRequest() );
this.effective_target = self;
org.jacorb.orb.ParsedIOR pior = delegate.getParsedIOR();
if ( piorOriginal != null )
this.target = orb._getObject( pior );
else
this.target = self;
Profile profile = pior.getEffectiveProfile();
if (profile instanceof org.jacorb.orb.etf.ProfileBase)
{
this.effective_profile = ((org.jacorb.orb.etf.ProfileBase)profile).asTaggedProfile();
this.effective_components = ((org.jacorb.orb.etf.ProfileBase)profile).getComponents().asArray();
}
if ( this.effective_components == null )
{
this.effective_components = new org.omg.IOP.TaggedComponent[ 0 ];
}
this.delegate = delegate;
this.request_id = ros.requestId();
InterceptorManager manager = orb.getInterceptorManager();
this.current = manager.getCurrent();
//allow interceptors access to request output stream
this.request_os = ros;
//allow (BiDir) interceptor to inspect the connection
this.connection = connection;
}
|
diff --git a/test/org/encog/neural/networks/training/TestBackpropagation.java b/test/org/encog/neural/networks/training/TestBackpropagation.java
index 717605251..c14349523 100644
--- a/test/org/encog/neural/networks/training/TestBackpropagation.java
+++ b/test/org/encog/neural/networks/training/TestBackpropagation.java
@@ -1,71 +1,71 @@
package org.encog.neural.networks.training;
import java.util.Iterator;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.encog.neural.data.NeuralDataSet;
import org.encog.neural.data.basic.BasicNeuralDataSet;
import org.encog.neural.networks.BasicNetwork;
import org.encog.neural.networks.CreateNetwork;
import org.encog.neural.networks.XOR;
import org.encog.neural.networks.layers.BasicLayer;
import org.encog.neural.networks.layers.Layer;
import org.encog.neural.networks.training.propagation.back.Backpropagation;
import org.encog.neural.prune.PruneSelective;
import org.junit.Test;
public class TestBackpropagation extends TestCase {
@Test
public void testBackpropagation() throws Throwable
{
NeuralDataSet trainingData = new BasicNeuralDataSet(XOR.XOR_INPUT,XOR.XOR_IDEAL);
BasicNetwork network = CreateNetwork.createXORNetworkUntrained();
Train train = new Backpropagation(network, trainingData, 0.7, 0.9);
train.iteration();
double error1 = train.getError();
train.iteration();
network = (BasicNetwork)train.getNetwork();
double error2 = train.getError();
double improve = (error1-error2)/error1;
- Assert.assertTrue("Error too high for backpropagation",improve>0.01);
+ Assert.assertTrue("Error too high for backpropagation",improve>0.001);
}
@Test
public void testToString() throws Throwable
{
BasicNetwork network = CreateNetwork.createXORNetworkUntrained();
network.getInputLayer().toString();
}
@Test
public void testCounts() throws Throwable
{
BasicNetwork network = CreateNetwork.createXORNetworkUntrained();
network.getInputLayer().toString();
Assert.assertEquals(1, network.getHiddenLayerCount());
Assert.assertEquals(6, network.calculateNeuronCount());
}
@Test
public void testPrune() throws Throwable
{
BasicNetwork network = CreateNetwork.createXORNetworkUntrained();
Iterator<Layer> itr = network.getHiddenLayers().iterator();
BasicLayer hidden = (BasicLayer)itr.next();
Assert.assertEquals(3,hidden.getNeuronCount());
PruneSelective prune = new PruneSelective(network);
prune.prune(hidden, 1);
Assert.assertEquals(2,hidden.getNeuronCount());
}
}
| true | true | public void testBackpropagation() throws Throwable
{
NeuralDataSet trainingData = new BasicNeuralDataSet(XOR.XOR_INPUT,XOR.XOR_IDEAL);
BasicNetwork network = CreateNetwork.createXORNetworkUntrained();
Train train = new Backpropagation(network, trainingData, 0.7, 0.9);
train.iteration();
double error1 = train.getError();
train.iteration();
network = (BasicNetwork)train.getNetwork();
double error2 = train.getError();
double improve = (error1-error2)/error1;
Assert.assertTrue("Error too high for backpropagation",improve>0.01);
}
| public void testBackpropagation() throws Throwable
{
NeuralDataSet trainingData = new BasicNeuralDataSet(XOR.XOR_INPUT,XOR.XOR_IDEAL);
BasicNetwork network = CreateNetwork.createXORNetworkUntrained();
Train train = new Backpropagation(network, trainingData, 0.7, 0.9);
train.iteration();
double error1 = train.getError();
train.iteration();
network = (BasicNetwork)train.getNetwork();
double error2 = train.getError();
double improve = (error1-error2)/error1;
Assert.assertTrue("Error too high for backpropagation",improve>0.001);
}
|
diff --git a/tapassist/src/tw/edu/ntu/csie/mhci/tapassist/utils/Layout.java b/tapassist/src/tw/edu/ntu/csie/mhci/tapassist/utils/Layout.java
index abd3a1a..cfde826 100644
--- a/tapassist/src/tw/edu/ntu/csie/mhci/tapassist/utils/Layout.java
+++ b/tapassist/src/tw/edu/ntu/csie/mhci/tapassist/utils/Layout.java
@@ -1,23 +1,23 @@
package tw.edu.ntu.csie.mhci.tapassist.utils;
import android.app.Activity;
import android.graphics.Rect;
import android.util.Log;
import android.view.Window;
public class Layout {
public static int getStatusBar(Activity activity) {
Rect rectgle = new Rect();
Window window = activity.getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
int StatusBarHeight = rectgle.top;
int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT)
.getTop();
int TitleBarHeight = contentViewTop - StatusBarHeight;
Log.i("debug", "StatusBar Height= " + StatusBarHeight
+ " , TitleBar Height = " + TitleBarHeight);
- return TitleBarHeight;
+ return contentViewTop;
}
}
| true | true | public static int getStatusBar(Activity activity) {
Rect rectgle = new Rect();
Window window = activity.getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
int StatusBarHeight = rectgle.top;
int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT)
.getTop();
int TitleBarHeight = contentViewTop - StatusBarHeight;
Log.i("debug", "StatusBar Height= " + StatusBarHeight
+ " , TitleBar Height = " + TitleBarHeight);
return TitleBarHeight;
}
| public static int getStatusBar(Activity activity) {
Rect rectgle = new Rect();
Window window = activity.getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
int StatusBarHeight = rectgle.top;
int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT)
.getTop();
int TitleBarHeight = contentViewTop - StatusBarHeight;
Log.i("debug", "StatusBar Height= " + StatusBarHeight
+ " , TitleBar Height = " + TitleBarHeight);
return contentViewTop;
}
|
diff --git a/src/net/gamerservices/npcx/myPlayer.java b/src/net/gamerservices/npcx/myPlayer.java
index e931019..ac4a688 100644
--- a/src/net/gamerservices/npcx/myPlayer.java
+++ b/src/net/gamerservices/npcx/myPlayer.java
@@ -1,138 +1,138 @@
package net.gamerservices.npcx;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import net.gamerservices.npclibfork.BasicHumanNpc;
import org.bukkit.Location;
import org.bukkit.entity.Player;
public class myPlayer {
public npcx parent;
public Player player;
public BasicHumanNpc target;
public boolean dead = false;
public String name;
public int zomgcount = 0;
public myZone lastmyzone;
public int lastchunkx;
public int lastchunkz;
myPlayer(npcx parent,Player player, String name)
{
this.parent = parent;
this.player = player;
this.name = name;
}
public int getNPCXBalance()
{
try {
PreparedStatement stmtNPC = this.parent.universe.conn.prepareStatement("SELECT coin FROM player WHERE name = ? LIMIT 1;");
stmtNPC.setString(1,this.player.getName());
stmtNPC.executeQuery();
ResultSet rsNPC = stmtNPC.getResultSet ();
while (rsNPC.next ())
{
return rsNPC.getInt ("coin");
}
rsNPC.close();
stmtNPC.close();
return 0;
} catch (Exception e)
{
e.printStackTrace();
return 0;
}
}
public boolean setNPCXBalance(int amount)
{
try
{
PreparedStatement stmt = this.parent.universe.conn.prepareStatement("INSERT INTO player (coin,name) VALUES (?,?) ON DUPLICATE KEY UPDATE coin=VALUES(coin) ",Statement.RETURN_GENERATED_KEYS);
stmt.setInt(1,amount);
stmt.setString(2,this.player.getName());
stmt.executeUpdate();
ResultSet keyset = stmt.getGeneratedKeys();
int key = 0;
if ( keyset.next() ) {
// Retrieve the auto generated key(s).
key = keyset.getInt(1);
}
stmt.close();
} catch (Exception e)
{
e.printStackTrace();
return false;
}
return false;
}
public boolean updateFactionNegative(myFaction faction) {
// TODO Auto-generated method stub
try
{
PreparedStatement stmt = this.parent.universe.conn.prepareStatement("INSERT INTO player_faction (player_name,faction_id,amount) VALUES (?,?,?) ON DUPLICATE KEY UPDATE amount=amount+VALUES(amount) ",Statement.RETURN_GENERATED_KEYS);
stmt.setString(1,this.player.getName());
stmt.setInt(2,faction.id);
stmt.setInt(3,-1);
stmt.executeUpdate();
ResultSet keyset = stmt.getGeneratedKeys();
int key = 0;
if ( keyset.next() ) {
// Retrieve the auto generated key(s).
key = keyset.getInt(1);
}
return true;
} catch (Exception e)
{
e.printStackTrace();
return false;
}
}
public int getPlayerFactionStanding(myFaction faction) {
// TODO Auto-generated method stub
try {
- PreparedStatement stmtNPC = this.parent.universe.conn.prepareStatement("SELECT amount FROM player_faction WHERE name = ? AND faction_id = ? LIMIT 1;");
+ PreparedStatement stmtNPC = this.parent.universe.conn.prepareStatement("SELECT amount FROM player_faction WHERE playername = ? AND faction_id = ? LIMIT 1;");
stmtNPC.setString(1,this.player.getName());
stmtNPC.setInt(2,faction.id);
stmtNPC.executeQuery();
ResultSet rsNPC = stmtNPC.getResultSet ();
while (rsNPC.next ())
{
return rsNPC.getInt ("amount");
}
rsNPC.close();
stmtNPC.close();
return 0;
} catch (Exception e)
{
e.printStackTrace();
return 0;
}
}
}
| true | true | public int getPlayerFactionStanding(myFaction faction) {
// TODO Auto-generated method stub
try {
PreparedStatement stmtNPC = this.parent.universe.conn.prepareStatement("SELECT amount FROM player_faction WHERE name = ? AND faction_id = ? LIMIT 1;");
stmtNPC.setString(1,this.player.getName());
stmtNPC.setInt(2,faction.id);
stmtNPC.executeQuery();
ResultSet rsNPC = stmtNPC.getResultSet ();
while (rsNPC.next ())
{
return rsNPC.getInt ("amount");
}
rsNPC.close();
stmtNPC.close();
return 0;
} catch (Exception e)
{
e.printStackTrace();
return 0;
}
}
| public int getPlayerFactionStanding(myFaction faction) {
// TODO Auto-generated method stub
try {
PreparedStatement stmtNPC = this.parent.universe.conn.prepareStatement("SELECT amount FROM player_faction WHERE playername = ? AND faction_id = ? LIMIT 1;");
stmtNPC.setString(1,this.player.getName());
stmtNPC.setInt(2,faction.id);
stmtNPC.executeQuery();
ResultSet rsNPC = stmtNPC.getResultSet ();
while (rsNPC.next ())
{
return rsNPC.getInt ("amount");
}
rsNPC.close();
stmtNPC.close();
return 0;
} catch (Exception e)
{
e.printStackTrace();
return 0;
}
}
|
diff --git a/src/org/opensolaris/opengrok/management/TimerFilter.java b/src/org/opensolaris/opengrok/management/TimerFilter.java
index e2fb796..348509c 100755
--- a/src/org/opensolaris/opengrok/management/TimerFilter.java
+++ b/src/org/opensolaris/opengrok/management/TimerFilter.java
@@ -1,54 +1,53 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* See LICENSE.txt included in this distribution for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2008 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
package org.opensolaris.opengrok.management;
import javax.management.Notification;
import javax.management.NotificationFilter;
import javax.management.timer.TimerNotification;
/**
*
* @author Jan S Berg
*/
public class TimerFilter implements NotificationFilter {
private final Integer id;
/** Creates a new instance of TimerFilter */
public TimerFilter(Integer id) {
this.id = id;
}
public boolean isNotificationEnabled(Notification n) {
- if (n.getType().equals("timer.notification") &&
- n instanceof TimerNotification) {
+ if (n instanceof TimerNotification) {
TimerNotification timerNotif = (TimerNotification) n;
if (timerNotif.getNotificationID().equals(id)) {
return true;
}
}
return false;
}
}
| true | true | public boolean isNotificationEnabled(Notification n) {
if (n.getType().equals("timer.notification") &&
n instanceof TimerNotification) {
TimerNotification timerNotif = (TimerNotification) n;
if (timerNotif.getNotificationID().equals(id)) {
return true;
}
}
return false;
}
| public boolean isNotificationEnabled(Notification n) {
if (n instanceof TimerNotification) {
TimerNotification timerNotif = (TimerNotification) n;
if (timerNotif.getNotificationID().equals(id)) {
return true;
}
}
return false;
}
|
diff --git a/src/xi/util/Logging.java b/src/xi/util/Logging.java
index 9755eca..9dd5797 100644
--- a/src/xi/util/Logging.java
+++ b/src/xi/util/Logging.java
@@ -1,20 +1,20 @@
package xi.util;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* FIXME: to be replaced with Leo's class.
*
*/
public class Logging {
public static <T> Logger getLogger(final Class<T> c) {
- return null;
+ return Logger.getLogger(c.getName());
}
public static void setLevel(final Level info) {
// no-op
}
}
| true | true | public static <T> Logger getLogger(final Class<T> c) {
return null;
}
| public static <T> Logger getLogger(final Class<T> c) {
return Logger.getLogger(c.getName());
}
|
diff --git a/src/java/com/android/internal/telephony/cat/CatService.java b/src/java/com/android/internal/telephony/cat/CatService.java
index 156c977..8ae5fea 100644
--- a/src/java/com/android/internal/telephony/cat/CatService.java
+++ b/src/java/com/android/internal/telephony/cat/CatService.java
@@ -1,907 +1,907 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.telephony.cat;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.AsyncResult;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.SystemProperties;
import com.android.internal.telephony.IccUtils;
import com.android.internal.telephony.CommandsInterface;
import com.android.internal.telephony.IccFileHandler;
import com.android.internal.telephony.IccRecords;
import com.android.internal.telephony.UiccCard;
import com.android.internal.telephony.UiccCardApplication;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Locale;
class RilMessage {
int mId;
Object mData;
ResultCode mResCode;
RilMessage(int msgId, String rawData) {
mId = msgId;
mData = rawData;
}
RilMessage(RilMessage other) {
this.mId = other.mId;
this.mData = other.mData;
this.mResCode = other.mResCode;
}
}
/**
* Class that implements SIM Toolkit Telephony Service. Interacts with the RIL
* and application.
*
* {@hide}
*/
public class CatService extends Handler implements AppInterface {
// Class members
private static IccRecords mIccRecords;
private static UiccCardApplication mUiccApplication;
// Service members.
// Protects singleton instance lazy initialization.
private static final Object sInstanceLock = new Object();
private static CatService sInstance;
private CommandsInterface mCmdIf;
private Context mContext;
private CatCmdMessage mCurrntCmd = null;
private CatCmdMessage mMenuCmd = null;
// Samsung STK
private int mTimeoutDest = 0;
private int mCallControlResultCode = 0;
private RilMessageDecoder mMsgDecoder = null;
private boolean mStkAppInstalled = false;
// Service constants.
static final int MSG_ID_SESSION_END = 1;
static final int MSG_ID_PROACTIVE_COMMAND = 2;
static final int MSG_ID_EVENT_NOTIFY = 3;
static final int MSG_ID_CALL_SETUP = 4;
static final int MSG_ID_REFRESH = 5;
static final int MSG_ID_RESPONSE = 6;
static final int MSG_ID_SIM_READY = 7;
static final int MSG_ID_TIMEOUT = 9; // Samsung STK
static final int MSG_ID_RIL_MSG_DECODED = 10;
static final int MSG_ID_SEND_SMS_RESULT = 12; // Samsung STK
// Events to signal SIM presence or absent in the device.
private static final int MSG_ID_ICC_RECORDS_LOADED = 20;
private static final int DEV_ID_KEYPAD = 0x01;
private static final int DEV_ID_DISPLAY = 0x02;
private static final int DEV_ID_EARPIECE = 0x03;
private static final int DEV_ID_UICC = 0x81;
private static final int DEV_ID_TERMINAL = 0x82;
private static final int DEV_ID_NETWORK = 0x83;
static final String STK_DEFAULT = "Defualt Message";
// Samsung STK SEND_SMS
static final int WAITING_SMS_RESULT = 2;
static final int WAITING_SMS_RESULT_TIME = 60000;
static final int SMS_SEND_OK = 0;
static final int SMS_SEND_FAIL = 32790;
static final int SMS_SEND_RETRY = 32810;
/* Intentionally private for singleton */
private CatService(CommandsInterface ci, UiccCardApplication ca, IccRecords ir,
Context context, IccFileHandler fh, UiccCard ic) {
if (ci == null || ca == null || ir == null || context == null || fh == null
|| ic == null) {
throw new NullPointerException(
"Service: Input parameters must not be null");
}
mCmdIf = ci;
mContext = context;
// Get the RilMessagesDecoder for decoding the messages.
mMsgDecoder = RilMessageDecoder.getInstance(this, fh);
// Register ril events handling.
mCmdIf.setOnCatSessionEnd(this, MSG_ID_SESSION_END, null);
mCmdIf.setOnCatProactiveCmd(this, MSG_ID_PROACTIVE_COMMAND, null);
mCmdIf.setOnCatEvent(this, MSG_ID_EVENT_NOTIFY, null);
mCmdIf.setOnCatCallSetUp(this, MSG_ID_CALL_SETUP, null);
mCmdIf.setOnCatSendSmsResult(this, MSG_ID_SEND_SMS_RESULT, null); // Samsung STK
//mCmdIf.setOnSimRefresh(this, MSG_ID_REFRESH, null);
mIccRecords = ir;
mUiccApplication = ca;
// Register for SIM ready event.
mUiccApplication.registerForReady(this, MSG_ID_SIM_READY, null);
mIccRecords.registerForRecordsLoaded(this, MSG_ID_ICC_RECORDS_LOADED, null);
// Check if STK application is availalbe
mStkAppInstalled = isStkAppInstalled();
CatLog.d(this, "Running CAT service. STK app installed:" + mStkAppInstalled);
}
public void dispose() {
mIccRecords.unregisterForRecordsLoaded(this);
mCmdIf.unSetOnCatSessionEnd(this);
mCmdIf.unSetOnCatProactiveCmd(this);
mCmdIf.unSetOnCatEvent(this);
mCmdIf.unSetOnCatCallSetUp(this);
mCmdIf.unSetOnCatSendSmsResult(this);
this.removeCallbacksAndMessages(null);
}
protected void finalize() {
CatLog.d(this, "Service finalized");
}
private void handleRilMsg(RilMessage rilMsg) {
if (rilMsg == null) {
return;
}
// dispatch messages
CommandParams cmdParams = null;
switch (rilMsg.mId) {
case MSG_ID_EVENT_NOTIFY:
if (rilMsg.mResCode == ResultCode.OK) {
cmdParams = (CommandParams) rilMsg.mData;
if (cmdParams != null) {
handleCommand(cmdParams, false);
}
}
break;
case MSG_ID_PROACTIVE_COMMAND:
try {
cmdParams = (CommandParams) rilMsg.mData;
} catch (ClassCastException e) {
// for error handling : cast exception
CatLog.d(this, "Fail to parse proactive command");
// Don't send Terminal Resp if command detail is not available
if (mCurrntCmd != null) {
sendTerminalResponse(mCurrntCmd.mCmdDet, ResultCode.CMD_DATA_NOT_UNDERSTOOD,
false, 0x00, null);
}
break;
}
if (cmdParams != null) {
if (rilMsg.mResCode == ResultCode.OK) {
handleCommand(cmdParams, true);
} else {
// for proactive commands that couldn't be decoded
// successfully respond with the code generated by the
// message decoder.
sendTerminalResponse(cmdParams.cmdDet, rilMsg.mResCode,
false, 0, null);
}
}
break;
case MSG_ID_REFRESH:
cmdParams = (CommandParams) rilMsg.mData;
if (cmdParams != null) {
handleCommand(cmdParams, false);
}
break;
case MSG_ID_SESSION_END:
handleSessionEnd();
break;
case MSG_ID_CALL_SETUP:
// prior event notify command supplied all the information
// needed for set up call processing.
break;
}
}
/**
* Handles RIL_UNSOL_STK_EVENT_NOTIFY or RIL_UNSOL_STK_PROACTIVE_COMMAND command
* from RIL.
* Sends valid proactive command data to the application using intents.
* RIL_REQUEST_STK_SEND_TERMINAL_RESPONSE will be send back if the command is
* from RIL_UNSOL_STK_PROACTIVE_COMMAND.
*/
private void handleCommand(CommandParams cmdParams, boolean isProactiveCmd) {
CatLog.d(this, cmdParams.getCommandType().name());
CharSequence message;
CatCmdMessage cmdMsg = new CatCmdMessage(cmdParams);
switch (cmdParams.getCommandType()) {
case SET_UP_MENU:
if (removeMenu(cmdMsg.getMenu())) {
mMenuCmd = null;
} else {
mMenuCmd = cmdMsg;
}
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
break;
case DISPLAY_TEXT:
// when application is not required to respond, send an immediate response.
if (!cmdMsg.geTextMessage().responseNeeded) {
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
}
break;
case REFRESH:
// ME side only handles refresh commands which meant to remove IDLE
// MODE TEXT.
cmdParams.cmdDet.typeOfCommand = CommandType.SET_UP_IDLE_MODE_TEXT.value();
break;
case SET_UP_IDLE_MODE_TEXT:
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
break;
case PROVIDE_LOCAL_INFORMATION:
ResponseData resp;
switch (cmdParams.cmdDet.commandQualifier) {
case CommandParamsFactory.DTTZ_SETTING:
resp = new DTTZResponseData(null);
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, resp);
break;
case CommandParamsFactory.LANGUAGE_SETTING:
resp = new LanguageResponseData(Locale.getDefault().getLanguage());
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, resp);
break;
default:
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
}
// No need to start STK app here.
return;
case LAUNCH_BROWSER:
if ((((LaunchBrowserParams) cmdParams).confirmMsg.text != null)
&& (((LaunchBrowserParams) cmdParams).confirmMsg.text.equals(STK_DEFAULT))) {
message = mContext.getText(com.android.internal.R.string.launchBrowserDefault);
((LaunchBrowserParams) cmdParams).confirmMsg.text = message.toString();
}
break;
case SELECT_ITEM:
case GET_INPUT:
case GET_INKEY:
break;
case SEND_DTMF:
case SEND_SMS:
- if (mContext.getResources().
- getBoolean(com.android.internal.R.bool.config_samsung_stk)) {
+ // Samsung STK
+ if (cmdParams instanceof SendSMSParams) {
handleProactiveCommandSendSMS((SendSMSParams) cmdParams);
}
// Fall through
case SEND_SS:
case SEND_USSD:
- if (mContext.getResources().
- getBoolean(com.android.internal.R.bool.config_samsung_stk)) {
+ // Samsung STK
+ if (cmdParams instanceof SendUSSDParams) {
handleProactiveCommandSendUSSD((SendUSSDParams) cmdParams);
}
if ((((DisplayTextParams)cmdParams).textMsg.text != null)
&& (((DisplayTextParams)cmdParams).textMsg.text.equals(STK_DEFAULT))) {
message = mContext.getText(com.android.internal.R.string.sending);
((DisplayTextParams)cmdParams).textMsg.text = message.toString();
}
break;
case PLAY_TONE:
break;
case SET_UP_CALL:
if ((((CallSetupParams) cmdParams).confirmMsg.text != null)
&& (((CallSetupParams) cmdParams).confirmMsg.text.equals(STK_DEFAULT))) {
message = mContext.getText(com.android.internal.R.string.SetupCallDefault);
((CallSetupParams) cmdParams).confirmMsg.text = message.toString();
}
break;
case OPEN_CHANNEL:
case CLOSE_CHANNEL:
case RECEIVE_DATA:
case SEND_DATA:
BIPClientParams cmd = (BIPClientParams) cmdParams;
if (cmd.bHasAlphaId && (cmd.textMsg.text == null)) {
CatLog.d(this, "cmd " + cmdParams.getCommandType() + " with null alpha id");
// If alpha length is zero, we just respond with OK.
if (isProactiveCmd) {
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
}
return;
}
// Respond with permanent failure to avoid retry if STK app is not present.
if (!mStkAppInstalled) {
CatLog.d(this, "No STK application found.");
if (isProactiveCmd) {
sendTerminalResponse(cmdParams.cmdDet,
ResultCode.BEYOND_TERMINAL_CAPABILITY,
false, 0, null);
return;
}
}
/*
* CLOSE_CHANNEL, RECEIVE_DATA and SEND_DATA can be delivered by
* either PROACTIVE_COMMAND or EVENT_NOTIFY.
* If PROACTIVE_COMMAND is used for those commands, send terminal
* response here.
*/
if (isProactiveCmd &&
((cmdParams.getCommandType() == CommandType.CLOSE_CHANNEL) ||
(cmdParams.getCommandType() == CommandType.RECEIVE_DATA) ||
(cmdParams.getCommandType() == CommandType.SEND_DATA))) {
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
}
break;
default:
CatLog.d(this, "Unsupported command");
return;
}
mCurrntCmd = cmdMsg;
Intent intent = new Intent(AppInterface.CAT_CMD_ACTION);
intent.putExtra("STK CMD", cmdMsg);
mContext.sendBroadcast(intent);
}
/**
* Handles RIL_UNSOL_STK_SESSION_END unsolicited command from RIL.
*
*/
private void handleSessionEnd() {
CatLog.d(this, "SESSION END");
mCurrntCmd = mMenuCmd;
Intent intent = new Intent(AppInterface.CAT_SESSION_END_ACTION);
mContext.sendBroadcast(intent);
}
private void sendTerminalResponse(CommandDetails cmdDet,
ResultCode resultCode, boolean includeAdditionalInfo,
int additionalInfo, ResponseData resp) {
if (cmdDet == null) {
return;
}
ByteArrayOutputStream buf = new ByteArrayOutputStream();
Input cmdInput = null;
if (mCurrntCmd != null) {
cmdInput = mCurrntCmd.geInput();
}
// command details
int tag = ComprehensionTlvTag.COMMAND_DETAILS.value();
if (cmdDet.compRequired) {
tag |= 0x80;
}
buf.write(tag);
buf.write(0x03); // length
buf.write(cmdDet.commandNumber);
buf.write(cmdDet.typeOfCommand);
buf.write(cmdDet.commandQualifier);
// device identities
// According to TS102.223/TS31.111 section 6.8 Structure of
// TERMINAL RESPONSE, "For all SIMPLE-TLV objects with Min=N,
// the ME should set the CR(comprehension required) flag to
// comprehension not required.(CR=0)"
// Since DEVICE_IDENTITIES and DURATION TLVs have Min=N,
// the CR flag is not set.
tag = ComprehensionTlvTag.DEVICE_IDENTITIES.value();
buf.write(tag);
buf.write(0x02); // length
buf.write(DEV_ID_TERMINAL); // source device id
buf.write(DEV_ID_UICC); // destination device id
// result
tag = 0x80 | ComprehensionTlvTag.RESULT.value();
buf.write(tag);
int length = includeAdditionalInfo ? 2 : 1;
buf.write(length);
buf.write(resultCode.value());
// additional info
if (includeAdditionalInfo) {
buf.write(additionalInfo);
}
// Fill optional data for each corresponding command
if (resp != null) {
resp.format(buf);
} else {
encodeOptionalTags(cmdDet, resultCode, cmdInput, buf);
}
byte[] rawData = buf.toByteArray();
String hexString = IccUtils.bytesToHexString(rawData);
if (false) {
CatLog.d(this, "TERMINAL RESPONSE: " + hexString);
}
mCmdIf.sendTerminalResponse(hexString, null);
}
private void encodeOptionalTags(CommandDetails cmdDet,
ResultCode resultCode, Input cmdInput, ByteArrayOutputStream buf) {
CommandType cmdType = AppInterface.CommandType.fromInt(cmdDet.typeOfCommand);
if (cmdType != null) {
switch (cmdType) {
case GET_INKEY:
// ETSI TS 102 384,27.22.4.2.8.4.2.
// If it is a response for GET_INKEY command and the response timeout
// occured, then add DURATION TLV for variable timeout case.
if ((resultCode.value() == ResultCode.NO_RESPONSE_FROM_USER.value()) &&
(cmdInput != null) && (cmdInput.duration != null)) {
getInKeyResponse(buf, cmdInput);
}
break;
case PROVIDE_LOCAL_INFORMATION:
if ((cmdDet.commandQualifier == CommandParamsFactory.LANGUAGE_SETTING) &&
(resultCode.value() == ResultCode.OK.value())) {
getPliResponse(buf);
}
break;
default:
CatLog.d(this, "encodeOptionalTags() Unsupported Cmd details=" + cmdDet);
break;
}
} else {
CatLog.d(this, "encodeOptionalTags() bad Cmd details=" + cmdDet);
}
}
private void getInKeyResponse(ByteArrayOutputStream buf, Input cmdInput) {
int tag = ComprehensionTlvTag.DURATION.value();
buf.write(tag);
buf.write(0x02); // length
buf.write(cmdInput.duration.timeUnit.SECOND.value()); // Time (Unit,Seconds)
buf.write(cmdInput.duration.timeInterval); // Time Duration
}
private void getPliResponse(ByteArrayOutputStream buf) {
// Locale Language Setting
String lang = SystemProperties.get("persist.sys.language");
if (lang != null) {
// tag
int tag = ComprehensionTlvTag.LANGUAGE.value();
buf.write(tag);
ResponseData.writeLength(buf, lang.length());
buf.write(lang.getBytes(), 0, lang.length());
}
}
private void sendMenuSelection(int menuId, boolean helpRequired) {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
// tag
int tag = BerTlv.BER_MENU_SELECTION_TAG;
buf.write(tag);
// length
buf.write(0x00); // place holder
// device identities
tag = 0x80 | ComprehensionTlvTag.DEVICE_IDENTITIES.value();
buf.write(tag);
buf.write(0x02); // length
buf.write(DEV_ID_KEYPAD); // source device id
buf.write(DEV_ID_UICC); // destination device id
// item identifier
tag = 0x80 | ComprehensionTlvTag.ITEM_ID.value();
buf.write(tag);
buf.write(0x01); // length
buf.write(menuId); // menu identifier chosen
// help request
if (helpRequired) {
tag = ComprehensionTlvTag.HELP_REQUEST.value();
buf.write(tag);
buf.write(0x00); // length
}
byte[] rawData = buf.toByteArray();
// write real length
int len = rawData.length - 2; // minus (tag + length)
rawData[1] = (byte) len;
String hexString = IccUtils.bytesToHexString(rawData);
mCmdIf.sendEnvelope(hexString, null);
}
private void eventDownload(int event, int sourceId, int destinationId,
byte[] additionalInfo, boolean oneShot) {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
// tag
int tag = BerTlv.BER_EVENT_DOWNLOAD_TAG;
buf.write(tag);
// length
buf.write(0x00); // place holder, assume length < 128.
// event list
tag = 0x80 | ComprehensionTlvTag.EVENT_LIST.value();
buf.write(tag);
buf.write(0x01); // length
buf.write(event); // event value
// device identities
tag = 0x80 | ComprehensionTlvTag.DEVICE_IDENTITIES.value();
buf.write(tag);
buf.write(0x02); // length
buf.write(sourceId); // source device id
buf.write(destinationId); // destination device id
// additional information
if (additionalInfo != null) {
for (byte b : additionalInfo) {
buf.write(b);
}
}
byte[] rawData = buf.toByteArray();
// write real length
int len = rawData.length - 2; // minus (tag + length)
rawData[1] = (byte) len;
String hexString = IccUtils.bytesToHexString(rawData);
mCmdIf.sendEnvelope(hexString, null);
}
/**
* Used for instantiating/updating the Service from the GsmPhone or CdmaPhone constructor.
*
* @param ci CommandsInterface object
* @param ir IccRecords object
* @param context phone app context
* @param fh Icc file handler
* @param ic Icc card
* @return The only Service object in the system
*/
public static CatService getInstance(CommandsInterface ci,
Context context, UiccCard ic) {
UiccCardApplication ca = null;
IccFileHandler fh = null;
IccRecords ir = null;
if (ic != null) {
/* Since Cat is not tied to any application, but rather is Uicc application
* in itself - just get first FileHandler and IccRecords object
*/
ca = ic.getApplicationIndex(0);
if (ca != null) {
fh = ca.getIccFileHandler();
ir = ca.getIccRecords();
}
}
synchronized (sInstanceLock) {
if (sInstance == null) {
if (ci == null || ca == null || ir == null || context == null || fh == null
|| ic == null) {
return null;
}
HandlerThread thread = new HandlerThread("Cat Telephony service");
thread.start();
sInstance = new CatService(ci, ca, ir, context, fh, ic);
CatLog.d(sInstance, "NEW sInstance");
} else if ((ir != null) && (mIccRecords != ir)) {
if (mIccRecords != null) {
mIccRecords.unregisterForRecordsLoaded(sInstance);
}
if (mUiccApplication != null) {
mUiccApplication.unregisterForReady(sInstance);
}
CatLog.d(sInstance,
"Reinitialize the Service with SIMRecords and UiccCardApplication");
mIccRecords = ir;
mUiccApplication = ca;
// re-Register for SIM ready event.
mIccRecords.registerForRecordsLoaded(sInstance, MSG_ID_ICC_RECORDS_LOADED, null);
mUiccApplication.registerForReady(sInstance, MSG_ID_SIM_READY, null);
CatLog.d(sInstance, "sr changed reinitialize and return current sInstance");
} else {
CatLog.d(sInstance, "Return current sInstance");
}
return sInstance;
}
}
/**
* Used by application to get an AppInterface object.
*
* @return The only Service object in the system
*/
public static AppInterface getInstance() {
return getInstance(null, null, null);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_ID_SESSION_END:
case MSG_ID_PROACTIVE_COMMAND:
case MSG_ID_EVENT_NOTIFY:
case MSG_ID_REFRESH:
CatLog.d(this, "ril message arrived");
String data = null;
if (msg.obj != null) {
AsyncResult ar = (AsyncResult) msg.obj;
if (ar != null && ar.result != null) {
try {
data = (String) ar.result;
} catch (ClassCastException e) {
break;
}
}
}
mMsgDecoder.sendStartDecodingMessageParams(new RilMessage(msg.what, data));
break;
case MSG_ID_CALL_SETUP:
mMsgDecoder.sendStartDecodingMessageParams(new RilMessage(msg.what, null));
break;
case MSG_ID_ICC_RECORDS_LOADED:
break;
case MSG_ID_RIL_MSG_DECODED:
handleRilMsg((RilMessage) msg.obj);
break;
case MSG_ID_RESPONSE:
handleCmdResponse((CatResponseMessage) msg.obj);
break;
case MSG_ID_SIM_READY:
CatLog.d(this, "SIM ready. Reporting STK service running now...");
mCmdIf.reportStkServiceIsRunning(null);
break;
case MSG_ID_TIMEOUT: // Should only be called for Samsung STK
if (mTimeoutDest == WAITING_SMS_RESULT) {
CatLog.d(this, "SMS SEND TIMEOUT");
if (CallControlResult.fromInt(mCallControlResultCode) ==
CallControlResult.CALL_CONTROL_NOT_ALLOWED)
sendTerminalResponse(mCurrntCmd.mCmdDet,
ResultCode.USIM_CALL_CONTROL_PERMANENT, true, 1, null);
else
sendTerminalResponse(mCurrntCmd.mCmdDet,
ResultCode.TERMINAL_CRNTLY_UNABLE_TO_PROCESS, false, 0, null);
break;
}
break;
case MSG_ID_SEND_SMS_RESULT: // Samsung STK SEND_SMS
if (mContext.getResources().
getBoolean(com.android.internal.R.bool.config_samsung_stk)) {
int[] sendResult;
AsyncResult ar;
CatLog.d(this, "handleMsg : MSG_ID_SEND_SMS_RESULT");
cancelTimeOut();
CatLog.d(this, "The Msg ID data:" + msg.what);
if (msg.obj == null)
break;
ar = (AsyncResult) msg.obj;
if (ar == null || ar.result == null || mCurrntCmd == null || mCurrntCmd.mCmdDet == null)
break;
sendResult = (int[]) ar.result;
switch (sendResult[0]) {
default:
CatLog.d(this, "SMS SEND GENERIC FAIL");
if (CallControlResult.fromInt(mCallControlResultCode) ==
CallControlResult.CALL_CONTROL_NOT_ALLOWED)
sendTerminalResponse(mCurrntCmd.mCmdDet,
ResultCode.USIM_CALL_CONTROL_PERMANENT, true, 1, null);
else
sendTerminalResponse(mCurrntCmd.mCmdDet,
ResultCode.TERMINAL_CRNTLY_UNABLE_TO_PROCESS, false, 0, null);
break;
case SMS_SEND_OK: // '\0'
CatLog.d(this, "SMS SEND OK");
if (CallControlResult.fromInt(mCallControlResultCode) ==
CallControlResult.CALL_CONTROL_NOT_ALLOWED)
sendTerminalResponse(mCurrntCmd.mCmdDet,
ResultCode.USIM_CALL_CONTROL_PERMANENT, true, 1, null);
else
sendTerminalResponse(mCurrntCmd.mCmdDet, ResultCode.OK, false, 0, null);
break;
case SMS_SEND_FAIL:
CatLog.d(this, "SMS SEND FAIL - MEMORY NOT AVAILABLE");
if (CallControlResult.fromInt(mCallControlResultCode) ==
CallControlResult.CALL_CONTROL_NOT_ALLOWED)
sendTerminalResponse(mCurrntCmd.mCmdDet,
ResultCode.USIM_CALL_CONTROL_PERMANENT, true, 1, null);
else
sendTerminalResponse(mCurrntCmd.mCmdDet,
ResultCode.TERMINAL_CRNTLY_UNABLE_TO_PROCESS, false, 0, null);
break;
case SMS_SEND_RETRY:
CatLog.d(this, "SMS SEND FAIL RETRY");
if (CallControlResult.fromInt(mCallControlResultCode) ==
CallControlResult.CALL_CONTROL_NOT_ALLOWED)
sendTerminalResponse(mCurrntCmd.mCmdDet,
ResultCode.USIM_CALL_CONTROL_PERMANENT, true, 1, null);
else
sendTerminalResponse(mCurrntCmd.mCmdDet,
ResultCode.NETWORK_CRNTLY_UNABLE_TO_PROCESS, false, 0, null);
break;
}
}
break;
default:
throw new AssertionError("Unrecognized CAT command: " + msg.what);
}
}
public synchronized void onCmdResponse(CatResponseMessage resMsg) {
if (resMsg == null) {
return;
}
// queue a response message.
Message msg = this.obtainMessage(MSG_ID_RESPONSE, resMsg);
msg.sendToTarget();
}
private boolean validateResponse(CatResponseMessage resMsg) {
if (mCurrntCmd != null) {
return (resMsg.cmdDet.compareTo(mCurrntCmd.mCmdDet));
}
return false;
}
private boolean removeMenu(Menu menu) {
try {
if (menu.items.size() == 1 && menu.items.get(0) == null) {
return true;
}
} catch (NullPointerException e) {
CatLog.d(this, "Unable to get Menu's items size");
return true;
}
return false;
}
private void handleCmdResponse(CatResponseMessage resMsg) {
// Make sure the response details match the last valid command. An invalid
// response is a one that doesn't have a corresponding proactive command
// and sending it can "confuse" the baseband/ril.
// One reason for out of order responses can be UI glitches. For example,
// if the application launch an activity, and that activity is stored
// by the framework inside the history stack. That activity will be
// available for relaunch using the latest application dialog
// (long press on the home button). Relaunching that activity can send
// the same command's result again to the CatService and can cause it to
// get out of sync with the SIM.
if (!validateResponse(resMsg)) {
return;
}
ResponseData resp = null;
boolean helpRequired = false;
CommandDetails cmdDet = resMsg.getCmdDetails();
switch (resMsg.resCode) {
case HELP_INFO_REQUIRED:
helpRequired = true;
// fall through
case OK:
case PRFRMD_WITH_PARTIAL_COMPREHENSION:
case PRFRMD_WITH_MISSING_INFO:
case PRFRMD_WITH_ADDITIONAL_EFS_READ:
case PRFRMD_ICON_NOT_DISPLAYED:
case PRFRMD_MODIFIED_BY_NAA:
case PRFRMD_LIMITED_SERVICE:
case PRFRMD_WITH_MODIFICATION:
case PRFRMD_NAA_NOT_ACTIVE:
case PRFRMD_TONE_NOT_PLAYED:
switch (AppInterface.CommandType.fromInt(cmdDet.typeOfCommand)) {
case SET_UP_MENU:
helpRequired = resMsg.resCode == ResultCode.HELP_INFO_REQUIRED;
sendMenuSelection(resMsg.usersMenuSelection, helpRequired);
return;
case SELECT_ITEM:
resp = new SelectItemResponseData(resMsg.usersMenuSelection);
break;
case GET_INPUT:
case GET_INKEY:
Input input = mCurrntCmd.geInput();
if (!input.yesNo) {
// when help is requested there is no need to send the text
// string object.
if (!helpRequired) {
resp = new GetInkeyInputResponseData(resMsg.usersInput,
input.ucs2, input.packed);
}
} else {
resp = new GetInkeyInputResponseData(
resMsg.usersYesNoSelection);
}
break;
case DISPLAY_TEXT:
case LAUNCH_BROWSER:
break;
case SET_UP_CALL:
mCmdIf.handleCallSetupRequestFromSim(resMsg.usersConfirm, null);
// No need to send terminal response for SET UP CALL. The user's
// confirmation result is send back using a dedicated ril message
// invoked by the CommandInterface call above.
mCurrntCmd = null;
return;
}
break;
case NO_RESPONSE_FROM_USER:
case UICC_SESSION_TERM_BY_USER:
case BACKWARD_MOVE_BY_USER:
case USER_NOT_ACCEPT:
resp = null;
break;
default:
return;
}
sendTerminalResponse(cmdDet, resMsg.resCode, false, 0, resp);
mCurrntCmd = null;
}
private boolean isStkAppInstalled() {
Intent intent = new Intent(AppInterface.CAT_CMD_ACTION);
PackageManager pm = mContext.getPackageManager();
List<ResolveInfo> broadcastReceivers =
pm.queryBroadcastReceivers(intent, PackageManager.GET_META_DATA);
int numReceiver = broadcastReceivers == null ? 0 : broadcastReceivers.size();
return (numReceiver > 0);
}
/**
* Samsung STK SEND_SMS
* @param cmdPar
*/
private void handleProactiveCommandSendSMS(SendSMSParams cmdPar) {
CatLog.d(this, "The smscaddress is: " + cmdPar.smscAddress);
CatLog.d(this, "The SMS tpdu is: " + cmdPar.pdu);
mCmdIf.sendSMS(cmdPar.smscAddress, cmdPar.pdu, null);
startTimeOut(WAITING_SMS_RESULT, WAITING_SMS_RESULT_TIME);
}
/**
* Samsung STK SEND_USSD
* @param cmdPar
*/
private void handleProactiveCommandSendUSSD(SendUSSDParams cmdPar) {
CatLog.d(this, "The USSD is: " + cmdPar.ussdString);
mCmdIf.sendUSSD(cmdPar.ussdString, null);
// Sent USSD, let framework handle the rest
}
private void cancelTimeOut() {
removeMessages(MSG_ID_TIMEOUT);
mTimeoutDest = 0;
}
private void startTimeOut(int timeout, int delay) {
cancelTimeOut();
mTimeoutDest = timeout;
sendMessageDelayed(obtainMessage(MSG_ID_TIMEOUT), delay);
}
}
| false | true | private void handleCommand(CommandParams cmdParams, boolean isProactiveCmd) {
CatLog.d(this, cmdParams.getCommandType().name());
CharSequence message;
CatCmdMessage cmdMsg = new CatCmdMessage(cmdParams);
switch (cmdParams.getCommandType()) {
case SET_UP_MENU:
if (removeMenu(cmdMsg.getMenu())) {
mMenuCmd = null;
} else {
mMenuCmd = cmdMsg;
}
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
break;
case DISPLAY_TEXT:
// when application is not required to respond, send an immediate response.
if (!cmdMsg.geTextMessage().responseNeeded) {
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
}
break;
case REFRESH:
// ME side only handles refresh commands which meant to remove IDLE
// MODE TEXT.
cmdParams.cmdDet.typeOfCommand = CommandType.SET_UP_IDLE_MODE_TEXT.value();
break;
case SET_UP_IDLE_MODE_TEXT:
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
break;
case PROVIDE_LOCAL_INFORMATION:
ResponseData resp;
switch (cmdParams.cmdDet.commandQualifier) {
case CommandParamsFactory.DTTZ_SETTING:
resp = new DTTZResponseData(null);
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, resp);
break;
case CommandParamsFactory.LANGUAGE_SETTING:
resp = new LanguageResponseData(Locale.getDefault().getLanguage());
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, resp);
break;
default:
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
}
// No need to start STK app here.
return;
case LAUNCH_BROWSER:
if ((((LaunchBrowserParams) cmdParams).confirmMsg.text != null)
&& (((LaunchBrowserParams) cmdParams).confirmMsg.text.equals(STK_DEFAULT))) {
message = mContext.getText(com.android.internal.R.string.launchBrowserDefault);
((LaunchBrowserParams) cmdParams).confirmMsg.text = message.toString();
}
break;
case SELECT_ITEM:
case GET_INPUT:
case GET_INKEY:
break;
case SEND_DTMF:
case SEND_SMS:
if (mContext.getResources().
getBoolean(com.android.internal.R.bool.config_samsung_stk)) {
handleProactiveCommandSendSMS((SendSMSParams) cmdParams);
}
// Fall through
case SEND_SS:
case SEND_USSD:
if (mContext.getResources().
getBoolean(com.android.internal.R.bool.config_samsung_stk)) {
handleProactiveCommandSendUSSD((SendUSSDParams) cmdParams);
}
if ((((DisplayTextParams)cmdParams).textMsg.text != null)
&& (((DisplayTextParams)cmdParams).textMsg.text.equals(STK_DEFAULT))) {
message = mContext.getText(com.android.internal.R.string.sending);
((DisplayTextParams)cmdParams).textMsg.text = message.toString();
}
break;
case PLAY_TONE:
break;
case SET_UP_CALL:
if ((((CallSetupParams) cmdParams).confirmMsg.text != null)
&& (((CallSetupParams) cmdParams).confirmMsg.text.equals(STK_DEFAULT))) {
message = mContext.getText(com.android.internal.R.string.SetupCallDefault);
((CallSetupParams) cmdParams).confirmMsg.text = message.toString();
}
break;
case OPEN_CHANNEL:
case CLOSE_CHANNEL:
case RECEIVE_DATA:
case SEND_DATA:
BIPClientParams cmd = (BIPClientParams) cmdParams;
if (cmd.bHasAlphaId && (cmd.textMsg.text == null)) {
CatLog.d(this, "cmd " + cmdParams.getCommandType() + " with null alpha id");
// If alpha length is zero, we just respond with OK.
if (isProactiveCmd) {
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
}
return;
}
// Respond with permanent failure to avoid retry if STK app is not present.
if (!mStkAppInstalled) {
CatLog.d(this, "No STK application found.");
if (isProactiveCmd) {
sendTerminalResponse(cmdParams.cmdDet,
ResultCode.BEYOND_TERMINAL_CAPABILITY,
false, 0, null);
return;
}
}
/*
* CLOSE_CHANNEL, RECEIVE_DATA and SEND_DATA can be delivered by
* either PROACTIVE_COMMAND or EVENT_NOTIFY.
* If PROACTIVE_COMMAND is used for those commands, send terminal
* response here.
*/
if (isProactiveCmd &&
((cmdParams.getCommandType() == CommandType.CLOSE_CHANNEL) ||
(cmdParams.getCommandType() == CommandType.RECEIVE_DATA) ||
(cmdParams.getCommandType() == CommandType.SEND_DATA))) {
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
}
break;
default:
CatLog.d(this, "Unsupported command");
return;
}
mCurrntCmd = cmdMsg;
Intent intent = new Intent(AppInterface.CAT_CMD_ACTION);
intent.putExtra("STK CMD", cmdMsg);
mContext.sendBroadcast(intent);
}
| private void handleCommand(CommandParams cmdParams, boolean isProactiveCmd) {
CatLog.d(this, cmdParams.getCommandType().name());
CharSequence message;
CatCmdMessage cmdMsg = new CatCmdMessage(cmdParams);
switch (cmdParams.getCommandType()) {
case SET_UP_MENU:
if (removeMenu(cmdMsg.getMenu())) {
mMenuCmd = null;
} else {
mMenuCmd = cmdMsg;
}
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
break;
case DISPLAY_TEXT:
// when application is not required to respond, send an immediate response.
if (!cmdMsg.geTextMessage().responseNeeded) {
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
}
break;
case REFRESH:
// ME side only handles refresh commands which meant to remove IDLE
// MODE TEXT.
cmdParams.cmdDet.typeOfCommand = CommandType.SET_UP_IDLE_MODE_TEXT.value();
break;
case SET_UP_IDLE_MODE_TEXT:
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
break;
case PROVIDE_LOCAL_INFORMATION:
ResponseData resp;
switch (cmdParams.cmdDet.commandQualifier) {
case CommandParamsFactory.DTTZ_SETTING:
resp = new DTTZResponseData(null);
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, resp);
break;
case CommandParamsFactory.LANGUAGE_SETTING:
resp = new LanguageResponseData(Locale.getDefault().getLanguage());
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, resp);
break;
default:
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
}
// No need to start STK app here.
return;
case LAUNCH_BROWSER:
if ((((LaunchBrowserParams) cmdParams).confirmMsg.text != null)
&& (((LaunchBrowserParams) cmdParams).confirmMsg.text.equals(STK_DEFAULT))) {
message = mContext.getText(com.android.internal.R.string.launchBrowserDefault);
((LaunchBrowserParams) cmdParams).confirmMsg.text = message.toString();
}
break;
case SELECT_ITEM:
case GET_INPUT:
case GET_INKEY:
break;
case SEND_DTMF:
case SEND_SMS:
// Samsung STK
if (cmdParams instanceof SendSMSParams) {
handleProactiveCommandSendSMS((SendSMSParams) cmdParams);
}
// Fall through
case SEND_SS:
case SEND_USSD:
// Samsung STK
if (cmdParams instanceof SendUSSDParams) {
handleProactiveCommandSendUSSD((SendUSSDParams) cmdParams);
}
if ((((DisplayTextParams)cmdParams).textMsg.text != null)
&& (((DisplayTextParams)cmdParams).textMsg.text.equals(STK_DEFAULT))) {
message = mContext.getText(com.android.internal.R.string.sending);
((DisplayTextParams)cmdParams).textMsg.text = message.toString();
}
break;
case PLAY_TONE:
break;
case SET_UP_CALL:
if ((((CallSetupParams) cmdParams).confirmMsg.text != null)
&& (((CallSetupParams) cmdParams).confirmMsg.text.equals(STK_DEFAULT))) {
message = mContext.getText(com.android.internal.R.string.SetupCallDefault);
((CallSetupParams) cmdParams).confirmMsg.text = message.toString();
}
break;
case OPEN_CHANNEL:
case CLOSE_CHANNEL:
case RECEIVE_DATA:
case SEND_DATA:
BIPClientParams cmd = (BIPClientParams) cmdParams;
if (cmd.bHasAlphaId && (cmd.textMsg.text == null)) {
CatLog.d(this, "cmd " + cmdParams.getCommandType() + " with null alpha id");
// If alpha length is zero, we just respond with OK.
if (isProactiveCmd) {
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
}
return;
}
// Respond with permanent failure to avoid retry if STK app is not present.
if (!mStkAppInstalled) {
CatLog.d(this, "No STK application found.");
if (isProactiveCmd) {
sendTerminalResponse(cmdParams.cmdDet,
ResultCode.BEYOND_TERMINAL_CAPABILITY,
false, 0, null);
return;
}
}
/*
* CLOSE_CHANNEL, RECEIVE_DATA and SEND_DATA can be delivered by
* either PROACTIVE_COMMAND or EVENT_NOTIFY.
* If PROACTIVE_COMMAND is used for those commands, send terminal
* response here.
*/
if (isProactiveCmd &&
((cmdParams.getCommandType() == CommandType.CLOSE_CHANNEL) ||
(cmdParams.getCommandType() == CommandType.RECEIVE_DATA) ||
(cmdParams.getCommandType() == CommandType.SEND_DATA))) {
sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
}
break;
default:
CatLog.d(this, "Unsupported command");
return;
}
mCurrntCmd = cmdMsg;
Intent intent = new Intent(AppInterface.CAT_CMD_ACTION);
intent.putExtra("STK CMD", cmdMsg);
mContext.sendBroadcast(intent);
}
|
diff --git a/java/src/ca/simplegames/micro/Micro.java b/java/src/ca/simplegames/micro/Micro.java
index ea704ff..a033c3c 100644
--- a/java/src/ca/simplegames/micro/Micro.java
+++ b/java/src/ca/simplegames/micro/Micro.java
@@ -1,388 +1,390 @@
/*
* Copyright (c)2013 Florin T.Pătraşcu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ca.simplegames.micro;
import ca.simplegames.micro.controllers.ControllerException;
import ca.simplegames.micro.controllers.ControllerNotFoundException;
import ca.simplegames.micro.helpers.HelperWrapper;
import ca.simplegames.micro.repositories.Repository;
import ca.simplegames.micro.repositories.RepositoryManager;
import ca.simplegames.micro.utils.ClassUtils;
import ca.simplegames.micro.utils.CollectionUtils;
import ca.simplegames.micro.utils.PathUtilities;
import ca.simplegames.micro.viewers.ViewException;
import org.apache.bsf.BSFManager;
import org.apache.commons.lang3.StringUtils;
import org.jrack.*;
import org.jrack.context.MapContext;
import org.jrack.utils.Mime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
/**
* A micro MVC implementation for Java web applications
*
* @author <a href="mailto:[email protected]">Florin T.PATRASCU</a>
* @since $Revision$ (created: 2013-01-01 4:22 PM)
*/
public class Micro {
private Logger log = LoggerFactory.getLogger(getClass());
public static final String DOT = ".";
public static final String SLASH = "/";
public static final String INDEX = "index";
public static final String HTML = "html";
public static final String HTML_EXTENSION = DOT + HTML;
public static final String DEFAULT_CONTENT_TYPE = Mime.mimeType(HTML_EXTENSION);
public static final String TOOLS = "Tools";
public static Context tools = new MicroContext()
.with("PathUtilities", new PathUtilities())
.with("StringUtils", new StringUtils());
private SiteContext site;
private String welcomeFile;
public Micro(String path, ServletContext servletContext, String userClassPaths) throws Exception {
final File applicationPath = new File(path);
final File webInfPath = new File(applicationPath, "WEB-INF");
showBanner();
site = new SiteContext(new MapContext<String>()
.with(Globals.SERVLET_CONTEXT, servletContext)
.with(Globals.SERVLET_PATH_NAME, path)
.with(Globals.SERVLET_PATH, applicationPath)
.with(Globals.WEB_INF_PATH, webInfPath)
);
welcomeFile = site.getWelcomeFile();
//initialize the classpath
StringBuilder cp = new StringBuilder();
if (new File(webInfPath, "/lib").exists()) {
cp.append(webInfPath.toString()).append("/lib,");
}
if (new File(webInfPath, "/classes").exists()) {
cp.append(webInfPath.toString()).append("/classes,");
}
if (StringUtils.isNotBlank(userClassPaths)) {
cp.append(",").append(userClassPaths);
}
String resources = ClassUtils.configureClasspath(webInfPath.toString(),
StringUtils.split(cp.toString(), ",:"));
if (log.isDebugEnabled()) {
log.info("classpath: " + resources);
}
configureBSF();
site.loadApplication(webInfPath.getAbsolutePath() + "/config");
// done with the init phase
//log.info("⦿‿⦿\n");
}
public RackResponse call(Context<String> input) {
MicroContext context = new MicroContext<String>();
//try {
input.with(Globals.SITE, site);
input.with(Rack.RACK_LOGGER, log);
String pathInfo = input.get(Rack.PATH_INFO);
context.with(Globals.RACK_INPUT, input)
.with(Globals.SITE, site)
.with(Rack.RACK_LOGGER, log)
.with(Globals.LOG, log)
.with(Globals.REQUEST, context.getRequest())
.with(Globals.MICRO_ENV, site.getMicroEnv())
// .with(Globals.CONTEXT, context) <-- don't, please!
.with(Globals.PARAMS, input.get(Rack.PARAMS)) //<- just a convenience
.with(Globals.SITE, site)
.with(Globals.PATH_INFO, pathInfo)
.with(TOOLS, tools);
input.with(Globals.CONTEXT, context); // mostly for helping the testing effort
for (Repository repository : site.getRepositoryManager().getRepositories()) {
context.with(repository.getName(), repository.getRepositoryWrapper(context));
}
RackResponse response = new RackResponse(RackResponseUtils.ReturnCode.OK)
.withContentType(null)
.withContentLength(0); // a la Sinatra, they're doing it right
context.setRackResponse(response);
try {
// inject the Helpers into the current context
List<HelperWrapper> helpers = site.getHelperManager().getHelpers();
if (!helpers.isEmpty()) {
for (HelperWrapper helper : helpers) {
if (helper != null) {
context.with(helper.getName(), helper.getInstance(context));
}
}
}
if (site.getFilterManager() != null) {
callFilters(site.getFilterManager().getBeforeFilters(), context);
}
if (!context.isHalt()) {
String path = input.get(JRack.PATH_INFO);
if (StringUtils.isBlank(path)) {
path = input.get(Rack.SCRIPT_NAME);
}
if (site.getRouteManager() != null) {
site.getRouteManager().call(path, context);
}
if (!context.isHalt()) {
path = (String) context.get(Globals.PATH);
if (path == null) { // user not deciding the PATH
path = maybeAppendHtmlToPath(context);
context.with(Globals.PATH, path.replace("//", SLASH));
}
final String pathBasedContentType = PathUtilities.extractType((String) context.get(Globals.PATH));
String templateName = StringUtils.defaultString(context.getTemplateName(),
RepositoryManager.DEFAULT_TEMPLATE_NAME);
Repository defaultRepository = site.getRepositoryManager().getDefaultRepository();
// verify if there is a default repository decided by 3rd party components; controllers, extensions, etc.
if (context.getDefaultRepositoryName() != null) {
defaultRepository = site.getRepositoryManager()
.getRepository(context.getDefaultRepositoryName());
}
// calculate the Template name
View view = (View) context.get(Globals.VIEW);
if (view != null && StringUtils.isNotBlank(view.getTemplate())) {
templateName = view.getTemplate();
} else {
view = defaultRepository.getView(path);
if (view != null && view.getTemplate() != null) {
templateName = view.getTemplate();
}
}
// Render the Default Template. The template will pull out the View, the result being sent out as
// the Template body merged with the View's own content. Controllers are executed *before*
// rendering the Template *and before* rendering the View, but only if there are any View or Template
// Controllers defined by the user.
Repository templatesRepository = site.getRepositoryManager().getTemplatesRepository();
if (context.getTemplatesRepositoryName() != null) {
templatesRepository = site.getRepositoryManager()
.getRepository(context.getTemplatesRepositoryName());
}
if (templatesRepository != null) {
String out = templatesRepository.getRepositoryWrapper(context)
.get(templateName + pathBasedContentType);
response.withContentLength(out.getBytes(Charset.forName(Globals.UTF8)).length)
.withBody(out);
} else {
throw new FileNotFoundException(String.format("templates repository: %s", context.getTemplatesRepositoryName()));
}
}
if (!context.isHalt()) {
if (site.getFilterManager() != null) {
callFilters(site.getFilterManager().getAfterFilters(), context);
}
}
}
return context.getRackResponse().withContentType(getContentType(context));
} catch (ControllerNotFoundException e) {
- e.printStackTrace();
+ context.with(Globals.ERROR, e);
return badJuju(context, HttpServletResponse.SC_NO_CONTENT, e);
} catch (ControllerException e) {
- e.printStackTrace();
+ context.with(Globals.ERROR, e);
return badJuju(context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
} catch (FileNotFoundException e) {
+ context.with(Globals.ERROR, e);
return badJuju(context, HttpServletResponse.SC_NOT_FOUND, e);
} catch (ViewException e) {
+ context.with(Globals.ERROR, e);
return badJuju(context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
}catch (RedirectException re){
return context.getRackResponse();
} catch (Exception e) { // must think more about this one :(
- e.printStackTrace();
+ context.with(Globals.ERROR, e);
return badJuju(context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
}
// Experimental!!!!!!
// } finally {
// // this is an experimental trick that will save some processing time required by BSF to load
// // various engines.
// @SuppressWarnings("unchecked")
// CloseableThreadLocal<BSFManager> closeableBsfManager = (CloseableThreadLocal<BSFManager>)
// context.get(Globals.CLOSEABLE_BSF_MANAGER);
// if(closeableBsfManager!=null){
// closeableBsfManager.close();
// }
// }
}
/**
* This method will do the following:
* - extract the resource file extension for the given path
* - check if there are any user defined mime types and use those otherwise
* will use the default Mime detection mechanism {@see Mime.mimeType}
* - if the response however has the Content-type defined already then the
* resulting content type is the one in the response.
*
* @param context the current context
* @return a String representing the content type value
*/
@SuppressWarnings("unchecked")
private String getContentType(MicroContext context) {
RackResponse response = context.getRackResponse();
String responseContentType = response.getHeaders().get(Globals.HEADERS_CONTENT_TYPE);
final String ext = PathUtilities.extractType((String) context.get(Globals.PATH));
String contentType = Mime.mimeType(ext);
if (responseContentType != null) {
contentType = responseContentType;
} else if (site.getUserMimeTypes() != null && site.getUserMimeTypes().containsKey(ext)) {
contentType = site.getUserMimeTypes().get(ext);
}
// verify the charset
Map<String, String[]> params = (Map<String, String[]>) context.get(Globals.PARAMS);
if (!CollectionUtils.isEmpty(params) && params.get(Globals.CHARSET) != null
&& !contentType.contains(Globals.CHARSET)) {
contentType = String.format("%s;%s", contentType, params.get(Globals.CHARSET)[0]);
}
return contentType;
}
private void configureBSF() {
BSFManager.registerScriptingEngine("beanshell", "bsh.util.BeanShellBSFEngine", new String[]{"bsh"});
BSFManager.registerScriptingEngine("groovy", "org.codehaus.groovy.bsf.GroovyEngine",
new String[]{"groovy", "gy"});
BSFManager.registerScriptingEngine("jruby19", "org.jruby.embed.bsf.JRubyEngine", new String[]{"ruby", "rb"});
}
private void showBanner() {
log.info("");
log.info(" _ __ ___ ( ) ___ _ __ ___ ");
log.info("| '_ ` _ \\| |/ __| '__/ _ \\ ");
log.info("| | | | | | | (__| | | (_) |");
log.info("|_| |_| |_|_|\\___|_| \\___/ (" + Globals.VERSION + ")");
log.info("= a modular micro MVC Java framework");
log.info("");
}
public SiteContext getSite() {
return site;
}
// todo improve me, por favor
private RackResponse badJuju(MicroContext context, int status, Exception e) {
context.with(Globals.ERROR, e);
try {
String baddie = site.getRepositoryManager().getTemplatesRepository()
.getRepositoryWrapper(context)
.get(status + HTML_EXTENSION);
return new RackResponse(status).withContentType(Mime.mimeType(HTML_EXTENSION))
.withContentLength(baddie.getBytes(Charset.forName(Globals.UTF8)).length)
.withBody(baddie);
} catch (Exception e1) {
return new RackResponse(status)
.withHeader("Content-Type", (Mime.mimeType(".html")))
.withBody(Globals.EMPTY_STRING)
.withContentLength(0);
}
}
private String maybeAppendHtmlToPath(MicroContext context) {
final Context rackInput = context.getRackInput();
String path = (String) rackInput.get(JRack.PATH_INFO);
if (StringUtils.isBlank(path)) {
path = (String) rackInput.get(Rack.SCRIPT_NAME);
}
if (welcomeFile.isEmpty() || path.contains(HTML)) {
return path;
}
if (path.lastIndexOf(DOT) == -1) {
if (!path.endsWith(SLASH)) {
path = path + SLASH;
}
String welcomeFile = StringUtils.defaultString(site.getWelcomeFile(), INDEX + DOT + HTML);
path = path + welcomeFile;
}
context.with(Globals.PATH_INFO, path);
return path;
}
private void callFilters(List<Filter> filters, MicroContext context) {
if (!filters.isEmpty()) {
for (Filter filter : filters) {
try {
filter.call(context);
if (context.isHalt()) {
break;
}
} catch (Exception e) {
e.printStackTrace();
log.error(String.format("Filter: %s, error: %s", filter, e.getMessage()));
}
}
}
}
public boolean isFilterAddsWelcomeFile() {
final String aTrue = "true";
return welcomeFile.equalsIgnoreCase(aTrue);
}
public static class PoweredBy {
public String getName() {
return Globals.FRAMEWORK_NAME;
}
public String getVersion() {
return Globals.VERSION;
}
public String toString() {
return String.format("%s version: %s", getName(), getVersion());
}
}
}
| false | true | public RackResponse call(Context<String> input) {
MicroContext context = new MicroContext<String>();
//try {
input.with(Globals.SITE, site);
input.with(Rack.RACK_LOGGER, log);
String pathInfo = input.get(Rack.PATH_INFO);
context.with(Globals.RACK_INPUT, input)
.with(Globals.SITE, site)
.with(Rack.RACK_LOGGER, log)
.with(Globals.LOG, log)
.with(Globals.REQUEST, context.getRequest())
.with(Globals.MICRO_ENV, site.getMicroEnv())
// .with(Globals.CONTEXT, context) <-- don't, please!
.with(Globals.PARAMS, input.get(Rack.PARAMS)) //<- just a convenience
.with(Globals.SITE, site)
.with(Globals.PATH_INFO, pathInfo)
.with(TOOLS, tools);
input.with(Globals.CONTEXT, context); // mostly for helping the testing effort
for (Repository repository : site.getRepositoryManager().getRepositories()) {
context.with(repository.getName(), repository.getRepositoryWrapper(context));
}
RackResponse response = new RackResponse(RackResponseUtils.ReturnCode.OK)
.withContentType(null)
.withContentLength(0); // a la Sinatra, they're doing it right
context.setRackResponse(response);
try {
// inject the Helpers into the current context
List<HelperWrapper> helpers = site.getHelperManager().getHelpers();
if (!helpers.isEmpty()) {
for (HelperWrapper helper : helpers) {
if (helper != null) {
context.with(helper.getName(), helper.getInstance(context));
}
}
}
if (site.getFilterManager() != null) {
callFilters(site.getFilterManager().getBeforeFilters(), context);
}
if (!context.isHalt()) {
String path = input.get(JRack.PATH_INFO);
if (StringUtils.isBlank(path)) {
path = input.get(Rack.SCRIPT_NAME);
}
if (site.getRouteManager() != null) {
site.getRouteManager().call(path, context);
}
if (!context.isHalt()) {
path = (String) context.get(Globals.PATH);
if (path == null) { // user not deciding the PATH
path = maybeAppendHtmlToPath(context);
context.with(Globals.PATH, path.replace("//", SLASH));
}
final String pathBasedContentType = PathUtilities.extractType((String) context.get(Globals.PATH));
String templateName = StringUtils.defaultString(context.getTemplateName(),
RepositoryManager.DEFAULT_TEMPLATE_NAME);
Repository defaultRepository = site.getRepositoryManager().getDefaultRepository();
// verify if there is a default repository decided by 3rd party components; controllers, extensions, etc.
if (context.getDefaultRepositoryName() != null) {
defaultRepository = site.getRepositoryManager()
.getRepository(context.getDefaultRepositoryName());
}
// calculate the Template name
View view = (View) context.get(Globals.VIEW);
if (view != null && StringUtils.isNotBlank(view.getTemplate())) {
templateName = view.getTemplate();
} else {
view = defaultRepository.getView(path);
if (view != null && view.getTemplate() != null) {
templateName = view.getTemplate();
}
}
// Render the Default Template. The template will pull out the View, the result being sent out as
// the Template body merged with the View's own content. Controllers are executed *before*
// rendering the Template *and before* rendering the View, but only if there are any View or Template
// Controllers defined by the user.
Repository templatesRepository = site.getRepositoryManager().getTemplatesRepository();
if (context.getTemplatesRepositoryName() != null) {
templatesRepository = site.getRepositoryManager()
.getRepository(context.getTemplatesRepositoryName());
}
if (templatesRepository != null) {
String out = templatesRepository.getRepositoryWrapper(context)
.get(templateName + pathBasedContentType);
response.withContentLength(out.getBytes(Charset.forName(Globals.UTF8)).length)
.withBody(out);
} else {
throw new FileNotFoundException(String.format("templates repository: %s", context.getTemplatesRepositoryName()));
}
}
if (!context.isHalt()) {
if (site.getFilterManager() != null) {
callFilters(site.getFilterManager().getAfterFilters(), context);
}
}
}
return context.getRackResponse().withContentType(getContentType(context));
} catch (ControllerNotFoundException e) {
e.printStackTrace();
return badJuju(context, HttpServletResponse.SC_NO_CONTENT, e);
} catch (ControllerException e) {
e.printStackTrace();
return badJuju(context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
} catch (FileNotFoundException e) {
return badJuju(context, HttpServletResponse.SC_NOT_FOUND, e);
} catch (ViewException e) {
return badJuju(context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
}catch (RedirectException re){
return context.getRackResponse();
} catch (Exception e) { // must think more about this one :(
e.printStackTrace();
return badJuju(context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
}
// Experimental!!!!!!
// } finally {
// // this is an experimental trick that will save some processing time required by BSF to load
// // various engines.
// @SuppressWarnings("unchecked")
// CloseableThreadLocal<BSFManager> closeableBsfManager = (CloseableThreadLocal<BSFManager>)
// context.get(Globals.CLOSEABLE_BSF_MANAGER);
// if(closeableBsfManager!=null){
// closeableBsfManager.close();
// }
// }
}
| public RackResponse call(Context<String> input) {
MicroContext context = new MicroContext<String>();
//try {
input.with(Globals.SITE, site);
input.with(Rack.RACK_LOGGER, log);
String pathInfo = input.get(Rack.PATH_INFO);
context.with(Globals.RACK_INPUT, input)
.with(Globals.SITE, site)
.with(Rack.RACK_LOGGER, log)
.with(Globals.LOG, log)
.with(Globals.REQUEST, context.getRequest())
.with(Globals.MICRO_ENV, site.getMicroEnv())
// .with(Globals.CONTEXT, context) <-- don't, please!
.with(Globals.PARAMS, input.get(Rack.PARAMS)) //<- just a convenience
.with(Globals.SITE, site)
.with(Globals.PATH_INFO, pathInfo)
.with(TOOLS, tools);
input.with(Globals.CONTEXT, context); // mostly for helping the testing effort
for (Repository repository : site.getRepositoryManager().getRepositories()) {
context.with(repository.getName(), repository.getRepositoryWrapper(context));
}
RackResponse response = new RackResponse(RackResponseUtils.ReturnCode.OK)
.withContentType(null)
.withContentLength(0); // a la Sinatra, they're doing it right
context.setRackResponse(response);
try {
// inject the Helpers into the current context
List<HelperWrapper> helpers = site.getHelperManager().getHelpers();
if (!helpers.isEmpty()) {
for (HelperWrapper helper : helpers) {
if (helper != null) {
context.with(helper.getName(), helper.getInstance(context));
}
}
}
if (site.getFilterManager() != null) {
callFilters(site.getFilterManager().getBeforeFilters(), context);
}
if (!context.isHalt()) {
String path = input.get(JRack.PATH_INFO);
if (StringUtils.isBlank(path)) {
path = input.get(Rack.SCRIPT_NAME);
}
if (site.getRouteManager() != null) {
site.getRouteManager().call(path, context);
}
if (!context.isHalt()) {
path = (String) context.get(Globals.PATH);
if (path == null) { // user not deciding the PATH
path = maybeAppendHtmlToPath(context);
context.with(Globals.PATH, path.replace("//", SLASH));
}
final String pathBasedContentType = PathUtilities.extractType((String) context.get(Globals.PATH));
String templateName = StringUtils.defaultString(context.getTemplateName(),
RepositoryManager.DEFAULT_TEMPLATE_NAME);
Repository defaultRepository = site.getRepositoryManager().getDefaultRepository();
// verify if there is a default repository decided by 3rd party components; controllers, extensions, etc.
if (context.getDefaultRepositoryName() != null) {
defaultRepository = site.getRepositoryManager()
.getRepository(context.getDefaultRepositoryName());
}
// calculate the Template name
View view = (View) context.get(Globals.VIEW);
if (view != null && StringUtils.isNotBlank(view.getTemplate())) {
templateName = view.getTemplate();
} else {
view = defaultRepository.getView(path);
if (view != null && view.getTemplate() != null) {
templateName = view.getTemplate();
}
}
// Render the Default Template. The template will pull out the View, the result being sent out as
// the Template body merged with the View's own content. Controllers are executed *before*
// rendering the Template *and before* rendering the View, but only if there are any View or Template
// Controllers defined by the user.
Repository templatesRepository = site.getRepositoryManager().getTemplatesRepository();
if (context.getTemplatesRepositoryName() != null) {
templatesRepository = site.getRepositoryManager()
.getRepository(context.getTemplatesRepositoryName());
}
if (templatesRepository != null) {
String out = templatesRepository.getRepositoryWrapper(context)
.get(templateName + pathBasedContentType);
response.withContentLength(out.getBytes(Charset.forName(Globals.UTF8)).length)
.withBody(out);
} else {
throw new FileNotFoundException(String.format("templates repository: %s", context.getTemplatesRepositoryName()));
}
}
if (!context.isHalt()) {
if (site.getFilterManager() != null) {
callFilters(site.getFilterManager().getAfterFilters(), context);
}
}
}
return context.getRackResponse().withContentType(getContentType(context));
} catch (ControllerNotFoundException e) {
context.with(Globals.ERROR, e);
return badJuju(context, HttpServletResponse.SC_NO_CONTENT, e);
} catch (ControllerException e) {
context.with(Globals.ERROR, e);
return badJuju(context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
} catch (FileNotFoundException e) {
context.with(Globals.ERROR, e);
return badJuju(context, HttpServletResponse.SC_NOT_FOUND, e);
} catch (ViewException e) {
context.with(Globals.ERROR, e);
return badJuju(context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
}catch (RedirectException re){
return context.getRackResponse();
} catch (Exception e) { // must think more about this one :(
context.with(Globals.ERROR, e);
return badJuju(context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
}
// Experimental!!!!!!
// } finally {
// // this is an experimental trick that will save some processing time required by BSF to load
// // various engines.
// @SuppressWarnings("unchecked")
// CloseableThreadLocal<BSFManager> closeableBsfManager = (CloseableThreadLocal<BSFManager>)
// context.get(Globals.CLOSEABLE_BSF_MANAGER);
// if(closeableBsfManager!=null){
// closeableBsfManager.close();
// }
// }
}
|
diff --git a/bibtexconverter-j/src/net/sourceforge/bibtexml/util/XSLTUtils.java b/bibtexconverter-j/src/net/sourceforge/bibtexml/util/XSLTUtils.java
index ead7c2f..45f99e0 100644
--- a/bibtexconverter-j/src/net/sourceforge/bibtexml/util/XSLTUtils.java
+++ b/bibtexconverter-j/src/net/sourceforge/bibtexml/util/XSLTUtils.java
@@ -1,565 +1,554 @@
package net.sourceforge.bibtexml.util;
/*
* $Id: XSLTUtils.java 326 2007-08-23 15:19:05Z ringler $
*
* Copyright (c) 2007 Moritz Ringler
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.prefs.Preferences;
import javax.swing.JFrame;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.TreeSet;
import java.util.regex.*;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import javax.xml.transform.stream.StreamSource;
import javax.xml.parsers.ParserConfigurationException;
import de.mospace.lang.DefaultClassLoaderProvider;
import de.mospace.lang.BrowserLauncher;
import de.mospace.lang.ClassLoaderProvider;
import de.mospace.swing.ExtensionInstaller;
import de.mospace.swing.PathInput;
import org.xml.sax.SAXException;
/**
This class configures JAXP to use an XSLT 2.0
transformation engine (currently saxon).
**/
public class XSLTUtils extends DefaultClassLoaderProvider{
public final static String TRANSFORMER_FACTORY_IMPLEMENTATION =
"net.sf.saxon.TransformerFactoryImpl";
private final static int MAX_IN_MEMORY_SIZE = 0x200000; //2097152
private static XSLTUtils instance;
private TransformerFactory tf;
private XSLTUtils(){
/* add default library directories to class path if they exist */
String fs = File.separator;
List<String> candidates = new ArrayList<String>();
candidates.add(System.getProperty("user.dir") + fs + "lib");
try{
candidates.add(new File(
DefaultClassLoaderProvider
.getRepositoryRootDir(XSLTUtils.class),
"lib").getAbsolutePath());
} catch(Exception ignore){
System.err.println(ignore);
System.err.flush();
}
String appdata = System.getenv("APPDATA");
if(appdata != null){
candidates.add(appdata + fs + "bibtexconverter");
}
candidates.add(
System.getProperty("user.home")+fs+".bibtexconverter"+fs+"lib");
Preferences node = Preferences.userNodeForPackage(net.sourceforge.bibtexml.BibTeXConverter.class);
String path = node.get("saxon", null);
if(path != null){
File f = new File(path);
if(f.isFile()){
f = f.getAbsoluteFile().getParentFile();
path = f.getPath();
}
}
candidates.add(path);
for (String cf : candidates){
if(cf != null){
File f = new File(cf);
if(f.isDirectory() && !DefaultClassLoaderProvider.isTemporary(f)){
registerLibraryDirectory(f);
} else if(f.isFile() && f.getName().endsWith(".jar")){
registerLibrary(f);
}
}
}
/* Try to obtain a Saxon transformer factory */
System.setProperty("javax.xml.transform.TransformerFactory",
TRANSFORMER_FACTORY_IMPLEMENTATION);
tf = tryToGetTransformerFactory();
}
public static synchronized XSLTUtils getInstance(){
if(instance == null){
instance = new XSLTUtils();
}
return instance;
}
public String getSaxonVersion(){
return getSaxonVersion("ProductTitle");
}
public String getSaxonVersion(String what){
String result = null;
try{
Class c = Class.forName("net.sf.saxon.Version", true, getClassLoader());
java.lang.reflect.Method m = c.getMethod("get" + what);
result = (String) m.invoke(null);
} catch (Exception ignore){
System.err.println(ignore);
System.err.flush();
}
return result;
}
public Object clone() throws CloneNotSupportedException{
throw new CloneNotSupportedException("Singleton");
}
/** Tries to obtain an instance of a Saxon TransformerFactory.
* If Saxon is on the application class path or in one of BibTeXConverter's
* installation-dependent library directories a Saxon transformer factory
* will be created and returned by calls to this method.<p>
* If Saxon has not been found in one of the above locations. This method
* asks the user to install Saxon. If the installation completes
* successfully, a Saxon transformer factory is created and returned
* by this and all future calls to this method.
* @return a Saxon TransformerFactory or null as detailed above
*/
public synchronized TransformerFactory loadTransformerFactory(final JFrame trig){
if(tf == null){
/* We first try to load from the existing class path and library
* directories.
*/
tf = tryToGetTransformerFactory();
}
if(tf == null){
/* We've been unsuccessfull so far. We ask the user to install
* saxon.
*/
if(SaxonInstaller.INSTANCE.installSaxon(trig, this)){
/* if the user has indeed installed saxon
* we update our custom class loader and
* try to create a TransformerFactory */
tf = tryToGetTransformerFactory();
}
}
return tf;
}
/** Tries to obtain an instance of a Saxon TransformerFactory. If saxon
* is not found, null is returned.
**/
public final synchronized TransformerFactory tryToGetTransformerFactory(){
if(tf == null){
Thread.currentThread().setContextClassLoader(getClassLoader());
try{
tf = TransformerFactory.newInstance();
System.out.println("Saxon found in " +
DefaultClassLoaderProvider.getRepositoryRoot(
tf.getClass()));
double saxonversion = 0;
try{
String sv = getSaxonVersion("ProductVersion");
//use only part up to second dot
int dot = sv.indexOf('.');
dot = sv.indexOf('.', dot + 1);
if(dot > 0){
sv = sv.substring(0, dot);
}
saxonversion = Double.parseDouble(sv);
} catch (Exception ignore){
System.err.println("Cannot parse saxon version.");
System.err.println(ignore);
System.err.flush();
}
System.out.println("Saxon version: " + saxonversion);
if(saxonversion >= 8.9){
System.out.println();
} else if (saxonversion >= 8.8){
//We need to switch the URI resolver to something that
//knows how to handle jar files
tf.setURIResolver(new JarAwareURIResolver());
} else {
System.out.println();
System.err.println("WARNING: This program has been developed" +
" and tested with saxon version 8.8 and later.");
}
System.out.flush();
System.err.flush();
} catch (TransformerFactoryConfigurationError ignore){
}
}
return tf;
}
private static final class SaxonInstaller{
private static SaxonInstaller INSTANCE = new SaxonInstaller();
private void addDir(final Set<File> set, final File f){
if(f != null &&
!DefaultClassLoaderProvider.isTemporary(f) &&
ExtensionInstaller.canWrite(f) &&
!f.isFile())
{
File file = f;
try{
file = f.getCanonicalFile();
} catch (IOException ignore) {
file = f;
}
set.add(file);
}
}
private File[] getUserInstallTargets(){
final Set<File> userInstallTargets = new TreeSet<File>();
addDir(userInstallTargets, new File(System.getProperty("user.dir"),
"lib"));
try{
addDir(userInstallTargets, new File(
DefaultClassLoaderProvider.getRepositoryRootDir(getClass()),
"lib"));
} catch (Exception ignore){
System.err.println(ignore.getMessage());
}
final String appdata = System.getenv("APPDATA");
if(appdata != null){
addDir(userInstallTargets, new File(appdata, "bibtexconverter"));
}
addDir(userInstallTargets, new File(System.getProperty("user.home") +
File.separator + ".bibtexconverter",
"lib"));
final String prefTarget =
Preferences.userNodeForPackage(getClass())
.get("saxon", null);
if(prefTarget != null){
addDir(userInstallTargets,
(new File(prefTarget)).getAbsoluteFile().getParentFile());
}
return userInstallTargets.toArray(new File[userInstallTargets.size()]);
}
public boolean installSaxon(final JFrame trigger, final ClassLoaderProvider clp){
final String saxonURI =
"http://sf.net/project/showfiles.php?group_id=29872&package_id=21888";
final ExtensionInstaller extInst = new ExtensionInstaller(trigger);
- final String systemInstallTarget = extInst.getWritableExtensionDirectory();
final File[] userInstallTargets = getUserInstallTargets();
Box dialogPane = Box.createVerticalBox();
JLabel text = new JLabel(
"<html>BibTeXConverter converts BibTeX to XML and " +
"derives all its other outputs<br>by applying XSLT stylesheets " +
"to the intermediary XML data." +
"To use this<br>XSLT-based functionality you need to download " +
"and install the free Saxon-B<br>XSLT engine by Michael Kay.<p>" +
"Saxon is not bundled with BibTeXConverter because "+
"it is released under a<br>GPL-incompatible open source license.<p>" +
"</html>");
dialogPane.add(text);//1
final String[] options = new String[]{
"Download and install saxon",
"Use an existing saxon installation"};
JOptionPane optionPane = new JOptionPane(
dialogPane,
JOptionPane.INFORMATION_MESSAGE,
JOptionPane.YES_NO_OPTION,
null,
options,
options[0]
);
JDialog dialog = optionPane.createDialog(trigger, "Saxon installation");
dialog.setModal(true);
dialog.setVisible(true);
final Object value = optionPane.getValue();
boolean freshInstall = true;
if(value == null){
return false;
} else if (value.equals(options[1])){
freshInstall = false;
} else if (value.equals(options[0])){
//freshInstall = true;
}
JButton button;
dialogPane = Box.createVerticalBox();
if(freshInstall){
button = new JButton(
"Open a web browser at http://sf.net/projects/saxon/files/");
button.addActionListener(new ActionListener(){
public void actionPerformed(final ActionEvent e){
try{
BrowserLauncher.openURL(saxonURI);
} catch (IOException ex){
JOptionPane.showMessageDialog(trigger,
"Can't open browser. Please do so yourself "+
"and visit<p>" + saxonURI);
}
}
});
final JPanel dl = new JPanel(new FlowLayout(FlowLayout.LEFT));
dl.add(button);
dl.add(new JLabel(" and download saxonb(\u22678-8)j.zip."));
for(Component c : dl.getComponents()){
((JComponent) c).setAlignmentX(0.0f);
}
dialogPane.add(Box.createVerticalStrut(10));
dialogPane.add(dl);//2
}
final String filename = (freshInstall? "downloaded Saxon zip" : "saxon jar");
text = new JLabel(
"<html><br>Please enter the location of the "+
filename +
" file here.</html>");
dialogPane.add(text);//3
final PathInput pinz = new PathInput("", freshInstall? ".zip" : ".jar");
dialogPane.add(pinz);//4
final ButtonGroup targets = new ButtonGroup();
if(freshInstall){
text = new JLabel(
"<html><br>Press OK to install saxon...</html>");
dialogPane.add(text);//5
JRadioButton btarget;
boolean targetSelected = false;
final Insets bmargin = new Insets(0,20,0,0);
- if(systemInstallTarget != null){
- dialogPane.add(Box.createVerticalStrut(5));
- text = new JLabel("system-wide (may affect other Java applications)");
- btarget = new JRadioButton(systemInstallTarget, false);
- btarget.setMargin(bmargin);
- btarget.setActionCommand(systemInstallTarget);
- targets.add(btarget);
- dialogPane.add(text);
- dialogPane.add(btarget);
- }
dialogPane.add(Box.createVerticalStrut(5));
if(userInstallTargets.length != 0){
text = new JLabel("for BibTeXConverter only");
dialogPane.add(text);
for(File f : userInstallTargets){
btarget = new JRadioButton(f.getAbsolutePath(), !targetSelected);
btarget.setActionCommand(f.getAbsolutePath());
btarget.setMargin(bmargin);
targets.add(btarget);
dialogPane.add(btarget);
targetSelected = true;
}
}
btarget = new JRadioButton("to a location of your choice", !targetSelected);
btarget.setActionCommand("*");
btarget.setMargin(bmargin);
targets.add(btarget);
dialogPane.add(btarget);
for(Component c : dialogPane.getComponents()){
((JComponent) c).setAlignmentX(0.0f);
}
}
optionPane = new JOptionPane(
dialogPane,
JOptionPane.INFORMATION_MESSAGE,
JOptionPane.OK_CANCEL_OPTION
);
dialog = optionPane.createDialog(trigger, "Saxon installation");
dialog.pack();
dialog.setModal(true);
boolean success = false;
for(boolean repeat = true; repeat;){
dialog.setVisible(true);
final Object result = (Integer) optionPane.getValue();
if(result == null){
repeat = false;
} else if(result == JOptionPane.UNINITIALIZED_VALUE){
} else if(result instanceof Integer){
final int res = ((Integer) result).intValue();
if(res == JOptionPane.OK_OPTION){
final boolean emptySaxonZip = pinz.getPath().equals("");
final boolean emptyTarget = freshInstall && (targets.getSelection() == null);
repeat = emptySaxonZip || emptyTarget;
success = !repeat;
if(repeat){
JOptionPane.showMessageDialog(trigger,
(emptySaxonZip? "Please specify the location of " +
"the " + filename + " file.\n" : "") +
(emptyTarget? "Please choose a target directory.\n"
: ""));
}
} else {
repeat = false;
}
}
}
String starget = null;
if(freshInstall && success){
starget = targets.getSelection().getActionCommand();
if("*".equals(starget)){
final JFileChooser jfc = new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
jfc.setMultiSelectionEnabled(false);
final int returnVal = jfc.showOpenDialog(trigger);
if(returnVal == JFileChooser.APPROVE_OPTION){
starget = jfc.getSelectedFile().getAbsolutePath();
} else {
starget = null;
}
}
}
if(freshInstall){
success = starget != null;
if(success){
String saxonZip = pinz.getPath();
File fSaxonZip = new File(pinz.getPath());
Matcher m = Pattern.compile("\\d+").matcher(fSaxonZip.getName());
String version = "9";
if(m.find()){
version = m.group(0);
}
File ftarget = new File(starget);
ftarget.mkdirs();
extInst.setTargetDirectory(ftarget);
final String saxon_jar = "saxon"+version+".jar";
//ftarget = new File(ftarget, saxon_jar);
Preferences.userNodeForPackage(net.sourceforge.bibtexml.BibTeXConverter.class)
.put("saxon", ftarget.getAbsolutePath());
//try to install saxon8-dom.jar and saxon8-jdom.jar
extInst.installExtension(new File(pinz.getPath()), "saxon"+version+"-dom.jar");
extInst.installExtension(new File(pinz.getPath()), "saxon"+version+"-jdom.jar");
//install saxon.jar
if(extInst.installExtension(new File(pinz.getPath()), "saxon"+version+".jar")){
JOptionPane.showMessageDialog(trigger,
"Saxon has been installed successfully.");
clp.registerLibraryDirectory(ftarget);
} else {
JOptionPane.showMessageDialog(trigger,
"<html>Saxon installation failed. " +
"Please extract " + saxon_jar +
" from the Saxon zip file<p>" +
"put it on your classpath " +
"and restart the application.</html>");
success = false;
}
}
} else if (success){
File ftarget = new File(pinz.getPath());
if(!ftarget.isDirectory()){
ftarget = ftarget.getAbsoluteFile().getParentFile();
}
Preferences.userNodeForPackage(net.sourceforge.bibtexml.BibTeXConverter.class)
.put("saxon", ftarget.getAbsolutePath());
success = clp.registerLibraryDirectory(ftarget);
}
return success;
}
}
private static class JarAwareURIResolver implements URIResolver{
public JarAwareURIResolver(){
//sole constructor
}
public Source resolve(String href,
String base)
throws TransformerException{
try{
URI uri = new URI(href);
if(uri.isAbsolute()){
//leave it as it is
} else if (base.startsWith("jar:")){
int lastslash = base.lastIndexOf('/');
if(lastslash >= 0){
uri = new URI(base.substring(0, lastslash + 1) + href);
} else {
uri = new URI(base + "/" + href);
}
} else {
URI baseuri = new URI(base);
uri = baseuri.resolve(uri);
}
URL url = uri.toURL();
InputStream in = url.openStream();
Source src = new StreamSource(new BufferedInputStream(in));
src.setSystemId(url.toString());
return src;
} catch (Exception ex){
throw new TransformerException(ex);
}
}
}
/** This method returns a Source that can be used by several transformers.
When Saxon DOM support is installed the returned Source will be a
DOMSource wrapping a Saxon
<code>net.sf.saxon.dom.DocumentOverNodeInfo</code>. Otherwise the
Source will be a StreamSource wrapping a ByteArrayInputStream
or a FileInputStream depending on the file size. In the latter two
cases rewind() will close the input stream and open a new
input stream on the underlying byte source, and dispose() will
close the input stream.<p>
The speed advantage that could be achieved with
in-memory sources compared to re-reading the source from file
for each transformation was not significant when I tested this.
**/
public ReusableSource makeReusableSource(File f) throws IOException{
ReusableSource result = null;
TransformerFactory tf = tryToGetTransformerFactory();
if(tf != null && tf.getFeature(DOMSource.FEATURE)){
try{
result = SaxonDOMSource.newInstance(f, getClassLoader());
} catch (SAXException ex){
} catch (ParserConfigurationException ex){
}
}
if(result == null){
if (f.length() < MAX_IN_MEMORY_SIZE){
result = new ByteArraySource(f);
} else {
result = new FileSource(f);
}
}
System.out.println(result.getClass());
return result;
}
}
| false | true | public boolean installSaxon(final JFrame trigger, final ClassLoaderProvider clp){
final String saxonURI =
"http://sf.net/project/showfiles.php?group_id=29872&package_id=21888";
final ExtensionInstaller extInst = new ExtensionInstaller(trigger);
final String systemInstallTarget = extInst.getWritableExtensionDirectory();
final File[] userInstallTargets = getUserInstallTargets();
Box dialogPane = Box.createVerticalBox();
JLabel text = new JLabel(
"<html>BibTeXConverter converts BibTeX to XML and " +
"derives all its other outputs<br>by applying XSLT stylesheets " +
"to the intermediary XML data." +
"To use this<br>XSLT-based functionality you need to download " +
"and install the free Saxon-B<br>XSLT engine by Michael Kay.<p>" +
"Saxon is not bundled with BibTeXConverter because "+
"it is released under a<br>GPL-incompatible open source license.<p>" +
"</html>");
dialogPane.add(text);//1
final String[] options = new String[]{
"Download and install saxon",
"Use an existing saxon installation"};
JOptionPane optionPane = new JOptionPane(
dialogPane,
JOptionPane.INFORMATION_MESSAGE,
JOptionPane.YES_NO_OPTION,
null,
options,
options[0]
);
JDialog dialog = optionPane.createDialog(trigger, "Saxon installation");
dialog.setModal(true);
dialog.setVisible(true);
final Object value = optionPane.getValue();
boolean freshInstall = true;
if(value == null){
return false;
} else if (value.equals(options[1])){
freshInstall = false;
} else if (value.equals(options[0])){
//freshInstall = true;
}
JButton button;
dialogPane = Box.createVerticalBox();
if(freshInstall){
button = new JButton(
"Open a web browser at http://sf.net/projects/saxon/files/");
button.addActionListener(new ActionListener(){
public void actionPerformed(final ActionEvent e){
try{
BrowserLauncher.openURL(saxonURI);
} catch (IOException ex){
JOptionPane.showMessageDialog(trigger,
"Can't open browser. Please do so yourself "+
"and visit<p>" + saxonURI);
}
}
});
final JPanel dl = new JPanel(new FlowLayout(FlowLayout.LEFT));
dl.add(button);
dl.add(new JLabel(" and download saxonb(\u22678-8)j.zip."));
for(Component c : dl.getComponents()){
((JComponent) c).setAlignmentX(0.0f);
}
dialogPane.add(Box.createVerticalStrut(10));
dialogPane.add(dl);//2
}
final String filename = (freshInstall? "downloaded Saxon zip" : "saxon jar");
text = new JLabel(
"<html><br>Please enter the location of the "+
filename +
" file here.</html>");
dialogPane.add(text);//3
final PathInput pinz = new PathInput("", freshInstall? ".zip" : ".jar");
dialogPane.add(pinz);//4
final ButtonGroup targets = new ButtonGroup();
if(freshInstall){
text = new JLabel(
"<html><br>Press OK to install saxon...</html>");
dialogPane.add(text);//5
JRadioButton btarget;
boolean targetSelected = false;
final Insets bmargin = new Insets(0,20,0,0);
if(systemInstallTarget != null){
dialogPane.add(Box.createVerticalStrut(5));
text = new JLabel("system-wide (may affect other Java applications)");
btarget = new JRadioButton(systemInstallTarget, false);
btarget.setMargin(bmargin);
btarget.setActionCommand(systemInstallTarget);
targets.add(btarget);
dialogPane.add(text);
dialogPane.add(btarget);
}
dialogPane.add(Box.createVerticalStrut(5));
if(userInstallTargets.length != 0){
text = new JLabel("for BibTeXConverter only");
dialogPane.add(text);
for(File f : userInstallTargets){
btarget = new JRadioButton(f.getAbsolutePath(), !targetSelected);
btarget.setActionCommand(f.getAbsolutePath());
btarget.setMargin(bmargin);
targets.add(btarget);
dialogPane.add(btarget);
targetSelected = true;
}
}
btarget = new JRadioButton("to a location of your choice", !targetSelected);
btarget.setActionCommand("*");
btarget.setMargin(bmargin);
targets.add(btarget);
dialogPane.add(btarget);
for(Component c : dialogPane.getComponents()){
((JComponent) c).setAlignmentX(0.0f);
}
}
optionPane = new JOptionPane(
dialogPane,
JOptionPane.INFORMATION_MESSAGE,
JOptionPane.OK_CANCEL_OPTION
);
dialog = optionPane.createDialog(trigger, "Saxon installation");
dialog.pack();
dialog.setModal(true);
boolean success = false;
for(boolean repeat = true; repeat;){
dialog.setVisible(true);
final Object result = (Integer) optionPane.getValue();
if(result == null){
repeat = false;
} else if(result == JOptionPane.UNINITIALIZED_VALUE){
} else if(result instanceof Integer){
final int res = ((Integer) result).intValue();
if(res == JOptionPane.OK_OPTION){
final boolean emptySaxonZip = pinz.getPath().equals("");
final boolean emptyTarget = freshInstall && (targets.getSelection() == null);
repeat = emptySaxonZip || emptyTarget;
success = !repeat;
if(repeat){
JOptionPane.showMessageDialog(trigger,
(emptySaxonZip? "Please specify the location of " +
"the " + filename + " file.\n" : "") +
(emptyTarget? "Please choose a target directory.\n"
: ""));
}
} else {
repeat = false;
}
}
}
String starget = null;
if(freshInstall && success){
starget = targets.getSelection().getActionCommand();
if("*".equals(starget)){
final JFileChooser jfc = new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
jfc.setMultiSelectionEnabled(false);
final int returnVal = jfc.showOpenDialog(trigger);
if(returnVal == JFileChooser.APPROVE_OPTION){
starget = jfc.getSelectedFile().getAbsolutePath();
} else {
starget = null;
}
}
}
if(freshInstall){
success = starget != null;
if(success){
String saxonZip = pinz.getPath();
File fSaxonZip = new File(pinz.getPath());
Matcher m = Pattern.compile("\\d+").matcher(fSaxonZip.getName());
String version = "9";
if(m.find()){
version = m.group(0);
}
File ftarget = new File(starget);
ftarget.mkdirs();
extInst.setTargetDirectory(ftarget);
final String saxon_jar = "saxon"+version+".jar";
//ftarget = new File(ftarget, saxon_jar);
Preferences.userNodeForPackage(net.sourceforge.bibtexml.BibTeXConverter.class)
.put("saxon", ftarget.getAbsolutePath());
//try to install saxon8-dom.jar and saxon8-jdom.jar
extInst.installExtension(new File(pinz.getPath()), "saxon"+version+"-dom.jar");
extInst.installExtension(new File(pinz.getPath()), "saxon"+version+"-jdom.jar");
//install saxon.jar
if(extInst.installExtension(new File(pinz.getPath()), "saxon"+version+".jar")){
JOptionPane.showMessageDialog(trigger,
"Saxon has been installed successfully.");
clp.registerLibraryDirectory(ftarget);
} else {
JOptionPane.showMessageDialog(trigger,
"<html>Saxon installation failed. " +
"Please extract " + saxon_jar +
" from the Saxon zip file<p>" +
"put it on your classpath " +
"and restart the application.</html>");
success = false;
}
}
} else if (success){
File ftarget = new File(pinz.getPath());
if(!ftarget.isDirectory()){
ftarget = ftarget.getAbsoluteFile().getParentFile();
}
Preferences.userNodeForPackage(net.sourceforge.bibtexml.BibTeXConverter.class)
.put("saxon", ftarget.getAbsolutePath());
success = clp.registerLibraryDirectory(ftarget);
}
return success;
}
| public boolean installSaxon(final JFrame trigger, final ClassLoaderProvider clp){
final String saxonURI =
"http://sf.net/project/showfiles.php?group_id=29872&package_id=21888";
final ExtensionInstaller extInst = new ExtensionInstaller(trigger);
final File[] userInstallTargets = getUserInstallTargets();
Box dialogPane = Box.createVerticalBox();
JLabel text = new JLabel(
"<html>BibTeXConverter converts BibTeX to XML and " +
"derives all its other outputs<br>by applying XSLT stylesheets " +
"to the intermediary XML data." +
"To use this<br>XSLT-based functionality you need to download " +
"and install the free Saxon-B<br>XSLT engine by Michael Kay.<p>" +
"Saxon is not bundled with BibTeXConverter because "+
"it is released under a<br>GPL-incompatible open source license.<p>" +
"</html>");
dialogPane.add(text);//1
final String[] options = new String[]{
"Download and install saxon",
"Use an existing saxon installation"};
JOptionPane optionPane = new JOptionPane(
dialogPane,
JOptionPane.INFORMATION_MESSAGE,
JOptionPane.YES_NO_OPTION,
null,
options,
options[0]
);
JDialog dialog = optionPane.createDialog(trigger, "Saxon installation");
dialog.setModal(true);
dialog.setVisible(true);
final Object value = optionPane.getValue();
boolean freshInstall = true;
if(value == null){
return false;
} else if (value.equals(options[1])){
freshInstall = false;
} else if (value.equals(options[0])){
//freshInstall = true;
}
JButton button;
dialogPane = Box.createVerticalBox();
if(freshInstall){
button = new JButton(
"Open a web browser at http://sf.net/projects/saxon/files/");
button.addActionListener(new ActionListener(){
public void actionPerformed(final ActionEvent e){
try{
BrowserLauncher.openURL(saxonURI);
} catch (IOException ex){
JOptionPane.showMessageDialog(trigger,
"Can't open browser. Please do so yourself "+
"and visit<p>" + saxonURI);
}
}
});
final JPanel dl = new JPanel(new FlowLayout(FlowLayout.LEFT));
dl.add(button);
dl.add(new JLabel(" and download saxonb(\u22678-8)j.zip."));
for(Component c : dl.getComponents()){
((JComponent) c).setAlignmentX(0.0f);
}
dialogPane.add(Box.createVerticalStrut(10));
dialogPane.add(dl);//2
}
final String filename = (freshInstall? "downloaded Saxon zip" : "saxon jar");
text = new JLabel(
"<html><br>Please enter the location of the "+
filename +
" file here.</html>");
dialogPane.add(text);//3
final PathInput pinz = new PathInput("", freshInstall? ".zip" : ".jar");
dialogPane.add(pinz);//4
final ButtonGroup targets = new ButtonGroup();
if(freshInstall){
text = new JLabel(
"<html><br>Press OK to install saxon...</html>");
dialogPane.add(text);//5
JRadioButton btarget;
boolean targetSelected = false;
final Insets bmargin = new Insets(0,20,0,0);
dialogPane.add(Box.createVerticalStrut(5));
if(userInstallTargets.length != 0){
text = new JLabel("for BibTeXConverter only");
dialogPane.add(text);
for(File f : userInstallTargets){
btarget = new JRadioButton(f.getAbsolutePath(), !targetSelected);
btarget.setActionCommand(f.getAbsolutePath());
btarget.setMargin(bmargin);
targets.add(btarget);
dialogPane.add(btarget);
targetSelected = true;
}
}
btarget = new JRadioButton("to a location of your choice", !targetSelected);
btarget.setActionCommand("*");
btarget.setMargin(bmargin);
targets.add(btarget);
dialogPane.add(btarget);
for(Component c : dialogPane.getComponents()){
((JComponent) c).setAlignmentX(0.0f);
}
}
optionPane = new JOptionPane(
dialogPane,
JOptionPane.INFORMATION_MESSAGE,
JOptionPane.OK_CANCEL_OPTION
);
dialog = optionPane.createDialog(trigger, "Saxon installation");
dialog.pack();
dialog.setModal(true);
boolean success = false;
for(boolean repeat = true; repeat;){
dialog.setVisible(true);
final Object result = (Integer) optionPane.getValue();
if(result == null){
repeat = false;
} else if(result == JOptionPane.UNINITIALIZED_VALUE){
} else if(result instanceof Integer){
final int res = ((Integer) result).intValue();
if(res == JOptionPane.OK_OPTION){
final boolean emptySaxonZip = pinz.getPath().equals("");
final boolean emptyTarget = freshInstall && (targets.getSelection() == null);
repeat = emptySaxonZip || emptyTarget;
success = !repeat;
if(repeat){
JOptionPane.showMessageDialog(trigger,
(emptySaxonZip? "Please specify the location of " +
"the " + filename + " file.\n" : "") +
(emptyTarget? "Please choose a target directory.\n"
: ""));
}
} else {
repeat = false;
}
}
}
String starget = null;
if(freshInstall && success){
starget = targets.getSelection().getActionCommand();
if("*".equals(starget)){
final JFileChooser jfc = new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
jfc.setMultiSelectionEnabled(false);
final int returnVal = jfc.showOpenDialog(trigger);
if(returnVal == JFileChooser.APPROVE_OPTION){
starget = jfc.getSelectedFile().getAbsolutePath();
} else {
starget = null;
}
}
}
if(freshInstall){
success = starget != null;
if(success){
String saxonZip = pinz.getPath();
File fSaxonZip = new File(pinz.getPath());
Matcher m = Pattern.compile("\\d+").matcher(fSaxonZip.getName());
String version = "9";
if(m.find()){
version = m.group(0);
}
File ftarget = new File(starget);
ftarget.mkdirs();
extInst.setTargetDirectory(ftarget);
final String saxon_jar = "saxon"+version+".jar";
//ftarget = new File(ftarget, saxon_jar);
Preferences.userNodeForPackage(net.sourceforge.bibtexml.BibTeXConverter.class)
.put("saxon", ftarget.getAbsolutePath());
//try to install saxon8-dom.jar and saxon8-jdom.jar
extInst.installExtension(new File(pinz.getPath()), "saxon"+version+"-dom.jar");
extInst.installExtension(new File(pinz.getPath()), "saxon"+version+"-jdom.jar");
//install saxon.jar
if(extInst.installExtension(new File(pinz.getPath()), "saxon"+version+".jar")){
JOptionPane.showMessageDialog(trigger,
"Saxon has been installed successfully.");
clp.registerLibraryDirectory(ftarget);
} else {
JOptionPane.showMessageDialog(trigger,
"<html>Saxon installation failed. " +
"Please extract " + saxon_jar +
" from the Saxon zip file<p>" +
"put it on your classpath " +
"and restart the application.</html>");
success = false;
}
}
} else if (success){
File ftarget = new File(pinz.getPath());
if(!ftarget.isDirectory()){
ftarget = ftarget.getAbsoluteFile().getParentFile();
}
Preferences.userNodeForPackage(net.sourceforge.bibtexml.BibTeXConverter.class)
.put("saxon", ftarget.getAbsolutePath());
success = clp.registerLibraryDirectory(ftarget);
}
return success;
}
|
diff --git a/birdeye/src/com/reed/birdseye/Assets.java b/birdeye/src/com/reed/birdseye/Assets.java
index caa3419..648dd9b 100644
--- a/birdeye/src/com/reed/birdseye/Assets.java
+++ b/birdeye/src/com/reed/birdseye/Assets.java
@@ -1,119 +1,119 @@
package com.reed.birdseye;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.esotericsoftware.spine.Animation;
import com.esotericsoftware.spine.SkeletonData;
import com.esotericsoftware.spine.SkeletonJson;
public class Assets {
static Texture itemSelector, buttons, character, material, level, floor,
tree, hydration, bucket, corn, lake, farm, house, houseIn,
craftmenu, crop, creeper, robot, robotGUI, ironOre, inventory,
copperOre, grass, dpad, dpadLEFT, dpadRIGHT, dpadUP, dpadDOWN,
pointsBar, currentItem;
static TextureRegion upChar_STILL, upChar_LEFT, upChar_RIGHT,
downChar_STILL, downChar_LEFT, downChar_RIGHT, leftChar_STILL,
leftChar_LEFT, leftChar_RIGHT, rightChar_STILL, rightChar_LEFT,
rightChar_RIGHT, mainChar, upCreeper_STILL, upCreeper_LEFT, upCreeper_RIGHT,
downCreeper_STILL, downCreeper_LEFT, downCreeper_RIGHT, leftCreeper_STILL,
leftCreeper_LEFT, leftCreeper_RIGHT, rightCreeper_STILL, rightCreeper_LEFT,
rightCreeper_RIGHT, mainCreeper;
// Spine stuffz
static TextureAtlas treeAtlas, leavesAtlas, toolsMasterAtlas;
static Animation treeAnim, leaveAnim, toolsMasterAnim;
static SkeletonData treeSkeletonData, leaveSkeletonData, toolsMasterData;
static BitmapFont cgfFont;
public static void load() {
level = new Texture(Gdx.files.internal("map1test.png"));
itemSelector = new Texture(Gdx.files.internal("itemselector.png"));
crop = new Texture(Gdx.files.internal("crop.png"));
// floor = new Texture(Gdx.files.internal("floor.png"));
lake = new Texture(Gdx.files.internal("lake.png"));
// buttons = new Texture(Gdx.files.internal("buttons.png"));
bucket = new Texture(Gdx.files.internal("bucket.png"));
hydration = new Texture(Gdx.files.internal("hydration.png"));
corn = new Texture(Gdx.files.internal("corn.png"));
character = new Texture(Gdx.files.internal("characters.png"));
material = new Texture(Gdx.files.internal("material.png"));
house = new Texture(Gdx.files.internal("hosue.png"));
houseIn = new Texture(Gdx.files.internal("inhouse.png"));
farm = new Texture(Gdx.files.internal("lilfarm2.png"));
craftmenu = new Texture(Gdx.files.internal("craftingMenu.png"));
// depreceated due to texture atlas
// tree = new Texture(Gdx.files.internal("tree.png"));
robot = new Texture(Gdx.files.internal("robot.png"));
robotGUI = new Texture(Gdx.files.internal("robotGui.png"));
ironOre = new Texture(Gdx.files.internal("ironOre.png"));
inventory = new Texture(Gdx.files.internal("inventory.png"));
copperOre = new Texture(Gdx.files.internal("copper.png"));
- grass = new Texture(Gdx.files.internal("testTILE.png"));
+ grass = new Texture(Gdx.files.internal("grass.png"));
dpad = new Texture(Gdx.files.internal("dPad.png"));
dpadLEFT = new Texture(Gdx.files.internal("dpad_left.png"));
dpadRIGHT = new Texture(Gdx.files.internal("dpad_right.png"));
dpadUP = new Texture(Gdx.files.internal("dpad_up.png"));
dpadDOWN = new Texture(Gdx.files.internal("dpad_down.png"));
buttons = new Texture(Gdx.files.internal("buttonsGray.png"));
pointsBar = new Texture(Gdx.files.internal("pointBar.png"));
currentItem = new Texture(Gdx.files.internal("currentItem.png"));
creeper = new Texture(Gdx.files.internal("creeperSprite.png"));
//character animations
downChar_STILL = new TextureRegion(character, 32, 0, 32, 48);
downChar_LEFT = new TextureRegion(character, 0, 0, 32, 48);
downChar_RIGHT = new TextureRegion(character, 64, 0, 32, 48);
leftChar_STILL = new TextureRegion(character, 32, 48, 32, 48);
leftChar_LEFT = new TextureRegion(character, 0, 48, 32, 48);
leftChar_RIGHT = new TextureRegion(character, 64, 48, 32, 48);
rightChar_STILL = new TextureRegion(character, 32, 96, 32, 48);
rightChar_LEFT = new TextureRegion(character, 0, 96, 32, 48);
rightChar_RIGHT = new TextureRegion(character, 64, 96, 32, 48);
upChar_STILL = new TextureRegion(character, 32, 144, 32, 48);
upChar_LEFT = new TextureRegion(character, 0, 144, 32, 48);
upChar_RIGHT = new TextureRegion(character, 64, 144, 32, 48);
//creeper animations
downCreeper_STILL = new TextureRegion(creeper, 32, 0, 32, 48);
downCreeper_LEFT = new TextureRegion(creeper, 0, 0, 32, 48);
downCreeper_RIGHT = new TextureRegion(creeper, 64, 0, 32, 48);
leftCreeper_STILL = new TextureRegion(creeper, 32, 48, 32, 48);
leftCreeper_LEFT = new TextureRegion(creeper, 0, 48, 32, 48);
leftCreeper_RIGHT = new TextureRegion(creeper, 64, 48, 32, 48);
rightCreeper_STILL = new TextureRegion(creeper, 32, 96, 32, 48);
rightCreeper_LEFT = new TextureRegion(creeper, 0, 96, 32, 48);
rightCreeper_RIGHT = new TextureRegion(creeper, 64, 96, 32, 48);
upCreeper_STILL = new TextureRegion(creeper, 32, 144, 32, 48);
upCreeper_LEFT = new TextureRegion(creeper, 0, 144, 32, 48);
upCreeper_RIGHT = new TextureRegion(creeper, 64, 144, 32, 48);
mainChar = downChar_STILL;
treeAtlas = new TextureAtlas(Gdx.files.internal("tree.atlas"));
SkeletonJson treeJson = new SkeletonJson(treeAtlas);
treeSkeletonData = treeJson.readSkeletonData(Gdx.files
.internal("tree.json"));
treeAnim = treeSkeletonData.findAnimation("tree fall");
leavesAtlas = new TextureAtlas(Gdx.files.internal("leaves.atlas"));
SkeletonJson leavesJson = new SkeletonJson(leavesAtlas);
leaveSkeletonData = leavesJson.readSkeletonData(Gdx.files
.internal("leavesSkel.json"));
leaveAnim = leaveSkeletonData.findAnimation("animation");
toolsMasterAtlas = new TextureAtlas(
Gdx.files.internal("toolAtlas.atlas"));
SkeletonJson toolsMasterJson = new SkeletonJson(toolsMasterAtlas);
toolsMasterData = toolsMasterJson.readSkeletonData(Gdx.files
.internal("toolsMaster.json"));
toolsMasterAnim = toolsMasterData.findAnimation("animation");
cgfFont = new BitmapFont(Gdx.files.internal("cgf.fnt"),
Gdx.files.internal("cgf_0.png"), false);
}
}
| true | true | public static void load() {
level = new Texture(Gdx.files.internal("map1test.png"));
itemSelector = new Texture(Gdx.files.internal("itemselector.png"));
crop = new Texture(Gdx.files.internal("crop.png"));
// floor = new Texture(Gdx.files.internal("floor.png"));
lake = new Texture(Gdx.files.internal("lake.png"));
// buttons = new Texture(Gdx.files.internal("buttons.png"));
bucket = new Texture(Gdx.files.internal("bucket.png"));
hydration = new Texture(Gdx.files.internal("hydration.png"));
corn = new Texture(Gdx.files.internal("corn.png"));
character = new Texture(Gdx.files.internal("characters.png"));
material = new Texture(Gdx.files.internal("material.png"));
house = new Texture(Gdx.files.internal("hosue.png"));
houseIn = new Texture(Gdx.files.internal("inhouse.png"));
farm = new Texture(Gdx.files.internal("lilfarm2.png"));
craftmenu = new Texture(Gdx.files.internal("craftingMenu.png"));
// depreceated due to texture atlas
// tree = new Texture(Gdx.files.internal("tree.png"));
robot = new Texture(Gdx.files.internal("robot.png"));
robotGUI = new Texture(Gdx.files.internal("robotGui.png"));
ironOre = new Texture(Gdx.files.internal("ironOre.png"));
inventory = new Texture(Gdx.files.internal("inventory.png"));
copperOre = new Texture(Gdx.files.internal("copper.png"));
grass = new Texture(Gdx.files.internal("testTILE.png"));
dpad = new Texture(Gdx.files.internal("dPad.png"));
dpadLEFT = new Texture(Gdx.files.internal("dpad_left.png"));
dpadRIGHT = new Texture(Gdx.files.internal("dpad_right.png"));
dpadUP = new Texture(Gdx.files.internal("dpad_up.png"));
dpadDOWN = new Texture(Gdx.files.internal("dpad_down.png"));
buttons = new Texture(Gdx.files.internal("buttonsGray.png"));
pointsBar = new Texture(Gdx.files.internal("pointBar.png"));
currentItem = new Texture(Gdx.files.internal("currentItem.png"));
creeper = new Texture(Gdx.files.internal("creeperSprite.png"));
//character animations
downChar_STILL = new TextureRegion(character, 32, 0, 32, 48);
downChar_LEFT = new TextureRegion(character, 0, 0, 32, 48);
downChar_RIGHT = new TextureRegion(character, 64, 0, 32, 48);
leftChar_STILL = new TextureRegion(character, 32, 48, 32, 48);
leftChar_LEFT = new TextureRegion(character, 0, 48, 32, 48);
leftChar_RIGHT = new TextureRegion(character, 64, 48, 32, 48);
rightChar_STILL = new TextureRegion(character, 32, 96, 32, 48);
rightChar_LEFT = new TextureRegion(character, 0, 96, 32, 48);
rightChar_RIGHT = new TextureRegion(character, 64, 96, 32, 48);
upChar_STILL = new TextureRegion(character, 32, 144, 32, 48);
upChar_LEFT = new TextureRegion(character, 0, 144, 32, 48);
upChar_RIGHT = new TextureRegion(character, 64, 144, 32, 48);
//creeper animations
downCreeper_STILL = new TextureRegion(creeper, 32, 0, 32, 48);
downCreeper_LEFT = new TextureRegion(creeper, 0, 0, 32, 48);
downCreeper_RIGHT = new TextureRegion(creeper, 64, 0, 32, 48);
leftCreeper_STILL = new TextureRegion(creeper, 32, 48, 32, 48);
leftCreeper_LEFT = new TextureRegion(creeper, 0, 48, 32, 48);
leftCreeper_RIGHT = new TextureRegion(creeper, 64, 48, 32, 48);
rightCreeper_STILL = new TextureRegion(creeper, 32, 96, 32, 48);
rightCreeper_LEFT = new TextureRegion(creeper, 0, 96, 32, 48);
rightCreeper_RIGHT = new TextureRegion(creeper, 64, 96, 32, 48);
upCreeper_STILL = new TextureRegion(creeper, 32, 144, 32, 48);
upCreeper_LEFT = new TextureRegion(creeper, 0, 144, 32, 48);
upCreeper_RIGHT = new TextureRegion(creeper, 64, 144, 32, 48);
mainChar = downChar_STILL;
treeAtlas = new TextureAtlas(Gdx.files.internal("tree.atlas"));
SkeletonJson treeJson = new SkeletonJson(treeAtlas);
treeSkeletonData = treeJson.readSkeletonData(Gdx.files
.internal("tree.json"));
treeAnim = treeSkeletonData.findAnimation("tree fall");
leavesAtlas = new TextureAtlas(Gdx.files.internal("leaves.atlas"));
SkeletonJson leavesJson = new SkeletonJson(leavesAtlas);
leaveSkeletonData = leavesJson.readSkeletonData(Gdx.files
.internal("leavesSkel.json"));
leaveAnim = leaveSkeletonData.findAnimation("animation");
toolsMasterAtlas = new TextureAtlas(
Gdx.files.internal("toolAtlas.atlas"));
SkeletonJson toolsMasterJson = new SkeletonJson(toolsMasterAtlas);
toolsMasterData = toolsMasterJson.readSkeletonData(Gdx.files
.internal("toolsMaster.json"));
toolsMasterAnim = toolsMasterData.findAnimation("animation");
cgfFont = new BitmapFont(Gdx.files.internal("cgf.fnt"),
Gdx.files.internal("cgf_0.png"), false);
}
| public static void load() {
level = new Texture(Gdx.files.internal("map1test.png"));
itemSelector = new Texture(Gdx.files.internal("itemselector.png"));
crop = new Texture(Gdx.files.internal("crop.png"));
// floor = new Texture(Gdx.files.internal("floor.png"));
lake = new Texture(Gdx.files.internal("lake.png"));
// buttons = new Texture(Gdx.files.internal("buttons.png"));
bucket = new Texture(Gdx.files.internal("bucket.png"));
hydration = new Texture(Gdx.files.internal("hydration.png"));
corn = new Texture(Gdx.files.internal("corn.png"));
character = new Texture(Gdx.files.internal("characters.png"));
material = new Texture(Gdx.files.internal("material.png"));
house = new Texture(Gdx.files.internal("hosue.png"));
houseIn = new Texture(Gdx.files.internal("inhouse.png"));
farm = new Texture(Gdx.files.internal("lilfarm2.png"));
craftmenu = new Texture(Gdx.files.internal("craftingMenu.png"));
// depreceated due to texture atlas
// tree = new Texture(Gdx.files.internal("tree.png"));
robot = new Texture(Gdx.files.internal("robot.png"));
robotGUI = new Texture(Gdx.files.internal("robotGui.png"));
ironOre = new Texture(Gdx.files.internal("ironOre.png"));
inventory = new Texture(Gdx.files.internal("inventory.png"));
copperOre = new Texture(Gdx.files.internal("copper.png"));
grass = new Texture(Gdx.files.internal("grass.png"));
dpad = new Texture(Gdx.files.internal("dPad.png"));
dpadLEFT = new Texture(Gdx.files.internal("dpad_left.png"));
dpadRIGHT = new Texture(Gdx.files.internal("dpad_right.png"));
dpadUP = new Texture(Gdx.files.internal("dpad_up.png"));
dpadDOWN = new Texture(Gdx.files.internal("dpad_down.png"));
buttons = new Texture(Gdx.files.internal("buttonsGray.png"));
pointsBar = new Texture(Gdx.files.internal("pointBar.png"));
currentItem = new Texture(Gdx.files.internal("currentItem.png"));
creeper = new Texture(Gdx.files.internal("creeperSprite.png"));
//character animations
downChar_STILL = new TextureRegion(character, 32, 0, 32, 48);
downChar_LEFT = new TextureRegion(character, 0, 0, 32, 48);
downChar_RIGHT = new TextureRegion(character, 64, 0, 32, 48);
leftChar_STILL = new TextureRegion(character, 32, 48, 32, 48);
leftChar_LEFT = new TextureRegion(character, 0, 48, 32, 48);
leftChar_RIGHT = new TextureRegion(character, 64, 48, 32, 48);
rightChar_STILL = new TextureRegion(character, 32, 96, 32, 48);
rightChar_LEFT = new TextureRegion(character, 0, 96, 32, 48);
rightChar_RIGHT = new TextureRegion(character, 64, 96, 32, 48);
upChar_STILL = new TextureRegion(character, 32, 144, 32, 48);
upChar_LEFT = new TextureRegion(character, 0, 144, 32, 48);
upChar_RIGHT = new TextureRegion(character, 64, 144, 32, 48);
//creeper animations
downCreeper_STILL = new TextureRegion(creeper, 32, 0, 32, 48);
downCreeper_LEFT = new TextureRegion(creeper, 0, 0, 32, 48);
downCreeper_RIGHT = new TextureRegion(creeper, 64, 0, 32, 48);
leftCreeper_STILL = new TextureRegion(creeper, 32, 48, 32, 48);
leftCreeper_LEFT = new TextureRegion(creeper, 0, 48, 32, 48);
leftCreeper_RIGHT = new TextureRegion(creeper, 64, 48, 32, 48);
rightCreeper_STILL = new TextureRegion(creeper, 32, 96, 32, 48);
rightCreeper_LEFT = new TextureRegion(creeper, 0, 96, 32, 48);
rightCreeper_RIGHT = new TextureRegion(creeper, 64, 96, 32, 48);
upCreeper_STILL = new TextureRegion(creeper, 32, 144, 32, 48);
upCreeper_LEFT = new TextureRegion(creeper, 0, 144, 32, 48);
upCreeper_RIGHT = new TextureRegion(creeper, 64, 144, 32, 48);
mainChar = downChar_STILL;
treeAtlas = new TextureAtlas(Gdx.files.internal("tree.atlas"));
SkeletonJson treeJson = new SkeletonJson(treeAtlas);
treeSkeletonData = treeJson.readSkeletonData(Gdx.files
.internal("tree.json"));
treeAnim = treeSkeletonData.findAnimation("tree fall");
leavesAtlas = new TextureAtlas(Gdx.files.internal("leaves.atlas"));
SkeletonJson leavesJson = new SkeletonJson(leavesAtlas);
leaveSkeletonData = leavesJson.readSkeletonData(Gdx.files
.internal("leavesSkel.json"));
leaveAnim = leaveSkeletonData.findAnimation("animation");
toolsMasterAtlas = new TextureAtlas(
Gdx.files.internal("toolAtlas.atlas"));
SkeletonJson toolsMasterJson = new SkeletonJson(toolsMasterAtlas);
toolsMasterData = toolsMasterJson.readSkeletonData(Gdx.files
.internal("toolsMaster.json"));
toolsMasterAnim = toolsMasterData.findAnimation("animation");
cgfFont = new BitmapFont(Gdx.files.internal("cgf.fnt"),
Gdx.files.internal("cgf_0.png"), false);
}
|
diff --git a/bindings/java/src/net/hyperic/sigar/test/TestLoadAverage.java b/bindings/java/src/net/hyperic/sigar/test/TestLoadAverage.java
index ee820d28..5e37b035 100644
--- a/bindings/java/src/net/hyperic/sigar/test/TestLoadAverage.java
+++ b/bindings/java/src/net/hyperic/sigar/test/TestLoadAverage.java
@@ -1,27 +1,27 @@
package net.hyperic.sigar.test;
import net.hyperic.sigar.Sigar;
import net.hyperic.sigar.SigarNotImplementedException;
public class TestLoadAverage extends SigarTestCase {
public TestLoadAverage(String name) {
super(name);
}
public void testCreate() throws Exception {
Sigar sigar = getSigar();
try {
double[] loadavg = sigar.getLoadAverage();
assertTrue(loadavg.length == 3);
traceln("1min=" + loadavg[0]);
traceln("5min=" + loadavg[1]);
traceln("15min=" + loadavg[2]);
- } catch (SigarNotImplementedException e) {
+ } catch (SigarNotImplementedException e) {
//win32
- }
+ }
}
}
| false | true | public void testCreate() throws Exception {
Sigar sigar = getSigar();
try {
double[] loadavg = sigar.getLoadAverage();
assertTrue(loadavg.length == 3);
traceln("1min=" + loadavg[0]);
traceln("5min=" + loadavg[1]);
traceln("15min=" + loadavg[2]);
} catch (SigarNotImplementedException e) {
//win32
}
}
| public void testCreate() throws Exception {
Sigar sigar = getSigar();
try {
double[] loadavg = sigar.getLoadAverage();
assertTrue(loadavg.length == 3);
traceln("1min=" + loadavg[0]);
traceln("5min=" + loadavg[1]);
traceln("15min=" + loadavg[2]);
} catch (SigarNotImplementedException e) {
//win32
}
}
|
diff --git a/SPiDSDK/src/com/schibsted/android/sdk/SPiDConfigurationBuilder.java b/SPiDSDK/src/com/schibsted/android/sdk/SPiDConfigurationBuilder.java
index 4914e23..9330eae 100644
--- a/SPiDSDK/src/com/schibsted/android/sdk/SPiDConfigurationBuilder.java
+++ b/SPiDSDK/src/com/schibsted/android/sdk/SPiDConfigurationBuilder.java
@@ -1,136 +1,136 @@
package com.schibsted.android.sdk;
import android.content.Context;
/**
* Created with IntelliJ IDEA.
* User: mikaellindstrom
* Date: 10/8/12
* Time: 4:33 PM
*/
public class SPiDConfigurationBuilder {
private String clientID;
private String clientSecret;
private String appURLScheme;
private String serverURL;
private String redirectURL;
private String authorizationURL;
private String registrationURL;
private String lostPasswordURL;
private String tokenURL;
private String serverClientID;
private Boolean useMobileWeb = Boolean.TRUE;
private String apiVersion = "2";
private Context context;
public SPiDConfigurationBuilder() {
}
public SPiDConfigurationBuilder clientID(String clientID) {
this.clientID = clientID;
return this;
}
public SPiDConfigurationBuilder clientSecret(String clientSecret) {
this.clientSecret = clientSecret;
return this;
}
public SPiDConfigurationBuilder appURLScheme(String appURLScheme) {
this.appURLScheme = appURLScheme;
return this;
}
public SPiDConfigurationBuilder serverURL(String serverURL) {
this.serverURL = serverURL;
return this;
}
public SPiDConfigurationBuilder redirectURL(String redirectURL) {
this.redirectURL = redirectURL;
return this;
}
public SPiDConfigurationBuilder authorizationURL(String authorizationURL) {
this.authorizationURL = authorizationURL;
return this;
}
public SPiDConfigurationBuilder registrationURL(String registrationURL) {
this.registrationURL = registrationURL;
return this;
}
public SPiDConfigurationBuilder lostPasswordURL(String lostPasswordURL) {
this.lostPasswordURL = lostPasswordURL;
return this;
}
public SPiDConfigurationBuilder tokenURL(String tokenURL) {
this.tokenURL = tokenURL;
return this;
}
public SPiDConfigurationBuilder serverClientID(String serverClientID) {
this.serverClientID = serverClientID;
return this;
}
public SPiDConfigurationBuilder apiVersion(String apiVersion) {
this.apiVersion = apiVersion;
return this;
}
public SPiDConfigurationBuilder context(Context context) {
this.context = context;
return this;
}
public void isEmptyString(String string, String errorMessage) {
if (string == null || string.trim().equals("")) {
throw new IllegalArgumentException(errorMessage);
}
}
public void isNull(Object object, String errorMessage) {
if (object == null) {
throw new IllegalArgumentException(errorMessage);
}
}
public SPiDConfiguration build() {
isEmptyString(clientID, "ClientID is missing");
isEmptyString(clientSecret, "ClientSecret is missing");
isEmptyString(appURLScheme, "AppURLScheme is missing");
isEmptyString(serverURL, "ServerURL is missing");
isNull(context, "Context is missing");
- if (redirectURL == null || !redirectURL.trim().equals("")) {
+ if (redirectURL == null || redirectURL.trim().equals("")) {
redirectURL = appURLScheme + "://";
}
- if (authorizationURL == null || !authorizationURL.trim().equals("")) {
+ if (authorizationURL == null || authorizationURL.trim().equals("")) {
authorizationURL = serverURL + "/auth/login";
}
- if (tokenURL == null || !tokenURL.trim().equals("")) {
+ if (tokenURL == null || tokenURL.trim().equals("")) {
tokenURL = serverURL + "/oauth/token";
}
- if (registrationURL == null || !registrationURL.trim().equals("")) {
+ if (registrationURL == null || registrationURL.trim().equals("")) {
registrationURL = serverURL + "/auth/signup";
}
- if (lostPasswordURL == null || !lostPasswordURL.trim().equals("")) {
+ if (lostPasswordURL == null || lostPasswordURL.trim().equals("")) {
lostPasswordURL = serverURL + "/auth/forgotpassword";
}
- if (serverClientID == null || !serverClientID.trim().equals("")) {
+ if (serverClientID == null || serverClientID.trim().equals("")) {
serverClientID = clientID;
}
return new SPiDConfiguration(clientID, clientSecret, appURLScheme, serverURL, redirectURL, authorizationURL, registrationURL, lostPasswordURL, tokenURL, serverClientID, useMobileWeb, apiVersion, context);
}
}
| false | true | public SPiDConfiguration build() {
isEmptyString(clientID, "ClientID is missing");
isEmptyString(clientSecret, "ClientSecret is missing");
isEmptyString(appURLScheme, "AppURLScheme is missing");
isEmptyString(serverURL, "ServerURL is missing");
isNull(context, "Context is missing");
if (redirectURL == null || !redirectURL.trim().equals("")) {
redirectURL = appURLScheme + "://";
}
if (authorizationURL == null || !authorizationURL.trim().equals("")) {
authorizationURL = serverURL + "/auth/login";
}
if (tokenURL == null || !tokenURL.trim().equals("")) {
tokenURL = serverURL + "/oauth/token";
}
if (registrationURL == null || !registrationURL.trim().equals("")) {
registrationURL = serverURL + "/auth/signup";
}
if (lostPasswordURL == null || !lostPasswordURL.trim().equals("")) {
lostPasswordURL = serverURL + "/auth/forgotpassword";
}
if (serverClientID == null || !serverClientID.trim().equals("")) {
serverClientID = clientID;
}
return new SPiDConfiguration(clientID, clientSecret, appURLScheme, serverURL, redirectURL, authorizationURL, registrationURL, lostPasswordURL, tokenURL, serverClientID, useMobileWeb, apiVersion, context);
}
| public SPiDConfiguration build() {
isEmptyString(clientID, "ClientID is missing");
isEmptyString(clientSecret, "ClientSecret is missing");
isEmptyString(appURLScheme, "AppURLScheme is missing");
isEmptyString(serverURL, "ServerURL is missing");
isNull(context, "Context is missing");
if (redirectURL == null || redirectURL.trim().equals("")) {
redirectURL = appURLScheme + "://";
}
if (authorizationURL == null || authorizationURL.trim().equals("")) {
authorizationURL = serverURL + "/auth/login";
}
if (tokenURL == null || tokenURL.trim().equals("")) {
tokenURL = serverURL + "/oauth/token";
}
if (registrationURL == null || registrationURL.trim().equals("")) {
registrationURL = serverURL + "/auth/signup";
}
if (lostPasswordURL == null || lostPasswordURL.trim().equals("")) {
lostPasswordURL = serverURL + "/auth/forgotpassword";
}
if (serverClientID == null || serverClientID.trim().equals("")) {
serverClientID = clientID;
}
return new SPiDConfiguration(clientID, clientSecret, appURLScheme, serverURL, redirectURL, authorizationURL, registrationURL, lostPasswordURL, tokenURL, serverClientID, useMobileWeb, apiVersion, context);
}
|
diff --git a/mod/jodd-wot/src/jodd/lagarto/adapter/htmlstapler/HtmlStaplerTagAdapter.java b/mod/jodd-wot/src/jodd/lagarto/adapter/htmlstapler/HtmlStaplerTagAdapter.java
index af12d7383..664b90370 100644
--- a/mod/jodd-wot/src/jodd/lagarto/adapter/htmlstapler/HtmlStaplerTagAdapter.java
+++ b/mod/jodd-wot/src/jodd/lagarto/adapter/htmlstapler/HtmlStaplerTagAdapter.java
@@ -1,102 +1,102 @@
// Copyright (c) 2003-2011, Jodd Team (jodd.org). All Rights Reserved.
package jodd.lagarto.adapter.htmlstapler;
import jodd.lagarto.Tag;
import jodd.lagarto.TagAdapter;
import jodd.lagarto.TagVisitor;
import javax.servlet.http.HttpServletRequest;
/**
* HTML Stapler tag adapter parses HTML page and collects all information
* about linking resource files.
*/
public class HtmlStaplerTagAdapter extends TagAdapter {
protected final HtmlStaplerBundlesManager bundlesManager;
protected final BundleAction jsBundleAction;
protected final BundleAction cssBundleAction;
protected boolean insideConditionalComment;
public HtmlStaplerTagAdapter(TagVisitor target, HttpServletRequest request) {
super(target);
bundlesManager = HtmlStaplerBundlesManager.getBundlesManager(request);
jsBundleAction = bundlesManager.start(request, "js");
cssBundleAction = bundlesManager.start(request, "css");
insideConditionalComment = false;
}
// ---------------------------------------------------------------- javascripts
@Override
public void script(Tag tag, CharSequence body) {
if (insideConditionalComment == false) {
String src = tag.getAttributeValue("src", false);
if (src != null) {
String link = jsBundleAction.processLink(src);
if (link != null) {
tag.setAttributeValue("src", false, link);
super.script(tag, body);
}
return;
}
}
super.script(tag, body);
}
// ---------------------------------------------------------------- css
@Override
public void tag(Tag tag) {
if (insideConditionalComment == false) {
if (tag.getName().equalsIgnoreCase("link")) {
String type = tag.getAttributeValue("type", false);
- if (type.equalsIgnoreCase("text/css") == true) {
+ if (type == null || type.equalsIgnoreCase("text/css") == true) {
String media = tag.getAttributeValue("media", false);
if (media == null || media.contains("screen")) {
String href = tag.getAttributeValue("href", false);
String link = cssBundleAction.processLink(href);
if (link != null) {
tag.setAttribute("href", false, link);
super.tag(tag);
}
return;
}
}
}
}
super.tag(tag);
}
// ---------------------------------------------------------------- conditional comments
@Override
public void condCommentStart(CharSequence conditionalComment, boolean isDownlevelHidden) {
insideConditionalComment = true;
super.condCommentStart(conditionalComment, isDownlevelHidden);
}
@Override
public void condCommentEnd(CharSequence conditionalComment, boolean isDownlevelHidden) {
insideConditionalComment = false;
super.condCommentEnd(conditionalComment, isDownlevelHidden);
}
// ---------------------------------------------------------------- end
@Override
public void end() {
jsBundleAction.end();
cssBundleAction.end();
super.end();
}
}
| true | true | public void tag(Tag tag) {
if (insideConditionalComment == false) {
if (tag.getName().equalsIgnoreCase("link")) {
String type = tag.getAttributeValue("type", false);
if (type.equalsIgnoreCase("text/css") == true) {
String media = tag.getAttributeValue("media", false);
if (media == null || media.contains("screen")) {
String href = tag.getAttributeValue("href", false);
String link = cssBundleAction.processLink(href);
if (link != null) {
tag.setAttribute("href", false, link);
super.tag(tag);
}
return;
}
}
}
}
super.tag(tag);
}
| public void tag(Tag tag) {
if (insideConditionalComment == false) {
if (tag.getName().equalsIgnoreCase("link")) {
String type = tag.getAttributeValue("type", false);
if (type == null || type.equalsIgnoreCase("text/css") == true) {
String media = tag.getAttributeValue("media", false);
if (media == null || media.contains("screen")) {
String href = tag.getAttributeValue("href", false);
String link = cssBundleAction.processLink(href);
if (link != null) {
tag.setAttribute("href", false, link);
super.tag(tag);
}
return;
}
}
}
}
super.tag(tag);
}
|
diff --git a/java/src/xpra/Start.java b/java/src/xpra/Start.java
index f5828c8e1..d2067dfa1 100644
--- a/java/src/xpra/Start.java
+++ b/java/src/xpra/Start.java
@@ -1,22 +1,29 @@
package xpra;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public abstract class Start {
public static final String DEFAULT_HOST = "localhost";
public static final int DEFAULT_PORT = 10000;
public void run(String[] args) throws IOException {
- Socket socket = new Socket(DEFAULT_HOST, DEFAULT_PORT);
- socket.setKeepAlive(true);
- InputStream is = socket.getInputStream();
- OutputStream os = socket.getOutputStream();
- this.makeClient(is, os).run(args);
+ Socket socket = null;
+ try {
+ socket = new Socket(DEFAULT_HOST, DEFAULT_PORT);
+ socket.setKeepAlive(true);
+ InputStream is = socket.getInputStream();
+ OutputStream os = socket.getOutputStream();
+ this.makeClient(is, os).run(args);
+ }
+ finally {
+ if (socket!=null)
+ socket.close();
+ }
}
public abstract AbstractClient makeClient(InputStream is, OutputStream os);
}
| true | true | public void run(String[] args) throws IOException {
Socket socket = new Socket(DEFAULT_HOST, DEFAULT_PORT);
socket.setKeepAlive(true);
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
this.makeClient(is, os).run(args);
}
| public void run(String[] args) throws IOException {
Socket socket = null;
try {
socket = new Socket(DEFAULT_HOST, DEFAULT_PORT);
socket.setKeepAlive(true);
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
this.makeClient(is, os).run(args);
}
finally {
if (socket!=null)
socket.close();
}
}
|
diff --git a/src/main/java/org/sonar/plugins/cxx/xunit/CxxXunitSensor.java b/src/main/java/org/sonar/plugins/cxx/xunit/CxxXunitSensor.java
index 3436c112..717ab222 100644
--- a/src/main/java/org/sonar/plugins/cxx/xunit/CxxXunitSensor.java
+++ b/src/main/java/org/sonar/plugins/cxx/xunit/CxxXunitSensor.java
@@ -1,173 +1,173 @@
/*
* Sonar Cxx Plugin, open source software quality management tool.
* Copyright (C) 2010 - 2011, Neticoa SAS France - Tous droits reserves.
* Author(s) : Franck Bonin, Neticoa SAS France.
*
* Sonar Cxx Plugin is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* Sonar Cxx Plugin is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Sonar Cxx Plugin; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugins.cxx.xunit;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.sonar.api.batch.CoverageExtension;
import org.sonar.api.batch.DependsUpon;
import org.sonar.api.batch.SensorContext;
import org.sonar.api.config.Settings;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.Measure;
import org.sonar.api.resources.Project;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.utils.ParsingUtils;
import org.sonar.api.utils.StaxParser;
import org.sonar.plugins.cxx.CxxLanguage;
import org.sonar.plugins.cxx.utils.CxxReportSensor;
import org.sonar.plugins.cxx.utils.CxxUtils;
/**
* {@inheritDoc}
*/
public class CxxXunitSensor extends CxxReportSensor {
public static final String REPORT_PATH_KEY = "sonar.cxx.xunit.reportPath";
public static final String XSLT_URL_KEY = "sonar.cxx.xunit.xsltURL";
private static final String DEFAULT_REPORT_PATH = "xunit-reports/xunit-result-*.xml";
private String xsltURL = null;
private CxxLanguage lang = null;
/**
* {@inheritDoc}
*/
public CxxXunitSensor(Settings conf, CxxLanguage cxxLang) {
super(conf);
this.lang = cxxLang;
xsltURL = conf.getString(XSLT_URL_KEY);
}
/**
* {@inheritDoc}
*/
@DependsUpon
public Class<?> dependsUponCoverageSensors() {
return CoverageExtension.class;
}
@Override
protected String reportPathKey() {
return REPORT_PATH_KEY;
}
@Override
protected String defaultReportPath() {
return DEFAULT_REPORT_PATH;
}
@Override
protected void processReport(final Project project, final SensorContext context, File report)
throws
java.io.IOException,
javax.xml.transform.TransformerException,
javax.xml.stream.XMLStreamException
{
parseReport(project, context, transformReport(report));
}
@Override
protected void handleNoReportsCase(SensorContext context) {
context.saveMeasure(CoreMetrics.TESTS, 0.0);
}
File transformReport(File report)
throws java.io.IOException, javax.xml.transform.TransformerException
{
File transformed = report;
if (xsltURL != null) {
CxxUtils.LOG.debug("Transforming the report using xslt '{}'", xsltURL);
InputStream inputStream = this.getClass().getResourceAsStream("/xsl/" + xsltURL);
if (inputStream == null) {
URL url = new URL(xsltURL);
inputStream = url.openStream();
}
Source xsl = new StreamSource(inputStream);
TransformerFactory factory = TransformerFactory.newInstance();
Templates template = factory.newTemplates(xsl);
Transformer xformer = template.newTransformer();
xformer.setOutputProperty(OutputKeys.INDENT, "yes");
Source source = new StreamSource(report);
transformed = new File(report.getAbsolutePath() + ".after_xslt");
Result result = new StreamResult(transformed);
xformer.transform(source, result);
} else {
CxxUtils.LOG.debug("Transformation skipped: no xslt given");
}
return transformed;
}
private void parseReport(Project project, SensorContext context, File report)
throws javax.xml.stream.XMLStreamException
{
CxxUtils.LOG.info("Parsing report '{}'", report);
TestSuiteParser parserHandler = new TestSuiteParser();
StaxParser parser = new StaxParser(parserHandler, false);
parser.parse(report);
for (TestSuite fileReport : parserHandler.getParsedReports()) {
String fileKey = fileReport.getKey();
org.sonar.api.resources.File unitTest =
- org.sonar.api.resources.File.fromIOFile(new File(fileKey), project);
+ org.sonar.api.resources.File.fromIOFile(new File(fileKey), project.getFileSystem().getTestDirs());
if (unitTest == null) {
unitTest = createVirtualFile(context, fileKey);
}
CxxUtils.LOG.debug("Saving test execution measures for file '{}' under resource '{}'",
fileKey, unitTest);
double testsCount = fileReport.getTests() - fileReport.getSkipped();
context.saveMeasure(unitTest, CoreMetrics.SKIPPED_TESTS, (double)fileReport.getSkipped());
context.saveMeasure(unitTest, CoreMetrics.TESTS, testsCount);
context.saveMeasure(unitTest, CoreMetrics.TEST_ERRORS, (double)fileReport.getErrors());
context.saveMeasure(unitTest, CoreMetrics.TEST_FAILURES, (double)fileReport.getFailures());
context.saveMeasure(unitTest, CoreMetrics.TEST_EXECUTION_TIME, (double)fileReport.getTime());
double passedTests = testsCount - fileReport.getErrors() - fileReport.getFailures();
if (testsCount > 0) {
double percentage = passedTests * 100d / testsCount;
context.saveMeasure(unitTest, CoreMetrics.TEST_SUCCESS_DENSITY, ParsingUtils.scaleValue(percentage));
}
context.saveMeasure(unitTest, new Measure(CoreMetrics.TEST_DATA, fileReport.getDetails()));
}
}
private org.sonar.api.resources.File createVirtualFile(SensorContext context,
String filename) {
org.sonar.api.resources.File virtualFile =
new org.sonar.api.resources.File(this.lang, filename);
virtualFile.setQualifier(Qualifiers.UNIT_TEST_FILE);
context.saveSource(virtualFile, "<source code could not be found>");
return virtualFile;
}
}
| true | true | private void parseReport(Project project, SensorContext context, File report)
throws javax.xml.stream.XMLStreamException
{
CxxUtils.LOG.info("Parsing report '{}'", report);
TestSuiteParser parserHandler = new TestSuiteParser();
StaxParser parser = new StaxParser(parserHandler, false);
parser.parse(report);
for (TestSuite fileReport : parserHandler.getParsedReports()) {
String fileKey = fileReport.getKey();
org.sonar.api.resources.File unitTest =
org.sonar.api.resources.File.fromIOFile(new File(fileKey), project);
if (unitTest == null) {
unitTest = createVirtualFile(context, fileKey);
}
CxxUtils.LOG.debug("Saving test execution measures for file '{}' under resource '{}'",
fileKey, unitTest);
double testsCount = fileReport.getTests() - fileReport.getSkipped();
context.saveMeasure(unitTest, CoreMetrics.SKIPPED_TESTS, (double)fileReport.getSkipped());
context.saveMeasure(unitTest, CoreMetrics.TESTS, testsCount);
context.saveMeasure(unitTest, CoreMetrics.TEST_ERRORS, (double)fileReport.getErrors());
context.saveMeasure(unitTest, CoreMetrics.TEST_FAILURES, (double)fileReport.getFailures());
context.saveMeasure(unitTest, CoreMetrics.TEST_EXECUTION_TIME, (double)fileReport.getTime());
double passedTests = testsCount - fileReport.getErrors() - fileReport.getFailures();
if (testsCount > 0) {
double percentage = passedTests * 100d / testsCount;
context.saveMeasure(unitTest, CoreMetrics.TEST_SUCCESS_DENSITY, ParsingUtils.scaleValue(percentage));
}
context.saveMeasure(unitTest, new Measure(CoreMetrics.TEST_DATA, fileReport.getDetails()));
}
}
| private void parseReport(Project project, SensorContext context, File report)
throws javax.xml.stream.XMLStreamException
{
CxxUtils.LOG.info("Parsing report '{}'", report);
TestSuiteParser parserHandler = new TestSuiteParser();
StaxParser parser = new StaxParser(parserHandler, false);
parser.parse(report);
for (TestSuite fileReport : parserHandler.getParsedReports()) {
String fileKey = fileReport.getKey();
org.sonar.api.resources.File unitTest =
org.sonar.api.resources.File.fromIOFile(new File(fileKey), project.getFileSystem().getTestDirs());
if (unitTest == null) {
unitTest = createVirtualFile(context, fileKey);
}
CxxUtils.LOG.debug("Saving test execution measures for file '{}' under resource '{}'",
fileKey, unitTest);
double testsCount = fileReport.getTests() - fileReport.getSkipped();
context.saveMeasure(unitTest, CoreMetrics.SKIPPED_TESTS, (double)fileReport.getSkipped());
context.saveMeasure(unitTest, CoreMetrics.TESTS, testsCount);
context.saveMeasure(unitTest, CoreMetrics.TEST_ERRORS, (double)fileReport.getErrors());
context.saveMeasure(unitTest, CoreMetrics.TEST_FAILURES, (double)fileReport.getFailures());
context.saveMeasure(unitTest, CoreMetrics.TEST_EXECUTION_TIME, (double)fileReport.getTime());
double passedTests = testsCount - fileReport.getErrors() - fileReport.getFailures();
if (testsCount > 0) {
double percentage = passedTests * 100d / testsCount;
context.saveMeasure(unitTest, CoreMetrics.TEST_SUCCESS_DENSITY, ParsingUtils.scaleValue(percentage));
}
context.saveMeasure(unitTest, new Measure(CoreMetrics.TEST_DATA, fileReport.getDetails()));
}
}
|
diff --git a/src/org/opensolaris/opengrok/analysis/TextAnalyzer.java b/src/org/opensolaris/opengrok/analysis/TextAnalyzer.java
index 63fe7af1..a946cf3d 100644
--- a/src/org/opensolaris/opengrok/analysis/TextAnalyzer.java
+++ b/src/org/opensolaris/opengrok/analysis/TextAnalyzer.java
@@ -1,64 +1,64 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* See LICENSE.txt included in this distribution for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
package org.opensolaris.opengrok.analysis;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import org.apache.lucene.document.Document;
public abstract class TextAnalyzer extends FileAnalyzer {
public TextAnalyzer(FileAnalyzerFactory factory) {
super(factory);
}
public final void analyze(Document doc, InputStream in) throws IOException {
String charset = null;
in.mark(3);
byte[] head = new byte[3];
int br = in.read(head, 0, 3);
if (br >= 2 &&
(head[0] == (byte)0xFE && head[1] == (byte)0xFF) ||
(head[0] == (byte)0xFF && head[1] == (byte)0xFE)) {
charset = "UTF-16";
in.reset();
- } else if (br >= 3 & head[0] == (byte)0xEF && head[1] == (byte)0xBB &&
+ } else if (br >= 3 && head[0] == (byte)0xEF && head[1] == (byte)0xBB &&
head[2] == (byte)0xBF) {
// InputStreamReader does not properly discard BOM on UTF8 streams,
// so don't reset the stream.
charset = "UTF-8";
}
if (charset == null) {
in.reset();
charset = Charset.defaultCharset().name();
}
analyze(doc, new InputStreamReader(in, charset));
}
protected abstract void analyze(Document doc, Reader reader) throws IOException;
}
| true | true | public final void analyze(Document doc, InputStream in) throws IOException {
String charset = null;
in.mark(3);
byte[] head = new byte[3];
int br = in.read(head, 0, 3);
if (br >= 2 &&
(head[0] == (byte)0xFE && head[1] == (byte)0xFF) ||
(head[0] == (byte)0xFF && head[1] == (byte)0xFE)) {
charset = "UTF-16";
in.reset();
} else if (br >= 3 & head[0] == (byte)0xEF && head[1] == (byte)0xBB &&
head[2] == (byte)0xBF) {
// InputStreamReader does not properly discard BOM on UTF8 streams,
// so don't reset the stream.
charset = "UTF-8";
}
if (charset == null) {
in.reset();
charset = Charset.defaultCharset().name();
}
analyze(doc, new InputStreamReader(in, charset));
}
| public final void analyze(Document doc, InputStream in) throws IOException {
String charset = null;
in.mark(3);
byte[] head = new byte[3];
int br = in.read(head, 0, 3);
if (br >= 2 &&
(head[0] == (byte)0xFE && head[1] == (byte)0xFF) ||
(head[0] == (byte)0xFF && head[1] == (byte)0xFE)) {
charset = "UTF-16";
in.reset();
} else if (br >= 3 && head[0] == (byte)0xEF && head[1] == (byte)0xBB &&
head[2] == (byte)0xBF) {
// InputStreamReader does not properly discard BOM on UTF8 streams,
// so don't reset the stream.
charset = "UTF-8";
}
if (charset == null) {
in.reset();
charset = Charset.defaultCharset().name();
}
analyze(doc, new InputStreamReader(in, charset));
}
|
diff --git a/src/Tests/functionalTests/component/binding/local/collective/Test.java b/src/Tests/functionalTests/component/binding/local/collective/Test.java
index a732d11b5..843799746 100644
--- a/src/Tests/functionalTests/component/binding/local/collective/Test.java
+++ b/src/Tests/functionalTests/component/binding/local/collective/Test.java
@@ -1,236 +1,236 @@
/*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2007 INRIA/University of Nice-Sophia Antipolis
* Contact: [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* Initial developer(s): The ProActive Team
* http://www.inria.fr/oasis/ProActive/contacts.html
* Contributor(s):
*
* ################################################################
*/
package functionalTests.component.binding.local.collective;
import java.util.Arrays;
import org.junit.Assert;
import org.objectweb.fractal.api.Component;
import org.objectweb.fractal.api.factory.GenericFactory;
import org.objectweb.fractal.api.type.ComponentType;
import org.objectweb.fractal.api.type.InterfaceType;
import org.objectweb.fractal.api.type.TypeFactory;
import org.objectweb.fractal.util.Fractal;
import org.objectweb.proactive.ProActive;
import org.objectweb.proactive.core.component.Constants;
import org.objectweb.proactive.core.component.ContentDescription;
import org.objectweb.proactive.core.component.ControllerDescription;
import org.objectweb.proactive.core.component.type.Composite;
import org.objectweb.proactive.core.group.ProActiveGroup;
import functionalTests.ComponentTest;
import functionalTests.component.I1;
import functionalTests.component.I2;
import functionalTests.component.Message;
import functionalTests.component.PrimitiveComponentB;
import functionalTests.component.PrimitiveComponentD;
import functionalTests.component.PrimitiveComponentE;
/**
* @author Matthieu Morel
*
* a test for bindings on client collective interfaces between remote components
*/
public class Test extends ComponentTest {
/**
*
*/
private static final long serialVersionUID = 8307154807769118654L;
public static String MESSAGE = "-->Main";
Component pD1;
Component pB1;
Component pB2;
Message message;
public Test() {
super("Communication between local primitive components through client collection interface",
"Communication between local primitive components through client collection interface ");
}
/**
* @see testsuite.test.FunctionalTest#action()
*/
@org.junit.Test
public void action() throws Exception {
Component boot = Fractal.getBootstrapComponent();
TypeFactory type_factory = Fractal.getTypeFactory(boot);
GenericFactory cf = Fractal.getGenericFactory(boot);
ComponentType D_Type = type_factory.createFcType(new InterfaceType[] {
type_factory.createFcItfType("i1", I1.class.getName(),
TypeFactory.SERVER, TypeFactory.MANDATORY,
TypeFactory.SINGLE),
type_factory.createFcItfType("i2", I2.class.getName(),
TypeFactory.CLIENT, TypeFactory.MANDATORY,
TypeFactory.COLLECTION)
});
ComponentType B_Type = type_factory.createFcType(new InterfaceType[] {
type_factory.createFcItfType("i2", I2.class.getName(),
TypeFactory.SERVER, TypeFactory.MANDATORY,
TypeFactory.SINGLE)
});
ComponentType eType = type_factory.createFcType(new InterfaceType[] {
type_factory.createFcItfType("i1", I1.class.getName(),
TypeFactory.SERVER, TypeFactory.MANDATORY,
TypeFactory.SINGLE),
type_factory.createFcItfType("i2", I2.class.getName(),
TypeFactory.CLIENT, TypeFactory.MANDATORY,
TypeFactory.COLLECTION)
});
ComponentType fType = type_factory.createFcType(new InterfaceType[] {
type_factory.createFcItfType("i2-server",
I2.class.getName(), TypeFactory.SERVER,
TypeFactory.MANDATORY, TypeFactory.COLLECTION),
type_factory.createFcItfType("i2-client",
I2.class.getName(), TypeFactory.CLIENT,
TypeFactory.MANDATORY, TypeFactory.COLLECTION)
});
// instantiate the components
pD1 = cf.newFcInstance(D_Type,
new ControllerDescription("pD1", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentD.class.getName(),
new Object[] { }));
pB1 = cf.newFcInstance(B_Type,
new ControllerDescription("pB1", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentB.class.getName(),
new Object[] { }));
pB2 = cf.newFcInstance(B_Type,
new ControllerDescription("pB2", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentB.class.getName(),
new Object[] { }));
// check that listFc() does not return the name of the collective interface :
// it should return no client interface
Assert.assertTrue(Fractal.getBindingController(pD1).listFc().length == 0);
// bind the components
Fractal.getBindingController(pD1)
.bindFc("i2_01", pB1.getFcInterface("i2"));
Fractal.getBindingController(pD1)
.bindFc("i2_02", pB2.getFcInterface("i2"));
// check that listFc() does not return the name of the collective interface
String[] listFc = Fractal.getBindingController(pD1).listFc();
String listItf = "[";
for (String string : listFc) {
listItf += (string + ", ");
}
listItf += "]";
- System.err.println("listItf" + listItf);
+ Arrays.sort(listFc);
Assert.assertTrue("Wrong interface list: " + listItf,
Arrays.equals(listFc, new String[] { "i2_01", "i2_02" }));
// start them
Fractal.getLifeCycleController(pD1).startFc();
Fractal.getLifeCycleController(pB1).startFc();
Fractal.getLifeCycleController(pB2).startFc();
message = null;
I1 i1 = (I1) pD1.getFcInterface("i1");
Message msg1 = i1.processInputMessage(new Message(MESSAGE));
message = msg1.append(MESSAGE);
// test collection itf with composite component
Component c1 = cf.newFcInstance(fType,
new ControllerDescription("composite1", Constants.COMPOSITE),
new ContentDescription(Composite.class.getName(),
new Object[] { }));
Component pB3 = cf.newFcInstance(B_Type,
new ControllerDescription("pB3", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentB.class.getName(),
new Object[] { }));
Component pB4 = cf.newFcInstance(B_Type,
new ControllerDescription("pB4", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentB.class.getName(),
new Object[] { }));
Component pB5 = cf.newFcInstance(B_Type,
new ControllerDescription("pB5", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentB.class.getName(),
new Object[] { }));
Component pB6 = cf.newFcInstance(B_Type,
new ControllerDescription("pB6", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentB.class.getName(),
new Object[] { }));
Component pE = cf.newFcInstance(eType,
new ControllerDescription("pE", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentE.class.getName(),
new Object[] { }));
Fractal.getContentController(c1).addFcSubComponent(pB3);
Fractal.getContentController(c1).addFcSubComponent(pB4);
Fractal.getContentController(c1).addFcSubComponent(pE);
Fractal.getBindingController(c1)
.bindFc("i2-server-01", pB3.getFcInterface("i2"));
Fractal.getBindingController(c1)
.bindFc("i2-server-02", pB4.getFcInterface("i2"));
Fractal.getBindingController(pE)
.bindFc("i2-01", c1.getFcInterface("i2-client-01"));
Fractal.getBindingController(pE)
.bindFc("i2-02", c1.getFcInterface("i2-client-02"));
Fractal.getBindingController(c1)
.bindFc("i2-client-01", pB5.getFcInterface("i2"));
Fractal.getBindingController(c1)
.bindFc("i2-client-02", pB6.getFcInterface("i2"));
Fractal.getLifeCycleController(c1).startFc();
Fractal.getLifeCycleController(pB5).startFc();
Fractal.getLifeCycleController(pB6).startFc();
((I1) pE.getFcInterface("i1")).processInputMessage(new Message(""));
Message expected = new Message("composite-" +
PrimitiveComponentB.MESSAGE);
Message m1 = ((I2) c1.getFcInterface("i2-server-01")).processOutputMessage(new Message(
"composite-"));
Message m2 = ((I2) c1.getFcInterface("i2-server-02")).processOutputMessage(new Message(
"composite-"));
Assert.assertEquals(new Message("composite-" +
PrimitiveComponentB.MESSAGE).toString(),
ProActive.getFutureValue(m1).toString());
Assert.assertEquals(new Message("composite-" +
PrimitiveComponentB.MESSAGE).toString(),
ProActive.getFutureValue(m2).toString());
StringBuffer resulting_msg = new StringBuffer();
int message_size = ProActiveGroup.size(message);
for (int i = 0; i < message_size; i++) {
resulting_msg.append(((Message) ProActiveGroup.get(message, i)).toString());
}
// this --> primitiveA --> primitiveB --> primitiveA --> this (message goes through composite components)
String single_message = Test.MESSAGE + PrimitiveComponentD.MESSAGE +
PrimitiveComponentB.MESSAGE + PrimitiveComponentD.MESSAGE +
Test.MESSAGE;
Assert.assertEquals(resulting_msg.toString(),
single_message + single_message);
}
}
| true | true | public void action() throws Exception {
Component boot = Fractal.getBootstrapComponent();
TypeFactory type_factory = Fractal.getTypeFactory(boot);
GenericFactory cf = Fractal.getGenericFactory(boot);
ComponentType D_Type = type_factory.createFcType(new InterfaceType[] {
type_factory.createFcItfType("i1", I1.class.getName(),
TypeFactory.SERVER, TypeFactory.MANDATORY,
TypeFactory.SINGLE),
type_factory.createFcItfType("i2", I2.class.getName(),
TypeFactory.CLIENT, TypeFactory.MANDATORY,
TypeFactory.COLLECTION)
});
ComponentType B_Type = type_factory.createFcType(new InterfaceType[] {
type_factory.createFcItfType("i2", I2.class.getName(),
TypeFactory.SERVER, TypeFactory.MANDATORY,
TypeFactory.SINGLE)
});
ComponentType eType = type_factory.createFcType(new InterfaceType[] {
type_factory.createFcItfType("i1", I1.class.getName(),
TypeFactory.SERVER, TypeFactory.MANDATORY,
TypeFactory.SINGLE),
type_factory.createFcItfType("i2", I2.class.getName(),
TypeFactory.CLIENT, TypeFactory.MANDATORY,
TypeFactory.COLLECTION)
});
ComponentType fType = type_factory.createFcType(new InterfaceType[] {
type_factory.createFcItfType("i2-server",
I2.class.getName(), TypeFactory.SERVER,
TypeFactory.MANDATORY, TypeFactory.COLLECTION),
type_factory.createFcItfType("i2-client",
I2.class.getName(), TypeFactory.CLIENT,
TypeFactory.MANDATORY, TypeFactory.COLLECTION)
});
// instantiate the components
pD1 = cf.newFcInstance(D_Type,
new ControllerDescription("pD1", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentD.class.getName(),
new Object[] { }));
pB1 = cf.newFcInstance(B_Type,
new ControllerDescription("pB1", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentB.class.getName(),
new Object[] { }));
pB2 = cf.newFcInstance(B_Type,
new ControllerDescription("pB2", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentB.class.getName(),
new Object[] { }));
// check that listFc() does not return the name of the collective interface :
// it should return no client interface
Assert.assertTrue(Fractal.getBindingController(pD1).listFc().length == 0);
// bind the components
Fractal.getBindingController(pD1)
.bindFc("i2_01", pB1.getFcInterface("i2"));
Fractal.getBindingController(pD1)
.bindFc("i2_02", pB2.getFcInterface("i2"));
// check that listFc() does not return the name of the collective interface
String[] listFc = Fractal.getBindingController(pD1).listFc();
String listItf = "[";
for (String string : listFc) {
listItf += (string + ", ");
}
listItf += "]";
System.err.println("listItf" + listItf);
Assert.assertTrue("Wrong interface list: " + listItf,
Arrays.equals(listFc, new String[] { "i2_01", "i2_02" }));
// start them
Fractal.getLifeCycleController(pD1).startFc();
Fractal.getLifeCycleController(pB1).startFc();
Fractal.getLifeCycleController(pB2).startFc();
message = null;
I1 i1 = (I1) pD1.getFcInterface("i1");
Message msg1 = i1.processInputMessage(new Message(MESSAGE));
message = msg1.append(MESSAGE);
// test collection itf with composite component
Component c1 = cf.newFcInstance(fType,
new ControllerDescription("composite1", Constants.COMPOSITE),
new ContentDescription(Composite.class.getName(),
new Object[] { }));
Component pB3 = cf.newFcInstance(B_Type,
new ControllerDescription("pB3", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentB.class.getName(),
new Object[] { }));
Component pB4 = cf.newFcInstance(B_Type,
new ControllerDescription("pB4", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentB.class.getName(),
new Object[] { }));
Component pB5 = cf.newFcInstance(B_Type,
new ControllerDescription("pB5", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentB.class.getName(),
new Object[] { }));
Component pB6 = cf.newFcInstance(B_Type,
new ControllerDescription("pB6", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentB.class.getName(),
new Object[] { }));
Component pE = cf.newFcInstance(eType,
new ControllerDescription("pE", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentE.class.getName(),
new Object[] { }));
Fractal.getContentController(c1).addFcSubComponent(pB3);
Fractal.getContentController(c1).addFcSubComponent(pB4);
Fractal.getContentController(c1).addFcSubComponent(pE);
Fractal.getBindingController(c1)
.bindFc("i2-server-01", pB3.getFcInterface("i2"));
Fractal.getBindingController(c1)
.bindFc("i2-server-02", pB4.getFcInterface("i2"));
Fractal.getBindingController(pE)
.bindFc("i2-01", c1.getFcInterface("i2-client-01"));
Fractal.getBindingController(pE)
.bindFc("i2-02", c1.getFcInterface("i2-client-02"));
Fractal.getBindingController(c1)
.bindFc("i2-client-01", pB5.getFcInterface("i2"));
Fractal.getBindingController(c1)
.bindFc("i2-client-02", pB6.getFcInterface("i2"));
Fractal.getLifeCycleController(c1).startFc();
Fractal.getLifeCycleController(pB5).startFc();
Fractal.getLifeCycleController(pB6).startFc();
((I1) pE.getFcInterface("i1")).processInputMessage(new Message(""));
Message expected = new Message("composite-" +
PrimitiveComponentB.MESSAGE);
Message m1 = ((I2) c1.getFcInterface("i2-server-01")).processOutputMessage(new Message(
"composite-"));
Message m2 = ((I2) c1.getFcInterface("i2-server-02")).processOutputMessage(new Message(
"composite-"));
Assert.assertEquals(new Message("composite-" +
PrimitiveComponentB.MESSAGE).toString(),
ProActive.getFutureValue(m1).toString());
Assert.assertEquals(new Message("composite-" +
PrimitiveComponentB.MESSAGE).toString(),
ProActive.getFutureValue(m2).toString());
StringBuffer resulting_msg = new StringBuffer();
int message_size = ProActiveGroup.size(message);
for (int i = 0; i < message_size; i++) {
resulting_msg.append(((Message) ProActiveGroup.get(message, i)).toString());
}
// this --> primitiveA --> primitiveB --> primitiveA --> this (message goes through composite components)
String single_message = Test.MESSAGE + PrimitiveComponentD.MESSAGE +
PrimitiveComponentB.MESSAGE + PrimitiveComponentD.MESSAGE +
Test.MESSAGE;
Assert.assertEquals(resulting_msg.toString(),
single_message + single_message);
}
| public void action() throws Exception {
Component boot = Fractal.getBootstrapComponent();
TypeFactory type_factory = Fractal.getTypeFactory(boot);
GenericFactory cf = Fractal.getGenericFactory(boot);
ComponentType D_Type = type_factory.createFcType(new InterfaceType[] {
type_factory.createFcItfType("i1", I1.class.getName(),
TypeFactory.SERVER, TypeFactory.MANDATORY,
TypeFactory.SINGLE),
type_factory.createFcItfType("i2", I2.class.getName(),
TypeFactory.CLIENT, TypeFactory.MANDATORY,
TypeFactory.COLLECTION)
});
ComponentType B_Type = type_factory.createFcType(new InterfaceType[] {
type_factory.createFcItfType("i2", I2.class.getName(),
TypeFactory.SERVER, TypeFactory.MANDATORY,
TypeFactory.SINGLE)
});
ComponentType eType = type_factory.createFcType(new InterfaceType[] {
type_factory.createFcItfType("i1", I1.class.getName(),
TypeFactory.SERVER, TypeFactory.MANDATORY,
TypeFactory.SINGLE),
type_factory.createFcItfType("i2", I2.class.getName(),
TypeFactory.CLIENT, TypeFactory.MANDATORY,
TypeFactory.COLLECTION)
});
ComponentType fType = type_factory.createFcType(new InterfaceType[] {
type_factory.createFcItfType("i2-server",
I2.class.getName(), TypeFactory.SERVER,
TypeFactory.MANDATORY, TypeFactory.COLLECTION),
type_factory.createFcItfType("i2-client",
I2.class.getName(), TypeFactory.CLIENT,
TypeFactory.MANDATORY, TypeFactory.COLLECTION)
});
// instantiate the components
pD1 = cf.newFcInstance(D_Type,
new ControllerDescription("pD1", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentD.class.getName(),
new Object[] { }));
pB1 = cf.newFcInstance(B_Type,
new ControllerDescription("pB1", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentB.class.getName(),
new Object[] { }));
pB2 = cf.newFcInstance(B_Type,
new ControllerDescription("pB2", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentB.class.getName(),
new Object[] { }));
// check that listFc() does not return the name of the collective interface :
// it should return no client interface
Assert.assertTrue(Fractal.getBindingController(pD1).listFc().length == 0);
// bind the components
Fractal.getBindingController(pD1)
.bindFc("i2_01", pB1.getFcInterface("i2"));
Fractal.getBindingController(pD1)
.bindFc("i2_02", pB2.getFcInterface("i2"));
// check that listFc() does not return the name of the collective interface
String[] listFc = Fractal.getBindingController(pD1).listFc();
String listItf = "[";
for (String string : listFc) {
listItf += (string + ", ");
}
listItf += "]";
Arrays.sort(listFc);
Assert.assertTrue("Wrong interface list: " + listItf,
Arrays.equals(listFc, new String[] { "i2_01", "i2_02" }));
// start them
Fractal.getLifeCycleController(pD1).startFc();
Fractal.getLifeCycleController(pB1).startFc();
Fractal.getLifeCycleController(pB2).startFc();
message = null;
I1 i1 = (I1) pD1.getFcInterface("i1");
Message msg1 = i1.processInputMessage(new Message(MESSAGE));
message = msg1.append(MESSAGE);
// test collection itf with composite component
Component c1 = cf.newFcInstance(fType,
new ControllerDescription("composite1", Constants.COMPOSITE),
new ContentDescription(Composite.class.getName(),
new Object[] { }));
Component pB3 = cf.newFcInstance(B_Type,
new ControllerDescription("pB3", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentB.class.getName(),
new Object[] { }));
Component pB4 = cf.newFcInstance(B_Type,
new ControllerDescription("pB4", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentB.class.getName(),
new Object[] { }));
Component pB5 = cf.newFcInstance(B_Type,
new ControllerDescription("pB5", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentB.class.getName(),
new Object[] { }));
Component pB6 = cf.newFcInstance(B_Type,
new ControllerDescription("pB6", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentB.class.getName(),
new Object[] { }));
Component pE = cf.newFcInstance(eType,
new ControllerDescription("pE", Constants.PRIMITIVE),
new ContentDescription(PrimitiveComponentE.class.getName(),
new Object[] { }));
Fractal.getContentController(c1).addFcSubComponent(pB3);
Fractal.getContentController(c1).addFcSubComponent(pB4);
Fractal.getContentController(c1).addFcSubComponent(pE);
Fractal.getBindingController(c1)
.bindFc("i2-server-01", pB3.getFcInterface("i2"));
Fractal.getBindingController(c1)
.bindFc("i2-server-02", pB4.getFcInterface("i2"));
Fractal.getBindingController(pE)
.bindFc("i2-01", c1.getFcInterface("i2-client-01"));
Fractal.getBindingController(pE)
.bindFc("i2-02", c1.getFcInterface("i2-client-02"));
Fractal.getBindingController(c1)
.bindFc("i2-client-01", pB5.getFcInterface("i2"));
Fractal.getBindingController(c1)
.bindFc("i2-client-02", pB6.getFcInterface("i2"));
Fractal.getLifeCycleController(c1).startFc();
Fractal.getLifeCycleController(pB5).startFc();
Fractal.getLifeCycleController(pB6).startFc();
((I1) pE.getFcInterface("i1")).processInputMessage(new Message(""));
Message expected = new Message("composite-" +
PrimitiveComponentB.MESSAGE);
Message m1 = ((I2) c1.getFcInterface("i2-server-01")).processOutputMessage(new Message(
"composite-"));
Message m2 = ((I2) c1.getFcInterface("i2-server-02")).processOutputMessage(new Message(
"composite-"));
Assert.assertEquals(new Message("composite-" +
PrimitiveComponentB.MESSAGE).toString(),
ProActive.getFutureValue(m1).toString());
Assert.assertEquals(new Message("composite-" +
PrimitiveComponentB.MESSAGE).toString(),
ProActive.getFutureValue(m2).toString());
StringBuffer resulting_msg = new StringBuffer();
int message_size = ProActiveGroup.size(message);
for (int i = 0; i < message_size; i++) {
resulting_msg.append(((Message) ProActiveGroup.get(message, i)).toString());
}
// this --> primitiveA --> primitiveB --> primitiveA --> this (message goes through composite components)
String single_message = Test.MESSAGE + PrimitiveComponentD.MESSAGE +
PrimitiveComponentB.MESSAGE + PrimitiveComponentD.MESSAGE +
Test.MESSAGE;
Assert.assertEquals(resulting_msg.toString(),
single_message + single_message);
}
|
diff --git a/src/main/java/com/xebialabs/overthere/ssh/LaxKeyVerifier.java b/src/main/java/com/xebialabs/overthere/ssh/LaxKeyVerifier.java
index e9854aa..6083963 100644
--- a/src/main/java/com/xebialabs/overthere/ssh/LaxKeyVerifier.java
+++ b/src/main/java/com/xebialabs/overthere/ssh/LaxKeyVerifier.java
@@ -1,20 +1,20 @@
package com.xebialabs.overthere.ssh;
import net.schmizz.sshj.transport.verification.HostKeyVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.PublicKey;
/**
* Always trusts the host,
*/
class LaxKeyVerifier implements HostKeyVerifier {
@Override
public boolean verify(String hostname, int port, PublicKey key) {
- logger.debug("Trusting host %s:%d", hostname, port);
+ logger.debug("Trusting host {}:{}", hostname, port);
return true;
}
private static final Logger logger = LoggerFactory.getLogger(LaxKeyVerifier.class);
}
| true | true | public boolean verify(String hostname, int port, PublicKey key) {
logger.debug("Trusting host %s:%d", hostname, port);
return true;
}
| public boolean verify(String hostname, int port, PublicKey key) {
logger.debug("Trusting host {}:{}", hostname, port);
return true;
}
|
diff --git a/src/org/proofpad/Acl2Parser.java b/src/org/proofpad/Acl2Parser.java
index 1f2250f..75f7443 100755
--- a/src/org/proofpad/Acl2Parser.java
+++ b/src/org/proofpad/Acl2Parser.java
@@ -1,759 +1,759 @@
package org.proofpad;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.Stack;
import java.util.logging.Logger;
import javax.swing.text.BadLocationException;
import org.fife.ui.rsyntaxtextarea.RSyntaxDocument;
import org.fife.ui.rsyntaxtextarea.Token;
import org.fife.ui.rsyntaxtextarea.parser.AbstractParser;
import org.fife.ui.rsyntaxtextarea.parser.DefaultParseResult;
import org.fife.ui.rsyntaxtextarea.parser.DefaultParserNotice;
import org.fife.ui.rsyntaxtextarea.parser.ParseResult;
import org.fife.ui.rsyntaxtextarea.parser.ParserNotice;
public class Acl2Parser extends AbstractParser {
public interface ParseListener {
void wasParsed();
}
private static Logger logger = Logger.getLogger(Acl2Parser.class.toString());
public static class CacheKey implements Serializable {
private static final long serialVersionUID = -4201796432147755450L;
private final File book;
private final long mtime;
public CacheKey(File book, long mtime) {
this.book = book;
this.mtime = mtime;
}
@Override
public int hashCode() {
return book.hashCode() ^ Long.valueOf(mtime).hashCode();
}
@Override
public boolean equals(Object other) {
return (other instanceof CacheKey &&
((CacheKey) other).book.equals(this.book) &&
((CacheKey) other).mtime == this.mtime);
}
}
private static class Range implements Serializable {
private static final long serialVersionUID = 3510110011135344206L;
public final int lower;
public final int upper;
Range(int lower, int upper) {
this.lower = lower;
this.upper = upper;
}
}
static class CacheSets implements Serializable {
private static final long serialVersionUID = -2233827686979689741L;
public Set<String> functions;
public Set<String> macros;
public Set<String> constants;
}
public Set<String> functions;
public Set<String> macros;
public Set<String> constants;
public File workingDir;
private Map<CacheKey, CacheSets> cache = Main.cache.getBookCache();
private File acl2Dir;
private final List<ParseListener> parseListeners = new LinkedList<Acl2Parser.ParseListener>();
private final Map<String, Acl2ParserNotice> funcNotices = new HashMap<String, Acl2Parser.Acl2ParserNotice>();
public Acl2Parser(File workingDir, File acl2Dir) {
this.workingDir = workingDir;
setAcl2Dir(acl2Dir);
}
private static Map<String, Range> paramCounts = new HashMap<String, Range>();
static {
paramCounts.put("-", new Range(1, 2));
paramCounts.put("/", new Range(1, 2));
paramCounts.put("/=", new Range(2, 2));
paramCounts.put("1+", new Range(1, 1));
paramCounts.put("1-", new Range(1, 1));
paramCounts.put("<=", new Range(2, 2));
paramCounts.put(">", new Range(2, 2));
paramCounts.put(">=", new Range(2, 2));
paramCounts.put("abs", new Range(1, 1));
paramCounts.put("acl2-numberp", new Range(1, 1));
paramCounts.put("acons", new Range(3, 3));
paramCounts.put("add-to-set-eq", new Range(2, 2));
paramCounts.put("add-to-set-eql", new Range(2, 2));
paramCounts.put("add-to-set-equal", new Range(2, 2));
paramCounts.put("alistp", new Range(1, 1));
paramCounts.put("alpha-char-p", new Range(1, 1));
paramCounts.put("alphorder", new Range(2, 2));
paramCounts.put("ash", new Range(2, 2));
paramCounts.put("assert$", new Range(2, 2));
paramCounts.put("assoc-eq", new Range(2, 2));
paramCounts.put("assoc-equal", new Range(2, 2));
paramCounts.put("assoc-keyword", new Range(2, 2));
paramCounts.put("atom", new Range(1, 1));
paramCounts.put("atom-listp", new Range(1, 1));
paramCounts.put("binary-*", new Range(2, 2));
paramCounts.put("binary-+", new Range(2, 2));
paramCounts.put("binary-append", new Range(2, 2));
paramCounts.put("boole$", new Range(3, 3));
paramCounts.put("booleanp", new Range(1, 1));
paramCounts.put("butlast", new Range(2, 2));
paramCounts.put("caaaar", new Range(1, 1));
paramCounts.put("caaadr", new Range(1, 1));
paramCounts.put("caaar", new Range(1, 1));
paramCounts.put("caadar", new Range(1, 1));
paramCounts.put("caaddr", new Range(1, 1));
paramCounts.put("caadr", new Range(1, 1));
paramCounts.put("caar", new Range(1, 1));
paramCounts.put("cadaar", new Range(1, 1));
paramCounts.put("cadadr", new Range(1, 1));
paramCounts.put("cadar", new Range(1, 1));
paramCounts.put("caddar", new Range(1, 1));
paramCounts.put("cadddr", new Range(1, 1));
paramCounts.put("caddr", new Range(1, 1));
paramCounts.put("cadr", new Range(1, 1));
paramCounts.put("car", new Range(1, 1));
paramCounts.put("cdaaar", new Range(1, 1));
paramCounts.put("cdaadr", new Range(1, 1));
paramCounts.put("cdaar", new Range(1, 1));
paramCounts.put("cdadar", new Range(1, 1));
paramCounts.put("cdaddr", new Range(1, 1));
paramCounts.put("cdadr", new Range(1, 1));
paramCounts.put("cdar", new Range(1, 1));
paramCounts.put("cddaar", new Range(1, 1));
paramCounts.put("cddadr", new Range(1, 1));
paramCounts.put("cddar", new Range(1, 1));
paramCounts.put("cdddar", new Range(1, 1));
paramCounts.put("cddddr", new Range(1, 1));
paramCounts.put("cdddr", new Range(1, 1));
paramCounts.put("cddr", new Range(1, 1));
paramCounts.put("cdr", new Range(1, 1));
paramCounts.put("ceiling", new Range(2, 2));
paramCounts.put("char", new Range(2, 2));
paramCounts.put("char-code", new Range(1, 1));
paramCounts.put("char-downcase", new Range(1, 1));
paramCounts.put("char-equal", new Range(2, 2));
paramCounts.put("char-upcase", new Range(1, 1));
paramCounts.put("char<", new Range(2, 2));
paramCounts.put("char<=", new Range(2, 2));
paramCounts.put("char>", new Range(2, 2));
paramCounts.put("char>=", new Range(2, 2));
paramCounts.put("character-alistp", new Range(1, 1));
paramCounts.put("character-listp", new Range(1, 1));
paramCounts.put("characterp", new Range(1, 1));
paramCounts.put("code-char", new Range(1, 1));
paramCounts.put("coerce", new Range(2, 2));
paramCounts.put("comp", new Range(1, 1));
paramCounts.put("comp-gcl", new Range(1, 1));
paramCounts.put("complex", new Range(2, 2));
paramCounts.put("complex-rationalp", new Range(1, 1));
paramCounts.put("complex/complex-rationalp", new Range(1, 1));
paramCounts.put("conjugate", new Range(1, 1));
paramCounts.put("cons", new Range(2, 2));
paramCounts.put("consp", new Range(1, 1));
paramCounts.put("cpu-core-count", new Range(1, 1));
paramCounts.put("delete-assoc-eq", new Range(2, 2));
paramCounts.put("denominator", new Range(1, 1));
paramCounts.put("digit-char-p", new Range(1, 2));
paramCounts.put("digit-to-char", new Range(1, 1));
paramCounts.put("ec-call", new Range(1, 1));
paramCounts.put("eighth", new Range(1, 1));
paramCounts.put("endp", new Range(1, 1));
paramCounts.put("eq", new Range(2, 2));
paramCounts.put("eql", new Range(2, 2));
paramCounts.put("eqlable-alistp", new Range(1, 1));
paramCounts.put("eqlable-listp", new Range(1, 1));
paramCounts.put("eqlablep", new Range(1, 1));
paramCounts.put("equal", new Range(2, 2));
paramCounts.put("error1", new Range(4, 4));
paramCounts.put("evenp", new Range(1, 1));
paramCounts.put("explode-nonnegative-integer", new Range(3, 5));
paramCounts.put("expt", new Range(2, 2));
paramCounts.put("fifth", new Range(1, 1));
paramCounts.put("first", new Range(1, 1));
paramCounts.put("fix", new Range(1, 1));
paramCounts.put("fix-true-list", new Range(1, 1));
paramCounts.put("floor", new Range(2, 2));
paramCounts.put("fms", new Range(5, 5));
paramCounts.put("fms!", new Range(5, 5));
paramCounts.put("fmt", new Range(5, 5));
paramCounts.put("fmt!", new Range(5, 5));
paramCounts.put("fmt1", new Range(6, 6));
paramCounts.put("fmt1!", new Range(6, 6));
paramCounts.put("fourth", new Range(1, 1));
paramCounts.put("get-output-stream-string$", new Range(2, 4));
paramCounts.put("getenv$", new Range(2, 2));
paramCounts.put("getprop", new Range(5, 5));
paramCounts.put("good-atom-listp", new Range(1, 1));
paramCounts.put("hard-error", new Range(3, 3));
paramCounts.put("identity", new Range(1, 1));
paramCounts.put("if", new Range(3, 3));
paramCounts.put("iff", new Range(2, 2));
paramCounts.put("ifix", new Range(1, 1));
paramCounts.put("illegal", new Range(3, 3));
paramCounts.put("imagpart", new Range(1, 1));
paramCounts.put("implies", new Range(2, 2));
paramCounts.put("improper-consp", new Range(1, 1));
paramCounts.put("int=", new Range(2, 2));
paramCounts.put("integer-length", new Range(1, 1));
paramCounts.put("integer-listp", new Range(1, 1));
paramCounts.put("integerp", new Range(1, 1));
paramCounts.put("intern", new Range(2, 2));
paramCounts.put("intern$", new Range(2, 2));
paramCounts.put("intern-in-package-of-symbol", new Range(2, 5));
paramCounts.put("intersectp-eq", new Range(2, 2));
paramCounts.put("intersectp-equal", new Range(2, 2));
paramCounts.put("keywordp", new Range(1, 1));
paramCounts.put("kwote", new Range(1, 1));
paramCounts.put("kwote-lst", new Range(1, 1));
paramCounts.put("last", new Range(1, 1));
paramCounts.put("len", new Range(1, 1));
paramCounts.put("length", new Range(1, 1));
paramCounts.put("lexorder", new Range(2, 2));
paramCounts.put("listp", new Range(1, 1));
paramCounts.put("logandc1", new Range(2, 2));
paramCounts.put("logandc2", new Range(2, 2));
paramCounts.put("logbitp", new Range(2, 2));
paramCounts.put("logcount", new Range(1, 1));
paramCounts.put("lognand", new Range(2, 2));
paramCounts.put("lognor", new Range(2, 2));
paramCounts.put("lognot", new Range(1, 1));
paramCounts.put("logorc1", new Range(2, 2));
paramCounts.put("logorc2", new Range(2, 2));
paramCounts.put("logtest", new Range(2, 2));
paramCounts.put("lower-case-p", new Range(1, 1));
paramCounts.put("make-ord", new Range(3, 3));
paramCounts.put("max", new Range(2, 2));
paramCounts.put("mbe1", new Range(2, 2));
paramCounts.put("mbt", new Range(1, 1));
paramCounts.put("member-eq", new Range(2, 2));
paramCounts.put("member-equal", new Range(2, 2));
paramCounts.put("min", new Range(2, 2));
paramCounts.put("minusp", new Range(1, 1));
paramCounts.put("mod", new Range(2, 2));
paramCounts.put("mod-expt", new Range(3, 3));
paramCounts.put("must-be-equal", new Range(2, 2));
paramCounts.put("mv-list", new Range(2, 2));
paramCounts.put("mv-nth", new Range(2, 2));
paramCounts.put("natp", new Range(1, 1));
paramCounts.put("nfix", new Range(1, 1));
paramCounts.put("ninth", new Range(1, 1));
paramCounts.put("no-duplicatesp-eq", new Range(1, 1));
paramCounts.put("nonnegative-integer-quotient", new Range(2, 4));
paramCounts.put("not", new Range(1, 1));
paramCounts.put("nth", new Range(2, 2));
paramCounts.put("nthcdr", new Range(2, 2));
paramCounts.put("null", new Range(1, 1));
paramCounts.put("numerator", new Range(1, 1));
paramCounts.put("o-finp", new Range(1, 1));
paramCounts.put("o-first-coeff", new Range(1, 1));
paramCounts.put("o-first-expt", new Range(1, 1));
paramCounts.put("o-infp", new Range(1, 1));
paramCounts.put("o-p", new Range(1, 1));
paramCounts.put("o-rst", new Range(1, 1));
paramCounts.put("o<", new Range(2, 2));
paramCounts.put("o<=", new Range(2, 2));
paramCounts.put("o>", new Range(2, 2));
paramCounts.put("o>=", new Range(2, 2));
paramCounts.put("oddp", new Range(1, 1));
paramCounts.put("pairlis$", new Range(2, 2));
paramCounts.put("peek-char$", new Range(2, 2));
paramCounts.put("pkg-imports", new Range(1, 1));
paramCounts.put("pkg-witness", new Range(1, 1));
paramCounts.put("plusp", new Range(1, 1));
paramCounts.put("position-eq", new Range(2, 2));
paramCounts.put("position-equal", new Range(2, 2));
paramCounts.put("posp", new Range(1, 1));
paramCounts.put("print-object$", new Range(3, 3));
paramCounts.put("prog2$", new Range(2, 2));
paramCounts.put("proofs-co", new Range(1, 1));
paramCounts.put("proper-consp", new Range(1, 1));
paramCounts.put("put-assoc-eq", new Range(3, 3));
paramCounts.put("put-assoc-eql", new Range(3, 3));
paramCounts.put("put-assoc-equal", new Range(3, 3));
paramCounts.put("putprop", new Range(4, 4));
paramCounts.put("r-eqlable-alistp", new Range(1, 1));
paramCounts.put("r-symbol-alistp", new Range(1, 1));
paramCounts.put("random$", new Range(2, 2));
paramCounts.put("rassoc-eq", new Range(2, 2));
paramCounts.put("rassoc-equal", new Range(2, 2));
paramCounts.put("rational-listp", new Range(1, 1));
paramCounts.put("rationalp", new Range(1, 1));
paramCounts.put("read-byte$", new Range(2, 2));
paramCounts.put("read-char$", new Range(2, 2));
paramCounts.put("read-object", new Range(2, 2));
paramCounts.put("real/rationalp", new Range(1, 1));
paramCounts.put("realfix", new Range(1, 1));
paramCounts.put("realpart", new Range(1, 1));
paramCounts.put("rem", new Range(2, 2));
paramCounts.put("remove-duplicates-eq", new Range(1, 1));
paramCounts.put("remove-duplicates-equal", new Range(1, 6));
paramCounts.put("remove-eq", new Range(2, 2));
paramCounts.put("remove-equal", new Range(2, 2));
paramCounts.put("remove1-eq", new Range(2, 2));
paramCounts.put("remove1-equal", new Range(2, 2));
paramCounts.put("rest", new Range(1, 1));
paramCounts.put("return-last", new Range(3, 3));
paramCounts.put("revappend", new Range(2, 2));
paramCounts.put("reverse", new Range(1, 1));
paramCounts.put("rfix", new Range(1, 1));
paramCounts.put("round", new Range(2, 2));
paramCounts.put("second", new Range(1, 1));
paramCounts.put("set-difference-eq", new Range(2, 2));
paramCounts.put("setenv$", new Range(2, 2));
paramCounts.put("seventh", new Range(1, 1));
paramCounts.put("signum", new Range(1, 1));
paramCounts.put("sixth", new Range(1, 1));
paramCounts.put("standard-char-p", new Range(1, 1));
paramCounts.put("string", new Range(1, 1));
paramCounts.put("string-append", new Range(2, 2));
paramCounts.put("string-downcase", new Range(1, 1));
paramCounts.put("string-equal", new Range(2, 2));
paramCounts.put("string-listp", new Range(1, 1));
paramCounts.put("string-upcase", new Range(1, 1));
paramCounts.put("string<", new Range(2, 2));
paramCounts.put("string<=", new Range(2, 2));
paramCounts.put("string>", new Range(2, 2));
paramCounts.put("string>=", new Range(2, 2));
paramCounts.put("stringp", new Range(1, 1));
paramCounts.put("strip-cars", new Range(1, 1));
paramCounts.put("strip-cdrs", new Range(1, 1));
paramCounts.put("sublis", new Range(2, 2));
paramCounts.put("subseq", new Range(3, 3));
paramCounts.put("subsetp-eq", new Range(2, 2));
paramCounts.put("subsetp-equal", new Range(2, 2));
paramCounts.put("subst", new Range(3, 3));
paramCounts.put("substitute", new Range(3, 3));
paramCounts.put("symbol-<", new Range(2, 2));
paramCounts.put("symbol-alistp", new Range(1, 1));
paramCounts.put("symbol-listp", new Range(1, 1));
paramCounts.put("symbol-name", new Range(1, 1));
paramCounts.put("symbolp", new Range(1, 1));
paramCounts.put("sys-call-status", new Range(1, 1));
paramCounts.put("take", new Range(2, 2));
paramCounts.put("tenth", new Range(1, 1));
paramCounts.put("the", new Range(2, 2));
paramCounts.put("third", new Range(1, 1));
paramCounts.put("true-list-listp", new Range(1, 1));
paramCounts.put("true-listp", new Range(1, 1));
paramCounts.put("truncate", new Range(2, 2));
paramCounts.put("unary--", new Range(1, 1));
paramCounts.put("unary-/", new Range(1, 1));
paramCounts.put("union-equal", new Range(2, 2));
paramCounts.put("update-nth", new Range(3, 3));
paramCounts.put("upper-case-p", new Range(1, 1));
paramCounts.put("with-live-state", new Range(1, 1));
paramCounts.put("write-byte$", new Range(3, 3));
paramCounts.put("xor", new Range(2, 2));
paramCounts.put("zerop", new Range(1, 1));
paramCounts.put("zip", new Range(1, 1));
paramCounts.put("zp", new Range(1, 1));
paramCounts.put("zpf", new Range(1, 1));
paramCounts.put("comp", new Range(1, 1));
paramCounts.put("defconst", new Range(2, 3));
paramCounts.put("defdoc", new Range(2, 2));
paramCounts.put("defpkg", new Range(2, 5));
paramCounts.put("defproxy", new Range(4, 4));
paramCounts.put("local", new Range(1, 1));
paramCounts.put("remove-custom-keyword-hint", new Range(1, 1));
paramCounts.put("set-body", new Range(2, 2));
paramCounts.put("show-custom-keyword-hint-expansion", new Range(1, 1));
paramCounts.put("table", new Range(1, 5));
paramCounts.put("unmemoize", new Range(1, 1));
paramCounts.put("add-binop", new Range(2, 2));
paramCounts.put("add-dive-into-macro", new Range(2, 2));
paramCounts.put("add-include-book-dir", new Range(2, 2));
paramCounts.put("add-macro-alias", new Range(2, 2));
paramCounts.put("add-nth-alias", new Range(2, 2));
paramCounts.put("binop-table", new Range(1, 1));
paramCounts.put("delete-include-book-dir", new Range(1, 1));
paramCounts.put("remove-binop", new Range(1, 1));
paramCounts.put("remove-default-hints", new Range(1, 1));
paramCounts.put("remove-default-hints!", new Range(1, 1));
paramCounts.put("remove-dive-into-macro", new Range(1, 1));
paramCounts.put("remove-macro-alias", new Range(1, 1));
paramCounts.put("remove-nth-alias", new Range(1, 1));
paramCounts.put("remove-override-hints", new Range(1, 1));
paramCounts.put("remove-override-hints!", new Range(1, 1));
paramCounts.put("set-backchain-limit", new Range(1, 1));
paramCounts.put("set-bogus-defun-hints-ok", new Range(1, 1));
paramCounts.put("set-bogus-mutual-recursion-ok", new Range(1, 1));
paramCounts.put("set-case-split-limitations", new Range(1, 1));
paramCounts.put("set-checkpoint-summary-limit", new Range(1, 1));
paramCounts.put("set-compile-fns", new Range(1, 1));
paramCounts.put("set-debugger-enable", new Range(1, 1));
paramCounts.put("set-default-backchain-limit", new Range(1, 1));
paramCounts.put("set-default-hints", new Range(1, 1));
paramCounts.put("set-default-hints!", new Range(1, 1));
paramCounts.put("set-deferred-ttag-notes", new Range(2, 6));
paramCounts.put("set-enforce-redundancy", new Range(1, 1));
paramCounts.put("set-gag-mode", new Range(1, 1));
paramCounts.put("set-guard-checking", new Range(1, 1));
paramCounts.put("set-ignore-doc-string-error", new Range(1, 1));
paramCounts.put("set-ignore-ok", new Range(1, 1));
paramCounts.put("set-inhibit-output-lst", new Range(1, 1));
paramCounts.put("set-inhibited-summary-types", new Range(1, 1));
paramCounts.put("set-invisible-fns-table", new Range(1, 1));
paramCounts.put("set-irrelevant-formals-ok", new Range(1, 1));
paramCounts.put("set-ld-keyword-aliases", new Range(2, 6));
paramCounts.put("set-ld-redefinition-action", new Range(2, 5));
paramCounts.put("set-ld-skip-proofs", new Range(2, 2));
paramCounts.put("set-let*-abstraction", new Range(1, 1));
paramCounts.put("set-let*-abstractionp", new Range(1, 1));
paramCounts.put("set-match-free-default", new Range(1, 1));
paramCounts.put("set-match-free-error", new Range(1, 1));
paramCounts.put("set-measure-function", new Range(1, 1));
paramCounts.put("set-non-linear", new Range(1, 1));
paramCounts.put("set-non-linearp", new Range(1, 1));
paramCounts.put("set-nu-rewriter-mode", new Range(1, 1));
paramCounts.put("set-override-hints", new Range(1, 1));
paramCounts.put("set-override-hints!", new Range(1, 1));
paramCounts.put("set-print-clause-ids", new Range(1, 1));
paramCounts.put("set-prover-step-limit", new Range(1, 1));
paramCounts.put("set-raw-mode", new Range(1, 1));
paramCounts.put("set-raw-proof-format", new Range(1, 1));
paramCounts.put("set-rewrite-stack-limit", new Range(1, 1));
paramCounts.put("set-ruler-extenders", new Range(1, 1));
paramCounts.put("set-rw-cache-state", new Range(1, 1));
paramCounts.put("set-rw-cache-state!", new Range(1, 1));
paramCounts.put("set-saved-output", new Range(2, 2));
paramCounts.put("set-state-ok", new Range(1, 1));
paramCounts.put("set-tainted-ok", new Range(1, 1));
paramCounts.put("set-tainted-okp", new Range(1, 1));
paramCounts.put("set-verify-guards-eagerness", new Range(1, 1));
paramCounts.put("set-waterfall-parallelism", new Range(1, 2));
paramCounts.put("set-waterfall-printing", new Range(1, 1));
paramCounts.put("set-well-founded-relation", new Range(1, 1));
paramCounts.put("set-write-acl2x", new Range(2, 2));
paramCounts.put("with-guard-checking", new Range(2, 2));
}
public class ParseToken {
public int offset;
public int line;
public String name;
public List<String> params = new ArrayList<String>();
public Set<String> vars = new HashSet<String>();
}
public class Acl2ParserNotice extends DefaultParserNotice {
public String funcName;
public Acl2ParserNotice(Acl2Parser parser, String msg, int line, int offs, int len, int level) {
super(parser, msg, line, offs, len);
//System.out.println("ERROR on line " + line + ": " + msg);
setLevel(level);
}
public Acl2ParserNotice(Acl2Parser parser, String msg,
ParseToken top, int end) {
this(parser, msg, top.line, top.offset, end - top.offset, ERROR);
}
public Acl2ParserNotice(Acl2Parser parser, String msg, int line,
Token token, int level) {
this(parser, msg, line, token.offset, token.textCount, level);
}
@Override
public boolean getShowInEditor() {
return getLevel() != INFO;
}
}
@Override
public ParseResult parse(RSyntaxDocument doc, String style /* ignored */) {
DefaultParseResult result = new DefaultParseResult(this);
int lines = doc.getDefaultRootElement().getElementCount();
result.setParsedLines(0, lines);
if (!Prefs.showErrors.get()) {
for (ParseListener pl : parseListeners) {
pl.wasParsed();
}
return result;
}
functions = new HashSet<String>();
macros = new HashSet<String>(Arrays.asList(new String [] {
- "declare", "include-book", "defproperty", "defttag"
+ "declare", "include-book", "defttag"
}));
constants = new HashSet<String>();
constants.add("state");
Stack<ParseToken> s = new Stack<ParseToken>();
Token token;
for (int line = 0; line < lines; line++) {
token = doc.getTokenListForLine(line);
while (token != null && token.isPaintable()) {
ParseToken top = (s.empty() ? null : s.peek());
String tokenName = token.getLexeme().toLowerCase();
if (top != null && top.name != null && !token.isWhitespace() &&
!token.isComment() && !token.isSingleChar(')') &&
!token.isSingleChar('`') && !token.isSingleChar(',') &&
!token.isSingleChar('\'')) {
// In a parameter position.
top.params.add(token.getLexeme());
if (top.name.equals("defun") && top.params.size() == 1) {
if (!macros.contains(tokenName) && !functions.contains(tokenName)) {
functions.add(tokenName);
if (funcNotices.containsKey(tokenName)) {
Acl2ParserNotice notice = funcNotices.get(tokenName);
notice.setToolTipText(String.format(
"<html>The function <b>%s</b> is defined below. Move the " +
"definition above this call.</html>",
htmlEncode(notice.funcName)));
}
} else {
result.addNotice(new Acl2ParserNotice(this,
"A function with this name is already defined", line, token,
ParserNotice.ERROR));
}
} else if ((top.name.equals("defmacro") || top.name.equals("defabbrev")) &&
top.params.size() == 1) {
if (!functions.contains(tokenName) && !macros.contains(tokenName)) {
macros.add(tokenName);
} else {
result.addNotice(new Acl2ParserNotice(this,
"A function with this name is already defined", line, token,
ParserNotice.ERROR));
}
} else if (top.name.equals("defconst") && top.params.size() == 1) {
if (!tokenName.startsWith("*") || !tokenName.endsWith("*")) {
Main.userData.addParseError("constNames");
result.addNotice(new Acl2ParserNotice(this,
"Constant names must begin and end with *.", line, token,
ParserNotice.ERROR));
} else {
if (!constants.contains(tokenName)) {
constants.add(tokenName);
} else {
result.addNotice(new Acl2ParserNotice(this,
"A constant with this name is already defined", line, token,
ParserNotice.ERROR));
}
}
}
}
ParseToken parent = s.size() <= 1 ? null : s.get(s.size() - 2);
ParseToken grandparent = s.size() <= 2 ? null : s.get(s.size() - 3);
boolean isVariableOfParent = parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1);
boolean isVariableOfGrandparent = (grandparent != null && grandparent.name != null &&
((grandparent.name.equals("let") || grandparent.name.equals("let*")) &&
grandparent.params.size() == 1 && top != null && top.params.size() == 0));
if (isVariableOfParent || isVariableOfGrandparent) {
if (token.type == Token.IDENTIFIER) {
if (parent != null && isVariableOfParent) {
parent.vars.add(token.getLexeme());
} else if (grandparent != null && isVariableOfGrandparent) {
grandparent.vars.add(token.getLexeme());
}
} else if (token.type != Token.WHITESPACE && !token.isSingleChar(')')) {
Main.userData.addParseError("expectedVariableName");
result.addNotice(new Acl2ParserNotice(this, "Expected a variable name",
line, token, ParserNotice.ERROR));
}
}
boolean isIgnoredBecauseMacro = false;
boolean isThm = false;
Set<String> vars = new HashSet<String>();
for (ParseToken ancestor : s) {
isIgnoredBecauseMacro |= macros.contains(ancestor.name);
vars.addAll(ancestor.vars);
isThm |= ancestor.name != null && (ancestor.name.equals("thm") ||
ancestor.name.equals("defthm") || ancestor.name.equals("defthmd"));
}
boolean isIgnoredBecauseParent = parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("defmacro") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1 ||
parent.name.equals("cond") /* any parameter */ ||
parent.name.equals("case") /* any parameter */);
boolean isIgnoredBecauseCurrent = top != null && top.name != null &&
(top.name.equals("defun") && top.params.size() == 1 ||
top.name.equals("defmacro") && top.params.size() == 1 ||
top.name.equals("assign") && top.params.size() == 1 ||
top.name.equals("@") && top.params.size() == 1);
boolean isIgnored = isIgnoredBecauseMacro || isIgnoredBecauseParent || isIgnoredBecauseCurrent ||
(top != null && grandparent != null && grandparent.name != null &&
(grandparent.name.equals("let") && grandparent.params.size() == 1 && top.params.size() == 0 ||
grandparent.name.equals("let*") && grandparent.params.size() == 1 && top.params.size() == 0));
if (token.isSingleChar('(')) {
if (top != null && top.name == null) top.name = "";
s.push(new ParseToken());
s.peek().line = line;
s.peek().offset = token.offset;
} else if (token.isSingleChar(')')) {
if (top == null) {
Main.userData.addParseError("UnmatchedCloseParen");
result.addNotice(new Acl2ParserNotice(this, "Unmatched )", line, token.offset, 1,
ParserNotice.ERROR));
} else {
Range range = paramCounts.get(top.name);
if (range != null && (top.params.size() < range.lower || top.params.size() > range.upper)) {
String msg;
if (range.lower == range.upper) {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects "
+ range.lower + " parameter" +
(range.lower == 1 ? "" : "s") + ".</html>";
} else {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects between "
+ range.lower + " and " + range.upper + " parameters.</html>";
}
Main.userData.addParseError("numOfParams");
result.addNotice(new Acl2ParserNotice(this, msg, top, token.offset + 1));
}
s.pop();
if (top.name != null && top.name.equals("include-book")) {
String bookName = top.params.get(0);
int dirLoc = top.params.indexOf(":dir") + 1;
File dir;
String dirKey = "";
if (dirLoc == 0) {
dir = workingDir;
} else {
dirKey = top.params.get(dirLoc);
if (dirKey.equals(":system")) {
dir = new File(getAcl2Dir(), "books");
} else if (dirKey.equals(":teachpacks")) {
dir = new File(getAcl2Dir(), "dracula");
} else {
Main.userData.addParseError("UnrecongizedBookLocation");
result.addNotice(new Acl2ParserNotice(this,
"Unrecognized book location: " + dirKey, top,
token.offset + 1));
dir = null;
}
}
if (Main.WIN) {
bookName.replaceAll("\\\\/", "\\");
}
File book = new File(dir, bookName.substring(1, bookName.length() - 1) + ".lisp");
CacheSets bookCache = null;
long mtime = book.lastModified();
if (dirKey.equals(":system")) {
mtime = Long.MAX_VALUE;
}
CacheKey key = new CacheKey(book, mtime);
if (cache.containsKey(key)) {
bookCache = cache.get(key);
} else {
try {
System.out.println("Book exists? " + book);
bookCache = parseBook(book, getAcl2Dir(), cache);
cache.put(key, bookCache);
} catch (FileNotFoundException e) {
Main.userData.addParseError("BookNotFound");
result.addNotice(new Acl2ParserNotice(this,
"File could not be found.", top, token.offset + 1));
} catch (BadLocationException e) { }
}
if (bookCache != null) {
functions.addAll(bookCache.functions);
macros.addAll(bookCache.macros);
constants.addAll(bookCache.constants);
}
}
}
} else if (top != null && top.name == null &&
!token.isComment() &&
!token.isWhitespace()) {
// This token is at the beginning of an s expression
top.name = token.getLexeme().toLowerCase();
if (token.type != Token.RESERVED_WORD &&
token.type != Token.RESERVED_WORD_2 &&
!functions.contains(top.name) &&
!macros.contains(top.name) &&
!isIgnored) {
Main.userData.addParseError("undefinedCallable");
Acl2ParserNotice undefinedFuncNotice = new Acl2ParserNotice(this,
String.format("<html>The function <b>%s</b> is undefined.</html>",
htmlEncode(top.name)), line, token, ParserNotice.ERROR);
undefinedFuncNotice.funcName = top.name;
funcNotices.put(top.name, undefinedFuncNotice);
result.addNotice(undefinedFuncNotice);
}
if (token.type == Token.RESERVED_WORD ||
token.type == Token.RESERVED_WORD_2) {
// TODO: Make these more noticeable?
Map<String, String> docs = Main.cache.getDocs();
String upperToken = token.getLexeme().toUpperCase();
if (docs.containsKey(upperToken)) {
String modKey = Main.OSX ? "\u2325\u2318" : "Ctrl + Alt + ";
String msg = "<html>" + docs.get(upperToken) + "<br><font " +
"color=\"gray\" size=\"2\">" + modKey +
"L for more.</font></html>";
result.addNotice(new Acl2ParserNotice(this,
msg, line, token, ParserNotice.INFO));
}
}
} else if (!isThm && !isIgnored && (token.type == Token.IDENTIFIER ||
token.type == Token.RESERVED_WORD || token.type == Token.RESERVED_WORD_2)
&& !constants.contains(token.getLexeme()) &&
!vars.contains(token.getLexeme())) {
Main.userData.addParseError("undeclaredVariable");
result.addNotice(new Acl2ParserNotice(this, token.getLexeme() +
" is undeclared.",
line, token, ParserNotice.ERROR));
}
token = token.getNextToken();
}
}
for (ParseListener pl : parseListeners) {
pl.wasParsed();
}
return result;
}
public static CacheSets parseBook(File book, File acl2Dir, Map<CacheKey, CacheSets> cache)
throws FileNotFoundException, BadLocationException {
CacheSets bookCache;
Scanner bookScanner = new Scanner(book);
bookScanner.useDelimiter("\\Z");
String bookContents = bookScanner.next();
bookScanner.close();
logger.info("PARSING: " + book);
book.lastModified();
Acl2Parser bookParser = new Acl2Parser(book.getParentFile(), acl2Dir);
bookParser.cache = cache;
RSyntaxDocument bookDoc = new PPDocument();
bookDoc.insertString(0, bookContents, null);
bookParser.parse(bookDoc, null);
bookCache = new CacheSets();
bookCache.functions = bookParser.functions;
bookCache.constants = bookParser.constants;
bookCache.macros = bookParser.macros;
return bookCache;
}
private static String htmlEncode(String name) {
return name.replace("&", "&").replace("<", "<").replace(">", ">");
}
public void addParseListener(ParseListener parseListener) {
parseListeners.add(parseListener);
}
public File getAcl2Dir() {
return acl2Dir;
}
public void setAcl2Dir(File acl2Dir) {
this.acl2Dir = acl2Dir;
}
}
| true | true | public ParseResult parse(RSyntaxDocument doc, String style /* ignored */) {
DefaultParseResult result = new DefaultParseResult(this);
int lines = doc.getDefaultRootElement().getElementCount();
result.setParsedLines(0, lines);
if (!Prefs.showErrors.get()) {
for (ParseListener pl : parseListeners) {
pl.wasParsed();
}
return result;
}
functions = new HashSet<String>();
macros = new HashSet<String>(Arrays.asList(new String [] {
"declare", "include-book", "defproperty", "defttag"
}));
constants = new HashSet<String>();
constants.add("state");
Stack<ParseToken> s = new Stack<ParseToken>();
Token token;
for (int line = 0; line < lines; line++) {
token = doc.getTokenListForLine(line);
while (token != null && token.isPaintable()) {
ParseToken top = (s.empty() ? null : s.peek());
String tokenName = token.getLexeme().toLowerCase();
if (top != null && top.name != null && !token.isWhitespace() &&
!token.isComment() && !token.isSingleChar(')') &&
!token.isSingleChar('`') && !token.isSingleChar(',') &&
!token.isSingleChar('\'')) {
// In a parameter position.
top.params.add(token.getLexeme());
if (top.name.equals("defun") && top.params.size() == 1) {
if (!macros.contains(tokenName) && !functions.contains(tokenName)) {
functions.add(tokenName);
if (funcNotices.containsKey(tokenName)) {
Acl2ParserNotice notice = funcNotices.get(tokenName);
notice.setToolTipText(String.format(
"<html>The function <b>%s</b> is defined below. Move the " +
"definition above this call.</html>",
htmlEncode(notice.funcName)));
}
} else {
result.addNotice(new Acl2ParserNotice(this,
"A function with this name is already defined", line, token,
ParserNotice.ERROR));
}
} else if ((top.name.equals("defmacro") || top.name.equals("defabbrev")) &&
top.params.size() == 1) {
if (!functions.contains(tokenName) && !macros.contains(tokenName)) {
macros.add(tokenName);
} else {
result.addNotice(new Acl2ParserNotice(this,
"A function with this name is already defined", line, token,
ParserNotice.ERROR));
}
} else if (top.name.equals("defconst") && top.params.size() == 1) {
if (!tokenName.startsWith("*") || !tokenName.endsWith("*")) {
Main.userData.addParseError("constNames");
result.addNotice(new Acl2ParserNotice(this,
"Constant names must begin and end with *.", line, token,
ParserNotice.ERROR));
} else {
if (!constants.contains(tokenName)) {
constants.add(tokenName);
} else {
result.addNotice(new Acl2ParserNotice(this,
"A constant with this name is already defined", line, token,
ParserNotice.ERROR));
}
}
}
}
ParseToken parent = s.size() <= 1 ? null : s.get(s.size() - 2);
ParseToken grandparent = s.size() <= 2 ? null : s.get(s.size() - 3);
boolean isVariableOfParent = parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1);
boolean isVariableOfGrandparent = (grandparent != null && grandparent.name != null &&
((grandparent.name.equals("let") || grandparent.name.equals("let*")) &&
grandparent.params.size() == 1 && top != null && top.params.size() == 0));
if (isVariableOfParent || isVariableOfGrandparent) {
if (token.type == Token.IDENTIFIER) {
if (parent != null && isVariableOfParent) {
parent.vars.add(token.getLexeme());
} else if (grandparent != null && isVariableOfGrandparent) {
grandparent.vars.add(token.getLexeme());
}
} else if (token.type != Token.WHITESPACE && !token.isSingleChar(')')) {
Main.userData.addParseError("expectedVariableName");
result.addNotice(new Acl2ParserNotice(this, "Expected a variable name",
line, token, ParserNotice.ERROR));
}
}
boolean isIgnoredBecauseMacro = false;
boolean isThm = false;
Set<String> vars = new HashSet<String>();
for (ParseToken ancestor : s) {
isIgnoredBecauseMacro |= macros.contains(ancestor.name);
vars.addAll(ancestor.vars);
isThm |= ancestor.name != null && (ancestor.name.equals("thm") ||
ancestor.name.equals("defthm") || ancestor.name.equals("defthmd"));
}
boolean isIgnoredBecauseParent = parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("defmacro") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1 ||
parent.name.equals("cond") /* any parameter */ ||
parent.name.equals("case") /* any parameter */);
boolean isIgnoredBecauseCurrent = top != null && top.name != null &&
(top.name.equals("defun") && top.params.size() == 1 ||
top.name.equals("defmacro") && top.params.size() == 1 ||
top.name.equals("assign") && top.params.size() == 1 ||
top.name.equals("@") && top.params.size() == 1);
boolean isIgnored = isIgnoredBecauseMacro || isIgnoredBecauseParent || isIgnoredBecauseCurrent ||
(top != null && grandparent != null && grandparent.name != null &&
(grandparent.name.equals("let") && grandparent.params.size() == 1 && top.params.size() == 0 ||
grandparent.name.equals("let*") && grandparent.params.size() == 1 && top.params.size() == 0));
if (token.isSingleChar('(')) {
if (top != null && top.name == null) top.name = "";
s.push(new ParseToken());
s.peek().line = line;
s.peek().offset = token.offset;
} else if (token.isSingleChar(')')) {
if (top == null) {
Main.userData.addParseError("UnmatchedCloseParen");
result.addNotice(new Acl2ParserNotice(this, "Unmatched )", line, token.offset, 1,
ParserNotice.ERROR));
} else {
Range range = paramCounts.get(top.name);
if (range != null && (top.params.size() < range.lower || top.params.size() > range.upper)) {
String msg;
if (range.lower == range.upper) {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects "
+ range.lower + " parameter" +
(range.lower == 1 ? "" : "s") + ".</html>";
} else {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects between "
+ range.lower + " and " + range.upper + " parameters.</html>";
}
Main.userData.addParseError("numOfParams");
result.addNotice(new Acl2ParserNotice(this, msg, top, token.offset + 1));
}
s.pop();
if (top.name != null && top.name.equals("include-book")) {
String bookName = top.params.get(0);
int dirLoc = top.params.indexOf(":dir") + 1;
File dir;
String dirKey = "";
if (dirLoc == 0) {
dir = workingDir;
} else {
dirKey = top.params.get(dirLoc);
if (dirKey.equals(":system")) {
dir = new File(getAcl2Dir(), "books");
} else if (dirKey.equals(":teachpacks")) {
dir = new File(getAcl2Dir(), "dracula");
} else {
Main.userData.addParseError("UnrecongizedBookLocation");
result.addNotice(new Acl2ParserNotice(this,
"Unrecognized book location: " + dirKey, top,
token.offset + 1));
dir = null;
}
}
if (Main.WIN) {
bookName.replaceAll("\\\\/", "\\");
}
File book = new File(dir, bookName.substring(1, bookName.length() - 1) + ".lisp");
CacheSets bookCache = null;
long mtime = book.lastModified();
if (dirKey.equals(":system")) {
mtime = Long.MAX_VALUE;
}
CacheKey key = new CacheKey(book, mtime);
if (cache.containsKey(key)) {
bookCache = cache.get(key);
} else {
try {
System.out.println("Book exists? " + book);
bookCache = parseBook(book, getAcl2Dir(), cache);
cache.put(key, bookCache);
} catch (FileNotFoundException e) {
Main.userData.addParseError("BookNotFound");
result.addNotice(new Acl2ParserNotice(this,
"File could not be found.", top, token.offset + 1));
} catch (BadLocationException e) { }
}
if (bookCache != null) {
functions.addAll(bookCache.functions);
macros.addAll(bookCache.macros);
constants.addAll(bookCache.constants);
}
}
}
} else if (top != null && top.name == null &&
!token.isComment() &&
!token.isWhitespace()) {
// This token is at the beginning of an s expression
top.name = token.getLexeme().toLowerCase();
if (token.type != Token.RESERVED_WORD &&
token.type != Token.RESERVED_WORD_2 &&
!functions.contains(top.name) &&
!macros.contains(top.name) &&
!isIgnored) {
Main.userData.addParseError("undefinedCallable");
Acl2ParserNotice undefinedFuncNotice = new Acl2ParserNotice(this,
String.format("<html>The function <b>%s</b> is undefined.</html>",
htmlEncode(top.name)), line, token, ParserNotice.ERROR);
undefinedFuncNotice.funcName = top.name;
funcNotices.put(top.name, undefinedFuncNotice);
result.addNotice(undefinedFuncNotice);
}
if (token.type == Token.RESERVED_WORD ||
token.type == Token.RESERVED_WORD_2) {
// TODO: Make these more noticeable?
Map<String, String> docs = Main.cache.getDocs();
String upperToken = token.getLexeme().toUpperCase();
if (docs.containsKey(upperToken)) {
String modKey = Main.OSX ? "\u2325\u2318" : "Ctrl + Alt + ";
String msg = "<html>" + docs.get(upperToken) + "<br><font " +
"color=\"gray\" size=\"2\">" + modKey +
"L for more.</font></html>";
result.addNotice(new Acl2ParserNotice(this,
msg, line, token, ParserNotice.INFO));
}
}
} else if (!isThm && !isIgnored && (token.type == Token.IDENTIFIER ||
token.type == Token.RESERVED_WORD || token.type == Token.RESERVED_WORD_2)
&& !constants.contains(token.getLexeme()) &&
!vars.contains(token.getLexeme())) {
Main.userData.addParseError("undeclaredVariable");
result.addNotice(new Acl2ParserNotice(this, token.getLexeme() +
" is undeclared.",
line, token, ParserNotice.ERROR));
}
token = token.getNextToken();
}
}
for (ParseListener pl : parseListeners) {
pl.wasParsed();
}
return result;
}
| public ParseResult parse(RSyntaxDocument doc, String style /* ignored */) {
DefaultParseResult result = new DefaultParseResult(this);
int lines = doc.getDefaultRootElement().getElementCount();
result.setParsedLines(0, lines);
if (!Prefs.showErrors.get()) {
for (ParseListener pl : parseListeners) {
pl.wasParsed();
}
return result;
}
functions = new HashSet<String>();
macros = new HashSet<String>(Arrays.asList(new String [] {
"declare", "include-book", "defttag"
}));
constants = new HashSet<String>();
constants.add("state");
Stack<ParseToken> s = new Stack<ParseToken>();
Token token;
for (int line = 0; line < lines; line++) {
token = doc.getTokenListForLine(line);
while (token != null && token.isPaintable()) {
ParseToken top = (s.empty() ? null : s.peek());
String tokenName = token.getLexeme().toLowerCase();
if (top != null && top.name != null && !token.isWhitespace() &&
!token.isComment() && !token.isSingleChar(')') &&
!token.isSingleChar('`') && !token.isSingleChar(',') &&
!token.isSingleChar('\'')) {
// In a parameter position.
top.params.add(token.getLexeme());
if (top.name.equals("defun") && top.params.size() == 1) {
if (!macros.contains(tokenName) && !functions.contains(tokenName)) {
functions.add(tokenName);
if (funcNotices.containsKey(tokenName)) {
Acl2ParserNotice notice = funcNotices.get(tokenName);
notice.setToolTipText(String.format(
"<html>The function <b>%s</b> is defined below. Move the " +
"definition above this call.</html>",
htmlEncode(notice.funcName)));
}
} else {
result.addNotice(new Acl2ParserNotice(this,
"A function with this name is already defined", line, token,
ParserNotice.ERROR));
}
} else if ((top.name.equals("defmacro") || top.name.equals("defabbrev")) &&
top.params.size() == 1) {
if (!functions.contains(tokenName) && !macros.contains(tokenName)) {
macros.add(tokenName);
} else {
result.addNotice(new Acl2ParserNotice(this,
"A function with this name is already defined", line, token,
ParserNotice.ERROR));
}
} else if (top.name.equals("defconst") && top.params.size() == 1) {
if (!tokenName.startsWith("*") || !tokenName.endsWith("*")) {
Main.userData.addParseError("constNames");
result.addNotice(new Acl2ParserNotice(this,
"Constant names must begin and end with *.", line, token,
ParserNotice.ERROR));
} else {
if (!constants.contains(tokenName)) {
constants.add(tokenName);
} else {
result.addNotice(new Acl2ParserNotice(this,
"A constant with this name is already defined", line, token,
ParserNotice.ERROR));
}
}
}
}
ParseToken parent = s.size() <= 1 ? null : s.get(s.size() - 2);
ParseToken grandparent = s.size() <= 2 ? null : s.get(s.size() - 3);
boolean isVariableOfParent = parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1);
boolean isVariableOfGrandparent = (grandparent != null && grandparent.name != null &&
((grandparent.name.equals("let") || grandparent.name.equals("let*")) &&
grandparent.params.size() == 1 && top != null && top.params.size() == 0));
if (isVariableOfParent || isVariableOfGrandparent) {
if (token.type == Token.IDENTIFIER) {
if (parent != null && isVariableOfParent) {
parent.vars.add(token.getLexeme());
} else if (grandparent != null && isVariableOfGrandparent) {
grandparent.vars.add(token.getLexeme());
}
} else if (token.type != Token.WHITESPACE && !token.isSingleChar(')')) {
Main.userData.addParseError("expectedVariableName");
result.addNotice(new Acl2ParserNotice(this, "Expected a variable name",
line, token, ParserNotice.ERROR));
}
}
boolean isIgnoredBecauseMacro = false;
boolean isThm = false;
Set<String> vars = new HashSet<String>();
for (ParseToken ancestor : s) {
isIgnoredBecauseMacro |= macros.contains(ancestor.name);
vars.addAll(ancestor.vars);
isThm |= ancestor.name != null && (ancestor.name.equals("thm") ||
ancestor.name.equals("defthm") || ancestor.name.equals("defthmd"));
}
boolean isIgnoredBecauseParent = parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("defmacro") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1 ||
parent.name.equals("cond") /* any parameter */ ||
parent.name.equals("case") /* any parameter */);
boolean isIgnoredBecauseCurrent = top != null && top.name != null &&
(top.name.equals("defun") && top.params.size() == 1 ||
top.name.equals("defmacro") && top.params.size() == 1 ||
top.name.equals("assign") && top.params.size() == 1 ||
top.name.equals("@") && top.params.size() == 1);
boolean isIgnored = isIgnoredBecauseMacro || isIgnoredBecauseParent || isIgnoredBecauseCurrent ||
(top != null && grandparent != null && grandparent.name != null &&
(grandparent.name.equals("let") && grandparent.params.size() == 1 && top.params.size() == 0 ||
grandparent.name.equals("let*") && grandparent.params.size() == 1 && top.params.size() == 0));
if (token.isSingleChar('(')) {
if (top != null && top.name == null) top.name = "";
s.push(new ParseToken());
s.peek().line = line;
s.peek().offset = token.offset;
} else if (token.isSingleChar(')')) {
if (top == null) {
Main.userData.addParseError("UnmatchedCloseParen");
result.addNotice(new Acl2ParserNotice(this, "Unmatched )", line, token.offset, 1,
ParserNotice.ERROR));
} else {
Range range = paramCounts.get(top.name);
if (range != null && (top.params.size() < range.lower || top.params.size() > range.upper)) {
String msg;
if (range.lower == range.upper) {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects "
+ range.lower + " parameter" +
(range.lower == 1 ? "" : "s") + ".</html>";
} else {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects between "
+ range.lower + " and " + range.upper + " parameters.</html>";
}
Main.userData.addParseError("numOfParams");
result.addNotice(new Acl2ParserNotice(this, msg, top, token.offset + 1));
}
s.pop();
if (top.name != null && top.name.equals("include-book")) {
String bookName = top.params.get(0);
int dirLoc = top.params.indexOf(":dir") + 1;
File dir;
String dirKey = "";
if (dirLoc == 0) {
dir = workingDir;
} else {
dirKey = top.params.get(dirLoc);
if (dirKey.equals(":system")) {
dir = new File(getAcl2Dir(), "books");
} else if (dirKey.equals(":teachpacks")) {
dir = new File(getAcl2Dir(), "dracula");
} else {
Main.userData.addParseError("UnrecongizedBookLocation");
result.addNotice(new Acl2ParserNotice(this,
"Unrecognized book location: " + dirKey, top,
token.offset + 1));
dir = null;
}
}
if (Main.WIN) {
bookName.replaceAll("\\\\/", "\\");
}
File book = new File(dir, bookName.substring(1, bookName.length() - 1) + ".lisp");
CacheSets bookCache = null;
long mtime = book.lastModified();
if (dirKey.equals(":system")) {
mtime = Long.MAX_VALUE;
}
CacheKey key = new CacheKey(book, mtime);
if (cache.containsKey(key)) {
bookCache = cache.get(key);
} else {
try {
System.out.println("Book exists? " + book);
bookCache = parseBook(book, getAcl2Dir(), cache);
cache.put(key, bookCache);
} catch (FileNotFoundException e) {
Main.userData.addParseError("BookNotFound");
result.addNotice(new Acl2ParserNotice(this,
"File could not be found.", top, token.offset + 1));
} catch (BadLocationException e) { }
}
if (bookCache != null) {
functions.addAll(bookCache.functions);
macros.addAll(bookCache.macros);
constants.addAll(bookCache.constants);
}
}
}
} else if (top != null && top.name == null &&
!token.isComment() &&
!token.isWhitespace()) {
// This token is at the beginning of an s expression
top.name = token.getLexeme().toLowerCase();
if (token.type != Token.RESERVED_WORD &&
token.type != Token.RESERVED_WORD_2 &&
!functions.contains(top.name) &&
!macros.contains(top.name) &&
!isIgnored) {
Main.userData.addParseError("undefinedCallable");
Acl2ParserNotice undefinedFuncNotice = new Acl2ParserNotice(this,
String.format("<html>The function <b>%s</b> is undefined.</html>",
htmlEncode(top.name)), line, token, ParserNotice.ERROR);
undefinedFuncNotice.funcName = top.name;
funcNotices.put(top.name, undefinedFuncNotice);
result.addNotice(undefinedFuncNotice);
}
if (token.type == Token.RESERVED_WORD ||
token.type == Token.RESERVED_WORD_2) {
// TODO: Make these more noticeable?
Map<String, String> docs = Main.cache.getDocs();
String upperToken = token.getLexeme().toUpperCase();
if (docs.containsKey(upperToken)) {
String modKey = Main.OSX ? "\u2325\u2318" : "Ctrl + Alt + ";
String msg = "<html>" + docs.get(upperToken) + "<br><font " +
"color=\"gray\" size=\"2\">" + modKey +
"L for more.</font></html>";
result.addNotice(new Acl2ParserNotice(this,
msg, line, token, ParserNotice.INFO));
}
}
} else if (!isThm && !isIgnored && (token.type == Token.IDENTIFIER ||
token.type == Token.RESERVED_WORD || token.type == Token.RESERVED_WORD_2)
&& !constants.contains(token.getLexeme()) &&
!vars.contains(token.getLexeme())) {
Main.userData.addParseError("undeclaredVariable");
result.addNotice(new Acl2ParserNotice(this, token.getLexeme() +
" is undeclared.",
line, token, ParserNotice.ERROR));
}
token = token.getNextToken();
}
}
for (ParseListener pl : parseListeners) {
pl.wasParsed();
}
return result;
}
|
diff --git a/modules/org.restlet/src/org/restlet/engine/util/ConnegUtils.java b/modules/org.restlet/src/org/restlet/engine/util/ConnegUtils.java
index 5c7f34c09..57cf3eca6 100644
--- a/modules/org.restlet/src/org/restlet/engine/util/ConnegUtils.java
+++ b/modules/org.restlet/src/org/restlet/engine/util/ConnegUtils.java
@@ -1,109 +1,107 @@
/**
* Copyright 2005-2010 Noelios Technologies.
*
* The contents of this file are subject to the terms of one of the following
* open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the
* "Licenses"). You can select the license that you prefer but you may not use
* this file except in compliance with one of these Licenses.
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.opensource.org/licenses/lgpl-3.0.html
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.opensource.org/licenses/lgpl-2.1.php
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.opensource.org/licenses/cddl1.php
*
* You can obtain a copy of the EPL 1.0 license at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royalty free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.noelios.com/products/restlet-engine
*
* Restlet is a registered trademark of Noelios Technologies.
*/
package org.restlet.engine.util;
import java.util.List;
import org.restlet.data.ClientInfo;
import org.restlet.data.Metadata;
import org.restlet.data.Preference;
import org.restlet.representation.Variant;
import org.restlet.service.MetadataService;
/**
* Content negotiation utilities.
*
* @author Jerome Louvel
*/
public class ConnegUtils {
/**
* Returns the preferred metadata taking into account both metadata
* supported by the server and client preferences.
*
* @param supported
* The metadata supported by the server.
* @param preferences
* The client preferences.
* @return The preferred metadata.
*/
public static <T extends Metadata> T getPreferredMetadata(
List<T> supported, List<Preference<T>> preferences) {
T result = null;
float maxQuality = 0;
if (supported != null) {
for (Preference<T> pref : preferences) {
- if (pref.getQuality() > maxQuality) {
- for (T m : supported) {
- if (pref.getMetadata().includes(m)) {
- result = pref.getMetadata();
- maxQuality = pref.getQuality();
- break;
- }
+ for (T metadata : supported) {
+ if (pref.getMetadata().isCompatible(metadata)
+ && (pref.getQuality() > maxQuality)) {
+ result = metadata;
+ maxQuality = pref.getQuality();
}
}
}
}
return result;
}
/**
* Returns the best variant representation for a given resource according
* the the client preferences.<br>
* A default language is provided in case the variants don't match the
* client preferences.
*
* @param clientInfo
* The client preferences.
* @param variants
* The list of variants to compare.
* @param metadataService
* The metadata service.
* @return The preferred variant.
* @see <a
* href="http://httpd.apache.org/docs/2.2/en/content-negotiation.html#algorithm">Apache
* content negotiation algorithm</a>
*/
public static Variant getPreferredVariant(ClientInfo clientInfo,
List<? extends Variant> variants, MetadataService metadataService) {
return new Conneg(clientInfo, metadataService)
.getPreferredVariant(variants);
}
/**
* Private constructor to ensure that the class acts as a true utility class
* i.e. it isn't instantiable and extensible.
*/
private ConnegUtils() {
}
}
| true | true | public static <T extends Metadata> T getPreferredMetadata(
List<T> supported, List<Preference<T>> preferences) {
T result = null;
float maxQuality = 0;
if (supported != null) {
for (Preference<T> pref : preferences) {
if (pref.getQuality() > maxQuality) {
for (T m : supported) {
if (pref.getMetadata().includes(m)) {
result = pref.getMetadata();
maxQuality = pref.getQuality();
break;
}
}
}
}
}
return result;
}
| public static <T extends Metadata> T getPreferredMetadata(
List<T> supported, List<Preference<T>> preferences) {
T result = null;
float maxQuality = 0;
if (supported != null) {
for (Preference<T> pref : preferences) {
for (T metadata : supported) {
if (pref.getMetadata().isCompatible(metadata)
&& (pref.getQuality() > maxQuality)) {
result = metadata;
maxQuality = pref.getQuality();
}
}
}
}
return result;
}
|
diff --git a/core/resources/src/main/java/org/opennaas/core/resources/shell/ClearResourcesCommand.java b/core/resources/src/main/java/org/opennaas/core/resources/shell/ClearResourcesCommand.java
index 5ad2e85b8..6230511fb 100644
--- a/core/resources/src/main/java/org/opennaas/core/resources/shell/ClearResourcesCommand.java
+++ b/core/resources/src/main/java/org/opennaas/core/resources/shell/ClearResourcesCommand.java
@@ -1,20 +1,20 @@
package org.opennaas.core.resources.shell;
import org.apache.felix.gogo.commands.Command;
@Command(scope = "resource", name = "clear", description = "Remove all resources in the platform (stopping active ones)")
public class ClearResourcesCommand extends GenericKarafCommand {
@Override
protected Object doExecute() throws Exception {
printInitCommand("clear resources");
try {
getResourceManager().destroyAllResources();
} catch (Exception e) {
- printError("Error celaring resources");
+ printError("Error clearing resources");
printError(e);
}
printEndCommand();
return null;
}
}
| true | true | protected Object doExecute() throws Exception {
printInitCommand("clear resources");
try {
getResourceManager().destroyAllResources();
} catch (Exception e) {
printError("Error celaring resources");
printError(e);
}
printEndCommand();
return null;
}
| protected Object doExecute() throws Exception {
printInitCommand("clear resources");
try {
getResourceManager().destroyAllResources();
} catch (Exception e) {
printError("Error clearing resources");
printError(e);
}
printEndCommand();
return null;
}
|
diff --git a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/wizards/InvitationWizardUserSelection.java b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/wizards/InvitationWizardUserSelection.java
index ee1ca030e..9e51ea5d7 100644
--- a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/wizards/InvitationWizardUserSelection.java
+++ b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/wizards/InvitationWizardUserSelection.java
@@ -1,316 +1,316 @@
package de.fu_berlin.inf.dpp.ui.wizards;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.log4j.Logger;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.packet.Presence;
import de.fu_berlin.inf.dpp.Saros;
import de.fu_berlin.inf.dpp.net.IRosterListener;
import de.fu_berlin.inf.dpp.net.JID;
import de.fu_berlin.inf.dpp.net.RosterTracker;
import de.fu_berlin.inf.dpp.net.internal.DiscoveryManager;
import de.fu_berlin.inf.dpp.net.internal.DiscoveryManager.CacheMissException;
import de.fu_berlin.inf.dpp.observables.InvitationProcessObservable;
import de.fu_berlin.inf.dpp.project.internal.SharedProject;
import de.fu_berlin.inf.dpp.util.Util;
public class InvitationWizardUserSelection extends WizardPage {
private static final Logger log = Logger
.getLogger(InvitationWizardUserSelection.class);
protected Saros saros;
protected Roster roster;
protected RosterTracker rosterTracker;
protected SharedProject sharedProject;
protected IRosterListener rosterListener;
protected DiscoveryManager discoveryManager;
protected InvitationProcessObservable invitationProcesses;
protected CheckboxTableViewer userListViewer;
protected Table userListTable;
protected Button onlySaros;
protected SelectionListener onlySarosListener;
protected ISelectionChangedListener userSelectionChangedListener;
protected InvitationWizardUserSelection(Saros saros,
SharedProject sharedProject, RosterTracker rosterTracker,
DiscoveryManager discoveryManager,
InvitationProcessObservable invitationProcesses) {
super("Select users to invite");
this.saros = saros;
this.roster = saros.getRoster();
this.sharedProject = sharedProject;
this.rosterTracker = rosterTracker;
this.discoveryManager = discoveryManager;
this.invitationProcesses = invitationProcesses;
setTitle("Pariticipant selection");
setDescription("Select the users you would like to invite");
}
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(2, false));
Label projectLabel = new Label(composite, SWT.NONE);
projectLabel.setText("Project");
Text projectName = new Text(composite, SWT.READ_ONLY | SWT.SINGLE
| SWT.BORDER);
projectName
.setLayoutData(new GridData(SWT.FILL, SWT.LEFT, false, false));
projectName.setText(sharedProject.getProject().getName());
// An empty label to skip a grid.
// TODO: what about garbage collection?
new Label(composite, SWT.NONE);
userListTable = new Table(composite, SWT.BORDER | SWT.CHECK | SWT.MULTI
| SWT.FULL_SELECTION);
TableColumn userColumn = new TableColumn(userListTable, SWT.NONE);
userColumn.setWidth(250);
userColumn.setText("User");
TableColumn sarosEnabledColumn = new TableColumn(userListTable,
SWT.CENTER);
sarosEnabledColumn.setWidth(100);
sarosEnabledColumn.setText("Saros support");
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
gd.minimumHeight = 150;
userListTable.setLayoutData(gd);
userListTable.setHeaderVisible(true);
userListViewer = new CheckboxTableViewer(userListTable);
PresenceFilter presenceFilter = new PresenceFilter();
SessionFilter sessionFilter = new SessionFilter();
final SarosSupportFilter sarosFilter = new SarosSupportFilter();
- ViewerFilter[] filters = { presenceFilter, sarosFilter, sessionFilter };
+ ViewerFilter[] filters = { presenceFilter, sessionFilter };
userListViewer.setFilters(filters);
rosterListener = getRosterListener(userListViewer);
rosterTracker.addRosterListener(rosterListener);
userListViewer.setLabelProvider(new UserListLabelProvider());
userListViewer.setContentProvider(new ArrayContentProvider());
userListViewer.setInput(roster.getEntries());
// An empty label to skip a grid.
// TODO: what about garbage collection?
new Label(composite, SWT.NONE);
// CheckBox to show only users with Saros support.
onlySaros = new Button(composite, SWT.CHECK);
- onlySaros.setSelection(true);
+ onlySaros.setSelection(false);
onlySaros.setText("Hide users without Saros support");
onlySarosListener = new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
if (((Button) e.widget).getSelection()) {
userListViewer.addFilter(sarosFilter);
} else {
userListViewer.removeFilter(sarosFilter);
}
}
};
onlySaros.addSelectionListener(onlySarosListener);
// Refresh the Finish button.
userSelectionChangedListener = new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
getContainer().updateButtons();
}
};
userListViewer
.addSelectionChangedListener(userSelectionChangedListener);
setControl(composite);
}
protected class UserListLabelProvider extends LabelProvider implements
ITableLabelProvider {
public Image getColumnImage(Object element, int columnIndex) {
// there is no image for the columns
return null;
}
public String getColumnText(Object element, int columnIndex) {
RosterEntry rosterEntry = (RosterEntry) element;
final JID jid = new JID(rosterEntry.getUser());
switch (columnIndex) {
case 0:
return rosterEntry.getUser();
case 1:
boolean supported;
try {
supported = discoveryManager.isSupportedNonBlock(jid,
Saros.NAMESPACE);
} catch (CacheMissException e) {
refreshSarosSupport(jid);
return "?";
}
return supported ? "Yes" : "No";
default:
return "default value";
}
}
}
/**
* A filter which will only be passed if the user is available.
*/
protected class PresenceFilter extends ViewerFilter {
@Override
public boolean select(Viewer viewer, Object parentElement,
Object element) {
RosterEntry rosterEntry = (RosterEntry) element;
Presence presence = roster.getPresence(rosterEntry.getUser());
if (presence.isAvailable())
return true;
return false;
}
}
/**
* A filter which will only be passed if the user has Saros support.
*/
protected class SarosSupportFilter extends ViewerFilter {
@Override
public boolean select(Viewer viewer, Object parentElement,
Object element) {
RosterEntry rosterEntry = (RosterEntry) element;
JID jid = new JID(rosterEntry.getUser());
boolean sarosSupport;
try {
sarosSupport = discoveryManager.isSupportedNonBlock(jid,
Saros.NAMESPACE);
} catch (CacheMissException e) {
/**
* If no entry passes the filter, the viewer will be empty, and
* the discovery will never be triggered. So we have to trigger
* the discovery here.
*/
refreshSarosSupport(jid);
sarosSupport = true;
}
return sarosSupport;
}
}
/**
* A filter which will only be passed if the user is not in the local
* session yet and there is currently no invitation in progress.
*/
protected class SessionFilter extends ViewerFilter {
@Override
public boolean select(Viewer viewer, Object parentElement,
Object element) {
RosterEntry rosterEntry = (RosterEntry) element;
JID jid = new JID(rosterEntry.getUser());
if (sharedProject.getResourceQualifiedJID(jid) != null)
return false;
if (invitationProcesses.getInvitationProcess(jid) != null)
return false;
return true;
}
}
protected IRosterListener getRosterListener(
final CheckboxTableViewer userListViewer) {
return new IRosterListener() {
public void rosterChanged(Roster roster) {
refreshUserList();
}
public void entriesAdded(Collection<String> addresses) {
refreshUserList();
}
public void entriesDeleted(Collection<String> addresses) {
refreshUserList();
}
public void entriesUpdated(Collection<String> addresses) {
refreshUserList();
}
public void presenceChanged(Presence presence) {
refreshUserList();
}
};
}
@Override
public void dispose() {
rosterTracker.removeRosterListener(rosterListener);
onlySaros.removeSelectionListener(onlySarosListener);
super.dispose();
}
/**
* Triggers the DiscoveryManager to discover Saros supportance and refreshes
* the {@link #userListViewer}.
*
* @param jid
* The JID of the user whose saros support should be discovered.
*/
protected void refreshSarosSupport(final JID jid) {
Util.runSafeAsync(log, new Runnable() {
public void run() {
boolean supported = discoveryManager.isSarosSupported(jid);
log.debug("discovered: " + supported);
refreshUserList();
}
});
}
protected void refreshUserList() {
Util.runSafeSWTAsync(log, new Runnable() {
public void run() {
userListViewer.refresh();
}
});
}
public ArrayList<JID> getSelectedUsers() {
ArrayList<JID> selectedUsers = new ArrayList<JID>();
JID jid;
for (Object element : userListViewer.getCheckedElements()) {
jid = new JID(((RosterEntry) element).getUser());
selectedUsers.add(jid);
}
return selectedUsers;
}
}
| false | true | public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(2, false));
Label projectLabel = new Label(composite, SWT.NONE);
projectLabel.setText("Project");
Text projectName = new Text(composite, SWT.READ_ONLY | SWT.SINGLE
| SWT.BORDER);
projectName
.setLayoutData(new GridData(SWT.FILL, SWT.LEFT, false, false));
projectName.setText(sharedProject.getProject().getName());
// An empty label to skip a grid.
// TODO: what about garbage collection?
new Label(composite, SWT.NONE);
userListTable = new Table(composite, SWT.BORDER | SWT.CHECK | SWT.MULTI
| SWT.FULL_SELECTION);
TableColumn userColumn = new TableColumn(userListTable, SWT.NONE);
userColumn.setWidth(250);
userColumn.setText("User");
TableColumn sarosEnabledColumn = new TableColumn(userListTable,
SWT.CENTER);
sarosEnabledColumn.setWidth(100);
sarosEnabledColumn.setText("Saros support");
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
gd.minimumHeight = 150;
userListTable.setLayoutData(gd);
userListTable.setHeaderVisible(true);
userListViewer = new CheckboxTableViewer(userListTable);
PresenceFilter presenceFilter = new PresenceFilter();
SessionFilter sessionFilter = new SessionFilter();
final SarosSupportFilter sarosFilter = new SarosSupportFilter();
ViewerFilter[] filters = { presenceFilter, sarosFilter, sessionFilter };
userListViewer.setFilters(filters);
rosterListener = getRosterListener(userListViewer);
rosterTracker.addRosterListener(rosterListener);
userListViewer.setLabelProvider(new UserListLabelProvider());
userListViewer.setContentProvider(new ArrayContentProvider());
userListViewer.setInput(roster.getEntries());
// An empty label to skip a grid.
// TODO: what about garbage collection?
new Label(composite, SWT.NONE);
// CheckBox to show only users with Saros support.
onlySaros = new Button(composite, SWT.CHECK);
onlySaros.setSelection(true);
onlySaros.setText("Hide users without Saros support");
onlySarosListener = new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
if (((Button) e.widget).getSelection()) {
userListViewer.addFilter(sarosFilter);
} else {
userListViewer.removeFilter(sarosFilter);
}
}
};
onlySaros.addSelectionListener(onlySarosListener);
// Refresh the Finish button.
userSelectionChangedListener = new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
getContainer().updateButtons();
}
};
userListViewer
.addSelectionChangedListener(userSelectionChangedListener);
setControl(composite);
}
| public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(2, false));
Label projectLabel = new Label(composite, SWT.NONE);
projectLabel.setText("Project");
Text projectName = new Text(composite, SWT.READ_ONLY | SWT.SINGLE
| SWT.BORDER);
projectName
.setLayoutData(new GridData(SWT.FILL, SWT.LEFT, false, false));
projectName.setText(sharedProject.getProject().getName());
// An empty label to skip a grid.
// TODO: what about garbage collection?
new Label(composite, SWT.NONE);
userListTable = new Table(composite, SWT.BORDER | SWT.CHECK | SWT.MULTI
| SWT.FULL_SELECTION);
TableColumn userColumn = new TableColumn(userListTable, SWT.NONE);
userColumn.setWidth(250);
userColumn.setText("User");
TableColumn sarosEnabledColumn = new TableColumn(userListTable,
SWT.CENTER);
sarosEnabledColumn.setWidth(100);
sarosEnabledColumn.setText("Saros support");
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
gd.minimumHeight = 150;
userListTable.setLayoutData(gd);
userListTable.setHeaderVisible(true);
userListViewer = new CheckboxTableViewer(userListTable);
PresenceFilter presenceFilter = new PresenceFilter();
SessionFilter sessionFilter = new SessionFilter();
final SarosSupportFilter sarosFilter = new SarosSupportFilter();
ViewerFilter[] filters = { presenceFilter, sessionFilter };
userListViewer.setFilters(filters);
rosterListener = getRosterListener(userListViewer);
rosterTracker.addRosterListener(rosterListener);
userListViewer.setLabelProvider(new UserListLabelProvider());
userListViewer.setContentProvider(new ArrayContentProvider());
userListViewer.setInput(roster.getEntries());
// An empty label to skip a grid.
// TODO: what about garbage collection?
new Label(composite, SWT.NONE);
// CheckBox to show only users with Saros support.
onlySaros = new Button(composite, SWT.CHECK);
onlySaros.setSelection(false);
onlySaros.setText("Hide users without Saros support");
onlySarosListener = new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
if (((Button) e.widget).getSelection()) {
userListViewer.addFilter(sarosFilter);
} else {
userListViewer.removeFilter(sarosFilter);
}
}
};
onlySaros.addSelectionListener(onlySarosListener);
// Refresh the Finish button.
userSelectionChangedListener = new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
getContainer().updateButtons();
}
};
userListViewer
.addSelectionChangedListener(userSelectionChangedListener);
setControl(composite);
}
|
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/web/resources/NamenodeWebHdfsMethods.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/web/resources/NamenodeWebHdfsMethods.java
index 97ae5f0a4..e90d6fb7d 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/web/resources/NamenodeWebHdfsMethods.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/web/resources/NamenodeWebHdfsMethods.java
@@ -1,640 +1,640 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.namenode.web.resources;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.PrivilegedExceptionAction;
import java.util.EnumSet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.ContentSummary;
import org.apache.hadoop.fs.Options;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.DirectoryListing;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenSecretManager;
import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor;
import org.apache.hadoop.hdfs.server.common.JspHelper;
import org.apache.hadoop.hdfs.server.namenode.NameNode;
import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocols;
import org.apache.hadoop.hdfs.web.JsonUtil;
import org.apache.hadoop.hdfs.web.ParamFilter;
import org.apache.hadoop.hdfs.web.WebHdfsFileSystem;
import org.apache.hadoop.hdfs.web.resources.AccessTimeParam;
import org.apache.hadoop.hdfs.web.resources.BlockSizeParam;
import org.apache.hadoop.hdfs.web.resources.BufferSizeParam;
import org.apache.hadoop.hdfs.web.resources.DelegationParam;
import org.apache.hadoop.hdfs.web.resources.DeleteOpParam;
import org.apache.hadoop.hdfs.web.resources.DestinationParam;
import org.apache.hadoop.hdfs.web.resources.GetOpParam;
import org.apache.hadoop.hdfs.web.resources.GroupParam;
import org.apache.hadoop.hdfs.web.resources.HttpOpParam;
import org.apache.hadoop.hdfs.web.resources.LengthParam;
import org.apache.hadoop.hdfs.web.resources.ModificationTimeParam;
import org.apache.hadoop.hdfs.web.resources.OffsetParam;
import org.apache.hadoop.hdfs.web.resources.OverwriteParam;
import org.apache.hadoop.hdfs.web.resources.OwnerParam;
import org.apache.hadoop.hdfs.web.resources.Param;
import org.apache.hadoop.hdfs.web.resources.PermissionParam;
import org.apache.hadoop.hdfs.web.resources.PostOpParam;
import org.apache.hadoop.hdfs.web.resources.PutOpParam;
import org.apache.hadoop.hdfs.web.resources.RecursiveParam;
import org.apache.hadoop.hdfs.web.resources.RenameOptionSetParam;
import org.apache.hadoop.hdfs.web.resources.RenewerParam;
import org.apache.hadoop.hdfs.web.resources.ReplicationParam;
import org.apache.hadoop.hdfs.web.resources.UriFsPathParam;
import org.apache.hadoop.hdfs.web.resources.UserParam;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.net.NodeBase;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.TokenIdentifier;
import com.sun.jersey.spi.container.ResourceFilters;
/** Web-hdfs NameNode implementation. */
@Path("")
@ResourceFilters(ParamFilter.class)
public class NamenodeWebHdfsMethods {
public static final Log LOG = LogFactory.getLog(NamenodeWebHdfsMethods.class);
private static final UriFsPathParam ROOT = new UriFsPathParam("");
private static final ThreadLocal<String> REMOTE_ADDRESS = new ThreadLocal<String>();
/** @return the remote client address. */
public static String getRemoteAddress() {
return REMOTE_ADDRESS.get();
}
private @Context ServletContext context;
private @Context HttpServletRequest request;
private @Context HttpServletResponse response;
private static DatanodeInfo chooseDatanode(final NameNode namenode,
final String path, final HttpOpParam.Op op, final long openOffset
) throws IOException {
if (op == GetOpParam.Op.OPEN
|| op == GetOpParam.Op.GETFILECHECKSUM
|| op == PostOpParam.Op.APPEND) {
final NamenodeProtocols np = namenode.getRpcServer();
final HdfsFileStatus status = np.getFileInfo(path);
if (status == null) {
throw new FileNotFoundException("File " + path + " not found.");
}
final long len = status.getLen();
if (op == GetOpParam.Op.OPEN && (openOffset < 0L || openOffset >= len)) {
throw new IOException("Offset=" + openOffset + " out of the range [0, "
+ len + "); " + op + ", path=" + path);
}
if (len > 0) {
final long offset = op == GetOpParam.Op.OPEN? openOffset: len - 1;
final LocatedBlocks locations = np.getBlockLocations(path, offset, 1);
final int count = locations.locatedBlockCount();
if (count > 0) {
return JspHelper.bestNode(locations.get(0));
}
}
}
return (DatanodeDescriptor)namenode.getNamesystem().getBlockManager(
).getDatanodeManager().getNetworkTopology().chooseRandom(
NodeBase.ROOT);
}
private Token<? extends TokenIdentifier> generateDelegationToken(
final NameNode namenode, final UserGroupInformation ugi,
final String renewer) throws IOException {
final Credentials c = DelegationTokenSecretManager.createCredentials(
namenode, ugi,
renewer != null? renewer: request.getUserPrincipal().getName());
final Token<? extends TokenIdentifier> t = c.getAllTokens().iterator().next();
t.setService(new Text(SecurityUtil.buildDTServiceName(
NameNode.getUri(namenode.getNameNodeAddress()),
NameNode.DEFAULT_PORT)));
return t;
}
private URI redirectURI(final NameNode namenode,
final UserGroupInformation ugi, final DelegationParam delegation,
final String path, final HttpOpParam.Op op, final long openOffset,
final Param<?, ?>... parameters) throws URISyntaxException, IOException {
final DatanodeInfo dn = chooseDatanode(namenode, path, op, openOffset);
final String delegationQuery;
if (!UserGroupInformation.isSecurityEnabled()) {
//security disabled
delegationQuery = "";
} else if (delegation.getValue() != null) {
//client has provided a token
delegationQuery = "&" + delegation;
} else {
//generate a token
final Token<? extends TokenIdentifier> t = generateDelegationToken(
namenode, ugi, request.getUserPrincipal().getName());
delegationQuery = "&" + new DelegationParam(t.encodeToUrlString());
}
final String query = op.toQueryString()
+ '&' + new UserParam(ugi) + delegationQuery
+ Param.toSortedString("&", parameters);
final String uripath = WebHdfsFileSystem.PATH_PREFIX + path;
final URI uri = new URI("http", null, dn.getHostName(), dn.getInfoPort(),
uripath, query, null);
if (LOG.isTraceEnabled()) {
LOG.trace("redirectURI=" + uri);
}
return uri;
}
/** Handle HTTP PUT request for the root. */
@PUT
@Path("/")
@Consumes({"*/*"})
@Produces({MediaType.APPLICATION_JSON})
public Response putRoot(
@Context final UserGroupInformation ugi,
@QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
final DelegationParam delegation,
@QueryParam(PutOpParam.NAME) @DefaultValue(PutOpParam.DEFAULT)
final PutOpParam op,
@QueryParam(DestinationParam.NAME) @DefaultValue(DestinationParam.DEFAULT)
final DestinationParam destination,
@QueryParam(OwnerParam.NAME) @DefaultValue(OwnerParam.DEFAULT)
final OwnerParam owner,
@QueryParam(GroupParam.NAME) @DefaultValue(GroupParam.DEFAULT)
final GroupParam group,
@QueryParam(PermissionParam.NAME) @DefaultValue(PermissionParam.DEFAULT)
final PermissionParam permission,
@QueryParam(OverwriteParam.NAME) @DefaultValue(OverwriteParam.DEFAULT)
final OverwriteParam overwrite,
@QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT)
final BufferSizeParam bufferSize,
@QueryParam(ReplicationParam.NAME) @DefaultValue(ReplicationParam.DEFAULT)
final ReplicationParam replication,
@QueryParam(BlockSizeParam.NAME) @DefaultValue(BlockSizeParam.DEFAULT)
final BlockSizeParam blockSize,
@QueryParam(ModificationTimeParam.NAME) @DefaultValue(ModificationTimeParam.DEFAULT)
final ModificationTimeParam modificationTime,
@QueryParam(AccessTimeParam.NAME) @DefaultValue(AccessTimeParam.DEFAULT)
final AccessTimeParam accessTime,
@QueryParam(RenameOptionSetParam.NAME) @DefaultValue(RenameOptionSetParam.DEFAULT)
final RenameOptionSetParam renameOptions
) throws IOException, InterruptedException {
return put(ugi, delegation, ROOT, op, destination, owner, group,
permission, overwrite, bufferSize, replication, blockSize,
modificationTime, accessTime, renameOptions);
}
/** Handle HTTP PUT request. */
@PUT
@Path("{" + UriFsPathParam.NAME + ":.*}")
@Consumes({"*/*"})
@Produces({MediaType.APPLICATION_JSON})
public Response put(
@Context final UserGroupInformation ugi,
@QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
final DelegationParam delegation,
@PathParam(UriFsPathParam.NAME) final UriFsPathParam path,
@QueryParam(PutOpParam.NAME) @DefaultValue(PutOpParam.DEFAULT)
final PutOpParam op,
@QueryParam(DestinationParam.NAME) @DefaultValue(DestinationParam.DEFAULT)
final DestinationParam destination,
@QueryParam(OwnerParam.NAME) @DefaultValue(OwnerParam.DEFAULT)
final OwnerParam owner,
@QueryParam(GroupParam.NAME) @DefaultValue(GroupParam.DEFAULT)
final GroupParam group,
@QueryParam(PermissionParam.NAME) @DefaultValue(PermissionParam.DEFAULT)
final PermissionParam permission,
@QueryParam(OverwriteParam.NAME) @DefaultValue(OverwriteParam.DEFAULT)
final OverwriteParam overwrite,
@QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT)
final BufferSizeParam bufferSize,
@QueryParam(ReplicationParam.NAME) @DefaultValue(ReplicationParam.DEFAULT)
final ReplicationParam replication,
@QueryParam(BlockSizeParam.NAME) @DefaultValue(BlockSizeParam.DEFAULT)
final BlockSizeParam blockSize,
@QueryParam(ModificationTimeParam.NAME) @DefaultValue(ModificationTimeParam.DEFAULT)
final ModificationTimeParam modificationTime,
@QueryParam(AccessTimeParam.NAME) @DefaultValue(AccessTimeParam.DEFAULT)
final AccessTimeParam accessTime,
@QueryParam(RenameOptionSetParam.NAME) @DefaultValue(RenameOptionSetParam.DEFAULT)
final RenameOptionSetParam renameOptions
) throws IOException, InterruptedException {
if (LOG.isTraceEnabled()) {
LOG.trace(op + ": " + path + ", ugi=" + ugi
+ Param.toSortedString(", ", destination, owner, group, permission,
overwrite, bufferSize, replication, blockSize,
modificationTime, accessTime, renameOptions));
}
//clear content type
response.setContentType(null);
return ugi.doAs(new PrivilegedExceptionAction<Response>() {
@Override
public Response run() throws IOException, URISyntaxException {
REMOTE_ADDRESS.set(request.getRemoteAddr());
try {
final String fullpath = path.getAbsolutePath();
final Configuration conf = (Configuration)context.getAttribute(JspHelper.CURRENT_CONF);
final NameNode namenode = (NameNode)context.getAttribute("name.node");
final NamenodeProtocols np = namenode.getRpcServer();
switch(op.getValue()) {
case CREATE:
{
final URI uri = redirectURI(namenode, ugi, delegation, fullpath,
op.getValue(), -1L,
permission, overwrite, bufferSize, replication, blockSize);
return Response.temporaryRedirect(uri).build();
}
case MKDIRS:
{
final boolean b = np.mkdirs(fullpath, permission.getFsPermission(), true);
final String js = JsonUtil.toJsonString("boolean", b);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
case RENAME:
{
final EnumSet<Options.Rename> s = renameOptions.getValue();
if (s.isEmpty()) {
final boolean b = np.rename(fullpath, destination.getValue());
final String js = JsonUtil.toJsonString("boolean", b);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
} else {
- np.rename(fullpath, dstPath.getValue(),
+ np.rename(fullpath, destination.getValue(),
s.toArray(new Options.Rename[s.size()]));
return Response.ok().type(MediaType.APPLICATION_JSON).build();
}
}
case SETREPLICATION:
{
final boolean b = np.setReplication(fullpath, replication.getValue(conf));
final String js = JsonUtil.toJsonString("boolean", b);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
case SETOWNER:
{
np.setOwner(fullpath, owner.getValue(), group.getValue());
return Response.ok().type(MediaType.APPLICATION_JSON).build();
}
case SETPERMISSION:
{
np.setPermission(fullpath, permission.getFsPermission());
return Response.ok().type(MediaType.APPLICATION_JSON).build();
}
case SETTIMES:
{
np.setTimes(fullpath, modificationTime.getValue(), accessTime.getValue());
return Response.ok().type(MediaType.APPLICATION_JSON).build();
}
default:
throw new UnsupportedOperationException(op + " is not supported");
}
} finally {
REMOTE_ADDRESS.set(null);
}
}
});
}
/** Handle HTTP POST request for the root. */
@POST
@Path("/")
@Consumes({"*/*"})
@Produces({MediaType.APPLICATION_JSON})
public Response postRoot(
@Context final UserGroupInformation ugi,
@QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
final DelegationParam delegation,
@QueryParam(PostOpParam.NAME) @DefaultValue(PostOpParam.DEFAULT)
final PostOpParam op,
@QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT)
final BufferSizeParam bufferSize
) throws IOException, InterruptedException {
return post(ugi, delegation, ROOT, op, bufferSize);
}
/** Handle HTTP POST request. */
@POST
@Path("{" + UriFsPathParam.NAME + ":.*}")
@Consumes({"*/*"})
@Produces({MediaType.APPLICATION_JSON})
public Response post(
@Context final UserGroupInformation ugi,
@QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
final DelegationParam delegation,
@PathParam(UriFsPathParam.NAME) final UriFsPathParam path,
@QueryParam(PostOpParam.NAME) @DefaultValue(PostOpParam.DEFAULT)
final PostOpParam op,
@QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT)
final BufferSizeParam bufferSize
) throws IOException, InterruptedException {
if (LOG.isTraceEnabled()) {
LOG.trace(op + ": " + path + ", ugi=" + ugi
+ Param.toSortedString(", ", bufferSize));
}
//clear content type
response.setContentType(null);
return ugi.doAs(new PrivilegedExceptionAction<Response>() {
@Override
public Response run() throws IOException, URISyntaxException {
REMOTE_ADDRESS.set(request.getRemoteAddr());
try {
final String fullpath = path.getAbsolutePath();
final NameNode namenode = (NameNode)context.getAttribute("name.node");
switch(op.getValue()) {
case APPEND:
{
final URI uri = redirectURI(namenode, ugi, delegation, fullpath,
op.getValue(), -1L, bufferSize);
return Response.temporaryRedirect(uri).build();
}
default:
throw new UnsupportedOperationException(op + " is not supported");
}
} finally {
REMOTE_ADDRESS.set(null);
}
}
});
}
/** Handle HTTP GET request for the root. */
@GET
@Path("/")
@Produces({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON})
public Response getRoot(
@Context final UserGroupInformation ugi,
@QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
final DelegationParam delegation,
@QueryParam(GetOpParam.NAME) @DefaultValue(GetOpParam.DEFAULT)
final GetOpParam op,
@QueryParam(OffsetParam.NAME) @DefaultValue(OffsetParam.DEFAULT)
final OffsetParam offset,
@QueryParam(LengthParam.NAME) @DefaultValue(LengthParam.DEFAULT)
final LengthParam length,
@QueryParam(RenewerParam.NAME) @DefaultValue(RenewerParam.DEFAULT)
final RenewerParam renewer,
@QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT)
final BufferSizeParam bufferSize
) throws IOException, URISyntaxException, InterruptedException {
return get(ugi, delegation, ROOT, op, offset, length, renewer, bufferSize);
}
/** Handle HTTP GET request. */
@GET
@Path("{" + UriFsPathParam.NAME + ":.*}")
@Produces({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON})
public Response get(
@Context final UserGroupInformation ugi,
@QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
final DelegationParam delegation,
@PathParam(UriFsPathParam.NAME) final UriFsPathParam path,
@QueryParam(GetOpParam.NAME) @DefaultValue(GetOpParam.DEFAULT)
final GetOpParam op,
@QueryParam(OffsetParam.NAME) @DefaultValue(OffsetParam.DEFAULT)
final OffsetParam offset,
@QueryParam(LengthParam.NAME) @DefaultValue(LengthParam.DEFAULT)
final LengthParam length,
@QueryParam(RenewerParam.NAME) @DefaultValue(RenewerParam.DEFAULT)
final RenewerParam renewer,
@QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT)
final BufferSizeParam bufferSize
) throws IOException, InterruptedException {
if (LOG.isTraceEnabled()) {
LOG.trace(op + ": " + path + ", ugi=" + ugi
+ Param.toSortedString(", ", offset, length, renewer, bufferSize));
}
//clear content type
response.setContentType(null);
return ugi.doAs(new PrivilegedExceptionAction<Response>() {
@Override
public Response run() throws IOException, URISyntaxException {
REMOTE_ADDRESS.set(request.getRemoteAddr());
try {
final NameNode namenode = (NameNode)context.getAttribute("name.node");
final String fullpath = path.getAbsolutePath();
final NamenodeProtocols np = namenode.getRpcServer();
switch(op.getValue()) {
case OPEN:
{
final URI uri = redirectURI(namenode, ugi, delegation, fullpath,
op.getValue(), offset.getValue(), offset, length, bufferSize);
return Response.temporaryRedirect(uri).build();
}
case GETFILEBLOCKLOCATIONS:
{
final long offsetValue = offset.getValue();
final Long lengthValue = length.getValue();
final LocatedBlocks locatedblocks = np.getBlockLocations(fullpath,
offsetValue, lengthValue != null? lengthValue: offsetValue + 1);
final String js = JsonUtil.toJsonString(locatedblocks);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
case GETFILESTATUS:
{
final HdfsFileStatus status = np.getFileInfo(fullpath);
final String js = JsonUtil.toJsonString(status, true);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
case LISTSTATUS:
{
final StreamingOutput streaming = getListingStream(np, fullpath);
return Response.ok(streaming).type(MediaType.APPLICATION_JSON).build();
}
case GETCONTENTSUMMARY:
{
final ContentSummary contentsummary = np.getContentSummary(fullpath);
final String js = JsonUtil.toJsonString(contentsummary);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
case GETFILECHECKSUM:
{
final URI uri = redirectURI(namenode, ugi, delegation, fullpath,
op.getValue(), -1L);
return Response.temporaryRedirect(uri).build();
}
case GETDELEGATIONTOKEN:
{
final Token<? extends TokenIdentifier> token = generateDelegationToken(
namenode, ugi, renewer.getValue());
final String js = JsonUtil.toJsonString(token);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
default:
throw new UnsupportedOperationException(op + " is not supported");
}
} finally {
REMOTE_ADDRESS.set(null);
}
}
});
}
private static DirectoryListing getDirectoryListing(final NamenodeProtocols np,
final String p, byte[] startAfter) throws IOException {
final DirectoryListing listing = np.getListing(p, startAfter, false);
if (listing == null) { // the directory does not exist
throw new FileNotFoundException("File " + p + " does not exist.");
}
return listing;
}
private static StreamingOutput getListingStream(final NamenodeProtocols np,
final String p) throws IOException {
final DirectoryListing first = getDirectoryListing(np, p,
HdfsFileStatus.EMPTY_NAME);
return new StreamingOutput() {
@Override
public void write(final OutputStream outstream) throws IOException {
final PrintStream out = new PrintStream(outstream);
out.println("{\"" + HdfsFileStatus.class.getSimpleName() + "es\":{\""
+ HdfsFileStatus.class.getSimpleName() + "\":[");
final HdfsFileStatus[] partial = first.getPartialListing();
if (partial.length > 0) {
out.print(JsonUtil.toJsonString(partial[0], false));
}
for(int i = 1; i < partial.length; i++) {
out.println(',');
out.print(JsonUtil.toJsonString(partial[i], false));
}
for(DirectoryListing curr = first; curr.hasMore(); ) {
curr = getDirectoryListing(np, p, curr.getLastName());
for(HdfsFileStatus s : curr.getPartialListing()) {
out.println(',');
out.print(JsonUtil.toJsonString(s, false));
}
}
out.println();
out.println("]}}");
}
};
}
/** Handle HTTP DELETE request for the root. */
@DELETE
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public Response deleteRoot(
@Context final UserGroupInformation ugi,
@QueryParam(DeleteOpParam.NAME) @DefaultValue(DeleteOpParam.DEFAULT)
final DeleteOpParam op,
@QueryParam(RecursiveParam.NAME) @DefaultValue(RecursiveParam.DEFAULT)
final RecursiveParam recursive
) throws IOException, InterruptedException {
return delete(ugi, ROOT, op, recursive);
}
/** Handle HTTP DELETE request. */
@DELETE
@Path("{" + UriFsPathParam.NAME + ":.*}")
@Produces(MediaType.APPLICATION_JSON)
public Response delete(
@Context final UserGroupInformation ugi,
@PathParam(UriFsPathParam.NAME) final UriFsPathParam path,
@QueryParam(DeleteOpParam.NAME) @DefaultValue(DeleteOpParam.DEFAULT)
final DeleteOpParam op,
@QueryParam(RecursiveParam.NAME) @DefaultValue(RecursiveParam.DEFAULT)
final RecursiveParam recursive
) throws IOException, InterruptedException {
if (LOG.isTraceEnabled()) {
LOG.trace(op + ": " + path + ", ugi=" + ugi
+ Param.toSortedString(", ", recursive));
}
//clear content type
response.setContentType(null);
return ugi.doAs(new PrivilegedExceptionAction<Response>() {
@Override
public Response run() throws IOException {
REMOTE_ADDRESS.set(request.getRemoteAddr());
try {
final NameNode namenode = (NameNode)context.getAttribute("name.node");
final String fullpath = path.getAbsolutePath();
switch(op.getValue()) {
case DELETE:
{
final boolean b = namenode.getRpcServer().delete(fullpath, recursive.getValue());
final String js = JsonUtil.toJsonString("boolean", b);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
default:
throw new UnsupportedOperationException(op + " is not supported");
}
} finally {
REMOTE_ADDRESS.set(null);
}
}
});
}
}
| true | true | public Response put(
@Context final UserGroupInformation ugi,
@QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
final DelegationParam delegation,
@PathParam(UriFsPathParam.NAME) final UriFsPathParam path,
@QueryParam(PutOpParam.NAME) @DefaultValue(PutOpParam.DEFAULT)
final PutOpParam op,
@QueryParam(DestinationParam.NAME) @DefaultValue(DestinationParam.DEFAULT)
final DestinationParam destination,
@QueryParam(OwnerParam.NAME) @DefaultValue(OwnerParam.DEFAULT)
final OwnerParam owner,
@QueryParam(GroupParam.NAME) @DefaultValue(GroupParam.DEFAULT)
final GroupParam group,
@QueryParam(PermissionParam.NAME) @DefaultValue(PermissionParam.DEFAULT)
final PermissionParam permission,
@QueryParam(OverwriteParam.NAME) @DefaultValue(OverwriteParam.DEFAULT)
final OverwriteParam overwrite,
@QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT)
final BufferSizeParam bufferSize,
@QueryParam(ReplicationParam.NAME) @DefaultValue(ReplicationParam.DEFAULT)
final ReplicationParam replication,
@QueryParam(BlockSizeParam.NAME) @DefaultValue(BlockSizeParam.DEFAULT)
final BlockSizeParam blockSize,
@QueryParam(ModificationTimeParam.NAME) @DefaultValue(ModificationTimeParam.DEFAULT)
final ModificationTimeParam modificationTime,
@QueryParam(AccessTimeParam.NAME) @DefaultValue(AccessTimeParam.DEFAULT)
final AccessTimeParam accessTime,
@QueryParam(RenameOptionSetParam.NAME) @DefaultValue(RenameOptionSetParam.DEFAULT)
final RenameOptionSetParam renameOptions
) throws IOException, InterruptedException {
if (LOG.isTraceEnabled()) {
LOG.trace(op + ": " + path + ", ugi=" + ugi
+ Param.toSortedString(", ", destination, owner, group, permission,
overwrite, bufferSize, replication, blockSize,
modificationTime, accessTime, renameOptions));
}
//clear content type
response.setContentType(null);
return ugi.doAs(new PrivilegedExceptionAction<Response>() {
@Override
public Response run() throws IOException, URISyntaxException {
REMOTE_ADDRESS.set(request.getRemoteAddr());
try {
final String fullpath = path.getAbsolutePath();
final Configuration conf = (Configuration)context.getAttribute(JspHelper.CURRENT_CONF);
final NameNode namenode = (NameNode)context.getAttribute("name.node");
final NamenodeProtocols np = namenode.getRpcServer();
switch(op.getValue()) {
case CREATE:
{
final URI uri = redirectURI(namenode, ugi, delegation, fullpath,
op.getValue(), -1L,
permission, overwrite, bufferSize, replication, blockSize);
return Response.temporaryRedirect(uri).build();
}
case MKDIRS:
{
final boolean b = np.mkdirs(fullpath, permission.getFsPermission(), true);
final String js = JsonUtil.toJsonString("boolean", b);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
case RENAME:
{
final EnumSet<Options.Rename> s = renameOptions.getValue();
if (s.isEmpty()) {
final boolean b = np.rename(fullpath, destination.getValue());
final String js = JsonUtil.toJsonString("boolean", b);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
} else {
np.rename(fullpath, dstPath.getValue(),
s.toArray(new Options.Rename[s.size()]));
return Response.ok().type(MediaType.APPLICATION_JSON).build();
}
}
case SETREPLICATION:
{
final boolean b = np.setReplication(fullpath, replication.getValue(conf));
final String js = JsonUtil.toJsonString("boolean", b);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
case SETOWNER:
{
np.setOwner(fullpath, owner.getValue(), group.getValue());
return Response.ok().type(MediaType.APPLICATION_JSON).build();
}
case SETPERMISSION:
{
np.setPermission(fullpath, permission.getFsPermission());
return Response.ok().type(MediaType.APPLICATION_JSON).build();
}
case SETTIMES:
{
np.setTimes(fullpath, modificationTime.getValue(), accessTime.getValue());
return Response.ok().type(MediaType.APPLICATION_JSON).build();
}
default:
throw new UnsupportedOperationException(op + " is not supported");
}
} finally {
REMOTE_ADDRESS.set(null);
}
}
});
}
| public Response put(
@Context final UserGroupInformation ugi,
@QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
final DelegationParam delegation,
@PathParam(UriFsPathParam.NAME) final UriFsPathParam path,
@QueryParam(PutOpParam.NAME) @DefaultValue(PutOpParam.DEFAULT)
final PutOpParam op,
@QueryParam(DestinationParam.NAME) @DefaultValue(DestinationParam.DEFAULT)
final DestinationParam destination,
@QueryParam(OwnerParam.NAME) @DefaultValue(OwnerParam.DEFAULT)
final OwnerParam owner,
@QueryParam(GroupParam.NAME) @DefaultValue(GroupParam.DEFAULT)
final GroupParam group,
@QueryParam(PermissionParam.NAME) @DefaultValue(PermissionParam.DEFAULT)
final PermissionParam permission,
@QueryParam(OverwriteParam.NAME) @DefaultValue(OverwriteParam.DEFAULT)
final OverwriteParam overwrite,
@QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT)
final BufferSizeParam bufferSize,
@QueryParam(ReplicationParam.NAME) @DefaultValue(ReplicationParam.DEFAULT)
final ReplicationParam replication,
@QueryParam(BlockSizeParam.NAME) @DefaultValue(BlockSizeParam.DEFAULT)
final BlockSizeParam blockSize,
@QueryParam(ModificationTimeParam.NAME) @DefaultValue(ModificationTimeParam.DEFAULT)
final ModificationTimeParam modificationTime,
@QueryParam(AccessTimeParam.NAME) @DefaultValue(AccessTimeParam.DEFAULT)
final AccessTimeParam accessTime,
@QueryParam(RenameOptionSetParam.NAME) @DefaultValue(RenameOptionSetParam.DEFAULT)
final RenameOptionSetParam renameOptions
) throws IOException, InterruptedException {
if (LOG.isTraceEnabled()) {
LOG.trace(op + ": " + path + ", ugi=" + ugi
+ Param.toSortedString(", ", destination, owner, group, permission,
overwrite, bufferSize, replication, blockSize,
modificationTime, accessTime, renameOptions));
}
//clear content type
response.setContentType(null);
return ugi.doAs(new PrivilegedExceptionAction<Response>() {
@Override
public Response run() throws IOException, URISyntaxException {
REMOTE_ADDRESS.set(request.getRemoteAddr());
try {
final String fullpath = path.getAbsolutePath();
final Configuration conf = (Configuration)context.getAttribute(JspHelper.CURRENT_CONF);
final NameNode namenode = (NameNode)context.getAttribute("name.node");
final NamenodeProtocols np = namenode.getRpcServer();
switch(op.getValue()) {
case CREATE:
{
final URI uri = redirectURI(namenode, ugi, delegation, fullpath,
op.getValue(), -1L,
permission, overwrite, bufferSize, replication, blockSize);
return Response.temporaryRedirect(uri).build();
}
case MKDIRS:
{
final boolean b = np.mkdirs(fullpath, permission.getFsPermission(), true);
final String js = JsonUtil.toJsonString("boolean", b);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
case RENAME:
{
final EnumSet<Options.Rename> s = renameOptions.getValue();
if (s.isEmpty()) {
final boolean b = np.rename(fullpath, destination.getValue());
final String js = JsonUtil.toJsonString("boolean", b);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
} else {
np.rename(fullpath, destination.getValue(),
s.toArray(new Options.Rename[s.size()]));
return Response.ok().type(MediaType.APPLICATION_JSON).build();
}
}
case SETREPLICATION:
{
final boolean b = np.setReplication(fullpath, replication.getValue(conf));
final String js = JsonUtil.toJsonString("boolean", b);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
case SETOWNER:
{
np.setOwner(fullpath, owner.getValue(), group.getValue());
return Response.ok().type(MediaType.APPLICATION_JSON).build();
}
case SETPERMISSION:
{
np.setPermission(fullpath, permission.getFsPermission());
return Response.ok().type(MediaType.APPLICATION_JSON).build();
}
case SETTIMES:
{
np.setTimes(fullpath, modificationTime.getValue(), accessTime.getValue());
return Response.ok().type(MediaType.APPLICATION_JSON).build();
}
default:
throw new UnsupportedOperationException(op + " is not supported");
}
} finally {
REMOTE_ADDRESS.set(null);
}
}
});
}
|
diff --git a/src/edu/uwm/ai/search/agent/SearchEntity.java b/src/edu/uwm/ai/search/agent/SearchEntity.java
index c6680c3..f02a056 100644
--- a/src/edu/uwm/ai/search/agent/SearchEntity.java
+++ b/src/edu/uwm/ai/search/agent/SearchEntity.java
@@ -1,130 +1,131 @@
/*
* This file is part of the search package.
*
* Copyright (C) 2012, Eric Fritz
* Copyright (C) 2012, Reed Johnson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package edu.uwm.ai.search.agent;
import java.util.List;
import processing.core.PApplet;
import edu.uwm.ai.search.World;
import edu.uwm.ai.search.search.SearchAlgorithm;
import edu.uwm.ai.search.search.SearchResult;
import edu.uwm.ai.search.util.Point;
/**
* @author Eric Fritz
* @author Reed Johnson
*/
public class SearchEntity extends Entity
{
private PApplet parent;
private int c;
private Entity e;
private SearchAlgorithm algorithm;
private List<Point> path;
private Point lastGoal;
private int pCost;
private int tCost;
private double pTime;
private double tTime;
private int totalSearches;
// TODO - store costs and draw them
public SearchEntity(PApplet parent, World w, Point p, int c, Entity e, SearchAlgorithm algorithm)
{
super(parent, w, p, c);
this.parent = parent;
this.c = c;
this.e = e;
this.algorithm = algorithm;
}
@Override
public void draw()
{
super.draw();
parent.fill(0);
parent.stroke(c);
int dimW = getWorld().getBlockWidth();
int dimH = getWorld().getBlockHeight();
int halfW = dimW / 2;
int halfH = dimH / 2;
if (path != null && !path.isEmpty()) {
Point a = getPoint();
int i = 0;
while (i < path.size()) {
Point b = path.get(i);
parent.line(a.getX() * dimW + halfW, a.getY() * dimH + halfH, b.getX() * dimW + halfW, b.getY() * dimH + halfH);
i++;
a = b;
}
}
}
public String getResults()
{
return String.format("[%3s] %8.2fms, %8.2fms total, %8.2fms avg, %6d nodes expanded, %6d total, %6d avg", algorithm, pTime, tTime, totalSearches == 0 ? 0 : (tTime / totalSearches), pCost, tCost, totalSearches == 0 ? 0 : (tCost / totalSearches));
}
public void update()
{
if (getPoint().equals(e.getPoint())) {
+ path.clear();
return;
}
if (path == null || path.isEmpty() || (lastGoal != null && !lastGoal.equals(e.getPoint()))) {
lastGoal = new Point(e.getPoint());
long st = System.nanoTime();
SearchResult result = algorithm.search(getPoint(), e.getPoint());
pTime = (System.nanoTime() - st) / 1e6;
pCost = result.getNumberNodesExpanded();
path = result.getPath();
if (!path.isEmpty()) {
tTime += pTime;
tCost += pCost;
totalSearches++;
if (!path.isEmpty()) {
path.remove(0);
}
}
}
if (!path.isEmpty()) {
moveTo(path.remove(0));
}
}
}
| true | true | public void update()
{
if (getPoint().equals(e.getPoint())) {
return;
}
if (path == null || path.isEmpty() || (lastGoal != null && !lastGoal.equals(e.getPoint()))) {
lastGoal = new Point(e.getPoint());
long st = System.nanoTime();
SearchResult result = algorithm.search(getPoint(), e.getPoint());
pTime = (System.nanoTime() - st) / 1e6;
pCost = result.getNumberNodesExpanded();
path = result.getPath();
if (!path.isEmpty()) {
tTime += pTime;
tCost += pCost;
totalSearches++;
if (!path.isEmpty()) {
path.remove(0);
}
}
}
if (!path.isEmpty()) {
moveTo(path.remove(0));
}
}
| public void update()
{
if (getPoint().equals(e.getPoint())) {
path.clear();
return;
}
if (path == null || path.isEmpty() || (lastGoal != null && !lastGoal.equals(e.getPoint()))) {
lastGoal = new Point(e.getPoint());
long st = System.nanoTime();
SearchResult result = algorithm.search(getPoint(), e.getPoint());
pTime = (System.nanoTime() - st) / 1e6;
pCost = result.getNumberNodesExpanded();
path = result.getPath();
if (!path.isEmpty()) {
tTime += pTime;
tCost += pCost;
totalSearches++;
if (!path.isEmpty()) {
path.remove(0);
}
}
}
if (!path.isEmpty()) {
moveTo(path.remove(0));
}
}
|
diff --git a/testservice/src/com/baidu/cafe/remote/Arms.java b/testservice/src/com/baidu/cafe/remote/Arms.java
index f888ada..58ed740 100644
--- a/testservice/src/com/baidu/cafe/remote/Arms.java
+++ b/testservice/src/com/baidu/cafe/remote/Arms.java
@@ -1,158 +1,158 @@
/*
* Copyright (C) 2011 Baidu.com Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baidu.cafe.remote;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
/**
* This class provides autotest assistance by AIDL+Service, including the
* following features: 1. file system 2. power 3. connectivity 4. telephony
* 5.storage 6. system 7. appbasic 8. media
*
* @author [email protected]
* @date 2011-06-20
* @version
* @todo
*/
public class Arms extends Service {
public Arms() {
}
@Override
public IBinder onBind(Intent intent) {
Log.print("service bind!");
return new ArmsBinder(this);
}
@Override
public void onCreate() {
super.onCreate();
// close for android.provider.Settings$SettingNotFoundException: adb_enabled
// keepAdb();
}
/*
* adb shell am startservice -a com.baidu.cafe.remote.action.name.COMMAND
* -e function "waitforTopActivity" -e parameter "String:com.baidu.calculator2.Calculator,long:5000"
*/
@Override
public void onStart(Intent intent, int startId) {
invokeArmsBinder(intent.getStringExtra("function"), intent.getStringExtra("parameter"));
}
class Parameter {
public Class type;
public Object value;
}
private void invokeArmsBinder(String function, String parameter) {
Log.print(function + "(" + parameter + ")");
Class[] types = null;
Object[] values = null;
// get parameter
- if ("null".equals(parameter)) {
+ if (null == parameter) {
types = new Class[] {};
values = new Object[] {};
} else {
String[] parameters = parameter.split(",");
types = new Class[parameters.length];
values = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
Parameter p = getParameter(parameters[i]);
types[i] = p.type;
values[i] = p.value;
}
}
try {
Method method = ArmsBinder.class.getDeclaredMethod(function, types);
if (!method.isAccessible()) {
method.setAccessible(true);
}
Object result = method.invoke(new ArmsBinder(this), values);
Log.print(result.toString());
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
private Parameter getParameter(String parameterString) {
Parameter p = new Parameter();
String type = parameterString.substring(0, parameterString.indexOf(":"));
String value = parameterString.substring(parameterString.indexOf(":") + 1, parameterString.length());
if ("String".equalsIgnoreCase(type)) {
p.type = String.class;
p.value = String.valueOf(value);
} else if ("int".equalsIgnoreCase(type)) {
p.type = int.class;
p.value = Integer.valueOf(value).intValue();
} else if ("boolean".equalsIgnoreCase(type)) {
p.type = boolean.class;
p.value = Boolean.valueOf(value).booleanValue();
} else if ("float".equalsIgnoreCase(type)) {
p.type = float.class;
p.value = Float.valueOf(value).floatValue();
} else if ("double".equalsIgnoreCase(type)) {
p.type = double.class;
p.value = Double.valueOf(value).doubleValue();
} else if ("long".equalsIgnoreCase(type)) {
p.type = long.class;
p.value = Long.valueOf(value).longValue();
}
return p;
}
private void keepAdb() {
new Thread(new Runnable() {
public void run() {
while (true) {
try {
int adbEnabled = Settings.Secure.getInt(getContentResolver(), Settings.Secure.ADB_ENABLED);
if (adbEnabled == 0) {
Settings.Secure.putInt(getContentResolver(), Settings.Secure.ADB_ENABLED, 1);
Log.print("resume adb!");
}
Thread.sleep(1000);
} catch (SettingNotFoundException e1) {
e1.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
| true | true | private void invokeArmsBinder(String function, String parameter) {
Log.print(function + "(" + parameter + ")");
Class[] types = null;
Object[] values = null;
// get parameter
if ("null".equals(parameter)) {
types = new Class[] {};
values = new Object[] {};
} else {
String[] parameters = parameter.split(",");
types = new Class[parameters.length];
values = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
Parameter p = getParameter(parameters[i]);
types[i] = p.type;
values[i] = p.value;
}
}
try {
Method method = ArmsBinder.class.getDeclaredMethod(function, types);
if (!method.isAccessible()) {
method.setAccessible(true);
}
Object result = method.invoke(new ArmsBinder(this), values);
Log.print(result.toString());
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
| private void invokeArmsBinder(String function, String parameter) {
Log.print(function + "(" + parameter + ")");
Class[] types = null;
Object[] values = null;
// get parameter
if (null == parameter) {
types = new Class[] {};
values = new Object[] {};
} else {
String[] parameters = parameter.split(",");
types = new Class[parameters.length];
values = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
Parameter p = getParameter(parameters[i]);
types[i] = p.type;
values[i] = p.value;
}
}
try {
Method method = ArmsBinder.class.getDeclaredMethod(function, types);
if (!method.isAccessible()) {
method.setAccessible(true);
}
Object result = method.invoke(new ArmsBinder(this), values);
Log.print(result.toString());
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
|
diff --git a/base/src/org/open2jam/gui/Interface.java b/base/src/org/open2jam/gui/Interface.java
index 3f60187..fd8685a 100644
--- a/base/src/org/open2jam/gui/Interface.java
+++ b/base/src/org/open2jam/gui/Interface.java
@@ -1,1098 +1,1098 @@
package org.open2jam.gui;
/*
* Interface.java
*
* Created on Oct 30, 2010, 6:51:02 PM
*/
import java.awt.event.ItemEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.logging.Level;
import org.open2jam.util.Logger;
import java.util.zip.CRC32;
import java.util.zip.GZIPInputStream;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableRowSorter;
import org.open2jam.parser.Chart;
import org.open2jam.render.TimeRender;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.open2jam.Config;
import org.open2jam.parser.ChartList;
import org.open2jam.render.DistanceRender;
import org.open2jam.render.Render;
/**
*
* @author fox
*/
public class Interface extends javax.swing.JFrame
implements PropertyChangeListener, ListSelectionListener {
private ChartListTableModel model_songlist;
private ChartTableModel model_chartlist;
private File cwd;
private ArrayList<File> dir_list;
private DisplayMode[] display_modes;
private int rank = 0;
private ChartList selected_chart;
private Chart selected_header;
private int last_model_idx;
private final TableRowSorter<ChartListTableModel> table_sorter;
private Configuration cfg_window = new Configuration(this);
private SkinConfiguration skin_window = new SkinConfiguration();
/** Creates new form Interface */
public Interface() {
initLogic();
initComponents();
loadDir(cwd);
this.setLocationRelativeTo(null);
load_progress.setVisible(false);
table_sorter = new TableRowSorter<ChartListTableModel>(model_songlist);
table_songlist.setRowSorter(table_sorter);
txt_filter.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {updateFilter();}
public void removeUpdate(DocumentEvent e) {updateFilter();}
public void changedUpdate(DocumentEvent e) {updateFilter();}
});
loadDirlist();
cfg_window.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent arg0) {
dir_list = Config.get().getDirsList();
loadDirlist();
}
});
javax.swing.table.TableColumn col;
col = table_songlist.getColumnModel().getColumn(0);
col.setPreferredWidth(180);
col = table_songlist.getColumnModel().getColumn(1);
col.setPreferredWidth(30);
col = table_songlist.getColumnModel().getColumn(2);
col.setPreferredWidth(80);
table_chartlist.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e)
{
if (e.getValueIsAdjusting()) return;
javax.swing.ListSelectionModel lsm = (javax.swing.ListSelectionModel)e.getSource();
if(lsm.isSelectionEmpty()) return;
int selectedRow = lsm.getMinSelectionIndex();
if(selectedRow < 0) return;
selected_header = selected_chart.get(selectedRow);
if(selectedRow != rank)
{
lbl_rank.setText("Overriden rank!!!");
}
else
{
lbl_rank.setText("Rank:");
}
updateInfo();
}
});
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
rank_group = new javax.swing.ButtonGroup();
panel_info = new javax.swing.JPanel();
lbl_title = new javax.swing.JLabel();
lbl_artist = new javax.swing.JLabel();
lbl_bpm = new javax.swing.JLabel();
lbl_level = new javax.swing.JLabel();
lbl_notes = new javax.swing.JLabel();
lbl_time = new javax.swing.JLabel();
lbl_genre = new javax.swing.JLabel();
lbl_bpm1 = new javax.swing.JLabel();
lbl_genre1 = new javax.swing.JLabel();
lbl_level1 = new javax.swing.JLabel();
lbl_notes1 = new javax.swing.JLabel();
lbl_time1 = new javax.swing.JLabel();
bt_play = new javax.swing.JButton();
lbl_cover = new javax.swing.JLabel();
lbl_keys1 = new javax.swing.JLabel();
lbl_keys = new javax.swing.JLabel();
jc_autoplay = new javax.swing.JCheckBox();
combo_channelModifier = new javax.swing.JComboBox();
lbl_channelModifier = new javax.swing.JLabel();
combo_visibilityModifier = new javax.swing.JComboBox();
lbl_visibilityModifier = new javax.swing.JLabel();
lbl_filename = new javax.swing.JLabel();
table_scroll2 = new javax.swing.JScrollPane();
table_chartlist = new javax.swing.JTable();
jc_timed_judgment = new javax.swing.JCheckBox();
panel_setting = new javax.swing.JPanel();
jr_rank_hard = new javax.swing.JRadioButton();
combo_displays = new javax.swing.JComboBox();
txt_res_height = new javax.swing.JTextField();
txt_res_width = new javax.swing.JTextField();
jc_vsync = new javax.swing.JCheckBox();
lbl_rank = new javax.swing.JLabel();
lbl_display = new javax.swing.JLabel();
jc_custom_size = new javax.swing.JCheckBox();
jr_rank_easy = new javax.swing.JRadioButton();
lbl_hispeed = new javax.swing.JLabel();
lbl_res_x = new javax.swing.JLabel();
jr_rank_normal = new javax.swing.JRadioButton();
jc_full_screen = new javax.swing.JCheckBox();
bt_choose_dir = new javax.swing.JButton();
load_progress = new javax.swing.JProgressBar();
js_hispeed = new javax.swing.JSpinner();
btn_configuration = new javax.swing.JButton();
btn_skin = new javax.swing.JButton();
combo_dirs = new javax.swing.JComboBox();
btn_reload = new javax.swing.JButton();
jc_bilinear = new javax.swing.JCheckBox();
table_scroll = new javax.swing.JScrollPane();
table_songlist = new javax.swing.JTable();
txt_filter = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
slider_main_vol = new javax.swing.JSlider();
slider_key_vol = new javax.swing.JSlider();
slider_bgm_vol = new javax.swing.JSlider();
lbl_main_vol = new javax.swing.JLabel();
lbl_key_vol = new javax.swing.JLabel();
lbl_bgm_vol = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
mitem_exit = new javax.swing.JMenuItem();
jMenu3 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
menu_about = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Open2Jam");
lbl_title.setFont(new java.awt.Font("Tahoma", 0, 18));
lbl_title.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_title.setText("Title");
lbl_artist.setFont(new java.awt.Font("Tahoma", 2, 11));
lbl_artist.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_artist.setText("Artist");
lbl_bpm.setText("content");
lbl_level.setText("content");
lbl_notes.setText("content");
lbl_time.setText("content");
lbl_genre.setText("content");
lbl_bpm1.setText("BPM:");
lbl_genre1.setText("Genre:");
lbl_level1.setText("Level:");
lbl_notes1.setText("Notes:");
lbl_time1.setText("Time:");
bt_play.setFont(new java.awt.Font("Tahoma", 0, 18));
bt_play.setText("Play !");
bt_play.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bt_playActionPerformed(evt);
}
});
lbl_cover.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_cover.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
lbl_cover.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
lbl_cover.setIconTextGap(0);
lbl_cover.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lbl_coverMouseClicked(evt);
}
});
lbl_keys1.setText("Keys:");
lbl_keys.setText("content");
jc_autoplay.setText("Autoplay");
combo_channelModifier.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--None--", "Mirror", "Shuffle", "Random" }));
lbl_channelModifier.setText("Channel Modifier:");
combo_visibilityModifier.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--None--", "Hidden", "Sudden", "Dark" }));
- combo_visibilityModifier.setEnabled(false);
lbl_visibilityModifier.setText("Visibility Modifier:");
lbl_filename.setFont(new java.awt.Font("Tahoma", 0, 10));
lbl_filename.setText("filename");
table_chartlist.setModel(model_chartlist);
table_chartlist.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
table_scroll2.setViewportView(table_chartlist);
jc_timed_judgment.setSelected(true);
jc_timed_judgment.setText("Use timed judment");
jc_timed_judgment.setToolTipText("Like Bemani games");
javax.swing.GroupLayout panel_infoLayout = new javax.swing.GroupLayout(panel_info);
panel_info.setLayout(panel_infoLayout);
panel_infoLayout.setHorizontalGroup(
panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel_infoLayout.createSequentialGroup()
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(table_scroll2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE)
.addComponent(lbl_title, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, panel_infoLayout.createSequentialGroup()
.addComponent(lbl_cover, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(panel_infoLayout.createSequentialGroup()
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_bpm1)
.addComponent(lbl_genre1)
.addComponent(lbl_level1)
.addComponent(lbl_notes1)
.addComponent(lbl_time1)
.addComponent(lbl_keys1))
.addGap(18, 18, 18)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_keys)
.addComponent(lbl_level, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)
.addComponent(lbl_notes, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)
.addComponent(lbl_time, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)
.addComponent(lbl_genre, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)
.addComponent(lbl_bpm, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)))
.addComponent(lbl_filename)))
.addComponent(lbl_artist, javax.swing.GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE)
.addGroup(panel_infoLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(panel_infoLayout.createSequentialGroup()
.addComponent(lbl_channelModifier)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(combo_channelModifier, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lbl_visibilityModifier))
.addGroup(panel_infoLayout.createSequentialGroup()
.addComponent(jc_timed_judgment)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jc_autoplay)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(bt_play)
.addComponent(combo_visibilityModifier, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap())
);
panel_infoLayout.setVerticalGroup(
panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_infoLayout.createSequentialGroup()
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(lbl_cover, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(panel_infoLayout.createSequentialGroup()
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_bpm1)
.addComponent(lbl_bpm))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_genre)
.addComponent(lbl_genre1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_level)
.addComponent(lbl_level1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_notes1)
.addComponent(lbl_notes))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_time)
.addComponent(lbl_time1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_keys1)
.addComponent(lbl_keys))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lbl_filename)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lbl_title, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lbl_artist)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(table_scroll2, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_visibilityModifier)
.addComponent(combo_visibilityModifier, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(combo_channelModifier, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_channelModifier))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jc_autoplay)
.addComponent(bt_play)
.addComponent(jc_timed_judgment)))
);
rank_group.add(jr_rank_hard);
jr_rank_hard.setText("Hard");
jr_rank_hard.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jr_rank_hard.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jr_rank_hard.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jr_rank_hardActionPerformed(evt);
}
});
combo_displays.setModel(new javax.swing.DefaultComboBoxModel(display_modes));
txt_res_height.setText("600");
txt_res_height.setEnabled(false);
txt_res_width.setText("800");
txt_res_width.setEnabled(false);
jc_vsync.setSelected(true);
jc_vsync.setText("Use VSync");
lbl_rank.setText("Rank:");
lbl_display.setText("Display:");
jc_custom_size.setFont(new java.awt.Font("Tahoma", 0, 10));
jc_custom_size.setText("Custom size:");
jc_custom_size.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
custom_size_clicked(evt);
}
});
rank_group.add(jr_rank_easy);
jr_rank_easy.setSelected(true);
jr_rank_easy.setText("Easy");
jr_rank_easy.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jr_rank_easy.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jr_rank_easy.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jr_rank_easyActionPerformed(evt);
}
});
lbl_hispeed.setText("Hi-Speed:");
lbl_res_x.setText("x");
rank_group.add(jr_rank_normal);
jr_rank_normal.setText("Normal");
jr_rank_normal.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jr_rank_normal.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jr_rank_normal.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jr_rank_normalActionPerformed(evt);
}
});
jc_full_screen.setText("Full screen");
bt_choose_dir.setText("Choose dir");
bt_choose_dir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bt_choose_dirActionPerformed(evt);
}
});
load_progress.setStringPainted(true);
js_hispeed.setModel(new javax.swing.SpinnerNumberModel(1.0d, 0.5d, 10.0d, 0.5d));
btn_configuration.setFont(new java.awt.Font("Tahoma", 0, 10));
btn_configuration.setText("Folders and Keys");
btn_configuration.setMaximumSize(new java.awt.Dimension(20, 20));
btn_configuration.setMinimumSize(new java.awt.Dimension(20, 20));
btn_configuration.setPreferredSize(new java.awt.Dimension(20, 20));
btn_configuration.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_configurationActionPerformed(evt);
}
});
- btn_skin.setFont(new java.awt.Font("Tahoma", 0, 10));
+ btn_skin.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
btn_skin.setText("Skin Selection");
+ btn_skin.setEnabled(false);
btn_skin.setMaximumSize(new java.awt.Dimension(20, 20));
btn_skin.setMinimumSize(new java.awt.Dimension(20, 20));
btn_skin.setPreferredSize(new java.awt.Dimension(20, 20));
btn_skin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_skinActionPerformed(evt);
}
});
combo_dirs.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
combo_dirsActionPerformed(evt);
}
});
btn_reload.setText("Reload");
btn_reload.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_reloadActionPerformed(evt);
}
});
jc_bilinear.setSelected(true);
jc_bilinear.setText("Bilinear filter");
javax.swing.GroupLayout panel_settingLayout = new javax.swing.GroupLayout(panel_setting);
panel_setting.setLayout(panel_settingLayout);
panel_settingLayout.setHorizontalGroup(
panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_settingLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_settingLayout.createSequentialGroup()
.addComponent(jr_rank_easy)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jr_rank_normal)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jr_rank_hard))
.addComponent(lbl_rank)
.addGroup(panel_settingLayout.createSequentialGroup()
.addComponent(lbl_hispeed)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(js_hispeed, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE)
.addGap(72, 72, 72))
.addComponent(lbl_display)
.addComponent(combo_displays, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(panel_settingLayout.createSequentialGroup()
.addComponent(bt_choose_dir)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(load_progress, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(panel_settingLayout.createSequentialGroup()
.addComponent(jc_custom_size, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_res_width, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lbl_res_x)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_res_height, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(panel_settingLayout.createSequentialGroup()
.addComponent(jc_vsync)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jc_full_screen))
.addGroup(panel_settingLayout.createSequentialGroup()
.addComponent(combo_dirs, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn_reload))
.addGroup(panel_settingLayout.createSequentialGroup()
.addComponent(btn_configuration, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE))
.addComponent(btn_skin, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jc_bilinear))
.addContainerGap())
);
panel_settingLayout.setVerticalGroup(
panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_settingLayout.createSequentialGroup()
.addContainerGap(18, Short.MAX_VALUE)
.addGroup(panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(bt_choose_dir)
.addComponent(load_progress, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(lbl_rank)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jr_rank_easy)
.addComponent(jr_rank_normal)
.addComponent(jr_rank_hard))
.addGap(22, 22, 22)
.addGroup(panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(js_hispeed, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_hispeed))
.addGap(18, 18, 18)
.addComponent(lbl_display)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(combo_displays, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(txt_res_width, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_res_height, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_res_x)
.addComponent(jc_custom_size))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jc_vsync)
.addComponent(jc_full_screen))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jc_bilinear)
.addGap(8, 8, 8)
.addComponent(btn_configuration, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn_skin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34)
.addGroup(panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(combo_dirs, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn_reload))
.addContainerGap())
);
table_songlist.setAutoCreateRowSorter(true);
table_songlist.setModel(model_songlist);
table_songlist.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
table_songlist.getSelectionModel().addListSelectionListener(this);
table_scroll.setViewportView(table_songlist);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12));
jLabel1.setText("Source");
slider_main_vol.setPaintLabels(true);
slider_main_vol.setToolTipText("Main Volume");
slider_key_vol.setPaintLabels(true);
slider_key_vol.setToolTipText("Key Volume");
slider_key_vol.setValue(100);
slider_bgm_vol.setPaintLabels(true);
slider_bgm_vol.setToolTipText("BGM Volume");
slider_bgm_vol.setValue(100);
lbl_main_vol.setText("Main Volume:");
lbl_key_vol.setText("Key Volume:");
lbl_bgm_vol.setText("BGM Volume:");
jMenu1.setText("File");
mitem_exit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
mitem_exit.setText("Exit");
mitem_exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mitem_exitActionPerformed(evt);
}
});
jMenu1.add(mitem_exit);
jMenuBar1.add(jMenu1);
jMenu3.setText("Tools");
jMenuItem1.setText("OJM Dumper");
jMenu3.add(jMenuItem1);
jMenuItem2.setText("OJN <-> BMS");
jMenu3.add(jMenuItem2);
jMenuBar1.add(jMenu3);
menu_about.setText("About");
menu_about.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
menu_about.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
menu_aboutMouseClicked(evt);
}
});
jMenuBar1.add(menu_about);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1))
.addComponent(panel_setting, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_main_vol)
.addComponent(lbl_bgm_vol)
.addComponent(lbl_key_vol))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(slider_bgm_vol, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
.addComponent(slider_key_vol, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
.addComponent(slider_main_vol, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(panel_info, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txt_filter, javax.swing.GroupLayout.DEFAULT_SIZE, 311, Short.MAX_VALUE)
.addComponent(table_scroll, javax.swing.GroupLayout.DEFAULT_SIZE, 311, Short.MAX_VALUE)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel_info, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(table_scroll, javax.swing.GroupLayout.DEFAULT_SIZE, 505, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_filter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(panel_setting, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(lbl_main_vol)
.addComponent(slider_main_vol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(lbl_key_vol)
.addComponent(slider_key_vol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(lbl_bgm_vol)
.addComponent(slider_bgm_vol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
.addComponent(jLabel1)))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void custom_size_clicked(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_custom_size_clicked
if (evt.getStateChange() == ItemEvent.SELECTED){
combo_displays.setEnabled(false);
txt_res_width.setEnabled(true);
lbl_res_x.setEnabled(true);
txt_res_height.setEnabled(true);
}else{
txt_res_width.setEnabled(false);
lbl_res_x.setEnabled(false);
txt_res_height.setEnabled(false);
combo_displays.setEnabled(true);
}
}//GEN-LAST:event_custom_size_clicked
private void bt_choose_dirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_choose_dirActionPerformed
JFileChooser jfc = new JFileChooser();
jfc.setCurrentDirectory(cwd);
jfc.setDialogTitle("Choose a directory");
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
jfc.setAcceptAllFileFilterUsed(false);
if (jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
cwd = jfc.getSelectedFile();
loadDir(cwd);
}
}//GEN-LAST:event_bt_choose_dirActionPerformed
private void lbl_coverMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbl_coverMouseClicked
if(selected_header.getCover() == null) return;
JOptionPane.showMessageDialog(this, null, "Cover",
JOptionPane.INFORMATION_MESSAGE, new ImageIcon(selected_header.getCover()));
}//GEN-LAST:event_lbl_coverMouseClicked
private void jr_rank_normalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jr_rank_normalActionPerformed
rank = 1;
int sel_row = table_songlist.getSelectedRow();
if(sel_row >= 0)last_model_idx = table_songlist.convertRowIndexToModel(sel_row);
model_songlist.setRank(rank);
}//GEN-LAST:event_jr_rank_normalActionPerformed
private void jr_rank_easyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jr_rank_easyActionPerformed
rank = 0;
int sel_row = table_songlist.getSelectedRow();
if(sel_row >= 0)last_model_idx = table_songlist.convertRowIndexToModel(sel_row);
model_songlist.setRank(rank);
}//GEN-LAST:event_jr_rank_easyActionPerformed
private void jr_rank_hardActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jr_rank_hardActionPerformed
rank = 2;
int sel_row = table_songlist.getSelectedRow();
if(sel_row >= 0)last_model_idx = table_songlist.convertRowIndexToModel(sel_row);
model_songlist.setRank(rank);
}//GEN-LAST:event_jr_rank_hardActionPerformed
private void bt_playActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_playActionPerformed
if(selected_header != null)
{
final double hispeed = (Double) js_hispeed.getValue();
final DisplayMode dm;
if(jc_custom_size.isSelected()){ // custom size selected
int w,h;
try{
w = Integer.parseInt(txt_res_width.getText());
h = Integer.parseInt(txt_res_height.getText());
}catch(Exception e){
JOptionPane.showMessageDialog(this, "Invalid value on custom size", "Error", JOptionPane.WARNING_MESSAGE);
return;
}
dm = new DisplayMode(w,h);
}else{
dm = (DisplayMode) combo_displays.getSelectedItem();
}
final boolean vsync = jc_vsync.isSelected();
boolean fs = jc_full_screen.isSelected();
final boolean autoplay = jc_autoplay.isSelected();
final boolean judgment = jc_timed_judgment.isSelected();
final int channelModifier = combo_channelModifier.getSelectedIndex();
final int visibilityModifier = combo_visibilityModifier.getSelectedIndex();
final int mainVol = slider_main_vol.getValue();
final int keyVol = slider_key_vol.getValue();
final int bgmVol = slider_bgm_vol.getValue();
final boolean bilinear = jc_bilinear.isSelected();
if(!dm.isFullscreenCapable() && fs)
{
String str = "This monitor can't support the selected resolution.\n"
+ "Do you want to play it in windowed mode?";
if(JOptionPane.showConfirmDialog(this, str, "Warning",
JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE)
== JOptionPane.YES_OPTION)
fs = false;
}
Render r;
if(judgment)
r = new TimeRender(selected_header, hispeed, autoplay, channelModifier, visibilityModifier, mainVol, keyVol, bgmVol);
else
r = new DistanceRender(selected_header, hispeed, autoplay, channelModifier, visibilityModifier, mainVol, keyVol, bgmVol);
r.setDisplay(dm, vsync, fs, bilinear);
r.startRendering();
}
}//GEN-LAST:event_bt_playActionPerformed
private void btn_configurationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_configurationActionPerformed
cfg_window.setVisible(true);
}//GEN-LAST:event_btn_configurationActionPerformed
private void mitem_exitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mitem_exitActionPerformed
System.exit(0); //TODO Not a good idea XD
}//GEN-LAST:event_mitem_exitActionPerformed
private void menu_aboutMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menu_aboutMouseClicked
String about = "Open2Jam\n"
+ "Main programmer: ChaosFox\n"
+ "Main code destroyer: CdK" ;
JOptionPane.showMessageDialog(this, about, "About", JOptionPane.ERROR_MESSAGE, null);
}//GEN-LAST:event_menu_aboutMouseClicked
private void btn_skinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_skinActionPerformed
skin_window.setVisible(true);
}//GEN-LAST:event_btn_skinActionPerformed
private void combo_dirsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_combo_dirsActionPerformed
if(dir_list.isEmpty()) return;
if(combo_dirs.getSelectedIndex()<0)return;
File s = dir_list.get(combo_dirs.getSelectedIndex());
loadDir(s);
}//GEN-LAST:event_combo_dirsActionPerformed
private void btn_reloadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_reloadActionPerformed
updateSelection();
}//GEN-LAST:event_btn_reloadActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton bt_choose_dir;
private javax.swing.JButton bt_play;
private javax.swing.JButton btn_configuration;
private javax.swing.JButton btn_reload;
private javax.swing.JButton btn_skin;
private javax.swing.JComboBox combo_channelModifier;
private javax.swing.JComboBox combo_dirs;
private javax.swing.JComboBox combo_displays;
private javax.swing.JComboBox combo_visibilityModifier;
private javax.swing.JLabel jLabel1;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JCheckBox jc_autoplay;
private javax.swing.JCheckBox jc_bilinear;
private javax.swing.JCheckBox jc_custom_size;
private javax.swing.JCheckBox jc_full_screen;
private javax.swing.JCheckBox jc_timed_judgment;
private javax.swing.JCheckBox jc_vsync;
private javax.swing.JRadioButton jr_rank_easy;
private javax.swing.JRadioButton jr_rank_hard;
private javax.swing.JRadioButton jr_rank_normal;
private javax.swing.JSpinner js_hispeed;
private javax.swing.JLabel lbl_artist;
private javax.swing.JLabel lbl_bgm_vol;
private javax.swing.JLabel lbl_bpm;
private javax.swing.JLabel lbl_bpm1;
private javax.swing.JLabel lbl_channelModifier;
private javax.swing.JLabel lbl_cover;
private javax.swing.JLabel lbl_display;
private javax.swing.JLabel lbl_filename;
private javax.swing.JLabel lbl_genre;
private javax.swing.JLabel lbl_genre1;
private javax.swing.JLabel lbl_hispeed;
private javax.swing.JLabel lbl_key_vol;
private javax.swing.JLabel lbl_keys;
private javax.swing.JLabel lbl_keys1;
private javax.swing.JLabel lbl_level;
private javax.swing.JLabel lbl_level1;
private javax.swing.JLabel lbl_main_vol;
private javax.swing.JLabel lbl_notes;
private javax.swing.JLabel lbl_notes1;
private javax.swing.JLabel lbl_rank;
private javax.swing.JLabel lbl_res_x;
private javax.swing.JLabel lbl_time;
private javax.swing.JLabel lbl_time1;
private javax.swing.JLabel lbl_title;
private javax.swing.JLabel lbl_visibilityModifier;
private javax.swing.JProgressBar load_progress;
private javax.swing.JMenu menu_about;
private javax.swing.JMenuItem mitem_exit;
private javax.swing.JPanel panel_info;
private javax.swing.JPanel panel_setting;
private javax.swing.ButtonGroup rank_group;
private javax.swing.JSlider slider_bgm_vol;
private javax.swing.JSlider slider_key_vol;
private javax.swing.JSlider slider_main_vol;
private javax.swing.JTable table_chartlist;
private javax.swing.JScrollPane table_scroll;
private javax.swing.JScrollPane table_scroll2;
private javax.swing.JTable table_songlist;
private javax.swing.JTextField txt_filter;
private javax.swing.JTextField txt_res_height;
private javax.swing.JTextField txt_res_width;
// End of variables declaration//GEN-END:variables
private void initLogic() {
dir_list = Config.get().getDirsList();
if(dir_list.isEmpty()) cwd = new File(System.getProperty("user.dir"));
else cwd = dir_list.get(0);
try {
List<DisplayMode> list = Arrays.asList(Display.getAvailableDisplayModes());
Collections.sort(list, new Comparator<DisplayMode>() {
public int compare(DisplayMode dm1, DisplayMode dm2) {
if(dm1.getBitsPerPixel() == dm2.getBitsPerPixel())
{
if(dm1.getWidth() == dm2.getWidth())
{
if(dm1.getHeight() == dm2.getHeight())
{
if(dm1.getFrequency() > dm2.getFrequency())return -1;
else if(dm1.getFrequency() < dm2.getFrequency())return 1;
else return 0;
}
else if(dm1.getHeight() > dm2.getHeight())return -1;
else return 1;
}
else if(dm1.getWidth() > dm2.getWidth())return -1;
else return 1;
}
else if(dm1.getBitsPerPixel() > dm2.getBitsPerPixel()) return -1;
return 1;
}
});
display_modes = list.toArray(new DisplayMode[list.size()]);
} catch (LWJGLException ex) {
Logger.global.log(Level.WARNING, "Could not get the display modes !! {0}", ex.getMessage());
display_modes = new DisplayMode[0];
}
model_songlist = new ChartListTableModel();
model_chartlist = new ChartTableModel();
}
public static File getCacheFile(File s)
{
//let's make a crc32 hash for the cache name
CRC32 cs = new CRC32();
cs.reset();
byte[] d = s.getAbsolutePath().getBytes();
cs.update(d, 0, d.length);
return new File("cache_"+Long.toHexString(cs.getValue()).toUpperCase()+".obj");
}
private void loadDir(File dir)
{
cwd = dir;
this.setTitle("Open2Jam - "+cwd);
File cache = getCacheFile(dir);
if(cache.exists()){
try {
GZIPInputStream gzip = new GZIPInputStream(new FileInputStream(cache));
ObjectInputStream obj = new ObjectInputStream(gzip);
@SuppressWarnings("unchecked") // yes, I'm sure its a list of chartlist
List<ChartList> l = (List<ChartList>) obj.readObject();
model_songlist.clear();
for(ChartList c : l)model_songlist.addRow(c);
obj.close();
} catch (IOException ex) {
Logger.global.log(Level.SEVERE, "{0}", ex);
updateSelection();
} catch (ClassNotFoundException ex) {
Logger.global.log(Level.SEVERE, "{0}", ex);
updateSelection();
}
}
else {
updateSelection();
}
}
private void updateSelection() {
bt_choose_dir.setEnabled(false);
btn_reload.setEnabled(false);
combo_dirs.setEnabled(false);
txt_filter.setVisible(false);
table_songlist.setEnabled(false);
load_progress.setValue(0);
load_progress.setVisible(true);
ChartModelLoader task = new ChartModelLoader(model_songlist, cwd);
task.addPropertyChangeListener(this);
task.execute();
}
private void loadDirlist()
{
DefaultComboBoxModel theModel = (DefaultComboBoxModel)combo_dirs.getModel();
theModel.removeAllElements();
if(dir_list.isEmpty()) return;
for(File f : dir_list)
{
combo_dirs.addItem(f.getName());
}
}
public void propertyChange(PropertyChangeEvent evt) {
if("progress".equals(evt.getPropertyName()))
{
int i = (Integer) evt.getNewValue();
load_progress.setValue(i);
if(i == 100)
{
bt_choose_dir.setEnabled(true);
combo_dirs.setEnabled(true);
btn_reload.setEnabled(true);
load_progress.setVisible(false);
txt_filter.setVisible(true);
table_songlist.setEnabled(true);
}
}
}
void updateFilter() {
try {
if(txt_filter.getText().length() == 0)table_sorter.setRowFilter(null);
else table_sorter.setRowFilter(RowFilter.regexFilter("(?i)"+txt_filter.getText()));
} catch (java.util.regex.PatternSyntaxException ignored) {
}
}
public void valueChanged(ListSelectionEvent e) {
int i = table_songlist.getSelectedRow();
if(i < 0 && last_model_idx >= 0){
i = last_model_idx;
int i_view = table_songlist.convertRowIndexToView(i);
table_songlist.getSelectionModel().setSelectionInterval(0, i_view);
table_scroll.getVerticalScrollBar().setValue(table_songlist.getCellRect(i_view, 0, false).y);
}else{
i = table_songlist.convertRowIndexToModel(i);
}
selected_chart = model_songlist.getRow(i);
if(selected_chart.size() > rank)selected_header = selected_chart.get(rank);
if(selected_chart != model_chartlist.getChartList()){
model_chartlist.clear();
model_chartlist.setChartList(selected_chart);
}
if(selected_chart.size()-1 < rank)
table_chartlist.getSelectionModel().setSelectionInterval(0, 0);
else
table_chartlist.getSelectionModel().setSelectionInterval(0, rank);
updateInfo();
}
private void updateInfo()
{
if(selected_header == null)return;
if(!selected_header.getSource().exists()) {JOptionPane.showMessageDialog(this, "Doesn't Exist"); return;}
lbl_artist.setText(resizeString(selected_header.getArtist(), 40));
lbl_title.setText(resizeString(selected_header.getTitle(), 30));
lbl_filename.setText(resizeString(selected_header.getSource().getName(), 30));
lbl_genre.setText(resizeString(selected_header.getGenre(), 30));
lbl_level.setText(selected_header.getLevel()+"");
lbl_bpm.setText(Float.toString((float)selected_header.getBPM()*100/100));
lbl_notes.setText(selected_header.getNoteCount()+"");
lbl_keys.setText(selected_header.getKeys()+"");
int d = selected_header.getDuration();
lbl_time.setText((d/60)+":"+(d%60 < 10 ? "0"+(d%60) : (d%60)));
BufferedImage i = selected_header.getCover();
if(i != null)
lbl_cover.setIcon(new ImageIcon(i.getScaledInstance(
lbl_cover.getWidth(),
lbl_cover.getHeight(),
BufferedImage.SCALE_SMOOTH
)));
else
lbl_cover.setIcon(null);
}
private String resizeString(String string, int size)
{
if(string == null)return "";
if(string.length() > size)
string = string.substring(0, size)+"...";
return string;
}
}
| false | true | private void initComponents() {
rank_group = new javax.swing.ButtonGroup();
panel_info = new javax.swing.JPanel();
lbl_title = new javax.swing.JLabel();
lbl_artist = new javax.swing.JLabel();
lbl_bpm = new javax.swing.JLabel();
lbl_level = new javax.swing.JLabel();
lbl_notes = new javax.swing.JLabel();
lbl_time = new javax.swing.JLabel();
lbl_genre = new javax.swing.JLabel();
lbl_bpm1 = new javax.swing.JLabel();
lbl_genre1 = new javax.swing.JLabel();
lbl_level1 = new javax.swing.JLabel();
lbl_notes1 = new javax.swing.JLabel();
lbl_time1 = new javax.swing.JLabel();
bt_play = new javax.swing.JButton();
lbl_cover = new javax.swing.JLabel();
lbl_keys1 = new javax.swing.JLabel();
lbl_keys = new javax.swing.JLabel();
jc_autoplay = new javax.swing.JCheckBox();
combo_channelModifier = new javax.swing.JComboBox();
lbl_channelModifier = new javax.swing.JLabel();
combo_visibilityModifier = new javax.swing.JComboBox();
lbl_visibilityModifier = new javax.swing.JLabel();
lbl_filename = new javax.swing.JLabel();
table_scroll2 = new javax.swing.JScrollPane();
table_chartlist = new javax.swing.JTable();
jc_timed_judgment = new javax.swing.JCheckBox();
panel_setting = new javax.swing.JPanel();
jr_rank_hard = new javax.swing.JRadioButton();
combo_displays = new javax.swing.JComboBox();
txt_res_height = new javax.swing.JTextField();
txt_res_width = new javax.swing.JTextField();
jc_vsync = new javax.swing.JCheckBox();
lbl_rank = new javax.swing.JLabel();
lbl_display = new javax.swing.JLabel();
jc_custom_size = new javax.swing.JCheckBox();
jr_rank_easy = new javax.swing.JRadioButton();
lbl_hispeed = new javax.swing.JLabel();
lbl_res_x = new javax.swing.JLabel();
jr_rank_normal = new javax.swing.JRadioButton();
jc_full_screen = new javax.swing.JCheckBox();
bt_choose_dir = new javax.swing.JButton();
load_progress = new javax.swing.JProgressBar();
js_hispeed = new javax.swing.JSpinner();
btn_configuration = new javax.swing.JButton();
btn_skin = new javax.swing.JButton();
combo_dirs = new javax.swing.JComboBox();
btn_reload = new javax.swing.JButton();
jc_bilinear = new javax.swing.JCheckBox();
table_scroll = new javax.swing.JScrollPane();
table_songlist = new javax.swing.JTable();
txt_filter = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
slider_main_vol = new javax.swing.JSlider();
slider_key_vol = new javax.swing.JSlider();
slider_bgm_vol = new javax.swing.JSlider();
lbl_main_vol = new javax.swing.JLabel();
lbl_key_vol = new javax.swing.JLabel();
lbl_bgm_vol = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
mitem_exit = new javax.swing.JMenuItem();
jMenu3 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
menu_about = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Open2Jam");
lbl_title.setFont(new java.awt.Font("Tahoma", 0, 18));
lbl_title.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_title.setText("Title");
lbl_artist.setFont(new java.awt.Font("Tahoma", 2, 11));
lbl_artist.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_artist.setText("Artist");
lbl_bpm.setText("content");
lbl_level.setText("content");
lbl_notes.setText("content");
lbl_time.setText("content");
lbl_genre.setText("content");
lbl_bpm1.setText("BPM:");
lbl_genre1.setText("Genre:");
lbl_level1.setText("Level:");
lbl_notes1.setText("Notes:");
lbl_time1.setText("Time:");
bt_play.setFont(new java.awt.Font("Tahoma", 0, 18));
bt_play.setText("Play !");
bt_play.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bt_playActionPerformed(evt);
}
});
lbl_cover.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_cover.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
lbl_cover.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
lbl_cover.setIconTextGap(0);
lbl_cover.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lbl_coverMouseClicked(evt);
}
});
lbl_keys1.setText("Keys:");
lbl_keys.setText("content");
jc_autoplay.setText("Autoplay");
combo_channelModifier.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--None--", "Mirror", "Shuffle", "Random" }));
lbl_channelModifier.setText("Channel Modifier:");
combo_visibilityModifier.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--None--", "Hidden", "Sudden", "Dark" }));
combo_visibilityModifier.setEnabled(false);
lbl_visibilityModifier.setText("Visibility Modifier:");
lbl_filename.setFont(new java.awt.Font("Tahoma", 0, 10));
lbl_filename.setText("filename");
table_chartlist.setModel(model_chartlist);
table_chartlist.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
table_scroll2.setViewportView(table_chartlist);
jc_timed_judgment.setSelected(true);
jc_timed_judgment.setText("Use timed judment");
jc_timed_judgment.setToolTipText("Like Bemani games");
javax.swing.GroupLayout panel_infoLayout = new javax.swing.GroupLayout(panel_info);
panel_info.setLayout(panel_infoLayout);
panel_infoLayout.setHorizontalGroup(
panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel_infoLayout.createSequentialGroup()
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(table_scroll2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE)
.addComponent(lbl_title, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, panel_infoLayout.createSequentialGroup()
.addComponent(lbl_cover, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(panel_infoLayout.createSequentialGroup()
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_bpm1)
.addComponent(lbl_genre1)
.addComponent(lbl_level1)
.addComponent(lbl_notes1)
.addComponent(lbl_time1)
.addComponent(lbl_keys1))
.addGap(18, 18, 18)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_keys)
.addComponent(lbl_level, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)
.addComponent(lbl_notes, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)
.addComponent(lbl_time, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)
.addComponent(lbl_genre, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)
.addComponent(lbl_bpm, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)))
.addComponent(lbl_filename)))
.addComponent(lbl_artist, javax.swing.GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE)
.addGroup(panel_infoLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(panel_infoLayout.createSequentialGroup()
.addComponent(lbl_channelModifier)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(combo_channelModifier, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lbl_visibilityModifier))
.addGroup(panel_infoLayout.createSequentialGroup()
.addComponent(jc_timed_judgment)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jc_autoplay)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(bt_play)
.addComponent(combo_visibilityModifier, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap())
);
panel_infoLayout.setVerticalGroup(
panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_infoLayout.createSequentialGroup()
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(lbl_cover, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(panel_infoLayout.createSequentialGroup()
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_bpm1)
.addComponent(lbl_bpm))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_genre)
.addComponent(lbl_genre1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_level)
.addComponent(lbl_level1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_notes1)
.addComponent(lbl_notes))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_time)
.addComponent(lbl_time1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_keys1)
.addComponent(lbl_keys))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lbl_filename)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lbl_title, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lbl_artist)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(table_scroll2, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_visibilityModifier)
.addComponent(combo_visibilityModifier, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(combo_channelModifier, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_channelModifier))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jc_autoplay)
.addComponent(bt_play)
.addComponent(jc_timed_judgment)))
);
rank_group.add(jr_rank_hard);
jr_rank_hard.setText("Hard");
jr_rank_hard.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jr_rank_hard.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jr_rank_hard.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jr_rank_hardActionPerformed(evt);
}
});
combo_displays.setModel(new javax.swing.DefaultComboBoxModel(display_modes));
txt_res_height.setText("600");
txt_res_height.setEnabled(false);
txt_res_width.setText("800");
txt_res_width.setEnabled(false);
jc_vsync.setSelected(true);
jc_vsync.setText("Use VSync");
lbl_rank.setText("Rank:");
lbl_display.setText("Display:");
jc_custom_size.setFont(new java.awt.Font("Tahoma", 0, 10));
jc_custom_size.setText("Custom size:");
jc_custom_size.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
custom_size_clicked(evt);
}
});
rank_group.add(jr_rank_easy);
jr_rank_easy.setSelected(true);
jr_rank_easy.setText("Easy");
jr_rank_easy.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jr_rank_easy.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jr_rank_easy.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jr_rank_easyActionPerformed(evt);
}
});
lbl_hispeed.setText("Hi-Speed:");
lbl_res_x.setText("x");
rank_group.add(jr_rank_normal);
jr_rank_normal.setText("Normal");
jr_rank_normal.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jr_rank_normal.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jr_rank_normal.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jr_rank_normalActionPerformed(evt);
}
});
jc_full_screen.setText("Full screen");
bt_choose_dir.setText("Choose dir");
bt_choose_dir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bt_choose_dirActionPerformed(evt);
}
});
load_progress.setStringPainted(true);
js_hispeed.setModel(new javax.swing.SpinnerNumberModel(1.0d, 0.5d, 10.0d, 0.5d));
btn_configuration.setFont(new java.awt.Font("Tahoma", 0, 10));
btn_configuration.setText("Folders and Keys");
btn_configuration.setMaximumSize(new java.awt.Dimension(20, 20));
btn_configuration.setMinimumSize(new java.awt.Dimension(20, 20));
btn_configuration.setPreferredSize(new java.awt.Dimension(20, 20));
btn_configuration.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_configurationActionPerformed(evt);
}
});
btn_skin.setFont(new java.awt.Font("Tahoma", 0, 10));
btn_skin.setText("Skin Selection");
btn_skin.setMaximumSize(new java.awt.Dimension(20, 20));
btn_skin.setMinimumSize(new java.awt.Dimension(20, 20));
btn_skin.setPreferredSize(new java.awt.Dimension(20, 20));
btn_skin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_skinActionPerformed(evt);
}
});
combo_dirs.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
combo_dirsActionPerformed(evt);
}
});
btn_reload.setText("Reload");
btn_reload.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_reloadActionPerformed(evt);
}
});
jc_bilinear.setSelected(true);
jc_bilinear.setText("Bilinear filter");
javax.swing.GroupLayout panel_settingLayout = new javax.swing.GroupLayout(panel_setting);
panel_setting.setLayout(panel_settingLayout);
panel_settingLayout.setHorizontalGroup(
panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_settingLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_settingLayout.createSequentialGroup()
.addComponent(jr_rank_easy)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jr_rank_normal)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jr_rank_hard))
.addComponent(lbl_rank)
.addGroup(panel_settingLayout.createSequentialGroup()
.addComponent(lbl_hispeed)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(js_hispeed, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE)
.addGap(72, 72, 72))
.addComponent(lbl_display)
.addComponent(combo_displays, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(panel_settingLayout.createSequentialGroup()
.addComponent(bt_choose_dir)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(load_progress, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(panel_settingLayout.createSequentialGroup()
.addComponent(jc_custom_size, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_res_width, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lbl_res_x)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_res_height, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(panel_settingLayout.createSequentialGroup()
.addComponent(jc_vsync)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jc_full_screen))
.addGroup(panel_settingLayout.createSequentialGroup()
.addComponent(combo_dirs, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn_reload))
.addGroup(panel_settingLayout.createSequentialGroup()
.addComponent(btn_configuration, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE))
.addComponent(btn_skin, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jc_bilinear))
.addContainerGap())
);
panel_settingLayout.setVerticalGroup(
panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_settingLayout.createSequentialGroup()
.addContainerGap(18, Short.MAX_VALUE)
.addGroup(panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(bt_choose_dir)
.addComponent(load_progress, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(lbl_rank)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jr_rank_easy)
.addComponent(jr_rank_normal)
.addComponent(jr_rank_hard))
.addGap(22, 22, 22)
.addGroup(panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(js_hispeed, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_hispeed))
.addGap(18, 18, 18)
.addComponent(lbl_display)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(combo_displays, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(txt_res_width, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_res_height, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_res_x)
.addComponent(jc_custom_size))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jc_vsync)
.addComponent(jc_full_screen))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jc_bilinear)
.addGap(8, 8, 8)
.addComponent(btn_configuration, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn_skin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34)
.addGroup(panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(combo_dirs, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn_reload))
.addContainerGap())
);
table_songlist.setAutoCreateRowSorter(true);
table_songlist.setModel(model_songlist);
table_songlist.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
table_songlist.getSelectionModel().addListSelectionListener(this);
table_scroll.setViewportView(table_songlist);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12));
jLabel1.setText("Source");
slider_main_vol.setPaintLabels(true);
slider_main_vol.setToolTipText("Main Volume");
slider_key_vol.setPaintLabels(true);
slider_key_vol.setToolTipText("Key Volume");
slider_key_vol.setValue(100);
slider_bgm_vol.setPaintLabels(true);
slider_bgm_vol.setToolTipText("BGM Volume");
slider_bgm_vol.setValue(100);
lbl_main_vol.setText("Main Volume:");
lbl_key_vol.setText("Key Volume:");
lbl_bgm_vol.setText("BGM Volume:");
jMenu1.setText("File");
mitem_exit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
mitem_exit.setText("Exit");
mitem_exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mitem_exitActionPerformed(evt);
}
});
jMenu1.add(mitem_exit);
jMenuBar1.add(jMenu1);
jMenu3.setText("Tools");
jMenuItem1.setText("OJM Dumper");
jMenu3.add(jMenuItem1);
jMenuItem2.setText("OJN <-> BMS");
jMenu3.add(jMenuItem2);
jMenuBar1.add(jMenu3);
menu_about.setText("About");
menu_about.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
menu_about.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
menu_aboutMouseClicked(evt);
}
});
jMenuBar1.add(menu_about);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1))
.addComponent(panel_setting, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_main_vol)
.addComponent(lbl_bgm_vol)
.addComponent(lbl_key_vol))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(slider_bgm_vol, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
.addComponent(slider_key_vol, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
.addComponent(slider_main_vol, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(panel_info, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txt_filter, javax.swing.GroupLayout.DEFAULT_SIZE, 311, Short.MAX_VALUE)
.addComponent(table_scroll, javax.swing.GroupLayout.DEFAULT_SIZE, 311, Short.MAX_VALUE)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel_info, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(table_scroll, javax.swing.GroupLayout.DEFAULT_SIZE, 505, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_filter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(panel_setting, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(lbl_main_vol)
.addComponent(slider_main_vol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(lbl_key_vol)
.addComponent(slider_key_vol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(lbl_bgm_vol)
.addComponent(slider_bgm_vol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
.addComponent(jLabel1)))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
rank_group = new javax.swing.ButtonGroup();
panel_info = new javax.swing.JPanel();
lbl_title = new javax.swing.JLabel();
lbl_artist = new javax.swing.JLabel();
lbl_bpm = new javax.swing.JLabel();
lbl_level = new javax.swing.JLabel();
lbl_notes = new javax.swing.JLabel();
lbl_time = new javax.swing.JLabel();
lbl_genre = new javax.swing.JLabel();
lbl_bpm1 = new javax.swing.JLabel();
lbl_genre1 = new javax.swing.JLabel();
lbl_level1 = new javax.swing.JLabel();
lbl_notes1 = new javax.swing.JLabel();
lbl_time1 = new javax.swing.JLabel();
bt_play = new javax.swing.JButton();
lbl_cover = new javax.swing.JLabel();
lbl_keys1 = new javax.swing.JLabel();
lbl_keys = new javax.swing.JLabel();
jc_autoplay = new javax.swing.JCheckBox();
combo_channelModifier = new javax.swing.JComboBox();
lbl_channelModifier = new javax.swing.JLabel();
combo_visibilityModifier = new javax.swing.JComboBox();
lbl_visibilityModifier = new javax.swing.JLabel();
lbl_filename = new javax.swing.JLabel();
table_scroll2 = new javax.swing.JScrollPane();
table_chartlist = new javax.swing.JTable();
jc_timed_judgment = new javax.swing.JCheckBox();
panel_setting = new javax.swing.JPanel();
jr_rank_hard = new javax.swing.JRadioButton();
combo_displays = new javax.swing.JComboBox();
txt_res_height = new javax.swing.JTextField();
txt_res_width = new javax.swing.JTextField();
jc_vsync = new javax.swing.JCheckBox();
lbl_rank = new javax.swing.JLabel();
lbl_display = new javax.swing.JLabel();
jc_custom_size = new javax.swing.JCheckBox();
jr_rank_easy = new javax.swing.JRadioButton();
lbl_hispeed = new javax.swing.JLabel();
lbl_res_x = new javax.swing.JLabel();
jr_rank_normal = new javax.swing.JRadioButton();
jc_full_screen = new javax.swing.JCheckBox();
bt_choose_dir = new javax.swing.JButton();
load_progress = new javax.swing.JProgressBar();
js_hispeed = new javax.swing.JSpinner();
btn_configuration = new javax.swing.JButton();
btn_skin = new javax.swing.JButton();
combo_dirs = new javax.swing.JComboBox();
btn_reload = new javax.swing.JButton();
jc_bilinear = new javax.swing.JCheckBox();
table_scroll = new javax.swing.JScrollPane();
table_songlist = new javax.swing.JTable();
txt_filter = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
slider_main_vol = new javax.swing.JSlider();
slider_key_vol = new javax.swing.JSlider();
slider_bgm_vol = new javax.swing.JSlider();
lbl_main_vol = new javax.swing.JLabel();
lbl_key_vol = new javax.swing.JLabel();
lbl_bgm_vol = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
mitem_exit = new javax.swing.JMenuItem();
jMenu3 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
menu_about = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Open2Jam");
lbl_title.setFont(new java.awt.Font("Tahoma", 0, 18));
lbl_title.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_title.setText("Title");
lbl_artist.setFont(new java.awt.Font("Tahoma", 2, 11));
lbl_artist.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_artist.setText("Artist");
lbl_bpm.setText("content");
lbl_level.setText("content");
lbl_notes.setText("content");
lbl_time.setText("content");
lbl_genre.setText("content");
lbl_bpm1.setText("BPM:");
lbl_genre1.setText("Genre:");
lbl_level1.setText("Level:");
lbl_notes1.setText("Notes:");
lbl_time1.setText("Time:");
bt_play.setFont(new java.awt.Font("Tahoma", 0, 18));
bt_play.setText("Play !");
bt_play.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bt_playActionPerformed(evt);
}
});
lbl_cover.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_cover.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
lbl_cover.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
lbl_cover.setIconTextGap(0);
lbl_cover.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lbl_coverMouseClicked(evt);
}
});
lbl_keys1.setText("Keys:");
lbl_keys.setText("content");
jc_autoplay.setText("Autoplay");
combo_channelModifier.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--None--", "Mirror", "Shuffle", "Random" }));
lbl_channelModifier.setText("Channel Modifier:");
combo_visibilityModifier.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--None--", "Hidden", "Sudden", "Dark" }));
lbl_visibilityModifier.setText("Visibility Modifier:");
lbl_filename.setFont(new java.awt.Font("Tahoma", 0, 10));
lbl_filename.setText("filename");
table_chartlist.setModel(model_chartlist);
table_chartlist.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
table_scroll2.setViewportView(table_chartlist);
jc_timed_judgment.setSelected(true);
jc_timed_judgment.setText("Use timed judment");
jc_timed_judgment.setToolTipText("Like Bemani games");
javax.swing.GroupLayout panel_infoLayout = new javax.swing.GroupLayout(panel_info);
panel_info.setLayout(panel_infoLayout);
panel_infoLayout.setHorizontalGroup(
panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel_infoLayout.createSequentialGroup()
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(table_scroll2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE)
.addComponent(lbl_title, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, panel_infoLayout.createSequentialGroup()
.addComponent(lbl_cover, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(panel_infoLayout.createSequentialGroup()
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_bpm1)
.addComponent(lbl_genre1)
.addComponent(lbl_level1)
.addComponent(lbl_notes1)
.addComponent(lbl_time1)
.addComponent(lbl_keys1))
.addGap(18, 18, 18)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_keys)
.addComponent(lbl_level, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)
.addComponent(lbl_notes, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)
.addComponent(lbl_time, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)
.addComponent(lbl_genre, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)
.addComponent(lbl_bpm, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)))
.addComponent(lbl_filename)))
.addComponent(lbl_artist, javax.swing.GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE)
.addGroup(panel_infoLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(panel_infoLayout.createSequentialGroup()
.addComponent(lbl_channelModifier)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(combo_channelModifier, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lbl_visibilityModifier))
.addGroup(panel_infoLayout.createSequentialGroup()
.addComponent(jc_timed_judgment)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jc_autoplay)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(bt_play)
.addComponent(combo_visibilityModifier, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap())
);
panel_infoLayout.setVerticalGroup(
panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_infoLayout.createSequentialGroup()
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(lbl_cover, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(panel_infoLayout.createSequentialGroup()
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_bpm1)
.addComponent(lbl_bpm))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_genre)
.addComponent(lbl_genre1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_level)
.addComponent(lbl_level1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_notes1)
.addComponent(lbl_notes))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_time)
.addComponent(lbl_time1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_keys1)
.addComponent(lbl_keys))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lbl_filename)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lbl_title, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lbl_artist)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(table_scroll2, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_visibilityModifier)
.addComponent(combo_visibilityModifier, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(combo_channelModifier, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_channelModifier))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_infoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jc_autoplay)
.addComponent(bt_play)
.addComponent(jc_timed_judgment)))
);
rank_group.add(jr_rank_hard);
jr_rank_hard.setText("Hard");
jr_rank_hard.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jr_rank_hard.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jr_rank_hard.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jr_rank_hardActionPerformed(evt);
}
});
combo_displays.setModel(new javax.swing.DefaultComboBoxModel(display_modes));
txt_res_height.setText("600");
txt_res_height.setEnabled(false);
txt_res_width.setText("800");
txt_res_width.setEnabled(false);
jc_vsync.setSelected(true);
jc_vsync.setText("Use VSync");
lbl_rank.setText("Rank:");
lbl_display.setText("Display:");
jc_custom_size.setFont(new java.awt.Font("Tahoma", 0, 10));
jc_custom_size.setText("Custom size:");
jc_custom_size.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
custom_size_clicked(evt);
}
});
rank_group.add(jr_rank_easy);
jr_rank_easy.setSelected(true);
jr_rank_easy.setText("Easy");
jr_rank_easy.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jr_rank_easy.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jr_rank_easy.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jr_rank_easyActionPerformed(evt);
}
});
lbl_hispeed.setText("Hi-Speed:");
lbl_res_x.setText("x");
rank_group.add(jr_rank_normal);
jr_rank_normal.setText("Normal");
jr_rank_normal.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jr_rank_normal.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jr_rank_normal.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jr_rank_normalActionPerformed(evt);
}
});
jc_full_screen.setText("Full screen");
bt_choose_dir.setText("Choose dir");
bt_choose_dir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bt_choose_dirActionPerformed(evt);
}
});
load_progress.setStringPainted(true);
js_hispeed.setModel(new javax.swing.SpinnerNumberModel(1.0d, 0.5d, 10.0d, 0.5d));
btn_configuration.setFont(new java.awt.Font("Tahoma", 0, 10));
btn_configuration.setText("Folders and Keys");
btn_configuration.setMaximumSize(new java.awt.Dimension(20, 20));
btn_configuration.setMinimumSize(new java.awt.Dimension(20, 20));
btn_configuration.setPreferredSize(new java.awt.Dimension(20, 20));
btn_configuration.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_configurationActionPerformed(evt);
}
});
btn_skin.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
btn_skin.setText("Skin Selection");
btn_skin.setEnabled(false);
btn_skin.setMaximumSize(new java.awt.Dimension(20, 20));
btn_skin.setMinimumSize(new java.awt.Dimension(20, 20));
btn_skin.setPreferredSize(new java.awt.Dimension(20, 20));
btn_skin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_skinActionPerformed(evt);
}
});
combo_dirs.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
combo_dirsActionPerformed(evt);
}
});
btn_reload.setText("Reload");
btn_reload.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_reloadActionPerformed(evt);
}
});
jc_bilinear.setSelected(true);
jc_bilinear.setText("Bilinear filter");
javax.swing.GroupLayout panel_settingLayout = new javax.swing.GroupLayout(panel_setting);
panel_setting.setLayout(panel_settingLayout);
panel_settingLayout.setHorizontalGroup(
panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_settingLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_settingLayout.createSequentialGroup()
.addComponent(jr_rank_easy)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jr_rank_normal)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jr_rank_hard))
.addComponent(lbl_rank)
.addGroup(panel_settingLayout.createSequentialGroup()
.addComponent(lbl_hispeed)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(js_hispeed, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE)
.addGap(72, 72, 72))
.addComponent(lbl_display)
.addComponent(combo_displays, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(panel_settingLayout.createSequentialGroup()
.addComponent(bt_choose_dir)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(load_progress, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(panel_settingLayout.createSequentialGroup()
.addComponent(jc_custom_size, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_res_width, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lbl_res_x)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_res_height, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(panel_settingLayout.createSequentialGroup()
.addComponent(jc_vsync)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jc_full_screen))
.addGroup(panel_settingLayout.createSequentialGroup()
.addComponent(combo_dirs, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn_reload))
.addGroup(panel_settingLayout.createSequentialGroup()
.addComponent(btn_configuration, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE))
.addComponent(btn_skin, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jc_bilinear))
.addContainerGap())
);
panel_settingLayout.setVerticalGroup(
panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_settingLayout.createSequentialGroup()
.addContainerGap(18, Short.MAX_VALUE)
.addGroup(panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(bt_choose_dir)
.addComponent(load_progress, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(lbl_rank)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jr_rank_easy)
.addComponent(jr_rank_normal)
.addComponent(jr_rank_hard))
.addGap(22, 22, 22)
.addGroup(panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(js_hispeed, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_hispeed))
.addGap(18, 18, 18)
.addComponent(lbl_display)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(combo_displays, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(txt_res_width, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_res_height, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_res_x)
.addComponent(jc_custom_size))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jc_vsync)
.addComponent(jc_full_screen))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jc_bilinear)
.addGap(8, 8, 8)
.addComponent(btn_configuration, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn_skin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34)
.addGroup(panel_settingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(combo_dirs, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn_reload))
.addContainerGap())
);
table_songlist.setAutoCreateRowSorter(true);
table_songlist.setModel(model_songlist);
table_songlist.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
table_songlist.getSelectionModel().addListSelectionListener(this);
table_scroll.setViewportView(table_songlist);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12));
jLabel1.setText("Source");
slider_main_vol.setPaintLabels(true);
slider_main_vol.setToolTipText("Main Volume");
slider_key_vol.setPaintLabels(true);
slider_key_vol.setToolTipText("Key Volume");
slider_key_vol.setValue(100);
slider_bgm_vol.setPaintLabels(true);
slider_bgm_vol.setToolTipText("BGM Volume");
slider_bgm_vol.setValue(100);
lbl_main_vol.setText("Main Volume:");
lbl_key_vol.setText("Key Volume:");
lbl_bgm_vol.setText("BGM Volume:");
jMenu1.setText("File");
mitem_exit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
mitem_exit.setText("Exit");
mitem_exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mitem_exitActionPerformed(evt);
}
});
jMenu1.add(mitem_exit);
jMenuBar1.add(jMenu1);
jMenu3.setText("Tools");
jMenuItem1.setText("OJM Dumper");
jMenu3.add(jMenuItem1);
jMenuItem2.setText("OJN <-> BMS");
jMenu3.add(jMenuItem2);
jMenuBar1.add(jMenu3);
menu_about.setText("About");
menu_about.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
menu_about.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
menu_aboutMouseClicked(evt);
}
});
jMenuBar1.add(menu_about);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1))
.addComponent(panel_setting, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_main_vol)
.addComponent(lbl_bgm_vol)
.addComponent(lbl_key_vol))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(slider_bgm_vol, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
.addComponent(slider_key_vol, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
.addComponent(slider_main_vol, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(panel_info, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txt_filter, javax.swing.GroupLayout.DEFAULT_SIZE, 311, Short.MAX_VALUE)
.addComponent(table_scroll, javax.swing.GroupLayout.DEFAULT_SIZE, 311, Short.MAX_VALUE)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel_info, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(table_scroll, javax.swing.GroupLayout.DEFAULT_SIZE, 505, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_filter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(panel_setting, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(lbl_main_vol)
.addComponent(slider_main_vol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(lbl_key_vol)
.addComponent(slider_key_vol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(lbl_bgm_vol)
.addComponent(slider_bgm_vol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
.addComponent(jLabel1)))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/main/java/org/aeonbits/owner/Converters.java b/src/main/java/org/aeonbits/owner/Converters.java
index f35b4f6..e6135eb 100644
--- a/src/main/java/org/aeonbits/owner/Converters.java
+++ b/src/main/java/org/aeonbits/owner/Converters.java
@@ -1,154 +1,149 @@
/*
* Copyright (c) 2013, Luigi R. Viggiano
* All rights reserved.
*
* This software is distributable under the BSD license.
* See the terms of the BSD license in the documentation provided with this software.
*/
package org.aeonbits.owner;
import java.beans.PropertyEditor;
import java.beans.PropertyEditorManager;
import java.io.File;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import static java.lang.reflect.Modifier.isStatic;
import static org.aeonbits.owner.Util.expandUserHome;
/**
* Converter class from {@link java.lang.String} to property types.
*
* @author Luigi R. Viggiano
*/
enum Converters {
PROPERTY_EDITOR {
@Override
Object convert(Class<?> targetType, String text) {
PropertyEditor editor = PropertyEditorManager.findEditor(targetType);
if (editor != null) {
editor.setAsText(text);
return editor.getValue();
}
return null;
}
},
FILE {
@Override
Object convert(Class<?> targetType, String text) {
if (targetType == File.class)
return new File(expandUserHome(text));
return null;
}
},
CLASS_WITH_STRING_CONSTRUCTOR {
@Override
Object convert(Class<?> targetType, String text) {
try {
Constructor<?> constructor = targetType.getConstructor(String.class);
return constructor.newInstance(text);
} catch (Exception e) {
return null;
}
}
},
CLASS_WITH_OBJECT_CONSTRUCTOR {
@Override
Object convert(Class<?> targetType, String text) {
try {
Constructor<?> constructor = targetType.getConstructor(Object.class);
return constructor.newInstance(text);
} catch (Exception e) {
return null;
}
}
},
CLASS_WITH_VALUE_OF_METHOD {
@Override
Object convert(Class<?> targetType, String text) {
try {
Method method = targetType.getMethod("valueOf", String.class);
if (isStatic(method.getModifiers()))
return method.invoke(null, text);
return null;
} catch (Exception e) {
return null;
}
}
},
CLASS {
@Override
Object convert(Class<?> targetType, String text) {
try {
return Class.forName(text);
} catch (ClassNotFoundException e) {
return null;
}
}
},
ARRAY {
@Override
Object convert(Class<?> targetType, String text) {
if (!targetType.isArray()) {
return null;
}
Class<?> type = targetType.getComponentType();
if (text.trim().isEmpty()) {
return Array.newInstance(type, 0);
}
- final String separator = ",";
- String[] chunks = text.split(separator);
+ final String separator = ","; // TODO: allow the user to specify his own, via annotation
+ String[] chunks = text.split(separator, -1);
Converters converter = findAppropriateConverter(type, chunks[0]);
Object[] result = (Object[]) Array.newInstance(type, chunks.length);
- try {
- for (int i = 0; i < chunks.length; i++) {
- final String chunk = chunks[i].trim();
- result[i] = converter.convert(type, chunk);
- }
- } catch (Exception e) {
- throw new UnsupportedOperationException(String.format("Cannot convert '%s' to %s", text,
- targetType.getCanonicalName()));
+ for (int i = 0; i < chunks.length; i++) {
+ final String chunk = chunks[i].trim();
+ result[i] = converter.convert(type, chunk);
}
return result;
}
private Converters findAppropriateConverter(Class<?> targetType, String text) {
for (Converters converter : values()) {
if (converter.convert(targetType, text) != null) {
return converter;
}
}
return UNSUPPORTED;
}
},
UNSUPPORTED {
@Override
Object convert(Class<?> targetType, String text) {
throw new UnsupportedOperationException(String.format("Cannot convert '%s' to %s", text,
targetType.getCanonicalName()));
}
};
abstract Object convert(Class<?> targetType, String text);
static Object unsupported(Class<?> targetType, String text) {
return UNSUPPORTED.convert(targetType, text);
}
}
| false | true | Object convert(Class<?> targetType, String text) {
if (!targetType.isArray()) {
return null;
}
Class<?> type = targetType.getComponentType();
if (text.trim().isEmpty()) {
return Array.newInstance(type, 0);
}
final String separator = ",";
String[] chunks = text.split(separator);
Converters converter = findAppropriateConverter(type, chunks[0]);
Object[] result = (Object[]) Array.newInstance(type, chunks.length);
try {
for (int i = 0; i < chunks.length; i++) {
final String chunk = chunks[i].trim();
result[i] = converter.convert(type, chunk);
}
} catch (Exception e) {
throw new UnsupportedOperationException(String.format("Cannot convert '%s' to %s", text,
targetType.getCanonicalName()));
}
return result;
}
| Object convert(Class<?> targetType, String text) {
if (!targetType.isArray()) {
return null;
}
Class<?> type = targetType.getComponentType();
if (text.trim().isEmpty()) {
return Array.newInstance(type, 0);
}
final String separator = ","; // TODO: allow the user to specify his own, via annotation
String[] chunks = text.split(separator, -1);
Converters converter = findAppropriateConverter(type, chunks[0]);
Object[] result = (Object[]) Array.newInstance(type, chunks.length);
for (int i = 0; i < chunks.length; i++) {
final String chunk = chunks[i].trim();
result[i] = converter.convert(type, chunk);
}
return result;
}
|
diff --git a/MandelBulb/src/mandelbulb/Main.java b/MandelBulb/src/mandelbulb/Main.java
index 53b4be6..e41cb48 100644
--- a/MandelBulb/src/mandelbulb/Main.java
+++ b/MandelBulb/src/mandelbulb/Main.java
@@ -1,126 +1,126 @@
/*
Copyright (C) 2009 Paul Richards.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package mandelbulb;
import java.awt.Color;
import javax.swing.JFrame;
public final class Main
{
private Main()
{
}
private final static class Evaluator implements Runnable
{
final RenderComponent renderComponent;
public Evaluator(RenderComponent renderComponent) {
this.renderComponent = renderComponent;
}
private static class Triplex
{
public final double x;
public final double y;
public final double z;
public Triplex(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
static Triplex add(Triplex a, Triplex b)
{
return new Triplex(
a.x + b.x,
a.y + b.y,
a.z + b.z);
}
static Triplex power(Triplex a, double n)
{
final double r = Math.sqrt(a.x*a.x + a.y*a.y + a.z*a.z);
final double theta = Math.atan2( Math.sqrt(a.x*a.x + a.y*a.y), a.z );
final double phi = Math.atan2(a.y, a.x);
return new Triplex(
Math.pow(r, n) * Math.sin(theta * n) * Math.cos(phi * n),
Math.pow(r, n) * Math.sin(theta * n) * Math.sin(phi * n),
Math.pow(r, n) * Math.cos(theta * n));
}
}
private static boolean evaluate(final Triplex c)
{
final int maxIter = 6;
final double n = 8;
Triplex z = new Triplex(0.0, 0.0, 0.0);
int i;
for (i = 0; i < maxIter && (z.x*z.x + z.y*z.y + z.z*z.z) < 100.0; i++) {
z = Triplex.add(Triplex.power(z, n), c);
}
return i == maxIter;
}
public void run() {
try {
OctTree tree = OctTree.createEmpty();
for (int level = 1; level <= 6; level++) {
final int resolution = 2 << level;
for (int iz = -resolution; iz < resolution; iz++) {
for (int iy = -resolution; iy < resolution; iy++) {
for (int ix = -resolution; ix < resolution; ix++) {
double x = (ix + 0.5) / resolution;
double y = (iy + 0.5) / resolution;
double z = (iz + 0.5) / resolution;
boolean inside = evaluate(new Triplex(x * 1.5, y * 1.5, z * 1.5));
double scale = 0.5 / resolution;
tree = tree.repSetRegion(x - scale, y - scale, z - scale, x + scale, y + scale, z + scale, inside);
}
}
}
final int nodeCount = tree.nodeCount();
System.out.println("Level " + level + ", resolution " + resolution + ", nodeCount " + nodeCount + ", nodeCount/resolution^2 " + (nodeCount / (resolution * resolution)));
renderComponent.setSegmentation(tree);
Thread.sleep(2000);
}
- renderComponent.setBackground(Color.GREEN);
+ renderComponent.setBackgroundColor(Color.GREEN);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args)
{
final RenderComponent renderComponent = new RenderComponent();
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(renderComponent);
frame.setSize(250, 250);
frame.setResizable(true);
frame.setVisible(true);
new Thread(new Evaluator(renderComponent)).start();
}
}
| true | true | public void run() {
try {
OctTree tree = OctTree.createEmpty();
for (int level = 1; level <= 6; level++) {
final int resolution = 2 << level;
for (int iz = -resolution; iz < resolution; iz++) {
for (int iy = -resolution; iy < resolution; iy++) {
for (int ix = -resolution; ix < resolution; ix++) {
double x = (ix + 0.5) / resolution;
double y = (iy + 0.5) / resolution;
double z = (iz + 0.5) / resolution;
boolean inside = evaluate(new Triplex(x * 1.5, y * 1.5, z * 1.5));
double scale = 0.5 / resolution;
tree = tree.repSetRegion(x - scale, y - scale, z - scale, x + scale, y + scale, z + scale, inside);
}
}
}
final int nodeCount = tree.nodeCount();
System.out.println("Level " + level + ", resolution " + resolution + ", nodeCount " + nodeCount + ", nodeCount/resolution^2 " + (nodeCount / (resolution * resolution)));
renderComponent.setSegmentation(tree);
Thread.sleep(2000);
}
renderComponent.setBackground(Color.GREEN);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
| public void run() {
try {
OctTree tree = OctTree.createEmpty();
for (int level = 1; level <= 6; level++) {
final int resolution = 2 << level;
for (int iz = -resolution; iz < resolution; iz++) {
for (int iy = -resolution; iy < resolution; iy++) {
for (int ix = -resolution; ix < resolution; ix++) {
double x = (ix + 0.5) / resolution;
double y = (iy + 0.5) / resolution;
double z = (iz + 0.5) / resolution;
boolean inside = evaluate(new Triplex(x * 1.5, y * 1.5, z * 1.5));
double scale = 0.5 / resolution;
tree = tree.repSetRegion(x - scale, y - scale, z - scale, x + scale, y + scale, z + scale, inside);
}
}
}
final int nodeCount = tree.nodeCount();
System.out.println("Level " + level + ", resolution " + resolution + ", nodeCount " + nodeCount + ", nodeCount/resolution^2 " + (nodeCount / (resolution * resolution)));
renderComponent.setSegmentation(tree);
Thread.sleep(2000);
}
renderComponent.setBackgroundColor(Color.GREEN);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
|
diff --git a/rdt/org.eclipse.ptp.rdt.sync.git.core/src/org/eclipse/ptp/internal/rdt/sync/git/core/GitSyncService.java b/rdt/org.eclipse.ptp.rdt.sync.git.core/src/org/eclipse/ptp/internal/rdt/sync/git/core/GitSyncService.java
index 94a25fe8d..8687900d2 100644
--- a/rdt/org.eclipse.ptp.rdt.sync.git.core/src/org/eclipse/ptp/internal/rdt/sync/git/core/GitSyncService.java
+++ b/rdt/org.eclipse.ptp.rdt.sync.git.core/src/org/eclipse/ptp/internal/rdt/sync/git/core/GitSyncService.java
@@ -1,481 +1,481 @@
/*******************************************************************************
* Copyright (c) 2011 Oak Ridge National Laboratory and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* John Eblen - initial implementation
*******************************************************************************/
package org.eclipse.ptp.internal.rdt.sync.git.core;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.ptp.internal.rdt.sync.git.core.messages.Messages;
import org.eclipse.ptp.rdt.sync.core.AbstractSyncFileFilter;
import org.eclipse.ptp.rdt.sync.core.RecursiveSubMonitor;
import org.eclipse.ptp.rdt.sync.core.SyncConfig;
import org.eclipse.ptp.rdt.sync.core.SyncFlag;
import org.eclipse.ptp.rdt.sync.core.SyncManager;
import org.eclipse.ptp.rdt.sync.core.exceptions.MissingConnectionException;
import org.eclipse.ptp.rdt.sync.core.exceptions.RemoteSyncException;
import org.eclipse.ptp.rdt.sync.core.exceptions.RemoteSyncMergeConflictException;
import org.eclipse.ptp.rdt.sync.core.services.AbstractSynchronizeService;
import org.eclipse.ptp.rdt.sync.core.services.ISynchronizeServiceDescriptor;
public class GitSyncService extends AbstractSynchronizeService {
// Simple pair class for bundling a project and build scenario.
// Since we use this as a key, equality testing is important.
// Note that we use the project location in equality testing, as this can change even though the project object stays the same.
private static class ProjectAndScenario {
private final IProject project;
private final SyncConfig scenario;
private final String projectLocation;
ProjectAndScenario(IProject p, SyncConfig bs) {
project = p;
scenario = bs;
projectLocation = p.getLocation().toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ProjectAndScenario other = (ProjectAndScenario) obj;
if (project == null) {
if (other.project != null) {
return false;
}
} else if (!project.equals(other.project)) {
return false;
}
if (projectLocation == null) {
if (other.projectLocation != null) {
return false;
}
} else if (!projectLocation.equals(other.projectLocation)) {
return false;
}
if (scenario == null) {
if (other.scenario != null) {
return false;
}
} else if (!scenario.equals(other.scenario)) {
return false;
}
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((project == null) ? 0 : project.hashCode());
result = prime * result + ((projectLocation == null) ? 0 : projectLocation.hashCode());
result = prime * result + ((scenario == null) ? 0 : scenario.hashCode());
return result;
}
}
private boolean hasBeenSynced = false;
private static final ReentrantLock syncLock = new ReentrantLock();
private Integer fWaitingThreadsCount = 0;
private Integer syncTaskId = -1; // ID for most recent synchronization task, functions as a time-stamp
private int finishedSyncTaskId = -1; // all synchronizations up to this ID (including it) have finished
private final Map<ProjectAndScenario, GitRemoteSyncConnection> syncConnectionMap = Collections
.synchronizedMap(new HashMap<ProjectAndScenario, GitRemoteSyncConnection>());
public GitSyncService(ISynchronizeServiceDescriptor descriptor) {
super(descriptor);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ptp.rdt.sync.core.serviceproviders.ISyncServiceProvider#checkout(org.eclipse.core.resources.IProject,
* org.eclipse.ptp.rdt.sync.core.SyncConfig, org.eclipse.core.runtime.IPath)
*/
@Override
public void checkout(IProject project, SyncConfig syncConfig, IPath[] paths) throws RemoteSyncException {
GitRemoteSyncConnection fSyncConnection = this.getSyncConnection(project, syncConfig, null);
if (fSyncConnection != null) {
fSyncConnection.checkout(paths);
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ptp.rdt.sync.core.serviceproviders.ISyncServiceProvider#checkoutRemote(org.eclipse.core.resources.IProject,
* org.eclipse.ptp.rdt.sync.core.SyncConfig, org.eclipse.core.runtime.IPath)
*/
@Override
public void checkoutRemoteCopy(IProject project, SyncConfig syncConfig, IPath[] paths) throws RemoteSyncException {
GitRemoteSyncConnection fSyncConnection = this.getSyncConnection(project, syncConfig, null);
if (fSyncConnection != null) {
fSyncConnection.checkoutRemoteCopy(paths);
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ptp.rdt.sync.core.serviceproviders.ISyncServiceProvider#close(org.eclipse.core.resources.IProject)
*/
@Override
public void close(IProject project) {
for (Map.Entry<ProjectAndScenario, GitRemoteSyncConnection> entry : syncConnectionMap.entrySet()) {
if (entry.getKey().project == project) {
entry.getValue().close();
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ptp.rdt.sync.core.serviceproviders.ISyncServiceProvider#getMergeConflictFiles()
*/
@Override
public Set<IPath> getMergeConflictFiles(IProject project, SyncConfig syncConfig) throws RemoteSyncException {
GitRemoteSyncConnection fSyncConnection = this.getSyncConnection(project, syncConfig, null);
if (fSyncConnection == null) {
return new HashSet<IPath>();
} else {
return fSyncConnection.getMergeConflictFiles();
}
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ptp.rdt.sync.core.serviceproviders.ISyncServiceProvider#getMergeConflictParts(org.eclipse.core.resources.IFile)
*/
@Override
public String[] getMergeConflictParts(IProject project, SyncConfig syncConfig, IFile file) throws RemoteSyncException {
GitRemoteSyncConnection fSyncConnection = this.getSyncConnection(project, syncConfig, null);
if (fSyncConnection == null) {
return null;
} else {
return fSyncConnection.getMergeConflictParts(file);
}
}
// Return appropriate sync connection or null for configs with no sync provider or if the connection is missing.
// Creates a new sync connection if necessary. This function must properly maintain the map of connections and also remember
// to set the file filter (always, not just for new connections).
// TODO: Create progress monitor if passed monitor is null.
private synchronized GitRemoteSyncConnection getSyncConnection(IProject project, SyncConfig syncConfig, IProgressMonitor monitor)
throws RemoteSyncException {
try {
if (syncConfig.getSyncProviderId() == null) {
return null;
}
ProjectAndScenario pas = new ProjectAndScenario(project, syncConfig);
if (!syncConnectionMap.containsKey(pas)) {
try {
GitRemoteSyncConnection grsc = new GitRemoteSyncConnection(project, project.getLocation().toString(),
syncConfig, getSyncFileFilter(project), monitor);
syncConnectionMap.put(pas, grsc);
} catch (MissingConnectionException e) {
return null;
}
}
GitRemoteSyncConnection fSyncConnection = syncConnectionMap.get(pas);
fSyncConnection.setFileFilter(getSyncFileFilter(project));
return fSyncConnection;
} finally {
if (monitor != null) {
monitor.done();
}
}
}
// Paths that the Git sync provider can ignore.
private boolean irrelevantPath(IProject project, IResource resource) {
if (SyncManager.getFileFilter(project).shouldIgnore(resource)) {
return true;
}
String path = resource.getFullPath().toString();
if (path.endsWith("/" + GitRemoteSyncConnection.gitDir)) { //$NON-NLS-1$
return true;
} else if (path.endsWith("/.git")) { //$NON-NLS-1$
return true;
} else if (path.endsWith("/.settings")) { //$NON-NLS-1$
return true;
} else {
return false;
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ptp.rdt.sync.core.serviceproviders.ISyncServiceProvider#setResolved(org.eclipse.core.resources.IProject,
* org.eclipse.ptp.rdt.sync.core.SyncConfig, org.eclipse.core.runtime.IPath)
*/
@Override
public void setMergeAsResolved(IProject project, SyncConfig syncConfig, IPath[] paths) throws RemoteSyncException {
GitRemoteSyncConnection fSyncConnection = this.getSyncConnection(project, syncConfig, null);
if (fSyncConnection != null) {
fSyncConnection.setMergeAsResolved(paths);
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ptp.rdt.sync.core.serviceproviders.ISyncServiceProvider#synchronize(org.eclipse.core.resources.IProject,
* org.eclipse.core.resources.IResourceDelta, org.eclipse.ptp.rdt.sync.core.SyncFileFilter,
* org.eclipse.core.runtime.IProgressMonitor, java.util.EnumSet)
*/
@Override
public void synchronize(final IProject project, SyncConfig syncConfig, IResourceDelta delta, IProgressMonitor monitor,
EnumSet<SyncFlag> syncFlags) throws CoreException {
RecursiveSubMonitor subMon = RecursiveSubMonitor.convert(monitor, 1000);
// On first sync, place .gitignore in directories. This is useful for folders that are already present and thus are never
// captured by a resource add or change event. (This can happen for projects converted to sync projects.)
if (!hasBeenSynced) {
+ hasBeenSynced = true;
project.accept(new IResourceVisitor() {
@Override
public boolean visit(IResource resource) throws CoreException {
if (irrelevantPath(project, resource)) {
return false;
}
if (resource.getType() == IResource.FOLDER) {
IFile emptyFile = project.getFile(resource.getProjectRelativePath().addTrailingSeparator() + ".gitignore"); //$NON-NLS-1$
try {
if (!(emptyFile.exists())) {
emptyFile.create(new ByteArrayInputStream("".getBytes()), false, null); //$NON-NLS-1$
}
} catch (CoreException e) {
// Nothing to do. Can happen if another thread creates the file between the check and creation.
}
}
return true;
}
});
}
- hasBeenSynced = true;
// Make a visitor that explores the delta. At the moment, this visitor is responsible for two tasks (the list may grow in
// the future):
// 1) Find out if there are any "relevant" resource changes (changes that need to be mirrored remotely)
// 2) Add an empty ".gitignore" file to new directories so that Git will sync them
class SyncResourceDeltaVisitor implements IResourceDeltaVisitor {
private boolean relevantChangeFound = false;
public boolean isRelevant() {
return relevantChangeFound;
}
@Override
public boolean visit(IResourceDelta delta) throws CoreException {
if (irrelevantPath(project, delta.getResource())) {
return false;
} else {
if ((delta.getAffectedChildren().length == 0) && (delta.getFlags() != IResourceDelta.MARKERS)) {
relevantChangeFound = true;
}
}
// Add .gitignore to empty directories
if (delta.getResource().getType() == IResource.FOLDER
&& (delta.getKind() == IResourceDelta.ADDED || delta.getKind() == IResourceDelta.CHANGED)) {
IFile emptyFile = project.getFile(delta.getResource().getProjectRelativePath().addTrailingSeparator()
+ ".gitignore"); //$NON-NLS-1$
try {
if (!(emptyFile.exists())) {
emptyFile.create(new ByteArrayInputStream("".getBytes()), false, null); //$NON-NLS-1$
}
} catch (CoreException e) {
// Nothing to do. Can happen if another thread creates the file between the check and creation.
}
}
return true;
}
}
// Explore delta only if it is not null
boolean hasRelevantChangedResources = false;
if (delta != null) {
SyncResourceDeltaVisitor visitor = new SyncResourceDeltaVisitor();
delta.accept(visitor);
hasRelevantChangedResources = visitor.isRelevant();
}
try {
/*
* A synchronize with SyncFlag.FORCE guarantees that both directories are in sync.
*
* More precise: it guarantees that all changes written to disk at the moment of the call are guaranteed to be
* synchronized between both directories. No guarantees are given for changes occurring during the synchronize call.
*
* To satisfy this guarantee, this call needs to make sure that both the current delta and all outstanding sync requests
* finish before this call returns.
*
* Example: Why sync if current delta is empty? The RemoteMakeBuilder forces a sync before and after building. In some
* cases, we want to ensure repos are synchronized regardless of the passed delta, which can be set to null.
*/
// TODO: We are not using the individual "sync to local" and "sync to remote" flags yet.
if (syncFlags.contains(SyncFlag.DISABLE_SYNC)) {
return;
}
if ((syncFlags == SyncFlag.NO_FORCE) && (!(hasRelevantChangedResources))) {
return;
}
int mySyncTaskId;
synchronized (syncTaskId) {
syncTaskId++;
mySyncTaskId = syncTaskId;
// suggestion for Deltas: add delta to list of deltas
}
synchronized (fWaitingThreadsCount) {
if (fWaitingThreadsCount > 0 && syncFlags == SyncFlag.NO_FORCE) {
return; // the queued thread will do the work for us. And we don't have to wait because of NO_FORCE
} else {
fWaitingThreadsCount++;
}
}
// lock syncLock. interruptible by progress monitor
try {
while (!syncLock.tryLock(50, TimeUnit.MILLISECONDS)) {
if (subMon.isCanceled()) {
throw new CoreException(new Status(IStatus.CANCEL, Activator.PLUGIN_ID, Messages.GitServiceProvider_1));
}
}
} catch (InterruptedException e1) {
throw new CoreException(new Status(IStatus.CANCEL, Activator.PLUGIN_ID, Messages.GitServiceProvider_2));
} finally {
synchronized (fWaitingThreadsCount) {
fWaitingThreadsCount--;
}
}
try {
// Do not sync if there are merge conflicts.
// This check must be done after acquiring the sync lock. Otherwise, the merge may trigger a sync that sees no
// conflicting files and proceeds to sync again - depending on how quickly the first sync records the data.
if (!(this.getMergeConflictFiles(project, syncConfig).isEmpty())) {
throw new RemoteSyncMergeConflictException(Messages.GitServiceProvider_4);
}
if (mySyncTaskId <= finishedSyncTaskId) { // some other thread has already done the work for us
return;
}
if (syncConfig == null) {
throw new RuntimeException(Messages.GitServiceProvider_3 + project.getName());
}
subMon.subTask(Messages.GitServiceProvider_7);
GitRemoteSyncConnection fSyncConnection = this.getSyncConnection(project, syncConfig, subMon.newChild(98));
if (fSyncConnection == null) {
// Should never happen
if (syncConfig.getSyncProviderId() == null) {
throw new RemoteSyncException(Messages.GitServiceProvider_5);
// Happens whenever connection does not exist
} else {
return;
}
}
// This synchronization operation will include all tasks up to current syncTaskId
// syncTaskId can be larger than mySyncTaskId (than we do also the work for other threads)
// we might synchronize even more than that if a file is already saved but syncTaskId wasn't increased yet
// thus we cannot guarantee a maximum but we can guarantee syncTaskId as a minimum
// suggestion for Deltas: make local copy of list of deltas, remove list of deltas
int willFinishTaskId;
synchronized (syncTaskId) {
willFinishTaskId = syncTaskId;
}
try {
subMon.subTask(Messages.GitServiceProvider_8);
fSyncConnection.sync(subMon.newChild(900), true);
// Unlike other exceptions, we need to do some post-sync activities after a merge exception.
// TODO: Refactor code to get rid of duplication of post-sync activities.
} catch (RemoteSyncMergeConflictException e) {
subMon.subTask(Messages.GitServiceProvider_9);
project.refreshLocal(IResource.DEPTH_INFINITE, subMon.newChild(1));
throw e;
}
finishedSyncTaskId = willFinishTaskId;
// TODO: review exception handling
} finally {
syncLock.unlock();
}
// Sync successful - re-enable error messages. This is really UI code, but there is no way at the moment to notify UI
// of a successful sync.
SyncManager.setShowErrors(project, true);
// Refresh after sync to display changes
subMon.subTask(Messages.GitServiceProvider_10);
project.refreshLocal(IResource.DEPTH_INFINITE, subMon.newChild(1));
} finally {
if (monitor != null) {
monitor.done();
}
}
}
@Override
public AbstractSyncFileFilter getSyncFileFilter(IProject project) {
return GitSyncFileFilter.getFilter(project);
}
@Override
public void setSyncFileFilter(IProject project, AbstractSyncFileFilter filter) {
Repository repository;
try {
repository = GitRemoteSyncConnection.getLocalRepo(project.getLocation().toString());
} catch (IOException e) {
Activator.log("Unable to save file filter for project " + project.getName(), e); //$NON-NLS-1$
return;
}
assert repository != null : Messages.GitSyncService_0;
GitSyncFileFilter.setFilter(project, filter, repository);
}
}
| false | true | public void synchronize(final IProject project, SyncConfig syncConfig, IResourceDelta delta, IProgressMonitor monitor,
EnumSet<SyncFlag> syncFlags) throws CoreException {
RecursiveSubMonitor subMon = RecursiveSubMonitor.convert(monitor, 1000);
// On first sync, place .gitignore in directories. This is useful for folders that are already present and thus are never
// captured by a resource add or change event. (This can happen for projects converted to sync projects.)
if (!hasBeenSynced) {
project.accept(new IResourceVisitor() {
@Override
public boolean visit(IResource resource) throws CoreException {
if (irrelevantPath(project, resource)) {
return false;
}
if (resource.getType() == IResource.FOLDER) {
IFile emptyFile = project.getFile(resource.getProjectRelativePath().addTrailingSeparator() + ".gitignore"); //$NON-NLS-1$
try {
if (!(emptyFile.exists())) {
emptyFile.create(new ByteArrayInputStream("".getBytes()), false, null); //$NON-NLS-1$
}
} catch (CoreException e) {
// Nothing to do. Can happen if another thread creates the file between the check and creation.
}
}
return true;
}
});
}
hasBeenSynced = true;
// Make a visitor that explores the delta. At the moment, this visitor is responsible for two tasks (the list may grow in
// the future):
// 1) Find out if there are any "relevant" resource changes (changes that need to be mirrored remotely)
// 2) Add an empty ".gitignore" file to new directories so that Git will sync them
class SyncResourceDeltaVisitor implements IResourceDeltaVisitor {
private boolean relevantChangeFound = false;
public boolean isRelevant() {
return relevantChangeFound;
}
@Override
public boolean visit(IResourceDelta delta) throws CoreException {
if (irrelevantPath(project, delta.getResource())) {
return false;
} else {
if ((delta.getAffectedChildren().length == 0) && (delta.getFlags() != IResourceDelta.MARKERS)) {
relevantChangeFound = true;
}
}
// Add .gitignore to empty directories
if (delta.getResource().getType() == IResource.FOLDER
&& (delta.getKind() == IResourceDelta.ADDED || delta.getKind() == IResourceDelta.CHANGED)) {
IFile emptyFile = project.getFile(delta.getResource().getProjectRelativePath().addTrailingSeparator()
+ ".gitignore"); //$NON-NLS-1$
try {
if (!(emptyFile.exists())) {
emptyFile.create(new ByteArrayInputStream("".getBytes()), false, null); //$NON-NLS-1$
}
} catch (CoreException e) {
// Nothing to do. Can happen if another thread creates the file between the check and creation.
}
}
return true;
}
}
// Explore delta only if it is not null
boolean hasRelevantChangedResources = false;
if (delta != null) {
SyncResourceDeltaVisitor visitor = new SyncResourceDeltaVisitor();
delta.accept(visitor);
hasRelevantChangedResources = visitor.isRelevant();
}
try {
/*
* A synchronize with SyncFlag.FORCE guarantees that both directories are in sync.
*
* More precise: it guarantees that all changes written to disk at the moment of the call are guaranteed to be
* synchronized between both directories. No guarantees are given for changes occurring during the synchronize call.
*
* To satisfy this guarantee, this call needs to make sure that both the current delta and all outstanding sync requests
* finish before this call returns.
*
* Example: Why sync if current delta is empty? The RemoteMakeBuilder forces a sync before and after building. In some
* cases, we want to ensure repos are synchronized regardless of the passed delta, which can be set to null.
*/
// TODO: We are not using the individual "sync to local" and "sync to remote" flags yet.
if (syncFlags.contains(SyncFlag.DISABLE_SYNC)) {
return;
}
if ((syncFlags == SyncFlag.NO_FORCE) && (!(hasRelevantChangedResources))) {
return;
}
int mySyncTaskId;
synchronized (syncTaskId) {
syncTaskId++;
mySyncTaskId = syncTaskId;
// suggestion for Deltas: add delta to list of deltas
}
synchronized (fWaitingThreadsCount) {
if (fWaitingThreadsCount > 0 && syncFlags == SyncFlag.NO_FORCE) {
return; // the queued thread will do the work for us. And we don't have to wait because of NO_FORCE
} else {
fWaitingThreadsCount++;
}
}
// lock syncLock. interruptible by progress monitor
try {
while (!syncLock.tryLock(50, TimeUnit.MILLISECONDS)) {
if (subMon.isCanceled()) {
throw new CoreException(new Status(IStatus.CANCEL, Activator.PLUGIN_ID, Messages.GitServiceProvider_1));
}
}
} catch (InterruptedException e1) {
throw new CoreException(new Status(IStatus.CANCEL, Activator.PLUGIN_ID, Messages.GitServiceProvider_2));
} finally {
synchronized (fWaitingThreadsCount) {
fWaitingThreadsCount--;
}
}
try {
// Do not sync if there are merge conflicts.
// This check must be done after acquiring the sync lock. Otherwise, the merge may trigger a sync that sees no
// conflicting files and proceeds to sync again - depending on how quickly the first sync records the data.
if (!(this.getMergeConflictFiles(project, syncConfig).isEmpty())) {
throw new RemoteSyncMergeConflictException(Messages.GitServiceProvider_4);
}
if (mySyncTaskId <= finishedSyncTaskId) { // some other thread has already done the work for us
return;
}
if (syncConfig == null) {
throw new RuntimeException(Messages.GitServiceProvider_3 + project.getName());
}
subMon.subTask(Messages.GitServiceProvider_7);
GitRemoteSyncConnection fSyncConnection = this.getSyncConnection(project, syncConfig, subMon.newChild(98));
if (fSyncConnection == null) {
// Should never happen
if (syncConfig.getSyncProviderId() == null) {
throw new RemoteSyncException(Messages.GitServiceProvider_5);
// Happens whenever connection does not exist
} else {
return;
}
}
// This synchronization operation will include all tasks up to current syncTaskId
// syncTaskId can be larger than mySyncTaskId (than we do also the work for other threads)
// we might synchronize even more than that if a file is already saved but syncTaskId wasn't increased yet
// thus we cannot guarantee a maximum but we can guarantee syncTaskId as a minimum
// suggestion for Deltas: make local copy of list of deltas, remove list of deltas
int willFinishTaskId;
synchronized (syncTaskId) {
willFinishTaskId = syncTaskId;
}
try {
subMon.subTask(Messages.GitServiceProvider_8);
fSyncConnection.sync(subMon.newChild(900), true);
// Unlike other exceptions, we need to do some post-sync activities after a merge exception.
// TODO: Refactor code to get rid of duplication of post-sync activities.
} catch (RemoteSyncMergeConflictException e) {
subMon.subTask(Messages.GitServiceProvider_9);
project.refreshLocal(IResource.DEPTH_INFINITE, subMon.newChild(1));
throw e;
}
finishedSyncTaskId = willFinishTaskId;
// TODO: review exception handling
} finally {
syncLock.unlock();
}
// Sync successful - re-enable error messages. This is really UI code, but there is no way at the moment to notify UI
// of a successful sync.
SyncManager.setShowErrors(project, true);
// Refresh after sync to display changes
subMon.subTask(Messages.GitServiceProvider_10);
project.refreshLocal(IResource.DEPTH_INFINITE, subMon.newChild(1));
} finally {
if (monitor != null) {
monitor.done();
}
}
}
| public void synchronize(final IProject project, SyncConfig syncConfig, IResourceDelta delta, IProgressMonitor monitor,
EnumSet<SyncFlag> syncFlags) throws CoreException {
RecursiveSubMonitor subMon = RecursiveSubMonitor.convert(monitor, 1000);
// On first sync, place .gitignore in directories. This is useful for folders that are already present and thus are never
// captured by a resource add or change event. (This can happen for projects converted to sync projects.)
if (!hasBeenSynced) {
hasBeenSynced = true;
project.accept(new IResourceVisitor() {
@Override
public boolean visit(IResource resource) throws CoreException {
if (irrelevantPath(project, resource)) {
return false;
}
if (resource.getType() == IResource.FOLDER) {
IFile emptyFile = project.getFile(resource.getProjectRelativePath().addTrailingSeparator() + ".gitignore"); //$NON-NLS-1$
try {
if (!(emptyFile.exists())) {
emptyFile.create(new ByteArrayInputStream("".getBytes()), false, null); //$NON-NLS-1$
}
} catch (CoreException e) {
// Nothing to do. Can happen if another thread creates the file between the check and creation.
}
}
return true;
}
});
}
// Make a visitor that explores the delta. At the moment, this visitor is responsible for two tasks (the list may grow in
// the future):
// 1) Find out if there are any "relevant" resource changes (changes that need to be mirrored remotely)
// 2) Add an empty ".gitignore" file to new directories so that Git will sync them
class SyncResourceDeltaVisitor implements IResourceDeltaVisitor {
private boolean relevantChangeFound = false;
public boolean isRelevant() {
return relevantChangeFound;
}
@Override
public boolean visit(IResourceDelta delta) throws CoreException {
if (irrelevantPath(project, delta.getResource())) {
return false;
} else {
if ((delta.getAffectedChildren().length == 0) && (delta.getFlags() != IResourceDelta.MARKERS)) {
relevantChangeFound = true;
}
}
// Add .gitignore to empty directories
if (delta.getResource().getType() == IResource.FOLDER
&& (delta.getKind() == IResourceDelta.ADDED || delta.getKind() == IResourceDelta.CHANGED)) {
IFile emptyFile = project.getFile(delta.getResource().getProjectRelativePath().addTrailingSeparator()
+ ".gitignore"); //$NON-NLS-1$
try {
if (!(emptyFile.exists())) {
emptyFile.create(new ByteArrayInputStream("".getBytes()), false, null); //$NON-NLS-1$
}
} catch (CoreException e) {
// Nothing to do. Can happen if another thread creates the file between the check and creation.
}
}
return true;
}
}
// Explore delta only if it is not null
boolean hasRelevantChangedResources = false;
if (delta != null) {
SyncResourceDeltaVisitor visitor = new SyncResourceDeltaVisitor();
delta.accept(visitor);
hasRelevantChangedResources = visitor.isRelevant();
}
try {
/*
* A synchronize with SyncFlag.FORCE guarantees that both directories are in sync.
*
* More precise: it guarantees that all changes written to disk at the moment of the call are guaranteed to be
* synchronized between both directories. No guarantees are given for changes occurring during the synchronize call.
*
* To satisfy this guarantee, this call needs to make sure that both the current delta and all outstanding sync requests
* finish before this call returns.
*
* Example: Why sync if current delta is empty? The RemoteMakeBuilder forces a sync before and after building. In some
* cases, we want to ensure repos are synchronized regardless of the passed delta, which can be set to null.
*/
// TODO: We are not using the individual "sync to local" and "sync to remote" flags yet.
if (syncFlags.contains(SyncFlag.DISABLE_SYNC)) {
return;
}
if ((syncFlags == SyncFlag.NO_FORCE) && (!(hasRelevantChangedResources))) {
return;
}
int mySyncTaskId;
synchronized (syncTaskId) {
syncTaskId++;
mySyncTaskId = syncTaskId;
// suggestion for Deltas: add delta to list of deltas
}
synchronized (fWaitingThreadsCount) {
if (fWaitingThreadsCount > 0 && syncFlags == SyncFlag.NO_FORCE) {
return; // the queued thread will do the work for us. And we don't have to wait because of NO_FORCE
} else {
fWaitingThreadsCount++;
}
}
// lock syncLock. interruptible by progress monitor
try {
while (!syncLock.tryLock(50, TimeUnit.MILLISECONDS)) {
if (subMon.isCanceled()) {
throw new CoreException(new Status(IStatus.CANCEL, Activator.PLUGIN_ID, Messages.GitServiceProvider_1));
}
}
} catch (InterruptedException e1) {
throw new CoreException(new Status(IStatus.CANCEL, Activator.PLUGIN_ID, Messages.GitServiceProvider_2));
} finally {
synchronized (fWaitingThreadsCount) {
fWaitingThreadsCount--;
}
}
try {
// Do not sync if there are merge conflicts.
// This check must be done after acquiring the sync lock. Otherwise, the merge may trigger a sync that sees no
// conflicting files and proceeds to sync again - depending on how quickly the first sync records the data.
if (!(this.getMergeConflictFiles(project, syncConfig).isEmpty())) {
throw new RemoteSyncMergeConflictException(Messages.GitServiceProvider_4);
}
if (mySyncTaskId <= finishedSyncTaskId) { // some other thread has already done the work for us
return;
}
if (syncConfig == null) {
throw new RuntimeException(Messages.GitServiceProvider_3 + project.getName());
}
subMon.subTask(Messages.GitServiceProvider_7);
GitRemoteSyncConnection fSyncConnection = this.getSyncConnection(project, syncConfig, subMon.newChild(98));
if (fSyncConnection == null) {
// Should never happen
if (syncConfig.getSyncProviderId() == null) {
throw new RemoteSyncException(Messages.GitServiceProvider_5);
// Happens whenever connection does not exist
} else {
return;
}
}
// This synchronization operation will include all tasks up to current syncTaskId
// syncTaskId can be larger than mySyncTaskId (than we do also the work for other threads)
// we might synchronize even more than that if a file is already saved but syncTaskId wasn't increased yet
// thus we cannot guarantee a maximum but we can guarantee syncTaskId as a minimum
// suggestion for Deltas: make local copy of list of deltas, remove list of deltas
int willFinishTaskId;
synchronized (syncTaskId) {
willFinishTaskId = syncTaskId;
}
try {
subMon.subTask(Messages.GitServiceProvider_8);
fSyncConnection.sync(subMon.newChild(900), true);
// Unlike other exceptions, we need to do some post-sync activities after a merge exception.
// TODO: Refactor code to get rid of duplication of post-sync activities.
} catch (RemoteSyncMergeConflictException e) {
subMon.subTask(Messages.GitServiceProvider_9);
project.refreshLocal(IResource.DEPTH_INFINITE, subMon.newChild(1));
throw e;
}
finishedSyncTaskId = willFinishTaskId;
// TODO: review exception handling
} finally {
syncLock.unlock();
}
// Sync successful - re-enable error messages. This is really UI code, but there is no way at the moment to notify UI
// of a successful sync.
SyncManager.setShowErrors(project, true);
// Refresh after sync to display changes
subMon.subTask(Messages.GitServiceProvider_10);
project.refreshLocal(IResource.DEPTH_INFINITE, subMon.newChild(1));
} finally {
if (monitor != null) {
monitor.done();
}
}
}
|
diff --git a/src/main/java/org/jacop/fz/Solve.java b/src/main/java/org/jacop/fz/Solve.java
index 036b0720..ec666bbd 100644
--- a/src/main/java/org/jacop/fz/Solve.java
+++ b/src/main/java/org/jacop/fz/Solve.java
@@ -1,1208 +1,1208 @@
/**
* Solve.java
* This file is part of JaCoP.
*
* JaCoP is a Java Constraint Programming solver.
*
* Copyright (C) 2000-2008 Krzysztof Kuchcinski and Radoslaw Szymanek
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* Notwithstanding any other provision of this License, the copyright
* owners of this work supplement the terms of this License with terms
* prohibiting misrepresentation of the origin of this work and requiring
* that modified versions of this work be marked in reasonable ways as
* different from the original version. This supplement of the license
* terms is in accordance with Section 7 of GNU Affero General Public
* License version 3.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.jacop.fz;
import java.util.ArrayList;
import java.util.Comparator;
import org.jacop.constraints.Constraint;
import org.jacop.constraints.XgtC;
import org.jacop.constraints.XltC;
import org.jacop.constraints.XplusYeqC;
import org.jacop.core.BooleanVar;
import org.jacop.core.IntDomain;
import org.jacop.core.IntVar;
import org.jacop.core.Store;
import org.jacop.core.Var;
import org.jacop.core.ValueEnumeration;
import org.jacop.search.CreditCalculator;
import org.jacop.search.DepthFirstSearch;
import org.jacop.search.IndomainMin;
import org.jacop.search.LDS;
import org.jacop.search.Search;
import org.jacop.search.SelectChoicePoint;
import org.jacop.search.SimpleSelect;
import org.jacop.search.SimpleSolutionListener;
import org.jacop.set.core.SetVar;
import org.jacop.set.search.IndomainSetMin;
/**
*
* The parser part responsible for parsing the solve part of the flatzinc file,
* building a related search and executing it.
*
* Current implementation runs also final search on all variables to ensure
* that they are ground.
*
* @author Krzysztof Kuchcinski
*
*/
public class Solve implements ParserTreeConstants {
Tables dictionary;
Options options;
Store store;
int initNumberConstraints;
int NumberBoolVariables;
Thread tread;
java.lang.management.ThreadMXBean searchTimeMeter;
long startCPU;
//ComparatorVariable tieBreaking=null;
SelectChoicePoint<Var> variable_selection;
ArrayList<Search<Var>> list_seq_searches = null;
boolean debug = false;
boolean print_search_info = false;
boolean setSearch = false;
boolean heuristicSeqSearch = false;
Var costVariable;
int costValue;
Parser parser;
// -------- for print-out of statistics
boolean singleSearch;
boolean Result;
boolean optimization;
SearchItem si;
// single search
boolean defaultSearch;
DepthFirstSearch<Var> label;
DepthFirstSearch<Var>[] final_search;
// sequence search
Search<Var> final_search_seq;
// --------
/**
* It creates a parser for the solve part of the flatzinc file.
*
* @param store the constraint store within which context the search will take place.
*/
public Solve(Store store) {
this.store = store;
}
/**
* It parses the solve part.
*
* @param node the current parsing node.
* @param table the table containing all the various variable definitions encoutered thus far.
* @param opt option specifies to flatzinc parser in respect to search (e.g. all solutions).
*/
public void search(ASTSolveItem node, Tables table, Options opt) {
// System.out.println(table);
initNumberConstraints = store.numberConstraints();
if (opt.getVerbose())
System.out.println("%% Model constraints defined.\n%% Variables = "+store.size() + ", Bool variables = "+NumberBoolVariables +
", Constraints = "+initNumberConstraints);
dictionary = table;
options = opt;
int solveKind=-1;
// node.dump("");
ASTSolveKind kind;
int count = node.jjtGetNumChildren();
// System.out.println("Number constraints = "+store.numberConstraints());
// System.out.println("Number of variables = "+store.size());
if (count == 1) {// only solve kind => default search
SearchItem si_int = new SearchItem(store, dictionary);
kind = (ASTSolveKind)node.jjtGetChild(0);
solveKind = getKind(kind.getKind());
run_single_search(solveKind, kind, null);
}
else if (count == 2) {// single annotation
SearchItem si = new SearchItem(store, dictionary);
si.searchParameters(node, 0);
// System.out.println("1. *** "+si);
String search_type = si.type();
if (search_type.equals("int_search") || search_type.equals("set_search") ||
search_type.equals("bool_search")) {
kind = (ASTSolveKind)node.jjtGetChild(1);
solveKind = getKind(kind.getKind());
run_single_search(solveKind, kind, si);
}
else if (search_type.equals("seq_search")) {
kind = (ASTSolveKind)node.jjtGetChild(1);
solveKind = getKind(kind.getKind());
run_sequence_search(solveKind, kind, si);
}
else {
System.err.println("Not recognized structure of solve statement \""+search_type+"\"; compilation aborted");
System.exit(0);
}
}
else if (count > 2) {// several annotations
SearchItem si = new SearchItem(store, dictionary);
si.searchParametersForSeveralAnnotations(node, 0);
// System.out.println("*** "+si +"\nsize="+si.search_seqSize());
kind = (ASTSolveKind)node.jjtGetChild(si.search_seqSize());
solveKind = getKind(kind.getKind());
// System.out.println ("kind="+kind+" solveKind="+solveKind);
run_sequence_search(solveKind, kind, si);
}
else
{
System.err.println("Not recognized structure of solve statement; compilation aborted");
System.exit(0);
}
}
void run_single_search(int solveKind, SimpleNode kind, SearchItem si) {
singleSearch = true;
defaultSearch = false;
this.si = si;
if (options.getVerbose()) {
String solve="notKnown";
switch (solveKind) {
case 0:
solve = "%% satisfy"; break; // satisfy
case 1:
solve = "%% minimize("+ getCost((ASTSolveExpr)kind.jjtGetChild(0))+") "; break; // minimize
case 2:
solve = "%% maximize("+ getCost((ASTSolveExpr)kind.jjtGetChild(0))+") "; break; // maximize
}
System.out.println(solve + " : " + si);
}
IntVar cost = null;
IntVar max_cost = null;
label = null;
optimization = false;
list_seq_searches = new ArrayList<Search<Var>>();
label = null;
if (si != null) {
if (si.type().equals("int_search")) {
label = int_search(si);
list_seq_searches.add(label);
//label.setSolutionListener(new EmptyListener<Var>());
label.setPrintInfo(false);
// time-out option
int to = options.getTimeOut();
if (to > 0)
label.setTimeOut(to);
}
else if (si.type().equals("bool_search")) {
label = int_search(si);
list_seq_searches.add(label);
//label.setSolutionListener(new EmptyListener<Var>());
label.setPrintInfo(false);
// time-out option
int to = options.getTimeOut();
if (to > 0)
label.setTimeOut(to);
}
else if (si.type().equals("set_search")) {
label = set_search(si);
list_seq_searches.add(label);
setSearch=true;
//label.setSolutionListener(new EmptyListener<Var>());
label.setPrintInfo(false);
// time-out option
int to = options.getTimeOut();
if (to > 0)
label.setTimeOut(to);
}
else {
System.err.println("Not recognized or supported search type \""+si.type()+"\"; compilation aborted");
System.exit(0);
}
}
if (solveKind > 0) {
optimization = true;
cost = getCost((ASTSolveExpr)kind.jjtGetChild(0));
if ( solveKind == 1) // minimize
costVariable = cost;
else { // maximize
max_cost = new IntVar(store, "-"+cost.id(), IntDomain.MinInt,
IntDomain.MaxInt);
pose(new XplusYeqC(max_cost, cost, 0));
costVariable = max_cost;
}
}
// adds child search for cost; to be sure that all variables get a value
final_search = setSubSearchForAll(label, options);
Search last_search;
if (si == null) {
defaultSearch = true;
si = new SearchItem(store, dictionary);
si.explore = "complete";
if (final_search[0] != null) {
label = final_search[0];
list_seq_searches.add(label);
for (int i=1; i<final_search.length; i++)
if (final_search[i] != null)
list_seq_searches.add(final_search[i]);
}
else if (final_search[1] != null) {
label = final_search[1];
list_seq_searches.add(label);
if (final_search[2] != null)
list_seq_searches.add(final_search[2]);
}
else if (final_search[2] != null) {
label = final_search[2];
list_seq_searches.add(label);
}
}
else {
for (DepthFirstSearch<Var> s : final_search)
if (s != null)
list_seq_searches.add(s);
}
last_search = list_seq_searches.get(list_seq_searches.size()-1);
// LDS & Credit heuristic search
if (si.exploration().equals("lds"))
lds_search(label, si.ldsValue);
// Credit heuristic search
else if (si.exploration().equals("credit"))
credit_search(label, si.creditValue, si.bbsValue);
Result = false;
tread = java.lang.Thread.currentThread();
java.lang.management.ThreadMXBean b = java.lang.management.ManagementFactory.getThreadMXBean();
searchTimeMeter = b;
startCPU = b.getThreadCpuTime(tread.getId());
// long startUser = b.getThreadUserTime(tread.getId());
if (si == null || si.exploration() == null || si.exploration().equals("complete")
|| si.exploration().equals("lds")
|| si.exploration().equals("credit")
)
switch (solveKind) {
case 0: // satisfy
if (options.getAll()) { // all solutions
label.getSolutionListener().searchAll(true);
label.getSolutionListener().recordSolutions(false);
// =====> add "search for all" flag to all sub-searches, 2012-03-19
java.util.LinkedHashSet<Search<? extends Var>> l =
new java.util.LinkedHashSet<Search<? extends Var>>();
l.add(label);
while (l.size() != 0) {
java.util.LinkedHashSet<Search<? extends Var>> ns =
new java.util.LinkedHashSet<Search<? extends Var>>();
for (Search s1 : l) {
Search<? extends Var>[] child = ((DepthFirstSearch)s1).childSearches;
if (child != null)
for (Search s : child) {
ns.add(s);
s.getSolutionListener().searchAll(true);
s.getSolutionListener().recordSolutions(false);
}
}
l = ns;
}
// <=====
if (options.getNumberSolutions()>0)
last_search.getSolutionListener().setSolutionLimit(options.getNumberSolutions());
}
// printSearch(label);
Result = label.labeling(store, variable_selection);
this.si = si;
break;
case 1: // minimize
if (options.getNumberSolutions()>0) {
for (Search<Var> list_seq_searche : list_seq_searches)
((DepthFirstSearch) list_seq_searche).respectSolutionListenerAdvice = true;
last_search.getSolutionListener().setSolutionLimit(options.getNumberSolutions());
}
Result = label.labeling(store, variable_selection, cost);
this.si = si;
break;
case 2: //maximize
if (options.getNumberSolutions()>0) {
for (Search<Var> list_seq_searche : list_seq_searches)
((DepthFirstSearch) list_seq_searche).respectSolutionListenerAdvice = true;
last_search.getSolutionListener().setSolutionLimit(options.getNumberSolutions());
}
Result = label.labeling(store, variable_selection, max_cost);
this.si = si;
break;
}
else {
System.err.println("Not recognized or supported "+si.exploration()+" search explorarion strategy ; compilation aborted");
System.exit(0);
}
printStatisticsForSingleSearch(false);
}
void printStatistics(boolean interrupted) {
if (singleSearch)
printStatisticsForSingleSearch(interrupted);
else
printStatisticsForSeqSearch(interrupted);
}
void printStatisticsForSingleSearch(boolean interrupted) {
if (label == null) {
System.out.println ("%% =====INTERRUPTED=====\n%% Model not yet posed..");
return;
}
if (Result) {
if (!optimization && options.getAll()) {
if (!interrupted)
if (si.exploration().equals("complete"))
if (! label.timeOutOccured) {
if (options.getNumberSolutions() == -1 || options.getNumberSolutions() > label.getSolutionListener().solutionsNo())
System.out.println("==========");
}
else
System.out.println("%% =====TIME-OUT=====");
else
if (label.timeOutOccured)
System.out.println("%% =====TIME-OUT=====");
}
else if (optimization) {
if (!interrupted)
if (si.exploration().equals("complete"))
if (! label.timeOutOccured) {
if (options.getNumberSolutions() == -1 || options.getNumberSolutions() > label.getSolutionListener().solutionsNo())
System.out.println("==========");
}
else
System.out.println("%% =====TIME-OUT=====");
else
if (label.timeOutOccured)
System.out.println("%% =====TIME-OUT=====");
}
}
else
if (label.timeOutOccured) {
System.out.println("=====UNKNOWN=====");
System.out.println("%% =====TIME-OUT=====");
}
else
if (interrupted)
System.out.println ("%% =====INTERRUPTED=====");
else
if (si.exploration().equals("complete"))
System.out.println("=====UNSATISFIABLE=====");
else
System.out.println("=====UNKNOWN=====");
if (options.getStatistics()) {
int nodes = 0, //label.getNodes(),
decisions = 0, //label.getDecisions(),
wrong = 0, //label.getWrongDecisions(),
backtracks = 0, //label.getBacktracks(),
depth = 0, //label.getMaximumDepth(),
solutions = 0; //label.getSolutionListener().solutionsNo();
if ( ! defaultSearch) {
nodes = label.getNodes();
decisions = label.getDecisions();
wrong = label.getWrongDecisions();
backtracks = label.getBacktracks();
depth = label.getMaximumDepth();
solutions = label.getSolutionListener().solutionsNo();
}
for (DepthFirstSearch<Var> l : final_search) {
if (l != null) {
nodes += l.getNodes();
decisions += l.getDecisions();
wrong += l.getWrongDecisions();
backtracks += l.getBacktracks();
depth += l.getMaximumDepth();
solutions = l.getSolutionListener().solutionsNo();
}
}
System.out.println("\n%% Model variables : "+ (store.size()+NumberBoolVariables)+
"\n%% Model constraints : "+initNumberConstraints+
"\n\n%% Search CPU time : " + (searchTimeMeter.getThreadCpuTime(tread.getId()) - startCPU)/(long)1e+6 + "ms"+
"\n%% Search nodes : "+nodes+
"\n%% Search decisions : "+decisions+
"\n%% Wrong search decisions : "+wrong+
"\n%% Search backtracks : "+backtracks+
"\n%% Max search depth : "+depth+
"\n%% Number solutions : "+ solutions
);
}
}
DepthFirstSearch<Var>[] setSubSearchForAll(DepthFirstSearch<Var> label, Options opt) {
DepthFirstSearch<Var>[] intAndSetSearch = new DepthFirstSearch[3];
Var[] int_search_variables = null,
set_search_variables = null,
bool_search_variables = null;
// collect integer & bool variables for search
int int_varSize = 0, bool_varSize=0;
for (int i=0; i<dictionary.defaultSearchVariables.size(); i++)
if (dictionary.defaultSearchVariables.get(i) instanceof org.jacop.core.BooleanVar)
bool_varSize++;
else
int_varSize++;
for (int i=0; i<dictionary.defaultSearchArrays.size(); i++)
if (dictionary.defaultSearchArrays.get(i).length != 0)
if (dictionary.defaultSearchArrays.get(i)[0] instanceof org.jacop.core.BooleanVar)
bool_varSize += dictionary.defaultSearchArrays.get(i).length;
else
int_varSize += dictionary.defaultSearchArrays.get(i).length;
int_search_variables = new IntVar[int_varSize];
bool_search_variables = new IntVar[bool_varSize];
int bool_n=0, int_n=0;
for (int i=0; i<dictionary.defaultSearchArrays.size(); i++)
for (int j=0; j<dictionary.defaultSearchArrays.get(i).length; j++) {
Var v = dictionary.defaultSearchArrays.get(i)[j];
if (v instanceof org.jacop.core.BooleanVar)
bool_search_variables[bool_n++] = v;
else
int_search_variables[int_n++] = v;
}
for (int i=0; i<dictionary.defaultSearchVariables.size(); i++) {
Var v = dictionary.defaultSearchVariables.get(i);
if (v instanceof org.jacop.core.BooleanVar)
bool_search_variables[bool_n++] = v;
else
int_search_variables[int_n++] = v;
}
java.util.Arrays.sort(int_search_variables, new DomainSizeComparator<Var>());
// collect set variables for search
int n=0;
int varSize = dictionary.defaultSearchSetVariables.size();
for (int i=0; i<dictionary.defaultSearchSetArrays.size(); i++)
varSize += dictionary.defaultSearchSetArrays.get(i).length;
set_search_variables = new SetVar[varSize];
for (int i=0; i<dictionary.defaultSearchSetArrays.size(); i++)
for (int j=0; j<dictionary.defaultSearchSetArrays.get(i).length; j++)
set_search_variables[n++] = dictionary.defaultSearchSetArrays.get(i)[j];
for (int i=0; i<dictionary.defaultSearchSetVariables.size(); i++)
set_search_variables[n++] = dictionary.defaultSearchSetVariables.get(i);
if (opt.getVerbose()) {
System.out.println ("%% default int search variables = " + java.util.Arrays.asList(int_search_variables));
System.out.println ("%% default boolean search variables = " + java.util.Arrays.asList(bool_search_variables));
System.out.println ("%% default set search variables = " + java.util.Arrays.asList(set_search_variables));
// System.out.println ("cost = " + costVariable);
}
DepthFirstSearch<Var> lastSearch = label;
DepthFirstSearch<Var> intSearch = new DepthFirstSearch<Var>();
if (int_search_variables.length != 0) {
// add search containing int variables to be sure that they get a value
SelectChoicePoint<Var> intSelect = new SimpleSelect<Var>(int_search_variables,
null,
// new JaCoP.search.MostConstrainedStatic<Var>(),
new IndomainMin());
if (variable_selection == null)
variable_selection = intSelect;
intSearch.setSelectChoicePoint(intSelect);
intSearch.setPrintInfo(false);
if (lastSearch != null)
lastSearch.addChildSearch(intSearch);
lastSearch = intSearch;
if (bool_search_variables.length == 0 && set_search_variables.length == 0 ) {
intSearch.setSolutionListener(new CostListener<Var>());
if (costVariable != null) {
intSearch.setCostVar( (IntVar)costVariable);
intSearch.setOptimize( true);
}
}
// else
// intSearch.setSolutionListener(new EmptyListener<Var>());
// if (searchAll) {
// intSearch.getSolutionListener().searchAll(true);
// intSearch.getSolutionListener().recordSolutions(false);
// }
// if (options.getNumberSolutions() > 0)
// intSearch.getSolutionListener().setSolutionLimit(options.getNumberSolutions());
// time-out option
int to = options.getTimeOut();
if (to > 0)
intSearch.setTimeOut(to);
intAndSetSearch[0] = intSearch;
}
DepthFirstSearch<Var> boolSearch = new DepthFirstSearch<Var>();
if (bool_search_variables.length != 0) {
// add search containing boolean variables to be sure that they get a value
SelectChoicePoint<Var> boolSelect = new SimpleSelect<Var>(bool_search_variables,
null,
// new JaCoP.search.MostConstrainedStatic<Var>(),
new IndomainMin());
if (variable_selection == null)
variable_selection = boolSelect;
boolSearch.setSelectChoicePoint(boolSelect);
boolSearch.setPrintInfo(false);
if (lastSearch != null)
lastSearch.addChildSearch(boolSearch);
lastSearch = boolSearch;
if (set_search_variables.length == 0) {
boolSearch.setSolutionListener(new CostListener<Var>());
if (costVariable != null) {
intSearch.setCostVar( (IntVar)costVariable);
intSearch.setOptimize( true);
}
}
// time-out option
int to = options.getTimeOut();
if (to > 0)
boolSearch.setTimeOut(to);
intAndSetSearch[1] = boolSearch;
}
if (set_search_variables.length != 0) {
// add set search containing all variables to be sure that they get a value
DepthFirstSearch<Var> setSearch = new DepthFirstSearch<Var>();
SelectChoicePoint<Var> setSelect = new SimpleSelect<Var>(set_search_variables,
null,
// new JaCoP.search.MostConstrainedStatic<Var>(),
new IndomainSetMin());
if (variable_selection == null)
variable_selection = setSelect;
setSearch.setSelectChoicePoint(setSelect);
setSearch.setPrintInfo(false);
if (lastSearch != null)
lastSearch.addChildSearch(setSearch);
setSearch.setSolutionListener(new CostListener<Var>());
if (costVariable != null) {
intSearch.setCostVar( (IntVar)costVariable);
intSearch.setOptimize( true);
}
// time-out option
int to = options.getTimeOut();
if (to > 0)
setSearch.setTimeOut(to);
intAndSetSearch[2] = setSearch;
}
if (int_search_variables.length == 0 &&
bool_search_variables.length == 0 &&
set_search_variables.length == 0) {
printSolution();
System.out.println("----------");
if (options.getStatistics())
System.out.println("\n%% Model variables : "+ (store.size()+ NumberBoolVariables) +
"\n%% Model constraints : "+initNumberConstraints+
"\n\n%% Search CPU time : " + "0ms"+
"\n%% Search nodes : 0"+
"\n%% Search decisions : 0"+
"\n%% Wrong search decisions : 0"+
"\n%% Search backtracks : 0"+
"\n%% Max search depth : 0"+
"\n%% Number solutions : 1"
);
System.exit(0);
}
return intAndSetSearch;
}
void run_sequence_search(int solveKind, SimpleNode kind, SearchItem si) {
singleSearch = false;
this.si = si;
if (options.getVerbose()) {
String solve="notKnown";
switch (solveKind) {
case 0: solve = "%% satisfy"; break; // satisfy
case 1:
solve = "%% minimize("+ getCost((ASTSolveExpr)kind.jjtGetChild(0))+") "; break; // minimize
case 2:
solve = "%% maximize("+ getCost((ASTSolveExpr)kind.jjtGetChild(0))+") "; break; // maximize
}
System.out.println(solve + " : seq_search([" + si + "])");
}
DepthFirstSearch<Var> masterLabel = null;
DepthFirstSearch<Var> last_search = null;
SelectChoicePoint<Var> masterSelect = null;
list_seq_searches = new ArrayList<Search<Var>>();
for (int i=0; i<si.getSearchItems().size(); i++) {
if (i == 0) { // master search
masterLabel = sub_search(si.getSearchItems().get(i), masterLabel, true);
last_search = masterLabel;
masterSelect = variable_selection;
if (!print_search_info) masterLabel.setPrintInfo(false);
}
else {
DepthFirstSearch<Var> label = sub_search(si.getSearchItems().get(i), last_search, false);
last_search.addChildSearch(label);
last_search = label;
if (!print_search_info) last_search.setPrintInfo(false);
}
}
DepthFirstSearch<Var>[] complementary_search = setSubSearchForAll(last_search, options);
for (DepthFirstSearch<Var> aComplementary_search : complementary_search) {
if (aComplementary_search != null) {
list_seq_searches.add(aComplementary_search);
if (!print_search_info) aComplementary_search.setPrintInfo(false);
}
}
// System.out.println("*** " + list_seq_searches);
Result = false;
IntVar cost;
optimization = false;
- Search<Var> final_search_seq = list_seq_searches.get(list_seq_searches.size()-1);
+ final_search_seq = list_seq_searches.get(list_seq_searches.size()-1);
tread = java.lang.Thread.currentThread();
java.lang.management.ThreadMXBean b = java.lang.management.ManagementFactory.getThreadMXBean();
searchTimeMeter = b;
startCPU = b.getThreadCpuTime(tread.getId());
// long startUser = b.getThreadUserTime(tread.getId());
int to = options.getTimeOut();
if (to > 0)
for (Search s : list_seq_searches)
s.setTimeOut(to);
int ns = options.getNumberSolutions();
if (si.exploration() == null || si.exploration().equals("complete"))
switch (solveKind) {
case 0: // satisfy
if (options.getAll() ) { // all solutions
for (int i=0; i<si.getSearchItems().size(); i++) { //list_seq_searches.size(); i++) {
list_seq_searches.get(i).getSolutionListener().searchAll(true);
list_seq_searches.get(i).getSolutionListener().recordSolutions(false);
if ( ns>0 )
list_seq_searches.get(i).getSolutionListener().setSolutionLimit(ns);
}
}
Result = masterLabel.labeling(store, masterSelect);
break;
case 1: // minimize
optimization = true;
cost = getCost((ASTSolveExpr)kind.jjtGetChild(0));
// Result = restart_search(masterLabel, masterSelect, cost, true);
for (Search<Var> list_seq_searche : list_seq_searches)
list_seq_searche.setOptimize(true);
if (ns > 0) {
for (int i=0; i<list_seq_searches.size()-1; i++)
((DepthFirstSearch)list_seq_searches.get(i)).respectSolutionListenerAdvice = true;
final_search_seq.getSolutionListener().setSolutionLimit(ns);
((DepthFirstSearch)final_search_seq).respectSolutionListenerAdvice = true;
}
Result = masterLabel.labeling(store, masterSelect, cost);
break;
case 2: //maximize
optimization = true;
cost = getCost((ASTSolveExpr)kind.jjtGetChild(0));
// Result = restart_search(masterLabel, masterSelect, cost, false);
IntVar max_cost = new IntVar(store, "-"+cost.id(), IntDomain.MinInt,
IntDomain.MaxInt);
pose(new XplusYeqC(max_cost, cost, 0));
for (Search<Var> list_seq_searche : list_seq_searches)
list_seq_searche.setOptimize(true);
if (ns > 0) {
for (int i=0; i<list_seq_searches.size()-1; i++)
((DepthFirstSearch)list_seq_searches.get(i)).respectSolutionListenerAdvice=true;
final_search_seq.getSolutionListener().setSolutionLimit(ns);
((DepthFirstSearch)final_search_seq).respectSolutionListenerAdvice=true;
}
Result = masterLabel.labeling(store, masterSelect, max_cost);
break;
}
else {
System.err.println("Not recognized or supported "+si.exploration()+
" search explorarion strategy ; compilation aborted");
System.exit(0);
}
printStatisticsForSeqSearch(false);
}
void printStatisticsForSeqSearch(boolean interrupted) {
if (list_seq_searches == null) {
System.out.println ("%% =====INTERRUPTED=====\n%% Model not yet posed..");
return;
}
if (Result) {
if (!optimization && options.getAll()) {
if (!heuristicSeqSearch)
if (! anyTimeOutOccured(list_seq_searches)) {
if (options.getNumberSolutions() == -1 || options.getNumberSolutions() > final_search_seq.getSolutionListener().solutionsNo())
System.out.println("==========");
}
else
System.out.println("%% =====TIME-OUT=====");
else
if (anyTimeOutOccured(list_seq_searches))
System.out.println("%% =====TIME-OUT=====");
}
else if (optimization) {
if (!heuristicSeqSearch)
if (! anyTimeOutOccured(list_seq_searches)) {
if (options.getNumberSolutions() == -1 || options.getNumberSolutions() > final_search_seq.getSolutionListener().solutionsNo())
System.out.println("==========");
}
else
System.out.println("%% =====TIME-OUT=====");
else
if (anyTimeOutOccured(list_seq_searches))
System.out.println("%% =====TIME-OUT=====");
}
}
else
if (anyTimeOutOccured(list_seq_searches)) {
System.out.println("=====UNKNOWN=====");
System.out.println("%% =====TIME-OUT=====");
}
else
if (interrupted)
System.out.println ("%% =====INTERRUPTED=====");
else
System.out.println("=====UNSATISFIABLE=====");
if (options.getStatistics()) {
int nodes=0, decisions=0, wrong=0, backtracks=0, depth=0,solutions=0;
for (Search<Var> label : list_seq_searches) {
nodes += label.getNodes();
decisions += label.getDecisions();
wrong += label.getWrongDecisions();
backtracks += label.getBacktracks();
depth += label.getMaximumDepth();
solutions = label.getSolutionListener().solutionsNo();
}
System.out.println("\n%% Model variables : "+ (store.size()+ NumberBoolVariables) +
"\n%% Model constraints : "+initNumberConstraints+
"\n\n%% Search CPU time : " + (searchTimeMeter.getThreadCpuTime(tread.getId()) - startCPU)/(long)1e+6 + "ms"+
"\n%% Search nodes : "+nodes+
"\n%% Search decisions : "+decisions+
"\n%% Wrong search decisions : "+wrong+
"\n%% Search backtracks : "+backtracks+
"\n%% Max search depth : "+depth+
"\n%% Number solutions : "+ solutions
);
}
}
boolean anyTimeOutOccured(ArrayList<Search<Var>> list_seq_searches) {
for (Search<Var> list_seq_searche : list_seq_searches)
if (((DepthFirstSearch) list_seq_searche).timeOutOccured)
return true;
return false;
}
DepthFirstSearch<Var> sub_search(SearchItem si, DepthFirstSearch<Var> l, boolean master) {
DepthFirstSearch<Var> last_search = l;
DepthFirstSearch<Var> label = null;
if (si.type().equals("int_search") || si.type().equals("bool_search")) {
label = int_search(si);
if (!master) label.setSelectChoicePoint(variable_selection);
// LDS heuristic search
if (si.exploration().equals("lds")) {
lds_search(label, si.ldsValue);
heuristicSeqSearch = true;
}
// Credit heuristic search
if (si.exploration().equals("credit")) {
credit_search(label, si.creditValue, si.bbsValue);
heuristicSeqSearch = true;
}
list_seq_searches.add(label);
}
else if (si.type().equals("set_search")) {
setSearch=true;
label = set_search(si);
if (!master)
label.setSelectChoicePoint(variable_selection);
// LDS heuristic search
if (si.exploration().equals("lds")) {
lds_search(label, si.ldsValue);
heuristicSeqSearch = true;
}
// Credit heuristic search
if (si.exploration().equals("credit")) {
credit_search(label, si.creditValue, si.bbsValue);
heuristicSeqSearch = true;
}
list_seq_searches.add(label);
}
else if (si.type().equals("seq_search")) {
for (int i=0; i<si.getSearchItems().size(); i++)
if (i == 0) { // master search
DepthFirstSearch<Var> label_seq = sub_search(si.getSearchItems().get(i), last_search, false);
last_search = label_seq;
label = label_seq;
}
else {
DepthFirstSearch<Var> label_seq = sub_search(si.getSearchItems().get(i), last_search, false);
last_search.addChildSearch(label_seq);
last_search = label_seq;
}
}
else {
System.err.println("Not recognized or supported search type \""+si.type()+"\"; compilation aborted");
System.exit(0);
}
return label;
}
DepthFirstSearch<Var> int_search(SearchItem si) {
variable_selection = si.getIntSelect();
return new DepthFirstSearch<Var>();
}
DepthFirstSearch<Var> set_search(SearchItem si) {
variable_selection = si.getSetSelect();
return new DepthFirstSearch<Var>();
}
// long T, TOld = 0;
void printSolution() {
// T = System.currentTimeMillis();
// System.out.println("% Search time since last solution : " + (T - TOld)/1000 + " s");
// TOld = T;
if (dictionary.outputVariables.size() > 0)
for (int i=0; i<dictionary.outputVariables.size(); i++) {
Var v = dictionary.outputVariables.get(i);
if (v instanceof BooleanVar) {
// print boolean variables
String boolVar = v.id()+" = ";
if (v.singleton())
switch ( ((BooleanVar)v).value()) {
case 0: boolVar += "false";
break;
case 1: boolVar += "true";
break;
default: boolVar += v.dom();
}
else
boolVar += "false..true";
System.out.println(boolVar+";");
}
else if (v instanceof SetVar) {
// print set variables
String setVar = v.id() + " = ";
if (v.singleton()) {
IntDomain glb = ((SetVar)v).dom().glb();
setVar += "{";
for (ValueEnumeration e = glb.valueEnumeration(); e.hasMoreElements();) {
int element = e.nextElement();
setVar += element;
if (e.hasMoreElements())
setVar += ", ";
}
setVar += "}";
}
else
setVar += v.dom().toString();
System.out.println(setVar+";");
}
else
System.out.println(v+";");
}
for (int i=0; i<dictionary.outputArray.size(); i++) {
OutputArrayAnnotation a = dictionary.outputArray.get(i);
System.out.println(a);
}
}
int getKind(String k) {
if (k.equals("satisfy")) // 0 = satisfy
return 0;
else if (k.equals("minimize")) // 1 = minimize
return 1;
else if (k.equals("maximize")) // 2 = maximize
return 2;
else {
System.err.println("Not supported search kind; compilation aborted");
System.exit(0);
return -1;
}
}
IntVar getCost(ASTSolveExpr node) {
if (node.getType() == 0) // ident
return dictionary.getVariable(node.getIdent());
else if (node.getType() == 1) // array access
return dictionary.getVariableArray(node.getIdent())[node.getIndex()];
else {
System.err.println("Wrong cost function specification " + node);
System.exit(0);
return new IntVar(store);
}
}
void pose(Constraint c) {
store.impose(c);
if (debug)
System.out.println(c);
}
/*
boolean restart_search(Search<Var> masterLabel, SelectChoicePoint<Var> masterSelect,
IntVar cost, boolean minimize) {
costVariable = cost;
Search<Var> final_search = list_seq_searches.get(list_seq_searches.size()-1);
for (Search s : list_seq_searches)
s.setAssignSolution(false);
store.setLevel(store.level+1);
boolean Result = true, optimalResult = false;
while (Result) {
Result = masterLabel.labeling(store, masterSelect);
if (minimize) //minimize
pose(new XltC(cost, costValue));
else // maximize
pose(new XgtC(cost, costValue));
optimalResult = optimalResult || Result;
if (options.getNumberSolutions() == final_search.getSolutionListener().solutionsNo())
break;
}
store.removeLevel(store.level);
store.setLevel(store.level-1);
Result = optimalResult;
if (Result)
for (Search s : list_seq_searches)
s.assignSolution();
return Result;
}
*/
void lds_search(DepthFirstSearch<Var> label, int lds_value) {
// System.out.println("LDS("+lds_value+")");
LDS<Var> lds = new LDS<Var>(lds_value);
if (label.getExitChildListener() == null)
label.setExitChildListener(lds);
else
label.getExitChildListener().setChildrenListeners(lds);
}
void credit_search(DepthFirstSearch<Var> label, int creditValue, int bbsValue) {
// System.out.println("Credit("+creditValue+", "+bbsValue+")");
int maxDepth = 1000; //IntDomain.MaxInt;
CreditCalculator<Var> credit = new CreditCalculator<Var>(creditValue, bbsValue, maxDepth);
if (label.getConsistencyListener() == null)
label.setConsistencyListener(credit);
else
label.getConsistencyListener().setChildrenListeners(credit);
label.setExitChildListener(credit);
label.setTimeOutListener(credit);
}
void setNumberBoolVariables(int n) {
NumberBoolVariables = n;
}
void printSearch(Search label) {
int N = 1;
System.out.println (N++ + ". " + label);
java.util.LinkedHashSet<Search<? extends Var>> l =
new java.util.LinkedHashSet<Search<? extends Var>>();
l.add(label);
while (l.size() != 0) {
java.util.LinkedHashSet<Search<? extends Var>> ns =
new java.util.LinkedHashSet<Search<? extends Var>>();
for (Search s1 : l) {
Search<? extends Var>[] child = ((DepthFirstSearch)s1).childSearches;
if (child != null)
for (Search s : child) {
System.out.println (N + ". " + s);
ns.add(s);
}
}
N++;
l = ns;
}
}
int FinalNumberSolutions = 0;
/**
*
*
* @author Krzysztof Kuchcinski
*
*/
public class CostListener<T extends Var> extends SimpleSolutionListener<T> {
public boolean executeAfterSolution(Search<T> search, SelectChoicePoint<T> select) {
boolean returnCode = super.executeAfterSolution(search, select);
/* // === used to print number of search nodes for each solution
int nodes=0;
for (Search<Var> label : list_seq_searches)
nodes += label.getNodes();
System.out.println("%% Search nodes : "+ nodes );
*/
if (costVariable != null)
costValue = ((IntVar)costVariable).value();
FinalNumberSolutions++;
printSolution();
System.out.println("----------");
return returnCode;
}
}
class DomainSizeComparator<T extends Var> implements Comparator<T> {
DomainSizeComparator() { }
public int compare(T o1, T o2) {
int v1 = o1.getSize();
int v2 = o2.getSize();
return v1 - v2;
}
}
}
| true | true | void run_sequence_search(int solveKind, SimpleNode kind, SearchItem si) {
singleSearch = false;
this.si = si;
if (options.getVerbose()) {
String solve="notKnown";
switch (solveKind) {
case 0: solve = "%% satisfy"; break; // satisfy
case 1:
solve = "%% minimize("+ getCost((ASTSolveExpr)kind.jjtGetChild(0))+") "; break; // minimize
case 2:
solve = "%% maximize("+ getCost((ASTSolveExpr)kind.jjtGetChild(0))+") "; break; // maximize
}
System.out.println(solve + " : seq_search([" + si + "])");
}
DepthFirstSearch<Var> masterLabel = null;
DepthFirstSearch<Var> last_search = null;
SelectChoicePoint<Var> masterSelect = null;
list_seq_searches = new ArrayList<Search<Var>>();
for (int i=0; i<si.getSearchItems().size(); i++) {
if (i == 0) { // master search
masterLabel = sub_search(si.getSearchItems().get(i), masterLabel, true);
last_search = masterLabel;
masterSelect = variable_selection;
if (!print_search_info) masterLabel.setPrintInfo(false);
}
else {
DepthFirstSearch<Var> label = sub_search(si.getSearchItems().get(i), last_search, false);
last_search.addChildSearch(label);
last_search = label;
if (!print_search_info) last_search.setPrintInfo(false);
}
}
DepthFirstSearch<Var>[] complementary_search = setSubSearchForAll(last_search, options);
for (DepthFirstSearch<Var> aComplementary_search : complementary_search) {
if (aComplementary_search != null) {
list_seq_searches.add(aComplementary_search);
if (!print_search_info) aComplementary_search.setPrintInfo(false);
}
}
// System.out.println("*** " + list_seq_searches);
Result = false;
IntVar cost;
optimization = false;
Search<Var> final_search_seq = list_seq_searches.get(list_seq_searches.size()-1);
tread = java.lang.Thread.currentThread();
java.lang.management.ThreadMXBean b = java.lang.management.ManagementFactory.getThreadMXBean();
searchTimeMeter = b;
startCPU = b.getThreadCpuTime(tread.getId());
// long startUser = b.getThreadUserTime(tread.getId());
int to = options.getTimeOut();
if (to > 0)
for (Search s : list_seq_searches)
s.setTimeOut(to);
int ns = options.getNumberSolutions();
if (si.exploration() == null || si.exploration().equals("complete"))
switch (solveKind) {
case 0: // satisfy
if (options.getAll() ) { // all solutions
for (int i=0; i<si.getSearchItems().size(); i++) { //list_seq_searches.size(); i++) {
list_seq_searches.get(i).getSolutionListener().searchAll(true);
list_seq_searches.get(i).getSolutionListener().recordSolutions(false);
if ( ns>0 )
list_seq_searches.get(i).getSolutionListener().setSolutionLimit(ns);
}
}
Result = masterLabel.labeling(store, masterSelect);
break;
case 1: // minimize
optimization = true;
cost = getCost((ASTSolveExpr)kind.jjtGetChild(0));
// Result = restart_search(masterLabel, masterSelect, cost, true);
for (Search<Var> list_seq_searche : list_seq_searches)
list_seq_searche.setOptimize(true);
if (ns > 0) {
for (int i=0; i<list_seq_searches.size()-1; i++)
((DepthFirstSearch)list_seq_searches.get(i)).respectSolutionListenerAdvice = true;
final_search_seq.getSolutionListener().setSolutionLimit(ns);
((DepthFirstSearch)final_search_seq).respectSolutionListenerAdvice = true;
}
Result = masterLabel.labeling(store, masterSelect, cost);
break;
case 2: //maximize
optimization = true;
cost = getCost((ASTSolveExpr)kind.jjtGetChild(0));
// Result = restart_search(masterLabel, masterSelect, cost, false);
IntVar max_cost = new IntVar(store, "-"+cost.id(), IntDomain.MinInt,
IntDomain.MaxInt);
pose(new XplusYeqC(max_cost, cost, 0));
for (Search<Var> list_seq_searche : list_seq_searches)
list_seq_searche.setOptimize(true);
if (ns > 0) {
for (int i=0; i<list_seq_searches.size()-1; i++)
((DepthFirstSearch)list_seq_searches.get(i)).respectSolutionListenerAdvice=true;
final_search_seq.getSolutionListener().setSolutionLimit(ns);
((DepthFirstSearch)final_search_seq).respectSolutionListenerAdvice=true;
}
Result = masterLabel.labeling(store, masterSelect, max_cost);
break;
}
else {
System.err.println("Not recognized or supported "+si.exploration()+
" search explorarion strategy ; compilation aborted");
System.exit(0);
}
printStatisticsForSeqSearch(false);
}
void printStatisticsForSeqSearch(boolean interrupted) {
if (list_seq_searches == null) {
System.out.println ("%% =====INTERRUPTED=====\n%% Model not yet posed..");
return;
}
if (Result) {
if (!optimization && options.getAll()) {
if (!heuristicSeqSearch)
if (! anyTimeOutOccured(list_seq_searches)) {
if (options.getNumberSolutions() == -1 || options.getNumberSolutions() > final_search_seq.getSolutionListener().solutionsNo())
System.out.println("==========");
}
else
System.out.println("%% =====TIME-OUT=====");
else
if (anyTimeOutOccured(list_seq_searches))
System.out.println("%% =====TIME-OUT=====");
}
else if (optimization) {
if (!heuristicSeqSearch)
if (! anyTimeOutOccured(list_seq_searches)) {
if (options.getNumberSolutions() == -1 || options.getNumberSolutions() > final_search_seq.getSolutionListener().solutionsNo())
System.out.println("==========");
}
else
System.out.println("%% =====TIME-OUT=====");
else
if (anyTimeOutOccured(list_seq_searches))
System.out.println("%% =====TIME-OUT=====");
}
}
else
if (anyTimeOutOccured(list_seq_searches)) {
System.out.println("=====UNKNOWN=====");
System.out.println("%% =====TIME-OUT=====");
}
else
if (interrupted)
System.out.println ("%% =====INTERRUPTED=====");
else
System.out.println("=====UNSATISFIABLE=====");
if (options.getStatistics()) {
int nodes=0, decisions=0, wrong=0, backtracks=0, depth=0,solutions=0;
for (Search<Var> label : list_seq_searches) {
nodes += label.getNodes();
decisions += label.getDecisions();
wrong += label.getWrongDecisions();
backtracks += label.getBacktracks();
depth += label.getMaximumDepth();
solutions = label.getSolutionListener().solutionsNo();
}
System.out.println("\n%% Model variables : "+ (store.size()+ NumberBoolVariables) +
"\n%% Model constraints : "+initNumberConstraints+
"\n\n%% Search CPU time : " + (searchTimeMeter.getThreadCpuTime(tread.getId()) - startCPU)/(long)1e+6 + "ms"+
"\n%% Search nodes : "+nodes+
"\n%% Search decisions : "+decisions+
"\n%% Wrong search decisions : "+wrong+
"\n%% Search backtracks : "+backtracks+
"\n%% Max search depth : "+depth+
"\n%% Number solutions : "+ solutions
);
}
}
boolean anyTimeOutOccured(ArrayList<Search<Var>> list_seq_searches) {
for (Search<Var> list_seq_searche : list_seq_searches)
if (((DepthFirstSearch) list_seq_searche).timeOutOccured)
return true;
return false;
}
DepthFirstSearch<Var> sub_search(SearchItem si, DepthFirstSearch<Var> l, boolean master) {
DepthFirstSearch<Var> last_search = l;
DepthFirstSearch<Var> label = null;
if (si.type().equals("int_search") || si.type().equals("bool_search")) {
label = int_search(si);
if (!master) label.setSelectChoicePoint(variable_selection);
// LDS heuristic search
if (si.exploration().equals("lds")) {
lds_search(label, si.ldsValue);
heuristicSeqSearch = true;
}
// Credit heuristic search
if (si.exploration().equals("credit")) {
credit_search(label, si.creditValue, si.bbsValue);
heuristicSeqSearch = true;
}
list_seq_searches.add(label);
}
else if (si.type().equals("set_search")) {
setSearch=true;
label = set_search(si);
if (!master)
label.setSelectChoicePoint(variable_selection);
// LDS heuristic search
if (si.exploration().equals("lds")) {
lds_search(label, si.ldsValue);
heuristicSeqSearch = true;
}
// Credit heuristic search
if (si.exploration().equals("credit")) {
credit_search(label, si.creditValue, si.bbsValue);
heuristicSeqSearch = true;
}
list_seq_searches.add(label);
}
else if (si.type().equals("seq_search")) {
for (int i=0; i<si.getSearchItems().size(); i++)
if (i == 0) { // master search
DepthFirstSearch<Var> label_seq = sub_search(si.getSearchItems().get(i), last_search, false);
last_search = label_seq;
label = label_seq;
}
else {
DepthFirstSearch<Var> label_seq = sub_search(si.getSearchItems().get(i), last_search, false);
last_search.addChildSearch(label_seq);
last_search = label_seq;
}
}
else {
System.err.println("Not recognized or supported search type \""+si.type()+"\"; compilation aborted");
System.exit(0);
}
return label;
}
DepthFirstSearch<Var> int_search(SearchItem si) {
variable_selection = si.getIntSelect();
return new DepthFirstSearch<Var>();
}
DepthFirstSearch<Var> set_search(SearchItem si) {
variable_selection = si.getSetSelect();
return new DepthFirstSearch<Var>();
}
// long T, TOld = 0;
void printSolution() {
// T = System.currentTimeMillis();
// System.out.println("% Search time since last solution : " + (T - TOld)/1000 + " s");
// TOld = T;
if (dictionary.outputVariables.size() > 0)
for (int i=0; i<dictionary.outputVariables.size(); i++) {
Var v = dictionary.outputVariables.get(i);
if (v instanceof BooleanVar) {
// print boolean variables
String boolVar = v.id()+" = ";
if (v.singleton())
switch ( ((BooleanVar)v).value()) {
case 0: boolVar += "false";
break;
case 1: boolVar += "true";
break;
default: boolVar += v.dom();
}
else
boolVar += "false..true";
System.out.println(boolVar+";");
}
else if (v instanceof SetVar) {
// print set variables
String setVar = v.id() + " = ";
if (v.singleton()) {
IntDomain glb = ((SetVar)v).dom().glb();
setVar += "{";
for (ValueEnumeration e = glb.valueEnumeration(); e.hasMoreElements();) {
int element = e.nextElement();
setVar += element;
if (e.hasMoreElements())
setVar += ", ";
}
setVar += "}";
}
else
setVar += v.dom().toString();
System.out.println(setVar+";");
}
else
System.out.println(v+";");
}
for (int i=0; i<dictionary.outputArray.size(); i++) {
OutputArrayAnnotation a = dictionary.outputArray.get(i);
System.out.println(a);
}
}
int getKind(String k) {
if (k.equals("satisfy")) // 0 = satisfy
return 0;
else if (k.equals("minimize")) // 1 = minimize
return 1;
else if (k.equals("maximize")) // 2 = maximize
return 2;
else {
System.err.println("Not supported search kind; compilation aborted");
System.exit(0);
return -1;
}
}
IntVar getCost(ASTSolveExpr node) {
if (node.getType() == 0) // ident
return dictionary.getVariable(node.getIdent());
else if (node.getType() == 1) // array access
return dictionary.getVariableArray(node.getIdent())[node.getIndex()];
else {
System.err.println("Wrong cost function specification " + node);
System.exit(0);
return new IntVar(store);
}
}
void pose(Constraint c) {
store.impose(c);
if (debug)
System.out.println(c);
}
/*
boolean restart_search(Search<Var> masterLabel, SelectChoicePoint<Var> masterSelect,
IntVar cost, boolean minimize) {
costVariable = cost;
Search<Var> final_search = list_seq_searches.get(list_seq_searches.size()-1);
for (Search s : list_seq_searches)
s.setAssignSolution(false);
store.setLevel(store.level+1);
boolean Result = true, optimalResult = false;
while (Result) {
Result = masterLabel.labeling(store, masterSelect);
if (minimize) //minimize
pose(new XltC(cost, costValue));
else // maximize
pose(new XgtC(cost, costValue));
optimalResult = optimalResult || Result;
if (options.getNumberSolutions() == final_search.getSolutionListener().solutionsNo())
break;
}
store.removeLevel(store.level);
store.setLevel(store.level-1);
Result = optimalResult;
if (Result)
for (Search s : list_seq_searches)
s.assignSolution();
return Result;
}
*/
void lds_search(DepthFirstSearch<Var> label, int lds_value) {
// System.out.println("LDS("+lds_value+")");
LDS<Var> lds = new LDS<Var>(lds_value);
if (label.getExitChildListener() == null)
label.setExitChildListener(lds);
else
label.getExitChildListener().setChildrenListeners(lds);
}
void credit_search(DepthFirstSearch<Var> label, int creditValue, int bbsValue) {
// System.out.println("Credit("+creditValue+", "+bbsValue+")");
int maxDepth = 1000; //IntDomain.MaxInt;
CreditCalculator<Var> credit = new CreditCalculator<Var>(creditValue, bbsValue, maxDepth);
if (label.getConsistencyListener() == null)
label.setConsistencyListener(credit);
else
label.getConsistencyListener().setChildrenListeners(credit);
label.setExitChildListener(credit);
label.setTimeOutListener(credit);
}
void setNumberBoolVariables(int n) {
NumberBoolVariables = n;
}
void printSearch(Search label) {
int N = 1;
System.out.println (N++ + ". " + label);
java.util.LinkedHashSet<Search<? extends Var>> l =
new java.util.LinkedHashSet<Search<? extends Var>>();
l.add(label);
while (l.size() != 0) {
java.util.LinkedHashSet<Search<? extends Var>> ns =
new java.util.LinkedHashSet<Search<? extends Var>>();
for (Search s1 : l) {
Search<? extends Var>[] child = ((DepthFirstSearch)s1).childSearches;
if (child != null)
for (Search s : child) {
System.out.println (N + ". " + s);
ns.add(s);
}
}
N++;
l = ns;
}
}
int FinalNumberSolutions = 0;
/**
*
*
* @author Krzysztof Kuchcinski
*
*/
public class CostListener<T extends Var> extends SimpleSolutionListener<T> {
public boolean executeAfterSolution(Search<T> search, SelectChoicePoint<T> select) {
boolean returnCode = super.executeAfterSolution(search, select);
/* // === used to print number of search nodes for each solution
int nodes=0;
for (Search<Var> label : list_seq_searches)
nodes += label.getNodes();
System.out.println("%% Search nodes : "+ nodes );
*/
if (costVariable != null)
costValue = ((IntVar)costVariable).value();
FinalNumberSolutions++;
printSolution();
System.out.println("----------");
return returnCode;
}
}
class DomainSizeComparator<T extends Var> implements Comparator<T> {
DomainSizeComparator() { }
public int compare(T o1, T o2) {
int v1 = o1.getSize();
int v2 = o2.getSize();
return v1 - v2;
}
}
}
| void run_sequence_search(int solveKind, SimpleNode kind, SearchItem si) {
singleSearch = false;
this.si = si;
if (options.getVerbose()) {
String solve="notKnown";
switch (solveKind) {
case 0: solve = "%% satisfy"; break; // satisfy
case 1:
solve = "%% minimize("+ getCost((ASTSolveExpr)kind.jjtGetChild(0))+") "; break; // minimize
case 2:
solve = "%% maximize("+ getCost((ASTSolveExpr)kind.jjtGetChild(0))+") "; break; // maximize
}
System.out.println(solve + " : seq_search([" + si + "])");
}
DepthFirstSearch<Var> masterLabel = null;
DepthFirstSearch<Var> last_search = null;
SelectChoicePoint<Var> masterSelect = null;
list_seq_searches = new ArrayList<Search<Var>>();
for (int i=0; i<si.getSearchItems().size(); i++) {
if (i == 0) { // master search
masterLabel = sub_search(si.getSearchItems().get(i), masterLabel, true);
last_search = masterLabel;
masterSelect = variable_selection;
if (!print_search_info) masterLabel.setPrintInfo(false);
}
else {
DepthFirstSearch<Var> label = sub_search(si.getSearchItems().get(i), last_search, false);
last_search.addChildSearch(label);
last_search = label;
if (!print_search_info) last_search.setPrintInfo(false);
}
}
DepthFirstSearch<Var>[] complementary_search = setSubSearchForAll(last_search, options);
for (DepthFirstSearch<Var> aComplementary_search : complementary_search) {
if (aComplementary_search != null) {
list_seq_searches.add(aComplementary_search);
if (!print_search_info) aComplementary_search.setPrintInfo(false);
}
}
// System.out.println("*** " + list_seq_searches);
Result = false;
IntVar cost;
optimization = false;
final_search_seq = list_seq_searches.get(list_seq_searches.size()-1);
tread = java.lang.Thread.currentThread();
java.lang.management.ThreadMXBean b = java.lang.management.ManagementFactory.getThreadMXBean();
searchTimeMeter = b;
startCPU = b.getThreadCpuTime(tread.getId());
// long startUser = b.getThreadUserTime(tread.getId());
int to = options.getTimeOut();
if (to > 0)
for (Search s : list_seq_searches)
s.setTimeOut(to);
int ns = options.getNumberSolutions();
if (si.exploration() == null || si.exploration().equals("complete"))
switch (solveKind) {
case 0: // satisfy
if (options.getAll() ) { // all solutions
for (int i=0; i<si.getSearchItems().size(); i++) { //list_seq_searches.size(); i++) {
list_seq_searches.get(i).getSolutionListener().searchAll(true);
list_seq_searches.get(i).getSolutionListener().recordSolutions(false);
if ( ns>0 )
list_seq_searches.get(i).getSolutionListener().setSolutionLimit(ns);
}
}
Result = masterLabel.labeling(store, masterSelect);
break;
case 1: // minimize
optimization = true;
cost = getCost((ASTSolveExpr)kind.jjtGetChild(0));
// Result = restart_search(masterLabel, masterSelect, cost, true);
for (Search<Var> list_seq_searche : list_seq_searches)
list_seq_searche.setOptimize(true);
if (ns > 0) {
for (int i=0; i<list_seq_searches.size()-1; i++)
((DepthFirstSearch)list_seq_searches.get(i)).respectSolutionListenerAdvice = true;
final_search_seq.getSolutionListener().setSolutionLimit(ns);
((DepthFirstSearch)final_search_seq).respectSolutionListenerAdvice = true;
}
Result = masterLabel.labeling(store, masterSelect, cost);
break;
case 2: //maximize
optimization = true;
cost = getCost((ASTSolveExpr)kind.jjtGetChild(0));
// Result = restart_search(masterLabel, masterSelect, cost, false);
IntVar max_cost = new IntVar(store, "-"+cost.id(), IntDomain.MinInt,
IntDomain.MaxInt);
pose(new XplusYeqC(max_cost, cost, 0));
for (Search<Var> list_seq_searche : list_seq_searches)
list_seq_searche.setOptimize(true);
if (ns > 0) {
for (int i=0; i<list_seq_searches.size()-1; i++)
((DepthFirstSearch)list_seq_searches.get(i)).respectSolutionListenerAdvice=true;
final_search_seq.getSolutionListener().setSolutionLimit(ns);
((DepthFirstSearch)final_search_seq).respectSolutionListenerAdvice=true;
}
Result = masterLabel.labeling(store, masterSelect, max_cost);
break;
}
else {
System.err.println("Not recognized or supported "+si.exploration()+
" search explorarion strategy ; compilation aborted");
System.exit(0);
}
printStatisticsForSeqSearch(false);
}
void printStatisticsForSeqSearch(boolean interrupted) {
if (list_seq_searches == null) {
System.out.println ("%% =====INTERRUPTED=====\n%% Model not yet posed..");
return;
}
if (Result) {
if (!optimization && options.getAll()) {
if (!heuristicSeqSearch)
if (! anyTimeOutOccured(list_seq_searches)) {
if (options.getNumberSolutions() == -1 || options.getNumberSolutions() > final_search_seq.getSolutionListener().solutionsNo())
System.out.println("==========");
}
else
System.out.println("%% =====TIME-OUT=====");
else
if (anyTimeOutOccured(list_seq_searches))
System.out.println("%% =====TIME-OUT=====");
}
else if (optimization) {
if (!heuristicSeqSearch)
if (! anyTimeOutOccured(list_seq_searches)) {
if (options.getNumberSolutions() == -1 || options.getNumberSolutions() > final_search_seq.getSolutionListener().solutionsNo())
System.out.println("==========");
}
else
System.out.println("%% =====TIME-OUT=====");
else
if (anyTimeOutOccured(list_seq_searches))
System.out.println("%% =====TIME-OUT=====");
}
}
else
if (anyTimeOutOccured(list_seq_searches)) {
System.out.println("=====UNKNOWN=====");
System.out.println("%% =====TIME-OUT=====");
}
else
if (interrupted)
System.out.println ("%% =====INTERRUPTED=====");
else
System.out.println("=====UNSATISFIABLE=====");
if (options.getStatistics()) {
int nodes=0, decisions=0, wrong=0, backtracks=0, depth=0,solutions=0;
for (Search<Var> label : list_seq_searches) {
nodes += label.getNodes();
decisions += label.getDecisions();
wrong += label.getWrongDecisions();
backtracks += label.getBacktracks();
depth += label.getMaximumDepth();
solutions = label.getSolutionListener().solutionsNo();
}
System.out.println("\n%% Model variables : "+ (store.size()+ NumberBoolVariables) +
"\n%% Model constraints : "+initNumberConstraints+
"\n\n%% Search CPU time : " + (searchTimeMeter.getThreadCpuTime(tread.getId()) - startCPU)/(long)1e+6 + "ms"+
"\n%% Search nodes : "+nodes+
"\n%% Search decisions : "+decisions+
"\n%% Wrong search decisions : "+wrong+
"\n%% Search backtracks : "+backtracks+
"\n%% Max search depth : "+depth+
"\n%% Number solutions : "+ solutions
);
}
}
boolean anyTimeOutOccured(ArrayList<Search<Var>> list_seq_searches) {
for (Search<Var> list_seq_searche : list_seq_searches)
if (((DepthFirstSearch) list_seq_searche).timeOutOccured)
return true;
return false;
}
DepthFirstSearch<Var> sub_search(SearchItem si, DepthFirstSearch<Var> l, boolean master) {
DepthFirstSearch<Var> last_search = l;
DepthFirstSearch<Var> label = null;
if (si.type().equals("int_search") || si.type().equals("bool_search")) {
label = int_search(si);
if (!master) label.setSelectChoicePoint(variable_selection);
// LDS heuristic search
if (si.exploration().equals("lds")) {
lds_search(label, si.ldsValue);
heuristicSeqSearch = true;
}
// Credit heuristic search
if (si.exploration().equals("credit")) {
credit_search(label, si.creditValue, si.bbsValue);
heuristicSeqSearch = true;
}
list_seq_searches.add(label);
}
else if (si.type().equals("set_search")) {
setSearch=true;
label = set_search(si);
if (!master)
label.setSelectChoicePoint(variable_selection);
// LDS heuristic search
if (si.exploration().equals("lds")) {
lds_search(label, si.ldsValue);
heuristicSeqSearch = true;
}
// Credit heuristic search
if (si.exploration().equals("credit")) {
credit_search(label, si.creditValue, si.bbsValue);
heuristicSeqSearch = true;
}
list_seq_searches.add(label);
}
else if (si.type().equals("seq_search")) {
for (int i=0; i<si.getSearchItems().size(); i++)
if (i == 0) { // master search
DepthFirstSearch<Var> label_seq = sub_search(si.getSearchItems().get(i), last_search, false);
last_search = label_seq;
label = label_seq;
}
else {
DepthFirstSearch<Var> label_seq = sub_search(si.getSearchItems().get(i), last_search, false);
last_search.addChildSearch(label_seq);
last_search = label_seq;
}
}
else {
System.err.println("Not recognized or supported search type \""+si.type()+"\"; compilation aborted");
System.exit(0);
}
return label;
}
DepthFirstSearch<Var> int_search(SearchItem si) {
variable_selection = si.getIntSelect();
return new DepthFirstSearch<Var>();
}
DepthFirstSearch<Var> set_search(SearchItem si) {
variable_selection = si.getSetSelect();
return new DepthFirstSearch<Var>();
}
// long T, TOld = 0;
void printSolution() {
// T = System.currentTimeMillis();
// System.out.println("% Search time since last solution : " + (T - TOld)/1000 + " s");
// TOld = T;
if (dictionary.outputVariables.size() > 0)
for (int i=0; i<dictionary.outputVariables.size(); i++) {
Var v = dictionary.outputVariables.get(i);
if (v instanceof BooleanVar) {
// print boolean variables
String boolVar = v.id()+" = ";
if (v.singleton())
switch ( ((BooleanVar)v).value()) {
case 0: boolVar += "false";
break;
case 1: boolVar += "true";
break;
default: boolVar += v.dom();
}
else
boolVar += "false..true";
System.out.println(boolVar+";");
}
else if (v instanceof SetVar) {
// print set variables
String setVar = v.id() + " = ";
if (v.singleton()) {
IntDomain glb = ((SetVar)v).dom().glb();
setVar += "{";
for (ValueEnumeration e = glb.valueEnumeration(); e.hasMoreElements();) {
int element = e.nextElement();
setVar += element;
if (e.hasMoreElements())
setVar += ", ";
}
setVar += "}";
}
else
setVar += v.dom().toString();
System.out.println(setVar+";");
}
else
System.out.println(v+";");
}
for (int i=0; i<dictionary.outputArray.size(); i++) {
OutputArrayAnnotation a = dictionary.outputArray.get(i);
System.out.println(a);
}
}
int getKind(String k) {
if (k.equals("satisfy")) // 0 = satisfy
return 0;
else if (k.equals("minimize")) // 1 = minimize
return 1;
else if (k.equals("maximize")) // 2 = maximize
return 2;
else {
System.err.println("Not supported search kind; compilation aborted");
System.exit(0);
return -1;
}
}
IntVar getCost(ASTSolveExpr node) {
if (node.getType() == 0) // ident
return dictionary.getVariable(node.getIdent());
else if (node.getType() == 1) // array access
return dictionary.getVariableArray(node.getIdent())[node.getIndex()];
else {
System.err.println("Wrong cost function specification " + node);
System.exit(0);
return new IntVar(store);
}
}
void pose(Constraint c) {
store.impose(c);
if (debug)
System.out.println(c);
}
/*
boolean restart_search(Search<Var> masterLabel, SelectChoicePoint<Var> masterSelect,
IntVar cost, boolean minimize) {
costVariable = cost;
Search<Var> final_search = list_seq_searches.get(list_seq_searches.size()-1);
for (Search s : list_seq_searches)
s.setAssignSolution(false);
store.setLevel(store.level+1);
boolean Result = true, optimalResult = false;
while (Result) {
Result = masterLabel.labeling(store, masterSelect);
if (minimize) //minimize
pose(new XltC(cost, costValue));
else // maximize
pose(new XgtC(cost, costValue));
optimalResult = optimalResult || Result;
if (options.getNumberSolutions() == final_search.getSolutionListener().solutionsNo())
break;
}
store.removeLevel(store.level);
store.setLevel(store.level-1);
Result = optimalResult;
if (Result)
for (Search s : list_seq_searches)
s.assignSolution();
return Result;
}
*/
void lds_search(DepthFirstSearch<Var> label, int lds_value) {
// System.out.println("LDS("+lds_value+")");
LDS<Var> lds = new LDS<Var>(lds_value);
if (label.getExitChildListener() == null)
label.setExitChildListener(lds);
else
label.getExitChildListener().setChildrenListeners(lds);
}
void credit_search(DepthFirstSearch<Var> label, int creditValue, int bbsValue) {
// System.out.println("Credit("+creditValue+", "+bbsValue+")");
int maxDepth = 1000; //IntDomain.MaxInt;
CreditCalculator<Var> credit = new CreditCalculator<Var>(creditValue, bbsValue, maxDepth);
if (label.getConsistencyListener() == null)
label.setConsistencyListener(credit);
else
label.getConsistencyListener().setChildrenListeners(credit);
label.setExitChildListener(credit);
label.setTimeOutListener(credit);
}
void setNumberBoolVariables(int n) {
NumberBoolVariables = n;
}
void printSearch(Search label) {
int N = 1;
System.out.println (N++ + ". " + label);
java.util.LinkedHashSet<Search<? extends Var>> l =
new java.util.LinkedHashSet<Search<? extends Var>>();
l.add(label);
while (l.size() != 0) {
java.util.LinkedHashSet<Search<? extends Var>> ns =
new java.util.LinkedHashSet<Search<? extends Var>>();
for (Search s1 : l) {
Search<? extends Var>[] child = ((DepthFirstSearch)s1).childSearches;
if (child != null)
for (Search s : child) {
System.out.println (N + ". " + s);
ns.add(s);
}
}
N++;
l = ns;
}
}
int FinalNumberSolutions = 0;
/**
*
*
* @author Krzysztof Kuchcinski
*
*/
public class CostListener<T extends Var> extends SimpleSolutionListener<T> {
public boolean executeAfterSolution(Search<T> search, SelectChoicePoint<T> select) {
boolean returnCode = super.executeAfterSolution(search, select);
/* // === used to print number of search nodes for each solution
int nodes=0;
for (Search<Var> label : list_seq_searches)
nodes += label.getNodes();
System.out.println("%% Search nodes : "+ nodes );
*/
if (costVariable != null)
costValue = ((IntVar)costVariable).value();
FinalNumberSolutions++;
printSolution();
System.out.println("----------");
return returnCode;
}
}
class DomainSizeComparator<T extends Var> implements Comparator<T> {
DomainSizeComparator() { }
public int compare(T o1, T o2) {
int v1 = o1.getSize();
int v2 = o2.getSize();
return v1 - v2;
}
}
}
|
diff --git a/src/main/java/org/jpc/engine/pdtconnector/PdtConnectorEngine.java b/src/main/java/org/jpc/engine/pdtconnector/PdtConnectorEngine.java
index 5f236bf..19957c0 100644
--- a/src/main/java/org/jpc/engine/pdtconnector/PdtConnectorEngine.java
+++ b/src/main/java/org/jpc/engine/pdtconnector/PdtConnectorEngine.java
@@ -1,59 +1,59 @@
package org.jpc.engine.pdtconnector;
import org.cs3.prolog.cterm.CTerm;
import org.cs3.prolog.cterm.CTermUtil;
import org.cs3.prolog.pif.PrologInterface;
import org.cs3.prolog.pif.PrologInterfaceException;
import org.jpc.Jpc;
import org.jpc.engine.prolog.AbstractPrologEngine;
import org.jpc.error.PrologParsingException;
import org.jpc.query.Query;
import org.jpc.term.Term;
public class PdtConnectorEngine extends AbstractPrologEngine {
private PrologInterface wrappedEngine;
public PdtConnectorEngine(PrologInterface wrappedEngine) {
this.wrappedEngine = wrappedEngine;
}
public PrologInterface getWrappedEngine() {
return wrappedEngine;
}
@Override
public void close() {
try {
wrappedEngine.stop();
} catch (PrologInterfaceException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean isCloseable() {
return true;
}
@Override
public boolean isMultiThreaded() {
return true;
}
@Override
public Term asTerm(String termString, Jpc context) { //TODO delete context here
try {
- CTerm pdtTerm = CTermUtil.parseNonCanonicalTerm(termString);
+ CTerm pdtTerm = CTermUtil.parseNonCanonicalTerm(termString, wrappedEngine);
return PdtConnectorBridge.fromPdtConnectorToJpc(pdtTerm);
} catch(Exception e) {
throw new PrologParsingException(termString, e);
}
}
@Override
protected Query basicQuery(Term goal, Jpc context) {
return new PdtConnectorQuery(this, goal, context);
}
}
| true | true | public Term asTerm(String termString, Jpc context) { //TODO delete context here
try {
CTerm pdtTerm = CTermUtil.parseNonCanonicalTerm(termString);
return PdtConnectorBridge.fromPdtConnectorToJpc(pdtTerm);
} catch(Exception e) {
throw new PrologParsingException(termString, e);
}
}
| public Term asTerm(String termString, Jpc context) { //TODO delete context here
try {
CTerm pdtTerm = CTermUtil.parseNonCanonicalTerm(termString, wrappedEngine);
return PdtConnectorBridge.fromPdtConnectorToJpc(pdtTerm);
} catch(Exception e) {
throw new PrologParsingException(termString, e);
}
}
|
diff --git a/bobo-browse/src/com/browseengine/bobo/api/BrowseHit.java b/bobo-browse/src/com/browseengine/bobo/api/BrowseHit.java
index f80de2e..62fc22d 100644
--- a/bobo-browse/src/com/browseengine/bobo/api/BrowseHit.java
+++ b/bobo-browse/src/com/browseengine/bobo/api/BrowseHit.java
@@ -1,213 +1,213 @@
package com.browseengine.bobo.api;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.lucene.document.Document;
import org.apache.lucene.search.Explanation;
/**
* A hit from a browse
*/
public class BrowseHit
implements Serializable
{
private static final long serialVersionUID = 1L;
/**
* Get the score
* @return score
* @see #setScore(float)
*/
public float getScore()
{
return score;
}
/**
* Get the field values
* @param field field name
* @return field value array
* @see #getField(String)
*/
public String[] getFields(String field)
{
return _fieldValues != null ? _fieldValues.get(field) : null;
}
/**
* Get the raw field values
* @param field field name
* @return field value array
* @see #getRawField(String)
*/
public Object[] getRawFields(String field)
{
return _rawFieldValues != null ? _rawFieldValues.get(field) : null;
}
/**
* Get the field value
* @param field field name
* @return field value
* @see #getFields(String)
*/
public String getField(String field)
{
String[] fields=getFields(field);
if (fields!=null && fields.length > 0)
{
return fields[0];
}
else
{
return null;
}
}
/**
* Get the raw field value
* @param field field name
* @return raw field value
* @see #getRawFields(String)
*/
public Object getRawField(String field)
{
Object[] fields=getRawFields(field);
if (fields!=null && fields.length > 0)
{
return fields[0];
}
else
{
return null;
}
}
private float score;
private int docid;
private Map<String,String[]> _fieldValues;
private Map<String,Object[]> _rawFieldValues;
private Comparable<?> _comparable;
private Document _storedFields;
private Explanation _explanation;
public Explanation getExplanation() {
return _explanation;
}
public void setExplanation(Explanation explanation) {
_explanation = explanation;
}
public void setComparable(Comparable<?> comparable)
{
_comparable = comparable;
}
public Comparable<?> getComparable()
{
return _comparable;
}
/**
* Gets the internal document id
* @return document id
* @see #setDocid(int)
*/
public int getDocid() {
return docid;
}
/**
* Sets the internal document id
* @param docid document id
* @see #getDocid()
*/
public void setDocid(int docid) {
this.docid = docid;
}
/**
* Gets the field values
* @return field value map
* @see #setFieldValues(Map)
*/
public Map<String,String[]> getFieldValues() {
return _fieldValues;
}
/**
* Sets the raw field value map
* @param rawFieldValues raw field value map
* @see #getRawFieldValues()
*/
public void setRawFieldValues(Map<String,Object[]> rawFieldValues) {
_rawFieldValues = rawFieldValues;
}
/**
* Gets the raw field values
* @return raw field value map
* @see #setRawFieldValues(Map)
*/
public Map<String,Object[]> getRawFieldValues() {
return _rawFieldValues;
}
/**
* Sets the field value map
* @param fieldValues field value map
* @see #getFieldValues()
*/
public void setFieldValues(Map<String,String[]> fieldValues) {
_fieldValues = fieldValues;
}
/**
* Sets the score
* @param score score
* @see #getScore()
*/
public void setScore(float score) {
this.score = score;
}
public void setStoredFields(Document doc){
_storedFields = doc;
}
public Document getStoredFields(){
return _storedFields;
}
public String toString(Map<String, String[]> map)
{
StringBuilder buffer = new StringBuilder();
Set<Map.Entry<String, String[]>> set = map.entrySet();
Iterator<Map.Entry<String, String[]>> iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry<String, String[]> e = iterator.next();
buffer.append(e.getKey());
buffer.append(":");
String[] vals = e.getValue();
- buffer.append(vals == null ? null: vals);
+ buffer.append(vals == null ? null: Arrays.toString(vals));
if (iterator.hasNext()) buffer.append(", ");
}
return buffer.toString();
}
@Override
public String toString() {
StringBuffer buffer=new StringBuffer();
buffer.append("docid: ").append(docid);
buffer.append("score: ").append(score).append('\n');
buffer.append("field values: ").append(toString(_fieldValues)).append('\n');
return buffer.toString();
}
}
| true | true | public String toString(Map<String, String[]> map)
{
StringBuilder buffer = new StringBuilder();
Set<Map.Entry<String, String[]>> set = map.entrySet();
Iterator<Map.Entry<String, String[]>> iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry<String, String[]> e = iterator.next();
buffer.append(e.getKey());
buffer.append(":");
String[] vals = e.getValue();
buffer.append(vals == null ? null: vals);
if (iterator.hasNext()) buffer.append(", ");
}
return buffer.toString();
}
| public String toString(Map<String, String[]> map)
{
StringBuilder buffer = new StringBuilder();
Set<Map.Entry<String, String[]>> set = map.entrySet();
Iterator<Map.Entry<String, String[]>> iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry<String, String[]> e = iterator.next();
buffer.append(e.getKey());
buffer.append(":");
String[] vals = e.getValue();
buffer.append(vals == null ? null: Arrays.toString(vals));
if (iterator.hasNext()) buffer.append(", ");
}
return buffer.toString();
}
|
diff --git a/SWADroid/src/es/ugr/swad/swadroid/model/DataBaseHelper.java b/SWADroid/src/es/ugr/swad/swadroid/model/DataBaseHelper.java
index 1bf130bc..4b6627d5 100644
--- a/SWADroid/src/es/ugr/swad/swadroid/model/DataBaseHelper.java
+++ b/SWADroid/src/es/ugr/swad/swadroid/model/DataBaseHelper.java
@@ -1,1904 +1,1904 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <[email protected]>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.model;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import org.xmlpull.v1.XmlPullParserException;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
//import net.sqlcipher.database.SQLiteDatabase;
//import net.sqlcipher.database.SQLiteStatement;
import android.os.Environment;
import android.util.Log;
import com.android.dataframework.DataFramework;
import com.android.dataframework.Entity;
import es.ugr.swad.swadroid.Global;
//import es.ugr.swad.swadroid.Preferences;
/**
* @author Juan Miguel Boyero Corral <[email protected]>
* @author Antonio Aguilera Malagon <[email protected]>
* @author Helena Rodriguez Gijon <[email protected]>
*/
public class DataBaseHelper {
/**
* Field for access to the database backend
*/
private DataFramework db;
/**
* Application context
*/
private Context mCtx;
/**
* Application preferences
*/
//private Preferences prefs = new Preferences();
/**
* Database name
*/
//private String DBName = "swadroid_db";
/**
* Database passphrase
*/
//private String DBKey;
/**
* Database passphrase length
*/
//private int DB_KEY_LENGTH = 128;
/**
* Constructor
* @param database Previously instantiated DataFramework object
*/
public DataBaseHelper(Context ctx) {
mCtx = ctx;
//prefs.getPreferences(mCtx);
//DBKey = prefs.getDBKey();
db = DataFramework.getInstance();
//Initialize SQLCipher libraries
//SQLiteDatabase.loadLibs(mCtx);
//If the passphrase is empty, generate a random passphrase and recreate database
/*if(DBKey.equals("")) {
DBKey = Global.randomString(DB_KEY_LENGTH);
prefs.setDBKey(DBKey);
mCtx.deleteDatabase(DBName);
SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(mCtx.getDatabasePath("swadroid_db_crypt"), DBKey, null);
database.close();
}
Log.d("DataBaseHelper", "DBKey=" + DBKey);*/
try {
//db.open(mCtx, mCtx.getPackageName(), DBKey);
db.open(mCtx, mCtx.getPackageName());
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Closes the database
*/
public synchronized void close() {
db.close();
}
/**
* Gets DB object
* @return DataFramework DB object
*/
public DataFramework getDb() {
return db;
}
/**
* Sets DB object
* @param db DataFramework DB object
*/
public void setDb(DataFramework db) {
this.db = db;
}
/**
* Selects the appropriated parameters for access a table
* @param table Table to be accessed
* @return A pair of strings containing the selected parameters
*/
private Pair<String, String> selectParamsPairTable(String table) {
String firstParam = null;
String secondParam = null;
if(table.equals(Global.DB_TABLE_TEST_QUESTIONS_COURSE)) {
firstParam = "qstCod";
secondParam = "crsCod";
} else if(table.equals(Global.DB_TABLE_TEST_QUESTION_ANSWERS)) {
firstParam = "qstCod";
secondParam = "ansCod";
} else if(table.equals(Global.DB_TABLE_USERS_COURSES)) {
firstParam = "userCode";
secondParam = "crsCod";
}else if(table.equals(Global.DB_TABLE_GROUPS_COURSES)){
firstParam = "grpCod";
secondParam = "crsCod";
}else if(table.equals(Global.DB_TABLE_GROUPS_GROUPTYPES)){
firstParam = "grpTypCod";
secondParam = "grpCod";
}else {
Log.e("selectParamsPairTable", "Table " + table + " not exists");
}
return new Pair<String, String>(firstParam, secondParam);
}
/**
* Gets ParTable class from table
* @param <T>
* */
/* private <T> PairTable<T, T> getPairTable(String table, T firstValue, T secondValue){
PairTable<T,T> par;
if(table.equals(Global.DB_TABLE_GROUPS_GROUPTYPES)){
par = new PairTable<T,T>(table,firstValue,secondValue);
}
return new Pair<Class,Class>(firstClass,secondClass);
}*/
/**
* Creates a Model's subclass object looking at the table selected
* @param table Table selected
* @param ent Cursor to the table rows
* @return A Model's subclass object
*/
@SuppressWarnings("rawtypes")
private Model createObjectByTable(String table, Entity ent) {
Model o = null;
Pair<String, String> params;
long id;
if(table.equals(Global.DB_TABLE_COURSES)) {
o = new Course(ent.getInt("id"),
ent.getInt("userRole"),
ent.getString("shortName"),
ent.getString("fullName"));
} else if(table.equals(Global.DB_TABLE_TEST_QUESTIONS_COURSE) ||
table.equals(Global.DB_TABLE_TEST_QUESTION_ANSWERS) ||
table.equals(Global.DB_TABLE_USERS_COURSES) ||
table.equals(Global.DB_TABLE_GROUPS_COURSES) ||
table.equals(Global.DB_TABLE_GROUPS_GROUPTYPES)) {
params = selectParamsPairTable(table);
o = new PairTable<Integer, Integer>(table,
ent.getInt(params.getFirst()),
ent.getInt(params.getSecond()));
} else if(table.equals(Global.DB_TABLE_NOTIFICATIONS)) {
o = new SWADNotification(ent.getInt("id"),
ent.getString("eventType"),
ent.getLong("eventTime"),
ent.getString("userSurname1"),
ent.getString("userSurname2"),
ent.getString("userFirstname"),
ent.getString("userPhoto"),
ent.getString("location"),
ent.getString("summary"),
ent.getInt("status"),
ent.getString("content"));
} else if(table.equals(Global.DB_TABLE_TEST_QUESTIONS)) {
id = ent.getInt("id");
PairTable q = (PairTable)getRow(Global.DB_TABLE_TEST_QUESTIONS_COURSE, "qstCod", Long.toString(id));
if(q != null) {
o = new TestQuestion(id,
(Integer) q.getFirst(),
ent.getString("stem"),
ent.getString("ansType"),
Global.parseStringBool(ent.getString("shuffle")));
} else {
o = null;
}
} else if(table.equals(Global.DB_TABLE_TEST_ANSWERS)) {
id = ent.getId();
int ansInd = ent.getInt("ansInd");
PairTable a = (PairTable)getRow(Global.DB_TABLE_TEST_QUESTION_ANSWERS, "ansCod", Long.toString(id));
if(a != null) {
o = new TestAnswer(id,
ansInd,
(Integer) a.getFirst(),
Global.parseStringBool(ent.getString("correct")),
ent.getString("answer"));
} else {
o = null;
}
} else if(table.equals(Global.DB_TABLE_TEST_TAGS)) {
id = ent.getInt("tagCod");
TestTag t = (TestTag)getRow(Global.DB_TABLE_TEST_QUESTION_TAGS, "tagCod", Long.toString(id));
if(t != null) {
o = new TestTag(id,
t.getQstCodList(),
ent.getString("tagTxt"),
ent.getInt("tagInd"));
} else {
o = null;
}
} else if(table.equals(Global.DB_TABLE_TEST_CONFIG)) {
o = new Test(ent.getInt("id"),
ent.getInt("min"),
ent.getInt("def"),
ent.getInt("max"),
ent.getString("feedback"),
ent.getLong("editTime"));
} else if(table.equals(Global.DB_TABLE_TEST_QUESTION_TAGS)) {
ArrayList<Integer> l = new ArrayList<Integer>();
l.add(ent.getInt("qstCod"));
o = new TestTag(ent.getInt("tagCod"),
l,
null,
ent.getInt("tagInd"));
} else if(table.equals(Global.DB_TABLE_USERS)) {
o = new User(ent.getInt("userCode"),
null, // wsKey
ent.getString("userID"),
ent.getString("userNickname"),
ent.getString("userSurname1"),
ent.getString("userSurname2"),
ent.getString("userFirstname"),
ent.getString("photoPath"),
ent.getInt("userRole"));
} else if (table.equals(Global.DB_TABLE_GROUPS)){
long groupTypeCode = getGroupTypeCodeFromGroup(ent.getLong("id"));
o = new Group(ent.getLong("id"),
ent.getString("groupName"),
groupTypeCode,
ent.getInt("maxStudents"),
ent.getInt("open"),
ent.getInt("students"),
ent.getInt("fileZones"),
ent.getInt("member"));
}else if (table.equals(Global.DB_TABLE_GROUP_TYPES)){
o = new GroupType(ent.getLong("id"),
ent.getString("groupTypeName"),
ent.getLong("courseCode"),
ent.getInt("mandatory"),
ent.getInt("multiple"),
ent.getLong("openTime"));
} else if(table.equals(Global.DB_TABLE_PRACTICE_SESSIONS)) {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
try {
o = new PracticeSession(ent.getId(),
ent.getInt("crsCod"),
ent.getInt("grpCod"),
format.parse(ent.getString("startDate")),
format.parse(ent.getString("endDate")),
ent.getString("site"),
ent.getString("description"));
} catch (ParseException e) {
e.printStackTrace();
}
}
return o;
}
/**
* Gets all rows of specified table
* @param table Table containing the rows
* @return A list of Model's subclass objects
*/
public List<Model> getAllRows(String table)
{
List<Model> result = new ArrayList<Model>();
List<Entity> rows = db.getEntityList(table);
Model row;
Iterator<Entity> iter = rows.iterator();
while (iter.hasNext()) {
Entity ent = iter.next();
row = createObjectByTable(table, ent);
result.add(row);
}
return result;
}
/**
* Gets the rows of specified table that matches "where" condition. The rows are ordered as says the "orderby"
* parameter
* @param table Table containing the rows
* @param where Where condition of SQL sentence
* @param orderby Orderby part of SQL sentence
* @return A list of Model's subclass objects
*/
public List<Model> getAllRows(String table, String where, String orderby)
{
List<Model> result = new ArrayList<Model>();
List<Entity> rows = db.getEntityList(table, where, orderby);
Model row;
if (rows != null) {
Iterator<Entity> iter = rows.iterator();
while (iter.hasNext()) {
Entity ent = iter.next();
row = createObjectByTable(table, ent);
result.add(row);
}
}
return result;
}
/**
* Gets a row of specified table
* @param table Table containing the rows
* @param fieldName Field's name
* @param fieldValue Field's value
* @return A Model's subclass object
* or null if the row does not exist in the specified table
*/
public Model getRow(String table, String fieldName, String fieldValue)
{
List<Entity> rows = db.getEntityList(table, fieldName + " = '" + fieldValue + "'");
Entity ent;
Model row = null;
if(rows.size() > 0) {
ent = rows.get(0);
row = createObjectByTable(table, ent);
}
return row;
}
/**
* Gets the id of users enrolled in the selected course
* @param courseCode Course code to be referenced
* @return A list of User's id
*/
public List<Long> getUsersCourse(long courseCode) {
List<Long> result = new ArrayList<Long>();
List<Entity> rows = db.getEntityList(Global.DB_TABLE_USERS_COURSES, "crsCod = '" + courseCode + "'");
if (rows != null) {
Iterator<Entity> iter = rows.iterator();
while (iter.hasNext()) {
Entity ent = iter.next();
result.add(ent.getLong("userCode"));
}
}
return result;
}
/**
* Gets the actual practice session in progress for the selected course and group
* @param courseCode Course code to be referenced
* @param groupId Group code to be referenced
* @return The practice session in progress if any, or null otherwise
*/
public PracticeSession getPracticeSessionInProgress(long courseCode, long groupId) {
String table = Global.DB_TABLE_PRACTICE_SESSIONS;
Calendar cal = Calendar.getInstance();
Calendar startDate = Calendar.getInstance();
Calendar endDate = Calendar.getInstance();
List<Entity> rows = db.getEntityList(table, "crsCod = " + courseCode + " AND grpCod = " + groupId);
PracticeSession ps = null;
if (rows != null) {
Iterator<Entity> iter = rows.iterator();
while (iter.hasNext()) {
Entity ent = iter.next();
ps = (PracticeSession) createObjectByTable(table, ent);
startDate.setTime(ps.getSessionStartDate());
endDate.setTime(ps.getSessionEndDate());
if (cal.after(startDate) && cal.before(endDate)) {
return ps;
}
}
}
return null;
}
/**
* Gets practice sessions for the selected course and group
* @param courseCode Course code to be referenced
* @param groupId Group code to be referenced
* @return The list of practice sessions
*/
public List<PracticeSession> getPracticeSessions(long courseCode, long groupId) {
List<PracticeSession> sessions = new ArrayList<PracticeSession>();
String table = Global.DB_TABLE_PRACTICE_SESSIONS;
String where = "crsCod = " + courseCode + " AND grpCod = " + groupId;
List<Entity> rows = db.getEntityList(table, where, "startDate asc");
PracticeSession ps = null;
if (rows != null) {
Iterator<Entity> iter = rows.iterator();
while (iter.hasNext()) {
Entity ent = iter.next();
ps = (PracticeSession) createObjectByTable(table, ent);
sessions.add(ps);
}
}
return sessions;
}
/**
* Gets the group which code is given
* @param groupId long that identifies uniquely the searched group
* @return group with the referenced code in case it exits
* null otherwise
* */
public Group getGroup(long groupId) {
String table = Global.DB_TABLE_GROUPS;
List<Entity> rows = db.getEntityList(table, "id = " + groupId);
Group g = null;
if (rows != null)
g = (Group) createObjectByTable(table, rows.get(0));
return g;
}
/**
* Gets the group codes in the selected course
* @param courseCode Course code to be referenced
* @return A list of group codes belonging to the selected course
*/
public List<Long> getGroupCodesCourse(long courseCode) {
List<Long> result = new ArrayList<Long>();
List<Entity> rows = db.getEntityList(Global.DB_TABLE_GROUPS_COURSES, "crsCod = '" + courseCode + "'");
if (rows != null) {
Iterator<Entity> iter = rows.iterator();
while (iter.hasNext()) {
Entity ent = iter.next();
result.add(ent.getLong("grpCod"));
}
}
return result;
}
/**
* Gets the groups belonging to the selected type of group
* @param groupTypeCode group type code to be referenced
* @return List of Groups
* */
public List <Group> getGroupsOfType(long groupTypeCode){
List <Group> groups = new ArrayList<Group>();
List <Long> groupCodes = getGroupsCodesOfType(groupTypeCode);
if(!groupCodes.isEmpty()){
Iterator<Long> iter = groupCodes.iterator();
while(iter.hasNext()){
groups.add((Group)getRow(Global.DB_TABLE_GROUPS,"id",String.valueOf(iter.next())));
}
}
return groups;
}
/**
*
* */
public Cursor getCursorGroupsOfType(long groupTypeCode){
String select = "SELECT g.* "+
" FROM " +
Global.DB_TABLE_GROUPS + " g, " + Global.DB_TABLE_GROUPS_GROUPTYPES + " ggt" +
" WHERE " +
"g.id = ggt.grpCod AND ggt.grpTypCod = ? ORDER BY groupName";
SQLiteDatabase db = DataFramework.getInstance().getDB();
//TODO sustituir rawquery por getCursor(String table, String[] fields, String selection,
//String[] selectionArgs, String groupby, String having, String orderby, String limit)
return db.rawQuery(select, new String [] { String.valueOf(groupTypeCode) });
}
public Cursor getCursor(String table, String where, String orderby){
return db.getCursor(table, where, orderby);
}
public Cursor getCursorGroupType(long courseCode){
return db.getCursor(Global.DB_TABLE_GROUP_TYPES, "courseCode =" + courseCode, "groupTypeName");
}
public GroupType getGroupTypeFromGroup(long groupCode){
long groupTypeCode = getGroupTypeCodeFromGroup(groupCode);
return (GroupType) getRow(Global.DB_TABLE_GROUP_TYPES,"id",String.valueOf(groupTypeCode));
}
/**
* Gets the code of the group type belonging the group with the given group code
* @param groupCode long that specifies the code of the group
* @return group type code in case the given group belongs to a group type
* -1 otherwise
* */
public long getGroupTypeCodeFromGroup(long groupCode){
List<Entity> rows = db.getEntityList(Global.DB_TABLE_GROUPS_GROUPTYPES, "grpCod = '" + groupCode +"'");
long groupTypeCode = -1;
if(!rows.isEmpty()){
groupTypeCode = rows.get(0).getLong("grpTypCod");
}
return groupTypeCode;
}
/**
* Gets the codes of groups belonging the selected type of group
* @param groupTypeCode group type code to be referenced
* @return List of group codes
* */
private List<Long> getGroupsCodesOfType(long groupTypeCode){
List <Long> groupCodes = new ArrayList<Long>();
List<Entity> rows = db.getEntityList(Global.DB_TABLE_GROUPS_GROUPTYPES, "grpTypCod = '" + groupTypeCode +"'");
if(rows != null){
Iterator<Entity> iter = rows.iterator();
while(iter.hasNext()){
groupCodes.add(iter.next().getLong("grpCod"));
}
}
return groupCodes;
}
/**
* Get groups belonging to the referred course to which the logged user is enrolled
* @param courseCode course code to which the groups belong
* @return List of the group
* */
public List<Group> getUserLoggedGroups(long courseCode){
List<Long> groupCodes = getGroupCodesCourse(courseCode);
List<Group> groups = new ArrayList<Group>();
if(!groupCodes.isEmpty()){
Iterator<Long> iter = groupCodes.iterator();
while(iter.hasNext()){
Group g = (Group) getRow(Global.DB_TABLE_GROUPS,"id",String.valueOf(iter.next()));
if(g.isMember()) groups.add(g);
}
}
return groups;
}
/**
* Gets the practice groups in the selected course
* @param courseCode Course code to be referenced
* @return Cursor access to the practice groups
*/
public Cursor getPracticeGroups(long courseCode) {
String select = "SELECT " +
"g._id, g.id, g.groupName" +
" FROM " +
Global.DB_TABLE_GROUPS + " g, " + Global.DB_TABLE_GROUPS_COURSES + " gc" +
" WHERE " +
"g.id = gc.grpCod AND gc.crsCod = ?";
SQLiteDatabase db = DataFramework.getInstance().getDB();
return db.rawQuery(select, new String [] { String.valueOf(courseCode) });
}
/**
* Gets the user codes of students in the selected session
* @param sessionId Session code to be referenced
* @return A list of User's id
*/
public List<Long> getStudentsAtSession(long sessionId) {
List<Long> result = new ArrayList<Long>();
List<Entity> rows = db.getEntityList(Global.DB_TABLE_ROLLCALL, "sessCod = " + sessionId);
if (rows != null) {
Iterator<Entity> iter = rows.iterator();
while (iter.hasNext()) {
Entity ent = iter.next();
result.add(ent.getLong("usrCod"));
}
}
return result;
}
public boolean hasAttendedSession(long userCode, long sessionId) {
List<Entity> rows = db.getEntityList(Global.DB_TABLE_ROLLCALL, "usrCod = " + userCode + " AND sessCod = " + sessionId);
return (rows.size() > 0);
}
/**
* Checks if the specified user is enrolled in the selected course
* @param userId User's DNI (national identity)
* @param selectedCourseCode Course code to be referenced
* @return True if user is enrolled in the selected course. False otherwise
*/
public boolean isUserEnrolledCourse(String userID, long selectedCourseCode) {
boolean enrolled = false;
User u = (User) getRow(Global.DB_TABLE_USERS, "userID", userID);
if (u != null) {
String sentencia = "SELECT userCode AS _id, crsCod" +
" FROM " + Global.DB_TABLE_USERS_COURSES +
" WHERE userCode = ? AND crsCod = ?" +
" ORDER BY 1";
Cursor c = db.getDB().rawQuery(sentencia, new String [] {
String.valueOf(u.getId()),
String.valueOf(selectedCourseCode)
});
if (c.moveToFirst()) {
enrolled = true;
}
c.close();
} else
enrolled = false;
return enrolled;
}
/**
* Gets the groups that owns the selected course
* @param courseCode Course code to be referenced
* @return Cursor access to the groups
* */
public List<Group> getGroups(long courseCode, String...filter){
String select = "SELECT grpCod FROM " + Global.DB_TABLE_GROUPS_COURSES + " WHERE crsCod = " + courseCode +";";
Cursor groupCodes = db.getDB().rawQuery(select, null);
List<Group> groups = new ArrayList<Group>(groupCodes.getCount());
while (groupCodes.moveToNext()){
Group group = (Group)this.getRow(Global.DB_TABLE_GROUPS, "id", String.valueOf(groupCodes.getInt(0)));
groups.add(group);
}
return groups;
}
/**
* Inserts a course in database
* @param c Course to be inserted
*/
public void insertCourse(Course c)
{
Entity ent = new Entity(Global.DB_TABLE_COURSES);
ent.setValue("id", c.getId());
ent.setValue("userRole", c.getUserRole());
ent.setValue("shortName", c.getShortName());
ent.setValue("fullName", c.getFullName());
ent.save();
}
/**
* Inserts a notification in database
* @param n Notification to be inserted
*/
public void insertNotification(SWADNotification n)
{
Entity ent = new Entity(Global.DB_TABLE_NOTIFICATIONS);
String eventTime = String.valueOf(n.getEventTime());
String status = String.valueOf(n.getStatus());
ent.setValue("id", n.getId());
ent.setValue("eventType", n.getEventType());
ent.setValue("eventTime", eventTime);
ent.setValue("userSurname1", n.getUserSurname1());
ent.setValue("userSurname2", n.getUserSurname2());
ent.setValue("userFirstname", n.getUserFirstName());
ent.setValue("userPhoto", n.getUserPhoto());
ent.setValue("location", n.getLocation());
ent.setValue("summary", n.getSummary());
ent.setValue("status", status);
ent.setValue("content", n.getContent());
ent.save();
}
/**
* Inserts a test question in database
* @param q Test question to be inserted
* @param selectedCourseCode Course code to be referenced
*/
public void insertTestQuestion(TestQuestion q, long selectedCourseCode)
{
Entity ent = new Entity(Global.DB_TABLE_TEST_QUESTIONS);
ent.setValue("id", q.getId());
ent.setValue("ansType", q.getAnswerType());
ent.setValue("stem", q.getStem());
ent.setValue("shuffle", Global.parseBoolString(q.getShuffle()));
ent.save();
ent = new Entity(Global.DB_TABLE_TEST_QUESTIONS_COURSE);
ent.setValue("qstCod", q.getId());
ent.setValue("crsCod", selectedCourseCode);
ent.save();
}
/**
* Inserts a test answer in database
* @param a Test answer to be inserted
* @param qstCod Test question code to be referenced
*/
public void insertTestAnswer(TestAnswer a, int qstCod)
{
Entity ent = new Entity(Global.DB_TABLE_TEST_ANSWERS);
long id;
ent.setValue("ansInd", a.getAnsInd());
ent.setValue("answer", a.getAnswer());
ent.setValue("correct", a.getCorrect());
ent.save();
id = ent.getId();
ent = new Entity(Global.DB_TABLE_TEST_QUESTION_ANSWERS);
ent.setValue("qstCod", qstCod);
ent.setValue("ansCod", id);
ent.save();
}
/**
* Inserts a test tag in database
* @param t Test tag to be inserted
*/
public void insertTestTag(TestTag t)
{
List<Entity> rows = db.getEntityList(Global.DB_TABLE_TEST_TAGS, "id = " + t.getId());
if(rows.isEmpty()) {
Entity ent = new Entity(Global.DB_TABLE_TEST_TAGS);
ent.setValue("id", t.getId());
ent.setValue("tagTxt", t.getTagTxt());
ent.save();
for(Integer i : t.getQstCodList()) {
ent = new Entity(Global.DB_TABLE_TEST_QUESTION_TAGS);
ent.setValue("qstCod", i);
ent.setValue("tagCod", t.getId());
ent.setValue("tagInd", t.getTagInd());
ent.save();
}
} else {
throw new SQLException();
}
}
/**
* Inserts a test config in database
* @param t Test config to be inserted
*/
public void insertTestConfig(Test t)
{
Entity ent = new Entity(Global.DB_TABLE_TEST_CONFIG);
ent.setValue("id", t.getId());
ent.setValue("min", t.getMin());
ent.setValue("def", t.getDef());
ent.setValue("max", t.getMax());
ent.setValue("feedback", t.getFeedback());
ent.setValue("editTime", t.getEditTime());
ent.save();
}
/**
* Inserts a relation in database
* @param p Relation to be inserted
*/
public void insertPairTable(PairTable<?, ?> p)
{
String table = p.getTable();
Pair<String, String> params = selectParamsPairTable(table);
Entity ent = new Entity(table);
ent.setValue(params.getFirst(), p.getFirst());
ent.setValue(params.getSecond(), p.getSecond());
ent.save();
}
/**
* Inserts a new row or updates an existing one in the table named @a tableName with the data that contains @a currentModel
* @param tableName string with the table name
* @param currentModel model with the new data
* @param ents vector of entities. In case this param is given, the entities given will be modified
*
* */
public boolean insertEntity(String tableName, Model currentModel,Entity...ents){
boolean returnValue = true;
Entity ent;
if(ents.length>= 1){
ent = ents[0];
}else{
ent = new Entity(tableName);
}
if(tableName.compareTo(Global.DB_TABLE_GROUPS) == 0){
Group g = (Group) currentModel;
ent.setValue("id", g.getId());
ent.setValue("groupName", g.getGroupName());
ent.setValue("maxStudents", g.getMaxStudents());
ent.setValue("students", g.getCurrentStudents());
ent.setValue("open", g.getOpen());
ent.setValue("fileZones", g.getDocumentsArea());
ent.setValue("member", g.getMember());
ent.save();
}
if(tableName.compareTo(Global.DB_TABLE_GROUP_TYPES) == 0){
GroupType gt = (GroupType) currentModel;
ent.setValue("id", gt.getId());
ent.setValue("groupTypeName", gt.getGroupTypeName());
ent.setValue("courseCode", gt.getCourseCode());
ent.setValue("mandatory", gt.getMandatory());
ent.setValue("multiple", gt.getMultiple());
ent.setValue("openTime", gt.getOpenTime());
ent.save();
}
return returnValue;
}
/**
* Inserts a relation in database
* @param p Relation to be inserted
*/
/* public void insertPairTable(String table)
{
Pair<Class, Class> pairClass = selectParamsClassPairTable(table);
class T1 = pairClass.getFirst();
Pair<String,String> pairParams = selectParamsPairTable(table);
PairTable<pairClass.getFirst(), pairClass.getSecond()>
String table = p.getTable();
Pair<String, String> params = selectParamsPairTable(table);
Entity ent = new Entity(table);
ent.setValue(params.getFirst(), p.getFirst());
ent.setValue(params.getSecond(), p.getSecond());
ent.save();
}
*/
/**
* Inserts a user in database or updates it if already exists
* @param u User to be inserted
*/
public void insertUser(User u) {
Entity ent;
List<Entity> rows = db.getEntityList(Global.DB_TABLE_USERS, "userCode = " + u.getId());
if(rows.isEmpty()) {
ent = new Entity(Global.DB_TABLE_USERS);
} else {
// If user exists and has photo, delete the old photo file
if (u.getPhotoFileName() != null) {
File externalPath = Environment.getExternalStorageDirectory();
String packageName = db.getContext().getPackageName();
File file = new File(externalPath.getAbsolutePath() + "/Android/data/" + packageName+ "/", u.getPhotoFileName());
//File file = new File(db.getContext().getExternalFilesDir(null), u.getPhotoFileName());
file.delete();
}
ent = rows.get(0);
}
ent.setValue("userCode", u.getId());
ent.setValue("userID", u.getUserID());
ent.setValue("userNickname", u.getUserNickname());
ent.setValue("userSurname1", u.getUserSurname1());
ent.setValue("userSurname2", u.getUserSurname2());
ent.setValue("userFirstname", u.getUserFirstname());
ent.setValue("photoPath", u.getUserPhoto());
ent.setValue("userRole", u.getUserRole());
ent.save();
}
/**
* Inserts a group in database
* @param g Group to be inserted
* @param courseCode Course code to be referenced
*/
public boolean insertGroup(Group g, long courseCode) {
List<Entity> rows = db.getEntityList(Global.DB_TABLE_GROUPS, "id = " + g.getId());
boolean returnValue = true;
if(rows.isEmpty()) {
insertEntity(Global.DB_TABLE_GROUPS,g);
} else { //already exits a group with the given code. just update
insertEntity(Global.DB_TABLE_GROUPS,g,rows.get(0));
}
//update all the relationship
long groupCode = g.getId();
rows = db.getEntityList(Global.DB_TABLE_GROUPS_COURSES,"grpCod =" + groupCode);
Course course = (Course) getRow(Global.DB_TABLE_COURSES,"id",String.valueOf(courseCode));
//course code is a foreign key. Therefore, to avoid a database error,
//it should not insert/modify rows in the relationship table if the course does not exists
if(course != null){
if(rows.isEmpty()){
PairTable<Long,Long> pair = new PairTable(Global.DB_TABLE_GROUPS_COURSES,g.getId(),courseCode);
insertPairTable(pair);
}else{
rows.get(0).setValue("crsCod", courseCode);
rows.get(0).save();
}
}else returnValue = false;
long groupTypeCode = g.getGroupTypeCode();
//WHILE THE WEB SERVICE TO GET GROUP TYPES STILL UNAVAILABLE, this condition is not evaluated
//GroupType groupType = (GroupType) getRow(Global.DB_TABLE_GROUP_TYPES,"id",String.valueOf(groupTypeCode));
//group type code is a foreign key. Therefore, to avoid a database error,
//it should not insert/modify rows in the relationship table if the group type does not exists
//if(groupType != null){
rows = db.getEntityList(Global.DB_TABLE_GROUPS_GROUPTYPES,"grpCod="+groupCode);
if(rows.isEmpty()){
Pair<String,String> params = selectParamsPairTable(Global.DB_TABLE_GROUPS_GROUPTYPES);
insertPairTable(new PairTable<Long,Long>(Global.DB_TABLE_GROUPS_GROUPTYPES,groupTypeCode,groupCode));
}else{
PairTable<Integer,Integer> prev = new PairTable(Global.DB_TABLE_GROUPS_GROUPTYPES,rows.get(0).getValue("grpTypCod"),rows.get(0).getValue("grpCod"));
PairTable<Integer,Integer> current = new PairTable(Global.DB_TABLE_GROUPS_GROUPTYPES,groupTypeCode,groupCode);
updatePairTable(prev,current);
}
/*}else returnValue = false;*/
return returnValue;
}
/**
* Insert a new group type in the database or updated if the group type exits already in the data base
* @param gt Group Type to be inserted
* */
public boolean insertGroupType(GroupType gt){
boolean returnValue = true;
GroupType row = (GroupType)getRow(Global.DB_TABLE_GROUP_TYPES,"id",String.valueOf(gt.getId()));
if(row == null){
insertEntity(Global.DB_TABLE_GROUP_TYPES,gt);
}else{
returnValue = false;
}
return returnValue;
}
public boolean insertCollection(String table,List<Model> currentModels, long...courseCode){
boolean result = true;
List<Model> modelsDB = getAllRows(table);
List<Model> newModels = new ArrayList<Model>();
List<Model> obsoleteModel = new ArrayList<Model>();
List<Model> modifiedModel = new ArrayList<Model>();
newModels.addAll(currentModels);
newModels.removeAll(modelsDB);
obsoleteModel.addAll(modelsDB);
obsoleteModel.removeAll(currentModels);
modifiedModel.addAll(currentModels);
modifiedModel.removeAll(newModels);
modifiedModel.removeAll(obsoleteModel);
if(table.compareTo(Global.DB_TABLE_GROUP_TYPES) == 0){
for(int i = 0; i < obsoleteModel.size(); ++i){
long code = obsoleteModel.get(i).getId();
removeAllRow(table,"id", code);
removeAllRow(Global.DB_TABLE_GROUPS_GROUPTYPES,"grpTypCod", code);
}
for(int i = 0; i < newModels.size(); ++i){
Model model = newModels.get(i);
insertEntity(table,model);
}
List<Entity> rows;
for(int i = 0; i < modifiedModel.size(); ++i){
Model m = modifiedModel.get(i);
rows = db.getEntityList(table, "id="+ m.getId());
insertEntity(table,m,rows.get(0));
}
}
if(table.compareTo(Global.DB_TABLE_GROUPS) == 0){
for(int i = 0; i < obsoleteModel.size(); ++i){
long code = obsoleteModel.get(i).getId();
removeAllRow(table,"id", code);
removeAllRow(Global.DB_TABLE_GROUPS_GROUPTYPES,"grpCod", code);
removeAllRow(Global.DB_TABLE_GROUPS_COURSES,"grpCod",code);
}
for(int i = 0; i < newModels.size(); ++i){
Model model = newModels.get(i);
insertGroup((Group) model, courseCode[0]);
}
for(int i = 0; i < modifiedModel.size(); ++i){
Model model = modifiedModel.get(i);
insertGroup((Group) model, courseCode[0]);
}
}
return result;
}
/**
* Inserts the rollcall data of a student to a practice session in database
* @param l User code of student
* @param sessCode Practice session code
*/
public void insertRollcallData(long l, long sessCode) {
List<Entity> rows = db.getEntityList(Global.DB_TABLE_ROLLCALL, "sessCod = " + sessCode + " AND usrCod = " + l);
if (rows.isEmpty()) {
Entity ent = new Entity(Global.DB_TABLE_ROLLCALL);
ent.setValue("sessCod", sessCode);
ent.setValue("usrCod", l);
ent.save();
}
}
/**
* Inserts a practice session in database
* @param courseCode Course code to be referenced
* @param groupCode Group code to be referenced
* @param startDate Start date-time of session
* @param endDate End date-time of session
* @param site Site where session takes place
* @param description Optional description of practice session
* @return True if practice session does not exist in database and is inserted. False otherwise.
*/
public boolean insertPracticeSession(long courseCode, long groupCode, String startDate, String endDate, String site, String description) {
String where = "crsCod = '" + courseCode + "' AND " +
"grpCod = '" + groupCode + "' AND " +
"startDate = '" + startDate + "' AND " +
"endDate = '" + endDate + "'";
List<Entity> rows = db.getEntityList(Global.DB_TABLE_PRACTICE_SESSIONS, where);
if (rows.isEmpty()) {
Entity ent = new Entity(Global.DB_TABLE_PRACTICE_SESSIONS);
ent.setValue("crsCod", courseCode);
ent.setValue("grpCod", groupCode);
ent.setValue("startDate", startDate);
ent.setValue("endDate", endDate);
if (site != null && site != "")
ent.setValue("site", site);
if (description != null && description != "")
ent.setValue("description", description);
ent.save();
return true;
} else {
return false;
}
}
/**
* Inserts a new record in database indicating that the user belongs
* to the course and group specified, or updates it if already exists
* @param u User to be inserted
* @param courseCode Course code to be referenced
* @param groupCode Group code to be referenced
*/
public void insertUserCourse(User u, long courseCode, long groupCode) {
Entity ent;
String where = "userCode = " + u.getId() + " AND crsCod = " + courseCode;
List<Entity> rows = db.getEntityList(Global.DB_TABLE_USERS_COURSES, where);
if(rows.isEmpty()) {
ent = new Entity(Global.DB_TABLE_USERS_COURSES);
} else {
ent = rows.get(0);
}
ent.setValue("userCode", u.getId());
ent.setValue("crsCod", courseCode);
if (groupCode == 0)
ent.setValue("grpCod", null);
else
ent.setValue("grpCod", groupCode);
ent.save();
}
/**
* Updates a course in database
* @param prev Course to be updated
* @param actual Updated course
*/
public void updateCourse(Course prev, Course actual)
{
List<Entity> rows = db.getEntityList(Global.DB_TABLE_COURSES, "id = " + prev.getId());
Entity ent = rows.get(0);
ent.setValue("id", actual.getId());
ent.setValue("userRole", actual.getUserRole());
ent.setValue("shortName", actual.getShortName());
ent.setValue("fullName", actual.getFullName());
ent.save();
}
/**
* Updates a course in database
* @param id Course code of course to be updated
* @param actual Updated course
*/
public void updateCourse(long id, Course actual)
{
List<Entity> rows = db.getEntityList(Global.DB_TABLE_COURSES, "id = " + id);
if(!rows.isEmpty()){
Entity ent = rows.get(0);
ent.setValue("id", actual.getId());
ent.setValue("userRole", actual.getUserRole());
ent.setValue("shortName", actual.getShortName());
ent.setValue("fullName", actual.getFullName());
ent.save();
}
}
/**
* Updates a notification in database
* @param prev Notification to be updated
* @param actual Updated notification
*/
public void updateNotification(SWADNotification prev, SWADNotification actual)
{
List<Entity> rows = db.getEntityList(Global.DB_TABLE_NOTIFICATIONS, "id = " + prev.getId());
Entity ent = rows.get(0);
String eventTime = String.valueOf(actual.getEventTime());
String status = String.valueOf(actual.getStatus());
ent.setValue("id", actual.getId());
ent.setValue("eventType", actual.getEventType());
ent.setValue("eventTime", eventTime);
ent.setValue("userSurname1", actual.getUserSurname1());
ent.setValue("userSurname2", actual.getUserSurname2());
ent.setValue("userFirstName", actual.getUserFirstName());
ent.setValue("location", actual.getLocation());
ent.setValue("summary", actual.getSummary());
ent.setValue("status", status);
ent.setValue("content", actual.getContent());
ent.save();
}
/**
* Updates a test question in database
* @param prev Test question to be updated
* @param actual Updated test question
* @param selectedCourseCode Course code to be referenced
*/
public void updateTestQuestion(TestQuestion prev, TestQuestion actual, long selectedCourseCode)
{
List<Entity> rows = db.getEntityList(Global.DB_TABLE_TEST_QUESTIONS, "id = " + prev.getId());
Entity ent = rows.get(0);
ent.setValue("id", actual.getId());
ent.setValue("ansType", actual.getAnswerType());
ent.setValue("stem", actual.getStem());
ent.setValue("shuffle", Global.parseBoolString(actual.getShuffle()));
ent.save();
rows = db.getEntityList(Global.DB_TABLE_TEST_QUESTIONS_COURSE, "qstCod = " + actual.getId());
Iterator<Entity> iter = rows.iterator();
while (iter.hasNext()) {
ent = iter.next();
ent.setValue("crsCod", selectedCourseCode);
ent.save();
}
}
/**
* Updates a test answer in database
* @param prev Test answer to be updated
* @param actual Updated test answer
* @param qstCod Test question code to be referenced
*/
public void updateTestAnswer(TestAnswer prev, TestAnswer actual, int qstCod)
{
List<Entity> rows = db.getEntityList(Global.DB_TABLE_TEST_ANSWERS, "_id = " + prev.getId());
Entity ent = rows.get(0);
ent.setValue("ansInd", actual.getAnsInd());
ent.setValue("answer", actual.getAnswer());
ent.setValue("correct", actual.getCorrect());
ent.save();
rows = db.getEntityList(Global.DB_TABLE_TEST_QUESTION_ANSWERS, "ansCod = " + actual.getId());
Iterator<Entity> iter = rows.iterator();
while (iter.hasNext()) {
ent = iter.next();
ent.setValue("qstCod", qstCod);
ent.save();
}
}
/**
* Updates a test tag in database
* @param prev Test tag to be updated
* @param actual Updated test tag
*/
public void updateTestTag(TestTag prev, TestTag actual)
{
List<Entity> rows = db.getEntityList(Global.DB_TABLE_TEST_TAGS, "id = " + prev.getId());
Entity ent = rows.get(0);
List<Integer> qstCodList = actual.getQstCodList();
SQLiteStatement st = db.getDB().compileStatement("INSERT OR IGNORE INTO " +
Global.DB_TABLE_TEST_QUESTION_TAGS + " VALUES (NULL, ?, ?, ?);");
ent.setValue("id", actual.getId());
ent.setValue("tagTxt", actual.getTagTxt());
ent.save();
for(Integer i : qstCodList) {
st.bindLong(1, i);
st.bindLong(2, actual.getId());
st.bindLong(3, actual.getTagInd());
st.executeInsert();
}
}
/**
* Updates a test config in database
* @param prev Test to be updated
* @param actual Updated test
*/
public void updateTestConfig(Test prev, Test actual)
{
List<Entity> rows = db.getEntityList(Global.DB_TABLE_TEST_CONFIG, "id = " + prev.getId());
Entity ent = rows.get(0);
ent.setValue("id", actual.getId());
ent.setValue("min", actual.getMin());
ent.setValue("def", actual.getDef());
ent.setValue("max", actual.getMax());
ent.setValue("feedback", actual.getFeedback());
ent.setValue("editTime", actual.getEditTime());
ent.save();
}
/**
* Updates a relation in database
* @param prev Relation to be updated
* @param actual Updated relation
*/
public void updatePairTable(PairTable<?, ?> prev, PairTable<?, ?> actual)
{
String table = prev.getTable();
String where;
//Integer first = (Integer) prev.getFirst();
//Integer second = (Integer) prev.getSecond();
Pair<String, String> params = selectParamsPairTable(table);
where = params.getFirst() + " = " + prev.getFirst() + " AND " + params.getSecond() + " = " + prev.getSecond();
List<Entity> rows = db.getEntityList(table, where);
if(!rows.isEmpty()){
Entity ent = rows.get(0);
ent.setValue(params.getFirst(), actual.getFirst());
ent.setValue(params.getSecond(), actual.getSecond());
ent.save();
}
}
/**
* Updates a user in database
* @param prev User to be updated
* @param actual Updated user
*/
public void updateUser(User prev, User actual) {
List<Entity> rows = db.getEntityList(Global.DB_TABLE_USERS, "id = " + prev.getId());
Entity ent = rows.get(0);
ent.setValue("userCode", actual.getId());
ent.setValue("userID", actual.getUserID());
ent.setValue("userNickname", actual.getUserNickname());
ent.setValue("userSurname1", actual.getUserSurname1());
ent.setValue("userSurname2", actual.getUserSurname2());
ent.setValue("userFirstname", actual.getUserFirstname());
ent.setValue("userPhoto", actual.getUserPhoto());
ent.setValue("userRole", actual.getUserRole());
ent.save();
}
/**
* Updates a Group and the relationship between Groups and Courses
* @param groupCode code of the group to be updated
* @param courseCode current code of the course related to the group
* @param currentGroup updated group
* */
public boolean updateGroup(long groupCode, long courseCode, Group currentGroup, long ... groupTypeCode){
List<Entity> rows = db.getEntityList(Global.DB_TABLE_GROUPS, "id =" + groupCode);
if(!rows.isEmpty()){
Entity ent = rows.get(0);
boolean returnValue = true;
insertEntity(Global.DB_TABLE_GROUPS,currentGroup,ent);
rows = db.getEntityList(Global.DB_TABLE_GROUPS_COURSES,"grpCod =" + groupCode);
Course course = (Course) getRow(Global.DB_TABLE_COURSES,"id",String.valueOf(courseCode));
//course code is a foreign key. Therefore, to avoid a database error,
//it should not insert/modify rows in the relationship table if the course does not exists
if(course != null){
if(rows.isEmpty()){
ent = new Entity(Global.DB_TABLE_GROUPS_COURSES);
ent.setValue("grpCod", groupCode);
ent.setValue("crsCod", courseCode);
ent.save();
}else{
rows.get(0).setValue("crsCod", courseCode);
rows.get(0).save();
}
}else returnValue = false;
if(groupTypeCode.length > 0){
GroupType groupType = (GroupType) getRow(Global.DB_TABLE_GROUP_TYPES,"id",String.valueOf(groupTypeCode[0]));
//group type code is a foreign key. Therefore, to avoid a database error,
//it should not insert/modify rows in the relationship table if the group type does not exists
if(groupType != null){
rows = db.getEntityList(Global.DB_TABLE_GROUPS_GROUPTYPES,"grpCod="+groupCode);
if(!rows.isEmpty()){
Pair<String,String> params = selectParamsPairTable(Global.DB_TABLE_GROUP_TYPES);
insertPairTable(new PairTable<Long,Long>(Global.DB_TABLE_GROUPS_GROUPTYPES,groupTypeCode[0],groupCode));
}else{
PairTable<Integer,Integer> prev = new PairTable(Global.DB_TABLE_GROUPS_GROUPTYPES,rows.get(0).getValue("grpTypCod"),rows.get(0).getValue("grpCod"));
PairTable<Integer,Integer> current = new PairTable(Global.DB_TABLE_GROUPS_GROUPTYPES,groupTypeCode[0],groupCode);
updatePairTable(prev,current);
}
}else returnValue = false;
}
return returnValue;
}else
return false;
}
private <T> boolean updateRelationship(Pair<String,String> tables, Pair<String,String> idsTables, String relationTable, Pair<String,T> remainField, Pair<String,T> changedField){
return true;
}
/**
* Updates a group in database
* @param prev Group to be updated
* @param actual Updated group
*/
public void updateGroup(Group prev, Group currentGroup) {
List<Entity> rows = db.getEntityList(Global.DB_TABLE_GROUPS, "id = " + prev.getId());
if(!rows.isEmpty()){
insertEntity(Global.DB_TABLE_GROUPS,currentGroup,rows.get(0));
}
if(prev.getId() != currentGroup.getId()){
//TODO in this case, the relationships with group types and courses should be updated
}
}
/**
* Updates an existing group type
* */
private boolean updateGroupType(GroupType prv, GroupType current){
List<Entity> rows = db.getEntityList(Global.DB_TABLE_GROUP_TYPES, "id="+prv.getId());
boolean returnValue = true;
if(!rows.isEmpty()){
Entity ent = rows.get(0); //the group type with a given group type code is unique
insertEntity(Global.DB_TABLE_GROUP_TYPES,current,ent);
}else returnValue = false;
return returnValue;
}
/**
* Removes a User from database and user photo from external storage
* @param u User to be removed
*/
public void removeUser(User u) {
removeRow(Global.DB_TABLE_USERS, u.getId());
File externalPath = Environment.getExternalStorageDirectory();
String packageName = db.getContext().getPackageName();
File file = new File(externalPath.getAbsolutePath() + "/Android/data/" + packageName+ "/", u.getPhotoFileName());
//File file = new File(db.getContext().getExternalFilesDir(null), u.getPhotoFileName());
file.delete();
}
/**
* Removes a Group from database
* @param g Group to be removed
*/
public void removeGroup(Group g) {
removeRow(Global.DB_TABLE_GROUPS, g.getId());
//Remove also relationships with courses and group types
removeAllRow(Global.DB_TABLE_GROUPS_GROUPTYPES,"grpCod",g.getId());
removeAllRow(Global.DB_TABLE_GROUPS_COURSES,"grpCod",g.getId());
}
/**
* Removes a row from a database table
* @param id Identifier of row to be removed
*/
public void removeRow(String table, long id)
{
List<Entity> rows = db.getEntityList(table, "id = " + id);
Entity ent = rows.get(0);
ent.delete();
}
/**
* Removes all rows from a database table where fieldName has the given value as value
* @param fieldName Name field to search
* @param value Value field of row to be removed
*/
public void removeAllRow(String table, String fieldName ,long value)
{
List<Entity> rows = db.getEntityList(table, fieldName + "= " + value);
for(int i = 0; i < rows.size(); ++i){
Entity ent = rows.get(i);
ent.delete();
}
}
/**
* Removes a PairTable from database
* @param p PairTable to be removed
*/
public void removePairTable(@SuppressWarnings("rawtypes") PairTable p)
{
String table = p.getTable();
Integer first = (Integer) p.getFirst();
Integer second = (Integer) p.getSecond();
String where;
List<Entity> rows;
Entity ent;
Pair<String, String> params = selectParamsPairTable(table);
where = params.getFirst() + " = " + first + " AND " + params.getSecond() + " = " + second;
rows = db.getEntityList(table, where);
ent = rows.get(0);
ent.delete();
}
/**
* Gets a field of last notification
* @param field A field of last notification
* @return The field of last notification
*/
public String getFieldOfLastNotification(String field)
{
String where = null;
String orderby = "eventTime DESC";
List<Entity> rows = db.getEntityList(Global.DB_TABLE_NOTIFICATIONS, where, orderby);
String f = "0";
if(rows.size() > 0)
{
Entity ent = rows.get(0);
f = (String) ent.getValue(field);
}
return f;
}
/**
* Gets last time the test was updated
* @param selectedCourseCode Test's course
* @return Last time the test was updated
*/
public String getTimeOfLastTestUpdate(long selectedCourseCode)
{
String where = "id=" + selectedCourseCode;
String orderby = null;
List<Entity> rows = db.getEntityList(Global.DB_TABLE_TEST_CONFIG, where, orderby);
String f = "0";
if(rows.size() > 0)
{
Entity ent = rows.get(0);
f = (String) ent.getValue("editTime");
}
if(f == null) {
f = "0";
}
return f;
}
/**
* Gets the tags of specified course ordered by tagInd field
* @param selectedCourseCode Test's course
* @return A list of the tags of specified course ordered by tagInd field
*/
public List<TestTag> getOrderedCourseTags(long selectedCourseCode)
{
String[] columns = {"T.id", "T.tagTxt", "Q.qstCod", "Q.tagInd"};
String tables = Global.DB_TABLE_TEST_TAGS + " AS T, " + Global.DB_TABLE_TEST_QUESTION_TAGS
+ " AS Q, " + Global.DB_TABLE_TEST_QUESTIONS_COURSE + " AS C";
String where = "T.id=Q.tagCod AND Q.qstCod=C.qstCod AND C.crsCod=" + selectedCourseCode;
String orderBy = "Q.tagInd ASC";
String groupBy = "T.id";
Cursor dbCursor = db.getDB().query(tables, columns, where, null, groupBy, null, orderBy);
List<TestTag> result = new ArrayList<TestTag>();
List<Integer> qstCodList;
int idOld = -1;
TestTag t = null;
while(dbCursor.moveToNext()) {
int id = dbCursor.getInt(0);
if(id != idOld) {
qstCodList = new ArrayList<Integer>();
String tagTxt = dbCursor.getString(1);
qstCodList.add(dbCursor.getInt(2));
int tagInd = dbCursor.getInt(3);
t = new TestTag(id, qstCodList, tagTxt, tagInd);
result.add(t);
idOld = id;
} else {
t.addQstCod(dbCursor.getInt(2));
}
}
return result;
}
/**
* Gets the questions of specified course and tags
* @param selectedCourseCode Test's course
* @param tagsList Tag's list of the questions to be extracted
* @return A list of the questions of specified course and tags
*/
public List<TestQuestion> getRandomCourseQuestionsByTagAndAnswerType(long selectedCourseCode, List<TestTag> tagsList,
List<String> answerTypesList, int maxQuestions)
{
String select = "SELECT DISTINCT Q.id, Q.ansType, Q.shuffle, Q.stem";
String tables = " FROM " + Global.DB_TABLE_TEST_QUESTIONS + " AS Q, "
+ Global.DB_TABLE_TEST_QUESTIONS_COURSE + " AS C, "
+ Global.DB_TABLE_TEST_QUESTION_TAGS + " AS T";
String where = " WHERE Q.id=C.qstCod AND Q.id=T.qstCod AND C.crsCod=" + selectedCourseCode;
String orderby = " ORDER BY RANDOM()";
String limit = " LIMIT " + maxQuestions;
Cursor dbCursorQuestions, dbCursorAnswers;
List<TestQuestion> result = new ArrayList<TestQuestion>();
List<TestAnswer> answers = new ArrayList<TestAnswer>();
int tagsListSize = tagsList.size();
int answerTypesListSize = answerTypesList.size();
if(!tagsList.get(0).getTagTxt().equals("all")) {
where += " AND (";
for(int i=0; i<tagsListSize; i++) {
where += "T.tagCod=" + tagsList.get(i).getId();
if(i < tagsListSize-1) {
where += " OR ";
}
}
where += ")";
if(!answerTypesList.get(0).equals("all")) {
where += " AND ";
}
}
if(!answerTypesList.get(0).equals("all")) {
if(tagsList.get(0).getTagTxt().equals("all")) {
where += " AND ";
}
where += "(";
for(int i=0; i<answerTypesListSize; i++) {
where += "Q.ansType='" + answerTypesList.get(i) + "'";
if(i < answerTypesListSize-1) {
where += " OR ";
}
}
where += ")";
}
dbCursorQuestions = db.getDB().rawQuery(select + tables + where + orderby + limit, null);
select = "SELECT DISTINCT A._id, A.ansInd, A.answer, A.correct";
tables = " FROM " + Global.DB_TABLE_TEST_ANSWERS + " AS A, "
+ Global.DB_TABLE_TEST_QUESTION_ANSWERS + " AS Q";
orderby = " ORDER BY A.ansInd";
while(dbCursorQuestions.moveToNext()) {
int qstCod = dbCursorQuestions.getInt(0);
String ansType = dbCursorQuestions.getString(1);
boolean shuffle = Global.parseStringBool(dbCursorQuestions.getString(2));
String stem = dbCursorQuestions.getString(3);
TestQuestion q = new TestQuestion(qstCod, selectedCourseCode, stem, ansType, shuffle);
where = " WHERE Q.qstCod=" + qstCod + " AND Q.ansCod=A._id";
dbCursorAnswers = db.getDB().rawQuery(select + tables + where + orderby, null);
answers = new ArrayList<TestAnswer>();
while(dbCursorAnswers.moveToNext()) {
long ansCod = dbCursorAnswers.getLong(0);
int ansInd = dbCursorAnswers.getInt(1);
String answer = dbCursorAnswers.getString(2);
boolean correct = dbCursorAnswers.getString(3).equals("true") ? true: false;
answers.add(new TestAnswer(ansCod, ansInd, qstCod, correct, answer));
}
q.setAnswers(answers);
result.add(q);
}
return result;
}
/**
* Clear old notifications
* @param size Max table size
*/
public void clearOldNotifications(int size)
{
String where = null;
String orderby = "eventTime ASC";
List<Entity> rows = db.getEntityList(Global.DB_TABLE_NOTIFICATIONS, where, orderby);
int numRows = rows.size();
int numDeletions = numRows - size;
if(numRows > size)
{
for(int i=0; i<numDeletions; i++)
rows.get(i).delete();
}
}
/**
* Empty table from database
* @param table Table to be emptied
*/
public void emptyTable(String table)
{
db.emptyTable(table);
}
/**
* Delete table from database
* @param table Table to be deleted
*/
public void deleteTable(String table)
{
db.deleteTable(table);
}
/**
* Delete all tables from database
*/
public void clearDB()
{
db.deleteTables();
}
/**
* Clean data of all tables from database. Removes users photos from external storage
*/
public void cleanTables()
{
emptyTable(Global.DB_TABLE_NOTIFICATIONS);
emptyTable(Global.DB_TABLE_COURSES);
emptyTable(Global.DB_TABLE_TEST_QUESTION_ANSWERS);
emptyTable(Global.DB_TABLE_TEST_QUESTION_TAGS);
emptyTable(Global.DB_TABLE_TEST_QUESTIONS_COURSE);
emptyTable(Global.DB_TABLE_TEST_ANSWERS);
emptyTable(Global.DB_TABLE_TEST_CONFIG);
emptyTable(Global.DB_TABLE_TEST_QUESTIONS);
emptyTable(Global.DB_TABLE_TEST_TAGS);
emptyTable(Global.DB_TABLE_USERS_COURSES);
emptyTable(Global.DB_TABLE_USERS);
emptyTable(Global.DB_TABLE_GROUPS_COURSES);
emptyTable(Global.DB_TABLE_GROUPS);
emptyTable(Global.DB_TABLE_PRACTICE_SESSIONS);
emptyTable(Global.DB_TABLE_ROLLCALL);
emptyTable(Global.DB_TABLE_GROUP_TYPES);
emptyTable(Global.DB_TABLE_GROUPS_GROUPTYPES);
compactDB();
// Removes users photos from external storage (Android 2.2 or higher only)
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO) {
File externalPath = Environment.getExternalStorageDirectory();
String packageName = db.getContext().getPackageName();
File dir = new File(externalPath.getAbsolutePath() + "/Android/data/" + packageName+ "/");
//File dir = db.getContext().getExternalFilesDir(null);
if(dir != null){
String [] children = dir.list();
if(children != null)
for (int i=0; i < children.length; i++){
File childrenFile = new File(dir,children[i]);
if(childrenFile.exists()) childrenFile.delete();
}
}
}
}
/**
* Begin a database transaction
*/
public void beginTransaction() {
db.getDB().execSQL("BEGIN;");
}
/**
* End a database transaction
*/
public void endTransaction() {
db.getDB().execSQL("END;");
}
/**
* Compact the database
*/
public void compactDB() {
db.getDB().execSQL("VACUUM;");
}
/**
* Initializes the database structure for the first use
*/
public void initializeDB() {
db.getDB().execSQL("CREATE UNIQUE INDEX " + Global.DB_TABLE_TEST_QUESTION_TAGS + "_unique on "
+ Global.DB_TABLE_TEST_QUESTION_TAGS + "(qstCod, tagCod);");
}
/**
* Upgrades the database structure
* @throws IOException
* @throws XmlPullParserException
*/
public void upgradeDB(Context context) throws XmlPullParserException, IOException {
int dbVersion = db.getDB().getVersion();
boolean found = false;
int i = 0;
//cleanTables();
//initializeDB();
/*
* Modify database keeping data:
* 1. Create temporary table __DB_TABLE_GROUPS (with the new model)
* 2. insert in the temporary table all the data (in the new model) from the old table
* 3. drop table DB_TABLE_GROUPS
* 4. create DB_TABLE_GROUPS with the new model.
* 5. insert in DB_TABLE_GROUPS all the data from __DB_TABLE_GROUPS
* 6. insert in DB_TABLE_GROUPS_GROUPTYPES the relationships between the deleted groups and group types
* 7. drop __DB_TABLE_GROUPS
* Just to modify database without to keep data just 7,6.
*
* */
/* From version 11 to 12
* changes on courses table:
* - old field name is erased
* The rest of the changes are only new fields and they are added automatic by Dataframework. */
if(dbVersion < 12) {
Cursor dbCursor = db.getDB().query(Global.DB_TABLE_COURSES, null, null, null, null, null, null);
String[] columnNames = dbCursor.getColumnNames();
while(i < columnNames.length && !found){
if(columnNames[i].compareTo("name") == 0) found = true;
++i;
}
if(found){
//without to keep data
db.getDB().execSQL( "DROP TABLE " + Global.DB_TABLE_COURSES + ";");//+
- db.getDB().execSQL("CREATE TABLE "+ Global.DB_TABLE_COURSES
+ db.getDB().execSQL("CREATE TABLE "+ Global.DB_TABLE_COURSES
+ " (_id integer primary key autoincrement, id long, userRole integer,shortName text, fullName text);");
//Keeping data (It will have columns without data):
/*
* db.getDB().execSQL("CREATE TEMPORARY TABLE __"+ Global.DB_TABLE_COURSES
+ " (_id integer primary key autoincrement, id long, userRole integer,"
+ " shortName text, fullName text); ");
db.getDB().execSQL(
"INSERT INTO __" + Global.DB_TABLE_COURSES + " SELECT _id, id, userRole, name, name "
+ " FROM "+ Global.DB_TABLE_COURSES + ";");
db.getDB().execSQL( "DROP TABLE " + Global.DB_TABLE_COURSES + ";");
db.getDB().execSQL("CREATE TABLE "+ Global.DB_TABLE_COURSES
+ " (_id integer primary key autoincrement, id long, userRole integer,"
+ " shortName text, fullName text); ");
db.getDB().execSQL(
"INSERT INTO " + Global.DB_TABLE_COURSES + " SELECT _id, id, userRole, shortName, fullName "
+ " FROM __"+ Global.DB_TABLE_COURSES + ";");*/
}
dbCursor = db.getDB().query(Global.DB_TABLE_COURSES, null, null, null, null, null, null);
columnNames = dbCursor.getColumnNames();
- }
+ }
/* version 12 - 13
* changes on groups table:
* - old field groupCode is now id
* - old field groupTypeCode is erased
* - old field groupTypeName is erased
* The rest of the changes are only new fields and they are added automatic by Dataframework.
* */
if(dbVersion < 13) {
Cursor dbCursor = db.getDB().query(Global.DB_TABLE_COURSES, null, null, null, null, null, null);
String[] columnNames = dbCursor.getColumnNames();
dbCursor = db.getDB().query(Global.DB_TABLE_GROUPS, null, null, null, null, null, null);
columnNames = dbCursor.getColumnNames();
while(i < columnNames.length && !found){
if(columnNames[i].compareTo("groupCode") == 0) found = true;
++i;
}
if(found){
//without to keep data
db.getDB().execSQL( "DROP TABLE " + Global.DB_TABLE_GROUPS + ";");
db.getDB().execSQL("CREATE TABLE " + Global.DB_TABLE_GROUPS+ " (_id integer primary key autoincrement, id long, groupName text, maxStudents integer,"
+ " students integer, open integer, fileZones integer, member integer); ");
/*db.getDB().execSQL(
"CREATE TEMPORARY TABLE __"+ Global.DB_TABLE_GROUPS
+ " (_id integer primary key autoincrement, id long, groupName text, maxStudents integer,"
+ " students integer, open integer, fileZones integer, member integer); ");
db.getDB().execSQL(
"INSERT INTO __" + Global.DB_TABLE_GROUPS + " SELECT _id, groupCode, groupName, maxStudents, "
+ "students, open, fileZones, member FROM "+ Global.DB_TABLE_GROUPS + ";");
db.getDB().execSQL( "DROP TABLE " + Global.DB_TABLE_GROUPS + ";");
db.getDB().execSQL("CREATE TABLE " + Global.DB_TABLE_GROUPS+ " (_id integer primary key autoincrement, id long, groupName text, maxStudents integer,"
+ " students integer, open integer, fileZones integer, member integer); ");
db.getDB().execSQL("INSERT INTO " + Global.DB_TABLE_GROUPS + " SELECT _id, id, groupName, maxStudents, "
+ "students, open, fileZones, member FROM __"+ Global.DB_TABLE_GROUPS + ";");
db.getDB().execSQL( "DROP TABLE __" + Global.DB_TABLE_GROUPS + ";");*/
}
dbCursor = db.getDB().query(Global.DB_TABLE_GROUPS, null, null, null, null, null, null);
columnNames = dbCursor.getColumnNames();
}
/*db.getDB().execSQL("CREATE TEMPORARY TABLE __"
+ Global.DB_TABLE_NOTIFICATIONS
+ " (_id INTEGER PRIMARY KEY AUTOINanCREMENT, id INTEGER, eventType TEXT, eventTime TEXT,"
+ " userSurname1 TEXT, userSurname2 TEXT, userFirstname TEXT, location TEXT, summary TEXT,"
+ "status TEXT, content TEXT); "
+ "INSERT INTO __" + Global.DB_TABLE_NOTIFICATIONS + " SELECT _id, id, eventType, eventTime, "
+ "userSurname1, userSurname2, userFirstname, location, summary, status, content FROM "
+ Global.DB_TABLE_NOTIFICATIONS + ";");
deleteTable(Global.DB_TABLE_TEST_QUESTION_ANSWERS);
deleteTable(Global.DB_TABLE_TEST_QUESTION_TAGS);
deleteTable(Global.DB_TABLE_TEST_QUESTIONS_COURSE);
deleteTable(Global.DB_TABLE_COURSES);
deleteTable(Global.DB_TABLE_TEST_ANSWERS);
deleteTable(Global.DB_TABLE_TEST_CONFIG);
deleteTable(Global.DB_TABLE_TEST_QUESTIONS);
deleteTable(Global.DB_TABLE_TEST_TAGS);
deleteTable(Global.DB_TABLE_NOTIFICATIONS);
deleteTable(Global.DB_TABLE_USERS_COURSES);
deleteTable(Global.DB_TABLE_USERS);
deleteTable(Global.DB_TABLE_GROUPS_COURSES);
deleteTable(Global.DB_TABLE_GROUPS);
deleteTable(Global.DB_TABLE_PRACTICE_SESSIONS);
deleteTable(Global.DB_TABLE_ROLLCALL);
deleteTable(Global.DB_TABLE_GROUP_TYPES);
deleteTable(Global.DB_TABLE_GROUPS_GROUPTYPES);
db.createTables();
db.getDB().execSQL("INSERT INTO " + Global.DB_TABLE_NOTIFICATIONS + " SELECT _id, id, eventType, eventTime, "
+ "userSurname1, userSurname2, userFirstname, location, summary, status, content FROM __"
+ Global.DB_TABLE_NOTIFICATIONS + ";"
+ "DROP TABLE __" + Global.DB_TABLE_NOTIFICATIONS + ";");*/
compactDB();
}
}
| false | true | public void upgradeDB(Context context) throws XmlPullParserException, IOException {
int dbVersion = db.getDB().getVersion();
boolean found = false;
int i = 0;
//cleanTables();
//initializeDB();
/*
* Modify database keeping data:
* 1. Create temporary table __DB_TABLE_GROUPS (with the new model)
* 2. insert in the temporary table all the data (in the new model) from the old table
* 3. drop table DB_TABLE_GROUPS
* 4. create DB_TABLE_GROUPS with the new model.
* 5. insert in DB_TABLE_GROUPS all the data from __DB_TABLE_GROUPS
* 6. insert in DB_TABLE_GROUPS_GROUPTYPES the relationships between the deleted groups and group types
* 7. drop __DB_TABLE_GROUPS
* Just to modify database without to keep data just 7,6.
*
* */
/* From version 11 to 12
* changes on courses table:
* - old field name is erased
* The rest of the changes are only new fields and they are added automatic by Dataframework. */
if(dbVersion < 12) {
Cursor dbCursor = db.getDB().query(Global.DB_TABLE_COURSES, null, null, null, null, null, null);
String[] columnNames = dbCursor.getColumnNames();
while(i < columnNames.length && !found){
if(columnNames[i].compareTo("name") == 0) found = true;
++i;
}
if(found){
//without to keep data
db.getDB().execSQL( "DROP TABLE " + Global.DB_TABLE_COURSES + ";");//+
db.getDB().execSQL("CREATE TABLE "+ Global.DB_TABLE_COURSES
+ " (_id integer primary key autoincrement, id long, userRole integer,shortName text, fullName text);");
//Keeping data (It will have columns without data):
/*
* db.getDB().execSQL("CREATE TEMPORARY TABLE __"+ Global.DB_TABLE_COURSES
+ " (_id integer primary key autoincrement, id long, userRole integer,"
+ " shortName text, fullName text); ");
db.getDB().execSQL(
"INSERT INTO __" + Global.DB_TABLE_COURSES + " SELECT _id, id, userRole, name, name "
+ " FROM "+ Global.DB_TABLE_COURSES + ";");
db.getDB().execSQL( "DROP TABLE " + Global.DB_TABLE_COURSES + ";");
db.getDB().execSQL("CREATE TABLE "+ Global.DB_TABLE_COURSES
+ " (_id integer primary key autoincrement, id long, userRole integer,"
+ " shortName text, fullName text); ");
db.getDB().execSQL(
"INSERT INTO " + Global.DB_TABLE_COURSES + " SELECT _id, id, userRole, shortName, fullName "
+ " FROM __"+ Global.DB_TABLE_COURSES + ";");*/
}
dbCursor = db.getDB().query(Global.DB_TABLE_COURSES, null, null, null, null, null, null);
columnNames = dbCursor.getColumnNames();
}
/* version 12 - 13
* changes on groups table:
* - old field groupCode is now id
* - old field groupTypeCode is erased
* - old field groupTypeName is erased
* The rest of the changes are only new fields and they are added automatic by Dataframework.
* */
if(dbVersion < 13) {
Cursor dbCursor = db.getDB().query(Global.DB_TABLE_COURSES, null, null, null, null, null, null);
String[] columnNames = dbCursor.getColumnNames();
dbCursor = db.getDB().query(Global.DB_TABLE_GROUPS, null, null, null, null, null, null);
columnNames = dbCursor.getColumnNames();
while(i < columnNames.length && !found){
if(columnNames[i].compareTo("groupCode") == 0) found = true;
++i;
}
if(found){
//without to keep data
db.getDB().execSQL( "DROP TABLE " + Global.DB_TABLE_GROUPS + ";");
db.getDB().execSQL("CREATE TABLE " + Global.DB_TABLE_GROUPS+ " (_id integer primary key autoincrement, id long, groupName text, maxStudents integer,"
+ " students integer, open integer, fileZones integer, member integer); ");
/*db.getDB().execSQL(
"CREATE TEMPORARY TABLE __"+ Global.DB_TABLE_GROUPS
+ " (_id integer primary key autoincrement, id long, groupName text, maxStudents integer,"
+ " students integer, open integer, fileZones integer, member integer); ");
db.getDB().execSQL(
"INSERT INTO __" + Global.DB_TABLE_GROUPS + " SELECT _id, groupCode, groupName, maxStudents, "
+ "students, open, fileZones, member FROM "+ Global.DB_TABLE_GROUPS + ";");
db.getDB().execSQL( "DROP TABLE " + Global.DB_TABLE_GROUPS + ";");
db.getDB().execSQL("CREATE TABLE " + Global.DB_TABLE_GROUPS+ " (_id integer primary key autoincrement, id long, groupName text, maxStudents integer,"
+ " students integer, open integer, fileZones integer, member integer); ");
db.getDB().execSQL("INSERT INTO " + Global.DB_TABLE_GROUPS + " SELECT _id, id, groupName, maxStudents, "
+ "students, open, fileZones, member FROM __"+ Global.DB_TABLE_GROUPS + ";");
db.getDB().execSQL( "DROP TABLE __" + Global.DB_TABLE_GROUPS + ";");*/
}
dbCursor = db.getDB().query(Global.DB_TABLE_GROUPS, null, null, null, null, null, null);
columnNames = dbCursor.getColumnNames();
}
/*db.getDB().execSQL("CREATE TEMPORARY TABLE __"
+ Global.DB_TABLE_NOTIFICATIONS
+ " (_id INTEGER PRIMARY KEY AUTOINanCREMENT, id INTEGER, eventType TEXT, eventTime TEXT,"
+ " userSurname1 TEXT, userSurname2 TEXT, userFirstname TEXT, location TEXT, summary TEXT,"
+ "status TEXT, content TEXT); "
+ "INSERT INTO __" + Global.DB_TABLE_NOTIFICATIONS + " SELECT _id, id, eventType, eventTime, "
+ "userSurname1, userSurname2, userFirstname, location, summary, status, content FROM "
+ Global.DB_TABLE_NOTIFICATIONS + ";");
deleteTable(Global.DB_TABLE_TEST_QUESTION_ANSWERS);
deleteTable(Global.DB_TABLE_TEST_QUESTION_TAGS);
deleteTable(Global.DB_TABLE_TEST_QUESTIONS_COURSE);
deleteTable(Global.DB_TABLE_COURSES);
deleteTable(Global.DB_TABLE_TEST_ANSWERS);
deleteTable(Global.DB_TABLE_TEST_CONFIG);
deleteTable(Global.DB_TABLE_TEST_QUESTIONS);
deleteTable(Global.DB_TABLE_TEST_TAGS);
deleteTable(Global.DB_TABLE_NOTIFICATIONS);
deleteTable(Global.DB_TABLE_USERS_COURSES);
deleteTable(Global.DB_TABLE_USERS);
deleteTable(Global.DB_TABLE_GROUPS_COURSES);
deleteTable(Global.DB_TABLE_GROUPS);
deleteTable(Global.DB_TABLE_PRACTICE_SESSIONS);
deleteTable(Global.DB_TABLE_ROLLCALL);
deleteTable(Global.DB_TABLE_GROUP_TYPES);
deleteTable(Global.DB_TABLE_GROUPS_GROUPTYPES);
db.createTables();
db.getDB().execSQL("INSERT INTO " + Global.DB_TABLE_NOTIFICATIONS + " SELECT _id, id, eventType, eventTime, "
+ "userSurname1, userSurname2, userFirstname, location, summary, status, content FROM __"
+ Global.DB_TABLE_NOTIFICATIONS + ";"
+ "DROP TABLE __" + Global.DB_TABLE_NOTIFICATIONS + ";");*/
compactDB();
}
| public void upgradeDB(Context context) throws XmlPullParserException, IOException {
int dbVersion = db.getDB().getVersion();
boolean found = false;
int i = 0;
//cleanTables();
//initializeDB();
/*
* Modify database keeping data:
* 1. Create temporary table __DB_TABLE_GROUPS (with the new model)
* 2. insert in the temporary table all the data (in the new model) from the old table
* 3. drop table DB_TABLE_GROUPS
* 4. create DB_TABLE_GROUPS with the new model.
* 5. insert in DB_TABLE_GROUPS all the data from __DB_TABLE_GROUPS
* 6. insert in DB_TABLE_GROUPS_GROUPTYPES the relationships between the deleted groups and group types
* 7. drop __DB_TABLE_GROUPS
* Just to modify database without to keep data just 7,6.
*
* */
/* From version 11 to 12
* changes on courses table:
* - old field name is erased
* The rest of the changes are only new fields and they are added automatic by Dataframework. */
if(dbVersion < 12) {
Cursor dbCursor = db.getDB().query(Global.DB_TABLE_COURSES, null, null, null, null, null, null);
String[] columnNames = dbCursor.getColumnNames();
while(i < columnNames.length && !found){
if(columnNames[i].compareTo("name") == 0) found = true;
++i;
}
if(found){
//without to keep data
db.getDB().execSQL( "DROP TABLE " + Global.DB_TABLE_COURSES + ";");//+
db.getDB().execSQL("CREATE TABLE "+ Global.DB_TABLE_COURSES
+ " (_id integer primary key autoincrement, id long, userRole integer,shortName text, fullName text);");
//Keeping data (It will have columns without data):
/*
* db.getDB().execSQL("CREATE TEMPORARY TABLE __"+ Global.DB_TABLE_COURSES
+ " (_id integer primary key autoincrement, id long, userRole integer,"
+ " shortName text, fullName text); ");
db.getDB().execSQL(
"INSERT INTO __" + Global.DB_TABLE_COURSES + " SELECT _id, id, userRole, name, name "
+ " FROM "+ Global.DB_TABLE_COURSES + ";");
db.getDB().execSQL( "DROP TABLE " + Global.DB_TABLE_COURSES + ";");
db.getDB().execSQL("CREATE TABLE "+ Global.DB_TABLE_COURSES
+ " (_id integer primary key autoincrement, id long, userRole integer,"
+ " shortName text, fullName text); ");
db.getDB().execSQL(
"INSERT INTO " + Global.DB_TABLE_COURSES + " SELECT _id, id, userRole, shortName, fullName "
+ " FROM __"+ Global.DB_TABLE_COURSES + ";");*/
}
dbCursor = db.getDB().query(Global.DB_TABLE_COURSES, null, null, null, null, null, null);
columnNames = dbCursor.getColumnNames();
}
/* version 12 - 13
* changes on groups table:
* - old field groupCode is now id
* - old field groupTypeCode is erased
* - old field groupTypeName is erased
* The rest of the changes are only new fields and they are added automatic by Dataframework.
* */
if(dbVersion < 13) {
Cursor dbCursor = db.getDB().query(Global.DB_TABLE_COURSES, null, null, null, null, null, null);
String[] columnNames = dbCursor.getColumnNames();
dbCursor = db.getDB().query(Global.DB_TABLE_GROUPS, null, null, null, null, null, null);
columnNames = dbCursor.getColumnNames();
while(i < columnNames.length && !found){
if(columnNames[i].compareTo("groupCode") == 0) found = true;
++i;
}
if(found){
//without to keep data
db.getDB().execSQL( "DROP TABLE " + Global.DB_TABLE_GROUPS + ";");
db.getDB().execSQL("CREATE TABLE " + Global.DB_TABLE_GROUPS+ " (_id integer primary key autoincrement, id long, groupName text, maxStudents integer,"
+ " students integer, open integer, fileZones integer, member integer); ");
/*db.getDB().execSQL(
"CREATE TEMPORARY TABLE __"+ Global.DB_TABLE_GROUPS
+ " (_id integer primary key autoincrement, id long, groupName text, maxStudents integer,"
+ " students integer, open integer, fileZones integer, member integer); ");
db.getDB().execSQL(
"INSERT INTO __" + Global.DB_TABLE_GROUPS + " SELECT _id, groupCode, groupName, maxStudents, "
+ "students, open, fileZones, member FROM "+ Global.DB_TABLE_GROUPS + ";");
db.getDB().execSQL( "DROP TABLE " + Global.DB_TABLE_GROUPS + ";");
db.getDB().execSQL("CREATE TABLE " + Global.DB_TABLE_GROUPS+ " (_id integer primary key autoincrement, id long, groupName text, maxStudents integer,"
+ " students integer, open integer, fileZones integer, member integer); ");
db.getDB().execSQL("INSERT INTO " + Global.DB_TABLE_GROUPS + " SELECT _id, id, groupName, maxStudents, "
+ "students, open, fileZones, member FROM __"+ Global.DB_TABLE_GROUPS + ";");
db.getDB().execSQL( "DROP TABLE __" + Global.DB_TABLE_GROUPS + ";");*/
}
dbCursor = db.getDB().query(Global.DB_TABLE_GROUPS, null, null, null, null, null, null);
columnNames = dbCursor.getColumnNames();
}
/*db.getDB().execSQL("CREATE TEMPORARY TABLE __"
+ Global.DB_TABLE_NOTIFICATIONS
+ " (_id INTEGER PRIMARY KEY AUTOINanCREMENT, id INTEGER, eventType TEXT, eventTime TEXT,"
+ " userSurname1 TEXT, userSurname2 TEXT, userFirstname TEXT, location TEXT, summary TEXT,"
+ "status TEXT, content TEXT); "
+ "INSERT INTO __" + Global.DB_TABLE_NOTIFICATIONS + " SELECT _id, id, eventType, eventTime, "
+ "userSurname1, userSurname2, userFirstname, location, summary, status, content FROM "
+ Global.DB_TABLE_NOTIFICATIONS + ";");
deleteTable(Global.DB_TABLE_TEST_QUESTION_ANSWERS);
deleteTable(Global.DB_TABLE_TEST_QUESTION_TAGS);
deleteTable(Global.DB_TABLE_TEST_QUESTIONS_COURSE);
deleteTable(Global.DB_TABLE_COURSES);
deleteTable(Global.DB_TABLE_TEST_ANSWERS);
deleteTable(Global.DB_TABLE_TEST_CONFIG);
deleteTable(Global.DB_TABLE_TEST_QUESTIONS);
deleteTable(Global.DB_TABLE_TEST_TAGS);
deleteTable(Global.DB_TABLE_NOTIFICATIONS);
deleteTable(Global.DB_TABLE_USERS_COURSES);
deleteTable(Global.DB_TABLE_USERS);
deleteTable(Global.DB_TABLE_GROUPS_COURSES);
deleteTable(Global.DB_TABLE_GROUPS);
deleteTable(Global.DB_TABLE_PRACTICE_SESSIONS);
deleteTable(Global.DB_TABLE_ROLLCALL);
deleteTable(Global.DB_TABLE_GROUP_TYPES);
deleteTable(Global.DB_TABLE_GROUPS_GROUPTYPES);
db.createTables();
db.getDB().execSQL("INSERT INTO " + Global.DB_TABLE_NOTIFICATIONS + " SELECT _id, id, eventType, eventTime, "
+ "userSurname1, userSurname2, userFirstname, location, summary, status, content FROM __"
+ Global.DB_TABLE_NOTIFICATIONS + ";"
+ "DROP TABLE __" + Global.DB_TABLE_NOTIFICATIONS + ";");*/
compactDB();
}
|
diff --git a/src/main/java/net/catharos/lib/command/CommandManager.java b/src/main/java/net/catharos/lib/command/CommandManager.java
index 2a65e7e..d7c18f0 100644
--- a/src/main/java/net/catharos/lib/command/CommandManager.java
+++ b/src/main/java/net/catharos/lib/command/CommandManager.java
@@ -1,163 +1,163 @@
package net.catharos.lib.command;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import net.catharos.lib.cLib;
import net.catharos.lib.util.ArrayUtil;
import net.catharos.lib.util.MessageUtil;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class CommandManager implements CommandExecutor {
protected final Map<String, Command> cmds;
protected final Map<Command, Method> methods;
protected final Map<Method, Object> instances;
public CommandManager() {
this.cmds = new HashMap<String, Command>();
this.methods = new HashMap<Command, Method>();
this.instances = new HashMap<Method, Object>();
}
public boolean registerCommands(Class clazz) {
Object obj;
try { obj = clazz.newInstance(); }
catch (Exception ex) { return false; }
return registerCommands(obj);
}
public boolean registerCommands(Object obj) {
boolean success = true;
for(Method method : obj.getClass().getMethods()) {
try {
Command cmd = method.getAnnotation(Command.class);
if(cmd == null) continue;
Type returnType = method.getReturnType();
if(returnType != Boolean.TYPE && returnType != Void.TYPE) {
throw new Exception("Unsupported return type: " + returnType.toString());
}
Class<?>[] params = method.getParameterTypes();
if(params.length != 2 || (params[0] != CommandSender.class) || !(params[1].isArray())) {
throw new Exception("Method " + method.getName() + " does not match the required parameters!");
}
cmds.put(cmd.name().toLowerCase(), cmd);
for(String s : cmd.aliases()) {
cmds.put(s.toLowerCase(), cmd);
}
methods.put(cmd, method);
instances.put(method, obj);
} catch(Exception e) {
cLib.getInstance().getLogger().warning(e.getMessage());
success = false;
continue;
}
}
return success;
}
public boolean onCommand(CommandSender cs, org.bukkit.command.Command cmnd, String label, String[] args) {
String str;
Command cmd;
for (int args_left = args.length; args_left >= 0; args_left--) {
// Build command string
str = label + ((args_left > 0) ? " " + ArrayUtil.implode( Arrays.copyOfRange( args, 0, args_left ), " " ) : "");
cmd = getCommand(str);
if(cmd != null) try {
// Check for console / player
if (!(cs instanceof Player) && !cmd.consoleCmd()) {
throw new Exception("The command cannot be executed from console." );
}
// Check permisisons
if (!hasPermission( cs, cmd.permission() )) {
throw new Exception("You are not allowed to use that command!" );
}
boolean help = (args.length > 0 && args[args.length - 1].equalsIgnoreCase( "?" )) ? true : false;
if (!help) {
String[] cmd_args = Arrays.copyOfRange( args, args_left, args.length );
if (cmd_args.length < cmd.minArgs() || (cmd.maxArgs() >= 0 && cmd_args.length > cmd.maxArgs())) {
help = true;
} else {
Method method = methods.get(cmd);
if(method == null) throw new Exception("Something went wrong: Method not found. Please call an admin!");
if(method.getReturnType() == Boolean.TYPE) {
help = !((Boolean) method.invoke(getInstance(method), cs, args));
} else {
method.invoke(getInstance(method), cs, args);
}
}
}
if (help) {
MessageUtil.sendMessage( cs, "&6----------------=[ &cHelp: &3%0&6]=----------------", cmd.name() );
String desc = cmd.description();
MessageUtil.sendMessage( cs, "&6Description&f: %0", desc.isEmpty() ? "&7(no description available)" : desc );
String usage = cmd.usage();
MessageUtil.sendMessage( cs, "&6Usage: &f%0", usage.isEmpty() ? "/" + cmd.name() : usage );
if(cmd.aliases().length > 0) MessageUtil.sendMessage( cs, "&6Aliases: &f/%0", ArrayUtil.implode( cmd.aliases(), ", /" ) );
}
return true;
} catch( Exception ex ) {
MessageUtil.sendError( cs, ex.getMessage());
return true;
}
}
// Send error message
if (args.length > 0) {
- MessageUtil.sendError( cs, "Command not found: &6%0 &7(/%0 %1)", args[args.length - 1], ArrayUtil.implode( args, " " ) );
+ MessageUtil.sendError( cs, "Command not found: &6%0 &7(/%0 %1)", args[args.length - 1], label, ArrayUtil.implode( args, " " ) );
} else {
MessageUtil.sendError( cs, "Command not found: &6%0", label );
}
return true;
}
public static boolean hasPermission( CommandSender sender, String perm ) {
if ((!(sender instanceof Player)) || (perm == null) || (perm.isEmpty())) return true;
Player player = (Player) sender;
return player.isOp() || player.hasPermission(perm);
}
public Command getCommand( String label ) {
return cmds.get(label);
}
private Object getInstance( Method m ) {
return instances.get(m);
}
}
| true | true | public boolean onCommand(CommandSender cs, org.bukkit.command.Command cmnd, String label, String[] args) {
String str;
Command cmd;
for (int args_left = args.length; args_left >= 0; args_left--) {
// Build command string
str = label + ((args_left > 0) ? " " + ArrayUtil.implode( Arrays.copyOfRange( args, 0, args_left ), " " ) : "");
cmd = getCommand(str);
if(cmd != null) try {
// Check for console / player
if (!(cs instanceof Player) && !cmd.consoleCmd()) {
throw new Exception("The command cannot be executed from console." );
}
// Check permisisons
if (!hasPermission( cs, cmd.permission() )) {
throw new Exception("You are not allowed to use that command!" );
}
boolean help = (args.length > 0 && args[args.length - 1].equalsIgnoreCase( "?" )) ? true : false;
if (!help) {
String[] cmd_args = Arrays.copyOfRange( args, args_left, args.length );
if (cmd_args.length < cmd.minArgs() || (cmd.maxArgs() >= 0 && cmd_args.length > cmd.maxArgs())) {
help = true;
} else {
Method method = methods.get(cmd);
if(method == null) throw new Exception("Something went wrong: Method not found. Please call an admin!");
if(method.getReturnType() == Boolean.TYPE) {
help = !((Boolean) method.invoke(getInstance(method), cs, args));
} else {
method.invoke(getInstance(method), cs, args);
}
}
}
if (help) {
MessageUtil.sendMessage( cs, "&6----------------=[ &cHelp: &3%0&6]=----------------", cmd.name() );
String desc = cmd.description();
MessageUtil.sendMessage( cs, "&6Description&f: %0", desc.isEmpty() ? "&7(no description available)" : desc );
String usage = cmd.usage();
MessageUtil.sendMessage( cs, "&6Usage: &f%0", usage.isEmpty() ? "/" + cmd.name() : usage );
if(cmd.aliases().length > 0) MessageUtil.sendMessage( cs, "&6Aliases: &f/%0", ArrayUtil.implode( cmd.aliases(), ", /" ) );
}
return true;
} catch( Exception ex ) {
MessageUtil.sendError( cs, ex.getMessage());
return true;
}
}
// Send error message
if (args.length > 0) {
MessageUtil.sendError( cs, "Command not found: &6%0 &7(/%0 %1)", args[args.length - 1], ArrayUtil.implode( args, " " ) );
} else {
MessageUtil.sendError( cs, "Command not found: &6%0", label );
}
return true;
}
| public boolean onCommand(CommandSender cs, org.bukkit.command.Command cmnd, String label, String[] args) {
String str;
Command cmd;
for (int args_left = args.length; args_left >= 0; args_left--) {
// Build command string
str = label + ((args_left > 0) ? " " + ArrayUtil.implode( Arrays.copyOfRange( args, 0, args_left ), " " ) : "");
cmd = getCommand(str);
if(cmd != null) try {
// Check for console / player
if (!(cs instanceof Player) && !cmd.consoleCmd()) {
throw new Exception("The command cannot be executed from console." );
}
// Check permisisons
if (!hasPermission( cs, cmd.permission() )) {
throw new Exception("You are not allowed to use that command!" );
}
boolean help = (args.length > 0 && args[args.length - 1].equalsIgnoreCase( "?" )) ? true : false;
if (!help) {
String[] cmd_args = Arrays.copyOfRange( args, args_left, args.length );
if (cmd_args.length < cmd.minArgs() || (cmd.maxArgs() >= 0 && cmd_args.length > cmd.maxArgs())) {
help = true;
} else {
Method method = methods.get(cmd);
if(method == null) throw new Exception("Something went wrong: Method not found. Please call an admin!");
if(method.getReturnType() == Boolean.TYPE) {
help = !((Boolean) method.invoke(getInstance(method), cs, args));
} else {
method.invoke(getInstance(method), cs, args);
}
}
}
if (help) {
MessageUtil.sendMessage( cs, "&6----------------=[ &cHelp: &3%0&6]=----------------", cmd.name() );
String desc = cmd.description();
MessageUtil.sendMessage( cs, "&6Description&f: %0", desc.isEmpty() ? "&7(no description available)" : desc );
String usage = cmd.usage();
MessageUtil.sendMessage( cs, "&6Usage: &f%0", usage.isEmpty() ? "/" + cmd.name() : usage );
if(cmd.aliases().length > 0) MessageUtil.sendMessage( cs, "&6Aliases: &f/%0", ArrayUtil.implode( cmd.aliases(), ", /" ) );
}
return true;
} catch( Exception ex ) {
MessageUtil.sendError( cs, ex.getMessage());
return true;
}
}
// Send error message
if (args.length > 0) {
MessageUtil.sendError( cs, "Command not found: &6%0 &7(/%0 %1)", args[args.length - 1], label, ArrayUtil.implode( args, " " ) );
} else {
MessageUtil.sendError( cs, "Command not found: &6%0", label );
}
return true;
}
|
diff --git a/Sysintegration/src/ch/zhaw/simulation/sysintegration/filechooser/script/LinuxFilechooser.java b/Sysintegration/src/ch/zhaw/simulation/sysintegration/filechooser/script/LinuxFilechooser.java
index 3b414057..6f4276e9 100644
--- a/Sysintegration/src/ch/zhaw/simulation/sysintegration/filechooser/script/LinuxFilechooser.java
+++ b/Sysintegration/src/ch/zhaw/simulation/sysintegration/filechooser/script/LinuxFilechooser.java
@@ -1,53 +1,53 @@
package ch.zhaw.simulation.sysintegration.filechooser.script;
import java.awt.Window;
import java.io.File;
import ch.zhaw.simulation.sysintegration.SimFileFilter;
import ch.zhaw.simulation.sysintegration.filechooser.FilechooserException;
public class LinuxFilechooser extends ScriptFilechooser {
@Override
public File showSaveDialog(Window parent, SimFileFilter filefilter, String lastSavePath) throws FilechooserException {
try {
String description = filefilter.getDescription();
String filter = filefilter.getExtension();
if (filter == null) {
filter = "*";
} else {
filter = "*" + filter;
}
String file = run(new String[] { "python", "filechooser/linux/filechooser.py", "Datei speichern...", description, filter, lastSavePath, "save" });
if (file == null) {
return null;
}
- return checkCanSave(new File(file), parent, filefilter, lastSavePath);
+ return checkFileSaveExists(file, parent, filefilter, lastSavePath);
} catch (Exception e) {
throw new FilechooserException(e);
}
}
@Override
public File showOpenDialog(Window parent, SimFileFilter filefilter, String lastSavePath) throws FilechooserException {
try {
String description = filefilter.getDescription();
String filter = filefilter.getExtension();
if (filter == null) {
filter = "*";
} else {
filter = "*" + filter;
}
String file = run(new String[] { "python", "filechooser/linux/filechooser.py", "Datei öffnen...", description, filter, lastSavePath, "open" });
if (file == null) {
return null;
}
return new File(file);
} catch (Exception e) {
throw new FilechooserException(e);
}
}
}
| true | true | public File showSaveDialog(Window parent, SimFileFilter filefilter, String lastSavePath) throws FilechooserException {
try {
String description = filefilter.getDescription();
String filter = filefilter.getExtension();
if (filter == null) {
filter = "*";
} else {
filter = "*" + filter;
}
String file = run(new String[] { "python", "filechooser/linux/filechooser.py", "Datei speichern...", description, filter, lastSavePath, "save" });
if (file == null) {
return null;
}
return checkCanSave(new File(file), parent, filefilter, lastSavePath);
} catch (Exception e) {
throw new FilechooserException(e);
}
}
| public File showSaveDialog(Window parent, SimFileFilter filefilter, String lastSavePath) throws FilechooserException {
try {
String description = filefilter.getDescription();
String filter = filefilter.getExtension();
if (filter == null) {
filter = "*";
} else {
filter = "*" + filter;
}
String file = run(new String[] { "python", "filechooser/linux/filechooser.py", "Datei speichern...", description, filter, lastSavePath, "save" });
if (file == null) {
return null;
}
return checkFileSaveExists(file, parent, filefilter, lastSavePath);
} catch (Exception e) {
throw new FilechooserException(e);
}
}
|
diff --git a/Madz.DatabaseMetaData/src/main/java/net/madz/db/core/meta/immutable/mysql/datatype/MySQLTextTypeBase.java b/Madz.DatabaseMetaData/src/main/java/net/madz/db/core/meta/immutable/mysql/datatype/MySQLTextTypeBase.java
index 20946a0..f0882c5 100644
--- a/Madz.DatabaseMetaData/src/main/java/net/madz/db/core/meta/immutable/mysql/datatype/MySQLTextTypeBase.java
+++ b/Madz.DatabaseMetaData/src/main/java/net/madz/db/core/meta/immutable/mysql/datatype/MySQLTextTypeBase.java
@@ -1,81 +1,82 @@
package net.madz.db.core.meta.immutable.mysql.datatype;
import net.madz.db.core.meta.mutable.mysql.MySQLColumnMetaDataBuilder;
public abstract class MySQLTextTypeBase implements DataType {
private boolean isBinary;
private String charsetName;
private String collationName;
public MySQLTextTypeBase() {
super();
}
public MySQLTextTypeBase(boolean isBinary) {
super();
this.isBinary = isBinary;
}
public MySQLTextTypeBase(String collationName) {
super();
this.collationName = collationName;
}
public MySQLTextTypeBase(String charsetName, String collationName) {
super();
this.charsetName = charsetName;
this.collationName = collationName;
}
public MySQLTextTypeBase(boolean isBinary, String charsetName) {
super();
this.isBinary = isBinary;
this.charsetName = charsetName;
}
public boolean isBinary() {
return isBinary;
}
public void setBinary(boolean isBinary) {
this.isBinary = isBinary;
}
public String getCharsetName() {
return charsetName;
}
public void setCharsetName(String charsetName) {
this.charsetName = charsetName;
}
public String getCollationName() {
return collationName;
}
public void setCollationName(String collationName) {
this.collationName = collationName;
}
@Override
public void build(MySQLColumnMetaDataBuilder builder) {
builder.setSqlTypeName(getName());
builder.setCharacterSet(charsetName);
builder.setCollationName(collationName);
builder.setCollationWithBin(isBinary);
final StringBuilder result = new StringBuilder();
result.append(getName());
if ( null != charsetName ) {
result.append(" CHARACTER SET ");
result.append(charsetName);
}
if ( isBinary ) {
result.append(" BINARY ");
}
if ( null != collationName ) {
+ result.append(" COLLATE ");
result.append(collationName);
}
builder.setColumnType(result.toString());
}
}
| true | true | public void build(MySQLColumnMetaDataBuilder builder) {
builder.setSqlTypeName(getName());
builder.setCharacterSet(charsetName);
builder.setCollationName(collationName);
builder.setCollationWithBin(isBinary);
final StringBuilder result = new StringBuilder();
result.append(getName());
if ( null != charsetName ) {
result.append(" CHARACTER SET ");
result.append(charsetName);
}
if ( isBinary ) {
result.append(" BINARY ");
}
if ( null != collationName ) {
result.append(collationName);
}
builder.setColumnType(result.toString());
}
| public void build(MySQLColumnMetaDataBuilder builder) {
builder.setSqlTypeName(getName());
builder.setCharacterSet(charsetName);
builder.setCollationName(collationName);
builder.setCollationWithBin(isBinary);
final StringBuilder result = new StringBuilder();
result.append(getName());
if ( null != charsetName ) {
result.append(" CHARACTER SET ");
result.append(charsetName);
}
if ( isBinary ) {
result.append(" BINARY ");
}
if ( null != collationName ) {
result.append(" COLLATE ");
result.append(collationName);
}
builder.setColumnType(result.toString());
}
|
diff --git a/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevTask.java b/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevTask.java
index 5404e4442..cb02154e9 100644
--- a/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevTask.java
+++ b/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevTask.java
@@ -1,49 +1,50 @@
package com.todoroo.astrid.producteev.sync;
import com.todoroo.andlib.data.Property.LongProperty;
import com.todoroo.andlib.data.Property.StringProperty;
import com.todoroo.andlib.utility.Preferences;
import com.todoroo.astrid.data.Metadata;
import com.todoroo.astrid.producteev.ProducteevUtilities;
/**
* Metadata entries for a Producteev Task
* @author Tim Su <[email protected]>
*
*/
public class ProducteevTask {
/** metadata key */
public static final String METADATA_KEY = "producteev"; //$NON-NLS-1$
/** task id in producteev */
public static final LongProperty ID = new LongProperty(Metadata.TABLE,
Metadata.VALUE1.name);
/** dashboard id */
public static final LongProperty DASHBOARD_ID = new LongProperty(Metadata.TABLE,
Metadata.VALUE2.name);
/** creator id */
public static final LongProperty CREATOR_ID = new LongProperty(Metadata.TABLE,
Metadata.VALUE3.name);
/** responsible id */
public static final LongProperty RESPONSIBLE_ID = new LongProperty(Metadata.TABLE,
Metadata.VALUE4.name);
/** repeating settings */
public static final StringProperty REPEATING_SETTING = new StringProperty(Metadata.TABLE,
Metadata.VALUE5.name);
public static Metadata newMetadata() {
Metadata metadata = new Metadata();
metadata.setValue(Metadata.KEY, ProducteevTask.METADATA_KEY);
metadata.setValue(ID, 0L);
metadata.setValue(DASHBOARD_ID, ProducteevUtilities.INSTANCE.getDefaultDashboard());
metadata.setValue(CREATOR_ID, Preferences.getLong(ProducteevUtilities.PREF_USER_ID, 0L));
metadata.setValue(RESPONSIBLE_ID, Preferences.getLong(ProducteevUtilities.PREF_USER_ID, 0L));
+ metadata.setValue(REPEATING_SETTING, ""); //$NON-NLS-1$
return metadata;
}
}
| true | true | public static Metadata newMetadata() {
Metadata metadata = new Metadata();
metadata.setValue(Metadata.KEY, ProducteevTask.METADATA_KEY);
metadata.setValue(ID, 0L);
metadata.setValue(DASHBOARD_ID, ProducteevUtilities.INSTANCE.getDefaultDashboard());
metadata.setValue(CREATOR_ID, Preferences.getLong(ProducteevUtilities.PREF_USER_ID, 0L));
metadata.setValue(RESPONSIBLE_ID, Preferences.getLong(ProducteevUtilities.PREF_USER_ID, 0L));
return metadata;
}
| public static Metadata newMetadata() {
Metadata metadata = new Metadata();
metadata.setValue(Metadata.KEY, ProducteevTask.METADATA_KEY);
metadata.setValue(ID, 0L);
metadata.setValue(DASHBOARD_ID, ProducteevUtilities.INSTANCE.getDefaultDashboard());
metadata.setValue(CREATOR_ID, Preferences.getLong(ProducteevUtilities.PREF_USER_ID, 0L));
metadata.setValue(RESPONSIBLE_ID, Preferences.getLong(ProducteevUtilities.PREF_USER_ID, 0L));
metadata.setValue(REPEATING_SETTING, ""); //$NON-NLS-1$
return metadata;
}
|
diff --git a/src/main/java/org/odlabs/wiquery/plugins/grid/GridPlugin.java b/src/main/java/org/odlabs/wiquery/plugins/grid/GridPlugin.java
index 092f380a..b5c5cfd1 100755
--- a/src/main/java/org/odlabs/wiquery/plugins/grid/GridPlugin.java
+++ b/src/main/java/org/odlabs/wiquery/plugins/grid/GridPlugin.java
@@ -1,71 +1,71 @@
/*
* Copyright (c) 2008 Objet Direct
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.odlabs.wiquery.plugins.grid;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.odlabs.wiquery.core.commons.IWiQueryPlugin;
import org.odlabs.wiquery.core.commons.WiQueryResourceManager;
import org.odlabs.wiquery.core.javascript.JsQuery;
import org.odlabs.wiquery.core.javascript.JsStatement;
/**
* $Id$
* <p>
* Builds a data grid from this container's markup.
* </p>
*
* @author Lionel Armanet
* @since 0.5
*/
public class GridPlugin extends WebMarkupContainer implements IWiQueryPlugin {
private static final long serialVersionUID = 8764581335554628538L;
/**
* Builds a new instance of {@link GridPlugin} for the given wicket id.
*/
public GridPlugin(String id) {
super(id);
}
/*
* (non-Javadoc)
*
* @see org.objetdirect.wickext.core.commons.JavaScriptCallable#statement()
*/
public JsStatement statement() {
return new JsQuery(this).$().chain("flexigrid");
}
/*
* (non-Javadoc)
*
* @see org.objetdirect.wickext.core.commons.WickextPlugin#getHeaderContribution()
*/
public void contribute(WiQueryResourceManager wiQueryResourceManager) {
wiQueryResourceManager.addCssResource(
- GridPlugin.class, "flexigrid/css/flexigrid/flexigrid.css");
+ GridPlugin.class, "flexigrid/flexigrid.css");
wiQueryResourceManager.addJavaScriptResource(
GridPlugin.class, "flexigrid/flexigrid.js");
}
}
| true | true | public void contribute(WiQueryResourceManager wiQueryResourceManager) {
wiQueryResourceManager.addCssResource(
GridPlugin.class, "flexigrid/css/flexigrid/flexigrid.css");
wiQueryResourceManager.addJavaScriptResource(
GridPlugin.class, "flexigrid/flexigrid.js");
}
| public void contribute(WiQueryResourceManager wiQueryResourceManager) {
wiQueryResourceManager.addCssResource(
GridPlugin.class, "flexigrid/flexigrid.css");
wiQueryResourceManager.addJavaScriptResource(
GridPlugin.class, "flexigrid/flexigrid.js");
}
|
diff --git a/fm-workbench/agree/com.rockwellcollins.atc.agree.analysis/src/com/rockwellcollins/atc/agree/analysis/AgreeCalendarUtils.java b/fm-workbench/agree/com.rockwellcollins.atc.agree.analysis/src/com/rockwellcollins/atc/agree/analysis/AgreeCalendarUtils.java
index 78c151ba..794c7dad 100644
--- a/fm-workbench/agree/com.rockwellcollins.atc.agree.analysis/src/com/rockwellcollins/atc/agree/analysis/AgreeCalendarUtils.java
+++ b/fm-workbench/agree/com.rockwellcollins.atc.agree.analysis/src/com/rockwellcollins/atc/agree/analysis/AgreeCalendarUtils.java
@@ -1,191 +1,191 @@
package com.rockwellcollins.atc.agree.analysis;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import jkind.lustre.BinaryExpr;
import jkind.lustre.BinaryOp;
import jkind.lustre.BoolExpr;
import jkind.lustre.Equation;
import jkind.lustre.Expr;
import jkind.lustre.IdExpr;
import jkind.lustre.IfThenElseExpr;
import jkind.lustre.IntExpr;
import jkind.lustre.NamedType;
import jkind.lustre.Node;
import jkind.lustre.NodeCallExpr;
import jkind.lustre.SubrangeIntType;
import jkind.lustre.UnaryExpr;
import jkind.lustre.UnaryOp;
import jkind.lustre.VarDecl;
public class AgreeCalendarUtils {
static private String dfaName = null;
static public Node getDFANode(String name, int synchrony){
if(synchrony <= 0){
throw new AgreeException("Attempt to use quasi-synchrony of value: "+synchrony);
}
dfaName = name;
VarDecl rVar = new VarDecl("_r",
new SubrangeIntType(BigInteger.valueOf(-synchrony),
BigInteger.valueOf(synchrony)));
IdExpr r = new IdExpr(rVar.id);
VarDecl rIsBoundedVar = new VarDecl("_r_is_bounded", NamedType.BOOL);
IdExpr rIsBounded = new IdExpr(rIsBoundedVar.id);
VarDecl outVar = new VarDecl("_out", NamedType.BOOL);
IdExpr out = new IdExpr(outVar.id);
VarDecl clkVar0 = new VarDecl("_clk0", NamedType.BOOL);
- IdExpr clk0 = new IdExpr(clkVar0.id);
+ IdExpr p = new IdExpr(clkVar0.id);
VarDecl clkVar1 = new VarDecl("_clk1", NamedType.BOOL);
- IdExpr clk1 = new IdExpr(clkVar1.id);
+ IdExpr q = new IdExpr(clkVar1.id);
List<VarDecl> inputs = new ArrayList<>();
inputs.add(clkVar0);
inputs.add(clkVar1);
List<VarDecl> outputs = new ArrayList<>();
outputs.add(outVar);
List<VarDecl> locals = new ArrayList<>();
locals.add(rVar);
locals.add(rIsBoundedVar);
Expr intZeroExpr = new IntExpr(BigInteger.ZERO);
Expr intOneExpr = new IntExpr(BigInteger.ONE);
Expr intNegOneExpr = new IntExpr(BigInteger.valueOf(-1));
Expr intSyncValExpr = new IntExpr(BigInteger.valueOf(synchrony));
Expr intNegSyncValxpr = new IntExpr(BigInteger.valueOf(-synchrony));
//(0 -> pre r)
Expr rPreExpr = new BinaryExpr(new IntExpr(BigInteger.ZERO), BinaryOp.ARROW, new UnaryExpr(UnaryOp.PRE, r));
//(0 -> pre r) < 0
Expr rPreLTExpr = new BinaryExpr(rPreExpr, BinaryOp.LESS, intZeroExpr);
//(0 -> pre r) > 0
Expr rPreGTExpr = new BinaryExpr(rPreExpr, BinaryOp.GREATER, intZeroExpr);
//(0 -> pre r) + 1
Expr rPrePlus = new BinaryExpr(rPreExpr, BinaryOp.PLUS, intOneExpr);
//(0 -> pre r) - 1
Expr rPreMinus = new BinaryExpr(rPreExpr, BinaryOp.MINUS, intOneExpr);
//if (0 -> pre r) < 0 then 1 else ((0 -> pre r) + 1)
Expr ifExpr0 = new IfThenElseExpr(rPreLTExpr, intOneExpr, rPrePlus);
//if (0 -> pre r) > 0 then -1 else ((0 -> pre r) - 1)
Expr ifExpr1 = new IfThenElseExpr(rPreGTExpr, intNegOneExpr, rPreMinus);
//if q then (if (0 -> pre r) > 0 then -1 else ((0 -> pre r) - 1)) else (0 -> pre r)
- Expr ifExprClk1 = new IfThenElseExpr(clk1, ifExpr1, rPreExpr);
+ Expr ifExprClk1 = new IfThenElseExpr(q, ifExpr1, rPreExpr);
//if p then (if (0 -> pre r) < 0 then 1 else ((0 -> pre r) + 1))
//else if q then (if (0 -> pre r) > 0 then -1 else ((0 -> pre r) - 1))
//else (0 -> pre r);
- Expr ifExprClk0 = new IfThenElseExpr(clk0, ifExpr0, ifExprClk1);
+ Expr ifExprClk0 = new IfThenElseExpr(p, ifExpr0, ifExprClk1);
//if p and q then 0
//else if p then (if (0 -> pre r) < 0 then 1 else ((0 -> pre r) + 1))
//else if q then (if (0 -> pre r) > 0 then -1 else ((0 -> pre r) - 1))
//else (0 -> pre r);
- Expr rExpr = new IfThenElseExpr(new BinaryExpr(clk0, BinaryOp.AND, clk1), intZeroExpr, ifExprClk0);
+ Expr rExpr = new IfThenElseExpr(new BinaryExpr(p, BinaryOp.AND, q), intZeroExpr, ifExprClk0);
- //((0 -> pre r) = 2 and p)
- Expr condExpr0 = new BinaryExpr(new BinaryExpr(rPreExpr, BinaryOp.EQUAL, intSyncValExpr), BinaryOp.AND, clk0);
- //((0 -> pre r) = -2 and q)
- Expr condExpr1 = new BinaryExpr(new BinaryExpr(rPreExpr, BinaryOp.EQUAL, intNegSyncValxpr), BinaryOp.AND, clk1);
- //not (((0 -> pre r) = 2 and p) or ((0 -> pre r) = -2 and q))
+ //((0 -> pre r) >= 2 and p)
+ Expr condExpr0 = new BinaryExpr(new BinaryExpr(rPreExpr, BinaryOp.GREATEREQUAL, intSyncValExpr), BinaryOp.AND, p);
+ //((0 -> pre r) <= -2 and q)
+ Expr condExpr1 = new BinaryExpr(new BinaryExpr(rPreExpr, BinaryOp.LESSEQUAL, intNegSyncValxpr), BinaryOp.AND, q);
+ //not (((0 -> pre r) >= 2 and p) or ((0 -> pre r) <= -2 and q))
Expr outExpr = new UnaryExpr(UnaryOp.NOT, new BinaryExpr(condExpr0, BinaryOp.OR, condExpr1));
//r <= 2 and r >= -2
- Expr rIsBoundedExpr = new BinaryExpr(new BinaryExpr(rExpr, BinaryOp.LESSEQUAL, intSyncValExpr),
- BinaryOp.OR,
- new BinaryExpr(rExpr, BinaryOp.GREATEREQUAL, intNegSyncValxpr));
+ Expr rIsBoundedExpr = new BinaryExpr(new BinaryExpr(r, BinaryOp.LESSEQUAL, intSyncValExpr),
+ BinaryOp.AND,
+ new BinaryExpr(r, BinaryOp.GREATEREQUAL, intNegSyncValxpr));
List<Equation> equations = new ArrayList<>();
equations.add(new Equation(r, rExpr));
equations.add(new Equation(rIsBounded, rIsBoundedExpr));
equations.add(new Equation(out, outExpr));
List<String> properties = new ArrayList<>();
properties.add(rIsBounded.id);
return new Node(dfaName, inputs, outputs, locals, equations, properties);
}
static public Node getCalendarNode(String name, int numClks){
if(dfaName == null){
throw new AgreeException("Each call to getCalendarNode must be preeceded by a call to getDFANode");
}
Node calendarNode;
Expr nodeExpr = null;
String clkVarPrefix = "_clk_";
IdExpr outVar = new IdExpr("_out");
//make the inputs and outputs
List<VarDecl> inputs = new ArrayList<>();
List<IdExpr> clks = new ArrayList<>();
for(int i = 0; i < numClks; i++){
inputs.add(new VarDecl(clkVarPrefix+i, NamedType.BOOL));
clks.add(new IdExpr(clkVarPrefix+i));
}
List<VarDecl> outputs = new ArrayList<>();
outputs.add(new VarDecl(outVar.id, NamedType.BOOL));
for(int i = 0; i < clks.size()-1; i++){
Expr clk0 = clks.get(i);
for(int j = i+1; j < clks.size(); j++){
Expr clk1 = clks.get(j);
Expr dfaExpr = getDFAExpr(clk0, clk1);
if(nodeExpr == null){
nodeExpr = dfaExpr;
}else{
nodeExpr = new BinaryExpr(nodeExpr, BinaryOp.AND, dfaExpr);
}
}
}
Equation nodeEq = new Equation(outVar, nodeExpr);
calendarNode = new Node(name, inputs, outputs, new ArrayList<VarDecl>(), Collections.singletonList(nodeEq));
dfaName = null;
return calendarNode;
}
static public List<Equation> getAllClksHaveTicked(String name, String clkPref, List<Expr> clks){
Expr result = new BoolExpr(true);
List<Equation> eqs = new ArrayList<>();
int i = 0;
for(Expr clk : clks){
Equation clkHasTicked = getClkHasTicked(new IdExpr(clkPref+i), clk);
result = new BinaryExpr(result, BinaryOp.AND, clkHasTicked.lhs.get(0));
eqs.add(clkHasTicked);
i++;
}
eqs.add(new Equation(new IdExpr(name), result));
return eqs;
}
static public Equation getClkHasTicked(IdExpr clkTickedId, Expr clkExpr){
// clkTickedID = clkExpr -> clkExpr or pre clkTickedId
Expr tickExpr = new BinaryExpr(clkExpr, BinaryOp.OR, new UnaryExpr(UnaryOp.PRE, clkTickedId));
return new Equation(clkTickedId, new BinaryExpr(clkExpr, BinaryOp.ARROW, tickExpr));
}
static private Expr getDFAExpr(Expr clk0, Expr clk1){
return new NodeCallExpr(dfaName, clk0, clk1);
}
}
| false | true | static public Node getDFANode(String name, int synchrony){
if(synchrony <= 0){
throw new AgreeException("Attempt to use quasi-synchrony of value: "+synchrony);
}
dfaName = name;
VarDecl rVar = new VarDecl("_r",
new SubrangeIntType(BigInteger.valueOf(-synchrony),
BigInteger.valueOf(synchrony)));
IdExpr r = new IdExpr(rVar.id);
VarDecl rIsBoundedVar = new VarDecl("_r_is_bounded", NamedType.BOOL);
IdExpr rIsBounded = new IdExpr(rIsBoundedVar.id);
VarDecl outVar = new VarDecl("_out", NamedType.BOOL);
IdExpr out = new IdExpr(outVar.id);
VarDecl clkVar0 = new VarDecl("_clk0", NamedType.BOOL);
IdExpr clk0 = new IdExpr(clkVar0.id);
VarDecl clkVar1 = new VarDecl("_clk1", NamedType.BOOL);
IdExpr clk1 = new IdExpr(clkVar1.id);
List<VarDecl> inputs = new ArrayList<>();
inputs.add(clkVar0);
inputs.add(clkVar1);
List<VarDecl> outputs = new ArrayList<>();
outputs.add(outVar);
List<VarDecl> locals = new ArrayList<>();
locals.add(rVar);
locals.add(rIsBoundedVar);
Expr intZeroExpr = new IntExpr(BigInteger.ZERO);
Expr intOneExpr = new IntExpr(BigInteger.ONE);
Expr intNegOneExpr = new IntExpr(BigInteger.valueOf(-1));
Expr intSyncValExpr = new IntExpr(BigInteger.valueOf(synchrony));
Expr intNegSyncValxpr = new IntExpr(BigInteger.valueOf(-synchrony));
//(0 -> pre r)
Expr rPreExpr = new BinaryExpr(new IntExpr(BigInteger.ZERO), BinaryOp.ARROW, new UnaryExpr(UnaryOp.PRE, r));
//(0 -> pre r) < 0
Expr rPreLTExpr = new BinaryExpr(rPreExpr, BinaryOp.LESS, intZeroExpr);
//(0 -> pre r) > 0
Expr rPreGTExpr = new BinaryExpr(rPreExpr, BinaryOp.GREATER, intZeroExpr);
//(0 -> pre r) + 1
Expr rPrePlus = new BinaryExpr(rPreExpr, BinaryOp.PLUS, intOneExpr);
//(0 -> pre r) - 1
Expr rPreMinus = new BinaryExpr(rPreExpr, BinaryOp.MINUS, intOneExpr);
//if (0 -> pre r) < 0 then 1 else ((0 -> pre r) + 1)
Expr ifExpr0 = new IfThenElseExpr(rPreLTExpr, intOneExpr, rPrePlus);
//if (0 -> pre r) > 0 then -1 else ((0 -> pre r) - 1)
Expr ifExpr1 = new IfThenElseExpr(rPreGTExpr, intNegOneExpr, rPreMinus);
//if q then (if (0 -> pre r) > 0 then -1 else ((0 -> pre r) - 1)) else (0 -> pre r)
Expr ifExprClk1 = new IfThenElseExpr(clk1, ifExpr1, rPreExpr);
//if p then (if (0 -> pre r) < 0 then 1 else ((0 -> pre r) + 1))
//else if q then (if (0 -> pre r) > 0 then -1 else ((0 -> pre r) - 1))
//else (0 -> pre r);
Expr ifExprClk0 = new IfThenElseExpr(clk0, ifExpr0, ifExprClk1);
//if p and q then 0
//else if p then (if (0 -> pre r) < 0 then 1 else ((0 -> pre r) + 1))
//else if q then (if (0 -> pre r) > 0 then -1 else ((0 -> pre r) - 1))
//else (0 -> pre r);
Expr rExpr = new IfThenElseExpr(new BinaryExpr(clk0, BinaryOp.AND, clk1), intZeroExpr, ifExprClk0);
//((0 -> pre r) = 2 and p)
Expr condExpr0 = new BinaryExpr(new BinaryExpr(rPreExpr, BinaryOp.EQUAL, intSyncValExpr), BinaryOp.AND, clk0);
//((0 -> pre r) = -2 and q)
Expr condExpr1 = new BinaryExpr(new BinaryExpr(rPreExpr, BinaryOp.EQUAL, intNegSyncValxpr), BinaryOp.AND, clk1);
//not (((0 -> pre r) = 2 and p) or ((0 -> pre r) = -2 and q))
Expr outExpr = new UnaryExpr(UnaryOp.NOT, new BinaryExpr(condExpr0, BinaryOp.OR, condExpr1));
//r <= 2 and r >= -2
Expr rIsBoundedExpr = new BinaryExpr(new BinaryExpr(rExpr, BinaryOp.LESSEQUAL, intSyncValExpr),
BinaryOp.OR,
new BinaryExpr(rExpr, BinaryOp.GREATEREQUAL, intNegSyncValxpr));
List<Equation> equations = new ArrayList<>();
equations.add(new Equation(r, rExpr));
equations.add(new Equation(rIsBounded, rIsBoundedExpr));
equations.add(new Equation(out, outExpr));
List<String> properties = new ArrayList<>();
properties.add(rIsBounded.id);
return new Node(dfaName, inputs, outputs, locals, equations, properties);
}
| static public Node getDFANode(String name, int synchrony){
if(synchrony <= 0){
throw new AgreeException("Attempt to use quasi-synchrony of value: "+synchrony);
}
dfaName = name;
VarDecl rVar = new VarDecl("_r",
new SubrangeIntType(BigInteger.valueOf(-synchrony),
BigInteger.valueOf(synchrony)));
IdExpr r = new IdExpr(rVar.id);
VarDecl rIsBoundedVar = new VarDecl("_r_is_bounded", NamedType.BOOL);
IdExpr rIsBounded = new IdExpr(rIsBoundedVar.id);
VarDecl outVar = new VarDecl("_out", NamedType.BOOL);
IdExpr out = new IdExpr(outVar.id);
VarDecl clkVar0 = new VarDecl("_clk0", NamedType.BOOL);
IdExpr p = new IdExpr(clkVar0.id);
VarDecl clkVar1 = new VarDecl("_clk1", NamedType.BOOL);
IdExpr q = new IdExpr(clkVar1.id);
List<VarDecl> inputs = new ArrayList<>();
inputs.add(clkVar0);
inputs.add(clkVar1);
List<VarDecl> outputs = new ArrayList<>();
outputs.add(outVar);
List<VarDecl> locals = new ArrayList<>();
locals.add(rVar);
locals.add(rIsBoundedVar);
Expr intZeroExpr = new IntExpr(BigInteger.ZERO);
Expr intOneExpr = new IntExpr(BigInteger.ONE);
Expr intNegOneExpr = new IntExpr(BigInteger.valueOf(-1));
Expr intSyncValExpr = new IntExpr(BigInteger.valueOf(synchrony));
Expr intNegSyncValxpr = new IntExpr(BigInteger.valueOf(-synchrony));
//(0 -> pre r)
Expr rPreExpr = new BinaryExpr(new IntExpr(BigInteger.ZERO), BinaryOp.ARROW, new UnaryExpr(UnaryOp.PRE, r));
//(0 -> pre r) < 0
Expr rPreLTExpr = new BinaryExpr(rPreExpr, BinaryOp.LESS, intZeroExpr);
//(0 -> pre r) > 0
Expr rPreGTExpr = new BinaryExpr(rPreExpr, BinaryOp.GREATER, intZeroExpr);
//(0 -> pre r) + 1
Expr rPrePlus = new BinaryExpr(rPreExpr, BinaryOp.PLUS, intOneExpr);
//(0 -> pre r) - 1
Expr rPreMinus = new BinaryExpr(rPreExpr, BinaryOp.MINUS, intOneExpr);
//if (0 -> pre r) < 0 then 1 else ((0 -> pre r) + 1)
Expr ifExpr0 = new IfThenElseExpr(rPreLTExpr, intOneExpr, rPrePlus);
//if (0 -> pre r) > 0 then -1 else ((0 -> pre r) - 1)
Expr ifExpr1 = new IfThenElseExpr(rPreGTExpr, intNegOneExpr, rPreMinus);
//if q then (if (0 -> pre r) > 0 then -1 else ((0 -> pre r) - 1)) else (0 -> pre r)
Expr ifExprClk1 = new IfThenElseExpr(q, ifExpr1, rPreExpr);
//if p then (if (0 -> pre r) < 0 then 1 else ((0 -> pre r) + 1))
//else if q then (if (0 -> pre r) > 0 then -1 else ((0 -> pre r) - 1))
//else (0 -> pre r);
Expr ifExprClk0 = new IfThenElseExpr(p, ifExpr0, ifExprClk1);
//if p and q then 0
//else if p then (if (0 -> pre r) < 0 then 1 else ((0 -> pre r) + 1))
//else if q then (if (0 -> pre r) > 0 then -1 else ((0 -> pre r) - 1))
//else (0 -> pre r);
Expr rExpr = new IfThenElseExpr(new BinaryExpr(p, BinaryOp.AND, q), intZeroExpr, ifExprClk0);
//((0 -> pre r) >= 2 and p)
Expr condExpr0 = new BinaryExpr(new BinaryExpr(rPreExpr, BinaryOp.GREATEREQUAL, intSyncValExpr), BinaryOp.AND, p);
//((0 -> pre r) <= -2 and q)
Expr condExpr1 = new BinaryExpr(new BinaryExpr(rPreExpr, BinaryOp.LESSEQUAL, intNegSyncValxpr), BinaryOp.AND, q);
//not (((0 -> pre r) >= 2 and p) or ((0 -> pre r) <= -2 and q))
Expr outExpr = new UnaryExpr(UnaryOp.NOT, new BinaryExpr(condExpr0, BinaryOp.OR, condExpr1));
//r <= 2 and r >= -2
Expr rIsBoundedExpr = new BinaryExpr(new BinaryExpr(r, BinaryOp.LESSEQUAL, intSyncValExpr),
BinaryOp.AND,
new BinaryExpr(r, BinaryOp.GREATEREQUAL, intNegSyncValxpr));
List<Equation> equations = new ArrayList<>();
equations.add(new Equation(r, rExpr));
equations.add(new Equation(rIsBounded, rIsBoundedExpr));
equations.add(new Equation(out, outExpr));
List<String> properties = new ArrayList<>();
properties.add(rIsBounded.id);
return new Node(dfaName, inputs, outputs, locals, equations, properties);
}
|
diff --git a/motech-scheduletracking-api/src/test/java/org/motechproject/scheduletracking/api/repository/TrackedSchedulesJsonReaderImplTest.java b/motech-scheduletracking-api/src/test/java/org/motechproject/scheduletracking/api/repository/TrackedSchedulesJsonReaderImplTest.java
index 097201e94..198d7da79 100644
--- a/motech-scheduletracking-api/src/test/java/org/motechproject/scheduletracking/api/repository/TrackedSchedulesJsonReaderImplTest.java
+++ b/motech-scheduletracking-api/src/test/java/org/motechproject/scheduletracking/api/repository/TrackedSchedulesJsonReaderImplTest.java
@@ -1,52 +1,52 @@
package org.motechproject.scheduletracking.api.repository;
import org.junit.Test;
import org.motechproject.scheduletracking.api.domain.json.MilestoneRecord;
import org.motechproject.scheduletracking.api.domain.json.ScheduleRecord;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class TrackedSchedulesJsonReaderImplTest {
@Test
public void shouldReadTheScheduleJsonFileCorrectly() {
TrackedSchedulesJsonReader jsonReader = new TrackedSchedulesJsonReaderImpl("/schedules");
List<ScheduleRecord> records = jsonReader.records();
- assertEquals(9, records.size());
+ assertEquals(10, records.size());
ScheduleRecord iptScheduleRecord = findRecord("IPTI Schedule", records);
ScheduleRecord eddScheduleRecord = findRecord("Delivery", records);
List<MilestoneRecord> milestoneRecords = iptScheduleRecord.milestoneRecords();
assertEquals(2, milestoneRecords.size());
assertEquals("IPTI 1", milestoneRecords.get(0).name());
assertEquals("IPTI 2", milestoneRecords.get(1).name());
milestoneRecords = eddScheduleRecord.milestoneRecords();
assertEquals(1, milestoneRecords.size());
assertEquals("Default", milestoneRecords.get(0).name());
}
@Test
public void shouldReadEmptyValues() {
TrackedSchedulesJsonReader jsonReader = new TrackedSchedulesJsonReaderImpl("/schedules");
List<ScheduleRecord> records = jsonReader.records();
ScheduleRecord scheduleRecord = findRecord("IPTI Schedule", records);
MilestoneRecord secondMilestone = scheduleRecord.milestoneRecords().get(1);
assertEquals("", secondMilestone.scheduleWindowsRecord().max().get(0));
}
@Test
public void shouldBeAbleReadJsonFilesFromADirectory() {
assertNotNull(new TrackedSchedulesJsonReaderImpl("/schedules").records());
}
private ScheduleRecord findRecord(String name, List<ScheduleRecord> records) {
for (ScheduleRecord record : records)
if (record.name().equals(name))
return record;
return null;
}
}
| true | true | public void shouldReadTheScheduleJsonFileCorrectly() {
TrackedSchedulesJsonReader jsonReader = new TrackedSchedulesJsonReaderImpl("/schedules");
List<ScheduleRecord> records = jsonReader.records();
assertEquals(9, records.size());
ScheduleRecord iptScheduleRecord = findRecord("IPTI Schedule", records);
ScheduleRecord eddScheduleRecord = findRecord("Delivery", records);
List<MilestoneRecord> milestoneRecords = iptScheduleRecord.milestoneRecords();
assertEquals(2, milestoneRecords.size());
assertEquals("IPTI 1", milestoneRecords.get(0).name());
assertEquals("IPTI 2", milestoneRecords.get(1).name());
milestoneRecords = eddScheduleRecord.milestoneRecords();
assertEquals(1, milestoneRecords.size());
assertEquals("Default", milestoneRecords.get(0).name());
}
| public void shouldReadTheScheduleJsonFileCorrectly() {
TrackedSchedulesJsonReader jsonReader = new TrackedSchedulesJsonReaderImpl("/schedules");
List<ScheduleRecord> records = jsonReader.records();
assertEquals(10, records.size());
ScheduleRecord iptScheduleRecord = findRecord("IPTI Schedule", records);
ScheduleRecord eddScheduleRecord = findRecord("Delivery", records);
List<MilestoneRecord> milestoneRecords = iptScheduleRecord.milestoneRecords();
assertEquals(2, milestoneRecords.size());
assertEquals("IPTI 1", milestoneRecords.get(0).name());
assertEquals("IPTI 2", milestoneRecords.get(1).name());
milestoneRecords = eddScheduleRecord.milestoneRecords();
assertEquals(1, milestoneRecords.size());
assertEquals("Default", milestoneRecords.get(0).name());
}
|
diff --git a/errai-demos/errai-jpa-demo-todo-list/src/main/java/org/jboss/errai/demo/todo/server/SchemaFixer.java b/errai-demos/errai-jpa-demo-todo-list/src/main/java/org/jboss/errai/demo/todo/server/SchemaFixer.java
index 537552d8a..3ff8e5348 100644
--- a/errai-demos/errai-jpa-demo-todo-list/src/main/java/org/jboss/errai/demo/todo/server/SchemaFixer.java
+++ b/errai-demos/errai-jpa-demo-todo-list/src/main/java/org/jboss/errai/demo/todo/server/SchemaFixer.java
@@ -1,29 +1,29 @@
package org.jboss.errai.demo.todo.server;
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;
@Startup @Singleton
public class SchemaFixer {
@Inject EntityManager em;
@PostConstruct
public void alterSchemaIfNeeded() {
System.out.println("Checking if schema needs update...");
- Query schemaCheck = em.createNativeQuery("SELECT 1 FROM information_schema.columns WHERE table_name='todolist_user' AND column_name='password'");
+ Query schemaCheck = em.createNativeQuery("SELECT 1 FROM information_schema.columns WHERE lower(table_name)='todolist_user' AND lower(column_name)='password'");
if (schemaCheck.getResultList().isEmpty()) {
System.out.println("Attempting to add password column...");
Query ddlStmt = em.createNativeQuery("ALTER TABLE todolist_user ADD COLUMN password VARCHAR(100)");
ddlStmt.executeUpdate();
}
else {
System.out.println("Schema is up to date.");
}
}
}
| true | true | public void alterSchemaIfNeeded() {
System.out.println("Checking if schema needs update...");
Query schemaCheck = em.createNativeQuery("SELECT 1 FROM information_schema.columns WHERE table_name='todolist_user' AND column_name='password'");
if (schemaCheck.getResultList().isEmpty()) {
System.out.println("Attempting to add password column...");
Query ddlStmt = em.createNativeQuery("ALTER TABLE todolist_user ADD COLUMN password VARCHAR(100)");
ddlStmt.executeUpdate();
}
else {
System.out.println("Schema is up to date.");
}
}
| public void alterSchemaIfNeeded() {
System.out.println("Checking if schema needs update...");
Query schemaCheck = em.createNativeQuery("SELECT 1 FROM information_schema.columns WHERE lower(table_name)='todolist_user' AND lower(column_name)='password'");
if (schemaCheck.getResultList().isEmpty()) {
System.out.println("Attempting to add password column...");
Query ddlStmt = em.createNativeQuery("ALTER TABLE todolist_user ADD COLUMN password VARCHAR(100)");
ddlStmt.executeUpdate();
}
else {
System.out.println("Schema is up to date.");
}
}
|
diff --git a/src/com/menny/android/anysoftkeyboard/MainForm.java b/src/com/menny/android/anysoftkeyboard/MainForm.java
index ef9847c5..01f54e40 100644
--- a/src/com/menny/android/anysoftkeyboard/MainForm.java
+++ b/src/com/menny/android/anysoftkeyboard/MainForm.java
@@ -1,36 +1,36 @@
package com.menny.android.anysoftkeyboard;
import android.app.TabActivity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.util.Log;
import android.widget.TabHost;
import android.widget.TextView;
public class MainForm extends TabActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String version = "";
try {
PackageInfo info = super.getApplication().getPackageManager().getPackageInfo(getApplication().getPackageName(), 0);
version = info.versionName + " (release "+info.versionCode+")";
} catch (NameNotFoundException e) {
Log.e("AnySoftKeyboard", "Failed to locate package information! This is very weird... I'm installed.");
}
TextView label = (TextView)super.findViewById(R.id.main_title_version);
- label.setText(label.getText()+version);
+ label.setText(version);
TabHost mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator(getString(R.string.main_tab_welcome)).setContent(R.id.main_tab1));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator(getString(R.string.main_tab_links)).setContent(R.id.main_tab2));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator(getString(R.string.main_tab_credits)).setContent(R.id.main_tab3));
mTabHost.setCurrentTab(0);
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String version = "";
try {
PackageInfo info = super.getApplication().getPackageManager().getPackageInfo(getApplication().getPackageName(), 0);
version = info.versionName + " (release "+info.versionCode+")";
} catch (NameNotFoundException e) {
Log.e("AnySoftKeyboard", "Failed to locate package information! This is very weird... I'm installed.");
}
TextView label = (TextView)super.findViewById(R.id.main_title_version);
label.setText(label.getText()+version);
TabHost mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator(getString(R.string.main_tab_welcome)).setContent(R.id.main_tab1));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator(getString(R.string.main_tab_links)).setContent(R.id.main_tab2));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator(getString(R.string.main_tab_credits)).setContent(R.id.main_tab3));
mTabHost.setCurrentTab(0);
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String version = "";
try {
PackageInfo info = super.getApplication().getPackageManager().getPackageInfo(getApplication().getPackageName(), 0);
version = info.versionName + " (release "+info.versionCode+")";
} catch (NameNotFoundException e) {
Log.e("AnySoftKeyboard", "Failed to locate package information! This is very weird... I'm installed.");
}
TextView label = (TextView)super.findViewById(R.id.main_title_version);
label.setText(version);
TabHost mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator(getString(R.string.main_tab_welcome)).setContent(R.id.main_tab1));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator(getString(R.string.main_tab_links)).setContent(R.id.main_tab2));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator(getString(R.string.main_tab_credits)).setContent(R.id.main_tab3));
mTabHost.setCurrentTab(0);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.