diff
stringlengths
164
2.11M
is_single_chunk
bool
2 classes
is_single_function
bool
2 classes
buggy_function
stringlengths
0
335k
fixed_function
stringlengths
23
335k
diff --git a/src/main/java/nl/tweeenveertig/openstack/client/mock/StoredObjectMock.java b/src/main/java/nl/tweeenveertig/openstack/client/mock/StoredObjectMock.java index b927ffd..105d232 100644 --- a/src/main/java/nl/tweeenveertig/openstack/client/mock/StoredObjectMock.java +++ b/src/main/java/nl/tweeenveertig/openstack/client/mock/StoredObjectMock.java @@ -1,168 +1,168 @@ package nl.tweeenveertig.openstack.client.mock; import nl.tweeenveertig.openstack.client.Container; import nl.tweeenveertig.openstack.headers.object.Etag; import nl.tweeenveertig.openstack.headers.object.ObjectContentLength; import nl.tweeenveertig.openstack.headers.object.ObjectContentType; import nl.tweeenveertig.openstack.headers.object.ObjectLastModified; import nl.tweeenveertig.openstack.model.DownloadInstructions; import nl.tweeenveertig.openstack.model.UploadInstructions; import nl.tweeenveertig.openstack.client.StoredObject; import nl.tweeenveertig.openstack.client.core.AbstractStoredObject; import nl.tweeenveertig.openstack.command.core.CommandException; import nl.tweeenveertig.openstack.command.core.CommandExceptionError; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.IOUtils; import org.apache.http.HttpStatus; import org.apache.http.impl.cookie.DateUtils; import javax.activation.MimetypesFileTypeMap; import java.io.*; import java.util.Date; public class StoredObjectMock extends AbstractStoredObject { private boolean created = false; private byte[] object; public StoredObjectMock(Container container, String name) { super(container, name); } @Override protected void getInfo() { this.info.setEtag(new Etag(object == null ? "" : DigestUtils.md5Hex(object))); this.info.setContentType(new ObjectContentType(new MimetypesFileTypeMap().getContentType(getName()))); this.info.setContentLength(new ObjectContentLength(Long.toString(object == null ? 0 : object.length))); } public InputStream downloadObjectAsInputStream() { return downloadObjectAsInputStream(new DownloadInstructions()); } public InputStream downloadObjectAsInputStream(DownloadInstructions downloadInstructions) { - return new MockInputStreamWrapper(new ByteArrayInputStream(downloadObject())); + return new MockInputStreamWrapper(new ByteArrayInputStream(downloadObject(downloadInstructions))); } public byte[] downloadObject() { return downloadObject(new DownloadInstructions()); } public byte[] downloadObject(DownloadInstructions downloadInstructions) { if (downloadInstructions.getRange() != null) { return downloadInstructions.getRange().copy(object); } if (downloadInstructions.getMatchConditional() != null) { downloadInstructions.getMatchConditional().matchAgainst(info.getEtag()); } if (downloadInstructions.getSinceConditional() != null) { downloadInstructions.getSinceConditional().sinceAgainst(info.getLastModifiedAsDate()); } return object; } public void downloadObject(File targetFile) { downloadObject(targetFile, new DownloadInstructions()); } public void downloadObject(File targetFile, DownloadInstructions downloadInstructions) { InputStream is = null; OutputStream os = null; try { - is = new ByteArrayInputStream(downloadObject()); + is = new ByteArrayInputStream(downloadObject(downloadInstructions)); os = new FileOutputStream(targetFile); IOUtils.copy(is, os); } catch (IOException err) { throw new CommandException("IO Failure", err); } finally { if (os != null) try { os.close(); } catch (IOException logOrIgnore) {} if (is != null) try { is.close(); } catch (IOException logOrIgnore) {} } } public void uploadObject(UploadInstructions uploadInstructions) { if (!this.created) { ((ContainerMock)getContainer()).createObject(this); this.created = true; } try { saveObject(IOUtils.toByteArray(uploadInstructions.getEntity().getContent())); } catch (IOException err) { throw new CommandException(err.getMessage()); } } public void uploadObject(InputStream inputStream) { try { this.uploadObject(IOUtils.toByteArray(inputStream)); } catch (IOException err) { throw new CommandException("Unable to convert inputstream to byte[]", err); } } public void uploadObject(byte[] fileToUpload) { uploadObject(new UploadInstructions(fileToUpload)); } public void uploadObject(File fileToUpload) { InputStream is = null; OutputStream os = null; try { // When doing a mime type check, this would be the right place to do it is = new FileInputStream(fileToUpload); os = new ByteArrayOutputStream(); IOUtils.copy(is, os); uploadObject(((ByteArrayOutputStream)os).toByteArray()); } catch (IOException err) { throw new CommandException("IO Failure", err); } finally { if (os != null) try { os.close(); } catch (IOException logOrIgnore) {} if (is != null) try { is.close(); } catch (IOException logOrIgnore) {} } } public void delete() { if (!this.created) { throw new CommandException(HttpStatus.SC_NOT_FOUND, CommandExceptionError.CONTAINER_OR_OBJECT_DOES_NOT_EXIST); } ((ContainerMock)getContainer()).deleteObject(this); invalidate(); } public void copyObject(Container targetContainer, StoredObject targetObject) { byte[] targetContent = object.clone(); if (!targetContainer.exists()) { targetContainer.create(); } targetObject.uploadObject(targetContent); } public void setContentType(String contentType) { info.setContentType(new ObjectContentType(contentType)); } public String getPublicURL() { return ""; } protected void saveObject(byte[] object) { this.object = object; this.info.setLastModified(new ObjectLastModified(new Date())); invalidate(); } public void invalidate() { ((ContainerMock)getContainer()).invalidate(); super.invalidate(); } @Override protected void saveMetadata() {} // no action necessary @Override public boolean exists() { return super.exists() && created; } }
false
false
null
null
diff --git a/jaxrs/providers/resteasy-validator-provider-11/src/main/java/org/jboss/resteasy/plugins/validation/GeneralValidatorImpl.java b/jaxrs/providers/resteasy-validator-provider-11/src/main/java/org/jboss/resteasy/plugins/validation/GeneralValidatorImpl.java index 09c3bda96..5525eaf6e 100755 --- a/jaxrs/providers/resteasy-validator-provider-11/src/main/java/org/jboss/resteasy/plugins/validation/GeneralValidatorImpl.java +++ b/jaxrs/providers/resteasy-validator-provider-11/src/main/java/org/jboss/resteasy/plugins/validation/GeneralValidatorImpl.java @@ -1,586 +1,587 @@ package org.jboss.resteasy.plugins.validation; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.MessageInterpolator; import javax.validation.ValidationException; import javax.validation.Validator; import javax.validation.ValidatorFactory; import javax.validation.executable.ExecutableType; import javax.validation.executable.ValidateOnExecution; import org.jboss.resteasy.api.validation.ResteasyConstraintViolation; import org.jboss.resteasy.api.validation.ConstraintType.Type; import org.jboss.resteasy.api.validation.ResteasyViolationException; import org.jboss.resteasy.plugins.providers.validation.ConstraintTypeUtil; import org.jboss.resteasy.plugins.providers.validation.ViolationsContainer; import org.jboss.resteasy.spi.HttpRequest; import org.jboss.resteasy.spi.validation.GeneralValidator; import com.fasterxml.classmate.Filter; import com.fasterxml.classmate.MemberResolver; import com.fasterxml.classmate.ResolvedType; import com.fasterxml.classmate.ResolvedTypeWithMembers; import com.fasterxml.classmate.TypeResolver; import com.fasterxml.classmate.members.RawMethod; import com.fasterxml.classmate.members.ResolvedMethod; /** * * @author <a href="[email protected]">Ron Sigal</a> * @version $Revision: 1.1 $ * * Copyright May 23, 2013 */ public class GeneralValidatorImpl implements GeneralValidator { /** * Used for resolving type parameters. Thread-safe. */ private TypeResolver typeResolver = new TypeResolver(); private ValidatorFactory validatorFactory; private Validator defaultValidator; private Map<Locale, Validator> validators = new HashMap<Locale, Validator>(); private Locale.Builder localeBuilder = new Locale.Builder(); private ConstraintTypeUtil util = new ConstraintTypeUtil11(); private boolean isExecutableValidationEnabled; private ExecutableType[] defaultValidatedExecutableTypes; public GeneralValidatorImpl(ValidatorFactory validatorFactory, boolean isExecutableValidationEnabled, Set<ExecutableType> defaultValidatedExecutableTypes) { this.validatorFactory = validatorFactory; this.isExecutableValidationEnabled = isExecutableValidationEnabled; this.defaultValidatedExecutableTypes = defaultValidatedExecutableTypes.toArray(new ExecutableType[]{}); } @Override public void validate(HttpRequest request, Object object, Class<?>... groups) { installValidator(request); Set<ResteasyConstraintViolation> rcvs = new HashSet<ResteasyConstraintViolation>(); try { Set<ConstraintViolation<Object>> cvs = getValidator(request).validate(object, groups); for (Iterator<ConstraintViolation<Object>> it = cvs.iterator(); it.hasNext(); ) { ConstraintViolation<Object> cv = it.next(); Type ct = util.getConstraintType(cv); Object o = cv.getInvalidValue(); String value = (o == null ? "" : o.toString()); rcvs.add(new ResteasyConstraintViolation(ct, cv.getPropertyPath().toString(), cv.getMessage(), value)); } } catch (Exception e) { ViolationsContainer<Object> violationsContainer = getViolationsContainer(request); violationsContainer.setException(e); throw new ResteasyViolationException(violationsContainer); } ViolationsContainer<Object> violationsContainer = getViolationsContainer(request); violationsContainer.addViolations(rcvs); } protected ViolationsContainer<Object> getViolationsContainer(HttpRequest request) { @SuppressWarnings("unchecked") ViolationsContainer<Object> violationsContainer = ViolationsContainer.class.cast(request.getAttribute(ViolationsContainer.class.getName())); if (violationsContainer == null) { violationsContainer = new ViolationsContainer<Object>(); request.setAttribute(ViolationsContainer.class.getName(), violationsContainer); } return violationsContainer; } @Override public void checkViolations(HttpRequest request) { @SuppressWarnings("unchecked") ViolationsContainer<Object> violationsContainer = ViolationsContainer.class.cast(request.getAttribute(ViolationsContainer.class.getName())); if (violationsContainer != null && violationsContainer.size() > 0) { throw new ResteasyViolationException(violationsContainer, request.getHttpHeaders().getAcceptableMediaTypes()); } } @Override public void validateAllParameters(HttpRequest request, Object object, Method method, Object[] parameterValues, Class<?>... groups) { if (method.getParameterTypes().length == 0) { checkViolations(request); return; } installValidator(request); ViolationsContainer<Object> violationsContainer = getViolationsContainer(request); Set<ResteasyConstraintViolation> rcvs = new HashSet<ResteasyConstraintViolation>(); try { Set<ConstraintViolation<Object>> cvs = getValidator(request).forExecutables().validateParameters(object, method, parameterValues, groups); for (Iterator<ConstraintViolation<Object>> it = cvs.iterator(); it.hasNext(); ) { ConstraintViolation<Object> cv = it.next(); Type ct = util.getConstraintType(cv); rcvs.add(new ResteasyConstraintViolation(ct, cv.getPropertyPath().toString(), cv.getMessage(), convertArrayToString(cv.getInvalidValue()))); } } catch (Exception e) { violationsContainer.setException(e); throw new ResteasyViolationException(violationsContainer); } violationsContainer.addViolations(rcvs); if (violationsContainer.size() > 0) { throw new ResteasyViolationException(violationsContainer, request.getHttpHeaders().getAcceptableMediaTypes()); } } @Override public void validateReturnValue(HttpRequest request, Object object, Method method, Object returnValue, Class<?>... groups) { installValidator(request); Set<ResteasyConstraintViolation> rcvs = new HashSet<ResteasyConstraintViolation>(); ViolationsContainer<Object> violationsContainer = getViolationsContainer(request); try { Set<ConstraintViolation<Object>> cvs = getValidator(request).forExecutables().validateReturnValue(object, method, returnValue, groups); for (Iterator<ConstraintViolation<Object>> it = cvs.iterator(); it.hasNext(); ) { ConstraintViolation<Object> cv = it.next(); Type ct = util.getConstraintType(cv); Object o = cv.getInvalidValue(); String value = (o == null ? "" : o.toString()); rcvs.add(new ResteasyConstraintViolation(ct, cv.getPropertyPath().toString(), cv.getMessage(), value)); } } catch (Exception e) { violationsContainer.setException(e); throw new ResteasyViolationException(violationsContainer); } violationsContainer.addViolations(rcvs); if (violationsContainer.size() > 0) { throw new ResteasyViolationException(violationsContainer, request.getHttpHeaders().getAcceptableMediaTypes()); } } @Override public boolean isValidatable(Class<?> clazz) { return true; } @Override public boolean isMethodValidatable(Method m) { if (!isExecutableValidationEnabled) { return false; } ExecutableType[] types = null; List<ExecutableType[]> typesList = getExecutableTypesOnMethodInHierarchy(m); if (typesList.size() > 1) { throw new ValidationException("@ValidateOnExecution found on multiple overridden methods"); } if (typesList.size() == 1) { types = typesList.get(0); } else { ValidateOnExecution voe = m.getDeclaringClass().getAnnotation(ValidateOnExecution.class); if (voe == null) { types = defaultValidatedExecutableTypes; } else { if (voe.type().length > 0) { types = voe.type(); } else { types = defaultValidatedExecutableTypes; } } } boolean isGetterMethod = isGetter(m); for (int i = 0; i < types.length; i++) { switch (types[i]) { case IMPLICIT: case ALL: return true; case NONE: continue; case NON_GETTER_METHODS: if (!isGetterMethod) { return true; } continue; case GETTER_METHODS: if (isGetterMethod) { return true; } continue; default: continue; } } return false; } protected List<ExecutableType[]> getExecutableTypesOnMethodInHierarchy(Method method) { Class<?> clazz = method.getDeclaringClass(); List<ExecutableType[]> typesList = new ArrayList<ExecutableType[]>(); while (clazz != null) { // We start by examining the method itself. Method superMethod = getSuperMethod(method, clazz); if (superMethod != null) { ExecutableType[] types = getExecutableTypesOnMethod(superMethod); if (types != null) { typesList.add(types); } } typesList.addAll(getExecutableTypesOnMethodInInterfaces(clazz, method)); clazz = clazz.getSuperclass(); } return typesList; } protected List<ExecutableType[]> getExecutableTypesOnMethodInInterfaces(Class<?> clazz, Method method) { List<ExecutableType[]> typesList = new ArrayList<ExecutableType[]>(); Class<?>[] interfaces = clazz.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { Method interfaceMethod = getSuperMethod(method, interfaces[i]); if (interfaceMethod != null) { ExecutableType[] types = getExecutableTypesOnMethod(interfaceMethod); if (types != null) { typesList.add(types); } } List<ExecutableType[]> superList = getExecutableTypesOnMethodInInterfaces(interfaces[i], method); if (superList.size() > 0) { typesList.addAll(superList); } } return typesList; } static protected ExecutableType[] getExecutableTypesOnMethod(Method method) { ValidateOnExecution voe = method.getAnnotation(ValidateOnExecution.class); if (voe == null || voe.type().length == 0) { return null; } ExecutableType[] types = voe.type(); if (types == null || types.length == 0) { return null; } return types; } static protected boolean isGetter(Method m) { String name = m.getName(); Class<?> returnType = m.getReturnType(); if (returnType.equals(Void.class)) { return false; } if (m.getParameterTypes().length > 0) { return false; } if (name.startsWith("get")) { return true; } if (name.startsWith("is") && returnType.equals(boolean.class)) { return true; } return false; } static protected String convertArrayToString(Object o) { String result = null; if (o instanceof Object[]) { Object[] array = Object[].class.cast(o); StringBuffer sb = new StringBuffer("[").append(convertArrayToString(array[0])); for (int i = 1; i < array.length; i++) { sb.append(", ").append(convertArrayToString(array[i])); } sb.append("]"); result = sb.toString(); } else { result = (o == null ? "" : o.toString()); } return result; } /** * Returns a super method, if any, of a method in a class. * Here, the "super" relationship is reflexive. That is, a method * is a super method of itself. */ protected Method getSuperMethod(Method method, Class<?> clazz) { Method[] methods = clazz.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { if (overrides(method, methods[i])) { return methods[i]; } } return null; } /** * Checks, whether {@code subTypeMethod} overrides {@code superTypeMethod}. * * N.B. "Override" here is reflexive. I.e., a method overrides itself. * * @param subTypeMethod The sub type method (cannot be {@code null}). * @param superTypeMethod The super type method (cannot be {@code null}). * * @return Returns {@code true} if {@code subTypeMethod} overrides {@code superTypeMethod}, {@code false} otherwise. * * Taken from Hibernate Validator */ protected boolean overrides(Method subTypeMethod, Method superTypeMethod) { if (subTypeMethod == null || superTypeMethod == null) { throw new RuntimeException("Expect two non-null methods"); } if (!subTypeMethod.getName().equals(superTypeMethod.getName())) { return false; } if (subTypeMethod.getParameterTypes().length != superTypeMethod.getParameterTypes().length) { return false; } if (!superTypeMethod.getDeclaringClass().isAssignableFrom(subTypeMethod.getDeclaringClass())) { return false; } return parametersResolveToSameTypes(subTypeMethod, superTypeMethod); } /** * Taken from Hibernate Validator */ protected boolean parametersResolveToSameTypes(Method subTypeMethod, Method superTypeMethod) { if (subTypeMethod.getParameterTypes().length == 0) { return true; } ResolvedType resolvedSubType = typeResolver.resolve(subTypeMethod.getDeclaringClass()); MemberResolver memberResolver = new MemberResolver(typeResolver); memberResolver.setMethodFilter(new SimpleMethodFilter(subTypeMethod, superTypeMethod)); ResolvedTypeWithMembers typeWithMembers = memberResolver.resolve(resolvedSubType, null, null); ResolvedMethod[] resolvedMethods = typeWithMembers.getMemberMethods(); // The ClassMate doc says that overridden methods are flattened to one // resolved method. But that is the case only for methods without any // generic parameters. if (resolvedMethods.length == 1) { return true; } // For methods with generic parameters I have to compare the argument // types (which are resolved) of the two filtered member methods. for (int i = 0; i < resolvedMethods[0].getArgumentCount(); i++) { if (!resolvedMethods[0].getArgumentType(i).equals(resolvedMethods[1].getArgumentType(i))) { return false; } } return true; } protected void installValidator(HttpRequest request) { Locale locale = getLocale(request); if (locale == null) { if (defaultValidator == null) { defaultValidator = validatorFactory.getValidator(); } return; } if (validators.get(locale) != null) { return; } // Check for /ValidationMessages_XX.properties ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); String localeStr = locale.toString(); URL validationMessagesURL = classLoader.getResource("/ValidationMessages_" + localeStr + ".properties"); if (validationMessagesURL == null) { if (localeStr.length() == 2) { // a locale like "de" isn't supported: use default locale if (defaultValidator == null) { defaultValidator = validatorFactory.getValidator(); } return; } - - // if e.g. "en_US" isn't supported, then try "en" - localeStr = localeStr.substring(0, 2); - validationMessagesURL = classLoader.getResource("/ValidationMessages_" + localeStr + ".properties"); - if (validationMessagesURL == null) - { - if (defaultValidator == null) - { - defaultValidator = validatorFactory.getValidator(); - } - return; - } - - // E.g. /ValidationMessages_en.properties is available, and accept-language=en_US is used - // Therefore use the locale "en", and not the default locale - locale = localeBuilder.setLanguage(localeStr).build(); + if(localeStr.length() > 2) { + // if e.g. "en_US" isn't supported, then try "en" + localeStr = localeStr.substring(0, 2); + validationMessagesURL = classLoader.getResource("/ValidationMessages_" + localeStr + ".properties"); + if (validationMessagesURL == null) + { + if (defaultValidator == null) + { + defaultValidator = validatorFactory.getValidator(); + } + return; + } + + // E.g. /ValidationMessages_en.properties is available, and accept-language=en_US is used + // Therefore use the locale "en", and not the default locale + locale = localeBuilder.setLanguage(localeStr).build(); + } } MessageInterpolator interpolator = new LocaleSpecificMessageInterpolator(validatorFactory.getMessageInterpolator(), locale); Validator validator = validatorFactory.usingContext().messageInterpolator(interpolator).getValidator(); validators.put(locale, validator); } private Validator getValidator(HttpRequest request) { Locale locale = getLocale(request); if (locale == null) { return defaultValidator; } Validator validator = validators.get(locale); if (validator == null) { // if e.g. "en_US" isn't supported, then try "en" String localeStr = locale.toString(); if (localeStr.length() > 2) { localeStr = localeStr.substring(0, 2); validator = validators.get(localeBuilder.setLanguage(localeStr).build()); } } return validator == null ? defaultValidator : validator; } private Locale getLocale(HttpRequest request) { List<Locale> locales = request.getHttpHeaders().getAcceptableLanguages(); Locale locale = locales == null || locales.isEmpty() ? null : locales.get(0); return locale; } /** * A filter implementation filtering methods matching given methods. * * @author Gunnar Morling * * Taken from Hibernate Validator */ static protected class SimpleMethodFilter implements Filter<RawMethod> { private final Method method1; private final Method method2; private SimpleMethodFilter(Method method1, Method method2) { this.method1 = method1; this.method2 = method2; } @Override public boolean include(RawMethod element) { return element.getRawMember().equals(method1) || element.getRawMember().equals(method2); } } static protected class LocaleSpecificMessageInterpolator implements MessageInterpolator { private final MessageInterpolator interpolator; private final Locale locale; public LocaleSpecificMessageInterpolator(MessageInterpolator interpolator, Locale locale) { this.interpolator = interpolator; this.locale = locale; } @Override public String interpolate(String messageTemplate, Context context) { return interpolator.interpolate(messageTemplate, context, locale); } @Override public String interpolate(String messageTemplate, Context context, Locale locale) { return interpolator.interpolate(messageTemplate, context, locale); } } }
true
false
null
null
diff --git a/jetty/src/main/java/org/jboss/errai/cdi/server/gwt/JettyLauncher.java b/jetty/src/main/java/org/jboss/errai/cdi/server/gwt/JettyLauncher.java index 023cb137f..655b27ce0 100644 --- a/jetty/src/main/java/org/jboss/errai/cdi/server/gwt/JettyLauncher.java +++ b/jetty/src/main/java/org/jboss/errai/cdi/server/gwt/JettyLauncher.java @@ -1,557 +1,557 @@ /* * Copyright 2008 Google 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 org.jboss.errai.cdi.server.gwt; import com.google.gwt.core.ext.ServletContainer; import com.google.gwt.core.ext.ServletContainerLauncher; import com.google.gwt.core.ext.TreeLogger; import com.google.gwt.core.ext.UnableToCompleteException; import com.google.gwt.dev.shell.jetty.JettyNullLogger; import com.google.gwt.dev.util.InstalledHelpInfo; import org.jboss.errai.bus.server.service.ServiceLocator; import org.jboss.errai.bus.server.servlet.AbstractErraiServlet; import org.jboss.errai.bus.server.servlet.DefaultBlockingServlet; import org.jboss.errai.bus.server.servlet.JettyContinuationsServlet; import org.mortbay.component.AbstractLifeCycle; import org.mortbay.jetty.*; import org.mortbay.jetty.HttpFields.Field; import org.mortbay.jetty.handler.RequestLogHandler; import org.mortbay.jetty.nio.SelectChannelConnector; import org.mortbay.jetty.webapp.WebAppClassLoader; import org.mortbay.jetty.webapp.WebAppContext; import org.mortbay.log.Log; import org.mortbay.log.Logger; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Iterator; /** * A {@link ServletContainerLauncher} for an embedded Jetty server. */ public class JettyLauncher extends ServletContainerLauncher { private static String[] __dftConfigurationClasses = { "org.mortbay.jetty.webapp.WebInfConfiguration", // "org.mortbay.jetty.plus.webapp.EnvConfiguration",//jetty-env "org.mortbay.jetty.plus.webapp.Configuration", //web.xml "org.mortbay.jetty.webapp.JettyWebXmlConfiguration",//jettyWeb }; /** * Log jetty requests/responses to TreeLogger. */ public static class JettyRequestLogger extends AbstractLifeCycle implements RequestLog { private final TreeLogger logger; public JettyRequestLogger(TreeLogger logger) { this.logger = logger; } /** * Log an HTTP request/response to TreeLogger. */ @SuppressWarnings("unchecked") public void log(Request request, Response response) { int status = response.getStatus(); if (status < 0) { // Copied from NCSARequestLog status = 404; } TreeLogger.Type logStatus, logHeaders; if (status >= 500) { logStatus = TreeLogger.ERROR; logHeaders = TreeLogger.INFO; } else if (status >= 400) { logStatus = TreeLogger.WARN; logHeaders = TreeLogger.INFO; } else { logStatus = TreeLogger.INFO; logHeaders = TreeLogger.DEBUG; } String userString = request.getRemoteUser(); if (userString == null) { userString = ""; } else { userString += "@"; } String bytesString = ""; if (response.getContentCount() > 0) { bytesString = " " + response.getContentCount() + " bytes"; } if (logger.isLoggable(logStatus)) { TreeLogger branch = logger.branch(logStatus, String.valueOf(status) + " - " + request.getMethod() + ' ' + request.getUri() + " (" + userString + request.getRemoteHost() + ')' + bytesString); if (branch.isLoggable(logHeaders)) { // Request headers TreeLogger headers = branch.branch(logHeaders, "Request headers"); Iterator<Field> headerFields = request.getConnection().getRequestFields().getFields(); while (headerFields.hasNext()) { Field headerField = headerFields.next(); headers.log(logHeaders, headerField.getName() + ": " + headerField.getValue()); } // Response headers headers = branch.branch(logHeaders, "Response headers"); headerFields = response.getHttpFields().getFields(); while (headerFields.hasNext()) { Field headerField = headerFields.next(); headers.log(logHeaders, headerField.getName() + ": " + headerField.getValue()); } } } } } /** * An adapter for the Jetty logging system to GWT's TreeLogger. This * implementation class is only public to allow {@link Log} to instantiate it. * <p/> * The weird static data / default construction setup is a game we play with * {@link Log}'s static initializer to prevent the initial log message from * going to stderr. */ public static class JettyTreeLogger implements Logger { private final TreeLogger logger; public JettyTreeLogger(TreeLogger logger) { if (logger == null) { throw new NullPointerException(); } this.logger = logger; } public void debug(String msg, Object arg0, Object arg1) { logger.log(TreeLogger.SPAM, format(msg, arg0, arg1)); } public void debug(String msg, Throwable th) { logger.log(TreeLogger.SPAM, msg, th); } public Logger getLogger(String name) { return this; } public void info(String msg, Object arg0, Object arg1) { logger.log(TreeLogger.INFO, format(msg, arg0, arg1)); } public boolean isDebugEnabled() { return logger.isLoggable(TreeLogger.SPAM); } public void setDebugEnabled(boolean enabled) { // ignored } public void warn(String msg, Object arg0, Object arg1) { logger.log(TreeLogger.WARN, format(msg, arg0, arg1)); } public void warn(String msg, Throwable th) { logger.log(TreeLogger.WARN, msg, th); } /** * Copied from org.mortbay.log.StdErrLog. */ private String format(String msg, Object arg0, Object arg1) { int i0 = msg.indexOf("{}"); int i1 = i0 < 0 ? -1 : msg.indexOf("{}", i0 + 2); if (arg1 != null && i1 >= 0) { msg = msg.substring(0, i1) + arg1 + msg.substring(i1 + 2); } if (arg0 != null && i0 >= 0) { msg = msg.substring(0, i0) + arg0 + msg.substring(i0 + 2); } return msg; } } /** * The resulting {@link ServletContainer} this is launched. */ protected static class JettyServletContainer extends ServletContainer { private final int actualPort; private final File appRootDir; private final TreeLogger logger; private final Server server; private final WebAppContext wac; public JettyServletContainer(TreeLogger logger, Server server, WebAppContext wac, int actualPort, File appRootDir) { this.logger = logger; this.server = server; this.wac = wac; this.actualPort = actualPort; this.appRootDir = appRootDir; } @Override public int getPort() { return actualPort; } @Override public void refresh() throws UnableToCompleteException { String msg = "Reloading web app to reflect changes in " + appRootDir.getAbsolutePath(); TreeLogger branch = logger.branch(TreeLogger.INFO, msg); // Temporarily log Jetty on the branch. Log.setLog(new JettyTreeLogger(branch)); try { wac.stop(); wac.start(); branch.log(TreeLogger.INFO, "Reload completed successfully"); } catch (Exception e) { branch.log(TreeLogger.ERROR, "Unable to restart embedded Jetty server", e); throw new UnableToCompleteException(); } finally { // Reset the top-level logger. Log.setLog(new JettyTreeLogger(logger)); } } @Override public void stop() throws UnableToCompleteException { TreeLogger branch = logger.branch(TreeLogger.INFO, "Stopping Jetty server"); // Temporarily log Jetty on the branch. Log.setLog(new JettyTreeLogger(branch)); try { server.stop(); server.setStopAtShutdown(false); branch.log(TreeLogger.INFO, "Stopped successfully"); } catch (Exception e) { branch.log(TreeLogger.ERROR, "Unable to stop embedded Jetty server", e); throw new UnableToCompleteException(); } finally { // Reset the top-level logger. Log.setLog(new JettyTreeLogger(logger)); } } } /** * A {@link WebAppContext} tailored to GWT hosted mode. Features hot-reload * with a new {@link WebAppClassLoader} to pick up disk changes. The default * Jetty {@code WebAppContext} will create new instances of servlets, but it * will not create a brand new {@link ClassLoader}. By creating a new {@code * ClassLoader} each time, we re-read updated classes from disk. * <p/> * Also provides special class filtering to isolate the web app from the GWT * hosting environment. */ protected static final class WebAppContextWithReload extends WebAppContext { /** * Specialized {@link WebAppClassLoader} that allows outside resources to be * brought in dynamically from the system path. A warning is issued when * this occurs. */ private class WebAppClassLoaderExtension extends WebAppClassLoader { private static final String META_INF_SERVICES = "META-INF/services/"; public WebAppClassLoaderExtension() throws IOException { super(bootStrapOnlyClassLoader, WebAppContextWithReload.this); } @Override public URL findResource(String name) { // Specifically for META-INF/services/javax.xml.parsers.SAXParserFactory String checkName = name; if (checkName.startsWith(META_INF_SERVICES)) { checkName = checkName.substring(META_INF_SERVICES.length()); } // For a system path, load from the outside world. URL found; if (isSystemPath(checkName)) { found = systemClassLoader.getResource(name); if (found != null) { return found; } } // Always check this ClassLoader first. found = super.findResource(name); if (found != null) { return found; } // See if the outside world has it. found = systemClassLoader.getResource(name); if (found == null) { return null; } // Warn, add containing URL to our own ClassLoader, and retry the call. String warnMessage = "Server resource '" + name + "' could not be found in the web app, but was found on the system classpath"; if (!addContainingClassPathEntry(warnMessage, found, name)) { return null; } return super.findResource(name); } /** * Override to additionally consider the most commonly available JSP and * XML implementation as system resources. (In fact, Jasper is in gwt-dev * via embedded Tomcat, so we always hit this case.) */ @Override public boolean isSystemPath(String name) { name = name.replace('/', '.'); return super.isSystemPath(name) || name.startsWith("org.apache.jasper.") || name.startsWith("org.apache.xerces."); } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { if ((name.startsWith("org.jboss.errai.bus.server.servlet.") - && !name.endsWith(ServiceLocator.class.getSimpleName()) + && !name.contains(ServiceLocator.class.getSimpleName()) && !name.contains(AbstractErraiServlet.class.getSimpleName()) - && !name.endsWith(JettyContinuationsServlet.class.getName()) - && !name.endsWith(DefaultBlockingServlet.class.getName())) || + && !name.contains(JettyContinuationsServlet.class.getName()) + && !name.contains(DefaultBlockingServlet.class.getName())) || name.equals("org.jboss.servlet.http.HttpEventServlet") || name.equals("org.apache.catalina.CometProcessor")) { return null; } // For system path, always prefer the outside world. if (isSystemPath(name)) { try { return systemClassLoader.loadClass(name); } catch (ClassNotFoundException e) { } } try { return super.findClass(name); } catch (ClassNotFoundException e) { // Don't allow server classes to be loaded from the outside. if (isServerPath(name)) { throw e; } } catch (NoClassDefFoundError e) { System.out.println(); } // See if the outside world has a URL for it. String resourceName = name.replace('.', '/') + ".class"; URL found = systemClassLoader.getResource(resourceName); if (found == null) { return null; } // Warn, add containing URL to our own ClassLoader, and retry the call. String warnMessage = "Server class '" + name + "' could not be found in the web app, but was found on the system classpath"; if (!addContainingClassPathEntry(warnMessage, found, resourceName)) { throw new ClassNotFoundException(name); } return super.findClass(name); } private boolean addContainingClassPathEntry(String warnMessage, URL resource, String resourceName) { TreeLogger.Type logLevel = (System.getProperty(PROPERTY_NOWARN_WEBAPP_CLASSPATH) == null) ? TreeLogger.WARN : TreeLogger.DEBUG; TreeLogger branch = logger.branch(logLevel, warnMessage); String classPathURL; String foundStr = resource.toExternalForm(); if (resource.getProtocol().equals("file")) { assert foundStr.endsWith(resourceName); classPathURL = foundStr.substring(0, foundStr.length() - resourceName.length()); } else if (resource.getProtocol().equals("jar")) { assert foundStr.startsWith("jar:"); assert foundStr.endsWith("!/" + resourceName); classPathURL = foundStr.substring(4, foundStr.length() - (2 + resourceName.length())); } else { branch.log(TreeLogger.ERROR, "Found resouce but unrecognized URL format: '" + foundStr + '\''); return false; } branch = branch.branch(logLevel, "Adding classpath entry '" + classPathURL + "' to the web app classpath for this session", null, new InstalledHelpInfo("webAppClassPath.html")); try { addClassPath(classPathURL); return true; } catch (IOException e) { branch.log(TreeLogger.ERROR, "Failed add container URL: '" + classPathURL + '\'', e); return false; } } } /** * Parent ClassLoader for the Jetty web app, which can only load JVM * classes. We would just use <code>null</code> for the parent ClassLoader * except this makes Jetty unhappy. */ private final ClassLoader bootStrapOnlyClassLoader = new ClassLoader(null) { }; private final TreeLogger logger; /** * In the usual case of launching {@link com.google.gwt.dev.DevMode}, * this will always by the system app ClassLoader. */ private final ClassLoader systemClassLoader = Thread.currentThread().getContextClassLoader(); @SuppressWarnings("unchecked") private WebAppContextWithReload(TreeLogger logger, String webApp, String contextPath) { super(webApp, contextPath); this.logger = logger; // Prevent file locking on Windows; pick up file changes. getInitParams().put( "org.mortbay.jetty.servlet.Default.useFileMappedBuffer", "false"); // Since the parent class loader is bootstrap-only, prefer it first. setParentLoaderPriority(true); } @Override protected void doStart() throws Exception { setClassLoader(new WebAppClassLoaderExtension()); super.doStart(); } @Override protected void doStop() throws Exception { super.doStop(); setClassLoader(null); } } /** * System property to suppress warnings about loading web app classes from the * system classpath. */ private static final String PROPERTY_NOWARN_WEBAPP_CLASSPATH = "gwt.nowarn.webapp.classpath"; static { // Suppress spammy Jetty log initialization. System.setProperty("org.mortbay.log.class", JettyNullLogger.class.getName()); Log.getLog(); /* * Make JDT the default Ant compiler so that JSP compilation just works * out-of-the-box. If we don't set this, it's very, very difficult to make * JSP compilation work. */ String antJavaC = System.getProperty("build.compiler", "org.eclipse.jdt.core.JDTCompilerAdapter"); System.setProperty("build.compiler", antJavaC); } @Override public String getIconPath() { return null; } @Override public String getName() { return "Jetty"; } @Override public ServletContainer start(TreeLogger logger, int port, File appRootDir) throws Exception { TreeLogger branch = logger.branch(TreeLogger.INFO, "Starting Jetty on port " + port, null); checkStartParams(branch, port, appRootDir); // Setup our branch logger during startup. Log.setLog(new JettyTreeLogger(branch)); // Turn off XML validation. System.setProperty("org.mortbay.xml.XmlParser.Validating", "false"); AbstractConnector connector = getConnector(); connector.setPort(port); // Don't share ports with an existing process. connector.setReuseAddress(false); // Linux keeps the port blocked after shutdown if we don't disable this. connector.setSoLingerTime(0); Server server = new Server(); server.addConnector(connector); // Create a new web app in the war directory. WebAppContext wac = new WebAppContextWithReload(logger, appRootDir.getAbsolutePath(), "/"); wac.setConfigurationClasses(__dftConfigurationClasses); RequestLogHandler logHandler = new RequestLogHandler(); logHandler.setRequestLog(new JettyRequestLogger(logger)); logHandler.setHandler(wac); server.setHandler(logHandler); server.start(); server.setStopAtShutdown(true); // Now that we're started, log to the top level logger. Log.setLog(new JettyTreeLogger(logger)); return new JettyServletContainer(logger, server, wac, connector.getLocalPort(), appRootDir); } protected AbstractConnector getConnector() { return new SelectChannelConnector(); } private void checkStartParams(TreeLogger logger, int port, File appRootDir) { if (logger == null) { throw new NullPointerException("logger cannot be null"); } if (port < 0 || port > 65535) { throw new IllegalArgumentException( "port must be either 0 (for auto) or less than 65536"); } if (appRootDir == null) { throw new NullPointerException("app root direcotry cannot be null"); } } }
false
false
null
null
diff --git a/src/main/java/net/codestory/http/templating/Template.java b/src/main/java/net/codestory/http/templating/Template.java index e9937c0..41c06b5 100644 --- a/src/main/java/net/codestory/http/templating/Template.java +++ b/src/main/java/net/codestory/http/templating/Template.java @@ -1,143 +1,143 @@ /** * Copyright (C) 2013 [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 net.codestory.http.templating; import static java.nio.charset.StandardCharsets.UTF_8; import java.io.*; import java.nio.charset.*; import java.nio.file.*; import java.util.*; import net.codestory.http.io.*; import com.github.mustachejava.*; public class Template { private final String url; public Template(String url) { this.url = url; } public String render() { return render(Collections.emptyMap()); } public String render(String key, Object value) { Map<String, Object> keyValues = new HashMap<>(); keyValues.put(key, value); return render(keyValues); } public String render(String k1, String v1, String k2, Object v2) { Map<String, Object> keyValues = new HashMap<>(); keyValues.put(k1, v1); keyValues.put(k2, v2); return render(keyValues); } public String render(String k1, Object v1, String k2, Object v2, String k3, Object v3) { Map<String, Object> keyValues = new HashMap<>(); keyValues.put(k1, v1); keyValues.put(k2, v2); keyValues.put(k3, v3); return render(keyValues); } public String render(String k1, Object v1, String k2, Object v2, String k3, Object v3, String k4, Object v4) { Map<String, Object> keyValues = new HashMap<>(); keyValues.put(k1, v1); keyValues.put(k2, v2); keyValues.put(k3, v3); keyValues.put(k4, v4); return render(keyValues); } public String render(Map<String, Object> keyValues) { DefaultMustacheFactory mustacheFactory = new DefaultMustacheFactory(); try { String templateContent = read(url); ContentWithVariables parsedTemplate = new YamlFrontMatter().parse(templateContent); String content = parsedTemplate.getContent(); Map<String, String> variables = parsedTemplate.getVariables(); Map<String, Object> allKeyValues = merge(keyValues, variables); Mustache mustache = mustacheFactory.compile(new StringReader(content), "", "[[", "]]"); Writer output = new StringWriter(); mustache.execute(output, allKeyValues).flush(); String body = output.toString(); if (variables.containsKey("layout")) { String layoutName = (String) allKeyValues.get("layout"); - allKeyValues.put("body", body); + allKeyValues.put("body", "[[body]]"); - return new Template(type(url) + layoutName).render(allKeyValues); + return new Template(type(url) + layoutName).render(allKeyValues).replace("[[body]]", body); } return body; } catch (IOException e) { throw new IllegalStateException("Unable to render template", e); } } private static Map<String, Object> merge(Map<String, Object> keyValues, Map<String, String> variables) { Map<String, Object> merged = new HashMap<>(); merged.putAll(keyValues); merged.putAll(variables); return merged; } private String read(String url) throws IOException { if (url.startsWith("classpath:")) { return readClasspath(url.substring(10)); } if (url.startsWith("file:")) { return readFile(url.substring(5)); } throw new IllegalArgumentException("Invalid path for static content. Should be prefixed by file: or classpath:"); } private String readClasspath(String path) throws IOException { if (ClassLoader.getSystemResourceAsStream(path) == null) { throw new IllegalArgumentException("Invalid classpath path: " + path); } return Resources.toString(path, UTF_8); } private String readFile(String path) throws IOException { if (!new File(path).exists()) { throw new IllegalArgumentException("Invalid file path: " + path); } return new String(Files.readAllBytes(Paths.get(path))); } // TEMP private String type(String url) throws IOException { if (url.startsWith("classpath:")) { return "classpath:"; } if (url.startsWith("file:")) { return "file:"; } throw new IllegalArgumentException("Invalid path for static content. Should be prefixed by file: or classpath:"); } } diff --git a/src/test/java/net/codestory/http/templating/TemplateTest.java b/src/test/java/net/codestory/http/templating/TemplateTest.java index 1890eec..4f34080 100644 --- a/src/test/java/net/codestory/http/templating/TemplateTest.java +++ b/src/test/java/net/codestory/http/templating/TemplateTest.java @@ -1,45 +1,45 @@ /** * Copyright (C) 2013 [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 net.codestory.http.templating; import static org.fest.assertions.Assertions.*; import java.util.*; import org.junit.*; public class TemplateTest { @Test public void render() { assertThat(new Template("classpath:web/0variable.txt").render()).isEqualTo("0 variables"); assertThat(new Template("classpath:web/1variable.txt").render("name", "Bob")).isEqualTo("Hello Bob"); assertThat(new Template("classpath:web/2variables.txt").render("verb", "Hello", "name", "Bob")).isEqualTo("Hello Bob"); assertThat(new Template("classpath:web/2variables.txt").render(new HashMap<String, Object>() {{ put("verb", "Hello"); put("name", 12); }})).isEqualTo("Hello 12"); } @Test public void yaml_front_matter() { assertThat(new Template("classpath:web/indexYaml.html").render()).contains("Hello Yaml"); } @Test public void layout() { - assertThat(new Template("classpath:web/pageYaml.html").render()).contains("PREFIX_LAYOUT_PREFIX_TEXT_SUFFIX_SUFFIX_LAYOUT"); + assertThat(new Template("classpath:web/pageYaml.html").render()).contains("PREFIX_LAYOUT<div>_PREFIX_TEXT_SUFFIX_</div>SUFFIX_LAYOUT"); } }
false
false
null
null
diff --git a/v4/java/android/support/v4/view/ViewPager.java b/v4/java/android/support/v4/view/ViewPager.java index edf919c33..5834afb64 100644 --- a/v4/java/android/support/v4/view/ViewPager.java +++ b/v4/java/android/support/v4/view/ViewPager.java @@ -1,2742 +1,2747 @@ /* * Copyright (C) 2011 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 android.support.v4.view; import android.content.Context; import android.content.res.TypedArray; import android.database.DataSetObserver; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.os.SystemClock; import android.support.v4.os.ParcelableCompat; import android.support.v4.os.ParcelableCompatCreatorCallbacks; import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat; import android.support.v4.widget.EdgeEffectCompat; import android.util.AttributeSet; import android.util.FloatMath; import android.util.Log; import android.view.FocusFinder; import android.view.Gravity; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SoundEffectConstants; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewParent; import android.view.accessibility.AccessibilityEvent; import android.view.animation.Interpolator; import android.widget.Scroller; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; /** * Layout manager that allows the user to flip left and right * through pages of data. You supply an implementation of a * {@link PagerAdapter} to generate the pages that the view shows. * * <p>Note this class is currently under early design and * development. The API will likely change in later updates of * the compatibility library, requiring changes to the source code * of apps when they are compiled against the newer version.</p> * * <p>ViewPager is most often used in conjunction with {@link android.app.Fragment}, * which is a convenient way to supply and manage the lifecycle of each page. * There are standard adapters implemented for using fragments with the ViewPager, * which cover the most common use cases. These are * {@link android.support.v4.app.FragmentPagerAdapter}, * {@link android.support.v4.app.FragmentStatePagerAdapter}, * {@link android.support.v13.app.FragmentPagerAdapter}, and * {@link android.support.v13.app.FragmentStatePagerAdapter}; each of these * classes have simple code showing how to build a full user interface * with them. * * <p>Here is a more complicated example of ViewPager, using it in conjuction * with {@link android.app.ActionBar} tabs. You can find other examples of using * ViewPager in the API 4+ Support Demos and API 13+ Support Demos sample code. * * {@sample development/samples/Support13Demos/src/com/example/android/supportv13/app/ActionBarTabsPager.java * complete} */ public class ViewPager extends ViewGroup { private static final String TAG = "ViewPager"; private static final boolean DEBUG = false; private static final boolean USE_CACHE = false; private static final int DEFAULT_OFFSCREEN_PAGES = 1; private static final int MAX_SETTLE_DURATION = 600; // ms private static final int MIN_DISTANCE_FOR_FLING = 25; // dips private static final int DEFAULT_GUTTER_SIZE = 16; // dips private static final int[] LAYOUT_ATTRS = new int[] { android.R.attr.layout_gravity }; static class ItemInfo { Object object; int position; boolean scrolling; float widthFactor; float offset; } private static final Comparator<ItemInfo> COMPARATOR = new Comparator<ItemInfo>(){ @Override public int compare(ItemInfo lhs, ItemInfo rhs) { return lhs.position - rhs.position; } }; private static final Interpolator sInterpolator = new Interpolator() { public float getInterpolation(float t) { t -= 1.0f; return t * t * t * t * t + 1.0f; } }; private final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>(); private final ItemInfo mTempItem = new ItemInfo(); private final Rect mTempRect = new Rect(); private PagerAdapter mAdapter; private int mCurItem; // Index of currently displayed page. private int mRestoredCurItem = -1; private Parcelable mRestoredAdapterState = null; private ClassLoader mRestoredClassLoader = null; private Scroller mScroller; private PagerObserver mObserver; private int mPageMargin; private Drawable mMarginDrawable; private int mTopPageBounds; private int mBottomPageBounds; // Offsets of the first and last items, if known. // Set during population, used to determine if we are at the beginning // or end of the pager data set during touch scrolling. private float mFirstOffset = -Float.MAX_VALUE; private float mLastOffset = Float.MAX_VALUE; private int mChildWidthMeasureSpec; private int mChildHeightMeasureSpec; private boolean mInLayout; private boolean mScrollingCacheEnabled; private boolean mPopulatePending; private int mOffscreenPageLimit = DEFAULT_OFFSCREEN_PAGES; private boolean mIsBeingDragged; private boolean mIsUnableToDrag; private boolean mIgnoreGutter; private int mDefaultGutterSize; private int mGutterSize; private int mTouchSlop; private float mInitialMotionX; /** * Position of the last motion event. */ private float mLastMotionX; private float mLastMotionY; /** * ID of the active pointer. This is used to retain consistency during * drags/flings if multiple pointers are used. */ private int mActivePointerId = INVALID_POINTER; /** * Sentinel value for no current active pointer. * Used by {@link #mActivePointerId}. */ private static final int INVALID_POINTER = -1; /** * Determines speed during touch scrolling */ private VelocityTracker mVelocityTracker; private int mMinimumVelocity; private int mMaximumVelocity; private int mFlingDistance; private int mCloseEnough; private int mSeenPositionMin; private int mSeenPositionMax; // If the pager is at least this close to its final position, complete the scroll // on touch down and let the user interact with the content inside instead of // "catching" the flinging pager. private static final int CLOSE_ENOUGH = 2; // dp private boolean mFakeDragging; private long mFakeDragBeginTime; private EdgeEffectCompat mLeftEdge; private EdgeEffectCompat mRightEdge; private boolean mFirstLayout = true; private boolean mNeedCalculatePageOffsets = false; private boolean mCalledSuper; private int mDecorChildCount; private OnPageChangeListener mOnPageChangeListener; private OnPageChangeListener mInternalPageChangeListener; private OnAdapterChangeListener mAdapterChangeListener; private PageTransformer mPageTransformer; private Method mSetChildrenDrawingOrderEnabled; private static final int DRAW_ORDER_DEFAULT = 0; private static final int DRAW_ORDER_FORWARD = 1; private static final int DRAW_ORDER_REVERSE = 2; private int mDrawingOrder; private ArrayList<View> mDrawingOrderedChildren; private static final ViewPositionComparator sPositionComparator = new ViewPositionComparator(); /** * Indicates that the pager is in an idle, settled state. The current page * is fully in view and no animation is in progress. */ public static final int SCROLL_STATE_IDLE = 0; /** * Indicates that the pager is currently being dragged by the user. */ public static final int SCROLL_STATE_DRAGGING = 1; /** * Indicates that the pager is in the process of settling to a final position. */ public static final int SCROLL_STATE_SETTLING = 2; private int mScrollState = SCROLL_STATE_IDLE; /** * Callback interface for responding to changing state of the selected page. */ public interface OnPageChangeListener { /** * This method will be invoked when the current page is scrolled, either as part * of a programmatically initiated smooth scroll or a user initiated touch scroll. * * @param position Position index of the first page currently being displayed. * Page position+1 will be visible if positionOffset is nonzero. * @param positionOffset Value from [0, 1) indicating the offset from the page at position. * @param positionOffsetPixels Value in pixels indicating the offset from position. */ public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels); /** * This method will be invoked when a new page becomes selected. Animation is not * necessarily complete. * * @param position Position index of the new selected page. */ public void onPageSelected(int position); /** * Called when the scroll state changes. Useful for discovering when the user * begins dragging, when the pager is automatically settling to the current page, * or when it is fully stopped/idle. * * @param state The new scroll state. * @see ViewPager#SCROLL_STATE_IDLE * @see ViewPager#SCROLL_STATE_DRAGGING * @see ViewPager#SCROLL_STATE_SETTLING */ public void onPageScrollStateChanged(int state); } /** * Simple implementation of the {@link OnPageChangeListener} interface with stub * implementations of each method. Extend this if you do not intend to override * every method of {@link OnPageChangeListener}. */ public static class SimpleOnPageChangeListener implements OnPageChangeListener { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // This space for rent } @Override public void onPageSelected(int position) { // This space for rent } @Override public void onPageScrollStateChanged(int state) { // This space for rent } } /** * A PageTransformer is invoked whenever a visible/attached page is scrolled. * This offers an opportunity for the application to apply a custom transformation * to the page views using animation properties. * * <p>As property animation is only supported as of Android 3.0 and forward, * setting a PageTransformer on a ViewPager on earlier platform versions will * be ignored.</p> */ public interface PageTransformer { /** * Apply a property transformation to the given page. * * @param page Apply the transformation to this page * @param position Position of page relative to the current front-and-center * position of the pager. 0 is front and center. 1 is one full * page position to the right, and -1 is one page position to the left. */ public void transformPage(View page, float position); } /** * Used internally to monitor when adapters are switched. */ interface OnAdapterChangeListener { public void onAdapterChanged(PagerAdapter oldAdapter, PagerAdapter newAdapter); } /** * Used internally to tag special types of child views that should be added as * pager decorations by default. */ interface Decor {} public ViewPager(Context context) { super(context); initViewPager(); } public ViewPager(Context context, AttributeSet attrs) { super(context, attrs); initViewPager(); } void initViewPager() { setWillNotDraw(false); setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); setFocusable(true); final Context context = getContext(); mScroller = new Scroller(context, sInterpolator); final ViewConfiguration configuration = ViewConfiguration.get(context); mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration); mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); mLeftEdge = new EdgeEffectCompat(context); mRightEdge = new EdgeEffectCompat(context); final float density = context.getResources().getDisplayMetrics().density; mFlingDistance = (int) (MIN_DISTANCE_FOR_FLING * density); mCloseEnough = (int) (CLOSE_ENOUGH * density); mDefaultGutterSize = (int) (DEFAULT_GUTTER_SIZE * density); ViewCompat.setAccessibilityDelegate(this, new MyAccessibilityDelegate()); if (ViewCompat.getImportantForAccessibility(this) == ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) { ViewCompat.setImportantForAccessibility(this, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); } } private void setScrollState(int newState) { if (mScrollState == newState) { return; } mScrollState = newState; if (newState == SCROLL_STATE_DRAGGING) { mSeenPositionMin = mSeenPositionMax = -1; } if (mPageTransformer != null) { // PageTransformers can do complex things that benefit from hardware layers. enableLayers(newState != SCROLL_STATE_IDLE); } if (mOnPageChangeListener != null) { mOnPageChangeListener.onPageScrollStateChanged(newState); } } /** * Set a PagerAdapter that will supply views for this pager as needed. * * @param adapter Adapter to use */ public void setAdapter(PagerAdapter adapter) { if (mAdapter != null) { mAdapter.unregisterDataSetObserver(mObserver); mAdapter.startUpdate(this); for (int i = 0; i < mItems.size(); i++) { final ItemInfo ii = mItems.get(i); mAdapter.destroyItem(this, ii.position, ii.object); } mAdapter.finishUpdate(this); mItems.clear(); removeNonDecorViews(); mCurItem = 0; scrollTo(0, 0); } final PagerAdapter oldAdapter = mAdapter; mAdapter = adapter; if (mAdapter != null) { if (mObserver == null) { mObserver = new PagerObserver(); } mAdapter.registerDataSetObserver(mObserver); mPopulatePending = false; mFirstLayout = true; if (mRestoredCurItem >= 0) { mAdapter.restoreState(mRestoredAdapterState, mRestoredClassLoader); setCurrentItemInternal(mRestoredCurItem, false, true); mRestoredCurItem = -1; mRestoredAdapterState = null; mRestoredClassLoader = null; } else { populate(); } } if (mAdapterChangeListener != null && oldAdapter != adapter) { mAdapterChangeListener.onAdapterChanged(oldAdapter, adapter); } } private void removeNonDecorViews() { for (int i = 0; i < getChildCount(); i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (!lp.isDecor) { removeViewAt(i); i--; } } } /** * Retrieve the current adapter supplying pages. * * @return The currently registered PagerAdapter */ public PagerAdapter getAdapter() { return mAdapter; } void setOnAdapterChangeListener(OnAdapterChangeListener listener) { mAdapterChangeListener = listener; } private int getClientWidth() { return getWidth() - getPaddingLeft() - getPaddingRight(); } /** * Set the currently selected page. If the ViewPager has already been through its first * layout with its current adapter there will be a smooth animated transition between * the current item and the specified item. * * @param item Item index to select */ public void setCurrentItem(int item) { mPopulatePending = false; setCurrentItemInternal(item, !mFirstLayout, false); } /** * Set the currently selected page. * * @param item Item index to select * @param smoothScroll True to smoothly scroll to the new item, false to transition immediately */ public void setCurrentItem(int item, boolean smoothScroll) { mPopulatePending = false; setCurrentItemInternal(item, smoothScroll, false); } public int getCurrentItem() { return mCurItem; } void setCurrentItemInternal(int item, boolean smoothScroll, boolean always) { setCurrentItemInternal(item, smoothScroll, always, 0); } void setCurrentItemInternal(int item, boolean smoothScroll, boolean always, int velocity) { if (mAdapter == null || mAdapter.getCount() <= 0) { setScrollingCacheEnabled(false); return; } if (!always && mCurItem == item && mItems.size() != 0) { setScrollingCacheEnabled(false); return; } if (item < 0) { item = 0; } else if (item >= mAdapter.getCount()) { item = mAdapter.getCount() - 1; } final int pageLimit = mOffscreenPageLimit; if (item > (mCurItem + pageLimit) || item < (mCurItem - pageLimit)) { // We are doing a jump by more than one page. To avoid // glitches, we want to keep all current pages in the view // until the scroll ends. for (int i=0; i<mItems.size(); i++) { mItems.get(i).scrolling = true; } } final boolean dispatchSelected = mCurItem != item; populate(item); + scrollToItem(item, smoothScroll, velocity, dispatchSelected); + } + + private void scrollToItem(int item, boolean smoothScroll, int velocity, + boolean dispatchSelected) { final ItemInfo curInfo = infoForPosition(item); int destX = 0; if (curInfo != null) { final int width = getClientWidth(); destX = (int) (width * Math.max(mFirstOffset, Math.min(curInfo.offset, mLastOffset))); } if (smoothScroll) { smoothScrollTo(destX, 0, velocity); if (dispatchSelected && mOnPageChangeListener != null) { mOnPageChangeListener.onPageSelected(item); } if (dispatchSelected && mInternalPageChangeListener != null) { mInternalPageChangeListener.onPageSelected(item); } } else { if (dispatchSelected && mOnPageChangeListener != null) { mOnPageChangeListener.onPageSelected(item); } if (dispatchSelected && mInternalPageChangeListener != null) { mInternalPageChangeListener.onPageSelected(item); } completeScroll(); scrollTo(destX, 0); } } /** * Set a listener that will be invoked whenever the page changes or is incrementally * scrolled. See {@link OnPageChangeListener}. * * @param listener Listener to set */ public void setOnPageChangeListener(OnPageChangeListener listener) { mOnPageChangeListener = listener; } /** * Set a {@link PageTransformer} that will be called for each attached page whenever * the scroll position is changed. This allows the application to apply custom property * transformations to each page, overriding the default sliding look and feel. * * <p><em>Note:</em> Prior to Android 3.0 the property animation APIs did not exist. * As a result, setting a PageTransformer prior to Android 3.0 (API 11) will have no effect.</p> * * @param reverseDrawingOrder true if the supplied PageTransformer requires page views * to be drawn from last to first instead of first to last. * @param transformer PageTransformer that will modify each page's animation properties */ public void setPageTransformer(boolean reverseDrawingOrder, PageTransformer transformer) { if (Build.VERSION.SDK_INT >= 11) { final boolean hasTransformer = transformer != null; final boolean needsPopulate = hasTransformer != (mPageTransformer != null); mPageTransformer = transformer; setChildrenDrawingOrderEnabledCompat(hasTransformer); if (hasTransformer) { mDrawingOrder = reverseDrawingOrder ? DRAW_ORDER_REVERSE : DRAW_ORDER_FORWARD; } else { mDrawingOrder = DRAW_ORDER_DEFAULT; } if (needsPopulate) populate(); } } void setChildrenDrawingOrderEnabledCompat(boolean enable) { if (mSetChildrenDrawingOrderEnabled == null) { try { mSetChildrenDrawingOrderEnabled = ViewGroup.class.getDeclaredMethod( "setChildrenDrawingOrderEnabled", new Class[] { Boolean.TYPE }); } catch (NoSuchMethodException e) { Log.e(TAG, "Can't find setChildrenDrawingOrderEnabled", e); } } try { mSetChildrenDrawingOrderEnabled.invoke(this, enable); } catch (Exception e) { Log.e(TAG, "Error changing children drawing order", e); } } @Override protected int getChildDrawingOrder(int childCount, int i) { final int index = mDrawingOrder == DRAW_ORDER_REVERSE ? childCount - 1 - i : i; final int result = ((LayoutParams) mDrawingOrderedChildren.get(index).getLayoutParams()).childIndex; return result; } /** * Set a separate OnPageChangeListener for internal use by the support library. * * @param listener Listener to set * @return The old listener that was set, if any. */ OnPageChangeListener setInternalPageChangeListener(OnPageChangeListener listener) { OnPageChangeListener oldListener = mInternalPageChangeListener; mInternalPageChangeListener = listener; return oldListener; } /** * Returns the number of pages that will be retained to either side of the * current page in the view hierarchy in an idle state. Defaults to 1. * * @return How many pages will be kept offscreen on either side * @see #setOffscreenPageLimit(int) */ public int getOffscreenPageLimit() { return mOffscreenPageLimit; } /** * Set the number of pages that should be retained to either side of the * current page in the view hierarchy in an idle state. Pages beyond this * limit will be recreated from the adapter when needed. * * <p>This is offered as an optimization. If you know in advance the number * of pages you will need to support or have lazy-loading mechanisms in place * on your pages, tweaking this setting can have benefits in perceived smoothness * of paging animations and interaction. If you have a small number of pages (3-4) * that you can keep active all at once, less time will be spent in layout for * newly created view subtrees as the user pages back and forth.</p> * * <p>You should keep this limit low, especially if your pages have complex layouts. * This setting defaults to 1.</p> * * @param limit How many pages will be kept offscreen in an idle state. */ public void setOffscreenPageLimit(int limit) { if (limit < DEFAULT_OFFSCREEN_PAGES) { Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to " + DEFAULT_OFFSCREEN_PAGES); limit = DEFAULT_OFFSCREEN_PAGES; } if (limit != mOffscreenPageLimit) { mOffscreenPageLimit = limit; populate(); } } /** * Set the margin between pages. * * @param marginPixels Distance between adjacent pages in pixels * @see #getPageMargin() * @see #setPageMarginDrawable(Drawable) * @see #setPageMarginDrawable(int) */ public void setPageMargin(int marginPixels) { final int oldMargin = mPageMargin; mPageMargin = marginPixels; final int width = getWidth(); recomputeScrollPosition(width, width, marginPixels, oldMargin); requestLayout(); } /** * Return the margin between pages. * * @return The size of the margin in pixels */ public int getPageMargin() { return mPageMargin; } /** * Set a drawable that will be used to fill the margin between pages. * * @param d Drawable to display between pages */ public void setPageMarginDrawable(Drawable d) { mMarginDrawable = d; if (d != null) refreshDrawableState(); setWillNotDraw(d == null); invalidate(); } /** * Set a drawable that will be used to fill the margin between pages. * * @param resId Resource ID of a drawable to display between pages */ public void setPageMarginDrawable(int resId) { setPageMarginDrawable(getContext().getResources().getDrawable(resId)); } @Override protected boolean verifyDrawable(Drawable who) { return super.verifyDrawable(who) || who == mMarginDrawable; } @Override protected void drawableStateChanged() { super.drawableStateChanged(); final Drawable d = mMarginDrawable; if (d != null && d.isStateful()) { d.setState(getDrawableState()); } } // We want the duration of the page snap animation to be influenced by the distance that // the screen has to travel, however, we don't want this duration to be effected in a // purely linear fashion. Instead, we use this method to moderate the effect that the distance // of travel has on the overall snap duration. float distanceInfluenceForSnapDuration(float f) { f -= 0.5f; // center the values about 0. f *= 0.3f * Math.PI / 2.0f; return (float) Math.sin(f); } /** * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. * * @param x the number of pixels to scroll by on the X axis * @param y the number of pixels to scroll by on the Y axis */ void smoothScrollTo(int x, int y) { smoothScrollTo(x, y, 0); } /** * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. * * @param x the number of pixels to scroll by on the X axis * @param y the number of pixels to scroll by on the Y axis * @param velocity the velocity associated with a fling, if applicable. (0 otherwise) */ void smoothScrollTo(int x, int y, int velocity) { if (getChildCount() == 0) { // Nothing to do. setScrollingCacheEnabled(false); return; } int sx = getScrollX(); int sy = getScrollY(); int dx = x - sx; int dy = y - sy; if (dx == 0 && dy == 0) { completeScroll(); populate(); setScrollState(SCROLL_STATE_IDLE); return; } setScrollingCacheEnabled(true); setScrollState(SCROLL_STATE_SETTLING); final int width = getClientWidth(); final int halfWidth = width / 2; final float distanceRatio = Math.min(1f, 1.0f * Math.abs(dx) / width); final float distance = halfWidth + halfWidth * distanceInfluenceForSnapDuration(distanceRatio); int duration = 0; velocity = Math.abs(velocity); if (velocity > 0) { duration = 4 * Math.round(1000 * Math.abs(distance / velocity)); } else { final float pageWidth = width * mAdapter.getPageWidth(mCurItem); final float pageDelta = (float) Math.abs(dx) / (pageWidth + mPageMargin); duration = (int) ((pageDelta + 1) * 100); } duration = Math.min(duration, MAX_SETTLE_DURATION); mScroller.startScroll(sx, sy, dx, dy, duration); ViewCompat.postInvalidateOnAnimation(this); } ItemInfo addNewItem(int position, int index) { ItemInfo ii = new ItemInfo(); ii.position = position; ii.object = mAdapter.instantiateItem(this, position); ii.widthFactor = mAdapter.getPageWidth(position); if (index < 0 || index >= mItems.size()) { mItems.add(ii); } else { mItems.add(index, ii); } return ii; } void dataSetChanged() { // This method only gets called if our observer is attached, so mAdapter is non-null. boolean needPopulate = mItems.size() < mOffscreenPageLimit * 2 + 1 && mItems.size() < mAdapter.getCount(); int newCurrItem = mCurItem; boolean isUpdating = false; for (int i = 0; i < mItems.size(); i++) { final ItemInfo ii = mItems.get(i); final int newPos = mAdapter.getItemPosition(ii.object); if (newPos == PagerAdapter.POSITION_UNCHANGED) { continue; } if (newPos == PagerAdapter.POSITION_NONE) { mItems.remove(i); i--; if (!isUpdating) { mAdapter.startUpdate(this); isUpdating = true; } mAdapter.destroyItem(this, ii.position, ii.object); needPopulate = true; if (mCurItem == ii.position) { // Keep the current item in the valid range newCurrItem = Math.max(0, Math.min(mCurItem, mAdapter.getCount() - 1)); needPopulate = true; } continue; } if (ii.position != newPos) { if (ii.position == mCurItem) { // Our current item changed position. Follow it. newCurrItem = newPos; } ii.position = newPos; needPopulate = true; } } if (isUpdating) { mAdapter.finishUpdate(this); } Collections.sort(mItems, COMPARATOR); if (needPopulate) { // Reset our known page widths; populate will recompute them. final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (!lp.isDecor) { lp.widthFactor = 0.f; } } setCurrentItemInternal(newCurrItem, false, true); requestLayout(); } } void populate() { populate(mCurItem); } void populate(int newCurrentItem) { ItemInfo oldCurInfo = null; if (mCurItem != newCurrentItem) { oldCurInfo = infoForPosition(mCurItem); mCurItem = newCurrentItem; } if (mAdapter == null) { return; } // Bail now if we are waiting to populate. This is to hold off // on creating views from the time the user releases their finger to // fling to a new position until we have finished the scroll to // that position, avoiding glitches from happening at that point. if (mPopulatePending) { if (DEBUG) Log.i(TAG, "populate is pending, skipping for now..."); return; } // Also, don't populate until we are attached to a window. This is to // avoid trying to populate before we have restored our view hierarchy // state and conflicting with what is restored. if (getWindowToken() == null) { return; } mAdapter.startUpdate(this); final int pageLimit = mOffscreenPageLimit; final int startPos = Math.max(0, mCurItem - pageLimit); final int N = mAdapter.getCount(); final int endPos = Math.min(N-1, mCurItem + pageLimit); // Locate the currently focused item or add it if needed. int curIndex = -1; ItemInfo curItem = null; for (curIndex = 0; curIndex < mItems.size(); curIndex++) { final ItemInfo ii = mItems.get(curIndex); if (ii.position >= mCurItem) { if (ii.position == mCurItem) curItem = ii; break; } } if (curItem == null && N > 0) { curItem = addNewItem(mCurItem, curIndex); } // Fill 3x the available width or up to the number of offscreen // pages requested to either side, whichever is larger. // If we have no current item we have no work to do. if (curItem != null) { float extraWidthLeft = 0.f; int itemIndex = curIndex - 1; ItemInfo ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; final float leftWidthNeeded = 2.f - curItem.widthFactor + (float) getPaddingLeft() / (float) getClientWidth(); for (int pos = mCurItem - 1; pos >= 0; pos--) { if (extraWidthLeft >= leftWidthNeeded && pos < startPos) { if (ii == null) { break; } if (pos == ii.position && !ii.scrolling) { mItems.remove(itemIndex); mAdapter.destroyItem(this, pos, ii.object); itemIndex--; curIndex--; ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; } } else if (ii != null && pos == ii.position) { extraWidthLeft += ii.widthFactor; itemIndex--; ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; } else { ii = addNewItem(pos, itemIndex + 1); extraWidthLeft += ii.widthFactor; curIndex++; ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; } } float extraWidthRight = curItem.widthFactor; itemIndex = curIndex + 1; if (extraWidthRight < 2.f) { ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; final float rightWidthNeeded = (float) getPaddingRight() / (float) getClientWidth() + 2.f; for (int pos = mCurItem + 1; pos < N; pos++) { if (extraWidthRight >= rightWidthNeeded && pos > endPos) { if (ii == null) { break; } if (pos == ii.position && !ii.scrolling) { mItems.remove(itemIndex); mAdapter.destroyItem(this, pos, ii.object); ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; } } else if (ii != null && pos == ii.position) { extraWidthRight += ii.widthFactor; itemIndex++; ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; } else { ii = addNewItem(pos, itemIndex); itemIndex++; extraWidthRight += ii.widthFactor; ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; } } } calculatePageOffsets(curItem, curIndex, oldCurInfo); } if (DEBUG) { Log.i(TAG, "Current page list:"); for (int i=0; i<mItems.size(); i++) { Log.i(TAG, "#" + i + ": page " + mItems.get(i).position); } } mAdapter.setPrimaryItem(this, mCurItem, curItem != null ? curItem.object : null); mAdapter.finishUpdate(this); // Check width measurement of current pages and drawing sort order. // Update LayoutParams as needed. final boolean sort = mDrawingOrder != DRAW_ORDER_DEFAULT; if (sort) { if (mDrawingOrderedChildren == null) { mDrawingOrderedChildren = new ArrayList<View>(); } else { mDrawingOrderedChildren.clear(); } } final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); lp.childIndex = i; if (!lp.isDecor && lp.widthFactor == 0.f) { // 0 means requery the adapter for this, it doesn't have a valid width. final ItemInfo ii = infoForChild(child); if (ii != null) { lp.widthFactor = ii.widthFactor; lp.position = ii.position; } } if (sort) mDrawingOrderedChildren.add(child); } if (sort) { Collections.sort(mDrawingOrderedChildren, sPositionComparator); } if (hasFocus()) { View currentFocused = findFocus(); ItemInfo ii = currentFocused != null ? infoForAnyChild(currentFocused) : null; if (ii == null || ii.position != mCurItem) { for (int i=0; i<getChildCount(); i++) { View child = getChildAt(i); ii = infoForChild(child); if (ii != null && ii.position == mCurItem) { if (child.requestFocus(FOCUS_FORWARD)) { break; } } } } } } private void calculatePageOffsets(ItemInfo curItem, int curIndex, ItemInfo oldCurInfo) { final int N = mAdapter.getCount(); final int width = getClientWidth(); final float marginOffset = width > 0 ? (float) mPageMargin / width : 0; // Fix up offsets for later layout. if (oldCurInfo != null) { final int oldCurPosition = oldCurInfo.position; // Base offsets off of oldCurInfo. if (oldCurPosition < curItem.position) { int itemIndex = 0; ItemInfo ii = null; float offset = oldCurInfo.offset + oldCurInfo.widthFactor + marginOffset; for (int pos = oldCurPosition + 1; pos <= curItem.position && itemIndex < mItems.size(); pos++) { ii = mItems.get(itemIndex); while (pos > ii.position && itemIndex < mItems.size() - 1) { itemIndex++; ii = mItems.get(itemIndex); } while (pos < ii.position) { // We don't have an item populated for this, // ask the adapter for an offset. offset += mAdapter.getPageWidth(pos) + marginOffset; pos++; } ii.offset = offset; offset += ii.widthFactor + marginOffset; } } else if (oldCurPosition > curItem.position) { int itemIndex = mItems.size() - 1; ItemInfo ii = null; float offset = oldCurInfo.offset; for (int pos = oldCurPosition - 1; pos >= curItem.position && itemIndex >= 0; pos--) { ii = mItems.get(itemIndex); while (pos < ii.position && itemIndex > 0) { itemIndex--; ii = mItems.get(itemIndex); } while (pos > ii.position) { // We don't have an item populated for this, // ask the adapter for an offset. offset -= mAdapter.getPageWidth(pos) + marginOffset; pos--; } offset -= ii.widthFactor + marginOffset; ii.offset = offset; } } } // Base all offsets off of curItem. final int itemCount = mItems.size(); float offset = curItem.offset; int pos = curItem.position - 1; mFirstOffset = curItem.position == 0 ? curItem.offset : -Float.MAX_VALUE; mLastOffset = curItem.position == N - 1 ? curItem.offset + curItem.widthFactor - 1 : Float.MAX_VALUE; // Previous pages for (int i = curIndex - 1; i >= 0; i--, pos--) { final ItemInfo ii = mItems.get(i); while (pos > ii.position) { offset -= mAdapter.getPageWidth(pos--) + marginOffset; } offset -= ii.widthFactor + marginOffset; ii.offset = offset; if (ii.position == 0) mFirstOffset = offset; } offset = curItem.offset + curItem.widthFactor + marginOffset; pos = curItem.position + 1; // Next pages for (int i = curIndex + 1; i < itemCount; i++, pos++) { final ItemInfo ii = mItems.get(i); while (pos < ii.position) { offset += mAdapter.getPageWidth(pos++) + marginOffset; } if (ii.position == N - 1) { mLastOffset = offset + ii.widthFactor - 1; } ii.offset = offset; offset += ii.widthFactor + marginOffset; } mNeedCalculatePageOffsets = false; } /** * This is the persistent state that is saved by ViewPager. Only needed * if you are creating a sublass of ViewPager that must save its own * state, in which case it should implement a subclass of this which * contains that state. */ public static class SavedState extends BaseSavedState { int position; Parcelable adapterState; ClassLoader loader; public SavedState(Parcelable superState) { super(superState); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(position); out.writeParcelable(adapterState, flags); } @Override public String toString() { return "FragmentPager.SavedState{" + Integer.toHexString(System.identityHashCode(this)) + " position=" + position + "}"; } public static final Parcelable.Creator<SavedState> CREATOR = ParcelableCompat.newCreator(new ParcelableCompatCreatorCallbacks<SavedState>() { @Override public SavedState createFromParcel(Parcel in, ClassLoader loader) { return new SavedState(in, loader); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }); SavedState(Parcel in, ClassLoader loader) { super(in); if (loader == null) { loader = getClass().getClassLoader(); } position = in.readInt(); adapterState = in.readParcelable(loader); this.loader = loader; } } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.position = mCurItem; if (mAdapter != null) { ss.adapterState = mAdapter.saveState(); } return ss; } @Override public void onRestoreInstanceState(Parcelable state) { if (!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } SavedState ss = (SavedState)state; super.onRestoreInstanceState(ss.getSuperState()); if (mAdapter != null) { mAdapter.restoreState(ss.adapterState, ss.loader); setCurrentItemInternal(ss.position, false, true); } else { mRestoredCurItem = ss.position; mRestoredAdapterState = ss.adapterState; mRestoredClassLoader = ss.loader; } } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { if (!checkLayoutParams(params)) { params = generateLayoutParams(params); } final LayoutParams lp = (LayoutParams) params; lp.isDecor |= child instanceof Decor; if (mInLayout) { if (lp != null && lp.isDecor) { throw new IllegalStateException("Cannot add pager decor view during layout"); } lp.needsMeasure = true; addViewInLayout(child, index, params); } else { super.addView(child, index, params); } if (USE_CACHE) { if (child.getVisibility() != GONE) { child.setDrawingCacheEnabled(mScrollingCacheEnabled); } else { child.setDrawingCacheEnabled(false); } } } ItemInfo infoForChild(View child) { for (int i=0; i<mItems.size(); i++) { ItemInfo ii = mItems.get(i); if (mAdapter.isViewFromObject(child, ii.object)) { return ii; } } return null; } ItemInfo infoForAnyChild(View child) { ViewParent parent; while ((parent=child.getParent()) != this) { if (parent == null || !(parent instanceof View)) { return null; } child = (View)parent; } return infoForChild(child); } ItemInfo infoForPosition(int position) { for (int i = 0; i < mItems.size(); i++) { ItemInfo ii = mItems.get(i); if (ii.position == position) { return ii; } } return null; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); mFirstLayout = true; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // For simple implementation, or internal size is always 0. // We depend on the container to specify the layout size of // our view. We can't really know what it is since we will be // adding and removing different arbitrary views and do not // want the layout to change as this happens. setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec)); final int measuredWidth = getMeasuredWidth(); final int maxGutterSize = measuredWidth / 10; mGutterSize = Math.min(maxGutterSize, mDefaultGutterSize); // Children are just made to fill our space. int childWidthSize = measuredWidth - getPaddingLeft() - getPaddingRight(); int childHeightSize = getMeasuredHeight() - getPaddingTop() - getPaddingBottom(); /* * Make sure all children have been properly measured. Decor views first. * Right now we cheat and make this less complicated by assuming decor * views won't intersect. We will pin to edges based on gravity. */ int size = getChildCount(); for (int i = 0; i < size; ++i) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp != null && lp.isDecor) { final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK; final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK; int widthMode = MeasureSpec.AT_MOST; int heightMode = MeasureSpec.AT_MOST; boolean consumeVertical = vgrav == Gravity.TOP || vgrav == Gravity.BOTTOM; boolean consumeHorizontal = hgrav == Gravity.LEFT || hgrav == Gravity.RIGHT; if (consumeVertical) { widthMode = MeasureSpec.EXACTLY; } else if (consumeHorizontal) { heightMode = MeasureSpec.EXACTLY; } int widthSize = childWidthSize; int heightSize = childHeightSize; if (lp.width != LayoutParams.WRAP_CONTENT) { widthMode = MeasureSpec.EXACTLY; if (lp.width != LayoutParams.FILL_PARENT) { widthSize = lp.width; } } if (lp.height != LayoutParams.WRAP_CONTENT) { heightMode = MeasureSpec.EXACTLY; if (lp.height != LayoutParams.FILL_PARENT) { heightSize = lp.height; } } final int widthSpec = MeasureSpec.makeMeasureSpec(widthSize, widthMode); final int heightSpec = MeasureSpec.makeMeasureSpec(heightSize, heightMode); child.measure(widthSpec, heightSpec); if (consumeVertical) { childHeightSize -= child.getMeasuredHeight(); } else if (consumeHorizontal) { childWidthSize -= child.getMeasuredWidth(); } } } } mChildWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY); mChildHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeightSize, MeasureSpec.EXACTLY); // Make sure we have created all fragments that we need to have shown. mInLayout = true; populate(); mInLayout = false; // Page views next. size = getChildCount(); for (int i = 0; i < size; ++i) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { if (DEBUG) Log.v(TAG, "Measuring #" + i + " " + child + ": " + mChildWidthMeasureSpec); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp == null || !lp.isDecor) { final int widthSpec = MeasureSpec.makeMeasureSpec( (int) (childWidthSize * lp.widthFactor), MeasureSpec.EXACTLY); child.measure(widthSpec, mChildHeightMeasureSpec); } } } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); // Make sure scroll position is set correctly. if (w != oldw) { recomputeScrollPosition(w, oldw, mPageMargin, mPageMargin); } } private void recomputeScrollPosition(int width, int oldWidth, int margin, int oldMargin) { if (oldWidth > 0 && !mItems.isEmpty()) { final int widthWithMargin = width - getPaddingLeft() - getPaddingRight() + margin; final int oldWidthWithMargin = oldWidth - getPaddingLeft() - getPaddingRight() + oldMargin; final int xpos = getScrollX(); final float pageOffset = (float) xpos / oldWidthWithMargin; final int newOffsetPixels = (int) (pageOffset * widthWithMargin); scrollTo(newOffsetPixels, getScrollY()); if (!mScroller.isFinished()) { // We now return to your regularly scheduled scroll, already in progress. final int newDuration = mScroller.getDuration() - mScroller.timePassed(); ItemInfo targetInfo = infoForPosition(mCurItem); mScroller.startScroll(newOffsetPixels, 0, (int) (targetInfo.offset * width), 0, newDuration); } } else { final ItemInfo ii = infoForPosition(mCurItem); final float scrollOffset = ii != null ? Math.min(ii.offset, mLastOffset) : 0; final int scrollPos = (int) (scrollOffset * (width - getPaddingLeft() - getPaddingRight())); if (scrollPos != getScrollX()) { completeScroll(); scrollTo(scrollPos, getScrollY()); } } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { mInLayout = true; populate(); mInLayout = false; final int count = getChildCount(); int width = r - l; int height = b - t; int paddingLeft = getPaddingLeft(); int paddingTop = getPaddingTop(); int paddingRight = getPaddingRight(); int paddingBottom = getPaddingBottom(); final int scrollX = getScrollX(); int decorCount = 0; // First pass - decor views. We need to do this in two passes so that // we have the proper offsets for non-decor views later. for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); int childLeft = 0; int childTop = 0; if (lp.isDecor) { final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK; final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK; switch (hgrav) { default: childLeft = paddingLeft; break; case Gravity.LEFT: childLeft = paddingLeft; paddingLeft += child.getMeasuredWidth(); break; case Gravity.CENTER_HORIZONTAL: childLeft = Math.max((width - child.getMeasuredWidth()) / 2, paddingLeft); break; case Gravity.RIGHT: childLeft = width - paddingRight - child.getMeasuredWidth(); paddingRight += child.getMeasuredWidth(); break; } switch (vgrav) { default: childTop = paddingTop; break; case Gravity.TOP: childTop = paddingTop; paddingTop += child.getMeasuredHeight(); break; case Gravity.CENTER_VERTICAL: childTop = Math.max((height - child.getMeasuredHeight()) / 2, paddingTop); break; case Gravity.BOTTOM: childTop = height - paddingBottom - child.getMeasuredHeight(); paddingBottom += child.getMeasuredHeight(); break; } childLeft += scrollX; child.layout(childLeft, childTop, childLeft + child.getMeasuredWidth(), childTop + child.getMeasuredHeight()); decorCount++; } } } final int childWidth = width - paddingLeft - paddingRight; // Page views. Do this once we have the right padding offsets from above. for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); ItemInfo ii; if (!lp.isDecor && (ii = infoForChild(child)) != null) { int loff = (int) (childWidth * ii.offset); int childLeft = paddingLeft + loff; int childTop = paddingTop; if (lp.needsMeasure) { // This was added during layout and needs measurement. // Do it now that we know what we're working with. lp.needsMeasure = false; final int widthSpec = MeasureSpec.makeMeasureSpec( (int) (childWidth * lp.widthFactor), MeasureSpec.EXACTLY); final int heightSpec = MeasureSpec.makeMeasureSpec( (int) (height - paddingTop - paddingBottom), MeasureSpec.EXACTLY); child.measure(widthSpec, heightSpec); } if (DEBUG) Log.v(TAG, "Positioning #" + i + " " + child + " f=" + ii.object + ":" + childLeft + "," + childTop + " " + child.getMeasuredWidth() + "x" + child.getMeasuredHeight()); child.layout(childLeft, childTop, childLeft + child.getMeasuredWidth(), childTop + child.getMeasuredHeight()); } } } mTopPageBounds = paddingTop; mBottomPageBounds = height - paddingBottom; mDecorChildCount = decorCount; mFirstLayout = false; } @Override public void computeScroll() { if (!mScroller.isFinished() && mScroller.computeScrollOffset()) { int oldX = getScrollX(); int oldY = getScrollY(); int x = mScroller.getCurrX(); int y = mScroller.getCurrY(); if (oldX != x || oldY != y) { scrollTo(x, y); if (!pageScrolled(x)) { mScroller.abortAnimation(); scrollTo(0, y); } } // Keep on drawing until the animation has finished. ViewCompat.postInvalidateOnAnimation(this); return; } // Done with scroll, clean up state. completeScroll(); } private boolean pageScrolled(int xpos) { if (mItems.size() == 0) { mCalledSuper = false; onPageScrolled(0, 0, 0); if (!mCalledSuper) { throw new IllegalStateException( "onPageScrolled did not call superclass implementation"); } return false; } final ItemInfo ii = infoForCurrentScrollPosition(); final int width = getClientWidth(); final int widthWithMargin = width + mPageMargin; final float marginOffset = (float) mPageMargin / width; final int currentPage = ii.position; final float pageOffset = (((float) xpos / width) - ii.offset) / (ii.widthFactor + marginOffset); final int offsetPixels = (int) (pageOffset * widthWithMargin); mCalledSuper = false; onPageScrolled(currentPage, pageOffset, offsetPixels); if (!mCalledSuper) { throw new IllegalStateException( "onPageScrolled did not call superclass implementation"); } return true; } /** * This method will be invoked when the current page is scrolled, either as part * of a programmatically initiated smooth scroll or a user initiated touch scroll. * If you override this method you must call through to the superclass implementation * (e.g. super.onPageScrolled(position, offset, offsetPixels)) before onPageScrolled * returns. * * @param position Position index of the first page currently being displayed. * Page position+1 will be visible if positionOffset is nonzero. * @param offset Value from [0, 1) indicating the offset from the page at position. * @param offsetPixels Value in pixels indicating the offset from position. */ protected void onPageScrolled(int position, float offset, int offsetPixels) { // Offset any decor views if needed - keep them on-screen at all times. if (mDecorChildCount > 0) { final int scrollX = getScrollX(); int paddingLeft = getPaddingLeft(); int paddingRight = getPaddingRight(); final int width = getWidth(); final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (!lp.isDecor) continue; final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK; int childLeft = 0; switch (hgrav) { default: childLeft = paddingLeft; break; case Gravity.LEFT: childLeft = paddingLeft; paddingLeft += child.getWidth(); break; case Gravity.CENTER_HORIZONTAL: childLeft = Math.max((width - child.getMeasuredWidth()) / 2, paddingLeft); break; case Gravity.RIGHT: childLeft = width - paddingRight - child.getMeasuredWidth(); paddingRight += child.getMeasuredWidth(); break; } childLeft += scrollX; final int childOffset = childLeft - child.getLeft(); if (childOffset != 0) { child.offsetLeftAndRight(childOffset); } } } if (mSeenPositionMin < 0 || position < mSeenPositionMin) { mSeenPositionMin = position; } if (mSeenPositionMax < 0 || FloatMath.ceil(position + offset) > mSeenPositionMax) { mSeenPositionMax = position + 1; } if (mOnPageChangeListener != null) { mOnPageChangeListener.onPageScrolled(position, offset, offsetPixels); } if (mInternalPageChangeListener != null) { mInternalPageChangeListener.onPageScrolled(position, offset, offsetPixels); } if (mPageTransformer != null) { final int scrollX = getScrollX(); final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp.isDecor) continue; final float transformPos = (float) (child.getLeft() - scrollX) / getClientWidth(); mPageTransformer.transformPage(child, transformPos); } } mCalledSuper = true; } private void completeScroll() { boolean needPopulate = mScrollState == SCROLL_STATE_SETTLING; if (needPopulate) { // Done with scroll, no longer want to cache view drawing. setScrollingCacheEnabled(false); mScroller.abortAnimation(); int oldX = getScrollX(); int oldY = getScrollY(); int x = mScroller.getCurrX(); int y = mScroller.getCurrY(); if (oldX != x || oldY != y) { scrollTo(x, y); } setScrollState(SCROLL_STATE_IDLE); } mPopulatePending = false; for (int i=0; i<mItems.size(); i++) { ItemInfo ii = mItems.get(i); if (ii.scrolling) { needPopulate = true; ii.scrolling = false; } } if (needPopulate) { populate(); } } private boolean isGutterDrag(float x, float dx) { return (x < mGutterSize && dx > 0) || (x > getWidth() - mGutterSize && dx < 0); } private void enableLayers(boolean enable) { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final int layerType = enable ? ViewCompat.LAYER_TYPE_HARDWARE : ViewCompat.LAYER_TYPE_NONE; ViewCompat.setLayerType(getChildAt(i), layerType, null); } } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { /* * This method JUST determines whether we want to intercept the motion. * If we return true, onMotionEvent will be called and we do the actual * scrolling there. */ final int action = ev.getAction() & MotionEventCompat.ACTION_MASK; // Always take care of the touch gesture being complete. if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { // Release the drag. if (DEBUG) Log.v(TAG, "Intercept done!"); mIsBeingDragged = false; mIsUnableToDrag = false; mActivePointerId = INVALID_POINTER; if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } return false; } // Nothing more to do here if we have decided whether or not we // are dragging. if (action != MotionEvent.ACTION_DOWN) { if (mIsBeingDragged) { if (DEBUG) Log.v(TAG, "Intercept returning true!"); return true; } if (mIsUnableToDrag) { if (DEBUG) Log.v(TAG, "Intercept returning false!"); return false; } } switch (action) { case MotionEvent.ACTION_MOVE: { /* * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check * whether the user has moved far enough from his original down touch. */ /* * Locally do absolute value. mLastMotionY is set to the y value * of the down event. */ final int activePointerId = mActivePointerId; if (activePointerId == INVALID_POINTER) { // If we don't have a valid id, the touch down wasn't on content. break; } final int pointerIndex = MotionEventCompat.findPointerIndex(ev, activePointerId); final float x = MotionEventCompat.getX(ev, pointerIndex); final float dx = x - mLastMotionX; final float xDiff = Math.abs(dx); final float y = MotionEventCompat.getY(ev, pointerIndex); final float yDiff = Math.abs(y - mLastMotionY); if (DEBUG) Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff); if (dx != 0 && !isGutterDrag(mLastMotionX, dx) && canScroll(this, false, (int) dx, (int) x, (int) y)) { // Nested view has scrollable area under this point. Let it be handled there. mInitialMotionX = mLastMotionX = x; mLastMotionY = y; mIsUnableToDrag = true; return false; } if (xDiff > mTouchSlop && xDiff > yDiff) { if (DEBUG) Log.v(TAG, "Starting drag!"); mIsBeingDragged = true; setScrollState(SCROLL_STATE_DRAGGING); mLastMotionX = dx > 0 ? mInitialMotionX + mTouchSlop : mInitialMotionX - mTouchSlop; setScrollingCacheEnabled(true); } else { if (yDiff > mTouchSlop) { // The finger has moved enough in the vertical // direction to be counted as a drag... abort // any attempt to drag horizontally, to work correctly // with children that have scrolling containers. if (DEBUG) Log.v(TAG, "Starting unable to drag!"); mIsUnableToDrag = true; } } if (mIsBeingDragged) { // Scroll to follow the motion event if (performDrag(x)) { ViewCompat.postInvalidateOnAnimation(this); } } break; } case MotionEvent.ACTION_DOWN: { /* * Remember location of down touch. * ACTION_DOWN always refers to pointer index 0. */ mLastMotionX = mInitialMotionX = ev.getX(); mLastMotionY = ev.getY(); mActivePointerId = MotionEventCompat.getPointerId(ev, 0); mIsUnableToDrag = false; mScroller.computeScrollOffset(); if (mScrollState == SCROLL_STATE_SETTLING && Math.abs(mScroller.getFinalX() - mScroller.getCurrX()) > mCloseEnough) { // Let the user 'catch' the pager as it animates. mScroller.abortAnimation(); mPopulatePending = false; populate(); mIsBeingDragged = true; setScrollState(SCROLL_STATE_DRAGGING); } else { completeScroll(); mIsBeingDragged = false; } if (DEBUG) Log.v(TAG, "Down at " + mLastMotionX + "," + mLastMotionY + " mIsBeingDragged=" + mIsBeingDragged + "mIsUnableToDrag=" + mIsUnableToDrag); break; } case MotionEventCompat.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; } if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); /* * The only time we want to intercept motion events is if we are in the * drag mode. */ return mIsBeingDragged; } @Override public boolean onTouchEvent(MotionEvent ev) { if (mFakeDragging) { // A fake drag is in progress already, ignore this real one // but still eat the touch events. // (It is likely that the user is multi-touching the screen.) return true; } if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) { // Don't handle edge touches immediately -- they may actually belong to one of our // descendants. return false; } if (mAdapter == null || mAdapter.getCount() == 0) { // Nothing to present or scroll; nothing to touch. return false; } if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); final int action = ev.getAction(); boolean needsInvalidate = false; switch (action & MotionEventCompat.ACTION_MASK) { case MotionEvent.ACTION_DOWN: { mScroller.abortAnimation(); mPopulatePending = false; populate(); mIsBeingDragged = true; setScrollState(SCROLL_STATE_DRAGGING); // Remember where the motion event started mLastMotionX = mInitialMotionX = ev.getX(); mActivePointerId = MotionEventCompat.getPointerId(ev, 0); break; } case MotionEvent.ACTION_MOVE: if (!mIsBeingDragged) { final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); final float x = MotionEventCompat.getX(ev, pointerIndex); final float xDiff = Math.abs(x - mLastMotionX); final float y = MotionEventCompat.getY(ev, pointerIndex); final float yDiff = Math.abs(y - mLastMotionY); if (DEBUG) Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff); if (xDiff > mTouchSlop && xDiff > yDiff) { if (DEBUG) Log.v(TAG, "Starting drag!"); mIsBeingDragged = true; mLastMotionX = x - mInitialMotionX > 0 ? mInitialMotionX + mTouchSlop : mInitialMotionX - mTouchSlop; setScrollState(SCROLL_STATE_DRAGGING); setScrollingCacheEnabled(true); } } // Not else! Note that mIsBeingDragged can be set above. if (mIsBeingDragged) { // Scroll to follow the motion event final int activePointerIndex = MotionEventCompat.findPointerIndex( ev, mActivePointerId); final float x = MotionEventCompat.getX(ev, activePointerIndex); needsInvalidate |= performDrag(x); } break; case MotionEvent.ACTION_UP: if (mIsBeingDragged) { final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); int initialVelocity = (int) VelocityTrackerCompat.getXVelocity( velocityTracker, mActivePointerId); mPopulatePending = true; final int width = getClientWidth(); final int scrollX = getScrollX(); final ItemInfo ii = infoForCurrentScrollPosition(); final int currentPage = ii.position; final float pageOffset = (((float) scrollX / width) - ii.offset) / ii.widthFactor; final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); final float x = MotionEventCompat.getX(ev, activePointerIndex); final int totalDelta = (int) (x - mInitialMotionX); int nextPage = determineTargetPage(currentPage, pageOffset, initialVelocity, totalDelta); setCurrentItemInternal(nextPage, true, true, initialVelocity); mActivePointerId = INVALID_POINTER; endDrag(); needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease(); } break; case MotionEvent.ACTION_CANCEL: if (mIsBeingDragged) { - setCurrentItemInternal(mCurItem, true, true); + scrollToItem(mCurItem, true, 0, false); mActivePointerId = INVALID_POINTER; endDrag(); needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease(); } break; case MotionEventCompat.ACTION_POINTER_DOWN: { final int index = MotionEventCompat.getActionIndex(ev); final float x = MotionEventCompat.getX(ev, index); mLastMotionX = x; mActivePointerId = MotionEventCompat.getPointerId(ev, index); break; } case MotionEventCompat.ACTION_POINTER_UP: onSecondaryPointerUp(ev); mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId)); break; } if (needsInvalidate) { ViewCompat.postInvalidateOnAnimation(this); } return true; } private boolean performDrag(float x) { boolean needsInvalidate = false; final float deltaX = mLastMotionX - x; mLastMotionX = x; float oldScrollX = getScrollX(); float scrollX = oldScrollX + deltaX; final int width = getClientWidth(); float leftBound = width * mFirstOffset; float rightBound = width * mLastOffset; boolean leftAbsolute = true; boolean rightAbsolute = true; final ItemInfo firstItem = mItems.get(0); final ItemInfo lastItem = mItems.get(mItems.size() - 1); if (firstItem.position != 0) { leftAbsolute = false; leftBound = firstItem.offset * width; } if (lastItem.position != mAdapter.getCount() - 1) { rightAbsolute = false; rightBound = lastItem.offset * width; } if (scrollX < leftBound) { if (leftAbsolute) { float over = leftBound - scrollX; needsInvalidate = mLeftEdge.onPull(Math.abs(over) / width); } scrollX = leftBound; } else if (scrollX > rightBound) { if (rightAbsolute) { float over = scrollX - rightBound; needsInvalidate = mRightEdge.onPull(Math.abs(over) / width); } scrollX = rightBound; } // Don't lose the rounded component mLastMotionX += scrollX - (int) scrollX; scrollTo((int) scrollX, getScrollY()); pageScrolled((int) scrollX); return needsInvalidate; } /** * @return Info about the page at the current scroll position. * This can be synthetic for a missing middle page; the 'object' field can be null. */ private ItemInfo infoForCurrentScrollPosition() { final int width = getClientWidth(); final float scrollOffset = width > 0 ? (float) getScrollX() / width : 0; final float marginOffset = width > 0 ? (float) mPageMargin / width : 0; int lastPos = -1; float lastOffset = 0.f; float lastWidth = 0.f; boolean first = true; ItemInfo lastItem = null; for (int i = 0; i < mItems.size(); i++) { ItemInfo ii = mItems.get(i); float offset; if (!first && ii.position != lastPos + 1) { // Create a synthetic item for a missing page. ii = mTempItem; ii.offset = lastOffset + lastWidth + marginOffset; ii.position = lastPos + 1; ii.widthFactor = mAdapter.getPageWidth(ii.position); i--; } offset = ii.offset; final float leftBound = offset; final float rightBound = offset + ii.widthFactor + marginOffset; if (first || scrollOffset >= leftBound) { if (scrollOffset < rightBound || i == mItems.size() - 1) { return ii; } } else { return lastItem; } first = false; lastPos = ii.position; lastOffset = offset; lastWidth = ii.widthFactor; lastItem = ii; } return lastItem; } private int determineTargetPage(int currentPage, float pageOffset, int velocity, int deltaX) { int targetPage; if (Math.abs(deltaX) > mFlingDistance && Math.abs(velocity) > mMinimumVelocity) { targetPage = velocity > 0 ? currentPage : currentPage + 1; } else if (mSeenPositionMin >= 0 && mSeenPositionMin < currentPage && pageOffset < 0.5f) { targetPage = currentPage + 1; } else if (mSeenPositionMax >= 0 && mSeenPositionMax > currentPage + 1 && pageOffset >= 0.5f) { targetPage = currentPage - 1; } else { targetPage = (int) (currentPage + pageOffset + 0.5f); } if (mItems.size() > 0) { final ItemInfo firstItem = mItems.get(0); final ItemInfo lastItem = mItems.get(mItems.size() - 1); // Only let the user target pages we have items for targetPage = Math.max(firstItem.position, Math.min(targetPage, lastItem.position)); } return targetPage; } @Override public void draw(Canvas canvas) { super.draw(canvas); boolean needsInvalidate = false; final int overScrollMode = ViewCompat.getOverScrollMode(this); if (overScrollMode == ViewCompat.OVER_SCROLL_ALWAYS || (overScrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS && mAdapter != null && mAdapter.getCount() > 1)) { if (!mLeftEdge.isFinished()) { final int restoreCount = canvas.save(); final int height = getHeight() - getPaddingTop() - getPaddingBottom(); final int width = getWidth(); canvas.rotate(270); canvas.translate(-height + getPaddingTop(), mFirstOffset * width); mLeftEdge.setSize(height, width); needsInvalidate |= mLeftEdge.draw(canvas); canvas.restoreToCount(restoreCount); } if (!mRightEdge.isFinished()) { final int restoreCount = canvas.save(); final int width = getWidth(); final int height = getHeight() - getPaddingTop() - getPaddingBottom(); canvas.rotate(90); canvas.translate(-getPaddingTop(), -(mLastOffset + 1) * width); mRightEdge.setSize(height, width); needsInvalidate |= mRightEdge.draw(canvas); canvas.restoreToCount(restoreCount); } } else { mLeftEdge.finish(); mRightEdge.finish(); } if (needsInvalidate) { // Keep animating ViewCompat.postInvalidateOnAnimation(this); } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // Draw the margin drawable between pages if needed. if (mPageMargin > 0 && mMarginDrawable != null && mItems.size() > 0 && mAdapter != null) { final int scrollX = getScrollX(); final int width = getWidth(); final float marginOffset = (float) mPageMargin / width; int itemIndex = 0; ItemInfo ii = mItems.get(0); float offset = ii.offset; final int itemCount = mItems.size(); final int firstPos = ii.position; final int lastPos = mItems.get(itemCount - 1).position; for (int pos = firstPos; pos < lastPos; pos++) { while (pos > ii.position && itemIndex < itemCount) { ii = mItems.get(++itemIndex); } float drawAt; if (pos == ii.position) { drawAt = (ii.offset + ii.widthFactor) * width; offset = ii.offset + ii.widthFactor + marginOffset; } else { float widthFactor = mAdapter.getPageWidth(pos); drawAt = (offset + widthFactor) * width; offset += widthFactor + marginOffset; } if (drawAt + mPageMargin > scrollX) { mMarginDrawable.setBounds((int) drawAt, mTopPageBounds, (int) (drawAt + mPageMargin + 0.5f), mBottomPageBounds); mMarginDrawable.draw(canvas); } if (drawAt > scrollX + width) { break; // No more visible, no sense in continuing } } } } /** * Start a fake drag of the pager. * * <p>A fake drag can be useful if you want to synchronize the motion of the ViewPager * with the touch scrolling of another view, while still letting the ViewPager * control the snapping motion and fling behavior. (e.g. parallax-scrolling tabs.) * Call {@link #fakeDragBy(float)} to simulate the actual drag motion. Call * {@link #endFakeDrag()} to complete the fake drag and fling as necessary. * * <p>During a fake drag the ViewPager will ignore all touch events. If a real drag * is already in progress, this method will return false. * * @return true if the fake drag began successfully, false if it could not be started. * * @see #fakeDragBy(float) * @see #endFakeDrag() */ public boolean beginFakeDrag() { if (mIsBeingDragged) { return false; } mFakeDragging = true; setScrollState(SCROLL_STATE_DRAGGING); mInitialMotionX = mLastMotionX = 0; if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } else { mVelocityTracker.clear(); } final long time = SystemClock.uptimeMillis(); final MotionEvent ev = MotionEvent.obtain(time, time, MotionEvent.ACTION_DOWN, 0, 0, 0); mVelocityTracker.addMovement(ev); ev.recycle(); mFakeDragBeginTime = time; return true; } /** * End a fake drag of the pager. * * @see #beginFakeDrag() * @see #fakeDragBy(float) */ public void endFakeDrag() { if (!mFakeDragging) { throw new IllegalStateException("No fake drag in progress. Call beginFakeDrag first."); } final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); int initialVelocity = (int) VelocityTrackerCompat.getXVelocity( velocityTracker, mActivePointerId); mPopulatePending = true; final int width = getClientWidth(); final int scrollX = getScrollX(); final ItemInfo ii = infoForCurrentScrollPosition(); final int currentPage = ii.position; final float pageOffset = (((float) scrollX / width) - ii.offset) / ii.widthFactor; final int totalDelta = (int) (mLastMotionX - mInitialMotionX); int nextPage = determineTargetPage(currentPage, pageOffset, initialVelocity, totalDelta); setCurrentItemInternal(nextPage, true, true, initialVelocity); endDrag(); mFakeDragging = false; } /** * Fake drag by an offset in pixels. You must have called {@link #beginFakeDrag()} first. * * @param xOffset Offset in pixels to drag by. * @see #beginFakeDrag() * @see #endFakeDrag() */ public void fakeDragBy(float xOffset) { if (!mFakeDragging) { throw new IllegalStateException("No fake drag in progress. Call beginFakeDrag first."); } mLastMotionX += xOffset; float oldScrollX = getScrollX(); float scrollX = oldScrollX - xOffset; final int width = getClientWidth(); float leftBound = width * mFirstOffset; float rightBound = width * mLastOffset; final ItemInfo firstItem = mItems.get(0); final ItemInfo lastItem = mItems.get(mItems.size() - 1); if (firstItem.position != 0) { leftBound = firstItem.offset * width; } if (lastItem.position != mAdapter.getCount() - 1) { rightBound = lastItem.offset * width; } if (scrollX < leftBound) { scrollX = leftBound; } else if (scrollX > rightBound) { scrollX = rightBound; } // Don't lose the rounded component mLastMotionX += scrollX - (int) scrollX; scrollTo((int) scrollX, getScrollY()); pageScrolled((int) scrollX); // Synthesize an event for the VelocityTracker. final long time = SystemClock.uptimeMillis(); final MotionEvent ev = MotionEvent.obtain(mFakeDragBeginTime, time, MotionEvent.ACTION_MOVE, mLastMotionX, 0, 0); mVelocityTracker.addMovement(ev); ev.recycle(); } /** * Returns true if a fake drag is in progress. * * @return true if currently in a fake drag, false otherwise. * * @see #beginFakeDrag() * @see #fakeDragBy(float) * @see #endFakeDrag() */ public boolean isFakeDragging() { return mFakeDragging; } private void onSecondaryPointerUp(MotionEvent ev) { final int pointerIndex = MotionEventCompat.getActionIndex(ev); final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mLastMotionX = MotionEventCompat.getX(ev, newPointerIndex); mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex); if (mVelocityTracker != null) { mVelocityTracker.clear(); } } } private void endDrag() { mIsBeingDragged = false; mIsUnableToDrag = false; if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } } private void setScrollingCacheEnabled(boolean enabled) { if (mScrollingCacheEnabled != enabled) { mScrollingCacheEnabled = enabled; if (USE_CACHE) { final int size = getChildCount(); for (int i = 0; i < size; ++i) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { child.setDrawingCacheEnabled(enabled); } } } } } /** * Tests scrollability within child views of v given a delta of dx. * * @param v View to test for horizontal scrollability * @param checkV Whether the view v passed should itself be checked for scrollability (true), * or just its children (false). * @param dx Delta scrolled in pixels * @param x X coordinate of the active touch point * @param y Y coordinate of the active touch point * @return true if child views of v can be scrolled by delta of dx. */ protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) { if (v instanceof ViewGroup) { final ViewGroup group = (ViewGroup) v; final int scrollX = v.getScrollX(); final int scrollY = v.getScrollY(); final int count = group.getChildCount(); // Count backwards - let topmost views consume scroll distance first. for (int i = count - 1; i >= 0; i--) { // TODO: Add versioned support here for transformed views. // This will not work for transformed views in Honeycomb+ final View child = group.getChildAt(i); if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() && y + scrollY >= child.getTop() && y + scrollY < child.getBottom() && canScroll(child, true, dx, x + scrollX - child.getLeft(), y + scrollY - child.getTop())) { return true; } } } return checkV && ViewCompat.canScrollHorizontally(v, -dx); } @Override public boolean dispatchKeyEvent(KeyEvent event) { // Let the focused view and/or our descendants get the key first return super.dispatchKeyEvent(event) || executeKeyEvent(event); } /** * You can call this function yourself to have the scroll view perform * scrolling from a key event, just as if the event had been dispatched to * it by the view hierarchy. * * @param event The key event to execute. * @return Return true if the event was handled, else false. */ public boolean executeKeyEvent(KeyEvent event) { boolean handled = false; if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_DPAD_LEFT: handled = arrowScroll(FOCUS_LEFT); break; case KeyEvent.KEYCODE_DPAD_RIGHT: handled = arrowScroll(FOCUS_RIGHT); break; case KeyEvent.KEYCODE_TAB: if (Build.VERSION.SDK_INT >= 11) { // The focus finder had a bug handling FOCUS_FORWARD and FOCUS_BACKWARD // before Android 3.0. Ignore the tab key on those devices. if (KeyEventCompat.hasNoModifiers(event)) { handled = arrowScroll(FOCUS_FORWARD); } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) { handled = arrowScroll(FOCUS_BACKWARD); } } break; } } return handled; } public boolean arrowScroll(int direction) { View currentFocused = findFocus(); if (currentFocused == this) currentFocused = null; boolean handled = false; View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction); if (nextFocused != null && nextFocused != currentFocused) { if (direction == View.FOCUS_LEFT) { // If there is nothing to the left, or this is causing us to // jump to the right, then what we really want to do is page left. final int nextLeft = getChildRectInPagerCoordinates(mTempRect, nextFocused).left; final int currLeft = getChildRectInPagerCoordinates(mTempRect, currentFocused).left; if (currentFocused != null && nextLeft >= currLeft) { handled = pageLeft(); } else { handled = nextFocused.requestFocus(); } } else if (direction == View.FOCUS_RIGHT) { // If there is nothing to the right, or this is causing us to // jump to the left, then what we really want to do is page right. final int nextLeft = getChildRectInPagerCoordinates(mTempRect, nextFocused).left; final int currLeft = getChildRectInPagerCoordinates(mTempRect, currentFocused).left; if (currentFocused != null && nextLeft <= currLeft) { handled = pageRight(); } else { handled = nextFocused.requestFocus(); } } } else if (direction == FOCUS_LEFT || direction == FOCUS_BACKWARD) { // Trying to move left and nothing there; try to page. handled = pageLeft(); } else if (direction == FOCUS_RIGHT || direction == FOCUS_FORWARD) { // Trying to move right and nothing there; try to page. handled = pageRight(); } if (handled) { playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction)); } return handled; } private Rect getChildRectInPagerCoordinates(Rect outRect, View child) { if (outRect == null) { outRect = new Rect(); } if (child == null) { outRect.set(0, 0, 0, 0); return outRect; } outRect.left = child.getLeft(); outRect.right = child.getRight(); outRect.top = child.getTop(); outRect.bottom = child.getBottom(); ViewParent parent = child.getParent(); while (parent instanceof ViewGroup && parent != this) { final ViewGroup group = (ViewGroup) parent; outRect.left += group.getLeft(); outRect.right += group.getRight(); outRect.top += group.getTop(); outRect.bottom += group.getBottom(); parent = group.getParent(); } return outRect; } boolean pageLeft() { if (mCurItem > 0) { setCurrentItem(mCurItem-1, true); return true; } return false; } boolean pageRight() { if (mAdapter != null && mCurItem < (mAdapter.getCount()-1)) { setCurrentItem(mCurItem+1, true); return true; } return false; } /** * We only want the current page that is being shown to be focusable. */ @Override public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { final int focusableCount = views.size(); final int descendantFocusability = getDescendantFocusability(); if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) { for (int i = 0; i < getChildCount(); i++) { final View child = getChildAt(i); if (child.getVisibility() == VISIBLE) { ItemInfo ii = infoForChild(child); if (ii != null && ii.position == mCurItem) { child.addFocusables(views, direction, focusableMode); } } } } // we add ourselves (if focusable) in all cases except for when we are // FOCUS_AFTER_DESCENDANTS and there are some descendants focusable. this is // to avoid the focus search finding layouts when a more precise search // among the focusable children would be more interesting. if ( descendantFocusability != FOCUS_AFTER_DESCENDANTS || // No focusable descendants (focusableCount == views.size())) { // Note that we can't call the superclass here, because it will // add all views in. So we need to do the same thing View does. if (!isFocusable()) { return; } if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE && isInTouchMode() && !isFocusableInTouchMode()) { return; } if (views != null) { views.add(this); } } } /** * We only want the current page that is being shown to be touchable. */ @Override public void addTouchables(ArrayList<View> views) { // Note that we don't call super.addTouchables(), which means that // we don't call View.addTouchables(). This is okay because a ViewPager // is itself not touchable. for (int i = 0; i < getChildCount(); i++) { final View child = getChildAt(i); if (child.getVisibility() == VISIBLE) { ItemInfo ii = infoForChild(child); if (ii != null && ii.position == mCurItem) { child.addTouchables(views); } } } } /** * We only want the current page that is being shown to be focusable. */ @Override protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { int index; int increment; int end; int count = getChildCount(); if ((direction & FOCUS_FORWARD) != 0) { index = 0; increment = 1; end = count; } else { index = count - 1; increment = -1; end = -1; } for (int i = index; i != end; i += increment) { View child = getChildAt(i); if (child.getVisibility() == VISIBLE) { ItemInfo ii = infoForChild(child); if (ii != null && ii.position == mCurItem) { if (child.requestFocus(direction, previouslyFocusedRect)) { return true; } } } } return false; } @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { // ViewPagers should only report accessibility info for the current page, // otherwise things get very confusing. // TODO: Should this note something about the paging container? final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (child.getVisibility() == VISIBLE) { final ItemInfo ii = infoForChild(child); if (ii != null && ii.position == mCurItem && child.dispatchPopulateAccessibilityEvent(event)) { return true; } } } return false; } @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { return new LayoutParams(); } @Override protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { return generateDefaultLayoutParams(); } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { return p instanceof LayoutParams && super.checkLayoutParams(p); } @Override public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { return new LayoutParams(getContext(), attrs); } class MyAccessibilityDelegate extends AccessibilityDelegateCompat { @Override public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { super.onInitializeAccessibilityEvent(host, event); event.setClassName(ViewPager.class.getName()); } @Override public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) { super.onInitializeAccessibilityNodeInfo(host, info); info.setClassName(ViewPager.class.getName()); info.setScrollable(mAdapter != null && mAdapter.getCount() > 1); if (mAdapter != null && mCurItem >= 0 && mCurItem < mAdapter.getCount() - 1) { info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD); } if (mAdapter != null && mCurItem > 0 && mCurItem < mAdapter.getCount()) { info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD); } } @Override public boolean performAccessibilityAction(View host, int action, Bundle args) { if (super.performAccessibilityAction(host, action, args)) { return true; } switch (action) { case AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD: { if (mAdapter != null && mCurItem >= 0 && mCurItem < mAdapter.getCount() - 1) { setCurrentItem(mCurItem + 1); return true; } } return false; case AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD: { if (mAdapter != null && mCurItem > 0 && mCurItem < mAdapter.getCount()) { setCurrentItem(mCurItem - 1); return true; } } return false; } return false; } } private class PagerObserver extends DataSetObserver { @Override public void onChanged() { dataSetChanged(); } @Override public void onInvalidated() { dataSetChanged(); } } /** * Layout parameters that should be supplied for views added to a * ViewPager. */ public static class LayoutParams extends ViewGroup.LayoutParams { /** * true if this view is a decoration on the pager itself and not * a view supplied by the adapter. */ public boolean isDecor; /** * Gravity setting for use on decor views only: * Where to position the view page within the overall ViewPager * container; constants are defined in {@link android.view.Gravity}. */ public int gravity; /** * Width as a 0-1 multiplier of the measured pager width */ float widthFactor = 0.f; /** * true if this view was added during layout and needs to be measured * before being positioned. */ boolean needsMeasure; /** * Adapter position this view is for if !isDecor */ int position; /** * Current child index within the ViewPager that this view occupies */ int childIndex; public LayoutParams() { super(FILL_PARENT, FILL_PARENT); } public LayoutParams(Context context, AttributeSet attrs) { super(context, attrs); final TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS); gravity = a.getInteger(0, Gravity.TOP); a.recycle(); } } static class ViewPositionComparator implements Comparator<View> { @Override public int compare(View lhs, View rhs) { final LayoutParams llp = (LayoutParams) lhs.getLayoutParams(); final LayoutParams rlp = (LayoutParams) rhs.getLayoutParams(); if (llp.isDecor != rlp.isDecor) { return llp.isDecor ? 1 : -1; } return llp.position - rlp.position; } } }
false
false
null
null
diff --git a/src/wikipathways/org/pathvisio/gui/wikipathways/AppletUserInterfaceHandler.java b/src/wikipathways/org/pathvisio/gui/wikipathways/AppletUserInterfaceHandler.java index 22a5ae26..327f9139 100644 --- a/src/wikipathways/org/pathvisio/gui/wikipathways/AppletUserInterfaceHandler.java +++ b/src/wikipathways/org/pathvisio/gui/wikipathways/AppletUserInterfaceHandler.java @@ -1,54 +1,57 @@ // PathVisio, // a tool for data visualization and analysis using Biological Pathways // Copyright 2006-2007 BiGCaT Bioinformatics // // 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.pathvisio.gui.wikipathways; import java.awt.BorderLayout; import java.awt.Component; import java.awt.KeyboardFocusManager; import java.net.URL; import javax.swing.JApplet; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; public class AppletUserInterfaceHandler extends SwingUserInterfaceHandler { - JApplet applet; + PathwayPageApplet applet; - public AppletUserInterfaceHandler(JApplet applet) { + public AppletUserInterfaceHandler(PathwayPageApplet applet) { super(JOptionPane.getFrameForComponent(applet)); this.applet = applet; } public Component getParent() { parent = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); parent = SwingUtilities.getRoot(parent); return parent; } public void showExitMessage(String msg) { + if(applet.isFullScreen()) { + applet.toEmbedded(); + } JLabel label = new JLabel(msg, JLabel.CENTER); applet.getContentPane().removeAll(); applet.getContentPane().add(label, BorderLayout.CENTER); applet.getContentPane().validate(); applet.getContentPane().repaint(); } public void showDocument(URL url, String target) { applet.getAppletContext().showDocument(url, target); } }
false
false
null
null
diff --git a/PopulateNext/Solution.java b/PopulateNext/Solution.java index bbb4333..b7b9f6a 100644 --- a/PopulateNext/Solution.java +++ b/PopulateNext/Solution.java @@ -1,58 +1,64 @@ /** * Definition for binary tree with next pointer. * public class TreeLinkNode { * int val; * TreeLinkNode left, right, next; * TreeLinkNode(int x) { val = x; } * } */ public class Solution { private TreeLinkNode findNextParentWithChild(TreeLinkNode node) { while(node.next != null) { node = node.next; if (node.left != null || node.right != null) return node; } return null; } public void connect(TreeLinkNode root) { // Start typing your Java solution below // DO NOT write main() function TreeLinkNode parent = root; TreeLinkNode nextParent = null; - while(parent != null && nextParent != null) { + while(parent != null || nextParent != null) { while(parent != null) { if(parent.left != null){ + if(nextParent == null){ + nextParent = parent.left; + } if(parent.right != null){ parent.left.next = parent.right; } else { TreeLinkNode nextParentWithChild = findNextParentWithChild(parent); if(nextParentWithChild == null) { parent.left.next = null; } else{ parent.left.next = (nextParentWithChild.left != null)? (nextParentWithChild.left):(nextParentWithChild.right); } } } if(parent.right != null) { - TreeLinkNode nextParentWithChild = findNextParentWithChild(parent); - if(nextParentWithChild == null) { - parent.right.next = null; - } - else{ - parent.right.next = (nextParentWithChild.left != null)? - (nextParentWithChild.left):(nextParentWithChild.right); - } + if(nextParent == null) { + nextParent = parent.right; + } + TreeLinkNode nextParentWithChild = findNextParentWithChild(parent); + if(nextParentWithChild == null) { + parent.right.next = null; + } + else{ + parent.right.next = (nextParentWithChild.left != null)? + (nextParentWithChild.left):(nextParentWithChild.right); + } } parent = parent.next; } if(nextParent != null) { parent = nextParent; nextParent = null; } } } }
false
true
public void connect(TreeLinkNode root) { // Start typing your Java solution below // DO NOT write main() function TreeLinkNode parent = root; TreeLinkNode nextParent = null; while(parent != null && nextParent != null) { while(parent != null) { if(parent.left != null){ if(parent.right != null){ parent.left.next = parent.right; } else { TreeLinkNode nextParentWithChild = findNextParentWithChild(parent); if(nextParentWithChild == null) { parent.left.next = null; } else{ parent.left.next = (nextParentWithChild.left != null)? (nextParentWithChild.left):(nextParentWithChild.right); } } } if(parent.right != null) { TreeLinkNode nextParentWithChild = findNextParentWithChild(parent); if(nextParentWithChild == null) { parent.right.next = null; } else{ parent.right.next = (nextParentWithChild.left != null)? (nextParentWithChild.left):(nextParentWithChild.right); } } parent = parent.next; } if(nextParent != null) { parent = nextParent; nextParent = null; } } }
public void connect(TreeLinkNode root) { // Start typing your Java solution below // DO NOT write main() function TreeLinkNode parent = root; TreeLinkNode nextParent = null; while(parent != null || nextParent != null) { while(parent != null) { if(parent.left != null){ if(nextParent == null){ nextParent = parent.left; } if(parent.right != null){ parent.left.next = parent.right; } else { TreeLinkNode nextParentWithChild = findNextParentWithChild(parent); if(nextParentWithChild == null) { parent.left.next = null; } else{ parent.left.next = (nextParentWithChild.left != null)? (nextParentWithChild.left):(nextParentWithChild.right); } } } if(parent.right != null) { if(nextParent == null) { nextParent = parent.right; } TreeLinkNode nextParentWithChild = findNextParentWithChild(parent); if(nextParentWithChild == null) { parent.right.next = null; } else{ parent.right.next = (nextParentWithChild.left != null)? (nextParentWithChild.left):(nextParentWithChild.right); } } parent = parent.next; } if(nextParent != null) { parent = nextParent; nextParent = null; } } }
diff --git a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/BrowseFilteredListener.java b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/BrowseFilteredListener.java index c8d1afa20..5a24bec2b 100644 --- a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/BrowseFilteredListener.java +++ b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/BrowseFilteredListener.java @@ -1,172 +1,181 @@ /******************************************************************************* * Copyright (c) 2004, 2007 Mylyn project committers 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 *******************************************************************************/ package org.eclipse.mylyn.internal.context.ui; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.mylyn.context.ui.InterestFilter; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; +import org.eclipse.ui.PlatformUI; import org.eclipse.ui.navigator.CommonViewer; /** * @author Mik Kersten */ public class BrowseFilteredListener implements MouseListener, KeyListener { private StructuredViewer viewer; public BrowseFilteredListener(StructuredViewer viewer) { this.viewer = viewer; } /** * @param treeViewer * cannot be null * @param targetSelection * cannot be null */ public void unfilterSelection(TreeViewer treeViewer, IStructuredSelection targetSelection) { InterestFilter filter = getInterestFilter(treeViewer); Object targetObject = targetSelection.getFirstElement(); if (targetObject != null) { filter.setTemporarilyUnfiltered(targetObject); if (targetObject instanceof Tree) { treeViewer.refresh(); } else { treeViewer.refresh(targetObject, true); treeViewer.expandToLevel(targetObject, 1); } } } private void unfilter(final InterestFilter filter, final TreeViewer treeViewer, Object targetObject) { if (targetObject != null) { filter.setTemporarilyUnfiltered(targetObject); if (targetObject instanceof Tree) { treeViewer.refresh(); } else { treeViewer.refresh(targetObject, true); treeViewer.expandToLevel(targetObject, 1); } } } public void keyPressed(KeyEvent event) { // ignore } public void keyReleased(KeyEvent event) { InterestFilter filter = getInterestFilter(viewer); if (event.keyCode == SWT.ARROW_RIGHT) { if (filter == null || !(viewer instanceof TreeViewer)) { return; } final TreeViewer treeViewer = (TreeViewer) viewer; ISelection selection = treeViewer.getSelection(); if (selection instanceof IStructuredSelection) { Object targetObject = ((IStructuredSelection) selection).getFirstElement(); unfilter(filter, treeViewer, targetObject); } } } public void mouseDown(MouseEvent event) { + // ignore + } + + public void mouseDoubleClick(MouseEvent e) { + // ignore + } + + public void mouseUp(MouseEvent event) { final InterestFilter filter = getInterestFilter(viewer); if (filter == null || !(viewer instanceof TreeViewer)) { return; } TreeViewer treeViewer = (TreeViewer) viewer; Object selectedObject = null; Object clickedObject = getClickedItem(event); if (clickedObject != null) { selectedObject = clickedObject; } else { selectedObject = treeViewer.getTree(); } if (isUnfilterEvent(event)) { if (treeViewer instanceof CommonViewer) { CommonViewer commonViewer = (CommonViewer) treeViewer; commonViewer.setSelection(new StructuredSelection(selectedObject), true); } unfilter(filter, treeViewer, selectedObject); } else { if (event.button == 1) { if ((event.stateMask & SWT.MOD1) != 0) { viewer.setSelection(new StructuredSelection(selectedObject)); + viewer.refresh(selectedObject); } else { - Object unfiltered = filter.getTemporarilyUnfiltered(); + final Object unfiltered = filter.getTemporarilyUnfiltered(); if (unfiltered != null) { filter.resetTemporarilyUnfiltered(); // NOTE: need to set selection otherwise it will be missed viewer.setSelection(new StructuredSelection(selectedObject)); - viewer.refresh(unfiltered); + + // TODO: using asyncExec so that viewer has chance to open + PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { + + public void run() { + viewer.refresh(unfiltered); + } + }); } } } } } - + private Object getClickedItem(MouseEvent event) { if (event.getSource() instanceof Table) { TableItem item = ((Table) event.getSource()).getItem(new Point(event.x, event.y)); if (item != null) { return item.getData(); } else { return null; } } else if (event.getSource() instanceof Tree) { TreeItem item = ((Tree) event.getSource()).getItem(new Point(event.x, event.y)); if (item != null) { return item.getData(); } else { return null; } } return null; } public static boolean isUnfilterEvent(MouseEvent event) { return (event.stateMask & SWT.ALT) != 0; } private InterestFilter getInterestFilter(StructuredViewer structuredViewer) { ViewerFilter[] filters = structuredViewer.getFilters(); for (int i = 0; i < filters.length; i++) { if (filters[i] instanceof InterestFilter) return (InterestFilter) filters[i]; } return null; } - - public void mouseUp(MouseEvent e) { - // ignore - } - - public void mouseDoubleClick(MouseEvent e) { - } - }
false
false
null
null
diff --git a/msv/src/com/sun/msv/reader/GrammarReader.java b/msv/src/com/sun/msv/reader/GrammarReader.java index 65c4e99a..cb83beb4 100644 --- a/msv/src/com/sun/msv/reader/GrammarReader.java +++ b/msv/src/com/sun/msv/reader/GrammarReader.java @@ -1,680 +1,682 @@ /* * @(#)$Id$ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader; import org.xml.sax.ContentHandler; import org.xml.sax.XMLReader; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.LocatorImpl; import org.xml.sax.helpers.NamespaceSupport; import org.xml.sax.helpers.XMLFilterImpl; import org.relaxng.datatype.DataType; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.Stack; import java.util.Vector; import java.util.Enumeration; import java.io.IOException; import java.net.URL; import java.net.MalformedURLException; import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.ParserConfigurationException; import com.sun.msv.grammar.*; import com.sun.msv.grammar.trex.*; import com.sun.msv.util.StartTagInfo; /** * base implementation of grammar readers that read grammar from SAX2 stream. * * GrammarReader class can be used as a ContentHandler that parses a grammar. * So the typical usage is * <PRE><XMP> * * GrammarReader reader = new RELAXGrammarReader(...); * XMLReader parser = .... // create a new XMLReader here * * parser.setContentHandler(reader); * parser.parse(whateverYouLike); * return reader.grammar; // obtain parsed grammar. * </XMP></PRE> * * Or you may want to use several pre-defined static "parse" methods for * ease of use. * * @seealso com.sun.msv.reader.relax.RELAXReader#parse * @seealso com.sun.msv.reader.trex.TREXGrammarReader#parse * * @author <a href="mailto:[email protected]">Kohsuke KAWAGUCHI</a> */ public abstract class GrammarReader extends XMLFilterImpl implements IDContextProvider { /** document Locator that is given by XML reader */ public Locator locator; /** this object receives errors and warnings */ public final GrammarReaderController controller; /** Reader may create another SAXParser from this factory */ public final SAXParserFactory parserFactory; /** this object must be used to create a new expression */ public final ExpressionPool pool; /** constructor that should be called from parse method. */ protected GrammarReader( GrammarReaderController controller, SAXParserFactory parserFactory, ExpressionPool pool, State initialState ) { this.controller = controller; this.parserFactory = parserFactory; if( !parserFactory.isNamespaceAware() ) throw new IllegalArgumentException("parser factory must be namespace-aware"); this.pool = pool; pushState( initialState, null ); } /** checks if given element is that of the grammar elements. */ protected abstract boolean isGrammarElement( StartTagInfo tag ); /** * namespace prefix to URI conversion map. * this variable is evacuated to InclusionContext when the parser is switched. */ public NamespaceSupport namespaceSupport = new NamespaceSupport(); /** * calls processName method of NamespaceSupport. * Therefore this method returns null if it fails to process QName. */ public final String[] splitQName( String qName ) { return namespaceSupport.processName(qName, new String[3], false ); } /** * intercepts an expression made by ExpressionState * before it is passed to the parent state. * * derived class can perform further wrap-up before it is received by the parent. * This mechanism is used by RELAXReader to handle occurs attribute. */ protected Expression interceptExpression( ExpressionState state, Expression exp ) { return exp; } /** * gets DataType object from type name. * * If undefined type name is specified, this method is responsible * to report an error, and recover. * * @param typeName * For RELAX, this is unqualified type name. For TREX, * this is a QName. */ public abstract DataType resolveDataType( String typeName ); /** * map from type name of Candidate Recommendation to the current type. */ private static final Map deprecatedTypes = initDeprecatedTypes(); private static Map initDeprecatedTypes() { Map m = new java.util.HashMap(); m.put("uriReference", com.sun.msv.datatype.AnyURIType.theInstance ); m.put("number", com.sun.msv.datatype.NumberType.theInstance ); m.put("timeDuration", com.sun.msv.datatype.DurationType.theInstance ); m.put("CDATA", com.sun.msv.datatype.NormalizedStringType.theInstance ); m.put("year", com.sun.msv.datatype.GYearType.theInstance ); m.put("yearMonth", com.sun.msv.datatype.GYearMonthType.theInstance ); m.put("month", com.sun.msv.datatype.GMonthType.theInstance ); m.put("monthDay", com.sun.msv.datatype.GMonthDayType.theInstance ); m.put("day", com.sun.msv.datatype.GDayType.theInstance ); return m; } /** * tries to obtain a DataType object by resolving obsolete names. * this method is useful for backward compatibility purpose. */ public DataType getBackwardCompatibleType( String typeName ) { DataType dt = (DataType)deprecatedTypes.get(typeName); if( dt!=null ) reportWarning( WRN_DEPRECATED_TYPENAME, typeName, dt.displayName() ); return dt; } // parsing and related services //====================================================== /** * information that must be sheltered before switching InputSource * (typically by inclusion). * * It is chained by previousContext field and used as a stack. */ private class InclusionContext { final NamespaceSupport nsSupport; final Locator locator; final String systemId; final InclusionContext previousContext; InclusionContext( NamespaceSupport ns, Locator loc, String sysId, InclusionContext prev ) { this.nsSupport = ns; this.locator = loc; this.systemId = sysId; this.previousContext = prev; } } /** current inclusion context */ private InclusionContext pendingIncludes; private void pushInclusionContext( ) { pendingIncludes = new InclusionContext( namespaceSupport, locator, locator.getSystemId(), pendingIncludes ); namespaceSupport = new NamespaceSupport(); locator = null; } private void popInclusionContext() { namespaceSupport = pendingIncludes.nsSupport; locator = pendingIncludes.locator; pendingIncludes = pendingIncludes.previousContext; } /** stores all URL of grammars currently being parsed. * * say "foo.rlx" includes "bar.rlx" and "bar.rlx" include "joe.rlx". * Then this stack hold "foo.rlx","bar.rlx","joe.rlx" when parsing "joe.rlx". */ private Stack includeStack = new Stack(); /** * resolve relative URL to the absolute URL. * * Also this method allows GrammarReaderController to redirect or * prohibit inclusion. * * @return * return null if an error occurs. */ public final InputSource resolveLocation( String url ) { // resolve a relative URL to an absolute one try { url = new URL( new URL(locator.getSystemId()), url ).toExternalForm(); } catch( MalformedURLException e ) {} try { InputSource source = controller.resolveEntity(null,url); if(source==null) return new InputSource(url); // default handling else return source; } catch( IOException ie ) { reportError( ie, ERR_IO_EXCEPTION ); return null; } catch( SAXException se ) { reportError( se, ERR_SAX_EXCEPTION ); return null; } } /** * switchs InputSource to the specified URL and * parses it by the specified state. * * derived classes can use this method to realize semantics of 'include'. * * @param newState * this state will parse top-level of new XML source. * this state receives document element by its createChildState method. */ public void switchSource( String url, State newState ) { final InputSource source = resolveLocation(url); if(source==null) return; // recover by ignoring this. url = source.getSystemId(); for( InclusionContext ic = pendingIncludes; ic!=null; ic=ic.previousContext ) if( ic.systemId.equals(url) ) { // recursive include. // computes what files are recurisve. String s=""; for( int i = includeStack.indexOf(url); i<includeStack.size(); i++ ) s += includeStack.elementAt(i) + " > "; s += url; reportError( ERR_RECURSIVE_INCLUDE, url ); return; // recover by ignoring this include. } pushInclusionContext(); State currentState = getCurrentState(); try { // this state will receive endDocument event. pushState( newState, null ); _parse( source, currentState.location ); } finally { // restore the current state. super.setContentHandler(currentState); popInclusionContext(); } } /** parses a grammar from the specified source */ public final void parse( String source ) { _parse(source,null); } /** parses a grammar from the specified source */ public final void parse( InputSource source ) { _parse(source,null); } /** parses a grammar from the specified source */ private void _parse( Object source, Locator errorSource ) { try { XMLReader reader = parserFactory.newSAXParser().getXMLReader(); reader.setContentHandler(this); // invoke XMLReader if( source instanceof InputSource ) reader.parse((InputSource)source); if( source instanceof String ) reader.parse((String)source); } catch( ParserConfigurationException e ) { reportError( ERR_XMLPARSERFACTORY_EXCEPTION, new Object[]{e.getMessage()}, e, new Locator[]{errorSource} ); } catch( IOException e ) { reportError( ERR_IO_EXCEPTION, new Object[]{e.getMessage()}, e, new Locator[]{errorSource} ); } catch( SAXException e ) { reportError( ERR_SAX_EXCEPTION, new Object[]{e.getMessage()}, e, new Locator[]{errorSource} ); } } /** * memorizes what declarations are referenced from where. * * this information is used to report the source of errors. */ public class BackwardReferenceMap { private final Map impl = new java.util.HashMap(); /** memorize a reference to an object. */ public void memorizeLink( Object target ) { ArrayList list; if( impl.containsKey(target) ) list = (ArrayList)impl.get(target); else { // new target. list = new ArrayList(); impl.put(target,list); } list.add(new LocatorImpl(locator)); } /** * gets all the refer who have a reference to this object. * @return null * if no one refers it. */ public Locator[] getReferer( Object target ) { // TODO: does anyone want to get all of the refer? if( impl.containsKey(target) ) { ArrayList lst = (ArrayList)impl.get(target); Locator[] locs = new Locator[lst.size()]; lst.toArray(locs); return locs; } else return null; } } /** keeps track of all backward references to every ReferenceExp. * * this map should be used to report the source of error * of undefined-something. */ public final BackwardReferenceMap backwardReference = new BackwardReferenceMap(); /** this map remembers where ReferenceExps are defined, * and where user defined types are defined. * * some ReferenceExp can be defined * in more than one location. * In those cases, the last one is always memorized. * This behavior is essential to correctly implement * TREX constraint that no two &lt;define&gt; is allowed in the same file. */ private final Map declaredLocations = new java.util.HashMap(); public void setDeclaredLocationOf( Object o ) { declaredLocations.put(o, new LocatorImpl(locator) ); } public Locator getDeclaredLocationOf( Object o ) { return (Locator)declaredLocations.get(o); } /** * detects undefined ReferenceExp and reports it as an error. * * this method is used in the final wrap-up process of parsing. */ public void detectUndefinedOnes( ReferenceContainer container, String errMsg ) { Iterator itr = container.iterator(); while( itr.hasNext() ) { // ReferenceExp object is created when it is first referenced or defined. // its exp field is supplied when it is defined. // therefore, ReferenceExp with its exp field null means // it is referenced but not defined. ReferenceExp ref = (ReferenceExp)itr.next(); if( !ref.isDefined() ) { reportError( backwardReference.getReferer(ref), errMsg, new Object[]{ref.name} ); ref.exp=Expression.nullSet; // recover by assuming a null definition. } } } // // stack of State objects and related services //============================================================ /** pushs the current state into the stack and sets new one */ public void pushState( State newState, StartTagInfo startTag ) { // ASSERT : parser.getContentHandler()==newState.parentState State parentState = getCurrentState(); super.setContentHandler(newState); newState.init( this, parentState, startTag ); // this order of statements ensures that // getCurrentState can be implemented by using getContentHandler() } /** pops the previous state from the stack */ public void popState() { State currentState = getCurrentState(); if( currentState.parentState!=null ) super.setContentHandler( currentState.parentState ); else // if the root state is poped, supply a dummy. super.setContentHandler( new org.xml.sax.helpers.DefaultHandler() ); } /** gets current State object. */ public final State getCurrentState() { return (State)super.getContentHandler(); } /** * this method must be implemented by the derived class to create * language-default expresion state. */ public abstract State createExpressionChildState( State parent, StartTagInfo tag ); // SAX events interception //============================================ public void startElement( String a, String b, String c, Attributes d ) throws SAXException { namespaceSupport.pushContext(); super.startElement(a,b,c,d); } public void endElement( String a, String b, String c ) throws SAXException { super.endElement(a,b,c); namespaceSupport.popContext(); } public void setDocumentLocator( Locator loc ) { super.setDocumentLocator(loc); this.locator = loc; } public void startPrefixMapping(String prefix, String uri ) throws SAXException { super.startPrefixMapping(prefix,uri); namespaceSupport.declarePrefix(prefix,uri); } public void endPrefixMapping(String prefix) {} // validation context provider //============================================ // implementing ValidationContextProvider is neccessary // to correctly handle facets. public String resolveNamespacePrefix( String prefix ) { return namespaceSupport.getURI(prefix); } public boolean isUnparsedEntity( String entityName ) { // we have to allow everything here? return true; } // when the user uses enumeration over ID type, // this method will be called. // To make it work, simply allow everything. public boolean onID( String symbolSpace, Object token ) { return true; } public void onIDREF( String symbolSpace, Object token ) {} /** * returns a persistent ValidationContextProvider. * this context provider is necessary to late-bind simple types. */ /* public IDContextProvider getPersistentVCP() { // dump prefix->URI mapping into a map. final Map prefixes = new java.util.HashMap(); Enumeration e = namespaceSupport.getDeclaredPrefixes(); while( e.hasMoreElements() ) { String prefix = (String)e.nextElement(); prefixes.put( prefix, namespaceSupport.getURI(prefix) ); } return new IDContextProvider(){ public String resolveNamespacePrefix( String prefix ) { return (String)prefixes.get(prefix); } public boolean isUnparsedEntity( String entityName ) { return true; } public boolean onID( String token ) { return true; } public void onIDREF( String token ) {} }; } */ // back patching //=========================================== /* several things cannot be done at the moment when the declaration is seen. These things have to be postponed until all the necessary information is prepared. (e.g., generating the expression that matches to <any />). those jobs are queued here and processed after the parsing is completed. Note that there is no mechanism in this class to execute jobs. The derived class has to decide its own timing to perform jobs. */ public static interface BackPatch { /** do back-patching. */ void patch(); /** gets State object who has submitted this patch job. */ State getOwnerState(); } protected final Vector backPatchJobs = new Vector(); public void addBackPatchJob( BackPatch job ) { backPatchJobs.add(job); } // error related services //======================================================== /** this flag is set to true if reportError method is called. * * Derived classes must check this flag to determine whether the parsing * was successful or not. */ public boolean hadError = false; public final void reportError( String propertyName ) { reportError( propertyName, null, null, null ); } public final void reportError( String propertyName, Object arg1 ) { reportError( propertyName, new Object[]{arg1}, null, null ); } public final void reportError( String propertyName, Object arg1, Object arg2 ) { reportError( propertyName, new Object[]{arg1,arg2}, null, null ); } public final void reportError( String propertyName, Object arg1, Object arg2, Object arg3 ) { reportError( propertyName, new Object[]{arg1,arg2,arg3}, null, null ); } public final void reportError( Exception nestedException, String propertyName ) { reportError( propertyName, null, nestedException, null ); } public final void reportError( Exception nestedException, String propertyName, Object arg1 ) { reportError( propertyName, new Object[]{arg1}, nestedException, null ); } public final void reportError( Locator[] locs, String propertyName, Object[] args ) { reportError( propertyName, args, null, locs ); } public final void reportWarning( String propertyName, Object arg1 ) { reportWarning( propertyName, new Object[]{arg1}, null ); } public final void reportWarning( String propertyName, Object arg1, Object arg2 ) { reportWarning( propertyName, new Object[]{arg1,arg2}, null ); } private Locator[] prepareLocation( Locator[] param ) { // if null is given, use the current location. if( param!=null ) { int cnt=0; for( int i=0; i<param.length; i++ ) if( param[i]!=null ) cnt++; if( param.length==cnt ) return param; // remove null from the array. Locator[] locs = new Locator[cnt]; cnt=0; for( int i=0; i<param.length; i++ ) if( param[i]!=null ) locs[cnt++] = param[i]; return locs; } if( locator!=null ) return new Locator[]{locator}; else return new Locator[0]; } /** reports an error to the controller */ public final void reportError( String propertyName, Object[] args, Exception nestedException, Locator[] errorLocations ) { hadError = true; controller.error( prepareLocation(errorLocations), localizeMessage(propertyName,args), nestedException ); } /** reports a warning to the controller */ public final void reportWarning( String propertyName, Object[] args, Locator[] locations ) { controller.warning( prepareLocation(locations), localizeMessage(propertyName,args) ); } /** formats localized message with arguments */ protected abstract String localizeMessage( String propertyName, Object[] args ); public static final String ERR_MALPLACED_ELEMENT = // arg:1 "GrammarReader.MalplacedElement"; public static final String ERR_IO_EXCEPTION = // arg:1 "GrammarReader.IOException"; public static final String ERR_SAX_EXCEPTION = // arg:1 "GrammarReader.SAXException"; public static final String ERR_XMLPARSERFACTORY_EXCEPTION = // arg:1 "GrammarReader.XMLParserFactoryException"; public static final String ERR_CHARACTERS = // arg:1 "GrammarReader.Characters"; + public static final String ERR_DISALLOWED_ATTRIBUTE = // arg:2 + "GrammarReader.DisallowedAttribute"; public static final String ERR_MISSING_ATTRIBUTE = // arg:2 "GrammarReader.MissingAttribute"; public static final String ERR_BAD_ATTRIBUTE_VALUE = // arg:2 "GrammarReader.BadAttributeValue"; public static final String ERR_MISSING_ATTRIBUTE_2 = // arg:3 "GrammarReader.MissingAttribute.2"; public static final String ERR_CONFLICTING_ATTRIBUTES = // arg:2 "GrammarReader.ConflictingAttribute"; public static final String ERR_RECURSIVE_INCLUDE = // arg:1 "GrammarReader.RecursiveInclude"; public static final String ERR_UNDEFINED_DATATYPE = // arg:1 "GrammarReader.UndefinedDataType"; public static final String ERR_DATATYPE_ALREADY_DEFINED = // arg:1 "GrammarReader.DataTypeAlreadyDefined"; public static final String ERR_MISSING_CHILD_EXPRESSION = // arg:none "GrammarReader.Abstract.MissingChildExpression"; public static final String ERR_MORE_THAN_ONE_CHILD_EXPRESSION = // arg:none "GrammarReader.Abstract.MoreThanOneChildExpression"; public static final String ERR_MORE_THAN_ONE_CHILD_TYPE = // arg:none "GrammarReader.Abstract.MoreThanOneChildType"; public static final String ERR_MISSING_CHILD_TYPE = // arg:none "GrammarReader.Abstract.MissingChildType"; public static final String ERR_ILLEGAL_FINAL_VALUE = "GrammarReader.IllegalFinalValue"; public static final String ERR_RUNAWAY_EXPRESSION = // arg:1 "GrammarReader.Abstract.RunAwayExpression"; public static final String ERR_MISSING_TOPLEVEL = // arg:0 "GrammarReader.Abstract.MissingTopLevel"; public static final String WRN_MAYBE_WRONG_NAMESPACE = // arg:1 "GrammarReader.Warning.MaybeWrongNamespace"; public static final String WRN_DEPRECATED_TYPENAME = // arg:2 "GrammarReader.Warning.DeprecatedTypeName"; public static final String ERR_BAD_TYPE = // arg:1 "GrammarReader.BadType"; }
true
false
null
null
diff --git a/jOOQ-meta/src/main/java/org/jooq/util/TableDefinition.java b/jOOQ-meta/src/main/java/org/jooq/util/TableDefinition.java index 562ed5a2b..96ee1411e 100644 --- a/jOOQ-meta/src/main/java/org/jooq/util/TableDefinition.java +++ b/jOOQ-meta/src/main/java/org/jooq/util/TableDefinition.java @@ -1,97 +1,97 @@ /** * Copyright (c) 2009-2013, Lukas Eder, [email protected] * All rights reserved. * * This software is licensed to you under the Apache License, Version 2.0 * (the "License"); You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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 "jOOQ" 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 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 org.jooq.util; import java.util.List; import org.jooq.Record; import org.jooq.Table; /** * The definition of a table or view. * * @author Lukas Eder */ public interface TableDefinition extends Definition { /** - * All columns in the type, table or view + * All columns in the type, table or view. */ List<ColumnDefinition> getColumns(); /** - * Get a column in this type by its name + * Get a column in this type by its name. */ ColumnDefinition getColumn(String columnName); /** - * Get a column in this type by its name + * Get a column in this type by its name. */ ColumnDefinition getColumn(String columnName, boolean ignoreCase); /** - * Get a column in this type by its index (starting at 0) + * Get a column in this type by its index (starting at 0). */ ColumnDefinition getColumn(int columnIndex); /** - * Get the primary key for this table + * Get the primary key for this table. */ UniqueKeyDefinition getPrimaryKey(); /** - * Get the unique keys for this table + * Get the unique keys for this table. */ List<UniqueKeyDefinition> getUniqueKeys(); /** - * Get the foreign keys for this table + * Get the foreign keys for this table. */ List<ForeignKeyDefinition> getForeignKeys(); /** * Get the <code>IDENTITY</code> column of this table, or <code>null</code>, * if no such column exists. */ IdentityDefinition getIdentity(); /** - * This TableDefinition as a {@link Table} + * This TableDefinition as a {@link Table}. */ Table<Record> getTable(); }
false
false
null
null
diff --git a/org.spoofax.jsglr/src/org/spoofax/jsglr/client/FineGrainedOnRegion.java b/org.spoofax.jsglr/src/org/spoofax/jsglr/client/FineGrainedOnRegion.java index b05357a2..af2ba6f8 100644 --- a/org.spoofax.jsglr/src/org/spoofax/jsglr/client/FineGrainedOnRegion.java +++ b/org.spoofax.jsglr/src/org/spoofax/jsglr/client/FineGrainedOnRegion.java @@ -1,177 +1,177 @@ package org.spoofax.jsglr.client; import java.util.ArrayList; public class FineGrainedOnRegion { private int acceptRecoveryPosition; private int regionEndPosition; private ArrayList<BacktrackPosition> choicePoints; private static int MAX_BACK_JUMPS=5; private SGLR mySGLR; private ParserHistory getHistory() { return mySGLR.getHistory(); } public void setInfoFGOnly(){ regionEndPosition=mySGLR.tokensSeen+5; acceptRecoveryPosition=regionEndPosition+10; int lastIndex=getHistory().getIndexLastLine(); for (int i = 0; i < lastIndex; i++) { IndentInfo line= getHistory().getLine(i); if(line.getStackNodes()!=null && line.getStackNodes().size()>0){ BacktrackPosition btPoint=new BacktrackPosition(line.getStackNodes(), line.getTokensSeen()); btPoint.setIndexHistory(i); choicePoints.add(btPoint); } } } public void setRegionInfo(StructureSkipSuggestion erroneousRegion, int acceptPosition){ regionEndPosition=erroneousRegion.getEndSkip().getTokensSeen(); acceptRecoveryPosition=acceptPosition; int lastIndex=Math.min(erroneousRegion.getIndexHistoryEnd(), getHistory().getIndexLastLine()); assert( - lastIndex>0 && + lastIndex >= 0 && erroneousRegion.getIndexHistoryStart()>=0 && erroneousRegion.getIndexHistoryStart()<=erroneousRegion.getIndexHistoryEnd() ); for (int i = erroneousRegion.getIndexHistoryStart(); i < lastIndex; i++) { IndentInfo line= getHistory().getLine(i); - if(line.getStackNodes()!=null && line.getStackNodes().size()>0){ + if (line.getStackNodes() != null && line.getStackNodes().size()>0){ BacktrackPosition btPoint=new BacktrackPosition(line.getStackNodes(), line.getTokensSeen()); btPoint.setIndexHistory(i); choicePoints.add(btPoint); } } } public boolean recover() { int btIndex=choicePoints.size()-1; if(btIndex>=0) return recoverFrom(btIndex, new ArrayList<RecoverNode>()); return false; } private boolean recoverFrom(int btIndex, ArrayList<RecoverNode> unexplored_branches) { ArrayList<RecoverNode> rec_Branches=new ArrayList<RecoverNode>(); if(btIndex>=0){ rec_Branches=collectRecoverBranches(btIndex); //collect permissive branches at btIndex line resetSGLR(btIndex); } else resetSGLR(0); rec_Branches.addAll(unexplored_branches); ArrayList<RecoverNode> newbranches=recoverParse(rec_Branches, regionEndPosition); //explore and collect if(acceptParse()) return true; if(choicePoints.size()-1-btIndex > MAX_BACK_JUMPS){ if(btIndex>0){ //Permissive branches constructed by one recovery are always explored ArrayList<RecoverNode> rec_Branches_prefix=new ArrayList<RecoverNode>(); rec_Branches_prefix=collectRecoverBranches(0, btIndex); resetSGLR(0); recoverParse(rec_Branches_prefix, regionEndPosition); return acceptParse(); } return false; } return recoverFrom(btIndex-1, newbranches); } private void resetSGLR(int btIndex) { BacktrackPosition btrPosition=choicePoints.get(btIndex); mySGLR.activeStacks.clear(true); //only permissive branches are explored getHistory().setTokenIndex(btrPosition.tokensSeen); } private ArrayList<RecoverNode> collectRecoverBranches(int btIndex) { resetSGLR(btIndex); mySGLR.activeStacks.addAll(choicePoints.get(btIndex).recoverStacks); int endPos=btIndex<choicePoints.size()-1 ? choicePoints.get(btIndex+1).tokensSeen-1 : regionEndPosition; ArrayList<RecoverNode> rec1_Branches=recoverParse(new ArrayList<RecoverNode>(), endPos); return rec1_Branches; } private ArrayList<RecoverNode> collectRecoverBranches(int btIndex, int btIndex_end) { resetSGLR(btIndex); mySGLR.activeStacks.addAll(choicePoints.get(btIndex).recoverStacks); int endPos=btIndex_end < choicePoints.size() ? choicePoints.get(btIndex_end).tokensSeen-1 : regionEndPosition; ArrayList<RecoverNode> rec1_Branches=recoverParse(new ArrayList<RecoverNode>(), endPos); return rec1_Branches; } /** * Explores permissive branches, and collects derived branches with higher recover count */ private ArrayList<RecoverNode> recoverParse(ArrayList<RecoverNode> candidates, int endRecoverSearchPos) { mySGLR.setFineGrainedOnRegion(true); ArrayList<RecoverNode> newCandidates=new ArrayList<RecoverNode>(); int curTokIndex; do { curTokIndex=getHistory().getTokenIndex(); addCurrentCandidates(candidates, curTokIndex); getHistory().readRecoverToken(mySGLR, false); //System.out.print((char)mySGLR.currentToken); mySGLR.doParseStep(); newCandidates.addAll(collectNewRecoverCandidates(curTokIndex)); mySGLR.clearRecoverStacks(); } while(getHistory().getTokenIndex()<= endRecoverSearchPos && mySGLR.acceptingStack==null && mySGLR.currentToken!=SGLR.EOF); mySGLR.setFineGrainedOnRegion(false); return newCandidates; } /** * Permissive branches are accepted if they are still alive at the accepting position */ private boolean acceptParse(){ while(getHistory().getTokenIndex()<= acceptRecoveryPosition && mySGLR.acceptingStack==null && mySGLR.activeStacks.size()>0){ getHistory().readRecoverToken(mySGLR, false); //System.out.print((char)mySGLR.currentToken); mySGLR.doParseStep(); } return mySGLR.activeStacks.size()>0 || mySGLR.acceptingStack!=null; } private ArrayList<RecoverNode> collectNewRecoverCandidates(int tokenIndex) { ArrayList<RecoverNode> results=new ArrayList<RecoverNode>(); for (Frame recoverStack : mySGLR.getRecoverStacks()) { RecoverNode rn = new RecoverNode(recoverStack, tokenIndex); results.add(rn); } return results; } private void addCurrentCandidates(ArrayList<RecoverNode> candidates, int tokenPosition) { for (RecoverNode recoverNode : candidates) { if(tokenPosition==recoverNode.tokensSeen){ Frame st =mySGLR.findStack(mySGLR.activeStacks, recoverNode.recoverStack.state); if(st!=null) { for (Link ln : recoverNode.recoverStack.getAllLinks()) { st.addLink(ln); } } else mySGLR.addStack(recoverNode.recoverStack); } } } public FineGrainedOnRegion(SGLR parser){ mySGLR=parser; choicePoints=new ArrayList<BacktrackPosition>(); } public boolean parseRemainingTokens() { // TODO what if parsing fails here??? while(!getHistory().hasFinishedRecoverTokens() && mySGLR.activeStacks.size()>0 && mySGLR.acceptingStack==null){ getHistory().readRecoverToken(mySGLR, true); //System.out.print((char)mySGLR.currentToken); mySGLR.doParseStep(); } return mySGLR.activeStacks.size()>0 || mySGLR.acceptingStack!=null; } }
false
false
null
null
diff --git a/src/com/android/email/activity/MessageList.java b/src/com/android/email/activity/MessageList.java index df0bd1c4..067659aa 100644 --- a/src/com/android/email/activity/MessageList.java +++ b/src/com/android/email/activity/MessageList.java @@ -1,1314 +1,1314 @@ /* * Copyright (C) 2009 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.email.activity; import com.android.email.Controller; import com.android.email.R; import com.android.email.Utility; import com.android.email.activity.setup.AccountSettings; import com.android.email.mail.MessagingException; import com.android.email.provider.EmailContent; import com.android.email.provider.EmailContent.Account; import com.android.email.provider.EmailContent.AccountColumns; import com.android.email.provider.EmailContent.Mailbox; import com.android.email.provider.EmailContent.MailboxColumns; import com.android.email.provider.EmailContent.MessageColumns; import com.android.email.service.MailService; import android.app.ListActivity; import android.app.NotificationManager; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnClickListener; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.Button; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; import java.util.Date; import java.util.HashSet; import java.util.Set; public class MessageList extends ListActivity implements OnItemClickListener, OnClickListener { // Intent extras (internal to this activity) private static final String EXTRA_ACCOUNT_ID = "com.android.email.activity._ACCOUNT_ID"; private static final String EXTRA_MAILBOX_TYPE = "com.android.email.activity.MAILBOX_TYPE"; private static final String EXTRA_MAILBOX_ID = "com.android.email.activity.MAILBOX_ID"; // UI support private ListView mListView; private View mMultiSelectPanel; private Button mReadUnreadButton; private Button mFavoriteButton; private Button mDeleteButton; private View mListFooterView; private TextView mListFooterText; private View mListFooterProgress; private static final int LIST_FOOTER_MODE_NONE = 0; private static final int LIST_FOOTER_MODE_REFRESH = 1; private static final int LIST_FOOTER_MODE_MORE = 2; private static final int LIST_FOOTER_MODE_SEND = 3; private int mListFooterMode; private MessageListAdapter mListAdapter; private MessageListHandler mHandler = new MessageListHandler(); private Controller mController = Controller.getInstance(getApplication()); private ControllerResults mControllerCallback = new ControllerResults(); private TextView mLeftTitle; private TextView mRightTitle; private ProgressBar mProgressIcon; private static final int[] mColorChipResIds = new int[] { R.drawable.appointment_indicator_leftside_1, R.drawable.appointment_indicator_leftside_2, R.drawable.appointment_indicator_leftside_3, R.drawable.appointment_indicator_leftside_4, R.drawable.appointment_indicator_leftside_5, R.drawable.appointment_indicator_leftside_6, R.drawable.appointment_indicator_leftside_7, R.drawable.appointment_indicator_leftside_8, R.drawable.appointment_indicator_leftside_9, R.drawable.appointment_indicator_leftside_10, R.drawable.appointment_indicator_leftside_11, R.drawable.appointment_indicator_leftside_12, R.drawable.appointment_indicator_leftside_13, R.drawable.appointment_indicator_leftside_14, R.drawable.appointment_indicator_leftside_15, R.drawable.appointment_indicator_leftside_16, R.drawable.appointment_indicator_leftside_17, R.drawable.appointment_indicator_leftside_18, R.drawable.appointment_indicator_leftside_19, R.drawable.appointment_indicator_leftside_20, R.drawable.appointment_indicator_leftside_21, }; // DB access private ContentResolver mResolver; private long mMailboxId; private LoadMessagesTask mLoadMessagesTask; private FindMailboxTask mFindMailboxTask; private SetTitleTask mSetTitleTask; private SetFooterTask mSetFooterTask; public final static String[] MAILBOX_FIND_INBOX_PROJECTION = new String[] { EmailContent.RECORD_ID, MailboxColumns.TYPE, MailboxColumns.FLAG_VISIBLE }; private static final int MAILBOX_NAME_COLUMN_ID = 0; private static final int MAILBOX_NAME_COLUMN_ACCOUNT_KEY = 1; private static final int MAILBOX_NAME_COLUMN_TYPE = 2; private static final String[] MAILBOX_NAME_PROJECTION = new String[] { MailboxColumns.DISPLAY_NAME, MailboxColumns.ACCOUNT_KEY, MailboxColumns.TYPE}; private static final int ACCOUNT_DISPLAY_NAME_COLUMN_ID = 0; private static final String[] ACCOUNT_NAME_PROJECTION = new String[] { AccountColumns.DISPLAY_NAME }; private static final String ID_SELECTION = EmailContent.RECORD_ID + "=?"; /** * Open a specific mailbox. * * TODO This should just shortcut to a more generic version that can accept a list of * accounts/mailboxes (e.g. merged inboxes). * * @param context * @param id mailbox key */ public static void actionHandleMailbox(Context context, long id) { Intent intent = new Intent(context, MessageList.class); intent.putExtra(EXTRA_MAILBOX_ID, id); context.startActivity(intent); } /** * Open a specific mailbox by account & type * * @param context The caller's context (for generating an intent) * @param accountId The account to open * @param mailboxType the type of mailbox to open (e.g. @see EmailContent.Mailbox.TYPE_INBOX) */ public static void actionHandleAccount(Context context, long accountId, int mailboxType) { Intent intent = new Intent(context, MessageList.class); intent.putExtra(EXTRA_ACCOUNT_ID, accountId); intent.putExtra(EXTRA_MAILBOX_TYPE, mailboxType); context.startActivity(intent); } /** * Return an intent to open a specific mailbox by account & type. It will also clear * notifications. * * @param context The caller's context (for generating an intent) * @param accountId The account to open, or -1 * @param mailboxId the ID of the mailbox to open, or -1 * @param mailboxType the type of mailbox to open (e.g. @see Mailbox.TYPE_INBOX) or -1 */ public static Intent actionHandleAccountIntent(Context context, long accountId, long mailboxId, int mailboxType) { Intent intent = new Intent(context, MessageList.class); intent.putExtra(EXTRA_ACCOUNT_ID, accountId); intent.putExtra(EXTRA_MAILBOX_ID, mailboxId); intent.putExtra(EXTRA_MAILBOX_TYPE, mailboxType); return intent; } /** * Used for generating lightweight (Uri-only) intents. * * @param context Calling context for building the intent * @param accountId The account of interest * @param mailboxType The folder name to open (typically Mailbox.TYPE_INBOX) * @return an Intent which can be used to view that account */ public static Intent actionHandleAccountUriIntent(Context context, long accountId, int mailboxType) { Intent i = actionHandleAccountIntent(context, accountId, -1, mailboxType); i.removeExtra(EXTRA_ACCOUNT_ID); Uri uri = ContentUris.withAppendedId(Account.CONTENT_URI, accountId); i.setData(uri); return i; } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.message_list); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.list_title); mListView = getListView(); mMultiSelectPanel = findViewById(R.id.footer_organize); mReadUnreadButton = (Button) findViewById(R.id.btn_read_unread); mFavoriteButton = (Button) findViewById(R.id.btn_multi_favorite); mDeleteButton = (Button) findViewById(R.id.btn_multi_delete); mLeftTitle = (TextView) findViewById(R.id.title_left_text); mRightTitle = (TextView) findViewById(R.id.title_right_text); mProgressIcon = (ProgressBar) findViewById(R.id.title_progress_icon); mReadUnreadButton.setOnClickListener(this); mFavoriteButton.setOnClickListener(this); mDeleteButton.setOnClickListener(this); mListView.setOnItemClickListener(this); mListView.setItemsCanFocus(false); registerForContextMenu(mListView); mListAdapter = new MessageListAdapter(this); setListAdapter(mListAdapter); mResolver = getContentResolver(); // TODO extend this to properly deal with multiple mailboxes, cursor, etc. // Select 'by id' or 'by type' or 'by uri' mode and launch appropriate queries mMailboxId = getIntent().getLongExtra(EXTRA_MAILBOX_ID, -1); if (mMailboxId != -1) { // Specific mailbox ID was provided - go directly to it mSetTitleTask = new SetTitleTask(mMailboxId); mSetTitleTask.execute(); mLoadMessagesTask = new LoadMessagesTask(mMailboxId, -1); mLoadMessagesTask.execute(); addFooterView(mMailboxId, -1, -1); } else { long accountId = -1; int mailboxType = getIntent().getIntExtra(EXTRA_MAILBOX_TYPE, Mailbox.TYPE_INBOX); Uri uri = getIntent().getData(); if (uri != null && "content".equals(uri.getScheme()) && EmailContent.AUTHORITY.equals(uri.getAuthority())) { // A content URI was provided - try to look up the account String accountIdString = uri.getPathSegments().get(1); if (accountIdString != null) { accountId = Long.parseLong(accountIdString); } mFindMailboxTask = new FindMailboxTask(accountId, mailboxType, false); mFindMailboxTask.execute(); } else { // Go by account id + type accountId = getIntent().getLongExtra(EXTRA_ACCOUNT_ID, -1); mFindMailboxTask = new FindMailboxTask(accountId, mailboxType, true); mFindMailboxTask.execute(); } addFooterView(-1, accountId, mailboxType); } // TODO set title to "account > mailbox (#unread)" } @Override public void onPause() { super.onPause(); mController.removeResultCallback(mControllerCallback); } @Override public void onResume() { super.onResume(); mController.addResultCallback(mControllerCallback); // clear notifications here NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(MailService.NEW_MESSAGE_NOTIFICATION_ID); } @Override protected void onDestroy() { super.onDestroy(); if (mLoadMessagesTask != null && mLoadMessagesTask.getStatus() != LoadMessagesTask.Status.FINISHED) { mLoadMessagesTask.cancel(true); mLoadMessagesTask = null; } if (mFindMailboxTask != null && mFindMailboxTask.getStatus() != FindMailboxTask.Status.FINISHED) { mFindMailboxTask.cancel(true); mFindMailboxTask = null; } if (mSetTitleTask != null && mSetTitleTask.getStatus() != SetTitleTask.Status.FINISHED) { mSetTitleTask.cancel(true); mSetTitleTask = null; } if (mSetFooterTask != null && mSetFooterTask.getStatus() != SetTitleTask.Status.FINISHED) { mSetFooterTask.cancel(true); mSetFooterTask = null; } } public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (view != mListFooterView) { MessageListItem itemView = (MessageListItem) view; onOpenMessage(id, itemView.mMailboxId); } else { doFooterClick(); } } public void onClick(View v) { switch (v.getId()) { case R.id.btn_read_unread: onMultiToggleRead(mListAdapter.getSelectedSet()); break; case R.id.btn_multi_favorite: onMultiToggleFavorite(mListAdapter.getSelectedSet()); break; case R.id.btn_multi_delete: onMultiDelete(mListAdapter.getSelectedSet()); break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (mMailboxId < 0) { getMenuInflater().inflate(R.menu.message_list_option_smart_folder, menu); } else { getMenuInflater().inflate(R.menu.message_list_option, menu); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.refresh: onRefresh(); return true; case R.id.folders: onFolders(); return true; case R.id.accounts: onAccounts(); return true; case R.id.compose: onCompose(); return true; case R.id.account_settings: onEditAccount(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); + + AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; // There is no context menu for the list footer - if (v == mListFooterView) { + if (info.targetView == mListFooterView) { return; } - - AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; MessageListItem itemView = (MessageListItem) info.targetView; Cursor c = (Cursor) mListView.getItemAtPosition(info.position); String messageName = c.getString(MessageListAdapter.COLUMN_SUBJECT); menu.setHeaderTitle(messageName); // TODO: There is probably a special context menu for the trash Mailbox mailbox = Mailbox.restoreMailboxWithId(this, itemView.mMailboxId); switch (mailbox.mType) { case EmailContent.Mailbox.TYPE_DRAFTS: getMenuInflater().inflate(R.menu.message_list_context_drafts, menu); break; case EmailContent.Mailbox.TYPE_OUTBOX: getMenuInflater().inflate(R.menu.message_list_context_outbox, menu); break; case EmailContent.Mailbox.TYPE_TRASH: getMenuInflater().inflate(R.menu.message_list_context_trash, menu); break; default: getMenuInflater().inflate(R.menu.message_list_context, menu); // The default menu contains "mark as read". If the message is read, change // the menu text to "mark as unread." if (itemView.mRead) { menu.findItem(R.id.mark_as_read).setTitle(R.string.mark_as_unread_action); } break; } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); MessageListItem itemView = (MessageListItem) info.targetView; switch (item.getItemId()) { case R.id.open: onOpenMessage(info.id, itemView.mMailboxId); break; case R.id.delete: onDelete(info.id, itemView.mAccountId); break; case R.id.reply: onReply(itemView.mMessageId); break; case R.id.reply_all: onReplyAll(itemView.mMessageId); break; case R.id.forward: onForward(itemView.mMessageId); break; case R.id.mark_as_read: onSetMessageRead(info.id, !itemView.mRead); break; } return super.onContextItemSelected(item); } private void onRefresh() { // TODO: This needs to loop through all open mailboxes (there might be more than one) // TODO: Should not be reading from DB in UI thread - need a cleaner way to get accountId if (mMailboxId >= 0) { Mailbox mailbox = Mailbox.restoreMailboxWithId(this, mMailboxId); mController.updateMailbox(mailbox.mAccountKey, mMailboxId, mControllerCallback); } } private void onFolders() { if (mMailboxId >= 0) { // TODO smaller projection Mailbox mailbox = Mailbox.restoreMailboxWithId(this, mMailboxId); MailboxList.actionHandleAccount(this, mailbox.mAccountKey); finish(); } } private void onAccounts() { AccountFolderList.actionShowAccounts(this); finish(); } private long lookupAccountIdFromMailboxId(long mailboxId) { // TODO: Select correct account to send from when there are multiple mailboxes // TODO: Should not be reading from DB in UI thread if (mailboxId < 0) { return -1; // no info, default account } EmailContent.Mailbox mailbox = EmailContent.Mailbox.restoreMailboxWithId(this, mailboxId); return mailbox.mAccountKey; } private void onCompose() { MessageCompose.actionCompose(this, lookupAccountIdFromMailboxId(mMailboxId)); } private void onEditAccount() { AccountSettings.actionSettings(this, lookupAccountIdFromMailboxId(mMailboxId)); } private void onOpenMessage(long messageId, long mailboxId) { // TODO: Should not be reading from DB in UI thread EmailContent.Mailbox mailbox = EmailContent.Mailbox.restoreMailboxWithId(this, mailboxId); if (mailbox.mType == EmailContent.Mailbox.TYPE_DRAFTS) { MessageCompose.actionEditDraft(this, messageId); } else { MessageView.actionView(this, messageId, mailboxId); } } private void onReply(long messageId) { MessageCompose.actionReply(this, messageId, false); } private void onReplyAll(long messageId) { MessageCompose.actionReply(this, messageId, true); } private void onForward(long messageId) { MessageCompose.actionForward(this, messageId); } private void onLoadMoreMessages() { if (mMailboxId >= 0) { mController.loadMoreMessages(mMailboxId, mControllerCallback); } } private void onSendPendingMessages() { long accountId = lookupAccountIdFromMailboxId(mMailboxId); mController.sendPendingMessages(accountId, mControllerCallback); } private void onDelete(long messageId, long accountId) { mController.deleteMessage(messageId, accountId); Toast.makeText(this, R.string.message_deleted_toast, Toast.LENGTH_SHORT).show(); } private void onSetMessageRead(long messageId, boolean newRead) { mController.setMessageRead(messageId, newRead); } private void onSetMessageFavorite(long messageId, boolean newFavorite) { mController.setMessageFavorite(messageId, newFavorite); } /** * Toggles a set read/unread states. Note, the default behavior is "mark unread", so the * sense of the helper methods is "true=unread". * * @param selectedSet The current list of selected items */ private void onMultiToggleRead(Set<Long> selectedSet) { toggleMultiple(selectedSet, new MultiToggleHelper() { public boolean getField(long messageId, Cursor c) { return c.getInt(MessageListAdapter.COLUMN_READ) == 0; } public boolean setField(long messageId, Cursor c, boolean newValue) { boolean oldValue = getField(messageId, c); if (oldValue != newValue) { onSetMessageRead(messageId, !newValue); return true; } return false; } }); } /** * Toggles a set of favorites (stars) * * @param selectedSet The current list of selected items */ private void onMultiToggleFavorite(Set<Long> selectedSet) { toggleMultiple(selectedSet, new MultiToggleHelper() { public boolean getField(long messageId, Cursor c) { return c.getInt(MessageListAdapter.COLUMN_FAVORITE) != 0; } public boolean setField(long messageId, Cursor c, boolean newValue) { boolean oldValue = getField(messageId, c); if (oldValue != newValue) { onSetMessageFavorite(messageId, newValue); return true; } return false; } }); } private void onMultiDelete(Set<Long> selectedSet) { // Clone the set, because deleting is going to thrash things HashSet<Long> cloneSet = new HashSet<Long>(selectedSet); for (Long id : cloneSet) { mController.deleteMessage(id, -1); } // TODO: count messages and show "n messages deleted" Toast.makeText(this, R.string.message_deleted_toast, Toast.LENGTH_SHORT).show(); selectedSet.clear(); showMultiPanel(false); } private interface MultiToggleHelper { /** * Return true if the field of interest is "set". If one or more are false, then our * bulk action will be to "set". If all are set, our bulk action will be to "clear". * @param messageId the message id of the current message * @param c the cursor, positioned to the item of interest * @return true if the field at this row is "set" */ public boolean getField(long messageId, Cursor c); /** * Set or clear the field of interest. Return true if a change was made. * @param messageId the message id of the current message * @param c the cursor, positioned to the item of interest * @param newValue the new value to be set at this row * @return true if a change was actually made */ public boolean setField(long messageId, Cursor c, boolean newValue); } /** * Toggle multiple fields in a message, using the following logic: If one or more fields * are "clear", then "set" them. If all fields are "set", then "clear" them all. * * @param selectedSet the set of messages that are selected * @param helper functions to implement the specific getter & setter * @return the number of messages that were updated */ private int toggleMultiple(Set<Long> selectedSet, MultiToggleHelper helper) { Cursor c = mListAdapter.getCursor(); boolean anyWereFound = false; boolean allWereSet = true; c.moveToPosition(-1); while (c.moveToNext()) { long id = c.getInt(MessageListAdapter.COLUMN_ID); if (selectedSet.contains(Long.valueOf(id))) { anyWereFound = true; if (!helper.getField(id, c)) { allWereSet = false; break; } } } int numChanged = 0; if (anyWereFound) { boolean newValue = !allWereSet; c.moveToPosition(-1); while (c.moveToNext()) { long id = c.getInt(MessageListAdapter.COLUMN_ID); if (selectedSet.contains(Long.valueOf(id))) { if (helper.setField(id, c, newValue)) { ++numChanged; } } } } return numChanged; } /** * Test selected messages for showing appropriate labels * @param selectedSet * @param column_id * @param defaultflag * @return true when the specified flagged message is selected */ private boolean testMultiple(Set<Long> selectedSet, int column_id, boolean defaultflag) { Cursor c = mListAdapter.getCursor(); c.moveToPosition(-1); while (c.moveToNext()) { long id = c.getInt(MessageListAdapter.COLUMN_ID); if (selectedSet.contains(Long.valueOf(id))) { if (c.getInt(column_id) == (defaultflag? 1 : 0)) { return true; } } } return false; } private void updateFooterButtonNames () { // Show "unread_action" when one or more read messages are selected. if (testMultiple(mListAdapter.getSelectedSet(), MessageListAdapter.COLUMN_READ, true)) { mReadUnreadButton.setText(R.string.unread_action); } else { mReadUnreadButton.setText(R.string.read_action); } // Show "set_star_action" when one or more un-starred messages are selected. if (testMultiple(mListAdapter.getSelectedSet(), MessageListAdapter.COLUMN_FAVORITE, false)) { mFavoriteButton.setText(R.string.set_star_action); } else { mFavoriteButton.setText(R.string.remove_star_action); } } /** * Show or hide the panel of multi-select options */ private void showMultiPanel(boolean show) { if (show && mMultiSelectPanel.getVisibility() != View.VISIBLE) { mMultiSelectPanel.setVisibility(View.VISIBLE); mMultiSelectPanel.startAnimation( AnimationUtils.loadAnimation(this, R.anim.footer_appear)); } else if (!show && mMultiSelectPanel.getVisibility() != View.GONE) { mMultiSelectPanel.setVisibility(View.GONE); mMultiSelectPanel.startAnimation( AnimationUtils.loadAnimation(this, R.anim.footer_disappear)); } if (show) { updateFooterButtonNames(); } } /** * Add the fixed footer view if appropriate (not always - not all accounts & mailboxes). * * Here are some rules (finish this list): * * Any merged box (except send): refresh * Any push-mode account: refresh * Any non-push-mode account: load more * Any outbox (send again): * * @param mailboxId the ID of the mailbox */ private void addFooterView(long mailboxId, long accountId, int mailboxType) { // first, look for shortcuts that don't need us to spin up a DB access task if (mailboxId == Mailbox.QUERY_ALL_INBOXES || mailboxId == Mailbox.QUERY_ALL_UNREAD || mailboxId == Mailbox.QUERY_ALL_FAVORITES || mailboxId == Mailbox.QUERY_ALL_DRAFTS) { finishFooterView(LIST_FOOTER_MODE_REFRESH); return; } if (mailboxId == Mailbox.QUERY_ALL_OUTBOX || mailboxType == Mailbox.TYPE_OUTBOX) { finishFooterView(LIST_FOOTER_MODE_SEND); return; } // We don't know enough to select the footer command type (yet), so we'll // launch an async task to do the remaining lookups and decide what to do mSetFooterTask = new SetFooterTask(); mSetFooterTask.execute(mailboxId, accountId); } private final static String[] MAILBOX_ACCOUNT_AND_TYPE_PROJECTION = new String[] { MailboxColumns.ACCOUNT_KEY, MailboxColumns.TYPE }; private class SetFooterTask extends AsyncTask<Long, Void, Integer> { /** * There are two operational modes here, requiring different lookup. * mailboxIs != -1: A specific mailbox - check its type, then look up its account * accountId != -1: A specific account - look up the account */ @Override protected Integer doInBackground(Long... params) { long mailboxId = params[0]; long accountId = params[1]; int mailboxType = -1; if (mailboxId != -1) { try { Uri uri = ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId); Cursor c = mResolver.query(uri, MAILBOX_ACCOUNT_AND_TYPE_PROJECTION, null, null, null); if (c.moveToFirst()) { try { accountId = c.getLong(0); mailboxType = c.getInt(1); } finally { c.close(); } } } catch (IllegalArgumentException iae) { // can't do any more here return LIST_FOOTER_MODE_NONE; } } if (mailboxType == Mailbox.TYPE_OUTBOX) { return LIST_FOOTER_MODE_SEND; } if (accountId != -1) { // This is inefficient but the best fix is not here but in isMessagingController Account account = Account.restoreAccountWithId(MessageList.this, accountId); if (account != null) { if (MessageList.this.mController.isMessagingController(account)) { return LIST_FOOTER_MODE_MORE; // IMAP or POP } else { return LIST_FOOTER_MODE_REFRESH; // EAS } } } return LIST_FOOTER_MODE_NONE; } @Override protected void onPostExecute(Integer listFooterMode) { finishFooterView(listFooterMode); } } /** * Add the fixed footer view as specified, and set up the test as well. * * @param listFooterMode the footer mode we've determined should be used for this list */ private void finishFooterView(int listFooterMode) { mListFooterMode = listFooterMode; if (mListFooterMode != LIST_FOOTER_MODE_NONE) { mListFooterView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)) .inflate(R.layout.message_list_item_footer, mListView, false); mList.addFooterView(mListFooterView); setListAdapter(mListAdapter); mListFooterProgress = mListFooterView.findViewById(R.id.progress); mListFooterText = (TextView) mListFooterView.findViewById(R.id.main_text); setListFooterText(false); } } /** * Set the list footer text based on mode and "active" status */ private void setListFooterText(boolean active) { if (mListFooterMode != LIST_FOOTER_MODE_NONE) { int footerTextId = 0; switch (mListFooterMode) { case LIST_FOOTER_MODE_REFRESH: footerTextId = active ? R.string.status_loading_more : R.string.refresh_action; break; case LIST_FOOTER_MODE_MORE: footerTextId = active ? R.string.status_loading_more : R.string.message_list_load_more_messages_action; break; case LIST_FOOTER_MODE_SEND: footerTextId = active ? R.string.status_sending_messages : R.string.message_list_send_pending_messages_action; break; } mListFooterText.setText(footerTextId); } } /** * Handle a click in the list footer, which changes meaning depending on what we're looking at. */ private void doFooterClick() { switch (mListFooterMode) { case LIST_FOOTER_MODE_NONE: // should never happen break; case LIST_FOOTER_MODE_REFRESH: onRefresh(); break; case LIST_FOOTER_MODE_MORE: onLoadMoreMessages(); break; case LIST_FOOTER_MODE_SEND: onSendPendingMessages(); break; } } /** * Async task for finding a single mailbox by type (possibly even going to the network). * * This is much too complex, as implemented. It uses this AsyncTask to check for a mailbox, * then (if not found) a Controller call to refresh mailboxes from the server, and a handler * to relaunch this task (a 2nd time) to read the results of the network refresh. The core * problem is that we have two different non-UI-thread jobs (reading DB and reading network) * and two different paradigms for dealing with them. Some unification would be needed here * to make this cleaner. * * TODO: If this problem spreads to other operations, find a cleaner way to handle it. */ private class FindMailboxTask extends AsyncTask<Void, Void, Long> { private long mAccountId; private int mMailboxType; private boolean mOkToRecurse; /** * Special constructor to cache some local info */ public FindMailboxTask(long accountId, int mailboxType, boolean okToRecurse) { mAccountId = accountId; mMailboxType = mailboxType; mOkToRecurse = okToRecurse; } @Override protected Long doInBackground(Void... params) { // See if we can find the requested mailbox in the DB. long mailboxId = Mailbox.findMailboxOfType(MessageList.this, mAccountId, mMailboxType); if (mailboxId == -1 && mOkToRecurse) { // Not found - launch network lookup mControllerCallback.mWaitForMailboxType = mMailboxType; mController.updateMailboxList(mAccountId, mControllerCallback); } return mailboxId; } @Override protected void onPostExecute(Long mailboxId) { if (mailboxId != -1) { mMailboxId = mailboxId; mSetTitleTask = new SetTitleTask(mMailboxId); mSetTitleTask.execute(); mLoadMessagesTask = new LoadMessagesTask(mMailboxId, mAccountId); mLoadMessagesTask.execute(); } } } /** * Async task for loading a single folder out of the UI thread * * The code here (for merged boxes) is a placeholder/hack and should be replaced. Some * specific notes: * TODO: Move the double query into a specialized URI that returns all inbox messages * and do the dirty work in raw SQL in the provider. * TODO: Generalize the query generation so we can reuse it in MessageView (for next/prev) */ private class LoadMessagesTask extends AsyncTask<Void, Void, Cursor> { private long mMailboxKey; private long mAccountKey; /** * Special constructor to cache some local info */ public LoadMessagesTask(long mailboxKey, long accountKey) { mMailboxKey = mailboxKey; mAccountKey = accountKey; } @Override protected Cursor doInBackground(Void... params) { String selection = Utility.buildMailboxIdSelection(MessageList.this.mResolver, mMailboxKey); Cursor c = MessageList.this.managedQuery( EmailContent.Message.CONTENT_URI, MessageList.this.mListAdapter.PROJECTION, selection, null, EmailContent.MessageColumns.TIMESTAMP + " DESC"); return c; } @Override protected void onPostExecute(Cursor cursor) { if (cursor.isClosed()) { return; } MessageList.this.mListAdapter.changeCursor(cursor); // TODO: remove this hack and only update at the right time if (cursor != null && cursor.getCount() == 0) { onRefresh(); } // Reset the "new messages" count in the service, since we're seeing them now if (mMailboxKey == Mailbox.QUERY_ALL_INBOXES) { MailService.resetNewMessageCount(MessageList.this, -1); } else if (mMailboxKey >= 0 && mAccountKey != -1) { MailService.resetNewMessageCount(MessageList.this, mAccountKey); } } } private class SetTitleTask extends AsyncTask<Void, Void, String[]> { private long mMailboxKey; public SetTitleTask(long mailboxKey) { mMailboxKey = mailboxKey; } @Override protected String[] doInBackground(Void... params) { // Check special Mailboxes if (mMailboxKey == Mailbox.QUERY_ALL_INBOXES) { return new String[] {null, getString(R.string.account_folder_list_summary_inbox)}; } else if (mMailboxKey == Mailbox.QUERY_ALL_FAVORITES) { return new String[] {null, getString(R.string.account_folder_list_summary_favorite)}; } else if (mMailboxKey == Mailbox.QUERY_ALL_DRAFTS) { return new String[] {null, getString(R.string.account_folder_list_summary_drafts)}; } else if (mMailboxKey == Mailbox.QUERY_ALL_OUTBOX) { return new String[] {null, getString(R.string.account_folder_list_summary_outbox)}; } String accountName = null; String mailboxName = null; String accountKey = null; Cursor c = MessageList.this.mResolver.query(Mailbox.CONTENT_URI, MAILBOX_NAME_PROJECTION, ID_SELECTION, new String[] { Long.toString(mMailboxKey) }, null); try { if (c.moveToFirst()) { mailboxName = Utility.FolderProperties.getInstance(MessageList.this) .getDisplayName(c.getInt(MAILBOX_NAME_COLUMN_TYPE)); if (mailboxName == null) { mailboxName = c.getString(MAILBOX_NAME_COLUMN_ID); } accountKey = c.getString(MAILBOX_NAME_COLUMN_ACCOUNT_KEY); } } finally { c.close(); } if (accountKey != null) { c = MessageList.this.mResolver.query(Account.CONTENT_URI, ACCOUNT_NAME_PROJECTION, ID_SELECTION, new String[] { accountKey }, null); try { if (c.moveToFirst()) { accountName = c.getString(ACCOUNT_DISPLAY_NAME_COLUMN_ID); } } finally { c.close(); } } return new String[] {accountName, mailboxName}; } @Override protected void onPostExecute(String[] names) { Log.d("MessageList", "ACCOUNT:" + names[0] + "MAILBOX" + names[1]); if (names[0] != null) { mRightTitle.setText(names[0]); } if (names[1] != null) { mLeftTitle.setText(names[1]); } } } /** * Handler for UI-thread operations (when called from callbacks or any other threads) */ class MessageListHandler extends Handler { private static final int MSG_PROGRESS = 1; private static final int MSG_LOOKUP_MAILBOX_TYPE = 2; @Override public void handleMessage(android.os.Message msg) { switch (msg.what) { case MSG_PROGRESS: boolean visible = (msg.arg1 != 0); if (visible) { mProgressIcon.setVisibility(View.VISIBLE); } else { mProgressIcon.setVisibility(View.GONE); } if (mListFooterProgress != null) { mListFooterProgress.setVisibility(visible ? View.VISIBLE : View.GONE); } setListFooterText(visible); break; case MSG_LOOKUP_MAILBOX_TYPE: // kill running async task, if any if (mFindMailboxTask != null && mFindMailboxTask.getStatus() != FindMailboxTask.Status.FINISHED) { mFindMailboxTask.cancel(true); mFindMailboxTask = null; } // start new one. do not recurse back to controller. long accountId = ((Long)msg.obj).longValue(); int mailboxType = msg.arg1; mFindMailboxTask = new FindMailboxTask(accountId, mailboxType, false); mFindMailboxTask.execute(); break; default: super.handleMessage(msg); } } /** * Call from any thread to start/stop progress indicator(s) * @param progress true to start, false to stop */ public void progress(boolean progress) { android.os.Message msg = android.os.Message.obtain(); msg.what = MSG_PROGRESS; msg.arg1 = progress ? 1 : 0; sendMessage(msg); } /** * Called from any thread to look for a mailbox of a specific type. This is designed * to be called from the Controller's MailboxList callback; It instructs the async task * not to recurse, in case the mailbox is not found after this. * * See FindMailboxTask for more notes on this handler. */ public void lookupMailboxType(long accountId, int mailboxType) { android.os.Message msg = android.os.Message.obtain(); msg.what = MSG_LOOKUP_MAILBOX_TYPE; msg.arg1 = mailboxType; msg.obj = Long.valueOf(accountId); sendMessage(msg); } } /** * Callback for async Controller results. */ private class ControllerResults implements Controller.Result { // These are preset for use by updateMailboxListCallback int mWaitForMailboxType = -1; // TODO report errors into UI // TODO check accountKey and only react to relevant notifications public void updateMailboxListCallback(MessagingException result, long accountKey, int progress) { if (progress == 0) { mHandler.progress(true); } else if (result != null || progress == 100) { mHandler.progress(false); if (mWaitForMailboxType != -1) { if (result == null) { mHandler.lookupMailboxType(accountKey, mWaitForMailboxType); } } } } // TODO report errors into UI // TODO check accountKey and only react to relevant notifications public void updateMailboxCallback(MessagingException result, long accountKey, long mailboxKey, int progress, int numNewMessages) { if (progress == 0) { mHandler.progress(true); } else if (result != null || progress == 100) { mHandler.progress(false); } } public void loadMessageForViewCallback(MessagingException result, long messageId, int progress) { } public void loadAttachmentCallback(MessagingException result, long messageId, long attachmentId, int progress) { } public void serviceCheckMailCallback(MessagingException result, long accountId, long mailboxId, int progress, long tag) { } // TODO report errors into UI public void sendMailCallback(MessagingException result, long accountId, long messageId, int progress) { if (mListFooterMode == LIST_FOOTER_MODE_SEND) { if (progress == 0) { mHandler.progress(true); } else if (result != null || progress == 100) { mHandler.progress(false); } } } } /** * This class implements the adapter for displaying messages based on cursors. */ /* package */ class MessageListAdapter extends CursorAdapter { public static final int COLUMN_ID = 0; public static final int COLUMN_MAILBOX_KEY = 1; public static final int COLUMN_ACCOUNT_KEY = 2; public static final int COLUMN_DISPLAY_NAME = 3; public static final int COLUMN_SUBJECT = 4; public static final int COLUMN_DATE = 5; public static final int COLUMN_READ = 6; public static final int COLUMN_FAVORITE = 7; public static final int COLUMN_ATTACHMENTS = 8; public final String[] PROJECTION = new String[] { EmailContent.RECORD_ID, MessageColumns.MAILBOX_KEY, MessageColumns.ACCOUNT_KEY, MessageColumns.DISPLAY_NAME, MessageColumns.SUBJECT, MessageColumns.TIMESTAMP, MessageColumns.FLAG_READ, MessageColumns.FLAG_FAVORITE, MessageColumns.FLAG_ATTACHMENT, }; Context mContext; private LayoutInflater mInflater; private Drawable mAttachmentIcon; private Drawable mFavoriteIconOn; private Drawable mFavoriteIconOff; private Drawable mSelectedIconOn; private Drawable mSelectedIconOff; private java.text.DateFormat mDateFormat; private java.text.DateFormat mDayFormat; private java.text.DateFormat mTimeFormat; private HashSet<Long> mChecked = new HashSet<Long>(); public MessageListAdapter(Context context) { super(context, null); mContext = context; mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); Resources resources = context.getResources(); mAttachmentIcon = resources.getDrawable(R.drawable.ic_mms_attachment_small); mFavoriteIconOn = resources.getDrawable(android.R.drawable.star_on); mFavoriteIconOff = resources.getDrawable(android.R.drawable.star_off); mSelectedIconOn = resources.getDrawable(R.drawable.btn_check_buttonless_on); mSelectedIconOff = resources.getDrawable(R.drawable.btn_check_buttonless_off); mDateFormat = android.text.format.DateFormat.getDateFormat(context); // short date mDayFormat = android.text.format.DateFormat.getDateFormat(context); // TODO: day mTimeFormat = android.text.format.DateFormat.getTimeFormat(context); // 12/24 time } public Set<Long> getSelectedSet() { return mChecked; } @Override public void bindView(View view, Context context, Cursor cursor) { // Reset the view (in case it was recycled) and prepare for binding MessageListItem itemView = (MessageListItem) view; itemView.bindViewInit(this, true); // Load the public fields in the view (for later use) itemView.mMessageId = cursor.getLong(COLUMN_ID); itemView.mMailboxId = cursor.getLong(COLUMN_MAILBOX_KEY); itemView.mAccountId = cursor.getLong(COLUMN_ACCOUNT_KEY); itemView.mRead = cursor.getInt(COLUMN_READ) != 0; itemView.mFavorite = cursor.getInt(COLUMN_FAVORITE) != 0; itemView.mSelected = mChecked.contains(Long.valueOf(itemView.mMessageId)); // Load the UI View chipView = view.findViewById(R.id.chip); int chipResId = mColorChipResIds[(int)itemView.mAccountId % mColorChipResIds.length]; chipView.setBackgroundResource(chipResId); // TODO always display chip. Use other indications (e.g. boldface) for read/unread chipView.getBackground().setAlpha(itemView.mRead ? 100 : 255); TextView fromView = (TextView) view.findViewById(R.id.from); String text = cursor.getString(COLUMN_DISPLAY_NAME); fromView.setText(text); boolean hasAttachments = cursor.getInt(COLUMN_ATTACHMENTS) != 0; fromView.setCompoundDrawablesWithIntrinsicBounds(null, null, hasAttachments ? mAttachmentIcon : null, null); TextView subjectView = (TextView) view.findViewById(R.id.subject); text = cursor.getString(COLUMN_SUBJECT); subjectView.setText(text); // TODO ui spec suggests "time", "day", "date" - implement "day" TextView dateView = (TextView) view.findViewById(R.id.date); long timestamp = cursor.getLong(COLUMN_DATE); Date date = new Date(timestamp); if (Utility.isDateToday(date)) { text = mTimeFormat.format(date); } else { text = mDateFormat.format(date); } dateView.setText(text); ImageView selectedView = (ImageView) view.findViewById(R.id.selected); selectedView.setImageDrawable(itemView.mSelected ? mSelectedIconOn : mSelectedIconOff); ImageView favoriteView = (ImageView) view.findViewById(R.id.favorite); favoriteView.setImageDrawable(itemView.mFavorite ? mFavoriteIconOn : mFavoriteIconOff); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return mInflater.inflate(R.layout.message_list_item, parent, false); } /** * This is used as a callback from the list items, to set the selected state * * @param itemView the item being changed * @param newSelected the new value of the selected flag (checkbox state) */ public void updateSelected(MessageListItem itemView, boolean newSelected) { ImageView selectedView = (ImageView) itemView.findViewById(R.id.selected); selectedView.setImageDrawable(newSelected ? mSelectedIconOn : mSelectedIconOff); // Set checkbox state in list, and show/hide panel if necessary Long id = Long.valueOf(itemView.mMessageId); if (newSelected) { mChecked.add(id); } else { mChecked.remove(id); } MessageList.this.showMultiPanel(mChecked.size() > 0); } /** * This is used as a callback from the list items, to set the favorite state * * @param itemView the item being changed * @param newFavorite the new value of the favorite flag (star state) */ public void updateFavorite(MessageListItem itemView, boolean newFavorite) { ImageView favoriteView = (ImageView) itemView.findViewById(R.id.favorite); favoriteView.setImageDrawable(newFavorite ? mFavoriteIconOn : mFavoriteIconOff); onSetMessageFavorite(itemView.mMessageId, newFavorite); } } }
false
false
null
null
diff --git a/src/edu/ucsc/gameAI/hfsm/HFSM.java b/src/edu/ucsc/gameAI/hfsm/HFSM.java index d36cb6f..9379d6e 100644 --- a/src/edu/ucsc/gameAI/hfsm/HFSM.java +++ b/src/edu/ucsc/gameAI/hfsm/HFSM.java @@ -1,184 +1,189 @@ package edu.ucsc.gameAI.hfsm; import java.util.Collection; import java.util.LinkedList; import pacman.game.Game; import edu.ucsc.gameAI.IAction; import edu.ucsc.gameAI.fsm.ITransition; public class HFSM extends HFSMBase implements IHFSM { Collection<IHState> _states; Collection<IHTransition> _transitions; IHState _initialState; IHState _currentState; IAction _action; IAction _entryAction; IAction _exitAction; IHFSM _parent; + + public HFSM(){ + _states = new LinkedList<IHState>(); + _transitions = new LinkedList<IHTransition>(); + } @Override public Collection<IHState> getStates() { // TODO Auto-generated method stub return _states; } @Override public void setStates(Collection<IHState> states) { // TODO Auto-generated method stub _states = states; } @Override public IAction getAction() { // TODO Auto-generated method stub return _action; } @Override public void setAction(IAction action) { // TODO Auto-generated method stub _action = action; } @Override public IAction getEntryAction() { // TODO Auto-generated method stub return _entryAction; } @Override public void setEntryAction(IAction action) { // TODO Auto-generated method stub _entryAction = action; } @Override public IAction getExitAction() { // TODO Auto-generated method stub return _exitAction; } @Override public void setExitAction(IAction action) { // TODO Auto-generated method stub _exitAction = action; } @Override public Collection<IHTransition> getTransitions() { // TODO Auto-generated method stub return _transitions; } @Override public void setTransitions(Collection<IHTransition> transitions) { // TODO Auto-generated method stub _transitions = transitions; } @Override public void addTransition(IHTransition transition) { // TODO Auto-generated method stub _transitions.add(transition); } @Override public IResult update(Game game) { if(_currentState == null){ _currentState = _initialState; } IResult result = new Result(); Collection<IHTransition> transitions = _currentState.getTransitions(); for(IHTransition trans : transitions){ if(trans.isTriggered(game)){ result.setTransition(trans); result.setLevel(trans.getLevel()); if(result.getLevel() == 0){ //We are in the same level IHState targetState = trans.getTargetState(); if(_currentState.getExitAction() != null) result.addAction(_currentState.getExitAction()); if(trans.getAction() != null) result.addAction(trans.getAction()); if(targetState.getEntryAction() != null) result.addAction(targetState.getEntryAction()); //Set current state to the target state _currentState = targetState; //Add normal action if this is a state if(getAction() != null) result.addAction(getAction()); //Need to clear the transition so it doesn't trigger again result.setTransition(null); break; }else if(result.getLevel() > 0){ //It needs to go to a higher state //exit our current state if(_currentState.getExitAction() != null) result.addAction(_currentState.getExitAction()); _currentState = null; //decrease the number of levels to go result.setLevel(result.getLevel()-1); break; }else{ //We now need to go down IHState targetState = result.getTransition().getTargetState(); IHFSM targetMachine = targetState.getParent(); if(result.getTransition().getAction() != null) result.addAction(result.getTransition().getAction()); result.addActions(targetMachine.updateDown(targetState, -result.getLevel(), game)); //Need to clear the transition so it doesn't trigger again result.setTransition(null); break; } } } //There was no transition if(result.getTransition() == null){ result = _currentState.update(game); if(getAction() != null) result.addAction(getAction()); } return result; } @Override public Collection<IAction> updateDown(IHState state, int level, Game game) { Collection<IAction> actions = new LinkedList<IAction>(); if(level > 0){ actions = _parent.updateDown(this, level-1, game); } if(_currentState != null){ actions.add(_currentState.getExitAction()); } _currentState = state; actions.add(state.getEntryAction()); return actions; } @Override public void setInitialState(IHState initialState) { // TODO Auto-generated method stub _initialState = initialState; } @Override public IHState getInitialState() { // TODO Auto-generated method stub return _initialState; } @Override public IHFSM getParent() { // TODO Auto-generated method stub return _parent; } @Override public void setParent(IHFSM parent) { // TODO Auto-generated method stub _parent = parent; } } diff --git a/src/edu/ucsc/gameAI/hfsm/Result.java b/src/edu/ucsc/gameAI/hfsm/Result.java index 99b0c7f..7aae004 100644 --- a/src/edu/ucsc/gameAI/hfsm/Result.java +++ b/src/edu/ucsc/gameAI/hfsm/Result.java @@ -1,54 +1,57 @@ package edu.ucsc.gameAI.hfsm; import java.util.Collection; import java.util.LinkedList; import edu.ucsc.gameAI.IAction; public class Result implements IResult{ Collection<IAction> _actions; IHTransition _transition; int _level; Result(){ } public Collection<IAction> getActions(){ + if(_actions == null){ + _actions = new LinkedList<IAction>(); + } return _actions; } public void setActions(Collection<IAction> actions){ _actions = actions; } public void addAction(IAction action){ if(_actions == null){ _actions = new LinkedList<IAction>(); } _actions.add(action); } public void addActions(Collection<IAction> actions){ Collection<IAction> actions_prime = new LinkedList<IAction>(); for(IAction action : actions_prime){ addAction(action); } } public IHTransition getTransition(){ return _transition; } public void setTransition(IHTransition transition){ _transition = transition; } public int getLevel(){ return _level; } public void setLevel(int level){ _level = level; } } diff --git a/src/pacman/Evaluator.java b/src/pacman/Evaluator.java index a64f2cf..601bfff 100644 --- a/src/pacman/Evaluator.java +++ b/src/pacman/Evaluator.java @@ -1,386 +1,387 @@ package pacman; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.EnumMap; import java.util.LinkedList; import java.util.Random; import pacman.controllers.Controller; import pacman.controllers.HumanController; import pacman.controllers.KeyBoardInput; import pacman.controllers.examples.AggressiveGhosts; import pacman.controllers.examples.Legacy; import pacman.controllers.examples.Legacy2TheReckoning; import pacman.controllers.examples.NearestPillPacMan; import pacman.controllers.examples.NearestPillPacManVS; import pacman.controllers.examples.RandomGhosts; import pacman.controllers.examples.RandomNonRevPacMan; import pacman.controllers.examples.RandomPacMan; import pacman.controllers.examples.StarterGhosts; import pacman.controllers.examples.StarterPacMan; import pacman.entries.ghosts.MyGhosts; import pacman.game.Game; import pacman.game.GameView; import pacman.game.Constants.GHOST; import pacman.game.Constants.MOVE; import static pacman.game.Constants.*; import edu.ucsc.gameAI.*; import edu.ucsc.gameAI.conditions.*; import edu.ucsc.gameAI.decisionTrees.binary.BinaryDecision; import edu.ucsc.gameAI.fsm.*; import edu.ucsc.gameAI.hfsm.HFSM; import edu.ucsc.gameAI.hfsm.HState; import edu.ucsc.gameAI.hfsm.HTransition; import edu.ucsc.gameAI.hfsm.IHFSM; import edu.ucsc.gameAI.hfsm.IHState; import edu.ucsc.gameAI.hfsm.IHTransition; +import edu.ucsc.gameAI.hfsm.IResult; /** * This class may be used to execute the game in timed or un-timed modes, with or without * visuals. Competitors should implement their controllers in game.entries.ghosts and * game.entries.pacman respectively. The skeleton classes are already provided. The package * structure should not be changed (although you may create sub-packages in these packages). */ @SuppressWarnings("unused") public class Evaluator { boolean bLeftState; // for hfsm test int ix1 = 0; int ix2 = 110; int iy1 = 0; int iy2 = 60; int iy3 = 120; State stateRun; State stateChase; Transition transScared; LinkedList<ITransition> listtscared ; Transition transCool ; LinkedList<ITransition> listtcool ; StateMachine fsm ; IHFSM hfsm ; IHFSM upIsUp ; IHFSM upIsDown ; Collection<IHState> statesLR; Collection<IHState> statesUpIsUp; Collection<IHState> statesUpIsDown; IHState neutralUU; IHState upUU; IHState downUU; IHState neutralUD; IHState upUD; IHState downUD; IHTransition leftLR; IHTransition rightLR; IHTransition neutralUpUU; IHTransition neutralDownUU; IHTransition downUpUU; IHTransition upDownUU; IHTransition neutralUpUD; IHTransition neutralDownUD; IHTransition upUpUD; IHTransition downDownUD; public Evaluator() { //create fsm stateRun = new State(); stateRun.setAction(new GoDownAction()); stateChase = new State(); stateChase.setAction(new GoUpAction()); transScared = new Transition(); transScared.setCondition(new PacmanInRegion(ix1,iy1,ix2,iy2)); // top half of the screen transScared.setTargetState(stateRun); listtscared = new LinkedList<ITransition>(); listtscared.add(transScared); transCool = new Transition(); transCool.setCondition(new PacmanInRegion(ix1,iy2+1,ix2,iy3)); // bottom of screen (screen is (4,4) to (104,116)) transCool.setTargetState(stateChase); listtcool = new LinkedList<ITransition>(); listtcool.add(transCool); stateRun.setTransitions(listtcool); stateChase.setTransitions(listtscared); fsm = new StateMachine(); fsm.setCurrentState(stateChase); //create hfsm hfsm = new HFSM(); upIsUp = new HFSM(); upIsDown = new HFSM(); statesLR = new ArrayList<IHState>(); statesUpIsUp = new ArrayList<IHState>(); statesUpIsDown = new ArrayList<IHState>(); //create states and add actions neutralUU = new HState("neutralUU"); neutralUU.setAction(new NeutralAction()); upUU = new HState("upUU"); upUU.setAction(new GoUpAction()); downUU = new HState("downUU"); downUU.setAction(new GoDownAction()); neutralUD = new HState("neutralUD"); neutralUD.setAction(new NeutralAction()); upUD = new HState("upUD"); upUD.setAction(new GoUpAction()); downUD = new HState("downUD"); downUD.setAction(new GoDownAction()); //create and add transitions to HFMS and states. leftLR = new HTransition(upIsUp, new PacmanLastMove(MOVE.LEFT)); rightLR = new HTransition(upIsDown, new PacmanLastMove(MOVE.RIGHT)); upIsUp.addTransition(rightLR); upIsDown.addTransition(leftLR); neutralUpUU = new HTransition(upUU, new PacmanLastMove(MOVE.UP)); neutralDownUU = new HTransition(downUU, new PacmanLastMove(MOVE.DOWN)); neutralUU.addTransition(neutralUpUU); neutralUU.addTransition(neutralDownUU); upDownUU = new HTransition(downUU, new PacmanLastMove(MOVE.DOWN)); upUU.addTransition(upDownUU); downUpUU = new HTransition(upUU, new PacmanLastMove(MOVE.UP)); downUU.addTransition(downUpUU); neutralUpUD = new HTransition(downUD, new PacmanLastMove(MOVE.UP)); neutralDownUD = new HTransition(upUD, new PacmanLastMove(MOVE.DOWN)); neutralUD.addTransition(neutralUpUD); neutralUD.addTransition(neutralDownUD); upUpUD = new HTransition(downUD, new PacmanLastMove(MOVE.UP)); upUD.addTransition(upUpUD); downDownUD = new HTransition(upUD, new PacmanLastMove(MOVE.DOWN)); downUD.addTransition(downDownUD); //add the states to the FSM. statesLR.add(upIsUp); statesLR.add(upIsDown); hfsm.setStates(statesLR); hfsm.setInitialState(upIsUp); // left state statesUpIsUp.add(neutralUU); statesUpIsUp.add(upUU); statesUpIsUp.add(downUU); upIsUp.setStates(statesUpIsUp); upIsUp.setInitialState(neutralUU); statesUpIsDown.add(neutralUD); statesUpIsDown.add(upUD); statesUpIsDown.add(downUD); upIsDown.setStates(statesUpIsDown); upIsDown.setInitialState(neutralUD); // for testing hfsm bLeftState = true; } // could be a function run every frame of runExperiment, accepting game as a parameter public void runUnitTests(Game game, Controller<MOVE> pacManController,Controller<EnumMap<GHOST,MOVE>> ghostController) { // test 1: is blinky edible IsEdible edible = new IsEdible(GHOST.BLINKY); // OR if (edible.test(game) == game.isGhostEdible(GHOST.BLINKY)) if (edible.test(game) == false) { //System.out.println("Test 1 passed"); } else { //System.out.println("Test 1 failed"); } // Game State Condition Tests if (new MazeIndex(game.getMazeIndex()).test(game)) ;//System.out.println("MazeIndex passed"); else System.out.println("MazeIndex failed"); if (new LevelCount(game.getCurrentLevel()).test(game)) ;//System.out.println("LevelCount passed"); else System.out.println("LevelCount failed"); if (new CurrentLevelTime(game.getCurrentLevelTime()-1,game.getCurrentLevelTime()+1).test(game)) ;//System.out.println("CurrentLevelTime passed"); else System.out.println("CurrentLevelTime failed"); if (!new TotalTime(game.getTotalTime()-1,game.getTotalTime()+1).test(game)) System.out.println("TotalTime failed"); if (!new Score(game.getScore()-1,game.getScore()+1).test(game)) System.out.println("Score failed"); if (!new GhostEatScore(game.getGhostCurrentEdibleScore()-1,game.getGhostCurrentEdibleScore()+1).test(game)) System.out.println("GhostEatScore failed"); if (!new TimeOfLastGlobalReversal(game.getTimeOfLastGlobalReversal()-1,game.getTimeOfLastGlobalReversal()+1).test(game)) System.out.println("TimeOfLastGlobalReversal failed"); if (!(new PacmanWasEaten().test(game) == game.wasPacManEaten())) System.out.println("PacmanWasEaten failed"); if (!(new PillWasEaten().test(game) == game.wasPillEaten())) System.out.println("PillWasEaten failed"); if (!(new PowerPillWasEaten().test(game) == game.wasPowerPillEaten())) System.out.println("PowerPillWasEaten failed"); for (int pill : game.getPillIndices()) if (!(new IsPillStillAvailable(pill).test(game) == game.isPillStillAvailable(pill))) System.out.println("IsPillStillAvailable failed"); for (int pill : game.getPillIndices()) if (!(new IsPowerPillStillAvailable(pill).test(game) == game.isPowerPillStillAvailable(pill))) System.out.println("IsPowerPillStillAvailable failed"); for (GHOST ghost : GHOST.values()) if (!(new GhostEaten(ghost).test(game) == game.wasGhostEaten(ghost))) //if (!(new GhostEaten(ghost).test(game) == game.isGhostEdible(ghost))) System.out.println("GhostEaten failed"); // Ghost State Conditions for (GHOST ghost : GHOST.values()) { if (!(new CurrentGhostNodeIndex(ghost, game.getGhostCurrentNodeIndex(ghost))).test(game)) System.out.println("CurrentGhostNodeIndex failed"); if (!(new EdibleTime(ghost, game.getGhostEdibleTime(ghost)-1,game.getGhostEdibleTime(ghost)+1)).test(game)) System.out.println("EdibleTime failed"); if (!(new LairTime(ghost, game.getGhostLairTime(ghost)-1,game.getGhostLairTime(ghost)+1)).test(game)) System.out.println("GhostEaten failed"); if (!(new GhostLastMove(ghost, game.getGhostLastMoveMade(ghost))).test(game)) System.out.println("GhostLastMove failed"); } // Ms Pac ManState Conditions if (!(new CurrentPacmanNodeIndex(game.getPacmanCurrentNodeIndex())).test(game)) System.out.println("CurrentPacmanNodeIndex failed"); if (!(new NumberOfLivesRemaining(game.getPacmanNumberOfLivesRemaining()-1,game.getPacmanNumberOfLivesRemaining()+1).test(game))) System.out.println("NumberOfLivesRemaining failed"); if (!(new PacmanLastMove(game.getPacmanLastMoveMade()).test(game))) System.out.println("PacmanLastMove failed"); // Inference Conditions int px; int py; for (int pill : game.getActivePillsIndices()) { px = game.getNodeXCood(pill); py = game.getNodeYCood(pill); if (!(new PillInRegion(px-1,py-1,px+1,py+1).test(game))) System.out.println("PillInRegion failed"); } for (int ppill : game.getActivePowerPillsIndices()) { px = game.getNodeXCood(ppill); py = game.getNodeYCood(ppill); if (!(new PowerPillInRegion(px-1,py-1,px+1,py+1).test(game))) System.out.println("PowerPillInRegion failed"); } for (GHOST ghost : GHOST.values()) { int ig = game.getGhostCurrentNodeIndex(ghost); int gx = game.getNodeXCood(ig); int gy = game.getNodeYCood(ig); if (!(new GhostInRegion(gx-1,gy-1,gx+1,gy+1).test(game))) System.out.println("GhostInRegion failed"); } int ipac = game.getPacmanCurrentNodeIndex(); int pacx = game.getNodeXCood(ipac); int pacy = game.getNodeYCood(ipac); if (!(new PacmanInRegion(pacx-1,pacy-1,pacx+1,pacy+1).test(game))) System.out.println("PacmanLastMove failed"); // Decision Tree BinaryDecision root = new BinaryDecision(); ipac = game.getPacmanCurrentNodeIndex(); pacx = game.getNodeXCood(ipac); pacy = game.getNodeYCood(ipac); root.setCondition(new PacmanInRegion(pacx-1,pacy-1,pacx+1,pacy+1)); root.setTrueBranch(new GoUpAction()); root.setFalseBranch(new GoDownAction()); if (root.makeDecision(game).getClass() != GoUpAction.class) System.out.println("Decision Tree failed"); // FSM (up when pacman in the bottom half of screen, down otherwise) Collection<IAction> actions = fsm.update(game); // test result int ip = game.getPacmanCurrentNodeIndex(); pacx = game.getNodeXCood(ip); pacy = game.getNodeYCood(ip); if (ix1 <= pacx && ix2 >= pacx && iy1 <= pacy && iy2 >= pacy && actions.size() > 0) { if (actions.iterator().next().getClass() != GoDownAction.class) System.out.println("FSM action result failed"); if (fsm.getCurrentState() != stateRun) System.out.println("FSM state failed"); } // hfsm boolean bCheck = true; actions = hfsm.update(game).getActions(); if (game.getPacmanLastMoveMade() == MOVE.LEFT && !bLeftState) { bLeftState = true; bCheck = false; } if (game.getPacmanLastMoveMade() == MOVE.RIGHT && bLeftState) { bLeftState = false; bCheck = false; } if (actions.size() < 1) bCheck = false; if (bCheck) { IAction act = actions.iterator().next(); MOVE mv = act.getMove(); if (game.getPacmanLastMoveMade() == MOVE.UP) { if (bLeftState) { if (mv != MOVE.UP) System.out.println("HFSM fail 1"); } else { if (mv != MOVE.DOWN) System.out.println("HFSM fail 2"); } } else if (game.getPacmanLastMoveMade() == MOVE.DOWN) { if (bLeftState) { if (mv != MOVE.DOWN) System.out.println("HFSM fail 3"); } else { if (mv != MOVE.UP) System.out.println("HFSM fail 4"); } } } // actions if (!(new GoUpAction().getClass() == GoUpAction.class)) System.out.println("GoUpAction failed"); if (!(new GoLeftAction().getClass() == GoLeftAction.class)) System.out.println("GoLeftAction failed"); if (!(new GoRightAction().getClass() == GoRightAction.class)) System.out.println("GoRightAction failed"); if (!(new GoDownAction().getClass() == GoDownAction.class)) System.out.println("GoDownAction failed"); } } \ No newline at end of file
false
false
null
null
diff --git a/de.hswt.hrm.catalog.dao.jdbc.test/src/de/hswt/hrm/catalog/dao/jdbc/CurrentDaoTest.java b/de.hswt.hrm.catalog.dao.jdbc.test/src/de/hswt/hrm/catalog/dao/jdbc/CurrentDaoTest.java index ded0211f..9e225e5b 100644 --- a/de.hswt.hrm.catalog.dao.jdbc.test/src/de/hswt/hrm/catalog/dao/jdbc/CurrentDaoTest.java +++ b/de.hswt.hrm.catalog.dao.jdbc.test/src/de/hswt/hrm/catalog/dao/jdbc/CurrentDaoTest.java @@ -1,108 +1,119 @@ package de.hswt.hrm.catalog.dao.jdbc; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Collection; import org.junit.Test; import de.hswt.hrm.catalog.model.Current; import de.hswt.hrm.catalog.model.Target; import de.hswt.hrm.common.database.exception.DatabaseException; import de.hswt.hrm.common.database.exception.ElementNotFoundException; import de.hswt.hrm.common.database.exception.SaveException; import de.hswt.hrm.test.database.AbstractDatabaseTest; public class CurrentDaoTest extends AbstractDatabaseTest { private void compareCurrentFields(final Current expected, final Current actual) { assertEquals("Name not set correctly.", expected.getName(), actual.getName()); assertEquals("Text not set correctly.", expected.getText(), actual.getText()); } @Test public void testInsertCurrent() throws ElementNotFoundException, DatabaseException { final String name = "CurrentName"; final String text = "Get outta here ..."; Current expected = new Current(name, text); // Check return value from insert TargetDao targetDao = new TargetDao(); CurrentDao currentDao = new CurrentDao(targetDao); Current parsed = currentDao.insert(expected); compareCurrentFields(expected, parsed); assertTrue("ID not set correctly.", parsed.getId() >= 0); // Request from database Current requested = currentDao.findById(parsed.getId()); compareCurrentFields(expected, requested); assertEquals("Requested object does not equal parsed one.", parsed, requested); } @Test public void testUpdateCurrent() throws ElementNotFoundException, DatabaseException { Current cur1 = new Current("FirstCurrent", "FirstText"); TargetDao targetDao = new TargetDao(); CurrentDao currentDao = new CurrentDao(targetDao); Current parsed = currentDao.insert(cur1); // We add another current to ensure that the update affects just one row. Current cur2 = new Current("SecondCurrent", "SecondText"); currentDao.insert(cur2); parsed.setText("Some Test"); parsed.setName("Some Name"); currentDao.update(parsed); Current requested = currentDao.findById(parsed.getId()); compareCurrentFields(parsed, requested); assertEquals("Requested object does not equal updated one.", parsed, requested); } @Test public void testFindAllCurrent() throws ElementNotFoundException, DatabaseException { Current cur1 = new Current("FirstCurrent", "FirstText"); Current cur2 = new Current("SecondCurrent", "SecondText"); TargetDao targetDao = new TargetDao(); CurrentDao currentDao = new CurrentDao(targetDao); currentDao.insert(cur1); currentDao.insert(cur2); Collection<Current> current = currentDao.findAll(); assertEquals("Count of retrieved currents does not match.", 2, current.size()); } @Test public void testFindByIdCurrent() throws ElementNotFoundException, DatabaseException { Current expected = new Current("FirstCurrent", "FirstText"); TargetDao targetDao = new TargetDao(); CurrentDao currentDao = new CurrentDao(targetDao); Current parsed = currentDao.insert(expected); Current requested = currentDao.findById(parsed.getId()); compareCurrentFields(expected, requested); } @Test public void testConnectTargetAndCurrentState() throws SaveException { TargetDao targetDao = new TargetDao(); CurrentDao currentDao = new CurrentDao(targetDao); Current current = new Current("FirstCurrent", "FirstText"); Target target = new Target("FirstTarget", "Some Text"); currentDao.addToTarget(target, current); // FIXME: check if could retrieve the added connection } @Test - public void testFindByTargetState() { - fail(); + public void testFindByTargetState() throws DatabaseException { + TargetDao targetDao = new TargetDao(); + CurrentDao currentDao = new CurrentDao(targetDao); + Target target = new Target("FirstTarget", "Some Text"); + Current current1 = new Current("FirstCurrent", "Some text.."); + Current current2 = new Current("SecondCurrent", "Some more text.."); + + target = targetDao.insert(target); + currentDao.addToTarget(target, current1); + currentDao.addToTarget(target, current2); + + Collection<Current> currentStates = currentDao.findByTarget(target); + assertEquals("Wrong number of current states returned.", 2, currentStates.size()); } } diff --git a/de.hswt.hrm.catalog.dao.jdbc/src/de/hswt/hrm/catalog/dao/jdbc/CurrentDao.java b/de.hswt.hrm.catalog.dao.jdbc/src/de/hswt/hrm/catalog/dao/jdbc/CurrentDao.java index 6ebe8fc5..dbe977e2 100644 --- a/de.hswt.hrm.catalog.dao.jdbc/src/de/hswt/hrm/catalog/dao/jdbc/CurrentDao.java +++ b/de.hswt.hrm.catalog.dao.jdbc/src/de/hswt/hrm/catalog/dao/jdbc/CurrentDao.java @@ -1,277 +1,277 @@ package de.hswt.hrm.catalog.dao.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import javax.inject.Inject; import org.apache.commons.dbutils.DbUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import de.hswt.hrm.common.database.DatabaseFactory; import de.hswt.hrm.common.database.NamedParameterStatement; import de.hswt.hrm.common.database.SqlQueryBuilder; import de.hswt.hrm.common.database.exception.DatabaseException; import de.hswt.hrm.common.database.exception.ElementNotFoundException; import de.hswt.hrm.common.database.exception.SaveException; import de.hswt.hrm.catalog.model.Current; import de.hswt.hrm.catalog.model.Target; import de.hswt.hrm.catalog.dao.core.ICurrentDao; import de.hswt.hrm.catalog.dao.core.ITargetDao; public class CurrentDao implements ICurrentDao { private final static Logger LOG = LoggerFactory.getLogger(CurrentDao.class); private final ITargetDao targetDao; @Inject public CurrentDao(final ITargetDao targetDao) { checkNotNull(targetDao, "TargetDao not properly injected to CurrentDao."); this.targetDao = targetDao; LOG.debug("TargetDao injected into CurrentDao."); } @Override public Collection<Current> findAll() throws DatabaseException { SqlQueryBuilder builder = new SqlQueryBuilder(); builder.select(TABLE_NAME, Fields.ID, Fields.NAME, Fields.TEXT); final String query = builder.toString(); try (Connection con = DatabaseFactory.getConnection()) { try (NamedParameterStatement stmt = NamedParameterStatement.fromConnection(con, query)) { ResultSet result = stmt.executeQuery(); Collection<Current> places = fromResultSet(result); DbUtils.closeQuietly(result); return places; } } catch (SQLException e) { throw new DatabaseException(e); } } @Override public Current findById(int id) throws DatabaseException, ElementNotFoundException { checkArgument(id >= 0, "Id must not be negative."); SqlQueryBuilder builder = new SqlQueryBuilder(); builder.select(TABLE_NAME, Fields.ID, Fields.NAME, Fields.TEXT); builder.where(Fields.ID); final String query = builder.toString(); try (Connection con = DatabaseFactory.getConnection()) { try (NamedParameterStatement stmt = NamedParameterStatement.fromConnection(con, query)) { stmt.setParameter(Fields.ID, id); ResultSet result = stmt.executeQuery(); Collection<Current> currents = fromResultSet(result); DbUtils.closeQuietly(result); if (currents.size() < 1) { throw new ElementNotFoundException(); } else if (currents.size() > 1) { throw new DatabaseException("ID '" + id + "' is not unique."); } return currents.iterator().next(); } } catch (SQLException e) { throw new DatabaseException(e); } } @Override public Collection<Current> findByTarget(final Target target) throws DatabaseException { checkNotNull(target, "Target is mandatory."); checkArgument(target.getId() >= 0, "Target must have a valid ID."); StringBuilder builder = new StringBuilder(); builder.append("SELECT"); builder.append(" ").append(TABLE_NAME).append(".").append(Fields.ID); - builder.append(" ").append(TABLE_NAME).append(".").append(Fields.NAME); + builder.append(", ").append(TABLE_NAME).append(".").append(Fields.NAME); builder.append(", ").append(TABLE_NAME).append(".").append(Fields.TEXT); builder.append(" FROM ").append(TABLE_NAME); builder.append(" JOIN ").append(CROSS_TABLE_NAME); builder.append(" ON ").append(CROSS_TABLE_NAME).append(".").append(Fields.CROSS_CURRENT_FK); builder.append(" = ").append(TABLE_NAME).append(".").append(Fields.ID); builder.append(" WHERE "); builder.append(CROSS_TABLE_NAME).append(".").append(Fields.CROSS_TARGET_FK); builder.append(" = ?;"); // String query = "SELECT Catalog_Current.Category_Current_State_Target_FK" // +", State_Current.State_Current_ID" // + ", State_Current_Name" // + " FROM State_Current" // + " JOIN Catalog_Current" // + " ON Catalog_Current.Category_Current_State_Current_FK" // + "= State_Current.State_Current_ID" // + " WHERE Category_Current_State_Target_FK = ?;"; final String query = builder.toString(); try (Connection con = DatabaseFactory.getConnection()) { try (PreparedStatement stmt = con.prepareStatement(query)) { stmt.setInt(1, target.getId()); ResultSet result = stmt.executeQuery(); Collection<Current> currents = fromResultSet(result); DbUtils.closeQuietly(result); return currents; } } catch (SQLException e) { throw new DatabaseException(e); } } /** * @see {@link ICurrentDao#insert(Current)} */ @Override public Current insert(Current current) throws SaveException { SqlQueryBuilder builder = new SqlQueryBuilder(); builder.insert(TABLE_NAME, Fields.NAME, Fields.TEXT); final String query = builder.toString(); try (Connection con = DatabaseFactory.getConnection()) { try (NamedParameterStatement stmt = NamedParameterStatement.fromConnection(con, query)) { stmt.setParameter(Fields.NAME, current.getName()); stmt.setParameter(Fields.TEXT, current.getText()); int affectedRows = stmt.executeUpdate(); if (affectedRows != 1) { throw new SaveException(); } try (ResultSet generatedKeys = stmt.getGeneratedKeys()) { if (generatedKeys.next()) { int id = generatedKeys.getInt(1); // Create new Current with id Current inserted = new Current(id, current.getName(), current.getText()); return inserted; } else { throw new SaveException("Could not retrieve generated ID."); } } } } catch (SQLException | DatabaseException e) { throw new SaveException(e); } } @Override public void addToTarget(Target target, Current current) throws SaveException { SqlQueryBuilder builder = new SqlQueryBuilder(); builder.insert(CROSS_TABLE_NAME, Fields.CROSS_TARGET_FK, Fields.CROSS_CURRENT_FK); // Insert target and current if not already in the database if (target.getId() < 0) { target = targetDao.insert(target); } if (current.getId() < 0) { current = insert(current); } final String query = builder.toString(); try (Connection con = DatabaseFactory.getConnection()) { try (NamedParameterStatement stmt = NamedParameterStatement.fromConnection(con, query)) { stmt.setParameter(Fields.CROSS_TARGET_FK, target.getId()); stmt.setParameter(Fields.CROSS_CURRENT_FK, current.getId()); int affectedRows = stmt.executeUpdate(); if (affectedRows != 1) { throw new SaveException(); } } } catch (SQLException | DatabaseException e) { throw new SaveException(e); } } @Override public void update(Current current) throws ElementNotFoundException, SaveException { checkNotNull(current, "Current must not be null."); if (current.getId() < 0) { throw new ElementNotFoundException("Element has no valid ID."); } SqlQueryBuilder builder = new SqlQueryBuilder(); builder.update(TABLE_NAME, Fields.NAME, Fields.TEXT); builder.where(Fields.ID); final String query = builder.toString(); try (Connection con = DatabaseFactory.getConnection()) { try (NamedParameterStatement stmt = NamedParameterStatement.fromConnection(con, query)) { stmt.setParameter(Fields.ID, current.getId()); stmt.setParameter(Fields.NAME, current.getName()); stmt.setParameter(Fields.TEXT, current.getText()); int affectedRows = stmt.executeUpdate(); if (affectedRows != 1) { throw new SaveException(); } } } catch (SQLException | DatabaseException e) { throw new SaveException(e); } } private Collection<Current> fromResultSet(ResultSet rs) throws SQLException { checkNotNull(rs, "Result must not be null."); Collection<Current> currentList = new ArrayList<>(); while (rs.next()) { int id = rs.getInt(Fields.ID); String name = rs.getString(Fields.NAME); String text = rs.getString(Fields.TEXT); Current current = new Current(id, name, text); currentList.add(current); } return currentList; } private static final String TABLE_NAME = "State_Current"; private static final String CROSS_TABLE_NAME = "Catalog_Current"; private static class Fields { public static final String ID = "State_Current_ID"; public static final String NAME = "State_Current_Name"; public static final String TEXT = "State_Current_Text"; public static final String CROSS_TARGET_FK = "Category_Current_State_Target_FK"; public static final String CROSS_CURRENT_FK = "Category_Current_State_Current_FK"; } }
false
false
null
null
diff --git a/src/rs/pedjaapps/KernelTuner/WidgetUpdateServiceBig.java b/src/rs/pedjaapps/KernelTuner/WidgetUpdateServiceBig.java index 5f5fa8c..6a00b9d 100755 --- a/src/rs/pedjaapps/KernelTuner/WidgetUpdateServiceBig.java +++ b/src/rs/pedjaapps/KernelTuner/WidgetUpdateServiceBig.java @@ -1,805 +1,839 @@ package rs.pedjaapps.KernelTuner; import android.annotation.*; import android.app.*; import android.appwidget.*; import android.content.*; import android.graphics.*; import android.graphics.Bitmap.*; import android.graphics.Paint.*; import android.os.*; import android.preference.*; import android.widget.*; import java.io.*; import java.util.*; import java.lang.Process; public class WidgetUpdateServiceBig extends Service { public String led; public String cpu0curr; public String gov; public String cpu0gov; public String cpu1gov; public String cpu0max = " "; public String cpu1max = " "; public String cpu0min = " 7 "; public String cpu1min = " "; public String gpu2d = " "; public String gpu3d = " "; public int countcpu0; public int countcpu1; public String vsync = " "; public String fastcharge = " "; public String out; public String cdepth = " "; public String kernel = " "; public String deepSleep; public String upTime; public String charge; public String battperc; public String batttemp; public String battvol; public String batttech; public String battcurrent; public String batthealth; public String battcap; public List<String> frequencies; public int angle; public int cf = 0; public String cpu1curr; public int cf2 = 0; - public int timeint = 1800; + public int timeint = 30; + int TEMP_ENABLE = 0; + public void mountdebugfs() { Process localProcess; try { localProcess = Runtime.getRuntime().exec("su"); DataOutputStream localDataOutputStream = new DataOutputStream(localProcess.getOutputStream()); localDataOutputStream.writeBytes("mount -t debugfs debugfs /sys/kernel/debug\n"); localDataOutputStream.writeBytes("echo -n enabled > /sys/devices/virtual/thermal/thermal_zone1/mode\n"); localDataOutputStream.writeBytes("echo -n enabled > /sys/devices/virtual/thermal/thermal_zone0/mode\n"); localDataOutputStream.writeBytes("exit\n"); localDataOutputStream.flush(); localDataOutputStream.close(); localProcess.waitFor(); localProcess.destroy(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } + public void enableTemp() + { + Process localProcess; + try + { + localProcess = Runtime.getRuntime().exec("su"); + + DataOutputStream localDataOutputStream = new DataOutputStream(localProcess.getOutputStream()); + localDataOutputStream.writeBytes("echo -n enabled > /sys/devices/virtual/thermal/thermal_zone1/mode\n"); + localDataOutputStream.writeBytes("echo -n enabled > /sys/devices/virtual/thermal/thermal_zone0/mode\n"); + localDataOutputStream.writeBytes("exit\n"); + localDataOutputStream.flush(); + localDataOutputStream.close(); + localProcess.waitFor(); + localProcess.destroy(); + } + catch (IOException e) + { + + e.printStackTrace(); + } + catch (InterruptedException e) + { + + e.printStackTrace(); + } + } public void info() { cpu0min = CPUInfo.cpu0MinFreq(); cpu0max = CPUInfo.cpu0MaxFreq(); cpu1min = CPUInfo.cpu1MinFreq(); cpu1max = CPUInfo.cpu1MaxFreq(); cpu0gov = CPUInfo.cpu0CurGov(); cpu1gov = CPUInfo.cpu1CurGov(); led = CPUInfo.cbb(); gpu2d = CPUInfo.gpu2d(); gpu3d = CPUInfo.gpu3d(); fastcharge = String.valueOf(CPUInfo.fcharge()); vsync = String.valueOf(CPUInfo.vsync()); cdepth = CPUInfo.cDepth(); frequencies = CPUInfo.frequencies(); cpu0curr = CPUInfo.cpu0CurFreq(); cpu1curr = CPUInfo.cpu1CurFreq(); upTime = CPUInfo.uptime(); deepSleep =CPUInfo.deepSleep(); try { File myFile = new File("/proc/version"); FileInputStream fIn = new FileInputStream(myFile); BufferedReader myReader = new BufferedReader( new InputStreamReader(fIn)); String aDataRow = ""; String aBuffer = ""; while ((aDataRow = myReader.readLine()) != null) { aBuffer += aDataRow + "\n"; } kernel = aBuffer.trim(); myReader.close(); } catch (Exception e) { kernel = "Kernel version file not found"; } try { File myFile = new File("/sys/class/power_supply/battery/capacity"); FileInputStream fIn = new FileInputStream(myFile); BufferedReader myReader = new BufferedReader( new InputStreamReader(fIn)); String aDataRow = ""; String aBuffer = ""; while ((aDataRow = myReader.readLine()) != null) { aBuffer += aDataRow + "\n"; } battperc = aBuffer.trim(); myReader.close(); } catch (Exception e) { battperc = "0"; } try { File myFile = new File("/sys/class/power_supply/battery/charging_source"); FileInputStream fIn = new FileInputStream(myFile); BufferedReader myReader = new BufferedReader( new InputStreamReader(fIn)); String aDataRow = ""; String aBuffer = ""; while ((aDataRow = myReader.readLine()) != null) { aBuffer += aDataRow + "\n"; } charge = aBuffer.trim(); myReader.close(); } catch (Exception e) { charge = "0"; } //System.out.println(cpu0min); try { File myFile = new File("/sys/class/power_supply/battery/batt_temp"); FileInputStream fIn = new FileInputStream(myFile); BufferedReader myReader = new BufferedReader( new InputStreamReader(fIn)); String aDataRow = ""; String aBuffer = ""; while ((aDataRow = myReader.readLine()) != null) { aBuffer += aDataRow + "\n"; } batttemp = aBuffer.trim(); myReader.close(); } catch (Exception e) { batttemp = "0"; } try { File myFile = new File("/sys/class/power_supply/battery/batt_vol"); FileInputStream fIn = new FileInputStream(myFile); BufferedReader myReader = new BufferedReader( new InputStreamReader(fIn)); String aDataRow = ""; String aBuffer = ""; while ((aDataRow = myReader.readLine()) != null) { aBuffer += aDataRow + "\n"; } battvol = aBuffer.trim(); myReader.close(); } catch (Exception e) { battvol = "0"; } try { File myFile = new File("/sys/class/power_supply/battery/technology"); FileInputStream fIn = new FileInputStream(myFile); BufferedReader myReader = new BufferedReader( new InputStreamReader(fIn)); String aDataRow = ""; String aBuffer = ""; while ((aDataRow = myReader.readLine()) != null) { aBuffer += aDataRow + "\n"; } batttech = aBuffer.trim(); myReader.close(); } catch (Exception e) { batttech = "err"; } try { File myFile = new File("/sys/class/power_supply/battery/batt_current"); FileInputStream fIn = new FileInputStream(myFile); BufferedReader myReader = new BufferedReader( new InputStreamReader(fIn)); String aDataRow = ""; String aBuffer = ""; while ((aDataRow = myReader.readLine()) != null) { aBuffer += aDataRow + "\n"; } battcurrent = aBuffer.trim(); myReader.close(); } catch (Exception e) { battcurrent = "err"; } try { File myFile = new File("/sys/class/power_supply/battery/health"); FileInputStream fIn = new FileInputStream(myFile); BufferedReader myReader = new BufferedReader( new InputStreamReader(fIn)); String aDataRow = ""; String aBuffer = ""; while ((aDataRow = myReader.readLine()) != null) { aBuffer += aDataRow + "\n"; } batthealth = aBuffer.trim(); myReader.close(); } catch (Exception e) { batthealth = "err"; } try { File myFile = new File("/sys/class/power_supply/battery/full_bat"); FileInputStream fIn = new FileInputStream(myFile); BufferedReader myReader = new BufferedReader( new InputStreamReader(fIn)); String aDataRow = ""; String aBuffer = ""; while ((aDataRow = myReader.readLine()) != null) { aBuffer += aDataRow + "\n"; } battcap = aBuffer.trim(); myReader.close(); } catch (Exception e) { battcap = "err"; } int freqslength = frequencies.size(); int index = frequencies.indexOf(cpu0curr); int index2 = frequencies.indexOf(cpu1curr); cf = index * 100 / freqslength + 4; cf2 = index2 * 100 / freqslength + 4; //System.out.println(angle); } @SuppressLint("ParserError") @Override public void onStart(Intent intent, int startId) { //Log.i(LOG, "Called"); // Create some random data AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this .getApplicationContext()); int[] allWidgetIds = intent .getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS); ComponentName thisWidget = new ComponentName(getApplicationContext(), AppWidgetBig.class); int[] allWidgetIds2 = appWidgetManager.getAppWidgetIds(thisWidget); //Log.w(LOG, "From Intent" + String.valueOf(allWidgetIds.length)); // Log.w(LOG, "Direct" + String.valueOf(allWidgetIds2.length)); File file = new File("/sys/kernel/debug"); if(file.list().length>0){ } else{ mountdebugfs(); } + if(TEMP_ENABLE==0){ + enableTemp(); + TEMP_ENABLE = 1; + } + info(); for (int widgetId : allWidgetIds) { RemoteViews remoteViews = new RemoteViews(this .getApplicationContext().getPackageName(), R.layout.widget_4x4); Paint p = new Paint(); p.setAntiAlias(true); p.setStyle(Style.STROKE); p.setStyle(Paint.Style.FILL); p.setStrokeWidth(8); p.setColor(0xFFFF0000); Bitmap bitmap = Bitmap.createBitmap(100, 100, Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); p.setColor(Color.BLUE); for (int i = 5, a = 8; a < 100 && i < 100; i = i + 4, a = a + 4) { Rect rect = new Rect(10, i, 50, a); RectF rectF = new RectF(rect); canvas.drawRoundRect(rectF, 1, 1, p); rect = new Rect(51, i, 91, a); rectF = new RectF(rect); canvas.drawRoundRect(rectF, 1, 1, p); } for (int i = 97, a = 100; a > 100 - cf && i > 100 - cf; i = i - 4, a = a - 4) { p.setColor(Color.GREEN); Rect rect = new Rect(10, i, 50, a); RectF rectF = new RectF(rect); canvas.drawRoundRect(rectF, 1, 1, p); rect = new Rect(51, i, 91, a); rectF = new RectF(rect); canvas.drawRoundRect(rectF, 1, 1, p); } Bitmap bitmap2 = Bitmap.createBitmap(100, 100, Config.ARGB_8888); Canvas canvas2 = new Canvas(bitmap2); // canvas2.drawArc(new RectF(5, 5, 90, 90), 90, angle, true, p); if (!cpu1curr.equals("offline")) { for (int i = 5, a = 8; a < 100 && i < 100; i = i + 4, a = a + 4) { p.setColor(Color.BLUE); Rect rect = new Rect(10, i, 50, a); RectF rectF = new RectF(rect); canvas2.drawRoundRect(rectF, 1, 1, p); rect = new Rect(51, i, 91, a); rectF = new RectF(rect); canvas2.drawRoundRect(rectF, 1, 1, p); } for (int i = 97, a = 100; a > 100 - cf2 && i > 100 - cf2; i = i - 4, a = a - 4) { p.setColor(Color.GREEN); Rect rect = new Rect(10, i, 50, a); RectF rectF = new RectF(rect); canvas2.drawRoundRect(rectF, 1, 1, p); rect = new Rect(51, i, 91, a); rectF = new RectF(rect); canvas2.drawRoundRect(rectF, 1, 1, p); } } else { for (int i = 5, a = 8; a < 100 && i < 100; i = i + 4, a = a + 4) { p.setColor(Color.BLUE); Rect rect = new Rect(10, i, 50, a); RectF rectF = new RectF(rect); canvas2.drawRoundRect(rectF, 1, 1, p); rect = new Rect(51, i, 91, a); rectF = new RectF(rect); canvas2.drawRoundRect(rectF, 1, 1, p); } } remoteViews.setImageViewBitmap(R.id.imageView7, bitmap); remoteViews.setImageViewBitmap(R.id.ImageView01, bitmap2); //System.out.println(cpu0min); if (!cpu0curr.equals("offline")) { remoteViews.setTextViewText(R.id.freq0, cpu0curr.substring(0, cpu0curr.length() - 3) + "Mhz"); } else { remoteViews.setTextViewText(R.id.freq0, cpu0curr); remoteViews.setTextColor(R.id.freq0, Color.RED); } if (!cpu1curr.equals("offline")) { remoteViews.setTextViewText(R.id.freq1, cpu1curr.substring(0, cpu1curr.length() - 3) + "Mhz"); remoteViews.setTextColor(R.id.freq1, Color.WHITE); } else { remoteViews.setTextViewText(R.id.freq1, cpu1curr); remoteViews.setTextColor(R.id.freq1, Color.RED); } remoteViews.setTextViewText(R.id.textView9, cpu0gov); remoteViews.setTextViewText(R.id.TextView02, cpu1gov); remoteViews.setTextColor(R.id.TextView02, Color.WHITE); if (cpu1gov.equals("offline")) { remoteViews.setTextColor(R.id.TextView02, Color.RED); } try { if (Integer.parseInt(led) < 2) { remoteViews.setImageViewResource(R.id.imageView5, R.drawable.red); } else if (Integer.parseInt(led) < 11 && Integer.parseInt(led) >= 2) { remoteViews.setImageViewResource(R.id.imageView5, R.drawable.yellow); } else if (Integer.parseInt(led) >= 11) { remoteViews.setImageViewResource(R.id.imageView5, R.drawable.green); } else { remoteViews.setImageViewResource(R.id.imageView5, R.drawable.err); }} catch (Exception e) { remoteViews.setImageViewResource(R.id.imageView5, R.drawable.err); } if (fastcharge.equals("1")) { remoteViews.setImageViewResource(R.id.imageView6, R.drawable.green); } else if (fastcharge.equals("0")) { remoteViews.setImageViewResource(R.id.imageView6, R.drawable.red); } else { remoteViews.setImageViewResource(R.id.imageView6, R.drawable.err); } if (vsync.equals("1")) { remoteViews.setImageViewResource(R.id.imageView4, R.drawable.green); } else if (vsync.equals("0")) { remoteViews.setImageViewResource(R.id.imageView4, R.drawable.red); } else { remoteViews.setImageViewResource(R.id.imageView4, R.drawable.err); } if (cdepth.equals("16")) { remoteViews.setImageViewResource(R.id.imageView3, R.drawable.red); } else if (cdepth.equals("24")) { remoteViews.setImageViewResource(R.id.imageView3, R.drawable.yellow); } else if (cdepth.equals("32")) { remoteViews.setImageViewResource(R.id.imageView3, R.drawable.green); } else { remoteViews.setImageViewResource(R.id.imageView3, R.drawable.err); } remoteViews.setTextViewText(R.id.textView1k, kernel.trim()); remoteViews.setTextViewText(R.id.textView11, upTime); remoteViews.setTextViewText(R.id.textView13, deepSleep); int battperciconint = 0; try { battperciconint = Integer.parseInt(battperc.substring(0, battperc.length()).trim()); } catch (Exception e) { battperciconint = 0; } if (battperciconint <= 15 && battperciconint != 0 && charge.equals("0")) { remoteViews.setImageViewResource(R.id.imageView10, R.drawable.battery_low); remoteViews.setTextColor(R.id.textView14, Color.RED); } else if (battperciconint > 30 && charge.equals("0")) { remoteViews.setImageViewResource(R.id.imageView10, R.drawable.battery_full); remoteViews.setTextColor(R.id.textView14, Color.GREEN); } else if (battperciconint < 30 && battperciconint > 15 && charge.equals("0")) { remoteViews.setImageViewResource(R.id.imageView10, R.drawable.battery_half); remoteViews.setTextColor(R.id.textView14, Color.YELLOW); } else if (charge.equals("1")) { remoteViews.setImageViewResource(R.id.imageView10, R.drawable.battery_charge_usb); remoteViews.setTextColor(R.id.textView14, Color.CYAN); } else if (charge.equals("2")) { remoteViews.setImageViewResource(R.id.imageView10, R.drawable.battery_charge_ac); remoteViews.setTextColor(R.id.textView14, Color.CYAN); } else if (battperciconint == 0) { remoteViews.setImageViewResource(R.id.imageView10, R.drawable.err); } remoteViews.setProgressBar(R.id.progressBar1, 100, battperciconint, false); remoteViews.setTextViewText(R.id.textView14, battperc + "%"); double battempint = Double.parseDouble(batttemp)/10; String cpuTemp = CPUInfo.cpuTemp(); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); String tempPref = sharedPrefs.getString("temp", "celsius"); if (tempPref.equals("fahrenheit")) { cpuTemp = String.valueOf((int)(Double.parseDouble(cpuTemp) * 1.8) + 32); remoteViews.setTextViewText(R.id.textView27, cpuTemp + "°F"); int temp = Integer.parseInt(cpuTemp); if (temp < 113) { remoteViews.setTextColor(R.id.textView27, Color.GREEN); } else if (temp >= 113 && temp < 138) { remoteViews.setTextColor(R.id.textView27, Color.YELLOW); } else if (temp >= 138) { remoteViews.setTextColor(R.id.textView27, Color.RED); } } else if (tempPref.equals("celsius")) { remoteViews.setTextViewText(R.id.textView27, cpuTemp + "°C"); int temp = Integer.parseInt(cpuTemp); if (temp < 45) { remoteViews.setTextColor(R.id.textView27, Color.GREEN); } else if (temp >= 45 && temp <= 59) { remoteViews.setTextColor(R.id.textView27, Color.YELLOW); } else if (temp > 59) { remoteViews.setTextColor(R.id.textView27, Color.RED); } } /** If kelvin is selected in settings convert cpu temp to kelvin */ else if (tempPref.equals("kelvin")) { cpuTemp = String.valueOf((int)(Double.parseDouble(cpuTemp) + 273.15)); remoteViews.setTextViewText(R.id.textView27, cpuTemp + "°K"); int temp = Integer.parseInt(cpuTemp); if (temp < 318) { remoteViews.setTextColor(R.id.textView27, Color.GREEN); } else if (temp >= 318 && temp <= 332) { remoteViews.setTextColor(R.id.textView27, Color.YELLOW); } else if (temp > 332) { remoteViews.setTextColor(R.id.textView27, Color.RED);; } } if (tempPref.equals("fahrenheit")) { battempint = (battempint * 1.8) + 32; remoteViews.setTextViewText(R.id.textView20, String.valueOf((int)battempint) + "°F"); if (battempint <= 104) { remoteViews.setTextColor(R.id.textView20, Color.GREEN); } else if (battempint > 104 && battempint < 131) { remoteViews.setTextColor(R.id.textView20, Color.YELLOW); } else if (battempint >= 140) { remoteViews.setTextColor(R.id.textView20, Color.RED); } } else if (tempPref.equals("celsius")) { remoteViews.setTextViewText(R.id.textView20, String.valueOf((int)battempint) + "°C"); if (battempint <= 45) { remoteViews.setTextColor(R.id.textView20, Color.GREEN); } else if (battempint > 45 && battempint < 55) { remoteViews.setTextColor(R.id.textView20, Color.YELLOW); } else if (battempint >= 55) { remoteViews.setTextColor(R.id.textView20, Color.RED); } } else if (tempPref.equals("kelvin")) { battempint = battempint + 273.15; remoteViews.setTextViewText(R.id.textView20, String.valueOf((int)battempint) + "°K"); if (battempint <= 318.15) { remoteViews.setTextColor(R.id.textView20, Color.GREEN); } else if (battempint > 318.15 && battempint < 328.15) { remoteViews.setTextColor(R.id.textView20, Color.YELLOW); } else if (battempint >= 328.15) { remoteViews.setTextColor(R.id.textView20, Color.RED); } } remoteViews.setTextViewText(R.id.textView21, battvol.trim() + "mV"); remoteViews.setTextViewText(R.id.textView22, batttech); remoteViews.setTextViewText(R.id.textView23, battcurrent + "mA"); if (battcurrent.substring(0, 1).equals("-")) { remoteViews.setTextColor(R.id.textView23, Color.RED); } else { remoteViews.setTextViewText(R.id.textView23, "+" + battcurrent + "mA"); remoteViews.setTextColor(R.id.textView23, Color.GREEN); } remoteViews.setTextViewText(R.id.textView24, batthealth); remoteViews.setTextViewText(R.id.textView26, battcap + "mAh"); // Register an onClickListener Intent clickIntent = new Intent(this.getApplicationContext(), AppWidgetBig.class); clickIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds); String timer = sharedPrefs.getString("widget_time", "30"); try { timeint = Integer.parseInt(timer.trim()); } catch (Exception e) { timeint = 30; } PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT); remoteViews.setOnClickPendingIntent(R.id.widget_layout2, pendingIntent); AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.SECOND, timeint*60); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 20 * 1000, pendingIntent); appWidgetManager.updateAppWidget(widgetId, remoteViews); } stopSelf(); super.onStart(intent, startId); } @Override public IBinder onBind(Intent intent) { return null; } }
false
false
null
null
diff --git a/src/ui/marker/EdgeMarker.java b/src/ui/marker/EdgeMarker.java index 05210bb..b682900 100644 --- a/src/ui/marker/EdgeMarker.java +++ b/src/ui/marker/EdgeMarker.java @@ -1,202 +1,205 @@ package ui.marker; import java.util.List; import processing.core.PConstants; import processing.core.PGraphics; import util.StringCouple; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.geo.Location; import de.fhpotsdam.unfolding.marker.SimpleLinesMarker; import de.fhpotsdam.unfolding.utils.MapPosition; import de.fhpotsdam.unfolding.utils.ScreenPosition; import de.looksgood.ani.Ani; import de.looksgood.ani.easing.Easing; public class EdgeMarker<E extends NamedMarker> extends SimpleLinesMarker { private static final float ANI_DURATION = .5f; private static final int DEFAULT_STROKE_WEIGHT = 1; private E m1, m2; private StringCouple id; private float strokeWeight; private float strokeWeightTarget; private float weightPercentage; private Ani currentAnimation; private Ani currentHideAnimation; public EdgeMarker(E m1, E m2){ super(m1.getLocation(), m2.getLocation()); this.m1 = m1; this.m2 = m2; weightPercentage = 1; currentHideAnimation = null; id = new StringCouple(m1.getName(), m2.getName()); strokeWeight = strokeWeightTarget = DEFAULT_STROKE_WEIGHT; currentAnimation = null; } public E getM1(){ return m1; } public E getM2(){ return m2; } public StringCouple getIds() { return id; } @Override public void setHidden(boolean hidden) { if (hidden == isHidden()) { super.setHidden(hidden); return; } super.setHidden(hidden); if (hidden) currentHideAnimation = Ani.to(this, ANI_DURATION, "weightPercentage", 0, Easing.QUAD_OUT); else // delay currentHideAnimation = Ani.to(this, ANI_DURATION, ANI_DURATION, "weightPercentage", 1, Easing.QUAD_IN); currentHideAnimation.start(); } public void setHiddenUnanimated(boolean hidden) { if (hidden == isHidden() && (currentHideAnimation == null || currentHideAnimation.isEnded())) return; super.setHidden(hidden); if (!hidden) { // show directly if (currentHideAnimation == null || currentHideAnimation.isEnded()) weightPercentage = 1; else { currentHideAnimation.setEnd(1); currentHideAnimation.end(); currentHideAnimation = null; } } else { // hide with a delay, but do it instantaneously if (currentHideAnimation != null && !currentHideAnimation.isEnded()) { currentHideAnimation.setEnd(weightPercentage); currentHideAnimation.end(); } currentHideAnimation = Ani.to(this, 0, ANI_DURATION, "weightPercentage", 0, Easing.LINEAR); currentHideAnimation.start(); } } @Override public void setStrokeWeight(int weight) { if (currentAnimation != null) { currentAnimation.setEnd(strokeWeightTarget = weight); currentAnimation.end(); return; } strokeWeight = weight; strokeWeightTarget = weight; } public void setWidth(int width) { setStrokeWeight(width); } public void setWidthAnimated(int width) { if (strokeWeightTarget == width) return; strokeWeightTarget = width; currentAnimation = Ani.to(this, ANI_DURATION, "strokeWeight", width, Easing.LINEAR, "onEnd:callback"); currentAnimation.start(); } @SuppressWarnings("unused") private void callback() { currentAnimation = null; } @Override public void setSelected(boolean selected){ if (selected == this.selected) return; this.selected = selected; if (selected) { m1.addSelectedLine(); m2.addSelectedLine(); } else { m1.removeSelectedLine(); m2.removeSelectedLine(); } } @Override public boolean isInside(UnfoldingMap map, float checkX, float checkY) { + if (weightPercentage == 0) + return false; + Location l1 = m1.getLocation(); Location l2 = m2.getLocation(); ScreenPosition sposa = map.getScreenPosition(l1), sposb = map.getScreenPosition(l2); float xa = sposa.x, xb = sposb.x, ya = sposa.y, yb = sposb.y; if(checkX > Math.max(xa, xb) || checkX < Math.min(xa, xb) || checkY > Math.max(ya, yb) || checkY < Math.min(ya, yb)){ return false; } float m = (ya - yb) / (xa - xb), b = ya - m * xa, d = (float) (Math.abs(checkY - m * checkX - b) / Math.sqrt(m*m + 1)); - return d < this.strokeWeight; + return d < strokeWeight * weightPercentage; } @Override public void draw(PGraphics pg, List<MapPosition> mapPositions) { if (mapPositions.isEmpty()) return; if (weightPercentage == 0) return; pg.pushStyle(); pg.noFill(); if (isSelected()) { pg.stroke(highlightColor); } else { pg.stroke(color); } pg.strokeWeight(strokeWeight * weightPercentage); pg.smooth(); pg.beginShape(PConstants.LINES); MapPosition last = mapPositions.get(0); for (int i = 1; i < mapPositions.size(); ++i) { MapPosition mp = mapPositions.get(i); pg.vertex(last.x, last.y); pg.vertex(mp.x, mp.y); last = mp; } pg.endShape(); pg.popStyle(); } }
false
false
null
null
diff --git a/src/org/concord/energy3d/model/Floor.java b/src/org/concord/energy3d/model/Floor.java index f40101ef..287131a5 100644 --- a/src/org/concord/energy3d/model/Floor.java +++ b/src/org/concord/energy3d/model/Floor.java @@ -1,232 +1,232 @@ package org.concord.energy3d.model; import java.nio.FloatBuffer; import java.util.ArrayList; import org.concord.energy3d.scene.Scene; import org.concord.energy3d.scene.Scene.TextureMode; import org.concord.energy3d.shapes.SizeAnnotation; import org.concord.energy3d.util.MeshLib; import org.concord.energy3d.util.Util; import org.concord.energy3d.util.WallVisitor; import org.poly2tri.Poly2Tri; import org.poly2tri.geometry.polygon.Polygon; import org.poly2tri.geometry.polygon.PolygonPoint; import org.poly2tri.triangulation.point.TPoint; import org.poly2tri.triangulation.tools.ardor3d.ArdorMeshMapper; import com.ardor3d.bounding.BoundingBox; import com.ardor3d.bounding.CollisionTreeManager; -import com.ardor3d.bounding.OrientedBoundingBox; import com.ardor3d.math.ColorRGBA; import com.ardor3d.math.Matrix3; import com.ardor3d.math.Vector3; import com.ardor3d.math.type.ReadOnlyVector3; import com.ardor3d.renderer.IndexMode; import com.ardor3d.renderer.state.MaterialState; import com.ardor3d.renderer.state.MaterialState.ColorMaterial; import com.ardor3d.scenegraph.Line; import com.ardor3d.scenegraph.Mesh; import com.ardor3d.scenegraph.hint.CullHint; import com.ardor3d.ui.text.BMText.Align; import com.ardor3d.util.geom.BufferUtils; public class Floor extends HousePart { private static final long serialVersionUID = 1L; private transient ArrayList<PolygonPoint> wallUpperPoints; private transient Mesh wireframeMesh; public Floor() { super(1, 1, 5.0); } @Override protected void init() { super.init(); relativeToHorizontal = true; mesh = new Mesh("Floor"); root.attachChild(mesh); mesh.getMeshData().setIndexMode(IndexMode.TriangleStrip); mesh.getMeshData().setVertexBuffer(BufferUtils.createVector3Buffer(4)); - mesh.setModelBound(new OrientedBoundingBox()); +// mesh.setModelBound(new OrientedBoundingBox()); + mesh.setModelBound(new BoundingBox()); wireframeMesh = new Line("Floor (Wireframe)"); wireframeMesh.getMeshData().setVertexBuffer(BufferUtils.createVector3Buffer(8)); wireframeMesh.setDefaultColor(ColorRGBA.BLACK); wireframeMesh.setModelBound(new BoundingBox()); Util.disablePickShadowLight(wireframeMesh); // root.attachChild(wireframeMesh); final MaterialState ms = new MaterialState(); ms.setColorMaterial(ColorMaterial.Diffuse); mesh.setRenderState(ms); updateTextureAndColor(); final UserData userData = new UserData(this); mesh.setUserData(userData); } @Override public void setPreviewPoint(final int x, final int y) { pickContainer(x, y, Wall.class); if (container != null) { final ReadOnlyVector3 base = getCenter(); final Vector3 p = Util.closestPoint(base, Vector3.UNIT_Z, x, y); snapToGrid(p, base, getGridSize()); final double zMin = container.getAbsPoint(0).getZ() + 0.01; final double zmax = container.getAbsPoint(1).getZ(); height = Math.min(zmax, Math.max(zMin, p.getZ())); } draw(); setEditPointsVisible(container != null); } private Polygon makePolygon(final ArrayList<PolygonPoint> wallUpperPoints) { double maxY = wallUpperPoints.get(0).getY(); for (final PolygonPoint p : wallUpperPoints) { p.set(p.getX(), p.getY(), height); if (p.getY() > maxY) maxY = p.getY(); } points.get(0).set(toRelative(getCenter(), container.getContainer())); return new Polygon(wallUpperPoints); } private void fillMeshWithPolygon(final Mesh mesh, final Polygon polygon) { Poly2Tri.triangulate(polygon); ArdorMeshMapper.updateTriangleMesh(mesh, polygon); ArdorMeshMapper.updateVertexNormals(mesh, polygon.getTriangles()); ArdorMeshMapper.updateFaceNormals(mesh, polygon.getTriangles()); final double scale = Scene.getInstance().getTextureMode() == TextureMode.Simple ? 0.2 : 1.0; ArdorMeshMapper.updateTextureCoordinates(mesh, polygon.getTriangles(), scale, new TPoint(0, 0, 0), new TPoint(1, 0, 0), new TPoint(0, 1, 0)); mesh.getMeshData().updateVertexCount(); CollisionTreeManager.INSTANCE.updateCollisionTree(mesh); mesh.updateModelBound(); } @Override protected void drawMesh() { if (container == null) { mesh.getSceneHints().setCullHint(CullHint.Always); return; } mesh.getSceneHints().setCullHint(CullHint.Inherit); wallUpperPoints = exploreWallNeighbors((Wall) container); final double scale = Scene.getInstance().getTextureMode() == TextureMode.Simple ? 2.0 : 10.0; MeshLib.fillMeshWithPolygon(mesh, makePolygon(wallUpperPoints), null, true, new TPoint(0, 0, 0), new TPoint(scale, 0, 0), new TPoint(0, scale, 0)); // fillMeshWithPolygon(mesh, makePolygon(wallUpperPoints)); drawWireframe(); updateEditShapes(); } protected ArrayList<PolygonPoint> exploreWallNeighbors(final Wall startWall) { final ArrayList<PolygonPoint> poly = new ArrayList<PolygonPoint>(); startWall.visitNeighbors(new WallVisitor() { @Override public void visit(final Wall currentWall, final Snap prev, final Snap next) { int pointIndex = 0; if (next != null) pointIndex = next.getSnapPointIndexOf(currentWall); pointIndex = pointIndex + 1; final ReadOnlyVector3 p1 = currentWall.getAbsPoint(pointIndex == 1 ? 3 : 1); final ReadOnlyVector3 p2 = currentWall.getAbsPoint(pointIndex); addPointToPolygon(poly, p1); addPointToPolygon(poly, p2); } }); return poly; } private void addPointToPolygon(final ArrayList<PolygonPoint> poly, final ReadOnlyVector3 p) { final PolygonPoint polygonPoint = new PolygonPoint(p.getX(), p.getY(), p.getZ()); if (!poly.contains(polygonPoint)) poly.add(polygonPoint); } @Override public void drawAnnotations() { if (container == null) return; int annotCounter = 0; for (int i = 0; i < wallUpperPoints.size(); i++) { PolygonPoint p = wallUpperPoints.get(i); final Vector3 a = new Vector3(p.getX(), p.getY(), p.getZ()); p = wallUpperPoints.get((i + 1) % wallUpperPoints.size()); final Vector3 b = new Vector3(p.getX(), p.getY(), p.getZ()); final SizeAnnotation sizeAnnot = fetchSizeAnnot(annotCounter++); sizeAnnot.setRange(a, b, getCenter(), getFaceDirection(), original == null, Align.Center, true, false, Scene.isDrawAnnotationsInside()); sizeAnnot.setLineWidth(original == null ? 1f : 2f); } } protected void drawWireframe() { if (container == null) return; final ArrayList<ReadOnlyVector3> convexHull = MeshLib.computeOutline(mesh.getMeshData().getVertexBuffer()); final int totalVertices = convexHull.size(); final FloatBuffer buf; if (wireframeMesh.getMeshData().getVertexBuffer().capacity() >= totalVertices * 2 * 3) { buf = wireframeMesh.getMeshData().getVertexBuffer(); buf.limit(buf.capacity()); buf.rewind(); } else { buf = BufferUtils.createVector3Buffer(totalVertices * 2); wireframeMesh.getMeshData().setVertexBuffer(buf); } for (int i = 0; i < convexHull.size(); i++) { final ReadOnlyVector3 p1 = convexHull.get(i); final ReadOnlyVector3 p2 = convexHull.get((i + 1) % convexHull.size()); buf.put(p1.getXf()).put(p1.getYf()).put(p1.getZf()); buf.put(p2.getXf()).put(p2.getYf()).put(p2.getZf()); } buf.limit(buf.position()); wireframeMesh.getMeshData().updateVertexCount(); wireframeMesh.updateModelBound(); wireframeMesh.setTranslation(getFaceDirection().multiply(0.001, null)); } @Override protected String getTextureFileName() { return Scene.getInstance().getTextureMode() == TextureMode.Simple ? "floor.png" : "floor.jpg"; } @Override public void flatten(final double flattenTime) { root.setRotation((new Matrix3().fromAngles(flattenTime * Math.PI / 2, 0, 0))); root.updateWorldTransform(true); super.flatten(flattenTime); } @Override public Vector3 getAbsPoint(final int index) { return toAbsolute(points.get(index), container == null ? null : container.getContainer()); } @Override public void setOriginal(final HousePart original) { wallUpperPoints = ((Floor) original).wallUpperPoints; root.detachChild(wireframeMesh); wireframeMesh = ((Floor) original).wireframeMesh.makeCopy(true); ((Line) wireframeMesh).setLineWidth(printWireframeThickness); root.attachChild(wireframeMesh); super.setOriginal(original); } @Override public boolean isDrawable() { return container != null; } @Override public void updateTextureAndColor() { updateTextureAndColor(mesh, Scene.getInstance().getFloorColor()); } } diff --git a/src/org/concord/energy3d/scene/Scene.java b/src/org/concord/energy3d/scene/Scene.java index 3b6b4a9c..e5eccc5e 100644 --- a/src/org/concord/energy3d/scene/Scene.java +++ b/src/org/concord/energy3d/scene/Scene.java @@ -1,622 +1,622 @@ package org.concord.energy3d.scene; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.concurrent.Callable; import org.concord.energy3d.gui.EnergyPanel; import org.concord.energy3d.gui.MainFrame; import org.concord.energy3d.gui.MainPanel; import org.concord.energy3d.model.Door; import org.concord.energy3d.model.Foundation; import org.concord.energy3d.model.HousePart; import org.concord.energy3d.model.Roof; import org.concord.energy3d.model.Snap; import org.concord.energy3d.model.Wall; import org.concord.energy3d.model.Window; import org.concord.energy3d.undo.SaveCommand; import org.concord.energy3d.util.Config; import com.ardor3d.math.ColorRGBA; import com.ardor3d.math.Vector3; import com.ardor3d.math.type.ReadOnlyColorRGBA; import com.ardor3d.math.type.ReadOnlyVector3; import com.ardor3d.renderer.Camera; import com.ardor3d.scenegraph.Node; public class Scene implements Serializable { public static enum Unit { Meter("m"), Centimeter("cm"), Inches("\""); private final String notation; private Unit(final String notation) { this.notation = notation; } public String getNotation() { return notation; } }; public static enum TextureMode { None, Simple, Full }; // public static final float TRANSPARENCY_LEVEL = 0.4f; // public static final ReadOnlyColorRGBA WHITE = new ColorRGBA(1, 1, 1, TRANSPARENCY_LEVEL); public static final ReadOnlyColorRGBA WHITE = ColorRGBA.WHITE; public static final ReadOnlyColorRGBA GRAY = ColorRGBA.LIGHT_GRAY; private static final long serialVersionUID = 1L; private static final Node root = new Node("House Root"); private static final Node originalHouseRoot = new Node("Original House Root"); private static final int currentVersion = 1; private static Scene instance; private static URL url = null; private static boolean redrawAll = false; private static boolean drawThickness = false; private static boolean drawAnnotationsInside = false; private static Unit unit = Unit.Meter; private transient boolean edited = false; private final ArrayList<HousePart> parts = new ArrayList<HousePart>(); private TextureMode textureMode = TextureMode.Full; private ReadOnlyVector3 cameraLocation; private ReadOnlyVector3 cameraDirection; private ReadOnlyColorRGBA foundationColor; private ReadOnlyColorRGBA wallColor; private ReadOnlyColorRGBA doorColor; private ReadOnlyColorRGBA floorColor; private ReadOnlyColorRGBA roofColor; private double overhangLength = 2.0; private double annotationScale = 1; private int version = currentVersion; private boolean isAnnotationsVisible = true; public static Scene getInstance() { if (instance == null) { try { if (Config.isApplet() && Config.getApplet().getParameter("file") != null) { final URL url = new URL(Config.getApplet().getCodeBase(), Config.getApplet().getParameter("file")); open(new URI(url.getProtocol(), url.getHost(), url.getPath(), null).toURL()); } else newFile(40, 30); } catch (final Throwable e) { e.printStackTrace(); newFile(40, 30); } } return instance; } public static void newFile(final double xLength, final double yLength) { try { open(null); } catch (final Exception e) { e.printStackTrace(); } final Foundation foundation = new Foundation(xLength, yLength); SceneManager.getTaskManager().update(new Callable<Object>() { @Override public Object call() throws Exception { instance.add(foundation); redrawAll = true; return null; } }); } public static void open(final URL file) throws Exception { Scene.url = file; if (PrintController.getInstance().isPrintPreview()) { MainPanel.getInstance().getPreviewButton().setSelected(false); while (!PrintController.getInstance().isFinished()) Thread.yield(); } if (url == null) { instance = new Scene(); System.out.println("done"); } else { System.out.print("Opening..." + file + "..."); final ObjectInputStream in = new ObjectInputStream(file.openStream()); instance = (Scene) in.readObject(); in.close(); for (final HousePart part : instance.parts) part.getRoot(); instance.cleanup(); instance.upgradeSceneToNewVersion(); loadCameraLocation(); } if (!Config.isApplet()) { if (instance.textureMode == TextureMode.None) MainFrame.getInstance().getNoTextureRadioButtonMenuItem().setSelected(true); else if (instance.textureMode == TextureMode.Simple) MainFrame.getInstance().getSimpleTextureRadioButtonMenuItem().setSelected(true); else MainFrame.getInstance().getFullTextureRadioButtonMenuItem().setSelected(true); } MainPanel.getInstance().getAnnotationToggleButton().setSelected(instance.isAnnotationsVisible); final CameraControl cameraControl = SceneManager.getInstance().getCameraControl(); if (cameraControl != null) cameraControl.reset(); SceneManager.getTaskManager().update(new Callable<Object>() { @Override public Object call() throws Exception { System.out.print("Open file..."); originalHouseRoot.detachAllChildren(); root.detachAllChildren(); root.attachChild(originalHouseRoot); if (url != null) { for (final HousePart housePart : instance.getParts()) originalHouseRoot.attachChild(housePart.getRoot()); redrawAll = true; System.out.println("done"); } root.updateWorldBound(true); SceneManager.getInstance().updateHeliodonAndAnnotationSize(); SceneManager.getInstance().getUndoManager().die(); SceneManager.getInstance().getUndoManager().addEdit(new SaveCommand()); Scene.getInstance().setEdited(false); return null; } }); } public static void loadCameraLocation() { final Camera camera = SceneManager.getInstance().getCameraNode().getCamera(); if (instance.getCameraLocation() != null && instance.getCameraDirection() != null) { camera.setLocation(instance.getCameraLocation()); camera.lookAt(instance.getCameraLocation().add(instance.getCameraDirection(), null), Vector3.UNIT_Z); } SceneManager.getInstance().getCameraNode().updateFromCamera(); Scene.getInstance().updateEditShapes(); } public static void importFile(final URL url) throws Exception { if (PrintController.getInstance().isPrintPreview()) { MainPanel.getInstance().getPreviewButton().setSelected(false); while (!PrintController.getInstance().isFinished()) Thread.yield(); } if (url != null) { System.out.print("Opening..." + url + "..."); final ObjectInputStream in = new ObjectInputStream(url.openStream()); final Scene instance = (Scene) in.readObject(); in.close(); // instance.fixUnintializedVariables(); instance.cleanup(); instance.upgradeSceneToNewVersion(); if (url != null) { for (final HousePart housePart : instance.getParts()) { Scene.getInstance().parts.add(housePart); originalHouseRoot.attachChild(housePart.getRoot()); } redrawAll = true; System.out.println("done"); } root.updateWorldBound(true); SceneManager.getInstance().updateHeliodonAndAnnotationSize(); SceneManager.getInstance().getUndoManager().die(); if (!Config.isApplet()) MainFrame.getInstance().refreshUndoRedo(); } } // private void fixUnintializedVariables() { // if (textureMode == null) { // textureMode = TextureMode.Full; // overhangLength = 0.2; //// foundationColor = wallColor = doorColor = floorColor = roofColor = ColorRGBA.WHITE; // } // } private void cleanup() { final ArrayList<HousePart> toBeRemoved = new ArrayList<HousePart>(); for (final HousePart housePart : getParts()) { if (!housePart.isValid() || ((housePart instanceof Roof || housePart instanceof Window || housePart instanceof Door) && housePart.getContainer() == null)) toBeRemoved.add(housePart); } for (final HousePart housePart : toBeRemoved) remove(housePart); fixDisconnectedWalls(); } private void upgradeSceneToNewVersion() { if (textureMode == null) { textureMode = TextureMode.Full; overhangLength = 0.2; // foundationColor = wallColor = doorColor = floorColor = roofColor = ColorRGBA.WHITE; } if (version < 1) { for (final HousePart part : parts) { if (part instanceof Foundation) ((Foundation)part).scaleHouse(10); } cameraLocation = cameraLocation.multiply(10, null); setOverhangLength(getOverhangLength() * 10); setAnnotationScale(1.0); } version = currentVersion ; } private void fixDisconnectedWalls() { for (final HousePart part : parts) { if (part instanceof Wall) { final Wall wall = (Wall) part; wall.fixDisconnectedWalls(); } } } public static void save(final URL url, final boolean setAsCurrentFile) throws Exception { instance.cleanup(); // save camera to file saveCameraLocation(); if (setAsCurrentFile) Scene.url = url; - System.out.print("Saving " + Scene.url + "..."); + System.out.print("Saving " + url + "..."); ObjectOutputStream out; - out = new ObjectOutputStream(new FileOutputStream(Scene.url.toURI().getPath())); + out = new ObjectOutputStream(new FileOutputStream(url.toURI().getPath())); out.writeObject(instance); out.close(); SceneManager.getInstance().getUndoManager().addEdit(new SaveCommand()); // Scene.getInstance().setEdited(false); System.out.println("done"); } public static void saveCameraLocation() { final Camera camera = SceneManager.getInstance().getCameraNode().getCamera(); instance.setCameraLocation(camera.getLocation().clone()); instance.setCameraDirection(SceneManager.getInstance().getCameraNode().getCamera().getDirection().clone()); } public static Node getRoot() { return root; } private Scene() { } public void add(final HousePart housePart) { final HousePart container = housePart.getContainer(); if (container != null) container.getChildren().add(housePart); addTree(housePart); if (container != null) container.draw(); } private void addTree(final HousePart housePart) { System.out.println("Adding: " + housePart); originalHouseRoot.attachChild(housePart.getRoot()); parts.add(housePart); for (final HousePart child : housePart.getChildren()) addTree(child); } public void remove(final HousePart housePart) { if (housePart == null) return; housePart.setGridsVisible(false); final HousePart container = housePart.getContainer(); if (container != null) container.getChildren().remove(housePart); removeTree(housePart); if (container != null) container.draw(); } private void removeTree(final HousePart housePart) { System.out.println("Removing: " + housePart); parts.remove(housePart); // this must happen before call to wall.delete() for (final HousePart child : housePart.getChildren()) removeTree(child); originalHouseRoot.detachChild(housePart.getRoot()); housePart.delete(); } public ArrayList<HousePart> getParts() { return parts; } public void drawResizeBounds() { for (final HousePart part : parts) { if (part instanceof Foundation) part.draw(); } } public Node getOriginalHouseRoot() { return originalHouseRoot; } public static URL getURL() { return url; } public void setAnnotationsVisible(final boolean visible) { isAnnotationsVisible = visible; for (final HousePart part : parts) part.setAnnotationsVisible(visible); if (PrintController.getInstance().isPrintPreview()) for (final HousePart part : PrintController.getInstance().getPrintParts()) part.setAnnotationsVisible(visible); if (PrintController.getInstance().isPrintPreview()) { PrintController.getInstance().restartAnimation(); } else SceneManager.getInstance().refresh(); } public void setTextureMode(final TextureMode textureMode) { this.textureMode = textureMode; redrawAll(); Scene.getInstance().updateRoofDashLinesColor(); } public void setDrawThickness(final boolean draw) { drawThickness = draw; redrawAll = true; } public boolean isDrawThickness() { return drawThickness; } public static boolean isDrawAnnotationsInside() { return drawAnnotationsInside; } public static void setDrawAnnotationsInside(final boolean drawAnnotationsInside) { Scene.drawAnnotationsInside = drawAnnotationsInside; for (final HousePart part : getInstance().getParts()) part.drawAnnotations(); if (PrintController.getInstance().getPrintParts() != null) for (final HousePart part : PrintController.getInstance().getPrintParts()) part.drawAnnotations(); } public void redrawAll() { if (PrintController.getInstance().isPrintPreview()) PrintController.getInstance().restartAnimation(); else redrawAll = true; } public void redrawAllNow() { Snap.clearAnnotationDrawn(); cleanup(); for (final HousePart part : parts) if (part instanceof Roof) part.draw(); for (final HousePart part : parts) if (!(part instanceof Roof)) part.draw(); // no need for redrawing printparts because they will be regenerated from original parts anyways redrawAll = false; } public void setUnit(final Unit unit) { Scene.unit = unit; redrawAll = true; } public Unit getUnit() { if (unit == null) unit = Unit.Meter; return unit; } public void setAnnotationScale(final double scale) { annotationScale = scale; } public double getAnnotationScale() { if (annotationScale == 0) annotationScale = 10; return annotationScale; } public TextureMode getTextureMode() { return textureMode; } // public void updateTextSizes() { // getOriginalHouseRoot().updateWorldBound(true); // final BoundingBox bounds = (BoundingBox) getOriginalHouseRoot().getWorldBound(); // if (bounds != null) { // final double size = Math.max(bounds.getXExtent(), Math.max(bounds.getYExtent(), bounds.getZExtent())); // final double fontSize = size / 20.0; // updateTextSizes(fontSize); // } // } // // public void updateTextSizes(final double fontSize) { // Annotation.setFontSize(fontSize); // updateTextSizes(root, fontSize); // } // // private void updateTextSizes(final Spatial spatial, final double fontSize) { // if (spatial instanceof BMText) { // final BMText label = (BMText) spatial; // if (label.getAutoScale() == AutoScale.Off) { // label.setFontScale(fontSize); // label.updateGeometricState(0); // } // } else if (spatial instanceof Node) { // for (final Spatial child : ((Node) spatial).getChildren()) // updateTextSizes(child, fontSize); // // now that text font is updated redraw the annotation // if (spatial instanceof Annotation) // ((Annotation) spatial).draw(); // } // } public void updateRoofDashLinesColor() { for (final HousePart part : parts) if (part instanceof Roof) ((Roof) part).updateDashLinesColor(); if (PrintController.getInstance().getPrintParts() != null) for (final HousePart part : PrintController.getInstance().getPrintParts()) if (part instanceof Roof) ((Roof) part).updateDashLinesColor(); } public void removeAllRoofs() { final ArrayList<HousePart> roofs = new ArrayList<HousePart>(); for (final HousePart part : parts) if (part instanceof Roof) roofs.add(part); for (final HousePart part : roofs) remove(part); } public static boolean isRedrawAll() { return redrawAll; } public boolean isAnnotationsVisible() { return isAnnotationsVisible; } public ReadOnlyVector3 getCameraLocation() { return cameraLocation; } public void setCameraLocation(final ReadOnlyVector3 cameraLocation) { this.cameraLocation = cameraLocation; } public ReadOnlyVector3 getCameraDirection() { return cameraDirection; } public void setCameraDirection(final ReadOnlyVector3 cameraDirection) { this.cameraDirection = cameraDirection; } public void removeAllGables() { for (final HousePart part : parts) if (part instanceof Roof) ((Roof) part).removeAllGables(); } public double getOverhangLength() { if (overhangLength < 0.01) return 0.01; else return overhangLength; } public void setOverhangLength(final double overhangLength) { this.overhangLength = overhangLength; } public ReadOnlyColorRGBA getFoundationColor() { if (foundationColor == null) return WHITE; else return foundationColor; } public void setFoundationColor(final ReadOnlyColorRGBA foundationColor) { this.foundationColor = foundationColor; } public ReadOnlyColorRGBA getWallColor() { if (wallColor == null) return WHITE; else return wallColor; } public void setWallColor(final ReadOnlyColorRGBA wallColor) { this.wallColor = wallColor; } public ReadOnlyColorRGBA getDoorColor() { if (doorColor == null) return WHITE; else return doorColor; } public void setDoorColor(final ReadOnlyColorRGBA doorColor) { this.doorColor = doorColor; } public ReadOnlyColorRGBA getFloorColor() { if (floorColor == null) return WHITE; else return floorColor; } public void setFloorColor(final ReadOnlyColorRGBA floorColor) { this.floorColor = floorColor; } public ReadOnlyColorRGBA getRoofColor() { if (roofColor == null) return WHITE; else return roofColor; } public void setRoofColor(final ReadOnlyColorRGBA roofColor) { this.roofColor = roofColor; } public boolean isEdited() { return edited; } public void setEdited(final boolean edited) { this.edited = edited; if (!Config.isApplet()) MainFrame.getInstance().updateTitleBar(); if (edited) if (Config.EXPERIMENT) EnergyPanel.getInstance().computeAreaAndEnergy(); } public void updateEditShapes() { for (final HousePart part : parts) part.updateEditShapes(); } public void setFreeze(final boolean freeze) { for (final HousePart part : parts) part.setFreeze(freeze); if (freeze) SceneManager.getInstance().hideAllEditPoints(); redrawAll(); } }
false
false
null
null
diff --git a/src/de/fuberlin/wiwiss/d2rq/server/ConfigLoader.java b/src/de/fuberlin/wiwiss/d2rq/server/ConfigLoader.java index 8a7b1f0..6a96d04 100644 --- a/src/de/fuberlin/wiwiss/d2rq/server/ConfigLoader.java +++ b/src/de/fuberlin/wiwiss/d2rq/server/ConfigLoader.java @@ -1,305 +1,310 @@ package de.fuberlin.wiwiss.d2rq.server; import java.io.File; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import javax.servlet.ServletContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.ResIterator; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.shared.JenaException; import com.hp.hpl.jena.util.FileManager; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; import de.fuberlin.wiwiss.d2rq.D2RQException; import de.fuberlin.wiwiss.d2rq.algebra.Relation; import de.fuberlin.wiwiss.d2rq.vocab.D2RConfig; import de.fuberlin.wiwiss.d2rq.vocab.D2RQ; public class ConfigLoader { public static final int DEFAULT_LIMIT_PER_CLASS_MAP = 50; public static final int DEFAULT_LIMIT_PER_PROPERTY_BRIDGE = 50; private static final Log log = LogFactory.getLog(ConfigLoader.class); /** * Accepts an absolute URI, relative file: URI, or plain file name * (including names with spaces, Windows backslashes etc) and returns an * equivalent full absolute URI. */ public static String toAbsoluteURI(String fileName) { // Permit backslashes when using the file: URI scheme under Windows // This is not required for the latter File.toURL() call if (System.getProperty("os.name").toLowerCase().indexOf("win") != -1) { fileName = fileName.replaceAll("\\\\", "/"); } try { // Check if it's an absolute URI already - but don't confuse Windows // drive letters with URI schemes if (fileName.matches("[a-zA-Z0-9]{2,}:.*") && new URI(fileName).isAbsolute()) { return fileName; } return new File(fileName).getAbsoluteFile().toURI().normalize() .toString(); } catch (URISyntaxException ex) { throw new D2RQException(ex); } } private boolean isLocalMappingFile; private String configURL; private String mappingFilename = null; private Model model = null; private int port = -1; private String baseURI = null; private String serverName = null; private Resource documentMetadata = null; private boolean vocabularyIncludeInstances = true; private boolean autoReloadMapping = true; private int limitPerClassMap = DEFAULT_LIMIT_PER_CLASS_MAP; private int limitPerPropertyBridge = DEFAULT_LIMIT_PER_PROPERTY_BRIDGE; /** * @param configURL * Config file URL, or <code>null</code> for an empty config */ public ConfigLoader(String configURL) { this.configURL = configURL; if (configURL == null) { isLocalMappingFile = false; } else { if (configURL.startsWith("file://")) { isLocalMappingFile = true; mappingFilename = configURL.substring(7); } else if (configURL.startsWith("file:")) { isLocalMappingFile = true; mappingFilename = configURL.substring(5); } else if (configURL.indexOf(":") == -1) { isLocalMappingFile = true; mappingFilename = configURL; } } } public void load() { if (configURL == null) { model = ModelFactory.createDefaultModel(); return; } this.model = FileManager.get().loadModel(this.configURL); Resource server = findServerResource(); if (server == null) { return; } Statement s = server.getProperty(D2RConfig.baseURI); if (s != null) { this.baseURI = s.getResource().getURI(); } s = server.getProperty(D2RConfig.port); if (s != null) { String value = s.getLiteral().getLexicalForm(); try { this.port = Integer.parseInt(value); } catch (NumberFormatException ex) { throw new D2RQException("Illegal integer value '" + value + "' for d2r:port"); } } s = server.getProperty(RDFS.label); if (s != null) { this.serverName = s.getString(); } s = server.getProperty(D2RConfig.documentMetadata); if (s != null) { this.documentMetadata = s.getResource(); } s = server.getProperty(D2RConfig.vocabularyIncludeInstances); if (s != null) { this.vocabularyIncludeInstances = s.getBoolean(); } s = server.getProperty(D2RConfig.autoReloadMapping); if (s != null) { this.autoReloadMapping = s.getBoolean(); } s = server.getProperty(D2RConfig.limitPerClassMap); if (s != null) { try { limitPerClassMap = s.getInt(); } catch (JenaException ex) { if (!s.getBoolean()) { limitPerClassMap = Relation.NO_LIMIT; } } } s = server.getProperty(D2RConfig.limitPerPropertyBridge); if (s != null) { try { limitPerPropertyBridge = s.getInt(); } catch (JenaException ex) { if (!s.getBoolean()) { limitPerPropertyBridge = Relation.NO_LIMIT; } } } } public boolean isLocalMappingFile() { return this.isLocalMappingFile; } public String getLocalMappingFilename() { if (!this.isLocalMappingFile) { return null; } return this.mappingFilename; } public int port() { if (this.model == null) { throw new IllegalStateException("Must load() first"); } return this.port; } public String baseURI() { if (this.model == null) { throw new IllegalStateException("Must load() first"); } return this.baseURI; } public String serverName() { if (this.model == null) { throw new IllegalStateException("Must load() first"); } return this.serverName; } public boolean getVocabularyIncludeInstances() { return this.vocabularyIncludeInstances; } public int getLimitPerClassMap() { return limitPerClassMap; } public int getLimitPerPropertyBridge() { return limitPerPropertyBridge; } public boolean getAutoReloadMapping() { return this.autoReloadMapping; } public void addDocumentMetadata(Model document, Resource documentResource) { if (this.documentMetadata == null) { return; } if (this.model == null) { throw new IllegalStateException("Must load() first"); } StmtIterator it = this.documentMetadata.listProperties(); while (it.hasNext()) { Statement stmt = it.nextStatement(); document.add(documentResource, stmt.getPredicate(), stmt.getObject()); } it = this.model.listStatements(null, null, this.documentMetadata); while (it.hasNext()) { Statement stmt = it.nextStatement(); if (stmt.getPredicate().equals(D2RConfig.documentMetadata)) { continue; } document.add(stmt.getSubject(), stmt.getPredicate(), documentResource); } } protected Resource findServerResource() { ResIterator it = this.model.listSubjectsWithProperty(RDF.type, D2RConfig.Server); if (!it.hasNext()) { return null; } return it.nextResource(); } protected Resource findDatabaseResource() { ResIterator it = this.model.listSubjectsWithProperty(RDF.type, D2RQ.Database); if (!it.hasNext()) { return null; } return it.nextResource(); } // cache resource metadata model, so we dont need to load the file on every // request (!) private Model resourceMetadataTemplate = null; protected Model getResourceMetadataTemplate(D2RServer server, ServletContext context) { if (resourceMetadataTemplate == null) { resourceMetadataTemplate = loadMetadataTemplate(server, context, D2RConfig.metadataTemplate, "resource-metadata.ttl"); } return resourceMetadataTemplate; } // cache dataset metadata model, so we dont need to load the file on every // request (!) private Model datasetMetadataTemplate = null; protected Model getDatasetMetadataTemplate(D2RServer server, ServletContext context) { if (datasetMetadataTemplate == null) { datasetMetadataTemplate = loadMetadataTemplate(server, context, D2RConfig.datasetMetadataTemplate, "dataset-metadata.ttl"); } return datasetMetadataTemplate; } private Model loadMetadataTemplate(D2RServer server, ServletContext context, Property configurationFlag, String defaultTemplateName) { Model metadataTemplate; File userTemplateFile = MetadataCreator.findTemplateFile(server, configurationFlag); Model userResourceTemplate = MetadataCreator .loadTemplateFile(userTemplateFile); if (userResourceTemplate != null && userResourceTemplate.size() > 0) { metadataTemplate = userResourceTemplate; log.info("Using user-specified metadata template at '" + userTemplateFile + "'"); } else { // load default template InputStream drtStream = context.getResourceAsStream("/WEB-INF/" + defaultTemplateName); log.info("Using default metadata template."); metadataTemplate = MetadataCreator.loadMetadataTemplate(drtStream); } return metadataTemplate; } protected boolean serveMetadata() { - return !findServerResource().hasProperty(D2RConfig.disableMetadata); + Resource server = findServerResource(); + if (server == null) { + return true; + } else { + return !server.hasProperty(D2RConfig.disableMetadata); + } } } \ No newline at end of file diff --git a/src/de/fuberlin/wiwiss/d2rq/server/D2RServer.java b/src/de/fuberlin/wiwiss/d2rq/server/D2RServer.java index b8c0ff4..908b2a4 100644 --- a/src/de/fuberlin/wiwiss/d2rq/server/D2RServer.java +++ b/src/de/fuberlin/wiwiss/d2rq/server/D2RServer.java @@ -1,279 +1,282 @@ package de.fuberlin.wiwiss.d2rq.server; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import javax.servlet.ServletContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.joseki.RDFServer; import org.joseki.Registry; import org.joseki.Service; import org.joseki.ServiceRegistry; import org.joseki.processors.SPARQL; import com.hp.hpl.jena.graph.BulkUpdateHandler; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.shared.JenaException; import com.hp.hpl.jena.shared.PrefixMapping; import com.hp.hpl.jena.sparql.core.describe.DescribeHandler; import com.hp.hpl.jena.sparql.core.describe.DescribeHandlerFactory; import com.hp.hpl.jena.sparql.core.describe.DescribeHandlerRegistry; import com.hp.hpl.jena.sparql.util.Context; import com.hp.hpl.jena.util.FileManager; import de.fuberlin.wiwiss.d2rq.ResourceDescriber; import de.fuberlin.wiwiss.d2rq.SystemLoader; import de.fuberlin.wiwiss.d2rq.algebra.Relation; import de.fuberlin.wiwiss.d2rq.map.Mapping; import de.fuberlin.wiwiss.d2rq.vocab.D2RConfig; /** * A D2R Server instance. Sets up a service, loads the D2RQ model, and starts * Joseki. * * @author Richard Cyganiak ([email protected]) */ public class D2RServer { private final static String SPARQL_SERVICE_NAME = "sparql"; /* These service names should match the mappings in web.xml */ private final static String RESOURCE_SERVICE_NAME = "resource"; private final static String DATASET_SERVICE_NAME = "dataset"; private final static String DATA_SERVICE_NAME = "data"; private final static String PAGE_SERVICE_NAME = "page"; private final static String VOCABULARY_STEM = "vocab/"; private final static String DEFAULT_SERVER_NAME = "D2R Server"; private final static String SYSTEM_LOADER = "D2RServer.SYSTEM_LOADER"; private static final Log log = LogFactory.getLog(D2RServer.class); /** System loader for access to the GraphD2RQ and configuration */ private final SystemLoader loader; /** config file parser and Java representation */ private final ConfigLoader config; /** base URI from command line */ private String overrideBaseURI = null; /** the dataset, auto-reloadable in case of local mapping files */ private AutoReloadableDataset dataset; /** Cached single instance */ private MetadataCreator metadataCreator; public D2RServer(SystemLoader loader) { this.loader = loader; this.config = loader.getServerConfig(); } public static D2RServer fromServletContext(ServletContext context) { return retrieveSystemLoader(context).getD2RServer(); } public void overrideBaseURI(String baseURI) { // This is a hack to allow hash URIs to be used at least in the // SPARQL endpoint. It will not work in the Web interface. if (!baseURI.endsWith("/") && !baseURI.endsWith("#")) { baseURI += "/"; } if (baseURI.indexOf('#') != -1) { log.warn("Base URIs containing '#' may not work correctly!"); } this.overrideBaseURI = baseURI; } public String baseURI() { if (this.overrideBaseURI != null) { return this.overrideBaseURI; } return this.config.baseURI(); } public String serverName() { if (this.config.serverName() != null) { return this.config.serverName(); } return D2RServer.DEFAULT_SERVER_NAME; } public boolean hasTruncatedResults() { return dataset.hasTruncatedResults(); } public String resourceBaseURI(String serviceStem) { // This is a hack to allow hash URIs to be used at least in the // SPARQL endpoint. It will not work in the Web interface. if (this.baseURI().endsWith("#")) { return this.baseURI(); } return this.baseURI() + serviceStem + D2RServer.RESOURCE_SERVICE_NAME + "/"; } public String resourceBaseURI() { return resourceBaseURI(""); } public static String getResourceServiceName() { return RESOURCE_SERVICE_NAME; } public static String getDataServiceName() { return DATA_SERVICE_NAME; } public static String getPageServiceName() { return PAGE_SERVICE_NAME; } public static String getDatasetServiceName() { return DATASET_SERVICE_NAME; } public static String getSparqlServiceName() { return SPARQL_SERVICE_NAME; } public String dataURL(String serviceStem, String relativeResourceURI) { return this.baseURI() + serviceStem + DATA_SERVICE_NAME + "/" + relativeResourceURI; } public String pageURL(String serviceStem, String relativeResourceURI) { return this.baseURI() + serviceStem + PAGE_SERVICE_NAME + "/" + relativeResourceURI; } public boolean isVocabularyResource(Resource r) { return r.getURI().startsWith(resourceBaseURI(VOCABULARY_STEM)); } public void addDocumentMetadata(Model document, Resource documentResource) { this.config.addDocumentMetadata(document, documentResource); } /** * @return the auto-reloadable dataset which contains a GraphD2RQ as its * default graph, no named graphs */ public AutoReloadableDataset dataset() { return this.dataset; } public Mapping getMapping() { return loader.getMapping(); } /** * delegate to auto-reloadable dataset, will reload if necessary */ public void checkMappingFileChanged() { dataset.checkMappingFileChanged(); } /** * delegate to auto-reloadable dataset * * * @return prefix mappings for the d2rq base graph */ public PrefixMapping getPrefixes() { return dataset.getPrefixMapping(); } public void start() { if (config.isLocalMappingFile()) { this.dataset = new AutoReloadableDataset(loader, config.getLocalMappingFilename(), config.getAutoReloadMapping()); } else { this.dataset = new AutoReloadableDataset(loader, null, false); } if (loader.getMapping().configuration().getUseAllOptimizations()) { log.info("Fast mode (all optimizations)"); } else { log.info("Safe mode (launch using --fast to use all optimizations)"); } // Set up a custom DescribeHandler that calls out to // {@link ResourceDescriber} DescribeHandlerRegistry.get().clear(); DescribeHandlerRegistry.get().add(new DescribeHandlerFactory() { public DescribeHandler create() { return new DescribeHandler() { private BulkUpdateHandler adder; public void start(Model accumulateResultModel, Context qContext) { adder = accumulateResultModel.getGraph() .getBulkUpdateHandler(); } public void describe(Resource resource) { log.info("DESCRIBE <" + resource + ">"); boolean outgoingTriplesOnly = isVocabularyResource(resource) && !getConfig().getVocabularyIncludeInstances(); adder.add(new ResourceDescriber(getMapping(), resource .asNode(), outgoingTriplesOnly, Relation.NO_LIMIT).description()); } public void finish() { } }; } }); Registry.add(RDFServer.ServiceRegistryName, createJosekiServiceRegistry()); } public void shutdown() { log.info("shutting down"); loader.getMapping().close(); } protected ServiceRegistry createJosekiServiceRegistry() { ServiceRegistry services = new ServiceRegistry(); Service service = new Service(new SPARQL(), D2RServer.SPARQL_SERVICE_NAME, new D2RQDatasetDesc(this.dataset)); services.add(D2RServer.SPARQL_SERVICE_NAME, service); return services; } public ConfigLoader getConfig() { return config; } public static void storeSystemLoader(SystemLoader loader, ServletContext context) { context.setAttribute(SYSTEM_LOADER, loader); } public static SystemLoader retrieveSystemLoader(ServletContext context) { return (SystemLoader) context.getAttribute(SYSTEM_LOADER); } private static String getUri(String base, String service) { + if (base == null) { + base = ""; + } return base.endsWith("/") ? base + service : base + "/" + service; } public String getDatasetIri() { // construct the dataset IRI from the configured base URI and "/dataset" // - as in web.xml return getUri(getConfig().baseURI(), D2RServer.getDatasetServiceName()); } public String getSparqlUrl() { return getUri(getConfig().baseURI(), D2RServer.getSparqlServiceName()); } } \ No newline at end of file diff --git a/src/de/fuberlin/wiwiss/d2rq/server/MetadataCreator.java b/src/de/fuberlin/wiwiss/d2rq/server/MetadataCreator.java index 3f36250..4c48398 100644 --- a/src/de/fuberlin/wiwiss/d2rq/server/MetadataCreator.java +++ b/src/de/fuberlin/wiwiss/d2rq/server/MetadataCreator.java @@ -1,236 +1,236 @@ package de.fuberlin.wiwiss.d2rq.server; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.hp.hpl.jena.rdf.model.AnonId; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.shared.JenaException; import de.fuberlin.wiwiss.d2rq.vocab.D2RConfig; import de.fuberlin.wiwiss.d2rq.vocab.D2RQ; import de.fuberlin.wiwiss.d2rq.vocab.META; /** * Implements a metadata extension. * * @author Hannes Muehleisen ([email protected]) */ public class MetadataCreator { private final static String metadataPlaceholderURIPrefix = "about:metadata:"; // model used to generate nodes private Model model = ModelFactory.createDefaultModel();; // local d2r instance private D2RServer server; // enabling / disabling flag private boolean enable = true; // model that holds the rdf template private Model tplModel; private static final Log log = LogFactory.getLog(MetadataCreator.class); public MetadataCreator(D2RServer server, Model template) { // store D2R server config for template location this.server = server; if (template != null && template.size() > 0) { this.enable = true; this.tplModel = template; } } public Model addMetadataFromTemplate(String resourceURI, String documentURL, String pageUrl) { if (!enable || tplModel == null) { return ModelFactory.createDefaultModel(); } // iterate over template statements to replace placeholders Model metadata = ModelFactory.createDefaultModel(); metadata.setNsPrefixes(tplModel.getNsPrefixMap()); StmtIterator it = tplModel.listStatements(); while (it.hasNext()) { Statement stmt = it.nextStatement(); Resource subj = stmt.getSubject(); Property pred = stmt.getPredicate(); RDFNode obj = stmt.getObject(); try { if (subj.toString().contains(metadataPlaceholderURIPrefix)) { subj = (Resource) parsePlaceholder(subj, documentURL, resourceURI, pageUrl); if (subj == null) { // create a unique blank node with a fixed id. subj = model.createResource(new AnonId(String .valueOf(stmt.getSubject().hashCode()))); } } if (obj.toString().contains(metadataPlaceholderURIPrefix)) { obj = parsePlaceholder(obj, documentURL, resourceURI, pageUrl); } // only add statements with some objects if (obj != null) { stmt = metadata.createStatement(subj, pred, obj); metadata.add(stmt); } } catch (Exception e) { // something went wrong, oops - lets better remove the offending // statement metadata.remove(stmt); log.info("Failed to parse metadata template statement " + stmt.toString()); e.printStackTrace(); } } // remove blank nodes that don't have any properties boolean changes = true; while (changes) { changes = false; StmtIterator stmtIt = metadata.listStatements(); List<Statement> remList = new ArrayList<Statement>(); while (stmtIt.hasNext()) { Statement s = stmtIt.nextStatement(); if (s.getObject().isAnon() && !((Resource) s.getObject().as(Resource.class)) .listProperties().hasNext()) { remList.add(s); changes = true; } } metadata.remove(remList); } // log.info(metadata.listStatements().toList()); return metadata; } private RDFNode parsePlaceholder(RDFNode phRes, String documentURL, String resourceURI, String pageURL) { String phURI = phRes.asNode().getURI(); // get package name and placeholder name from placeholder URI phURI = phURI.replace(metadataPlaceholderURIPrefix, ""); String phPackage = phURI.substring(0, phURI.indexOf(":") + 1); String phName = phURI.replace(phPackage, ""); phPackage = phPackage.replace(":", ""); Resource serverConfig = server.getConfig().findServerResource(); if (phPackage.equals("runtime")) { // <about:metadata:runtime:time> - the current time if (phName.equals("time")) { return model.createTypedLiteral(Calendar.getInstance()); } // <about:metadata:runtime:graph> - URI of the graph if (phName.equals("graph")) { return model.createResource(documentURL); } // <about:metadata:runtime:resource> - URI of the resource if (phName.equals("resource")) { return model.createResource(resourceURI); } // <about:metadata:runtime:page> - URI of the resource if (phName.equals("page")) { return model.createResource(pageURL); } // <about:metadata:runtime:dataset> - URI of the resource if (phName.equals("dataset")) { return model.createResource(server.getDatasetIri()); } } // <about:metadata:server:*> - The d2r server configuration parameters if (phPackage.equals("config") || phPackage.equals("server")) { // look for requested property in the dataset config Property p = model.createProperty(D2RConfig.NS + phName); - if (serverConfig.hasProperty(p)) { + if (serverConfig != null && serverConfig.hasProperty(p)) { return serverConfig.getProperty(p).getObject(); } } // <about:metadata:database:*> - The d2rq database configuration // parameters Resource mappingConfig = server.getConfig().findDatabaseResource(); if (phPackage.equals("database")) { Property p = model.createProperty(D2RQ.NS + phName); - if (mappingConfig.hasProperty(p)) { + if (mappingConfig != null && mappingConfig.hasProperty(p)) { return mappingConfig.getProperty(p).getObject(); } } // <about:metadata:metadata:*> - The metadata provided by users if (phPackage.equals("metadata")) { // look for requested property in the dataset config Property p = model.createProperty(META.NS + phName); - if (serverConfig.hasProperty(p)) + if (serverConfig != null && serverConfig.hasProperty(p)) return serverConfig.getProperty(p).getObject(); } return model .createResource(new AnonId(String.valueOf(phRes.hashCode()))); } public static File findTemplateFile(D2RServer server, Property fileConfigurationProperty) { Resource config = server.getConfig().findServerResource(); if (config == null || !config.hasProperty(fileConfigurationProperty)) { return null; } String metadataTemplate = config.getProperty(fileConfigurationProperty) .getString(); String templatePath; if (metadataTemplate.startsWith(File.separator)) { templatePath = metadataTemplate; } else { File mappingFile = new File(server.getConfig() .getLocalMappingFilename()); String folder = mappingFile.getParent(); if (folder != null) { templatePath = folder + File.separator + metadataTemplate; } else { templatePath = metadataTemplate; } } File f = new File(templatePath); return f; } public static Model loadTemplateFile(File f) { try { return loadMetadataTemplate(new FileInputStream(f)); } catch (Exception e) { return null; } } public static Model loadMetadataTemplate(InputStream is) { try { Model tplModel = ModelFactory.createDefaultModel(); tplModel.read(is, "about:prefix:", "TTL"); return tplModel; } catch (JenaException e) { // ignore } return null; } }
false
false
null
null
diff --git a/main/src/cgeo/geocaching/activity/Progress.java b/main/src/cgeo/geocaching/activity/Progress.java index 88a29ecca..f4b7a334f 100644 --- a/main/src/cgeo/geocaching/activity/Progress.java +++ b/main/src/cgeo/geocaching/activity/Progress.java @@ -1,70 +1,72 @@ package cgeo.geocaching.activity; import android.app.ProgressDialog; import android.content.Context; import android.os.Message; +import android.view.WindowManager; /** * progress dialog wrapper for easier management of resources */ public class Progress { private ProgressDialog dialog; public synchronized void dismiss() { if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } dialog = null; } public synchronized void show(final Context context, final String title, final String message, final boolean indeterminate, final Message cancelMessage) { if (dialog == null) { dialog = ProgressDialog.show(context, title, message, indeterminate, cancelMessage != null); dialog.setProgress(0); if (cancelMessage != null) { dialog.setCancelMessage(cancelMessage); } } } public synchronized void show(final Context context, final String title, final String message, final int style, final Message cancelMessage) { if (dialog == null) { dialog = new ProgressDialog(context); dialog.setProgress(0); dialog.setTitle(title); dialog.setMessage(message); dialog.setProgressStyle(style); if (cancelMessage != null) { dialog.setCancelable(true); dialog.setCancelMessage(cancelMessage); } else { dialog.setCancelable(false); } + dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); dialog.show(); } } public synchronized void setMessage(final String message) { if (dialog != null && dialog.isShowing()) { dialog.setMessage(message); } } public synchronized boolean isShowing() { return dialog != null && dialog.isShowing(); } public synchronized void setMaxProgressAndReset(final int max) { if (dialog != null && dialog.isShowing()) { dialog.setMax(max); dialog.setProgress(0); } } public synchronized void setProgress(final int progress) { if (dialog != null && dialog.isShowing()) { dialog.setProgress(progress); } } }
false
false
null
null
diff --git a/runtime/ceylon/language/any.java b/runtime/ceylon/language/any.java index 1992aded..c6ebe622 100644 --- a/runtime/ceylon/language/any.java +++ b/runtime/ceylon/language/any.java @@ -1,27 +1,27 @@ package ceylon.language; import com.redhat.ceylon.compiler.java.metadata.Ceylon; import com.redhat.ceylon.compiler.java.metadata.Method; import com.redhat.ceylon.compiler.java.metadata.Name; import com.redhat.ceylon.compiler.java.metadata.Sequenced; import com.redhat.ceylon.compiler.java.metadata.TypeInfo; @Ceylon @Method public final class any { private any() { } @TypeInfo("ceylon.language.Boolean") - public static boolean any(@Name("values") @Sequenced + public static boolean any(@Name("values") @Sequenced @TypeInfo("ceylon.language.Iterable<ceylon.language.Boolean>") final Iterable<? extends Boolean> values) { java.lang.Object $tmp; for (Iterator<? extends Boolean> $val$iter$0 = values.getIterator(); !(($tmp = $val$iter$0.next()) instanceof Finished);) { if (((Boolean)$tmp).booleanValue()) return true; } return false; } } diff --git a/runtime/ceylon/language/elements.java b/runtime/ceylon/language/elements.java new file mode 100644 index 00000000..c4084ed1 --- /dev/null +++ b/runtime/ceylon/language/elements.java @@ -0,0 +1,25 @@ +package ceylon.language; + +import com.redhat.ceylon.compiler.java.metadata.Ceylon; +import com.redhat.ceylon.compiler.java.metadata.Method; +import com.redhat.ceylon.compiler.java.metadata.Name; +import com.redhat.ceylon.compiler.java.metadata.Sequenced; +import com.redhat.ceylon.compiler.java.metadata.TypeInfo; +import com.redhat.ceylon.compiler.java.metadata.TypeParameter; +import com.redhat.ceylon.compiler.java.metadata.TypeParameters; + +@Ceylon +@Method +public final class elements { + + private elements() { + } + + @TypeInfo("ceylon.language.Iterable<Element>") + @TypeParameters(@TypeParameter(value="Element")) + public static <Element> Iterable<? extends Element> elements(@Name("elements") + @Sequenced @TypeInfo("ceylon.language.Iterable<Element>") + final Iterable<? extends Element> elements) { + return elements; + } +} diff --git a/runtime/ceylon/language/every.java b/runtime/ceylon/language/every.java index e72b33b9..0800d3ed 100644 --- a/runtime/ceylon/language/every.java +++ b/runtime/ceylon/language/every.java @@ -1,27 +1,27 @@ package ceylon.language; import com.redhat.ceylon.compiler.java.metadata.Ceylon; import com.redhat.ceylon.compiler.java.metadata.Method; import com.redhat.ceylon.compiler.java.metadata.Name; import com.redhat.ceylon.compiler.java.metadata.Sequenced; import com.redhat.ceylon.compiler.java.metadata.TypeInfo; @Ceylon @Method public final class every { private every() { } @TypeInfo("ceylon.language.Boolean") - public static boolean every(@Name("values") @Sequenced + public static boolean every(@Name("values") @Sequenced @TypeInfo("ceylon.language.Iterable<ceylon.language.Boolean>") final Iterable<? extends Boolean> values) { java.lang.Object $tmp; for (Iterator<? extends Boolean> $val$iter$0 = values.getIterator(); !(($tmp = $val$iter$0.next()) instanceof Finished);) { if (!((Boolean)$tmp).booleanValue()) return false; } return true; } }
false
false
null
null
diff --git a/flyway-core/src/test/java/com/googlecode/flyway/core/dbsupport/SqlScriptSmallTest.java b/flyway-core/src/test/java/com/googlecode/flyway/core/dbsupport/SqlScriptSmallTest.java index 6b752db7e..d5dcd36d5 100644 --- a/flyway-core/src/test/java/com/googlecode/flyway/core/dbsupport/SqlScriptSmallTest.java +++ b/flyway-core/src/test/java/com/googlecode/flyway/core/dbsupport/SqlScriptSmallTest.java @@ -1,282 +1,293 @@ /** * Copyright (C) 2010-2013 the original author or authors. * * 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.googlecode.flyway.core.dbsupport; import com.googlecode.flyway.core.dbsupport.mysql.MySQLDbSupport; import com.googlecode.flyway.core.util.PlaceholderReplacer; import org.junit.Ignore; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; /** * Test for SqlScript. */ public class SqlScriptSmallTest { - /** * Class under test. */ private SqlScript sqlScript = new SqlScript(new MySQLDbSupport(null)); /** * Input lines. */ private List<String> lines = new ArrayList<String>(); @Test public void stripSqlCommentsNoComment() { lines.add("select * from table;"); List<SqlStatement> sqlStatements = sqlScript.linesToStatements(lines); assertEquals("select * from table", sqlStatements.get(0).getSql()); } @Test public void stripSqlCommentsSingleLineComment() { lines.add("--select * from table;"); List<SqlStatement> sqlStatements = sqlScript.linesToStatements(lines); assertEquals(0, sqlStatements.size()); } @Test public void stripSqlCommentsMultiLineCommentSingleLine() { lines.add("/*comment line*/"); lines.add("select * from table;"); List<SqlStatement> sqlStatements = sqlScript.linesToStatements(lines); assertEquals("select * from table", sqlStatements.get(0).getSql()); } @Test public void stripSqlCommentsMultiLineCommentMultipleLines() { lines.add("/*comment line"); lines.add("more comment text*/"); List<SqlStatement> sqlStatements = sqlScript.linesToStatements(lines); assertEquals(0, sqlStatements.size()); } @Test public void linesToStatements() { lines.add("select col1, col2"); lines.add("from mytable"); lines.add("where col1 > 10;"); List<SqlStatement> sqlStatements = sqlScript.linesToStatements(lines); assertNotNull(sqlStatements); assertEquals(1, sqlStatements.size()); SqlStatement sqlStatement = sqlStatements.get(0); assertEquals(1, sqlStatement.getLineNumber()); assertEquals("select col1, col2\nfrom mytable\nwhere col1 > 10", sqlStatement.getSql()); } @Test public void linesToStatementsDelimiterKeywordInMultilineComment() { lines.add("/*"); lines.add("DELIMITER $$"); lines.add("*/"); lines.add("SELECT 1;"); lines.add("/*"); lines.add("END;"); lines.add("$$"); lines.add("DELIMITER ;"); lines.add("*/"); List<SqlStatement> sqlStatements = sqlScript.linesToStatements(lines); assertEquals(1, sqlStatements.size()); SqlStatement sqlStatement = sqlStatements.get(0); assertEquals(4, sqlStatement.getLineNumber()); assertEquals("SELECT 1", sqlStatement.getSql()); } @Test public void linesToStatementsMultipleDelimiterStatements() { lines.add("delimiter ;"); lines.add("select 1;"); lines.add("select 2;"); lines.add("delimiter $$"); lines.add("select 3;"); lines.add("$$"); lines.add("select 4;"); lines.add("$$"); List<SqlStatement> sqlStatements = sqlScript.linesToStatements(lines); assertEquals(4, sqlStatements.size()); assertEquals("select 1", sqlStatements.get(0).getSql()); assertEquals("select 2", sqlStatements.get(1).getSql()); assertEquals("select 3;\n", sqlStatements.get(2).getSql()); assertEquals("select 4;\n", sqlStatements.get(3).getSql()); } @Test public void linesToStatementsMySQLCommentDirectives() { lines.add("/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;"); lines.add("DROP TABLE IF EXISTS account;"); lines.add("/*!40101 SET character_set_client = utf8 */;"); List<SqlStatement> sqlStatements = sqlScript.linesToStatements(lines); assertNotNull(sqlStatements); assertEquals(3, sqlStatements.size()); SqlStatement sqlStatement = sqlStatements.get(0); assertEquals(1, sqlStatement.getLineNumber()); assertEquals("/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */", sqlStatement.getSql()); } @Test(timeout = 3000) public void linesToStatementsSuperLongStatement() { lines.add("INSERT INTO T1 (A, B, C, D) VALUES"); for (int i = 0; i < 10000; i++) { lines.add("(1, '2', '3', '4'),"); } lines.add("(1, '2', '3', '4');"); List<SqlStatement> sqlStatements = sqlScript.linesToStatements(lines); assertNotNull(sqlStatements); assertEquals(1, sqlStatements.size()); SqlStatement sqlStatement = sqlStatements.get(0); assertEquals(1, sqlStatement.getLineNumber()); } @Test public void linesToStatementsMultilineCommentsWithDashes() { lines.add("/*--------------------------------------------"); lines.add("Some comments"); lines.add("-----------------------------------------*/"); lines.add("SELECT 1;"); List<SqlStatement> sqlStatements = sqlScript.linesToStatements(lines); assertNotNull(sqlStatements); assertEquals(1, sqlStatements.size()); SqlStatement sqlStatement = sqlStatements.get(0); assertEquals(4, sqlStatement.getLineNumber()); } @Test public void linesToStatementsPreserveEmptyLinesInsideStatement() { lines.add("update emailtemplate set body = 'Hi $order.billingContactDisplayName,"); lines.add(""); lines.add("Thanks for your interest in our products!"); lines.add(""); lines.add("Please find your quote attached in PDF format.'"); lines.add("where templatename = 'quote_template';"); List<SqlStatement> sqlStatements = sqlScript.linesToStatements(lines); assertNotNull(sqlStatements); assertEquals(1, sqlStatements.size()); SqlStatement sqlStatement = sqlStatements.get(0); assertEquals(1, sqlStatement.getLineNumber()); assertEquals("update emailtemplate set body = 'Hi $order.billingContactDisplayName,\n" + "\n" + "Thanks for your interest in our products!\n" + "\n" + "Please find your quote attached in PDF format.'\n" + "where templatename = 'quote_template'", sqlStatement.getSql()); } @Test public void linesToStatementsSkipEmptyLinesBetweenStatements() { lines.add("update emailtemplate set body = 'Hi';"); lines.add(""); lines.add("update emailtemplate set body = 'Hello';"); lines.add(""); lines.add(""); lines.add("update emailtemplate set body = 'Howdy';"); List<SqlStatement> sqlStatements = sqlScript.linesToStatements(lines); assertNotNull(sqlStatements); assertEquals(3, sqlStatements.size()); assertEquals(1, sqlStatements.get(0).getLineNumber()); assertEquals("update emailtemplate set body = 'Hi'", sqlStatements.get(0).getSql()); assertEquals(3, sqlStatements.get(1).getLineNumber()); assertEquals("update emailtemplate set body = 'Hello'", sqlStatements.get(1).getSql()); assertEquals(6, sqlStatements.get(2).getLineNumber()); assertEquals("update emailtemplate set body = 'Howdy'", sqlStatements.get(2).getSql()); } @Test public void parsePlaceholderComments() { String source = "${drop_view} \"SOME_VIEW\" IF EXISTS;\n" + "CREATE ${or_replace} VIEW \"SOME_VIEW\";\n"; Map<String, String> placeholders = new HashMap<String, String>(); placeholders.put("drop_view", "--"); placeholders.put("or_replace", "OR REPLACE"); PlaceholderReplacer placeholderReplacer = new PlaceholderReplacer(placeholders, "${", "}"); List<SqlStatement> sqlStatements = sqlScript.parse(placeholderReplacer.replacePlaceholders(source)); assertNotNull(sqlStatements); assertEquals(1, sqlStatements.size()); SqlStatement sqlStatement = sqlStatements.get(0); assertEquals(2, sqlStatement.getLineNumber()); assertEquals("CREATE OR REPLACE VIEW \"SOME_VIEW\"", sqlStatement.getSql()); } @Test public void parseNoTrim() { String source = "update emailtemplate set body = 'Hi $order.billingContactDisplayName,\n" + "\n" + " Thanks for your interest in our products!\n" + "\n" + " Please find your quote attached in PDF format.'\n" + "where templatename = 'quote_template'"; List<SqlStatement> sqlStatements = sqlScript.parse(source); assertNotNull(sqlStatements); assertEquals(1, sqlStatements.size()); SqlStatement sqlStatement = sqlStatements.get(0); assertEquals(1, sqlStatement.getLineNumber()); assertEquals(source, sqlStatement.getSql()); } @Test public void parsePreserveTrailingCommentsInsideStatement() { String source = "update emailtemplate /* yes, it's true */\n" + " set body='Thanks !' /* my pleasure */\n" + " and subject = 'To our favorite customer!'"; List<SqlStatement> sqlStatements = sqlScript.parse(source); assertNotNull(sqlStatements); assertEquals(1, sqlStatements.size()); SqlStatement sqlStatement = sqlStatements.get(0); assertEquals(1, sqlStatement.getLineNumber()); assertEquals(source, sqlStatement.getSql()); } + @Test + public void mysqlPoundSymbol() { + String source = "INSERT INTO `bonlayout` (`vertriebslinie`, `lang`, `position`, `layout`) VALUES ('CH01RE', 'en', 'EC_BLZ_1_0', '<RIGHT>Bank code: \n" + + "___________________________</RIGHT>');\n" + + "INSERT INTO `bonlayout` (`vertriebslinie`, `lang`, `position`, `layout`) VALUES ('CH01RE', 'en', 'EC_KNR_1_0', '<RIGHT>Account #: \n" + + "___________________________</RIGHT>');"; + + List<SqlStatement> sqlStatements = sqlScript.parse(source); + assertNotNull(sqlStatements); + assertEquals(2, sqlStatements.size()); + } + @Ignore("Currently broken") @Test public void parseWithTrailingComment() { String sql = "ALTER TABLE A RENAME TO B; -- trailing comment\r\n" + "ALTER TABLE B RENAME TO C;"; List<SqlStatement> statements = sqlScript.parse(sql); assertEquals(2, statements.size()); } }
false
false
null
null
diff --git a/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/InitializeRootDSERunnable.java b/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/InitializeRootDSERunnable.java index ebe444d39..e721bc22d 100644 --- a/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/InitializeRootDSERunnable.java +++ b/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/InitializeRootDSERunnable.java @@ -1,422 +1,427 @@ /* * 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.directory.studio.ldapbrowser.core.jobs; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.directory.api.ldap.model.constants.SchemaConstants; import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException; import org.apache.directory.api.ldap.model.message.SearchScope; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Connection.AliasDereferencingMethod; import org.apache.directory.studio.connection.core.Connection.ReferralHandlingMethod; import org.apache.directory.studio.connection.core.ConnectionCorePlugin; import org.apache.directory.studio.connection.core.DetectedConnectionProperties; import org.apache.directory.studio.connection.core.jobs.StudioConnectionBulkRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.events.AttributesInitializedEvent; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; import org.apache.directory.studio.ldapbrowser.core.model.IAttribute; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.IEntry; import org.apache.directory.studio.ldapbrowser.core.model.IRootDSE; import org.apache.directory.studio.ldapbrowser.core.model.ISearch; import org.apache.directory.studio.ldapbrowser.core.model.ISearchResult; import org.apache.directory.studio.ldapbrowser.core.model.impl.BaseDNEntry; import org.apache.directory.studio.ldapbrowser.core.model.impl.DirectoryMetadataEntry; import org.apache.directory.studio.ldapbrowser.core.model.impl.Search; /** * Runnable to initialize the Root DSE. * * @author <a href="mailto:[email protected]">Apache Directory Project</a> */ public class InitializeRootDSERunnable implements StudioConnectionBulkRunnableWithProgress { /** The requested attributes when reading the Root DSE. */ public static final String[] ROOT_DSE_ATTRIBUTES = { SchemaConstants.NAMING_CONTEXTS_AT, SchemaConstants.SUBSCHEMA_SUBENTRY_AT, SchemaConstants.SUPPORTED_LDAP_VERSION_AT, SchemaConstants.SUPPORTED_SASL_MECHANISMS_AT, SchemaConstants.SUPPORTED_EXTENSION_AT, SchemaConstants.SUPPORTED_CONTROL_AT, SchemaConstants.SUPPORTED_FEATURES_AT, SchemaConstants.VENDOR_NAME_AT, SchemaConstants.VENDOR_VERSION_AT, SchemaConstants.ALL_OPERATIONAL_ATTRIBUTES }; private IRootDSE rootDSE; /** * Creates a new instance of InitializeRootDSERunnable. * * @param rootDSE the root DSE */ private InitializeRootDSERunnable( IRootDSE rootDSE ) { this.rootDSE = rootDSE; } /** * {@inheritDoc} */ public Connection[] getConnections() { return new Connection[] { rootDSE.getBrowserConnection().getConnection() }; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__init_entries_title_attonly; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { return new IEntry[] { rootDSE }; } /** * {@inheritDoc} */ public String getErrorMessage() { return BrowserCoreMessages.jobs__init_entries_error_1; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( " ", 3 ); //$NON-NLS-1$ monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.setTaskName( BrowserCoreMessages.bind( BrowserCoreMessages.jobs__init_entries_task, new String[] { rootDSE.getDn().getName() } ) ); monitor.worked( 1 ); monitor.reportProgress( BrowserCoreMessages.bind( BrowserCoreMessages.jobs__init_entries_progress_att, new String[] { rootDSE.getDn().getName() } ) ); loadRootDSE( rootDSE.getBrowserConnection(), monitor ); } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { EventRegistry.fireEntryUpdated( new AttributesInitializedEvent( rootDSE ), this ); } /** * Loads the Root DSE. * * @param browserConnection the browser connection * @param monitor the progress monitor * * @throws Exception the exception */ public static synchronized void loadRootDSE( IBrowserConnection browserConnection, StudioProgressMonitor monitor ) { // clear old children InitializeChildrenRunnable.clearCaches( browserConnection.getRootDSE(), true ); // delete old attributes IAttribute[] oldAttributes = browserConnection.getRootDSE().getAttributes(); if ( oldAttributes != null ) { for ( IAttribute oldAttribute : oldAttributes ) { browserConnection.getRootDSE().deleteAttribute( oldAttribute ); } } // load well-known Root DSE attributes and operational attributes ISearch search = new Search( null, browserConnection, Dn.EMPTY_DN, ISearch.FILTER_TRUE, ROOT_DSE_ATTRIBUTES, SearchScope.OBJECT, 0, 0, Connection.AliasDereferencingMethod.NEVER, Connection.ReferralHandlingMethod.IGNORE, false, null ); SearchRunnable.searchAndUpdateModel( browserConnection, search, monitor ); // load all user attributes search = new Search( null, browserConnection, Dn.EMPTY_DN, ISearch.FILTER_TRUE, new String[] { SchemaConstants.ALL_USER_ATTRIBUTES }, SearchScope.OBJECT, 0, 0, Connection.AliasDereferencingMethod.NEVER, Connection.ReferralHandlingMethod.IGNORE, false, null ); SearchRunnable.searchAndUpdateModel( browserConnection, search, monitor ); // the list of entries under the Root DSE Map<Dn, IEntry> rootDseEntries = new HashMap<Dn, IEntry>(); // 1st: add base DNs, either the specified or from the namingContexts attribute if ( !browserConnection.isFetchBaseDNs() && browserConnection.getBaseDN() != null && !"".equals( browserConnection.getBaseDN().toString() ) ) //$NON-NLS-1$ { // only add the specified base Dn Dn dn = browserConnection.getBaseDN(); IEntry entry = browserConnection.getEntryFromCache( dn ); if ( entry == null ) { entry = new BaseDNEntry( dn, browserConnection ); browserConnection.cacheEntry( entry ); } rootDseEntries.put( dn, entry ); } else { // get base DNs from namingContexts attribute Set<String> namingContextSet = new HashSet<String>(); IAttribute attribute = browserConnection.getRootDSE().getAttribute( SchemaConstants.NAMING_CONTEXTS_AT ); if ( attribute != null ) { String[] values = attribute.getStringValues(); for ( int i = 0; i < values.length; i++ ) { namingContextSet.add( values[i] ); } } if ( !namingContextSet.isEmpty() ) { for ( String namingContext : namingContextSet ) { if ( namingContext.length() > 0 && namingContext.charAt( namingContext.length() - 1 ) == '\u0000' ) { namingContext = namingContext.substring( 0, namingContext.length() - 1 ); } if ( !"".equals( namingContext ) ) //$NON-NLS-1$ { try { Dn dn = new Dn( namingContext ); IEntry entry = browserConnection.getEntryFromCache( dn ); if ( entry == null ) { entry = new BaseDNEntry( dn, browserConnection ); browserConnection.cacheEntry( entry ); } rootDseEntries.put( dn, entry ); } catch ( LdapInvalidDnException e ) { monitor.reportError( BrowserCoreMessages.model__error_setting_base_dn, e ); } } else { // special handling of empty namingContext (Novell eDirectory): // perform a one-level search and add all result DNs to the set searchRootDseEntries( browserConnection, rootDseEntries, monitor ); } } } else { // special handling of non-existing namingContexts attribute (Oracle Internet Directory) // perform a one-level search and add all result DNs to the set searchRootDseEntries( browserConnection, rootDseEntries, monitor ); } } // 2nd: add schema sub-entry IEntry[] schemaEntries = getDirectoryMetadataEntries( browserConnection, SchemaConstants.SUBSCHEMA_SUBENTRY_AT ); for ( IEntry entry : schemaEntries ) { if ( entry instanceof DirectoryMetadataEntry ) { ( ( DirectoryMetadataEntry ) entry ).setSchemaEntry( true ); } rootDseEntries.put( entry.getDn(), entry ); } // get other meta data entries IAttribute[] rootDseAttributes = browserConnection.getRootDSE().getAttributes(); if ( rootDseAttributes != null ) { for ( IAttribute attribute : rootDseAttributes ) { IEntry[] metadataEntries = getDirectoryMetadataEntries( browserConnection, attribute.getDescription() ); for ( IEntry entry : metadataEntries ) { rootDseEntries.put( entry.getDn(), entry ); } } } // try to init entries StudioProgressMonitor dummyMonitor = new StudioProgressMonitor( monitor ); for ( IEntry entry : rootDseEntries.values() ) { initBaseEntry( entry, dummyMonitor ); } // set flags browserConnection.getRootDSE().setHasMoreChildren( false ); browserConnection.getRootDSE().setAttributesInitialized( true ); browserConnection.getRootDSE().setInitOperationalAttributes( true ); browserConnection.getRootDSE().setChildrenInitialized( true ); browserConnection.getRootDSE().setHasChildrenHint( true ); browserConnection.getRootDSE().setDirectoryEntry( true ); // Set detected connection properties DetectedConnectionProperties detectedConnectionProperties = browserConnection.getConnection() .getDetectedConnectionProperties(); IAttribute vendorNameAttribute = browserConnection.getRootDSE().getAttribute( "vendorName" ); //$NON-NLS-1$ if ( ( vendorNameAttribute != null ) && ( vendorNameAttribute.getValueSize() > 0 ) ) { detectedConnectionProperties.setVendorName( vendorNameAttribute.getStringValue() ); } IAttribute vendorVersionAttribute = browserConnection.getRootDSE().getAttribute( "vendorVersion" ); //$NON-NLS-1$ if ( ( vendorVersionAttribute != null ) && ( vendorVersionAttribute.getValueSize() > 0 ) ) { detectedConnectionProperties.setVendorVersion( vendorVersionAttribute.getStringValue() ); } IAttribute supportedControlAttribute = browserConnection.getRootDSE().getAttribute( "supportedControl" ); //$NON-NLS-1$ if ( ( supportedControlAttribute != null ) && ( supportedControlAttribute.getValueSize() > 0 ) ) { detectedConnectionProperties.setSupportedControls( Arrays.asList( supportedControlAttribute .getStringValues() ) ); } IAttribute supportedExtensionAttribute = browserConnection.getRootDSE().getAttribute( "supportedExtension" ); //$NON-NLS-1$ if ( ( supportedExtensionAttribute != null ) && ( supportedExtensionAttribute.getValueSize() > 0 ) ) { detectedConnectionProperties.setSupportedExtensions( Arrays.asList( supportedExtensionAttribute .getStringValues() ) ); } IAttribute supportedFeaturesAttribute = browserConnection.getRootDSE().getAttribute( "supportedFeatures" ); //$NON-NLS-1$ if ( ( supportedFeaturesAttribute != null ) && ( supportedFeaturesAttribute.getValueSize() > 0 ) ) { detectedConnectionProperties.setSupportedFeatures( Arrays.asList( supportedFeaturesAttribute .getStringValues() ) ); } detectedConnectionProperties .setServerType( ServerTypeDetector.detectServerType( browserConnection.getRootDSE() ) ); ConnectionCorePlugin.getDefault().getConnectionManager() .connectionUpdated( browserConnection.getConnection() ); } private static void initBaseEntry( IEntry entry, StudioProgressMonitor monitor ) { IBrowserConnection browserConnection = entry.getBrowserConnection(); Dn dn = entry.getDn(); // search the entry AliasDereferencingMethod derefAliasMethod = browserConnection.getAliasesDereferencingMethod(); ReferralHandlingMethod handleReferralsMethod = browserConnection.getReferralsHandlingMethod(); ISearch search = new Search( null, browserConnection, dn, ISearch.FILTER_TRUE, ISearch.NO_ATTRIBUTES, SearchScope.OBJECT, 1, 0, derefAliasMethod, handleReferralsMethod, true, null ); SearchRunnable.searchAndUpdateModel( browserConnection, search, monitor ); ISearchResult[] results = search.getSearchResults(); if ( results != null && results.length == 1 ) { // add entry to Root DSE ISearchResult result = results[0]; entry = result.getEntry(); browserConnection.getRootDSE().addChild( entry ); } else { // Dn exists in the Root DSE, but doesn't exist in directory browserConnection.uncacheEntryRecursive( entry ); } } private static IEntry[] getDirectoryMetadataEntries( IBrowserConnection browserConnection, String metadataAttributeName ) { List<Dn> metadataEntryDnList = new ArrayList<Dn>(); IAttribute attribute = browserConnection.getRootDSE().getAttribute( metadataAttributeName ); if ( attribute != null ) { String[] values = attribute.getStringValues(); for ( String dn : values ) { if ( dn != null && !"".equals( dn ) ) //$NON-NLS-1$ { try { metadataEntryDnList.add( new Dn( dn ) ); } catch ( LdapInvalidDnException e ) { } } } } IEntry[] metadataEntries = new IEntry[metadataEntryDnList.size()]; for ( int i = 0; i < metadataEntryDnList.size(); i++ ) { Dn dn = metadataEntryDnList.get( i ); metadataEntries[i] = browserConnection.getEntryFromCache( dn ); if ( metadataEntries[i] == null ) { metadataEntries[i] = new DirectoryMetadataEntry( dn, browserConnection ); metadataEntries[i].setDirectoryEntry( true ); browserConnection.cacheEntry( metadataEntries[i] ); } } return metadataEntries; } private static void searchRootDseEntries( IBrowserConnection browserConnection, Map<Dn, IEntry> rootDseEntries, StudioProgressMonitor monitor ) { ISearch search = new Search( null, browserConnection, Dn.EMPTY_DN, ISearch.FILTER_TRUE, ISearch.NO_ATTRIBUTES, SearchScope.ONELEVEL, 0, 0, Connection.AliasDereferencingMethod.NEVER, Connection.ReferralHandlingMethod.IGNORE, false, null ); SearchRunnable.searchAndUpdateModel( browserConnection, search, monitor ); + ISearchResult[] results = search.getSearchResults(); - for ( ISearchResult searchResult : results ) + + if ( results != null ) { - IEntry entry = searchResult.getEntry(); - rootDseEntries.put( entry.getDn(), entry ); + for ( ISearchResult searchResult : results ) + { + IEntry entry = searchResult.getEntry(); + rootDseEntries.put( entry.getDn(), entry ); + } } } }
false
false
null
null
diff --git a/almanach/almanach-ejb/src/test/java/com/stratelia/webactiv/almanach/BaseAlmanachTest.java b/almanach/almanach-ejb/src/test/java/com/stratelia/webactiv/almanach/BaseAlmanachTest.java index de42de78c..e7a08adde 100644 --- a/almanach/almanach-ejb/src/test/java/com/stratelia/webactiv/almanach/BaseAlmanachTest.java +++ b/almanach/almanach-ejb/src/test/java/com/stratelia/webactiv/almanach/BaseAlmanachTest.java @@ -1,93 +1,93 @@ /* * Copyright (C) 2000 - 2011 Silverpeas * * 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. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have recieved a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/legal/licensing" * * 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. * * 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 com.stratelia.webactiv.almanach; import com.silverpeas.components.model.AbstractJndiCase; import com.silverpeas.components.model.SilverpeasJndiCase; import com.stratelia.webactiv.util.DBUtil; import java.io.IOException; import java.sql.Connection; import java.util.Calendar; import java.util.Date; import javax.naming.NamingException; import org.dbunit.database.IDatabaseConnection; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; /** * Base class for tests in the almanach component. * It prepares the database to use in tests. */ public abstract class BaseAlmanachTest extends AbstractJndiCase { /** * The month to use in tests: april. */ public static final int TEST_MONTH = 4; /** * The year to use in tests: 2011 */ public static final int TEST_YEAR = 2011; /** * The all available almanach instances in tests. */ public static final String[] almanachIds = {"almanach272", "almanach509", "almanach701"}; private IDatabaseConnection dbConnection; private Connection connection; @BeforeClass public static void generalSetUp() throws IOException, NamingException, Exception { baseTest = new SilverpeasJndiCase("com/stratelia/webactiv/almanach/model/events-dataset.xml", "create-database.ddl"); baseTest.configureJNDIDatasource(); IDatabaseConnection databaseConnection = baseTest.getDatabaseTester().getConnection(); executeDDL(databaseConnection, baseTest.getDdlFile()); baseTest.getDatabaseTester().closeConnection(databaseConnection); } @Before public void bootstrapDatabase() throws Exception { dbConnection = baseTest.getConnection(); connection = dbConnection.getConnection(); - DBUtil.getInstance(connection); + DBUtil.getInstanceForTest(connection); } @After public void shutdownDatabase() throws Exception { baseTest.getDatabaseTester().closeConnection(dbConnection); } public Connection getConnection() { return connection; } public static Date dateToUseInTests() { Calendar date = Calendar.getInstance(); date.set(Calendar.YEAR, TEST_YEAR); date.set(Calendar.MONTH, TEST_MONTH - 1); date.set(Calendar.DAY_OF_MONTH, 14); return date.getTime(); } } diff --git a/almanach/almanach-war/src/main/java/com/stratelia/webactiv/almanach/servlets/AlmanachRequestRouter.java b/almanach/almanach-war/src/main/java/com/stratelia/webactiv/almanach/servlets/AlmanachRequestRouter.java index 43b8d7765..d348f1981 100644 --- a/almanach/almanach-war/src/main/java/com/stratelia/webactiv/almanach/servlets/AlmanachRequestRouter.java +++ b/almanach/almanach-war/src/main/java/com/stratelia/webactiv/almanach/servlets/AlmanachRequestRouter.java @@ -1,597 +1,594 @@ /** * Copyright (C) 2000 - 2011 Silverpeas * * 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. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have recieved a copy of the text describing * the FLOSS exception, and it is also available here: * "http://repository.silverpeas.com/legal/licensing" * * 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. * * 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 com.stratelia.webactiv.almanach.servlets; import com.stratelia.webactiv.util.FileServerUtils; import com.silverpeas.export.ExportException; import com.silverpeas.export.NoDataToExportException; import com.stratelia.silverpeas.util.ResourcesWrapper; import javax.servlet.http.HttpServletRequest; import com.stratelia.silverpeas.peasCore.ComponentContext; import com.stratelia.silverpeas.peasCore.ComponentSessionController; import com.stratelia.silverpeas.peasCore.MainSessionController; import com.stratelia.silverpeas.peasCore.servlets.ComponentRequestRouter; import com.stratelia.silverpeas.silvertrace.SilverTrace; import com.stratelia.webactiv.almanach.control.AlmanachCalendarView; import com.stratelia.webactiv.almanach.control.AlmanachSessionController; import com.stratelia.webactiv.almanach.control.CalendarViewType; import com.stratelia.webactiv.almanach.model.EventDetail; import com.stratelia.webactiv.almanach.model.Periodicity; import com.stratelia.webactiv.util.DBUtil; import com.stratelia.webactiv.util.DateUtil; import com.stratelia.webactiv.util.GeneralPropertiesManager; import com.stratelia.webactiv.util.ResourceLocator; import java.net.URLEncoder; import static com.stratelia.webactiv.almanach.control.CalendarViewType.*; import static com.silverpeas.util.StringUtil.*; public class AlmanachRequestRouter extends ComponentRequestRouter { private static final long serialVersionUID = 1L; @Override public ComponentSessionController createComponentSessionController( MainSessionController mainSessionCtrl, ComponentContext context) { return ((ComponentSessionController) new AlmanachSessionController( mainSessionCtrl, context)); } /** * This method has to be implemented in the component request rooter class. returns the session * control bean name to be put in the request object ex : for almanach, returns "almanach" * @return */ @Override public String getSessionControlBeanName() { return "almanach"; } /** * Set almanach settings * @param almanach * @param request */ private void setGlobalInfo(AlmanachSessionController almanach, HttpServletRequest request) { ResourceLocator settings = almanach.getSettings(); request.setAttribute("settings", settings); } /** * This method has to be implemented by the component request Router it has to compute a * destination page * @param function The entering request function (ex : "Main.jsp") * @param componentSC The component Session Control, build and initialised. * @param request The entering request. The request Router need it to get parameters * @return The complete destination URL for a forward (ex : * "/almanach/jsp/almanach.jsp?flag=user") */ @Override public String getDestination(String function, ComponentSessionController componentSC, HttpServletRequest request) { SilverTrace.info("almanach", "AlmanachRequestRouter.getDestination()", "root.MSG_GEN_ENTER_METHOD"); AlmanachSessionController almanach = (AlmanachSessionController) componentSC; setGlobalInfo(almanach, request); String destination = ""; // the flag is the best user's profile String flag = getFlag(componentSC.getUserRoles()); try { if (function.startsWith("Main") || function.startsWith("almanach") || function.startsWith("portlet")) { // contrôle de l'Action de l'utilisateur String action = request.getParameter("Action"); // accès première fois, initialisation de l'almanach à la date du jour // (utile pour générer le Header) if (action == null || action.isEmpty()) { action = "View"; String viewType = request.getParameter("view"); if (isDefined(viewType)) { almanach.setViewMode(CalendarViewType.valueOf(viewType)); } } else if ("PreviousView".equals(action)) { almanach.previousView(); } else if ("NextView".equals(action)) { almanach.nextView(); } else if ("GoToday".equals(action)) { almanach.today(); } else if ("ViewByMonth".equals(action)) { almanach.setViewMode(MONTHLY); } else if ("ViewByWeek".equals(action)) { almanach.setViewMode(WEEKLY); } else if ("ViewNextEvents".equals(action)) { almanach.setViewMode(NEXT_EVENTS); } AlmanachCalendarView view = almanach.getAlmanachCalendarView(); request.setAttribute("calendarView", view); request.setAttribute("othersAlmanachs", almanach.getOthersAlmanachs()); request.setAttribute("accessibleInstances", almanach.getAccessibleInstances()); request.setAttribute("RSSUrl", almanach.getRSSUrl()); request.setAttribute("almanachURL", almanach.getAlmanachICSURL()); if (function.startsWith("portlet")) { destination = "/almanach/jsp/portletCalendar.jsp?flag=" + flag; } else { if (view.getViewType() == NEXT_EVENTS) { destination = "/almanach/jsp/nextEvents.jsp?flag=" + flag; } else { destination = "/almanach/jsp/calendar.jsp?flag=" + flag; } } } else if (function.startsWith("viewEventContent")) { // initialisation de l'objet event - String id = request.getParameter("Id"); // not null + String id = request.getParameter("Id"); + + if (!StringUtil.isDefined(id)) { + id = (String) request.getAttribute("Id"); + } else { + request.setAttribute("From", request.getParameter("Function")); + } // récupère l'Event et sa périodicité EventDetail event = almanach.getEventDetail(id); // Met en session l'événement courant almanach.setCurrentEvent(event); - if (event.getPeriodicity() != null) { - String dateIteration = request.getParameter("Date"); // not null (yyyy/MM/jj) + String dateIteration = request.getParameter("Date"); // not null (yyyy/MM/jj) + if (event.isPeriodic() && StringUtil.isDefined(dateIteration)) { java.util.Calendar calDateIteration = java.util.Calendar.getInstance(); calDateIteration.setTime(DateUtil.parse(dateIteration)); request.setAttribute("DateDebutIteration", calDateIteration.getTime()); calDateIteration.add(java.util.Calendar.DATE, event.getNbDaysDuration()); request.setAttribute("DateFinIteration", calDateIteration.getTime()); } else { request.setAttribute("DateDebutIteration", event.getStartDate()); request.setAttribute("DateFinIteration", event.getEndDate()); } request.setAttribute("CompleteEvent", event); - request.setAttribute("From", request.getParameter("Function")); + request.setAttribute("Contributor", almanach.getUserDetail(event.getCreatorId())); destination = "/almanach/jsp/viewEventContent.jsp?flag=" + flag; } else if (function.startsWith("createEvent")) { String day = request.getParameter("Day"); EventDetail event = new EventDetail(); String[] startDay = {"", ""}; if (day != null && day.length() > 0) { event.setStartDate(DateUtil.parseISO8601Date(day)); ResourcesWrapper resources = (ResourcesWrapper) request.getAttribute("resources"); startDay[0] = resources.getInputDate(event.getStartDate()); if (!day.endsWith("00:00")) { startDay[1] = day.substring(day.indexOf("T") + 1); event.setStartHour(startDay[1]); } } request.setAttribute("Day", startDay); request.setAttribute("Event", event); request.setAttribute("Language", almanach.getLanguage()); request.setAttribute("MaxDateFieldLength", DBUtil.getDateFieldLength()); request.setAttribute("MaxTextFieldLength", DBUtil.getTextFieldLength()); if (flag.equals("publisher") || flag.equals("admin")) { destination = "/almanach/jsp/createEvent.jsp"; } else { destination = GeneralPropertiesManager.getGeneralResourceLocator().getString( "sessionTimeout"); } } else if (function.equals("ReallyAddEvent")) { EventDetail event = new EventDetail(); String title = request.getParameter("Title"); String description = request.getParameter("Description"); String startDate = request.getParameter("StartDate"); String startHour = request.getParameter("StartHour"); String endDate = request.getParameter("EndDate"); String endHour = request.getParameter("EndHour"); String place = request.getParameter("Place"); String eventUrl = request.getParameter("EventUrl"); String priority = request.getParameter("Priority"); int unity = 0; String unit = request.getParameter("Unity"); if (isDefined(unit) && isInteger(unit)) { unity = Integer.parseInt(unit); } String frequency = request.getParameter("Frequency"); String weekDayWeek2 = request.getParameter("WeekDayWeek2"); String weekDayWeek3 = request.getParameter("WeekDayWeek3"); String weekDayWeek4 = request.getParameter("WeekDayWeek4"); String weekDayWeek5 = request.getParameter("WeekDayWeek5"); String weekDayWeek6 = request.getParameter("WeekDayWeek6"); String weekDayWeek7 = request.getParameter("WeekDayWeek7"); String weekDayWeek1 = request.getParameter("WeekDayWeek1"); String choiceMonth = request.getParameter("ChoiceMonth"); String monthNumWeek = request.getParameter("MonthNumWeek"); String monthDayWeek = request.getParameter("MonthDayWeek"); String periodicityUntilDate = request.getParameter("PeriodicityUntilDate"); event.setTitle(title); event.setNameDescription(description); event.setStartDate(DateUtil.stringToDate(startDate, almanach.getLanguage())); event.setStartHour(startHour); if (isDefined(endDate)) { event.setEndDate(DateUtil.stringToDate(endDate, almanach.getLanguage())); } else { event.setEndDate(null); } event.setEndHour(endHour); event.setPlace(place); event.setEventUrl(eventUrl); int priorityInt = 0; if (priority != null && priority.length() > 0) { priorityInt = 1; } event.setPriority(priorityInt); // Périodicité Periodicity periodicity = null; if (unity > Periodicity.UNIT_NONE) { if (periodicity == null) { periodicity = new Periodicity(); } periodicity.setUnity(unity); periodicity.setFrequency(Integer.parseInt(frequency)); switch (unity) { case Periodicity.UNIT_WEEK: String daysWeekBinary = ""; daysWeekBinary = addValueBinary(daysWeekBinary, weekDayWeek2); daysWeekBinary = addValueBinary(daysWeekBinary, weekDayWeek3); daysWeekBinary = addValueBinary(daysWeekBinary, weekDayWeek4); daysWeekBinary = addValueBinary(daysWeekBinary, weekDayWeek5); daysWeekBinary = addValueBinary(daysWeekBinary, weekDayWeek6); daysWeekBinary = addValueBinary(daysWeekBinary, weekDayWeek7); daysWeekBinary = addValueBinary(daysWeekBinary, weekDayWeek1); periodicity.setDaysWeekBinary(daysWeekBinary); break; case Periodicity.UNIT_MONTH: if ("MonthDay".equals(choiceMonth)) { periodicity.setNumWeek(new Integer(monthNumWeek).intValue()); periodicity.setDay(new Integer(monthDayWeek).intValue()); } break; } if (isDefined(periodicityUntilDate)) { periodicity.setUntilDatePeriod(DateUtil.stringToDate(periodicityUntilDate, endHour, almanach.getLanguage())); } } else {// update -> pas de périodicité periodicity = null; } event.setPeriodicity(periodicity); // Ajoute l'événement almanach.addEvent(event); destination = getDestination("almanach", almanach, request); } else if (function.startsWith("editEvent")) { String id = request.getParameter("Id"); // peut etre null en cas de // création String dateIteration = request.getParameter("Date"); // peut etre null // récupère l'Event et sa périodicité EventDetail event = almanach.getEventDetail(id); java.util.Calendar calDateIteration = java.util.Calendar.getInstance(); calDateIteration.setTime(DateUtil.parse(dateIteration)); request.setAttribute("DateDebutIteration", calDateIteration.getTime()); calDateIteration.add(java.util.Calendar.DATE, event.getNbDaysDuration()); request.setAttribute("DateFinIteration", calDateIteration.getTime()); request.setAttribute("CompleteEvent", event); // Met en session l'événement courant almanach.setCurrentEvent(event); if (flag.equals("publisher") || flag.equals("admin")) { destination = "/almanach/jsp/editEvent.jsp"; } else { destination = GeneralPropertiesManager.getGeneralResourceLocator().getString( "sessionTimeout"); } } else if (function.equals("ReallyUpdateEvent")) { String action = request.getParameter("Action");// ReallyUpdateOccurence // | ReallyUpdateSerial | // ReallyUpdate String id = request.getParameter("Id"); // not null String dateDebutIteration = request.getParameter("DateDebutIteration"); // format // client String dateFinIteration = request.getParameter("DateFinIteration"); // format // client EventDetail event = almanach.getEventDetail(id); String title = request.getParameter("Title"); String description = request.getParameter("Description"); String startDate = request.getParameter("StartDate"); String startHour = request.getParameter("StartHour"); String endDate = request.getParameter("EndDate"); String endHour = request.getParameter("EndHour"); String place = request.getParameter("Place"); String eventUrl = request.getParameter("EventUrl"); String priority = request.getParameter("Priority"); String unity = request.getParameter("Unity"); String frequency = request.getParameter("Frequency"); String weekDayWeek2 = request.getParameter("WeekDayWeek2"); String weekDayWeek3 = request.getParameter("WeekDayWeek3"); String weekDayWeek4 = request.getParameter("WeekDayWeek4"); String weekDayWeek5 = request.getParameter("WeekDayWeek5"); String weekDayWeek6 = request.getParameter("WeekDayWeek6"); String weekDayWeek7 = request.getParameter("WeekDayWeek7"); String weekDayWeek1 = request.getParameter("WeekDayWeek1"); String choiceMonth = request.getParameter("ChoiceMonth"); String monthNumWeek = request.getParameter("MonthNumWeek"); String monthDayWeek = request.getParameter("MonthDayWeek"); String periodicityStartDate = request.getParameter("PeriodicityStartDate"); String periodicityUntilDate = request.getParameter("PeriodicityUntilDate"); event.setTitle(title); event.setNameDescription(description); event.setStartDate(DateUtil.stringToDate(startDate, almanach.getLanguage())); event.setStartHour(startHour); if ((endDate != null) && (endDate.length() > 0)) { event.setEndDate(DateUtil.stringToDate(endDate, almanach.getLanguage())); } else { event.setEndDate(null); } int nbDaysDuration = event.getNbDaysDuration(); event.setEndHour(endHour); event.setPlace(place); event.setEventUrl(eventUrl); int priorityInt = 0; if (priority != null && priority.length() > 0) { priorityInt = 1; } event.setPriority(priorityInt); // Périodicité Periodicity periodicity = null; if (id != null && id.length() > 0) { // récupère la périodicité de l'événement periodicity = event.getPeriodicity(); } if (unity != null && !"0".equals(unity)) { if (periodicity == null) { periodicity = new Periodicity(); } periodicity.setUnity(new Integer(unity).intValue()); periodicity.setFrequency(new Integer(frequency).intValue()); if ("2".equals(unity)) {// Periodicity.UNIT_WEEK String daysWeekBinary = ""; daysWeekBinary = addValueBinary(daysWeekBinary, weekDayWeek2); daysWeekBinary = addValueBinary(daysWeekBinary, weekDayWeek3); daysWeekBinary = addValueBinary(daysWeekBinary, weekDayWeek4); daysWeekBinary = addValueBinary(daysWeekBinary, weekDayWeek5); daysWeekBinary = addValueBinary(daysWeekBinary, weekDayWeek6); daysWeekBinary = addValueBinary(daysWeekBinary, weekDayWeek7); daysWeekBinary = addValueBinary(daysWeekBinary, weekDayWeek1); periodicity.setDaysWeekBinary(daysWeekBinary); } else if ("3".equals(unity)) {// Periodicity.UNIT_MONTH if ("MonthDay".equals(choiceMonth)) { periodicity.setNumWeek(new Integer(monthNumWeek).intValue()); periodicity.setDay(new Integer(monthDayWeek).intValue()); } } if (periodicityUntilDate != null && periodicityUntilDate.length() > 0) { periodicity.setUntilDatePeriod(DateUtil.stringToDate( periodicityUntilDate, almanach.getLanguage())); } else { periodicity.setUntilDatePeriod(null); } } else {// update -> pas de périodicité periodicity = null; periodicityStartDate = startDate; // meme date } event.setPeriodicity(periodicity); if ("ReallyUpdateOccurence".equals(action)) { // Met à jour l'événement et toutes les occurences de la série almanach.updateEventOccurence(event, dateDebutIteration, dateFinIteration); } else if ("ReallyUpdateSerial".equals(action)) { java.util.Date startDateEvent = DateUtil.stringToDate( periodicityStartDate, almanach.getLanguage()); event.setStartDate(startDateEvent); java.util.Calendar calStartDate = java.util.Calendar.getInstance(); calStartDate.setTime(startDateEvent); calStartDate.add(java.util.Calendar.DATE, nbDaysDuration); event.setEndDate(calStartDate.getTime()); // Met à jour l'événement almanach.updateEvent(event); } else if ("ReallyUpdate".equals(action)) { java.util.Date startDateEvent = DateUtil.stringToDate( periodicityStartDate, almanach.getLanguage()); event.setStartDate(startDateEvent); java.util.Calendar calStartDate = java.util.Calendar.getInstance(); calStartDate.setTime(startDateEvent); calStartDate.add(java.util.Calendar.DATE, nbDaysDuration); event.setEndDate(calStartDate.getTime()); // Met à jour l'événement almanach.updateEvent(event); } destination = getDestination("almanach", almanach, request); } else if (function.startsWith("editAttFiles")) { String id = request.getParameter("Id"); String dateIteration = request.getParameter("Date"); // récupère l'Event EventDetail event = almanach.getEventDetail(id); request.setAttribute("DateDebutIteration", dateIteration); request.setAttribute("Event", event); request.setAttribute("PdcUsed", almanach.isPdcUsed()); String componentUrl = almanach.getComponentUrl() + "editAttFiles.jsp?Id=" + event.getPK(). getId() + "&Date=" + dateIteration; request.setAttribute("ComponentURL", URLEncoder.encode(componentUrl, "UTF-8")); destination = "/almanach/jsp/editAttFiles.jsp"; } else if (function.startsWith("pdcPositions")) { String id = request.getParameter("Id"); String dateIteration = request.getParameter("Date"); // récupère l'Event EventDetail event = almanach.getEventDetail(id); request.setAttribute("DateDebutIteration", DateUtil.parse(dateIteration)); request.setAttribute("Event", event); destination = "/almanach/jsp/pdcPositions.jsp"; } else if (function.startsWith("Pdf")) { // Recuperation des parametres String fileName = almanach.buildPdf(function); request.setAttribute("FileName", fileName); destination = "/almanach/jsp/pdf.jsp"; } else if (function.startsWith("searchResult")) { String id = request.getParameter("Id"); + request.setAttribute("Id", id); - // récupère l'Event et sa périodicité - EventDetail event = almanach.getEventDetail(id); - - java.util.Calendar calDateIteration = java.util.Calendar.getInstance(); - calDateIteration.setTime(event.getStartDate()); - request.setAttribute("DateDebutIteration", calDateIteration.getTime()); - calDateIteration.add(java.util.Calendar.DATE, event.getNbDaysDuration()); - request.setAttribute("DateFinIteration", calDateIteration.getTime()); - request.setAttribute("CompleteEvent", event); - - destination = "/almanach/jsp/viewEventContent.jsp?flag=" + flag; + destination = getDestination("viewEventContent", componentSC, request); } else if (function.startsWith("GoToFilesTab")) { // ?? destination = "/almanach/jsp/editAttFiles.jsp?Id=" + request.getParameter("Id"); } else if (function.equals("RemoveEvent")) { String dateDebutIteration = request.getParameter("DateDebutIteration"); // format // client String dateFinIteration = request.getParameter("DateFinIteration"); // format // client String action = request.getParameter("Action"); if ("ReallyDeleteOccurence".equals(action)) { // Supprime l'occurence almanach.removeOccurenceEvent(almanach.getCurrentEvent(), dateDebutIteration, dateFinIteration); } else if ("ReallyDelete".equals(action)) { // Supprime l'événement et toutes les occurences de la série almanach.removeEvent(almanach.getCurrentEvent().getPK().getId()); } destination = getDestination("Main", componentSC, request); } else if (function.equals("UpdateAgregation")) { String[] instanceIds = request.getParameterValues("chk_almanach"); SilverTrace.info("almanach", "AlmanachRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "instanceIds = " + instanceIds); almanach.updateAgregatedAlmanachs(instanceIds); destination = getDestination("almanach", almanach, request); } else if (function.equals("ToAlertUser")) { String id = request.getParameter("Id"); SilverTrace.info("almanach", "AlmanachRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "id = " + id); try { destination = almanach.initAlertUser(id); } catch (Exception e) { request.setAttribute("javax.servlet.jsp.jspException", e); } } else if ("ViewYearEvents".equals(function)) { AlmanachCalendarView calendar = almanach.getYearlyAlmanachCalendarView(); request.setAttribute("calendarView", calendar); request.setAttribute("Function", function); destination = "/almanach/jsp/viewEvents.jsp"; } else if ("ViewMonthEvents".equals(function)) { AlmanachCalendarView calendar = almanach.getMonthlyAlmanachCalendarView(); request.setAttribute("calendarView", calendar); request.setAttribute("Function", function); destination = "/almanach/jsp/viewEvents.jsp"; } else if ("ViewYearEventsPOPUP".equals(function)) { AlmanachCalendarView calendarView = almanach.getYearlyAlmanachCalendarView(); request.setAttribute("calendarView", calendarView); destination = "/almanach/jsp/viewEventsPopup.jsp"; } else if ("exportToICal".equals(function)) { try { String icsFile = almanach.exportToICal(); request.setAttribute("messageKey", "almanach.export.ical.success"); request.setAttribute("icsName", icsFile); request.setAttribute("icsURL", FileServerUtils.getUrlToTempDir(icsFile)); } catch (NoDataToExportException ex) { SilverTrace.info("almanach", getClass().getSimpleName() + ".getDestination()", "root.EX_NO_MESSAGE", ex.getMessage()); request.setAttribute("messageKey", "almanach.export.ical.empty"); } catch (ExportException ex) { SilverTrace.error("almanach", getClass().getSimpleName() + ".getDestination()", "root.EX_NO_MESSAGE", ex.getMessage()); request.setAttribute("messageKey", "almanach.export.ical.failure"); } destination = "/almanach/jsp/exportIcal.jsp"; } else { destination = "/almanach/jsp/" + function; } } catch (Exception e) { request.setAttribute("javax.servlet.jsp.jspException", e); return "/admin/jsp/errorpageMain.jsp"; } SilverTrace.info("almanach", "AlmanachRequestRouter.getDestination()", "root.MSG_GEN_EXIT_METHOD", "destination = " + destination); return destination; } public String getFlag(String[] profiles) { String flag = "user"; for (int i = 0; i < profiles.length; i++) { // if admin, return it, we won't find a better profile if (profiles[i].equals("admin")) { return profiles[i]; } else if (profiles[i].equals("publisher")) { flag = profiles[i]; } } return flag; } private String addValueBinary(final String binary, final String test) { String result = binary; if (test != null) { result += "1"; } else { result += "0"; } return result; } }
false
false
null
null
diff --git a/backend/src/com/mymed/tests/stress/SessionThread.java b/backend/src/com/mymed/tests/stress/SessionThread.java index ecef70f2d..c3ed56a0e 100644 --- a/backend/src/com/mymed/tests/stress/SessionThread.java +++ b/backend/src/com/mymed/tests/stress/SessionThread.java @@ -1,122 +1,129 @@ package com.mymed.tests.stress; import java.util.LinkedList; import com.mymed.model.data.session.MSessionBean; +/** + * This is the class that implements the threads that are executed and the + * simple sync logic for the Session test + * + * @author Milo Casagrande + * + */ public class SessionThread extends Thread implements NumberOfElements { private final LinkedList<MSessionBean> sessionList = new LinkedList<MSessionBean>(); private final SessionTest sessionTest; private final Thread addSession; private final Thread removeSession; private final boolean remove; /** * Create the new session thread */ public SessionThread() { this(true, NUMBER_OF_ELEMENTS); } /** * Create the new session thread, but do not perform the remove thread, only * add new session to the database * * @param remove * if to perform the remove thread or not * @param maxElements * the maximum number of elements to create */ public SessionThread(final boolean remove, final int maxElements) { super(); this.remove = remove; sessionTest = new SessionTest(maxElements); addSession = new Thread("addSession") { @Override public void run() { System.err.println("Starting the add session thread..."); synchronized (sessionList) { try { while (sessionList.isEmpty()) { final MSessionBean sessionBean = sessionTest.createSessionBean(); if (sessionBean == null) { break; } sessionList.add(sessionBean); try { sessionTest.createSession(sessionBean); } catch (final Exception ex) { ex.printStackTrace(); interrupt(); break; } // To execute only if we do not perform the remove // thread if (!remove) { sessionList.pop(); } sessionList.notifyAll(); if (remove) { sessionList.wait(); } } sessionList.notifyAll(); } catch (final Exception ex) { ex.printStackTrace(); } } } }; removeSession = new Thread() { @Override public void run() { System.err.println("Starting the remove session thread..."); synchronized (sessionList) { try { while (sessionList.isEmpty()) { sessionList.wait(); } while (!sessionList.isEmpty()) { final MSessionBean sessionBean = sessionList.pop(); try { sessionTest.removeSession(sessionBean); } catch (final Exception ex) { ex.printStackTrace(); interrupt(); break; } sessionList.notifyAll(); sessionList.wait(); } sessionList.notifyAll(); } catch (final Exception ex) { ex.printStackTrace(); } } } }; } @Override public void run() { addSession.start(); if (remove) { removeSession.start(); } } } diff --git a/backend/src/com/mymed/tests/stress/UserSessionStressTest.java b/backend/src/com/mymed/tests/stress/UserSessionStressTest.java index 9c994868b..0b491b402 100644 --- a/backend/src/com/mymed/tests/stress/UserSessionStressTest.java +++ b/backend/src/com/mymed/tests/stress/UserSessionStressTest.java @@ -1,43 +1,43 @@ package com.mymed.tests.stress; /** - * Perform the stress test on the session $ user tables. This test uses only a - * maximum of two threads: one to create and insert the elements in the - * database, the other to delete the entry from the database. + * Perform the stress test on the session & user tables. This test uses only a + * maximum of four threads: two to create and insert the elements in the + * database, the other to delete the entry from the database, for each tables. * <p> * This class accepts no parameters, or two parameters on the command line. If * only one parameter, or more than two parameters are passed, it will be * treated as no parameters at all are passed. * <p> * If two parameters are passed, the first one controls whatever to run also the * deletion thread, the second one controls the number of elements that will be * created: * <ol> * <li><code>args0</code>: must be a boolean value, <code>true</code> or * <code>false</code></li> * <li><code>args1</code>: must be a positive integer more than 0 * </ol> * * @author Milo Casagrande * */ public class UserSessionStressTest { public static void main(final String[] args) { final SessionThread sessionThread; final UserThread userThread; if (args.length != 0 && args[0] != null) { final boolean remove = Boolean.valueOf(args[0]); final int maxElements = Math.abs(Integer.parseInt(args[1])); sessionThread = new SessionThread(remove, maxElements); userThread = new UserThread(remove, maxElements); } else { sessionThread = new SessionThread(); userThread = new UserThread(); } userThread.start(); sessionThread.start(); } }
false
false
null
null
diff --git a/persistence-jpa/src/main/java/org/cognitor/server/hibernate/type/StringLongType.java b/persistence-jpa/src/main/java/org/cognitor/server/hibernate/type/StringLongType.java index 2ecd809..e1256c3 100644 --- a/persistence-jpa/src/main/java/org/cognitor/server/hibernate/type/StringLongType.java +++ b/persistence-jpa/src/main/java/org/cognitor/server/hibernate/type/StringLongType.java @@ -1,117 +1,117 @@ package org.cognitor.server.hibernate.type; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.usertype.UserType; import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; /** * This class is used to so that Hibernate can generate a numerical sequence * in the database but the value is stored in a String. * * This is required for Id values that are Strings because they might be used - * with other peristence solutions which do not require an id to be numerical. + * with other persistence solutions which do not require an id to be numerical. * * @author Patrick Kranz */ public class StringLongType implements UserType { /** * {@inheritDoc} */ @Override public int[] sqlTypes() { return new int[] {Types.BIGINT}; } /** * {@inheritDoc} */ @Override public Class returnedClass() { return String.class; } /** * {@inheritDoc} */ @Override public boolean equals(Object x, Object y) throws HibernateException { return !((x == null ^ y == null) || x == null) && x.equals(y); } /** * {@inheritDoc} */ @Override public int hashCode(Object x) throws HibernateException { if (x == null) throw new HibernateException("Can not calculate hash code for null value"); return x.hashCode(); } /** * {@inheritDoc} */ @Override public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException { long persistentValue = rs.getLong(names[0]); return Long.toString(persistentValue); } /** * {@inheritDoc} */ @Override public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException { try { st.setLong(index, Long.parseLong((String) value)); } catch (NumberFormatException exception) { throw new HibernateException("Unable to parse value to long: " + value, exception); } } /** * {@inheritDoc} */ @Override public Object deepCopy(Object value) throws HibernateException { return value; } /** * {@inheritDoc} */ @Override public boolean isMutable() { return false; } /** * {@inheritDoc} */ @Override public Serializable disassemble(Object value) throws HibernateException { return (Serializable) deepCopy(value); } /** * {@inheritDoc} */ @Override public Object assemble(Serializable cached, Object owner) throws HibernateException { return deepCopy(cached); } /** * {@inheritDoc} */ @Override public Object replace(Object original, Object target, Object owner) throws HibernateException { return original; } }
true
false
null
null
diff --git a/src/org/rascalmpl/library/vis/figure/combine/Overlap.java b/src/org/rascalmpl/library/vis/figure/combine/Overlap.java index 344305ec90..8f856ebba7 100644 --- a/src/org/rascalmpl/library/vis/figure/combine/Overlap.java +++ b/src/org/rascalmpl/library/vis/figure/combine/Overlap.java @@ -1,104 +1,104 @@ package org.rascalmpl.library.vis.figure.combine; import static org.rascalmpl.library.vis.properties.TwoDProperties.ALIGN; import static org.rascalmpl.library.vis.properties.TwoDProperties.GROW; import static org.rascalmpl.library.vis.properties.TwoDProperties.SHRINK; import static org.rascalmpl.library.vis.util.vector.Dimension.HOR_VER; import java.util.List; import java.util.Vector; import org.rascalmpl.library.vis.figure.Figure; import org.rascalmpl.library.vis.figure.interaction.MouseOver; import org.rascalmpl.library.vis.properties.PropertyManager; import org.rascalmpl.library.vis.swt.IFigureConstructionEnv; import org.rascalmpl.library.vis.util.vector.Coordinate; import org.rascalmpl.library.vis.util.vector.Dimension; import org.rascalmpl.library.vis.util.vector.Rectangle; public class Overlap extends LayoutProxy{ public Figure over; public Overlap(Figure under, Figure over, PropertyManager properties){ super(under,properties); children = new Figure[2]; children[0] = under; children[1] = over; this.over = over; } @Override public void initElem(IFigureConstructionEnv env, MouseOver mparent, boolean swtSeen, boolean visible){ super.initElem(env, mparent, swtSeen, visible); env.registerOverlap(this); } public void setOverlap(Figure fig){ children[1] = fig; over = fig; } @Override public void resizeElement(Rectangle view) { super.resizeElement(view); for(Dimension d : HOR_VER){ if(over.prop.is2DPropertySet(d, SHRINK)){ double sizeLeft = Math.max(0,location.get(d) - view.getLocation().get(d)); double sizeRight = - Math.max(0,view.getSize().get(d) - ((location.get(d) - view.getLocation().get(d)) + size.get(d)));; + Math.max(0,view.getSize().get(d) - ((location.get(d) - view.getLocation().get(d)) + size.get(d))); double align = over.prop.get2DReal(d, ALIGN); double sizeMiddle = size.get(d) * (0.5 - Math.abs(align - 0.5 )); if(align > 0.5){ sizeLeft*= 1.0 - (align - 0.5)*2.0; } if(align < 0.5){ sizeRight*= 1.0 - (0.5 - align)*2.0; } over.size.set(d,over.prop.get2DReal(d, SHRINK) * (sizeLeft + sizeMiddle + sizeRight)); } else { over.size.set(d,innerFig.size.get(d) * over.prop.get2DReal(d, GROW)); } if(over.size.get(d) > view.getSize().get(d)){ over.size.set(d,view.getSize().get(d)); } if(over.minSize.get(d) > over.size.get(d)){ over.size.set(d,over.minSize.get(d)); } over.location.set(d, (over.prop.get2DReal(d, ALIGN) * (innerFig.size.get(d) - over.size.get(d))) + (over.prop.get2DReal(d,ALIGN) -0.5)*2.0 * over.size.get(d)); if(over.location.get(d) + location.get(d) < view.getLocation().get(d)){ //over.location.set(d,view.getLocation().get(d)); } if(location.get(d) + over.location.get(d) + over.size.get(d) > view.getRightDown().get(d)){ //over.location.set(d,view.getRightDown().get(d) - over.size.get(d)); } } } @Override public void destroyElement(IFigureConstructionEnv env) { env.unregisterOverlap(this); } public Vector<Figure> getVisibleChildren(Rectangle r) { Vector<Figure> visChildren = new Vector<Figure>(); visChildren.add(innerFig); // overlap is drawed from elsewhere return visChildren; } public void getFiguresUnderMouse(Coordinate c,List<Figure> result){ if(!mouseInside(c)){ return; } innerFig.getFiguresUnderMouse(c, result); if(handlesInput()){ result.add(this); } } } diff --git a/src/org/rascalmpl/semantics/dynamic/PreModule.java b/src/org/rascalmpl/semantics/dynamic/PreModule.java index 8f494a5dc3..9d8abe11a3 100644 --- a/src/org/rascalmpl/semantics/dynamic/PreModule.java +++ b/src/org/rascalmpl/semantics/dynamic/PreModule.java @@ -1,76 +1,74 @@ /******************************************************************************* * Copyright (c) 2009-2011 CWI * 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: * * Jurgen J. Vinju - [email protected] - CWI * * Tijs van der Storm - [email protected] * * Mark Hills - [email protected] (CWI) * * Arnold Lankamp - [email protected] *******************************************************************************/ package org.rascalmpl.semantics.dynamic; -import java.util.List; - import org.eclipse.imp.pdb.facts.IConstructor; import org.rascalmpl.ast.Header; import org.rascalmpl.ast.Rest; import org.rascalmpl.interpreter.Evaluator; import org.rascalmpl.interpreter.env.Environment; import org.rascalmpl.interpreter.env.GlobalEnvironment; import org.rascalmpl.interpreter.env.ModuleEnvironment; import org.rascalmpl.interpreter.utils.Names; public abstract class PreModule extends org.rascalmpl.ast.PreModule { static public class Default extends org.rascalmpl.ast.PreModule.Default { public Default(IConstructor node, Header header, Rest rest) { super(node, header, rest); // TODO Auto-generated constructor stub } @Override public String declareSyntax(Evaluator eval, boolean withImports) { String name = eval.getModuleName(this); GlobalEnvironment heap = eval.__getHeap(); ModuleEnvironment env = heap.getModule(name); if (env == null) { env = new ModuleEnvironment(name, heap); heap.addModule(env); } if (!env.isSyntaxDefined()) { env.setBootstrap(eval.needBootstrapParser(this)); env.setCachedParser(eval.getCachedParser(this)); Environment oldEnv = eval.getCurrentEnvt(); eval.setCurrentEnvt(env); env.setSyntaxDefined(true); try { this.getHeader().declareSyntax(eval, withImports); } catch (RuntimeException e) { env.setSyntaxDefined(false); throw e; } finally { eval.setCurrentEnvt(oldEnv); } } return Names.fullName(getHeader().getName()); } } public PreModule(IConstructor __param1) { super(__param1); } } diff --git a/src/org/rascalmpl/tasks/ITransaction.java b/src/org/rascalmpl/tasks/ITransaction.java index deca977691..f044d91470 100644 --- a/src/org/rascalmpl/tasks/ITransaction.java +++ b/src/org/rascalmpl/tasks/ITransaction.java @@ -1,63 +1,60 @@ /******************************************************************************* * Copyright (c) 2009-2011 CWI * 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: * * Anya Helene Bagge - [email protected] (Univ. Bergen) *******************************************************************************/ package org.rascalmpl.tasks; import java.util.Collection; import org.eclipse.imp.pdb.facts.IValue; -import org.eclipse.imp.pdb.facts.type.Type; import org.rascalmpl.interpreter.IRascalMonitor; -import org.rascalmpl.tasks.IFact; - public interface ITransaction<K,N,V> { IFact<V> setFact(K key, N name, V value); IFact<V> setFact(K key, N name, V value, Collection<IFact<V>> deps); IFact<V> setFact(K key, N name, V value, Collection<IFact<V>> deps, IFactFactory factory); //V getFact(K key, N name); V getFact(IRascalMonitor monitor, K key, N name); /** * This method does *not* trigger fact production * @param key * @param name * @return The fact's value, if it exists */ V queryFact(K key, N name); /** * This method does *not* trigger fact production * @param key * @param name * @return The fact itself, if it exists */ IFact<V> findFact(K key, N name); void removeFact(K key, N name); void abandon(); void commit(); void commit(Collection<IFact<V>> deps); void registerListener(IDependencyListener listener, K key); void unregisterListener(IDependencyListener listener, K key); IFact<IValue> setFact(K key, V name, IFact<V> fact); }
false
false
null
null
diff --git a/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java b/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java index 8a20205..eb2f29c 100644 --- a/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java +++ b/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java @@ -1,186 +1,187 @@ package uk.ac.gla.dcs.tp3.w.algorithm; import java.util.LinkedList; import uk.ac.gla.dcs.tp3.w.league.League; import uk.ac.gla.dcs.tp3.w.league.Match; import uk.ac.gla.dcs.tp3.w.league.Team; public class Graph { private Vertex[] vertices; private int[][] matrix; private Vertex source; private Vertex sink; public Graph() { this(null, null); } public Graph(League l, Team t) { if (l == null || t == null) return; // Number of team nodes is one less than total number of teams. // The team nodes do not include the team being tested for elimination. int teamTotal = l.getTeams().length; // The r-combination of teamTotal for length 2 is the number of possible // combinations for matches between the list of Teams-{t}. int gameTotal = comb(teamTotal - 1, 2); // Total number of vertices is the number of teams-1 + number of match // pairs + source + sink. vertices = new Vertex[teamTotal + gameTotal + 1]; // Set first vertex to be source, and last vertex to be sink. // Create blank vertices for source and sink. source = new Vertex(0); sink = new Vertex(vertices.length - 1); vertices[0] = source; vertices[vertices.length - 1] = sink; // Create vertices for each team node, and make them adjacent to // the sink. Team[] teamsReal = l.getTeams(); Team[] teams = new Team[teamsReal.length - 1]; // Remove team T from the working list of Teams int pos = 0; for (Team to : teamsReal) { if (!to.equals(t)) { teams[pos] = to; pos++; } } // Create vertex for each team pair and make it adjacent from the // source. // Team[i] is in vertices[vertices.length -2 -i] pos = vertices.length - 2; for (int i = 0; i < teams.length; i++) { vertices[pos] = new TeamVertex(teams[i], pos); vertices[pos].getAdjList().add( new AdjListNode(teams[i].getUpcomingMatches().length, vertices[vertices.length - 1])); pos--; } // Create vertex for each team pair and make it adjacent from the // source. pos = 1; + // TODO limit this to something more sensible int infinity = Integer.MAX_VALUE; - for (int i = 0; i < teamTotal + 1; i++) { - for (int j = 1; j < teamTotal; j++) { + for (int i = 0; i < teams.length; i++) { + for (int j = 1; j < teams.length; j++) { vertices[pos] = new PairVertex(teams[i], teams[j], pos); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - i])); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - j])); vertices[0].getAdjList().add(new AdjListNode(0, vertices[pos])); pos++; } } // For each match not yet played and not involving t, increment the // capacity of the vertex going from home and away team node->sink and // float->pair node of home and away for (Match M : l.getFixtures()) { if (!M.isPlayed() && !(M.getAwayTeam().equals(t)) || M.getHomeTeam().equals(t)) { Team home = M.getHomeTeam(); Team away = M.getAwayTeam(); for (int i = vertices.length - 2; i < teams.length; i--) { TeamVertex TV = (TeamVertex) vertices[i]; if (TV.getTeam().equals(home)) { vertices[i].getAdjList().peek().incCapacity(); } else if (TV.getTeam().equals(away)) { vertices[i].getAdjList().peek().incCapacity(); } } for (AdjListNode A : vertices[0].getAdjList()) { PairVertex PV = (PairVertex) A.getVertex(); if ((PV.getTeamA().equals(home) && PV.getTeamB().equals( away)) || PV.getTeamA().equals(away) && PV.getTeamB().equals(home)) { A.incCapacity(); } } } } // TODO Create the adjacency matrix representation of the graph. } public Vertex[] getV() { return vertices; } public void setV(Vertex[] v) { this.vertices = v; } public int[][] getMatrix() { return matrix; } public int getSize() { return vertices.length; } public void setMatrix(int[][] matrix) { this.matrix = matrix; } public Vertex getSource() { return source; } public void setSource(Vertex source) { this.source = source; } public Vertex getSink() { return sink; } public void setSink(Vertex sink) { this.sink = sink; } private static int fact(int s) { // For s < 2, the factorial is 1. Otherwise, multiply s by fact(s-1) return (s < 2) ? 1 : s * fact(s - 1); } private static int comb(int n, int r) { // r-combination of size n is n!/r!(n-r)! return (fact(n) / (fact(r) * fact(n - r))); } /** * carry out a breadth first search/traversal of the graph */ public void bfs() { // TODO Read over this code, I (GR) just dropped this in here from // bfs-example. for (Vertex v : vertices) v.setVisited(false); LinkedList<Vertex> queue = new LinkedList<Vertex>(); for (Vertex v : vertices) { if (!v.getVisited()) { v.setVisited(true); v.setPredecessor(v.getIndex()); queue.add(v); while (!queue.isEmpty()) { Vertex u = queue.removeFirst(); LinkedList<AdjListNode> list = u.getAdjList(); for (AdjListNode node : list) { Vertex w = node.getVertex(); if (!w.getVisited()) { w.setVisited(true); w.setPredecessor(u.getIndex()); queue.add(w); } } } } } } }
false
true
public Graph(League l, Team t) { if (l == null || t == null) return; // Number of team nodes is one less than total number of teams. // The team nodes do not include the team being tested for elimination. int teamTotal = l.getTeams().length; // The r-combination of teamTotal for length 2 is the number of possible // combinations for matches between the list of Teams-{t}. int gameTotal = comb(teamTotal - 1, 2); // Total number of vertices is the number of teams-1 + number of match // pairs + source + sink. vertices = new Vertex[teamTotal + gameTotal + 1]; // Set first vertex to be source, and last vertex to be sink. // Create blank vertices for source and sink. source = new Vertex(0); sink = new Vertex(vertices.length - 1); vertices[0] = source; vertices[vertices.length - 1] = sink; // Create vertices for each team node, and make them adjacent to // the sink. Team[] teamsReal = l.getTeams(); Team[] teams = new Team[teamsReal.length - 1]; // Remove team T from the working list of Teams int pos = 0; for (Team to : teamsReal) { if (!to.equals(t)) { teams[pos] = to; pos++; } } // Create vertex for each team pair and make it adjacent from the // source. // Team[i] is in vertices[vertices.length -2 -i] pos = vertices.length - 2; for (int i = 0; i < teams.length; i++) { vertices[pos] = new TeamVertex(teams[i], pos); vertices[pos].getAdjList().add( new AdjListNode(teams[i].getUpcomingMatches().length, vertices[vertices.length - 1])); pos--; } // Create vertex for each team pair and make it adjacent from the // source. pos = 1; int infinity = Integer.MAX_VALUE; for (int i = 0; i < teamTotal + 1; i++) { for (int j = 1; j < teamTotal; j++) { vertices[pos] = new PairVertex(teams[i], teams[j], pos); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - i])); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - j])); vertices[0].getAdjList().add(new AdjListNode(0, vertices[pos])); pos++; } } // For each match not yet played and not involving t, increment the // capacity of the vertex going from home and away team node->sink and // float->pair node of home and away for (Match M : l.getFixtures()) { if (!M.isPlayed() && !(M.getAwayTeam().equals(t)) || M.getHomeTeam().equals(t)) { Team home = M.getHomeTeam(); Team away = M.getAwayTeam(); for (int i = vertices.length - 2; i < teams.length; i--) { TeamVertex TV = (TeamVertex) vertices[i]; if (TV.getTeam().equals(home)) { vertices[i].getAdjList().peek().incCapacity(); } else if (TV.getTeam().equals(away)) { vertices[i].getAdjList().peek().incCapacity(); } } for (AdjListNode A : vertices[0].getAdjList()) { PairVertex PV = (PairVertex) A.getVertex(); if ((PV.getTeamA().equals(home) && PV.getTeamB().equals( away)) || PV.getTeamA().equals(away) && PV.getTeamB().equals(home)) { A.incCapacity(); } } } } // TODO Create the adjacency matrix representation of the graph. }
public Graph(League l, Team t) { if (l == null || t == null) return; // Number of team nodes is one less than total number of teams. // The team nodes do not include the team being tested for elimination. int teamTotal = l.getTeams().length; // The r-combination of teamTotal for length 2 is the number of possible // combinations for matches between the list of Teams-{t}. int gameTotal = comb(teamTotal - 1, 2); // Total number of vertices is the number of teams-1 + number of match // pairs + source + sink. vertices = new Vertex[teamTotal + gameTotal + 1]; // Set first vertex to be source, and last vertex to be sink. // Create blank vertices for source and sink. source = new Vertex(0); sink = new Vertex(vertices.length - 1); vertices[0] = source; vertices[vertices.length - 1] = sink; // Create vertices for each team node, and make them adjacent to // the sink. Team[] teamsReal = l.getTeams(); Team[] teams = new Team[teamsReal.length - 1]; // Remove team T from the working list of Teams int pos = 0; for (Team to : teamsReal) { if (!to.equals(t)) { teams[pos] = to; pos++; } } // Create vertex for each team pair and make it adjacent from the // source. // Team[i] is in vertices[vertices.length -2 -i] pos = vertices.length - 2; for (int i = 0; i < teams.length; i++) { vertices[pos] = new TeamVertex(teams[i], pos); vertices[pos].getAdjList().add( new AdjListNode(teams[i].getUpcomingMatches().length, vertices[vertices.length - 1])); pos--; } // Create vertex for each team pair and make it adjacent from the // source. pos = 1; // TODO limit this to something more sensible int infinity = Integer.MAX_VALUE; for (int i = 0; i < teams.length; i++) { for (int j = 1; j < teams.length; j++) { vertices[pos] = new PairVertex(teams[i], teams[j], pos); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - i])); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - j])); vertices[0].getAdjList().add(new AdjListNode(0, vertices[pos])); pos++; } } // For each match not yet played and not involving t, increment the // capacity of the vertex going from home and away team node->sink and // float->pair node of home and away for (Match M : l.getFixtures()) { if (!M.isPlayed() && !(M.getAwayTeam().equals(t)) || M.getHomeTeam().equals(t)) { Team home = M.getHomeTeam(); Team away = M.getAwayTeam(); for (int i = vertices.length - 2; i < teams.length; i--) { TeamVertex TV = (TeamVertex) vertices[i]; if (TV.getTeam().equals(home)) { vertices[i].getAdjList().peek().incCapacity(); } else if (TV.getTeam().equals(away)) { vertices[i].getAdjList().peek().incCapacity(); } } for (AdjListNode A : vertices[0].getAdjList()) { PairVertex PV = (PairVertex) A.getVertex(); if ((PV.getTeamA().equals(home) && PV.getTeamB().equals( away)) || PV.getTeamA().equals(away) && PV.getTeamB().equals(home)) { A.incCapacity(); } } } } // TODO Create the adjacency matrix representation of the graph. }
diff --git a/src/org/protege/editor/owl/client/panel/ServerConnectionDialog.java b/src/org/protege/editor/owl/client/panel/ServerConnectionDialog.java index 8c8ce11..28104b8 100644 --- a/src/org/protege/editor/owl/client/panel/ServerConnectionDialog.java +++ b/src/org/protege/editor/owl/client/panel/ServerConnectionDialog.java @@ -1,214 +1,219 @@ package org.protege.editor.owl.client.panel; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.net.URI; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import org.protege.editor.core.ProtegeApplication; import org.protege.editor.owl.OWLEditorKit; import org.protege.editor.owl.client.connect.ServerConnectionManager; import org.protege.editor.owl.ui.UIHelper; import org.protege.owl.server.api.ChangeMetaData; import org.protege.owl.server.api.Client; import org.protege.owl.server.api.RemoteOntologyDocument; import org.protege.owl.server.api.RemoteServerDirectory; import org.protege.owl.server.api.RemoteServerDocument; import org.protege.owl.server.api.VersionedOntologyDocument; import org.protege.owl.server.api.exception.OWLServerException; import org.protege.owl.server.api.exception.UserDeclinedAuthenticationException; import org.protege.owl.server.connect.rmi.RMIClient; import org.protege.owl.server.util.ClientUtilities; import org.semanticweb.owlapi.apibinding.OWLManager; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyManager; // ToDo - this only barely works - add error checking... public class ServerConnectionDialog extends JDialog { private static final long serialVersionUID = 720048610707964509L; private OWLEditorKit editorKit; private Client client; private RemoteServerDirectory currentDirectory; private RemoteOntologyDocument remoteOntology; private ServerTableModel tableModel; private JTextField urlField; private JButton uploadButton; private JButton newDirectoryButton; public ServerConnectionDialog(Frame owner, OWLEditorKit editorKit) { - super(owner, "Server Connection Dialog"); + super(owner, "Connect to Server"); this.editorKit = editorKit; } public void initialise() { JPanel panel = new JPanel(new BorderLayout()); panel.add(getNorth(), BorderLayout.NORTH); panel.add(getCenter(),BorderLayout.CENTER); panel.add(getSouth(), BorderLayout.SOUTH); setContentPane(panel); + setPreferredSize(new Dimension(800, 500)); pack(); validate(); } public Client getClient() { return client; } public RemoteOntologyDocument getRemoteOntology() { return remoteOntology; } private JPanel getNorth() { JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER)); urlField = new JTextField(RMIClient.SCHEME + "://localhost:" + "5100/"); // Registry.REGISTRY_PORT + "/"); panel.add(urlField); urlField.addActionListener(new ConnectActionListener()); return panel; } private JScrollPane getCenter() { tableModel = new ServerTableModel(); JTable table = new JTable(tableModel); table.addMouseListener(new ClientTableMouseAdapter(table)); JScrollPane pane = new JScrollPane(table); pane.setSize(new Dimension(800, 600)); return pane; } private JPanel getSouth() { JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER)); JButton connect = new JButton("Connect"); connect.addActionListener(new ConnectActionListener()); panel.add(connect); uploadButton = new JButton("Upload"); uploadButton.addActionListener(new UploadActionListener()); uploadButton.setEnabled(false); panel.add(uploadButton); newDirectoryButton = new JButton("New Server Directory"); newDirectoryButton.addActionListener(new NewDirectoryListener()); newDirectoryButton.setEnabled(false); panel.add(newDirectoryButton); return panel; } public void setDirectory(RemoteServerDirectory dir) throws OWLServerException { urlField.setText(dir.getServerLocation().toString()); tableModel.loadServerData(client, dir); currentDirectory = dir; } private class ClientTableMouseAdapter extends MouseAdapter { private JTable table; public ClientTableMouseAdapter(JTable table) { this.table = table; } @Override public void mouseClicked(MouseEvent e) { try { if (e.getClickCount() == 2) { int row = table.getSelectedRow(); RemoteServerDocument doc = tableModel.getValueAt(row); if (doc instanceof RemoteOntologyDocument) { RemoteOntologyDocument remoteOntology = (RemoteOntologyDocument) doc; ServerConnectionManager connectionManager = ServerConnectionManager.get(editorKit); VersionedOntologyDocument vont = ClientUtilities.loadOntology(client, editorKit.getOWLModelManager().getOWLOntologyManager(), remoteOntology); editorKit.getOWLModelManager().setActiveOntology(vont.getOntology()); connectionManager.addVersionedOntology(vont); ServerConnectionDialog.this.setVisible(false); } else if (doc instanceof RemoteServerDirectory) { setDirectory((RemoteServerDirectory) doc); } } } catch (Exception ex) { ProtegeApplication.getErrorLog().logError(ex); } } } /* * ToDo -- This is really messed up but I wanted to see it work... */ private class ConnectActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { try { IRI serverLocation = IRI.create(urlField.getText()); ServerConnectionManager connectionManager = ServerConnectionManager.get(editorKit); client = connectionManager.createClient(serverLocation); if (client != null) { uploadButton.setEnabled(true); newDirectoryButton.setEnabled(true); RemoteServerDocument dir = client.getServerDocument(serverLocation); if (dir instanceof RemoteServerDirectory) { setDirectory((RemoteServerDirectory) dir); } JOptionPane.showMessageDialog(getOwner(), "Connected!"); } } catch (UserDeclinedAuthenticationException udae) { ; // ignore this because the user knows that he stopped the connection attempt. } catch (OWLServerException ose) { ProtegeApplication.getErrorLog().logError(ose); } } } private class UploadActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if (client != null) { try { File input = new UIHelper(editorKit).chooseOWLFile("Choose file to upload"); - OWLOntologyManager manager = OWLManager.createOWLOntologyManager(); - OWLOntology ontology = manager.loadOntologyFromOntologyDocument(input); - String name = (String) JOptionPane.showInputDialog(getOwner(), "Name of upload: "); - String urlText = urlField.getText(); - String urlTextWithEndingSlash = urlText.endsWith("/") ? urlText : (urlText + "/"); - ClientUtilities.createServerOntology(client, IRI.create(urlTextWithEndingSlash + name + ".history"), new ChangeMetaData("Uploaded from file " + input), ontology); - tableModel.loadServerData(client, currentDirectory); - JOptionPane.showMessageDialog(getOwner(), "Uploaded!"); + if (input != null) { + OWLOntologyManager manager = OWLManager.createOWLOntologyManager(); + OWLOntology ontology = manager.loadOntologyFromOntologyDocument(input); + String name = (String) JOptionPane.showInputDialog(getOwner(), "Name of upload: "); + String urlText = urlField.getText(); + String urlTextWithEndingSlash = urlText.endsWith("/") ? urlText : (urlText + "/"); + ClientUtilities.createServerOntology(client, IRI.create(urlTextWithEndingSlash + name + ".history"), new ChangeMetaData("Uploaded from file " + input), ontology); + tableModel.loadServerData(client, currentDirectory); + JOptionPane.showMessageDialog(getOwner(), "Uploaded!"); + } } catch (Exception ex) { ProtegeApplication.getErrorLog().logError(ex); } } } } private class NewDirectoryListener implements ActionListener { @Override public void actionPerformed(ActionEvent event) { try { String dirName = (String) JOptionPane.showInputDialog(getOwner(), "Enter the directory name: ", "Create Server Directory", JOptionPane.PLAIN_MESSAGE); - URI dir = URI.create(urlField.getText()).resolve(dirName); - client.createRemoteDirectory(IRI.create(dir)); - setDirectory(currentDirectory); + if ((dirName != null) && (dirName.length() > 0)) { + URI dir = URI.create(urlField.getText()).resolve(dirName); + client.createRemoteDirectory(IRI.create(dir)); + setDirectory(currentDirectory); + } } catch (OWLServerException ioe) { throw new RuntimeException(ioe); } } } }
false
false
null
null
diff --git a/src/org/romaframework/core/schema/reflection/SchemaFieldReflection.java b/src/org/romaframework/core/schema/reflection/SchemaFieldReflection.java index 59e6e5f..69e06a0 100644 --- a/src/org/romaframework/core/schema/reflection/SchemaFieldReflection.java +++ b/src/org/romaframework/core/schema/reflection/SchemaFieldReflection.java @@ -1,184 +1,186 @@ package org.romaframework.core.schema.reflection; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.util.ArrayList; import java.util.List; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.romaframework.core.Roma; import org.romaframework.core.aspect.Aspect; import org.romaframework.core.binding.BindingException; import org.romaframework.core.flow.Controller; import org.romaframework.core.flow.SchemaFieldListener; import org.romaframework.core.schema.FeatureLoader; import org.romaframework.core.schema.SchemaClass; import org.romaframework.core.schema.SchemaClassDefinition; import org.romaframework.core.schema.SchemaField; +import org.romaframework.core.schema.SchemaParameter; import org.romaframework.core.schema.config.SchemaConfiguration; import org.romaframework.core.schema.xmlannotations.XmlEventAnnotation; import org.romaframework.core.schema.xmlannotations.XmlFieldAnnotation; public class SchemaFieldReflection extends SchemaField { private static final long serialVersionUID = 8401682154724053320L; protected Field field; protected Class<?> languageType; protected Method getterMethod; protected Method setterMethod; private static Log log = LogFactory.getLog(SchemaFieldReflection.class); public SchemaFieldReflection(SchemaClassDefinition entity, String iName) { super(entity, iName); } @Override public boolean isArray() { return getLanguageType().isArray(); } public void configure() { SchemaConfiguration classDescriptor = entity.getSchemaClass().getDescriptor(); XmlFieldAnnotation parentDescriptor = null; if (classDescriptor != null && classDescriptor.getType() != null && classDescriptor.getType().getFields() != null) { // SEARCH FORM DEFINITION IN DESCRIPTOR parentDescriptor = classDescriptor.getType().getField(name); } FeatureLoader.loadFieldFeatures(this, parentDescriptor); // BROWSE ALL ASPECTS for (Aspect aspect : Roma.aspects()) { aspect.configField(this); } if (parentDescriptor != null && parentDescriptor.getEvents() != null) { Set<XmlEventAnnotation> events = parentDescriptor.getEvents(); for (XmlEventAnnotation xmlConfigEventType : events) { SchemaEventReflection eventInfo = (SchemaEventReflection) getEvent(xmlConfigEventType.getName()); if (eventInfo == null) { // EVENT NOT EXISTENT: CREATE IT AND INSERT IN THE COLLECTION - eventInfo = new SchemaEventReflection(this, xmlConfigEventType.getName(), null); + eventInfo = new SchemaEventReflection(this, xmlConfigEventType.getName(), new ArrayList<SchemaParameter>()); setEvent(xmlConfigEventType.getName(), eventInfo); } eventInfo.configure(); } } } @Override public Object getValue(Object iObject) throws BindingException { if (iObject == null) return null; List<SchemaFieldListener> listeners = Controller.getInstance().getListeners(SchemaFieldListener.class); try { // CREATE THE CONTEXT BEFORE TO CALL THE ACTION Roma.context().create(); // CALL ALL LISTENERS BEFORE TO RETURN THE VALUE Object value = invokeCallbackBeforeFieldRead(listeners, iObject); if (value != SchemaFieldListener.IGNORED) return value; // TRY TO INVOKE GETTER IF ANY if (getterMethod != null) { try { value = getterMethod.invoke(iObject, (Object[]) null); } catch (IllegalArgumentException e) { // PROBABLY AN ISSUE OF CLASS VERSION throw new BindingException(iObject, name, "Error on using different classes together. Maybe it's an issue due to class reloading. Assure to use objects of the same class."); } catch (InvocationTargetException e) { Throwable nested = e.getCause(); if (nested == null) { nested = e.getTargetException(); } // BYPASS REFLECTION EXCEPTION: THROW REAL NESTED EXCEPTION throw new BindingException(iObject, name, nested); } } else { // READ FROM FIELD if (!field.isAccessible()) { field.setAccessible(true); } value = field.get(iObject); } // CALL ALL LISTENERS BEFORE TO RETURN THE VALUE value = invokeCallbackAfterFieldRead(listeners, iObject, value); return value; } catch (Exception e) { throw new BindingException(iObject, name, e); } finally { // ASSURE TO DESTROY THE CONTEXT Roma.context().destroy(); } } protected void setValueFinal(Object iObject, Object iValue) throws IllegalAccessException, InvocationTargetException { // TRY TO INVOKE SETTER IF ANY if (setterMethod != null) { setterMethod.invoke(iObject, new Object[] { iValue }); } else { // WRITE THE FIELD if (field == null) { log.debug("[SchemaHelper.setFieldValue] Cannot set the value '" + iValue + "' for field '" + name + "' on object " + iObject + " since it has neither setter neir field declared"); return; } if (!field.isAccessible()) { field.setAccessible(true); } field.set(iObject, iValue); } } @Override public String toString() { return name + " (field:" + field + ")"; } public Field getField() { return field; } public Method getGetterMethod() { return getterMethod; } public Method getSetterMethod() { return setterMethod; } public Class<?> getLanguageType() { return languageType; } public void setLanguageType(Class<?> clazz) { languageType = clazz; } @Override protected SchemaClass getSchemaClassFromLanguageType() { return Roma.schema().getSchemaClass(getLanguageType()); } }
false
false
null
null
diff --git a/omod/src/main/java/org/openmrs/module/appointment/web/DWRAppointmentService.java b/omod/src/main/java/org/openmrs/module/appointment/web/DWRAppointmentService.java index e8d2864..4fa0843 100644 --- a/omod/src/main/java/org/openmrs/module/appointment/web/DWRAppointmentService.java +++ b/omod/src/main/java/org/openmrs/module/appointment/web/DWRAppointmentService.java @@ -1,171 +1,172 @@ package org.openmrs.module.appointment.web; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.servlet.http.HttpSession; import org.directwebremoting.WebContext; import org.directwebremoting.WebContextFactory; import org.openmrs.Location; import org.openmrs.Patient; import org.openmrs.PersonAttribute; import org.openmrs.api.PatientService; import org.openmrs.api.context.Context; import org.openmrs.module.appointment.Appointment; import org.openmrs.module.appointment.Appointment.AppointmentStatus; import org.openmrs.module.appointment.AppointmentBlock; import org.openmrs.module.appointment.AppointmentType; import org.openmrs.module.appointment.TimeSlot; import org.openmrs.module.appointment.api.AppointmentService; /** * DWR patient methods. The methods in here are used in the webapp to get data from the database via * javascript calls. * * @see PatientService */ public class DWRAppointmentService { public PatientData getPatientDescription(Integer patientId) { Patient patient = Context.getPatientService().getPatient(patientId); if (patient == null) return null; PatientData patientData = new PatientData(); patientData .setIdentifiers(Context.getService(AppointmentService.class).getPatientIdentifiersRepresentation(patient)); //Get Patient's phone Integer phonePropertyId = Integer.parseInt(Context.getAdministrationService().getGlobalProperty( "appointment.phoneNumberPersonAttributeTypeId")); PersonAttribute phoneAttribute = patient.getAttribute(phonePropertyId); if (phoneAttribute != null) patientData.setPhoneNumber(phoneAttribute.getValue()); //Checks if patient missed his/her last appointment. Appointment lastAppointment = Context.getService(AppointmentService.class).getLastAppointment(patient); if (lastAppointment != null && lastAppointment.getStatus() == AppointmentStatus.MISSED) patientData.setDateMissedLastAppointment(Context.getDateFormat().format( lastAppointment.getTimeSlot().getStartDate())); return patientData; } public List<AppointmentBlockData> getAppointmentBlocks(String fromDate, String toDate, Integer locationId) throws ParseException { List<AppointmentBlock> appointmentBlockList = new ArrayList<AppointmentBlock>(); List<AppointmentBlockData> appointmentBlockDatalist = new ArrayList<AppointmentBlockData>(); Date fromAsDate = null; Date toAsDate = null; //location needs authentication if (Context.isAuthenticated()) { AppointmentService appointmentService = Context.getService(AppointmentService.class); Location location = null; if (locationId != null) { location = Context.getLocationService().getLocation(locationId); } //In case the user selected a date. if (!fromDate.isEmpty()) { fromAsDate = Context.getDateTimeFormat().parse(fromDate); } if (!toDate.isEmpty()) { toAsDate = Context.getDateTimeFormat().parse(toDate); } appointmentBlockList = appointmentService .getAppointmentBlocks(fromAsDate, toAsDate, buildLocationList(location)); for (AppointmentBlock appointmentBlock : appointmentBlockList) { //don't include voided appointment blocks if (!appointmentBlock.isVoided()) { - Set<String> typesDescription = new HashSet<String>(); + Set<String> typesNames = new HashSet<String>(); Set<AppointmentType> appointmentTypes = appointmentBlock.getTypes(); for (AppointmentType appointmentType : appointmentTypes) { - typesDescription.add(appointmentType.getDescription()); + typesNames.add(appointmentType.getName()); } - appointmentBlockDatalist.add(new AppointmentBlockData(appointmentBlock.getId(), appointmentBlock - .getLocation().getName(), appointmentBlock.getProvider().getName(), typesDescription, - appointmentBlock.getStartDate(), appointmentBlock.getEndDate(), this - .getTimeSlotLength(appointmentBlock.getId()))); + appointmentBlockDatalist + .add(new AppointmentBlockData(appointmentBlock.getId(), + appointmentBlock.getLocation().getName(), appointmentBlock.getProvider().getName(), + typesNames, appointmentBlock.getStartDate(), appointmentBlock.getEndDate(), this + .getTimeSlotLength(appointmentBlock.getId()))); } } } return appointmentBlockDatalist; } public Integer[] getNumberOfAppointmentsInAppointmentBlock(Integer appointmentBlockId) { Integer[] appointmentsCount = null; if (Context.isAuthenticated()) { AppointmentService as = Context.getService(AppointmentService.class); if (appointmentBlockId != null) { appointmentsCount = new Integer[3]; appointmentsCount[0] = 0; appointmentsCount[1] = 0; appointmentsCount[2] = 0; //Assumption - Exists such an appointment block in the data base with the given Id AppointmentBlock appointmentBlock = as.getAppointmentBlock(appointmentBlockId); //Getting the timeslots of the given appointment block List<TimeSlot> timeSlots = as.getTimeSlotsInAppointmentBlock(appointmentBlock); for (TimeSlot timeSlot : timeSlots) { List<Appointment> appointmentsInTimeSlot = as.getAppointmentsInTimeSlot(timeSlot); for (Appointment appointment : appointmentsInTimeSlot) { if (appointment.getStatus().toString().equalsIgnoreCase(AppointmentStatus.INCONSULTATION.toString()) || appointment.getStatus().toString().equalsIgnoreCase(AppointmentStatus.WAITING.toString())) { //Active appointments appointmentsCount[0]++; } else if (appointment.getStatus().toString().equalsIgnoreCase( AppointmentStatus.SCHEDULED.toString())) { appointmentsCount[1]++; //Scheduled appointments } else { appointmentsCount[2]++; //Missed/Cancelled/Completed appointments } } } } } return appointmentsCount; } public boolean validateDates(String fromDate, String toDate) throws ParseException { boolean error = false; WebContext webContext = WebContextFactory.get(); HttpSession httpSession = webContext.getHttpServletRequest().getSession(); //date validation if (!Context.getDateTimeFormat().parse(fromDate).before(Context.getDateTimeFormat().parse(toDate))) { error = true; } return error; } private String buildLocationList(Location location) { String ans = ""; if (location != null) { ans = location.getId() + ""; if (location.getChildLocations().size() == 0) return ans; else { for (Location locationChild : location.getChildLocations()) { ans += "," + buildLocationList(locationChild); } } } return ans; } private String getTimeSlotLength(Integer appointmentBlockId) { if (appointmentBlockId == null) return ""; else { if (Context.isAuthenticated()) { AppointmentService as = Context.getService(AppointmentService.class); AppointmentBlock appointmentBlock = as.getAppointmentBlock(appointmentBlockId); TimeSlot timeSlot = Context.getService(AppointmentService.class).getTimeSlotsInAppointmentBlock( appointmentBlock).get(0); return (timeSlot.getEndDate().getTime() - timeSlot.getStartDate().getTime()) / 60000 + ""; } } return ""; } }
false
true
public List<AppointmentBlockData> getAppointmentBlocks(String fromDate, String toDate, Integer locationId) throws ParseException { List<AppointmentBlock> appointmentBlockList = new ArrayList<AppointmentBlock>(); List<AppointmentBlockData> appointmentBlockDatalist = new ArrayList<AppointmentBlockData>(); Date fromAsDate = null; Date toAsDate = null; //location needs authentication if (Context.isAuthenticated()) { AppointmentService appointmentService = Context.getService(AppointmentService.class); Location location = null; if (locationId != null) { location = Context.getLocationService().getLocation(locationId); } //In case the user selected a date. if (!fromDate.isEmpty()) { fromAsDate = Context.getDateTimeFormat().parse(fromDate); } if (!toDate.isEmpty()) { toAsDate = Context.getDateTimeFormat().parse(toDate); } appointmentBlockList = appointmentService .getAppointmentBlocks(fromAsDate, toAsDate, buildLocationList(location)); for (AppointmentBlock appointmentBlock : appointmentBlockList) { //don't include voided appointment blocks if (!appointmentBlock.isVoided()) { Set<String> typesDescription = new HashSet<String>(); Set<AppointmentType> appointmentTypes = appointmentBlock.getTypes(); for (AppointmentType appointmentType : appointmentTypes) { typesDescription.add(appointmentType.getDescription()); } appointmentBlockDatalist.add(new AppointmentBlockData(appointmentBlock.getId(), appointmentBlock .getLocation().getName(), appointmentBlock.getProvider().getName(), typesDescription, appointmentBlock.getStartDate(), appointmentBlock.getEndDate(), this .getTimeSlotLength(appointmentBlock.getId()))); } } } return appointmentBlockDatalist; }
public List<AppointmentBlockData> getAppointmentBlocks(String fromDate, String toDate, Integer locationId) throws ParseException { List<AppointmentBlock> appointmentBlockList = new ArrayList<AppointmentBlock>(); List<AppointmentBlockData> appointmentBlockDatalist = new ArrayList<AppointmentBlockData>(); Date fromAsDate = null; Date toAsDate = null; //location needs authentication if (Context.isAuthenticated()) { AppointmentService appointmentService = Context.getService(AppointmentService.class); Location location = null; if (locationId != null) { location = Context.getLocationService().getLocation(locationId); } //In case the user selected a date. if (!fromDate.isEmpty()) { fromAsDate = Context.getDateTimeFormat().parse(fromDate); } if (!toDate.isEmpty()) { toAsDate = Context.getDateTimeFormat().parse(toDate); } appointmentBlockList = appointmentService .getAppointmentBlocks(fromAsDate, toAsDate, buildLocationList(location)); for (AppointmentBlock appointmentBlock : appointmentBlockList) { //don't include voided appointment blocks if (!appointmentBlock.isVoided()) { Set<String> typesNames = new HashSet<String>(); Set<AppointmentType> appointmentTypes = appointmentBlock.getTypes(); for (AppointmentType appointmentType : appointmentTypes) { typesNames.add(appointmentType.getName()); } appointmentBlockDatalist .add(new AppointmentBlockData(appointmentBlock.getId(), appointmentBlock.getLocation().getName(), appointmentBlock.getProvider().getName(), typesNames, appointmentBlock.getStartDate(), appointmentBlock.getEndDate(), this .getTimeSlotLength(appointmentBlock.getId()))); } } } return appointmentBlockDatalist; }
diff --git a/programs/slammer/gui/RecordManagerPanel.java b/programs/slammer/gui/RecordManagerPanel.java index a0af61ca..fe40fc46 100644 --- a/programs/slammer/gui/RecordManagerPanel.java +++ b/programs/slammer/gui/RecordManagerPanel.java @@ -1,790 +1,791 @@ /* This file is in the public domain. */ package slammer.gui; import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; import javax.swing.border.*; import java.io.*; import java.util.ArrayList; import org.jfree.data.xy.*; import org.jfree.chart.*; import org.jfree.chart.axis.*; import org.jfree.chart.renderer.xy.StandardXYItemRenderer; import org.jfree.chart.plot.XYPlot; import org.jfree.data.Range; import slammer.*; import slammer.analysis.*; class RecordManagerPanel extends JPanel implements ActionListener { SlammerTabbedPane parent; SlammerTable table; JComboBox eqList = new JComboBox(); JButton graph = new JButton("Graph"); JButton graph2 = new JButton("Graph"); JButton saveGraph = new JButton("Save results as text"); JFileChooser saveChooser = new JFileChooser(); JButton delete = new JButton("Delete selected record(s) from database"); ButtonGroup timeAxisGroup = new ButtonGroup(); JRadioButton timeAxisGs = new JRadioButton("g's", true); JRadioButton timeAxisCmss = new JRadioButton("cm/s/s"); ButtonGroup saveGroup = new ButtonGroup(); JRadioButton saveTab = new JRadioButton("Tab"); JRadioButton saveSpace = new JRadioButton("Space"); JRadioButton saveComma = new JRadioButton("Comma"); JButton save = new JButton("Save changes"); JTextField modFile = new JTextField(5); JTextField modEq = new JTextField(5); JTextField modRec = new JTextField(5); JTextField modDI = new JTextField(5); JTextField modLoc = new JTextField(5); JTextField modMag = new JTextField(5); JTextField modOwn = new JTextField(5); JTextField modEpi = new JTextField(5); JTextField modLat = new JTextField(5); JTextField modFoc = new JTextField(5); JTextField modLng = new JTextField(5); JTextField modRup = new JTextField(5); JTextField modVs = new JTextField(5); JComboBox modSite = new JComboBox(SlammerTable.SiteClassArray); JComboBox modMech = new JComboBox(SlammerTable.FocMechArray); ButtonGroup TypeGroup = new ButtonGroup(); JRadioButton typeTime = new JRadioButton("Time Series", true); JRadioButton typeFourier = new JRadioButton("Fourier Amplitude Spectrum"); JRadioButton typeSpectra = new JRadioButton("Response Spectra"); JComboBox spectraCB = new JComboBox(new String[] { "Absolute-Acceleration", "Relative-Velocity", "Relative-Displacement", "Psuedo Absolute-Acceleration", "Psuedo Relative-Velocity" }); String[] spectraCBStr = new String[] { "cm/s/s", "cm/s", "cm", "cm/s/s", "cm/s" }; JComboBox spectraDomain = new JComboBox(new String[] { "Frequency", "Period" }); String[] spectraDomainStr = new String[] { "Hz", "s" }; String[] spectraDirStr = new String[] { "Highest", "Shortest" }; JLabel spectraDomainLabel = new JLabel(); JTextField spectraDamp = new JTextField("0"); JTextField spectraHigh = new JTextField("100.00"); JButton add = new JButton("Add record(s)..."); JTabbedPane managerTP = new JTabbedPane(); public RecordManagerPanel(SlammerTabbedPane parent) throws Exception { this.parent = parent; table = new SlammerTable(false, false); ListSelectionModel recordSelect = table.getSelectionModel(); recordSelect.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent event) { try { recordSelect(event); } catch (Exception e) { Utils.catchException(e); } } }); TypeGroup.add(typeTime); TypeGroup.add(typeFourier); TypeGroup.add(typeSpectra); timeAxisGroup.add(timeAxisGs); timeAxisGroup.add(timeAxisCmss); saveGroup.add(saveTab); saveGroup.add(saveSpace); saveGroup.add(saveComma); Utils.addEQList(eqList, Boolean.TRUE); eqList.setActionCommand("eqListChange"); eqList.addActionListener(this); save.setActionCommand("save"); save.addActionListener(this); delete.setActionCommand("delete"); delete.addActionListener(this); graph.setActionCommand("graph"); graph.addActionListener(this); graph2.setActionCommand("graph"); graph2.addActionListener(this); saveGraph.setActionCommand("saveGraph"); saveGraph.addActionListener(this); managerTP.addTab("Modify Record", createModifyPanel()); managerTP.addTab("Graphing Options", createGraphPanel()); spectraDomain.setActionCommand("domain"); spectraDomain.addActionListener(this); updateDomainLabel(); setLayout(new BorderLayout()); add(BorderLayout.NORTH, createNorthPanel()); add(BorderLayout.CENTER, table); add(BorderLayout.SOUTH, managerTP); recordClear(); } private JPanel createNorthPanel() { JPanel panel = new JPanel(new BorderLayout()); ArrayList list = new ArrayList(); list.add(new JLabel("Display records from: ")); list.add(eqList); panel.add(BorderLayout.WEST, GUIUtils.makeRecursiveLayoutRight(list)); list = new ArrayList(); list.add(graph); list.add(delete); panel.add(BorderLayout.EAST, GUIUtils.makeRecursiveLayoutRight(list)); return panel; } private JPanel createModifyPanel() { JPanel panel = new JPanel(new BorderLayout()); JPanel north = new JPanel(new BorderLayout()); JLabel label = new JLabel("Modify record:"); label.setFont(GUIUtils.headerFont); JPanel file = new JPanel(new BorderLayout()); file.add(BorderLayout.WEST, new JLabel("File Location ")); file.add(BorderLayout.CENTER, modFile); north.add(BorderLayout.WEST, label); north.add(BorderLayout.EAST, save); north.add(BorderLayout.SOUTH, file); panel.add(BorderLayout.NORTH, north); JPanel south = new JPanel(new GridLayout(0, 4)); south.add(new JLabel("Earthquake name")); south.add(modEq); south.add(new JLabel(" Record name")); south.add(modRec); south.add(new JLabel("Digitization Interval (s)")); south.add(modDI); south.add(new JLabel(" Location [optional]")); south.add(modLoc); south.add(new JLabel("Moment Magnitude [optional]")); south.add(modMag); south.add(new JLabel(" Station owner [optional]")); south.add(modOwn); south.add(new JLabel("Epicentral distance (km) [optional]")); south.add(modEpi); south.add(new JLabel(" Latitude [optional]")); south.add(modLat); south.add(new JLabel("Focal distance (km) [optional]")); south.add(modFoc); south.add(new JLabel(" Longitude [optional]")); south.add(modLng); south.add(new JLabel("Rupture distance (km) [optional]")); south.add(modRup); south.add(new JLabel(" Vs30 (m/s) [optional]")); south.add(modVs); south.add(new JLabel("Focal Mechanism [optional]")); south.add(modMech); south.add(new JLabel(" Site Class [optional]")); south.add(modSite); panel.add(BorderLayout.SOUTH, south); return panel; } public JPanel createGraphPanel() { JPanel panel = new JPanel(); GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); JLabel label; Insets left = new Insets(0, 1, 0, 0); Insets none = new Insets(0, 0, 0, 0); panel.setLayout(gridbag); int x = 0; int y = 0; c.anchor = GridBagConstraints.WEST; c.fill = GridBagConstraints.BOTH; Border b = BorderFactory.createCompoundBorder( BorderFactory.createMatteBorder(0, 0, 1, 1, Color.BLACK), BorderFactory.createEmptyBorder(2, 1, 2, 1) ); Border bleft = BorderFactory.createMatteBorder(0, 1, 0, 0, Color.BLACK); - Border bdown = BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK); + Border bdown = BorderFactory.createCompoundBorder( + BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK), + BorderFactory.createEmptyBorder(0, 2, 0, 0) + ); JPanel graphPanel = new JPanel(new GridLayout(1, 0)); graphPanel.add(graph2); graphPanel.add(saveGraph); c.gridx = x++; c.gridy = y++; c.gridwidth = 3; gridbag.setConstraints(graphPanel, c); panel.add(graphPanel); c.gridwidth = 1; c.gridy = y++; typeTime.setBorder(b); typeTime.setBorderPainted(true); gridbag.setConstraints(typeTime, c); panel.add(typeTime); c.gridx = x++; - c.insets = left; label = new JLabel("Vertical Axis"); label.setBorder(bdown); gridbag.setConstraints(label, c); panel.add(label); c.gridx = x++; - c.insets = none; Box timeAxisPanel = new Box(BoxLayout.X_AXIS); timeAxisPanel.add(timeAxisGs); timeAxisPanel.add(timeAxisCmss); timeAxisPanel.setBorder(bdown); gridbag.setConstraints(timeAxisPanel, c); panel.add(timeAxisPanel); x -= 3; c.gridx = x++; c.gridy = y++; typeFourier.setBorder(b); typeFourier.setBorderPainted(true); gridbag.setConstraints(typeFourier, c); panel.add(typeFourier); c.gridy = y--; c.gridheight = 4; typeSpectra.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, Color.BLACK)); typeSpectra.setBorderPainted(true); gridbag.setConstraints(typeSpectra, c); panel.add(typeSpectra); c.gridx = x++; c.gridy = y++; c.gridheight = 1; c.gridwidth = 2; label = new JLabel(""); label.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK)); gridbag.setConstraints(label, c); panel.add(label); c.gridy = y++; c.gridwidth = 1; c.insets = left; label = new JLabel("Domain Axis"); gridbag.setConstraints(label, c); panel.add(label); c.gridx = x--; c.insets = none; gridbag.setConstraints(spectraDomain, c); panel.add(spectraDomain); c.gridx = x++; c.gridy = y++; c.insets = left; label = new JLabel("Response Type"); gridbag.setConstraints(label, c); panel.add(label); c.gridx = x--; c.insets = none; gridbag.setConstraints(spectraCB, c); panel.add(spectraCB); c.gridx = x++; c.gridy = y++; c.insets = left; label = new JLabel("Damping (%)"); gridbag.setConstraints(label, c); panel.add(label); c.gridx = x--; c.insets = none; gridbag.setConstraints(spectraDamp, c); panel.add(spectraDamp); c.gridx = x++; c.gridy = y++; c.insets = left; gridbag.setConstraints(spectraDomainLabel, c); panel.add(spectraDomainLabel); c.gridx = x++; c.insets = none; gridbag.setConstraints(spectraHigh, c); panel.add(spectraHigh); y -= 7; c.gridy = y++; c.insets = new Insets(0, 10, 0, 0); c.gridx = x++; label = new JLabel("Save delimiter:"); gridbag.setConstraints(label, c); panel.add(label); c.gridy = y++; gridbag.setConstraints(saveTab, c); panel.add(saveTab); c.gridy = y++; gridbag.setConstraints(saveSpace, c); panel.add(saveSpace); c.gridy = y++; gridbag.setConstraints(saveComma, c); panel.add(saveComma); return panel; } public void actionPerformed(java.awt.event.ActionEvent e) { try { String command = e.getActionCommand(); if(command.equals("delete")) { int n = JOptionPane.showConfirmDialog(this, "Do you want to delete these records?", "Delete?", JOptionPane.YES_NO_OPTION); if(n != JOptionPane.YES_OPTION) return; table.deleteSelected(true); } else if(command.equals("domain")) { try { Double d = new Double(spectraHigh.getText()); spectraHigh.setText(Analysis.fmtTwo.format(new Double(1.0 / d.doubleValue()))); } catch(Exception ex){} updateDomainLabel(); } else if(command.equals("eqListChange")) { if(Utils.locked()) return; boolean isEq = true; int index = eqList.getSelectedIndex(); for(int i = 0; i < eqList.getItemCount(); i++) { if(((String)eqList.getItemAt(i)).equals(" -- Groups -- ")) { if(i == index) return; else if(index > i) isEq = false; break; } } Utils.getDB().runUpdate("update data set select1=0 where select1=1"); if(isEq) { String where; if(index == 0) // "All earthquakes" where = ""; else where = "where eq='" + (String)eqList.getSelectedItem() + "'"; Utils.getDB().runUpdate("update data set select1=1 " + where); } else { Object[][] res = Utils.getDB().runQuery("select record,analyze from grp where name='" + (String)eqList.getSelectedItem() + "'"); for(int i = 1; i < res.length; i++) Utils.getDB().runUpdate("update data set select1=1 where id=" + res[i][0].toString()); } table.setModel(SlammerTable.REFRESH); recordClear(); } else if(command.equals("graph") || command.equals("saveGraph")) { int row = table.getSelectedRow(); if(row == -1) return; String eq = table.getModel().getValueAt(row, 0).toString(); String record = table.getModel().getValueAt(row, 1).toString(); Object[][] res = null; res = Utils.getDB().runQuery("select path,digi_int from data where eq='" + eq + "' and record='" + record + "'"); if(res == null) return; String path = res[1][0].toString(); double di = Double.parseDouble(res[1][1].toString()); File f = new File(path); if(f.canRead() == false) { GUIUtils.popupError("Cannot read or open the file " + path + "."); return; } DoubleList dat = new DoubleList(path, 0, 1, typeTime.isSelected() && timeAxisGs.isSelected()); if(dat.bad()) { GUIUtils.popupError("Invalid data at data point " + dat.badEntry() + " in " + path + "."); return; } XYSeries xys = new XYSeries(""); dat.reset(); String xAxis = null, yAxis = null, title = ""; if(typeTime.isSelected()) { title = "Time Series"; xAxis = "Time (s)"; Double val; double last1 = 0, last2 = 0, current; double diff1, diff2; double time = 0, timeStor = 0, td; int perSec = 50; double interval = 1.0 / (double)perSec; yAxis = "Acceleration ("; if(timeAxisGs.isSelected()) yAxis += "g's"; else yAxis += "cm/s/s"; yAxis += ")"; // add the first point if((val = dat.each()) != null) { xys.add(time, val); time += di; last2 = val.doubleValue(); } // don't add the second point, but update the data if((val = dat.each()) != null) { time += di; last1 = val.doubleValue(); } while((val = dat.each()) != null) { td = time - di; current = val.doubleValue(); diff1 = last1 - current; diff2 = last1 - last2; if( (diff1 <= 0 && diff2 <= 0) || (diff1 >= 0 && diff2 >= 0) || (td >= (timeStor + interval))) { xys.add(td, last1); timeStor = td; } last2 = last1; last1 = current; time += di; } } else if(typeFourier.isSelected()) { title = "Fourier Amplitude Spectrum"; xAxis = "Frequency (Hz)"; yAxis = "Fourier Amplitude (cm/s)"; double[] arr = new double[dat.size()]; Double temp; for(int i = 0; (temp = dat.each()) != null; i++) arr[i] = temp.doubleValue(); double[][] fft = ImportRecords.fftWrap(arr, di); double df = 1.0 / ((double)(arr.length) * di); double current; double freq = 0; int step, i; for(i = 0; i < arr.length;) { // don't graph anything below 0.1 hz if(freq > 0.1) xys.add(freq, Math.sqrt(Math.pow(fft[i][0], 2) + Math.pow(fft[i][1], 2))); // throw out 3/4 of the points above 10 hz if(freq > 10.0) step = 4; else step = 1; i += step; freq = i * df; } } else if(typeSpectra.isSelected()) { int index = spectraCB.getSelectedIndex(); title = spectraCB.getSelectedItem().toString() + " Response Spectrum at "; xAxis = spectraDomain.getSelectedItem() + " (" + spectraDomainStr[spectraDomain.getSelectedIndex()] + ")"; yAxis = "Response (" + spectraCBStr[spectraCB.getSelectedIndex()] + ")"; double[] arr = new double[dat.size()]; Double temp; for(int i = 0; (temp = dat.each()) != null; i++) arr[i] = temp.doubleValue(); double freqMax = Double.parseDouble(spectraHigh.getText()); double damp = Double.parseDouble(spectraDamp.getText()) / 100.0; title = title + spectraDamp.getText()+ "% Damping"; boolean domainFreq = true; if(spectraDomain.getSelectedItem().equals("Period")) { domainFreq = false; freqMax = 1.0 / freqMax; } double[] z; // don't start with 0, LogarithmicAxis doesn't allow it for(double prev = 0, p = 0.05; prev < freqMax;) { z = ImportRecords.cmpmax(arr, 2.0 * Math.PI * p, damp, di); xys.add( domainFreq ? p : 1.0 / p, z[index]); // make sure we always hit the max frequency prev = p; p += Math.log10(p + 1.0) / 8.0; if(p > freqMax) p = freqMax; } } title += ": " + eq + " - " + record; if(command.equals("graph")) { XYSeriesCollection xysc = new XYSeriesCollection(xys); JFreeChart chart = ChartFactory.createXYLineChart(title, xAxis, yAxis, xysc, org.jfree.chart.plot.PlotOrientation.VERTICAL, false, true, false); if(typeFourier.isSelected() || typeSpectra.isSelected()) { chart.getXYPlot().setRangeAxis(new LogarithmicAxis(yAxis)); chart.getXYPlot().setDomainAxis(new LogarithmicAxis(xAxis)); } ChartFrame frame = new ChartFrame(title, chart); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } else if(command.equals("saveGraph")) { if(JFileChooser.APPROVE_OPTION == saveChooser.showOpenDialog(this)) { double xysdata[][] = xys.toArray(); FileWriter w = new FileWriter(saveChooser.getSelectedFile()); String delim = "\t"; if(saveSpace.isSelected()) delim = " "; if(saveComma.isSelected()) delim = ","; w.write("# " + title + "\n"); w.write("# " + xAxis + delim + yAxis + "\n"); for(int i = 0; i < xysdata[0].length; i++) w.write(xysdata[0][i] + delim + xysdata[1][i] + "\n"); w.close(); } } } else if(command.equals("save")) { if(JOptionPane.showConfirmDialog(this, "Are you sure you want to modify this record?", "Are you sure?", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return; String error = AddRecordsPanel.manipRecord(false, modFile.getText(), modEq.getText(), modRec.getText(), modDI.getText(), Utils.nullify(modMag.getText()), Utils.nullify(modEpi.getText()), Utils.nullify(modFoc.getText()), Utils.nullify(modRup.getText()), Utils.nullify(modVs.getText()), modMech.getSelectedItem().toString(), modLoc.getText(), modOwn.getText(), Utils.nullify(modLat.getText()), Utils.nullify(modLng.getText()), modSite.getSelectedItem().toString() ); if(!error.equals("")) GUIUtils.popupError(error); table.setModel(SlammerTable.REFRESH); } } catch (Exception ex) { Utils.catchException(ex); } } public void recordSelect(ListSelectionEvent e) { if(e == null) return; if (e.getValueIsAdjusting()) return; ListSelectionModel lsm = (ListSelectionModel)e.getSource(); if (!lsm.isSelectionEmpty()) { int selectedRow = lsm.getMinSelectionIndex(); String eq = table.getModel().getValueAt(selectedRow, 0).toString(); String record = table.getModel().getValueAt(selectedRow, 1).toString(); Object[][] res = null; try { res = Utils.getDB().runQuery("select path, eq, record, digi_int, location, mom_mag, owner, epi_dist, latitude, foc_dist, longitude, rup_dist, vs30, class, foc_mech, change from data where eq='" + eq + "' and record='" + record + "'"); } catch(Exception ex) { Utils.catchException(ex); } boolean enable = false; if(res != null) { if(res.length > 1) { int incr = 0; modFile.setText(res[1][incr++].toString()); modEq.setText(res[1][incr++].toString()); modRec.setText(res[1][incr++].toString()); modDI.setText(res[1][incr++].toString()); modLoc.setText(res[1][incr++].toString()); modMag.setText(Utils.shorten(res[1][incr++])); modOwn.setText(res[1][incr++].toString()); modEpi.setText(Utils.shorten(res[1][incr++])); modLat.setText(Utils.shorten(res[1][incr++])); modFoc.setText(Utils.shorten(res[1][incr++])); modLng.setText(Utils.shorten(res[1][incr++])); modRup.setText(Utils.shorten(res[1][incr++])); modVs.setText(Utils.shorten(res[1][incr++])); modSite.setSelectedItem(SlammerTable.SiteClassArray[Integer.parseInt(Utils.shorten(res[1][incr++].toString()))]); modMech.setSelectedItem(SlammerTable.FocMechArray[Integer.parseInt(Utils.shorten(res[1][incr++].toString()))]); enable = res[1][incr++].toString().equals("1") ? true : false; } else { recordClear(); } } else { recordClear(); } recordEnable(true); } } public void recordEnable(boolean b) { modFile.setEditable(b); modEq.setEditable(b); modRec.setEditable(b); modDI.setEditable(b); modLoc.setEditable(b); modMag.setEditable(b); modOwn.setEditable(b); modEpi.setEditable(b); modLat.setEditable(b); modFoc.setEditable(b); modLng.setEditable(b); modRup.setEditable(b); modVs.setEditable(b); modSite.setEnabled(b); modMech.setEnabled(b); save.setEnabled(b); } public void recordClear() { modFile.setText(""); modEq.setText(""); modRec.setText(""); modDI.setText(""); modLoc.setText(""); modMag.setText(""); modOwn.setText(""); modEpi.setText(""); modLat.setText(""); modFoc.setText(""); modLng.setText(""); modRup.setText(""); modVs.setText(""); modSite.setSelectedItem(""); modMech.setSelectedItem(""); recordEnable(false); } public void updateDomainLabel() { spectraDomainLabel.setText(spectraDirStr[spectraDomain.getSelectedIndex()] + " " + spectraDomain.getSelectedItem() + " (" + spectraDomainStr[spectraDomain.getSelectedIndex()] + ")"); } }
false
false
null
null
diff --git a/branches/crux/5.1/crux-dev/src/main/java/org/cruxframework/crux/gwt/rebind/CaptionPanelFactory.java b/branches/crux/5.1/crux-dev/src/main/java/org/cruxframework/crux/gwt/rebind/CaptionPanelFactory.java index 57b17f045..876c06013 100644 --- a/branches/crux/5.1/crux-dev/src/main/java/org/cruxframework/crux/gwt/rebind/CaptionPanelFactory.java +++ b/branches/crux/5.1/crux-dev/src/main/java/org/cruxframework/crux/gwt/rebind/CaptionPanelFactory.java @@ -1,96 +1,96 @@ /* * Copyright 2011 cruxframework.org. * * 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.cruxframework.crux.gwt.rebind; import org.cruxframework.crux.core.rebind.AbstractProxyCreator.SourcePrinter; import org.cruxframework.crux.core.rebind.CruxGeneratorException; import org.cruxframework.crux.core.rebind.screen.widget.WidgetCreatorContext; import org.cruxframework.crux.core.rebind.screen.widget.creator.children.AnyWidgetChildProcessor; import org.cruxframework.crux.core.rebind.screen.widget.creator.children.ChoiceChildProcessor; import org.cruxframework.crux.core.rebind.screen.widget.creator.children.WidgetChildProcessor; import org.cruxframework.crux.core.rebind.screen.widget.creator.children.WidgetChildProcessor.HTMLTag; import org.cruxframework.crux.core.rebind.screen.widget.declarative.DeclarativeFactory; import org.cruxframework.crux.core.rebind.screen.widget.declarative.TagAttribute; import org.cruxframework.crux.core.rebind.screen.widget.declarative.TagAttributes; import org.cruxframework.crux.core.rebind.screen.widget.declarative.TagChild; import org.cruxframework.crux.core.rebind.screen.widget.declarative.TagChildren; import org.cruxframework.crux.core.rebind.screen.widget.declarative.TagConstraints; import com.google.gwt.user.client.ui.CaptionPanel; /** * Factory for CaptionPanel widgets * @author Gesse S. F. Dafe */ @DeclarativeFactory(id="captionPanel", library="gwt", targetWidget=CaptionPanel.class) @TagAttributes({ - @TagAttribute("captionText") + @TagAttribute(value = "captionText", supportsI18N = true) }) @TagChildren({ @TagChild(CaptionPanelFactory.CaptionProcessor.class), @TagChild(CaptionPanelFactory.ContentProcessor.class) }) public class CaptionPanelFactory extends CompositeFactory<WidgetCreatorContext> { @Override public void processChildren(SourcePrinter out, WidgetCreatorContext context) throws CruxGeneratorException {} @TagConstraints(minOccurs="0") @TagChildren({ @TagChild(CaptionTextProcessor.class), @TagChild(CaptionHTMLProcessor.class) }) public static class CaptionProcessor extends ChoiceChildProcessor<WidgetCreatorContext> {} @TagConstraints(minOccurs="0", tagName="widget") @TagChildren({ @TagChild(WidgetProcessor.class) }) public static class ContentProcessor extends WidgetChildProcessor<WidgetCreatorContext> {} @TagConstraints(minOccurs="0", widgetProperty="contentWidget") public static class WidgetProcessor extends AnyWidgetChildProcessor<WidgetCreatorContext> {} @TagConstraints(tagName="captionText", type=String.class) public static class CaptionTextProcessor extends WidgetChildProcessor<WidgetCreatorContext> { @Override public void processChildren(SourcePrinter out, WidgetCreatorContext context) throws CruxGeneratorException { String title = getWidgetCreator().getDeclaredMessage(getWidgetCreator(). ensureTextChild(context.getChildElement(), false, context.getWidgetId(), false)); out.println(context.getWidget()+".setCaptionText("+title+");"); } } @TagConstraints(tagName="captionHTML", type=HTMLTag.class) public static class CaptionHTMLProcessor extends WidgetChildProcessor<WidgetCreatorContext> { @Override public void processChildren(SourcePrinter out, WidgetCreatorContext context) throws CruxGeneratorException { String title = getWidgetCreator().ensureHtmlChild(context.getChildElement(), false, context.getWidgetId()); out.println(context.getWidget()+".setCaptionHTML("+title+");"); } } @Override public WidgetCreatorContext instantiateContext() { return new WidgetCreatorContext(); } }
true
false
null
null
diff --git a/framework/src/main/java/org/apache/felix/framework/URLHandlers.java b/framework/src/main/java/org/apache/felix/framework/URLHandlers.java index 9b49a594c..d6b444d16 100644 --- a/framework/src/main/java/org/apache/felix/framework/URLHandlers.java +++ b/framework/src/main/java/org/apache/felix/framework/URLHandlers.java @@ -1,641 +1,646 @@ /* * 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.felix.framework; import java.net.ContentHandler; import java.net.ContentHandlerFactory; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; import java.net.URLStreamHandlerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.apache.felix.framework.util.FelixConstants; import org.apache.felix.framework.util.SecureAction; import org.apache.felix.framework.util.SecurityManagerEx; import org.osgi.service.url.URLStreamHandlerService; /** * <p> * This class is a singleton and implements the stream and content handler * factories for all framework instances executing within the JVM. Any * calls to retrieve stream or content handlers is routed through this class * and it acts as a multiplexer for all framework instances. To achieve this, * all framework instances register with this class when they are created so * that it can maintain a centralized registry of instances. * </p> * <p> * When this class receives a request for a stream or content handler, it * always returns a proxy handler instead of only returning a proxy if a * handler currently exists. This approach is used for three reasons: * </p> * <ol> * <li>Potential caching behavior by the JVM of stream handlers does not give * you a second chance to provide a handler. * </li> * <li>Due to the dynamic nature of OSGi services, handlers may appear at * any time, so always creating a proxy makes sense. * </li> * <li>Since these handler factories service all framework instances, * some instances may have handlers and others may not, so returning * a proxy is the only answer that makes sense. * </li> * </ol> * <p> * It is possible to disable the URL Handlers service by setting the * <tt>framework.service.urlhandlers</tt> configuration property to <tt>false</tt>. * When multiple framework instances are in use, if no framework instances enable * the URL Handlers service, then the singleton stream and content factories will * never be set (i.e., <tt>URL.setURLStreamHandlerFactory()</tt> and * <tt>URLConnection.setContentHandlerFactory()</tt>). However, if one instance * enables URL Handlers service, then the factory methods will be invoked. In * that case, framework instances that disable the URL Handlers service will * simply not provide that services to their contained bundles, while framework * instances with the service enabled will. * </p> **/ class URLHandlers implements URLStreamHandlerFactory, ContentHandlerFactory { private static final Class[] CLASS_TYPE = new Class[]{Class.class}; private static final Class URLHANDLERS_CLASS = URLHandlers.class; private static final SecureAction m_secureAction = new SecureAction(); private static volatile SecurityManagerEx m_sm = null; private static volatile URLHandlers m_handler = null; // This maps classloaders of URLHandlers in other classloaders to lists of // their frameworks. private static Map m_classloaderToFrameworkLists = new HashMap(); // The list to hold all enabled frameworks registered with this handlers private static final List m_frameworks = new ArrayList(); private static int m_counter = 0; private static Map m_contentHandlerCache = null; private static Map m_streamHandlerCache = null; private static URLStreamHandlerFactory m_streamHandlerFactory; private static ContentHandlerFactory m_contentHandlerFactory; private static final String STREAM_HANDLER_PACKAGE_PROP = "java.protocol.handler.pkgs"; private static final String DEFAULT_STREAM_HANDLER_PACKAGE = "sun.net.www.protocol|com.ibm.oti.net.www.protocol|gnu.java.net.protocol|wonka.net|com.acunia.wonka.net|org.apache.harmony.luni.internal.net.www.protocol|weblogic.utils|weblogic.net|javax.net.ssl|COM.newmonics.www.protocols"; private static Object m_rootURLHandlers; private static final String m_streamPkgs; private static final Map m_builtIn = new HashMap(); private static final boolean m_loaded; static { String pkgs = new SecureAction().getSystemProperty(STREAM_HANDLER_PACKAGE_PROP, ""); m_streamPkgs = (pkgs.equals("")) ? DEFAULT_STREAM_HANDLER_PACKAGE : pkgs + "|" + DEFAULT_STREAM_HANDLER_PACKAGE; m_loaded = (null != URLHandlersStreamHandlerProxy.class) && (null != URLHandlersContentHandlerProxy.class) && (null != URLStreamHandlerService.class); } private static final Map m_handlerToURL = new HashMap(); private void init(String protocol) { try { m_handlerToURL.put(getBuiltInStreamHandler(protocol, null), new URL(protocol + ":") ); } catch (Throwable ex) { ex.printStackTrace(); // Ignore, this is a best effort (maybe log it or something). } } /** * <p> * Only one instance of this class is created per classloader * and that one instance is registered as the stream and content handler * factories for the JVM. Unless, we already register one from a different * classloader. In this case we attach to this root. * </p> **/ private URLHandlers() { init("file"); init("ftp"); init("http"); init("https"); try { getBuiltInStreamHandler("jar", null); } catch (Throwable ex) { ex.printStackTrace(); // Ignore, this is a best effort (maybe log it or something) } m_sm = new SecurityManagerEx(); synchronized (URL.class) { try { URL.setURLStreamHandlerFactory(this); m_streamHandlerFactory = this; m_rootURLHandlers = this; } catch (Error err) { try { // there already is a factory set so try to swap it with ours. m_streamHandlerFactory = (URLStreamHandlerFactory) m_secureAction.swapStaticFieldIfNotClass(URL.class, URLStreamHandlerFactory.class, URLHANDLERS_CLASS, "streamHandlerLock"); if (m_streamHandlerFactory == null) { throw err; } if (!m_streamHandlerFactory.getClass().getName().equals(URLHANDLERS_CLASS.getName())) { URL.setURLStreamHandlerFactory(this); m_rootURLHandlers = this; } else if (URLHANDLERS_CLASS != m_streamHandlerFactory.getClass()) { try { m_secureAction.invoke( m_secureAction.getDeclaredMethod(m_streamHandlerFactory.getClass(), "registerFrameworkListsForContextSearch", new Class[]{ClassLoader.class, List.class}), m_streamHandlerFactory, new Object[]{ URLHANDLERS_CLASS.getClassLoader(), m_frameworks }); m_rootURLHandlers = m_streamHandlerFactory; } catch (Exception ex) { new RuntimeException(ex.getMessage()); } } } catch (Exception e) { throw err; } } try { URLConnection.setContentHandlerFactory(this); m_contentHandlerFactory = this; } catch (Error err) { // there already is a factory set so try to swap it with ours. try { m_contentHandlerFactory = (ContentHandlerFactory) m_secureAction.swapStaticFieldIfNotClass( URLConnection.class, ContentHandlerFactory.class, URLHANDLERS_CLASS, null); if (m_contentHandlerFactory == null) { throw err; } if (!m_contentHandlerFactory.getClass().getName().equals( URLHANDLERS_CLASS.getName())) { URLConnection.setContentHandlerFactory(this); } } catch (Exception ex) { throw err; } } } // are we not the new root? if (!((m_streamHandlerFactory == this) || !URLHANDLERS_CLASS.getName().equals( m_streamHandlerFactory.getClass().getName()))) { m_sm = null; m_handlerToURL.clear(); m_builtIn.clear(); } } static void registerFrameworkListsForContextSearch(ClassLoader index, List frameworkLists) { synchronized (URL.class) { synchronized (m_classloaderToFrameworkLists) { m_classloaderToFrameworkLists.put(index, frameworkLists); } } } static void unregisterFrameworkListsForContextSearch(ClassLoader index) { synchronized (URL.class) { synchronized (m_classloaderToFrameworkLists) { m_classloaderToFrameworkLists.remove(index); if (m_classloaderToFrameworkLists.isEmpty() ) { synchronized (m_frameworks) { if (m_frameworks.isEmpty()) { try { m_secureAction.swapStaticFieldIfNotClass(URL.class, URLStreamHandlerFactory.class, null, "streamHandlerLock"); } catch (Exception ex) { // TODO log this ex.printStackTrace(); } if (m_streamHandlerFactory.getClass() != URLHANDLERS_CLASS) { URL.setURLStreamHandlerFactory(m_streamHandlerFactory); } try { m_secureAction.swapStaticFieldIfNotClass( URLConnection.class, ContentHandlerFactory.class, null, null); } catch (Exception ex) { // TODO log this ex.printStackTrace(); } if (m_contentHandlerFactory.getClass() != URLHANDLERS_CLASS) { URLConnection.setContentHandlerFactory(m_contentHandlerFactory); } } } } } } } private URLStreamHandler getBuiltInStreamHandler(String protocol, URLStreamHandlerFactory factory) { synchronized (m_builtIn) { if (m_builtIn.containsKey(protocol)) { return (URLStreamHandler) m_builtIn.get(protocol); } } if (factory != null) { URLStreamHandler result = factory.createURLStreamHandler(protocol); if (result != null) { return addToCache(protocol, result); } } // Check for built-in handlers for the mime type. // Iterate over built-in packages. StringTokenizer pkgTok = new StringTokenizer(m_streamPkgs, "| "); while (pkgTok.hasMoreTokens()) { String pkg = pkgTok.nextToken().trim(); String className = pkg + "." + protocol + ".Handler"; try { // If a built-in handler is found then cache and return it Class handler = m_secureAction.forName(className); if (handler != null) { return addToCache(protocol, (URLStreamHandler) handler.newInstance()); } } catch (Exception ex) { // This could be a class not found exception or an // instantiation exception, not much we can do in either // case other than ignore it. } } return addToCache(protocol, null); } private synchronized URLStreamHandler addToCache(String protocol, URLStreamHandler result) { if (!m_builtIn.containsKey(protocol)) { m_builtIn.put(protocol, result); return result; } return (URLStreamHandler) m_builtIn.get(protocol); } /** * <p> * This is a method implementation for the <tt>URLStreamHandlerFactory</tt> * interface. It simply creates a stream handler proxy object for the * specified protocol. It caches the returned proxy; therefore, subsequent * requests for the same protocol will receive the same handler proxy. * </p> * @param protocol the protocol for which a stream handler should be returned. * @return a stream handler proxy for the specified protocol. **/ public URLStreamHandler createURLStreamHandler(String protocol) { // See if there is a cached stream handler. // IMPLEMENTATION NOTE: Caching is not strictly necessary for // stream handlers since the Java runtime caches them. Caching is // performed for code consistency between stream and content // handlers and also because caching behavior may not be guaranteed // across different JRE implementations. URLStreamHandler handler = getFromStreamCache(protocol); if (handler != null) { return handler; } // If this is the framework's "bundle:" protocol, then return // a handler for that immediately, since no one else can be // allowed to deal with it. if (protocol.equals(FelixConstants.BUNDLE_URL_PROTOCOL)) { return addToStreamCache(protocol, new URLHandlersBundleStreamHandler(m_secureAction)); } handler = getBuiltInStreamHandler(protocol, (m_streamHandlerFactory != this) ? m_streamHandlerFactory : null); // If built-in content handler, then create a proxy handler. return addToStreamCache(protocol, new URLHandlersStreamHandlerProxy(protocol, m_secureAction, handler, (URL) m_handlerToURL.get(handler))); } /** * <p> * This is a method implementation for the <tt>ContentHandlerFactory</tt> * interface. It simply creates a content handler proxy object for the * specified mime type. It caches the returned proxy; therefore, subsequent * requests for the same content type will receive the same handler proxy. * </p> * @param mimeType the mime type for which a content handler should be returned. * @return a content handler proxy for the specified mime type. **/ public ContentHandler createContentHandler(String mimeType) { // See if there is a cached stream handler. // IMPLEMENTATION NOTE: Caching is not strictly necessary for // stream handlers since the Java runtime caches them. Caching is // performed for code consistency between stream and content // handlers and also because caching behavior may not be guaranteed // across different JRE implementations. ContentHandler handler = getFromContentCache(mimeType); if (handler != null) { return handler; } return addToContentCache(mimeType, new URLHandlersContentHandlerProxy(mimeType, m_secureAction, (m_contentHandlerFactory != this) ? m_contentHandlerFactory : null)); } private synchronized ContentHandler addToContentCache(String mimeType, ContentHandler handler) { if (m_contentHandlerCache == null) { m_contentHandlerCache = new HashMap(); } return (ContentHandler) addToCache(m_contentHandlerCache, mimeType, handler); } private synchronized ContentHandler getFromContentCache(String mimeType) { return (ContentHandler) ((m_contentHandlerCache != null) ? m_contentHandlerCache.get(mimeType) : null); } private synchronized URLStreamHandler addToStreamCache(String protocol, URLStreamHandler handler) { if (m_streamHandlerCache == null) { m_streamHandlerCache = new HashMap(); } return (URLStreamHandler) addToCache(m_streamHandlerCache, protocol, handler); } private synchronized URLStreamHandler getFromStreamCache(String protocol) { return (URLStreamHandler) ((m_streamHandlerCache != null) ? m_streamHandlerCache.get(protocol) : null); } private Object addToCache(Map cache, String key, Object value) { if (value == null) { return null; } Object result = cache.get(key); if (result == null) { cache.put(key, value); result = value; } return result; } /** * <p> * Static method that adds a framework instance to the centralized * instance registry. * </p> * @param framework the framework instance to be added to the instance * registry. * @param enable a flag indicating whether or not the framework wants to * enable the URL Handlers service. **/ public static void registerFrameworkInstance(Object framework, boolean enable) { synchronized (m_frameworks) { // If the URL Handlers service is not going to be enabled, // then return immediately. if (enable) { // We need to create an instance if this is the first // time this method is called, which will set the handler // factories. if (m_handler == null) { m_handler = new URLHandlers(); } m_frameworks.add(framework); } m_counter++; } } /** * <p> * Static method that removes a framework instance from the centralized * instance registry. * </p> * @param framework the framework instance to be removed from the instance * registry. **/ public static void unregisterFrameworkInstance(Object framework) { + boolean unregister = false; synchronized (m_frameworks) { m_counter--; if (m_frameworks.remove(framework)) { if (m_frameworks.isEmpty()) { - try - { - m_secureAction.invoke(m_secureAction.getDeclaredMethod( - m_rootURLHandlers.getClass(), - "unregisterFrameworkListsForContextSearch", - new Class[]{ ClassLoader.class}), - m_rootURLHandlers, - new Object[] {URLHANDLERS_CLASS.getClassLoader()}); - } - catch (Exception e) - { - // TODO: this should not happen - e.printStackTrace(); - } + unregister = true; m_handler = null; } } } + if (unregister) + { + try + { + m_secureAction.invoke(m_secureAction.getDeclaredMethod( + m_rootURLHandlers.getClass(), + "unregisterFrameworkListsForContextSearch", + new Class[]{ ClassLoader.class}), + m_rootURLHandlers, + new Object[] {URLHANDLERS_CLASS.getClassLoader()}); + } + catch (Exception e) + { + // TODO: this should not happen + e.printStackTrace(); + } + } } /** * <p> * This method returns the system bundle context for the caller. * It determines the appropriate system bundle by retrieving the * class call stack and find the first class that is loaded from * a bundle. It then checks to see which of the registered framework * instances owns the class and returns its system bundle context. * </p> * @return the system bundle context associated with the caller or * <tt>null</tt> if no associated framework was found. **/ public static Object getFrameworkFromContext() { // This is a hack. The idea is to return the only registered framework synchronized (m_classloaderToFrameworkLists) { if (m_classloaderToFrameworkLists.isEmpty()) { synchronized (m_frameworks) { if ((m_counter == 1) && (m_frameworks.size() == 1)) { return m_frameworks.get(0); } } } } // get the current class call stack. Class[] stack = m_sm.getClassContext(); // Find the first class that is loaded from a bundle. Class targetClass = null; for (int i = 0; i < stack.length; i++) { if ((stack[i].getClassLoader() != null) && "org.apache.felix.framework.searchpolicy.ModuleImpl.ModuleClassLoader".equals( stack[i].getClassLoader().getClass().getName())) { targetClass = stack[i]; break; } } // If we found a class loaded from a bundle, then iterate // over the framework instances and see which framework owns // the bundle that loaded the class. if (targetClass != null) { synchronized (m_classloaderToFrameworkLists) { ClassLoader index = targetClass.getClassLoader().getClass().getClassLoader(); List frameworks = (List) m_classloaderToFrameworkLists.get( index); if ((frameworks == null) && (index == URLHANDLERS_CLASS.getClassLoader())) { frameworks = m_frameworks; } if (frameworks != null) { synchronized (frameworks) { // Check the registry of framework instances for (int i = 0; i < frameworks.size(); i++) { Object framework = frameworks.get(i); try { if (m_secureAction.invoke( m_secureAction.getDeclaredMethod(framework.getClass(), "getBundle", CLASS_TYPE), framework, new Object[]{targetClass}) != null) { return framework; } } catch (Exception ex) { // This should not happen but if it does there is // not much we can do other then ignore it. // Maybe log this or something. ex.printStackTrace(); } } } } } } return null; } } \ No newline at end of file
false
false
null
null
diff --git a/srcj/com/sun/electric/tool/user/tecEditWizard/TechEditWizardData.java b/srcj/com/sun/electric/tool/user/tecEditWizard/TechEditWizardData.java index d1589c4a1..a3a87b8e6 100644 --- a/srcj/com/sun/electric/tool/user/tecEditWizard/TechEditWizardData.java +++ b/srcj/com/sun/electric/tool/user/tecEditWizard/TechEditWizardData.java @@ -1,2829 +1,2827 @@ /* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: TechEditWizardData.java * Create an Electric XML Technology from a simple numeric description of design rules * Written in Perl by Andrew Wewist, translated to Java by Steven Rubin. * * Copyright (c) 2008 Sun Microsystems and Static Free Software * * Electric(tm) 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. * * Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, Mass 02111-1307, USA. */ package com.sun.electric.tool.user.tecEditWizard; import com.sun.electric.database.text.TextUtils; import com.sun.electric.database.geometry.*; import com.sun.electric.database.geometry.Poly; import com.sun.electric.tool.Job; import com.sun.electric.tool.io.FileType; import com.sun.electric.tool.user.dialogs.OpenFile; import com.sun.electric.technology.*; import java.awt.Color; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Class to handle the "Technology Creation Wizard" dialog. */ public class TechEditWizardData { /************************************** THE DATA **************************************/ private String tech_name; private String tech_description; private int num_metal_layers; private int stepsize; // DIFFUSION RULES private WizardField diff_width = new WizardField(); private WizardField diff_poly_overhang = new WizardField(); // min. diff overhang from gate edge private WizardField diff_contact_overhang = new WizardField(); // min. diff overhang contact private WizardField diff_spacing = new WizardField(); // POLY RULES private WizardField poly_width = new WizardField(); private WizardField poly_endcap = new WizardField(); // min. poly gate extension from edge of diffusion private WizardField poly_spacing = new WizardField(); private WizardField poly_diff_spacing = new WizardField(); // min. spacing between poly and diffusion // GATE RULES private WizardField gate_length = new WizardField(); // min. transistor gate length private WizardField gate_width = new WizardField(); // min. transistor gate width private WizardField gate_spacing = new WizardField(); // min. gate to gate spacing on diffusion private WizardField gate_contact_spacing = new WizardField(); // min. spacing from gate edge to contact inside diffusion // CONTACT RULES private WizardField contact_size = new WizardField(); private WizardField contact_spacing = new WizardField(); private WizardField contact_metal_overhang_inline_only = new WizardField(); // metal overhang when overhanging contact from two sides only private WizardField contact_metal_overhang_all_sides = new WizardField(); // metal overhang when surrounding contact private WizardField contact_poly_overhang = new WizardField(); // poly overhang contact private WizardField polycon_diff_spacing = new WizardField(); // spacing between poly-metal contact edge and diffusion // WELL AND IMPLANT RULES private WizardField nplus_width = new WizardField(); private WizardField nplus_overhang_diff = new WizardField(); private WizardField nplus_spacing = new WizardField(); private WizardField pplus_width = new WizardField(); private WizardField pplus_overhang_diff = new WizardField(); private WizardField pplus_spacing = new WizardField(); private WizardField nwell_width = new WizardField(); private WizardField nwell_overhang_diff = new WizardField(); private WizardField nwell_spacing = new WizardField(); // METAL RULES private WizardField [] metal_width; private WizardField [] metal_spacing; // VIA RULES private WizardField [] via_size; private WizardField [] via_spacing; private WizardField [] via_array_spacing; private WizardField [] via_overhang_inline; // ANTENNA RULES private double poly_antenna_ratio; private double [] metal_antenna_ratio; // GDS-II LAYERS private int gds_diff_layer; private int gds_poly_layer; private int gds_nplus_layer; private int gds_pplus_layer; private int gds_nwell_layer; private int gds_contact_layer; private int [] gds_metal_layer; private int [] gds_via_layer; private int gds_marking_layer; // Device marking layer TechEditWizardData() { stepsize = 100; num_metal_layers = 2; metal_width = new WizardField[num_metal_layers]; metal_spacing = new WizardField[num_metal_layers]; via_size = new WizardField[num_metal_layers-1]; via_spacing = new WizardField[num_metal_layers-1]; via_array_spacing = new WizardField[num_metal_layers-1]; via_overhang_inline = new WizardField[num_metal_layers-1]; metal_antenna_ratio = new double[num_metal_layers]; gds_metal_layer = new int[num_metal_layers]; gds_via_layer = new int[num_metal_layers-1]; for(int i=0; i<num_metal_layers; i++) { metal_width[i] = new WizardField(); metal_spacing[i] = new WizardField(); } for(int i=0; i<num_metal_layers-1; i++) { via_size[i] = new WizardField(); via_spacing[i] = new WizardField(); via_array_spacing[i] = new WizardField(); via_overhang_inline[i] = new WizardField(); } } /************************************** ACCESSOR METHODS **************************************/ public String getTechName() { return tech_name; } public void setTechName(String s) { tech_name = s; } public String getTechDescription() { return tech_description; } public void setTechDescription(String s) { tech_description = s; } public int getStepSize() { return stepsize; } public void setStepSize(int n) { stepsize = n; } public int getNumMetalLayers() { return num_metal_layers; } public void setNumMetalLayers(int n) { int smallest = Math.min(n, num_metal_layers); WizardField [] new_metal_width = new WizardField[n]; for(int i=0; i<smallest; i++) new_metal_width[i] = metal_width[i]; for(int i=smallest; i<n; i++) new_metal_width[i] = new WizardField(); metal_width = new_metal_width; WizardField [] new_metal_spacing = new WizardField[n]; for(int i=0; i<smallest; i++) new_metal_spacing[i] = metal_spacing[i]; for(int i=smallest; i<n; i++) new_metal_spacing[i] = new WizardField(); metal_spacing = new_metal_spacing; WizardField [] new_via_size = new WizardField[n-1]; for(int i=0; i<smallest-1; i++) new_via_size[i] = via_size[i]; for(int i=smallest-1; i<n-1; i++) new_via_size[i] = new WizardField(); via_size = new_via_size; WizardField [] new_via_spacing = new WizardField[n-1]; for(int i=0; i<smallest-1; i++) new_via_spacing[i] = via_spacing[i]; for(int i=smallest-1; i<n-1; i++) new_via_spacing[i] = new WizardField(); via_spacing = new_via_spacing; WizardField [] new_via_array_spacing = new WizardField[n-1]; for(int i=0; i<smallest-1; i++) new_via_array_spacing[i] = via_array_spacing[i]; for(int i=smallest-1; i<n-1; i++) new_via_array_spacing[i] = new WizardField(); via_array_spacing = new_via_array_spacing; WizardField [] new_via_overhang_inline = new WizardField[n-1]; for(int i=0; i<smallest-1; i++) new_via_overhang_inline[i] = via_overhang_inline[i]; for(int i=smallest-1; i<n-1; i++) new_via_overhang_inline[i] = new WizardField(); via_overhang_inline = new_via_overhang_inline; double [] new_metal_antenna_ratio = new double[n]; for(int i=0; i<smallest; i++) new_metal_antenna_ratio[i] = metal_antenna_ratio[i]; metal_antenna_ratio = new_metal_antenna_ratio; int [] new_gds_metal_layer = new int[n]; for(int i=0; i<smallest; i++) new_gds_metal_layer[i] = gds_metal_layer[i]; gds_metal_layer = new_gds_metal_layer; int [] new_gds_via_layer = new int[n-1]; for(int i=0; i<smallest-1; i++) new_gds_via_layer[i] = gds_via_layer[i]; gds_via_layer = new_gds_via_layer; num_metal_layers = n; } // DIFFUSION RULES public WizardField getDiffWidth() { return diff_width; } public void setDiffWidth(WizardField v) { diff_width = v; } public WizardField getDiffPolyOverhang() { return diff_poly_overhang; } public void setDiffPolyOverhang(WizardField v) { diff_poly_overhang = v; } public WizardField getDiffContactOverhang() { return diff_contact_overhang; } public void setDiffContactOverhang(WizardField v) { diff_contact_overhang = v; } public WizardField getDiffSpacing() { return diff_spacing; } public void setDiffSpacing(WizardField v) { diff_spacing = v; } // POLY RULES public WizardField getPolyWidth() { return poly_width; } public void setPolyWidth(WizardField v) { poly_width = v; } public WizardField getPolyEndcap() { return poly_endcap; } public void setPolyEndcap(WizardField v) { poly_endcap = v; } public WizardField getPolySpacing() { return poly_spacing; } public void setPolySpacing(WizardField v) { poly_spacing = v; } public WizardField getPolyDiffSpacing() { return poly_diff_spacing; } public void setPolyDiffSpacing(WizardField v) { poly_diff_spacing = v; } // GATE RULES public WizardField getGateLength() { return gate_length; } public void setGateLength(WizardField v) { gate_length = v; } public WizardField getGateWidth() { return gate_width; } public void setGateWidth(WizardField v) { gate_width = v; } public WizardField getGateSpacing() { return gate_spacing; } public void setGateSpacing(WizardField v) { gate_spacing = v; } public WizardField getGateContactSpacing() { return gate_contact_spacing; } public void setGateContactSpacing(WizardField v) { gate_contact_spacing = v; } // CONTACT RULES public WizardField getContactSize() { return contact_size; } public void setContactSize(WizardField v) { contact_size = v; } public WizardField getContactSpacing() { return contact_spacing; } public void setContactSpacing(WizardField v) { contact_spacing = v; } public WizardField getContactMetalOverhangInlineOnly() { return contact_metal_overhang_inline_only; } public void setContactMetalOverhangInlineOnly(WizardField v) { contact_metal_overhang_inline_only = v; } public WizardField getContactMetalOverhangAllSides() { return contact_metal_overhang_all_sides; } public void setContactMetalOverhangAllSides(WizardField v) { contact_metal_overhang_all_sides = v; } public WizardField getContactPolyOverhang() { return contact_poly_overhang; } public void setContactPolyOverhang(WizardField v) { contact_poly_overhang = v; } public WizardField getPolyconDiffSpacing() { return polycon_diff_spacing; } public void setPolyconDiffSpacing(WizardField v) { polycon_diff_spacing = v; } // WELL AND IMPLANT RULES public WizardField getNPlusWidth() { return nplus_width; } public void setNPlusWidth(WizardField v) { nplus_width = v; } public WizardField getNPlusOverhangDiff() { return nplus_overhang_diff; } public void setNPlusOverhangDiff(WizardField v) { nplus_overhang_diff = v; } public WizardField getNPlusSpacing() { return nplus_spacing; } public void setNPlusSpacing(WizardField v) { nplus_spacing = v; } public WizardField getPPlusWidth() { return pplus_width; } public void setPPlusWidth(WizardField v) { pplus_width = v; } public WizardField getPPlusOverhangDiff() { return pplus_overhang_diff; } public void setPPlusOverhangDiff(WizardField v) { pplus_overhang_diff = v; } public WizardField getPPlusSpacing() { return pplus_spacing; } public void setPPlusSpacing(WizardField v) { pplus_spacing = v; } public WizardField getNWellWidth() { return nwell_width; } public void setNWellWidth(WizardField v) { nwell_width = v; } public WizardField getNWellOverhangDiff() { return nwell_overhang_diff; } public void setNWellOverhangDiff(WizardField v) { nwell_overhang_diff = v; } public WizardField getNWellSpacing() { return nwell_spacing; } public void setNWellSpacing(WizardField v) { nwell_spacing = v; } // METAL RULES public WizardField [] getMetalWidth() { return metal_width; } public void setMetalWidth(int met, WizardField value) { metal_width[met] = value; } public WizardField [] getMetalSpacing() { return metal_spacing; } public void setMetalSpacing(int met, WizardField value) { metal_spacing[met] = value; } // VIA RULES public WizardField [] getViaSize() { return via_size; } public void setViaSize(int via, WizardField value) { via_size[via] = value; } public WizardField [] getViaSpacing() { return via_spacing; } public void setViaSpacing(int via, WizardField value) { via_spacing[via] = value; } public WizardField [] getViaArraySpacing() { return via_array_spacing; } public void setViaArraySpacing(int via, WizardField value) { via_array_spacing[via] = value; } public WizardField [] getViaOverhangInline() { return via_overhang_inline; } public void setViaOverhangInline(int via, WizardField value) { via_overhang_inline[via] = value; } // ANTENNA RULES public double getPolyAntennaRatio() { return poly_antenna_ratio; } public void setPolyAntennaRatio(double v) { poly_antenna_ratio = v; } public double [] getMetalAntennaRatio() { return metal_antenna_ratio; } public void setMetalAntennaRatio(int met, double value) { metal_antenna_ratio[met] = value; } // GDS-II LAYERS public int getGDSDiff() { return gds_diff_layer; } public void setGDSDiff(int l) { gds_diff_layer = l; } public int getGDSPoly() { return gds_poly_layer; } public void setGDSPoly(int l) { gds_poly_layer = l; } public int getGDSNPlus() { return gds_nplus_layer; } public void setGDSNPlus(int l) { gds_nplus_layer = l; } public int getGDSPPlus() { return gds_pplus_layer; } public void setGDSPPlus(int l) { gds_pplus_layer = l; } public int getGDSNWell() { return gds_nwell_layer; } public void setGDSNWell(int l) { gds_nwell_layer = l; } public int getGDSContact() { return gds_contact_layer; } public void setGDSContact(int l) { gds_contact_layer = l; } public int [] getGDSMetal() { return gds_metal_layer; } public void setGDSMetal(int met, int l) { gds_metal_layer[met] = l; } public int [] getGDSVia() { return gds_via_layer; } public void setGDSVia(int via, int l) { gds_via_layer[via] = l; } public int getGDSMarking() { return gds_marking_layer; } public void setGDSMarking(int l) { gds_marking_layer = l; } public String errorInData() { // check the General data if (tech_name == null || tech_name.length() == 0) return "General panel: No technology name"; if (stepsize == 0) return "General panel: Invalid unit size"; // check the Active data if (diff_width.v == 0) return "Active panel: Invalid width"; // check the Poly data if (poly_width.v == 0) return "Poly panel: Invalid width"; // check the Gate data if (gate_width.v == 0) return "Gate panel: Invalid width"; if (gate_length.v == 0) return "Gate panel: Invalid length"; // check the Contact data if (contact_size.v == 0) return "Contact panel: Invalid size"; // check the Well/Implant data if (nplus_width.v == 0) return "Well/Implant panel: Invalid NPlus width"; if (pplus_width.v == 0) return "Well/Implant panel: Invalid PPlus width"; if (nwell_width.v == 0) return "Well/Implant panel: Invalid NWell width"; // check the Metal data for(int i=0; i<num_metal_layers; i++) if (metal_width[i].v == 0) return "Metal panel: Invalid Metal-" + (i+1) + " width"; // check the Via data for(int i=0; i<num_metal_layers-1; i++) if (via_size[i].v == 0) return "Via panel: Invalid Via-" + (i+1) + " size"; return null; } /************************************** IMPORT RAW NUMBERS FROM DISK **************************************/ /** * Method to import data from a file to this object. * @return true on success; false on failure. */ public boolean importData() { String fileName = OpenFile.chooseInputFile(FileType.ANY, "Technology Wizard File"); if (fileName == null) return false; URL url = TextUtils.makeURLToFile(fileName); try { URLConnection urlCon = url.openConnection(); InputStreamReader is = new InputStreamReader(urlCon.getInputStream()); LineNumberReader lineReader = new LineNumberReader(is); for(;;) { String buf = lineReader.readLine(); if (buf == null) break; buf = buf.trim(); if (buf.length() == 0 || buf.startsWith("#")) continue; // parse the assignment if (buf.startsWith("$") || buf.startsWith("@")) { int spacePos = buf.indexOf(' '); int equalsPos = buf.indexOf('='); if (equalsPos < 0) { Job.getUserInterface().showErrorMessage("Missing '=' on line " + lineReader.getLineNumber(), "Syntax Error In Technology File"); break; } if (spacePos < 0) spacePos = equalsPos; else spacePos = Math.min(spacePos, equalsPos); String varName = buf.substring(1, spacePos); int semiPos = buf.indexOf(';'); if (semiPos < 0) { Job.getUserInterface().showErrorMessage("Missing ';' on line " + lineReader.getLineNumber(), "Syntax Error In Technology File"); break; } equalsPos++; while (equalsPos < semiPos && buf.charAt(equalsPos) == ' ') equalsPos++; String varValue = buf.substring(equalsPos, semiPos); // now figure out what to assign if (varName.equalsIgnoreCase("tech_libname")) { } else if (varName.equalsIgnoreCase("tech_name")) setTechName(stripQuotes(varValue)); else if (varName.equalsIgnoreCase("tech_description")) setTechDescription(stripQuotes(varValue)); else if (varName.equalsIgnoreCase("num_metal_layers")) setNumMetalLayers(TextUtils.atoi(varValue)); else if (varName.equalsIgnoreCase("stepsize")) setStepSize(TextUtils.atoi(varValue)); else if (varName.equalsIgnoreCase("diff_width")) diff_width.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("diff_width_rule")) diff_width.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("diff_poly_overhang")) diff_poly_overhang.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("diff_poly_overhang_rule")) diff_poly_overhang.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("diff_contact_overhang")) diff_contact_overhang.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("diff_contact_overhang_rule")) diff_contact_overhang.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("diff_spacing")) diff_spacing.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("diff_spacing_rule")) diff_spacing.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("poly_width")) poly_width.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("poly_width_rule")) poly_width.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("poly_endcap")) poly_endcap.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("poly_endcap_rule")) poly_endcap.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("poly_spacing")) poly_spacing.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("poly_spacing_rule")) poly_spacing.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("poly_diff_spacing")) poly_diff_spacing.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("poly_diff_spacing_rule")) poly_diff_spacing.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("gate_length")) gate_length.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("gate_length_rule")) gate_length.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("gate_width")) gate_width.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("gate_width_rule")) gate_width.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("gate_spacing")) gate_spacing.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("gate_spacing_rule")) gate_spacing.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("gate_contact_spacing")) gate_contact_spacing.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("gate_contact_spacing_rule")) gate_contact_spacing.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("contact_size")) contact_size.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("contact_size_rule")) contact_size.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("contact_spacing")) contact_spacing.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("contact_spacing_rule")) contact_spacing.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("contact_metal_overhang_inline_only")) contact_metal_overhang_inline_only.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("contact_metal_overhang_inline_only_rule")) contact_metal_overhang_inline_only.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("contact_metal_overhang_all_sides")) contact_metal_overhang_all_sides.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("contact_metal_overhang_all_sides_rule")) contact_metal_overhang_all_sides.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("contact_poly_overhang")) contact_poly_overhang.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("contact_poly_overhang_rule")) contact_poly_overhang.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("polycon_diff_spacing")) polycon_diff_spacing.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("polycon_diff_spacing_rule")) polycon_diff_spacing.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("nplus_width")) nplus_width.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("nplus_width_rule")) nplus_width.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("nplus_overhang_diff")) nplus_overhang_diff.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("nplus_overhang_diff_rule")) nplus_overhang_diff.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("nplus_spacing")) nplus_spacing.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("nplus_spacing_rule")) nplus_spacing.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("pplus_width")) pplus_width.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("pplus_width_rule")) pplus_width.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("pplus_overhang_diff")) pplus_overhang_diff.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("pplus_overhang_diff_rule")) pplus_overhang_diff.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("pplus_spacing")) pplus_spacing.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("pplus_spacing_rule")) pplus_spacing.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("nwell_width")) nwell_width.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("nwell_width_rule")) nwell_width.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("nwell_overhang_diff")) nwell_overhang_diff.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("nwell_overhang_diff_rule")) nwell_overhang_diff.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("nwell_spacing")) nwell_spacing.v = TextUtils.atof(varValue); else if (varName.equalsIgnoreCase("nwell_spacing_rule")) nwell_spacing.rule = stripQuotes(varValue); else if (varName.equalsIgnoreCase("metal_width")) fillWizardArray(varValue, metal_width, num_metal_layers, false); else if (varName.equalsIgnoreCase("metal_width_rule")) fillWizardArray(varValue, metal_width, num_metal_layers, true); else if (varName.equalsIgnoreCase("metal_spacing")) fillWizardArray(varValue, metal_spacing, num_metal_layers, false); else if (varName.equalsIgnoreCase("metal_spacing_rule")) fillWizardArray(varValue, metal_spacing, num_metal_layers, true); else if (varName.equalsIgnoreCase("via_size")) fillWizardArray(varValue, via_size, num_metal_layers-1, false); else if (varName.equalsIgnoreCase("via_size_rule")) fillWizardArray(varValue, via_size, num_metal_layers-1, true); else if (varName.equalsIgnoreCase("via_spacing")) fillWizardArray(varValue, via_spacing, num_metal_layers-1, false); else if (varName.equalsIgnoreCase("via_spacing_rule")) fillWizardArray(varValue, via_spacing, num_metal_layers-1, true); else if (varName.equalsIgnoreCase("via_array_spacing")) fillWizardArray(varValue, via_array_spacing, num_metal_layers-1, false); else if (varName.equalsIgnoreCase("via_array_spacing_rule")) fillWizardArray(varValue, via_array_spacing, num_metal_layers-1, true); else if (varName.equalsIgnoreCase("via_overhang_inline")) fillWizardArray(varValue, via_overhang_inline, num_metal_layers-1, false); else if (varName.equalsIgnoreCase("via_overhang_inline_rule")) fillWizardArray(varValue, via_overhang_inline, num_metal_layers-1, true); else if (varName.equalsIgnoreCase("poly_antenna_ratio")) setPolyAntennaRatio(TextUtils.atof(varValue)); else if (varName.equalsIgnoreCase("metal_antenna_ratio")) metal_antenna_ratio = makeDoubleArray(varValue); else if (varName.equalsIgnoreCase("gds_diff_layer")) setGDSDiff(TextUtils.atoi(varValue)); else if (varName.equalsIgnoreCase("gds_poly_layer")) setGDSPoly(TextUtils.atoi(varValue)); else if (varName.equalsIgnoreCase("gds_nplus_layer")) setGDSNPlus(TextUtils.atoi(varValue)); else if (varName.equalsIgnoreCase("gds_pplus_layer")) setGDSPPlus(TextUtils.atoi(varValue)); else if (varName.equalsIgnoreCase("gds_nwell_layer")) setGDSNWell(TextUtils.atoi(varValue)); else if (varName.equalsIgnoreCase("gds_contact_layer")) setGDSContact(TextUtils.atoi(varValue)); else if (varName.equalsIgnoreCase("gds_metal_layer")) gds_metal_layer = makeIntArray(varValue); else if (varName.equalsIgnoreCase("gds_via_layer")) gds_via_layer = makeIntArray(varValue); else if (varName.equalsIgnoreCase("gds_marking_layer")) setGDSMarking(TextUtils.atoi(varValue)); else { Job.getUserInterface().showErrorMessage("Unknown keyword '" + varName + "' on line " + lineReader.getLineNumber(), "Syntax Error In Technology File"); break; } } } lineReader.close(); } catch (IOException e) { System.out.println("Error reading " + fileName); return false; } return true; } private String stripQuotes(String str) { if (str.startsWith("\"") && str.endsWith("\"")) return str.substring(1, str.length()-1); return str; } private int [] makeIntArray(String str) { WizardField [] foundArray = new WizardField[num_metal_layers]; for(int i=0; i<num_metal_layers; i++) foundArray[i] = new WizardField(); fillWizardArray(str, foundArray, num_metal_layers, false); int [] retArray = new int[foundArray.length]; for(int i=0; i<foundArray.length; i++) retArray[i] = (int)foundArray[i].v; return retArray; } private double [] makeDoubleArray(String str) { WizardField [] foundArray = new WizardField[num_metal_layers]; for(int i=0; i<num_metal_layers; i++) foundArray[i] = new WizardField(); fillWizardArray(str, foundArray, num_metal_layers, false); double [] retArray = new double[foundArray.length]; for(int i=0; i<foundArray.length; i++) retArray[i] = foundArray[i].v; return retArray; } private void fillWizardArray(String str, WizardField [] fieldArray, int expectedLength, boolean getRule) { if (!str.startsWith("(")) { Job.getUserInterface().showErrorMessage("Array does not start with '(' on " + str, "Syntax Error In Technology File"); return; } int pos = 1; int index = 0; for(;;) { while (pos < str.length() && str.charAt(pos) == ' ') pos++; if (getRule) { if (str.charAt(pos) != '"') { Job.getUserInterface().showErrorMessage("Rule element does not start with quote on " + str, "Syntax Error In Technology File"); return; } pos++; int end = pos; while (end < str.length() && str.charAt(end) != '"') end++; if (str.charAt(end) != '"') { Job.getUserInterface().showErrorMessage("Rule element does not end with quote on " + str, "Syntax Error In Technology File"); return; } fieldArray[index++].rule = str.substring(pos, end); pos = end+1; } else { double v = TextUtils.atof(str.substring(pos)); fieldArray[index++].v = v; } while (pos < str.length() && str.charAt(pos) != ',' && str.charAt(pos) != ')') pos++; if (str.charAt(pos) != ',') break; pos++; } } /************************************** EXPORT RAW NUMBERS TO DISK **************************************/ public void exportData() { String fileName = OpenFile.chooseOutputFile(FileType.TEXT, "Technology Wizard File", "Technology.txt"); if (fileName == null) return; try { PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(fileName))); dumpNumbers(printWriter); printWriter.close(); } catch (IOException e) { System.out.println("Error writing XML file"); return; } } private void dumpNumbers(PrintWriter pw) { pw.println("#### Technology wizard data file"); pw.println("####"); pw.println("#### All dimensions in nanometers."); pw.println(); pw.println("$tech_name = \"" + tech_name + "\";"); pw.println("$tech_description = \"" + tech_description + "\";"); pw.println("$num_metal_layers = " + num_metal_layers + ";"); pw.println(); pw.println("## stepsize is minimum granularity that will be used as movement grid"); pw.println("## set to manufacturing grid or lowest common denominator with design rules"); pw.println("$stepsize = " + stepsize + ";"); pw.println(); pw.println("###### DIFFUSION RULES #####"); pw.println("$diff_width = " + TextUtils.formatDouble(diff_width.v) + ";"); pw.println("$diff_width_rule = \"" + diff_width.rule + "\";"); pw.println("$diff_poly_overhang = " + TextUtils.formatDouble(diff_poly_overhang.v) + "; # min. diff overhang from gate edge"); pw.println("$diff_poly_overhang_rule = \"" + diff_poly_overhang.rule + "\"; # min. diff overhang from gate edge"); pw.println("$diff_contact_overhang = " + TextUtils.formatDouble(diff_contact_overhang.v) + "; # min. diff overhang contact"); pw.println("$diff_contact_overhang_rule = \"" + diff_contact_overhang.rule + "\"; # min. diff overhang contact"); pw.println("$diff_spacing = " + TextUtils.formatDouble(diff_spacing.v) + ";"); pw.println("$diff_spacing_rule = \"" + diff_spacing.rule + "\";"); pw.println(); pw.println("###### POLY RULES #####"); pw.println("$poly_width = " + TextUtils.formatDouble(poly_width.v) + ";"); pw.println("$poly_width_rule = \"" + poly_width.rule + "\";"); pw.println("$poly_endcap = " + TextUtils.formatDouble(poly_endcap.v) + "; # min. poly gate extension from edge of diffusion"); pw.println("$poly_endcap_rule = \"" + poly_endcap.rule + "\"; # min. poly gate extension from edge of diffusion"); pw.println("$poly_spacing = " + TextUtils.formatDouble(poly_spacing.v) + ";"); pw.println("$poly_spacing_rule = \"" + poly_spacing.rule + "\";"); pw.println("$poly_diff_spacing = " + TextUtils.formatDouble(poly_diff_spacing.v) + "; # min. spacing between poly and diffusion"); pw.println("$poly_diff_spacing_rule = \"" + poly_diff_spacing.rule + "\"; # min. spacing between poly and diffusion"); pw.println(); pw.println("###### GATE RULES #####"); pw.println("$gate_length = " + TextUtils.formatDouble(gate_length.v) + "; # min. transistor gate length"); pw.println("$gate_length_rule = \"" + gate_length.rule + "\"; # min. transistor gate length"); pw.println("$gate_width = " + TextUtils.formatDouble(gate_width.v) + "; # min. transistor gate width"); pw.println("$gate_width_rule = \"" + gate_width.rule + "\"; # min. transistor gate width"); pw.println("$gate_spacing = " + TextUtils.formatDouble(gate_spacing.v) + "; # min. gate to gate spacing on diffusion"); pw.println("$gate_spacing_rule = \"" + gate_spacing.rule + "\"; # min. gate to gate spacing on diffusion"); pw.println("$gate_contact_spacing = " + TextUtils.formatDouble(gate_contact_spacing.v) + "; # min. spacing from gate edge to contact inside diffusion"); pw.println("$gate_contact_spacing_rule = \"" + gate_contact_spacing.rule + "\"; # min. spacing from gate edge to contact inside diffusion"); pw.println(); pw.println("###### CONTACT RULES #####"); pw.println("$contact_size = " + TextUtils.formatDouble(contact_size.v) + ";"); pw.println("$contact_size_rule = \"" + contact_size.rule + "\";"); pw.println("$contact_spacing = " + TextUtils.formatDouble(contact_spacing.v) + ";"); pw.println("$contact_spacing_rule = \"" + contact_spacing.rule + "\";"); pw.println("$contact_metal_overhang_inline_only = " + TextUtils.formatDouble(contact_metal_overhang_inline_only.v) + "; # metal overhang when overhanging contact from two sides only"); pw.println("$contact_metal_overhang_inline_only_rule = \"" + contact_metal_overhang_inline_only.rule + "\"; # metal overhang when overhanging contact from two sides only"); pw.println("$contact_metal_overhang_all_sides = " + TextUtils.formatDouble(contact_metal_overhang_all_sides.v) + "; # metal overhang when surrounding contact"); pw.println("$contact_metal_overhang_all_sides_rule = \"" + contact_metal_overhang_all_sides.rule + "\"; # metal overhang when surrounding contact"); pw.println("$contact_poly_overhang = " + TextUtils.formatDouble(contact_poly_overhang.v) + "; # poly overhang contact"); pw.println("$contact_poly_overhang_rule = \"" + contact_poly_overhang.rule + "\"; # poly overhang contact"); pw.println("$polycon_diff_spacing = " + TextUtils.formatDouble(polycon_diff_spacing.v) + "; # spacing between poly-metal contact edge and diffusion"); pw.println("$polycon_diff_spacing_rule = \"" + polycon_diff_spacing.rule + "\"; # spacing between poly-metal contact edge and diffusion"); pw.println(); pw.println("###### WELL AND IMPLANT RULES #####"); pw.println("$nplus_width = " + TextUtils.formatDouble(nplus_width.v) + ";"); pw.println("$nplus_width_rule = \"" + nplus_width.rule + "\";"); pw.println("$nplus_overhang_diff = " + TextUtils.formatDouble(nplus_overhang_diff.v) + ";"); pw.println("$nplus_overhang_diff_rule = \"" + nplus_overhang_diff.rule + "\";"); pw.println("$nplus_spacing = " + TextUtils.formatDouble(nplus_spacing.v) + ";"); pw.println("$nplus_spacing_rule = \"" + nplus_spacing.rule + "\";"); pw.println(); pw.println("$pplus_width = " + TextUtils.formatDouble(pplus_width.v) + ";"); pw.println("$pplus_width_rule = \"" + pplus_width.rule + "\";"); pw.println("$pplus_overhang_diff = " + TextUtils.formatDouble(pplus_overhang_diff.v) + ";"); pw.println("$pplus_overhang_diff_rule = \"" + pplus_overhang_diff.rule + "\";"); pw.println("$pplus_spacing = " + TextUtils.formatDouble(pplus_spacing.v) + ";"); pw.println("$pplus_spacing_rule = \"" + pplus_spacing.rule + "\";"); pw.println(); pw.println("$nwell_width = " + TextUtils.formatDouble(nwell_width.v) + ";"); pw.println("$nwell_width_rule = \"" + nwell_width.rule + "\";"); pw.println("$nwell_overhang_diff = " + TextUtils.formatDouble(nwell_overhang_diff.v) + ";"); pw.println("$nwell_overhang_diff_rule = \"" + nwell_overhang_diff.rule + "\";"); pw.println("$nwell_spacing = " + TextUtils.formatDouble(nwell_spacing.v) + ";"); pw.println("$nwell_spacing_rule = \"" + nwell_spacing.rule + "\";"); pw.println(); pw.println("###### METAL RULES #####"); pw.print("@metal_width = ("); for(int i=0; i<num_metal_layers; i++) { if (i > 0) pw.print(", "); pw.print(TextUtils.formatDouble(metal_width[i].v)); } pw.println(");"); pw.print("@metal_width_rule = ("); for(int i=0; i<num_metal_layers; i++) { if (i > 0) pw.print(", "); pw.print("\"" + metal_width[i].rule + "\""); } pw.println(");"); pw.print("@metal_spacing = ("); for(int i=0; i<num_metal_layers; i++) { if (i > 0) pw.print(", "); pw.print(TextUtils.formatDouble(metal_spacing[i].v)); } pw.println(");"); pw.print("@metal_spacing_rule = ("); for(int i=0; i<num_metal_layers; i++) { if (i > 0) pw.print(", "); pw.print("\"" + metal_spacing[i].rule + "\""); } pw.println(");"); pw.println(); pw.println("###### VIA RULES #####"); pw.print("@via_size = ("); for(int i=0; i<num_metal_layers-1; i++) { if (i > 0) pw.print(", "); pw.print(TextUtils.formatDouble(via_size[i].v)); } pw.println(");"); pw.print("@via_size_rule = ("); for(int i=0; i<num_metal_layers-1; i++) { if (i > 0) pw.print(", "); pw.print("\"" + via_size[i].rule + "\""); } pw.println(");"); pw.print("@via_spacing = ("); for(int i=0; i<num_metal_layers-1; i++) { if (i > 0) pw.print(", "); pw.print(TextUtils.formatDouble(via_spacing[i].v)); } pw.println(");"); pw.print("@via_spacing_rule = ("); for(int i=0; i<num_metal_layers-1; i++) { if (i > 0) pw.print(", "); pw.print("\"" + via_spacing[i].rule + "\""); } pw.println(");"); pw.println(); pw.println("## \"sep2d\" spacing, close proximity via array spacing"); pw.print("@via_array_spacing = ("); for(int i=0; i<num_metal_layers-1; i++) { if (i > 0) pw.print(", "); pw.print(TextUtils.formatDouble(via_array_spacing[i].v)); } pw.println(");"); pw.print("@via_array_spacing_rule = ("); for(int i=0; i<num_metal_layers-1; i++) { if (i > 0) pw.print(", "); pw.print("\"" + via_array_spacing[i].rule + "\""); } pw.println(");"); pw.print("@via_overhang_inline = ("); for(int i=0; i<num_metal_layers-1; i++) { if (i > 0) pw.print(", "); pw.print(TextUtils.formatDouble(via_overhang_inline[i].v)); } pw.println(");"); pw.print("@via_overhang_inline_rule = ("); for(int i=0; i<num_metal_layers-1; i++) { if (i > 0) pw.print(", "); pw.print("\"" + via_overhang_inline[i].rule + "\""); } pw.println(");"); pw.println(); pw.println("###### ANTENNA RULES #####"); pw.println("$poly_antenna_ratio = " + TextUtils.formatDouble(poly_antenna_ratio) + ";"); pw.print("@metal_antenna_ratio = ("); for(int i=0; i<num_metal_layers; i++) { if (i > 0) pw.print(", "); pw.print(TextUtils.formatDouble(metal_antenna_ratio[i])); } pw.println(");"); pw.println(); pw.println("###### GDS-II LAYERS #####"); pw.println("$gds_diff_layer = " + gds_diff_layer + ";"); pw.println("$gds_poly_layer = " + gds_poly_layer + ";"); pw.println("$gds_nplus_layer = " + gds_nplus_layer + ";"); pw.println("$gds_pplus_layer = " + gds_pplus_layer + ";"); pw.println("$gds_nwell_layer = " + gds_nwell_layer + ";"); pw.println("$gds_contact_layer = " + gds_contact_layer + ";"); pw.print("@gds_metal_layer = ("); for(int i=0; i<num_metal_layers; i++) { if (i > 0) pw.print(", "); pw.print(gds_metal_layer[i]); } pw.println(");"); pw.print("@gds_via_layer = ("); for(int i=0; i<num_metal_layers-1; i++) { if (i > 0) pw.print(", "); pw.print(gds_via_layer[i]); } pw.println(");"); pw.println(); pw.println("## Device marking layer"); pw.println("$gds_marking_layer = " + gds_marking_layer + ";"); pw.println(); pw.println("# End of techfile"); } /************************************** WRITE XML FILE **************************************/ public void writeXML() { String errorMessage = errorInData(); if (errorMessage != null) { Job.getUserInterface().showErrorMessage("ERROR: " + errorMessage, "Missing Technology Data"); return; } String fileName = OpenFile.chooseOutputFile(FileType.XML, "Technology XML File", "Technology.xml"); if (fileName == null) return; try { dumpXMLFile(fileName+"New"); PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(fileName))); dumpTechnology(printWriter); printWriter.close(); } catch (IOException e) { System.out.println("Error writing XML file"); return; } } /** * Method to create the XML version of a PrimitiveNode * @return */ private Xml.PrimitiveNode makeXmlPrimitive(List<Xml.PrimitiveNode> nodes, String name, PrimitiveNode.Function function, double width, double height, double ppLeft, double ppBottom, SizeOffset so, List<Xml.NodeLayer> nodeLayers, List<Xml.PrimitivePort> nodePorts, - PrimitiveNode.NodeSizeRule nodeSizeRule) + PrimitiveNode.NodeSizeRule nodeSizeRule, boolean isArcsShrink) { Xml.PrimitiveNode n = new Xml.PrimitiveNode(); - boolean isArcsShrink = true; n.name = name; n.function = function; n.shrinkArcs = isArcsShrink; // n.square = isSquare(); // n.canBeZeroSize = isCanBeZeroSize(); // n.wipes = isWipeOn1or2(); // n.lockable = isLockedPrim(); // n.edgeSelect = isEdgeSelect(); // n.skipSizeInPalette = isSkipSizeInPalette(); // n.notUsed = isNotUsed(); // n.lowVt = isNodeBitOn(PrimitiveNode.LOWVTBIT); // n.highVt = isNodeBitOn(PrimitiveNode.HIGHVTBIT); // n.nativeBit = isNodeBitOn(PrimitiveNode.NATIVEBIT); // n.od18 = isNodeBitOn(PrimitiveNode.OD18BIT); // n.od25 = isNodeBitOn(PrimitiveNode.OD25BIT); // n.od33 = isNodeBitOn(PrimitiveNode.OD33BIT); // PrimitiveNode.NodeSizeRule nodeSizeRule = getMinSizeRule(); // EPoint minFullSize = nodeSizeRule != null ? // EPoint.fromLambda(0.5*nodeSizeRule.getWidth(), 0.5*nodeSizeRule.getHeight()) : // EPoint.fromLambda(0.5*getDefWidth(), 0.5*getDefHeight()); EPoint minFullSize = EPoint.fromLambda(0.5*width, 0.5*height); EPoint topLeft = EPoint.fromLambda(ppLeft, ppBottom + height); EPoint size = EPoint.fromLambda(width, height); double getDefWidth = width, getDefHeight = height; if (function == PrimitiveNode.Function.PIN && isArcsShrink) { // assert getNumPorts() == 1; // assert nodeSizeRule == null; // PrimitivePort pp = getPort(0); // assert pp.getLeft().getMultiplier() == -0.5 && pp.getRight().getMultiplier() == 0.5 && pp.getBottom().getMultiplier() == -0.5 && pp.getTop().getMultiplier() == 0.5; // assert pp.getLeft().getAdder() == -pp.getRight().getAdder() && pp.getBottom().getAdder() == -pp.getTop().getAdder(); minFullSize = EPoint.fromLambda(ppLeft, ppBottom); } // DRCTemplate nodeSize = xmlRules.getRule(pnp.getPrimNodeIndexInTech(), DRCTemplate.DRCRuleType.NODSIZ); // SizeOffset so = getProtoSizeOffset(); if (so.getLowXOffset() == 0 && so.getHighXOffset() == 0 && so.getLowYOffset() == 0 && so.getHighYOffset() == 0) so = null; if (!minFullSize.equals(EPoint.ORIGIN)) /* n.diskOffset = minFullSize*/; // if (so != null) { // EPoint p2 = EPoint.fromGrid( // minFullSize.getGridX() - ((so.getLowXGridOffset() + so.getHighXGridOffset()) >> 1), // minFullSize.getGridY() - ((so.getLowYGridOffset() + so.getHighYGridOffset()) >> 1)); // n.diskOffset.put(Integer.valueOf(1), minFullSize); // n.diskOffset.put(Integer.valueOf(2), p2); // n.diskOffset.put(Integer.valueOf(2), minFullSize); // } // n.defaultWidth.addLambda(DBMath.round(getDefWidth)); // - 2*minFullSize.getLambdaX()); // n.defaultHeight.addLambda(DBMath.round(getDefHeight)); // - 2*minFullSize.getLambdaY()); ERectangle baseRectangle = ERectangle.fromGrid(topLeft.getGridX(), topLeft.getGridY(), size.getGridX(), size.getGridY()); /* n.nodeBase = baseRectangle;*/ // List<Technology.NodeLayer> nodeLayers = Arrays.asList(getLayers()); // List<Technology.NodeLayer> electricalNodeLayers = nodeLayers; // if (getElectricalLayers() != null) // electricalNodeLayers = Arrays.asList(getElectricalLayers()); boolean isSerp = false; //getSpecialType() == PrimitiveNode.SERPTRANS; if (nodeLayers != null) n.nodeLayers.addAll(nodeLayers); // int m = 0; // for (Technology.NodeLayer nld: electricalNodeLayers) { // int j = nodeLayers.indexOf(nld); // if (j < 0) { // n.nodeLayers.add(nld.makeXml(isSerp, minFullSize, false, true)); // continue; // } // while (m < j) // n.nodeLayers.add(nodeLayers.get(m++).makeXml(isSerp, minFullSize, true, false)); // n.nodeLayers.add(nodeLayers.get(m++).makeXml(isSerp, minFullSize, true, true)); // } // while (m < nodeLayers.size()) // n.nodeLayers.add(nodeLayers.get(m++).makeXml(isSerp, minFullSize, true, false)); // for (Iterator<PrimitivePort> pit = getPrimitivePorts(); pit.hasNext(); ) { // PrimitivePort pp = pit.next(); // n.ports.add(pp.makeXml(minFullSize)); // } n.specialType = PrimitiveNode.NORMAL; // getSpecialType(); // if (getSpecialValues() != null) // n.specialValues = getSpecialValues().clone(); if (nodeSizeRule != null) { n.nodeSizeRule = new Xml.NodeSizeRule(); n.nodeSizeRule.width = nodeSizeRule.getWidth(); n.nodeSizeRule.height = nodeSizeRule.getHeight(); n.nodeSizeRule.rule = nodeSizeRule.getRuleName(); } // n.spiceTemplate = "";//getSpiceTemplate(); // ports n.ports.addAll(nodePorts); nodes.add(n); return n; } /** * Method to create the XML version of a ArcProto * @param name * @param function * @return */ private Xml.ArcProto makeXmlArc(List<Xml.ArcProto> arcs, String name, com.sun.electric.technology.ArcProto.Function function, double ant, Xml.ArcLayer ... arcLayers) { Xml.ArcProto a = new Xml.ArcProto(); a.name = name; a.function = function; a.wipable = true; // a.curvable = false; // a.special = false; // a.notUsed = false; // a.skipSizeInPalette = false; // a.elibWidthOffset = getLambdaElibWidthOffset(); a.extended = true; a.fixedAngle = true; a.angleIncrement = 90; a.antennaRatio = DBMath.round(ant); for (Xml.ArcLayer al: arcLayers) a.arcLayers.add(al); /* // arc pins a.arcPin = new Xml.ArcPin(); a.arcPin.name = name + "-Pin"; //arcPin.getName(); // PrimitivePort port = arcPin.getPort(0); a.arcPin.portName = name; //port.getName(); a.arcPin.elibSize = 0; // 2*arcPin.getSizeCorrector(0).getX(); // for (ArcProto cap: port.getConnections()) { // if (cap.getTechnology() == tech && cap != this) // a.arcPin.portArcs.add(cap.getName()); // } */ arcs.add(a); return a; } /** * Method to create the XML version of a Layer. * @return */ private Xml.Layer makeXmlLayer(List<Xml.Layer> layers, Map<Xml.Layer,WizardField> layer_width, String name, Layer.Function function, int extraf, EGraphics graph, char cifLetter, WizardField width, boolean pureLayerNode) { Xml.Layer l = new Xml.Layer(); l.name = name; l.function = function; l.extraFunction = extraf; l.desc = graph; l.thick3D = 1; l.height3D = 1; l.mode3D = "NONE"; l.factor3D = 1; l.cif = "C" + cifLetter + cifLetter; l.skill = name; l.resistance = 1; l.capacitance = 0; l.edgeCapacitance = 0; // if (layer.getPseudoLayer() != null) // l.pseudoLayer = layer.getPseudoLayer().getName(); if (pureLayerNode) { l.pureLayerNode = new Xml.PureLayerNode(); l.pureLayerNode.name = name + "-Node"; l.pureLayerNode.style = Poly.Type.FILLED; l.pureLayerNode.size.addLambda(scaledValue(width.v)); l.pureLayerNode.port = "Port_" + name; /* l.pureLayerNode.size.addRule(width.rule, 1);*/ l.pureLayerNode.portArcs.add(name); // for (ArcProto ap: pureLayerNode.getPort(0).getConnections()) { // if (ap.getTechnology() != tech) continue; // l.pureLayerNode.portArcs.add(ap.getName()); // } } layers.add(l); layer_width.put(l, width); return l; } /** * Method to create the XML version of NodeLayer * @param hla * @param lb * @param style */ private Xml.NodeLayer makeXmlNodeLayer(double hla, Xml.Layer lb, Poly.Type style) { Xml.NodeLayer nl = new Xml.NodeLayer(); nl.layer = lb.name; nl.style = style; nl.inLayers = nl.inElectricalLayers = true; nl.representation = Technology.NodeLayer.BOX; nl.lx.k = -1; nl.hx.k = 1; nl.ly.k = -1; nl.hy.k = 1; nl.lx.addLambda(-hla); nl.hx.addLambda(hla); nl.ly.addLambda(-hla); nl.hy.addLambda(hla); return nl; } private Xml.NodeLayer makeXmlMulticut(double hla, Xml.Layer lb, WizardField sizeRule, WizardField sepRule, WizardField sepRule2D) { Xml.NodeLayer nl = new Xml.NodeLayer(); nl.layer = lb.name; nl.style = Poly.Type.FILLED; nl.inLayers = nl.inElectricalLayers = true; nl.representation = Technology.NodeLayer.MULTICUTBOX; nl.lx.k = -1; nl.hx.k = 1; nl.ly.k = -1; nl.hy.k = 1; // nl.sizeRule = sizeRule; nl.sizex = scaledValue(sizeRule.v); nl.sizey = scaledValue(sizeRule.v); nl.sep1d = scaledValue(sepRule.v); nl.sep2d = scaledValue(sepRule2D.v); return nl; } /** * Method to create the XML versio nof PrimitivePort * @param name * @param portAngle * @param portRange * @param portTopology * @param minFullSize * @param leftRight * @param bottomTop * @param portArcs * @return */ private Xml.PrimitivePort makeXmlPrimitivePort(String name, int portAngle, int portRange, int portTopology, EPoint minFullSize, double leftRight, double bottomTop, List<String> portArcs) { Xml.PrimitivePort ppd = new Xml.PrimitivePort(); ppd.name = name; ppd.portAngle = portAngle; ppd.portRange = portRange; ppd.portTopology = portTopology; ppd.lx.k = -1; //getLeft().getMultiplier()*2; ppd.lx.addLambda(DBMath.round(leftRight + minFullSize.getLambdaX()*ppd.lx.k)); ppd.hx.k = 1; //getRight().getMultiplier()*2; ppd.hx.addLambda(DBMath.round(leftRight + minFullSize.getLambdaX()*ppd.hx.k)); ppd.ly.k = -1; // getBottom().getMultiplier()*2; ppd.ly.addLambda(DBMath.round(bottomTop + minFullSize.getLambdaY()*ppd.ly.k)); ppd.hy.k = 1; // getTop().getMultiplier()*2; ppd.hy.addLambda(DBMath.round(bottomTop + minFullSize.getLambdaY()*ppd.hy.k)); if (portArcs != null) { for (String s: portArcs) { ppd.portArcs.add(s); } } return ppd; } private void dumpXMLFile(String fileName) throws IOException { Xml.Technology t = new Xml.Technology(); t.techName = getTechName(); t.shortTechName = getTechName(); t.description = getTechDescription(); t.minNumMetals = t.maxNumMetals = t.defaultNumMetals = getNumMetalLayers(); t.scaleValue = getStepSize(); t.scaleRelevant = true; // t.scaleRelevant = isScaleRelevant(); t.defaultFoundry = "NONE"; t.minResistance = 1.0; t.minCapacitance = 0.1; // LAYER COLOURS Color [] metal_colour = new Color[] { new Color(0,150,255), // cyan/blue new Color(148,0,211), // purple new Color(255,215,0), // yellow new Color(132,112,255), // mauve new Color(255,160,122), // salmon new Color(34,139,34), // dull green new Color(178,34,34), // dull red new Color(34,34,178), // dull blue new Color(153,153,153), // light gray new Color(102,102,102) // dark gray }; Color poly_colour = new Color(255,155,192); // pink Color diff_colour = new Color(107,226,96); // light green Color via_colour = new Color(205,205,205); // lighter gray Color contact_colour = new Color(40,40,40); // darker gray Color nplus_colour = new Color(224,238,224); Color pplus_colour = new Color(224,224,120); Color nwell_colour = new Color(140,140,140); // Five transparent colors: poly_colour, diff_colour, metal_colour[0->2] Color[] colorMap = {poly_colour, diff_colour, metal_colour[0], metal_colour[1], metal_colour[2]}; for (int i = 0; i < colorMap.length; i++) { Color transparentColor = colorMap[i]; t.transparentLayers.add(transparentColor); } // Layers List<Xml.Layer> metalLayers = new ArrayList<Xml.Layer>(); List<Xml.Layer> viaLayers = new ArrayList<Xml.Layer>(); Map<Xml.Layer,WizardField> layer_width = new LinkedHashMap<Xml.Layer,WizardField>(); int[] nullPattern = new int[] {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}; int cifNumber = 0; for (int i = 0; i < num_metal_layers; i++) { // Adding the metal int metalNum = i + 1; double opacity = (75 - metalNum * 5)/100.0; int metLayHigh = i / 10; int metLayDig = i % 10; int r = metal_colour[metLayDig].getRed() * (10-metLayHigh) / 10; int g = metal_colour[metLayDig].getGreen() * (10-metLayHigh) / 10; int b = metal_colour[metLayDig].getBlue() * (10-metLayHigh) / 10; int tcol = 0; int[] pattern = null; switch (metLayDig) { case 0: tcol = 3; break; case 1: tcol = 4; break; case 2: tcol = 5; break; case 3: pattern = new int[] {0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000}; break; case 4: pattern = new int[] { 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444, // X X X X 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444, // X X X X 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444, // X X X X 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444}; break; case 5: pattern = new int[] { 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555}; break; case 6: pattern = new int[] { 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111, // X X X X 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111, // X X X X 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111, // X X X X 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111}; break; case 7: pattern = new int[] { 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000}; break; case 8: pattern = new int[] {0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888}; // X X X X break; case 9: pattern = new int[] { 0x5555, // X X X X X X X X 0x5555, // X X X X X X X X 0x5555, // X X X X X X X X 0x5555, // X X X X X X X X 0x5555, // X X X X X X X X 0x5555, // X X X X X X X X 0x5555, // X X X X X X X X 0x5555, // X X X X X X X X 0x5555, // X X X X X X X X 0x5555, // X X X X X X X X 0x5555, // X X X X X X X X 0x5555, // X X X X X X X X 0x5555, // X X X X X X X X 0x5555, // X X X X X X X X 0x5555, // X X X X X X X X 0x5555}; break; } boolean onDisplay = true, onPrinter = true; if (pattern == null) { pattern = nullPattern; onDisplay = false; onPrinter = false; } EGraphics graph = new EGraphics(onDisplay, onPrinter, null, tcol, r, g, b, opacity, true, pattern); Layer.Function fun = Layer.Function.getMetal(metalNum); if (fun == null) throw new IOException("invalid number of metals"); Xml.Layer layer = makeXmlLayer(t.layers, layer_width, "Metal-"+metalNum, fun, 0, graph, (char)('A' + cifNumber++), metal_width[i], true); metalLayers.add(layer); } for (int i = 0; i < num_metal_layers - 1; i++) { // Adding the metal int metalNum = i + 1; // adding the via int r = via_colour.getRed(); int g = via_colour.getGreen(); int b = via_colour.getBlue(); double opacity = 0.7; EGraphics graph = new EGraphics(false, false, null, 0, r, g, b, opacity, true, nullPattern); Layer.Function fun = Layer.Function.getContact(metalNum); if (fun == null) throw new IOException("invalid number of vias"); viaLayers.add(makeXmlLayer(t.layers, layer_width, "Via-"+metalNum, fun, Layer.Function.CONMETAL, graph, (char)('A' + cifNumber++), via_size[i], false)); } // Poly EGraphics graph = new EGraphics(false, false, null, 1, 0, 0, 0, 1, true, nullPattern); Xml.Layer polyLayer = makeXmlLayer(t.layers, layer_width, "Poly", Layer.Function.POLY1, 0, graph, (char)('A' + cifNumber++), poly_width, true); // PolyGate makeXmlLayer(t.layers, layer_width, "PolyGate", Layer.Function.GATE, 0, graph, (char)('A' + cifNumber++), poly_width, false); // PolyCon and DiffCon graph = new EGraphics(false, false, null, 0, contact_colour.getRed(), contact_colour.getGreen(), contact_colour.getBlue(), 1, true, nullPattern); // PolyCon makeXmlLayer(t.layers, layer_width, "PolyCon", Layer.Function.CONTACT1, Layer.Function.CONPOLY, graph, (char)('A' + cifNumber++), contact_size, false); // DiffCon makeXmlLayer(t.layers, layer_width, "DiffCon", Layer.Function.CONTACT1, Layer.Function.CONDIFF, graph, (char)('A' + cifNumber++), contact_size, false); // P-Diff and N-Diff graph = new EGraphics(false, false, null, 2, 0, 0, 0, 1, true, nullPattern); // N-Diff Xml.Layer diffNLayer = makeXmlLayer(t.layers, layer_width, "N-Diff", Layer.Function.DIFFN, 0, graph, (char)('A' + cifNumber++), diff_width, true); // P-Diff Xml.Layer diffPLayer = makeXmlLayer(t.layers, layer_width, "P-Diff", Layer.Function.DIFFP, 0, graph, (char)('A' + cifNumber++), diff_width, true); // NPlus and PPlus int [] pattern = new int[] { 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808, // X X 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808}; // NPlus graph = new EGraphics(true, true, null, 0, nplus_colour.getRed(), nplus_colour.getGreen(), nplus_colour.getBlue(), 1, true, pattern); Xml.Layer nplusLayer = makeXmlLayer(t.layers, layer_width, "NPlus", com.sun.electric.technology.Layer.Function.IMPLANTN, 0, graph, (char)('A' + cifNumber++), nplus_width, false); // PPlus graph = new EGraphics(true, true, null, 0, pplus_colour.getRed(), pplus_colour.getGreen(), pplus_colour.getBlue(), 1, true, pattern); Xml.Layer pplusLayer = makeXmlLayer(t.layers, layer_width, "PPlus", Layer.Function.IMPLANTP, 0, graph, (char)('A' + cifNumber++), pplus_width, false); // layers.add("N-Well"); pattern = new int[] { 0x0202, // X X 0x0101, // X X 0x8080, // X X 0x4040, // X X 0x2020, // X X 0x1010, // X X 0x0808, // X X 0x0404, // X X 0x0202, // X X 0x0101, // X X 0x8080, // X X 0x4040, // X X 0x2020, // X X 0x1010, // X X 0x0808, // X X 0x0404}; graph = new EGraphics(true, true, null, 0, nwell_colour.getRed(), nwell_colour.getGreen(), nwell_colour.getBlue(), 1, true, pattern); Xml.Layer nwellLayer = makeXmlLayer(t.layers, layer_width, "N-Well", Layer.Function.WELLN, 0, graph, (char)('A' + cifNumber++), nwell_width, false); // layers.add("DeviceMark"); graph = new EGraphics(true, true, null, 0, 255, 0, 0, 0.4, true, nullPattern); // N-Diff makeXmlLayer(t.layers, layer_width, "DeviceMark", Layer.Function.CONTROL, 0, graph, (char)('A' + cifNumber++), nplus_width, false); // write arcs // metal arcs for(int i=1; i<=num_metal_layers; i++) { double ant = (int)Math.round(metal_antenna_ratio[i-1]) | 200; makeXmlArc(t.arcs, "Metal-"+i, ArcProto.Function.getContact(i), ant, makeXmlArcLayer(metalLayers.get(i-1), metal_width[i-1])); } // poly arc double ant = (int)Math.round(poly_antenna_ratio) | 200; makeXmlArc(t.arcs, "Poly", ArcProto.Function.getPoly(1), ant, makeXmlArcLayer(polyLayer, poly_width)); // NDiff/PDiff makeXmlArc(t.arcs, "N-Diff", ArcProto.Function.DIFFN, 0, makeXmlArcLayer(diffNLayer, diff_width), makeXmlArcLayer(nplusLayer, diff_width, nplus_overhang_diff)); makeXmlArc(t.arcs, "P-Diff", ArcProto.Function.DIFFP, 0, makeXmlArcLayer(diffPLayer, diff_width), makeXmlArcLayer(pplusLayer, diff_width, pplus_overhang_diff), makeXmlArcLayer(nwellLayer, diff_width, nwell_overhang_diff)); // Pins and contacts List<Xml.NodeLayer> nodesList = new ArrayList<Xml.NodeLayer>(); List<Xml.PrimitivePort> nodePorts = new ArrayList<Xml.PrimitivePort>(); List<String> portNames = new ArrayList<String>(); for(int i=1; i<num_metal_layers; i++) { -// double hla = DBMath.round(metal_width[i-1].v / (stepsize*2)); double hla = scaledValue(metal_width[i-1].v / 2); Xml.Layer lb = metalLayers.get(i-1); // Pin bottom metal nodePorts.clear(); nodesList.clear(); portNames.clear(); nodesList.add(makeXmlNodeLayer(hla, lb, Poly.Type.CROSSED)); // pin bottom metal EPoint minFullSize = EPoint.fromLambda(0, 0); portNames.add(lb.name); nodePorts.add(makeXmlPrimitivePort(lb.name.toLowerCase(), 0, 180, 0, minFullSize, 0, 0, portNames)); makeXmlPrimitive(t.nodes, lb.name + "-Pin", PrimitiveNode.Function.PIN, hla, hla, 0, 0, new SizeOffset(hla, hla, hla, hla), - nodesList, nodePorts, null); + nodesList, nodePorts, null, true); // Contact Square nodePorts.clear(); nodesList.clear(); double metalW = via_size[i-1].v/2 + contact_metal_overhang_all_sides.v; hla = scaledValue(metalW); nodesList.add(makeXmlNodeLayer(hla, lb, Poly.Type.FILLED)); // bottom layer Xml.Layer lt = metalLayers.get(i); nodesList.add(makeXmlNodeLayer(hla, lt, Poly.Type.FILLED)); // top layer // via Xml.Layer via = viaLayers.get(i-1); nodesList.add(makeXmlMulticut(hla, via, via_size[i-1], via_spacing[i-1], via_array_spacing[i-1])); // via String name = lb.name + "-" + lt.name; // port minFullSize = EPoint.fromLambda(0, 0); portNames.add(lt.name); Xml.PrimitivePort pp = makeXmlPrimitivePort(name.toLowerCase(), 0, 180, 0, minFullSize, 0, 0, portNames); nodePorts.add(pp); // Square contacts makeXmlPrimitive(t.nodes, name + "-Con", PrimitiveNode.Function.CONTACT, hla, hla, 0, 0, new SizeOffset(hla, hla, hla, hla), - nodesList, nodePorts, null); + nodesList, nodePorts, null, false); } Xml.Foundry f = new Xml.Foundry(); f.name = Foundry.Type.NONE.name(); t.foundries.add(f); makeLayerRuleMinWid(t, diffPLayer, diff_width); makeLayerRuleMinWid(t, diffNLayer, diff_width); makeLayerRuleMinWid(t, pplusLayer, pplus_width); makeLayersRuleSurround(t, pplusLayer, diffPLayer, pplus_overhang_diff); makeLayerRuleMinWid(t, nplusLayer, nplus_width); makeLayersRuleSurround(t, nplusLayer, diffNLayer, nplus_overhang_diff); makeLayerRuleMinWid(t, nwellLayer, nwell_width); makeLayersRuleSurround(t, nwellLayer, diffPLayer, nwell_overhang_diff); makeLayerRuleMinWid(t, polyLayer, poly_width); for (int i = 0; i < num_metal_layers; i++) { Xml.Layer met = metalLayers.get(i); makeLayerRuleMinWid(t, met, metal_width[i]); if (i >= num_metal_layers - 1) continue; Xml.Layer via = viaLayers.get(i); makeLayerRuleMinWid(t, via, via_size[i]); makeLayersRule(t, via, DRCTemplate.DRCRuleType.CONSPA, via_spacing[i]); makeLayersRule(t, via, DRCTemplate.DRCRuleType.UCONSPA2D, via_array_spacing[i]); } // write finally the file t.writeXml(fileName); } private Xml.ArcLayer makeXmlArcLayer(Xml.Layer layer, WizardField ... flds) { Xml.ArcLayer al = new Xml.ArcLayer(); al.layer = layer.name; al.style = Poly.Type.FILLED; for (int i = 0; i < flds.length; i++) al.extend.addLambda(scaledValue(flds[i].v/2)); return al; } private Technology.Distance makeXmlDistance(WizardField ... flds) { Technology.Distance dist = new Technology.Distance(); dist.addRule(flds[0].rule, 0.5); for (int i = 1; i < flds.length; i++) dist.addRule(flds[i].rule, 1); return dist; } private void makeLayerRuleMinWid(Xml.Technology t, Xml.Layer l, WizardField fld) { for (Xml.Foundry f: t.foundries) { f.rules.add(new DRCTemplate(fld.rule, DRCTemplate.DRCMode.ALL.mode(), DRCTemplate.DRCRuleType.MINWID, l.name, null, new double[] {scaledValue(fld.v)}, null, null)); } } private void makeLayersRule(Xml.Technology t, Xml.Layer l, DRCTemplate.DRCRuleType ruleType, WizardField fld) { for (Xml.Foundry f: t.foundries) { f.rules.add(new DRCTemplate(fld.rule, DRCTemplate.DRCMode.ALL.mode(), ruleType, l.name, l.name, new double[] {scaledValue(fld.v)}, null, null)); } } private void makeLayersRuleSurround(Xml.Technology t, Xml.Layer l1, Xml.Layer l2, WizardField fld) { double value = scaledValue(fld.v); for (Xml.Foundry f: t.foundries) { f.rules.add(new DRCTemplate(fld.rule, DRCTemplate.DRCMode.ALL.mode(), DRCTemplate.DRCRuleType.SURROUND, l1.name, l2.name, new double[] {value, value}, null, null)); } } private void dumpTechnology(PrintWriter pw) { // LAYER COLOURS Color [] metal_colour = new Color[] { new Color(0,150,255), // cyan/blue new Color(148,0,211), // purple new Color(255,215,0), // yellow new Color(132,112,255), // mauve new Color(255,160,122), // salmon new Color(34,139,34), // dull green new Color(178,34,34), // dull red new Color(34,34,178), // dull blue new Color(153,153,153), // light gray new Color(102,102,102) // dark gray }; Color poly_colour = new Color(255,155,192); // pink Color diff_colour = new Color(107,226,96); // light green Color via_colour = new Color(205,205,205); // lighter gray Color contact_colour = new Color(40,40,40); // darker gray Color nplus_colour = new Color(224,238,224); Color pplus_colour = new Color(224,224,120); Color nwell_colour = new Color(140,140,140); // write the header String foundry_name = "NONE"; pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); pw.println(); pw.println("<!--"); pw.println(" *"); pw.println(" * Electric technology file for process \"" + tech_name + "\""); pw.println(" *"); pw.println(" * Automatically generated by Electric's technology wizard"); pw.println(" *"); pw.println("-->"); pw.println(); pw.println("<technology name=\"" + tech_name + "\""); pw.println(" xmlns=\"http://electric.sun.com/Technology\""); pw.println(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""); pw.println(" xsi:schemaLocation=\"http://electric.sun.com/Technology ../../technology/Technology.xsd\">"); pw.println(); pw.println(" <shortName>" + tech_name + "</shortName>"); pw.println(" <description>" + tech_description + "</description>"); pw.println(" <numMetals min=\"" + num_metal_layers + "\" max=\"" + num_metal_layers + "\" default=\"" + num_metal_layers + "\"/>"); pw.println(" <scale value=\"" + floaty(stepsize) + "\" relevant=\"true\"/>"); pw.println(" <defaultFoundry value=\"" + foundry_name + "\"/>"); pw.println(" <minResistance value=\"1.0\"/>"); pw.println(" <minCapacitance value=\"0.1\"/>"); pw.println(); // write the transparent layer colors int li = 1; pw.println(" <!-- Transparent layers -->"); pw.println(" <transparentLayer transparent=\"" + (li++) + "\">"); pw.println(" <r>" + poly_colour.getRed() + "</r>"); pw.println(" <g>" + poly_colour.getGreen() + "</g>"); pw.println(" <b>" + poly_colour.getBlue() + "</b>"); pw.println(" </transparentLayer>"); pw.println(" <transparentLayer transparent=\"" + (li++) + "\">"); pw.println(" <r>" + diff_colour.getRed() + "</r>"); pw.println(" <g>" + diff_colour.getGreen() + "</g>"); pw.println(" <b>" + diff_colour.getBlue() + "</b>"); pw.println(" </transparentLayer>"); pw.println(" <transparentLayer transparent=\"" + (li++) + "\">"); pw.println(" <r>" + metal_colour[0].getRed() + "</r>"); pw.println(" <g>" + metal_colour[0].getGreen() + "</g>"); pw.println(" <b>" + metal_colour[0].getBlue() + "</b>"); pw.println(" </transparentLayer>"); pw.println(" <transparentLayer transparent=\"" + (li++) + "\">"); pw.println(" <r>" + metal_colour[1].getRed() + "</r>"); pw.println(" <g>" + metal_colour[1].getGreen() + "</g>"); pw.println(" <b>" + metal_colour[1].getBlue() + "</b>"); pw.println(" </transparentLayer>"); pw.println(" <transparentLayer transparent=\"" + (li++) + "\">"); pw.println(" <r>" + metal_colour[2].getRed() + "</r>"); pw.println(" <g>" + metal_colour[2].getGreen() + "</g>"); pw.println(" <b>" + metal_colour[2].getBlue() + "</b>"); pw.println(" </transparentLayer>"); // write the layers pw.println(); pw.println("<!-- LAYERS -->"); List<String> layers = new ArrayList<String>(); for(int i=1; i<=num_metal_layers; i++) layers.add("Metal-"+i); for(int i=1; i<=num_metal_layers-1; i++) layers.add("Via-"+i); layers.add("Poly"); layers.add("PolyGate"); layers.add("PolyCon"); layers.add("DiffCon"); layers.add("N-Diff"); layers.add("P-Diff"); layers.add("NPlus"); layers.add("PPlus"); layers.add("N-Well"); layers.add("DeviceMark"); for(int i=0; i<layers.size(); i++) { String l = layers.get(i); int tcol = 0; String fun = ""; String extrafun = ""; int r = 255; int g = 0; int b = 0; double opacity = 0.4; double la = -1; String pat = null; if (l.startsWith("Metal")) { int metLay = TextUtils.atoi(l.substring(6)); int metLayDig = (metLay-1) % 10; switch (metLayDig) { case 0: tcol = 3; break; case 1: tcol = 4; break; case 2: tcol = 5; break; case 3: pat=" <pattern>XXXXXXXXXXXXXXXX</pattern>\n" + " <pattern> </pattern>\n" + " <pattern>XXXXXXXXXXXXXXXX</pattern>\n" + " <pattern> </pattern>\n" + " <pattern>XXXXXXXXXXXXXXXX</pattern>\n" + " <pattern> </pattern>\n" + " <pattern>XXXXXXXXXXXXXXXX</pattern>\n" + " <pattern> </pattern>\n" + " <pattern>XXXXXXXXXXXXXXXX</pattern>\n" + " <pattern> </pattern>\n" + " <pattern>XXXXXXXXXXXXXXXX</pattern>\n" + " <pattern> </pattern>\n" + " <pattern>XXXXXXXXXXXXXXXX</pattern>\n" + " <pattern> </pattern>\n" + " <pattern>XXXXXXXXXXXXXXXX</pattern>\n" + " <pattern> </pattern>"; break; case 4: pat=" <pattern>X X X X </pattern>\n" + " <pattern> X X X X</pattern>\n" + " <pattern> X X X X </pattern>\n" + " <pattern> X X X X </pattern>\n" + " <pattern>X X X X </pattern>\n" + " <pattern> X X X X</pattern>\n" + " <pattern> X X X X </pattern>\n" + " <pattern> X X X X </pattern>\n" + " <pattern>X X X X </pattern>\n" + " <pattern> X X X X</pattern>\n" + " <pattern> X X X X </pattern>\n" + " <pattern> X X X X </pattern>\n" + " <pattern>X X X X </pattern>\n" + " <pattern> X X X X</pattern>\n" + " <pattern> X X X X </pattern>\n" + " <pattern> X X X X </pattern>"; break; case 5: pat=" <pattern> X X X X</pattern>\n" + " <pattern>XXXXXXXXXXXXXXXX</pattern>\n" + " <pattern> X X X X</pattern>\n" + " <pattern> X X X X X X X X</pattern>\n" + " <pattern> X X X X</pattern>\n" + " <pattern>XXXXXXXXXXXXXXXX</pattern>\n" + " <pattern> X X X X</pattern>\n" + " <pattern> X X X X X X X X</pattern>\n" + " <pattern> X X X X</pattern>\n" + " <pattern>XXXXXXXXXXXXXXXX</pattern>\n" + " <pattern> X X X X</pattern>\n" + " <pattern> X X X X X X X X</pattern>\n" + " <pattern> X X X X</pattern>\n" + " <pattern>XXXXXXXXXXXXXXXX</pattern>\n" + " <pattern> X X X X</pattern>\n" + " <pattern> X X X X X X X X</pattern>"; break; case 6: pat=" <pattern>X X X X </pattern>\n" + " <pattern> X X X X </pattern>\n" + " <pattern> X X X X </pattern>\n" + " <pattern> X X X X</pattern>\n" + " <pattern>X X X X </pattern>\n" + " <pattern> X X X X </pattern>\n" + " <pattern> X X X X </pattern>\n" + " <pattern> X X X X</pattern>\n" + " <pattern>X X X X </pattern>\n" + " <pattern> X X X X </pattern>\n" + " <pattern> X X X X </pattern>\n" + " <pattern> X X X X</pattern>\n" + " <pattern>X X X X </pattern>\n" + " <pattern> X X X X </pattern>\n" + " <pattern> X X X X </pattern>\n" + " <pattern> X X X X</pattern>"; break; case 7: pat=" <pattern> X X X X </pattern>\n" + " <pattern> </pattern>\n" + " <pattern>X X X X </pattern>\n" + " <pattern> </pattern>\n" + " <pattern> X X X X </pattern>\n" + " <pattern> </pattern>\n" + " <pattern>X X X X </pattern>\n" + " <pattern> </pattern>\n" + " <pattern> X X X X </pattern>\n" + " <pattern> </pattern>\n" + " <pattern>X X X X </pattern>\n" + " <pattern> </pattern>\n" + " <pattern> X X X X </pattern>\n" + " <pattern> </pattern>\n" + " <pattern>X X X X </pattern>\n" + " <pattern> </pattern>"; break; case 8: pat=" <pattern> </pattern>\n" + " <pattern> X X X X </pattern>\n" + " <pattern> </pattern>\n" + " <pattern>X X X X </pattern>\n" + " <pattern> </pattern>\n" + " <pattern> X X X X </pattern>\n" + " <pattern> </pattern>\n" + " <pattern>X X X X </pattern>\n" + " <pattern> </pattern>\n" + " <pattern> X X X X </pattern>\n" + " <pattern> </pattern>\n" + " <pattern>X X X X </pattern>\n" + " <pattern> </pattern>\n" + " <pattern> X X X X </pattern>\n" + " <pattern> </pattern>\n" + " <pattern>X X X X </pattern>"; break; case 9: pat=" <pattern>X X X X X X X X </pattern>\n" + " <pattern>X X X X X X X X </pattern>\n" + " <pattern>X X X X X X X X </pattern>\n" + " <pattern>X X X X X X X X </pattern>\n" + " <pattern>X X X X X X X X </pattern>\n" + " <pattern>X X X X X X X X </pattern>\n" + " <pattern>X X X X X X X X </pattern>\n" + " <pattern>X X X X X X X X </pattern>\n" + " <pattern>X X X X X X X X </pattern>\n" + " <pattern>X X X X X X X X </pattern>\n" + " <pattern>X X X X X X X X </pattern>\n" + " <pattern>X X X X X X X X </pattern>\n" + " <pattern>X X X X X X X X </pattern>\n" + " <pattern>X X X X X X X X </pattern>\n" + " <pattern>X X X X X X X X </pattern>\n" + " <pattern>X X X X X X X X </pattern>"; break; } fun = "METAL" + metLay; int metLayHigh = (metLay-1) / 10; r = metal_colour[metLayDig].getRed() * (10-metLayHigh) / 10; g = metal_colour[metLayDig].getGreen() * (10-metLayHigh) / 10; b = metal_colour[metLayDig].getBlue() * (10-metLayHigh) / 10; opacity = (75 - metLay * 5)/100.0; la = metal_width[metLay-1].v / stepsize; } if (l.startsWith("Via")) { int viaLay = TextUtils.atoi(l.substring(4)); fun = "CONTACT" + viaLay; extrafun = "connects-metal"; r = via_colour.getRed(); g = via_colour.getGreen(); b = via_colour.getBlue(); opacity = 0.7; la = via_size[viaLay-1].v / stepsize; } if (l.equals("DeviceMark")) { fun = "CONTROL"; la = nplus_width.v / stepsize; pat=" <pattern> </pattern>\n" + " <pattern> </pattern>\n" + " <pattern> </pattern>\n" + " <pattern> </pattern>\n" + " <pattern> </pattern>\n" + " <pattern> </pattern>\n" + " <pattern> </pattern>\n" + " <pattern> </pattern>\n" + " <pattern> </pattern>\n" + " <pattern> </pattern>\n" + " <pattern> </pattern>\n" + " <pattern> </pattern>\n" + " <pattern> </pattern>\n" + " <pattern> </pattern>\n" + " <pattern> </pattern>\n" + " <pattern> </pattern>"; } if (l.equals("Poly")) { fun = "POLY1"; tcol = 1; opacity = 1; la = poly_width.v / stepsize; } if (l.equals("PolyGate")) { fun = "GATE"; tcol = 1; opacity = 1; } if (l.equals("P-Diff")) { fun = "DIFFP"; tcol = 2; opacity = 1; la = diff_width.v / stepsize; } if (l.equals("N-Diff")) { fun = "DIFFN"; tcol = 2; opacity = 1; la = diff_width.v / stepsize; } if (l.equals("NPlus")) { fun = "IMPLANTN"; r = nplus_colour.getRed(); g = nplus_colour.getGreen(); b = nplus_colour.getBlue(); opacity = 1; la = nplus_width.v / stepsize; pat=" <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern>X X </pattern>\n" + " <pattern> X X</pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern>X X </pattern>\n" + " <pattern> X X</pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>"; } if (l.equals("PPlus")) { fun = "IMPLANTP"; r = pplus_colour.getRed(); g = pplus_colour.getGreen(); b = pplus_colour.getBlue(); opacity = 1; la = pplus_width.v / stepsize; pat=" <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern>X X </pattern>\n" + " <pattern> X X</pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern>X X </pattern>\n" + " <pattern> X X</pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>"; } if (l.equals("N-Well")) { fun = "WELLN"; r = nwell_colour.getRed(); g = nwell_colour.getGreen(); b = nwell_colour.getBlue(); opacity = 1; la = nwell_width.v / stepsize; pat=" <pattern> X X</pattern>\n" + " <pattern>X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X</pattern>\n" + " <pattern>X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>\n" + " <pattern> X X </pattern>"; } if (l.equals("PolyCon")) { fun = "CONTACT1"; extrafun = "connects-poly"; r = contact_colour.getRed(); g = contact_colour.getGreen(); b = contact_colour.getBlue(); opacity = 1; la = contact_size.v / stepsize; } if (l.equals("DiffCon")) { fun = "CONTACT1"; extrafun = "connects-diff"; r = contact_colour.getRed(); g = contact_colour.getGreen(); b = contact_colour.getBlue(); opacity = 1; la = contact_size.v / stepsize; } pw.println(); pw.println(" <layer name=\"" + l + "\" " + (fun.length() > 0 ? ("fun=\"" + fun + "\"") : "") + (extrafun.length() > 0 ? (" extraFun=\"" + extrafun + "\"") : "") + ">"); if (tcol == 0) { pw.println(" <opaqueColor r=\"" + r + "\" g=\"" + g + "\" b=\"" + b + "\"/>"); } else { pw.println(" <transparentColor transparent=\"" + tcol + "\"/>"); } pw.println(" <patternedOnDisplay>" + (pat == null ? "false" : "true") + "</patternedOnDisplay>"); pw.println(" <patternedOnPrinter>" + (pat == null ? "false" : "true") + "</patternedOnPrinter>"); if (pat == null) { for(int j=0; j<16; j++) pw.println(" <pattern> </pattern>"); } else { pw.println(pat); } pw.println(" <outlined>NOPAT</outlined>"); pw.println(" <opacity>" + opacity + "</opacity>"); pw.println(" <foreground>true</foreground>"); pw.println(" <display3D thick=\"1.0\" height=\"1.0\" mode=\"NONE\" factor=\"1.0\"/>"); char cifLetter = (char)('A' + i); pw.println(" <cifLayer cif=\"C" + cifLetter + cifLetter + "\"/>"); pw.println(" <skillLayer skill=\"" + l + "\"/>"); pw.println(" <parasitics resistance=\"1.0\" capacitance=\"0.0\" edgeCapacitance=\"0.0\"/>"); if (fun.startsWith("METAL") || fun.startsWith("POLY") || fun.startsWith("DIFF")) { pw.println(" <pureLayerNode name=\"" + l + "-Node\" port=\"Port_" + l + "\">"); pw.println(" <lambda>" + floaty(la) + "</lambda>"); pw.println(" <portArc>" + l + "</portArc>"); pw.println(" </pureLayerNode>"); } pw.println(" </layer>"); } // write the arcs List<String> arcs = new ArrayList<String>(); for(int i=1; i<=num_metal_layers; i++) arcs.add("Metal-"+i); arcs.add("Poly"); arcs.add("N-Diff"); arcs.add("P-Diff"); pw.println(); pw.println("<!-- ARCS -->"); for(String l : arcs) { String fun = ""; int ant = -1; double la = 0; List<String> h = new ArrayList<String>(); if (l.startsWith("Metal")) { int metalLay = TextUtils.atoi(l.substring(6)); fun = "METAL" + metalLay; la = metal_width[metalLay-1].v / stepsize; ant = (int)Math.round(metal_antenna_ratio[metalLay-1]) | 200; h.add(l + "=" + la); } if (l.equals("N-Diff")) { fun = "DIFFN"; h.add("N-Diff=" + (diff_width.v/stepsize)); h.add("NPlus=" + ((nplus_overhang_diff.v*2+diff_width.v)/stepsize)); } if (l.equals("P-Diff")) { fun = "DIFFP"; h.add("P-Diff=" + (diff_width.v / stepsize)); h.add("PPlus=" + ((pplus_overhang_diff.v*2 + diff_width.v) / stepsize)); h.add("N-Well=" + ((nwell_overhang_diff.v*2 + diff_width.v) / stepsize)); } if (l.equals("Poly")) { fun = "POLY1"; la = poly_width.v / stepsize; ant = (int)Math.round(poly_antenna_ratio) | 200; h.add(l + "=" + la); } double max = 0; for(String hEach : h) { int equalsPos = hEach.indexOf('='); double lim = TextUtils.atof(hEach.substring(equalsPos+1)); if (lim > max) max = lim; } if (ant >= 0) ant = Math.round(ant); pw.println(); pw.println(" <arcProto name=\"" + l + "\" fun=\"" + fun + "\">"); pw.println(" <wipable/>"); pw.println(" <extended>true</extended>"); pw.println(" <fixedAngle>true</fixedAngle>"); pw.println(" <angleIncrement>90</angleIncrement>"); if (ant >= 0) pw.println(" <antennaRatio>" + floaty(ant) + "</antennaRatio>"); for(String each : h) { int equalsPos = each.indexOf('='); String nom = each.substring(0, equalsPos); double lim = TextUtils.atof(each.substring(equalsPos+1)); pw.println(" <arcLayer layer=\"" + nom + "\" style=\"FILLED\">"); pw.println(" <lambda>" + floaty(lim/2) + "</lambda>"); pw.println(" </arcLayer>"); } pw.println(" </arcProto>"); } // write the pins pw.println(); pw.println("<!-- PINS -->"); for(int i=1; i<=num_metal_layers; i++) { double hla = metal_width[i-1].v / (stepsize*2); String shla = floaty(hla); pw.println(); pw.println(" <primitiveNode name=\"Metal-" + i + "-Pin\" fun=\"PIN\">"); pw.println(" <shrinkArcs/>"); pw.println(" <sizeOffset lx=\"" + shla + "\" hx=\"" + shla + "\" ly=\"" + shla + "\" hy=\"" + shla +"\"/>"); pw.println(" <nodeLayer layer=\"Metal-" + i + "\" style=\"CROSSED\">"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + shla + "\" khx=\"" + shla + "\" kly=\"-" + shla + "\" khy=\"" + shla +"\"/>"); pw.println(" </box>"); pw.println(" </nodeLayer>"); pw.println(" <primitivePort name=\"M" + i + "\">"); pw.println(" <portAngle primary=\"0\" range=\"180\"/>"); pw.println(" <portTopology>0</portTopology>"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"0.0\" khx=\"0.0\" kly=\"0.0\" khy=\"0.0\"/>"); pw.println(" </box>"); pw.println(" <portArc>Metal-" + i + "</portArc>"); pw.println(" </primitivePort>"); pw.println(" </primitiveNode>"); } double hla = poly_width.v / (stepsize*2); String shla = floaty(hla); pw.println(); pw.println(" <primitiveNode name=\"Poly-Pin\" fun=\"PIN\">"); pw.println(" <shrinkArcs/>"); pw.println(" <sizeOffset lx=\"" + shla + "\" hx=\"" + shla + "\" ly=\"" + shla + "\" hy=\"" + shla +"\"/>"); pw.println(" <nodeLayer layer=\"Poly\" style=\"CROSSED\">"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + shla + "\" khx=\"" + shla + "\" kly=\"-" + shla + "\" khy=\"" + shla + "\"/>"); pw.println(" </box>"); pw.println(" </nodeLayer>"); pw.println(" <primitivePort name=\"Poly\">"); pw.println(" <portAngle primary=\"0\" range=\"180\"/>"); pw.println(" <portTopology>0</portTopology>"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"0.0\" khx=\"0.0\" kly=\"0.0\" khy=\"0.0\"/>"); pw.println(" </box>"); pw.println(" <portArc>Poly</portArc>"); pw.println(" </primitivePort>"); pw.println(" </primitiveNode>"); pw.println(); pw.println("<!-- P-Diff AND N-Diff PINS -->"); for(int i=0; i<=1; i++) { String t, d1, d2, d3; if (i == 1) { t = "P"; d1 = floaty(diff_width.v/(stepsize*2)); d2 = floaty((diff_width.v+pplus_overhang_diff.v*2)/(stepsize*2)); d3 = floaty((diff_width.v+nwell_overhang_diff.v*2)/(stepsize*2)); } else { t = "N"; d1 = floaty(diff_width.v/(stepsize*2)); d2 = floaty((diff_width.v+nplus_overhang_diff.v*2)/(stepsize*2)); d3 = d2; } String x = floaty(TextUtils.atof(d3) - TextUtils.atof(d1)); pw.println(); pw.println(" <primitiveNode name=\"" + t + "-Diff-Pin\" fun=\"PIN\">"); pw.println(" <shrinkArcs/>"); // pw.println(" <diskOffset untilVersion=\"1\" x=\"" + d3 + "\" y=\"" + d3 + "\"/>"); // pw.println(" <diskOffset untilVersion=\"2\" x=\"" + d1 + "\" y=\"" + d1 + "\"/>"); pw.println(" <sizeOffset lx=\"" + x + "\" hx=\"" + x + "\" ly=\"" + x + "\" hy=\"" + x + "\"/>"); if (t.equals("P")) { pw.println(" <nodeLayer layer=\"N-Well\" style=\"CROSSED\">"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + d3 + "\" khx=\"" + d3 + "\" kly=\"-" + d3 + "\" khy=\"" + d3 + "\"/>"); pw.println(" </box>"); pw.println(" </nodeLayer>"); } pw.println(" <nodeLayer layer=\"" + t + "Plus\" style=\"CROSSED\">"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + d2 + "\" khx=\"" + d2 + "\" kly=\"-" + d2 + "\" khy=\"" + d2 + "\"/>"); pw.println(" </box>"); pw.println(" </nodeLayer>"); pw.println(" <nodeLayer layer=\"" + t + "-Diff\" style=\"CROSSED\">"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + d1 + "\" khx=\"" + d1 + "\" kly=\"-" + d1 + "\" khy=\"" + d1 + "\"/>"); pw.println(" </box>"); pw.println(" </nodeLayer>"); pw.println(" <primitivePort name=\"" + t + "-Diff\">"); pw.println(" <portAngle primary=\"0\" range=\"180\"/>"); pw.println(" <portTopology>0</portTopology>"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"0.0\" khx=\"0.0\" kly=\"0.0\" khy=\"0.0\"/>"); pw.println(" </box>"); pw.println(" <portArc>" + t + "-Diff</portArc>"); pw.println(" </primitivePort>"); pw.println(" </primitiveNode>"); } // write the contacts pw.println(); pw.println("<!-- METAL TO METAL VIAS / CONTACTS -->"); for(int alt=0; alt<=1; alt++) { for(int vl=0; vl<num_metal_layers; vl++) { String src, il; if (vl == 0) { src = "Poly"; il = "PolyCon"; } else { src = "Metal-" + vl; il = "Via-" + vl; } String dest = "Metal-" + (vl+1); String upperx, uppery, lowerx, lowery, cs, cs2, c; if (vl == 0) { // poly if (alt != 0) { upperx = floaty((contact_metal_overhang_inline_only.v*2+contact_size.v)/(stepsize*2)); uppery = floaty(contact_size.v/(stepsize*2)); } else { upperx = floaty((contact_metal_overhang_all_sides.v*2+contact_size.v)/(stepsize*2)); uppery = upperx; } lowerx = floaty((contact_poly_overhang.v*2+contact_size.v)/(stepsize*2)); lowery = lowerx; cs = floaty(contact_spacing.v/stepsize); cs2 = cs; c = floaty(contact_size.v/stepsize); } else { if (alt != 0) { upperx = floaty(via_size[vl-1].v/(stepsize*2)); uppery = floaty((via_overhang_inline[vl-1].v*2+via_size[vl-1].v)/(stepsize*2)); lowerx = uppery; lowery = upperx; } else { upperx = floaty((via_overhang_inline[vl-1].v*2+via_size[vl-1].v)/(stepsize*2)); uppery = floaty(via_size[vl-1].v/(stepsize*2)); lowerx = upperx; lowery = uppery; } c = floaty(via_size[vl-1].v/stepsize); cs = floaty(via_spacing[vl-1].v/stepsize); cs2 = floaty(via_array_spacing[vl-1].v/stepsize); } double maxx = TextUtils.atof(upperx); if (TextUtils.atof(lowerx) > maxx) maxx = TextUtils.atof(lowerx); double maxy = TextUtils.atof(uppery); if (TextUtils.atof(lowery) > maxy) maxy = TextUtils.atof(lowery); double minx = TextUtils.atof(upperx); if (TextUtils.atof(lowerx) < minx) minx = TextUtils.atof(lowerx); double miny = TextUtils.atof(uppery); if (TextUtils.atof(lowery) < miny) miny = TextUtils.atof(lowery); String ox = floaty(maxx-minx); String oy = floaty(maxy-miny); pw.println(); pw.println(" <primitiveNode name=\"" + src + "-" + dest + "-Con" + (alt != 0 ? "-X" : "") + "\" fun=\"CONTACT\">"); // pw.println(" <diskOffset untilVersion=\"2\" x=\"" + maxx + "\" y=\"" + maxy + "\"/>"); // pw.println(" <sizeOffset lx=\"" + ox + "\" hx=\"" + ox + "\" ly=\"" + oy + "\" hy=\"" + oy + "\"/>"); pw.println(" <nodeLayer layer=\"" + src + "\" style=\"FILLED\">"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + lowerx + "\" khx=\"" + lowerx + "\" kly=\"-" + lowery + "\" khy=\"" + lowery + "\"/>"); pw.println(" </box>"); pw.println(" </nodeLayer>"); pw.println(" <nodeLayer layer=\"" + dest + "\" style=\"FILLED\">"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + upperx + "\" khx=\"" + upperx + "\" kly=\"-" + uppery + "\" khy=\"" + uppery + "\"/>"); pw.println(" </box>"); pw.println(" </nodeLayer>"); pw.println(" <nodeLayer layer=\"" + il + "\" style=\"FILLED\">"); pw.println(" <multicutbox sizex=\"" + c + "\" sizey=\"" + c + "\" sep1d=\"" + cs + "\" sep2d=\"" + cs2 + "\">"); pw.println(" <lambdaBox klx=\"0.0\" khx=\"0.0\" kly=\"0.0\" khy=\"0.0\"/>"); pw.println(" </multicutbox>"); pw.println(" </nodeLayer>"); pw.println(" <primitivePort name=\"" + src + "-" + dest + "\">"); pw.println(" <portAngle primary=\"0\" range=\"180\"/>"); pw.println(" <portTopology>0</portTopology>"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + minx + "\" khx=\"" + minx + "\" kly=\"-" + miny + "\" khy=\"" + miny + "\"/>"); pw.println(" </box>"); pw.println(" <portArc>" + src + "</portArc>"); pw.println(" <portArc>" + dest + "</portArc>"); pw.println(" </primitivePort>"); pw.println(" <minSizeRule width=\"" + floaty(2*maxx) + "\" height=\"" + floaty(2*maxy) + "\" rule=\"" + src + "-" + dest + " rules\"/>"); pw.println(" </primitiveNode>"); } } pw.println(); pw.println("<!-- N-Diff-Metal-1 and P-Diff-Metal-1 -->"); for(int alt=0; alt<=1; alt++) { for(int i=0; i<2; i++) { String t = "", sx = "", mx = "", my = ""; if (i == 0) { t = "N"; sx = floaty((nplus_overhang_diff.v*2+diff_contact_overhang.v*2+contact_size.v)/(stepsize*2)); } else { t = "P"; sx = floaty((pplus_overhang_diff.v*2+diff_contact_overhang.v*2+contact_size.v)/(stepsize*2)); } if (alt != 0) { mx = floaty((contact_metal_overhang_inline_only.v*2+contact_size.v)/(stepsize*2)); my = floaty(contact_size.v/(stepsize*2)); } else { mx = floaty((contact_metal_overhang_all_sides.v*2+contact_size.v)/(stepsize*2)); my = mx; } String dx = floaty((diff_contact_overhang.v*2+contact_size.v)/(stepsize*2)); String wx = floaty((nwell_overhang_diff.v*2+diff_contact_overhang.v*2+contact_size.v)/(stepsize*2)); String maxx = mx; if (TextUtils.atof(dx) > TextUtils.atof(maxx)) maxx = dx; if (i==1 && TextUtils.atof(wx) > TextUtils.atof(maxx)) maxx = wx; String maxy = my; if (TextUtils.atof(dx) > TextUtils.atof(maxy)) maxy = dx; if (i==1 && TextUtils.atof(wx) > TextUtils.atof(maxy)) maxy = wx; String minx = mx; if (TextUtils.atof(dx) < TextUtils.atof(minx)) minx = dx; if (i==1 && TextUtils.atof(wx) < TextUtils.atof(minx)) minx = wx; String miny = my; if (TextUtils.atof(dx) < TextUtils.atof(miny)) miny = dx; if (i==1 && TextUtils.atof(wx) < TextUtils.atof(miny)) miny = wx; String sox = floaty(TextUtils.atof(maxx)-TextUtils.atof(dx)); String soy = floaty(TextUtils.atof(maxy)-TextUtils.atof(dx)); pw.println(); pw.println(" <primitiveNode name=\"" + t + "-Diff-Metal-1" + (alt != 0 ? "-X" : "") + "\" fun=\"CONTACT\">"); // pw.println(" <diskOffset untilVersion=\"1\" x=\"" + maxx + "\" y=\"" + maxy + "\"/>"); // pw.println(" <diskOffset untilVersion=\"2\" x=\"" + minx + "\" y=\"" + miny + "\"/>"); pw.println(" <sizeOffset lx=\"" + sox + "\" hx=\"" + sox + "\" ly=\"" + soy + "\" hy=\"" + soy + "\"/>"); pw.println(" <nodeLayer layer=\"Metal-1\" style=\"FILLED\">"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + mx + "\" khx=\"" + mx + "\" kly=\"-" + my + "\" khy=\"" + my + "\"/>"); pw.println(" </box>"); pw.println(" </nodeLayer>"); pw.println(" <nodeLayer layer=\"" + t + "-Diff\" style=\"FILLED\">"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + dx + "\" khx=\"" + dx + "\" kly=\"-" + dx + "\" khy=\"" + dx + "\"/>"); pw.println(" </box>"); pw.println(" </nodeLayer>"); if (i != 0) { pw.println(" <nodeLayer layer=\"N-Well\" style=\"FILLED\">"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + wx + "\" khx=\"" + wx + "\" kly=\"-" + wx + "\" khy=\"" + wx + "\"/>"); pw.println(" </box>"); pw.println(" </nodeLayer>"); } pw.println(" <nodeLayer layer=\"" + t + "Plus\" style=\"FILLED\">"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + sx + "\" khx=\"" + sx + "\" kly=\"-" + sx + "\" khy=\"" + sx + "\"/>"); pw.println(" </box>"); pw.println(" </nodeLayer>"); pw.println(" <nodeLayer layer=\"DiffCon\" style=\"FILLED\">"); pw.println(" <multicutbox sizex=\"" + floaty(contact_size.v/stepsize) + "\" sizey=\"" + floaty(contact_size.v/stepsize) + "\" sep1d=\"" + (floaty(contact_spacing.v/stepsize)) + "\" sep2d=\"" + floaty(contact_spacing.v/stepsize) + "\">"); pw.println(" <lambdaBox klx=\"0.0\" khx=\"0.0\" kly=\"0.0\" khy=\"0.0\"/>"); pw.println(" </multicutbox>"); pw.println(" </nodeLayer>"); pw.println(" <primitivePort name=\"" + t + "-Diff-Metal-1" + "\">"); pw.println(" <portAngle primary=\"0\" range=\"180\"/>"); pw.println(" <portTopology>0</portTopology>"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + dx + "\" khx=\"" + dx + "\" kly=\"-" + dx + "\" khy=\"" + dx + "\"/>"); pw.println(" </box>"); pw.println(" <portArc>" + t + "-Diff</portArc>"); pw.println(" <portArc>Metal-1</portArc>"); pw.println(" </primitivePort>"); pw.println(" <minSizeRule width=\"" + floaty(2*TextUtils.atof(maxx)) + "\" height=\"" + floaty(2*TextUtils.atof(maxy)) + "\" rule=\"" + t + "-Diff, " + t + "+, M1" + (i==1 ? ", N-Well" : "") + " and Contact rules\"/>"); pw.println(" </primitiveNode>"); } } pw.println(); pw.println("<!-- VDD-Tie-Metal-1 and VSS-Tie-Metal-1 -->"); for(int alt=0; alt<=1; alt++) { for(int i=0; i<2; i++) { String t, fun, dt, sx, mx, my; if (i == 0) { t = "VDD"; fun = "WELL"; dt = "N"; sx = floaty((nplus_overhang_diff.v*2+diff_contact_overhang.v*2+contact_size.v)/(stepsize*2)); } else { t = "VSS"; fun = "SUBSTRATE"; dt = "P"; sx = floaty((pplus_overhang_diff.v*2+diff_contact_overhang.v*2+contact_size.v)/(stepsize*2)); } if (alt != 0) { mx = floaty((contact_metal_overhang_inline_only.v*2+contact_size.v)/(stepsize*2)); my = floaty(contact_size.v/(stepsize*2)); } else { mx = floaty((contact_metal_overhang_all_sides.v*2+contact_size.v)/(stepsize*2)); my = mx; } String dx = floaty((diff_contact_overhang.v*2+contact_size.v)/(stepsize*2)); String wx = floaty((nwell_overhang_diff.v*2+diff_contact_overhang.v*2+contact_size.v)/(stepsize*2)); String maxx = mx; if (TextUtils.atof(dx) > TextUtils.atof(maxx)) maxx = dx; if (i==0 && TextUtils.atof(wx)>TextUtils.atof(maxx)) maxx = wx; String maxy = my; if (TextUtils.atof(dx) > TextUtils.atof(maxy)) maxy = dx; if (i==0 && TextUtils.atof(wx)>TextUtils.atof(maxy)) maxy = wx; String minx = mx; if (TextUtils.atof(dx) < TextUtils.atof(minx)) minx = dx; if (i==0 && TextUtils.atof(wx)<TextUtils.atof(minx)) minx = wx; String miny = my; if (TextUtils.atof(dx) < TextUtils.atof(miny)) miny = dx; if (i==0 && TextUtils.atof(wx)<TextUtils.atof(miny)) miny = wx; String sox = floaty(TextUtils.atof(maxx)-TextUtils.atof(dx)); String soy = floaty(TextUtils.atof(maxy)-TextUtils.atof(dx)); pw.println(); pw.println(" <primitiveNode name=\"" + t + "-Tie-Metal-1" + (alt != 0 ? "-X" : "") + "\" fun=\"" + fun + "\">"); // pw.println(" <diskOffset untilVersion=\"1\" x=\"" + maxx + "\" y=\"" + maxy + "\"/>"); // pw.println(" <diskOffset untilVersion=\"2\" x=\"" + minx + "\" y=\"" + miny + "\"/>"); pw.println(" <sizeOffset lx=\"" + sox + "\" hx=\"" + sox + "\" ly=\"" + soy + "\" hy=\"" + soy + "\"/>"); pw.println(" <nodeLayer layer=\"Metal-1\" style=\"FILLED\">"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + mx + "\" khx=\"" + mx + "\" kly=\"-" + my + "\" khy=\"" + my + "\"/>"); pw.println(" </box>"); pw.println(" </nodeLayer>"); pw.println(" <nodeLayer layer=\"" + dt + "-Diff\" style=\"FILLED\">"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + dx + "\" khx=\"" + dx + "\" kly=\"-" + dx + "\" khy=\"" + dx + "\"/>"); pw.println(" </box>"); pw.println(" </nodeLayer>"); if (i != 1) { pw.println(" <nodeLayer layer=\"N-Well\" style=\"FILLED\">"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + wx + "\" khx=\"" + wx + "\" kly=\"-" + wx + "\" khy=\"" + wx + "\"/>"); pw.println(" </box>"); pw.println(" </nodeLayer>"); } pw.println(" <nodeLayer layer=\"" + dt + "Plus\" style=\"FILLED\">"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + sx + "\" khx=\"" + sx + "\" kly=\"-" + sx + "\" khy=\"" + sx + "\"/>"); pw.println(" </box>"); pw.println(" </nodeLayer>"); pw.println(" <nodeLayer layer=\"DiffCon\" style=\"FILLED\">"); pw.println(" <multicutbox sizex=\"" + floaty(contact_size.v/stepsize) + "\" sizey=\"" + floaty(contact_size.v/stepsize) + "\" sep1d=\"" + floaty(contact_spacing.v/stepsize) + "\" sep2d=\"" + floaty(contact_spacing.v/stepsize) + "\">"); pw.println(" <lambdaBox klx=\"0.0\" khx=\"0.0\" kly=\"0.0\" khy=\"0.0\"/>"); pw.println(" </multicutbox>"); pw.println(" </nodeLayer>"); pw.println(" <primitivePort name=\"" + t + "-Tie-M1" + "\">"); pw.println(" <portAngle primary=\"0\" range=\"180\"/>"); pw.println(" <portTopology>0</portTopology>"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + dx + "\" khx=\"" + dx + "\" kly=\"-" + dx + "\" khy=\"" + dx + "\"/>"); pw.println(" </box>"); pw.println(" <portArc>Metal-1</portArc>"); pw.println(" </primitivePort>"); pw.println(" <minSizeRule width=\"" + floaty(2*TextUtils.atof(maxx)) + "\" height=\"" + floaty(2*TextUtils.atof(maxy)) + "\" rule=\"" + dt + "-Diff, " + dt + "+, M1" + (i==0 ? ", N-Well" : "") + " and Contact rules\"/>"); pw.println(" </primitiveNode>"); } } // write the transistors for(int i=0; i<2; i++) { String wellx = "", welly = "", t, impx, impy; if (i==0) { t = "P"; wellx = floaty((gate_width.v+nwell_overhang_diff.v*2)/(stepsize*2)); welly = floaty((gate_length.v+diff_poly_overhang.v*2+nwell_overhang_diff.v*2)/(stepsize*2)); impx = floaty((gate_width.v+pplus_overhang_diff.v*2)/(stepsize*2)); impy = floaty((gate_length.v+diff_poly_overhang.v*2+pplus_overhang_diff.v*2)/(stepsize*2)); } else { t = "N"; impx = floaty((gate_width.v+nplus_overhang_diff.v*2)/(stepsize*2)); impy = floaty((gate_length.v+diff_poly_overhang.v*2+nplus_overhang_diff.v*2)/(stepsize*2)); } String diffx = floaty(gate_width.v/(stepsize*2)); String diffy = floaty((gate_length.v+diff_poly_overhang.v*2)/(stepsize*2)); String porty = floaty((gate_length.v+diff_poly_overhang.v*2-diff_width.v)/(stepsize*2)); String polyx = floaty((gate_width.v+poly_endcap.v*2)/(stepsize*2)); String polyy = floaty(gate_length.v/(stepsize*2)); String polyx2 = floaty((poly_endcap.v*2)/(stepsize*2)); String sx = floaty(TextUtils.atof(polyx)-TextUtils.atof(diffx)); String sy = floaty(TextUtils.atof(diffy)-TextUtils.atof(polyy)); pw.println(); pw.println("<!-- " + t + "-Transistor -->"); pw.println(); pw.println(" <primitiveNode name=\"" + t + "-Transistor\" fun=\"TRA" + t + "MOS\">"); // pw.println(" <diskOffset untilVersion=\"2\" x=\"" + polyx + "\" y=\"" + diffy + "\"/>"); // pw.println(" <sizeOffset lx=\"" + sx + "\" hx=\"" + sx + "\" ly=\"" + sy + "\" hy=\"" + sy + "\"/>"); pw.println(" <nodeLayer layer=\"Poly\" style=\"FILLED\">"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + polyx + "\" khx=\"" + polyx + "\" kly=\"-" + polyy + "\" khy=\"" + polyy + "\"/>"); pw.println(" </box>"); pw.println(" </nodeLayer>"); pw.println(" <nodeLayer layer=\"PolyGate\" style=\"FILLED\">"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + diffx + "\" khx=\"" + diffx + "\" kly=\"-" + polyy + "\" khy=\"" + polyy + "\"/>"); pw.println(" </box>"); pw.println(" </nodeLayer>"); pw.println(" <nodeLayer layer=\"" + t + "-Diff\" style=\"FILLED\">"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + diffx + "\" khx=\"" + diffx + "\" kly=\"-" + diffy + "\" khy=\"" + diffy + "\"/>"); pw.println(" </box>"); pw.println(" </nodeLayer>"); pw.println(" <nodeLayer layer=\"" + t + "Plus\" style=\"FILLED\">"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + impx + "\" khx=\"" + impx + "\" kly=\"-" + impy + "\" khy=\"" + impy + "\"/>"); pw.println(" </box>"); pw.println(" </nodeLayer>"); pw.println(" <nodeLayer layer=\"DeviceMark\" style=\"FILLED\">"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + impx + "\" khx=\"" + impx + "\" kly=\"-" + impy + "\" khy=\"" + impy + "\"/>"); pw.println(" </box>"); pw.println(" </nodeLayer>"); if (i==0) { pw.println(" <nodeLayer layer=\"N-Well\" style=\"FILLED\">"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + wellx + "\" khx=\"" + wellx + "\" kly=\"-" + welly + "\" khy=\"" + welly + "\"/>"); pw.println(" </box>"); pw.println(" </nodeLayer>"); } pw.println(" <primitivePort name=\"Gate-Left\">"); pw.println(" <portAngle primary=\"180\" range=\"90\"/>"); pw.println(" <portTopology>0</portTopology>"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + polyx + "\" khx=\"-" + polyx2 + "\" kly=\"-" + polyy + "\" khy=\"" + polyy + "\"/>"); pw.println(" </box>"); pw.println(" <portArc>Poly</portArc>"); pw.println(" </primitivePort>"); pw.println(" <primitivePort name=\"Diff-Top\">"); pw.println(" <portAngle primary=\"90\" range=\"90\"/>"); pw.println(" <portTopology>1</portTopology>"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + diffx + "\" khx=\"" + diffx + "\" kly=\"" + porty + "\" khy=\"" + porty + "\"/>"); pw.println(" </box>"); pw.println(" <portArc>" + t + "-Diff</portArc>"); pw.println(" </primitivePort>"); pw.println(" <primitivePort name=\"Gate-Right\">"); pw.println(" <portAngle primary=\"0\" range=\"90\"/>"); pw.println(" <portTopology>0</portTopology>"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"" + polyx2 + "\" khx=\"" + polyx + "\" kly=\"-" + polyy + "\" khy=\"" + polyy + "\"/>"); pw.println(" </box>"); pw.println(" <portArc>Poly</portArc>"); pw.println(" </primitivePort>"); pw.println(" <primitivePort name=\"Diff-Bottom\">"); pw.println(" <portAngle primary=\"270\" range=\"90\"/>"); pw.println(" <portTopology>2</portTopology>"); pw.println(" <box>"); pw.println(" <lambdaBox klx=\"-" + diffx + "\" khx=\"" + diffx + "\" kly=\"-" + porty + "\" khy=\"-" + porty + "\"/>"); pw.println(" </box>"); pw.println(" <portArc>" + t + "-Diff</portArc>"); pw.println(" </primitivePort>"); pw.println(" </primitiveNode>"); } // write trailing boilerplate pw.println(); pw.println("<!-- SKELETON HEADERS -->"); pw.println(); pw.println(" <spiceHeader level=\"1\">"); pw.println(" <spiceLine line=\"* Spice header (level 1)\"/>"); pw.println(" </spiceHeader>"); pw.println(); pw.println(" <spiceHeader level=\"2\">"); pw.println(" <spiceLine line=\"* Spice header (level 2)\"/>"); pw.println(" </spiceHeader>"); // write the component menu layout int ts = 5; pw.println(); pw.println("<!-- PALETTE -->"); pw.println(); pw.println(" <menuPalette numColumns=\"3\">"); for(int i=1; i<=num_metal_layers; i++) { int h = i-1; pw.println(); pw.println(" <menuBox>"); pw.println(" <menuArc>Metal-" + i + "</menuArc>"); pw.println(" </menuBox>"); pw.println(" <menuBox>"); pw.println(" <menuNode>Metal-" + i + "-Pin</menuNode>"); pw.println(" </menuBox>"); if (i != 1) { pw.println(" <menuBox>"); String name = "Metal-" + h + "-Metal-" + i + "-Con"; pw.println(" <menuNodeInst protoName=\"" + name + "\" function=\"CONTACT\">"); pw.println(" <menuNodeText text=\"" + name + "\" size=\"" + ts + "\"/>"); pw.println(" </menuNodeInst>"); pw.println(" <menuNodeInst protoName=\"" + name + "-X\" function=\"CONTACT\"/>"); pw.println(" </menuBox>"); } else { pw.println(" <menuBox>"); pw.println(" </menuBox>"); } } pw.println(); pw.println(" <menuBox>"); pw.println(" <menuArc>Poly</menuArc>"); pw.println(" </menuBox>"); pw.println(" <menuBox>"); pw.println(" <menuNode>Poly-Pin</menuNode>"); pw.println(" </menuBox>"); pw.println(" <menuBox>"); pw.println(" <menuNodeInst protoName=\"Poly-Metal-1-Con\" function=\"CONTACT\"/>"); // pw.println(" </menuNodeInst>"); pw.println(" <menuNodeInst protoName=\"Poly-Metal-1-Con-X\" function=\"CONTACT\"/>"); pw.println(" </menuBox>"); pw.println(); pw.println(" <menuBox>"); pw.println(" <menuArc>P-Diff</menuArc>"); pw.println(" </menuBox>"); pw.println(" <menuBox>"); pw.println(" <menuNode>P-Diff-Pin</menuNode>"); pw.println(" </menuBox>"); pw.println(" <menuBox>"); pw.println(" <menuNodeInst protoName=\"P-Transistor\" function=\"TRAPMOS\">"); pw.println(" <menuNodeText text=\"P\" size=\"" + ts + "\"/>"); pw.println(" </menuNodeInst>"); pw.println(" </menuBox>"); pw.println(); pw.println(" <menuBox>"); pw.println(" <menuArc>N-Diff</menuArc>"); pw.println(" </menuBox>"); pw.println(" <menuBox>"); pw.println(" <menuNode>N-Diff-Pin</menuNode>"); pw.println(" </menuBox>"); pw.println(" <menuBox>"); pw.println(" <menuNodeInst protoName=\"N-Transistor\" function=\"TRANMOS\">"); pw.println(" <menuNodeText text=\"N\" size=\"" + ts + "\"/>"); pw.println(" </menuNodeInst>"); pw.println(" </menuBox>"); pw.println(); pw.println(" <menuBox>"); pw.println(" <menuNodeInst protoName=\"VSS-Tie-Metal-1\" function=\"SUBSTRATE\">"); pw.println(" <menuNodeText text=\"VSS-Tie\" size=\"" + ts + "\"/>"); pw.println(" </menuNodeInst>"); pw.println(" <menuNodeInst protoName=\"VSS-Tie-Metal-1-X\" function=\"SUBSTRATE\"/>"); pw.println(" </menuBox>"); pw.println(); pw.println(" <menuBox>"); pw.println(" <menuNodeInst protoName=\"N-Diff-Metal-1\" function=\"CONTACT\">"); pw.println(" <menuNodeText text=\"N-Con\" size=\"" + ts + "\"/>"); pw.println(" </menuNodeInst>"); pw.println(" <menuNodeInst protoName=\"N-Diff-Metal-1-X\" function=\"CONTACT\"/>"); pw.println(" </menuBox>"); pw.println(" <menuBox>"); pw.println(" </menuBox>"); pw.println(); pw.println(" <menuBox>"); pw.println(" <menuNodeInst protoName=\"VDD-Tie-Metal-1\" function=\"WELL\">"); pw.println(" <menuNodeText text=\"VDD-Tie\" size=\"" + ts + "\"/>"); pw.println(" </menuNodeInst>"); pw.println(" <menuNodeInst protoName=\"VDD-Tie-Metal-1-X\" function=\"WELL\"/>"); pw.println(" </menuBox>"); pw.println(" <menuBox>"); pw.println(" <menuNodeInst protoName=\"P-Diff-Metal-1\" function=\"CONTACT\">"); pw.println(" <menuNodeText text=\"P-Con\" size=\"" + ts + "\"/>"); pw.println(" </menuNodeInst>"); pw.println(" <menuNodeInst protoName=\"P-Diff-Metal-1-X\" function=\"CONTACT\"/>"); pw.println(" </menuBox>"); pw.println(" <menuBox>"); pw.println(" </menuBox>"); pw.println(); pw.println(" <menuBox>"); pw.println(" <menuText>Pure</menuText>"); pw.println(" </menuBox>"); pw.println(" <menuBox>"); pw.println(" <menuText>Misc.</menuText>"); pw.println(" </menuBox>"); pw.println(" <menuBox>"); pw.println(" <menuText>Cell</menuText>"); pw.println(" </menuBox>"); pw.println(" </menuPalette>"); pw.println(); pw.println(" <Foundry name=\"" + foundry_name + "\">"); // write GDS layers pw.println(); for(int i=1; i<=num_metal_layers; i++) { pw.println(" <layerGds layer=\"Metal-" + i + "\" gds=\"" + gds_metal_layer[i-1] + "\"/>"); if (i != num_metal_layers) { pw.println(" <layerGds layer=\"Via-" + i + "\" gds=\"" + gds_via_layer[i-1] + "\"/>"); } } pw.println(" <layerGds layer=\"Poly\" gds=\"" + gds_poly_layer + "\"/>"); pw.println(" <layerGds layer=\"PolyGate\" gds=\"" + gds_poly_layer + "\"/>"); pw.println(" <layerGds layer=\"DiffCon\" gds=\"" + gds_contact_layer + "\"/>"); pw.println(" <layerGds layer=\"PolyCon\" gds=\"" + gds_contact_layer + "\"/>"); pw.println(" <layerGds layer=\"N-Diff\" gds=\"" + gds_diff_layer + "\"/>"); pw.println(" <layerGds layer=\"P-Diff\" gds=\"" + gds_diff_layer + "\"/>"); pw.println(" <layerGds layer=\"NPlus\" gds=\"" + gds_nplus_layer + "\"/>"); pw.println(" <layerGds layer=\"PPlus\" gds=\"" + gds_pplus_layer + "\"/>"); pw.println(" <layerGds layer=\"N-Well\" gds=\"" + gds_nwell_layer + "\"/>"); pw.println(" <layerGds layer=\"DeviceMark\" gds=\"" + gds_marking_layer + "\"/>"); // write GDS layers pw.println(); for(int i=1; i<=num_metal_layers; i++) { pw.println(" <layerGds layer=\"Metal-" + i + "\" gds=\"" + gds_metal_layer[i-1] + "\"/>"); if (i != num_metal_layers) { pw.println(" <layerGds layer=\"Via-" + i + "\" gds=\"" + gds_via_layer[i-1] + "\"/>"); } } pw.println(" <layerGds layer=\"Poly\" gds=\"" + gds_poly_layer + "\"/>"); pw.println(" <layerGds layer=\"PolyGate\" gds=\"" + gds_poly_layer + "\"/>"); pw.println(" <layerGds layer=\"DiffCon\" gds=\"" + gds_contact_layer + "\"/>"); pw.println(" <layerGds layer=\"PolyCon\" gds=\"" + gds_contact_layer + "\"/>"); pw.println(" <layerGds layer=\"N-Diff\" gds=\"" + gds_diff_layer + "\"/>"); pw.println(" <layerGds layer=\"P-Diff\" gds=\"" + gds_diff_layer + "\"/>"); pw.println(" <layerGds layer=\"NPlus\" gds=\"" + gds_nplus_layer + "\"/>"); pw.println(" <layerGds layer=\"PPlus\" gds=\"" + gds_pplus_layer + "\"/>"); pw.println(" <layerGds layer=\"N-Well\" gds=\"" + gds_nwell_layer + "\"/>"); pw.println(" <layerGds layer=\"DeviceMark\" gds=\"" + gds_marking_layer + "\"/>"); pw.println(); // Write basic design rules not implicit in primitives // WIDTHS for(int i=0; i<num_metal_layers; i++) { pw.println(" <LayerRule ruleName=\"" + metal_width[i].rule + "\" layerName=\"Metal-" + (i+1) + "\" type=\"MINWID\" when=\"ALL\" value=\"" + floaty(metal_width[i].v/stepsize) + "\"/>"); } pw.println(" <LayerRule ruleName=\"" + diff_width.rule + "\" layerName=\"N-Diff\" type=\"MINWID\" when=\"ALL\" value=\"" + floaty(diff_width.v/stepsize) + "\"/>"); pw.println(" <LayerRule ruleName=\"" + diff_width.rule + "\" layerName=\"P-Diff\" type=\"MINWID\" when=\"ALL\" value=\"" + floaty(diff_width.v/stepsize) + "\"/>"); pw.println(" <LayerRule ruleName=\"" + nwell_width.rule + "\" layerName=\"N-Well\" type=\"MINWID\" when=\"ALL\" value=\"" + floaty(nwell_width.v/stepsize) + "\"/>"); pw.println(" <LayerRule ruleName=\"" + nplus_width.rule + "\" layerName=\"NPlus\" type=\"MINWID\" when=\"ALL\" value=\"" + floaty(nplus_width.v/stepsize) + "\"/>"); pw.println(" <LayerRule ruleName=\"" + pplus_width.rule + "\" layerName=\"PPlus\" type=\"MINWID\" when=\"ALL\" value=\"" + floaty(pplus_width.v/stepsize) + "\"/>"); pw.println(" <LayerRule ruleName=\"" + poly_width.rule + "\" layerName=\"Poly\" type=\"MINWID\" when=\"ALL\" value=\"" + floaty(poly_width.v/stepsize) + "\"/>"); pw.println(" <LayerRule ruleName=\"" + poly_width.rule + "\" layerName=\"PolyGate\" type=\"MINWID\" when=\"ALL\" value=\"" + floaty(poly_width.v/stepsize) + "\"/>"); // SPACINGS pw.println(" <LayersRule ruleName=\"" + diff_spacing.rule + "\" layerNames=\"{N-Diff,N-Diff}\" type=\"UCONSPA\" when=\"ALL\" value=\"" + floaty(diff_spacing.v/stepsize) + "\"/>"); pw.println(" <LayersRule ruleName=\"" + diff_spacing.rule + "\" layerNames=\"{N-Diff,P-Diff}\" type=\"UCONSPA\" when=\"ALL\" value=\"" + floaty(diff_spacing.v/stepsize) + "\"/>"); pw.println(" <LayersRule ruleName=\"" + diff_spacing.rule + "\" layerNames=\"{P-Diff,P-Diff}\" type=\"UCONSPA\" when=\"ALL\" value=\"" + floaty(diff_spacing.v/stepsize) + "\"/>"); pw.println(" <LayersRule ruleName=\"" + poly_diff_spacing.rule + "\" layerNames=\"{Poly,N-Diff}\" type=\"UCONSPA\" when=\"ALL\" value=\"" + floaty(poly_diff_spacing.v/stepsize) + "\"/>"); pw.println(" <LayersRule ruleName=\"" + poly_diff_spacing.rule + "\" layerNames=\"{Poly,P-Diff}\" type=\"UCONSPA\" when=\"ALL\" value=\"" + floaty(poly_diff_spacing.v/stepsize) + "\"/>"); pw.println(" <LayersRule ruleName=\"" + poly_spacing.rule + "\" layerNames=\"{Poly,Poly}\" type=\"UCONSPA\" when=\"ALL\" value=\"" + floaty(poly_spacing.v/stepsize) + "\"/>"); pw.println(" <LayersRule ruleName=\"" + gate_spacing.rule + "\" layerNames=\"{PolyGate,PolyGate}\" type=\"UCONSPA\" when=\"ALL\" value=\"" + floaty(gate_spacing.v/stepsize) + "\"/>"); pw.println(" <LayersRule ruleName=\"" + nwell_spacing.rule + "\" layerNames=\"{N-Well,N-Well}\" type=\"UCONSPA\" when=\"ALL\" value=\"" + floaty(nwell_spacing.v/stepsize) + "\"/>"); pw.println(" <LayersRule ruleName=\"" + nplus_spacing.rule + "\" layerNames=\"{NPlus,NPlus}\" type=\"UCONSPA\" when=\"ALL\" value=\"" + floaty(nplus_spacing.v/stepsize) + "\"/>"); pw.println(" <LayersRule ruleName=\"" + pplus_spacing.rule + "\" layerNames=\"{PPlus,PPlus}\" type=\"UCONSPA\" when=\"ALL\" value=\"" + floaty(pplus_spacing.v/stepsize) + "\"/>"); pw.println(" <LayersRule ruleName=\"" + contact_spacing.rule + "\" layerNames=\"{PolyCon,PolyCon}\" type=\"UCONSPA\" when=\"ALL\" value=\"" + floaty(contact_spacing.v/stepsize) + "\"/>"); pw.println(" <LayersRule ruleName=\"" + contact_spacing.rule + "\" layerNames=\"{DiffCon,DiffCon}\" type=\"UCONSPA\" when=\"ALL\" value=\"" + floaty(contact_spacing.v/stepsize) + "\"/>"); pw.println(" <LayersRule ruleName=\"" + polycon_diff_spacing.rule + "\" layerNames=\"{PolyCon,N-Diff}\" type=\"UCONSPA\" when=\"ALL\" value=\"" + floaty(polycon_diff_spacing.v/stepsize) + "\"/>"); pw.println(" <LayersRule ruleName=\"" + polycon_diff_spacing.rule + "\" layerNames=\"{PolyCon,P-Diff}\" type=\"UCONSPA\" when=\"ALL\" value=\"" + floaty(polycon_diff_spacing.v/stepsize) + "\"/>"); pw.println(" <LayersRule ruleName=\"" + gate_contact_spacing.rule + "\" layerNames=\"{DiffCon,Poly}\" type=\"UCONSPA\" when=\"ALL\" value=\"" + floaty(gate_contact_spacing.v/stepsize) + "\"/>"); pw.println(" <LayersRule ruleName=\"" + gate_contact_spacing.rule + "\" layerNames=\"{DiffCon,PolyGate}\" type=\"UCONSPA\" when=\"ALL\" value=\"" + floaty(gate_contact_spacing.v/stepsize) + "\"/>"); for(int i=1; i<=num_metal_layers; i++) { pw.println(" <LayersRule ruleName=\"" + metal_spacing[i-1].rule + "\" layerNames=\"{Metal-" + i + ",Metal-" + i + "}\" type=\"UCONSPA\" when=\"ALL\" value=\"" + floaty(metal_spacing[i-1].v/stepsize) + "\"/>"); if (i != num_metal_layers) { pw.println(" <LayersRule ruleName=\"" + via_spacing[i-1].rule + "\" layerNames=\"{Via-" + i + ",Via-" + i + "}\" type=\"UCONSPA\" when=\"ALL\" value=\"" + floaty(via_spacing[i-1].v/stepsize) + "\"/>"); } } pw.println(" </Foundry>"); pw.println(); pw.println("</technology>"); } private String floaty(double v) { if (v < 0) System.out.println("Negative distance of " + v + " in the tech editor wizard"); double roundedV = DBMath.round(v); return roundedV + ""; // the "" is needed to call the String constructor } private double scaledValue(double val) { return DBMath.round(val / stepsize); } }
false
false
null
null
diff --git a/testing/itests/src/test/java/org/apache/servicemix/kernel/testing/itests/SimpleTest.java b/testing/itests/src/test/java/org/apache/servicemix/kernel/testing/itests/SimpleTest.java index 8168b4a9..feba4752 100644 --- a/testing/itests/src/test/java/org/apache/servicemix/kernel/testing/itests/SimpleTest.java +++ b/testing/itests/src/test/java/org/apache/servicemix/kernel/testing/itests/SimpleTest.java @@ -1,77 +1,76 @@ /* * 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.servicemix.kernel.testing.itests; -import java.util.Properties; - import javax.xml.stream.XMLInputFactory; import org.apache.servicemix.kernel.testing.support.AbstractIntegrationTest; public class SimpleTest extends AbstractIntegrationTest { - private Properties dependencies; - /** * The manifest to use for the "virtual bundle" created * out of the test classes and resources in this project * * This is actually the boilerplate manifest with one additional * import-package added. We should provide a simpler customization * point for such use cases that doesn't require duplication * of the entire manifest... */ protected String getManifestLocation() { return "classpath:org/apache/servicemix/MANIFEST.MF"; } /** * The location of the packaged OSGi bundles to be installed * for this test. Values are Spring resource paths. The bundles * we want to use are part of the same multi-project maven * build as this project is. Hence we use the localMavenArtifact * helper method to find the bundles produced by the package * phase of the maven build (these tests will run after the * packaging phase, in the integration-test phase). * * JUnit, commons-logging, spring-core and the spring OSGi * test bundle are automatically included so do not need * to be specified here. */ protected String[] getTestBundlesNames() { return new String[] { getBundle("org.apache.servicemix.specs", "org.apache.servicemix.specs.stax-api-1.0"), }; } public void testWoodstox() throws Exception { - Thread.currentThread().setContextClassLoader(XMLInputFactory.class.getClassLoader()); - System.err.println(XMLInputFactory.class.getClassLoader()); - System.err.println(getClass().getClassLoader()); - XMLInputFactory factory = null; - try { - factory = XMLInputFactory.newInstance(); - fail("Factory should not have been found"); - } catch (Throwable t) { - System.err.println(t.getMessage()); + //JDK 1.6 and above ship with a StaX implementation + if (System.getProperty("java.version").startsWith("1.5")) { + Thread.currentThread().setContextClassLoader(XMLInputFactory.class.getClassLoader()); + System.err.println(XMLInputFactory.class.getClassLoader()); + System.err.println(getClass().getClassLoader()); + XMLInputFactory factory = null; + try { + factory = XMLInputFactory.newInstance(); + fail("Factory should not have been found"); + } catch (Throwable t) { + System.err.println(t.getMessage()); + } + assertNull(factory); + installBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.woodstox", null, "jar"); + assertNotNull(XMLInputFactory.newInstance()); } - assertNull(factory); - installBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.woodstox", null, "jar"); - assertNotNull(XMLInputFactory.newInstance()); } }
false
false
null
null
diff --git a/nuget-agent/src/jetbrains/buildServer/nuget/agent/runner/install/PackagesInstallerRunner.java b/nuget-agent/src/jetbrains/buildServer/nuget/agent/runner/install/PackagesInstallerRunner.java index 488820ab..823454e8 100644 --- a/nuget-agent/src/jetbrains/buildServer/nuget/agent/runner/install/PackagesInstallerRunner.java +++ b/nuget-agent/src/jetbrains/buildServer/nuget/agent/runner/install/PackagesInstallerRunner.java @@ -1,97 +1,99 @@ /* * Copyright 2000-2011 JetBrains s.r.o. * * 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 jetbrains.buildServer.nuget.agent.runner.install; import jetbrains.buildServer.RunBuildException; import jetbrains.buildServer.agent.AgentRunningBuild; import jetbrains.buildServer.agent.BuildProcess; import jetbrains.buildServer.agent.BuildRunnerContext; import jetbrains.buildServer.nuget.agent.commands.NuGetActionFactory; import jetbrains.buildServer.nuget.agent.parameters.NuGetFetchParameters; import jetbrains.buildServer.nuget.agent.parameters.PackagesInstallParameters; import jetbrains.buildServer.nuget.agent.parameters.PackagesParametersFactory; import jetbrains.buildServer.nuget.agent.parameters.PackagesUpdateParameters; import jetbrains.buildServer.nuget.agent.runner.NuGetRunnerBase; import jetbrains.buildServer.nuget.agent.runner.install.impl.InstallStagesImpl; import jetbrains.buildServer.nuget.agent.runner.install.impl.locate.LocateNuGetConfigBuildProcess; import jetbrains.buildServer.nuget.agent.runner.install.impl.locate.LocateNuGetConfigProcessFactory; import jetbrains.buildServer.nuget.agent.util.impl.CompositeBuildProcessImpl; import jetbrains.buildServer.nuget.common.PackagesConstants; import org.jetbrains.annotations.NotNull; /** * Created by Eugene Petrenko ([email protected]) * Date: 07.07.11 13:55 */ public class PackagesInstallerRunner extends NuGetRunnerBase { private final LocateNuGetConfigProcessFactory myFactory; public PackagesInstallerRunner(@NotNull final NuGetActionFactory actionFactory, @NotNull final PackagesParametersFactory parametersFactory, @NotNull final LocateNuGetConfigProcessFactory factory) { super(actionFactory, parametersFactory); myFactory = factory; } @NotNull public BuildProcess createBuildProcess(@NotNull AgentRunningBuild runningBuild, @NotNull final BuildRunnerContext context) throws RunBuildException { CompositeBuildProcessImpl process = new CompositeBuildProcessImpl(); InstallStages stages = new InstallStagesImpl(process); createStages(context, stages); return process; } private void createStages(@NotNull final BuildRunnerContext context, @NotNull final InstallStages stages) throws RunBuildException { final NuGetFetchParameters parameters = myParametersFactory.loadNuGetFetchParameters(context); final PackagesInstallParameters installParameters = myParametersFactory.loadInstallPackagesParameters(context, parameters); final PackagesUpdateParameters updateParameters = myParametersFactory.loadUpdatePackagesParameters(context, parameters); if (installParameters == null) { throw new RunBuildException("NuGet install packages must be enabled"); } final LocateNuGetConfigBuildProcess locate = myFactory.createPrecess(context, parameters); locate.addInstallStageListener(new PackagesInstallerBuilder( myActionFactory, stages.getInstallStage(), context, installParameters)); - locate.addInstallStageListener(new PackagesUpdateBuilder( - myActionFactory, - stages.getUpdateStage(), - stages.getPostUpdateStart(), - context, - installParameters, - updateParameters)); + if (updateParameters != null) { + locate.addInstallStageListener(new PackagesUpdateBuilder( + myActionFactory, + stages.getUpdateStage(), + stages.getPostUpdateStart(), + context, + installParameters, + updateParameters)); + } locate.addInstallStageListener(new PackagesReportBuilder( myActionFactory, stages.getReportStage(), context)); stages.getLocateStage().pushBuildProcess(locate); } @NotNull public String getType() { return PackagesConstants.INSTALL_RUN_TYPE; } } diff --git a/nuget-tests/src/jetbrains/buildServer/nuget/tests/integration/InstallPackageIntegtatoinTest.java b/nuget-tests/src/jetbrains/buildServer/nuget/tests/integration/InstallPackageIntegtatoinTest.java index 3730d3b3..fdd21982 100644 --- a/nuget-tests/src/jetbrains/buildServer/nuget/tests/integration/InstallPackageIntegtatoinTest.java +++ b/nuget-tests/src/jetbrains/buildServer/nuget/tests/integration/InstallPackageIntegtatoinTest.java @@ -1,336 +1,341 @@ /* * Copyright 2000-2011 JetBrains s.r.o. * * 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 jetbrains.buildServer.nuget.tests.integration; import jetbrains.buildServer.RunBuildException; import jetbrains.buildServer.agent.BuildFinishedStatus; import jetbrains.buildServer.agent.BuildProcess; import jetbrains.buildServer.nuget.agent.dependencies.impl.NuGetPackagesCollectorImpl; import jetbrains.buildServer.nuget.agent.runner.install.PackagesInstallerRunner; import jetbrains.buildServer.nuget.agent.parameters.PackagesInstallParameters; import jetbrains.buildServer.nuget.agent.parameters.PackagesUpdateParameters; import jetbrains.buildServer.nuget.agent.runner.install.impl.RepositoryPathResolverImpl; -import jetbrains.buildServer.nuget.agent.runner.install.impl.locate.LocateNuGetConfigProcessFactory; -import jetbrains.buildServer.nuget.agent.runner.install.impl.locate.PackagesConfigScanner; -import jetbrains.buildServer.nuget.agent.runner.install.impl.locate.ResourcesConfigPackagesScanner; +import jetbrains.buildServer.nuget.agent.runner.install.impl.locate.*; +import jetbrains.buildServer.nuget.agent.util.sln.impl.SolutionParserImpl; import jetbrains.buildServer.nuget.common.PackageInfo; import jetbrains.buildServer.nuget.common.PackagesUpdateMode; import jetbrains.buildServer.util.ArchiveUtil; import jetbrains.buildServer.util.TestFor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jmock.Expectations; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.File; import java.util.*; /** * Created by Eugene Petrenko ([email protected]) * Date: 08.07.11 2:15 */ public class InstallPackageIntegtatoinTest extends IntegrationTestBase { protected PackagesInstallParameters myInstall; protected PackagesUpdateParameters myUpdate; @BeforeMethod @Override protected void setUp() throws Exception { super.setUp(); myInstall = m.mock(PackagesInstallParameters.class); myUpdate = m.mock(PackagesUpdateParameters.class); m.checking(new Expectations(){{ allowing(myInstall).getNuGetParameters(); will(returnValue(myNuGet)); allowing(myUpdate).getNuGetParameters(); will(returnValue(myNuGet)); allowing(myLogger).activityStarted(with(equal("install")), with(any(String.class)), with(any(String.class))); allowing(myLogger).activityFinished(with(equal("install")), with(any(String.class))); }}); } @Test(dataProvider = NUGET_VERSIONS) public void test_01_online_sources(@NotNull final NuGet nuget) throws RunBuildException { ArchiveUtil.unpackZip(getTestDataPath("test-01.zip"), "", myRoot); fetchPackages(new File(myRoot, "sln1-lib.sln"), Collections.<String>emptyList(), false, false, nuget, Arrays.asList( new PackageInfo("Machine.Specifications", "0.4.13.0"), new PackageInfo("NUnit", "2.5.7.10213"), new PackageInfo("Ninject", "2.2.1.4")) ); String packages = "packages"; List<File> packageses = listFiles(packages); System.out.println("installed packageses = " + packageses); Assert.assertTrue(new File(myRoot, "packages/NUnit.2.5.7.10213").isDirectory()); Assert.assertTrue(new File(myRoot, "packages/NInject.2.2.1.4").isDirectory()); Assert.assertTrue(new File(myRoot, "packages/Machine.Specifications.0.4.13.0").isDirectory()); Assert.assertEquals(4, packageses.size()); } @Test(dataProvider = NUGET_VERSIONS) public void test_01_online_sources_update_forConfig(@NotNull final NuGet nuget) throws RunBuildException { ArchiveUtil.unpackZip(getTestDataPath("test-01.zip"), "", myRoot); m.checking(new Expectations() {{ allowing(myLogger).activityStarted(with(equal("update")), with(any(String.class)), with(equal("nuget"))); allowing(myLogger).activityFinished(with(equal("update")), with(equal("nuget"))); allowing(myUpdate).getUseSafeUpdate(); will(returnValue(false)); allowing(myUpdate).getPackagesToUpdate(); will(returnValue(Collections.<String>emptyList())); allowing(myUpdate).getUpdateMode(); will(returnValue(PackagesUpdateMode.FOR_EACH_PACKAGES_CONFIG)); }}); fetchPackages(new File(myRoot, "sln1-lib.sln"), Collections.<String>emptyList(), false, true, nuget, null); List<File> packageses = listFiles("packages"); System.out.println("installed packageses = " + packageses); Assert.assertTrue(new File(myRoot, "packages/NUnit.2.5.7.10213").isDirectory()); Assert.assertTrue(new File(myRoot, "packages/NUnit.2.5.10.11092").isDirectory()); Assert.assertTrue(new File(myRoot, "packages/NInject.2.2.1.4").isDirectory()); Assert.assertTrue(new File(myRoot, "packages/Machine.Specifications.0.4.13.0").isDirectory()); Assert.assertEquals(5, packageses.size()); } @Test(dataProvider = NUGET_VERSIONS) public void test_01_online_sources_update_forSln(@NotNull final NuGet nuget) throws RunBuildException { ArchiveUtil.unpackZip(getTestDataPath("test-01.zip"), "", myRoot); m.checking(new Expectations() {{ allowing(myLogger).activityStarted(with(equal("update")), with(any(String.class)), with(equal("nuget"))); allowing(myLogger).activityFinished(with(equal("update")), with(equal("nuget"))); allowing(myUpdate).getUseSafeUpdate(); will(returnValue(false)); allowing(myUpdate).getPackagesToUpdate(); will(returnValue(Collections.<String>emptyList())); allowing(myUpdate).getUpdateMode(); will(returnValue(PackagesUpdateMode.FOR_SLN)); }}); fetchPackages(new File(myRoot, "sln1-lib.sln"), Collections.<String>emptyList(), false, true, nuget, null); List<File> packageses = listFiles("packages"); System.out.println("installed packageses = " + packageses); Assert.assertTrue(new File(myRoot, "packages/NUnit.2.5.7.10213").isDirectory()); Assert.assertTrue(new File(myRoot, "packages/NUnit.2.5.10.11092").isDirectory()); Assert.assertTrue(new File(myRoot, "packages/NInject.2.2.1.4").isDirectory()); Assert.assertTrue(new File(myRoot, "packages/Machine.Specifications.0.4.13.0").isDirectory()); Assert.assertEquals(5, packageses.size()); } @Test(dataProvider = NUGET_VERSIONS) public void test_01_online_sources_update_safe(@NotNull final NuGet nuget) throws RunBuildException { ArchiveUtil.unpackZip(getTestDataPath("test-01.zip"), "", myRoot); m.checking(new Expectations() {{ allowing(myLogger).activityStarted(with(equal("update")), with(any(String.class)), with(equal("nuget"))); allowing(myLogger).activityFinished(with(equal("update")), with(equal("nuget"))); allowing(myUpdate).getUseSafeUpdate(); will(returnValue(true)); allowing(myUpdate).getPackagesToUpdate(); will(returnValue(Collections.<String>emptyList())); allowing(myUpdate).getUpdateMode(); will(returnValue(PackagesUpdateMode.FOR_EACH_PACKAGES_CONFIG)); }}); fetchPackages(new File(myRoot, "sln1-lib.sln"), Collections.<String>emptyList(), false, true, nuget, null); List<File> packageses = listFiles("packages"); System.out.println("installed packageses = " + packageses); Assert.assertTrue(new File(myRoot, "packages/NUnit.2.5.7.10213").isDirectory()); Assert.assertTrue(new File(myRoot, "packages/NUnit.2.5.10.11092").isDirectory()); Assert.assertTrue(new File(myRoot, "packages/NInject.2.2.1.4").isDirectory()); Assert.assertTrue(new File(myRoot, "packages/Machine.Specifications.0.4.13.0").isDirectory()); Assert.assertEquals(5, packageses.size()); } @Test(dataProvider = NUGET_VERSIONS) public void test_01_online_sources_ecludeVersion(@NotNull final NuGet nuget) throws RunBuildException { ArchiveUtil.unpackZip(getTestDataPath("test-01.zip"), "", myRoot); fetchPackages(new File(myRoot, "sln1-lib.sln"), Collections.<String>emptyList(), true, false, nuget, Arrays.asList( new PackageInfo("Machine.Specifications", "0.4.13.0"), new PackageInfo("NUnit", "2.5.7.10213"), new PackageInfo("Ninject", "2.2.1.4"))); List<File> packageses = listFiles("packages"); System.out.println("installed packageses = " + packageses); Assert.assertTrue(new File(myRoot, "packages/NUnit").isDirectory()); Assert.assertTrue(new File(myRoot, "packages/NInject").isDirectory()); Assert.assertTrue(new File(myRoot, "packages/Machine.Specifications").isDirectory()); Assert.assertEquals(4, packageses.size()); } @Test(enabled = false, dependsOnGroups = "Need to understand how to check NuGet uses only specified sources", dataProvider = NUGET_VERSIONS) public void test_01_local_sources(@NotNull final NuGet nuget) throws RunBuildException { ArchiveUtil.unpackZip(getTestDataPath("test-01.zip"), "", myRoot); File sourcesDir = new File(myRoot, "js"); ArchiveUtil.unpackZip(Paths.getTestDataPath("test-01-sources.zip"), "", sourcesDir); fetchPackages(new File(myRoot, "sln1-lib.sln"), Arrays.asList("file:///" + sourcesDir.getPath()), false, false, nuget, null); List<File> packageses = listFiles("packages"); System.out.println("installed packageses = " + packageses); Assert.assertTrue(new File(myRoot, "packages/NUnit.2.5.7.10213").isDirectory()); Assert.assertTrue(new File(myRoot, "packages/NInject.2.2.1.4").isDirectory()); Assert.assertTrue(new File(myRoot, "packages/Machine.Specifications.0.4.13.0").isDirectory()); Assert.assertEquals(4, packageses.size()); } @Test(dataProvider = NUGET_VERSIONS_15p) public void test_02_NuGetConfig_anoterPackagesPath(@NotNull final NuGet nuget) throws RunBuildException { ArchiveUtil.unpackZip(getTestDataPath("test-02.zip"), "", myRoot); fetchPackages(new File(myRoot, "ConsoleApplication1/ConsoleApplication1.sln"), Collections.<String>emptyList(), true, false, nuget, Arrays.asList( new PackageInfo("Castle.Core", "3.0.0.3001"), new PackageInfo("NUnit", "2.5.10.11092"), new PackageInfo("jQuery", "1.7.1"), new PackageInfo("Microsoft.Web.Infrastructure", "1.0.0.0"), new PackageInfo("WebActivator", "1.5"))); List<File> packageses = listFiles("lib"); System.out.println("installed packageses = " + packageses); Assert.assertTrue(new File(myRoot, "lib/NUnit").isDirectory()); Assert.assertTrue(new File(myRoot, "lib/Castle.Core").isDirectory()); Assert.assertTrue(new File(myRoot, "lib/jQuery").isDirectory()); Assert.assertTrue(new File(myRoot, "lib/Microsoft.Web.Infrastructure").isDirectory()); Assert.assertTrue(new File(myRoot, "lib/WebActivator").isDirectory()); Assert.assertEquals(6, packageses.size()); } @Test(dataProvider = NUGET_VERSIONS_15p, dependsOnGroups = "support no packages scenriod/parse sln/scan projects") public void test_no_packages_scenario(@NotNull final NuGet nuget) throws RunBuildException { ArchiveUtil.unpackZip(getTestDataPath("nuget-nopackages.zip"), "", myRoot); fetchPackages( new File(myRoot, "nuget-nopackages/ConsoleApplication1.sln"), Collections.<String>emptyList(), true, false, nuget, Arrays.asList( new PackageInfo("Castle.Core", "3.0.0.3001"), new PackageInfo("NUnit", "2.5.10.11092"), new PackageInfo("jQuery", "1.7.1"), new PackageInfo("Microsoft.Web.Infrastructure", "1.0.0.0"), new PackageInfo("WebActivator", "1.5"))); List<File> packageses = listFiles("lib"); System.out.println("installed packageses = " + packageses); Assert.assertTrue(new File(myRoot, "lib/NUnit").isDirectory()); Assert.assertTrue(new File(myRoot, "lib/Castle.Core").isDirectory()); Assert.assertTrue(new File(myRoot, "lib/jQuery").isDirectory()); Assert.assertTrue(new File(myRoot, "lib/Microsoft.Web.Infrastructure").isDirectory()); Assert.assertTrue(new File(myRoot, "lib/WebActivator").isDirectory()); Assert.assertEquals(6, packageses.size()); } @TestFor(issues = "TW-21061") @Test(dataProvider = NUGET_VERSIONS_17p) public void test_solution_wide_online_sources(@NotNull final NuGet nuget) throws RunBuildException { ArchiveUtil.unpackZip(getTestDataPath("test-shared-packages.zip"), "", myRoot); fetchPackages(new File(myRoot, "ConsoleApplication1.sln"), Collections.<String>emptyList(), false, false, nuget, Arrays.asList( new PackageInfo("Microsoft.Web.Infrastructure", "1.0.0.0"), new PackageInfo("NUnit", "2.5.10.11092"), new PackageInfo("Ninject", "3.0.0.15"), new PackageInfo("WebActivator", "1.5"), new PackageInfo("jQuery", "1.7.2")) ); List<File> packageses = listFiles("packages"); System.out.println("installed packageses = " + packageses); Assert.assertTrue(new File(myRoot, "packages/Microsoft.Web.Infrastructure.1.0.0.0").isDirectory()); Assert.assertTrue(new File(myRoot, "packages/NUnit.2.5.10.11092").isDirectory()); Assert.assertTrue(new File(myRoot, "packages/NInject.3.0.0.15").isDirectory()); Assert.assertTrue(new File(myRoot, "packages/WebActivator.1.5").isDirectory()); Assert.assertTrue(new File(myRoot, "packages/jQuery.1.7.2").isDirectory()); Assert.assertEquals(5 + 1 , packageses.size()); } private void fetchPackages(final File sln, final List<String> sources, final boolean excludeVersion, final boolean update, @NotNull final NuGet nuget, @Nullable Collection<PackageInfo> detectedPackages) throws RunBuildException { m.checking(new Expectations() {{ allowing(myParametersFactory).loadNuGetFetchParameters(myContext); will(returnValue(myNuGet)); allowing(myParametersFactory).loadInstallPackagesParameters(myContext, myNuGet); will(returnValue(myInstall)); allowing(myNuGet).getNuGetExeFile(); will(returnValue(nuget.getPath())); allowing(myNuGet).getSolutionFile(); will(returnValue(sln)); allowing(myNuGet).getNuGetPackageSources(); will(returnValue(sources)); allowing(myInstall).getExcludeVersion(); will(returnValue(excludeVersion)); allowing(myParametersFactory).loadUpdatePackagesParameters(myContext, myNuGet); will(returnValue(update ? myUpdate : null)); }}); BuildProcess proc = new PackagesInstallerRunner( myActionFactory, myParametersFactory, - new LocateNuGetConfigProcessFactory(new RepositoryPathResolverImpl(), Arrays.<PackagesConfigScanner>asList(new ResourcesConfigPackagesScanner())) + new LocateNuGetConfigProcessFactory( + new RepositoryPathResolverImpl(), + Arrays.asList( + new ResourcesConfigPackagesScanner(), + new SolutionPackagesScanner(new SolutionParserImpl()), + new SolutionWidePackagesConfigScanner()) + ) ).createBuildProcess(myBuild, myContext); ((NuGetPackagesCollectorImpl)myCollector).removeAllPackages(); assertRunSuccessfully(proc, BuildFinishedStatus.FINISHED_SUCCESS); System.out.println(myCollector.getUsedPackages()); if (detectedPackages != null) { Assert.assertEquals( new TreeSet<PackageInfo>(myCollector.getUsedPackages().getUsedPackages()), new TreeSet<PackageInfo>(detectedPackages)); } m.assertIsSatisfied(); } @NotNull private List<File> listFiles(String packages) { final File[] files = new File(myRoot, packages).listFiles(); Assert.assertNotNull(files); return Arrays.asList(files); } }
false
false
null
null
diff --git a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/persistence/entity/HistoricTaskInstanceManager.java b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/persistence/entity/HistoricTaskInstanceManager.java index 6268ec53..2fed6a7d 100644 --- a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/persistence/entity/HistoricTaskInstanceManager.java +++ b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/persistence/entity/HistoricTaskInstanceManager.java @@ -1,148 +1,152 @@ /* 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.activiti.engine.impl.persistence.entity; import java.util.Date; import java.util.List; import org.activiti.engine.ActivitiException; import org.activiti.engine.history.HistoricTaskInstance; import org.activiti.engine.impl.HistoricTaskInstanceQueryImpl; import org.activiti.engine.impl.Page; import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl; import org.activiti.engine.impl.context.Context; import org.activiti.engine.impl.interceptor.CommandContext; import org.activiti.engine.impl.persistence.AbstractHistoricManager; /** * @author Tom Baeyens */ public class HistoricTaskInstanceManager extends AbstractHistoricManager { @SuppressWarnings("unchecked") public void deleteHistoricTaskInstancesByProcessInstanceId(String processInstanceId) { if (historyLevel>=ProcessEngineConfigurationImpl.HISTORYLEVEL_AUDIT) { List<String> taskInstanceIds = (List<String>) getDbSqlSession().selectList("selectHistoricTaskInstanceIdsByProcessInstanceId", processInstanceId); for (String taskInstanceId: taskInstanceIds) { deleteHistoricTaskInstanceById(taskInstanceId); } } } public long findHistoricTaskInstanceCountByQueryCriteria(HistoricTaskInstanceQueryImpl historicTaskInstanceQuery) { return (Long) getDbSqlSession().selectOne("selectHistoricTaskInstanceCountByQueryCriteria", historicTaskInstanceQuery); } @SuppressWarnings("unchecked") public List<HistoricTaskInstance> findHistoricTaskInstancesByQueryCriteria(HistoricTaskInstanceQueryImpl historicTaskInstanceQuery, Page page) { return getDbSqlSession().selectList("selectHistoricTaskInstancesByQueryCriteria", historicTaskInstanceQuery, page); } public HistoricTaskInstanceEntity findHistoricTaskInstanceById(String taskId) { if (taskId == null) { throw new ActivitiException("Invalid historic task id : null"); } return (HistoricTaskInstanceEntity) getDbSqlSession().selectOne("selectHistoricTaskInstance", taskId); } public void deleteHistoricTaskInstanceById(String taskId) { HistoricTaskInstanceEntity historicTaskInstance = findHistoricTaskInstanceById(taskId); if(historicTaskInstance!=null) { CommandContext commandContext = Context.getCommandContext(); commandContext .getHistoricDetailManager() .deleteHistoricDetailsByTaskId(taskId); commandContext .getCommentManager() .deleteCommentsByTaskId(taskId); + commandContext + .getAttachmentManager() + .deleteAttachmentsByTaskId(taskId); + getDbSqlSession().delete(HistoricTaskInstanceEntity.class, taskId); } } public void markTaskInstanceEnded(String taskId, String deleteReason) { if (historyLevel>=ProcessEngineConfigurationImpl.HISTORYLEVEL_AUDIT) { HistoricTaskInstanceEntity historicTaskInstance = getDbSqlSession().selectById(HistoricTaskInstanceEntity.class, taskId); if (historicTaskInstance!=null) { historicTaskInstance.markEnded(deleteReason); } } } public void setTaskAssignee(String taskId, String assignee) { if (historyLevel >= ProcessEngineConfigurationImpl.HISTORYLEVEL_AUDIT) { HistoricTaskInstanceEntity historicTaskInstance = getDbSqlSession().selectById(HistoricTaskInstanceEntity.class, taskId); if (historicTaskInstance!=null) { historicTaskInstance.setAssignee(assignee); } } } public void setTaskOwner(String taskId, String owner) { if (historyLevel >= ProcessEngineConfigurationImpl.HISTORYLEVEL_AUDIT) { HistoricTaskInstanceEntity historicTaskInstance = getDbSqlSession().selectById(HistoricTaskInstanceEntity.class, taskId); if (historicTaskInstance!=null) { historicTaskInstance.setOwner(owner); } } } public void setTaskName(String id, String taskName) { if (historyLevel >= ProcessEngineConfigurationImpl.HISTORYLEVEL_AUDIT) { HistoricTaskInstanceEntity historicTaskInstance = getDbSqlSession().selectById(HistoricTaskInstanceEntity.class, id); if (historicTaskInstance!=null) { historicTaskInstance.setName(taskName); } } } public void setTaskDescription(String id, String description) { if (historyLevel >= ProcessEngineConfigurationImpl.HISTORYLEVEL_AUDIT) { HistoricTaskInstanceEntity historicTaskInstance = getDbSqlSession().selectById(HistoricTaskInstanceEntity.class, id); if (historicTaskInstance!=null) { historicTaskInstance.setDescription(description); } } } public void setTaskDueDate(String id, Date dueDate) { if (historyLevel >= ProcessEngineConfigurationImpl.HISTORYLEVEL_AUDIT) { HistoricTaskInstanceEntity historicTaskInstance = getDbSqlSession().selectById(HistoricTaskInstanceEntity.class, id); if (historicTaskInstance!=null) { historicTaskInstance.setDueDate(dueDate); } } } public void setTaskPriority(String id, int priority) { if (historyLevel >= ProcessEngineConfigurationImpl.HISTORYLEVEL_AUDIT) { HistoricTaskInstanceEntity historicTaskInstance = getDbSqlSession().selectById(HistoricTaskInstanceEntity.class, id); if (historicTaskInstance!=null) { historicTaskInstance.setPriority(priority); } } } public void setTaskParentTaskId(String id, String parentTaskId) { if (historyLevel >= ProcessEngineConfigurationImpl.HISTORYLEVEL_AUDIT) { HistoricTaskInstanceEntity historicTaskInstance = getDbSqlSession().selectById(HistoricTaskInstanceEntity.class, id); if (historicTaskInstance!=null) { historicTaskInstance.setParentTaskId(parentTaskId); } } } } diff --git a/modules/activiti-engine/src/test/java/org/activiti/engine/test/api/task/TaskServiceTest.java b/modules/activiti-engine/src/test/java/org/activiti/engine/test/api/task/TaskServiceTest.java index 5dc97882..9581d532 100644 --- a/modules/activiti-engine/src/test/java/org/activiti/engine/test/api/task/TaskServiceTest.java +++ b/modules/activiti-engine/src/test/java/org/activiti/engine/test/api/task/TaskServiceTest.java @@ -1,767 +1,770 @@ /* 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.activiti.engine.test.api.task; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.activiti.engine.ActivitiException; import org.activiti.engine.history.HistoricTaskInstance; import org.activiti.engine.identity.Group; import org.activiti.engine.identity.User; import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl; import org.activiti.engine.impl.test.PluggableActivitiTestCase; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.engine.task.Attachment; import org.activiti.engine.task.Comment; import org.activiti.engine.task.DelegationState; import org.activiti.engine.task.Event; import org.activiti.engine.task.IdentityLink; import org.activiti.engine.task.IdentityLinkType; import org.activiti.engine.task.Task; import org.activiti.engine.test.Deployment; /** * @author Frederik Heremans * @author Joram Barrez */ public class TaskServiceTest extends PluggableActivitiTestCase { public void testSaveTaskUpdate() throws Exception{ SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss"); Task task = taskService.newTask(); task.setDescription("description"); task.setName("taskname"); task.setPriority(0); task.setAssignee("taskassignee"); task.setOwner("taskowner"); Date dueDate = sdf.parse("01/02/2003 04:05:06"); task.setDueDate(dueDate); taskService.saveTask(task); // Fetch the task again and update task = taskService.createTaskQuery().taskId(task.getId()).singleResult(); assertEquals("description", task.getDescription()); assertEquals("taskname", task.getName()); assertEquals("taskassignee", task.getAssignee()); assertEquals("taskowner", task.getOwner()); assertEquals(dueDate, task.getDueDate()); assertEquals(0, task.getPriority()); task.setName("updatedtaskname"); task.setDescription("updateddescription"); task.setPriority(1); task.setAssignee("updatedassignee"); task.setOwner("updatedowner"); dueDate = sdf.parse("01/02/2003 04:05:06"); task.setDueDate(dueDate); taskService.saveTask(task); task = taskService.createTaskQuery().taskId(task.getId()).singleResult(); assertEquals("updatedtaskname", task.getName()); assertEquals("updateddescription", task.getDescription()); assertEquals("updatedassignee", task.getAssignee()); assertEquals("updatedowner", task.getOwner()); assertEquals(dueDate, task.getDueDate()); assertEquals(1, task.getPriority()); HistoricTaskInstance historicTaskInstance = historyService .createHistoricTaskInstanceQuery() .taskId(task.getId()) .singleResult(); assertEquals("updatedtaskname", historicTaskInstance.getName()); assertEquals("updateddescription", historicTaskInstance.getDescription()); assertEquals("updatedassignee", historicTaskInstance.getAssignee()); assertEquals("updatedowner", historicTaskInstance.getOwner()); assertEquals(dueDate, historicTaskInstance.getDueDate()); assertEquals(1, historicTaskInstance.getPriority()); // Finally, delete task taskService.deleteTask(task.getId(), true); } public void testTaskOwner() { Task task = taskService.newTask(); task.setOwner("johndoe"); taskService.saveTask(task); // Fetch the task again and update task = taskService.createTaskQuery().taskId(task.getId()).singleResult(); assertEquals("johndoe", task.getOwner()); task.setOwner("joesmoe"); taskService.saveTask(task); task = taskService.createTaskQuery().taskId(task.getId()).singleResult(); assertEquals("joesmoe", task.getOwner()); // Finally, delete task taskService.deleteTask(task.getId(), true); } public void testTaskComments() { int historyLevel = processEngineConfiguration.getHistoryLevel(); if (historyLevel>ProcessEngineConfigurationImpl.HISTORYLEVEL_NONE) { Task task = taskService.newTask(); task.setOwner("johndoe"); taskService.saveTask(task); String taskId = task.getId(); identityService.setAuthenticatedUserId("johndoe"); // Fetch the task again and update taskService.addComment(taskId, null, "look at this \n isn't this great? slkdjf sldkfjs ldkfjs ldkfjs ldkfj sldkfj sldkfj sldkjg laksfg sdfgsd;flgkj ksajdhf skjdfh ksjdhf skjdhf kalskjgh lskh dfialurhg kajsh dfuieqpgkja rzvkfnjviuqerhogiuvysbegkjz lkhf ais liasduh flaisduh ajiasudh vaisudhv nsfd"); Comment comment = taskService.getTaskComments(taskId).get(0); assertEquals("johndoe", comment.getUserId()); assertEquals(taskId, comment.getTaskId()); assertNull(comment.getProcessInstanceId()); assertEquals("look at this isn't this great? slkdjf sldkfjs ldkfjs ldkfjs ldkfj sldkfj sldkfj sldkjg laksfg sdfgsd;flgkj ksajdhf skjdfh ksjdhf skjdhf kalskjgh lskh dfialurhg ...", ((Event)comment).getMessage()); assertEquals("look at this \n isn't this great? slkdjf sldkfjs ldkfjs ldkfjs ldkfj sldkfj sldkfj sldkjg laksfg sdfgsd;flgkj ksajdhf skjdfh ksjdhf skjdhf kalskjgh lskh dfialurhg kajsh dfuieqpgkja rzvkfnjviuqerhogiuvysbegkjz lkhf ais liasduh flaisduh ajiasudh vaisudhv nsfd", comment.getFullMessage()); assertNotNull(comment.getTime()); taskService.addComment(taskId, "pid", "one"); taskService.addComment(taskId, "pid", "two"); Set<String> expectedComments = new HashSet<String>(); expectedComments.add("one"); expectedComments.add("two"); Set<String> comments = new HashSet<String>(); for (Comment cmt: taskService.getProcessInstanceComments("pid")) { comments.add(cmt.getFullMessage()); } assertEquals(expectedComments, comments); // Finally, delete task taskService.deleteTask(taskId, true); } } public void testTaskAttachments() { int historyLevel = processEngineConfiguration.getHistoryLevel(); if (historyLevel>ProcessEngineConfigurationImpl.HISTORYLEVEL_NONE) { Task task = taskService.newTask(); task.setOwner("johndoe"); taskService.saveTask(task); String taskId = task.getId(); identityService.setAuthenticatedUserId("johndoe"); // Fetch the task again and update taskService.createAttachment("web page", taskId, "someprocessinstanceid", "weatherforcast", "temperatures and more", "http://weather.com"); Attachment attachment = taskService.getTaskAttachments(taskId).get(0); assertEquals("weatherforcast", attachment.getName()); assertEquals("temperatures and more", attachment.getDescription()); assertEquals("web page", attachment.getType()); assertEquals(taskId, attachment.getTaskId()); assertEquals("someprocessinstanceid", attachment.getProcessInstanceId()); assertEquals("http://weather.com", attachment.getUrl()); assertNull(taskService.getAttachmentContent(attachment.getId())); // Finally, clean up + taskService.deleteTask(taskId); + + assertEquals(0, taskService.getTaskComments(taskId).size()); + taskService.deleteTask(taskId, true); - taskService.deleteAttachment(attachment.getId()); } } public void testTaskDelegation() { Task task = taskService.newTask(); task.setOwner("johndoe"); task.delegate("joesmoe"); taskService.saveTask(task); String taskId = task.getId(); task = taskService.createTaskQuery().taskId(taskId).singleResult(); assertEquals("johndoe", task.getOwner()); assertEquals("joesmoe", task.getAssignee()); assertEquals(DelegationState.PENDING, task.getDelegationState()); taskService.resolveTask(taskId); task = taskService.createTaskQuery().taskId(taskId).singleResult(); assertEquals("johndoe", task.getOwner()); assertEquals("johndoe", task.getAssignee()); assertEquals(DelegationState.RESOLVED, task.getDelegationState()); task.setAssignee(null); task.setDelegationState(null); taskService.saveTask(task); task = taskService.createTaskQuery().taskId(taskId).singleResult(); assertEquals("johndoe", task.getOwner()); assertNull(task.getAssignee()); assertNull(task.getDelegationState()); task.setAssignee("jackblack"); task.setDelegationState(DelegationState.RESOLVED); taskService.saveTask(task); task = taskService.createTaskQuery().taskId(taskId).singleResult(); assertEquals("johndoe", task.getOwner()); assertEquals("jackblack", task.getAssignee()); assertEquals(DelegationState.RESOLVED, task.getDelegationState()); // Finally, delete task taskService.deleteTask(taskId, true); } public void testTaskDelegationThroughServiceCall() { Task task = taskService.newTask(); task.setOwner("johndoe"); taskService.saveTask(task); String taskId = task.getId(); // Fetch the task again and update task = taskService.createTaskQuery().taskId(taskId).singleResult(); taskService.delegateTask(taskId, "joesmoe"); task = taskService.createTaskQuery().taskId(taskId).singleResult(); assertEquals("johndoe", task.getOwner()); assertEquals("joesmoe", task.getAssignee()); assertEquals(DelegationState.PENDING, task.getDelegationState()); taskService.resolveTask(taskId); task = taskService.createTaskQuery().taskId(taskId).singleResult(); assertEquals("johndoe", task.getOwner()); assertEquals("johndoe", task.getAssignee()); assertEquals(DelegationState.RESOLVED, task.getDelegationState()); // Finally, delete task taskService.deleteTask(taskId, true); } public void testTaskAssignee() { Task task = taskService.newTask(); task.setAssignee("johndoe"); taskService.saveTask(task); // Fetch the task again and update task = taskService.createTaskQuery().taskId(task.getId()).singleResult(); assertEquals("johndoe", task.getAssignee()); task.setAssignee("joesmoe"); taskService.saveTask(task); task = taskService.createTaskQuery().taskId(task.getId()).singleResult(); assertEquals("joesmoe", task.getAssignee()); // Finally, delete task taskService.deleteTask(task.getId(), true); } public void testSaveTaskNullTask() { try { taskService.saveTask(null); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("task is null", ae.getMessage()); } } public void testDeleteTaskNullTaskId() { try { taskService.deleteTask(null); fail("ActivitiException expected"); } catch (ActivitiException ae) { // Expected exception } } public void testDeleteTaskUnexistingTaskId() { // Deleting unexisting task should be silently ignored taskService.deleteTask("unexistingtaskid"); } public void testDeleteTasksNullTaskIds() { try { taskService.deleteTasks(null); fail("ActivitiException expected"); } catch (ActivitiException ae) { // Expected exception } } public void testDeleteTasksTaskIdsUnexistingTaskId() { Task existingTask = taskService.newTask(); taskService.saveTask(existingTask); // The unexisting taskId's should be silently ignored. Existing task should // have been deleted. taskService.deleteTasks(Arrays.asList("unexistingtaskid1", existingTask.getId()), true); existingTask = taskService.createTaskQuery().taskId(existingTask.getId()).singleResult(); assertNull(existingTask); } public void testClaimNullArguments() { try { taskService.claim(null, "userid"); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("taskId is null", ae.getMessage()); } } public void testClaimUnexistingTaskId() { User user = identityService.newUser("user"); identityService.saveUser(user); try { taskService.claim("unexistingtaskid", user.getId()); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("Cannot find task with id unexistingtaskid", ae.getMessage()); } identityService.deleteUser(user.getId()); } public void testClaimAlreadyClaimedTaskByOtherUser() { Task task = taskService.newTask(); taskService.saveTask(task); User user = identityService.newUser("user"); identityService.saveUser(user); User secondUser = identityService.newUser("seconduser"); identityService.saveUser(secondUser); // Claim task the first time taskService.claim(task.getId(), user.getId()); try { taskService.claim(task.getId(), secondUser.getId()); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("Task " + task.getId() + " is already claimed by someone else", ae.getMessage()); } taskService.deleteTask(task.getId(), true); identityService.deleteUser(user.getId()); identityService.deleteUser(secondUser.getId()); } public void testClaimAlreadyClaimedTaskBySameUser() { Task task = taskService.newTask(); taskService.saveTask(task); User user = identityService.newUser("user"); identityService.saveUser(user); // Claim task the first time taskService.claim(task.getId(), user.getId()); task = taskService.createTaskQuery().taskId(task.getId()).singleResult(); // Claim the task again with the same user. No exception should be thrown taskService.claim(task.getId(), user.getId()); taskService.deleteTask(task.getId(), true); identityService.deleteUser(user.getId()); } public void testUnClaimTask() { Task task = taskService.newTask(); taskService.saveTask(task); User user = identityService.newUser("user"); identityService.saveUser(user); // Claim task the first time taskService.claim(task.getId(), user.getId()); task = taskService.createTaskQuery().taskId(task.getId()).singleResult(); assertEquals(user.getId(), task.getAssignee()); // Unclaim the task taskService.claim(task.getId(), null); task = taskService.createTaskQuery().taskId(task.getId()).singleResult(); assertNull(task.getAssignee()); taskService.deleteTask(task.getId(), true); identityService.deleteUser(user.getId()); } public void testCompleteTaskNullTaskId() { try { taskService.complete(null); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("taskId is null", ae.getMessage()); } } public void testCompleteTaskUnexistingTaskId() { try { taskService.complete("unexistingtask"); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("Cannot find task with id unexistingtask", ae.getMessage()); } } public void testCompleteTaskWithParametersNullTaskId() { try { taskService.complete(null); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("taskId is null", ae.getMessage()); } } public void testCompleteTaskWithParametersUnexistingTaskId() { try { taskService.complete("unexistingtask"); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("Cannot find task with id unexistingtask", ae.getMessage()); } } public void testCompleteTaskWithParametersNullParameters() { Task task = taskService.newTask(); taskService.saveTask(task); String taskId = task.getId(); taskService.complete(taskId, null); if (processEngineConfiguration.getHistoryLevel()>=ProcessEngineConfigurationImpl.HISTORYLEVEL_AUDIT) { historyService.deleteHistoricTaskInstance(taskId); } // Fetch the task again task = taskService.createTaskQuery().taskId(taskId).singleResult(); assertNull(task); } @SuppressWarnings("unchecked") public void testCompleteTaskWithParametersEmptyParameters() { Task task = taskService.newTask(); taskService.saveTask(task); String taskId = task.getId(); taskService.complete(taskId, Collections.EMPTY_MAP); if (processEngineConfiguration.getHistoryLevel()>=ProcessEngineConfigurationImpl.HISTORYLEVEL_AUDIT) { historyService.deleteHistoricTaskInstance(taskId); } // Fetch the task again task = taskService.createTaskQuery().taskId(taskId).singleResult(); assertNull(task); } @Deployment(resources = { "org/activiti/engine/test/api/twoTasksProcess.bpmn20.xml" }) public void testCompleteWithParametersTask() { ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("twoTasksProcess"); // Fetch first task Task task = taskService.createTaskQuery().singleResult(); assertEquals("First task", task.getName()); // Complete first task Map<String, Object> taskParams = new HashMap<String, Object>(); taskParams.put("myParam", "myValue"); taskService.complete(task.getId(), taskParams); // Fetch second task task = taskService.createTaskQuery().singleResult(); assertEquals("Second task", task.getName()); // Verify task parameters set on execution Map<String, Object> variables = runtimeService.getVariables(processInstance.getId()); assertEquals(1, variables.size()); assertEquals("myValue", variables.get("myParam")); taskService.deleteTask(task.getId(), true); } public void testSetAssignee() { User user = identityService.newUser("user"); identityService.saveUser(user); Task task = taskService.newTask(); assertNull(task.getAssignee()); taskService.saveTask(task); // Set assignee taskService.setAssignee(task.getId(), user.getId()); // Fetch task again task = taskService.createTaskQuery().taskId(task.getId()).singleResult(); assertEquals(user.getId(), task.getAssignee()); identityService.deleteUser(user.getId()); taskService.deleteTask(task.getId(), true); } public void testSetAssigneeNullTaskId() { try { taskService.setAssignee(null, "userId"); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("taskId is null", ae.getMessage()); } } public void testSetAssigneeUnexistingTask() { User user = identityService.newUser("user"); identityService.saveUser(user); try { taskService.setAssignee("unexistingTaskId", user.getId()); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("Cannot find task with id unexistingTaskId", ae.getMessage()); } identityService.deleteUser(user.getId()); } public void testAddCandidateUserDuplicate() { // Check behavior when adding the same user twice as candidate User user = identityService.newUser("user"); identityService.saveUser(user); Task task = taskService.newTask(); taskService.saveTask(task); taskService.addCandidateUser(task.getId(), user.getId()); // Add as candidate the second time taskService.addCandidateUser(task.getId(), user.getId()); identityService.deleteUser(user.getId()); taskService.deleteTask(task.getId(), true); } public void testAddCandidateUserNullTaskId() { try { taskService.addCandidateUser(null, "userId"); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("taskId is null", ae.getMessage()); } } public void testAddCandidateUserNullUserId() { try { taskService.addCandidateUser("taskId", null); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("userId and groupId cannot both be null", ae.getMessage()); } } public void testAddCandidateUserUnexistingTask() { User user = identityService.newUser("user"); identityService.saveUser(user); try { taskService.addCandidateUser("unexistingTaskId", user.getId()); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("Cannot find task with id unexistingTaskId", ae.getMessage()); } identityService.deleteUser(user.getId()); } public void testAddCandidateGroupNullTaskId() { try { taskService.addCandidateGroup(null, "groupId"); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("taskId is null", ae.getMessage()); } } public void testAddCandidateGroupNullGroupId() { try { taskService.addCandidateGroup("taskId", null); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("userId and groupId cannot both be null", ae.getMessage()); } } public void testAddCandidateGroupUnexistingTask() { Group group = identityService.newGroup("group"); identityService.saveGroup(group); try { taskService.addCandidateGroup("unexistingTaskId", group.getId()); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("Cannot find task with id unexistingTaskId", ae.getMessage()); } identityService.deleteGroup(group.getId()); } public void testAddGroupIdentityLinkNullTaskId() { try { taskService.addGroupIdentityLink(null, "groupId", IdentityLinkType.CANDIDATE); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("taskId is null", ae.getMessage()); } } public void testAddGroupIdentityLinkNullUserId() { try { taskService.addGroupIdentityLink("taskId", null, IdentityLinkType.CANDIDATE); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("userId and groupId cannot both be null", ae.getMessage()); } } public void testAddGroupIdentityLinkUnexistingTask() { User user = identityService.newUser("user"); identityService.saveUser(user); try { taskService.addGroupIdentityLink("unexistingTaskId", user.getId(), IdentityLinkType.CANDIDATE); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("Cannot find task with id unexistingTaskId", ae.getMessage()); } identityService.deleteUser(user.getId()); } public void testAddUserIdentityLinkNullTaskId() { try { taskService.addUserIdentityLink(null, "userId", IdentityLinkType.CANDIDATE); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("taskId is null", ae.getMessage()); } } public void testAddUserIdentityLinkNullUserId() { try { taskService.addUserIdentityLink("taskId", null, IdentityLinkType.CANDIDATE); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("userId and groupId cannot both be null", ae.getMessage()); } } public void testAddUserIdentityLinkUnexistingTask() { User user = identityService.newUser("user"); identityService.saveUser(user); try { taskService.addUserIdentityLink("unexistingTaskId", user.getId(), IdentityLinkType.CANDIDATE); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("Cannot find task with id unexistingTaskId", ae.getMessage()); } identityService.deleteUser(user.getId()); } public void testGetIdentityLinksWithCandidateUser() { Task task = taskService.newTask(); taskService.saveTask(task); String taskId = task.getId(); identityService.saveUser(identityService.newUser("kermit")); taskService.addCandidateUser(taskId, "kermit"); List<IdentityLink> identityLinks = taskService.getIdentityLinksForTask(taskId); assertEquals(1, identityLinks.size()); assertEquals("kermit", identityLinks.get(0).getUserId()); assertNull(identityLinks.get(0).getGroupId()); assertEquals(IdentityLinkType.CANDIDATE, identityLinks.get(0).getType()); //cleanup taskService.deleteTask(taskId, true); identityService.deleteUser("kermit"); } public void testGetIdentityLinksWithCandidateGroup() { Task task = taskService.newTask(); taskService.saveTask(task); String taskId = task.getId(); identityService.saveGroup(identityService.newGroup("muppets")); taskService.addCandidateGroup(taskId, "muppets"); List<IdentityLink> identityLinks = taskService.getIdentityLinksForTask(taskId); assertEquals(1, identityLinks.size()); assertEquals("muppets", identityLinks.get(0).getGroupId()); assertNull(identityLinks.get(0).getUserId()); assertEquals(IdentityLinkType.CANDIDATE, identityLinks.get(0).getType()); //cleanup taskService.deleteTask(taskId, true); identityService.deleteGroup("muppets"); } public void testGetIdentityLinksWithAssignee() { Task task = taskService.newTask(); taskService.saveTask(task); String taskId = task.getId(); identityService.saveUser(identityService.newUser("kermit")); taskService.claim(taskId, "kermit"); List<IdentityLink> identityLinks = taskService.getIdentityLinksForTask(taskId); assertEquals(1, identityLinks.size()); assertEquals("kermit", identityLinks.get(0).getUserId()); assertNull(identityLinks.get(0).getGroupId()); assertEquals(IdentityLinkType.ASSIGNEE, identityLinks.get(0).getType()); //cleanup taskService.deleteTask(taskId, true); identityService.deleteUser("kermit"); } public void testSetPriority() { Task task = taskService.newTask(); taskService.saveTask(task); taskService.setPriority(task.getId(), 12345); // Fetch task again to check if the priority is set task = taskService.createTaskQuery().taskId(task.getId()).singleResult(); assertEquals(12345, task.getPriority()); taskService.deleteTask(task.getId(), true); } public void testSetPriorityUnexistingTaskId() { try { taskService.setPriority("unexistingtask", 12345); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("Cannot find task with id unexistingtask", ae.getMessage()); } } public void testSetPriorityNullTaskId() { try { taskService.setPriority(null, 12345); fail("ActivitiException expected"); } catch (ActivitiException ae) { assertTextPresent("taskId is null", ae.getMessage()); } } }
false
false
null
null
diff --git a/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/assets/SRSCachingInterceptor.java b/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/assets/SRSCachingInterceptor.java index cf3780836..b4cc161a3 100644 --- a/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/assets/SRSCachingInterceptor.java +++ b/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/assets/SRSCachingInterceptor.java @@ -1,78 +1,90 @@ // Copyright 2011, 2012 The Apache Software Foundation // // 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.apache.tapestry5.internal.services.assets; import org.apache.tapestry5.internal.TapestryInternalUtils; import org.apache.tapestry5.ioc.Resource; import org.apache.tapestry5.ioc.internal.util.CollectionFactory; import org.apache.tapestry5.services.assets.ResourceDependencies; import org.apache.tapestry5.services.assets.StreamableResource; import org.apache.tapestry5.services.assets.StreamableResourceProcessing; import org.apache.tapestry5.services.assets.StreamableResourceSource; import java.io.IOException; import java.lang.ref.SoftReference; import java.util.Map; /** * An interceptor for the {@link StreamableResourceSource} service that handles caching of content. */ public class SRSCachingInterceptor extends DelegatingSRS { private final Map<Resource, SoftReference<StreamableResource>> cache = CollectionFactory.newConcurrentMap(); public SRSCachingInterceptor(StreamableResourceSource delegate, ResourceChangeTracker tracker) { super(delegate); tracker.clearOnInvalidation(cache); } public StreamableResource getStreamableResource(Resource baseResource, StreamableResourceProcessing processing, ResourceDependencies dependencies) throws IOException { - if (processing == StreamableResourceProcessing.FOR_AGGREGATION) + if (!enableCache(processing)) { return delegate.getStreamableResource(baseResource, processing, dependencies); } StreamableResource result = TapestryInternalUtils.getAndDeref(cache, baseResource); if (result == null) { result = delegate.getStreamableResource(baseResource, processing, dependencies); if (isCacheable(result)) { dependencies.addDependency(baseResource); cache.put(baseResource, new SoftReference<StreamableResource>(result)); } } return result; } /** * Always returns true; a subclass may extend this to only cache the resource in some circumstances. * * @param resource * @return true to cache the resource */ protected boolean isCacheable(StreamableResource resource) { return true; } + + /** + * Returns true unless the processing is {@link StreamableResourceProcessing#FOR_AGGREGATION}. + * Subclasses may override. When the cache is not enabled, the request is passed on to the interceptor's + * {@link #delegate}, and no attempt is made to read or update this interceptor's cache. + * + * @since 5.3.5 + */ + protected boolean enableCache(StreamableResourceProcessing processing) + { + return processing != StreamableResourceProcessing.FOR_AGGREGATION; + } } diff --git a/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/assets/SRSCompressedCachingInterceptor.java b/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/assets/SRSCompressedCachingInterceptor.java index ce95a39cb..4e138773a 100644 --- a/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/assets/SRSCompressedCachingInterceptor.java +++ b/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/assets/SRSCompressedCachingInterceptor.java @@ -1,41 +1,50 @@ // Copyright 2011, 2012 The Apache Software Foundation // // 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.apache.tapestry5.internal.services.assets; import org.apache.tapestry5.services.assets.CompressionStatus; import org.apache.tapestry5.services.assets.StreamableResource; +import org.apache.tapestry5.services.assets.StreamableResourceProcessing; import org.apache.tapestry5.services.assets.StreamableResourceSource; /** * Specialization of {@link SRSCachingInterceptor} that only attempts to cache * compressed resources. */ public class SRSCompressedCachingInterceptor extends SRSCachingInterceptor { public SRSCompressedCachingInterceptor(StreamableResourceSource delegate, ResourceChangeTracker tracker) { super(delegate, tracker); } /** * Return true only if the resource is compressed. */ @Override protected boolean isCacheable(StreamableResource resource) { return resource.getCompression() == CompressionStatus.COMPRESSED; } + /** + * Returns true just when the processing enables compression. + */ + @Override + protected boolean enableCache(StreamableResourceProcessing processing) + { + return processing == StreamableResourceProcessing.COMPRESSION_ENABLED; + } }
false
false
null
null
diff --git a/Core/src/org/sleuthkit/autopsy/core/Installer.java b/Core/src/org/sleuthkit/autopsy/core/Installer.java index fc791743f..218c00c3a 100644 --- a/Core/src/org/sleuthkit/autopsy/core/Installer.java +++ b/Core/src/org/sleuthkit/autopsy/core/Installer.java @@ -1,216 +1,216 @@ /* * Autopsy Forensic Browser * * Copyright 2011 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * 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.sleuthkit.autopsy.core; import com.sun.javafx.application.PlatformImpl; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import javafx.application.Platform; import org.sleuthkit.autopsy.coreutils.Logger; import org.openide.modules.ModuleInstall; import org.openide.windows.WindowManager; import org.sleuthkit.autopsy.casemodule.Case; import org.sleuthkit.autopsy.coreutils.MessageNotifyUtil; import org.sleuthkit.autopsy.coreutils.PlatformUtil; /** * Wrapper over Installers in packages in Core module This is the main * registered installer in the MANIFEST.MF */ public class Installer extends ModuleInstall { private List<ModuleInstall> packageInstallers; private static final Logger logger = Logger.getLogger(Installer.class.getName()); private volatile boolean javaFxInit = true; static { loadDynLibraries(); } private static void loadDynLibraries() { if (PlatformUtil.isWindowsOS()) { try { //on windows force loading ms crt dependencies first //in case linker can't find them on some systems //Note: if shipping with a different CRT version, this will only print a warning //and try to use linker mechanism to find the correct versions of libs. //We should update this if we officially switch to a new version of CRT/compiler System.loadLibrary("msvcr100"); System.loadLibrary("msvcp100"); logger.log(Level.INFO, "MS CRT libraries loaded"); } catch (UnsatisfiedLinkError e) { logger.log(Level.SEVERE, "Error loading ms crt libraries, ", e); } } try { System.loadLibrary("zlib"); logger.log(Level.INFO, "ZLIB library loaded loaded"); } catch (UnsatisfiedLinkError e) { logger.log(Level.SEVERE, "Error loading ZLIB library, ", e); } try { System.loadLibrary("libewf"); logger.log(Level.INFO, "EWF library loaded"); } catch (UnsatisfiedLinkError e) { logger.log(Level.SEVERE, "Error loading EWF library, ", e); } /* We should rename the Windows dll, to remove the lib prefix. */ try { String tskLibName = null; if (PlatformUtil.isWindowsOS()) { tskLibName = "libtsk_jni"; } else { tskLibName = "tsk_jni"; } System.loadLibrary(tskLibName); logger.log(Level.INFO, "TSK_JNI library loaded"); } catch (UnsatisfiedLinkError e) { logger.log(Level.SEVERE, "Error loading tsk_jni library", e); } } public Installer() { javaFxInit = true; packageInstallers = new ArrayList<ModuleInstall>(); packageInstallers.add(org.sleuthkit.autopsy.coreutils.Installer.getDefault()); packageInstallers.add(org.sleuthkit.autopsy.corecomponents.Installer.getDefault()); packageInstallers.add(org.sleuthkit.autopsy.datamodel.Installer.getDefault()); packageInstallers.add(org.sleuthkit.autopsy.ingest.Installer.getDefault()); } /** * Check if JavaFx initialized * @return false if java fx not initialized (classes coult not load), true if initialized */ public boolean isJavaFxInited() { return this.javaFxInit; } private void initJavaFx() { //initialize java fx if exists try { Platform.setImplicitExit(false); PlatformImpl.startup(new Runnable() { @Override public void run() { logger.log(Level.INFO, "Initializing JavaFX for image viewing"); } }); } catch (UnsatisfiedLinkError | NoClassDefFoundError | Exception e) { //in case javafx not present javaFxInit = false; final String msg = "Error initializing JavaFX. "; final String details = " Some features will not be available. " - + " Check that you have the right JRE installed (Sun JRE > 1.7.10). "; + + " Check that you have the right JRE installed (Oracle JRE > 1.7.10). "; logger.log(Level.SEVERE, msg + details, e); WindowManager.getDefault().invokeWhenUIReady(new Runnable() { @Override public void run() { MessageNotifyUtil.Notify.error(msg, details); } }); } } @Override public void restored() { super.restored(); logger.log(Level.INFO, "restored()"); initJavaFx(); for (ModuleInstall mi : packageInstallers) { logger.log(Level.INFO, mi.getClass().getName() + " restored()"); try { mi.restored(); } catch (Exception e) { logger.log(Level.WARNING, "", e); } } } @Override public void validate() throws IllegalStateException { super.validate(); logger.log(Level.INFO, "validate()"); for (ModuleInstall mi : packageInstallers) { logger.log(Level.INFO, mi.getClass().getName() + " validate()"); try { mi.validate(); } catch (Exception e) { logger.log(Level.WARNING, "", e); } } } @Override public void uninstalled() { super.uninstalled(); logger.log(Level.INFO, "uninstalled()"); for (ModuleInstall mi : packageInstallers) { logger.log(Level.INFO, mi.getClass().getName() + " uninstalled()"); try { mi.uninstalled(); } catch (Exception e) { logger.log(Level.WARNING, "", e); } } } @Override public void close() { super.close(); logger.log(Level.INFO, "close()"); //exit JavaFx plat if (javaFxInit) { Platform.exit(); } for (ModuleInstall mi : packageInstallers) { logger.log(Level.INFO, mi.getClass().getName() + " close()"); try { mi.close(); } catch (Exception e) { logger.log(Level.WARNING, "", e); } } } }
true
false
null
null
diff --git a/org.amanzi.awe.afp/src/org/amanzi/awe/afp/wizards/AfpWizardPage.java b/org.amanzi.awe.afp/src/org/amanzi/awe/afp/wizards/AfpWizardPage.java index fb6af128e..921680bd8 100644 --- a/org.amanzi.awe.afp/src/org/amanzi/awe/afp/wizards/AfpWizardPage.java +++ b/org.amanzi.awe.afp/src/org/amanzi/awe/afp/wizards/AfpWizardPage.java @@ -1,470 +1,470 @@ package org.amanzi.awe.afp.wizards; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import org.amanzi.awe.afp.filters.AfpTRXFilter; import org.amanzi.awe.afp.models.AfpModel; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Point; 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.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import org.neo4j.graphdb.Node; public class AfpWizardPage extends WizardPage implements SelectionListener { public static final String ASSIGN = "assign"; public static final String CLEAR = "clear"; public static final String LOAD = "load"; private Label filterInfoLabel; private Group trxFilterGroup; private Label siteFilterInfoLabel; private Group siteTrxFilterGroup; protected AfpModel model; private TableViewer viewer; private AfpTRXFilter filter; private FilterListener listener; protected Button assignButton; protected HashMap<String,Set<Object>> uniqueSitePropertyValues = new HashMap<String,Set<Object>>(); protected HashMap<String,Set<Object>> uniqueSectorPropertyValues = new HashMap<String,Set<Object>>(); protected HashMap<String,Set<Object>> uniqueTrxPropertyValues = new HashMap<String,Set<Object>>(); protected AfpWizardPage(String pageName) { super(pageName); for(String p: AfpModel.sitePropertiesName) { uniqueSitePropertyValues.put(p, new HashSet<Object>()); } for(String p: AfpModel.sectorPropertiesName) { uniqueSectorPropertyValues.put(p, new HashSet<Object>()); } for(String p: AfpModel.trxPropertiesName) { uniqueTrxPropertyValues.put(p, new HashSet<Object>()); } } protected AfpWizardPage(String pageName, AfpModel model) { super(pageName); this.model = model; for(String p: AfpModel.sitePropertiesName) { uniqueSitePropertyValues.put(p, new HashSet<Object>()); } for(String p: AfpModel.sectorPropertiesName) { uniqueSectorPropertyValues.put(p, new HashSet<Object>()); } for(String p: AfpModel.trxPropertiesName) { uniqueTrxPropertyValues.put(p, new HashSet<Object>()); } } @Override public void createControl(Composite parent) { // TODO Auto-generated method stub } public void refreshPage() { if (this instanceof AfpSeparationRulesPage){ updateSectorFilterLabel(model.getTotalSectors(), model.getTotalSectors()); updateSiteFilterLabel(model.getTotalSites(), model.getTotalSites()); } else if(this instanceof AfpSYHoppingMALsPage){ // updateTRXFilterLabel(0, model.getTotalRemainingMalTRX()); } else{ updateTRXFilterLabel(model.getTotalTRX(),model.getTotalRemainingTRX()); } } public void updateTRXFilterLabel(int selected, int total){ filterInfoLabel.setText(String.format("Filter Status: %d Trxs selected out of %d", selected, total)); trxFilterGroup.layout(); } public void updateSectorFilterLabel(int selected, int total){ filterInfoLabel.setText(String.format("Filter Status: %d sectors selected out of %d", selected, total)); trxFilterGroup.layout(); } public void updateSiteFilterLabel(int selected, int total){ siteFilterInfoLabel.setText(String.format("Filter Status: %d sites selected out of %d", selected, total)); siteTrxFilterGroup.layout(); } protected Table addTRXFilterGroup(Group main, String[] headers, int emptyrows, boolean isSite, FilterListener listener, String[] noListenerHeaders){ final Shell parentShell = main.getShell(); this.listener = listener; Arrays.sort(noListenerHeaders); parentShell.addMouseListener(new MouseListener(){ @Override public void mouseDoubleClick(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseDown(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseUp(MouseEvent e) { // TODO Auto-generated method stub } }); /** Create TRXs Filters Group */ Group trxFilterGroup = new Group(main, SWT.NONE); trxFilterGroup.setLayout(new GridLayout(4, false)); trxFilterGroup.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false,1 ,2)); trxFilterGroup.setText("TRXs Filter"); Label filterInfoLabel = new Label(trxFilterGroup, SWT.LEFT); if (isSite){ this.siteTrxFilterGroup = trxFilterGroup; this.siteFilterInfoLabel = filterInfoLabel; } else { this.trxFilterGroup = trxFilterGroup; this.filterInfoLabel = filterInfoLabel; } Button loadButton = new Button(trxFilterGroup, SWT.RIGHT); loadButton.setLayoutData(new GridData(GridData.END, GridData.BEGINNING, true, false, 1 , 1)); loadButton.setText("Load"); loadButton.setData(LOAD); loadButton.setEnabled(false); loadButton.addSelectionListener(this); Button clearButton = new Button(trxFilterGroup, SWT.RIGHT); clearButton.setLayoutData(new GridData(GridData.END, GridData.BEGINNING, false, false, 1 , 1)); clearButton.setText("Clear"); clearButton.setData(CLEAR); clearButton.addSelectionListener(this); assignButton = new Button(trxFilterGroup, SWT.RIGHT); assignButton.setLayoutData(new GridData(GridData.END, GridData.BEGINNING, false, false, 1 , 1)); assignButton.setText("Assign"); assignButton.setData(ASSIGN); assignButton.addSelectionListener(this); viewer = new TableViewer(trxFilterGroup, SWT.H_SCROLL | SWT.V_SCROLL); Table filterTable = viewer.getTable(); filterTable.setHeaderVisible(true); filterTable.setLinesVisible(true); // filter = new AfpTRXFilter(); // viewer.addFilter(filter); for (String item : headers) { TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE); TableColumn column = viewerColumn.getColumn(); column.setText(item); column.setData(item); column.setResizable(true); if (Arrays.binarySearch(noListenerHeaders, item) < 0) column.addListener(SWT.Selection, new ColumnFilterListener(parentShell)); } // Table filterTable = new Table(trxFilterGroup, SWT.VIRTUAL | SWT.MULTI); // filterTable.setHeaderVisible(true); GridData tableGrid = new GridData(GridData.FILL, GridData.CENTER, true, true, 4 ,1); filterTable.setLayoutData(tableGrid); // for (String item : headers) { // TableColumn column = new TableColumn(filterTable, SWT.NONE); // column.setText(item); // } for (int i=0;i<emptyrows;i++) { TableItem item = new TableItem(filterTable, SWT.NONE); for (int j = 0; j < headers.length; j++){ item.setText(j, ""); } } for (int i = 0; i < headers.length; i++) { filterTable.getColumn(i).pack(); } return filterTable; } @Override public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } @Override public void widgetSelected(SelectionEvent e) { // TODO Auto-generated method stub } /** * * @param colName * @return unique values for the column */ protected Object[] getColumnUniqueValues(String colName){ return null; } class ColumnFilterListener implements Listener{ Shell parentShell; public ColumnFilterListener(final Shell subShell) { super(); this.parentShell = subShell; } @Override public void handleEvent(Event event) { final ArrayList<String> selectedValues = new ArrayList<String>(); - final Shell subShell = new Shell(parentShell,SWT.PRIMARY_MODAL); + final Shell subShell = new Shell(parentShell,SWT.PRIMARY_MODAL|SWT.RESIZE|SWT.DIALOG_TRIM); subShell.setLayout(new GridLayout(2, false)); Point location = subShell.getDisplay().getCursorLocation(); - subShell.setLocation(location.x,450); + subShell.setLocation(location.x,location.y); /*subShell.addMouseListener(new MouseAdapter(){ @Override public void mouseDown(MouseEvent e) { // TODO Auto-generated method stub System.out.println("Yeah, I can listen it"); super.mouseDown(e); System.out.println("Yeah, I can listen it"); } @Override public void mouseUp(MouseEvent e) { // TODO Auto-generated method stub System.out.println("Yeah, I can listen it"); super.mouseUp(e); System.out.println("Yeah, I can listen it"); } } new MouseListener(){ @Override public void mouseDoubleClick(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseDown(MouseEvent e) { Point location = subShell.getDisplay().getCursorLocation(); Rectangle bounds = subShell.getBounds(); if (!(bounds.contains(location))) subShell.dispose(); } @Override public void mouseUp(MouseEvent e) { Point location = subShell.getDisplay().getCursorLocation(); Rectangle bounds = subShell.getBounds(); if (!(bounds.contains(location))) subShell.dispose(); } });*/ // subShell.setLayoutData(gridData); // subShell.setSize(100, 200); // subShell.setBounds(50, 50, 100, 200); //subShell.setLocation(300, 200); // subShell.setText("Filter"); final String col = (String)event.widget.getData(); Group filterGroup = new Group(subShell, SWT.NONE | SWT.SCROLL_PAGE); filterGroup.setLayout(new GridLayout(2, false)); filterGroup.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, false, false,2 ,1)); Object[] values = getColumnUniqueValues(col); if(values == null) { subShell.dispose(); return; } if(values.length == 0) { subShell.dispose(); return; } final Tree tree = new Tree(filterGroup, SWT.CHECK | SWT.BORDER|SWT.V_SCROLL); GridData gridData = new GridData(GridData.FILL, GridData.FILL, true, false, 2, 1); gridData.heightHint = 200; tree.setLayoutData(gridData); for (Object value : values){ TreeItem item = new TreeItem(tree, 0); item.setText(value.toString()); } Button applyButton = new Button(filterGroup, SWT.PUSH); applyButton.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, true, 1, 1)); applyButton.setText("Apply"); applyButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (TreeItem item : tree.getItems()) { if (item.getChecked()) { selectedValues.add(item.getText()); } } listener.onFilterSelected(col, selectedValues); // filter.setEqualityText("900"); // viewer.refresh(true); subShell.dispose(); } }); Button cacelButton = new Button(filterGroup, SWT.PUSH); cacelButton.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, true, true, 1, 1)); cacelButton.setText("Cancel"); cacelButton.addSelectionListener(new SelectionAdapter(){ @Override public void widgetSelected(SelectionEvent e) { subShell.dispose(); } }); subShell.pack(); subShell.open(); }//end handle event } protected void addSiteUniqueProperties(Node node) { // add to unique properties for(String p:AfpModel.sitePropertiesName ) { Object oVal = node.getProperty(p,null); if(oVal != null) { Set<Object> s = uniqueSitePropertyValues.get(p); if(s != null) { s.add(oVal); } } } } protected void addSectorUniqueProperties(Node node) { // add to unique properties for(String p:AfpModel.sectorPropertiesName ) { Object oVal = node.getProperty(p,null); if(oVal != null) { Set<Object> s = uniqueSectorPropertyValues.get(p); if(s != null) { s.add(oVal); } } } } protected void addTrxUniqueProperties(Node node) { // add to unique properties for(String p:AfpModel.trxPropertiesName ) { Object oVal = node.getProperty(p,null); if(oVal != null) { Set<Object> s= uniqueTrxPropertyValues.get(p); if(s != null) { s.add(oVal); } } } } public Object[] getSiteUniqueValuesForProperty(String prop) { Set<Object> s = this.uniqueSitePropertyValues.get(prop); if(s!= null) { if(s.size() >0) { return s.toArray(new Object[0]); } } return null; } public Object[] getSectorUniqueValuesForProperty(String prop) { Set<Object> s = this.uniqueSectorPropertyValues.get(prop); if(s!= null) { if(s.size() >0) { return s.toArray(new Object[0]); } } return null; } public Object[] getTrxUniqueValuesForProperty(String prop) { Set<Object> s = this.uniqueTrxPropertyValues.get(prop); if(s!= null) { if(s.size() >0) { return s.toArray(new Object[0]); } } return null; } protected void clearAllUniqueValuesForProperty() { for(Set s: this.uniqueSectorPropertyValues.values()) { s.clear(); } for(Set s: this.uniqueSitePropertyValues.values()) { s.clear(); } for(Set s: this.uniqueTrxPropertyValues.values()) { s.clear(); } } }
false
false
null
null
diff --git a/source/java/org/rsna/ctp/stdstages/dicom/DicomStorageSCU.java b/source/java/org/rsna/ctp/stdstages/dicom/DicomStorageSCU.java index e9c4b8e..0934294 100644 --- a/source/java/org/rsna/ctp/stdstages/dicom/DicomStorageSCU.java +++ b/source/java/org/rsna/ctp/stdstages/dicom/DicomStorageSCU.java @@ -1,480 +1,482 @@ /*--------------------------------------------------------------- * Copyright 2005 by the Radiological Society of North America * * This source software is released under the terms of the * RSNA Public License (http://mirc.rsna.org/rsnapubliclicense) *----------------------------------------------------------------*/ package org.rsna.ctp.stdstages.dicom; import java.io.BufferedInputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.security.GeneralSecurityException; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; import org.apache.log4j.Logger; import org.dcm4che.data.Command; import org.dcm4che.data.Dataset; import org.dcm4che.data.DcmDecodeParam; import org.dcm4che.data.DcmElement; import org.dcm4che.data.DcmEncodeParam; import org.dcm4che.data.DcmObjectFactory; import org.dcm4che.data.DcmParseException; import org.dcm4che.data.DcmParser; import org.dcm4che.data.DcmParserFactory; import org.dcm4che.data.FileFormat; import org.dcm4che.dict.DictionaryFactory; import org.dcm4che.dict.Tags; import org.dcm4che.dict.UIDDictionary; import org.dcm4che.dict.UIDs; import org.dcm4che.dict.VRs; import org.dcm4che.net.AAssociateAC; import org.dcm4che.net.AAssociateRQ; import org.dcm4che.net.ActiveAssociation; import org.dcm4che.net.Association; import org.dcm4che.net.AssociationFactory; import org.dcm4che.net.DataSource; import org.dcm4che.net.Dimse; import org.dcm4che.net.PDU; import org.dcm4che.net.PresContext; import org.dcm4che.util.DcmURL; import org.rsna.ctp.objects.DicomObject; import org.rsna.ctp.pipeline.Status; /** * Class to make DICOM associations and transmit instances over them. */ public class DicomStorageSCU { private static final String[] DEF_TS = { UIDs.ImplicitVRLittleEndian }; static final Logger logger = Logger.getLogger(DicomStorageSCU.class); private static final UIDDictionary uidDict = DictionaryFactory.getInstance().getDefaultUIDDictionary(); private static final AssociationFactory aFact = AssociationFactory.getInstance(); private static final DcmObjectFactory oFact = DcmObjectFactory.getInstance(); private static final DcmParserFactory pFact = DcmParserFactory.getInstance(); private int priority = Command.MEDIUM; private int acTimeout = 15000; private int dimseTimeout = 0; private int soCloseDelay = 500; private int maxPDULength = 16352; private AAssociateRQ assocRQ = aFact.newAAssociateRQ(); private boolean packPDVs = false; private int bufferSize = 2048; private byte[] buffer = null; private ActiveAssociation active = null; private Association assoc = null; private PresContext pc = null; private boolean forceClose; private int hostTag = 0; private int portTag = 0; private int calledAETTag = 0; private int callingAETTag = 0; private String currentHost = ""; private int currentPort = 0; private String currentCalledAET = ""; private String currentCallingAET = ""; private String currentTSUID = null; private String currentSOPClassUID = null; private DcmURL url = null; private long lastFailureMessageTime = 0; private static long anHour = 60 * 60 * 1000; /** * Class constructor; creates a DICOM sender. * @param url the URL in the form "<tt>dicom://calledAET:callingAET@host:port</tt>". * @param forceClose true to force the closure of the association after sending an object; false to leave * the association open after a transmission. * @param hostTag the tag in the DicomObject from which to get the host name of the destination SCP, or 0 if * the host name in the URL is to be used for all transmissions * @param portTag the tag in the DicomObject from which to get the port of the destination SCP, or 0 if * the port in the URL is to be used for all transmissions * @param calledAETTag the tag in the DicomObject from which to get the calledAET, or 0 if * the calledAET in the URL is to be used for all transmissions * @param callingAETTag the tag in the DicomObject from which to get the callingAET, or 0 if * the callingAET in the URL is to be used for all transmissions */ public DicomStorageSCU(String url, boolean forceClose, int hostTag, int portTag, int calledAETTag, int callingAETTag) { this.url = new DcmURL(url); this.forceClose = forceClose; this.hostTag = hostTag; this.portTag = portTag; this.calledAETTag = calledAETTag; this.callingAETTag = callingAETTag; buffer = new byte[bufferSize]; } /** * Close the association if it is open. */ public void close() { if (active != null) { try { active.release(true); } catch (Exception ignore) { } active = null; currentTSUID = null; pc = null; } } /** * Send one file to the URL specified in the constructor. * This method parses the file as a DicomObject and calls * the send(DicomObject) method. * @param file the file to parse and send * @return the Status from the send(DicomObject) method, * or Status.FAIL if the file does not parse as a DicomObject. */ public Status send(File file) { DicomObject dob = null; try { dob = new DicomObject(file, true); Status status = send(dob); dob.close(); return status; } catch (Exception ex) { logger.warn("Unable to parse file as DicomObject: "+file); return Status.FAIL; } } /** * Send one DicomObject to the URL specified in the constructor. * NOTE: the DicomObject must be instantiated with the file left * open so the sender can get at the whole dataset. Thus, the object * should be opened with the full constructor: *<br><br><tt>dicomObject = new DicomObject(fileToExport, true);</tt> */ public Status send(DicomObject dicomObject) { DcmParser parser = dicomObject.getDcmParser(); Dataset ds = dicomObject.getDataset(); String sopInstUID = dicomObject.getSOPInstanceUID(); String sopClassUID = dicomObject.getSOPClassUID(); String tsUID = dicomObject.getTransferSyntaxUID(); String requestedHost = getHost(dicomObject, hostTag, url.getHost()); int requestedPort = getPort(dicomObject, portTag, url.getPort()); String requestedCalledAET = getAET(dicomObject, calledAETTag, url.getCalledAET()); String requestedCallingAET = getAET(dicomObject, callingAETTag, url.getCallingAET()); try { //See if we have to make a new association for this request. if ( //if the active association does not exist or if it has been closed by the other end, then YES (active == null) || (active.getAssociation().getState() != Association.ASSOCIATION_ESTABLISHED) || //if the transfer syntax has changed, then YES (currentTSUID == null) || !tsUID.equals(currentTSUID) || //if the SOP Class has changed, then YES (currentSOPClassUID == null) || !sopClassUID.equals(currentSOPClassUID) || //if the host has changed, then YES !requestedHost.equals(currentHost) || //if the port has changed, then YES (requestedPort != currentPort) || //if the called AET has changed, then YES !requestedCalledAET.equals(currentCalledAET) || //if the calling AET has changed, then YES !requestedCallingAET.equals(currentCallingAET) ) { //Alas, we can't reuse the current association. //Close it if it is open close(); //Create a new association initAssocParam(requestedCalledAET, maskNull(requestedCallingAET)); initPresContext(sopClassUID); active = openAssoc(requestedHost, requestedPort); if (active == null) return Status.RETRY; //probably off-line assoc = active.getAssociation(); //Negotiate the transfer syntax pc = assoc.getAcceptedPresContext(sopClassUID, tsUID); if (!parser.getDcmDecodeParam().encapsulated) { if (pc == null) pc = assoc.getAcceptedPresContext(sopClassUID, UIDs.ExplicitVRLittleEndian); if (pc == null) pc = assoc.getAcceptedPresContext(sopClassUID, UIDs.ExplicitVRBigEndian); if (pc == null) pc = assoc.getAcceptedPresContext(sopClassUID, UIDs.ImplicitVRLittleEndian); } if (pc == null) { currentTSUID = null; currentSOPClassUID = null; logger.debug("Unable to negotiate a transfer syntax for "+dicomObject.getSOPInstanceUID()); logger.debug("...SOPClass: "+dicomObject.getSOPClassName()); return Status.FAIL; } currentTSUID = pc.getTransferSyntaxUID(); currentSOPClassUID = sopClassUID; currentHost = requestedHost; currentPort = requestedPort; currentCalledAET = requestedCalledAET; currentCallingAET = requestedCallingAET; } //Make the command and do the transfer. Command command = oFact.newCommand(); command = command.initCStoreRQ(assoc.nextMsgID(), sopClassUID, sopInstUID, priority); Dimse request = aFact.newDimse(pc.pcid(), command, new MyDataSource(parser, ds, buffer)); Dimse response = active.invoke(request).get(); int status = response.getCommand().getStatus(); if (forceClose) close(); if (status == 0) { lastFailureMessageTime = 0; return Status.OK; } else { close(); return Status.FAIL; } } catch (Exception ex) { close(); String msg = ex.getMessage(); if ((msg != null) && msg.contains("Connection refused")) { long time = System.currentTimeMillis(); if ((time - lastFailureMessageTime) > anHour) { logger.warn("dicom://"+requestedCalledAET+":"+requestedCallingAET+"@"+requestedHost+":"+requestedPort); logger.warn(ex); lastFailureMessageTime = time; } } else { + logger.debug("Error processing a DicomObject for transmission", ex); logger.warn(ex); logger.warn("..."+dicomObject.getSOPInstanceUID()); logger.warn("..."+dicomObject.getSOPClassName()); - if ((msg != null) && msg.contains("NullPointerException")) return Status.FAIL; + if ((ex instanceof java.io.EOFException) || + (ex instanceof java.lang.NullPointerException)) return Status.FAIL; } } return Status.RETRY; } private final class MyDataSource implements DataSource { final DcmParser parser; final Dataset ds; final byte[] buffer; MyDataSource(DcmParser parser, Dataset ds, byte[] buffer) { this.parser = parser; this.ds = ds; this.buffer = buffer; } public void writeTo(OutputStream out, String tsUID) throws IOException { DcmEncodeParam netParam = (DcmEncodeParam) DcmDecodeParam.valueOf(tsUID); ds.writeDataset(out, netParam); DcmDecodeParam fileParam = parser.getDcmDecodeParam(); if (parser.getReadTag() == Tags.PixelData) { ds.writeHeader( out, netParam, parser.getReadTag(), parser.getReadVR(), parser.getReadLength()); if (netParam.encapsulated) { parser.parseHeader(); while (parser.getReadTag() == Tags.Item) { ds.writeHeader( out, netParam, parser.getReadTag(), parser.getReadVR(), parser.getReadLength()); writeValueTo(out, false); parser.parseHeader(); } if (parser.getReadTag() != Tags.SeqDelimitationItem) { throw new DcmParseException( "Unexpected Tag: " + Tags.toString(parser.getReadTag())); } if (parser.getReadLength() != 0) { throw new DcmParseException( "(fffe,e0dd), Length:" + parser.getReadLength()); } ds.writeHeader( out, netParam, Tags.SeqDelimitationItem, VRs.NONE, 0); } else { boolean swap = fileParam.byteOrder != netParam.byteOrder && parser.getReadVR() == VRs.OW; writeValueTo(out, swap); } parser.parseHeader(); //get ready for the next element } //Now do any elements after the pixels one at a time. //This is done to allow streaming of large raw data elements //that occur above Tags.PixelData. boolean swap = fileParam.byteOrder != netParam.byteOrder; while (!parser.hasSeenEOF() && parser.getReadTag() != -1) { ds.writeHeader( out, netParam, parser.getReadTag(), parser.getReadVR(), parser.getReadLength()); writeValueTo(out, swap); parser.parseHeader(); } } private void writeValueTo(OutputStream out, boolean swap) throws IOException { InputStream in = parser.getInputStream(); int len = parser.getReadLength(); if (swap && (len & 1) != 0) { throw new DcmParseException( "Illegal length for swapping value bytes: " + len); } if (buffer == null) { if (swap) { int tmp; for (int i = 0; i < len; ++i, ++i) { tmp = in.read(); out.write(in.read()); out.write(tmp); } } else { for (int i = 0; i < len; ++i) { out.write(in.read()); } } } else { byte tmp; int c, remain = len; while (remain > 0) { c = in.read(buffer, 0, Math.min(buffer.length, remain)); if (c == -1) { throw new EOFException("EOF while reading element value"); } if (swap) { if ((c & 1) != 0) { buffer[c++] = (byte) in.read(); } for (int i = 0; i < c; ++i, ++i) { tmp = buffer[i]; buffer[i] = buffer[i + 1]; buffer[i + 1] = tmp; } } out.write(buffer, 0, c); remain -= c; } } parser.setStreamPosition(parser.getStreamPosition() + len); } } private Socket newSocket(String host, int port) throws IOException, GeneralSecurityException { return new Socket(host, port); } private static String maskNull(String aet) { return (aet != null) ? aet : "DCMSND"; } private String getHost(DicomObject dicomObject, int tag, String defaultHost) { String host = defaultHost; try { if (tag != 0) { byte[] bytes = dicomObject.getElementBytes(tag); host = new String(bytes).trim(); host = (host.equals("") ? defaultHost : host); } } catch (Exception ex) { host = defaultHost; } return host; } private int getPort(DicomObject dicomObject, int tag, int defaultPort) { int port = defaultPort; try { if (tag != 0) { byte[] bytes = dicomObject.getElementBytes(tag); try { port = Integer.parseInt( new String(bytes).trim() ); } catch (Exception ex) { port = 0; } port = ((port == 0) ? defaultPort : port); } } catch (Exception ex) { port = defaultPort; } return port; } private String getAET(DicomObject dicomObject, int tag, String defaultAET) { String aet = defaultAET; try { if (tag != 0) { byte[] bytes = dicomObject.getElementBytes(tag); aet = new String(bytes).trim(); aet = (aet.equals("") ? defaultAET : aet); } } catch (Exception ex) { aet = defaultAET; } return aet; } private final void initAssocParam(String calledAET, String callingAET) { assocRQ.setCalledAET( calledAET ); assocRQ.setCallingAET( maskNull( callingAET ) ); assocRQ.setMaxPDULength( maxPDULength ); assocRQ.setAsyncOpsWindow( aFact.newAsyncOpsWindow(0,1) ); } private ActiveAssociation openAssoc(String host, int port) throws IOException, GeneralSecurityException { Association assoc = aFact.newRequestor(newSocket(host, port)); assoc.setAcTimeout(acTimeout); assoc.setDimseTimeout(dimseTimeout); assoc.setSoCloseDelay(soCloseDelay); assoc.setPackPDVs(packPDVs); PDU assocAC = assoc.connect(assocRQ); if (!(assocAC instanceof AAssociateAC)) return null; ActiveAssociation retval = aFact.newActiveAssociation(assoc, null); retval.start(); return retval; } private final void initPresContext(String asUID) { PCTable pcTable = PCTable.getInstance(); assocRQ.clearPresContext(); LinkedList<String> tsList = pcTable.get(asUID); if (tsList != null) { int pcid = 1; Iterator<String> it = tsList.iterator(); while (it.hasNext()) { String[] tsUID = new String[1]; tsUID[0] = it.next(); assocRQ.addPresContext(aFact.newPresContext(pcid, asUID, tsUID)); pcid += 2; } } } } diff --git a/source/java/org/rsna/ctp/stdstages/storage/StorageServlet.java b/source/java/org/rsna/ctp/stdstages/storage/StorageServlet.java index 914397e..bd4565b 100644 --- a/source/java/org/rsna/ctp/stdstages/storage/StorageServlet.java +++ b/source/java/org/rsna/ctp/stdstages/storage/StorageServlet.java @@ -1,327 +1,327 @@ /*--------------------------------------------------------------- * Copyright 2011 by the Radiological Society of North America * * This source software is released under the terms of the * RSNA Public License (http://mirc.rsna.org/rsnapubliclicense) *----------------------------------------------------------------*/ package org.rsna.ctp.stdstages.storage; import java.io.File; import java.util.Iterator; import java.util.List; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.rsna.ctp.objects.DicomObject; import org.rsna.ctp.objects.FileObject; import org.rsna.server.HttpRequest; import org.rsna.server.HttpResponse; import org.rsna.server.Path; import org.rsna.server.User; import org.rsna.servlets.Servlet; import org.rsna.servlets.Servlet; import org.rsna.util.FileUtil; import org.rsna.util.XmlUtil; /** * A Servlet which provides web access to the studies stored in a FileStorageService. */ public class StorageServlet extends Servlet { static final Logger logger = Logger.getLogger(StorageServlet.class); /** * Construct a StorageServlet. * @param root the root directory of the server. * @param context the path identifying the servlet. */ public StorageServlet(File root, String context) { super(root, context); } /** * The GET handler: return a page displaying the list of studies * stored in the FileStorageService. * @param req the request object * @param res the response object */ public void doGet(HttpRequest req, HttpResponse res) { //Get the FileSystemManager. FileSystemManager fsm = FileSystemManager.getInstance(root); if (fsm == null) { //There is no FileSystemManager for this root. res.setResponseCode( res.notfound ); res.send(); } //Figure out what was requested from the length of the path. Path path = new Path(req.path); switch (path.length()) { case 1: listFileSystems(req, res, fsm); return; case 2: listStudies(req, res, path, fsm); return; case 3: listObjects(req, res, path, fsm); return; case 4: getObject(req, res, path, fsm); return; } //Not one of those; return NotFound res.setResponseCode( res.notfound ); res.send(); } //List all the file systems. private void listFileSystems(HttpRequest req, HttpResponse res, FileSystemManager fsm) { List<String> fsList = fsm.getFileSystemsFor(req.getUser()); - if (fsm.getSize() == 1) { + if (fsList.size() == 1) { //Only one FileSystem, just list its studies. //First, make a Path to the FileSystem. Path path = new Path("/storage/" + fsList.get(0)); listStudies(req, res, path, fsm); } else { - //More than one FileSystem; list them. + //Zero or more than one FileSystem; list them. StringBuffer sb = new StringBuffer(); sb.append("<html><head>"); sb.append("<title>Storage Service</title>"); sb.append("<link rel=\"stylesheet\" href=\"/BaseStyles.css\" type=\"text/css\"/>"); sb.append("<style>"); sb.append("th,td{padding-left:10px; padding-right:10px;}"); sb.append("td{background-color:white;}"); sb.append("</style>"); sb.append("</head><body>"); sb.append("<center><h1>File System List</h1></center>"); sb.append("<center>"); if (fsList.size() > 0) { sb.append("<table border=\"1\">"); //Insert a table row for each file system here Iterator<String> lit = fsList.iterator(); while (lit.hasNext()) { String fsName = lit.next(); sb.append("<tr>"); sb.append("<td>"); sb.append("<a href=\"/storage/"+fsName+"\">"+fsName+"</a>"); sb.append("</td>"); sb.append("</tr>"); } sb.append("</table>"); } else sb.append("<p>The storage service is empty.</p>"); sb.append("</center>"); sb.append("</body></html>"); res.write(sb.toString()); res.setContentType("html"); res.disableCaching(); res.send(); } } //List all studies in one file system. private void listStudies(HttpRequest req, HttpResponse res, Path path, FileSystemManager fsm) { String admin = req.userHasRole("admin") ? "yes" : "no"; String dir = (fsm.getExportDirectory() != null) ? "yes" : "no"; String delete = req.userHasRole("delete") ? "yes" : "no"; String key = req.getParameter("key"); if (key == null) key = "storageDate"; String fsName = path.element(1); FileSystem fs = fsm.getFileSystem(fsName, false); String page = "Access to the requested File System is not allowed."; if ((fs != null) && fs.allowsAccessBy(req.getUser())) { File xslFile = new File("pages/list-studies.xsl"); if (fs != null) { String[] params = new String[] { "context", "/storage/"+fsName, "dir", dir, "delete", delete, "key", key }; try { page = XmlUtil.getTransformedText(fs.getIndex(), xslFile, params); } catch (Exception e) { logger.warn("Unable to get the study list page."); } } } res.write(page); res.setContentType("html"); res.disableCaching(); res.send(); } //List all the objects in one study. File xslFile; private void listObjects(HttpRequest req, HttpResponse res, Path path, FileSystemManager fsm) { User user = req.getUser(); String fsName = path.element(1); String studyUID = path.element(2); FileSystem fs = fsm.getFileSystem(fsName, false); Study study = null; String page = "Access to the requested Study is not allowed."; if ((fs != null) && fs.allowsAccessBy(user)) { study = fs.getStudyByUID(studyUID); if (study != null) { String format = req.getParameter("format"); format = (format==null) ? "list" : format; if (!format.equals("zip") && !format.equals("delete") & !format.equals("dir")) { if (format.equals("list")) xslFile = new File("pages/list-objects.xsl"); else xslFile = new File("pages/view-objects.xsl"); String[] params = new String[] { "context", "/storage/"+fsName }; try { page = XmlUtil.getTransformedText(study.getIndex(), xslFile, params); } catch (Exception e) { logger.debug("Unable to get the object listing page."); } res.write(page); res.setContentType("html"); res.disableCaching(); res.send(); return; } else if (format.equals("zip")) { File zipFile = null; try { zipFile = File.createTempFile("ZIP-",".zip",root); File studyDir = study.getDirectory(); if (FileUtil.zipDirectory(studyDir, zipFile)) { res.write(zipFile); res.setContentType("zip"); res.setContentDisposition(zipFile); res.send(); //Handle the delete if present String delete = req.getParameter("delete"); if ((delete != null) && (delete.equals("yes")) && (user != null) && (user.getUsername().equals(fs.getName()) || user.hasRole("delete"))) { fs.deleteStudyByUID(studyUID); } zipFile.delete(); return; } } catch (Exception ex) { logger.debug("Internal server error in zip export.", ex); } res.setResponseCode( res.servererror ); res.send(); return; } else if (format.equals("dir")) { File expdir = fsm.getExportDirectory(); if ((expdir != null) && user.hasRole("admin")) { try { expdir.mkdirs(); File studyDir = study.getDirectory(); File[] files = studyDir.listFiles(); for (File file : files) { String name = file.getName(); if (!name.startsWith("__")) { File outfile = new File(expdir, name); FileUtil.copy(file, outfile); } } //Redirect to the level above. String subpath = path.subpath(0, path.length()-2); res.redirect(subpath); return; } catch (Exception ex) { logger.debug("Internal server error in directory export.", ex); res.setResponseCode( res.servererror ); res.send(); } } res.setResponseCode( res.forbidden ); //Not authorized res.send(); return; } else if (format.equals("delete")) { if ((user != null) && (user.getUsername().equals(fs.getName()) || user.hasRole("delete"))) { fs.deleteStudyByUID(studyUID); //Redirect to the level above. String subpath = path.subpath(0, path.length()-2); res.redirect(subpath); return; } res.setResponseCode( res.forbidden ); //Not authorized res.send(); return; } } } res.write(page); res.send(); } //Get an object. private void getObject(HttpRequest req, HttpResponse res, Path path, FileSystemManager fsm) { boolean admin = req.userHasRole("admin"); String fsName = path.element(1); String studyUID = path.element(2); FileSystem fs = fsm.getFileSystem(fsName, false); Study study; FileObject fo; if ( (fs != null) && fs.allowsAccessBy(req.getUser()) && ((study=fs.getStudyByUID(studyUID)) != null) && ((fo = study.getObject(path.element(3))) != null) ) { if (fo instanceof DicomObject) { //This is a DicomObject; see how we are to return it. //There are three options: // 1. as a DICOM element list (triggered by format=list) // 2. as a JPEG image (triggered by format=jpeg) // 3. as a file download (if no format parameter is present) String format = req.getParameter("format", ""); DicomObject dob = (DicomObject)fo; if (format.equals("list")) { //Return an element listing page res.write( dob.getElementTablePage( req.userHasRole("admin") ) ); res.setContentType("html"); } else if (format.equals("jpeg")) { //Return a JPEG image //Get the qualifiers. ImageQualifiers q = new ImageQualifiers(req); //Make the name of the jpeg String jpegName = fo.getFile().getName() + q.toString() + ".jpeg"; //See if the jpeg file already exists. File jpegFile = new File(fo.getFile().getParentFile(), jpegName); if (!jpegFile.exists()) { //No, create it if (dob.saveAsJPEG(jpegFile, 0, q.maxWidth, q.minWidth, q.quality) == null) { //Error, return a code res.setResponseCode( res.servererror ); res.send(); return; } } res.write(jpegFile); res.setContentType("jpeg"); res.disableCaching(); } else { res.write(fo.getFile()); res.setContentType("dcm"); } } else { File file = fo.getFile(); res.write(file); res.setContentType(file); } } else res.setResponseCode( res.notfound ); res.send(); } }
false
false
null
null
diff --git a/src/net/sourceforge/servestream/utils/M3UPlaylistParser.java b/src/net/sourceforge/servestream/utils/M3UPlaylistParser.java index 5fc023d..79da43c 100644 --- a/src/net/sourceforge/servestream/utils/M3UPlaylistParser.java +++ b/src/net/sourceforge/servestream/utils/M3UPlaylistParser.java @@ -1,96 +1,92 @@ /* * ServeStream: A HTTP stream browser/player for Android * Copyright 2010 William Seemann * * 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 net.sourceforge.servestream.utils; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class M3UPlaylistParser extends PlaylistParser { public final static String TAG = M3UPlaylistParser.class.getName(); public final static String EXTENSION = "m3u"; - + private final static String EXTENDED_INFO_TAG = "#EXTM3U"; + private final static String RECORD_TAG = "#EXTINF"; + private MediaFile mediaFile = null; private boolean processingEntry = false; /** * Default constructor */ public M3UPlaylistParser(URL playlistUrl) { super(playlistUrl); } /** * Retrieves the files listed in a .m3u file */ public void retrieveAndParsePlaylist() { if (mPlaylistUrl == null) return; HttpURLConnection conn = null; String line = null; BufferedReader reader = null;; try { conn = URLUtils.getConnection(mPlaylistUrl); // Start the query reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); conn.connect(); while ((line = reader.readLine()) != null) { - if (!(line.equals("#EXTM3U") || line.trim().equals(""))) { + if (!(line.equals(EXTENDED_INFO_TAG) || line.trim().equals(""))) { - if (line.contains("#EXTINF")) { - + if (line.contains(RECORD_TAG)) { mediaFile = new MediaFile(); - - int index = line.lastIndexOf(','); - - if (index != -1) - mediaFile.setPlaylistMetadata(line.substring(index + 1)); - + mediaFile.setPlaylistMetadata(line.replaceAll("^(.*?),", "")); processingEntry = true; } else { if (!processingEntry) mediaFile = new MediaFile(); mediaFile.setURL(line.trim()); savePlaylistFile(); } } } } catch (Exception ex) { ex.printStackTrace(); } finally { Utils.closeBufferedReader(reader); Utils.closeHttpConnection(conn); } } public void savePlaylistFile() { mNumberOfFiles = mNumberOfFiles + 1; mediaFile.setTrackNumber(mNumberOfFiles); mPlaylistFiles.add(mediaFile); processingEntry = false; } }
false
false
null
null
diff --git a/src/com/possebom/mypharmacy/GetMedicine.java b/src/com/possebom/mypharmacy/GetMedicine.java index 4d23521..640e5d1 100644 --- a/src/com/possebom/mypharmacy/GetMedicine.java +++ b/src/com/possebom/mypharmacy/GetMedicine.java @@ -1,83 +1,83 @@ package com.possebom.mypharmacy; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.ProgressDialog; import android.os.AsyncTask; import android.util.Log; import com.possebom.mypharmacy.model.Medicine; public class GetMedicine extends AsyncTask<Void, Void, Void> { private static final String TAG = "MEDICINE"; private String barcode; private ProgressDialog progressDialog; private JSONObject json; private String country; private GetMedicineListener listener; public GetMedicine(ProgressDialog progressDialog,GetMedicineListener listener, String barcode, String country) { this.barcode = barcode; this.country = country; this.listener = listener; this.progressDialog = progressDialog; } @Override protected void onPreExecute() { super.onPreExecute(); progressDialog.show(); } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); Medicine medicine = new Medicine(); try { medicine.setBrandName(json.getString("brandName")); medicine.setDrug(json.getString("drug")); medicine.setConcentration(json.getString("concentration")); medicine.setForm(json.getString("form")); medicine.setLaboratory(json.getString("laboratory")); - } catch (JSONException e) { + } catch (Exception e) { Log.e(TAG, "Error on json : " + e.toString()); } listener.onRemoteCallComplete(medicine); - if (progressDialog.isShowing()) { + if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } } @Override protected Void doInBackground(Void... arg0) { HttpClient httpclient = new DefaultHttpClient(); ResponseHandler<String> handler = new BasicResponseHandler(); HttpGet request = new HttpGet("http://possebom.com/android/mypharmacy/getMedicine.php?country="+country+"&barcode="+barcode); try { String result = new String(httpclient.execute(request, handler).getBytes("ISO-8859-1"),"UTF-8"); JSONArray jsonArray = new JSONArray(result); json = jsonArray.getJSONObject(0); httpclient.getConnectionManager().shutdown(); } catch (Exception e) { json = null; Log.e(TAG, "Error converting result " + e.toString()); } return null; } public interface GetMedicineListener { public void onRemoteCallComplete(Medicine medicine); } }
false
true
protected void onPostExecute(Void result) { super.onPostExecute(result); Medicine medicine = new Medicine(); try { medicine.setBrandName(json.getString("brandName")); medicine.setDrug(json.getString("drug")); medicine.setConcentration(json.getString("concentration")); medicine.setForm(json.getString("form")); medicine.setLaboratory(json.getString("laboratory")); } catch (JSONException e) { Log.e(TAG, "Error on json : " + e.toString()); } listener.onRemoteCallComplete(medicine); if (progressDialog.isShowing()) { progressDialog.dismiss(); } }
protected void onPostExecute(Void result) { super.onPostExecute(result); Medicine medicine = new Medicine(); try { medicine.setBrandName(json.getString("brandName")); medicine.setDrug(json.getString("drug")); medicine.setConcentration(json.getString("concentration")); medicine.setForm(json.getString("form")); medicine.setLaboratory(json.getString("laboratory")); } catch (Exception e) { Log.e(TAG, "Error on json : " + e.toString()); } listener.onRemoteCallComplete(medicine); if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } }
diff --git a/src/service/IdemixService.java b/src/service/IdemixService.java index 655063f..7c8f204 100644 --- a/src/service/IdemixService.java +++ b/src/service/IdemixService.java @@ -1,239 +1,251 @@ package service; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import net.sourceforge.scuba.smartcards.CardService; import net.sourceforge.scuba.smartcards.CardServiceException; import net.sourceforge.scuba.smartcards.ICommandAPDU; import net.sourceforge.scuba.smartcards.IResponseAPDU; import net.sourceforge.scuba.util.Hex; import com.ibm.zurich.idmx.api.ProverInterface; import com.ibm.zurich.idmx.api.RecipientInterface; import com.ibm.zurich.idmx.dm.Credential; import com.ibm.zurich.idmx.dm.Values; import com.ibm.zurich.idmx.issuance.IssuanceSpec; import com.ibm.zurich.idmx.issuance.Message; import com.ibm.zurich.idmx.showproof.Proof; import com.ibm.zurich.idmx.showproof.ProofSpec; public class IdemixService implements ProverInterface, RecipientInterface { /** * Control the amount of output generated by this class. */ private static final boolean VERBOSE = true; /** * SCUBA service to communicate with the card. */ protected CardService service; protected IssuanceSpec issuanceSpec; protected short credentialId; public IdemixService(CardService service, short credentialId) { this.service = service; this.credentialId = credentialId; } public HashMap<String,IResponseAPDU> executeCommands(List<ProtocolCommand> commands) throws CardServiceException { HashMap<String,IResponseAPDU> responses = new HashMap<String, IResponseAPDU>(); for (ProtocolCommand c: commands) { IResponseAPDU response = transmit(service, c.command); responses.put(c.key, response); if (response.getSW() != 0x00009000) { // don't bother with the rest of the commands... // TODO: get error message from global table String errorMessage = c.errorMap != null && c.errorMap.containsKey(response.getSW()) ? c.errorMap.get(response.getSW()) : ""; throw new CardServiceException(String.format("Command failed: \"%s\", SW: %04x (%s)",c.description, response.getSW(), errorMessage )); } } return responses; } /////////////////////////////// /** * Open a communication channel to an Idemix applet. */ public void open() throws CardServiceException { if (!service.isOpen()) { service.open(); } executeCommands(IdemixSmartcard.singleCommand(IdemixSmartcard.selectAppletCommand)); } /** * Send an APDU over the communication channel to the smart card. * * @param apdu the APDU to be send to the smart card. * @return ResponseAPDU the response from the smart card. * @throws CardServiceException if some error occurred while transmitting. */ public static IResponseAPDU transmit(CardService service, ICommandAPDU capdu) throws CardServiceException { if (VERBOSE) { System.out.println(); System.out.println("C: " + Hex.bytesToHexString(capdu.getBytes())); } long start = System.nanoTime(); IResponseAPDU rapdu = service.transmit(capdu); long duration = (System.nanoTime() - start)/1000000; if (VERBOSE) { System.out.println(" duration: " + duration + " ms"); System.out.println("R: " + Hex.bytesToHexString(rapdu.getBytes())); } return rapdu; } /** * Close the communication channel with the Idemix applet. + * TODO: WL: why is CardService a parameter here while it + * is a class member? */ + @Deprecated public void close(CardService service) { if (service != null) { service.close(); } } /** + * Close the communication channel with the Idemix applet. + */ + public void close() { + if (service != null) { + service.close(); + } + } + + /** * Select the Idemix applet on the smart card. * * @throws CardServiceException if an error occurred. */ public void selectApplet() throws CardServiceException { executeCommands(IdemixSmartcard.singleCommand(IdemixSmartcard.selectAppletCommand)); } /** * Send the pin to the card * * @throws CardServiceException if an error occurred. */ public void sendPin(byte[] pin) throws CardServiceException { executeCommands(IdemixSmartcard.singleCommand(IdemixSmartcard.sendPinCommand(pin))); } /** * Generate the master secret: * * <pre> * m_0 * </pre> * * @throws CardServiceException if an error occurred. */ public void generateMasterSecret() throws CardServiceException { ArrayList<ProtocolCommand> commands = new ArrayList<ProtocolCommand>(); commands.add(IdemixSmartcard.generateMasterSecretCommand); executeCommands(commands); } /** * @param theNonce1 * Nonce provided by the verifier. * @return Message containing the proof about the hidden and committed * attributes sent to the Issuer. */ public Message round1(final Message msg) { try { return IdemixSmartcard.processRound1Responses( executeCommands( IdemixSmartcard.round1Commands(issuanceSpec, msg))); } catch (CardServiceException e) { System.err.println(e.getMessage() + "\n"); e.printStackTrace(); return null; } } /** * Called with the second protocol flow as input, outputs the Credential. * This is the last step of the issuance protocol, where the Recipient * verifies that the signature is valid and outputs it. * * @param msg * the second flow of the protocol, a message from the Issuer * @return null */ public Credential round3(final Message msg) { // Hide CardServiceExceptions, instead return null on failure try { // send Signature executeCommands(IdemixSmartcard.round3Commands(issuanceSpec, msg)); // Do NOT return the generated Idemix credential return null; // Report caught exceptions } catch (CardServiceException e) { System.err.println(e.getMessage() + "\n"); e.printStackTrace(); return null; } } /** * Builds an Identity mixer show-proof data structure, which can be passed * to the verifier for verification. * * @return Identity mixer show-proof data structure. */ public Proof buildProof(final BigInteger nonce, final ProofSpec spec) { // Hide CardServiceExceptions, instead return null on failure try { return IdemixSmartcard.processBuildProofResponses(executeCommands(IdemixSmartcard.buildProofCommands(nonce, spec, credentialId)), spec); // Report caught exceptions } catch (CardServiceException e) { System.err.println(e.getMessage() + "\n"); e.printStackTrace(); return null; } } /** * Set the specification of a certificate issuance: * * <ul> * <li> issuer public key, and * <li> context. * </ul> * * @param spec the specification to be set. * @throws CardServiceException if an error occurred. */ public void setIssuanceSpecification(IssuanceSpec spec) throws CardServiceException { issuanceSpec = spec; executeCommands(IdemixSmartcard.setIssuanceSpecificationCommands(spec, credentialId)); } /** * Set the attributes: * * <pre> * m_1, ..., m_l * </pre> * * @param spec the issuance specification for the ordering of the values. * @param values the attributes to be set. * @throws CardServiceException if an error occurred. */ public void setAttributes(IssuanceSpec spec, Values values) throws CardServiceException { executeCommands(IdemixSmartcard.setAttributesCommands(spec, values)); } }
false
false
null
null
diff --git a/src/org/dyndns/pawitp/muwifiautologin/MuWifiLogin.java b/src/org/dyndns/pawitp/muwifiautologin/MuWifiLogin.java index eeb6711..8cc64f9 100644 --- a/src/org/dyndns/pawitp/muwifiautologin/MuWifiLogin.java +++ b/src/org/dyndns/pawitp/muwifiautologin/MuWifiLogin.java @@ -1,87 +1,88 @@ package org.dyndns.pawitp.muwifiautologin; import java.io.IOException; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.util.Log; import android.widget.Toast; public class MuWifiLogin { static final String TAG = "MuWifiLogin"; static final int LOGIN_ERROR_ID = 1; static final int LOGIN_ONGOING_ID = 2; private Context mContext; private SharedPreferences mPrefs; private NotificationManager mNotifMan; private Notification mNotification; public MuWifiLogin(Context context, SharedPreferences prefs) { mContext = context; mPrefs = prefs; mNotifMan = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); mNotification = new Notification(R.drawable.ic_stat_notify_key, null, System.currentTimeMillis()); mNotification.flags = Notification.FLAG_ONGOING_EVENT; } public void login() { MuWifiClient loginClient = new MuWifiClient(mPrefs.getString(Preferences.KEY_USERNAME, null), mPrefs.getString(Preferences.KEY_PASSWORD, null)); try { updateOngoingNotification(mContext.getString(R.string.notification_login_ongoing_text_determine_requirement)); if (loginClient.loginRequired()) { Log.v(TAG, "Login required"); updateOngoingNotification(mContext.getString(R.string.notification_login_ongoing_text_logging_in)); loginClient.login(); Toast.makeText(mContext, R.string.login_successful, Toast.LENGTH_SHORT).show(); Log.v(TAG, "Login successful"); } else { Toast.makeText(mContext, R.string.no_login_required, Toast.LENGTH_SHORT).show(); Log.v(TAG, "No login required"); } } catch (LoginException e) { Log.v(TAG, "Login failed"); Intent notificationIntent = new Intent(mContext, ErrorWebView.class); notificationIntent.putExtra(ErrorWebView.EXTRA_CONTENT, e.getMessage()); createErrorNotification(notificationIntent); } catch (IOException e) { Log.v(TAG, "Login failed: IOException"); Intent notificationIntent = new Intent(mContext, ErrorTextView.class); notificationIntent.putExtra(ErrorTextView.EXTRA_CONTENT, e.toString()); createErrorNotification(notificationIntent); } finally { mNotifMan.cancel(LOGIN_ONGOING_ID); } } private void updateOngoingNotification(String message) { PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, new Intent() , 0); mNotification.setLatestEventInfo(mContext, mContext.getString(R.string.notification_login_ongoing_title), message, contentIntent); mNotifMan.notify(LOGIN_ONGOING_ID, mNotification); } private void createErrorNotification(Intent notificationIntent) { notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, 0); Notification notification = new Notification(R.drawable.ic_stat_notify_key, mContext.getString(R.string.ticker_login_error), System.currentTimeMillis()); notification.setLatestEventInfo(mContext, mContext.getString(R.string.notification_login_error_title), mContext.getString(R.string.notification_login_error_text), contentIntent); notification.flags = Notification.FLAG_AUTO_CANCEL; + notification.defaults = Notification.DEFAULT_ALL; mNotifMan.notify(LOGIN_ERROR_ID, notification); } }
true
false
null
null
diff --git a/public/java/src/org/broadinstitute/sting/utils/codecs/vcf/AbstractVCFCodec.java b/public/java/src/org/broadinstitute/sting/utils/codecs/vcf/AbstractVCFCodec.java index 3212e3904..0e0cb14bf 100755 --- a/public/java/src/org/broadinstitute/sting/utils/codecs/vcf/AbstractVCFCodec.java +++ b/public/java/src/org/broadinstitute/sting/utils/codecs/vcf/AbstractVCFCodec.java @@ -1,632 +1,639 @@ package org.broadinstitute.sting.utils.codecs.vcf; import org.apache.log4j.Logger; import org.broad.tribble.Feature; import org.broad.tribble.FeatureCodec; import org.broad.tribble.NameAwareCodec; import org.broad.tribble.TribbleException; import org.broad.tribble.readers.LineReader; import org.broad.tribble.util.BlockCompressedInputStream; import org.broad.tribble.util.ParsingUtils; import org.broadinstitute.sting.gatk.refdata.SelfScopingFeatureCodec; import org.broadinstitute.sting.utils.exceptions.ReviewedStingException; import org.broadinstitute.sting.utils.exceptions.UserException; import org.broadinstitute.sting.utils.variantcontext.Allele; import org.broadinstitute.sting.utils.variantcontext.Genotype; import org.broadinstitute.sting.utils.variantcontext.VariantContext; import java.io.*; import java.util.*; import java.util.zip.GZIPInputStream; public abstract class AbstractVCFCodec implements FeatureCodec, NameAwareCodec, VCFParser, SelfScopingFeatureCodec { protected final static Logger log = Logger.getLogger(VCFCodec.class); protected final static int NUM_STANDARD_FIELDS = 8; // INFO is the 8th column protected VCFHeaderVersion version; // we have to store the list of strings that make up the header until they're needed protected VCFHeader header = null; // a mapping of the allele protected Map<String, List<Allele>> alleleMap = new HashMap<String, List<Allele>>(3); // for ParsingUtils.split protected String[] GTValueArray = new String[100]; protected String[] genotypeKeyArray = new String[100]; protected String[] infoFieldArray = new String[1000]; protected String[] infoValueArray = new String[1000]; // for performance testing purposes public static boolean validate = true; // a key optimization -- we need a per thread string parts array, so we don't allocate a big array over and over // todo: make this thread safe? protected String[] parts = null; protected String[] genotypeParts = null; // for performance we cache the hashmap of filter encodings for quick lookup protected HashMap<String,LinkedHashSet<String>> filterHash = new HashMap<String,LinkedHashSet<String>>(); // a mapping of the VCF fields to their type, filter fields, and format fields, for quick lookup to validate against TreeMap<String, VCFHeaderLineType> infoFields = new TreeMap<String, VCFHeaderLineType>(); TreeMap<String, VCFHeaderLineType> formatFields = new TreeMap<String, VCFHeaderLineType>(); Set<String> filterFields = new HashSet<String>(); // we store a name to give to each of the variant contexts we emit protected String name = "Unknown"; protected int lineNo = 0; protected Map<String, String> stringCache = new HashMap<String, String>(); /** * @param reader the line reader to take header lines from * @return the number of header lines */ public abstract Object readHeader(LineReader reader); /** * create a genotype map * @param str the string * @param alleles the list of alleles * @param chr chrom * @param pos position * @return a mapping of sample name to genotype object */ public abstract Map<String, Genotype> createGenotypeMap(String str, List<Allele> alleles, String chr, int pos); /** * parse the filter string, first checking to see if we already have parsed it in a previous attempt * @param filterString the string to parse * @return a set of the filters applied */ protected abstract Set<String> parseFilters(String filterString); /** * create a VCF header * @param headerStrings a list of strings that represent all the ## entries * @param line the single # line (column names) * @return the count of header lines */ protected Object createHeader(List<String> headerStrings, String line) { headerStrings.add(line); Set<VCFHeaderLine> metaData = new TreeSet<VCFHeaderLine>(); Set<String> auxTags = new LinkedHashSet<String>(); // iterate over all the passed in strings for ( String str : headerStrings ) { if ( !str.startsWith(VCFHeader.METADATA_INDICATOR) ) { String[] strings = str.substring(1).split(VCFConstants.FIELD_SEPARATOR); if ( strings.length < VCFHeader.HEADER_FIELDS.values().length ) throw new TribbleException.InvalidHeader("there are not enough columns present in the header line: " + str); int arrayIndex = 0; for (VCFHeader.HEADER_FIELDS field : VCFHeader.HEADER_FIELDS.values()) { try { if (field != VCFHeader.HEADER_FIELDS.valueOf(strings[arrayIndex])) throw new TribbleException.InvalidHeader("we were expecting column name '" + field + "' but we saw '" + strings[arrayIndex] + "'"); } catch (IllegalArgumentException e) { throw new TribbleException.InvalidHeader("unknown column name '" + strings[arrayIndex] + "'; it does not match a legal column header name."); } arrayIndex++; } boolean sawFormatTag = false; if ( arrayIndex < strings.length ) { if ( !strings[arrayIndex].equals("FORMAT") ) throw new TribbleException.InvalidHeader("we were expecting column name 'FORMAT' but we saw '" + strings[arrayIndex] + "'"); sawFormatTag = true; arrayIndex++; } while ( arrayIndex < strings.length ) auxTags.add(strings[arrayIndex++]); if ( sawFormatTag && auxTags.size() == 0 ) throw new UserException.MalformedVCFHeader("The FORMAT field was provided but there is no genotype/sample data"); } else { if ( str.startsWith("##INFO=") ) { VCFInfoHeaderLine info = new VCFInfoHeaderLine(str.substring(7),version); metaData.add(info); infoFields.put(info.getName(), info.getType()); } else if ( str.startsWith("##FILTER=") ) { VCFFilterHeaderLine filter = new VCFFilterHeaderLine(str.substring(9),version); metaData.add(filter); filterFields.add(filter.getName()); } else if ( str.startsWith("##FORMAT=") ) { VCFFormatHeaderLine format = new VCFFormatHeaderLine(str.substring(9),version); metaData.add(format); formatFields.put(format.getName(), format.getType()); } else { int equals = str.indexOf("="); if ( equals != -1 ) metaData.add(new VCFHeaderLine(str.substring(2, equals), str.substring(equals+1))); } } } header = new VCFHeader(metaData, auxTags); return header; } /** * the fast decode function * @param line the line of text for the record * @return a feature, (not guaranteed complete) that has the correct start and stop */ public Feature decodeLoc(String line) { lineNo++; - String[] locParts = new String[6]; + + // the same line reader is not used for parsing the header and parsing lines, if we see a #, we've seen a header line + if (line.startsWith(VCFHeader.HEADER_INDICATOR)) return null; + + // our header cannot be null, we need the genotype sample names and counts + if (header == null) throw new ReviewedStingException("VCF Header cannot be null when decoding a record"); + + final String[] locParts = new String[6]; int nParts = ParsingUtils.split(line, locParts, VCFConstants.FIELD_SEPARATOR_CHAR, true); if ( nParts != 6 ) throw new UserException.MalformedVCF("there aren't enough columns for line " + line, lineNo); // get our alleles (because the end position depends on them) - String ref = getCachedString(locParts[3].toUpperCase()); - String alts = getCachedString(locParts[4].toUpperCase()); - List<Allele> alleles = parseAlleles(ref, alts, lineNo); + final String ref = getCachedString(locParts[3].toUpperCase()); + final String alts = getCachedString(locParts[4].toUpperCase()); + final List<Allele> alleles = parseAlleles(ref, alts, lineNo); // find out our location - int start = Integer.valueOf(locParts[1]); + final int start = Integer.valueOf(locParts[1]); int stop = start; // ref alleles don't need to be single bases for monomorphic sites if ( alleles.size() == 1 ) { stop = start + alleles.get(0).length() - 1; } else if ( !isSingleNucleotideEvent(alleles) ) { stop = clipAlleles(start, ref, alleles, null, lineNo); } return new VCFLocFeature(locParts[0], start, stop); } private final static class VCFLocFeature implements Feature { final String chr; final int start, stop; private VCFLocFeature(String chr, int start, int stop) { this.chr = chr; this.start = start; this.stop = stop; } public String getChr() { return chr; } public int getStart() { return start; } public int getEnd() { return stop; } } /** * decode the line into a feature (VariantContext) * @param line the line * @return a VariantContext */ public Feature decode(String line) { // the same line reader is not used for parsing the header and parsing lines, if we see a #, we've seen a header line if (line.startsWith(VCFHeader.HEADER_INDICATOR)) return null; // our header cannot be null, we need the genotype sample names and counts if (header == null) throw new ReviewedStingException("VCF Header cannot be null when decoding a record"); if (parts == null) parts = new String[Math.min(header.getColumnCount(), NUM_STANDARD_FIELDS+1)]; int nParts = ParsingUtils.split(line, parts, VCFConstants.FIELD_SEPARATOR_CHAR, true); // if we have don't have a header, or we have a header with no genotyping data check that we have eight columns. Otherwise check that we have nine (normal colummns + genotyping data) if (( (header == null || !header.hasGenotypingData()) && nParts != NUM_STANDARD_FIELDS) || (header != null && header.hasGenotypingData() && nParts != (NUM_STANDARD_FIELDS + 1)) ) throw new UserException.MalformedVCF("there aren't enough columns for line " + line + " (we expected " + (header == null ? NUM_STANDARD_FIELDS : NUM_STANDARD_FIELDS + 1) + " tokens, and saw " + nParts + " )", lineNo); return parseVCFLine(parts); } protected void generateException(String message) { throw new UserException.MalformedVCF(message, lineNo); } protected static void generateException(String message, int lineNo) { throw new UserException.MalformedVCF(message, lineNo); } /** * parse out the VCF line * * @param parts the parts split up * @return a variant context object */ private VariantContext parseVCFLine(String[] parts) { // increment the line count lineNo++; // parse out the required fields String contig = getCachedString(parts[0]); int pos = Integer.valueOf(parts[1]); String id = null; if ( parts[2].length() == 0 ) generateException("The VCF specification requires a valid ID field"); else if ( parts[2].equals(VCFConstants.EMPTY_ID_FIELD) ) id = VCFConstants.EMPTY_ID_FIELD; else id = new String(parts[2]); String ref = getCachedString(parts[3].toUpperCase()); String alts = getCachedString(parts[4].toUpperCase()); Double qual = parseQual(parts[5]); String filter = getCachedString(parts[6]); String info = new String(parts[7]); // get our alleles, filters, and setup an attribute map List<Allele> alleles = parseAlleles(ref, alts, lineNo); Set<String> filters = parseFilters(filter); Map<String, Object> attributes = parseInfo(info, id); // find out our current location, and clip the alleles down to their minimum length int loc = pos; // ref alleles don't need to be single bases for monomorphic sites if ( alleles.size() == 1 ) { loc = pos + alleles.get(0).length() - 1; } else if ( !isSingleNucleotideEvent(alleles) ) { ArrayList<Allele> newAlleles = new ArrayList<Allele>(); loc = clipAlleles(pos, ref, alleles, newAlleles, lineNo); alleles = newAlleles; } // do we have genotyping data if (parts.length > NUM_STANDARD_FIELDS) { attributes.put(VariantContext.UNPARSED_GENOTYPE_MAP_KEY, new String(parts[8])); attributes.put(VariantContext.UNPARSED_GENOTYPE_PARSER_KEY, this); } VariantContext vc = null; try { vc = new VariantContext(name, contig, pos, loc, alleles, qual, filters, attributes, ref.getBytes()[0]); } catch (Exception e) { generateException(e.getMessage()); } // did we resort the sample names? If so, we need to load the genotype data if ( !header.samplesWereAlreadySorted() ) vc.getGenotypes(); return vc; } /** * * @return the type of record */ public Class<VariantContext> getFeatureType() { return VariantContext.class; } /** * get the name of this codec * @return our set name */ public String getName() { return name; } /** * set the name of this codec * @param name new name */ public void setName(String name) { this.name = name; } /** * Return a cached copy of the supplied string. * * @param str string * @return interned string */ protected String getCachedString(String str) { String internedString = stringCache.get(str); if ( internedString == null ) { internedString = new String(str); stringCache.put(internedString, internedString); } return internedString; } /** * parse out the info fields * @param infoField the fields * @param id the indentifier * @return a mapping of keys to objects */ private Map<String, Object> parseInfo(String infoField, String id) { Map<String, Object> attributes = new HashMap<String, Object>(); if ( infoField.length() == 0 ) generateException("The VCF specification requires a valid info field"); if ( !infoField.equals(VCFConstants.EMPTY_INFO_FIELD) ) { if ( infoField.indexOf("\t") != -1 || infoField.indexOf(" ") != -1 ) generateException("The VCF specification does not allow for whitespace in the INFO field"); int infoFieldSplitSize = ParsingUtils.split(infoField, infoFieldArray, VCFConstants.INFO_FIELD_SEPARATOR_CHAR, false); for (int i = 0; i < infoFieldSplitSize; i++) { String key; Object value; int eqI = infoFieldArray[i].indexOf("="); if ( eqI != -1 ) { key = infoFieldArray[i].substring(0, eqI); String str = infoFieldArray[i].substring(eqI+1); // split on the INFO field separator int infoValueSplitSize = ParsingUtils.split(str, infoValueArray, VCFConstants.INFO_FIELD_ARRAY_SEPARATOR_CHAR, false); if ( infoValueSplitSize == 1 ) { value = infoValueArray[0]; } else { ArrayList<String> valueList = new ArrayList<String>(infoValueSplitSize); for ( int j = 0; j < infoValueSplitSize; j++ ) valueList.add(infoValueArray[j]); value = valueList; } } else { key = infoFieldArray[i]; value = true; } attributes.put(key, value); } } if ( ! id.equals(VCFConstants.EMPTY_ID_FIELD) ) attributes.put(VariantContext.ID_KEY, id); return attributes; } /** * create a an allele from an index and an array of alleles * @param index the index * @param alleles the alleles * @return an Allele */ protected static Allele oneAllele(String index, List<Allele> alleles) { if ( index.equals(VCFConstants.EMPTY_ALLELE) ) return Allele.NO_CALL; int i = Integer.valueOf(index); if ( i >= alleles.size() ) throw new TribbleException.InternalCodecException("The allele with index " + index + " is not defined in the REF/ALT columns in the record"); return alleles.get(i); } /** * parse genotype alleles from the genotype string * @param GT GT string * @param alleles list of possible alleles * @param cache cache of alleles for GT * @return the allele list for the GT string */ protected static List<Allele> parseGenotypeAlleles(String GT, List<Allele> alleles, Map<String, List<Allele>> cache) { // cache results [since they are immutable] and return a single object for each genotype List<Allele> GTAlleles = cache.get(GT); if ( GTAlleles == null ) { StringTokenizer st = new StringTokenizer(GT, VCFConstants.PHASING_TOKENS); GTAlleles = new ArrayList<Allele>(st.countTokens()); while ( st.hasMoreTokens() ) { String genotype = st.nextToken(); GTAlleles.add(oneAllele(genotype, alleles)); } cache.put(GT, GTAlleles); } return GTAlleles; } /** * parse out the qual value * @param qualString the quality string * @return return a double */ protected static Double parseQual(String qualString) { // if we're the VCF 4 missing char, return immediately if ( qualString.equals(VCFConstants.MISSING_VALUE_v4)) return VariantContext.NO_NEG_LOG_10PERROR; Double val = Double.valueOf(qualString); // check to see if they encoded the missing qual score in VCF 3 style, with either the -1 or -1.0. check for val < 0 to save some CPU cycles if ((val < 0) && (Math.abs(val - VCFConstants.MISSING_QUALITY_v3_DOUBLE) < VCFConstants.VCF_ENCODING_EPSILON)) return VariantContext.NO_NEG_LOG_10PERROR; // scale and return the value return val / 10.0; } /** * parse out the alleles * @param ref the reference base * @param alts a string of alternates to break into alleles * @param lineNo the line number for this record * @return a list of alleles, and a pair of the shortest and longest sequence */ protected static List<Allele> parseAlleles(String ref, String alts, int lineNo) { List<Allele> alleles = new ArrayList<Allele>(2); // we are almost always biallelic // ref checkAllele(ref, true, lineNo); Allele refAllele = Allele.create(ref, true); alleles.add(refAllele); if ( alts.indexOf(",") == -1 ) // only 1 alternatives, don't call string split parseSingleAltAllele(alleles, alts, lineNo); else for ( String alt : alts.split(",") ) parseSingleAltAllele(alleles, alt, lineNo); return alleles; } /** * check to make sure the allele is an acceptable allele * @param allele the allele to check * @param isRef are we the reference allele? * @param lineNo the line number for this record */ private static void checkAllele(String allele, boolean isRef, int lineNo) { if ( allele == null || allele.length() == 0 ) generateException("Empty alleles are not permitted in VCF records", lineNo); if ( isSymbolicAllele(allele) ) { if ( isRef ) { generateException("Symbolic alleles not allowed as reference allele: " + allele, lineNo); } } else { // check for VCF3 insertions or deletions if ( (allele.charAt(0) == VCFConstants.DELETION_ALLELE_v3) || (allele.charAt(0) == VCFConstants.INSERTION_ALLELE_v3) ) generateException("Insertions/Deletions are not supported when reading 3.x VCF's. Please" + " convert your file to VCF4 using VCFTools, available at http://vcftools.sourceforge.net/index.html", lineNo); if (!Allele.acceptableAlleleBases(allele)) generateException("Unparsable vcf record with allele " + allele, lineNo); if ( isRef && allele.equals(VCFConstants.EMPTY_ALLELE) ) generateException("The reference allele cannot be missing", lineNo); } } /** * return true if this is a symbolic allele (e.g. <SOMETAG>) otherwise false * @param allele the allele to check * @return true if the allele is a symbolic allele, otherwise false */ private static boolean isSymbolicAllele(String allele) { return (allele != null && allele.startsWith("<") && allele.endsWith(">") && allele.length() > 2); } /** * parse a single allele, given the allele list * @param alleles the alleles available * @param alt the allele to parse * @param lineNo the line number for this record */ private static void parseSingleAltAllele(List<Allele> alleles, String alt, int lineNo) { checkAllele(alt, false, lineNo); Allele allele = Allele.create(alt, false); if ( ! allele.isNoCall() ) alleles.add(allele); } protected static boolean isSingleNucleotideEvent(List<Allele> alleles) { for ( Allele a : alleles ) { if ( a.length() != 1 ) return false; } return true; } public static int computeForwardClipping(List<Allele> unclippedAlleles, String ref) { boolean clipping = true; for ( Allele a : unclippedAlleles ) { if ( a.isSymbolic() ) continue; if ( a.length() < 1 || (a.getBases()[0] != ref.getBytes()[0]) ) { clipping = false; break; } } return (clipping) ? 1 : 0; } protected static int computeReverseClipping(List<Allele> unclippedAlleles, String ref, int forwardClipping, int lineNo) { int clipping = 0; boolean stillClipping = true; while ( stillClipping ) { for ( Allele a : unclippedAlleles ) { if ( a.isSymbolic() ) continue; if ( a.length() - clipping <= forwardClipping || a.length() - forwardClipping == 0 ) stillClipping = false; else if ( ref.length() == clipping ) generateException("bad alleles encountered", lineNo); else if ( a.getBases()[a.length()-clipping-1] != ref.getBytes()[ref.length()-clipping-1] ) stillClipping = false; } if ( stillClipping ) clipping++; } return clipping; } /** * clip the alleles, based on the reference * * @param position the unadjusted start position (pre-clipping) * @param ref the reference string * @param unclippedAlleles the list of unclipped alleles * @param clippedAlleles output list of clipped alleles * @param lineNo the current line number in the file * @return the new reference end position of this event */ protected static int clipAlleles(int position, String ref, List<Allele> unclippedAlleles, List<Allele> clippedAlleles, int lineNo) { int forwardClipping = computeForwardClipping(unclippedAlleles, ref); int reverseClipping = computeReverseClipping(unclippedAlleles, ref, forwardClipping, lineNo); if ( clippedAlleles != null ) { for ( Allele a : unclippedAlleles ) { if ( a.isSymbolic() ) { clippedAlleles.add(a); } else { clippedAlleles.add(Allele.create(Arrays.copyOfRange(a.getBases(), forwardClipping, a.getBases().length-reverseClipping), a.isReference())); } } } // the new reference length int refLength = ref.length() - reverseClipping; return position+Math.max(refLength - 1,0); } public final static boolean canDecodeFile(final File potentialInput, final String MAGIC_HEADER_LINE) { try { return isVCFStream(new FileInputStream(potentialInput), MAGIC_HEADER_LINE) || isVCFStream(new GZIPInputStream(new FileInputStream(potentialInput)), MAGIC_HEADER_LINE) || isVCFStream(new BlockCompressedInputStream(new FileInputStream(potentialInput)), MAGIC_HEADER_LINE); } catch ( FileNotFoundException e ) { return false; } catch ( IOException e ) { return false; } } private final static boolean isVCFStream(final InputStream stream, final String MAGIC_HEADER_LINE) { try { byte[] buff = new byte[MAGIC_HEADER_LINE.length()]; int nread = stream.read(buff, 0, MAGIC_HEADER_LINE.length()); boolean eq = Arrays.equals(buff, MAGIC_HEADER_LINE.getBytes()); return eq; // String firstLine = new String(buff); // return firstLine.startsWith(MAGIC_HEADER_LINE); } catch ( IOException e ) { return false; } catch ( RuntimeException e ) { return false; } finally { try { stream.close(); } catch ( IOException e ) {} } } }
false
false
null
null
diff --git a/src/openmap/com/bbn/openmap/omGraphics/OMColorChooser.java b/src/openmap/com/bbn/openmap/omGraphics/OMColorChooser.java index eee03aed..31c93d76 100644 --- a/src/openmap/com/bbn/openmap/omGraphics/OMColorChooser.java +++ b/src/openmap/com/bbn/openmap/omGraphics/OMColorChooser.java @@ -1,251 +1,258 @@ // ********************************************************************** // // <copyright> // // BBN Technologies // 10 Moulton Street // Cambridge, MA 02138 // (617) 873-8000 // // Copyright (C) BBNT Solutions LLC. All rights reserved. // // </copyright> // ********************************************************************** // // $RCSfile: OMColorChooser.java,v $ -// $Revision: 1.8 $ -// $Date: 2005/08/11 20:39:14 $ +// $Revision: 1.9 $ +// $Date: 2006/01/27 15:14:44 $ // $Author: dietrick $ // // ********************************************************************** package com.bbn.openmap.omGraphics; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.Serializable; +import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.JColorChooser; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.colorchooser.ColorSelectionModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import com.bbn.openmap.Environment; import com.bbn.openmap.I18n; /** * A wrapper class that pops up a modified JColorChooser class. The * modification involves replacing the preview panel with a slider * that modifies the alpha transparency part of the color. * * @author dietrick * @author Oliver Hinds added preview panel to see color with * transparency. */ public class OMColorChooser { /** * Displays a dialog that lets you change a color. Locks up the * application until a choice is made, returning the chosen color, * or null if nothing was chosen. * * @param component the source component. * @param title the String title for the window. * @param startingColor the initial color. */ public static Color showDialog(Component component, String title, Color startingColor) { Color initColor = startingColor != null ? startingColor : Color.white; final JColorChooser jcc = new JColorChooser(initColor); ColorTracker ok = new ColorTracker(jcc); jcc.getSelectionModel().addChangeListener(ok); - jcc.setPreviewPanel(ok.getTransparancyAdjustment(initColor.getAlpha())); + /* WORKAROUND for Java bug #5029286 and #6199676 */ + // jcc.setPreviewPanel(ok.getTransparancyAdjustment(initColor.getAlpha())); + JComponent previewPanel = ok.getTransparancyAdjustment(initColor.getAlpha()); + previewPanel.setSize(previewPanel.getPreferredSize()); + previewPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 1, 0)); + jcc.setPreviewPanel(previewPanel); + JDialog colorDialog = JColorChooser.createDialog(component, title, true, jcc, ok, null); colorDialog.show(); return ok.getColor(); } public static void main(String[] argv) { Color testColor = showDialog(null, "Choose a Color", Color.white); System.out.println("Color: " + testColor + ", hex value: " + Integer.toHexString(testColor.getRGB())); System.exit(0); } } /** * A modified ActionListener used by the JColorChooser. Based on the * one used in javax.swing.JColorChooser, but with the extended * capability to handle transparancy. */ class ColorTracker implements ActionListener, ChangeListener, Serializable { ColorRect preview; JColorChooser chooser; Color color; int transparency; private I18n i18n = Environment.getI18n(); boolean isOK = false;//added because method <code>getColor</code> does not return null if action was not performed public ColorTracker(JColorChooser c) { chooser = c; preview = new ColorRect(chooser.getColor()); } /** * ActionListener interface. Sets the color from the * JColorChooser. */ public void actionPerformed(ActionEvent e) { color = chooser.getColor(); setPreviewColor(color); isOK = true; } /** * ChangeListener interface. Called when the color changes */ public void stateChanged(ChangeEvent e) { if (!(e.getSource() instanceof ColorSelectionModel)) return; setPreviewColor(((ColorSelectionModel) e.getSource()).getSelectedColor()); } /** * sets the preview color */ public void setPreviewColor(Color c) { c = new Color(c.getRed(), c.getGreen(), c.getBlue(), transparency); preview.setColor(c); preview.repaint(); color = c; } /** * Get the Color set in the JColorChooser, and set the alpha value * based on the transparency slider. */ public Color getColor() { if (!isOK) { return null; } if (color != null) { color = new Color(color.getRed(), color.getGreen(), color.getBlue(), transparency); } return color; } /** * Create the Swing components that let you change the * transparency of the color received from the JColorChooser. * * @param initialValue the starting alpha value for the color. * @return JComponent to adjust the transparency value. */ public JComponent getTransparancyAdjustment(int initialValue) { transparency = initialValue; // This sets initial transparency effect in preview... setPreviewColor(preview.getColor()); JPanel slidePanel = new JPanel(); Box slideBox = Box.createHorizontalBox(); JSlider opaqueSlide = new JSlider(JSlider.HORIZONTAL, 0/* min */, 255/* max */, initialValue/* inital */); java.util.Hashtable dict = new java.util.Hashtable(); String opaqueLabel = i18n.get(ColorTracker.class, "opaque", "opaque"); String clearLabel = i18n.get(ColorTracker.class, "clear", "clear"); if (opaqueLabel == null || opaqueLabel.length() == 0) { // translations are too long :( dict.put(new Integer(126), new JLabel(clearLabel)); } else { dict.put(new Integer(50), new JLabel(clearLabel)); dict.put(new Integer(200), new JLabel(opaqueLabel)); } //commented because polish translations are too long opaqueSlide.setLabelTable(dict); opaqueSlide.setPaintLabels(true); opaqueSlide.setMajorTickSpacing(50); opaqueSlide.setPaintTicks(true); opaqueSlide.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent ce) { JSlider slider = (JSlider) ce.getSource(); if (slider.getValueIsAdjusting()) { transparency = slider.getValue(); } // This sets transparency in preview... setPreviewColor(preview.getColor()); } }); preview.setPreferredSize(new Dimension(100, slideBox.getHeight())); slideBox.add(preview); slideBox.add(Box.createGlue()); slideBox.add(opaqueSlide); slideBox.add(Box.createGlue()); slidePanel.add(slideBox); // You know what, it just has to be something, so the // UIManager will think it's valid. It will get resized as // appropriate when the JDialog gets packed. slidePanel.setSize(new Dimension(50, 50)); return slidePanel; } } // class to display the currently selected color class ColorRect extends JPanel { Color c; // color to display /** * constructor */ public ColorRect(Color _c) { setBackground(Color.white); c = _c; } /** * set the color to tht specified * * @param _c color to paint */ public void setColor(Color _c) { c = _c; } /** * get the color */ public Color getColor() { return c; } /** * paints this panel */ public void paint(Graphics g) { super.paint(g); g.setColor(c); ((Graphics2D) g).fill(g.getClip()); } } \ No newline at end of file
false
false
null
null
diff --git a/src/main/java/com/cloudapp/impl/model/CloudAppItemImpl.java b/src/main/java/com/cloudapp/impl/model/CloudAppItemImpl.java index 6b991a9..9d6739e 100644 --- a/src/main/java/com/cloudapp/impl/model/CloudAppItemImpl.java +++ b/src/main/java/com/cloudapp/impl/model/CloudAppItemImpl.java @@ -1,111 +1,111 @@ package com.cloudapp.impl.model; import java.text.ParseException; import java.util.Date; import org.json.JSONObject; import com.cloudapp.api.CloudAppException; import com.cloudapp.api.model.CloudAppItem; public class CloudAppItemImpl extends CloudAppModel implements CloudAppItem { public CloudAppItemImpl(JSONObject json) { this.json = json; } public String getHref() throws CloudAppException { return getString("href"); } public String getName() throws CloudAppException { return getString("name"); } public boolean isPrivate() throws CloudAppException { return getBoolean("private"); } public boolean isSubscribed() throws CloudAppException { return getBoolean("subscribed"); } public boolean isTrashed() throws CloudAppException { String d = getString("deleted_at"); - return (d == null || d == "null"); + return !(d == null || d == "null"); } public String getUrl() throws CloudAppException { return getString("url"); } public String getContentUrl() throws CloudAppException { return getString("content_url"); } public Type getItemType() throws CloudAppException { String t = getString("item_type"); try { return Type.valueOf(t.toUpperCase()); } catch (IllegalArgumentException e) { return Type.UNKNOWN; } } public long getViewCounter() throws CloudAppException { return getLong("view_counter"); } public String getIconUrl() throws CloudAppException { return getString("icon"); } public String getRemoteUrl() throws CloudAppException { return getString("remote_url"); } public String getRedirectUrl() throws CloudAppException { return getString("redirect_url"); } public String getThumbnailUrl() throws CloudAppException { if (json.has("thumbnail_url")) { return getString("thumbnail_url"); } else { return null; } } public String getSource() throws CloudAppException { return getString("source"); } public Date getCreatedAt() throws CloudAppException { try { String d = getString("created_at"); return format.parse(d); } catch (ParseException e) { throw new CloudAppException(500, "Could not parse the date.", e); } } public Date getUpdatedAt() throws CloudAppException { try { String d = getString("updated_at"); return format.parse(d); } catch (ParseException e) { throw new CloudAppException(500, "Could not parse the date.", e); } } public Date getDeletedAt() throws CloudAppException { try { String d = getString("deleted_at"); return format.parse(d); } catch (ParseException e) { throw new CloudAppException(500, "Could not parse the date.", e); } } }
true
false
null
null
diff --git a/nifty-core/src/main/java/de/lessvoid/nifty/elements/Element.java b/nifty-core/src/main/java/de/lessvoid/nifty/elements/Element.java index 6bbdb5e1..1eb21913 100644 --- a/nifty-core/src/main/java/de/lessvoid/nifty/elements/Element.java +++ b/nifty-core/src/main/java/de/lessvoid/nifty/elements/Element.java @@ -1,2696 +1,2696 @@ package de.lessvoid.nifty.elements; import de.lessvoid.nifty.EndNotify; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.NiftyEvent; import de.lessvoid.nifty.NiftyMethodInvoker; import de.lessvoid.nifty.controls.Controller; import de.lessvoid.nifty.controls.FocusHandler; import de.lessvoid.nifty.controls.NiftyControl; import de.lessvoid.nifty.controls.NiftyInputControl; import de.lessvoid.nifty.effects.*; import de.lessvoid.nifty.elements.events.ElementDisableEvent; import de.lessvoid.nifty.elements.events.ElementEnableEvent; import de.lessvoid.nifty.elements.events.ElementHideEvent; import de.lessvoid.nifty.elements.events.ElementShowEvent; import de.lessvoid.nifty.elements.render.ElementRenderer; import de.lessvoid.nifty.elements.render.ImageRenderer; import de.lessvoid.nifty.elements.render.PanelRenderer; import de.lessvoid.nifty.elements.render.TextRenderer; import de.lessvoid.nifty.elements.tools.ElementTreeTraverser; import de.lessvoid.nifty.input.NiftyMouseInputEvent; import de.lessvoid.nifty.input.keyboard.KeyboardInputEvent; import de.lessvoid.nifty.layout.BoxConstraints; import de.lessvoid.nifty.layout.LayoutPart; import de.lessvoid.nifty.layout.align.HorizontalAlign; import de.lessvoid.nifty.layout.align.VerticalAlign; import de.lessvoid.nifty.layout.manager.LayoutManager; import de.lessvoid.nifty.loaderv2.types.ElementType; import de.lessvoid.nifty.loaderv2.types.PopupType; import de.lessvoid.nifty.loaderv2.types.apply.*; import de.lessvoid.nifty.loaderv2.types.helper.PaddingAttributeParser; import de.lessvoid.nifty.render.NiftyRenderEngine; import de.lessvoid.nifty.screen.KeyInputHandler; import de.lessvoid.nifty.screen.MouseOverHandler; import de.lessvoid.nifty.screen.Screen; import de.lessvoid.nifty.spi.time.TimeProvider; import de.lessvoid.nifty.tools.SizeValue; import de.lessvoid.xml.xpp3.Attributes; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.*; import java.util.logging.Logger; /** * @author void */ public class Element implements NiftyEvent, EffectManager.Notify { @Nonnull private static final Logger log = Logger.getLogger(Element.class.getName()); @Nonnull private final ElementType elementType; @Nullable private String id; private int renderOrder; @Nullable private Element parent; @Nullable private List<Element> children; /** * This set defines the render order of the child elements using a Comparator. */ @Nullable private Set<Element> elementsRenderOrderSet; /** * This is the shared instance of the comparator used to get the rendering oder for the child elements of another * element. */ @Nonnull private static final Comparator<Element> RENDER_ORDER_COMPARATOR = new RenderOrderComparator(); /** * We keep a copy of the elementsRenderOrderSet in a simple array for being more GC friendly while rendering. */ @Nullable private Element[] elementsRenderOrder; /** * The LayoutManager we should use for all child elements. */ @Nullable private LayoutManager layoutManager; /** * The LayoutPart for laying out this element. */ @Nonnull private final LayoutPart layoutPart; /** * The ElementRenderer we should use to render this element. */ @Nonnull private final ElementRenderer[] elementRenderer; @Nonnull private EffectManager effectManager; @Nonnull private ElementInteraction interaction; /** * Effect state cache (this includes info about the child state) and is only * update when Effect states are changed. */ @Nonnull private final ElementEffectStateCache effectStateCache = new ElementEffectStateCache(); /** * Nifty instance this element is attached to. */ @Nonnull private final Nifty nifty; /** * The focus handler this element is attached to. */ @Nonnull private final FocusHandler focusHandler; /** * Whether the element is enabled or not. */ private boolean enabled; /** * This helps us to keep track when you enable or disable this multiple times. We don't want * to start the onEnabled/onDisabled effects when the element is already enabled/disabled. */ private int enabledCount; /** * Whether the element is visible or not. */ private boolean visible; /** * this is set to true, when there's no interaction with the element * possible. this happens when the onEndScreen effect starts. */ private boolean done; /** * this is set to true when there's no interaction with this element possibe. * (as long as onStartScreen and onEndScreen events are active even when this * element is not using the onStartScreen effect at all but a parent element did) */ private boolean interactionBlocked; /** * Whether the element is visible to mouse events. */ private boolean visibleToMouseEvents; private boolean clipChildren; /** * The attached control when this element is a control. */ @Nullable private NiftyInputControl attachedInputControl = null; /** * Whether this element can be focused or not. */ private boolean focusable = false; /** * This attribute determines the element before (!) the new element will be inserted into the focusHandler. * You can set this to any element id on the screen and this element will be inserted right before the * given element. This is especially useful when you dynamically remove and add elements and you need to * enforce a specific focus order. * <p/> * The default value is null which will simply add the elements as they are created. */ @Nullable private String focusableInsertBeforeElementId; /** * The screen this element is part of. */ @Nullable private Screen screen; @Nonnull private TimeProvider time; @Nonnull private final List<String> elementDebugOut = new ArrayList<String>(); @Nonnull private final StringBuilder elementDebug = new StringBuilder(); private boolean parentClipArea = false; private int parentClipX; private int parentClipY; private int parentClipWidth; private int parentClipHeight; /* * Whether or not this element should ignore all mouse events. */ private boolean ignoreMouseEvents; /* * Whether or not this element should ignore all keyboard events. */ private boolean ignoreKeyboardEvents; @Nonnull private static final Convert convert; @Nonnull private static final Map<Class<? extends ElementRenderer>, ApplyRenderer> rendererApplier; static { convert = new Convert(); rendererApplier = new HashMap<Class<? extends ElementRenderer>, ApplyRenderer>(); rendererApplier.put(TextRenderer.class, new ApplyRenderText(convert)); rendererApplier.put(ImageRenderer.class, new ApplyRendererImage(convert)); rendererApplier.put(PanelRenderer.class, new ApplyRendererPanel(convert)); } @Nullable private Map<String, Object> userData; public Element( @Nonnull final Nifty nifty, @Nonnull final ElementType elementType, @Nullable final String id, @Nullable final Element parent, @Nonnull final FocusHandler focusHandler, final boolean visibleToMouseEvents, @Nonnull final TimeProvider timeProvider, @Nonnull final ElementRenderer... elementRenderer) { this( nifty, elementType, id, parent, new LayoutPart(), focusHandler, visibleToMouseEvents, timeProvider, elementRenderer); } /** * Use this constructor to specify a LayoutPart */ public Element( @Nonnull final Nifty nifty, @Nonnull final ElementType elementType, @Nullable final String id, @Nullable final Element parent, @Nonnull final LayoutPart layoutPart, @Nonnull final FocusHandler focusHandler, final boolean visibleToMouseEvents, @Nonnull final TimeProvider timeProvider, @Nonnull final ElementRenderer... elementRenderer) { this.nifty = nifty; this.elementType = elementType; this.id = id; this.parent = parent; this.elementRenderer = elementRenderer; this.effectManager = new EffectManager(this); this.effectManager.setAlternateKey(this.nifty.getAlternateKey()); this.layoutPart = layoutPart; this.enabled = true; this.enabledCount = 0; this.visible = true; this.done = false; this.interactionBlocked = false; this.focusHandler = focusHandler; this.visibleToMouseEvents = visibleToMouseEvents; this.time = timeProvider; this.interaction = new ElementInteraction(this.nifty, this); } /** * This is used when the element is being created from an ElementType in the loading process. */ public void initializeFromAttributes( @Nonnull final Screen targetScreen, @Nonnull final Attributes attributes, @Nonnull final NiftyRenderEngine renderEngine) { BoxConstraints boxConstraints = layoutPart.getBoxConstraints(); boxConstraints.setHeight(convert.sizeValue(attributes.get("height"))); boxConstraints.setWidth(convert.sizeValue(attributes.get("width"))); boxConstraints.setX(convert.sizeValue(attributes.get("x"))); boxConstraints.setY(convert.sizeValue(attributes.get("y"))); boxConstraints.setHorizontalAlign(convert.horizontalAlign(attributes.get("align"))); boxConstraints.setVerticalAlign(convert.verticalAlign(attributes.get("valign"))); String paddingLeft = Convert.DEFAULT_PADDING; String paddingRight = Convert.DEFAULT_PADDING; String paddingTop = Convert.DEFAULT_PADDING; String paddingBottom = Convert.DEFAULT_PADDING; if (attributes.isSet("padding")) { try { String padding = attributes.get("padding"); assert padding != null; // checked by isSet PaddingAttributeParser paddingParser = new PaddingAttributeParser(padding); paddingLeft = paddingParser.getLeft(); paddingRight = paddingParser.getRight(); paddingTop = paddingParser.getTop(); paddingBottom = paddingParser.getBottom(); } catch (Exception e) { log.warning(e.getMessage()); } } boxConstraints.setPaddingLeft(convert.paddingSizeValue(attributes.get("paddingLeft"), paddingLeft)); boxConstraints.setPaddingRight(convert.paddingSizeValue(attributes.get("paddingRight"), paddingRight)); boxConstraints.setPaddingTop(convert.paddingSizeValue(attributes.get("paddingTop"), paddingTop)); boxConstraints.setPaddingBottom(convert.paddingSizeValue(attributes.get("paddingBottom"), paddingBottom)); String marginLeft = Convert.DEFAULT_MARGIN; String marginRight = Convert.DEFAULT_MARGIN; String marginTop = Convert.DEFAULT_MARGIN; String marginBottom = Convert.DEFAULT_MARGIN; if (attributes.isSet("margin")) { try { String margin = attributes.get("margin"); assert margin != null; // checked by isSet PaddingAttributeParser marginParser = new PaddingAttributeParser(margin); marginLeft = marginParser.getLeft(); marginRight = marginParser.getRight(); marginTop = marginParser.getTop(); marginBottom = marginParser.getBottom(); } catch (Exception e) { log.warning(e.getMessage()); } } boxConstraints.setMarginLeft(convert.paddingSizeValue(attributes.get("marginLeft"), marginLeft)); boxConstraints.setMarginRight(convert.paddingSizeValue(attributes.get("marginRight"), marginRight)); boxConstraints.setMarginTop(convert.paddingSizeValue(attributes.get("marginTop"), marginTop)); boxConstraints.setMarginBottom(convert.paddingSizeValue(attributes.get("marginBottom"), marginBottom)); this.clipChildren = attributes.getAsBoolean("childClip", Convert.DEFAULT_CHILD_CLIP); this.renderOrder = attributes.getAsInteger("renderOrder", Convert.DEFAULT_RENDER_ORDER); boolean visible = attributes.getAsBoolean("visible", Convert.DEFAULT_VISIBLE); if (visible) { this.visible = true; } this.visibleToMouseEvents = attributes.getAsBoolean("visibleToMouse", Convert.DEFAULT_VISIBLE_TO_MOUSE); this.layoutManager = convert.layoutManager(attributes.get("childLayout")); this.focusable = attributes.getAsBoolean("focusable", Convert.DEFAULT_FOCUSABLE); this.focusableInsertBeforeElementId = attributes.get("focusableInsertBeforeElementId"); for (int i = 0; i < elementRenderer.length; i++) { ElementRenderer renderer = elementRenderer[i]; ApplyRenderer rendererApply = rendererApplier.get(renderer.getClass()); rendererApply.apply(targetScreen, this, attributes, renderEngine); } } public void initializeFromPostAttributes(@Nonnull final Attributes attributes) { boolean visible = attributes.getAsBoolean("visible", Convert.DEFAULT_VISIBLE); if (!visible) { hideWithChildren(); } } private void hideWithChildren() { visible = false; if (children != null) { for (int i = 0; i < children.size(); i++) { Element element = children.get(i); element.hideWithChildren(); } } } @Nullable public String getId() { return id; } /** * Get the parent of this element. * * @return either the parent of the element or {@code this} in case the element is the root element */ @Nonnull public Element getParent() { return parent == null ? this : parent; } /** * Check if this element has a parent. If this is not the case the element is a root element. * * @return {@code true} in case the element has a parent */ public boolean hasParent() { return parent != null; } public void setParent(@Nullable final Element element) { parent = element; // This element has a new parent. Check the parent's clip area and update this element accordingly. if (parentHasClipArea()) { setParentClipArea(parentClipX, parentClipY, parentClipWidth, parentClipHeight); notifyListeners(); } else { parentClipArea = false; } } private boolean parentHasClipArea() { if (parent == null) { return false; } return parent.parentClipArea; } @Nonnull public String getElementStateString(@Nonnull final String offset) { return getElementStateString(offset, ".*"); } @Nonnull public String getElementStateString(@Nonnull final String offset, @Nonnull final String regex) { elementDebugOut.clear(); elementDebugOut.add(" type: [" + elementType.output(offset.length()) + "]"); elementDebugOut.add(" style [" + getElementType().getAttributes().get("style") + "]"); elementDebugOut.add(" state [" + getState() + "]"); elementDebugOut.add(" position [x=" + getX() + ", y=" + getY() + ", w=" + getWidth() + ", h=" + getHeight() + "]"); elementDebugOut.add(" constraint [" + outputSizeValue(layoutPart.getBoxConstraints().getX()) + ", " + "" + outputSizeValue(layoutPart.getBoxConstraints().getY()) + ", " + outputSizeValue(layoutPart .getBoxConstraints().getWidth()) + ", " + outputSizeValue(layoutPart.getBoxConstraints().getHeight()) + "]"); elementDebugOut.add(" padding [" + outputSizeValue(layoutPart.getBoxConstraints().getPaddingLeft()) + ", " + "" + outputSizeValue(layoutPart.getBoxConstraints().getPaddingRight()) + ", " + "" + outputSizeValue(layoutPart.getBoxConstraints().getPaddingTop()) + ", " + "" + outputSizeValue(layoutPart.getBoxConstraints().getPaddingBottom()) + "]"); elementDebugOut.add(" margin [" + outputSizeValue(layoutPart.getBoxConstraints().getMarginLeft()) + ", " + "" + outputSizeValue(layoutPart.getBoxConstraints().getMarginRight()) + ", " + "" + outputSizeValue(layoutPart.getBoxConstraints().getMarginTop()) + ", " + "" + outputSizeValue(layoutPart.getBoxConstraints().getMarginBottom()) + "]"); StringBuilder state = new StringBuilder(); if (focusable) { state.append(" focusable"); } if (enabled) { if (state.length() > 0) { state.append(","); } state.append(" enabled(").append(enabledCount).append(")"); } if (visible) { if (state.length() > 0) { state.append(","); } state.append(" visible"); } if (visibleToMouseEvents) { if (state.length() > 0) { state.append(","); } state.append(" mouseable"); } if (clipChildren) { if (state.length() > 0) { state.append(","); } state.append(" clipChildren"); } elementDebugOut.add(" flags [" + state + "]"); elementDebugOut.add(" effects [" + effectManager.getStateString(offset) + "]"); elementDebugOut.add(" renderOrder [" + renderOrder + "]"); if (parentClipArea) { elementDebugOut.add(" parent clip [x=" + parentClipX + ", y=" + parentClipY + ", w=" + parentClipWidth + ", " + "h=" + parentClipHeight + "]"); } StringBuilder renderOrder = new StringBuilder(); renderOrder.append(" render order: "); if (children != null && elementsRenderOrderSet != null) { for (Element e : elementsRenderOrderSet) { renderOrder.append("[").append(e.id).append(" (") .append((e.renderOrder == 0) ? children.indexOf(e) : e.renderOrder).append(")]"); } } elementDebugOut.add(renderOrder.toString()); elementDebug.delete(0, elementDebug.length()); for (int i = 0; i < elementDebugOut.size(); i++) { String line = elementDebugOut.get(i); if (line.matches(regex)) { if (elementDebug.length() > 0) { elementDebug.append("\n").append(offset); } elementDebug.append(line); } } return elementDebug.toString(); } @Nonnull private String getState() { if (isEffectActive(EffectEventId.onStartScreen)) { return "starting"; } if (isEffectActive(EffectEventId.onEndScreen)) { return "ending"; } if (!visible) { return "hidden"; } if (interactionBlocked) { return "interactionBlocked"; } if (!enabled) { return "disabled"; } return "normal"; } @Nullable private String outputSizeValue(@Nullable final SizeValue value) { if (value == null) { return "null"; } else { return value.toString(); } } /** * Gets the x location of the top left corner of this element. */ public int getX() { return layoutPart.getBox().getX(); } /** * Gets the y location of the top left corner of this element. */ public int getY() { return layoutPart.getBox().getY(); } public int getHeight() { return layoutPart.getBox().getHeight(); } public int getWidth() { return layoutPart.getBox().getWidth(); } public void setHeight(int height) { layoutPart.getBox().setHeight(height); } public void setWidth(int width) { layoutPart.getBox().setWidth(width); } /** * @deprecated Use {@link #getChildren()} */ @Nonnull @Deprecated public List<Element> getElements() { return getChildren(); } @Nonnull public List<Element> getChildren() { if (children == null) { return Collections.emptyList(); } return Collections.unmodifiableList(children); } /** * Get the amount of children assigned to this element. * * @return the amaount of children */ public int getChildrenCount() { return elementsRenderOrder != null ? elementsRenderOrder.length : 0; } /** * Get all children, children of children, etc, recursively. * * @return an iterator that will traverse the element's entire tree downward. */ @Nonnull public Iterator<Element> getDescendants() { if (children == null) { // We don't want to give up Java 1.6 compatibility right now. Since Collections.emptyIterator() is Java 1.7 API // for now we've made our own replacement (see end of class). If we finally switch over to 1.7 we can use the // original method. // // return Collections.emptyIterator(); return emptyIterator(); } return new ElementTreeTraverser(this); } /** * @deprecated Use {@link #addChild(Element)} instead. * <p/> * Adds a child element to the end of the list of this element's children. */ @Deprecated public void add(@Nonnull final Element child) { addChild(child); } /** * @deprecated Use {@link #insertChild(Element, int)} instead. * <p/> * Inserts a child element at the specified index in this element's list of children. */ @Deprecated public void add(@Nonnull final Element child, final int index) { insertChild(child, index); } /** * Adds a child element to the end of the list of this element's children. */ public void addChild(@Nonnull final Element child) { insertChild(child, getChildrenCount()); } /** * Inserts a child element at the specified index in this element's list of children. */ public void insertChild(@Nonnull final Element child, final int index) { final int lastValidIndex = getChildrenCount(); int usedIndex = index; if (index < 0 || index > lastValidIndex) { log.severe("Index is out of range. Index: " + index + " Last valid: " + lastValidIndex); usedIndex = Math.min(lastValidIndex, Math.max(0, index)); } if (children == null) { children = new ArrayList<Element>(); } children.add(usedIndex, child); if (elementsRenderOrderSet == null) { elementsRenderOrderSet = new TreeSet<Element>(RENDER_ORDER_COMPARATOR); } if (!elementsRenderOrderSet.add(child)) { log.severe("Adding the element failed as it seems this element is already part of the children list. This is " + "bad. Rebuilding the children list is required now."); final int childCount = children.size(); boolean foundProblem = false; for (int i = 0; i < childCount; i++) { if (i == usedIndex) { continue; } Element testChild = children.get(i); if (testChild.equals(child)) { foundProblem = true; children.remove(i); break; } } if (!foundProblem) { /* Can't locate the issue, recovery failed -> undoing insert and throwing exception */ children.remove(usedIndex); throw new IllegalStateException("Insert item failed, render list refused the item, " + "but duplicate couldn't be located in the children list. Element is corrupted."); } } else { elementsRenderOrder = elementsRenderOrderSet.toArray(new Element[elementsRenderOrderSet.size()]); } } /** * Set the index of this element in it's parent's list of children. */ public void setIndex(final int index) { if (parent == null) { return; } List<Element> parentChildren = parent.children; if (parentChildren == null) { log.severe("Element tree corrupted. Parent element has not children."); } else { final int curInd = parentChildren.indexOf(this); if (curInd >= 0 && index != curInd) { Element shouldBeThis = parentChildren.remove(curInd); if (shouldBeThis.equals(this)) { parentChildren.add(index, this); } else { log.severe("Setting index failed, detected index did not return correct element. Undoing operation"); parentChildren.add(curInd, shouldBeThis); } } } } public void render(@Nonnull final NiftyRenderEngine r) { if (visible) { if (effectManager.isEmpty()) { r.saveState(null); renderElement(r); renderChildren(r); r.restoreState(); } else { r.saveState(null); effectManager.begin(r, this); effectManager.renderPre(r, this); renderElement(r); effectManager.renderPost(r, this); renderChildren(r); effectManager.end(r); r.restoreState(); r.saveState(null); effectManager.renderOverlay(r, this); r.restoreState(); } } } private void renderElement(@Nonnull final NiftyRenderEngine r) { for (int i = 0; i < elementRenderer.length; i++) { ElementRenderer renderer = elementRenderer[i]; renderer.render(this, r); } } private void renderChildren(@Nonnull final NiftyRenderEngine r) { if (clipChildren) { r.enableClip(getX(), getY(), getX() + getWidth(), getY() + getHeight()); renderInternalChildElements(r); r.disableClip(); } else { renderInternalChildElements(r); } } private void renderInternalChildElements(@Nonnull final NiftyRenderEngine r) { if (elementsRenderOrder != null) { for (int i = 0; i < elementsRenderOrder.length; i++) { Element p = elementsRenderOrder[i]; p.render(r); } } } public void setLayoutManager(@Nullable final LayoutManager newLayout) { this.layoutManager = newLayout; } public void resetLayout() { TextRenderer textRenderer = getRenderer(TextRenderer.class); if (textRenderer != null) { textRenderer.resetLayout(this); } if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element e = children.get(i); e.resetLayout(); } } } private void preProcessConstraintWidth() { if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element e = children.get(i); e.preProcessConstraintWidth(); } } preProcessConstraintWidthThisLevel(); } private void preProcessConstraintWidthThisLevel() { // This is either the original width value, or a value we set here. SizeValue myWidth = getConstraintWidth(); if (layoutManager != null) { // unset width, or width="sum" or width="max" // try to calculate the width constraint using the children // but only if all child elements have a fixed pixel width. // The difference between an unset width and width="sum" is that the latter does not fail if // there are values that are not pixel, it simply considers them to be "0". // width="sum" also simply sums the width values, it does not care about the layout manager. if (myWidth.hasDefault()) { List<LayoutPart> layoutPartChild = getLayoutChildrenWithIndependentWidth(); // if all (!) child elements have a pixel fixed width we can calculate a new width constraint for this element! if (!layoutPartChild.isEmpty() && getChildrenCount() == layoutPartChild.size()) { SizeValue newWidth = layoutManager.calculateConstraintWidth(this.layoutPart, layoutPartChild); if (newWidth.hasValue()) { int newWidthPx = newWidth.getValueAsInt(0); - newWidthPx += this.layoutPart.getBoxConstraints().getPaddingTop().getValueAsInt(newWidth.getValueAsInt + newWidthPx += this.layoutPart.getBoxConstraints().getPaddingLeft().getValueAsInt(newWidth.getValueAsInt (newWidthPx)); - newWidthPx += this.layoutPart.getBoxConstraints().getPaddingBottom().getValueAsInt(newWidth.getValueAsInt + newWidthPx += this.layoutPart.getBoxConstraints().getPaddingRight().getValueAsInt(newWidth.getValueAsInt (newWidthPx)); setConstraintWidth(SizeValue.def(newWidthPx)); } } else { setConstraintWidth(SizeValue.def()); } } else if (myWidth.hasSum()) { List<LayoutPart> layoutPartChild = getLayoutChildrenWithIndependentWidth(); SizeValue newWidth = layoutPart.getSumWidth(layoutPartChild); if (newWidth.hasValue()) { int newWidthPx = newWidth.getValueAsInt(0); - newWidthPx += this.layoutPart.getBoxConstraints().getPaddingTop().getValueAsInt(newWidth.getValueAsInt + newWidthPx += this.layoutPart.getBoxConstraints().getPaddingLeft().getValueAsInt(newWidth.getValueAsInt (newWidthPx)); - newWidthPx += this.layoutPart.getBoxConstraints().getPaddingBottom().getValueAsInt(newWidth.getValueAsInt + newWidthPx += this.layoutPart.getBoxConstraints().getPaddingRight().getValueAsInt(newWidth.getValueAsInt (newWidthPx)); setConstraintWidth(SizeValue.sum(newWidthPx)); } else { setConstraintWidth(SizeValue.sum(0)); } } else if (myWidth.hasMax()) { List<LayoutPart> layoutPartChild = getLayoutChildrenWithIndependentWidth(); SizeValue newWidth = layoutPart.getMaxWidth(layoutPartChild); if (newWidth.hasValue()) { int newWidthPx = newWidth.getValueAsInt(0); - newWidthPx += this.layoutPart.getBoxConstraints().getPaddingTop().getValueAsInt(newWidth.getValueAsInt + newWidthPx += this.layoutPart.getBoxConstraints().getPaddingLeft().getValueAsInt(newWidth.getValueAsInt (newWidthPx)); - newWidthPx += this.layoutPart.getBoxConstraints().getPaddingBottom().getValueAsInt(newWidth.getValueAsInt + newWidthPx += this.layoutPart.getBoxConstraints().getPaddingRight().getValueAsInt(newWidth.getValueAsInt (newWidthPx)); setConstraintWidth(SizeValue.max(newWidthPx)); } else { setConstraintWidth(SizeValue.max(0)); } } } } @Nonnull private List<LayoutPart> getLayoutChildrenWithIndependentWidth() { if (children == null) { return Collections.emptyList(); } final int childrenCount = children.size(); List<LayoutPart> layoutPartChild = new ArrayList<LayoutPart>(childrenCount); for (int i = 0; i < childrenCount; i++) { Element e = children.get(i); SizeValue childWidth = e.getConstraintWidth(); if (childWidth.isPixel() && childWidth.isIndependentFromParent()) { layoutPartChild.add(e.layoutPart); } } return layoutPartChild; } private void preProcessConstraintHeight() { if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element e = children.get(i); e.preProcessConstraintHeight(); } } preProcessConstraintHeightThisLevel(); } private void preProcessConstraintHeightThisLevel() { // This is either the original height value, or a value we set here. SizeValue myHeight = getConstraintHeight(); if (layoutManager != null) { // unset height, or height="sum" or height="max" // try to calculate the height constraint using the children // but only if all child elements have a fixed pixel height. // The difference between an unset height and height="sum" is that the latter does not fail if // there are values that are not pixel, it simply considers them to be "0". // height="sum" also simply sums the height values, it does not care about the layout manager. if (myHeight.hasDefault()) { List<LayoutPart> layoutPartChild = getLayoutChildrenWithIndependentHeight(); // if all (!) child elements have a pixel fixed height we can calculate a new height constraint for this // element! if (!layoutPartChild.isEmpty() && getChildrenCount() == layoutPartChild.size()) { SizeValue newHeight = layoutManager.calculateConstraintHeight(this.layoutPart, layoutPartChild); if (newHeight.hasValue()) { int newHeightPx = newHeight.getValueAsInt(0); newHeightPx += this.layoutPart.getBoxConstraints().getPaddingTop().getValueAsInt(newHeight.getValueAsInt (newHeightPx)); newHeightPx += this.layoutPart.getBoxConstraints().getPaddingBottom().getValueAsInt(newHeight .getValueAsInt(newHeightPx)); setConstraintHeight(SizeValue.def(newHeightPx)); } } else { setConstraintHeight(SizeValue.def()); } } else if (myHeight.hasSum()) { List<LayoutPart> layoutPartChild = getLayoutChildrenWithIndependentHeight(); SizeValue newHeight = layoutPart.getSumHeight(layoutPartChild); if (newHeight.hasValue()) { int newHeightPx = newHeight.getValueAsInt(0); newHeightPx += this.layoutPart.getBoxConstraints().getPaddingTop().getValueAsInt(newHeight.getValueAsInt (newHeightPx)); newHeightPx += this.layoutPart.getBoxConstraints().getPaddingBottom().getValueAsInt(newHeight.getValueAsInt (newHeightPx)); setConstraintHeight(SizeValue.sum(newHeightPx)); } else { setConstraintHeight(SizeValue.sum(0)); } } else if (myHeight.hasMax()) { List<LayoutPart> layoutPartChild = getLayoutChildrenWithIndependentHeight(); SizeValue newHeight = layoutPart.getMaxHeight(layoutPartChild); if (newHeight.hasValue()) { int newHeightPx = newHeight.getValueAsInt(0); newHeightPx += this.layoutPart.getBoxConstraints().getPaddingTop().getValueAsInt(newHeight.getValueAsInt (newHeightPx)); newHeightPx += this.layoutPart.getBoxConstraints().getPaddingBottom().getValueAsInt(newHeight.getValueAsInt (newHeightPx)); setConstraintHeight(SizeValue.max(newHeightPx)); } else { setConstraintHeight(SizeValue.max(0)); } } } } @Nonnull private List<LayoutPart> getLayoutChildrenWithIndependentHeight() { if (children == null) { return Collections.emptyList(); } final int childrenCount = children.size(); List<LayoutPart> layoutPartChild = new ArrayList<LayoutPart>(childrenCount); for (int i = 0; i < childrenCount; i++) { Element e = children.get(i); SizeValue childHeight = e.getConstraintHeight(); if (childHeight.isPixel() && childHeight.isIndependentFromParent()) { layoutPartChild.add(e.layoutPart); } } return layoutPartChild; } private void processLayoutInternal() { if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); TextRenderer textRenderer = w.getRenderer(TextRenderer.class); if (textRenderer != null) { textRenderer.setWidthConstraint(w, w.getConstraintWidth(), getWidth(), nifty.getRenderEngine()); } } } } private void processLayout() { processLayoutInternal(); if (layoutManager != null) { if (children != null) { final int childrenCount = children.size(); // we need a list of LayoutPart and not of Element, so we'll build one on the fly here List<LayoutPart> layoutPartChild = new ArrayList<LayoutPart>(childrenCount); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); layoutPartChild.add(w.layoutPart); } // use out layoutManager to layout our children layoutManager.layoutElements(layoutPart, layoutPartChild); } if (attachedInputControl != null) { NiftyControl niftyControl = attachedInputControl.getNiftyControl(NiftyControl.class); if (niftyControl != null) { if (niftyControl.isBound()) { niftyControl.layoutCallback(); } } } if (children != null) { // repeat this step for all child elements final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.processLayout(); } } } if (clipChildren && children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.setParentClipArea(getX(), getY(), getWidth(), getHeight()); } } } public void layoutElements() { prepareLayout(); processLayout(); prepareLayout(); processLayout(); prepareLayout(); processLayout(); } private void prepareLayout() { preProcessConstraintWidth(); preProcessConstraintHeight(); } private void setParentClipArea(final int x, final int y, final int width, final int height) { parentClipArea = true; parentClipX = x; parentClipY = y; parentClipWidth = width; parentClipHeight = height; if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.setParentClipArea(parentClipX, parentClipY, parentClipWidth, parentClipHeight); } } } public void resetEffects() { effectManager.reset(); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.resetEffects(); } } } public void resetAllEffects() { effectManager.resetAll(); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.resetAllEffects(); } } } public void resetForHide() { effectManager.resetForHide(); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.resetForHide(); } } } public void resetSingleEffect(@Nonnull final EffectEventId effectEventId) { effectManager.resetSingleEffect(effectEventId); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.resetSingleEffect(effectEventId); } } } public void resetSingleEffect(@Nonnull final EffectEventId effectEventId, @Nonnull final String customKey) { effectManager.resetSingleEffect(effectEventId, customKey); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.resetSingleEffect(effectEventId, customKey); } } } public void resetMouseDown() { interaction.resetMouseDown(); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.resetMouseDown(); } } } public void setConstraintX(@Nonnull final SizeValue newX) { layoutPart.getBoxConstraints().setX(newX); notifyListeners(); } public void setConstraintY(@Nonnull final SizeValue newY) { layoutPart.getBoxConstraints().setY(newY); notifyListeners(); } public void setConstraintWidth(@Nonnull final SizeValue newWidth) { layoutPart.getBoxConstraints().setWidth(newWidth); notifyListeners(); } public void setConstraintHeight(@Nonnull final SizeValue newHeight) { layoutPart.getBoxConstraints().setHeight(newHeight); notifyListeners(); } @Nonnull public SizeValue getConstraintX() { return layoutPart.getBoxConstraints().getX(); } @Nonnull public SizeValue getConstraintY() { return layoutPart.getBoxConstraints().getY(); } @Nonnull public SizeValue getConstraintWidth() { return layoutPart.getBoxConstraints().getWidth(); } @Nonnull public SizeValue getConstraintHeight() { return layoutPart.getBoxConstraints().getHeight(); } public void setConstraintHorizontalAlign(@Nonnull final HorizontalAlign newHorizontalAlign) { layoutPart.getBoxConstraints().setHorizontalAlign(newHorizontalAlign); } public void setConstraintVerticalAlign(@Nonnull final VerticalAlign newVerticalAlign) { layoutPart.getBoxConstraints().setVerticalAlign(newVerticalAlign); } @Nonnull public HorizontalAlign getConstraintHorizontalAlign() { return layoutPart.getBoxConstraints().getHorizontalAlign(); } @Nonnull public VerticalAlign getConstraintVerticalAlign() { return layoutPart.getBoxConstraints().getVerticalAlign(); } public void registerEffect( @Nonnull final EffectEventId theId, @Nonnull final Effect e) { log.fine("[" + id + "] register: " + theId.toString() + "(" + e.getStateString() + ")"); effectManager.registerEffect(theId, e); } public void startEffect(@Nonnull final EffectEventId effectEventId) { startEffect(effectEventId, null); } public void startEffect(@Nonnull final EffectEventId effectEventId, @Nullable final EndNotify effectEndNotify) { startEffect(effectEventId, effectEndNotify, null); } public void startEffect( @Nonnull final EffectEventId effectEventId, @Nullable final EndNotify effectEndNotify, @Nullable final String customKey) { startEffectDoIt(effectEventId, effectEndNotify, customKey, true); } public void startEffectWithoutChildren(@Nonnull final EffectEventId effectEventId) { startEffectWithoutChildren(effectEventId, null); } public void startEffectWithoutChildren( @Nonnull final EffectEventId effectEventId, @Nullable final EndNotify effectEndNotify) { startEffectWithoutChildren(effectEventId, effectEndNotify, null); } public void startEffectWithoutChildren( @Nonnull final EffectEventId effectEventId, @Nullable final EndNotify effectEndNotify, @Nullable final String customKey) { startEffectDoIt(effectEventId, effectEndNotify, customKey, false); } private void startEffectDoIt( @Nonnull final EffectEventId effectEventId, @Nullable final EndNotify effectEndNotify, @Nullable final String customKey, final boolean withChildren) { if (effectEventId == EffectEventId.onStartScreen) { if (!visible) { return; } done = false; interactionBlocked = true; } if (effectEventId == EffectEventId.onEndScreen) { if (!visible && (effectEndNotify != null)) { // it doesn't make sense to start the onEndScreen effect when the element is hidden // just call the effectEndNotify directly and quit effectEndNotify.perform(); return; } done = true; interactionBlocked = true; } // whenever the effect ends we forward to this event // that checks first, if all child elements are finished // and when yes forwards to the actual effectEndNotify event. // // this way we ensure that all child finished the effects // before forwarding this to the real event handler. // // little bit tricky though :/ LocalEndNotify forwardToSelf = new LocalEndNotify(effectEventId, effectEndNotify); // start the effect for our self effectManager.startEffect(effectEventId, this, time, forwardToSelf, customKey); // notify all child elements of the start effect if (withChildren && children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.startEffectInternal(effectEventId, forwardToSelf, customKey); } } if (effectEventId == EffectEventId.onFocus) { if (attachedInputControl != null) { attachedInputControl.onFocus(true); } } // just in case there was no effect activated, we'll check here, if we're already done forwardToSelf.perform(); } private void startEffectInternal( @Nonnull final EffectEventId effectEventId, @Nullable final EndNotify effectEndNotify, @Nullable final String customKey) { if (effectEventId == EffectEventId.onStartScreen) { if (!visible) { return; } done = false; interactionBlocked = true; } if (effectEventId == EffectEventId.onEndScreen) { if (!visible) { return; } done = true; interactionBlocked = true; } // whenever the effect ends we forward to this event // that checks first, if all child elements are finished // and when yes forwards to the actual effectEndNotify event. // // this way we ensure that all child finished the effects // before forwarding this to the real event handler. // // little bit tricky though :/ LocalEndNotify forwardToSelf = new LocalEndNotify(effectEventId, effectEndNotify); // start the effect for our self effectManager.startEffect(effectEventId, this, time, forwardToSelf, customKey); // notify all child elements of the start effect if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.startEffectInternal(effectEventId, forwardToSelf, customKey); } } if (effectEventId == EffectEventId.onFocus) { if (attachedInputControl != null) { attachedInputControl.onFocus(true); } } } public void stopEffect(@Nonnull final EffectEventId effectEventId) { stopEffectInternal(effectEventId, true); } public void stopEffectWithoutChildren(@Nonnull final EffectEventId effectEventId) { stopEffectInternal(effectEventId, false); } private void stopEffectInternal(@Nonnull final EffectEventId effectEventId, final boolean withChildren) { if (EffectEventId.onStartScreen == effectEventId || EffectEventId.onEndScreen == effectEventId) { interactionBlocked = false; if (!visible) { return; } } effectManager.stopEffect(effectEventId); // notify all child elements of the start effect if (withChildren && children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.stopEffect(effectEventId); } } if (effectEventId == EffectEventId.onFocus) { if (attachedInputControl != null) { attachedInputControl.onFocus(false); } } } /** * Checks if a certain effect is still active in this element or any of its children. * * @return true if the effect has ended and false otherwise */ public boolean isEffectActive(@Nonnull final EffectEventId effectEventId) { return effectStateCache.get(effectEventId); } public void enable() { if (enabled) { return; } enableInternal(); } private void enableInternal() { enabledCount++; if (enabledCount == 0) { enabled = true; enableEffect(); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { children.get(i).enableInternal(); } } } else { if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { children.get(i).enableInternal(); } } } } void enableEffect() { stopEffectWithoutChildren(EffectEventId.onDisabled); startEffectWithoutChildren(EffectEventId.onEnabled); if (id != null) { nifty.publishEvent(id, new ElementEnableEvent(this)); } } public void disable() { if (!enabled) { return; } disableInternal(); } private void disableInternal() { enabledCount--; if (enabledCount == -1) { enabled = false; disableFocus(); disableEffect(); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { children.get(i).disableInternal(); } } } else { if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { children.get(i).disableInternal(); } } } } public void disableFocus() { if (focusHandler.getKeyboardFocusElement() == this) { Element prevElement = focusHandler.getNext(this); prevElement.setFocus(); } focusHandler.lostKeyboardFocus(this); focusHandler.lostMouseFocus(this); } void disableEffect() { stopEffectWithoutChildren(EffectEventId.onHover); stopEffectWithoutChildren(EffectEventId.onStartHover); stopEffectWithoutChildren(EffectEventId.onEndHover); stopEffectWithoutChildren(EffectEventId.onEnabled); startEffectWithoutChildren(EffectEventId.onDisabled); if (id != null) { nifty.publishEvent(id, new ElementDisableEvent(this)); } } public boolean isEnabled() { return enabled; } public void show() { show(null); } public void show(@Nullable final EndNotify perform) { // don't show if show is still in progress if (isEffectActive(EffectEventId.onShow)) { return; } // stop any onHide effects when a new onShow effect is about to be started if (isEffectActive(EffectEventId.onHide)) { resetSingleEffect(EffectEventId.onHide); } // show internalShow(); startEffect(EffectEventId.onShow, perform); } private void internalShow() { visible = true; effectManager.restoreForShow(); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element element = children.get(i); element.internalShow(); } } if (id != null) { nifty.publishEvent(id, new ElementShowEvent(this)); } } public void setVisible(final boolean visibleParam) { if (visibleParam) { show(); } else { hide(); } } public void hide() { hide(null); } public void hide(@Nullable final EndNotify perform) { // don't hide if not visible if (!isVisible()) { return; } // don't hide if hide is still in progress if (isEffectActive(EffectEventId.onHide)) { return; } // stop any onShow effects when a new onHide effect is about to be started if (isEffectActive(EffectEventId.onShow)) { resetSingleEffect(EffectEventId.onShow); } // start effect and shizzle startEffect(EffectEventId.onHide, new EndNotify() { @Override public void perform() { resetForHide(); internalHide(); if (perform != null) { perform.perform(); } } }); } public void showWithoutEffects() { internalShow(); } public void hideWithoutEffect() { // don't hide if not visible if (!isVisible()) { return; } resetEffects(); internalHide(); } private void internalHide() { visible = false; disableFocus(); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element element = children.get(i); element.internalHide(); } } if (id != null) { nifty.publishEvent(id, new ElementHideEvent(this)); } } public boolean isVisible() { return visible; } public void setHotSpotFalloff(@Nullable final Falloff newFalloff) { effectManager.setFalloff(newFalloff); } @Nullable public Falloff getFalloff() { return effectManager.getFalloff(); } public boolean canHandleMouseEvents() { if (isEffectActive(EffectEventId.onStartScreen)) { return false; } if (isEffectActive(EffectEventId.onEndScreen)) { return false; } if (!visible) { return false; } if (done) { return false; } if (!visibleToMouseEvents) { return false; } if (!focusHandler.canProcessMouseEvents(this)) { return false; } if (interactionBlocked) { return false; } if (!enabled) { return false; } if (isIgnoreMouseEvents()) { return false; } return true; } /** * This is a special version of canHandleMouseEvents() that will return true if this element is able to process * mouse events in general. This method will return true even when the element is temporarily not able to handle * events because onStartScreen or onEndScreen effects are active. * * @return true can handle mouse events, false can't handle them */ boolean canTheoreticallyHandleMouseEvents() { if (!visible) { return false; } if (done) { return false; } if (!visibleToMouseEvents) { return false; } if (!focusHandler.canProcessMouseEvents(this)) { return false; } if (!enabled) { return false; } if (isIgnoreMouseEvents()) { return false; } return true; } /** * This should check if the mouse event is inside the current element and if it is * forward the event to it's child. The purpose of this is to build a list of all * elements from front to back that are available for a certain mouse position. */ public void buildMouseOverElements( @Nonnull final NiftyMouseInputEvent mouseEvent, final long eventTime, @Nonnull final MouseOverHandler mouseOverHandler) { boolean isInside = isInside(mouseEvent); if (canHandleMouseEvents()) { if (isInside) { mouseOverHandler.addMouseOverElement(this); } else { mouseOverHandler.addMouseElement(this); } } else if (canTheoreticallyHandleMouseEvents()) { if (isInside) { mouseOverHandler.canTheoreticallyHandleMouse(this); } } if (visible) { if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.buildMouseOverElements(mouseEvent, eventTime, mouseOverHandler); } } } } public void mouseEventHoverPreprocess(@Nonnull final NiftyMouseInputEvent mouseEvent, final long eventTime) { effectManager.handleHoverDeactivate(this, mouseEvent.getMouseX(), mouseEvent.getMouseY()); } public boolean mouseEvent(@Nonnull final NiftyMouseInputEvent mouseEvent, final long eventTime) { mouseEventHover(mouseEvent); return interaction.process(mouseEvent, eventTime, isInside(mouseEvent), canHandleInteraction(), focusHandler.hasExclusiveMouseFocus(this)); } private void mouseEventHover(@Nonnull final NiftyMouseInputEvent mouseEvent) { effectManager.handleHover(this, mouseEvent.getMouseX(), mouseEvent.getMouseY()); effectManager.handleHoverStartAndEnd(this, mouseEvent.getMouseX(), mouseEvent.getMouseY()); } /** * Handles the MouseOverEvent. Must not call child elements. This is handled by the caller. * * @return true the mouse event has been consumed and false when the mouse event can be processed further down */ public boolean mouseOverEvent(@Nonnull final NiftyMouseInputEvent mouseEvent, final long eventTime) { boolean isMouseEventConsumed = false; if (interaction.onMouseOver(this, mouseEvent)) { isMouseEventConsumed = true; } if ((mouseEvent.getMouseWheel() != 0) && interaction.onMouseWheel(this, mouseEvent)) { isMouseEventConsumed = true; } return isMouseEventConsumed; } /** * Checks to see if the given mouse position is inside of this element. */ private boolean isInside(@Nonnull final NiftyMouseInputEvent inputEvent) { return isMouseInsideElement(inputEvent.getMouseX(), inputEvent.getMouseY()); } public boolean isMouseInsideElement(final int mouseX, final int mouseY) { if (parentClipArea) { // must be inside the parent to continue if (isInsideParentClipArea(mouseX, mouseY)) { return mouseX >= getX() && mouseX <= (getX() + getWidth()) && mouseY > (getY()) && mouseY < (getY() + getHeight()); } else { return false; } } else { return mouseX >= getX() && mouseX <= (getX() + getWidth()) && mouseY > (getY()) && mouseY < (getY() + getHeight()); } } private boolean isInsideParentClipArea(final int mouseX, final int mouseY) { return mouseX >= parentClipX && mouseX <= (parentClipX + parentClipWidth) && mouseY > (parentClipY) && mouseY < (parentClipY + parentClipHeight); } public void onClick() { if (canHandleInteraction()) { interaction.activate(nifty); } } private boolean canHandleInteraction() { if (screen == null || !enabled) { return false; } return !screen.isEffectActive(EffectEventId.onStartScreen) && !screen.isEffectActive(EffectEventId.onEndScreen); } /** * @param name the name (id) of the element * @return the element or null if an element with the specified name cannot be found * @deprecated Please use {@link #findElementById(String)}. */ @Nullable @Deprecated public Element findElementByName(final String name) { return findElementById(name); } /** * @return the element or null if an element with the specified id cannot be found */ @Nullable public Element findElementById(@Nullable final String findId) { if (findId == null) { return null; } if (id != null && id.equals(findId)) { return this; } if (childIdMatch(findId, id)) { return this; } if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element e = children.get(i); Element found = e.findElementById(findId); if (found != null) { return found; } } } return null; } private boolean childIdMatch(@Nonnull final String name, @Nullable final String id) { if (name.startsWith("#")) { if (id != null && id.endsWith(name)) { return true; } } return false; } public void setOnClickAlternateKey(final String newAlternateKey) { interaction.setAlternateKey(newAlternateKey); } public void setAlternateKey(@Nullable final String alternateKey) { effectManager.setAlternateKey(alternateKey); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element e = children.get(i); e.setAlternateKey(alternateKey); } } } @Nonnull public EffectManager getEffectManager() { return effectManager; } public void setEffectManager(@Nonnull final EffectManager effectManagerParam) { effectManager = effectManagerParam; } private void bindToScreen(@Nonnull final Screen newScreen) { screen = newScreen; if (id != null) { screen.registerElementId(id); } } private void bindToFocusHandler(final boolean isPopup) { if (!focusable) { return; } if (hasAncestorPopup() && !isPopup) { return; } if (screen == null) { log.severe("Trying to bind element [" + String.valueOf(getId()) + "] to focus handler while screen is not " + "bound."); } else { focusHandler.addElement(this, screen.findElementById(focusableInsertBeforeElementId)); } } private boolean hasAncestorPopup() { return findAncestorPopupElement() != null; } @Nullable private Element findAncestorPopupElement() { if (elementType instanceof PopupType) { return this; } if (parent == null) { return null; } return parent.findAncestorPopupElement(); } public void onStartScreen() { onStartScreenSubscribeControllerAnnotations(); onStartScreenInternal(); } private void onStartScreenSubscribeControllerAnnotations() { if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element e = children.get(i); e.onStartScreenSubscribeControllerAnnotations(); } } if (attachedInputControl != null) { nifty.subscribeAnnotations(attachedInputControl.getController()); } } private void onStartScreenInternal() { if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element e = children.get(i); e.onStartScreenInternal(); } } if (screen == null) { log.severe("Internal start of screen called, but no screen is bound to the element [" + String.valueOf(getId()) + "]"); } else { if (attachedInputControl != null) { attachedInputControl.onStartScreen(nifty, screen); } } } /** * Gets this element's renderer matching the specified class. * * @param <T> the {@link de.lessvoid.nifty.elements.render.ElementRenderer} type to check for * @param requestedRendererClass the {@link de.lessvoid.nifty.elements.render.ElementRenderer} class to check for * @return the {@link de.lessvoid.nifty.elements.render.ElementRenderer} that matches the specified class, or null if * there is no matching renderer */ @Nullable public <T extends ElementRenderer> T getRenderer(@Nonnull final Class<T> requestedRendererClass) { for (int i = 0; i < elementRenderer.length; i++) { ElementRenderer renderer = elementRenderer[i]; if (requestedRendererClass.isInstance(renderer)) { return requestedRendererClass.cast(renderer); } } return null; } public void setVisibleToMouseEvents(final boolean newVisibleToMouseEvents) { this.visibleToMouseEvents = newVisibleToMouseEvents; } public boolean keyEvent(@Nonnull final KeyboardInputEvent inputEvent) { if (attachedInputControl != null && id != null) { return attachedInputControl.keyEvent(nifty, inputEvent, id); } return false; } public void setClipChildren(final boolean clipChildrenParam) { this.clipChildren = clipChildrenParam; } public boolean isClipChildren() { return this.clipChildren; } public void setRenderOrder(final int renderOrder) { this.renderOrder = renderOrder; if (parent != null) { parent.renderOrderChanged(this); } } private void renderOrderChanged(@Nonnull final Element element) { if (elementsRenderOrderSet == null) { log.warning("Can't report a changed order, parent doesn't seem to have children?! O.o"); return; } Iterator<Element> childItr = elementsRenderOrderSet.iterator(); boolean foundOldEntry = false; while (childItr.hasNext()) { Element checkElement = childItr.next(); if (checkElement.equals(element)) { childItr.remove(); foundOldEntry = true; break; } } if (foundOldEntry) { elementsRenderOrderSet.add(element); if (elementsRenderOrder == null || elementsRenderOrder.length != elementsRenderOrderSet.size()) { elementsRenderOrder = new Element[elementsRenderOrderSet.size()]; } elementsRenderOrder = elementsRenderOrderSet.toArray(elementsRenderOrder); } else { log.warning("Failed to locate the element with changed id in the render set."); } } public int getRenderOrder() { return renderOrder; } /** * Attempts to set the focus to this element. */ public void setFocus() { if (nifty.getCurrentScreen() != null) { if (isFocusable()) { focusHandler.setKeyFocus(this); } } } public void attachInputControl(final NiftyInputControl newInputControl) { attachedInputControl = newInputControl; } private boolean hasParentActiveOnStartOrOnEndScreenEffect() { if (parent != null) { return parent.effectManager.isActive(EffectEventId.onStartScreen) || parent.effectManager.isActive(EffectEventId.onEndScreen) || parent.hasParentActiveOnStartOrOnEndScreenEffect(); } return false; } private void resetInteractionBlocked() { interactionBlocked = false; if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element child = children.get(i); child.resetInteractionBlocked(); } } } /** * @author void */ public class LocalEndNotify implements EndNotify { @Nonnull private final EffectEventId effectEventId; @Nullable private final EndNotify effectEndNotify; public LocalEndNotify( @Nonnull final EffectEventId effectEventIdParam, @Nullable final EndNotify effectEndNotifyParam) { effectEventId = effectEventIdParam; effectEndNotify = effectEndNotifyParam; } @Override public void perform() { if (effectEventId.equals(EffectEventId.onStartScreen) || effectEventId.equals(EffectEventId.onEndScreen)) { if (interactionBlocked && !hasParentActiveOnStartOrOnEndScreenEffect() && !isEffectActive(effectEventId)) { resetInteractionBlocked(); } } // notify parent if: // a) the effect is done for our self // b) the effect is done for all of our children if (!isEffectActive(effectEventId)) { // all fine. we can notify the actual event handler if (effectEndNotify != null) { effectEndNotify.perform(); } } } } public void setId(@Nullable final String id) { @Nullable String oldId = this.id; this.id = id; if (parent == null) { return; } if (oldId == null && id == null) { return; } if ((oldId != null && oldId.equals(id)) || (id != null && id.equals(oldId))) { return; } /* So the ID changed and we got a parent. This means the render order set is likely to be corrupted now. We need to update it to ensure that everything is still working properly. */ parent.renderOrderChanged(this); } @Nonnull public ElementType getElementType() { return elementType; } @Nonnull public ElementRenderer[] getElementRenderer() { return elementRenderer; } public void setFocusable(final boolean isFocusable) { this.focusable = isFocusable; if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element child = children.get(i); child.setFocusable(isFocusable); } } } @Nullable public NiftyInputControl getAttachedInputControl() { return attachedInputControl; } public void bindControls(@Nonnull final Screen target) { if (screen == target) { return; } bindToScreen(target); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element child = children.get(i); child.bindControls(target); } } if (attachedInputControl != null) { attachedInputControl.bindControl(nifty, target, this, elementType.getAttributes()); } } public void initControls(final boolean isPopup) { if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element child = children.get(i); child.initControls(isPopup); } } if (attachedInputControl != null) { attachedInputControl.initControl(elementType.getAttributes()); } bindToFocusHandler(isPopup); } /** * Removes this element and all of its children from the focusHandler. */ public void removeFromFocusHandler() { focusHandler.remove(this); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element child = children.get(i); child.removeFromFocusHandler(); } } } @Nonnull public FocusHandler getFocusHandler() { return focusHandler; } public void setStyle(@Nonnull final String newStyle) { final String oldStyle = getStyle(); if (oldStyle != null) { removeStyle(oldStyle); } elementType.getAttributes().set("style", newStyle); elementType.applyStyles(nifty.getDefaultStyleResolver()); if (screen == null) { log.warning("Can't properly apply style as long as the element is not bound to a screen."); } else { elementType.applyAttributes(screen, this, elementType.getAttributes(), nifty.getRenderEngine()); elementType.applyEffects(nifty, screen, this); elementType.applyInteract(nifty, screen, this); } log.fine("after setStyle [" + newStyle + "]\n" + elementType.output(0)); notifyListeners(); } @Nullable public String getStyle() { return elementType.getAttributes().get("style"); } void removeStyle(@Nonnull final String style) { log.fine("before removeStyle [" + style + "]\n" + elementType.output(0)); elementType.removeWithTag(style); effectManager.removeAllEffects(); log.fine("after removeStyle [" + style + "]\n" + elementType.output(0)); notifyListeners(); } /** * Adds an additional input handler to this element and its children. * * @param handler additional handler */ public void addInputHandler(@Nonnull final KeyInputHandler handler) { if (attachedInputControl != null) { attachedInputControl.addInputHandler(handler); } if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element child = children.get(i); child.addInputHandler(handler); } } } /** * Adds an additional input handler to this element and its children. * * @param handler additional handler */ public void addPreInputHandler(@Nonnull final KeyInputHandler handler) { if (attachedInputControl != null) { attachedInputControl.addPreInputHandler(handler); } if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element child = children.get(i); child.addPreInputHandler(handler); } } } @Nullable public <T extends Controller> T findControl( @Nonnull final String elementName, @Nonnull final Class<T> requestedControlClass) { Element element = findElementById(elementName); if (element == null) { return null; } return element.getControl(requestedControlClass); } @Nullable public <T extends NiftyControl> T findNiftyControl( @Nonnull final String elementName, @Nonnull final Class<T> requestedControlClass) { Element element = findElementById(elementName); if (element == null) { return null; } return element.getNiftyControl(requestedControlClass); } @Nullable public <T extends Controller> T getControl(@Nonnull final Class<T> requestedControlClass) { if (attachedInputControl != null) { T t = attachedInputControl.getControl(requestedControlClass); if (t != null) { return t; } } if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element child = children.get(i); T t = child.getControl(requestedControlClass); if (t != null) { return t; } } } return null; } @Nullable public <T extends NiftyControl> T getNiftyControl(@Nonnull final Class<T> requestedControlClass) { if (attachedInputControl != null) { T t = attachedInputControl.getNiftyControl(requestedControlClass); if (t != null) { return t; } } if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element child = children.get(i); T t = child.getNiftyControl(requestedControlClass); if (t != null) { return t; } } } log.warning("missing element/control with id [" + id + "] for requested control class [" + requestedControlClass.getName() + "]"); return null; } public boolean isFocusable() { return focusable && enabled && visible && hasVisibleParent() && !isIgnoreKeyboardEvents(); } private boolean hasVisibleParent() { if (parent != null) { return parent.visible && parent.hasVisibleParent(); } return true; } public void setOnMouseOverMethod(@Nullable final NiftyMethodInvoker onMouseOverMethod) { interaction.setOnMouseOver(onMouseOverMethod); } @Nonnull public LayoutPart getLayoutPart() { return layoutPart; } public boolean isVisibleToMouseEvents() { return visibleToMouseEvents; } @Nonnull public SizeValue getPaddingLeft() { return layoutPart.getBoxConstraints().getPaddingLeft(); } @Nonnull public SizeValue getPaddingRight() { return layoutPart.getBoxConstraints().getPaddingRight(); } @Nonnull public SizeValue getPaddingTop() { return layoutPart.getBoxConstraints().getPaddingTop(); } @Nonnull public SizeValue getPaddingBottom() { return layoutPart.getBoxConstraints().getPaddingBottom(); } @Nonnull public SizeValue getMarginLeft() { return layoutPart.getBoxConstraints().getMarginLeft(); } @Nonnull public SizeValue getMarginRight() { return layoutPart.getBoxConstraints().getMarginRight(); } @Nonnull public SizeValue getMarginTop() { return layoutPart.getBoxConstraints().getMarginTop(); } @Nonnull public SizeValue getMarginBottom() { return layoutPart.getBoxConstraints().getMarginBottom(); } public void setPaddingLeft(@Nonnull final SizeValue paddingValue) { layoutPart.getBoxConstraints().setPaddingLeft(paddingValue); notifyListeners(); } public void setPaddingRight(@Nonnull final SizeValue paddingValue) { layoutPart.getBoxConstraints().setPaddingRight(paddingValue); notifyListeners(); } public void setPaddingTop(@Nonnull final SizeValue paddingValue) { layoutPart.getBoxConstraints().setPaddingTop(paddingValue); notifyListeners(); } public void setPaddingBottom(@Nonnull final SizeValue paddingValue) { layoutPart.getBoxConstraints().setPaddingBottom(paddingValue); notifyListeners(); } public void setMarginLeft(@Nonnull final SizeValue value) { layoutPart.getBoxConstraints().setMarginLeft(value); notifyListeners(); } public void setMarginRight(@Nonnull final SizeValue value) { layoutPart.getBoxConstraints().setMarginRight(value); notifyListeners(); } public void setMarginTop(@Nonnull final SizeValue value) { layoutPart.getBoxConstraints().setMarginTop(value); notifyListeners(); } public void setMarginBottom(@Nonnull final SizeValue value) { layoutPart.getBoxConstraints().setMarginBottom(value); notifyListeners(); } @Override @Nonnull public String toString() { return id + " (" + super.toString() + ")"; } public boolean isStarted() { return isEffectActive(EffectEventId.onStartScreen); } public void markForRemoval() { markForRemoval(null); } public void markForRemoval(@Nullable final EndNotify endNotify) { if (screen == null) { log.warning("Marking the element [" + String.valueOf(getId()) + "] for removal is not possible when there is " + "not screen bound."); } else { nifty.removeElement(screen, this, endNotify); } } public void markForMove(@Nonnull final Element destination) { markForMove(destination, null); } public void markForMove(@Nonnull final Element destination, @Nullable final EndNotify endNotify) { if (screen == null) { log.warning("Marking the element [" + String.valueOf(getId()) + "] for moving is not possible when there is not" + " screen bound."); } else { nifty.moveElement(screen, this, destination, endNotify); } } public void reactivate() { done = false; if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { children.get(i).reactivate(); } } } private void notifyListeners() { if (id != null) { nifty.publishEvent(id, this); } } @Nonnull public Nifty getNifty() { return nifty; } @Nonnull public <T extends EffectImpl> List<Effect> getEffects( @Nonnull final EffectEventId effectEventId, @Nonnull final Class<T> requestedClass) { return effectManager.getEffects(effectEventId, requestedClass); } public void onEndScreen(@Nonnull final Screen screen) { if (id != null) { screen.unregisterElementId(id); nifty.unsubscribeElement(screen, id); } if (attachedInputControl != null) { attachedInputControl.onEndScreen(nifty, screen, id); } if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { children.get(i).onEndScreen(screen); } } } @Nonnull public ElementInteraction getElementInteraction() { return interaction; } public void setIgnoreMouseEvents(final boolean newValue) { ignoreMouseEvents = newValue; if (newValue) { focusHandler.lostMouseFocus(this); } } public boolean isIgnoreMouseEvents() { return ignoreMouseEvents; } public void setIgnoreKeyboardEvents(final boolean newValue) { ignoreKeyboardEvents = newValue; if (newValue) { focusHandler.lostKeyboardFocus(this); } } public boolean isIgnoreKeyboardEvents() { return ignoreKeyboardEvents; } @Override public void effectStateChanged(@Nonnull final EffectEventId eventId, final boolean active) { // Get the oldState first. boolean oldState = effectStateCache.get(eventId); // The given EffectEventId changed its state. This means we now must update // the ElementEffectStartedCache for this element. We do this by recalculating // our state taking the state of all child elements into account. boolean newState = isEffectActiveRecalc(eventId); // When our state has been changed due to the update we will update the cache // and tell our parent element to update as well. if (newState != oldState) { effectStateCache.set(eventId, newState); if (parent != null) { parent.effectStateChanged(eventId, newState); } } } private boolean isEffectActiveRecalc(@Nonnull final EffectEventId eventId) { if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); if (w.isEffectActiveRecalc(eventId)) { return true; } } } return effectManager.isActive(eventId); } // package private to prevent public access void internalRemoveElement(@Nonnull final Element element) { if (elementsRenderOrderSet != null && children != null) { // so now that's odd: we need to remove the element first from the // elementsRenderOrder and THEN from the elements list. this is because // the elementsRenderOrder comparator uses the index of the element in // the elements list >_< // // the main issue here is of course the splitted data structure. something // we need to address in 1.4 or 2.0. elementsRenderOrderSet.remove(element); // now that the element has been removed from the elementsRenderOrder set // we can remove it from the elements list as well. children.remove(element); if (children.isEmpty()) { elementsRenderOrderSet = null; children = null; } else if (children.size() != elementsRenderOrderSet.size()) { log.severe("Problem at removing a element. RenderOrderSet and children list don't have the same size " + "anymore. Rebuilding the render order set."); elementsRenderOrderSet.clear(); elementsRenderOrderSet.addAll(children); } } if (elementsRenderOrderSet != null) { elementsRenderOrder = elementsRenderOrderSet.toArray(new Element[elementsRenderOrderSet.size()]); } else { elementsRenderOrder = null; } } // package private to prevent public access void internalRemoveElementWithChildren() { if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { children.get(i).internalRemoveElementWithChildren(); } } elementsRenderOrderSet = null; children = null; elementsRenderOrder = null; } /** * Sets custom user data for this element. * * @param key the key for the object to set */ public void setUserData(@Nonnull final String key, @Nullable final Object data) { if (data == null) { if (userData != null) { userData.remove(key); if (userData.isEmpty()) { userData = null; } } } else { if (userData == null) { userData = new HashMap<String, Object>(); } userData.put(key, data); } } /** * Gets custom user data set with {@link #setUserData(String, Object)} by key */ @Nullable @SuppressWarnings("unchecked") public <T> T getUserData(@Nonnull final String key) { if (userData == null) { return null; } return (T) userData.get(key); } /** * Gets all custom user data keys set with {@link #setUserData(String, Object)} */ @Nonnull public Set<String> getUserDataKeys() { if (userData != null) { return userData.keySet(); } return Collections.emptySet(); } /** * This uses the renderOrder attribute of the elements to compare them. If the renderOrder * attribute is not set (is 0) then the index of the element in the elements list is used * as the renderOrder value. This is done to keep the original sort order of the elements for * rendering. The value is not cached and is directly recalculated using the element index in * the list. The child count for an element is usually low (< 10) and the comparator is only * executed when the child elements change. So this lookup shouldn't hurt performance too much. * <p/> * If you change the default value of renderOrder then your value is being used. So if you set it * to some high value (> 1000 to be save) this element is rendered after all the other elements. * If you set it to some very low value (< -1000 to be save) then this element is rendered before * all the others. */ private static final class RenderOrderComparator implements Comparator<Element> { @Override public int compare(@Nonnull final Element o1, @Nonnull final Element o2) { int o1RenderOrder = getRenderOrder(o1); int o2RenderOrder = getRenderOrder(o2); if (o1RenderOrder < o2RenderOrder) { return -1; } else if (o1RenderOrder > o2RenderOrder) { return 1; } // this means the renderOrder values are equal. since this is a set // we can't return 0 because this would mean (for the set) that the // elements are equal and one of the values will be removed. so here // we simply compare the String representation of the elements so that // we keep a fixed sort order. String o1Id = o1.id; String o2Id = o2.id; if (o1Id == null && o2Id != null) { return -1; } else if (o1Id != null && o2Id == null) { return 1; } else if (o1Id != null) { int idCompareResult = o1Id.compareTo(o2Id); if (idCompareResult != 0) { return idCompareResult; } } // ids equal or both null use super.toString() // hashCode() should return a value thats different for both elements since // adding the same element twice to the same parent element is not supported. return Integer.valueOf(o1.hashCode()).compareTo(Integer.valueOf(o2.hashCode())); } private int getRenderOrder(@Nonnull final Element element) { if (element.renderOrder != 0) { return element.renderOrder; } return element.getChildren().indexOf(element); } } // We don't want to give up Java 1.6 compatibility right now. @SuppressWarnings("unchecked") @Nonnull private static <T> Iterator<T> emptyIterator() { return (Iterator<T>) EmptyIterator.EMPTY_ITERATOR; } private static class EmptyIterator<E> implements Iterator<E> { static final EmptyIterator<Object> EMPTY_ITERATOR = new EmptyIterator<Object>(); @Override public boolean hasNext() { return false; } @Override @Nonnull public E next() { throw new NoSuchElementException(); } @Override public void remove() { throw new IllegalStateException(); } } }
false
false
null
null
diff --git a/src/com/hstefan/aunctiondroid/ProfileActivity.java b/src/com/hstefan/aunctiondroid/ProfileActivity.java index 2d76d33..7156984 100644 --- a/src/com/hstefan/aunctiondroid/ProfileActivity.java +++ b/src/com/hstefan/aunctiondroid/ProfileActivity.java @@ -1,185 +1,185 @@ package com.hstefan.aunctiondroid; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import com.hstefan.aunctiondroid.db.DbHelper; import com.hstefan.aunctiondroid.db.entities.User; public class ProfileActivity extends Activity { SQLiteDatabase myDb; long id_item; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); id_item = 0; setContentView(R.layout.profile); Log.i("Session started:", User.getActive().getEmail() + ":" + User.getActive().getPass()); myDb = AunctionDroidActivity.getHelper().getWritableDatabase(); setListners(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_item_row, menu); return true; } @Override protected void onResume() { super.onResume(); Log.i("Profile", "Resumed"); TextView tv = (TextView)findViewById(R.id.funds_label_id); tv.setText("Balance: " + Integer.toString(User.getActive().getMoney())); setListAdapter(); } private void setListAdapter() { StringBuilder str_builder = new StringBuilder("SELECT "); str_builder.append(DbHelper.ITEM_TABLE); str_builder.append(".id as _id,"); str_builder.append(DbHelper.ITEM_TABLE + ".name"); str_builder.append(" FROM "); str_builder.append(DbHelper.ITEM_TABLE + ","); str_builder.append(DbHelper.USER_TABLE + ","); str_builder.append(DbHelper.USER_ITEM_TABLE); str_builder.append(" WHERE "); str_builder.append("(" + DbHelper.ITEM_TABLE + ".id = "); str_builder.append(DbHelper.USER_ITEM_TABLE + ".id_item" + ")" + " AND"); str_builder.append(" (" + DbHelper.USER_ITEM_TABLE + ".id_user = "); str_builder.append(DbHelper.USER_TABLE + ".id)"); Cursor cursor = myDb.rawQuery(str_builder.toString(), null); System.out.println(cursor.toString()); SimpleCursorAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.item_row, cursor, new String[] {"name"}, new int[] {R.id.item_name}); ListView list = (ListView)findViewById(R.id.profile_items_list_id); if(list != null) list.setAdapter(adapter); else Log.d("Adapter", "failed to atach"); //Now Playing: Metallica - Fade To Black - Ride The Lightning - 1984 - Rock - MP3 - 320 kbps - 6:57 min Log.d("Rows resulted in query", Long.toString(cursor.getCount())); } private void setListners() { Button reg_button = (Button)findViewById(R.id.register_button_id); reg_button.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(ProfileActivity.this, RegisterItemActivity.class); startActivity(intent); } }); Button buy_button = (Button)findViewById(R.id.buy_button_id); buy_button.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(ProfileActivity.this, ViewAunctionsActivity.class); startActivity(intent); } }); ListView list_view = (ListView)findViewById(R.id.profile_items_list_id); list_view.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(final AdapterView<?> adapter, View v, final int pos, long id) { final CharSequence[] items = {"Delete", "Sell"}; AlertDialog.Builder builder = new AlertDialog.Builder(ProfileActivity.this); - builder.setTitle("Pick a color"); + builder.setTitle("Lolwat"); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if(item == 0) { onItemDeletion(adapter, pos); } else if(item == 1) { onItemSell(adapter, pos); } } }); AlertDialog alert = builder.create(); alert.show(); } }); } private void onItemDeletion(AdapterView<?> adapter, int pos) { long id = adapter.getItemIdAtPosition(pos); System.out.println("IDDDDDDDDDDDDD " + Long.toString(id)); myDb.delete(DbHelper.ITEM_TABLE, "id=?", new String[]{Long.toString(id)}); myDb.delete(DbHelper.USER_ITEM_TABLE, "id_item=?", new String[]{Long.toString(id)}); setListAdapter(); } @Override protected Dialog onCreateDialog(int id) { final Dialog dialog = new Dialog(this); switch(id) { case 0: dialog.setContentView(R.layout.create_auction); dialog.setTitle("Create aunction"); Button confirm = (Button)dialog.findViewById(R.id.create_aunction_confirm_button); confirm.setOnClickListener(new OnClickListener() { public void onClick(View v) { createAunction(v, dialog.findViewById(R.id.price_edittext)); dismissDialog(0); } }); Button nevermind = (Button)dialog.findViewById(R.id.cancel_aunction); nevermind.setOnClickListener(new OnClickListener() { public void onClick(View v) { ProfileActivity.this.dismissDialog(0); } }); return dialog; } return null; } protected void createAunction(View v, View view) { ContentValues cv = new ContentValues(); cv.put("id_user", User.getActive().getId()); cv.put("id_item", id_item); EditText p_text = (EditText)view.findViewById(R.id.price_edittext); cv.put("price", p_text.getEditableText().toString()); myDb.insert(DbHelper.AUNCTIONS_TABLE, null, cv); } private void onItemSell(AdapterView<?> adapter, int pos) { id_item = adapter.getItemIdAtPosition(pos); showDialog(0); } } diff --git a/src/com/hstefan/aunctiondroid/ViewAunctionsActivity.java b/src/com/hstefan/aunctiondroid/ViewAunctionsActivity.java index f1b12d9..b87ab8e 100644 --- a/src/com/hstefan/aunctiondroid/ViewAunctionsActivity.java +++ b/src/com/hstefan/aunctiondroid/ViewAunctionsActivity.java @@ -1,119 +1,120 @@ package com.hstefan.aunctiondroid; import com.hstefan.aunctiondroid.db.DbHelper; import com.hstefan.aunctiondroid.db.entities.User; import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; public class ViewAunctionsActivity extends Activity { SQLiteDatabase myDb; @Override protected void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.bidlist); myDb = AunctionDroidActivity.getHelper().getWritableDatabase(); setListners(); + setListAdapter(); } @Override protected void onResume() { super.onResume(); setListAdapter(); } private void setListAdapter() { StringBuilder str_builder = new StringBuilder("SELECT "); str_builder.append(DbHelper.ITEM_TABLE); str_builder.append(".id as _id,"); str_builder.append(DbHelper.ITEM_TABLE + ".name,"); str_builder.append(DbHelper.AUNCTIONS_TABLE + ".price"); str_builder.append(" FROM "); str_builder.append(DbHelper.ITEM_TABLE + ","); str_builder.append(DbHelper.USER_TABLE + ","); str_builder.append(DbHelper.USER_ITEM_TABLE + ","); str_builder.append(DbHelper.AUNCTIONS_TABLE); str_builder.append(" WHERE "); str_builder.append("(" + DbHelper.ITEM_TABLE + ".id = "); str_builder.append(DbHelper.USER_ITEM_TABLE + ".id_item" + ") AND "); str_builder.append("(" + DbHelper.USER_ITEM_TABLE + ".id_user = "); str_builder.append(DbHelper.USER_TABLE + ".id) AND ("); str_builder.append(DbHelper.AUNCTIONS_TABLE + ".id_user = "); str_builder.append(DbHelper.USER_TABLE + ".id) AND (" ); str_builder.append(DbHelper.AUNCTIONS_TABLE + ".id_item = "); str_builder.append(DbHelper.ITEM_TABLE + ".id)" ); //Now Playing: Rush - Marathon - Power Windows - 1985 - Classic Prog - MP3 - 320 kbps - 6:10 min Cursor cursor = myDb.rawQuery(str_builder.toString(), null); System.out.println(cursor.toString()); SimpleCursorAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.bidlist_row, cursor, new String[] {"name", "price"}, new int[] {R.id.bid_item_name_id, R.id.bid_item_price_text_id}); ListView list = (ListView)findViewById(R.id.bid_list_view); if(list != null) list.setAdapter(adapter); else Log.d("Adapter", "failed to atach"); //Now Playing: Metallica - Fade To Black - Ride The Lightning - 1984 - Rock - MP3 - 320 kbps - 6:57 min Log.d("Rows resulted in query", Long.toString(cursor.getCount())); } private void setListners() { ListView list = (ListView)findViewById(R.id.bid_list_view); list.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> adapter, View v, int pos, long id) { TextView price_v = (TextView)v.findViewById(R.id.bid_item_price_text_id); int price = Integer.parseInt(price_v.getEditableText().toString()); User u = User.getActive(); if(u.getMoney() >= price) { u.setMoney(u.getMoney() - price); ContentValues cv = new ContentValues(); cv.put("money", u.getMoney()); //atualiza o saldo do comprador myDb.update(DbHelper.AUNCTIONS_TABLE, cv, "id=?", new String[]{ Integer.toString(u.getId())}); Cursor c = myDb.query(DbHelper.AUNCTIONS_TABLE, new String[] {"id_user,id_item"}, "id_item=?", new String[]{ Long.toString(id) }, null, null, null); c.moveToFirst(); int user_id = c.getInt(0); //id do vendedor int item_id = c.getInt(1); //id_item Cursor cs = myDb.query(DbHelper.USER_TABLE, new String[] {"money"}, "id=?", new String[]{ Long.toString(user_id)}, null, null, null); cs.moveToFirst(); int money = cs.getInt(0); //saldo do vendedor ContentValues seller = new ContentValues(); seller.put("money", money + price); //aumenta o saldo do comprador myDb.update(DbHelper.USER_TABLE, seller, "id=?", new String[]{ Long.toString(user_id)}); //deleta o item da tabela de vendas myDb.delete(DbHelper.AUNCTIONS_TABLE, "id=?", new String[] { Long.toString(id) }); //muda o dono do item ContentValues owner = new ContentValues(); owner.put("id_user", u.getId()); myDb.update(DbHelper.USER_ITEM_TABLE, owner, "id_item=? AND id_user=?", new String[] {Integer.toString(item_id), Integer.toString(user_id)}); } } }); } } diff --git a/src/com/hstefan/aunctiondroid/db/DbHelper.java b/src/com/hstefan/aunctiondroid/db/DbHelper.java index 561b367..969c464 100644 --- a/src/com/hstefan/aunctiondroid/db/DbHelper.java +++ b/src/com/hstefan/aunctiondroid/db/DbHelper.java @@ -1,174 +1,181 @@ package com.hstefan.aunctiondroid.db; import java.io.FileNotFoundException; import android.content.ContentValues; import android.content.Context; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DbHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME= "aunctiondroid.db"; public static final int DATABASE_VERSION = 4; public static final String USER_TABLE = "user"; public static final String ITEM_TABLE = "item"; public static final String USER_ITEM_TABLE = "user_item"; public static final String AUNCTIONS_TABLE = "aunctions"; public static final String DB_SAMPLE_DATA_FILE = ".auctiondroid_sample"; public DbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); //eraseTableRows(); //insertExampleData(getWritableDatabase()); try { context.openFileInput(DB_SAMPLE_DATA_FILE); } catch (FileNotFoundException e) { try { context.openFileOutput(DB_SAMPLE_DATA_FILE, 0); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } @SuppressWarnings("unused") private void eraseTableRows() { SQLiteDatabase db = getWritableDatabase(); db.delete(USER_ITEM_TABLE, null, null); Log.i("Dropping table", USER_ITEM_TABLE); db.delete(ITEM_TABLE, null, null); Log.i("Dropping table", ITEM_TABLE); db.delete(USER_TABLE, null, null); Log.i("Dropping table", USER_TABLE); db.delete(AUNCTIONS_TABLE, null, null); Log.i("Dropping table", AUNCTIONS_TABLE); } @Override public void onCreate(SQLiteDatabase db) { if(DATABASE_VERSION >= 1) { String create_sql = "CREATE TABLE " + USER_TABLE + "(id INTEGER PRIMARY KEY AUTOINCREMENT," + "email TEXT NOT NULL," + "password TEXT NOT NULL)"; db.execSQL(create_sql); Log.i("Creating SQLite table", USER_TABLE); } if(DATABASE_VERSION >= 2) { String create_sql = "CREATE TABLE " + ITEM_TABLE + "(id INTEGER PRIMARY KEY AUTOINCREMENT," + "name TEXT NOT NULL)"; db.execSQL(create_sql); Log.i("Creating SQLite table", ITEM_TABLE); create_sql = "CREATE TABLE " + USER_ITEM_TABLE + "(id_user INTEGER, id_item INTEGER, " + "FOREIGN KEY(id_user) REFERENCES " + USER_TABLE + "," + "FOREIGN KEY(id_item) REFERENCES " + ITEM_TABLE + ")"; db.execSQL(create_sql); Log.i("Creating SQLite table", USER_ITEM_TABLE); } if(DATABASE_VERSION >= 3) { StringBuilder builder = new StringBuilder(); builder.append("ALTER TABLE "); builder.append(USER_TABLE); builder.append(" ADD money INTEGER"); db.execSQL(builder.toString()); Log.i("Upgrading SQLite table", USER_TABLE); builder.setLength(0); builder.append("CREATE TABLE "); builder.append(AUNCTIONS_TABLE); builder.append("(id INTEGER PRIMARY KEY, id_item INTEGER, id_user INTEGER,"); builder.append("price INTEGER NOT NULL, "); builder.append("FOREIGN KEY (id_item) REFERENCES "); builder.append(ITEM_TABLE); builder.append(","); builder.append("FOREIGN KEY (id_user) REFERENCES "); builder.append(USER_TABLE); builder.append(")"); db.execSQL(builder.toString()); Log.i("Creating SQLite table", AUNCTIONS_TABLE); //Now Playing: Metallica - St. Anger - St. Anger - 2003 - Rock - MP3 - 320 kbps - 7:21 min } if(DATABASE_VERSION >= 4) { db.execSQL("DROP TABLE " + AUNCTIONS_TABLE); Log.i("Dropping table", AUNCTIONS_TABLE); StringBuilder builder = new StringBuilder(); builder.setLength(0); builder.append("CREATE TABLE "); builder.append(AUNCTIONS_TABLE); builder.append("(id INTEGER PRIMARY KEY AUTOINCREMENT, id_item INTEGER, id_user INTEGER,"); builder.append("price INTEGER NOT NULL, "); builder.append("FOREIGN KEY (id_item) REFERENCES "); builder.append(ITEM_TABLE); builder.append(","); builder.append("FOREIGN KEY (id_user) REFERENCES "); builder.append(USER_TABLE); builder.append(")"); db.execSQL(builder.toString()); Log.i("Creating SQLite table", AUNCTIONS_TABLE); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if(oldVersion == 1 && newVersion == 2) { String create_sql = "CREATE TABLE " + ITEM_TABLE + "(id INTEGER PRIMARY KEY AUTOINCREMENT," + "name TEXT NOT NULL)"; db.execSQL(create_sql); Log.i("Creating SQLite table(upgrade)", ITEM_TABLE); create_sql = "CREATE TABLE " + USER_ITEM_TABLE + "(id_user INTEGER, id_item INTEGER, " + "FOREIGN KEY(id_user) REFERENCES " + USER_TABLE + "," + "FOREIGN KEY(id_item) REFERENCES " + ITEM_TABLE + ")"; db.execSQL(create_sql); Log.i("Creating SQLite table(upgrade)", USER_ITEM_TABLE); } if(DATABASE_VERSION >= 3 && newVersion != 4) { StringBuilder builder = new StringBuilder(); builder.append("ALTER TABLE "); builder.append(USER_TABLE); builder.append(" ADD money INTEGER"); db.execSQL(builder.toString()); Log.i("Upgrading SQLite table", USER_TABLE); builder.setLength(0); builder.append("CREATE TABLE "); builder.append(AUNCTIONS_TABLE); builder.append("(id INTEGER PRIMARY KEY AUTOINCREMENT, id_item INTEGER, id_user INTEGER,"); builder.append("price INTEGER NOT NULL, "); builder.append("FOREIGN KEY (id_item) REFERENCES "); builder.append(ITEM_TABLE); builder.append(","); builder.append("FOREIGN KEY (id_user) REFERENCES "); builder.append(USER_TABLE); builder.append(")"); db.execSQL(builder.toString()); Log.i("Upgrading SQLite table", AUNCTIONS_TABLE); } } private void insertExampleData(SQLiteDatabase db) { if(DATABASE_VERSION >= 1) { try { ContentValues cv = new ContentValues(); cv.put("email", "[email protected]"); cv.put("password", new String(PassDigester.digest("123"))); cv.put("money" , 1000); db.insert(USER_TABLE, null, cv); - Log.i("Example data", "inserted"); + + ContentValues cv2 = new ContentValues(); + cv2.put("email", "[email protected]"); + cv2.put("password", new String(PassDigester.digest("abc"))); + cv2.put("money" , 1000); + db.insert(USER_TABLE, null, cv2); + + Log.i("Example data", "inserted"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
false
false
null
null
diff --git a/src/com/qozix/layouts/ZoomPanLayout.java b/src/com/qozix/layouts/ZoomPanLayout.java index 72c29d7..12aad11 100644 --- a/src/com/qozix/layouts/ZoomPanLayout.java +++ b/src/com/qozix/layouts/ZoomPanLayout.java @@ -1,924 +1,937 @@ package com.qozix.layouts; import java.lang.ref.WeakReference; import java.util.HashSet; import android.content.Context; import android.graphics.Point; import android.graphics.Rect; import android.os.Handler; import android.os.Message; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewGroup; import com.qozix.animation.Tween; import com.qozix.animation.TweenListener; import com.qozix.animation.easing.Strong; import com.qozix.widgets.Scroller; /** * ZoomPanLayout extends ViewGroup to provide support for scrolling and zooming. Fling, drag, pinch and * double-tap events are supported natively. * * ZoomPanLayout does not support direct insertion of child Views, and manages positioning through an intermediary View. * the addChild method provides an interface to add layouts to that intermediary view. Each of these children are provided * with LayoutParams of MATCH_PARENT for both axes, and will always be positioned at 0,0, so should generally be ViewGroups * themselves (RelativeLayouts or FrameLayouts are generally appropriate). */ public class ZoomPanLayout extends ViewGroup { private static final int MINIMUM_VELOCITY = 50; private static final int ZOOM_ANIMATION_DURATION = 500; private static final int SLIDE_DURATION = 500; private static final int VELOCITY_UNITS = 1000; private static final int DOUBLE_TAP_TIME_THRESHOLD = 250; private static final int SINGLE_TAP_DISTANCE_THRESHOLD = 50; private static final double MINIMUM_PINCH_SCALE = 0.0; private static final float FRICTION = 0.99f; private int baseWidth; private int baseHeight; private int scaledWidth; private int scaledHeight; private double scale = 1; private double historicalScale = 1; private double minScale = 0; private double maxScale = 1; private boolean scaleToFit = true; private Point pinchStartScroll = new Point(); private Point pinchStartOffset = new Point(); private double pinchStartDistance; private Point doubleTapStartScroll = new Point(); private Point doubleTapStartOffset = new Point(); private double doubleTapDestinationScale; private Point firstFinger = new Point(); private Point secondFinger = new Point(); private Point lastFirstFinger = new Point(); private Point lastSecondFinger = new Point(); private Point scrollPosition = new Point(); private Point singleTapHistory = new Point(); private Point doubleTapHistory = new Point(); private Point firstFingerLastDown = new Point(); private Point secondFingerLastDown = new Point(); private Point actualPoint = new Point(); private Point destinationScroll = new Point(); private boolean secondFingerIsDown = false; private boolean firstFingerIsDown = false; private boolean isTapInterrupted = false; private boolean isBeingFlung = false; private boolean isDragging = false; private boolean isPinching = false; private int dragStartThreshold = 30; private int pinchStartThreshold = 30; private long lastTouchedAt; private ScrollActionHandler scrollActionHandler; private Scroller scroller; private VelocityTracker velocity; private HashSet<GestureListener> gestureListeners = new HashSet<GestureListener>(); private HashSet<ZoomPanListener> zoomPanListeners = new HashSet<ZoomPanListener>(); private StaticLayout clip; private TweenListener tweenListener = new TweenListener() { @Override public void onTweenComplete() { isTweening = false; for ( ZoomPanListener listener : zoomPanListeners ) { listener.onZoomComplete( scale ); listener.onZoomPanEvent(); } } @Override public void onTweenProgress( double progress, double eased ) { double originalChange = doubleTapDestinationScale - historicalScale; double updatedChange = originalChange * eased; double currentScale = historicalScale + updatedChange; setScale( currentScale ); maintainScrollDuringScaleTween(); } @Override public void onTweenStart() { saveHistoricalScale(); isTweening = true; for ( ZoomPanListener listener : zoomPanListeners ) { listener.onZoomStart( scale ); listener.onZoomPanEvent(); } } }; private boolean isTweening; private Tween tween = new Tween(); { tween.setAnimationEase( Strong.EaseOut ); tween.addTweenListener( tweenListener ); } /** * Constructor to use when creating a ZoomPanLayout from code. Inflating from XML is not currently supported. * @param context (Context) The Context the ZoomPanLayout is running in, through which it can access the current theme, resources, etc. */ public ZoomPanLayout( Context context ) { super( context ); setWillNotDraw( false ); scrollActionHandler = new ScrollActionHandler( this ); scroller = new Scroller( context ); scroller.setFriction( FRICTION ); clip = new StaticLayout( context ); super.addView( clip, -1, new LayoutParams( -1, -1 ) ); updateClip(); } //------------------------------------------------------------------------------------ // PUBLIC API //------------------------------------------------------------------------------------ /** * Determines whether the ZoomPanLayout should limit it's minimum scale to no less than what would be required to fill it's container * @param shouldScaleToFit (boolean) True to limit minimum scale, false to allow arbitrary minimum scale (see {@link setScaleLimits}) */ public void setScaleToFit( boolean shouldScaleToFit ) { scaleToFit = shouldScaleToFit; calculateMinimumScaleToFit(); } /** * Set minimum and maximum scale values for this ZoomPanLayout. * Note that if {@link shouldScaleToFit} is set to true, the minimum value set here will be ignored * Default values are 0 and 1. * @param min * @param max */ public void setScaleLimits( double min, double max ) { // if scaleToFit is set, don't allow overwrite if ( !scaleToFit ) { minScale = min; } maxScale = max; setScale( scale ); } /** * Sets the size (width and height) of the ZoomPanLayout as it should be rendered at a scale of 1f (100%) * @param wide width * @param tall height */ public void setSize( int wide, int tall ) { baseWidth = wide; baseHeight = tall; scaledWidth = (int) ( baseWidth * scale ); scaledHeight = (int) ( baseHeight * scale ); updateClip(); } /** * Returns the base (un-scaled) width * @return (int) base width */ public int getBaseWidth() { return baseWidth; } /** * Returns the base (un-scaled) height * @return (int) base height */ public int getBaseHeight() { return baseHeight; } /** * Returns the scaled width * @return (int) scaled width */ public int getScaledWidth() { return scaledWidth; } /** * Returns the scaled height * @return (int) scaled height */ public int getScaledHeight() { return scaledHeight; } /** * Sets the scale (0-1) of the ZoomPanLayout * @param scale (double) The new value of the ZoomPanLayout scale */ public void setScale( double d ) { d = Math.max( d, minScale ); d = Math.min( d, maxScale ); if ( scale != d ) { scale = d; scaledWidth = (int) ( baseWidth * scale ); scaledHeight = (int) ( baseHeight * scale ); updateClip(); postInvalidate(); for ( ZoomPanListener listener : zoomPanListeners ) { listener.onScaleChanged( scale ); listener.onZoomPanEvent(); } } } /** * Requests a redraw */ public void redraw() { updateClip(); postInvalidate(); } /** * Retrieves the current scale of the ZoomPanLayout * @return (double) the current scale of the ZoomPanLayout */ public double getScale() { return scale; } /** * Returns whether the ZoomPanLayout is currently being flung * @return (boolean) true if the ZoomPanLayout is currently flinging, false otherwise */ public boolean isFlinging() { return isBeingFlung; } /** * Returns the single child of the ZoomPanLayout, a ViewGroup that serves as an intermediary container * @return (View) The child view of the ZoomPanLayout that manages all contained views */ public View getClip() { return clip; } /** * Returns the minimum distance required to start a drag operation, in pixels. * @return (int) Pixel threshold required to start a drag. */ public int getDragStartThreshold(){ return dragStartThreshold; } /** * Returns the minimum distance required to start a drag operation, in pixels. * @param threshold (int) Pixel threshold required to start a drag. */ public void setDragStartThreshold( int threshold ){ dragStartThreshold = threshold; } /** * Returns the minimum distance required to start a pinch operation, in pixels. * @return (int) Pixel threshold required to start a pinch. */ public int getPinchStartThreshold(){ return pinchStartThreshold; } /** * Returns the minimum distance required to start a pinch operation, in pixels. * @param threshold (int) Pixel threshold required to start a pinch. */ public void setPinchStartThreshold( int threshold ){ pinchStartThreshold = threshold; } /** * Adds a GestureListener to the ZoomPanLayout, which will receive gesture events * @param listener (GestureListener) Listener to add * @return (boolean) true when the listener set did not already contain the Listener, false otherwise */ public boolean addGestureListener( GestureListener listener ) { return gestureListeners.add( listener ); } /** * Removes a GestureListener from the ZoomPanLayout * @param listener (GestureListener) Listener to remove * @return (boolean) if the Listener was removed, false otherwise */ public boolean removeGestureListener( GestureListener listener ) { return gestureListeners.remove( listener ); } /** * Adds a ZoomPanListener to the ZoomPanLayout, which will receive events relating to zoom and pan actions * @param listener (ZoomPanListener) Listener to add * @return (boolean) true when the listener set did not already contain the Listener, false otherwise */ public boolean addZoomPanListener( ZoomPanListener listener ) { return zoomPanListeners.add( listener ); } /** * Removes a ZoomPanListener from the ZoomPanLayout * @param listener (ZoomPanListener) Listener to remove * @return (boolean) if the Listener was removed, false otherwise */ public boolean removeZoomPanListener( ZoomPanListener listener ) { return zoomPanListeners.remove( listener ); } /** * Scrolls the ZoomPanLayout to the x and y values specified by {@param point} Point * @param point (Point) Point instance containing the destination x and y values */ public void scrollToPoint( Point point ) { constrainPoint( point ); int ox = getScrollX(); int oy = getScrollY(); int nx = (int) point.x; int ny = (int) point.y; scrollTo( nx, ny ); if ( ox != nx || oy != ny ) { for ( ZoomPanListener listener : zoomPanListeners ) { listener.onScrollChanged( nx, ny ); listener.onZoomPanEvent(); } } } /** * Scrolls and centers the ZoomPanLayout to the x and y values specified by {@param point} Point * @param point (Point) Point instance containing the destination x and y values */ public void scrollToAndCenter( Point point ) { // TODO: int x = (int) -( getWidth() * 0.5 ); int y = (int) -( getHeight() * 0.5 ); point.offset( x, y ); scrollToPoint( point ); } /** * Scrolls the ZoomPanLayout to the x and y values specified by {@param point} Point using scrolling animation * @param point (Point) Point instance containing the destination x and y values */ public void slideToPoint( Point point ) { // TODO: constrainPoint( point ); int startX = getScrollX(); int startY = getScrollY(); int dx = point.x - startX; int dy = point.y - startY; scroller.startScroll( startX, startY, dx, dy, SLIDE_DURATION ); invalidate(); // we're posting invalidate in computeScroll, yet both are required } /** * Scrolls and centers the ZoomPanLayout to the x and y values specified by {@param point} Point using scrolling animation * @param point (Point) Point instance containing the destination x and y values */ public void slideToAndCenter( Point point ) { // TODO: int x = (int) -( getWidth() * 0.5 ); int y = (int) -( getHeight() * 0.5 ); point.offset( x, y ); slideToPoint( point ); } /** * <i>This method is experimental</i> * Scroll and scale to match passed Rect as closely as possible. * The widget will attempt to frame the Rectangle, so that it's contained * within the viewport, if possible. * @param rect (Rect) rectangle to frame */ public void frameViewport( Rect rect ) { // position it scrollToPoint( new Point( rect.left, rect.top ) ); // TODO: center the axis that's smaller? // scale it double scaleX = getWidth() / (double) rect.width(); double scaleY = getHeight() / (double) rect.height(); double minimumScale = Math.min( scaleX, scaleY ); smoothScaleTo( minimumScale, SLIDE_DURATION ); } /** * Adds a View to the intermediary ViewGroup that manages layout for the ZoomPanLayout. * This View will be laid out at the width and height specified by {@setSize} at 0, 0 * All ViewGroup.addView signatures are routed through this signature, so the only parameters * considered are child and index. * @param child (View) The View to be added to the ZoomPanLayout view tree * @param index (int) The position at which to add the child View */ @Override public void addView( View child, int index, LayoutParams params ) { LayoutParams lp = new LayoutParams( scaledWidth, scaledHeight ); clip.addView( child, index, lp ); } @Override public void removeAllViews() { clip.removeAllViews(); } @Override public void removeViewAt( int index ) { clip.removeViewAt( index ); } @Override public void removeViews( int start, int count ) { clip.removeViews( start, count ); } /** * Scales the ZoomPanLayout with animated progress * @param destination (double) The final scale to animate to * @param duration (int) The duration (in milliseconds) of the animation */ public void smoothScaleTo( double destination, int duration ) { if ( isTweening ) { return; } - doubleTapDestinationScale = destination; - tween.setDuration( duration ); - tween.start(); + saveHistoricalScale(); + int x = (int) ( ( getWidth() * 0.5 ) + 0.5 ); + int y = (int) ( ( getHeight() * 0.5 ) + 0.5 ); + doubleTapStartOffset.set( x, y ); + doubleTapStartScroll.set( getScrollX(), getScrollY() ); + doubleTapStartScroll.offset( x, y ); + startSmoothScaleTo( destination, duration ); } //------------------------------------------------------------------------------------ // PRIVATE/PROTECTED //------------------------------------------------------------------------------------ @Override protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec ) { measureChildren( widthMeasureSpec, heightMeasureSpec ); int w = clip.getMeasuredWidth(); int h = clip.getMeasuredHeight(); w = Math.max( w, getSuggestedMinimumWidth() ); h = Math.max( h, getSuggestedMinimumHeight() ); w = resolveSize( w, widthMeasureSpec ); h = resolveSize( h, heightMeasureSpec ); setMeasuredDimension( w, h ); } @Override protected void onLayout( boolean changed, int l, int t, int r, int b ) { clip.layout( 0, 0, clip.getMeasuredWidth(), clip.getMeasuredHeight() ); constrainScroll(); if ( changed ) { calculateMinimumScaleToFit(); } } private void calculateMinimumScaleToFit() { if ( scaleToFit ) { double minimumScaleX = getWidth() / (double) baseWidth; double minimumScaleY = getHeight() / (double) baseHeight; double recalculatedMinScale = Math.max( minimumScaleX, minimumScaleY ); if ( recalculatedMinScale != minScale ) { minScale = recalculatedMinScale; setScale( scale ); } } } private void updateClip() { updateViewClip( clip ); for ( int i = 0; i < clip.getChildCount(); i++ ) { View child = clip.getChildAt( i ); updateViewClip( child ); } constrainScroll(); } private void updateViewClip( View v ) { LayoutParams lp = v.getLayoutParams(); lp.width = scaledWidth; lp.height = scaledHeight; v.setLayoutParams( lp ); } @Override public void computeScroll() { if ( scroller.computeScrollOffset() ) { Point destination = new Point( scroller.getCurrX(), scroller.getCurrY() ); scrollToPoint( destination ); dispatchScrollActionNotification(); postInvalidate(); // should not be necessary but is... } } private void dispatchScrollActionNotification() { if ( scrollActionHandler.hasMessages( 0 ) ) { scrollActionHandler.removeMessages( 0 ); } scrollActionHandler.sendEmptyMessageDelayed( 0, 100 ); } private void handleScrollerAction() { Point point = new Point(); point.x = getScrollX(); point.y = getScrollY(); for ( GestureListener listener : gestureListeners ) { listener.onScrollComplete( point ); } if ( isBeingFlung ) { isBeingFlung = false; for ( GestureListener listener : gestureListeners ) { listener.onFlingComplete( point ); } } } private void constrainPoint( Point point ) { int x = point.x; int y = point.y; int mx = Math.max( 0, Math.min( x, getLimitX() ) ); int my = Math.max( 0, Math.min( y, getLimitY() ) ); if ( x != mx || y != my ) { point.set( mx, my ); } } private void constrainScroll() { // TODO: Point currentScroll = new Point( getScrollX(), getScrollY() ); Point limitScroll = new Point( currentScroll ); constrainPoint( limitScroll ); if ( !currentScroll.equals( limitScroll ) ) { scrollToPoint( limitScroll ); } } private int getLimitX() { return scaledWidth - getWidth(); } private int getLimitY() { return scaledHeight - getHeight(); } private void saveHistoricalScale() { historicalScale = scale; } private void savePinchHistory() { int x = (int) ( ( firstFinger.x + secondFinger.x ) * 0.5 ); int y = (int) ( ( firstFinger.y + secondFinger.y ) * 0.5 ); pinchStartOffset.set( x, y ); pinchStartScroll.set( getScrollX(), getScrollY() ); pinchStartScroll.offset( x, y ); } private void maintainScrollDuringPinchOperation() { double deltaScale = scale / historicalScale; int x = (int) ( pinchStartScroll.x * deltaScale ) - pinchStartOffset.x; int y = (int) ( pinchStartScroll.y * deltaScale ) - pinchStartOffset.y; destinationScroll.set( x, y ); scrollToPoint( destinationScroll ); } private void saveDoubleTapHistory() { doubleTapStartOffset.set( firstFinger.x, firstFinger.y ); doubleTapStartScroll.set( getScrollX(), getScrollY() ); doubleTapStartScroll.offset( doubleTapStartOffset.x, doubleTapStartOffset.y ); } private void maintainScrollDuringScaleTween() { double deltaScale = scale / historicalScale; int x = (int) ( doubleTapStartScroll.x * deltaScale ) - doubleTapStartOffset.x; int y = (int) ( doubleTapStartScroll.y * deltaScale ) - doubleTapStartOffset.y; destinationScroll.set( x, y ); scrollToPoint( destinationScroll ); } private void saveHistoricalPinchDistance() { int dx = firstFinger.x - secondFinger.x; int dy = firstFinger.y - secondFinger.y; pinchStartDistance = Math.sqrt( dx * dx + dy * dy ); } private void setScaleFromPinch() { int dx = firstFinger.x - secondFinger.x; int dy = firstFinger.y - secondFinger.y; double pinchCurrentDistance = Math.sqrt( dx * dx + dy * dy ); double currentScale = pinchCurrentDistance / pinchStartDistance; currentScale = Math.max( currentScale, MINIMUM_PINCH_SCALE ); currentScale = historicalScale * currentScale; setScale( currentScale ); } private void performDrag() { Point delta = new Point(); if ( secondFingerIsDown && !firstFingerIsDown ) { delta.set( lastSecondFinger.x, lastSecondFinger.y ); delta.offset( -secondFinger.x, -secondFinger.y ); } else { delta.set( lastFirstFinger.x, lastFirstFinger.y ); delta.offset( -firstFinger.x, -firstFinger.y ); } scrollPosition.offset( delta.x, delta.y ); scrollToPoint( scrollPosition ); } private boolean performFling() { if ( secondFingerIsDown ) { return false; } velocity.computeCurrentVelocity( VELOCITY_UNITS ); double xv = velocity.getXVelocity(); double yv = velocity.getYVelocity(); double totalVelocity = Math.abs( xv ) + Math.abs( yv ); if ( totalVelocity > MINIMUM_VELOCITY ) { scroller.fling( getScrollX(), getScrollY(), (int) -xv, (int) -yv, 0, getLimitX(), 0, getLimitY() ); postInvalidate(); return true; } return false; } // if the taps occurred within threshold, it's a double tap private boolean determineIfQualifiedDoubleTap() { long now = System.currentTimeMillis(); long ellapsed = now - lastTouchedAt; lastTouchedAt = now; return ( ellapsed <= DOUBLE_TAP_TIME_THRESHOLD ) && ( Math.abs( firstFinger.x - doubleTapHistory.x ) <= SINGLE_TAP_DISTANCE_THRESHOLD ) && ( Math.abs( firstFinger.y - doubleTapHistory.y ) <= SINGLE_TAP_DISTANCE_THRESHOLD ); } private void saveTapActionOrigination() { singleTapHistory.set( firstFinger.x, firstFinger.y ); } private void saveDoubleTapOrigination() { doubleTapHistory.set( firstFinger.x, firstFinger.y ); } private void saveFirstFingerDown() { firstFingerLastDown.set ( firstFinger.x, firstFinger.y ); } private void saveSecondFingerDown() { secondFingerLastDown.set ( secondFinger.x, secondFinger.y ); } private void setTapInterrupted( boolean v ) { isTapInterrupted = v; } // if the touch event has traveled past threshold since the finger first when down, it's not a tap private boolean determineIfQualifiedSingleTap() { return !isTapInterrupted && ( Math.abs( firstFinger.x - singleTapHistory.x ) <= SINGLE_TAP_DISTANCE_THRESHOLD ) && ( Math.abs( firstFinger.y - singleTapHistory.y ) <= SINGLE_TAP_DISTANCE_THRESHOLD ); } + + private void startSmoothScaleTo( double destination, int duration ){ + if ( isTweening ) { + return; + } + doubleTapDestinationScale = destination; + tween.setDuration( duration ); + tween.start(); + } private void processEvent( MotionEvent event ) { // copy for history lastFirstFinger.set( firstFinger.x, firstFinger.y ); lastSecondFinger.set( secondFinger.x, secondFinger.y ); // set false for now firstFingerIsDown = false; secondFingerIsDown = false; // determine which finger is down and populate the appropriate points for ( int i = 0; i < event.getPointerCount(); i++ ) { int id = event.getPointerId( i ); int x = (int) event.getX( i ); int y = (int) event.getY( i ); switch ( id ) { case 0: firstFingerIsDown = true; firstFinger.set( x, y ); actualPoint.set( x, y ); break; case 1: secondFingerIsDown = true; secondFinger.set( x, y ); actualPoint.set( x, y ); break; } } // record scroll position and adjust finger point to account for scroll offset scrollPosition.set( getScrollX(), getScrollY() ); actualPoint.offset( scrollPosition.x, scrollPosition.y ); // update velocity for flinging // TODO: this can probably be moved to the ACTION_MOVE switch if ( velocity == null ) { velocity = VelocityTracker.obtain(); } velocity.addMovement( event ); } @Override public boolean onTouchEvent( MotionEvent event ) { // update positions processEvent( event ); // get the type of action final int action = event.getAction() & MotionEvent.ACTION_MASK; // react based on nature of touch event switch ( action ) { // first finger goes down case MotionEvent.ACTION_DOWN: if ( !scroller.isFinished() ) { scroller.abortAnimation(); } isBeingFlung = false; isDragging = false; setTapInterrupted( false ); saveFirstFingerDown(); saveTapActionOrigination(); for ( GestureListener listener : gestureListeners ) { listener.onFingerDown( actualPoint ); } break; // second finger goes down case MotionEvent.ACTION_POINTER_DOWN: isPinching = false; saveSecondFingerDown(); setTapInterrupted( true ); for ( GestureListener listener : gestureListeners ) { listener.onFingerDown( actualPoint ); } break; // either finger moves case MotionEvent.ACTION_MOVE: // if both fingers are down, that means it's a pinch if ( firstFingerIsDown && secondFingerIsDown ) { if ( !isPinching ) { double firstFingerDistance = getDistance( firstFinger, firstFingerLastDown ); double secondFingerDistance = getDistance( secondFinger, secondFingerLastDown ); double distance = ( firstFingerDistance + secondFingerDistance ) * 0.5; isPinching = distance >= pinchStartThreshold; // are we starting a pinch action? if ( isPinching ) { saveHistoricalPinchDistance(); saveHistoricalScale(); savePinchHistory(); for ( GestureListener listener : gestureListeners ) { listener.onPinchStart( pinchStartOffset ); } for ( ZoomPanListener listener : zoomPanListeners ) { listener.onZoomStart( scale ); listener.onZoomPanEvent(); } } } if ( isPinching ) { setScaleFromPinch(); maintainScrollDuringPinchOperation(); for ( GestureListener listener : gestureListeners ) { listener.onPinch( pinchStartOffset ); } } // otherwise it's a drag } else { if ( !isDragging ) { double distance = getDistance( firstFinger, firstFingerLastDown ); isDragging = distance >= dragStartThreshold; } if ( isDragging ) { performDrag(); for ( GestureListener listener : gestureListeners ) { listener.onDrag( actualPoint ); } } } break; // first finger goes up case MotionEvent.ACTION_UP: if ( performFling() ) { isBeingFlung = true; Point startPoint = new Point( getScrollX(), getScrollY() ); Point finalPoint = new Point( scroller.getFinalX(), scroller.getFinalY() ); for ( GestureListener listener : gestureListeners ) { listener.onFling( startPoint, finalPoint ); } } if ( velocity != null ) { velocity.recycle(); velocity = null; } // could be a single tap... if ( determineIfQualifiedSingleTap() ) { for ( GestureListener listener : gestureListeners ) { listener.onTap( actualPoint ); } } // or a double tap if ( determineIfQualifiedDoubleTap() ) { scroller.forceFinished( true ); saveHistoricalScale(); saveDoubleTapHistory(); double destination = Math.min( maxScale, scale * 2 ); - smoothScaleTo( destination, ZOOM_ANIMATION_DURATION ); + startSmoothScaleTo( destination, ZOOM_ANIMATION_DURATION ); for ( GestureListener listener : gestureListeners ) { listener.onDoubleTap( actualPoint ); } } // either way it's a finger up event for ( GestureListener listener : gestureListeners ) { listener.onFingerUp( actualPoint ); } // save coordinates to measure against the next double tap saveDoubleTapOrigination(); isDragging = false; isPinching = false; break; // second finger goes up case MotionEvent.ACTION_POINTER_UP: isPinching = false; setTapInterrupted( true ); for ( GestureListener listener : gestureListeners ) { listener.onFingerUp( actualPoint ); } for ( GestureListener listener : gestureListeners ) { listener.onPinchComplete( pinchStartOffset ); } for ( ZoomPanListener listener : zoomPanListeners ) { listener.onZoomComplete( scale ); listener.onZoomPanEvent(); } break; } return true; } // sugar to calculate distance between 2 Points, because android.graphics.Point is horrible private static double getDistance( Point p1, Point p2 ) { int x = p1.x - p2.x; int y = p1.y - p2.y; return Math.sqrt( x * x + y * y ); } private static class ScrollActionHandler extends Handler { private final WeakReference<ZoomPanLayout> reference; public ScrollActionHandler( ZoomPanLayout zoomPanLayout ) { super(); reference = new WeakReference<ZoomPanLayout>( zoomPanLayout ); } @Override public void handleMessage( Message msg ) { ZoomPanLayout zoomPanLayout = reference.get(); if ( zoomPanLayout != null ) { zoomPanLayout.handleScrollerAction(); } } } //------------------------------------------------------------------------------------ // Public static interfaces and classes //------------------------------------------------------------------------------------ public static interface ZoomPanListener { public void onScaleChanged( double scale ); public void onScrollChanged( int x, int y ); public void onZoomStart( double scale ); public void onZoomComplete( double scale ); public void onZoomPanEvent(); } public static interface GestureListener { public void onFingerDown( Point point ); public void onScrollComplete( Point point ); public void onFingerUp( Point point ); public void onDrag( Point point ); public void onDoubleTap( Point point ); public void onTap( Point point ); public void onPinch( Point point ); public void onPinchStart( Point point ); public void onPinchComplete( Point point ); public void onFling( Point startPoint, Point finalPoint ); public void onFlingComplete( Point point ); } } \ No newline at end of file
false
false
null
null
diff --git a/flyway-core/src/main/java/com/googlecode/flyway/core/dbsupport/oracle/OracleDbSupport.java b/flyway-core/src/main/java/com/googlecode/flyway/core/dbsupport/oracle/OracleDbSupport.java index 0742ff07e..1e4df7a71 100644 --- a/flyway-core/src/main/java/com/googlecode/flyway/core/dbsupport/oracle/OracleDbSupport.java +++ b/flyway-core/src/main/java/com/googlecode/flyway/core/dbsupport/oracle/OracleDbSupport.java @@ -1,202 +1,202 @@ /** * Copyright (C) 2010-2011 the original author or authors. * * 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.googlecode.flyway.core.dbsupport.oracle; import com.googlecode.flyway.core.dbsupport.DbSupport; import com.googlecode.flyway.core.exception.FlywayException; import com.googlecode.flyway.core.migration.sql.PlaceholderReplacer; import com.googlecode.flyway.core.migration.sql.SqlScript; import com.googlecode.flyway.core.migration.sql.SqlStatement; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.ConnectionCallback; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * Oracle-specific support. */ public class OracleDbSupport implements DbSupport { /** * Logger. */ private static final Log LOG = LogFactory.getLog(OracleDbSupport.class); /** * The jdbcTemplate to use. */ private final JdbcTemplate jdbcTemplate; /** * Creates a new instance. * * @param jdbcTemplate The jdbcTemplate to use. */ public OracleDbSupport(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public String getScriptLocation() { return "com/googlecode/flyway/core/dbsupport/oracle/"; } public String getCurrentUserFunction() { return "USER"; } public String getCurrentSchema() { return (String) jdbcTemplate.queryForObject("SELECT USER FROM dual", String.class); } public boolean isSchemaEmpty(String schema) { int objectCount = jdbcTemplate.queryForInt("SELECT count(*) FROM all_objects WHERE owner = ?", new Object[]{schema}); return objectCount == 0; } public boolean tableExists(final String schema, final String table) { return (Boolean) jdbcTemplate.execute(new ConnectionCallback() { public Boolean doInConnection(Connection connection) throws SQLException, DataAccessException { ResultSet resultSet = connection.getMetaData().getTables(null, schema.toUpperCase(), table.toUpperCase(), null); return resultSet.next(); } }); } public boolean supportsDdlTransactions() { return false; } public void lockTable(String schema, String table) { jdbcTemplate.execute("select * from " + schema + "." + table + " for update"); } public String getBooleanTrue() { return "1"; } public String getBooleanFalse() { return "0"; } public SqlScript createSqlScript(String sqlScriptSource, PlaceholderReplacer placeholderReplacer) { return new OracleSqlScript(sqlScriptSource, placeholderReplacer); } public SqlScript createCleanScript(String schema) { if ("SYSTEM".equals(schema.toUpperCase())) { throw new FlywayException("Clean not supported on Oracle for user 'SYSTEM'! You should NEVER add your own objects to the SYSTEM schema!"); } final List<String> allDropStatements = new ArrayList<String>(); allDropStatements.add("PURGE RECYCLEBIN"); allDropStatements.addAll(generateDropStatementsForSpatialExtensions(schema)); allDropStatements.addAll(generateDropStatementsForObjectType("SEQUENCE", "", schema)); allDropStatements.addAll(generateDropStatementsForObjectType("FUNCTION", "", schema)); allDropStatements.addAll(generateDropStatementsForObjectType("MATERIALIZED VIEW", "PRESERVE TABLE", schema)); allDropStatements.addAll(generateDropStatementsForObjectType("PACKAGE", "", schema)); allDropStatements.addAll(generateDropStatementsForObjectType("PROCEDURE", "", schema)); allDropStatements.addAll(generateDropStatementsForObjectType("SYNONYM", "", schema)); allDropStatements.addAll(generateDropStatementsForObjectType("VIEW", "CASCADE CONSTRAINTS", schema)); allDropStatements.addAll(generateDropStatementsForObjectType("TABLE", "CASCADE CONSTRAINTS PURGE", schema)); - allDropStatements.addAll(generateDropStatementsForObjectType("TYPE", "", schema)); + allDropStatements.addAll(generateDropStatementsForObjectType("TYPE", "FORCE", schema)); List<SqlStatement> sqlStatements = new ArrayList<SqlStatement>(); int lineNumber = 1; for (String dropStatement : allDropStatements) { sqlStatements.add(new SqlStatement(lineNumber, dropStatement)); lineNumber++; } return new SqlScript(sqlStatements); } /** * Generates the drop statements for all database objects of this type. * * @param objectType The type of database object to drop. * @param extraArguments The extra arguments to add to the drop statement. * @param schema The schema for which to generate the statements. * @return The complete drop statements, ready to execute. */ @SuppressWarnings({"unchecked"}) private List<String> generateDropStatementsForObjectType(String objectType, final String extraArguments, final String schema) { String query = "SELECT object_type, object_name FROM all_objects WHERE object_type = ? AND owner = ?" // Ignore Recycle bin objects + " AND object_name NOT LIKE 'BIN$%'" // Ignore Spatial Index Tables and Sequences as they get dropped automatically when the index gets dropped. + " AND object_name NOT LIKE 'MDRT_%$' AND object_name NOT LIKE 'MDRS_%$'" // Ignore Materialized View Logs + " AND object_name NOT LIKE 'MLOG$%' AND object_name NOT LIKE 'RUPD$%'"; return jdbcTemplate.query(query, new Object[]{objectType, schema.toUpperCase()}, new RowMapper() { public String mapRow(ResultSet rs, int rowNum) throws SQLException { return "DROP " + rs.getString("OBJECT_TYPE") + " " + schema + ".\"" + rs.getString("OBJECT_NAME") + "\" " + extraArguments; } }); } /** * Generates the drop statements for Oracle Spatial Extensions-related database objects. * * @param schema The schema for which to generate the statements. * @return The complete drop statements, ready to execute. */ private List<String> generateDropStatementsForSpatialExtensions(String schema) { List<String> statements = new ArrayList<String>(); if (!spatialExtensionsAvailable()) { LOG.debug("Oracle Spatial Extensions are not available. No cleaning of MDSYS tables and views."); return statements; } if (!getCurrentSchema().equalsIgnoreCase(schema)) { int count = jdbcTemplate.queryForInt("SELECT COUNT (*) FROM all_sdo_geom_metadata WHERE owner=?", new Object[] {schema.toUpperCase()}); count += jdbcTemplate.queryForInt("SELECT COUNT (*) FROM all_sdo_index_info WHERE sdo_index_owner=?", new Object[] {schema.toUpperCase()}); if (count > 0) { LOG.warn("Unable to clean Oracle Spatial objects for schema '" + schema + "' as they do not belong to the default schema for this connection!"); } return statements; } statements.add("DELETE FROM mdsys.user_sdo_geom_metadata"); @SuppressWarnings({"unchecked"}) List<String> indexNames = jdbcTemplate.queryForList("select INDEX_NAME from USER_SDO_INDEX_INFO", String.class); for (String indexName : indexNames) { statements.add("DROP INDEX \"" + indexName + "\""); } return statements; } /** * Checks whether Oracle Spatial extensions are available or not. * * @return {@code true} if they are available, {@code false} if not. */ private boolean spatialExtensionsAvailable() { return jdbcTemplate.queryForInt("SELECT COUNT(*) FROM all_views WHERE owner = 'MDSYS' AND view_name = 'USER_SDO_GEOM_METADATA'") > 0; } } diff --git a/flyway-core/src/test/java/com/googlecode/flyway/core/dbsupport/oracle/OracleMigrationMediumTest.java b/flyway-core/src/test/java/com/googlecode/flyway/core/dbsupport/oracle/OracleMigrationMediumTest.java index e45f52cae..b96c5557e 100644 --- a/flyway-core/src/test/java/com/googlecode/flyway/core/dbsupport/oracle/OracleMigrationMediumTest.java +++ b/flyway-core/src/test/java/com/googlecode/flyway/core/dbsupport/oracle/OracleMigrationMediumTest.java @@ -1,166 +1,177 @@ /** * Copyright (C) 2010-2011 the original author or authors. * * 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.googlecode.flyway.core.dbsupport.oracle; import com.googlecode.flyway.core.dbsupport.DbSupport; import com.googlecode.flyway.core.exception.FlywayException; import com.googlecode.flyway.core.metadatatable.MetaDataTableRow; import com.googlecode.flyway.core.migration.MigrationTestCase; import com.googlecode.flyway.core.migration.SchemaVersion; import org.junit.Test; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.ContextConfiguration; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * Test to demonstrate the migration functionality using Mysql. */ @SuppressWarnings({"JavaDoc"}) @ContextConfiguration(locations = {"classpath:migration/dbsupport/oracle/oracle-context.xml"}) public class OracleMigrationMediumTest extends MigrationTestCase { @Override protected String getQuoteBaseDir() { return "migration/quote"; } @Override protected DbSupport getDbSupport(JdbcTemplate jdbcTemplate) { return new OracleDbSupport(jdbcTemplate); } /** * Tests migrations containing placeholders. */ @Test public void migrationsWithPlaceholders() throws FlywayException { int countUserObjects1 = jdbcTemplate.queryForInt("SELECT count(*) FROM user_objects"); Map<String, String> placeholders = new HashMap<String, String>(); placeholders.put("tableName", "test_user"); flyway.setPlaceholders(placeholders); flyway.setBaseDir("migration/dbsupport/oracle/sql/placeholders"); flyway.migrate(); SchemaVersion schemaVersion = flyway.status().getVersion(); assertEquals("1.1", schemaVersion.toString()); assertEquals("Populate table", flyway.status().getDescription()); assertEquals("Mr. T triggered", jdbcTemplate.queryForObject("select name from test_user", String.class)); flyway.clean(); int countUserObjects2 = jdbcTemplate.queryForInt("SELECT count(*) FROM user_objects"); assertEquals(countUserObjects1, countUserObjects2); final List<MetaDataTableRow> metaDataTableRows = flyway.history(); for (MetaDataTableRow metaDataTableRow : metaDataTableRows) { assertNotNull(metaDataTableRow.getScript() + " has no checksum", metaDataTableRow.getChecksum()); } } /** * Tests clean for Oracle Spatial Extensions. */ @Test public void cleanSpatialExtensions() throws FlywayException { assertEquals(0, objectsCount()); flyway.setBaseDir("migration/dbsupport/oracle/sql/spatial"); flyway.migrate(); assertTrue(objectsCount() > 0); flyway.clean(); assertEquals(0, objectsCount()); // Running migrate again on an unclean database, triggers duplicate object exceptions. flyway.migrate(); assertTrue(objectsCount() > 0); } /** * Tests parsing of CREATE PACKAGE. */ @Test public void createPackage() throws FlywayException { flyway.setBaseDir("migration/dbsupport/oracle/sql/package"); flyway.migrate(); } /** * Tests parsing of object names that countain keywords such as MY_TABLE. */ @Test public void objectNames() throws FlywayException { flyway.setBaseDir("migration/dbsupport/oracle/sql/objectnames"); flyway.migrate(); } /** * Tests cleaning up after CREATE MATERIALIZED VIEW. */ @Test public void createMaterializedView() throws FlywayException { flyway.setBaseDir("migration/dbsupport/oracle/sql/materialized"); flyway.migrate(); flyway.clean(); } /** * Test clean with recycle bin */ @Test public void cleanWithRecycleBin() { assertEquals(0, recycleBinCount()); // in SYSTEM tablespace the recycle bin is deactivated jdbcTemplate.update("CREATE TABLE test_user (name VARCHAR(25) NOT NULL, PRIMARY KEY(name)) tablespace USERS"); jdbcTemplate.update("DROP TABLE test_user"); assertTrue(recycleBinCount() > 0); flyway.clean(); assertEquals(0, recycleBinCount()); } /** * @return The number of objects for the current user. */ private int objectsCount() { return jdbcTemplate.queryForInt("select count(*) from user_objects"); } /** * @return The number of objects in the recycle bin. */ private int recycleBinCount() { return jdbcTemplate.queryForInt("select count(*) from recyclebin"); } /** * Tests parsing support for q-Quote string literals. */ @Test public void qQuote() throws FlywayException { flyway.setBaseDir("migration/dbsupport/oracle/sql/qquote"); flyway.migrate(); } + + /** + * Tests support for user defined types. + */ + @Test + public void type() throws FlywayException { + flyway.setBaseDir("migration/dbsupport/oracle/sql/type"); + flyway.migrate(); + flyway.clean(); + flyway.migrate(); + } }
false
false
null
null
diff --git a/src/main/src/main/java/org/geoserver/feature/retype/RetypingDataStore.java b/src/main/src/main/java/org/geoserver/feature/retype/RetypingDataStore.java index d107b3da97..45b402e079 100644 --- a/src/main/src/main/java/org/geoserver/feature/retype/RetypingDataStore.java +++ b/src/main/src/main/java/org/geoserver/feature/retype/RetypingDataStore.java @@ -1,334 +1,325 @@ /* Copyright (c) 2001 - 2007 TOPP - www.openplans.org. All rights reserved. * This code is licensed under the GPL 2.0 license, availible at the root * application directory. */ package org.geoserver.feature.retype; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.geoserver.feature.RetypingFeatureCollection; import org.geotools.data.DataAccess; import org.geotools.data.DataSourceException; import org.geotools.data.DataStore; import org.geotools.data.DataUtilities; import org.geotools.data.DefaultQuery; import org.geotools.data.FeatureLocking; import org.geotools.data.FeatureReader; import org.geotools.data.FeatureStore; import org.geotools.data.FeatureWriter; import org.geotools.data.LockingManager; import org.geotools.data.Query; import org.geotools.data.ServiceInfo; import org.geotools.data.Transaction; import org.geotools.data.simple.SimpleFeatureLocking; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.data.simple.SimpleFeatureStore; import org.geotools.feature.NameImpl; -import org.geotools.feature.SchemaException; import org.geotools.feature.simple.SimpleFeatureTypeBuilder; import org.geotools.util.logging.Logging; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.type.Name; import org.opengis.filter.Filter; /** * A simple data store that can be used to rename feature types (despite the name, the only retyping * considered is the name change, thought it would not be that hard to extend it so that it * could shave off some attribute too) */ public class RetypingDataStore implements DataStore { static final Logger LOGGER = Logging.getLogger(RetypingDataStore.class); DataStore wrapped; Map forwardMap = new HashMap(); Map backwardsMap = new HashMap(); public RetypingDataStore(DataStore wrapped) throws IOException { this.wrapped = wrapped; // force update of type mapping maps getTypeNames(); } public void createSchema(SimpleFeatureType featureType) throws IOException { throw new UnsupportedOperationException( "GeoServer does not support schema creation at the moment"); } public void updateSchema(String typeName, SimpleFeatureType featureType) throws IOException { throw new UnsupportedOperationException( "GeoServer does not support schema updates at the moment"); } public FeatureWriter<SimpleFeatureType, SimpleFeature> getFeatureWriter(String typeName, Filter filter, Transaction transaction) throws IOException { FeatureTypeMap map = getTypeMapBackwards(typeName, true); updateMap(map, false); FeatureWriter<SimpleFeatureType, SimpleFeature> writer = wrapped.getFeatureWriter(map.getOriginalName(), filter, transaction); if (map.isUnchanged()) return writer; return new RetypingFeatureCollection.RetypingFeatureWriter(writer, map.getFeatureType()); } public FeatureWriter<SimpleFeatureType, SimpleFeature> getFeatureWriter(String typeName, Transaction transaction) throws IOException { FeatureTypeMap map = getTypeMapBackwards(typeName, true); updateMap(map, false); FeatureWriter<SimpleFeatureType, SimpleFeature> writer; writer = wrapped.getFeatureWriter(map.getOriginalName(), transaction); if (map.isUnchanged()) return writer; return new RetypingFeatureCollection.RetypingFeatureWriter(writer, map.getFeatureType()); } public FeatureWriter<SimpleFeatureType, SimpleFeature> getFeatureWriterAppend(String typeName, Transaction transaction) throws IOException { FeatureTypeMap map = getTypeMapBackwards(typeName, true); updateMap(map, false); FeatureWriter<SimpleFeatureType, SimpleFeature> writer; writer = wrapped.getFeatureWriterAppend(map.getOriginalName(), transaction); if (map.isUnchanged()) return writer; return new RetypingFeatureCollection.RetypingFeatureWriter(writer, map.getFeatureType()); } public SimpleFeatureType getSchema(String typeName) throws IOException { FeatureTypeMap map = getTypeMapBackwards(typeName, false); if(map == null) throw new IOException("Unknown type " + typeName); updateMap(map, true); return map.getFeatureType(); } public String[] getTypeNames() throws IOException { // here we transform the names, and also refresh the type maps so that // they // don't contain stale elements String[] names = wrapped.getTypeNames(); String[] transformedNames = new String[names.length]; Map backup = new HashMap(forwardMap); forwardMap.clear(); backwardsMap.clear(); for (int i = 0; i < names.length; i++) { String original = names[i]; transformedNames[i] = transformFeatureTypeName(original); FeatureTypeMap map = (FeatureTypeMap) backup.get(original); if (map == null) { map = new FeatureTypeMap(original, transformedNames[i]); } forwardMap.put(map.getOriginalName(), map); backwardsMap.put(map.getName(), map); } return transformedNames; } public FeatureReader<SimpleFeatureType, SimpleFeature> getFeatureReader(Query query, Transaction transaction) throws IOException { FeatureTypeMap map = getTypeMapBackwards(query.getTypeName(), true); updateMap(map, false); FeatureReader<SimpleFeatureType, SimpleFeature> reader; reader = wrapped.getFeatureReader(retypeQuery(query, map), transaction); if (map.isUnchanged()) return reader; return new RetypingFeatureCollection.RetypingFeatureReader(reader, map.getFeatureType()); } public SimpleFeatureSource getFeatureSource(String typeName) throws IOException { FeatureTypeMap map = getTypeMapBackwards(typeName, true); updateMap(map, false); SimpleFeatureSource source = wrapped.getFeatureSource(map.getOriginalName()); if (map.isUnchanged()) return source; if (source instanceof FeatureLocking) { SimpleFeatureLocking locking = DataUtilities.simple((FeatureLocking) source); return new RetypingFeatureLocking(this, locking, map); } else if (source instanceof FeatureStore) { SimpleFeatureStore store = DataUtilities.simple((FeatureStore) source); return new RetypingFeatureStore(this, store, map); } return new RetypingFeatureSource(this, source, map); } public LockingManager getLockingManager() { return wrapped.getLockingManager(); } - public SimpleFeatureSource getView(Query query) throws IOException, - SchemaException { - FeatureTypeMap map = getTypeMapBackwards(query.getTypeName(), true); - updateMap(map, false); - SimpleFeatureSource view = wrapped.getView(query); - return new RetypingFeatureSource(this, view, map); - } - /** * Returns the type map given the external type name * * @param externalTypeName * @return * @throws IOException */ FeatureTypeMap getTypeMapBackwards(String externalTypeName, boolean checkMap) throws IOException { FeatureTypeMap map = (FeatureTypeMap) backwardsMap.get(externalTypeName); if (map == null && checkMap) throw new IOException("Type mapping has not been established for type " + externalTypeName + ". " + "Make sure you access types using getTypeNames() or getSchema() " + "before trying to read/write onto them"); return map; } /** * Make sure the FeatureTypeMap is fully loaded * * @param map * @throws IOException */ void updateMap(FeatureTypeMap map, boolean forceUpdate) throws IOException { try { if (map.getFeatureType() == null || forceUpdate) { SimpleFeatureType original = wrapped.getSchema(map.getOriginalName()); SimpleFeatureType transformed = transformFeatureType(original); map.setFeatureTypes(original, transformed); } } catch (IOException e) { LOGGER.log(Level.INFO, "Failure to remap feature type " + map.getOriginalName() + ". The type will be ignored", e); // if the feature type cannot be found in the original data store, // remove it from the map backwardsMap.remove(map.getName()); forwardMap.remove(map.getOriginalName()); } } /** * Transforms the original feature type into a destination one according to * the renaming rules. For the moment, it's just a feature type name * replacement * * @param original * @return * @throws IOException */ protected SimpleFeatureType transformFeatureType(SimpleFeatureType original) throws IOException { String transfomedName = transformFeatureTypeName(original.getTypeName()); if (transfomedName.equals(original.getTypeName())) return original; try { SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder(); b.init(original); b.setName(transfomedName); return b.buildFeatureType(); } catch (Exception e) { throw new DataSourceException("Could not build the renamed feature type.", e); } } /** * Just transform the feature type name * * @param originalName * @return */ protected String transformFeatureTypeName(String originalName) { // if(originalName.indexOf(":") >= 0) { // return originalName.substring(originalName.indexOf(":") + 1); // } else { // return originalName; // } return originalName.replaceAll(":", "_"); } public void dispose() { wrapped.dispose(); } /** * Retypes a query from the extenal type to the internal one using the * provided typemap * @param q * @param typeMap * @return * @throws IOException */ Query retypeQuery(Query q, FeatureTypeMap typeMap) { DefaultQuery modified = new DefaultQuery(q); modified.setTypeName(typeMap.getOriginalName()); modified.setFilter(retypeFilter(q.getFilter(), typeMap)); return modified; } /** * Retypes a filter making sure the fids are using the internal typename prefix * @param filter * @param typeMap * @return */ Filter retypeFilter(Filter filter, FeatureTypeMap typeMap) { FidTransformeVisitor visitor = new FidTransformeVisitor(typeMap); return (Filter) filter.accept(visitor, null); } public ServiceInfo getInfo() { return wrapped.getInfo(); } /** * Delegates to {@link #getFeatureSource(String)} with * {@code name.getLocalPart()} * * @since 2.5 * @see DataAccess#getFeatureSource(Name) */ public SimpleFeatureSource getFeatureSource(Name typeName) throws IOException { return getFeatureSource(typeName.getLocalPart()); } /** * Returns the same list of names than {@link #getTypeNames()} meaning the * returned Names have no namespace set. * * @since 1.7 * @see DataAccess#getNames() */ public List<Name> getNames() throws IOException { String[] typeNames = getTypeNames(); List<Name> names = new ArrayList<Name>(typeNames.length); for (String typeName : typeNames) { names.add(new NameImpl(typeName)); } return names; } /** * Delegates to {@link #getSchema(String)} with {@code name.getLocalPart()} * * @since 1.7 * @see DataAccess#getSchema(Name) */ public SimpleFeatureType getSchema(Name name) throws IOException { return getSchema(name.getLocalPart()); } /** * Delegates to {@link #updateSchema(String, SimpleFeatureType)} with * {@code name.getLocalPart()} * * @since 1.7 * @see DataAccess#getFeatureSource(Name) */ public void updateSchema(Name typeName, SimpleFeatureType featureType) throws IOException { updateSchema(typeName.getLocalPart(), featureType); } } diff --git a/src/main/src/main/java/org/geoserver/security/decorators/DecoratingDataStore.java b/src/main/src/main/java/org/geoserver/security/decorators/DecoratingDataStore.java index 700ae88e29..412dcdfc67 100644 --- a/src/main/src/main/java/org/geoserver/security/decorators/DecoratingDataStore.java +++ b/src/main/src/main/java/org/geoserver/security/decorators/DecoratingDataStore.java @@ -1,112 +1,107 @@ /* Copyright (c) 2001 - 2007 TOPP - www.openplans.org. All rights reserved. * This code is licensed under the GPL 2.0 license, available at the root * application directory. */ package org.geoserver.security.decorators; import java.io.IOException; import java.util.List; import org.geoserver.catalog.impl.AbstractDecorator; import org.geotools.data.DataStore; import org.geotools.data.FeatureReader; import org.geotools.data.FeatureWriter; import org.geotools.data.LockingManager; import org.geotools.data.Query; import org.geotools.data.ServiceInfo; import org.geotools.data.Transaction; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.feature.SchemaException; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.type.Name; import org.opengis.filter.Filter; /** * Delegates every method to the wrapped feature source. Subclasses will * override selected methods to perform their "decoration" job * * @author Andrea Aime - TOPP TODO: Move this class to gt2 */ public abstract class DecoratingDataStore extends AbstractDecorator<DataStore> implements DataStore { public DecoratingDataStore(DataStore delegate) { super(delegate); } public void createSchema(SimpleFeatureType featureType) throws IOException { delegate.createSchema(featureType); } public void dispose() { delegate.dispose(); } public FeatureReader<SimpleFeatureType, SimpleFeature> getFeatureReader(Query query, Transaction transaction) throws IOException { return delegate.getFeatureReader(query, transaction); } public SimpleFeatureSource getFeatureSource(Name typeName) throws IOException { return delegate.getFeatureSource(typeName); } public SimpleFeatureSource getFeatureSource(String typeName) throws IOException { return delegate.getFeatureSource(typeName); } public FeatureWriter<SimpleFeatureType, SimpleFeature> getFeatureWriter(String typeName, Filter filter, Transaction transaction) throws IOException { return delegate.getFeatureWriter(typeName, filter, transaction); } public FeatureWriter<SimpleFeatureType, SimpleFeature> getFeatureWriter(String typeName, Transaction transaction) throws IOException { return delegate.getFeatureWriter(typeName, transaction); } public FeatureWriter<SimpleFeatureType, SimpleFeature> getFeatureWriterAppend(String typeName, Transaction transaction) throws IOException { return delegate.getFeatureWriterAppend(typeName, transaction); } public ServiceInfo getInfo() { return delegate.getInfo(); } public LockingManager getLockingManager() { return delegate.getLockingManager(); } public List<Name> getNames() throws IOException { return delegate.getNames(); } public SimpleFeatureType getSchema(Name name) throws IOException { return delegate.getSchema(name); } public SimpleFeatureType getSchema(String typeName) throws IOException { return delegate.getSchema(typeName); } public String[] getTypeNames() throws IOException { return delegate.getTypeNames(); } - public SimpleFeatureSource getView(Query query) throws IOException, - SchemaException { - return delegate.getView(query); - } - public void updateSchema(Name typeName, SimpleFeatureType featureType) throws IOException { delegate.updateSchema(typeName, featureType); } public void updateSchema(String typeName, SimpleFeatureType featureType) throws IOException { delegate.updateSchema(typeName, featureType); } }
false
false
null
null
diff --git a/WEB-INF/src/edu/wustl/catissuecore/applet/model/SpecimenArrayTableModel.java b/WEB-INF/src/edu/wustl/catissuecore/applet/model/SpecimenArrayTableModel.java index 871ac4184..09f436059 100644 --- a/WEB-INF/src/edu/wustl/catissuecore/applet/model/SpecimenArrayTableModel.java +++ b/WEB-INF/src/edu/wustl/catissuecore/applet/model/SpecimenArrayTableModel.java @@ -1,245 +1,253 @@ /* * <p>Title: SpecimenArrayTableModel.java</p> * <p>Description: This class initializes the fields of SpecimenArrayTableModel.java</p> * Copyright: Copyright (c) year 2006 * Company: Washington University, School of Medicine, St. Louis. * @version 1.1 * Created on Sep 14, 2006 */ package edu.wustl.catissuecore.applet.model; import java.util.Map; import edu.wustl.catissuecore.applet.AppletConstants; import edu.wustl.catissuecore.applet.util.SpecimenArrayAppletUtil; /** * <p> * This model is used as table model for specimen array page table component.It is extending the base table * model.</p> * @author Ashwin Gupta * @version 1.1 * @see edu.wustl.catissuecore.appletui.model.BaseTabelModel */ public class SpecimenArrayTableModel extends BaseTabelModel { /** * Default Serial Version ID */ private static final long serialVersionUID = -6435519649631034159L; /** * specimenArrayModelMap - map is used to pass model */ private Map specimenArrayModelMap; /** * List of specimen array grid content POJOs */ // private List specimenArrayGridContentList; /** * row count */ private int rowCount; /** * column count */ private int columnCount; /** * column count */ private String copySelectedOption; /** * How specimens are entered either by Label/Barcode. */ private String enterSpecimenBy; /** * Specify the specimenClass field */ private String specimenClass; /** * Constructor to initialize array table model. * @param specimenArrayModelMap map of array model * @param rowCount row count * @param columnCount column count */ private SpecimenArrayTableModel(Map specimenArrayModelMap,int rowCount,int columnCount) { super(); this.specimenArrayModelMap = specimenArrayModelMap; // specimenArrayGridContentList = (List) specimenArrayModelMap.get(AppletConstants.ARRAY_GRID_COMPONENT_KEY); this.rowCount = rowCount; this.columnCount = columnCount; } /** * Constructor to initialize array table model. * @param specimenArrayModelMap map of array model * @param rowCount row count * @param columnCount column count * @param enterSpecimenBy how specimens are entered either by Label/Barcode. */ public SpecimenArrayTableModel(Map specimenArrayModelMap,int rowCount,int columnCount,String enterSpecimenBy,String specimenClass) { this(specimenArrayModelMap,rowCount,columnCount); this.enterSpecimenBy = enterSpecimenBy; this.specimenClass = specimenClass; } /** * @return specimenArrayModelMap */ public Map getSpecimenArrayModelMap() { return specimenArrayModelMap; } /** * set specimenArrayModelMap * @param specimenArrayModelMap */ public void setSpecimenArrayModelMap(Map specimenArrayModelMap) { this.specimenArrayModelMap = specimenArrayModelMap; } /** * @see javax.swing.table.TableModel#getColumnCount() */ public int getColumnCount() { return columnCount; } /** * @see javax.swing.table.TableModel#getRowCount() */ public int getRowCount() { return rowCount; } /** * @see javax.swing.table.TableModel#getValueAt(int, int) */ public Object getValueAt(int rowIndex, int columnIndex) { return specimenArrayModelMap.get(SpecimenArrayAppletUtil.getArrayMapKey(rowIndex,columnIndex,columnCount,getAttributeIndex())); } /** * @see javax.swing.table.TableModel#setValueAt(java.lang.Object, int, int) */ public void setValueAt(Object aValue, int rowIndex, int columnIndex) { specimenArrayModelMap.put(SpecimenArrayAppletUtil.getArrayMapKey(rowIndex,columnIndex,columnCount,getAttributeIndex()),aValue.toString()); // if one dimension & two dimension position is not set String posOneDimkey = SpecimenArrayAppletUtil.getArrayMapKey(rowIndex,columnIndex,columnCount,AppletConstants.ARRAY_CONTENT_ATTR_POS_DIM_ONE_INDEX); String posTwoDimkey = SpecimenArrayAppletUtil.getArrayMapKey(rowIndex,columnIndex,columnCount,AppletConstants.ARRAY_CONTENT_ATTR_POS_DIM_TWO_INDEX); if ((specimenArrayModelMap.get(posOneDimkey) == null) || (specimenArrayModelMap.get(posOneDimkey).toString().equals(""))) { specimenArrayModelMap.put(posOneDimkey,String.valueOf(rowIndex)); specimenArrayModelMap.put(posTwoDimkey,String.valueOf(columnIndex)); } } /** * @see javax.swing.table.TableModel#isCellEditable(int, int) */ public boolean isCellEditable(int rowIndex, int columnIndex) { return true; } /** * @see javax.swing.table.TableModel#getColumnName(int) */ public String getColumnName(int column) { return String.valueOf(column + 1); } /** * @return attribute index of array content attributes */ private int getAttributeIndex() { int attrIndex = 0; if (enterSpecimenBy.equals("Label")) { attrIndex = AppletConstants.ARRAY_CONTENT_ATTR_LABEL_INDEX; } else { attrIndex = AppletConstants.ARRAY_CONTENT_ATTR_BARCODE_INDEX; } return attrIndex; } /** * create specimen array grid content. * @return array grid content private SpecimenArrayGridContent createSpecimenArrayGridContent() { SpecimenArrayGridContent arrayGridContent = new SpecimenArrayGridContent(); return arrayGridContent; } */ /** * @return Returns the specimenClass. */ public String getSpecimenClass() { return specimenClass; } /** * @return Returns the copySelectedOption. */ public String getCopySelectedOption() { return copySelectedOption; } /** * @param copySelectedOption The copySelectedOption to set. */ public void setCopySelectedOption(String copySelectedOption) { this.copySelectedOption = copySelectedOption; } /** * @return Returns the enterSpecimenBy. */ public String getEnterSpecimenBy() { return enterSpecimenBy; } /** * @param enterSpecimenBy The enterSpecimenBy to set. */ public void setEnterSpecimenBy(String enterSpecimenBy) { this.enterSpecimenBy = enterSpecimenBy; } /** * change enter specimen by. * @param enterSpecimenBy enter specimen by */ public void changeEnterSpecimenBy(String enterSpecimenBy) { int attrIndex = 0; if (enterSpecimenBy.equals("Label")) { attrIndex = AppletConstants.ARRAY_CONTENT_ATTR_LABEL_INDEX; } else { attrIndex = AppletConstants.ARRAY_CONTENT_ATTR_BARCODE_INDEX; } - System.out.println(" In table model " + enterSpecimenBy); String value = null; + Object valueObj = null; for (int i=0; i < rowCount ; i++) { for (int j=0;j < columnCount; j++) { - value = getValueAt(i,j).toString(); - specimenArrayModelMap.put(SpecimenArrayAppletUtil.getArrayMapKey(i,j,columnCount,attrIndex),value); - // change old selction to "" - specimenArrayModelMap.put(SpecimenArrayAppletUtil.getArrayMapKey(i,j,columnCount,getAttributeIndex()),""); + valueObj = getValueAt(i,j); + if (valueObj == null) + { + value = String.valueOf(""); + } + else + { + value = valueObj.toString(); + } + specimenArrayModelMap.put(SpecimenArrayAppletUtil.getArrayMapKey(i,j,columnCount,attrIndex),value); + // change old selction to "" + specimenArrayModelMap.put(SpecimenArrayAppletUtil.getArrayMapKey(i,j,columnCount,getAttributeIndex()),""); } } this.enterSpecimenBy = enterSpecimenBy; } } diff --git a/WEB-INF/src/edu/wustl/catissuecore/applet/ui/SpecimenArrayApplet.java b/WEB-INF/src/edu/wustl/catissuecore/applet/ui/SpecimenArrayApplet.java index 27f629274..ccf053623 100644 --- a/WEB-INF/src/edu/wustl/catissuecore/applet/ui/SpecimenArrayApplet.java +++ b/WEB-INF/src/edu/wustl/catissuecore/applet/ui/SpecimenArrayApplet.java @@ -1,333 +1,342 @@ /* * <p>Title: SpecimenArrayApplet.java</p> * <p>Description: This class initializes the fields of SpecimenArrayApplet.java</p> * Copyright: Copyright (c) year 2006 * Company: Washington University, School of Medicine, St. Louis. * @version 1.1 * Created on Sep 18, 2006 */ /** * */ package edu.wustl.catissuecore.applet.ui; import java.awt.Dimension; import java.awt.FlowLayout; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.table.TableModel; import edu.wustl.catissuecore.applet.AppletConstants; import edu.wustl.catissuecore.applet.AppletServerCommunicator; import edu.wustl.catissuecore.applet.component.SpecimenArrayTable; import edu.wustl.catissuecore.applet.listener.ApplyButtonActionHandler; import edu.wustl.catissuecore.applet.listener.ArrayCopyOptionActionHandler; import edu.wustl.catissuecore.applet.listener.SpecimenArrayCopyMouseHandler; import edu.wustl.catissuecore.applet.listener.SpecimenArrayPasteActionHandler; import edu.wustl.catissuecore.applet.model.AppletModelInterface; import edu.wustl.catissuecore.applet.model.BaseAppletModel; import edu.wustl.catissuecore.applet.model.SpecimenArrayTableModel; /** * <p>This class specifies the methods used to render specimen array applet.It is extending * BaseApplet class. * </p> * @author Ashwin Gupta * @version 1.1 */ public class SpecimenArrayApplet extends BaseApplet { /** * Default Serial Version ID */ private static final long serialVersionUID = 1L; /** * Specify the quantityTextField field */ private JTextField quantityTextField = null; /** * Specify the concentrationTextField field */ private JTextField concentrationTextField = null; /** * Specify the applyButton field */ private JButton applyButton = null; /** * Specify the copyButton field */ JButton copyButton = null; /** * Specify the pasteButton field */ JButton pasteButton = null; private SpecimenArrayTable arrayTable = null; /** * Specify the session_id field */ String session_id = null; /** * Specify the enterSpecimenBy field */ String enterSpecimenBy = null; /** * @see edu.wustl.catissuecore.appletui.applet.BaseApplet#doInit() */ protected void doInit() { super.doInit(); // /* int rowCount = 3; int columnCount = 3; String specimenClass = "Molecular"; Map tableModelMap = new HashMap(); String enterSpecimenBy = "Label"; */ session_id = getParameter("session_id"); int rowCount = new Integer(getParameter("rowCount")).intValue(); int columnCount = new Integer(getParameter("columnCount")).intValue(); String specimenClass = getParameter("specimenClass"); enterSpecimenBy = getParameter("enterSpecimenBy"); Map tableModelMap = getTableModelData(); JLabel concLabel = new JLabel("Concentration"); concLabel.setOpaque(false); JLabel quantityLabel = new JLabel("Quantity"); quantityLabel.setOpaque(false); concentrationTextField = new JTextField(); concentrationTextField.setName("concentrationTextField"); concentrationTextField.setEnabled(false); Dimension concDimension = new Dimension(100,concentrationTextField.getPreferredSize().height); concentrationTextField.setPreferredSize(concDimension); JPanel concPanel = new JPanel(); concPanel.setOpaque(false); concPanel.setLayout(new FlowLayout(FlowLayout.LEFT,5,0)); concPanel.add(concLabel); concPanel.add(concentrationTextField); quantityTextField = new JTextField(); quantityTextField.setName("quantityTextField"); quantityTextField.setEnabled(false); Dimension quantityDimension = new Dimension(100,quantityTextField.getPreferredSize().height); quantityTextField.setPreferredSize(quantityDimension); //System.out.println(quantityTextField.getPreferredSize()); JPanel quantityPanel = new JPanel(); quantityPanel.setOpaque(false); quantityPanel.setLayout(new FlowLayout(FlowLayout.LEFT,5,0)); quantityPanel.add(quantityLabel); quantityPanel.add(quantityTextField); applyButton = new JButton("Apply"); applyButton.setEnabled(false); JPanel applyPanel = new JPanel(); applyPanel.setBackground(AppletConstants.BG_COLOR); //applyPanel.setOpaque(false); applyPanel.setLayout(new FlowLayout(FlowLayout.LEFT,10,0)); applyPanel.add(concPanel); applyPanel.add(quantityPanel); applyPanel.add(applyButton); TableModel tableModel = new SpecimenArrayTableModel(tableModelMap,rowCount,columnCount,enterSpecimenBy,specimenClass); arrayTable = new SpecimenArrayTable(tableModel); arrayTable.setOpaque(false); arrayTable.getColumnModel().setColumnSelectionAllowed(true); arrayTable.setCellSelectionEnabled(true); arrayTable.setRowSelectionAllowed(true); arrayTable.getColumnModel().getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); JScrollPane scrollPane = new JScrollPane(arrayTable); scrollPane.setPreferredSize(new Dimension(100,100)); scrollPane.setOpaque(false); //scrollPane.setBackground(Color.WHITE); scrollPane.getViewport().setBackground(AppletConstants.BG_COLOR); applyButton.addActionListener(new ApplyButtonActionHandler(arrayTable)); JPopupMenu popupMenu = new JPopupMenu(); ArrayCopyOptionActionHandler actionHandler = new ArrayCopyOptionActionHandler(arrayTable); JMenuItem labelMenuItem = new JMenuItem(AppletConstants.ARRAY_COPY_OPTION_LABELBAR); labelMenuItem.addActionListener(actionHandler); JMenuItem quantityMenuItem = new JMenuItem(AppletConstants.ARRAY_COPY_OPTION_QUANTITY); quantityMenuItem.addActionListener(actionHandler); JMenuItem concMenuItem = new JMenuItem(AppletConstants.ARRAY_COPY_OPTION_CONCENTRATION); concMenuItem.addActionListener(actionHandler); JMenuItem allMenuItem = new JMenuItem(AppletConstants.ARRAY_COPY_OPTION_ALL); allMenuItem.addActionListener(actionHandler); if (!specimenClass.equalsIgnoreCase("Molecular")) { quantityMenuItem.setEnabled(false); concMenuItem.setEnabled(false); } popupMenu.add(labelMenuItem); popupMenu.add(quantityMenuItem); popupMenu.add(concMenuItem); popupMenu.add(allMenuItem); copyButton = new JButton("Copy"); //copyButton.addActionListener(new SpecimenArrayCopyActionHandler(popupMenu)); copyButton.addMouseListener(new SpecimenArrayCopyMouseHandler(popupMenu)); applyPanel.add(copyButton); pasteButton = new JButton("Paste"); pasteButton.addActionListener(new SpecimenArrayPasteActionHandler(arrayTable)); applyPanel.add(pasteButton); copyButton.setEnabled(false); pasteButton.setEnabled(false); //System.out.println(" decrease gap :: 10"); this.getContentPane().setLayout(new VerticalLayout(0,10)); this.getContentPane().add(applyPanel); this.getContentPane().add(scrollPane); this.getContentPane().setBackground(AppletConstants.BG_COLOR); } /** * Gets table model data * @return table data map */ private Map getTableModelData() { Map tableDataMap = null; String urlString = serverURL + AppletConstants.SPECIMEN_ARRAY_APPLET_ACTION + ";jsessionid="+session_id+"?" + AppletConstants.APPLET_ACTION_PARAM_NAME + "=getArrayData"; AppletModelInterface model = new BaseAppletModel(); model.setData(new HashMap()); try { model = (AppletModelInterface) AppletServerCommunicator.doAppletServerCommunication(urlString,model); tableDataMap = model.getData(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return tableDataMap; } /** * update session data */ public void updateSessionData() { // set last cell data setLastCellData(); String urlString = serverURL + AppletConstants.SPECIMEN_ARRAY_APPLET_ACTION + ";jsessionid="+session_id+"?" + AppletConstants.APPLET_ACTION_PARAM_NAME + "=updateSessionData"; AppletModelInterface model = new BaseAppletModel(); Map arrayContentDataMap = ((SpecimenArrayTableModel) arrayTable.getModel()).getSpecimenArrayModelMap(); model.setData(arrayContentDataMap); try { model = (AppletModelInterface) AppletServerCommunicator.doAppletServerCommunication(urlString,model); //arrayContentDataMap = model.getData(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * Set Last Cell Data */ private void setLastCellData() { int selectedRow = arrayTable.getSelectedRow(); int selectedColumn = arrayTable.getSelectedColumn(); - arrayTable.getCellEditor(selectedRow,selectedColumn).stopCellEditing(); + /* + System.out.println(" model map:: " + ((SpecimenArrayTableModel) arrayTable.getModel()).getSpecimenArrayModelMap()); + System.out.println(" selectedRow " + selectedRow); + System.out.println(" selectedColumn " + selectedColumn); + */ + if ((selectedRow > -1) && (selectedColumn > -1) && (selectedRow <= arrayTable.getRowCount()) && (selectedColumn <= arrayTable.getColumnCount())) + { + arrayTable.getCellEditor(selectedRow,selectedColumn).stopCellEditing(); + } + //System.out.println(" after stopping model map:: " + ((SpecimenArrayTableModel) arrayTable.getModel()).getSpecimenArrayModelMap()); } /** * @param enterSpecimenBy enter specimen by */ public void changeEnterSpecimenBy(String enterSpecimenBy) { System.out.println(" Enter Specimen By " + enterSpecimenBy); this.enterSpecimenBy = enterSpecimenBy; ((SpecimenArrayTableModel) arrayTable.getModel()).changeEnterSpecimenBy(enterSpecimenBy); } /** * @return Returns the concentrationTextField. */ public JTextField getConcentrationTextField() { return concentrationTextField; } /** * @param concentrationTextField The concentrationTextField to set. */ public void setConcentrationTextField(JTextField concentrationTextField) { this.concentrationTextField = concentrationTextField; } /** * @return Returns the quantityTextField. */ public JTextField getQuantityTextField() { return quantityTextField; } /** * @param quantityTextField The quantityTextField to set. */ public void setQuantityTextField(JTextField quantityTextField) { this.quantityTextField = quantityTextField; } /** * @return Returns the applyButton. */ public JButton getApplyButton() { return applyButton; } /** * @param applyButton The applyButton to set. */ public void setApplyButton(JButton applyButton) { this.applyButton = applyButton; } /** * @return Returns the copyButton. */ public JButton getCopyButton() { return copyButton; } /** * @return Returns the pasteButton. */ public JButton getPasteButton() { return pasteButton; } }
false
false
null
null
diff --git a/jfugue/src/org/jfugue/Player.java b/jfugue/src/org/jfugue/Player.java index cc84cbd..b8b5d6a 100644 --- a/jfugue/src/org/jfugue/Player.java +++ b/jfugue/src/org/jfugue/Player.java @@ -1,642 +1,645 @@ /* * JFugue - API for Music Programming * Copyright (C) 2003-2008 David Koelle * * http://www.jfugue.org * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jfugue; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Map; import javax.sound.midi.InvalidMidiDataException; import javax.sound.midi.MetaEventListener; import javax.sound.midi.MetaMessage; import javax.sound.midi.MidiChannel; import javax.sound.midi.MidiFileFormat; import javax.sound.midi.MidiSystem; import javax.sound.midi.MidiUnavailableException; import javax.sound.midi.Sequence; import javax.sound.midi.Sequencer; import javax.sound.midi.Synthesizer; import org.jfugue.parsers.MidiParser; import org.jfugue.parsers.MusicStringParser; import org.jfugue.parsers.Parser; /** * Prepares a pattern to be turned into music by the Renderer. This class * also handles saving the sequence derived from a pattern as a MIDI file. * *@see MidiRenderer *@see Pattern *@author David Koelle *@version 2.0 */ public class Player { private Sequencer sequencer; + private Synthesizer synth; private MusicStringParser parser; private MidiRenderer renderer; private float sequenceTiming = Sequence.PPQ; private int resolution = 128; private volatile boolean paused = false; private volatile boolean started = false; private volatile boolean finished = false; // @SuppressWarnings("unused") // private Map rememberedPatterns; /** * Instantiates a new Player object, which is used for playing music. */ public Player() { this(true); } /** * Instantiates a new Player object, which is used for playing music. * The <code>connected</code> parameter is passed directly to MidiSystem.getSequencer. * Pass false when you do not want to copy a live synthesizer - for example, * if your Player is on a server, and you don't want to create new synthesizers every time * the constructor is called. */ public Player(boolean connected) { try { // Get default sequencer. setSequencer(MidiSystem.getSequencer(connected)); // use non connected sequencer so no copy of live synthesizer will be created. } catch (MidiUnavailableException e) { throw new JFugueException(JFugueException.SEQUENCER_DEVICE_NOT_SUPPORTED_WITH_EXCEPTION + e.getMessage()); } initParser(); } /** * Creates a new Player instance using a Sequencer that you have provided. * @param sequencer The Sequencer to send the MIDI events */ public Player(Sequencer sequencer) { setSequencer(sequencer); initParser(); } /** * Creates a new Player instance using a Sequencer obtained from the Synthesizer that you have provided. * @param synth The Synthesizer you want to use for this Player. */ public Player(Synthesizer synth) throws MidiUnavailableException { this(Player.getSequencerConnectedToSynthesizer(synth)); + this.synth = synth; } private void initParser() { this.parser = new MusicStringParser(); this.renderer = new MidiRenderer(sequenceTiming, resolution); this.parser.addParserListener(this.renderer); } private void initSequencer() { // Close the sequencer and synthesizer getSequencer().addMetaEventListener(new MetaEventListener() { public void meta(MetaMessage event) { if (event.getType() == 47) { close(); } } }); } private void openSequencer() { if (getSequencer() == null) { throw new JFugueException(JFugueException.SEQUENCER_DEVICE_NOT_SUPPORTED); } // Open the sequencer, if it is not already open if (!getSequencer().isOpen()) { try { getSequencer().open(); } catch (MidiUnavailableException e) { throw new JFugueException(JFugueException.SEQUENCER_DEVICE_NOT_SUPPORTED_WITH_EXCEPTION + e.getMessage()); } } } /** * Returns the instance of the MusicStringParser that the Player uses to parse * music strings. You can attach additional ParserListeners to this Parser to * know exactly when musical events are taking place. (Similarly, you could * create an Anticipator with a delay of 0, but this is much more direct). * * You could also remove the Player's default MidiRenderer from this Parser. * * @return instance of this Player's MusicStringParser */ public Parser getParser() { return this.parser; } /** * Allows you to set the MusicStringParser for this Player. You shouldn't use this unless * you definitely want to hijack the Player's MusicStringParser. You might decide to do this * if you're creating a new subclass of MusicStringParser to test out some new functionality. * Or, you might have set up a MusicStringParser with an assortment of ParserListeners and * you want to use those listeners instead of Player's default listener (although really, you * should call getParser() and add your listeners to that parser). * * @param parser Your new instance of a MusicStringParser */ public void setParser(MusicStringParser parser) { this.parser = parser; } /** * Returns the MidiRenderer that this Player will use to play MIDI events. * @return the MidiRenderer that this Player will use to play MIDI events */ public ParserListener getParserListener() { return this.renderer; } /** * Plays a pattern by setting up a Renderer and feeding the pattern to it. * @param pattern the pattern to play * @see MidiRenderer */ public void play(PatternInterface pattern) { Sequence sequence = getSequence(pattern); play(sequence); } /** * Appends together and plays all of the patterns passed in. * @param patterns the patterns to play * @see MidiRenderer */ public void play(Pattern... patterns) { PatternInterface allPatterns = new Pattern(); for (Pattern p : patterns) { allPatterns.add(p); } play(allPatterns); } /** * Replaces pattern identifiers with patterns from the map. * @param context A map of pattern identifiers to Pattern objects * @param pattern The pattern to play */ public void play(Map<String, Pattern> context, PatternInterface pattern) { PatternInterface contextPattern = Pattern.createPattern(context, pattern); play(contextPattern); } /** * Appends together and plays all of the patterns passed in, replacing * pattern identifiers with actual patterns from the map. * @param context A map of pattern identifiers to Pattern objects * @param patterns The patterns to play */ public void play(Map<String, Pattern> context, Pattern... patterns) { PatternInterface contextPattern = Pattern.createPattern(context, patterns); play(contextPattern); } /** * Plays a {@link Rhythm} by setting up a Renderer and feeding the {@link Rhythm} to it. * @param rhythm the {@link Rhythm} to play * @see MidiRenderer */ public void play(Rhythm rhythm) { PatternInterface pattern = rhythm.getPattern(); Sequence sequence = getSequence(pattern); play(sequence); } /** * Plays a MIDI Sequence * @param sequence the Sequence to play * @throws JFugueException if there is a problem playing the music * @see MidiRenderer */ public void play(Sequence sequence) { // Open the sequencer openSequencer(); intentionalDelay(); System.out.println("Seq is "+sequence); // Set the sequence try { getSequencer().setSequence(sequence); } catch (Exception e) { throw new JFugueException(JFugueException.ERROR_PLAYING_MUSIC + e.getMessage()); } setStarted(true); // Start the sequence getSequencer().start(); // Wait for the sequence to finish while (isOn()) { try { Thread.sleep(20); // don't hog all of the CPU } catch (InterruptedException e) { try { stop(); } catch (Exception e2) { // do nothing } throw new JFugueException(JFugueException.ERROR_SLEEP); } } // Close the sequencer getSequencer().close(); intentionalDelay(); setStarted(false); setFinished(true); } /** * Ugliness here! Why do we need an Intentional Delay? * Well, it turns out that getSequencer().open() and getSequencer().close() * within javax.sound.midi are happening asynchronously, and this delay * makes things happy enough that: * - Music strings don't skip (which you'll see if you take out the delay, and call * player.play("some music string") in a while loop) * - We don't get an IllegalArgumentException by trying to send a sequence to a sequencer * that, despite openSequencer() having just been called, apparently isn't actually open */ private void intentionalDelay() { try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } private synchronized boolean isOn() { return isPlaying() || isPaused(); } /** * Plays a string of music. Be sure to call player.close() after play() has returned. * @param musicString the MusicString (JFugue-formatted string) to play */ public void play(String musicString) { if (musicString.indexOf(".mid") > 0) { // If the user tried to call this method with "filename.mid" or "filename.midi", throw the following exception throw new JFugueException(JFugueException.PLAYS_STRING_NOT_FILE_EXC); } PatternInterface pattern = new Pattern(musicString); play(pattern); } /** * Plays a MIDI file, without doing any conversions to MusicStrings. * Be sure to call player.close() after play() has returned. * @param file the MIDI file to play * @throws IOException * @throws InvalidMidiDataException */ public void playMidiDirectly(File file) throws IOException, InvalidMidiDataException { Sequence sequence = MidiSystem.getSequence(file); play(sequence); } /** * Plays a URL that contains a MIDI sequence. Be sure to call player.close() after play() has returned. * @param url the URL to play * @throws IOException * @throws InvalidMidiDataException */ public void playMidiDirectly(URL url) throws IOException, InvalidMidiDataException { Sequence sequence = MidiSystem.getSequence(url); play(sequence); } public void play(Anticipator anticipator, PatternInterface pattern, long offset) { Sequence sequence = getSequence(pattern); Sequence sequence2 = getSequence(pattern); play(anticipator, sequence, sequence2, offset); } public void play(Anticipator anticipator, Sequence sequence, Sequence sequence2, long offset) { anticipator.play(sequence); if (offset > 0) { try { Thread.sleep(offset); } catch (InterruptedException e) { throw new JFugueException(JFugueException.ERROR_SLEEP); } } play(sequence2); } /** * Convenience method for playing multiple patterns simultaneously. Assumes that * the patterns do not contain Voice tokens (such as "V0"). Assigns each pattern * a voice, from 0 through 15, except 9 (which is the percussion track). For this * reason, if more than 15 patterns are passed in, an IllegalArgumentException is thrown. * * @param patterns The patterns to play in harmony * @return The combined pattern, including voice tokens */ public PatternInterface playInHarmony(Pattern... patterns) { if (patterns.length > 15) { throw new IllegalArgumentException("playInHarmony no more than 15 patterns; "+patterns.length+" were passed in"); } PatternInterface retVal = new Pattern(); int voice = 0; for (int i=0; i < patterns.length; i++) { retVal.add("V"+voice); retVal.add(patterns[i]); voice++; if (voice == 9) { voice = 10; } } play(retVal); return retVal; } /** * Closes MIDI resources - be sure to call this after play() has returned. */ public void close() { getSequencer().close(); try { - // TODO: This is a potential bug, if the Player has been passed in a Synthesizer - if (MidiSystem.getSynthesizer() != null) { + if (synth != null) { + synth.close(); + } else if (MidiSystem.getSynthesizer() != null) { MidiSystem.getSynthesizer().close(); } } catch (MidiUnavailableException e) { throw new JFugueException(JFugueException.GENERAL_ERROR + e.getMessage()); } } private void setStarted(boolean started) { this.started = started; } private void setFinished(boolean finished) { this.finished = finished; } public boolean isStarted() { return this.started; } public boolean isFinished() { return this.finished; } public boolean isPlaying() { return getSequencer().isRunning(); } public boolean isPaused() { return paused; } public synchronized void pause() { paused = true; if (isPlaying()) { getSequencer().stop(); } } public synchronized void resume() { paused = false; getSequencer().start(); } public synchronized void stop() { paused = false; getSequencer().stop(); getSequencer().setMicrosecondPosition(0); } public void jumpTo(long microseconds) { getSequencer().setMicrosecondPosition(microseconds); } public long getSequenceLength(Sequence sequence) { return sequence.getMicrosecondLength(); } public long getSequencePosition() { return getSequencer().getMicrosecondPosition(); } /** * Saves the MIDI data from a pattern into a file. * @param pattern the pattern to save * @param file the File to save the pattern to. Should include file extension, such as .mid */ public void saveMidi(PatternInterface pattern, File file) throws IOException { Sequence sequence = getSequence(pattern); int[] writers = MidiSystem.getMidiFileTypes(sequence); if (writers.length == 0) return; MidiSystem.write(sequence, writers[0], file); } /** * Saves the MIDI data from a MusicString into a file. * @param musicString the MusicString to save * @param file the File to save the MusicString to. Should include file extension, such as .mid */ public void saveMidi(String musicString, File file) throws IOException { PatternInterface pattern = new Pattern(musicString); saveMidi(pattern, file); } /** * Parses a MIDI file and returns a Pattern representing the MIDI file. * This is an excellent example of JFugue's Parser-Renderer architecture: * * <pre> * MidiParser parser = new MidiParser(); * MusicStringRenderer renderer = new MusicStringRenderer(); * parser.addParserListener(renderer); * parser.parse(sequence); * </pre> * * @param file The name of the MIDI file * @return a Pattern containing the MusicString representing the MIDI music * @throws IOException If there is a problem opening the MIDI file * @throws InvalidMidiDataException If there is a problem obtaining MIDI resources */ public PatternInterface loadMidi(File file) throws IOException, InvalidMidiDataException { MidiFileFormat format = MidiSystem.getMidiFileFormat(file); this.sequenceTiming = format.getDivisionType(); this.resolution = format.getResolution(); MidiParser parser = new MidiParser(); MusicStringRenderer renderer = new MusicStringRenderer(); parser.addParserListener(renderer); parser.parse(MidiSystem.getSequence(file)); PatternInterface pattern = new Pattern(renderer.getPattern().getMusicString()); return pattern; } /** * Stops all notes from playing on all MIDI channels. * Uses the synthesizer provided by MidiSystem.getSynthesizer(). */ public static void allNotesOff() { try { - // TODO: This is a potential bug, if the Player has been passed in a Synthesizer allNotesOff(MidiSystem.getSynthesizer()); } catch (MidiUnavailableException e) { throw new JFugueException(JFugueException.GENERAL_ERROR); } } /** * Stops all notes from playing on all MIDI channels. + * Uses the synthesizer provided to the method. */ public static void allNotesOff(Synthesizer synth) { try { if (!synth.isOpen()) { synth.open(); } MidiChannel[] channels = synth.getChannels(); for (int i=0; i < channels.length; i++) { channels[i].allNotesOff(); } } catch (MidiUnavailableException e) { throw new JFugueException(JFugueException.GENERAL_ERROR); } } /** * Returns the sequencer containing the MIDI data from a pattern that has been parsed. * @return the Sequencer from the pattern that was recently parsed */ public Sequencer getSequencer() { return this.sequencer; } private void setSequencer(Sequencer sequencer) { this.sequencer = sequencer; initSequencer(); } /** * Returns the sequence containing the MIDI data from the given pattern. * @return the Sequence from the given pattern */ public Sequence getSequence(PatternInterface pattern) { this.renderer.reset(); this.parser.parse(pattern); Sequence sequence = this.renderer.getSequence(); return sequence; } /** * Returns an instance of a Sequencer that uses the provided Synthesizer as its receiver. * This is useful when you have made changes to a specific Synthesizer--for example, you've * loaded in new patches--that you want the Sequencer to use. You can then pass the Sequencer * to the Player constructor. * * @param synth The Synthesizer to use as the receiver for the returned Sequencer * @return a Sequencer with the provided Synthesizer as its receiver * @throws MidiUnavailableException */ public static Sequencer getSequencerConnectedToSynthesizer(Synthesizer synth) throws MidiUnavailableException { Sequencer sequencer = MidiSystem.getSequencer(false); // Get Sequencer which is not connected to new Synthesizer. sequencer.open(); if (!synth.isOpen()) { synth.open(); } sequencer.getTransmitter().setReceiver(synth.getReceiver()); // Connect the Synthesizer to our synthesizer instance. return sequencer; } } \ No newline at end of file
false
false
null
null
diff --git a/src/com/paypal/core/Constants.java b/src/com/paypal/core/Constants.java index bf86cd3..fed9f24 100644 --- a/src/com/paypal/core/Constants.java +++ b/src/com/paypal/core/Constants.java @@ -1,11 +1,11 @@ package com.paypal.core; public class Constants { public static final String ENCODING_FORMAT = "UTF8"; public static final String EMPTY_STRING = ""; public static final String ACCCOUT_PREFIX = "acct"; public static final String SANDBOX_EMAIL_ADDRESS = "[email protected]"; public static final String SOAP = "SOAP"; public static final String SDK_NAME = "sdk-buttonmanager-java"; - public static final String SDK_VERSION = "0.7.88"; + public static final String SDK_VERSION = "0.8.88"; }
true
false
null
null
diff --git a/src/net/java/sip/communicator/impl/gui/GuiActivator.java b/src/net/java/sip/communicator/impl/gui/GuiActivator.java index ff324785d..66af4a650 100644 --- a/src/net/java/sip/communicator/impl/gui/GuiActivator.java +++ b/src/net/java/sip/communicator/impl/gui/GuiActivator.java @@ -1,915 +1,932 @@ /* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.gui; import java.util.*; import net.java.sip.communicator.impl.gui.main.account.*; import net.java.sip.communicator.impl.gui.main.contactlist.*; import net.java.sip.communicator.impl.gui.utils.*; import net.java.sip.communicator.service.audionotifier.*; import net.java.sip.communicator.service.browserlauncher.*; import net.java.sip.communicator.service.callhistory.*; import net.java.sip.communicator.service.configuration.*; import net.java.sip.communicator.service.contactlist.*; import net.java.sip.communicator.service.contactsource.*; import net.java.sip.communicator.service.desktop.*; import net.java.sip.communicator.service.fileaccess.*; import net.java.sip.communicator.service.gui.*; import net.java.sip.communicator.service.keybindings.*; import net.java.sip.communicator.service.metahistory.*; import net.java.sip.communicator.service.neomedia.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.replacement.*; import net.java.sip.communicator.service.replacement.smilies.*; import net.java.sip.communicator.service.resources.*; import net.java.sip.communicator.service.shutdown.*; import net.java.sip.communicator.service.systray.*; import net.java.sip.communicator.util.*; import org.osgi.framework.*; /** * The GUI Activator class. * * @author Yana Stamcheva */ public class GuiActivator implements BundleActivator { /** * The <tt>Logger</tt> used by the <tt>GuiActivator</tt> class and its * instances for logging output. */ private static final Logger logger = Logger.getLogger(GuiActivator.class); private static UIServiceImpl uiService = null; /** * OSGi bundle context. */ public static BundleContext bundleContext; private static ConfigurationService configService; private static MetaHistoryService metaHistoryService; private static MetaContactListService metaCListService; private static CallHistoryService callHistoryService; private static AudioNotifierService audioNotifierService; private static BrowserLauncherService browserLauncherService; private static SystrayService systrayService; private static ResourceManagementService resourcesService; private static KeybindingsService keybindingsService; private static FileAccessService fileAccessService; private static DesktopService desktopService; private static MediaService mediaService; private static SmiliesReplacementService smiliesService; private static PhoneNumberI18nService phoneNumberService; private static AccountManager accountManager; private static List<ContactSourceService> contactSources; private static SecurityAuthority securityAuthority; private static final Map<Object, ProtocolProviderFactory> providerFactoriesMap = new Hashtable<Object, ProtocolProviderFactory>(); private static final Map<String, ReplacementService> replacementSourcesMap = new Hashtable<String, ReplacementService>(); /** * Indicates if this bundle has been started. */ public static boolean isStarted = false; /** * The contact list object. */ private static TreeContactList contactList; /** * Called when this bundle is started. * * @param bContext The execution context of the bundle being started. * @throws Exception if the bundle is not correctly started */ public void start(BundleContext bContext) throws Exception { isStarted = true; GuiActivator.bundleContext = bContext; ConfigurationManager.loadGuiConfigurations(); try { // Create the ui service uiService = new UIServiceImpl(); uiService.loadApplicationGui(); if (logger.isInfoEnabled()) logger.info("UI Service...[ STARTED ]"); bundleContext.registerService(UIService.class.getName(), uiService, null); if (logger.isInfoEnabled()) logger.info("UI Service ...[REGISTERED]"); // UIServiceImpl also implements ShutdownService. bundleContext.registerService(ShutdownService.class.getName(), (ShutdownService) uiService, null); logger.logEntry(); } finally { logger.logExit(); } GuiActivator.getConfigurationService() .addPropertyChangeListener(uiService); bundleContext.addServiceListener(uiService); } /** * Called when this bundle is stopped so the Framework can perform the * bundle-specific activities necessary to stop the bundle. * * @param bContext The execution context of the bundle being stopped. * @throws Exception If this method throws an exception, the bundle is * still marked as stopped, and the Framework will remove the bundle's * listeners, unregister all services registered by the bundle, and * release all services used by the bundle. */ public void stop(BundleContext bContext) throws Exception { if (logger.isInfoEnabled()) logger.info("UI Service ...[STOPPED]"); isStarted = false; GuiActivator.getConfigurationService() .removePropertyChangeListener(uiService); bContext.removeServiceListener(uiService); } /** * Returns all <tt>ProtocolProviderFactory</tt>s obtained from the bundle * context. * * @return all <tt>ProtocolProviderFactory</tt>s obtained from the bundle * context */ public static Map<Object, ProtocolProviderFactory> getProtocolProviderFactories() { ServiceReference[] serRefs = null; try { // get all registered provider factories serRefs = bundleContext.getServiceReferences( ProtocolProviderFactory.class.getName(), null); } catch (InvalidSyntaxException e) { logger.error("LoginManager : " + e); } if (serRefs != null) { for (ServiceReference serRef : serRefs) { ProtocolProviderFactory providerFactory = (ProtocolProviderFactory) bundleContext.getService(serRef); providerFactoriesMap.put( serRef.getProperty(ProtocolProviderFactory.PROTOCOL), providerFactory); } } return providerFactoriesMap; } /** * Returns a <tt>ProtocolProviderFactory</tt> for a given protocol * provider. * @param protocolProvider the <tt>ProtocolProviderService</tt>, which * factory we're looking for * @return a <tt>ProtocolProviderFactory</tt> for a given protocol * provider */ public static ProtocolProviderFactory getProtocolProviderFactory( ProtocolProviderService protocolProvider) { return getProtocolProviderFactory(protocolProvider.getProtocolName()); } /** * Returns a <tt>ProtocolProviderFactory</tt> for a given protocol * provider. * @param protocolName the name of the protocol * @return a <tt>ProtocolProviderFactory</tt> for a given protocol * provider */ public static ProtocolProviderFactory getProtocolProviderFactory( String protocolName) { String osgiFilter = "(" + ProtocolProviderFactory.PROTOCOL + "="+protocolName+")"; ProtocolProviderFactory protocolProviderFactory = null; try { ServiceReference[] serRefs = bundleContext.getServiceReferences( ProtocolProviderFactory.class.getName(), osgiFilter); if (serRefs != null && serRefs.length > 0) protocolProviderFactory = (ProtocolProviderFactory) bundleContext .getService(serRefs[0]); } catch (InvalidSyntaxException ex) { logger.error("GuiActivator : " + ex); } return protocolProviderFactory; } /** * Returns the <tt>ProtocolProviderService</tt> corresponding to the given * account identifier that is registered in the given factory * @param accountID the identifier of the account * @return the <tt>ProtocolProviderService</tt> corresponding to the given * account identifier that is registered in the given factory */ public static ProtocolProviderService getRegisteredProviderForAccount( AccountID accountID) { for (ProtocolProviderFactory factory : getProtocolProviderFactories().values()) { if (factory.getRegisteredAccounts().contains(accountID)) { ServiceReference serRef = factory.getProviderForAccount(accountID); if (serRef != null) { return (ProtocolProviderService) bundleContext.getService(serRef); } } } return null; } /** * Returns a list of all currently registered telephony providers for the * given protocol name. * @param protocolName the protocol name * @param operationSetClass the operation set class for which we're looking * for providers * @return a list of all currently registered providers for the given * <tt>protocolName</tt> and supporting the given <tt>operationSetClass</tt> */ public static List<ProtocolProviderService> getRegisteredProviders( String protocolName, Class<? extends OperationSet> operationSetClass) { List<ProtocolProviderService> opSetProviders = new LinkedList<ProtocolProviderService>(); ProtocolProviderFactory providerFactory = GuiActivator.getProtocolProviderFactory(protocolName); if (providerFactory != null) { ServiceReference serRef; ProtocolProviderService protocolProvider; for (AccountID accountID : providerFactory.getRegisteredAccounts()) { serRef = providerFactory.getProviderForAccount(accountID); protocolProvider = (ProtocolProviderService) GuiActivator.bundleContext .getService(serRef); if (protocolProvider.getOperationSet(operationSetClass) != null && protocolProvider.isRegistered()) { opSetProviders.add(protocolProvider); } } } return opSetProviders; } /** * Returns a list of all currently registered providers, which support the * given <tt>operationSetClass</tt>. * * @param opSetClass the operation set class for which we're looking * for providers * @return a list of all currently registered providers, which support the * given <tt>operationSetClass</tt> */ public static List<ProtocolProviderService> getRegisteredProviders( Class<? extends OperationSet> opSetClass) { List<ProtocolProviderService> opSetProviders = new LinkedList<ProtocolProviderService>(); for (ProtocolProviderFactory providerFactory : GuiActivator .getProtocolProviderFactories().values()) { ServiceReference serRef; ProtocolProviderService protocolProvider; for (AccountID accountID : providerFactory.getRegisteredAccounts()) { serRef = providerFactory.getProviderForAccount(accountID); protocolProvider = (ProtocolProviderService) GuiActivator.bundleContext .getService(serRef); if (protocolProvider.getOperationSet(opSetClass) != null && protocolProvider.isRegistered()) { opSetProviders.add(protocolProvider); } } } return opSetProviders; } /** * Returns a list of all registered protocol providers that could be used * for the operation given by the operation set. Prefers the given preferred * protocol provider and preferred protocol name if they're available and * registered. * * @param opSet * @param preferredProvider * @param preferredProtocolName * @return a list of all registered protocol providers that could be used * for the operation given by the operation set */ public static List<ProtocolProviderService> getOpSetRegisteredProviders( Class<? extends OperationSet> opSet, ProtocolProviderService preferredProvider, String preferredProtocolName) { List<ProtocolProviderService> providers = new ArrayList<ProtocolProviderService>(); if (preferredProvider != null) { if (preferredProvider.isRegistered()) providers.add(preferredProvider); // If we have a provider, but it's not registered we try to // obtain all registered providers for the same protocol as the // given preferred provider. else { providers = GuiActivator.getRegisteredProviders( preferredProvider.getProtocolName(), opSet); } } // If we don't have a preferred provider we try to obtain a // preferred protocol name and all registered providers for it. else { if (preferredProtocolName != null) providers = GuiActivator.getRegisteredProviders( preferredProtocolName, opSet); // If the protocol name is null we simply obtain all telephony // providers. else providers = GuiActivator.getRegisteredProviders(opSet); } return providers; } /** * Returns the <tt>AccountManager</tt> obtained from the bundle context. * @return the <tt>AccountManager</tt> obtained from the bundle context */ public static AccountManager getAccountManager() { if(accountManager == null) { accountManager = ServiceUtils.getService(bundleContext, AccountManager.class); } return accountManager; } /** * Returns the <tt>ConfigurationService</tt> obtained from the bundle * context. * @return the <tt>ConfigurationService</tt> obtained from the bundle * context */ public static ConfigurationService getConfigurationService() { if(configService == null) { configService = ServiceUtils.getService( bundleContext, ConfigurationService.class); } return configService; } /** * Returns the <tt>MetaHistoryService</tt> obtained from the bundle * context. * @return the <tt>MetaHistoryService</tt> obtained from the bundle * context */ public static MetaHistoryService getMetaHistoryService() { if (metaHistoryService == null) { metaHistoryService = ServiceUtils.getService( bundleContext, MetaHistoryService.class); } return metaHistoryService; } /** * Returns the <tt>MetaContactListService</tt> obtained from the bundle * context. * @return the <tt>MetaContactListService</tt> obtained from the bundle * context */ public static MetaContactListService getContactListService() { if (metaCListService == null) { metaCListService = ServiceUtils.getService( bundleContext, MetaContactListService.class); } return metaCListService; } /** * Returns the <tt>CallHistoryService</tt> obtained from the bundle * context. * @return the <tt>CallHistoryService</tt> obtained from the bundle * context */ public static CallHistoryService getCallHistoryService() { if (callHistoryService == null) { callHistoryService = ServiceUtils.getService( bundleContext, CallHistoryService.class); } return callHistoryService; } /** * Returns the <tt>AudioNotifierService</tt> obtained from the bundle * context. * @return the <tt>AudioNotifierService</tt> obtained from the bundle * context */ public static AudioNotifierService getAudioNotifier() { if (audioNotifierService == null) { audioNotifierService = ServiceUtils.getService( bundleContext, AudioNotifierService.class); } return audioNotifierService; } /** * Returns the <tt>BrowserLauncherService</tt> obtained from the bundle * context. * @return the <tt>BrowserLauncherService</tt> obtained from the bundle * context */ public static BrowserLauncherService getBrowserLauncher() { if (browserLauncherService == null) { browserLauncherService = ServiceUtils.getService( bundleContext, BrowserLauncherService.class); } return browserLauncherService; } /** * Returns the current implementation of the <tt>UIService</tt>. * @return the current implementation of the <tt>UIService</tt> */ public static UIServiceImpl getUIService() { return uiService; } /** * Returns the <tt>SystrayService</tt> obtained from the bundle context. * * @return the <tt>SystrayService</tt> obtained from the bundle context */ public static SystrayService getSystrayService() { if (systrayService == null) { systrayService = ServiceUtils.getService(bundleContext, SystrayService.class); } return systrayService; } /** * Returns the <tt>KeybindingsService</tt> obtained from the bundle context. * * @return the <tt>KeybindingsService</tt> obtained from the bundle context */ public static KeybindingsService getKeybindingsService() { if (keybindingsService == null) { keybindingsService = ServiceUtils.getService( bundleContext, KeybindingsService.class); } return keybindingsService; } /** * Returns the <tt>ResourceManagementService</tt>, through which we will * access all resources. * * @return the <tt>ResourceManagementService</tt>, through which we will * access all resources. */ public static ResourceManagementService getResources() { if (resourcesService == null) { resourcesService = ServiceUtils.getService( bundleContext, ResourceManagementService.class); } return resourcesService; } /** * Returns the <tt>FileAccessService</tt> obtained from the bundle context. * * @return the <tt>FileAccessService</tt> obtained from the bundle context */ public static FileAccessService getFileAccessService() { if (fileAccessService == null) { fileAccessService = ServiceUtils.getService( bundleContext, FileAccessService.class); } return fileAccessService; } /** * Returns the <tt>DesktopService</tt> obtained from the bundle context. * * @return the <tt>DesktopService</tt> obtained from the bundle context */ public static DesktopService getDesktopService() { if (desktopService == null) { desktopService = ServiceUtils.getService(bundleContext, DesktopService.class); } return desktopService; } /** * Returns an instance of the <tt>MediaService</tt> obtained from the * bundle context. * @return an instance of the <tt>MediaService</tt> obtained from the * bundle context */ public static MediaService getMediaService() { if (mediaService == null) { mediaService = ServiceUtils.getService(bundleContext, MediaService.class); } return mediaService; } /** * Returns a list of all registered contact sources. * @return a list of all registered contact sources */ public static List<ContactSourceService> getContactSources() { if (contactSources != null) return contactSources; contactSources = new Vector<ContactSourceService>(); ServiceReference[] serRefs = null; try { // get all registered provider factories serRefs = bundleContext.getServiceReferences( ContactSourceService.class.getName(), null); } catch (InvalidSyntaxException e) { logger.error("GuiActivator : " + e); } if (serRefs != null) { for (ServiceReference serRef : serRefs) { ContactSourceService contactSource = (ContactSourceService) bundleContext.getService(serRef); contactSources.add(contactSource); } } return contactSources; } /** * Returns all <tt>ReplacementService</tt>s obtained from the bundle * context. * * @return all <tt>ReplacementService</tt> implementation obtained from the * bundle context */ public static Map<String, ReplacementService> getReplacementSources() { ServiceReference[] serRefs = null; try { // get all registered sources serRefs = bundleContext.getServiceReferences(ReplacementService.class .getName(), null); } catch (InvalidSyntaxException e) { logger.error("Error : " + e); } if (serRefs != null) { for (int i = 0; i < serRefs.length; i++) { ReplacementService replacementSources = (ReplacementService) bundleContext.getService(serRefs[i]); replacementSourcesMap.put((String)serRefs[i] .getProperty(ReplacementService.SOURCE_NAME), replacementSources); } } return replacementSourcesMap; } /** * Returns the <tt>SmiliesReplacementService</tt> obtained from the bundle * context. * * @return the <tt>SmiliesReplacementService</tt> implementation obtained * from the bundle context */ public static SmiliesReplacementService getSmiliesReplacementSource() { if (smiliesService == null) { smiliesService = ServiceUtils.getService(bundleContext, SmiliesReplacementService.class); } return smiliesService; } /** * Returns the <tt>PhoneNumberI18nService</tt> obtained from the bundle * context. * * @return the <tt>PhoneNumberI18nService</tt> implementation obtained * from the bundle context */ public static PhoneNumberI18nService getPhoneNumberService() { if (phoneNumberService == null) { phoneNumberService = ServiceUtils.getService(bundleContext, PhoneNumberI18nService.class); } return phoneNumberService; } /** * Returns the <tt>SecurityAuthority</tt> implementation registered to * handle security authority events. * * @return the <tt>SecurityAuthority</tt> implementation obtained * from the bundle context */ public static SecurityAuthority getSecurityAuthority() { if (securityAuthority == null) { securityAuthority = ServiceUtils.getService(bundleContext, SecurityAuthority.class); } return securityAuthority; } /** * Returns the <tt>SecurityAuthority</tt> implementation registered to * handle security authority events. * * @param protocolName protocol name * @return the <tt>SecurityAuthority</tt> implementation obtained * from the bundle context */ public static SecurityAuthority getSecurityAuthority(String protocolName) { String osgiFilter = "(" + ProtocolProviderFactory.PROTOCOL + "=" + protocolName + ")"; SecurityAuthority securityAuthority = null; try { ServiceReference[] serRefs = bundleContext.getServiceReferences( SecurityAuthority.class.getName(), osgiFilter); if (serRefs != null && serRefs.length > 0) securityAuthority = (SecurityAuthority) bundleContext .getService(serRefs[0]); } catch (InvalidSyntaxException ex) { logger.error("GuiActivator : " + ex); } return securityAuthority; } /** * Sets the <tt>contactList</tt> component currently used to show the * contact list. * @param list the contact list object to set */ public static void setContactList(TreeContactList list) { contactList = list; } /** * Returns the component used to show the contact list. * @return the component used to show the contact list */ public static TreeContactList getContactList() { return contactList; } /** * Returns the list of wrapped protocol providers. * * @param providers the list of protocol providers * @return an array of wrapped protocol providers */ public static Object[] getAccounts(List<ProtocolProviderService> providers) { ArrayList<Account> accounts = new ArrayList<Account>(); Iterator<ProtocolProviderService> accountsIter = providers.iterator(); while (accountsIter.hasNext()) { accounts.add(new Account(accountsIter.next())); } return accounts.toArray(); } /** * Returns the preferred account if there's one. * * @return the <tt>ProtocolProviderService</tt> corresponding to the * preferred account */ public static ProtocolProviderService getPreferredAccount() { // check for preferred wizard String prefWName = GuiActivator.getResources(). getSettingsString("impl.gui.PREFERRED_ACCOUNT_WIZARD"); if(prefWName == null || prefWName.length() <= 0) return null; ServiceReference[] accountWizardRefs = null; try { accountWizardRefs = GuiActivator.bundleContext .getServiceReferences( AccountRegistrationWizard.class.getName(), null); } catch (InvalidSyntaxException ex) { // this shouldn't happen since we're providing no parameter string // but let's log just in case. logger.error( "Error while retrieving service refs", ex); return null; } // in case we found any, add them in this container. if (accountWizardRefs != null) { if (logger.isDebugEnabled()) logger.debug("Found " + accountWizardRefs.length + " already installed providers."); for (int i = 0; i < accountWizardRefs.length; i++) { AccountRegistrationWizard wizard = (AccountRegistrationWizard) GuiActivator.bundleContext .getService(accountWizardRefs[i]); // is it the preferred protocol ? if(wizard.getClass().getName().equals(prefWName)) { - ArrayList<AccountID> registeredAccounts - = getProtocolProviderFactory(wizard.getProtocolName()) - .getRegisteredAccounts(); - - if (registeredAccounts.size() > 0) - return getRegisteredProviderForAccount( - registeredAccounts.get(0)); + for (ProtocolProviderFactory providerFactory : GuiActivator + .getProtocolProviderFactories().values()) + { + ServiceReference serRef; + ProtocolProviderService protocolProvider; + + for (AccountID accountID + : providerFactory.getRegisteredAccounts()) + { + serRef = providerFactory.getProviderForAccount( + accountID); + + protocolProvider = (ProtocolProviderService) + GuiActivator.bundleContext + .getService(serRef); + + if (protocolProvider.getAccountID() + .getProtocolDisplayName() + .equals(wizard.getProtocolName())) + { + return protocolProvider; + } + } + } } } } return null; } }
true
false
null
null
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/rpc/SubmissionBasedRemoteService.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/rpc/SubmissionBasedRemoteService.java index c6b6c606..344b9a0b 100644 --- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/rpc/SubmissionBasedRemoteService.java +++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/rpc/SubmissionBasedRemoteService.java @@ -1,98 +1,98 @@ /* * Copyright 2009-2014 European Molecular Biology Laboratory * * 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 impl * See the License for the specific language governing permissions and * limitations under the License. */ package uk.ac.ebi.fg.annotare2.web.server.rpc; import com.google.gwt.user.server.rpc.UnexpectedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.ebi.fg.annotare2.db.dao.RecordNotFoundException; import uk.ac.ebi.fg.annotare2.db.model.ArrayDesignSubmission; import uk.ac.ebi.fg.annotare2.db.model.ExperimentSubmission; import uk.ac.ebi.fg.annotare2.db.model.Submission; import uk.ac.ebi.fg.annotare2.db.model.enums.Permission; import uk.ac.ebi.fg.annotare2.web.gwt.common.client.NoPermissionException; import uk.ac.ebi.fg.annotare2.web.gwt.common.client.ResourceNotFoundException; import uk.ac.ebi.fg.annotare2.web.server.services.AccessControlException; import uk.ac.ebi.fg.annotare2.web.server.services.AccountService; import uk.ac.ebi.fg.annotare2.web.server.services.EmailSender; import uk.ac.ebi.fg.annotare2.web.server.services.SubmissionManager; /** * @author Olga Melnichuk */ public abstract class SubmissionBasedRemoteService extends AuthBasedRemoteService { private static final Logger log = LoggerFactory.getLogger(SubmissionBasedRemoteService.class); private final SubmissionManager submissionManager; private final EmailSender email; protected SubmissionBasedRemoteService(AccountService accountService, SubmissionManager submissionManager, EmailSender emailSender) { super(accountService, emailSender); this.email = emailSender; this.submissionManager = submissionManager; } protected Submission getSubmission(long id, Permission permission) throws RecordNotFoundException, AccessControlException { return submissionManager.getSubmission(getCurrentUser(), id, permission); } protected ExperimentSubmission getExperimentSubmission(long id, Permission permission) throws RecordNotFoundException, AccessControlException { return submissionManager.getExperimentSubmission(getCurrentUser(), id, permission); } protected ArrayDesignSubmission getArrayDesignSubmission(long id, Permission permission) throws RecordNotFoundException, AccessControlException { return submissionManager.getArrayDesignSubmission(getCurrentUser(), id, permission); } protected ExperimentSubmission createExperimentSubmission() throws AccessControlException { return submissionManager.createExperimentSubmission(getCurrentUser()); } protected ArrayDesignSubmission createArrayDesignSubmission() throws AccessControlException { return submissionManager.createArrayDesignSubmission(getCurrentUser()); } protected void save(Submission submission) { submissionManager.save(submission); } protected void deleteSubmissionSoftly(Submission submission) { submissionManager.deleteSubmissionSoftly(submission); } protected UnexpectedException unexpected(Throwable e) { log.error("server error", e); email.sendException("Unexpected server error for [" + getCurrentUserEmail() + "]", e); return new UnexpectedException("Unexpected server error", e); } protected ResourceNotFoundException noSuchRecord(RecordNotFoundException e) { log.error("server error", e); email.sendException("Submission not found for [" + getCurrentUserEmail() + "]", e); return new ResourceNotFoundException("Submission not found"); } protected NoPermissionException noPermission(AccessControlException e) { - log.error("server error", e); + log.error(e.getMessage()); //TODO: no need to email this //email.sendException("No permission for [" + getCurrentUserEmail() + "]", e); return new NoPermissionException("No permission"); } }
true
false
null
null
diff --git a/forms/src/org/riotfamily/forms/element/core/TextField.java b/forms/src/org/riotfamily/forms/element/core/TextField.java index 3eb4dcd58..f78899872 100755 --- a/forms/src/org/riotfamily/forms/element/core/TextField.java +++ b/forms/src/org/riotfamily/forms/element/core/TextField.java @@ -1,165 +1,165 @@ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Riot. * * The Initial Developer of the Original Code is * Neteye GmbH. * Portions created by the Initial Developer are Copyright (C) 2006 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Felix Gnass [fgnass at neteye dot de] * * ***** END LICENSE BLOCK ***** */ package org.riotfamily.forms.element.core; import java.io.PrintWriter; import java.util.regex.Pattern; import org.riotfamily.common.markup.DocumentWriter; import org.riotfamily.common.markup.Html; import org.riotfamily.forms.FormRequest; import org.riotfamily.forms.element.support.AbstractTextElement; import org.riotfamily.forms.error.ErrorUtils; import org.riotfamily.forms.support.MessageUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** * A text input field. */ public class TextField extends AbstractTextElement { private static final String CONFIRM_SUFFIX = "-confirm"; private static final String DEFAULT_CONFIRM_MESSAGE_KEY = "label.textField.confirmInput"; private static final String DEFAULT_REGEX_MISMATCH_MESSAGE_KEY = "error.textField.regexMismatch"; private boolean confirm; private String confirmText = null; private String confirmMessageKey; private String confirmMessageText; private Pattern pattern; private String regexMismatchMessageKey = DEFAULT_REGEX_MISMATCH_MESSAGE_KEY; private String regexMismatchMessageText; public TextField() { this("text"); } public TextField(String s) { super(s); } public void setConfirm(boolean confirm) { this.confirm = confirm; } public void setConfirmMessageKey(String confirmMessageKey) { this.confirmMessageKey = confirmMessageKey; } public void setConfirmMessageText(String confirmMessageText) { this.confirmMessageText = confirmMessageText; } public void setRegex(String regex) { this.pattern = Pattern.compile(regex); setValidateOnChange(true); } public void setRegexMismatchMessageKey(String regexMismatchMessageKey) { this.regexMismatchMessageKey = regexMismatchMessageKey; } public void setRegexMismatchMessageText(String regexMismatchMessageText) { this.regexMismatchMessageText = regexMismatchMessageText; } public void renderInternal(PrintWriter writer) { if (confirm) { DocumentWriter doc = new DocumentWriter(writer); doc.start(Html.DIV).attribute(Html.COMMON_CLASS, "confirm-text"); doc.body(); super.renderInternal(writer); String msg = MessageUtils.getMessage(this, getConfirmMessage()); doc.start(Html.P).body(msg).end(); doc.startEmpty(Html.INPUT) .attribute(Html.INPUT_TYPE, getType()) .attribute(Html.COMMON_CLASS, getStyleClass()) .attribute(Html.INPUT_NAME, getConfirmParamName()) .attribute(Html.INPUT_VALUE, confirmText != null ? confirmText : getText()); doc.closeAll(); } else { super.renderInternal(writer); } } public void processRequest(FormRequest request) { if (confirm) { confirmText = request.getParameter(getConfirmParamName()); } super.processRequest(request); } protected void validate(boolean formSubmitted) { super.validate(formSubmitted); if (formSubmitted && confirm) { if (!ObjectUtils.nullSafeEquals(getText(), confirmText)) { - ErrorUtils.reject(this, "confirmFailed"); + ErrorUtils.reject(this, "error.textField.confirmationFailed"); } } if (pattern != null && StringUtils.hasLength(getText())) { if (!pattern.matcher(getText()).matches()) { getForm().getErrors().rejectValue(getFieldName(), regexMismatchMessageKey, regexMismatchMessageText); } } } protected String getConfirmParamName() { return getParamName() + CONFIRM_SUFFIX; } protected String getConfirmMessage() { if (confirmMessageText != null) { return confirmMessageText; } else if (confirmMessageKey != null){ return MessageUtils.getMessage(this, confirmMessageKey); } else { return MessageUtils.getMessage(this, getDefaultConfirmMessageKey()); } } protected String getDefaultConfirmMessageKey() { return DEFAULT_CONFIRM_MESSAGE_KEY; } }
true
false
null
null
diff --git a/core/src/test/java/de/betterform/xml/xforms/ContainerTest.java b/core/src/test/java/de/betterform/xml/xforms/ContainerTest.java index 46aa6503..63b738b2 100644 --- a/core/src/test/java/de/betterform/xml/xforms/ContainerTest.java +++ b/core/src/test/java/de/betterform/xml/xforms/ContainerTest.java @@ -1,267 +1,267 @@ /* * Copyright (c) 2011. betterForm Project - http://www.betterform.de * Licensed under the terms of BSD License */ package de.betterform.xml.xforms; import junit.framework.TestCase; import de.betterform.xml.dom.DOMUtil; import de.betterform.xml.events.XFormsEventNames; import de.betterform.xml.xforms.exception.XFormsBindingException; import de.betterform.xml.xforms.exception.XFormsException; import de.betterform.xml.xforms.model.Model; import org.w3c.dom.Document; import org.w3c.dom.events.EventTarget; import java.util.Map; /** * @author joern turner - <[email protected]> * @version $Id: ContainerTest.java 3471 2008-08-15 21:55:23Z joern $ */ public class ContainerTest extends TestCase { /* static { org.apache.log4j.BasicConfigurator.configure(); } */ private XFormsProcessorImpl processor; private TestEventListener versionEventListener; /** * __UNDOCUMENTED__ * * @throws Exception __UNDOCUMENTED__ */ public void testGetDOM() throws Exception { processor.setXForms(getClass().getResourceAsStream("model-test.xml")); Document dom = processor.getContainer().getDocument(); assertTrue(dom != null); } // public void testGetModels() throws Exception{ // processor.setXForms(getXmlResource("model-test.xml")); // processor.init(); // assertTrue(processor.getContainer().getModelList().size()==2); // } public void testGetDefaultModel() throws Exception { processor.setXForms(getClass().getResourceAsStream("model-test.xml")); processor.init(); Model m = processor.getContainer().getDefaultModel(); assertTrue(m.getId().equals("C1")); } /** * test that XForms 1.1 will be returned as version if there's no version attribute on model * * @throws Exception */ public void testGetVersionNull() throws Exception{ String path = getClass().getResource("buglet3.xml").getPath(); this.processor.setXForms(getClass().getResourceAsStream("buglet3.xml")); this.processor.setBaseURI("file://" + path); this.processor.init(); String version = this.processor.getContainer().getVersion(); assertEquals(Container.XFORMS_1_1,version); this.processor.shutdown(); } public void testGetVersion11()throws Exception{ String path = getClass().getResource("buglet2.xml").getPath(); this.processor.setXForms(getClass().getResourceAsStream("buglet2.xml")); this.processor.setBaseURI("file://" + path); this.versionEventListener = new TestEventListener(); ((EventTarget)this.processor.getXForms().getDocumentElement()).addEventListener(XFormsEventNames.VERSION_EXCEPTION, this.versionEventListener, true); //initialize/bootstrap processor this.processor.init(); assertNull(this.versionEventListener.getType()); } public void testVersionInvalid()throws Exception{ String path = getClass().getResource("buglet7.xml").getPath(); this.processor.setXForms(getClass().getResourceAsStream("buglet7.xml")); this.processor.setBaseURI("file://" + path); /* Check for event -> doesn´t occur right now because processor shutdown before event reaches client. this.versionEventListener = new TestEventListener(); ((EventTarget)this.processor.getXForms().getDocumentElement()).addEventListener(XFormsEventNames.VERSION_EXCEPTION, this.versionEventListener, true); //initialize/bootstrap processor this.processor.init(); //Check for event -> doesn´t occur right now because processor shutdown before event reaches client. assertNotNull(this.versionEventListener.getType()); */ Exception exception = null; try{ this.processor.init(); }catch(XFormsException e){ exception = e; } assertNotNull(exception); - assertEquals("xforms-version-exception: version setting of default model not supported: '2011.12'::", exception.getMessage()); + assertEquals("xforms-version-exception: version exception: version setting of default model not supported: '2011.12'::/envelope[1]/xforms:model[1]", exception.getMessage()); } public void testDefaulModelHasLowerVersion()throws Exception{ String path = getClass().getResource("buglet8.xml").getPath(); this.processor.setXForms(getClass().getResourceAsStream("buglet8.xml")); this.processor.setBaseURI("file://" + path); /* Check for event -> doesn´t occur right now because processor shutdown before event reaches client. this.versionEventListener = new TestEventListener(); ((EventTarget)this.processor.getXForms().getDocumentElement()).addEventListener(XFormsEventNames.VERSION_EXCEPTION, this.versionEventListener, true); //initialize/bootstrap processor this.processor.init(); //Check for event -> doesn´t occur right now because processor shutdown before event reaches client. assertNotNull(this.versionEventListener.getType()); */ Exception exception = null; try{ this.processor.init(); }catch(XFormsException e){ exception = e; } assertNotNull(exception); - assertEquals("xforms-version-exception: Incompatible version setting: 1.1 on model: /envelope[1]/xforms:model[2]::", exception.getMessage()); + assertEquals("xforms-version-exception: version exception: Incompatible version setting: 1.1 on model: /envelope[1]/xforms:model[2]::/envelope[1]/xforms:model[1]", exception.getMessage()); } public void testGetVersion10_11()throws Exception{ String path = getClass().getResource("buglet4.xml").getPath(); this.processor.setXForms(getClass().getResourceAsStream("buglet4.xml")); this.processor.setBaseURI("file://" + path); //initialize/bootstrap processor this.processor.init(); String version = this.processor.getContainer().getVersion(); assertEquals(Container.XFORMS_1_1,version); this.processor.shutdown(); } public void testGetVersionIncompatible() throws Exception{ String path = getClass().getResource("buglet5.xml").getPath(); this.processor.setXForms(getClass().getResourceAsStream("buglet5.xml")); this.processor.setBaseURI("file://" + path); this.versionEventListener = new TestEventListener(); ((EventTarget)this.processor.getXForms().getDocumentElement()).addEventListener(XFormsEventNames.VERSION_EXCEPTION, this.versionEventListener, true); Exception exception = null; try{ this.processor.init(); }catch(XFormsException e){ exception = e; } assertNotNull(exception); - assertEquals("xforms-version-exception: version setting of default model not supported: '1.2'::", exception.getMessage()); + assertEquals("xforms-version-exception: version exception: version setting of default model not supported: '1.2'::/envelope[1]/xforms:model[1]", exception.getMessage()); } public void testInitNoModel() throws Exception{ String path = getClass().getResource("buglet6.xml").getPath(); this.processor.setXForms(getClass().getResourceAsStream("buglet6.xml")); this.processor.setBaseURI("file://" + path); try{ this.processor.init(); }catch (XFormsException e){ assertEquals("No XForms Model found",e.getMessage()); } } /** * __UNDOCUMENTED__ * * @throws Exception __UNDOCUMENTED__ */ public void testGetModel() throws Exception { processor.setXForms(getClass().getResourceAsStream("model-test.xml")); processor.init(); Model m = processor.getContainer().getModel(""); assertTrue(m != null); assertTrue(m.getElement().getLocalName().equals("model")); m = processor.getContainer().getModel("messages"); assertTrue(m != null); assertTrue(m.getElement().getLocalName().equals("model")); m = processor.getContainer().getModel(null); assertTrue(m != null); } /** * __UNDOCUMENTED__ * * @throws Exception __UNDOCUMENTED__ */ public void testInit() throws Exception { this.processor.setXForms(getClass().getResourceAsStream("controls-broken.xml")); TestEventListener errorListener = new TestEventListener(); EventTarget eventTarget = (EventTarget) this.processor.getXForms().getDocumentElement(); eventTarget.addEventListener("xforms-binding-exception", errorListener, true); try { this.processor.init(); fail("exception expected"); } catch (XFormsException e) { assertTrue("wrong fatal error", e instanceof XFormsBindingException); assertTrue("wrong error event type", ("xforms-binding-exception").equals(errorListener.getType())); assertTrue("wrong error event target", ("text-input").equals(errorListener.getId())); Map errorMap= (Map) errorListener.getContext(); assertTrue("wrong error context info", ("wrong").equals(errorMap.get("defaultinfo"))); } } public void testGetElementById() throws Exception{ this.processor.setXForms(getClass().getResourceAsStream("BindingTest.xhtml")); this.processor.init(); String name = processor.getContainer().getElementById("input-1").getLocalName(); assertEquals("input",name); } public void testInclude() throws Exception{ this.processor.setXForms(getClass().getResourceAsStream("include.xml")); String path = getClass().getResource("XFormsProcessorImplTest.xhtml").getPath(); String baseURI = "file://" + path.substring(0, path.lastIndexOf("XFormsProcessorImplTest.xhtml")); this.processor.setBaseURI(baseURI); DOMUtil.prettyPrintDOM(this.processor.getContainer().getDocument()); } /** * */ protected void setUp() throws Exception { processor = new XFormsProcessorImpl(); } /** * __UNDOCUMENTED__ */ protected void tearDown() { this.processor = null; } }
false
false
null
null
diff --git a/src/com/dmdirc/addons/dcc/DCCSendWindow.java b/src/com/dmdirc/addons/dcc/DCCSendWindow.java index 99f354ed..b3248841 100644 --- a/src/com/dmdirc/addons/dcc/DCCSendWindow.java +++ b/src/com/dmdirc/addons/dcc/DCCSendWindow.java @@ -1,383 +1,383 @@ /* * Copyright (c) 2006-2010 Chris Smith, Shane Mc Cormack, Gregory Holmes * * 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.dmdirc.addons.dcc; import com.dmdirc.Server; import com.dmdirc.ServerState; import com.dmdirc.actions.ActionManager; import com.dmdirc.addons.dcc.actions.DCCActions; import com.dmdirc.config.IdentityManager; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.parser.interfaces.Parser; import com.dmdirc.parser.interfaces.callbacks.SocketCloseListener; import java.awt.Desktop; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JProgressBar; import net.miginfocom.swing.MigLayout; /** * This class links DCC Send objects to a window. * * @author Shane 'Dataforce' McCormack */ public class DCCSendWindow extends DCCFrame implements DCCSendInterface, ActionListener, SocketCloseListener { /** The DCCSend object we are a window for */ private final DCCSend dcc; /** Other Nickname */ private final String otherNickname; /** Total data transfered */ private volatile long transferCount = 0; /** Time Started */ private long timeStarted = 0; /** Progress Bar */ private final JProgressBar progress = new JProgressBar(); /** Status Label */ private final JLabel status = new JLabel("Status: Waiting"); /** Speed Label */ private final JLabel speed = new JLabel("Speed: Unknown"); /** Time Label */ private final JLabel remaining = new JLabel("Time Remaining: Unknown"); /** Time Taken */ private final JLabel taken = new JLabel("Time Taken: 00:00"); /** Button */ private final JButton button = new JButton("Cancel"); /** Open Button */ private final JButton openButton = new JButton("Open"); /** Plugin that this send belongs to. */ private final DCCPlugin myPlugin; /** IRC Parser that caused this send */ private Parser parser = null; /** Server that caused this send */ private Server server = null; /** Show open button. */ private boolean showOpen = Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.OPEN); /** * Creates a new instance of DCCSendWindow with a given DCCSend object. * * @param plugin the DCC Plugin responsible for this window * @param dcc The DCCSend object this window wraps around * @param title The title of this window * @param targetNick Nickname of target * @param server The server that initiated this send */ public DCCSendWindow(final DCCPlugin plugin, final DCCSend dcc, final String title, final String targetNick, final Server server) { super(plugin, title, dcc.getType() == DCCSend.TransferType.SEND ? "dcc-send-inactive" : "dcc-receive-inactive"); this.dcc = dcc; this.server = server; this.parser = server == null ? null : server.getParser(); this.myPlugin = plugin; if (parser != null) { parser.getCallbackManager().addNonCriticalCallback(SocketCloseListener.class, this); } dcc.setHandler(this); otherNickname = targetNick; getContentPane().setLayout(new MigLayout("hidemode 0")); progress.setMinimum(0); progress.setMaximum(100); progress.setStringPainted(true); progress.setValue(0); if (dcc.getType() == DCCSend.TransferType.SEND) { getContentPane().add(new JLabel("Sending: " + dcc.getShortFileName()), "wrap"); getContentPane().add(new JLabel("To: " + targetNick), "wrap"); } else { getContentPane().add(new JLabel("Recieving: " + dcc.getShortFileName()), "wrap"); getContentPane().add(new JLabel("From: " + targetNick), "wrap"); } getContentPane().add(status, "wrap"); getContentPane().add(speed, "wrap"); getContentPane().add(remaining, "wrap"); getContentPane().add(taken, "wrap"); getContentPane().add(progress, "growx, wrap"); button.addActionListener(this); openButton.addActionListener(this); openButton.setVisible(false); getContentPane().add(openButton, "split 2, align right"); getContentPane().add(button, "align right"); plugin.addWindow(this); } /** {@inheritDoc} */ @Override public void onSocketClosed(final Parser tParser) { // Remove our reference to the parser (and its reference to us) parser.getCallbackManager().delAllCallback(this); parser = null; // Can't resend without the parser. if ("Resend".equals(button.getText())) { button.setText("Close Window"); } } /** * Get the DCCSend Object associated with this window * * @return The DCCSend Object associated with this window */ public DCCSend getDCC() { return dcc; } /** * {@inheritDoc} * * @param e Action event */ @Override public void actionPerformed(final ActionEvent e) { if (e.getActionCommand().equals("Cancel")) { if (dcc.getType() == DCCSend.TransferType.SEND) { button.setText("Resend"); } else { button.setText("Close Window"); } status.setText("Status: Cancelled"); dcc.close(); } else if (e.getActionCommand().equals("Resend")) { button.setText("Cancel"); status.setText("Status: Resending..."); synchronized (this) { transferCount = 0; } dcc.reset(); if (parser != null && server.getState() == ServerState.CONNECTED) { final String myNickname = parser.getLocalClient().getNickname(); // Check again incase we have changed nickname to the same nickname that // this send is for. if (parser.getStringConverter().equalsIgnoreCase(otherNickname, myNickname)) { final Thread errorThread = new Thread(new Runnable() { /** {@inheritDoc} */ @Override public void run() { JOptionPane.showMessageDialog(null, "You can't DCC yourself.", "DCC Error", JOptionPane.ERROR_MESSAGE); } }); errorThread.start(); return; } else { if (IdentityManager.getGlobalConfig().getOptionBool(plugin.getDomain(), "send.reverse")) { parser.sendCTCP(otherNickname, "DCC", "SEND \"" + (new File(dcc.getFileName())).getName() + "\" " + DCC.ipToLong(myPlugin.getListenIP(parser)) + " 0 " + dcc.getFileSize() + " " + dcc.makeToken() + ((dcc.isTurbo()) ? " T" : "")); return; } else if (plugin.listen(dcc)) { parser.sendCTCP(otherNickname, "DCC", "SEND \"" + (new File(dcc.getFileName())).getName() + "\" " + DCC.ipToLong(myPlugin.getListenIP(parser)) + " " + dcc.getPort() + " " + dcc.getFileSize() + ((dcc.isTurbo()) ? " T" : "")); return; } } } else { status.setText("Status: Resend failed."); button.setText("Close Window"); } } else if (e.getActionCommand().equals("Close Window")) { close(); } else if (e.getSource() == openButton) { final File file = new File(dcc.getFileName()); try { Desktop.getDesktop().open(file); } catch (IllegalArgumentException ex) { Logger.userError(ErrorLevel.LOW, "Unable to open file: " + - file + ex); + file, ex); openButton.setEnabled(false); } catch (IOException ex) { try { Desktop.getDesktop().open(file.getParentFile()); } catch (IllegalArgumentException ex1) { Logger.userError(ErrorLevel.LOW, "Unable to open folder: " + - file.getParentFile() + ex1); + file.getParentFile(), ex1); openButton.setEnabled(false); } catch (IOException ex1) { Logger.userError(ErrorLevel.LOW, "No associated handler " + - "to open file or directory." + ex1); + "to open file or directory.", ex1); openButton.setEnabled(false); } } } } /** * Called when data is sent/recieved * * @param dcc The DCCSend that this message is from * @param bytes The number of new bytes that were transfered */ @Override public void dataTransfered(final DCCSend dcc, final int bytes) { final double percent; synchronized (this) { transferCount += bytes; percent = (100.00 / dcc.getFileSize()) * (transferCount + dcc.getFileStart()); } if (dcc.getType() == DCCSend.TransferType.SEND) { status.setText("Status: Sending"); } else { status.setText("Status: Recieving"); } updateSpeedAndTime(); progress.setValue((int) Math.floor(percent)); ActionManager.processEvent(DCCActions.DCC_SEND_DATATRANSFERED, null, this, bytes); } /** * Update the transfer speed, time remaining and time taken labels. */ public void updateSpeedAndTime() { final long time = (System.currentTimeMillis() - timeStarted) / 1000; final double bytesPerSecond; synchronized (this) { bytesPerSecond = (time > 0) ? (transferCount / time) : transferCount; } if (bytesPerSecond > 1048576) { speed.setText(String.format("Speed: %.2f MB/s", (bytesPerSecond / 1048576))); } else if (bytesPerSecond > 1024) { speed.setText(String.format("Speed: %.2f KB/s", (bytesPerSecond / 1024))); } else { speed.setText(String.format("Speed: %.2f B/s", bytesPerSecond)); } final long remaningBytes; synchronized (this) { remaningBytes = dcc.getFileSize() - dcc.getFileStart() - transferCount; } final double remainingSeconds = (bytesPerSecond > 0) ? (remaningBytes / bytesPerSecond) : 1; remaining.setText(String.format("Time Remaining: %s", duration((int) Math.floor(remainingSeconds)))); taken.setText(String.format("Time Taken: %s", timeStarted == 0 ? "N/A" : duration(time))); } /** * Get the duration in seconds as a string. * * @param secondsInput to get duration for * @return Duration as a string */ private String duration(final long secondsInput) { final StringBuilder result = new StringBuilder(); final long hours = (secondsInput / 3600); final long minutes = (secondsInput / 60 % 60); final long seconds = (secondsInput % 60); if (hours > 0) { result.append(hours + ":"); } result.append(String.format("%0,2d:%0,2d", minutes, seconds)); return result.toString(); } /** * Called when the socket is closed * * @param dcc The DCCSend that this message is from */ @Override public void socketClosed(final DCCSend dcc) { ActionManager.processEvent(DCCActions.DCC_SEND_SOCKETCLOSED, null, this); if (!isWindowClosing()) { synchronized (this) { if (transferCount == dcc.getFileSize()) { status.setText("Status: Transfer Compelete."); if (showOpen && dcc.getType() == DCCSend.TransferType.RECEIVE) { openButton.setVisible(true); } progress.setValue(100); setIcon(dcc.getType() == DCCSend.TransferType.SEND ? "dcc-send-done" : "dcc-receive-done"); button.setText("Close Window"); } else { status.setText("Status: Transfer Failed."); setIcon(dcc.getType() == DCCSend.TransferType.SEND ? "dcc-send-failed" : "dcc-receive-failed"); if (dcc.getType() == DCCSend.TransferType.SEND) { button.setText("Resend"); } else { button.setText("Close Window"); } } } updateSpeedAndTime(); } } /** * Called when the socket is opened * * @param dcc The DCCSend that this message is from */ @Override public void socketOpened(final DCCSend dcc) { ActionManager.processEvent(DCCActions.DCC_SEND_SOCKETOPENED, null, this); status.setText("Status: Socket Opened"); timeStarted = System.currentTimeMillis(); setIcon(dcc.getType() == DCCSend.TransferType.SEND ? "dcc-send-active" : "dcc-receive-active"); } /** * Closes this container (and it's associated frame). */ @Override public void windowClosing() { super.windowClosing(); dcc.removeFromSends(); dcc.close(); } }
false
true
public void actionPerformed(final ActionEvent e) { if (e.getActionCommand().equals("Cancel")) { if (dcc.getType() == DCCSend.TransferType.SEND) { button.setText("Resend"); } else { button.setText("Close Window"); } status.setText("Status: Cancelled"); dcc.close(); } else if (e.getActionCommand().equals("Resend")) { button.setText("Cancel"); status.setText("Status: Resending..."); synchronized (this) { transferCount = 0; } dcc.reset(); if (parser != null && server.getState() == ServerState.CONNECTED) { final String myNickname = parser.getLocalClient().getNickname(); // Check again incase we have changed nickname to the same nickname that // this send is for. if (parser.getStringConverter().equalsIgnoreCase(otherNickname, myNickname)) { final Thread errorThread = new Thread(new Runnable() { /** {@inheritDoc} */ @Override public void run() { JOptionPane.showMessageDialog(null, "You can't DCC yourself.", "DCC Error", JOptionPane.ERROR_MESSAGE); } }); errorThread.start(); return; } else { if (IdentityManager.getGlobalConfig().getOptionBool(plugin.getDomain(), "send.reverse")) { parser.sendCTCP(otherNickname, "DCC", "SEND \"" + (new File(dcc.getFileName())).getName() + "\" " + DCC.ipToLong(myPlugin.getListenIP(parser)) + " 0 " + dcc.getFileSize() + " " + dcc.makeToken() + ((dcc.isTurbo()) ? " T" : "")); return; } else if (plugin.listen(dcc)) { parser.sendCTCP(otherNickname, "DCC", "SEND \"" + (new File(dcc.getFileName())).getName() + "\" " + DCC.ipToLong(myPlugin.getListenIP(parser)) + " " + dcc.getPort() + " " + dcc.getFileSize() + ((dcc.isTurbo()) ? " T" : "")); return; } } } else { status.setText("Status: Resend failed."); button.setText("Close Window"); } } else if (e.getActionCommand().equals("Close Window")) { close(); } else if (e.getSource() == openButton) { final File file = new File(dcc.getFileName()); try { Desktop.getDesktop().open(file); } catch (IllegalArgumentException ex) { Logger.userError(ErrorLevel.LOW, "Unable to open file: " + file + ex); openButton.setEnabled(false); } catch (IOException ex) { try { Desktop.getDesktop().open(file.getParentFile()); } catch (IllegalArgumentException ex1) { Logger.userError(ErrorLevel.LOW, "Unable to open folder: " + file.getParentFile() + ex1); openButton.setEnabled(false); } catch (IOException ex1) { Logger.userError(ErrorLevel.LOW, "No associated handler " + "to open file or directory." + ex1); openButton.setEnabled(false); } } } }
public void actionPerformed(final ActionEvent e) { if (e.getActionCommand().equals("Cancel")) { if (dcc.getType() == DCCSend.TransferType.SEND) { button.setText("Resend"); } else { button.setText("Close Window"); } status.setText("Status: Cancelled"); dcc.close(); } else if (e.getActionCommand().equals("Resend")) { button.setText("Cancel"); status.setText("Status: Resending..."); synchronized (this) { transferCount = 0; } dcc.reset(); if (parser != null && server.getState() == ServerState.CONNECTED) { final String myNickname = parser.getLocalClient().getNickname(); // Check again incase we have changed nickname to the same nickname that // this send is for. if (parser.getStringConverter().equalsIgnoreCase(otherNickname, myNickname)) { final Thread errorThread = new Thread(new Runnable() { /** {@inheritDoc} */ @Override public void run() { JOptionPane.showMessageDialog(null, "You can't DCC yourself.", "DCC Error", JOptionPane.ERROR_MESSAGE); } }); errorThread.start(); return; } else { if (IdentityManager.getGlobalConfig().getOptionBool(plugin.getDomain(), "send.reverse")) { parser.sendCTCP(otherNickname, "DCC", "SEND \"" + (new File(dcc.getFileName())).getName() + "\" " + DCC.ipToLong(myPlugin.getListenIP(parser)) + " 0 " + dcc.getFileSize() + " " + dcc.makeToken() + ((dcc.isTurbo()) ? " T" : "")); return; } else if (plugin.listen(dcc)) { parser.sendCTCP(otherNickname, "DCC", "SEND \"" + (new File(dcc.getFileName())).getName() + "\" " + DCC.ipToLong(myPlugin.getListenIP(parser)) + " " + dcc.getPort() + " " + dcc.getFileSize() + ((dcc.isTurbo()) ? " T" : "")); return; } } } else { status.setText("Status: Resend failed."); button.setText("Close Window"); } } else if (e.getActionCommand().equals("Close Window")) { close(); } else if (e.getSource() == openButton) { final File file = new File(dcc.getFileName()); try { Desktop.getDesktop().open(file); } catch (IllegalArgumentException ex) { Logger.userError(ErrorLevel.LOW, "Unable to open file: " + file, ex); openButton.setEnabled(false); } catch (IOException ex) { try { Desktop.getDesktop().open(file.getParentFile()); } catch (IllegalArgumentException ex1) { Logger.userError(ErrorLevel.LOW, "Unable to open folder: " + file.getParentFile(), ex1); openButton.setEnabled(false); } catch (IOException ex1) { Logger.userError(ErrorLevel.LOW, "No associated handler " + "to open file or directory.", ex1); openButton.setEnabled(false); } } } }
diff --git a/helloworld-mbean/helloworld-mbean-webapp/src/main/java/org/jboss/as/quickstarts/mbeanhelloworld/util/CDIExtension.java b/helloworld-mbean/helloworld-mbean-webapp/src/main/java/org/jboss/as/quickstarts/mbeanhelloworld/util/CDIExtension.java index ec7b86bf1..1786ddc48 100644 --- a/helloworld-mbean/helloworld-mbean-webapp/src/main/java/org/jboss/as/quickstarts/mbeanhelloworld/util/CDIExtension.java +++ b/helloworld-mbean/helloworld-mbean-webapp/src/main/java/org/jboss/as/quickstarts/mbeanhelloworld/util/CDIExtension.java @@ -1,50 +1,50 @@ /* * JBoss, Home of Professional Open Source * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual * contributors by the @authors tag. See the copyright.txt in the * distribution for a full listing of individual contributors. * * 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.jboss.as.quickstarts.mbeanhelloworld.util; import javax.enterprise.context.spi.CreationalContext; import javax.enterprise.event.Observes; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.inject.spi.BeforeBeanDiscovery; import javax.enterprise.inject.spi.Extension; /** * A CDI Extension to retrieve bean in a non-CDI context. * * @author Jeremie Lagarde * */ public class CDIExtension implements Extension { private static BeanManager beanManager; void beforeBeanDiscovery(@Observes BeforeBeanDiscovery beforeBeanDiscovery, BeanManager beanManager) { setBeanManager(beanManager); } @SuppressWarnings("unchecked") public static <T> T getBean(Class<T> beanType) { final Bean<T> bean = (Bean<T>) beanManager.getBeans(beanType).iterator().next(); final CreationalContext<T> ctx = beanManager.createCreationalContext(bean); - return (T) beanManager.getReference(bean, bean.getClass(), ctx); + return (T) beanManager.getReference(bean, beanType, ctx); } private static void setBeanManager(BeanManager beanManager) { CDIExtension.beanManager = beanManager; } }
true
true
public static <T> T getBean(Class<T> beanType) { final Bean<T> bean = (Bean<T>) beanManager.getBeans(beanType).iterator().next(); final CreationalContext<T> ctx = beanManager.createCreationalContext(bean); return (T) beanManager.getReference(bean, bean.getClass(), ctx); }
public static <T> T getBean(Class<T> beanType) { final Bean<T> bean = (Bean<T>) beanManager.getBeans(beanType).iterator().next(); final CreationalContext<T> ctx = beanManager.createCreationalContext(bean); return (T) beanManager.getReference(bean, beanType, ctx); }
diff --git a/source/org/jfree/chart/renderer/xy/XYBlockRenderer.java b/source/org/jfree/chart/renderer/xy/XYBlockRenderer.java index 39e63e5..f50eb72 100644 --- a/source/org/jfree/chart/renderer/xy/XYBlockRenderer.java +++ b/source/org/jfree/chart/renderer/xy/XYBlockRenderer.java @@ -1,420 +1,435 @@ /* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2007, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * XYBlockRenderer.java * -------------------- * (C) Copyright 2006, 2007, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: XYBlockRenderer.java,v 1.1.2.3 2007/03/09 15:59:21 mungady Exp $ * * Changes * ------- * 05-Jul-2006 : Version 1 (DG); * 02-Feb-2007 : Added getPaintScale() method (DG); * 09-Mar-2007 : Fixed cloning (DG); * 21-Jun-2007 : Removed JCommon dependencies (DG); + * 03-Aug-2007 : Fix for bug 1766646 (DG); * */ package org.jfree.chart.renderer.xy; import java.awt.BasicStroke; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.LookupPaintScale; import org.jfree.chart.renderer.PaintScale; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.util.RectangleAnchor; import org.jfree.data.Range; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYZDataset; /** * A renderer that represents data from an {@link XYZDataset} by drawing a * color block at each (x, y) point, where the color is a function of the * z-value from the dataset. * * @since 1.0.4 */ public class XYBlockRenderer extends AbstractXYItemRenderer implements XYItemRenderer, Cloneable, Serializable { /** * The block width (defaults to 1.0). */ private double blockWidth = 1.0; /** * The block height (defaults to 1.0). */ private double blockHeight = 1.0; /** * The anchor point used to align each block to its (x, y) location. The * default value is <code>RectangleAnchor.CENTER</code>. */ private RectangleAnchor blockAnchor = RectangleAnchor.CENTER; /** Temporary storage for the x-offset used to align the block anchor. */ private double xOffset; /** Temporary storage for the y-offset used to align the block anchor. */ private double yOffset; /** The paint scale. */ private PaintScale paintScale; /** * Creates a new <code>XYBlockRenderer</code> instance with default * attributes. */ public XYBlockRenderer() { updateOffsets(); this.paintScale = new LookupPaintScale(); } /** * Returns the block width, in data/axis units. * * @return The block width. * * @see #setBlockWidth(double) */ public double getBlockWidth() { return this.blockWidth; } /** * Sets the width of the blocks used to represent each data item. * * @param width the new width, in data/axis units (must be > 0.0). * * @see #getBlockWidth() */ public void setBlockWidth(double width) { if (width <= 0.0) { throw new IllegalArgumentException( "The 'width' argument must be > 0.0"); } this.blockWidth = width; updateOffsets(); this.notifyListeners(new RendererChangeEvent(this)); } /** * Returns the block height, in data/axis units. * * @return The block height. * * @see #setBlockHeight(double) */ public double getBlockHeight() { return this.blockHeight; } /** * Sets the height of the blocks used to represent each data item. * * @param height the new height, in data/axis units (must be > 0.0). * * @see #getBlockHeight() */ public void setBlockHeight(double height) { if (height <= 0.0) { throw new IllegalArgumentException( "The 'height' argument must be > 0.0"); } this.blockHeight = height; updateOffsets(); this.notifyListeners(new RendererChangeEvent(this)); } /** * Returns the anchor point used to align a block at its (x, y) location. * The default values is {@link RectangleAnchor#CENTER}. * * @return The anchor point (never <code>null</code>). * * @see #setBlockAnchor(RectangleAnchor) */ public RectangleAnchor getBlockAnchor() { return this.blockAnchor; } /** * Sets the anchor point used to align a block at its (x, y) location and * sends a {@link RendererChangeEvent} to all registered listeners. * * @param anchor the anchor. * * @see #getBlockAnchor() */ public void setBlockAnchor(RectangleAnchor anchor) { if (anchor == null) { throw new IllegalArgumentException("Null 'anchor' argument."); } if (this.blockAnchor.equals(anchor)) { return; // no change } this.blockAnchor = anchor; updateOffsets(); notifyListeners(new RendererChangeEvent(this)); } /** * Returns the paint scale used by the renderer. * * @return The paint scale (never <code>null</code>). * * @see #setPaintScale(PaintScale) * @since 1.0.4 */ public PaintScale getPaintScale() { return this.paintScale; } /** * Sets the paint scale used by the renderer. * * @param scale the scale (<code>null</code> not permitted). * * @see #getPaintScale() * @since 1.0.4 */ public void setPaintScale(PaintScale scale) { if (scale == null) { throw new IllegalArgumentException("Null 'scale' argument."); } this.paintScale = scale; notifyListeners(new RendererChangeEvent(this)); } /** * Updates the offsets to take into account the block width, height and * anchor. */ private void updateOffsets() { if (this.blockAnchor.equals(RectangleAnchor.BOTTOM_LEFT)) { this.xOffset = 0.0; this.yOffset = 0.0; } else if (this.blockAnchor.equals(RectangleAnchor.BOTTOM)) { this.xOffset = -this.blockWidth / 2.0; this.yOffset = 0.0; } else if (this.blockAnchor.equals(RectangleAnchor.BOTTOM_RIGHT)) { this.xOffset = -this.blockWidth; this.yOffset = 0.0; } else if (this.blockAnchor.equals(RectangleAnchor.LEFT)) { this.xOffset = 0.0; this.yOffset = -this.blockHeight / 2.0; } else if (this.blockAnchor.equals(RectangleAnchor.CENTER)) { this.xOffset = -this.blockWidth / 2.0; this.yOffset = -this.blockHeight / 2.0; } else if (this.blockAnchor.equals(RectangleAnchor.RIGHT)) { this.xOffset = -this.blockWidth; this.yOffset = -this.blockHeight / 2.0; } else if (this.blockAnchor.equals(RectangleAnchor.TOP_LEFT)) { this.xOffset = 0.0; this.yOffset = -this.blockHeight; } else if (this.blockAnchor.equals(RectangleAnchor.TOP)) { this.xOffset = -this.blockWidth / 2.0; this.yOffset = -this.blockHeight; } else if (this.blockAnchor.equals(RectangleAnchor.TOP_RIGHT)) { this.xOffset = -this.blockWidth; this.yOffset = -this.blockHeight; } } /** * Returns the lower and upper bounds (range) of the x-values in the * specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range (<code>null</code> if the dataset is <code>null</code> * or empty). + * + * @see #findRangeBounds(XYDataset) */ public Range findDomainBounds(XYDataset dataset) { if (dataset != null) { Range r = DatasetUtilities.findDomainBounds(dataset, false); - return new Range(r.getLowerBound() + this.xOffset, - r.getUpperBound() + this.blockWidth + this.xOffset); + if (r == null) { + return null; + } + else { + return new Range(r.getLowerBound() + this.xOffset, + r.getUpperBound() + this.blockWidth + this.xOffset); + } } else { return null; } } /** * Returns the range of values the renderer requires to display all the * items from the specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range (<code>null</code> if the dataset is <code>null</code> * or empty). + * + * @see #findDomainBounds(XYDataset) */ public Range findRangeBounds(XYDataset dataset) { if (dataset != null) { Range r = DatasetUtilities.findRangeBounds(dataset, false); - return new Range(r.getLowerBound() + this.yOffset, - r.getUpperBound() + this.blockHeight + this.yOffset); + if (r == null) { + return null; + } + else { + return new Range(r.getLowerBound() + this.yOffset, + r.getUpperBound() + this.blockHeight + this.yOffset); + } } else { return null; } } /** * Draws the block representing the specified item. * * @param g2 the graphics device. * @param state the state. * @param dataArea the data area. * @param info the plot rendering info. * @param plot the plot. * @param domainAxis the x-axis. * @param rangeAxis the y-axis. * @param dataset the dataset. * @param series the series index. * @param item the item index. * @param crosshairState the crosshair state. * @param pass the pass index. */ public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { double x = dataset.getXValue(series, item); double y = dataset.getYValue(series, item); double z = 0.0; if (dataset instanceof XYZDataset) { z = ((XYZDataset) dataset).getZValue(series, item); } Paint p = this.paintScale.getPaint(z); double xx0 = domainAxis.valueToJava2D(x + this.xOffset, dataArea, plot.getDomainAxisEdge()); double yy0 = rangeAxis.valueToJava2D(y + this.yOffset, dataArea, plot.getRangeAxisEdge()); double xx1 = domainAxis.valueToJava2D(x + this.blockWidth + this.xOffset, dataArea, plot.getDomainAxisEdge()); double yy1 = rangeAxis.valueToJava2D(y + this.blockHeight + this.yOffset, dataArea, plot.getRangeAxisEdge()); Rectangle2D block; PlotOrientation orientation = plot.getOrientation(); if (orientation.equals(PlotOrientation.HORIZONTAL)) { block = new Rectangle2D.Double(Math.min(yy0, yy1), Math.min(xx0, xx1), Math.abs(yy1 - yy0), Math.abs(xx0 - xx1)); } else { block = new Rectangle2D.Double(Math.min(xx0, xx1), Math.min(yy0, yy1), Math.abs(xx1 - xx0), Math.abs(yy1 - yy0)); } g2.setPaint(p); g2.fill(block); g2.setStroke(new BasicStroke(1.0f)); g2.draw(block); } /** * Tests this <code>XYBlockRenderer</code> for equality with an arbitrary * object. This method returns <code>true</code> if and only if: * <ul> * <li><code>obj</code> is an instance of <code>XYBlockRenderer</code> (not * <code>null</code>);</li> * <li><code>obj</code> has the same field values as this * <code>XYBlockRenderer</code>;</li> * </ul> * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYBlockRenderer)) { return false; } XYBlockRenderer that = (XYBlockRenderer) obj; if (this.blockHeight != that.blockHeight) { return false; } if (this.blockWidth != that.blockWidth) { return false; } if (!this.blockAnchor.equals(that.blockAnchor)) { return false; } if (!this.paintScale.equals(that.paintScale)) { return false; } return super.equals(obj); } /** * Returns a clone of this renderer. * * @return A clone of this renderer. * * @throws CloneNotSupportedException if there is a problem creating the * clone. */ public Object clone() throws CloneNotSupportedException { XYBlockRenderer clone = (XYBlockRenderer) super.clone(); if (this.paintScale instanceof PublicCloneable) { PublicCloneable pc = (PublicCloneable) this.paintScale; clone.paintScale = (PaintScale) pc.clone(); } return clone; } }
false
false
null
null
diff --git a/core/src/main/java/brooklyn/management/internal/BrooklynGarbageCollector.java b/core/src/main/java/brooklyn/management/internal/BrooklynGarbageCollector.java index 81efa7818..379be638f 100644 --- a/core/src/main/java/brooklyn/management/internal/BrooklynGarbageCollector.java +++ b/core/src/main/java/brooklyn/management/internal/BrooklynGarbageCollector.java @@ -1,177 +1,193 @@ package brooklyn.management.internal; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import brooklyn.config.BrooklynProperties; import brooklyn.config.ConfigKey; import brooklyn.entity.Entity; import brooklyn.event.basic.BasicConfigKey; import brooklyn.management.Task; import brooklyn.util.exceptions.Exceptions; import brooklyn.util.exceptions.RuntimeInterruptedException; import brooklyn.util.task.BasicExecutionManager; import brooklyn.util.task.ExecutionListener; import brooklyn.util.text.Strings; import com.google.common.collect.Lists; /** * Deletes record of old tasks, to prevent space leaks and the eating up of more and more memory. * * The deletion policy is configurable: * <ul> * <li>Period - how frequently to look at the existing tasks to delete some, if required * <li>Max tasks per tag - the maximum number of tasks to be kept for a given tag (e.g. for * effector calls invoked on a particular entity) * <li>Max task age - the time after which a completed task will be automatically deleted * (i.e. any task completed more than maxTaskAge+period milliseconds ago will definitely * be deleted. * </ul> * * The default is to check with a period of one minute, to keep at most 100 tasks per tag, and to * delete old completed tasks after one day. * * @author aled */ public class BrooklynGarbageCollector { protected static final Logger LOG = LoggerFactory.getLogger(BrooklynGarbageCollector.class); public static final ConfigKey<Long> GC_PERIOD = new BasicConfigKey<Long>( Long.class, "brooklyn.gc.period", "the period, in millisconds, for checking if any tasks need to be deleted", 60*1000L); + public static final ConfigKey<Boolean> DO_SYSTEM_GC = new BasicConfigKey<Boolean>( + Boolean.class, "brooklyn.gc.doSystemGc", "whether to periodically call System.gc()", false); + public static final ConfigKey<Integer> MAX_TASKS_PER_TAG = new BasicConfigKey<Integer>( Integer.class, "brooklyn.gc.maxTasksPerTag", "the maximum number of tasks to be kept for a given tag (e.g. for effector calls invoked on a particular entity)", 100); public static final ConfigKey<Long> MAX_TASK_AGE = new BasicConfigKey<Long>( Long.class, "brooklyn.gc.maxTaskAge", "the number of milliseconds after which a completed task will be automatically deleted", TimeUnit.DAYS.toMillis(1)); private final BasicExecutionManager executionManager; private final ScheduledExecutorService executor; private final long gcPeriodMs; private final int maxTasksPerTag; private final long maxTaskAge; + private final boolean doSystemGc; private volatile boolean running = true; public BrooklynGarbageCollector(BrooklynProperties brooklynProperties, BasicExecutionManager executionManager){ this.executionManager = executionManager; gcPeriodMs = brooklynProperties.getConfig(GC_PERIOD); maxTasksPerTag = brooklynProperties.getConfig(MAX_TASKS_PER_TAG); maxTaskAge = brooklynProperties.getConfig(MAX_TASK_AGE); + doSystemGc = brooklynProperties.getConfig(DO_SYSTEM_GC); executor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, "brooklyn-gc"); }}); executionManager.addListener(new ExecutionListener() { @Override public void onTaskDone(Task<?> task) { BrooklynGarbageCollector.this.onTaskDone(task); }}); executor.scheduleWithFixedDelay( new Runnable() { @Override public void run() { try { logUsage("brooklyn gc (before)"); - gc(); + gcTasks(); logUsage("brooklyn gc (after)"); - System.gc(); System.gc(); - logUsage("brooklyn gc (after system gc)"); + + if (doSystemGc) { + // Can be very useful when tracking down OOMEs etc, where a lot of tasks are executing + // Empirically observed that (on OS X jvm at least) calling twice blocks - logs a significant + // amount of memory having been released, as though a full-gc had been run. But this is highly + // dependent on the JVM implementation. + System.gc(); System.gc(); + logUsage("brooklyn gc (after system gc)"); + } } catch (RuntimeInterruptedException e) { throw e; // graceful shutdown } catch (Throwable t) { LOG.warn("Error during management-context GC", t); throw Exceptions.propagate(t); } } }, gcPeriodMs, gcPeriodMs, TimeUnit.MILLISECONDS); } public void logUsage(String prefix) { if (LOG.isDebugEnabled()) LOG.debug(prefix+" - "+"using "+ Strings.makeSizeString(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())+" / "+ Strings.makeSizeString(Runtime.getRuntime().totalMemory()) + " memory; "+ "tasks: " + executionManager.getNumActiveTasks()+" active,"+ executionManager.getNumInMemoryTasks()+" in memory "+ "("+executionManager.getNumIncompleteTasks()+" incomplete and "+ executionManager.getTotalTasksSubmitted()+" total submitted)" ); } public void shutdownNow() { running = false; if (executor != null) executor.shutdownNow(); } public void onUnmanaged(Entity entity) { executionManager.deleteTag(entity); } public void onTaskDone(Task<?> task) { Set<Object> tags = task.getTags(); if (tags.contains(AbstractManagementContext.EFFECTOR_TAG) || tags.contains(AbstractManagementContext.NON_TRANSIENT_TASK_TAG)) { // keep it for a while } else { executionManager.deleteTask(task); } } - private void gc() { + /** + * Deletes old tasks. The age/number of tasks to keep is controlled by fields like + * {@link #maxTasksPerTag} and {@link #maxTaskAge}. + */ + private void gcTasks() { if (!running) return; Set<Object> taskTags = executionManager.getTaskTags(); for (Object tag : taskTags) { if (tag == null || tag.equals(AbstractManagementContext.EFFECTOR_TAG)) { continue; // there'll be other tags } Set<Task<?>> tasksWithTag = executionManager.getTasksWithTag(tag); int numTasksToDelete = (tasksWithTag.size() - maxTasksPerTag); if (numTasksToDelete > 0 || maxTaskAge > 0) { List<Task<?>> sortedTasks = Lists.newArrayList(tasksWithTag); Collections.sort(sortedTasks, new Comparator<Task<?>>() { @Override public int compare(Task<?> t1, Task<?> t2) { long end1 = t1.isDone() ? t1.getEndTimeUtc() : Long.MAX_VALUE; long end2 = t2.isDone() ? t2.getEndTimeUtc() : Long.MAX_VALUE; return (end1 < end2) ? -1 : ((end1 == end2) ? 0 : 1); } }); if (numTasksToDelete > 0) { for (Task<?> taskToDelete : sortedTasks.subList(0, numTasksToDelete)) { if (!taskToDelete.isDone()) break; executionManager.deleteTask(taskToDelete); } } if (maxTaskAge > 0) { for (Task<?> taskContender : sortedTasks.subList((numTasksToDelete > 0 ? numTasksToDelete : 0), sortedTasks.size())) { if (taskContender.isDone() && (System.currentTimeMillis() - taskContender.getEndTimeUtc() > maxTaskAge)) { executionManager.deleteTask(taskContender); } else { break; // all subsequent tasks will be newer; stop looking } } } } } } } diff --git a/core/src/test/java/brooklyn/util/text/StringsTest.java b/core/src/test/java/brooklyn/util/text/StringsTest.java index a1a40f4c3..a19acf8dd 100644 --- a/core/src/test/java/brooklyn/util/text/StringsTest.java +++ b/core/src/test/java/brooklyn/util/text/StringsTest.java @@ -1,183 +1,188 @@ /* * Copyright (c) 2009-2013 Cloudsoft Corporation Ltd. */ package brooklyn.util.text; import static org.testng.Assert.*; import org.testng.annotations.Test; import brooklyn.util.MutableMap; @Test public class StringsTest { public void isBlankOrEmpty() { assertTrue(Strings.isEmpty(null)); assertTrue(Strings.isEmpty("")); assertFalse(Strings.isEmpty(" \t ")); assertFalse(Strings.isEmpty("abc")); assertFalse(Strings.isEmpty(" abc ")); assertFalse(Strings.isNonEmpty(null)); assertFalse(Strings.isNonEmpty("")); assertTrue(Strings.isNonEmpty(" \t ")); assertTrue(Strings.isNonEmpty("abc")); assertTrue(Strings.isNonEmpty(" abc ")); assertTrue(Strings.isBlank(null)); assertTrue(Strings.isBlank("")); assertTrue(Strings.isBlank(" \t ")); assertFalse(Strings.isBlank("abc")); assertFalse(Strings.isBlank(" abc ")); assertFalse(Strings.isNonBlank(null)); assertFalse(Strings.isNonBlank("")); assertFalse(Strings.isNonBlank(" \t ")); assertTrue(Strings.isNonBlank("abc")); assertTrue(Strings.isNonBlank(" abc ")); } public void testMakeValidFilename() { assertEquals("abcdef", Strings.makeValidFilename("abcdef")); assertEquals("abc_def", Strings.makeValidFilename("abc$$$def")); assertEquals("abc_def", Strings.makeValidFilename("$$$abc$$$def$$$")); assertEquals("a_b_c", Strings.makeValidFilename("a b c")); assertEquals("a.b.c", Strings.makeValidFilename("a.b.c")); } @Test(expectedExceptions = { NullPointerException.class }) public void testMakeValidFilenameNull() { Strings.makeValidFilename(null); } @Test(expectedExceptions = { IllegalArgumentException.class }) public void testMakeValidFilenameEmpty() { Strings.makeValidFilename(""); } @Test(expectedExceptions = { IllegalArgumentException.class }) public void testMakeValidFilenameBlank() { Strings.makeValidFilename(" \t "); } public void makeValidJavaName() { assertEquals("__null", Strings.makeValidJavaName(null)); assertEquals("__empty", Strings.makeValidJavaName("")); assertEquals("abcdef", Strings.makeValidJavaName("abcdef")); assertEquals("abcdef", Strings.makeValidJavaName("a'b'c'd'e'f")); assertEquals("_12345", Strings.makeValidJavaName("12345")); } public void makeValidUniqueJavaName() { assertEquals("__null", Strings.makeValidUniqueJavaName(null)); assertEquals("__empty", Strings.makeValidUniqueJavaName("")); assertEquals("abcdef", Strings.makeValidUniqueJavaName("abcdef")); assertEquals("_12345", Strings.makeValidUniqueJavaName("12345")); } public void testRemoveFromEnd() { assertEquals("", Strings.removeFromEnd("", "bar")); assertEquals(null, Strings.removeFromEnd(null, "bar")); assertEquals("foo", Strings.removeFromEnd("foobar", "bar")); assertEquals("foo", Strings.removeFromEnd("foo", "bar")); assertEquals("foo", Strings.removeFromEnd("foobar", "foo", "bar")); // test they are applied in order assertEquals("foob", Strings.removeFromEnd("foobar", "ar", "bar", "b")); } public void testRemoveAllFromEnd() { assertEquals("", Strings.removeAllFromEnd("", "bar")); assertEquals(null, Strings.removeAllFromEnd(null, "bar")); assertEquals("", Strings.removeAllFromEnd("foobar", "foo", "bar")); assertEquals("f", Strings.removeAllFromEnd("foobar", "ar", "car", "b", "o")); // test they are applied in order assertEquals("foo", Strings.removeAllFromEnd("foobar", "ar", "car", "b", "ob")); assertEquals("foobar", Strings.removeAllFromEnd("foobar", "zz", "x")); } public void testRemoveFromStart() { assertEquals("", Strings.removeFromStart("", "foo")); assertEquals(null, Strings.removeFromStart(null, "foo")); assertEquals("bar", Strings.removeFromStart("foobar", "foo")); assertEquals("foo", Strings.removeFromStart("foo", "bar")); assertEquals("bar", Strings.removeFromStart("foobar", "foo", "bar")); assertEquals("obar", Strings.removeFromStart("foobar", "ob", "fo", "foo", "o")); } public void testRemoveAllFromStart() { assertEquals("", Strings.removeAllFromStart("", "foo")); assertEquals(null, Strings.removeAllFromStart(null, "foo")); assertEquals("bar", Strings.removeAllFromStart("foobar", "foo")); assertEquals("foo", Strings.removeAllFromStart("foo", "bar")); assertEquals("", Strings.removeAllFromStart("foobar", "foo", "bar")); assertEquals("ar", Strings.removeAllFromStart("foobar", "fo", "ob", "o")); assertEquals("ar", Strings.removeAllFromStart("foobar", "ob", "fo", "o")); // test they are applied in order, "ob" doesn't match because "o" eats the o assertEquals("bar", Strings.removeAllFromStart("foobar", "o", "fo", "ob")); } public void testRemoveFromStart2() { assertEquals(Strings.removeFromStart("xyz", "x"), "yz"); assertEquals(Strings.removeFromStart("xyz", "."), "xyz"); assertEquals(Strings.removeFromStart("http://foo.com", "http://"), "foo.com"); } public void testRemoveFromEnd2() { assertEquals(Strings.removeFromEnd("xyz", "z"), "xy"); assertEquals(Strings.removeFromEnd("xyz", "."), "xyz"); assertEquals(Strings.removeFromEnd("http://foo.com/", "/"), "http://foo.com"); } public void testReplaceAll() { assertEquals(Strings.replaceAll("xyz", "x", ""), "yz"); assertEquals(Strings.replaceAll("xyz", ".", ""), "xyz"); assertEquals(Strings.replaceAll("http://foo.com/", "/", ""), "http:foo.com"); assertEquals(Strings.replaceAll("http://foo.com/", "http:", "https:"), "https://foo.com/"); } public void testReplaceAllNonRegex() { assertEquals(Strings.replaceAllNonRegex("xyz", "x", ""), "yz"); assertEquals(Strings.replaceAllNonRegex("xyz", ".", ""), "xyz"); assertEquals(Strings.replaceAllNonRegex("http://foo.com/", "/", ""), "http:foo.com"); assertEquals(Strings.replaceAllNonRegex("http://foo.com/", "http:", "https:"), "https://foo.com/"); } public void testReplaceAllRegex() { assertEquals(Strings.replaceAllRegex("xyz", "x", ""), "yz"); assertEquals(Strings.replaceAllRegex("xyz", ".", ""), ""); assertEquals(Strings.replaceAllRegex("http://foo.com/", "/", ""), "http:foo.com"); assertEquals(Strings.replaceAllRegex("http://foo.com/", "http:", "https:"), "https://foo.com/"); } public void testReplaceMap() { assertEquals(Strings.replaceAll("xyz", MutableMap.builder().put("x","a").put("y","").build()), "az"); } public void testContainsLiteral() { assertTrue(Strings.containsLiteral("hello", "ell")); assertTrue(Strings.containsLiteral("hello", "h")); assertFalse(Strings.containsLiteral("hello", "H")); assertFalse(Strings.containsLiteral("hello", "O")); assertFalse(Strings.containsLiteral("hello", "x")); assertFalse(Strings.containsLiteral("hello", "ELL")); assertTrue(Strings.containsLiteral("hello", "hello")); assertTrue(Strings.containsLiteral("hELlo", "ELl")); assertFalse(Strings.containsLiteral("hello", "!")); } public void testContainsLiteralIgnoreCase() { assertTrue(Strings.containsLiteralIgnoreCase("hello", "ell")); assertTrue(Strings.containsLiteralIgnoreCase("hello", "H")); assertTrue(Strings.containsLiteralIgnoreCase("hello", "O")); assertFalse(Strings.containsLiteralIgnoreCase("hello", "X")); assertTrue(Strings.containsLiteralIgnoreCase("hello", "ELL")); assertTrue(Strings.containsLiteralIgnoreCase("hello", "hello")); assertTrue(Strings.containsLiteralIgnoreCase("hELlo", "Hello")); assertFalse(Strings.containsLiteralIgnoreCase("hello", "!")); } public void testSizeString() { + assertEquals(Strings.makeSizeString(0), "0b"); + assertEquals(Strings.makeSizeString(999), "999b"); + assertEquals(Strings.makeSizeString(1234), "1.23kb"); assertEquals(Strings.makeSizeString(23456789), "23.5mb"); + assertEquals(Strings.makeSizeString(23456789012L), "23.5gb"); + assertEquals(Strings.makeSizeString(23456789012345L), "2.35E4gb"); } }
false
false
null
null
diff --git a/src/org/eclipse/core/internal/localstore/RefreshLocalVisitor.java b/src/org/eclipse/core/internal/localstore/RefreshLocalVisitor.java index c061e133..6f28213e 100644 --- a/src/org/eclipse/core/internal/localstore/RefreshLocalVisitor.java +++ b/src/org/eclipse/core/internal/localstore/RefreshLocalVisitor.java @@ -1,322 +1,324 @@ /******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.core.internal.localstore; import org.eclipse.core.internal.resources.*; import org.eclipse.core.internal.utils.Policy; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; // /** * Visits a unified tree, and synchronizes the file system with the * resource tree. After the visit is complete, the file system will * be synchronized with the workspace tree with respect to * resource existence, gender, and timestamp. */ public class RefreshLocalVisitor implements IUnifiedTreeVisitor, ILocalStoreConstants { protected IProgressMonitor monitor; protected Workspace workspace; protected boolean resourceChanged; protected MultiStatus errors; /* * Fields for progress monitoring algorithm. * Initially, give progress for every 4 resources, double * this value at halfway point, then reset halfway point * to be half of remaining work. (this gives an infinite * series that converges at total work after an infinite * number of resources). */ public static final int TOTAL_WORK = 250; private int halfWay = TOTAL_WORK / 2; private int currentIncrement = 4; private int nextProgress = currentIncrement; private int worked = 0; /** control constants */ protected static final int RL_UNKNOWN = 0; protected static final int RL_IN_SYNC = 1; protected static final int RL_NOT_IN_SYNC = 2; public RefreshLocalVisitor(IProgressMonitor monitor) { this.monitor = monitor; workspace = (Workspace) ResourcesPlugin.getWorkspace(); resourceChanged = false; String msg = Policy.bind("resources.errorMultiRefresh"); //$NON-NLS-1$ errors = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.FAILED_READ_LOCAL, msg, null); } /** * This method has the same implementation as resourceChanged but as they are different * cases, we prefer to use different methods. */ protected void contentAdded(UnifiedTreeNode node, Resource target) throws CoreException { resourceChanged(node, target); } protected void createResource(UnifiedTreeNode node, Resource target) throws CoreException { ResourceInfo info = target.getResourceInfo(false, false); int flags = target.getFlags(info); if (target.exists(flags, false)) return; /* make sure target's parent exists */ if (node.getLevel() == 0) { IContainer parent = target.getParent(); if (parent.getType() == IResource.FOLDER) ((Folder) target.getParent()).ensureExists(monitor); } /* Use the basic file creation protocol since we don't want to create any content on disk. */ info = workspace.createResource(target, false); /* Mark this resource as having unknown children */ info.set(ICoreConstants.M_CHILDREN_UNKNOWN); target.getLocalManager().updateLocalSync(info, node.getLastModified()); } protected void deleteResource(UnifiedTreeNode node, Resource target) throws CoreException { ResourceInfo info = target.getResourceInfo(false, false); int flags = target.getFlags(info); //don't delete linked resources if (ResourceInfo.isSet(flags, ICoreConstants.M_LINK)) { //just clear local sync info info = target.getResourceInfo(false, true); - info.clearModificationStamp(); + //handle concurrent deletion + if (info != null) + info.clearModificationStamp(); return; } if (target.exists(flags, false)) target.deleteResource(true, null); node.setExistsWorkspace(false); } protected void fileToFolder(UnifiedTreeNode node, Resource target) throws CoreException { ResourceInfo info = target.getResourceInfo(false, false); int flags = target.getFlags(info); if (target.exists(flags, true)) { target = (Folder) ((File) target).changeToFolder(); } else { if (!target.exists(flags, false)) { target = (Resource) workspace.getRoot().getFolder(target.getFullPath()); // Use the basic file creation protocol since we don't want to create any content on disk. workspace.createResource(target, false); } } node.setResource(target); info = target.getResourceInfo(false, true); target.getLocalManager().updateLocalSync(info, node.getLastModified()); } protected void folderToFile(UnifiedTreeNode node, Resource target) throws CoreException { ResourceInfo info = target.getResourceInfo(false, false); int flags = target.getFlags(info); if (target.exists(flags, true)) target = (File) ((Folder) target).changeToFile(); else { if (!target.exists(flags, false)) { target = (Resource) workspace.getRoot().getFile(target.getFullPath()); // Use the basic file creation protocol since we don't want to // create any content on disk. workspace.createResource(target, false); } } node.setResource(target); info = target.getResourceInfo(false, true); target.getLocalManager().updateLocalSync(info, node.getLastModified()); } /** * Returns the status of the nodes visited so far. This will be a multi-status * that describes all problems that have occurred, or an OK status if everything * went smoothly. */ public IStatus getErrorStatus() { return errors; } /** * Refreshes the parent of a resource currently being synchronized. */ protected void refresh(Container parent) throws CoreException { parent.getLocalManager().refresh(parent, IResource.DEPTH_ZERO, false, null); } protected void resourceChanged(UnifiedTreeNode node, Resource target) throws CoreException { ResourceInfo info = target.getResourceInfo(false, true); if (info == null) return; target.getLocalManager().updateLocalSync(info, node.getLastModified()); info.incrementContentId(); // forget content-related caching flags info.clear(ICoreConstants.M_CONTENT_CACHE); workspace.updateModificationStamp(info); } public boolean resourcesChanged() { return resourceChanged; } /** * deletion or creation -- Returns: * - RL_IN_SYNC - the resource is in-sync with the file system * - RL_NOT_IN_SYNC - the resource is not in-sync with file system * - RL_UNKNOWN - couldn't determine the sync status for this resource */ protected int synchronizeExistence(UnifiedTreeNode node, Resource target, int level) throws CoreException { boolean existsInWorkspace = node.existsInWorkspace(); if (!existsInWorkspace) { if (!CoreFileSystemLibrary.isCaseSensitive() && level == 0) { // do we have any alphabetic variants on the workspace? IResource variant = target.findExistingResourceVariant(target.getFullPath()); if (variant != null) return RL_UNKNOWN; } // do we have a gender variant in the workspace? IResource genderVariant = workspace.getRoot().findMember(target.getFullPath()); if (genderVariant != null) return RL_UNKNOWN; } if (existsInWorkspace) { if (!node.existsInFileSystem()) { //non-local files are always in sync if (target.isLocal(IResource.DEPTH_ZERO)) { deleteResource(node, target); resourceChanged = true; return RL_NOT_IN_SYNC; } return RL_IN_SYNC; } } else { if (node.existsInFileSystem()) { if (!CoreFileSystemLibrary.isCaseSensitive()) { Container parent = (Container) target.getParent(); if (!parent.exists()) { refresh(parent); if (!parent.exists()) return RL_NOT_IN_SYNC; } if (!target.getName().equals(node.getLocalName())) return RL_IN_SYNC; } createResource(node, target); resourceChanged = true; return RL_NOT_IN_SYNC; } } return RL_UNKNOWN; } /** * gender change -- Returns true if gender was in sync. */ protected boolean synchronizeGender(UnifiedTreeNode node, Resource target) throws CoreException { if (!node.existsInWorkspace()) { //may be an existing resource in the workspace of different gender IResource genderVariant = workspace.getRoot().findMember(target.getFullPath()); if (genderVariant != null) target = (Resource) genderVariant; } if (target.getType() == IResource.FILE) { if (!node.isFile()) { fileToFolder(node, target); resourceChanged = true; return false; } } else { if (!node.isFolder()) { folderToFile(node, target); resourceChanged = true; return false; } } return true; } /** * lastModified */ protected void synchronizeLastModified(UnifiedTreeNode node, Resource target) throws CoreException { if (target.isLocal(IResource.DEPTH_ZERO)) resourceChanged(node, target); else contentAdded(node, target); resourceChanged = true; } public boolean visit(UnifiedTreeNode node) throws CoreException { Policy.checkCanceled(monitor); try { Resource target = (Resource) node.getResource(); int targetType = target.getType(); if (targetType == IResource.PROJECT) return true; if (node.existsInWorkspace() && node.existsInFileSystem()) { /* for folders we only care about updating local status */ if (targetType == IResource.FOLDER && node.isFolder()) { // if not local, mark as local if (!target.isLocal(IResource.DEPTH_ZERO)) { ResourceInfo info = target.getResourceInfo(false, true); if (info == null) return true; target.getLocalManager().updateLocalSync(info, node.getLastModified()); } return true; } /* compare file last modified */ if (targetType == IResource.FILE && node.isFile()) { ResourceInfo info = target.getResourceInfo(false, false); if (info != null && info.getLocalSyncInfo() == node.getLastModified()) return true; } } else { if (node.existsInFileSystem() && !Path.EMPTY.isValidSegment(node.getLocalName())) { String message = Policy.bind("resources.invalidResourceName", node.getLocalName()); //$NON-NLS-1$ errors.merge(new ResourceStatus(IResourceStatus.INVALID_RESOURCE_NAME, message)); return false; } int state = synchronizeExistence(node, target, node.getLevel()); if (state == RL_IN_SYNC || state == RL_NOT_IN_SYNC) { if (targetType == IResource.FILE) { try { ((File) target).updateMetadataFiles(); } catch (CoreException e) { errors.merge(e.getStatus()); } } return true; } } if (synchronizeGender(node, target)) synchronizeLastModified(node, target); if (targetType == IResource.FILE) { try { ((File) target).updateMetadataFiles(); } catch (CoreException e) { errors.merge(e.getStatus()); } } return true; } finally { if (--nextProgress <= 0) { //we have exhausted the current increment, so report progress monitor.worked(1); worked++; if (worked >= halfWay) { //we have passed the current halfway point, so double the //increment and reset the halfway point. currentIncrement *= 2; halfWay += (TOTAL_WORK - halfWay) / 2; } //reset the progress counter to another full increment nextProgress = currentIncrement; } } } } \ No newline at end of file
true
false
null
null
diff --git a/cadpage/src/net/anei/cadpage/vendors/Vendor.java b/cadpage/src/net/anei/cadpage/vendors/Vendor.java index 96d73ef2b..11bda0eff 100644 --- a/cadpage/src/net/anei/cadpage/vendors/Vendor.java +++ b/cadpage/src/net/anei/cadpage/vendors/Vendor.java @@ -1,482 +1,485 @@ package net.anei.cadpage.vendors; import net.anei.cadpage.C2DMReceiver; import net.anei.cadpage.HttpService; import net.anei.cadpage.SmsPopupUtils; import net.anei.cadpage.HttpService.HttpRequest; import net.anei.cadpage.ManagePreferences; import net.anei.cadpage.R; import net.anei.cadpage.donation.DonationManager; import net.anei.cadpage.donation.MainDonateEvent; import net.anei.cadpage.donation.UserAcctManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; abstract class Vendor { private String vendorCode; private int titleId; private int summaryId; private int textId; private int iconId; private int logoId; private Uri baseURI; private String triggerCode; private String emailAddress; private String title = null; private Uri discoverUri = null;; private SharedPreferences prefs; // True if vendor is active (ie has successfully registered with server private boolean enabled = false; // True if vendor was active, but was inactivated because the vendor failed // to respond to a reregister request private boolean broken = false; // True if we have have identified text pages coming from this vendor private boolean textPage = false; // True if we are in processing of registering with vendor server private boolean inProgress = false; // Account and security token used to identify user account to vendor private String account; private String token; // Vendor preference that may need to be updated when status changes private VendorPreference preference = null; // Vendor Activity that may need to be updated when status changes private VendorActivity activity = null; Vendor(int titleId, int summaryId, int textId, int iconId, int logoId, String urlString, String triggerCode, String emailAddress) { // Calculate vendor code by stripping "Vendor" off the end of the class name String clsName = this.getClass().getName(); int pt = clsName.lastIndexOf('.'); clsName = clsName.substring(pt+1); pt = clsName.indexOf("Vendor"); vendorCode = clsName.substring(0,pt); this.titleId = titleId; this.summaryId = summaryId; this.textId = textId; this.iconId = iconId; this.logoId = logoId; this.baseURI = Uri.parse(urlString); this.triggerCode = triggerCode; this.emailAddress = emailAddress; } /** * @return resource ID of text string name of this vendor */ int getTitleId() { return titleId; } /** * @return resource ID of text summary description of this vendor */ int getSummaryId() { return summaryId; } /** * @return vendor text description resource ID */ int getTextId() { return textId; } /** * @return vendor Icon resource ID */ int getIconId() { return iconId; } /** * @return vendor logo resource ID */ int getLogoId() { return logoId; } /** * @return vendor code by which this vendor is recognized */ String getVendorCode() { return vendorCode; } /** * @param request type of request this will be used for * @return base vendor URI that we use to communicate with this vendor */ Uri getBaseURI(String req) { return getBaseURI(); } /** * @return base vendor URI that we use to communicate with this vendor */ Uri getBaseURI() { return baseURI; } /** * @return trigger code at beginning of SMS text page that identifies this vendor */ String getTrigerCode() { return triggerCode; } /** * @return support email address */ String getEmailAddress() { return emailAddress; } /** * @return true if users registered with this vendor are sponsored by the agency */ boolean isSponsored() { return false; } /** * @return true if service is up and running and should be available for everyone, * false if should only be available for developers */ boolean isAvailable() { return false; } /** * Register VendorPreference associated with this vendor * @param preference Vendor preference object */ void registerPreference(VendorPreference preference) { this.preference = preference; } /** * Register Activity associated with this vendor * @param activity vendor activity */ void registerActivity(VendorActivity activity) { this.activity = activity; } /** * Perform initial setup that requires a context * @param context current context */ void setup(Context context) { title = context.getString(titleId); prefs = context.getSharedPreferences(vendorCode + "Vendor", Context.MODE_PRIVATE); enabled = prefs.getBoolean("enabled", false); broken = prefs.getBoolean("broken", false); account = prefs.getString("account", null); token = prefs.getString("token", null); textPage = prefs.getBoolean("textPage", false); } /** * @return Name of sponsoring agency if an active vendor is sponsoring Cadpage */ public String getSponsor() { if (isSponsored() && isEnabled()) return title; return null; } /** * Save the critical status members to persistant storage */ private void saveStatus() { SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("enabled", enabled); editor.putBoolean("broken", broken); editor.putString("account", account); editor.putString("token", token); editor.commit(); } /** * Set the text page received flag to selected value * @param textPage new value */ public void setTextPage(boolean textPage) { if (enabled) return; if (textPage == this.textPage) return; this.textPage = textPage; SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("textPage", textPage); editor.commit(); } /** * Append vendor status info to logging buffer * @param sb String buffer accumulated log information */ void addStatusInfo(StringBuilder sb) { sb.append("\n\nVendor:" + vendorCode); sb.append("\nenabled:" + enabled); sb.append("\nbroken:" + broken); sb.append("\ntextPage:" + textPage); if (enabled || broken) { sb.append("\naccount:" + account); sb.append("\ntoken:" + token); } } /** * @return enabled status of vendor */ boolean isEnabled() { return enabled; } /** * @return broken status of vendor */ boolean isBroken() { return broken; } /** * Process user request for more information about vendor * @param context current context */ void moreInfoReq(Context context) { + if (!SmsPopupUtils.haveNet(context)) return; Uri uri; if (!enabled) { uri = baseURI.buildUpon().appendQueryParameter("req", "info").build(); } else { uri = buildRequestUri("profile", ManagePreferences.registrationId()); } viewPage(context, uri); } /** * Process user request to register with vendor * @param context Current context */ void registerReq(Context context) { registerReq(context, null); } /** * Process vendor discovery request * @param context current context * @param uri URI included in discover request or null if user request */ public void registerReq(Context context, Uri uri) { // If already enabled, we don't have to do anything if (enabled) { reconnect(context); return; } - + + // Make sure we have network connectivity + if (!SmsPopupUtils.haveNet(context)) return; + // Set registration in progress flag // and save the discovery URI inProgress = true; discoverUri = uri; // See if we already have a registration ID, if we do, use it to send // registration request to vendor server String regId = ManagePreferences.registrationId(); if (regId != null) { registerC2DMId(context, regId); } // If we don't request one and and send the request to the server when // it comes back in else { C2DMReceiver.register(context); } } /** * Process user request to unregister from this service * @param context current context */ void unregisterReq(Context context) { if (!enabled) return; // Disable access and save that status change enabled = false; saveStatus(); reportStatusChange(); // Send an unregister request to the vendor server // we really don't care how it responds Uri uri = buildRequestUri("unregister", ManagePreferences.registrationId()); HttpService.addHttpRequest(context, new HttpRequest(uri){}); // Finally unregister from Google C2DM service. If there are other vendor // services that are still active, they will request a new registration ID C2DMReceiver.unregister(context); } /** * Called when a new or changed C2DM registration ID is reported * @param context current context * @param registrationId registration ID */ void registerC2DMId(final Context context, String registrationId) { // If we are in process of registering with server, send the web registration request if (inProgress) { // If we got a discovery URI from the vendor, send directly to that // It isn't our problem if it isn't accepted if (discoverUri != null) { Uri uri = discoverUri.buildUpon().appendQueryParameter("CadpageRegId", registrationId).build(); HttpService.addHttpRequest(context, new HttpRequest(uri){}); } // Otherwise build a registration URL and display it in the web browser else { Uri uri = buildRequestUri("register", registrationId); viewPage(context, uri); } inProgress = false; discoverUri = null; } // Otherwise, if we are registered with this server, pass the new registration // ID to them else if (enabled) { sendReregister(context, registrationId); } } /** * Send current registration ID to vendor * @param context current context */ void reconnect(Context context) { if (enabled || broken) { String registrationId = ManagePreferences.registrationId(); if (registrationId != null) sendReregister(context, registrationId); } } /** * Send reregister request to vendor * @param context current context * @param registrationId registration ID */ private void sendReregister(final Context context, String registrationId) { Uri uri = buildRequestUri("reregister", registrationId); HttpService.addHttpRequest(context, new HttpService.HttpRequest(uri){ @Override public void processError(int status, String result) { // If response was successful, we don't care about any details if (status % 100 == 2) return; showNotice(context, R.string.vendor_register_err_msg, result); enabled = false; broken = (status != 400); saveStatus(); reportStatusChange(); }}); } /** * Handle vendor register/unregister request * @param context current context * @param type REGISTER/UNREGISTER request type * @param account vendor account * @param token vendor security token */ void vendorRequest(Context context, String type, String account, String token) { boolean register = type.equals("REGISTER"); boolean change = (this.enabled != register); this.enabled = register; this.broken = false; this.account = account; this.token = token; saveStatus(); if (change) { reportStatusChange(); showNotice(context, register ? R.string.vendor_connect_msg : R.string.vendor_disconnect_msg, null); if (register) setTextPage(false); else C2DMReceiver.unregister(context); } } /** * Report enabled status change to all interested parties */ private void reportStatusChange() { if (isSponsored()) { DonationManager.instance().reset(); MainDonateEvent.instance().refreshStatus(); } if (preference != null) preference.update(); if (activity != null) activity.update(); } /** * Build a request URI * @param req request type * @param registrationId registration ID * @return request URI */ private Uri buildRequestUri(String req, String registrationId) { String phone = UserAcctManager.instance().getPhoneNumber(); Uri.Builder builder = getBaseURI(req).buildUpon(); builder = builder.appendQueryParameter("req", req); builder = builder.appendQueryParameter("vendor", getVendorCode()); if (account != null) builder = builder.appendQueryParameter("account", account); if (token != null) builder = builder.appendQueryParameter("token", token); if (phone != null) builder = builder.appendQueryParameter("phone", phone); builder = builder.appendQueryParameter("type", "C2DM"); if (registrationId != null) builder = builder.appendQueryParameter("CadpageRegId", registrationId); // Add random seed to register request to defeat any browser cache if (req.equals("register")) builder = builder.appendQueryParameter("seed", "" + System.currentTimeMillis() % 10000); return builder.build(); } /** * Display direct paging notification to user * @param context current context * @param msgId message resource ID */ private void showNotice(Context context, int msgId, String extra) { String title = context.getString(titleId); String message = context.getString(msgId, title, extra); NoticeActivity.showNotice(context, message); } /** * Display selected URI in web viewer * @param context current context * @param uri URI to be displayed */ private void viewPage(Context context, Uri uri) { - if (!SmsPopupUtils.haveNet(context)) return; Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } }
false
false
null
null
diff --git a/src/org/liberty/android/fantastischmemo/EditScreen.java b/src/org/liberty/android/fantastischmemo/EditScreen.java index d46357be..00a3f0dd 100644 --- a/src/org/liberty/android/fantastischmemo/EditScreen.java +++ b/src/org/liberty/android/fantastischmemo/EditScreen.java @@ -1,609 +1,615 @@ /* Copyright (C) 2010 Haowen Ning 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. */ package org.liberty.android.fantastischmemo; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.Date; import android.graphics.Color; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnDismissListener; import android.os.Bundle; import android.content.Context; import android.preference.PreferenceManager; import android.text.Html; import android.view.Gravity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.Display; import android.view.WindowManager; import android.view.LayoutInflater; import android.widget.Button; import android.widget.ImageButton; import android.os.Handler; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.EditText; import android.util.Log; import android.os.SystemClock; import android.net.Uri; import android.gesture.Gesture; import android.gesture.GestureLibraries; import android.gesture.GestureLibrary; import android.gesture.GestureOverlayView; import android.gesture.Prediction; import android.gesture.GestureOverlayView.OnGesturePerformedListener; public class EditScreen extends MemoScreenBase implements OnGesturePerformedListener, View.OnClickListener{ private int currentId = -1; private int totalItem = -1; private int maxId = -1; private Context mContext; private GestureLibrary mLibrary; private Button newButton; private Button nextButton; private Button prevButton; private Item savedItem = null; private Item copyItem = null; private boolean searchInflated = false; private final int ACTIVITY_MERGE = 10; private static final String TAG = "org.liberty.android.fantastischmemo.EditScreen"; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.memo_screen_gesture); Bundle extras = getIntent().getExtras(); if(extras != null) { if(currentId < 0){ currentId = extras.getInt("openid", 1); } } mContext = this; mHandler = new Handler(); /* Initiate the gesture */ mLibrary = GestureLibraries.fromRawResource(this, R.raw.gestures); if (!mLibrary.load()) { finish(); } GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gesture_overlay); gestures.addOnGesturePerformedListener(this); createButtons(); buttonBinding(); if(prepare() == false){ new AlertDialog.Builder(mContext) .setTitle(getString(R.string.open_database_error_title)) .setMessage(getString(R.string.open_database_error_message)) .setPositiveButton(getString(R.string.back_menu_text), new OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { finish(); } }) .setNegativeButton(getString(R.string.help_button_text), new OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { Intent myIntent = new Intent(); myIntent.setAction(Intent.ACTION_VIEW); myIntent.addCategory(Intent.CATEGORY_BROWSABLE); myIntent.setData(Uri.parse(getString(R.string.website_help_error_open))); startActivity(myIntent); finish(); } }) .create() .show(); } } @Override public void onDestroy(){ super.onDestroy(); try{ dbHelper.close(); } catch(Exception e){ } } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt("id", currentId); super.onSaveInstanceState(outState); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); currentId = savedInstanceState.getInt("id", 1); prepare(); } @Override public void onClick(View v){ if(v == newButton){ createNewItem(); } else if(v == nextButton){ getNextItem(); } else if(v == prevButton){ getPreviousItem(); } else if(v == (ImageButton)findViewById(R.id.search_close_btn)){ dismissSearchOverlay(); } else if(v == (ImageButton)findViewById(R.id.search_next_btn)){ doSearch(true); } else if(v == (ImageButton)findViewById(R.id.search_previous_btn)){ doSearch(false); } } @Override protected boolean prepare(){ if(dbHelper == null){ try{ dbHelper = new DatabaseHelper(mContext, dbPath, dbName); } catch(Exception e){ Log.e(TAG, "Error" + e.toString(), e); return false; } } loadSettings(); maxId = dbHelper.getNewId() - 1; totalItem = dbHelper.getTotalCount(); if(totalItem <= 0){ /* Ask user to create a new card when the db is empty */ createNewItem(); } else{ if(currentId < 1){ currentId = 1; } else if(currentId > maxId){ currentId = maxId; } currentItem = dbHelper.getItemById(currentId, 0, true, activeFilter); /* Re-fetch the id in case that the item with id 1 is * deleted. */ currentId = currentItem.getId(); setTitle(getString(R.string.stat_total) + totalItem); updateMemoScreen(); } return true; } @Override protected int feedData(){ /* Dummy feed Data */ return 1; } @Override public boolean onCreateOptionsMenu(Menu menu){ MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.edit_screen_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){ Intent myIntent = new Intent(); switch (item.getItemId()) { case R.id.editmenu_help: myIntent.setAction(Intent.ACTION_VIEW); myIntent.addCategory(Intent.CATEGORY_BROWSABLE); myIntent.setData(Uri.parse(getString(R.string.website_help_edit))); startActivity(myIntent); return true; case R.id.editmenu_search_id: createSearchOverlay(); return true; case R.id.editmenu_edit_id: doEdit(); return true; case R.id.editmenu_delete_id: doDelete(); return true; case R.id.editmenu_detail_id: myIntent.setClass(this, DetailScreen.class); myIntent.putExtra("dbname", dbName); myIntent.putExtra("dbpath", dbPath); myIntent.putExtra("itemid", currentItem.getId()); startActivityForResult(myIntent, 2); return true; case R.id.editmenu_settings_id: myIntent.setClass(this, SettingsScreen.class); myIntent.putExtra("dbname", dbName); myIntent.putExtra("dbpath", dbPath); startActivityForResult(myIntent, 1); //finish(); return true; case R.id.menu_edit_filter: doFilter(); return true; case R.id.editmenu_list_id: myIntent.setClass(this, ListEditScreen.class); myIntent.putExtra("dbname", dbName); myIntent.putExtra("dbpath", dbPath); myIntent.putExtra("openid", currentItem.getId()); startActivity(myIntent); return true; case R.id.editmenu_merge_id: myIntent.setClass(this, FileBrowser.class); myIntent.putExtra("default_root", dbPath); myIntent.putExtra("file_extension", ".db"); startActivityForResult(myIntent, ACTIVITY_MERGE); return true; case R.id.editmenu_copy_id: doCopy(); return true; case R.id.editmenu_paste_id: doPaste(); return true; } return false; } @Override public void onActivityResult(int requestCode, int resultCode, final Intent data){ super.onActivityResult(requestCode, resultCode, data); final int request = requestCode; if(resultCode == Activity.RESULT_OK){ if(requestCode == ACTIVITY_MERGE){ new AlertDialog.Builder(this) .setTitle(R.string.merge_method_title) .setMessage(R.string.merge_method_message) .setPositiveButton(R.string.merge_method_here, new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface arg0, int arg1) { doMerge(data); } }) .setNeutralButton(R.string.merge_method_end, new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface arg0, int arg1) { /* set the current item to the last one */ currentItem = dbHelper.getItemById(maxId, 0, true, activeFilter); currentId = currentItem.getId(); doMerge(data); } }) .create() .show(); returnValue = 0; } } } @Override protected void createButtons(){ /* Inflate buttons from XML */ LinearLayout root = (LinearLayout)findViewById(R.id.layout_buttons); LayoutInflater.from(this).inflate(R.layout.edit_screen_buttons, root); newButton = (Button)findViewById(R.id.edit_screen_btn_new); prevButton = (Button)findViewById(R.id.edit_screen_btn_prev); nextButton = (Button)findViewById(R.id.edit_screen_btn_next); } @Override protected void buttonBinding(){ newButton.setOnClickListener(this); nextButton.setOnClickListener(this); prevButton.setOnClickListener(this); } @Override protected boolean fetchCurrentItem(){ /* Dummy, there is no queue in this activity */ return true; } @Override protected void restartActivity(){ //loadSettings(); //updateMemoScreen(); Intent myIntent = new Intent(this, EditScreen.class); myIntent.putExtra("dbname", dbName); myIntent.putExtra("dbpath", dbPath); myIntent.putExtra("openid", currentItem.getId()); + myIntent.putExtra("active_filter", activeFilter); finish(); startActivity(myIntent); } @Override protected void refreshAfterEditItem(){ int max = dbHelper.getNewId() - 1; if(max != maxId){ currentId = max; prepare(); } else if(max == 0){ /* If user cancel editing, * it will exit the activity. */ finish(); } else{ if(savedItem != null){ currentItem = savedItem; } } } @Override protected void refreshAfterDeleteItem(){ setTitle(getString(R.string.stat_total) + totalItem); updateMemoScreen(); prepare(); } @Override public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture){ ArrayList<Prediction> predictions = mLibrary.recognize(gesture); // We want at least one prediction if (predictions.size() > 0) { Prediction prediction = predictions.get(0); // We want at least some confidence in the result if (prediction.score > 1.0) { // Show the spell Log.v(TAG, "Gesture: " + prediction.name); if(prediction.name.equals("swipe-right")){ getPreviousItem(); } else if(prediction.name.equals("swipe-left")){ getNextItem(); } else if(prediction.name.equals("o") || prediction.name.equals("o2")){ doEdit(); } else if(prediction.name.equals("cross")){ doDelete(); } } } } private void getNextItem(){ if(totalItem > 0){ currentId += 1; currentItem = dbHelper.getItemById(currentId, 0, true, activeFilter); if(currentItem == null){ currentItem = dbHelper.getItemById(0, 0, true, activeFilter); } } if(currentItem != null){ currentId = currentItem.getId(); setTitle(getString(R.string.stat_total) + totalItem); updateMemoScreen(); } else{ showFilterFailureDialog(); } } private void getPreviousItem(){ if(totalItem > 0){ currentId -= 1; currentItem = dbHelper.getItemById(currentId, 0, false, activeFilter); if(currentItem == null){ currentItem = dbHelper.getItemById(maxId, 0, false, activeFilter); } } if(currentItem != null){ currentId = currentItem.getId(); setTitle(getString(R.string.stat_total) + totalItem); updateMemoScreen(); } else{ showFilterFailureDialog(); } } private void createNewItem(){ /* Reuse the doEdit to get the edit dialog * and display the edit dialog */ savedItem = currentItem; Item newItem = new Item(); newItem.setId(dbHelper.getNewId()); if(currentItem != null){ newItem.setCategory(currentItem.getCategory()); } currentItem = newItem; doEdit(); } private void createSearchOverlay(){ if(searchInflated == false){ LinearLayout root = (LinearLayout)findViewById(R.id.memo_screen_root); LayoutInflater.from(this).inflate(R.layout.search_overlay, root); ImageButton close = (ImageButton)findViewById(R.id.search_close_btn); close.setOnClickListener(this); ImageButton prev = (ImageButton)findViewById(R.id.search_previous_btn); prev.setOnClickListener(this); ImageButton next = (ImageButton)findViewById(R.id.search_next_btn); next.setOnClickListener(this); searchInflated = true; } else{ LinearLayout layout = (LinearLayout)findViewById(R.id.search_root); layout.setVisibility(View.VISIBLE); } } private void dismissSearchOverlay(){ if(searchInflated == true){ LinearLayout layout = (LinearLayout)findViewById(R.id.search_root); layout.setVisibility(View.GONE); } } private void doSearch(boolean forward){ EditText et = (EditText)findViewById(R.id.search_entry); String text = et.getText().toString(); boolean processed = false; + Item searchItem = null; if(text.charAt(0) == '#'){ String num = text.substring(1); int intNum = 0; try{ intNum = Integer.parseInt(num); if(intNum > 0 && intNum <= maxId){ - currentItem = dbHelper.getItemById(intNum, 0, true, activeFilter); - if(currentItem != null){ + searchItem = dbHelper.getItemById(intNum, 0, true, activeFilter); + if(searchItem != null){ currentId = intNum; + currentItem = searchItem; prepare(); processed = true; return; } } } catch(NumberFormatException e){ } } if(processed == false && !text.equals("")){ text = text.replace('*', '%'); text = text.replace('?', '_'); int resId = dbHelper.searchItem(currentItem.getId(), text, forward); if(resId > 0){ - currentItem = dbHelper.getItemById(resId, 0, forward, activeFilter); - currentId = currentItem.getId(); - prepare(); + searchItem = dbHelper.getItemById(resId, 0, forward, activeFilter); + if(searchItem != null){ + currentItem = searchItem; + currentId = searchItem.getId(); + prepare(); + } } } } private void doMerge(final Intent data){ final ProgressDialog progressDialog = ProgressDialog.show(this, getString(R.string.merging_title), getString(R.string.merging_summary), true); new Thread(){ @Override public void run(){ final String name = data.getStringExtra("org.liberty.android.fantastischmemo.dbName"); final String path = data.getStringExtra("org.liberty.android.fantastischmemo.dbPath"); try{ dbHelper.mergeDatabase(path, name, currentId); } catch(final Exception e){ mHandler.post(new Runnable(){ @Override public void run(){ progressDialog.dismiss(); new AlertDialog.Builder(mContext) .setTitle(R.string.merge_fail_title) .setMessage(getString(R.string.merge_fail_message) + " " + e.toString()) .setPositiveButton(R.string.ok_text, null) .create() .show(); } }); } mHandler.post(new Runnable(){ @Override public void run(){ progressDialog.dismiss(); new AlertDialog.Builder(EditScreen.this) .setTitle(R.string.merge_success_title) .setMessage(getString(R.string.merge_success_message) + " " + dbName + ", " + name) .setPositiveButton(R.string.ok_text, new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface arg0, int arg1) { restartActivity(); } }) .create() .show(); } }); } }.start(); } private void doCopy(){ copyItem = currentItem; } private void doPaste(){ if(copyItem != null){ dbHelper.insertItem(copyItem, currentId); currentId += 1; prepare(); } } }
false
false
null
null
diff --git a/ak/MultiToolHolders/ItemMultiToolHolder.java b/ak/MultiToolHolders/ItemMultiToolHolder.java index 53a3cca..fca6dbd 100644 --- a/ak/MultiToolHolders/ItemMultiToolHolder.java +++ b/ak/MultiToolHolders/ItemMultiToolHolder.java @@ -1,691 +1,692 @@ package ak.MultiToolHolders; import static net.minecraftforge.client.IItemRenderer.ItemRenderType.*; import java.io.DataOutputStream; import java.util.List; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.ItemRenderer; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.enchantment.EnchantmentThorns; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.EnumAction; import net.minecraft.item.Item; import net.minecraft.item.ItemDye; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.potion.Potion; import net.minecraft.stats.AchievementList; import net.minecraft.stats.StatList; import net.minecraft.storagebox.ItemStorageBox; import net.minecraft.util.DamageSource; import net.minecraft.util.Icon; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraftforge.client.IItemRenderer; import net.minecraftforge.client.MinecraftForgeClient; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.player.AttackEntityEvent; import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import ak.MultiToolHolders.Client.MTHKeyHandler; import com.google.common.io.ByteArrayDataInput; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.network.PacketDispatcher; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class ItemMultiToolHolder extends Item implements IItemRenderer { public int SlotNum; public ToolHolderData tools; private Random rand = new Random(); private int Slotsize; private boolean OpenKeydown; private boolean NextKeydown; private boolean PrevKeydown; private Minecraft mc; public ItemMultiToolHolder(int par1, int slot) { super(par1); this.hasSubtypes = true; this.setMaxStackSize(1); this.Slotsize = slot; this.SlotNum = 0; } public void addInformation(ItemStack item, EntityPlayer player, List list, boolean advToolTio) { String ToolName; int SlotNum; if(item != null && item.getItem() instanceof ItemMultiToolHolder) { ToolHolderData tooldata = ItemMultiToolHolder.getToolData(item, player.worldObj); SlotNum = ((ItemMultiToolHolder)item.getItem()).SlotNum; if(tooldata != null) { if(tooldata.getStackInSlot(SlotNum) != null) { if(MultiToolHolders.loadSB && tooldata.getStackInSlot(SlotNum).getItem() instanceof ItemStorageBox) { tooldata.getStackInSlot(SlotNum).getItem().addInformation(tooldata.getStackInSlot(SlotNum), player, list, advToolTio); } else { ToolName = tooldata.getStackInSlot(SlotNum).getDisplayName(); list.add(ToolName); } } } } } @SideOnly(Side.CLIENT) public boolean isFull3D() { if(this.tools !=null && this.tools.getStackInSlot(SlotNum) != null) return this.tools.getStackInSlot(SlotNum).getItem().isFull3D(); else return false; } @SideOnly(Side.CLIENT) @Override public boolean handleRenderType(ItemStack item, ItemRenderType type) { return type == ItemRenderType.EQUIPPED; } @SideOnly(Side.CLIENT) @Override public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { ToolHolderData tooldata = ((ItemMultiToolHolder)item.getItem()).tools; if(tooldata != null && tooldata.getStackInSlot(SlotNum) != null) { ItemStack tool = tooldata.getStackInSlot(SlotNum); IItemRenderer customRenderer = MinecraftForgeClient.getItemRenderer(tool, EQUIPPED); if(customRenderer != null) return customRenderer.shouldUseRenderHelper(type, tool, helper); else return helper == ItemRendererHelper.EQUIPPED_BLOCK; } else return helper == ItemRendererHelper.EQUIPPED_BLOCK; } @SideOnly(Side.CLIENT) @Override public void renderItem(ItemRenderType type, ItemStack item, Object... data) { ToolHolderData tooldata = ((ItemMultiToolHolder)item.getItem()).tools;//this.getData(item, ((EntityLiving) data[1]).worldObj); if(tooldata != null && tooldata.getStackInSlot(SlotNum) != null) { ItemStack tool = tooldata.getStackInSlot(SlotNum); IItemRenderer customRenderer = MinecraftForgeClient.getItemRenderer(tool, EQUIPPED); if(customRenderer !=null) customRenderer.renderItem(type, tool, data); else renderToolHolder((EntityLiving) data[1], tool); } else { renderToolHolder((EntityLiving) data[1], item); } } @SideOnly(Side.CLIENT) public void renderToolHolder(EntityLiving entity, ItemStack stack) { mc = Minecraft.getMinecraft(); Icon icon = entity.getItemIcon(stack, 0); if (icon == null) { // GL11.glPopMatrix(); return; } if (stack.getItemSpriteNumber() == 0) { this.mc.renderEngine.bindTexture("/terrain.png"); } else { this.mc.renderEngine.bindTexture("/gui/items.png"); } GL11.glTranslatef(0.5F, 0.5F, 0.5F); Tessellator tessellator = Tessellator.instance; float f = icon.getMinU(); float f1 = icon.getMaxU(); float f2 = icon.getMinV(); float f3 = icon.getMaxV(); float f4 = 0.0F; float f5 = 0.3F; GL11.glEnable(GL12.GL_RESCALE_NORMAL); GL11.glTranslatef(-f4, -f5, 0.0F); float f6 = 1.5F; GL11.glScalef(f6, f6, f6); GL11.glRotatef(50.0F, 0.0F, 1.0F, 0.0F); GL11.glRotatef(335.0F, 0.0F, 0.0F, 1.0F); GL11.glTranslatef(-0.9375F, -0.0625F, 0.0F); RenderManager.instance.itemRenderer.renderItemIn2D(tessellator, f1, f2, f, f3, icon.getSheetWidth(), icon.getSheetHeight(), 0.0625F); if (stack != null && stack.hasEffect()/* && par3 == 0*/) { GL11.glDepthFunc(GL11.GL_EQUAL); GL11.glDisable(GL11.GL_LIGHTING); this.mc.renderEngine.bindTexture("%blur%/misc/glint.png"); GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_COLOR, GL11.GL_ONE); float f7 = 0.76F; GL11.glColor4f(0.5F * f7, 0.25F * f7, 0.8F * f7, 1.0F); GL11.glMatrixMode(GL11.GL_TEXTURE); GL11.glPushMatrix(); float f8 = 0.125F; GL11.glScalef(f8, f8, f8); float f9 = (float)(Minecraft.getSystemTime() % 3000L) / 3000.0F * 8.0F; GL11.glTranslatef(f9, 0.0F, 0.0F); GL11.glRotatef(-50.0F, 0.0F, 0.0F, 1.0F); ItemRenderer.renderItemIn2D(tessellator, 0.0F, 0.0F, 1.0F, 1.0F, 256, 256, 0.0625F); GL11.glPopMatrix(); GL11.glPushMatrix(); GL11.glScalef(f8, f8, f8); f9 = (float)(Minecraft.getSystemTime() % 4873L) / 4873.0F * 8.0F; GL11.glTranslatef(-f9, 0.0F, 0.0F); GL11.glRotatef(10.0F, 0.0F, 0.0F, 1.0F); ItemRenderer.renderItemIn2D(tessellator, 0.0F, 0.0F, 1.0F, 1.0F, 256, 256, 0.0625F); GL11.glPopMatrix(); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glDisable(GL11.GL_BLEND); GL11.glEnable(GL11.GL_LIGHTING); GL11.glDepthFunc(GL11.GL_LEQUAL); } GL11.glDisable(GL12.GL_RESCALE_NORMAL); } @SideOnly(Side.CLIENT) public static void renderToolsInfo(ItemStack item) { Minecraft mc = Minecraft.getMinecraft(); String name = item.getDisplayName(); int meta = item.getItemDamage(); int wide = mc.displayWidth; int height = mc.displayHeight; ScaledResolution sr = new ScaledResolution(mc.gameSettings, wide, height); wide = sr.getScaledWidth(); height = sr.getScaledHeight(); mc.fontRenderer.drawString(name, MultiToolHolders.toolTipX, height - MultiToolHolders.toolTipY, ItemDye.dyeColors[15]); mc.fontRenderer.drawString(String.valueOf(meta), MultiToolHolders.toolTipX, height - MultiToolHolders.toolTipY +10, ItemDye.dyeColors[15]); } public void onUpdate(ItemStack item, World world, Entity entity, int par4, boolean par5) { if (entity instanceof EntityPlayer && par5) { EntityPlayer entityPlayer = (EntityPlayer) entity; // ItemMultiToolHolder toolholder = (ItemMultiToolHolder) item.getItem(); ItemStack nowItem; Side side = FMLCommonHandler.instance().getEffectiveSide(); if(side.isServer()) { this.tools = this.getData(item, world); this.tools.onUpdate(world, entityPlayer); this.tools.onInventoryChanged(); } if (item.hasTagCompound()) { item.getTagCompound().removeTag("ench"); } if(this.tools != null && this.tools.getStackInSlot(SlotNum) != null) { nowItem = this.tools.getStackInSlot(SlotNum); nowItem.getItem().onUpdate(nowItem, world, entity, par4, par5); this.setEnchantments(item, nowItem); } if(par5 && (entityPlayer.openContainer == null || !(entityPlayer.openContainer instanceof ContainerToolHolder))) { if(side.isClient()) { this.NextKeydown = MTHKeyHandler.nextKeydown && MTHKeyHandler.nextKeyup; this.PrevKeydown = MTHKeyHandler.prevKeydown && MTHKeyHandler.prevKeyup; String name; int meta; String display; if(this.NextKeydown) { MTHKeyHandler.nextKeyup = false; this.SlotNum++; if(this.SlotNum == this.Slotsize) this.SlotNum = 0; } else if(this.PrevKeydown) { MTHKeyHandler.prevKeyup = false; this.SlotNum--; if(this.SlotNum == -1) this.SlotNum = this.Slotsize - 1; } if((this.NextKeydown || this.PrevKeydown) && this.tools != null && this.tools.getStackInSlot(SlotNum) != null) { nowItem = this.tools.getStackInSlot(SlotNum); name = nowItem.getDisplayName(); meta = nowItem.getMaxDamage() - nowItem.getItemDamage(); display = String.format("%s duration:%d", name, meta); if(MultiToolHolders.loadSB && nowItem.getItem() instanceof ItemStorageBox && ItemStorageBox.peekItemStackAll(nowItem) != null) { ItemStack storaged = ItemStorageBox.peekItemStackAll(nowItem); name = storaged.getDisplayName(); meta = storaged.stackSize; display = String.format("%s Stack:%d", name,meta); } entityPlayer.addChatMessage(display); } this.OpenKeydown = MTHKeyHandler.openKeydown && MTHKeyHandler.openKeyup; PacketDispatcher.sendPacketToServer(PacketHandler.getPacketTool(this)); } if(this.OpenKeydown) { MTHKeyHandler.openKeyup = false; int GuiID = (this.Slotsize == 3)? MultiToolHolders.guiIdHolder3:(this.Slotsize == 5)? MultiToolHolders.guiIdHolder5:(this.Slotsize == 7)? MultiToolHolders.guiIdHolder7:MultiToolHolders.guiIdHolder9; entityPlayer.openGui(MultiToolHolders.instance, GuiID, world, 0, 0, 0); } } } } public static ToolHolderData getToolData(ItemStack item, World world) { ToolHolderData tooldata = null; if(item != null && item.getItem() instanceof ItemMultiToolHolder) { tooldata = ((ItemMultiToolHolder)item.getItem()).getData(item, world); } return tooldata; } public ToolHolderData getData(ItemStack var1, World var2) { String itemName = "Holder" + this.Slotsize; int itemDamage = var1.getItemDamage(); String var3 = String.format("%s_%s", itemName, itemDamage);; ToolHolderData var4 = (ToolHolderData)var2.loadItemData(ToolHolderData.class, var3); if (var4 == null) { var4 = new ToolHolderData(var3); var4.markDirty(); var2.setItemData(var3, var4); } return var4; } private void makeData(ItemStack var1, World var2) { String itemName = "Holder" + this.Slotsize; var1.setItemDamage(var2.getUniqueDataId(itemName)); int itemDamage = var1.getItemDamage(); String var3 = String.format("%s_%s", itemName, itemDamage);; ToolHolderData var4 = new ToolHolderData(var3); var4.markDirty(); var2.setItemData(var3, var4); } public void onCreated(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer) { if (par1ItemStack.getItem() instanceof ItemMultiToolHolder) { this.makeData(par1ItemStack, par2World); } } public boolean onLeftClickEntity(ItemStack stack, EntityPlayer player, Entity entity) { if(this.tools.getStackInSlot(SlotNum) != null) { this.attackTargetEntityWithTheItem(entity, player, this.tools.getStackInSlot(SlotNum)); return true; } else return false; } public boolean onItemUseFirst(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { if(this.tools !=null && this.tools.getStackInSlot(SlotNum) != null) { boolean ret = this.tools.getStackInSlot(SlotNum).getItem().onItemUseFirst(this.tools.getStackInSlot(SlotNum), player, world, x, y, z, side, hitX, hitY, hitZ); if (this.tools.getStackInSlot(SlotNum).stackSize <= 0) { this.destroyTheItem(player, this.tools.getStackInSlot(SlotNum)); } return ret; } else return false; } public boolean onItemUse(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, World par3World, int par4, int par5, int par6, int par7, float par8, float par9, float par10) { if(this.tools !=null && this.tools.getStackInSlot(SlotNum) != null) { boolean ret = this.tools.getStackInSlot(SlotNum).getItem().onItemUse(this.tools.getStackInSlot(SlotNum), par2EntityPlayer, par3World, par4, par5, par6, par7, par8, par9, par10); if (this.tools.getStackInSlot(SlotNum).stackSize <= 0) { this.destroyTheItem(par2EntityPlayer, this.tools.getStackInSlot(SlotNum)); } return ret; } else return false; } public void onPlayerStoppedUsing(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer, int par4) { if(this.tools !=null && this.tools.getStackInSlot(SlotNum) != null) { this.tools.getStackInSlot(SlotNum).getItem().onPlayerStoppedUsing(this.tools.getStackInSlot(SlotNum), par2World, par3EntityPlayer, par4); if (this.tools.getStackInSlot(SlotNum).stackSize <= 0) { this.destroyTheItem( par3EntityPlayer, this.tools.getStackInSlot(SlotNum)); } } } public ItemStack onEaten(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer) { if(this.tools !=null && this.tools.getStackInSlot(SlotNum) != null) { this.tools.getStackInSlot(SlotNum).getItem().onEaten(this.tools.getStackInSlot(SlotNum), par2World, par3EntityPlayer); } return par1ItemStack; } public ItemStack onItemRightClick(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer) { if(this.tools !=null && this.tools.getStackInSlot(SlotNum) != null) { this.tools.setInventorySlotContents(SlotNum, this.tools.getStackInSlot(SlotNum).getItem().onItemRightClick(this.tools.getStackInSlot(SlotNum), par2World, par3EntityPlayer)); } - par3EntityPlayer.setItemInUse(par1ItemStack, this.getMaxItemUseDuration(par1ItemStack)); + if(this.getItemUseAction(par1ItemStack) != EnumAction.none) + par3EntityPlayer.setItemInUse(par1ItemStack, this.getMaxItemUseDuration(par1ItemStack)); return par1ItemStack; } public boolean itemInteractionForEntity(ItemStack par1ItemStack, EntityLiving par2EntityLiving) { if(this.tools != null && this.tools.getStackInSlot(SlotNum) != null) return this.tools.getStackInSlot(SlotNum).getItem().itemInteractionForEntity(this.tools.getStackInSlot(SlotNum), par2EntityLiving); else return false; } public EnumAction getItemUseAction(ItemStack par1ItemStack) { if(this.tools !=null && this.tools.getStackInSlot(SlotNum) != null) { return this.tools.getStackInSlot(SlotNum).getItemUseAction(); } else return super.getItemUseAction(par1ItemStack); } public int getMaxItemUseDuration(ItemStack par1ItemStack) { if(this.tools !=null && this.tools.getStackInSlot(SlotNum) != null) { return this.tools.getStackInSlot(SlotNum).getMaxItemUseDuration(); } else return super.getMaxItemUseDuration(par1ItemStack); } public float getStrVsBlock(ItemStack par1ItemStack, Block par2Block){ if(this.tools !=null && this.tools.getStackInSlot(SlotNum) != null) return this.tools.getStackInSlot(SlotNum).getStrVsBlock(par2Block); else return super.getStrVsBlock(par1ItemStack, par2Block); } @Override public float getStrVsBlock(ItemStack stack, Block block, int meta) { if(this.tools !=null && this.tools.getStackInSlot(SlotNum) != null) { return this.tools.getStackInSlot(SlotNum).getItem().getStrVsBlock(this.tools.getStackInSlot(SlotNum), block, meta); } else return super.getStrVsBlock(stack, block, meta); } public int getDamageVsEntity(Entity par1Entity) { if(this.tools !=null && this.tools.getStackInSlot(SlotNum) != null) { return this.tools.getStackInSlot(SlotNum).getItem().getDamageVsEntity(par1Entity); } else return super.getDamageVsEntity(par1Entity); } public int getDamageVsEntity(Entity par1Entity, ItemStack itemStack) { if(this.tools !=null && this.tools.getStackInSlot(SlotNum) != null) { return this.tools.getStackInSlot(SlotNum).getItem().getDamageVsEntity(par1Entity, this.tools.getStackInSlot(SlotNum)); } else return super.getDamageVsEntity(par1Entity, itemStack); } public boolean canHarvestBlock(Block par1Block) { if(this.tools !=null && this.tools.getStackInSlot(SlotNum) != null) { return this.tools.getStackInSlot(SlotNum).canHarvestBlock(par1Block); } else return super.canHarvestBlock(par1Block); } public boolean onBlockDestroyed(ItemStack par1ItemStack, World par2World, int par3, int par4, int par5, int par6, EntityLiving par7EntityLiving) { if(this.tools !=null && this.tools.getStackInSlot(SlotNum) != null) { boolean ret = this.tools.getStackInSlot(SlotNum).getItem().onBlockDestroyed(this.tools.getStackInSlot(SlotNum), par2World, par3, par4, par5, par6, par7EntityLiving); if (this.tools.getStackInSlot(SlotNum).stackSize <= 0) { this.destroyTheItem((EntityPlayer) par7EntityLiving, this.tools.getStackInSlot(SlotNum)); } this.tools.onInventoryChanged(); return ret; } else return super.onBlockDestroyed(par1ItemStack, par2World, par3, par4, par5, par6, par7EntityLiving); } public void attackTargetEntityWithTheItem(Entity par1Entity, EntityPlayer player,ItemStack stack) { if (MinecraftForge.EVENT_BUS.post(new AttackEntityEvent(player, par1Entity))) { return; } if (stack != null && stack.getItem().onLeftClickEntity(stack, player, par1Entity)) { return; } if (par1Entity.canAttackWithItem()) { if (!par1Entity.func_85031_j(player)) { int var2 = stack.getDamageVsEntity(par1Entity); if (player.isPotionActive(Potion.damageBoost)) { var2 += 3 << player.getActivePotionEffect(Potion.damageBoost).getAmplifier(); } if (player.isPotionActive(Potion.weakness)) { var2 -= 2 << player.getActivePotionEffect(Potion.weakness).getAmplifier(); } int var3 = 0; int var4 = 0; if (par1Entity instanceof EntityLiving) { var4 = this.getEnchantmentModifierLiving(stack, player, (EntityLiving)par1Entity); var3 += EnchantmentHelper.getEnchantmentLevel(Enchantment.knockback.effectId, stack); } if (player.isSprinting()) { ++var3; } if (var2 > 0 || var4 > 0) { boolean var5 = player.fallDistance > 0.0F && !player.onGround && !player.isOnLadder() && !player.isInWater() && !player.isPotionActive(Potion.blindness) && player.ridingEntity == null && par1Entity instanceof EntityLiving; if (var5) { var2 += this.rand.nextInt(var2 / 2 + 2); } var2 += var4; boolean var6 = false; int var7 = EnchantmentHelper.getEnchantmentLevel(Enchantment.fireAspect.effectId, stack); if (par1Entity instanceof EntityLiving && var7 > 0 && !par1Entity.isBurning()) { var6 = true; par1Entity.setFire(1); } boolean var8 = par1Entity.attackEntityFrom(DamageSource.causePlayerDamage(player), var2); if (var8) { if (var3 > 0) { par1Entity.addVelocity((double)(-MathHelper.sin(player.rotationYaw * (float)Math.PI / 180.0F) * (float)var3 * 0.5F), 0.1D, (double)(MathHelper.cos(player.rotationYaw * (float)Math.PI / 180.0F) * (float)var3 * 0.5F)); player.motionX *= 0.6D; player.motionZ *= 0.6D; player.setSprinting(false); } if (var5) { player.onCriticalHit(par1Entity); } if (var4 > 0) { player.onEnchantmentCritical(par1Entity); } if (var2 >= 18) { player.triggerAchievement(AchievementList.overkill); } player.setLastAttackingEntity(par1Entity); if (par1Entity instanceof EntityLiving) { EnchantmentThorns.func_92096_a(player, (EntityLiving)par1Entity, this.rand); } } ItemStack var9 = stack; if (var9 != null && par1Entity instanceof EntityLiving) { var9.hitEntity((EntityLiving)par1Entity, player); if (var9.stackSize <= 0) { this.destroyTheItem(player, stack); } } if (par1Entity instanceof EntityLiving) { player.addStat(StatList.damageDealtStat, var2); if (var7 > 0 && var8) { par1Entity.setFire(var7 * 4); } else if (var6) { par1Entity.extinguish(); } } player.addExhaustion(0.3F); } } } } public void destroyTheItem(EntityPlayer player, ItemStack orig) { this.tools.setInventorySlotContents(this.SlotNum, (ItemStack)null); MinecraftForge.EVENT_BUS.post(new PlayerDestroyItemEvent(player, orig)); } public int getEnchantmentModifierLiving(ItemStack stack, EntityLiving attacker, EntityLiving enemy) { int calc = 0; if (stack != null) { NBTTagList nbttaglist = stack.getEnchantmentTagList(); if (nbttaglist != null) { for (int i = 0; i < nbttaglist.tagCount(); ++i) { short short1 = ((NBTTagCompound)nbttaglist.tagAt(i)).getShort("id"); short short2 = ((NBTTagCompound)nbttaglist.tagAt(i)).getShort("lvl"); if (Enchantment.enchantmentsList[short1] != null) { calc += Enchantment.enchantmentsList[short1].calcModifierLiving(short2, enemy); } } } } return calc > 0 ? 1 + rand.nextInt(calc) : 0; } public void setEnchantments(ItemStack ToEnchant, ItemStack Enchanted) { int EnchNum; int EnchLv; NBTTagList list = Enchanted.getEnchantmentTagList(); if(list !=null) { for (int i = 0; i < list.tagCount(); ++i) { if(((NBTTagCompound)list.tagAt(i)).getShort("lvl") > 0) { EnchNum = ((NBTTagCompound)list.tagAt(i)).getShort("id"); EnchLv = ((NBTTagCompound)list.tagAt(i)).getShort("lvl"); ToEnchant.addEnchantment(Enchantment.enchantmentsList[EnchNum], EnchLv); } } } } // パケットの読み込み(パケットの受け取りはPacketHandlerで行う) public void readPacketData(ByteArrayDataInput data) { try { this.SlotNum = data.readInt(); this.OpenKeydown = data.readBoolean(); } catch (Exception e) { e.printStackTrace(); } } // パケットの書き込み(パケットの生成自体はPacketHandlerで行う) public void writePacketData(DataOutputStream dos) { try { dos.writeInt(SlotNum); dos.writeBoolean(OpenKeydown); } catch (Exception e) { e.printStackTrace(); } } } \ No newline at end of file diff --git a/ak/MultiToolHolders/MultiToolHolders.java b/ak/MultiToolHolders/MultiToolHolders.java index a1df66d..cecd6cb 100644 --- a/ak/MultiToolHolders/MultiToolHolders.java +++ b/ak/MultiToolHolders/MultiToolHolders.java @@ -1,217 +1,217 @@ package ak.MultiToolHolders; import java.util.Arrays; import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.storagebox.ItemStorageBox; import net.minecraft.util.WeightedRandomChestContent; import net.minecraft.world.World; import net.minecraftforge.common.ChestGenHooks; import net.minecraftforge.common.Configuration; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.ForgeSubscribe; import net.minecraftforge.event.entity.player.EntityItemPickupEvent; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.Init; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.Mod.PostInit; import cpw.mods.fml.common.Mod.PreInit; import cpw.mods.fml.common.ModMetadata; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.network.NetworkMod; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.LanguageRegistry; -@Mod(modid="MultiToolHolders", name="MultiToolHolders", version="1.2") +@Mod(modid="MultiToolHolders", name="MultiToolHolders", version="1.2b") @NetworkMod(clientSideRequired=true, serverSideRequired=false, channels={"MTH|Tool"}, packetHandler=PacketHandler.class) public class MultiToolHolders { public static int ItemIDShift; public static Item ItemMultiToolHolder3; public static Item ItemMultiToolHolder5; public static Item ItemMultiToolHolder7; public static Item ItemMultiToolHolder9; public static boolean Debug; public static String GuiToolHolder3 ="/mods/ak/MultiToolHolders/textures/gui/ToolHolder3.png"; public static String GuiToolHolder5 ="/mods/ak/MultiToolHolders/textures/gui/ToolHolder5.png"; public static String GuiToolHolder7 ="/mods/ak/MultiToolHolders/textures/gui/ToolHolder7.png"; public static String GuiToolHolder9 ="/mods/ak/MultiToolHolders/textures/gui/ToolHolder9.png"; public static String TextureDomain = "ak/MultiToolHolders:"; public static String itemTexture = "/ak/MultiToolHolders/textures/items.png"; @Instance("MultiToolHolders") public static MultiToolHolders instance; @SidedProxy(clientSide = "ak.MultiToolHolders.Client.ClientProxy", serverSide = "ak.MultiToolHolders.CommonProxy") public static CommonProxy proxy; public static int guiIdHolder3 = 0; public static int guiIdHolder5 = 1; public static int guiIdHolder9 = 2; public static int guiIdHolder7 = 3; public static int toolTipX = 5; public static int toolTipY = 20; public static boolean loadSB = false; @PreInit public void preInit(FMLPreInitializationEvent event) { setUpModInfo(event.getModMetadata()); Configuration config = new Configuration(event.getSuggestedConfigurationFile()); config.load(); ItemIDShift = config.get(Configuration.CATEGORY_ITEM, "Item ID Shift Number", 7000).getInt(); Debug = config.get(Configuration.CATEGORY_GENERAL, "Debug mode", false, "For Debugger").getBoolean(false); config.save(); } private void setUpModInfo(ModMetadata meta) { meta.authorList = Arrays.asList(new String[]{"A.K."}); meta.autogenerated = true; meta.description = "Add Tool Holders"; meta.logoFile = ""; meta.url = "http://forum.minecraftuser.jp/viewtopic.php?f=13&t=6672"; } @Init public void load(FMLInitializationEvent event) { ItemMultiToolHolder3 = (new ItemMultiToolHolder(ItemIDShift - 256, 3)).setUnlocalizedName(this.TextureDomain + "Holder3").setCreativeTab(CreativeTabs.tabTools); ItemMultiToolHolder5 = (new ItemMultiToolHolder(ItemIDShift - 256 + 1, 5)).setUnlocalizedName(this.TextureDomain + "Holder5").setCreativeTab(CreativeTabs.tabTools); ItemMultiToolHolder9 = (new ItemMultiToolHolder(ItemIDShift - 256 + 2, 9)).setUnlocalizedName(this.TextureDomain + "Holder9").setCreativeTab(CreativeTabs.tabTools); ItemMultiToolHolder7 = (new ItemMultiToolHolder(ItemIDShift - 256 + 3, 7)).setUnlocalizedName(this.TextureDomain + "Holder7").setCreativeTab(CreativeTabs.tabTools); MinecraftForge.EVENT_BUS.register(new PlayerPickUpHooks()); NetworkRegistry.instance().registerGuiHandler(this, proxy); proxy.registerClientInformation(); proxy.registerTileEntitySpecialRenderer(); GameRegistry.addRecipe(new ItemStack(ItemMultiToolHolder3), new Object[]{"AAA","ABA", "CCC", Character.valueOf('A'), Item.ingotIron,Character.valueOf('B'),Block.chest, Character.valueOf('C'),Block.tripWireSource}); GameRegistry.addRecipe(new ItemStack(ItemMultiToolHolder7), new Object[]{"AAA","ABA", "CCC", Character.valueOf('A'), Item.ingotGold,Character.valueOf('B'),Block.chest, Character.valueOf('C'),Block.tripWireSource}); GameRegistry.addRecipe(new ItemStack(ItemMultiToolHolder9), new Object[]{"AAA","ABA", "CCC", Character.valueOf('A'), Item.diamond,Character.valueOf('B'),Block.chest, Character.valueOf('C'),Block.tripWireSource}); GameRegistry.addRecipe(new ItemStack(ItemMultiToolHolder5), new Object[]{"AAA","ABA", "CCC", Character.valueOf('A'), new ItemStack(Item.dyePowder,1,4),Character.valueOf('B'),Block.chest, Character.valueOf('C'),Block.tripWireSource}); if(this.Debug) DebugSystem(); } @PostInit public void postInit(FMLPostInitializationEvent event) { AddLocalization(); loadSB = Loader.isModLoaded("mod_StorageBox"); } public class PlayerPickUpHooks { @ForgeSubscribe public void pickUpEvent(EntityItemPickupEvent event) { if(loadSB) { EntityPlayer player = event.entityPlayer; EntityItem item = event.item; int stackSize = item.getEntityItem().stackSize; ItemStack[] inv = player.inventory.mainInventory; if(pickUpItemInToolHolder(player.worldObj,inv,item.getEntityItem())) { event.setCanceled(true); player.worldObj.playSoundAtEntity(item, "random.pop", 0.2F, ((player.worldObj.rand.nextFloat() - player.worldObj.rand.nextFloat()) * 0.7F + 1.0F) * 2.0F); player.onItemPickup(item, stackSize); } } } private boolean pickUpItemInToolHolder(World world,ItemStack[] inv, ItemStack item) { ToolHolderData data; ItemStack storageStack; for(int i=0;i<inv.length;i++) { if(inv[i] != null && inv[i].getItem() instanceof ItemMultiToolHolder) { data = ItemMultiToolHolder.getToolData(inv[i], world); if(data != null) { for(int j=0;j<data.getSizeInventory();j++) { if(data.tools[j] != null && data.tools[j].getItem() instanceof ItemStorageBox && ItemStorageBox.isAutoCollect(data.tools[j])) { storageStack = ItemStorageBox.peekItemStackAll(data.tools[j]); if(storageStack != null && item.isItemEqual(storageStack)) { ItemStorageBox.addItemStack(data.tools[j], item); item.stackSize = 0; return true; } } } } } } return false; } } public void AddLocalization() { LanguageRegistry.addName(ItemMultiToolHolder3, "3-Way Tool Holder"); LanguageRegistry.addName(ItemMultiToolHolder5, "5-Way Tool Holder"); LanguageRegistry.addName(ItemMultiToolHolder9, "9-Way Tool Holder"); LanguageRegistry.addName(ItemMultiToolHolder7, "7-Way Tool Holder"); LanguageRegistry.instance().addNameForObject(ItemMultiToolHolder3, "ja_JP","3-Wayツールホルダー"); LanguageRegistry.instance().addNameForObject(ItemMultiToolHolder5, "ja_JP","5-Wayツールホルダー"); LanguageRegistry.instance().addNameForObject(ItemMultiToolHolder9, "ja_JP","9-Wayツールホルダー"); LanguageRegistry.instance().addNameForObject(ItemMultiToolHolder7, "ja_JP","7-Wayツールホルダー"); LanguageRegistry.instance().addStringLocalization("container.toolholder", "ToolHolder"); LanguageRegistry.instance().addStringLocalization("container.toolholder", "ja_JP", "ツールホルダー"); LanguageRegistry.instance().addStringLocalization("container.toolholder", "ToolHolder"); LanguageRegistry.instance().addStringLocalization("container.toolholder", "ja_JP", "ツールホルダー"); LanguageRegistry.instance().addStringLocalization("Key.openToolHolder", "Open ToolHolder"); LanguageRegistry.instance().addStringLocalization("Key.openToolHolder", "ja_JP", "ツールホルダーを開く"); LanguageRegistry.instance().addStringLocalization("Key.nextToolHolder", "ToolHolder Next Slot"); LanguageRegistry.instance().addStringLocalization("Key.nextToolHolder", "ja_JP", "次のスロット"); LanguageRegistry.instance().addStringLocalization("Key.prevToolHolder", "ToolHolder Previous Slot"); LanguageRegistry.instance().addStringLocalization("Key.prevToolHolder", "ja_JP", "前のスロット"); } public void DungeonLootItemResist() { WeightedRandomChestContent Chest; ItemStack[] items = new ItemStack[]{new ItemStack(ItemMultiToolHolder3),new ItemStack(ItemMultiToolHolder5),new ItemStack(ItemMultiToolHolder7),new ItemStack(ItemMultiToolHolder9)}; int[] weights = new int[]{10,5,3,1}; for (int i= 0;i<items.length;i++) { Chest = new WeightedRandomChestContent(items[i], 0, 1, weights[i]);; ChestGenHooks.addItem(ChestGenHooks.MINESHAFT_CORRIDOR, Chest); ChestGenHooks.addItem(ChestGenHooks.PYRAMID_DESERT_CHEST, Chest); ChestGenHooks.addItem(ChestGenHooks.PYRAMID_JUNGLE_CHEST, Chest); ChestGenHooks.addItem(ChestGenHooks.PYRAMID_JUNGLE_DISPENSER, Chest); ChestGenHooks.addItem(ChestGenHooks.STRONGHOLD_CORRIDOR, Chest); ChestGenHooks.addItem(ChestGenHooks.STRONGHOLD_LIBRARY, Chest); ChestGenHooks.addItem(ChestGenHooks.STRONGHOLD_CROSSING, Chest); ChestGenHooks.addItem(ChestGenHooks.VILLAGE_BLACKSMITH, Chest); ChestGenHooks.addItem(ChestGenHooks.BONUS_CHEST, Chest); ChestGenHooks.addItem(ChestGenHooks.DUNGEON_CHEST, Chest); } } public void DebugSystem() { } } \ No newline at end of file
false
false
null
null
diff --git a/org.dawb.workbench.plotting/src/org/dawb/workbench/plotting/system/swtxy/RegionArea.java b/org.dawb.workbench.plotting/src/org/dawb/workbench/plotting/system/swtxy/RegionArea.java index eb980b0a4..af04bc01c 100644 --- a/org.dawb.workbench.plotting/src/org/dawb/workbench/plotting/system/swtxy/RegionArea.java +++ b/org.dawb.workbench.plotting/src/org/dawb/workbench/plotting/system/swtxy/RegionArea.java @@ -1,573 +1,576 @@ package org.dawb.workbench.plotting.system.swtxy; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.csstudio.swt.xygraph.figures.Axis; import org.csstudio.swt.xygraph.figures.PlotArea; import org.csstudio.swt.xygraph.figures.Trace; import org.csstudio.swt.xygraph.undo.ZoomType; import org.dawb.common.services.ImageServiceBean.ImageOrigin; import org.dawb.common.ui.plot.IAxis; import org.dawb.common.ui.plot.region.IRegion.RegionType; import org.dawb.common.ui.plot.region.IRegionListener; import org.dawb.common.ui.plot.region.RegionEvent; import org.dawb.common.ui.plot.trace.ITraceListener; import org.dawb.common.ui.plot.trace.TraceEvent; import org.dawb.workbench.plotting.system.dialog.AddRegionCommand; import org.dawb.workbench.plotting.system.swtxy.selection.AbstractSelectionRegion; import org.dawb.workbench.plotting.system.swtxy.selection.SelectionRegionFactory; import org.eclipse.draw2d.Graphics; import org.eclipse.draw2d.MouseEvent; import org.eclipse.draw2d.MouseListener; import org.eclipse.draw2d.MouseMotionListener; import org.eclipse.draw2d.geometry.Point; import org.eclipse.draw2d.geometry.PointList; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.swt.graphics.PaletteData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RegionArea extends PlotArea { private static final Logger logger = LoggerFactory.getLogger(RegionArea.class); protected ISelectionProvider selectionProvider; private final Map<String,AbstractSelectionRegion> regions; private final Map<String,ImageTrace> imageTraces; private Collection<IRegionListener> regionListeners; private Collection<ITraceListener> imageTraceListeners; private AbstractSelectionRegion regionBeingAdded; private PointList regionPoints; public RegionArea(XYRegionGraph xyGraph) { super(xyGraph); this.regions = new LinkedHashMap<String,AbstractSelectionRegion>(); this.imageTraces = new LinkedHashMap<String,ImageTrace>(); } public void addRegion(final AbstractSelectionRegion region){ addRegion(region, true); } private void addRegion(final AbstractSelectionRegion region, boolean fireListeners){ regions.put(region.getName(), region); region.setXyGraph(xyGraph); region.createContents(this); region.setSelectionProvider(selectionProvider); if (fireListeners) fireRegionAdded(new RegionEvent(region)); clearRegionTool(); revalidate(); } public boolean removeRegion(final AbstractSelectionRegion region){ final AbstractSelectionRegion gone = regions.remove(region.getName()); if (gone!=null){ region.remove(); // Clears up children (you can live without this fireRegionRemoved(new RegionEvent(region)); revalidate(); } return gone!=null; } public void renameRegion(final AbstractSelectionRegion region, String name) { regions.remove(region.getName()); region.setName(name); regions.put(name, region); } public void clearRegions() { clearRegionsInternal(); revalidate(); } protected void clearRegionsInternal() { clearRegionTool(); if (regions==null) return; + + final Collection<String> deleted = new HashSet<String>(5); for (AbstractSelectionRegion region : regions.values()) { if (!region.isUserRegion()) continue; + deleted.add(region.getName()); region.remove(); } - regions.clear(); + regions.keySet().removeAll(deleted); fireRegionsRemoved(new RegionEvent(this)); } public ImageTrace createImageTrace(String name, Axis xAxis, Axis yAxis) { if (imageTraces.containsKey(name)) throw new RuntimeException("There is an image called '"+name+"' already plotted!"); final ImageTrace trace = new ImageTrace(name, xAxis, yAxis); fireImageTraceCreated(new TraceEvent(trace)); return trace; } /**Add a trace to the plot area. * @param trace the trace to be added. */ public void addImageTrace(final ImageTrace trace){ imageTraces.put(trace.getName(), trace); add(trace); // Move all regions to front again if (getRegionMap()!=null) for (String name : getRegionMap().keySet()) { try { getRegionMap().get(name).toFront(); } catch (Exception ne) { continue; } } revalidate(); fireImageTraceAdded(new TraceEvent(trace)); } public boolean removeImageTrace(final ImageTrace trace){ final ImageTrace gone = imageTraces.remove(trace.getName()); if (gone!=null){ trace.remove(); fireImageTraceRemoved(new TraceEvent(trace)); revalidate(); } return gone!=null; } public void clearImageTraces() { if (imageTraces==null) return; for (ImageTrace trace : imageTraces.values()) { trace.remove(); fireImageTraceRemoved(new TraceEvent(trace)); } imageTraces.clear(); revalidate(); } @Override protected void layout() { final Rectangle clientArea = getClientArea(); for(ImageTrace trace : imageTraces.values()){ if(trace != null && trace.isVisible()) //Shrink will make the trace has no intersection with axes, //which will make it only repaints the trace area. trace.setBounds(clientArea);//.getCopy().shrink(1, 1)); } super.layout(); } @Override protected void paintClientArea(final Graphics graphics) { super.paintClientArea(graphics); if (regionBeingAdded!=null && regionPoints!=null && regionPoints.size() > 0) { regionBeingAdded.paintBeforeAdded(graphics, regionPoints, getBounds()); } } private RegionMouseListener regionListener; /** * Create region of interest * @param name * @param xAxis * @param yAxis * @param regionType * @param startingWithMouseEvent * @return region * @throws Exception */ public AbstractSelectionRegion createRegion(String name, Axis x, Axis y, RegionType regionType, boolean startingWithMouseEvent) throws Exception { if (getRegionMap()!=null) { if (getRegionMap().containsKey(name)) throw new Exception("The region '"+name+"' already exists."); } AbstractSelectionRegion region = SelectionRegionFactory.createSelectionRegion(name, x, y, regionType); if (startingWithMouseEvent) { xyGraph.setZoomType(ZoomType.NONE); if (region.getRegionCursor()!=null) setCursor(region.getRegionCursor()); regionBeingAdded = region; // Mouse listener for region bounds regionListener = new RegionMouseListener(regionBeingAdded.getMinimumMousePresses(), regionBeingAdded.getMaximumMousePresses()); addMouseListener(regionListener); addMouseMotionListener(regionListener); } fireRegionCreated(new RegionEvent(region)); return region; } public void disposeRegion(AbstractSelectionRegion region) { removeRegion(region); setCursor(null); clearRegionTool(); } public void setZoomType(final ZoomType zoomType) { clearRegionTool(); super.setZoomType(zoomType); } protected void clearRegionTool() { if (regionListener!=null) { removeMouseListener(regionListener); removeMouseMotionListener(regionListener); regionListener = null; setCursor(null); } } /** * * @param l */ public boolean addRegionListener(final IRegionListener l) { if (regionListeners == null) regionListeners = new HashSet<IRegionListener>(7); return regionListeners.add(l); } /** * * @param l */ public boolean removeRegionListener(final IRegionListener l) { if (regionListeners == null) return true; return regionListeners.remove(l); } protected void fireRegionCreated(RegionEvent evt) { if (regionListeners==null) return; for (IRegionListener l : regionListeners) { try { l.regionCreated(evt); } catch (Throwable ne) { logger.error("Notifying of region creation", ne); continue; } } } protected void fireRegionAdded(RegionEvent evt) { if (regionListeners==null) return; for (IRegionListener l : regionListeners) { try { l.regionAdded(evt); } catch (Throwable ne) { logger.error("Notifying of region add", ne); continue; } } } protected void fireRegionRemoved(RegionEvent evt) { if (regionListeners==null) return; for (IRegionListener l : regionListeners) { try { l.regionRemoved(evt); } catch (Throwable ne) { logger.error("Notifying of region removal", ne); continue; } } } protected void fireRegionsRemoved(RegionEvent evt) { if (regionListeners==null) return; for (IRegionListener l : regionListeners) { try { l.regionsRemoved(evt); } catch (Throwable ne) { logger.error("Notifying of region removal", ne); continue; } } } /** * * @param l */ public boolean addImageTraceListener(final ITraceListener l) { if (imageTraceListeners == null) imageTraceListeners = new HashSet<ITraceListener>(7); return imageTraceListeners.add(l); } /** * * @param l */ public boolean removeImageTraceListener(final ITraceListener l) { if (imageTraceListeners == null) return true; return imageTraceListeners.remove(l); } protected void fireImageTraceCreated(TraceEvent evt) { if (imageTraceListeners==null) return; for (ITraceListener l : imageTraceListeners) l.traceCreated(evt); } protected void fireImageTraceAdded(TraceEvent evt) { if (imageTraceListeners==null) return; for (ITraceListener l : imageTraceListeners) l.traceAdded(evt); } protected void fireImageTraceRemoved(TraceEvent evt) { if (imageTraceListeners==null) return; for (ITraceListener l : imageTraceListeners) l.traceRemoved(evt); } public Map<String, AbstractSelectionRegion> getRegionMap() { return regions; } public List<AbstractSelectionRegion> getRegions() { final Collection<AbstractSelectionRegion> vals = regions.values(); return new ArrayList<AbstractSelectionRegion>(vals); } // private Image rawImage; // @Override // protected void paintClientArea(final Graphics graphics) { // TODO // if (rawImage==null) { // rawImage = new Image(Display.getCurrent(), "C:/tmp/ESRF_Pilatus_Data.png"); // } // // final Rectangle bounds = getBounds(); // final Image scaled = new Image(Display.getCurrent(), // rawImage.getImageData().scaledTo(bounds.width,bounds.height)); // graphics.drawImage(scaled, new Point(0,0)); // // super.paintClientArea(graphics); // // } public Collection<String> getRegionNames() { return regions.keySet(); } public void setSelectionProvider(ISelectionProvider provider) { this.selectionProvider = provider; } public AbstractSelectionRegion getRegion(String name) { if (regions==null) return null; return regions.get(name); } class RegionMouseListener extends MouseMotionListener.Stub implements MouseListener { private int last = -1; // index of point that is being dragged around private final int maxLast; // region allows multiple mouse button presses private final int minLast; private boolean isDragging; private static final int MIN_DIST = 2; public RegionMouseListener(final int minPresses, final int maxPresses) { minLast = minPresses - 1; maxLast = maxPresses - 1; regionPoints = new PointList(2); isDragging = false; } @Override public void mousePressed(MouseEvent me) { final Point loc = me.getLocation(); if (isDragging) { isDragging = false; if (maxLast > 0 && last >= maxLast) { // System.err.println("End with last = " + last + " / " + maxLast); releaseMouse(); } else if (me.button == 2) { regionPoints.removePoint(last--); // System.err.println("End with last-- = " + last + " / " + maxLast); releaseMouse(); } } else { if (last > 0 && loc.getDistance(regionPoints.getPoint(last)) <= MIN_DIST) { // System.err.println("Cancel with last = " + last + " / " + maxLast); if (maxLast >= 0 || last >= minLast) { releaseMouse(); } else { System.err.println("Not enough points!"); } } else { regionPoints.addPoint(loc); last++; // System.err.println("Added on press (from non-drag), now last = " + last); isDragging = maxLast == 0; } } me.consume(); repaint(); } @Override public void mouseReleased(MouseEvent me) { if (isDragging) { isDragging = false; if (maxLast >= 0 && last >= maxLast) { // System.err.println("Release with last = " + last + " / " + maxLast); releaseMouse(); } me.consume(); repaint(); } } @Override public void mouseDoubleClicked(MouseEvent me) { } @Override public void mouseDragged(final MouseEvent me) { mouseMoved(me); } @Override public void mouseMoved(final MouseEvent me) { if (last < 0) return; final Point loc = me.getLocation(); if (isDragging) { regionPoints.setPoint(loc, last); me.consume(); repaint(); } else if (loc.getDistance(regionPoints.getPoint(last)) > MIN_DIST) { regionPoints.addPoint(loc); last++; isDragging = true; me.consume(); repaint(); // System.err.println("Added on move, last = " + last); } } @Override public void mouseExited(final MouseEvent me) { // mouseReleased(me); } private void releaseMouse() { removeMouseListener(this); removeMouseMotionListener(this); if (regionListener == this) { regionListener = null; } else { clearRegionTool(); // Actually something has gone wrong if this happens. } setCursor(null); addRegion(regionBeingAdded, false); ((XYRegionGraph) xyGraph).getOperationsManager().addCommand( new AddRegionCommand((XYRegionGraph) xyGraph, regionBeingAdded)); regionBeingAdded.setLocalBounds(regionPoints, getBounds()); fireRegionAdded(new RegionEvent(regionBeingAdded)); regionBeingAdded = null; regionPoints = null; } } protected Map<String,ImageTrace> getImageTraces() { return this.imageTraces; } /** * Must call in UI thread safe way. */ public void clearTraces() { final List<Trace> traceList = getTraceList(); if (traceList!=null) { for (Trace trace : traceList) { remove(trace); if (trace instanceof LineTrace) ((LineTrace)trace).dispose(); } traceList.clear(); } if (imageTraces!=null) { final Collection<ImageTrace> its = new HashSet<ImageTrace>(imageTraces.values()); for (ImageTrace trace : its) { final ImageTrace gone = imageTraces.remove(trace.getName()); if (gone!=null){ trace.remove(); fireImageTraceRemoved(new TraceEvent(trace)); } } imageTraces.clear(); } } public void setPaletteData(PaletteData data) { if (imageTraces!=null) for (ImageTrace trace : imageTraces.values()) { trace.setPaletteData(data); } } public void setImageOrigin(ImageOrigin origin) { if (imageTraces!=null) for (ImageTrace trace : imageTraces.values()) { trace.setImageOrigin(origin); } } public ImageTrace getImageTrace() { if (imageTraces!=null && imageTraces.size()>0) return imageTraces.values().iterator().next(); return null; } public void dispose() { clearTraces(); clearRegionsInternal(); if (regionListeners!=null) regionListeners.clear(); if (imageTraceListeners!=null) imageTraceListeners.clear(); if (regions!=null) regions.clear(); if (imageTraces!=null) imageTraces.clear(); } /** * Call to find out of any of the current regions are user editable. * @return */ public boolean hasUserRegions() { if (getRegionMap()==null || getRegionMap().isEmpty()) return false; for (String regionName : getRegionMap().keySet()) { if (getRegionMap().get(regionName).isUserRegion()) return true; } return false; } }
false
false
null
null
diff --git a/core/java/android/app/SearchDialog.java b/core/java/android/app/SearchDialog.java index 4dd2433e..ea3d762a 100644 --- a/core/java/android/app/SearchDialog.java +++ b/core/java/android/app/SearchDialog.java @@ -1,1898 +1,1897 @@ /* * Copyright (C) 2008 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 android.app; import static android.app.SuggestionsAdapter.getColumnString; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.database.Cursor; import android.graphics.drawable.Animatable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.os.SystemClock; import android.provider.Browser; import android.server.search.SearchableInfo; import android.speech.RecognizerIntent; import android.text.Editable; import android.text.InputType; import android.text.TextUtils; import android.text.TextWatcher; import android.text.util.Regex; import android.util.AndroidRuntimeException; import android.util.AttributeSet; import android.util.Log; import android.view.ContextThemeWrapper; import android.view.Gravity; import android.view.KeyEvent; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import java.util.ArrayList; import java.util.WeakHashMap; import java.util.concurrent.atomic.AtomicLong; /** * System search dialog. This is controlled by the * SearchManagerService and runs in the system process. * * @hide */ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemSelectedListener { // Debugging support private static final boolean DBG = false; private static final String LOG_TAG = "SearchDialog"; private static final boolean DBG_LOG_TIMING = false; private static final String INSTANCE_KEY_COMPONENT = "comp"; private static final String INSTANCE_KEY_APPDATA = "data"; private static final String INSTANCE_KEY_GLOBALSEARCH = "glob"; private static final String INSTANCE_KEY_STORED_COMPONENT = "sComp"; private static final String INSTANCE_KEY_STORED_APPDATA = "sData"; private static final String INSTANCE_KEY_PREVIOUS_COMPONENTS = "sPrev"; private static final String INSTANCE_KEY_USER_QUERY = "uQry"; // The extra key used in an intent to the speech recognizer for in-app voice search. private static final String EXTRA_CALLING_PACKAGE = "calling_package"; private static final int SEARCH_PLATE_LEFT_PADDING_GLOBAL = 12; private static final int SEARCH_PLATE_LEFT_PADDING_NON_GLOBAL = 7; // views & widgets private TextView mBadgeLabel; private ImageView mAppIcon; private SearchAutoComplete mSearchAutoComplete; private Button mGoButton; private ImageButton mVoiceButton; private View mSearchPlate; private Drawable mWorkingSpinner; // interaction with searchable application private SearchableInfo mSearchable; private ComponentName mLaunchComponent; private Bundle mAppSearchData; private boolean mGlobalSearchMode; private Context mActivityContext; // Values we store to allow user to toggle between in-app search and global search. private ComponentName mStoredComponentName; private Bundle mStoredAppSearchData; // stack of previous searchables, to support the BACK key after // SearchManager.INTENT_ACTION_CHANGE_SEARCH_SOURCE. // The top of the stack (= previous searchable) is the last element of the list, // since adding and removing is efficient at the end of an ArrayList. private ArrayList<ComponentName> mPreviousComponents; // For voice searching private Intent mVoiceWebSearchIntent; private Intent mVoiceAppSearchIntent; // support for AutoCompleteTextView suggestions display private SuggestionsAdapter mSuggestionsAdapter; // Whether to rewrite queries when selecting suggestions private static final boolean REWRITE_QUERIES = true; // The query entered by the user. This is not changed when selecting a suggestion // that modifies the contents of the text field. But if the user then edits // the suggestion, the resulting string is saved. private String mUserQuery; // A weak map of drawables we've gotten from other packages, so we don't load them // more than once. private final WeakHashMap<String, Drawable.ConstantState> mOutsideDrawablesCache = new WeakHashMap<String, Drawable.ConstantState>(); // Last known IME options value for the search edit text. private int mSearchAutoCompleteImeOptions; /** * Constructor - fires it up and makes it look like the search UI. * * @param context Application Context we can use for system acess */ public SearchDialog(Context context) { super(context, com.android.internal.R.style.Theme_GlobalSearchBar); } /** * We create the search dialog just once, and it stays around (hidden) * until activated by the user. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(com.android.internal.R.layout.search_bar); Window theWindow = getWindow(); WindowManager.LayoutParams lp = theWindow.getAttributes(); lp.type = WindowManager.LayoutParams.TYPE_SEARCH_BAR; lp.width = ViewGroup.LayoutParams.FILL_PARENT; // taking up the whole window (even when transparent) is less than ideal, // but necessary to show the popup window until the window manager supports // having windows anchored by their parent but not clipped by them. lp.height = ViewGroup.LayoutParams.FILL_PARENT; lp.gravity = Gravity.TOP | Gravity.FILL_HORIZONTAL; lp.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE; theWindow.setAttributes(lp); // get the view elements for local access mBadgeLabel = (TextView) findViewById(com.android.internal.R.id.search_badge); mSearchAutoComplete = (SearchAutoComplete) findViewById(com.android.internal.R.id.search_src_text); mAppIcon = (ImageView) findViewById(com.android.internal.R.id.search_app_icon); mGoButton = (Button) findViewById(com.android.internal.R.id.search_go_btn); mVoiceButton = (ImageButton) findViewById(com.android.internal.R.id.search_voice_btn); mSearchPlate = findViewById(com.android.internal.R.id.search_plate); mWorkingSpinner = getContext().getResources(). getDrawable(com.android.internal.R.drawable.search_spinner); // attach listeners mSearchAutoComplete.addTextChangedListener(mTextWatcher); mSearchAutoComplete.setOnKeyListener(mTextKeyListener); mSearchAutoComplete.setOnItemClickListener(this); mSearchAutoComplete.setOnItemSelectedListener(this); mGoButton.setOnClickListener(mGoButtonClickListener); mGoButton.setOnKeyListener(mButtonsKeyListener); mVoiceButton.setOnClickListener(mVoiceButtonClickListener); mVoiceButton.setOnKeyListener(mButtonsKeyListener); mSearchAutoComplete.setSearchDialog(this); // pre-hide all the extraneous elements mBadgeLabel.setVisibility(View.GONE); // Additional adjustments to make Dialog work for Search // Touching outside of the search dialog will dismiss it setCanceledOnTouchOutside(true); // Save voice intent for later queries/launching mVoiceWebSearchIntent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH); mVoiceWebSearchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mVoiceWebSearchIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH); mVoiceAppSearchIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); mVoiceAppSearchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mSearchAutoCompleteImeOptions = mSearchAutoComplete.getImeOptions(); } /** * Set up the search dialog * * @return true if search dialog launched, false if not */ public boolean show(String initialQuery, boolean selectInitialQuery, ComponentName componentName, Bundle appSearchData, boolean globalSearch) { // Reset any stored values from last time dialog was shown. mStoredComponentName = null; mStoredAppSearchData = null; boolean success = doShow(initialQuery, selectInitialQuery, componentName, appSearchData, globalSearch); if (success) { // Display the drop down as soon as possible instead of waiting for the rest of the // pending UI stuff to get done, so that things appear faster to the user. mSearchAutoComplete.showDropDownAfterLayout(); } return success; } private boolean isInRealAppSearch() { return !mGlobalSearchMode && (mPreviousComponents == null || mPreviousComponents.isEmpty()); } /** * Called in response to a press of the hard search button in * {@link #onKeyDown(int, KeyEvent)}, this method toggles between in-app * search and global search when relevant. * * If pressed within an in-app search context, this switches the search dialog out to * global search. If pressed within a global search context that was originally an in-app * search context, this switches back to the in-app search context. If pressed within a * global search context that has no original in-app search context (e.g., global search * from Home), this does nothing. * * @return false if we wanted to toggle context but could not do so successfully, true * in all other cases */ private boolean toggleGlobalSearch() { String currentSearchText = mSearchAutoComplete.getText().toString(); if (!mGlobalSearchMode) { mStoredComponentName = mLaunchComponent; mStoredAppSearchData = mAppSearchData; // If this is the browser, we have a special case to not show the icon to the left // of the text field, for extra space for url entry (this should be reconciled in // Eclair). So special case a second tap of the search button to remove any // already-entered text so that we can be sure to show the "Quick Search Box" hint // text to still make it clear to the user that we've jumped out to global search. // // TODO: When the browser icon issue is reconciled in Eclair, remove this special case. if (isBrowserSearch()) currentSearchText = ""; return doShow(currentSearchText, false, null, mAppSearchData, true); } else { if (mStoredComponentName != null) { // This means we should toggle *back* to an in-app search context from // global search. return doShow(currentSearchText, false, mStoredComponentName, mStoredAppSearchData, false); } else { return true; } } } /** * Does the rest of the work required to show the search dialog. Called by both * {@link #show(String, boolean, ComponentName, Bundle, boolean)} and * {@link #toggleGlobalSearch()}. * * @return true if search dialog showed, false if not */ private boolean doShow(String initialQuery, boolean selectInitialQuery, ComponentName componentName, Bundle appSearchData, boolean globalSearch) { // set up the searchable and show the dialog if (!show(componentName, appSearchData, globalSearch)) { return false; } // finally, load the user's initial text (which may trigger suggestions) setUserQuery(initialQuery); if (selectInitialQuery) { mSearchAutoComplete.selectAll(); } return true; } /** * Sets up the search dialog and shows it. * * @return <code>true</code> if search dialog launched */ private boolean show(ComponentName componentName, Bundle appSearchData, boolean globalSearch) { if (DBG) { Log.d(LOG_TAG, "show(" + componentName + ", " + appSearchData + ", " + globalSearch + ")"); } SearchManager searchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE); // Try to get the searchable info for the provided component (or for global search, // if globalSearch == true). mSearchable = searchManager.getSearchableInfo(componentName, globalSearch); // If we got back nothing, and it wasn't a request for global search, then try again // for global search, as we'll try to launch that in lieu of any component-specific search. if (!globalSearch && mSearchable == null) { globalSearch = true; mSearchable = searchManager.getSearchableInfo(componentName, globalSearch); } // If there's not even a searchable info available for global search, then really give up. if (mSearchable == null) { Log.w(LOG_TAG, "No global search provider."); return false; } mLaunchComponent = componentName; mAppSearchData = appSearchData; // Using globalSearch here is just an optimization, just calling // isDefaultSearchable() should always give the same result. mGlobalSearchMode = globalSearch || searchManager.isDefaultSearchable(mSearchable); mActivityContext = mSearchable.getActivityContext(getContext()); // show the dialog. this will call onStart(). if (!isShowing()) { // The Dialog uses a ContextThemeWrapper for the context; use this to change the // theme out from underneath us, between the global search theme and the in-app // search theme. They are identical except that the global search theme does not // dim the background of the window (because global search is full screen so it's // not needed and this should save a little bit of time on global search invocation). Object context = getContext(); if (context instanceof ContextThemeWrapper) { ContextThemeWrapper wrapper = (ContextThemeWrapper) context; if (globalSearch) { wrapper.setTheme(com.android.internal.R.style.Theme_GlobalSearchBar); } else { wrapper.setTheme(com.android.internal.R.style.Theme_SearchBar); } } show(); } updateUI(); return true; } /** * The search dialog is being dismissed, so handle all of the local shutdown operations. * * This function is designed to be idempotent so that dismiss() can be safely called at any time * (even if already closed) and more likely to really dump any memory. No leaks! */ @Override public void onStop() { super.onStop(); closeSuggestionsAdapter(); // dump extra memory we're hanging on to mLaunchComponent = null; mAppSearchData = null; mSearchable = null; mActivityContext = null; mUserQuery = null; mPreviousComponents = null; } /** * Sets the search dialog to the 'working' state, which shows a working spinner in the * right hand size of the text field. * * @param working true to show spinner, false to hide spinner */ public void setWorking(boolean working) { if (working) { mSearchAutoComplete.setCompoundDrawablesWithIntrinsicBounds( null, null, mWorkingSpinner, null); ((Animatable) mWorkingSpinner).start(); } else { mSearchAutoComplete.setCompoundDrawablesWithIntrinsicBounds( null, null, null, null); ((Animatable) mWorkingSpinner).stop(); } } /** * Closes and gets rid of the suggestions adapter. */ private void closeSuggestionsAdapter() { // remove the adapter from the autocomplete first, to avoid any updates // when we drop the cursor mSearchAutoComplete.setAdapter((SuggestionsAdapter)null); // close any leftover cursor if (mSuggestionsAdapter != null) { mSuggestionsAdapter.changeCursor(null); } mSuggestionsAdapter = null; } /** * Save the minimal set of data necessary to recreate the search * * @return A bundle with the state of the dialog, or {@code null} if the search * dialog is not showing. */ @Override public Bundle onSaveInstanceState() { if (!isShowing()) return null; Bundle bundle = new Bundle(); // setup info so I can recreate this particular search bundle.putParcelable(INSTANCE_KEY_COMPONENT, mLaunchComponent); bundle.putBundle(INSTANCE_KEY_APPDATA, mAppSearchData); bundle.putBoolean(INSTANCE_KEY_GLOBALSEARCH, mGlobalSearchMode); bundle.putParcelable(INSTANCE_KEY_STORED_COMPONENT, mStoredComponentName); bundle.putBundle(INSTANCE_KEY_STORED_APPDATA, mStoredAppSearchData); bundle.putParcelableArrayList(INSTANCE_KEY_PREVIOUS_COMPONENTS, mPreviousComponents); bundle.putString(INSTANCE_KEY_USER_QUERY, mUserQuery); return bundle; } /** * Restore the state of the dialog from a previously saved bundle. * * TODO: go through this and make sure that it saves everything that is saved * * @param savedInstanceState The state of the dialog previously saved by * {@link #onSaveInstanceState()}. */ @Override public void onRestoreInstanceState(Bundle savedInstanceState) { if (savedInstanceState == null) return; ComponentName launchComponent = savedInstanceState.getParcelable(INSTANCE_KEY_COMPONENT); Bundle appSearchData = savedInstanceState.getBundle(INSTANCE_KEY_APPDATA); boolean globalSearch = savedInstanceState.getBoolean(INSTANCE_KEY_GLOBALSEARCH); ComponentName storedComponentName = savedInstanceState.getParcelable(INSTANCE_KEY_STORED_COMPONENT); Bundle storedAppSearchData = savedInstanceState.getBundle(INSTANCE_KEY_STORED_APPDATA); ArrayList<ComponentName> previousComponents = savedInstanceState.getParcelableArrayList(INSTANCE_KEY_PREVIOUS_COMPONENTS); String userQuery = savedInstanceState.getString(INSTANCE_KEY_USER_QUERY); // Set stored state mStoredComponentName = storedComponentName; mStoredAppSearchData = storedAppSearchData; mPreviousComponents = previousComponents; // show the dialog. if (!doShow(userQuery, false, launchComponent, appSearchData, globalSearch)) { // for some reason, we couldn't re-instantiate return; } } /** * Called after resources have changed, e.g. after screen rotation or locale change. */ public void onConfigurationChanged() { if (isShowing()) { // Redraw (resources may have changed) updateSearchButton(); updateSearchAppIcon(); updateSearchBadge(); updateQueryHint(); } } /** * Update the UI according to the info in the current value of {@link #mSearchable}. */ private void updateUI() { if (mSearchable != null) { mDecor.setVisibility(View.VISIBLE); updateSearchAutoComplete(); updateSearchButton(); updateSearchAppIcon(); updateSearchBadge(); updateQueryHint(); updateVoiceButton(); // In order to properly configure the input method (if one is being used), we // need to let it know if we'll be providing suggestions. Although it would be // difficult/expensive to know if every last detail has been configured properly, we // can at least see if a suggestions provider has been configured, and use that // as our trigger. int inputType = mSearchable.getInputType(); // We only touch this if the input type is set up for text (which it almost certainly // should be, in the case of search!) if ((inputType & InputType.TYPE_MASK_CLASS) == InputType.TYPE_CLASS_TEXT) { // The existence of a suggestions authority is the proxy for "suggestions // are available here" inputType &= ~InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE; if (mSearchable.getSuggestAuthority() != null) { inputType |= InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE; } } mSearchAutoComplete.setInputType(inputType); mSearchAutoCompleteImeOptions = mSearchable.getImeOptions(); mSearchAutoComplete.setImeOptions(mSearchAutoCompleteImeOptions); } } /** * Updates the auto-complete text view. */ private void updateSearchAutoComplete() { // close any existing suggestions adapter closeSuggestionsAdapter(); mSearchAutoComplete.setDropDownAnimationStyle(0); // no animation mSearchAutoComplete.setThreshold(mSearchable.getSuggestThreshold()); // we dismiss the entire dialog instead mSearchAutoComplete.setDropDownDismissedOnCompletion(false); if (!isInRealAppSearch()) { mSearchAutoComplete.setDropDownAlwaysVisible(true); // fill space until results come in } else { mSearchAutoComplete.setDropDownAlwaysVisible(false); } mSearchAutoComplete.setForceIgnoreOutsideTouch(true); // attach the suggestions adapter, if suggestions are available // The existence of a suggestions authority is the proxy for "suggestions available here" if (mSearchable.getSuggestAuthority() != null) { mSuggestionsAdapter = new SuggestionsAdapter(getContext(), this, mSearchable, mOutsideDrawablesCache, mGlobalSearchMode); mSearchAutoComplete.setAdapter(mSuggestionsAdapter); } } /** * Update the text in the search button. Note: This is deprecated functionality, for * 1.0 compatibility only. */ private void updateSearchButton() { String textLabel = null; Drawable iconLabel = null; int textId = mSearchable.getSearchButtonText(); if (textId != 0) { textLabel = mActivityContext.getResources().getString(textId); } else { iconLabel = getContext().getResources(). getDrawable(com.android.internal.R.drawable.ic_btn_search); } mGoButton.setText(textLabel); mGoButton.setCompoundDrawablesWithIntrinsicBounds(iconLabel, null, null, null); } private void updateSearchAppIcon() { // In Donut, we special-case the case of the browser to hide the app icon as if it were // global search, for extra space for url entry. // // TODO: Remove this special case once the issue has been reconciled in Eclair. if (mGlobalSearchMode || isBrowserSearch()) { mAppIcon.setImageResource(0); mAppIcon.setVisibility(View.GONE); mSearchPlate.setPadding(SEARCH_PLATE_LEFT_PADDING_GLOBAL, mSearchPlate.getPaddingTop(), mSearchPlate.getPaddingRight(), mSearchPlate.getPaddingBottom()); } else { PackageManager pm = getContext().getPackageManager(); Drawable icon; try { ActivityInfo info = pm.getActivityInfo(mLaunchComponent, 0); icon = pm.getApplicationIcon(info.applicationInfo); if (DBG) Log.d(LOG_TAG, "Using app-specific icon"); } catch (NameNotFoundException e) { icon = pm.getDefaultActivityIcon(); Log.w(LOG_TAG, mLaunchComponent + " not found, using generic app icon"); } mAppIcon.setImageDrawable(icon); mAppIcon.setVisibility(View.VISIBLE); mSearchPlate.setPadding(SEARCH_PLATE_LEFT_PADDING_NON_GLOBAL, mSearchPlate.getPaddingTop(), mSearchPlate.getPaddingRight(), mSearchPlate.getPaddingBottom()); } } /** * Setup the search "Badge" if requested by mode flags. */ private void updateSearchBadge() { // assume both hidden int visibility = View.GONE; Drawable icon = null; CharSequence text = null; // optionally show one or the other. if (mSearchable.useBadgeIcon()) { icon = mActivityContext.getResources().getDrawable(mSearchable.getIconId()); visibility = View.VISIBLE; if (DBG) Log.d(LOG_TAG, "Using badge icon: " + mSearchable.getIconId()); } else if (mSearchable.useBadgeLabel()) { text = mActivityContext.getResources().getText(mSearchable.getLabelId()).toString(); visibility = View.VISIBLE; if (DBG) Log.d(LOG_TAG, "Using badge label: " + mSearchable.getLabelId()); } mBadgeLabel.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null); mBadgeLabel.setText(text); mBadgeLabel.setVisibility(visibility); } /** * Update the hint in the query text field. */ private void updateQueryHint() { if (isShowing()) { String hint = null; if (mSearchable != null) { int hintId = mSearchable.getHintId(); if (hintId != 0) { hint = mActivityContext.getString(hintId); } } mSearchAutoComplete.setHint(hint); } } /** * Update the visibility of the voice button. There are actually two voice search modes, * either of which will activate the button. */ private void updateVoiceButton() { int visibility = View.GONE; if (mSearchable.getVoiceSearchEnabled()) { Intent testIntent = null; if (mSearchable.getVoiceSearchLaunchWebSearch()) { testIntent = mVoiceWebSearchIntent; } else if (mSearchable.getVoiceSearchLaunchRecognizer()) { testIntent = mVoiceAppSearchIntent; } if (testIntent != null) { ResolveInfo ri = getContext().getPackageManager(). resolveActivity(testIntent, PackageManager.MATCH_DEFAULT_ONLY); if (ri != null) { visibility = View.VISIBLE; } } } mVoiceButton.setVisibility(visibility); } /** * Hack to determine whether this is the browser, so we can remove the browser icon * to the left of the search field, as a special requirement for Donut. * * TODO: For Eclair, reconcile this with the rest of the global search UI. */ private boolean isBrowserSearch() { return mLaunchComponent.flattenToShortString().startsWith("com.android.browser/"); } /* * Menu. */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Show search settings menu item if anyone handles the intent for it Intent settingsIntent = new Intent(SearchManager.INTENT_ACTION_SEARCH_SETTINGS); settingsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PackageManager pm = getContext().getPackageManager(); ActivityInfo activityInfo = settingsIntent.resolveActivityInfo(pm, 0); if (activityInfo != null) { settingsIntent.setClassName(activityInfo.applicationInfo.packageName, activityInfo.name); CharSequence label = activityInfo.loadLabel(getContext().getPackageManager()); menu.add(Menu.NONE, Menu.NONE, Menu.NONE, label) .setIcon(android.R.drawable.ic_menu_preferences) .setAlphabeticShortcut('P') .setIntent(settingsIntent); return true; } return super.onCreateOptionsMenu(menu); } @Override public boolean onMenuOpened(int featureId, Menu menu) { // The menu shows up above the IME, regardless of whether it is in front // of the drop-down or not. This looks weird when there is no IME, so // we make sure it is visible. mSearchAutoComplete.ensureImeVisible(); return super.onMenuOpened(featureId, menu); } /** * Listeners of various types */ /** * {@link Dialog#onTouchEvent(MotionEvent)} will cancel the dialog only when the * touch is outside the window. But the window includes space for the drop-down, * so we also cancel on taps outside the search bar when the drop-down is not showing. */ @Override public boolean onTouchEvent(MotionEvent event) { // cancel if the drop-down is not showing and the touch event was outside the search plate if (!mSearchAutoComplete.isPopupShowing() && isOutOfBounds(mSearchPlate, event)) { if (DBG) Log.d(LOG_TAG, "Pop-up not showing and outside of search plate."); cancel(); return true; } // Let Dialog handle events outside the window while the pop-up is showing. return super.onTouchEvent(event); } private boolean isOutOfBounds(View v, MotionEvent event) { final int x = (int) event.getX(); final int y = (int) event.getY(); final int slop = ViewConfiguration.get(mContext).getScaledWindowTouchSlop(); return (x < -slop) || (y < -slop) || (x > (v.getWidth()+slop)) || (y > (v.getHeight()+slop)); } /** * Dialog's OnKeyListener implements various search-specific functionality * * @param keyCode This is the keycode of the typed key, and is the same value as * found in the KeyEvent parameter. * @param event The complete event record for the typed key * * @return Return true if the event was handled here, or false if not. */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (DBG) Log.d(LOG_TAG, "onKeyDown(" + keyCode + "," + event + ")"); if (mSearchable == null) { return false; } // handle back key to go back to previous searchable, etc. if (handleBackKey(keyCode, event)) { return true; } if (keyCode == KeyEvent.KEYCODE_SEARCH) { // If the search key is pressed, toggle between global and in-app search. If we are // currently doing global search and there is no in-app search context to toggle to, // just don't do anything. return toggleGlobalSearch(); } // if it's an action specified by the searchable activity, launch the // entered query with the action key SearchableInfo.ActionKeyInfo actionKey = mSearchable.findActionKey(keyCode); if ((actionKey != null) && (actionKey.getQueryActionMsg() != null)) { launchQuerySearch(keyCode, actionKey.getQueryActionMsg()); return true; } return false; } /** * Callback to watch the textedit field for empty/non-empty */ private TextWatcher mTextWatcher = new TextWatcher() { public void beforeTextChanged(CharSequence s, int start, int before, int after) { } public void onTextChanged(CharSequence s, int start, int before, int after) { if (DBG_LOG_TIMING) { dbgLogTiming("onTextChanged()"); } if (mSearchable == null) { return; } updateWidgetState(); if (!mSearchAutoComplete.isPerformingCompletion()) { // The user changed the query, remember it. mUserQuery = s == null ? "" : s.toString(); } } public void afterTextChanged(Editable s) { if (mSearchable == null) { return; } if (mSearchable.autoUrlDetect() && !mSearchAutoComplete.isPerformingCompletion()) { // The user changed the query, check if it is a URL and if so change the search // button in the soft keyboard to the 'Go' button. int options = (mSearchAutoComplete.getImeOptions() & (~EditorInfo.IME_MASK_ACTION)); if (Regex.WEB_URL_PATTERN.matcher(mUserQuery).matches()) { options = options | EditorInfo.IME_ACTION_GO; } else { options = options | EditorInfo.IME_ACTION_SEARCH; } if (options != mSearchAutoCompleteImeOptions) { mSearchAutoCompleteImeOptions = options; mSearchAutoComplete.setImeOptions(options); // This call is required to update the soft keyboard UI with latest IME flags. mSearchAutoComplete.setInputType(mSearchAutoComplete.getInputType()); } } } }; /** * Enable/Disable the cancel button based on edit text state (any text?) */ private void updateWidgetState() { // enable the button if we have one or more non-space characters boolean enabled = !mSearchAutoComplete.isEmpty(); mGoButton.setEnabled(enabled); mGoButton.setFocusable(enabled); } /** * React to typing in the GO search button by refocusing to EditText. * Continue typing the query. */ View.OnKeyListener mButtonsKeyListener = new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // guard against possible race conditions if (mSearchable == null) { return false; } if (!event.isSystem() && (keyCode != KeyEvent.KEYCODE_DPAD_UP) && (keyCode != KeyEvent.KEYCODE_DPAD_LEFT) && (keyCode != KeyEvent.KEYCODE_DPAD_RIGHT) && (keyCode != KeyEvent.KEYCODE_DPAD_CENTER)) { // restore focus and give key to EditText ... if (mSearchAutoComplete.requestFocus()) { return mSearchAutoComplete.dispatchKeyEvent(event); } } return false; } }; /** * React to a click in the GO button by launching a search. */ View.OnClickListener mGoButtonClickListener = new View.OnClickListener() { public void onClick(View v) { // guard against possible race conditions if (mSearchable == null) { return; } launchQuerySearch(); } }; /** * React to a click in the voice search button. */ View.OnClickListener mVoiceButtonClickListener = new View.OnClickListener() { public void onClick(View v) { // guard against possible race conditions if (mSearchable == null) { return; } try { if (mSearchable.getVoiceSearchLaunchWebSearch()) { getContext().startActivity(mVoiceWebSearchIntent); } else if (mSearchable.getVoiceSearchLaunchRecognizer()) { Intent appSearchIntent = createVoiceAppSearchIntent(mVoiceAppSearchIntent); getContext().startActivity(appSearchIntent); } } catch (ActivityNotFoundException e) { // Should not happen, since we check the availability of // voice search before showing the button. But just in case... Log.w(LOG_TAG, "Could not find voice search activity"); } } }; /** * Create and return an Intent that can launch the voice search activity, perform a specific * voice transcription, and forward the results to the searchable activity. * * @param baseIntent The voice app search intent to start from * @return A completely-configured intent ready to send to the voice search activity */ private Intent createVoiceAppSearchIntent(Intent baseIntent) { ComponentName searchActivity = mSearchable.getSearchActivity(); // create the necessary intent to set up a search-and-forward operation // in the voice search system. We have to keep the bundle separate, // because it becomes immutable once it enters the PendingIntent Intent queryIntent = new Intent(Intent.ACTION_SEARCH); queryIntent.setComponent(searchActivity); PendingIntent pending = PendingIntent.getActivity( getContext(), 0, queryIntent, PendingIntent.FLAG_ONE_SHOT); // Now set up the bundle that will be inserted into the pending intent // when it's time to do the search. We always build it here (even if empty) // because the voice search activity will always need to insert "QUERY" into // it anyway. Bundle queryExtras = new Bundle(); if (mAppSearchData != null) { queryExtras.putBundle(SearchManager.APP_DATA, mAppSearchData); } // Now build the intent to launch the voice search. Add all necessary // extras to launch the voice recognizer, and then all the necessary extras // to forward the results to the searchable activity Intent voiceIntent = new Intent(baseIntent); // Add all of the configuration options supplied by the searchable's metadata String languageModel = RecognizerIntent.LANGUAGE_MODEL_FREE_FORM; String prompt = null; String language = null; int maxResults = 1; Resources resources = mActivityContext.getResources(); if (mSearchable.getVoiceLanguageModeId() != 0) { languageModel = resources.getString(mSearchable.getVoiceLanguageModeId()); } if (mSearchable.getVoicePromptTextId() != 0) { prompt = resources.getString(mSearchable.getVoicePromptTextId()); } if (mSearchable.getVoiceLanguageId() != 0) { language = resources.getString(mSearchable.getVoiceLanguageId()); } if (mSearchable.getVoiceMaxResults() != 0) { maxResults = mSearchable.getVoiceMaxResults(); } voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, languageModel); voiceIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt); voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language); voiceIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxResults); voiceIntent.putExtra(EXTRA_CALLING_PACKAGE, searchActivity == null ? null : searchActivity.toShortString()); // Add the values that configure forwarding the results voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT, pending); voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT_BUNDLE, queryExtras); return voiceIntent; } /** * Corrects http/https typo errors in the given url string, and if the protocol specifier was * not present defaults to http. * * @param inUrl URL to check and fix * @return fixed URL string. */ private String fixUrl(String inUrl) { if (inUrl.startsWith("http://") || inUrl.startsWith("https://")) return inUrl; if (inUrl.startsWith("http:") || inUrl.startsWith("https:")) { if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) { inUrl = inUrl.replaceFirst("/", "//"); } else { inUrl = inUrl.replaceFirst(":", "://"); } } if (inUrl.indexOf("://") == -1) { inUrl = "http://" + inUrl; } return inUrl; } /** * React to the user typing "enter" or other hardwired keys while typing in the search box. * This handles these special keys while the edit box has focus. */ View.OnKeyListener mTextKeyListener = new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // guard against possible race conditions if (mSearchable == null) { return false; } if (DBG_LOG_TIMING) dbgLogTiming("doTextKey()"); if (DBG) { Log.d(LOG_TAG, "mTextListener.onKey(" + keyCode + "," + event + "), selection: " + mSearchAutoComplete.getListSelection()); } // If a suggestion is selected, handle enter, search key, and action keys // as presses on the selected suggestion if (mSearchAutoComplete.isPopupShowing() && mSearchAutoComplete.getListSelection() != ListView.INVALID_POSITION) { return onSuggestionsKey(v, keyCode, event); } // If there is text in the query box, handle enter, and action keys // The search key is handled by the dialog's onKeyDown(). if (!mSearchAutoComplete.isEmpty()) { if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) { v.cancelLongPress(); // If this is a url entered by the user & we displayed the 'Go' button which // the user clicked, launch the url instead of using it as a search query. if (mSearchable.autoUrlDetect() && (mSearchAutoCompleteImeOptions & EditorInfo.IME_MASK_ACTION) == EditorInfo.IME_ACTION_GO) { Uri uri = Uri.parse(fixUrl(mSearchAutoComplete.getText().toString())); Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); launchIntent(intent); } else { // Launch as a regular search. launchQuerySearch(); } return true; } if (event.getAction() == KeyEvent.ACTION_DOWN) { SearchableInfo.ActionKeyInfo actionKey = mSearchable.findActionKey(keyCode); if ((actionKey != null) && (actionKey.getQueryActionMsg() != null)) { launchQuerySearch(keyCode, actionKey.getQueryActionMsg()); return true; } } } return false; } }; @Override public void hide() { if (!isShowing()) return; // We made sure the IME was displayed, so also make sure it is closed // when we go away. InputMethodManager imm = (InputMethodManager)getContext() .getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { imm.hideSoftInputFromWindow( getWindow().getDecorView().getWindowToken(), 0); } super.hide(); } /** * React to the user typing while in the suggestions list. First, check for action * keys. If not handled, try refocusing regular characters into the EditText. */ private boolean onSuggestionsKey(View v, int keyCode, KeyEvent event) { // guard against possible race conditions (late arrival after dismiss) if (mSearchable == null) { return false; } if (mSuggestionsAdapter == null) { return false; } if (event.getAction() == KeyEvent.ACTION_DOWN) { if (DBG_LOG_TIMING) { dbgLogTiming("onSuggestionsKey()"); } // First, check for enter or search (both of which we'll treat as a "click") if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_SEARCH) { int position = mSearchAutoComplete.getListSelection(); return launchSuggestion(position); } // Next, check for left/right moves, which we use to "return" the user to the edit view if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) { // give "focus" to text editor, with cursor at the beginning if // left key, at end if right key // TODO: Reverse left/right for right-to-left languages, e.g. Arabic int selPoint = (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) ? 0 : mSearchAutoComplete.length(); mSearchAutoComplete.setSelection(selPoint); mSearchAutoComplete.setListSelection(0); mSearchAutoComplete.clearListSelection(); mSearchAutoComplete.ensureImeVisible(); return true; } // Next, check for an "up and out" move if (keyCode == KeyEvent.KEYCODE_DPAD_UP && 0 == mSearchAutoComplete.getListSelection()) { restoreUserQuery(); // let ACTV complete the move return false; } // Next, check for an "action key" SearchableInfo.ActionKeyInfo actionKey = mSearchable.findActionKey(keyCode); if ((actionKey != null) && ((actionKey.getSuggestActionMsg() != null) || (actionKey.getSuggestActionMsgColumn() != null))) { // launch suggestion using action key column int position = mSearchAutoComplete.getListSelection(); if (position != ListView.INVALID_POSITION) { Cursor c = mSuggestionsAdapter.getCursor(); if (c.moveToPosition(position)) { final String actionMsg = getActionKeyMessage(c, actionKey); if (actionMsg != null && (actionMsg.length() > 0)) { return launchSuggestion(position, keyCode, actionMsg); } } } } } return false; } /** * Launch a search for the text in the query text field. */ protected void launchQuerySearch() { launchQuerySearch(KeyEvent.KEYCODE_UNKNOWN, null); } /** * Launch a search for the text in the query text field. * * @param actionKey The key code of the action key that was pressed, * or {@link KeyEvent#KEYCODE_UNKNOWN} if none. * @param actionMsg The message for the action key that was pressed, * or <code>null</code> if none. */ protected void launchQuerySearch(int actionKey, String actionMsg) { String query = mSearchAutoComplete.getText().toString(); String action = mGlobalSearchMode ? Intent.ACTION_WEB_SEARCH : Intent.ACTION_SEARCH; Intent intent = createIntent(action, null, null, query, null, actionKey, actionMsg); launchIntent(intent); } /** * Launches an intent based on a suggestion. * * @param position The index of the suggestion to create the intent from. * @return true if a successful launch, false if could not (e.g. bad position). */ protected boolean launchSuggestion(int position) { return launchSuggestion(position, KeyEvent.KEYCODE_UNKNOWN, null); } /** * Launches an intent based on a suggestion. * * @param position The index of the suggestion to create the intent from. * @param actionKey The key code of the action key that was pressed, * or {@link KeyEvent#KEYCODE_UNKNOWN} if none. * @param actionMsg The message for the action key that was pressed, * or <code>null</code> if none. * @return true if a successful launch, false if could not (e.g. bad position). */ protected boolean launchSuggestion(int position, int actionKey, String actionMsg) { Cursor c = mSuggestionsAdapter.getCursor(); if ((c != null) && c.moveToPosition(position)) { Intent intent = createIntentFromSuggestion(c, actionKey, actionMsg); // report back about the click if (mGlobalSearchMode) { // in global search mode, do it via cursor mSuggestionsAdapter.callCursorOnClick(c, position); } else if (intent != null && mPreviousComponents != null && !mPreviousComponents.isEmpty()) { // in-app search (and we have pivoted in as told by mPreviousComponents, // which is used for keeping track of what we pop back to when we are pivoting into // in app search.) reportInAppClickToGlobalSearch(c, intent); } // launch the intent launchIntent(intent); return true; } return false; } /** * Report a click from an in app search result back to global search for shortcutting porpoises. * * @param c The cursor that is pointing to the clicked position. * @param intent The intent that will be launched for the click. */ private void reportInAppClickToGlobalSearch(Cursor c, Intent intent) { // for in app search, still tell global search via content provider Uri uri = getClickReportingUri(); final ContentValues cv = new ContentValues(); cv.put(SearchManager.SEARCH_CLICK_REPORT_COLUMN_QUERY, mUserQuery); final ComponentName source = mSearchable.getSearchActivity(); cv.put(SearchManager.SEARCH_CLICK_REPORT_COLUMN_COMPONENT, source.flattenToShortString()); // grab the intent columns from the intent we created since it has additional // logic for falling back on the searchable default cv.put(SearchManager.SUGGEST_COLUMN_INTENT_ACTION, intent.getAction()); cv.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA, intent.getDataString()); cv.put(SearchManager.SUGGEST_COLUMN_INTENT_COMPONENT_NAME, intent.getStringExtra(SearchManager.COMPONENT_NAME_KEY)); // ensure the icons will work for global search cv.put(SearchManager.SUGGEST_COLUMN_ICON_1, wrapIconForPackage( - source, + mSearchable.getSuggestPackage(), getColumnString(c, SearchManager.SUGGEST_COLUMN_ICON_1))); cv.put(SearchManager.SUGGEST_COLUMN_ICON_2, wrapIconForPackage( - source, + mSearchable.getSuggestPackage(), getColumnString(c, SearchManager.SUGGEST_COLUMN_ICON_2))); // the rest can be passed through directly cv.put(SearchManager.SUGGEST_COLUMN_FORMAT, getColumnString(c, SearchManager.SUGGEST_COLUMN_FORMAT)); cv.put(SearchManager.SUGGEST_COLUMN_TEXT_1, getColumnString(c, SearchManager.SUGGEST_COLUMN_TEXT_1)); cv.put(SearchManager.SUGGEST_COLUMN_TEXT_2, getColumnString(c, SearchManager.SUGGEST_COLUMN_TEXT_2)); cv.put(SearchManager.SUGGEST_COLUMN_QUERY, getColumnString(c, SearchManager.SUGGEST_COLUMN_QUERY)); cv.put(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, getColumnString(c, SearchManager.SUGGEST_COLUMN_SHORTCUT_ID)); // note: deliberately omitting background color since it is only for global search // "more results" entries mContext.getContentResolver().insert(uri, cv); } /** * @return A URI appropriate for reporting a click. */ private Uri getClickReportingUri() { Uri.Builder uriBuilder = new Uri.Builder() .scheme(ContentResolver.SCHEME_CONTENT) .authority(SearchManager.SEARCH_CLICK_REPORT_AUTHORITY); uriBuilder.appendPath(SearchManager.SEARCH_CLICK_REPORT_URI_PATH); return uriBuilder .query("") // TODO: Remove, workaround for a bug in Uri.writeToParcel() .fragment("") // TODO: Remove, workaround for a bug in Uri.writeToParcel() .build(); } /** * Wraps an icon for a particular package. If the icon is a resource id, it is converted into * an android.resource:// URI. * - * @param source The source of the icon + * @param packageName The source of the icon * @param icon The icon retrieved from a suggestion column * @return An icon string appropriate for the package. */ - private String wrapIconForPackage(ComponentName source, String icon) { + private String wrapIconForPackage(String packageName, String icon) { if (icon == null || icon.length() == 0 || "0".equals(icon)) { // SearchManager specifies that null or zero can be returned to indicate // no icon. We also allow empty string. return null; } else if (!Character.isDigit(icon.charAt(0))){ return icon; } else { - String packageName = source.getPackageName(); return new Uri.Builder() .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) .authority(packageName) .encodedPath(icon) .toString(); } } /** * Launches an intent, including any special intent handling. Doesn't dismiss the dialog * since that will be handled in {@link SearchDialogWrapper#performActivityResuming} */ private void launchIntent(Intent intent) { if (intent == null) { return; } if (handleSpecialIntent(intent)){ return; } Log.d(LOG_TAG, "launching " + intent); try { // in global search mode, we send the activity straight to the original suggestion // source. this is because GlobalSearch may not have permission to launch the // intent, and to avoid the extra step of going through GlobalSearch. if (mGlobalSearchMode) { launchGlobalSearchIntent(intent); } else { // If the intent was created from a suggestion, it will always have an explicit // component here. Log.i(LOG_TAG, "Starting (as ourselves) " + intent.toURI()); getContext().startActivity(intent); // If the search switches to a different activity, // SearchDialogWrapper#performActivityResuming // will handle hiding the dialog when the next activity starts, but for // real in-app search, we still need to dismiss the dialog. if (isInRealAppSearch()) { dismiss(); } } } catch (RuntimeException ex) { Log.e(LOG_TAG, "Failed launch activity: " + intent, ex); } } private void launchGlobalSearchIntent(Intent intent) { final String packageName; // GlobalSearch puts the original source of the suggestion in the // 'component name' column. If set, we send the intent to that activity. // We trust GlobalSearch to always set this to the suggestion source. String intentComponent = intent.getStringExtra(SearchManager.COMPONENT_NAME_KEY); if (intentComponent != null) { ComponentName componentName = ComponentName.unflattenFromString(intentComponent); intent.setComponent(componentName); intent.removeExtra(SearchManager.COMPONENT_NAME_KEY); // Launch the intent as the suggestion source. // This prevents sources from using the search dialog to launch // intents that they don't have permission for themselves. packageName = componentName.getPackageName(); } else { // If there is no component in the suggestion, it must be a built-in suggestion // from GlobalSearch (e.g. "Search the web for") or the intent // launched when pressing the search/go button in the search dialog. // Launch the intent with the permissions of GlobalSearch. packageName = mSearchable.getSearchActivity().getPackageName(); } // Launch all global search suggestions as new tasks, since they don't relate // to the current task. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); setBrowserApplicationId(intent); startActivityInPackage(intent, packageName); } /** * If the intent is to open an HTTP or HTTPS URL, we set * {@link Browser#EXTRA_APPLICATION_ID} so that any existing browser window that * has been opened by us for the same URL will be reused. */ private void setBrowserApplicationId(Intent intent) { Uri data = intent.getData(); if (Intent.ACTION_VIEW.equals(intent.getAction()) && data != null) { String scheme = data.getScheme(); if (scheme != null && scheme.startsWith("http")) { intent.putExtra(Browser.EXTRA_APPLICATION_ID, data.toString()); } } } /** * Starts an activity as if it had been started by the given package. * * @param intent The description of the activity to start. * @param packageName * @throws ActivityNotFoundException If the intent could not be resolved to * and existing activity. * @throws SecurityException If the package does not have permission to start * start the activity. * @throws AndroidRuntimeException If some other error occurs. */ private void startActivityInPackage(Intent intent, String packageName) { try { int uid = ActivityThread.getPackageManager().getPackageUid(packageName); if (uid < 0) { throw new AndroidRuntimeException("Package UID not found " + packageName); } String resolvedType = intent.resolveTypeIfNeeded(getContext().getContentResolver()); IBinder resultTo = null; String resultWho = null; int requestCode = -1; boolean onlyIfNeeded = false; Log.i(LOG_TAG, "Starting (uid " + uid + ", " + packageName + ") " + intent.toURI()); int result = ActivityManagerNative.getDefault().startActivityInPackage( uid, intent, resolvedType, resultTo, resultWho, requestCode, onlyIfNeeded); checkStartActivityResult(result, intent); } catch (RemoteException ex) { throw new AndroidRuntimeException(ex); } } // Stolen from Instrumentation.checkStartActivityResult() private static void checkStartActivityResult(int res, Intent intent) { if (res >= IActivityManager.START_SUCCESS) { return; } switch (res) { case IActivityManager.START_INTENT_NOT_RESOLVED: case IActivityManager.START_CLASS_NOT_FOUND: if (intent.getComponent() != null) throw new ActivityNotFoundException( "Unable to find explicit activity class " + intent.getComponent().toShortString() + "; have you declared this activity in your AndroidManifest.xml?"); throw new ActivityNotFoundException( "No Activity found to handle " + intent); case IActivityManager.START_PERMISSION_DENIED: throw new SecurityException("Not allowed to start activity " + intent); case IActivityManager.START_FORWARD_AND_REQUEST_CONFLICT: throw new AndroidRuntimeException( "FORWARD_RESULT_FLAG used while also requesting a result"); default: throw new AndroidRuntimeException("Unknown error code " + res + " when starting " + intent); } } /** * Handles the special intent actions declared in {@link SearchManager}. * * @return <code>true</code> if the intent was handled. */ private boolean handleSpecialIntent(Intent intent) { String action = intent.getAction(); if (SearchManager.INTENT_ACTION_CHANGE_SEARCH_SOURCE.equals(action)) { handleChangeSourceIntent(intent); return true; } return false; } /** * Handles {@link SearchManager#INTENT_ACTION_CHANGE_SEARCH_SOURCE}. */ private void handleChangeSourceIntent(Intent intent) { Uri dataUri = intent.getData(); if (dataUri == null) { Log.w(LOG_TAG, "SearchManager.INTENT_ACTION_CHANGE_SOURCE without intent data."); return; } ComponentName componentName = ComponentName.unflattenFromString(dataUri.toString()); if (componentName == null) { Log.w(LOG_TAG, "Invalid ComponentName: " + dataUri); return; } if (DBG) Log.d(LOG_TAG, "Switching to " + componentName); pushPreviousComponent(mLaunchComponent); if (!show(componentName, mAppSearchData, false)) { Log.w(LOG_TAG, "Failed to switch to source " + componentName); popPreviousComponent(); return; } String query = intent.getStringExtra(SearchManager.QUERY); setUserQuery(query); mSearchAutoComplete.showDropDown(); } /** * Sets the list item selection in the AutoCompleteTextView's ListView. */ public void setListSelection(int index) { mSearchAutoComplete.setListSelection(index); } /** * Saves the previous component that was searched, so that we can go * back to it. */ private void pushPreviousComponent(ComponentName componentName) { if (mPreviousComponents == null) { mPreviousComponents = new ArrayList<ComponentName>(); } mPreviousComponents.add(componentName); } /** * Pops the previous component off the stack and returns it. * * @return The component name, or <code>null</code> if there was * no previous component. */ private ComponentName popPreviousComponent() { if (mPreviousComponents == null) { return null; } int size = mPreviousComponents.size(); if (size == 0) { return null; } return mPreviousComponents.remove(size - 1); } /** * Goes back to the previous component that was searched, if any. * * @return <code>true</code> if there was a previous component that we could go back to. */ private boolean backToPreviousComponent() { ComponentName previous = popPreviousComponent(); if (previous == null) { return false; } if (!show(previous, mAppSearchData, false)) { Log.w(LOG_TAG, "Failed to switch to source " + previous); return false; } // must touch text to trigger suggestions // TODO: should this be the text as it was when the user left // the source that we are now going back to? String query = mSearchAutoComplete.getText().toString(); setUserQuery(query); return true; } /** * When a particular suggestion has been selected, perform the various lookups required * to use the suggestion. This includes checking the cursor for suggestion-specific data, * and/or falling back to the XML for defaults; It also creates REST style Uri data when * the suggestion includes a data id. * * @param c The suggestions cursor, moved to the row of the user's selection * @param actionKey The key code of the action key that was pressed, * or {@link KeyEvent#KEYCODE_UNKNOWN} if none. * @param actionMsg The message for the action key that was pressed, * or <code>null</code> if none. * @return An intent for the suggestion at the cursor's position. */ private Intent createIntentFromSuggestion(Cursor c, int actionKey, String actionMsg) { try { // use specific action if supplied, or default action if supplied, or fixed default String action = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_ACTION); // some items are display only, or have effect via the cursor respond click reporting. if (SearchManager.INTENT_ACTION_NONE.equals(action)) { return null; } if (action == null) { action = mSearchable.getSuggestIntentAction(); } if (action == null) { action = Intent.ACTION_SEARCH; } // use specific data if supplied, or default data if supplied String data = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_DATA); if (data == null) { data = mSearchable.getSuggestIntentData(); } // then, if an ID was provided, append it. if (data != null) { String id = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID); if (id != null) { data = data + "/" + Uri.encode(id); } } Uri dataUri = (data == null) ? null : Uri.parse(data); String componentName = getColumnString( c, SearchManager.SUGGEST_COLUMN_INTENT_COMPONENT_NAME); String query = getColumnString(c, SearchManager.SUGGEST_COLUMN_QUERY); String extraData = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA); return createIntent(action, dataUri, extraData, query, componentName, actionKey, actionMsg); } catch (RuntimeException e ) { int rowNum; try { // be really paranoid now rowNum = c.getPosition(); } catch (RuntimeException e2 ) { rowNum = -1; } Log.w(LOG_TAG, "Search Suggestions cursor at row " + rowNum + " returned exception" + e.toString()); return null; } } /** * Constructs an intent from the given information and the search dialog state. * * @param action Intent action. * @param data Intent data, or <code>null</code>. * @param extraData Data for {@link SearchManager#EXTRA_DATA_KEY} or <code>null</code>. * @param query Intent query, or <code>null</code>. * @param componentName Data for {@link SearchManager#COMPONENT_NAME_KEY} or <code>null</code>. * @param actionKey The key code of the action key that was pressed, * or {@link KeyEvent#KEYCODE_UNKNOWN} if none. * @param actionMsg The message for the action key that was pressed, * or <code>null</code> if none. * @return The intent. */ private Intent createIntent(String action, Uri data, String extraData, String query, String componentName, int actionKey, String actionMsg) { // Now build the Intent Intent intent = new Intent(action); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (data != null) { intent.setData(data); } intent.putExtra(SearchManager.USER_QUERY, mUserQuery); if (query != null) { intent.putExtra(SearchManager.QUERY, query); } if (extraData != null) { intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData); } if (componentName != null) { intent.putExtra(SearchManager.COMPONENT_NAME_KEY, componentName); } if (mAppSearchData != null) { intent.putExtra(SearchManager.APP_DATA, mAppSearchData); } if (actionKey != KeyEvent.KEYCODE_UNKNOWN) { intent.putExtra(SearchManager.ACTION_KEY, actionKey); intent.putExtra(SearchManager.ACTION_MSG, actionMsg); } // Only allow 3rd-party intents from GlobalSearch if (!mGlobalSearchMode) { intent.setComponent(mSearchable.getSearchActivity()); } return intent; } /** * For a given suggestion and a given cursor row, get the action message. If not provided * by the specific row/column, also check for a single definition (for the action key). * * @param c The cursor providing suggestions * @param actionKey The actionkey record being examined * * @return Returns a string, or null if no action key message for this suggestion */ private static String getActionKeyMessage(Cursor c, SearchableInfo.ActionKeyInfo actionKey) { String result = null; // check first in the cursor data, for a suggestion-specific message final String column = actionKey.getSuggestActionMsgColumn(); if (column != null) { result = SuggestionsAdapter.getColumnString(c, column); } // If the cursor didn't give us a message, see if there's a single message defined // for the actionkey (for all suggestions) if (result == null) { result = actionKey.getSuggestActionMsg(); } return result; } /** * Local subclass for AutoCompleteTextView. */ public static class SearchAutoComplete extends AutoCompleteTextView { private int mThreshold; private SearchDialog mSearchDialog; public SearchAutoComplete(Context context) { super(context); mThreshold = getThreshold(); } public SearchAutoComplete(Context context, AttributeSet attrs) { super(context, attrs); mThreshold = getThreshold(); } public SearchAutoComplete(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mThreshold = getThreshold(); } private void setSearchDialog(SearchDialog searchDialog) { mSearchDialog = searchDialog; } @Override public void setThreshold(int threshold) { super.setThreshold(threshold); mThreshold = threshold; } /** * Returns true if the text field is empty, or contains only whitespace. */ private boolean isEmpty() { return TextUtils.getTrimmedLength(getText()) == 0; } /** * We override this method to avoid replacing the query box text * when a suggestion is clicked. */ @Override protected void replaceText(CharSequence text) { } /** * We override this method to avoid an extra onItemClick being called on the * drop-down's OnItemClickListener by {@link AutoCompleteTextView#onKeyUp(int, KeyEvent)} * when an item is clicked with the trackball. */ @Override public void performCompletion() { } /** * We override this method to be sure and show the soft keyboard if appropriate when * the TextView has focus. */ @Override public void onWindowFocusChanged(boolean hasWindowFocus) { super.onWindowFocusChanged(hasWindowFocus); if (hasWindowFocus) { InputMethodManager inputManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.showSoftInput(this, 0); } } /** * We override this method so that we can allow a threshold of zero, which ACTV does not. */ @Override public boolean enoughToFilter() { return mThreshold <= 0 || super.enoughToFilter(); } /** * {@link AutoCompleteTextView#onKeyPreIme(int, KeyEvent)}) dismisses the drop-down on BACK, * so we must override this method to modify the BACK behavior. */ @Override public boolean onKeyPreIme(int keyCode, KeyEvent event) { if (mSearchDialog.mSearchable == null) { return false; } if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { if (mSearchDialog.backToPreviousComponent()) { return true; } // If the drop-down obscures the keyboard, the user wouldn't see anything // happening when pressing back, so we dismiss the entire dialog instead. if (isInputMethodNotNeeded()) { mSearchDialog.cancel(); return true; } return false; // will dismiss soft keyboard if necessary } return false; } } protected boolean handleBackKey(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { if (backToPreviousComponent()) { return true; } cancel(); return true; } return false; } /** * Implements OnItemClickListener */ public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (DBG) Log.d(LOG_TAG, "onItemClick() position " + position); launchSuggestion(position); } /** * Implements OnItemSelectedListener */ public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (DBG) Log.d(LOG_TAG, "onItemSelected() position " + position); // A suggestion has been selected, rewrite the query if possible, // otherwise the restore the original query. if (REWRITE_QUERIES) { rewriteQueryFromSuggestion(position); } } /** * Implements OnItemSelectedListener */ public void onNothingSelected(AdapterView<?> parent) { if (DBG) Log.d(LOG_TAG, "onNothingSelected()"); } /** * Query rewriting. */ private void rewriteQueryFromSuggestion(int position) { Cursor c = mSuggestionsAdapter.getCursor(); if (c == null) { return; } if (c.moveToPosition(position)) { // Get the new query from the suggestion. CharSequence newQuery = mSuggestionsAdapter.convertToString(c); if (newQuery != null) { // The suggestion rewrites the query. if (DBG) Log.d(LOG_TAG, "Rewriting query to '" + newQuery + "'"); // Update the text field, without getting new suggestions. setQuery(newQuery); } else { // The suggestion does not rewrite the query, restore the user's query. if (DBG) Log.d(LOG_TAG, "Suggestion gives no rewrite, restoring user query."); restoreUserQuery(); } } else { // We got a bad position, restore the user's query. Log.w(LOG_TAG, "Bad suggestion position: " + position); restoreUserQuery(); } } /** * Restores the query entered by the user if needed. */ private void restoreUserQuery() { if (DBG) Log.d(LOG_TAG, "Restoring query to '" + mUserQuery + "'"); setQuery(mUserQuery); } /** * Sets the text in the query box, without updating the suggestions. */ private void setQuery(CharSequence query) { mSearchAutoComplete.setText(query, false); if (query != null) { mSearchAutoComplete.setSelection(query.length()); } } /** * Sets the text in the query box, updating the suggestions. */ private void setUserQuery(String query) { if (query == null) { query = ""; } mUserQuery = query; mSearchAutoComplete.setText(query); mSearchAutoComplete.setSelection(query.length()); } /** * Debugging Support */ /** * For debugging only, sample the millisecond clock and log it. * Uses AtomicLong so we can use in multiple threads */ private AtomicLong mLastLogTime = new AtomicLong(SystemClock.uptimeMillis()); private void dbgLogTiming(final String caller) { long millis = SystemClock.uptimeMillis(); long oldTime = mLastLogTime.getAndSet(millis); long delta = millis - oldTime; final String report = millis + " (+" + delta + ") ticks for Search keystroke in " + caller; Log.d(LOG_TAG,report); } } diff --git a/core/java/android/server/search/SearchableInfo.java b/core/java/android/server/search/SearchableInfo.java index 045b0c2f..69ef98c0 100644 --- a/core/java/android/server/search/SearchableInfo.java +++ b/core/java/android/server/search/SearchableInfo.java @@ -1,787 +1,795 @@ /* * 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 android.server.search; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ComponentName; import android.content.Context; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ProviderInfo; import android.content.res.TypedArray; import android.content.res.XmlResourceParser; import android.os.Parcel; import android.os.Parcelable; import android.text.InputType; import android.util.AttributeSet; import android.util.Log; import android.util.Xml; import android.view.inputmethod.EditorInfo; import java.io.IOException; import java.util.HashMap; public final class SearchableInfo implements Parcelable { // general debugging support private static final boolean DBG = false; private static final String LOG_TAG = "SearchableInfo"; // static strings used for XML lookups. // TODO how should these be documented for the developer, in a more structured way than // the current long wordy javadoc in SearchManager.java ? private static final String MD_LABEL_SEARCHABLE = "android.app.searchable"; private static final String MD_XML_ELEMENT_SEARCHABLE = "searchable"; private static final String MD_XML_ELEMENT_SEARCHABLE_ACTION_KEY = "actionkey"; // flags in the searchMode attribute private static final int SEARCH_MODE_BADGE_LABEL = 0x04; private static final int SEARCH_MODE_BADGE_ICON = 0x08; private static final int SEARCH_MODE_QUERY_REWRITE_FROM_DATA = 0x10; private static final int SEARCH_MODE_QUERY_REWRITE_FROM_TEXT = 0x20; // true member variables - what we know about the searchability private final int mLabelId; private final ComponentName mSearchActivity; private final int mHintId; private final int mSearchMode; private final int mIconId; private final int mSearchButtonText; private final int mSearchInputType; private final int mSearchImeOptions; private final boolean mIncludeInGlobalSearch; private final boolean mQueryAfterZeroResults; private final boolean mAutoUrlDetect; private final String mSettingsDescription; private final String mSuggestAuthority; private final String mSuggestPath; private final String mSuggestSelection; private final String mSuggestIntentAction; private final String mSuggestIntentData; private final int mSuggestThreshold; // Maps key codes to action key information. auto-boxing is not so bad here, // since keycodes for the hard keys are < 127. For such values, Integer.valueOf() // uses shared Integer objects. // This is not final, to allow lazy initialization. private HashMap<Integer,ActionKeyInfo> mActionKeys = null; private final String mSuggestProviderPackage; // Flag values for Searchable_voiceSearchMode private static int VOICE_SEARCH_SHOW_BUTTON = 1; private static int VOICE_SEARCH_LAUNCH_WEB_SEARCH = 2; private static int VOICE_SEARCH_LAUNCH_RECOGNIZER = 4; private final int mVoiceSearchMode; private final int mVoiceLanguageModeId; // voiceLanguageModel private final int mVoicePromptTextId; // voicePromptText private final int mVoiceLanguageId; // voiceLanguage private final int mVoiceMaxResults; // voiceMaxResults /** * Retrieve the authority for obtaining search suggestions. * * @return Returns a string containing the suggestions authority. */ public String getSuggestAuthority() { return mSuggestAuthority; } /** + * Gets the name of the package where the suggestion provider lives, + * or {@code null}. + */ + public String getSuggestPackage() { + return mSuggestProviderPackage; + } + + /** * Gets the component name of the searchable activity. */ public ComponentName getSearchActivity() { return mSearchActivity; } /** * Checks whether the badge should be a text label. */ public boolean useBadgeLabel() { return 0 != (mSearchMode & SEARCH_MODE_BADGE_LABEL); } /** * Checks whether the badge should be an icon. */ public boolean useBadgeIcon() { return (0 != (mSearchMode & SEARCH_MODE_BADGE_ICON)) && (mIconId != 0); } /** * Checks whether the text in the query field should come from the suggestion intent data. */ public boolean shouldRewriteQueryFromData() { return 0 != (mSearchMode & SEARCH_MODE_QUERY_REWRITE_FROM_DATA); } /** * Checks whether the text in the query field should come from the suggestion title. */ public boolean shouldRewriteQueryFromText() { return 0 != (mSearchMode & SEARCH_MODE_QUERY_REWRITE_FROM_TEXT); } /** * Gets the description to use for this source in system search settings, or null if * none has been specified. */ public String getSettingsDescription() { return mSettingsDescription; } /** * Retrieve the path for obtaining search suggestions. * * @return Returns a string containing the suggestions path, or null if not provided. */ public String getSuggestPath() { return mSuggestPath; } /** * Retrieve the selection pattern for obtaining search suggestions. This must * include a single ? which will be used for the user-typed characters. * * @return Returns a string containing the suggestions authority. */ public String getSuggestSelection() { return mSuggestSelection; } /** * Retrieve the (optional) intent action for use with these suggestions. This is * useful if all intents will have the same action (e.g. "android.intent.action.VIEW"). * * Can be overriden in any given suggestion via the AUTOSUGGEST_COLUMN_INTENT_ACTION column. * * @return Returns a string containing the default intent action. */ public String getSuggestIntentAction() { return mSuggestIntentAction; } /** * Retrieve the (optional) intent data for use with these suggestions. This is * useful if all intents will have similar data URIs (e.g. "android.intent.action.VIEW"), * but you'll likely need to provide a specific ID as well via the column * AUTOSUGGEST_COLUMN_INTENT_DATA_ID, which will be appended to the intent data URI. * * Can be overriden in any given suggestion via the AUTOSUGGEST_COLUMN_INTENT_DATA column. * * @return Returns a string containing the default intent data. */ public String getSuggestIntentData() { return mSuggestIntentData; } /** * Gets the suggestion threshold for use with these suggestions. * * @return The value of the <code>searchSuggestThreshold</code> attribute, * or 0 if the attribute is not set. */ public int getSuggestThreshold() { return mSuggestThreshold; } /** * Get the context for the searchable activity. * * This is fairly expensive so do it on the original scan, or when an app is * selected, but don't hang on to the result forever. * * @param context You need to supply a context to start with * @return Returns a context related to the searchable activity */ public Context getActivityContext(Context context) { return createActivityContext(context, mSearchActivity); } /** * Creates a context for another activity. */ private static Context createActivityContext(Context context, ComponentName activity) { Context theirContext = null; try { theirContext = context.createPackageContext(activity.getPackageName(), 0); } catch (PackageManager.NameNotFoundException e) { // unexpected, but we deal with this by null-checking theirContext } catch (java.lang.SecurityException e) { // unexpected, but we deal with this by null-checking theirContext } return theirContext; } /** * Get the context for the suggestions provider. * * This is fairly expensive so do it on the original scan, or when an app is * selected, but don't hang on to the result forever. * * @param context You need to supply a context to start with * @param activityContext If we can determine that the provider and the activity are the * same, we'll just return this one. * @return Returns a context related to the context provider */ public Context getProviderContext(Context context, Context activityContext) { Context theirContext = null; if (mSearchActivity.getPackageName().equals(mSuggestProviderPackage)) { return activityContext; } if (mSuggestProviderPackage != null) try { theirContext = context.createPackageContext(mSuggestProviderPackage, 0); } catch (PackageManager.NameNotFoundException e) { // unexpected, but we deal with this by null-checking theirContext } catch (java.lang.SecurityException e) { // unexpected, but we deal with this by null-checking theirContext } return theirContext; } /** * Constructor * * Given a ComponentName, get the searchability info * and build a local copy of it. Use the factory, not this. * * @param activityContext runtime context for the activity that the searchable info is about. * @param attr The attribute set we found in the XML file, contains the values that are used to * construct the object. * @param cName The component name of the searchable activity * @throws IllegalArgumentException if the searchability info is invalid or insufficient */ private SearchableInfo(Context activityContext, AttributeSet attr, final ComponentName cName) { mSearchActivity = cName; TypedArray a = activityContext.obtainStyledAttributes(attr, com.android.internal.R.styleable.Searchable); mSearchMode = a.getInt(com.android.internal.R.styleable.Searchable_searchMode, 0); mLabelId = a.getResourceId(com.android.internal.R.styleable.Searchable_label, 0); mHintId = a.getResourceId(com.android.internal.R.styleable.Searchable_hint, 0); mIconId = a.getResourceId(com.android.internal.R.styleable.Searchable_icon, 0); mSearchButtonText = a.getResourceId( com.android.internal.R.styleable.Searchable_searchButtonText, 0); mSearchInputType = a.getInt(com.android.internal.R.styleable.Searchable_inputType, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL); mSearchImeOptions = a.getInt(com.android.internal.R.styleable.Searchable_imeOptions, EditorInfo.IME_ACTION_SEARCH); mIncludeInGlobalSearch = a.getBoolean( com.android.internal.R.styleable.Searchable_includeInGlobalSearch, false); mQueryAfterZeroResults = a.getBoolean( com.android.internal.R.styleable.Searchable_queryAfterZeroResults, false); mAutoUrlDetect = a.getBoolean( com.android.internal.R.styleable.Searchable_autoUrlDetect, false); mSettingsDescription = a.getString( com.android.internal.R.styleable.Searchable_searchSettingsDescription); mSuggestAuthority = a.getString( com.android.internal.R.styleable.Searchable_searchSuggestAuthority); mSuggestPath = a.getString( com.android.internal.R.styleable.Searchable_searchSuggestPath); mSuggestSelection = a.getString( com.android.internal.R.styleable.Searchable_searchSuggestSelection); mSuggestIntentAction = a.getString( com.android.internal.R.styleable.Searchable_searchSuggestIntentAction); mSuggestIntentData = a.getString( com.android.internal.R.styleable.Searchable_searchSuggestIntentData); mSuggestThreshold = a.getInt( com.android.internal.R.styleable.Searchable_searchSuggestThreshold, 0); mVoiceSearchMode = a.getInt(com.android.internal.R.styleable.Searchable_voiceSearchMode, 0); // TODO this didn't work - came back zero from YouTube mVoiceLanguageModeId = a.getResourceId(com.android.internal.R.styleable.Searchable_voiceLanguageModel, 0); mVoicePromptTextId = a.getResourceId(com.android.internal.R.styleable.Searchable_voicePromptText, 0); mVoiceLanguageId = a.getResourceId(com.android.internal.R.styleable.Searchable_voiceLanguage, 0); mVoiceMaxResults = a.getInt(com.android.internal.R.styleable.Searchable_voiceMaxResults, 0); a.recycle(); // get package info for suggestions provider (if any) String suggestProviderPackage = null; if (mSuggestAuthority != null) { PackageManager pm = activityContext.getPackageManager(); ProviderInfo pi = pm.resolveContentProvider(mSuggestAuthority, 0); if (pi != null) { suggestProviderPackage = pi.packageName; } } mSuggestProviderPackage = suggestProviderPackage; // for now, implement some form of rules - minimal data if (mLabelId == 0) { throw new IllegalArgumentException("Search label must be a resource reference."); } } /** * Private class used to hold the "action key" configuration */ public static class ActionKeyInfo implements Parcelable { private final int mKeyCode; private final String mQueryActionMsg; private final String mSuggestActionMsg; private final String mSuggestActionMsgColumn; /** * Create one object using attributeset as input data. * @param activityContext runtime context of the activity that the action key information * is about. * @param attr The attribute set we found in the XML file, contains the values that are used to * construct the object. * @throws IllegalArgumentException if the action key configuration is invalid */ public ActionKeyInfo(Context activityContext, AttributeSet attr) { TypedArray a = activityContext.obtainStyledAttributes(attr, com.android.internal.R.styleable.SearchableActionKey); mKeyCode = a.getInt( com.android.internal.R.styleable.SearchableActionKey_keycode, 0); mQueryActionMsg = a.getString( com.android.internal.R.styleable.SearchableActionKey_queryActionMsg); mSuggestActionMsg = a.getString( com.android.internal.R.styleable.SearchableActionKey_suggestActionMsg); mSuggestActionMsgColumn = a.getString( com.android.internal.R.styleable.SearchableActionKey_suggestActionMsgColumn); a.recycle(); // sanity check. if (mKeyCode == 0) { throw new IllegalArgumentException("No keycode."); } else if ((mQueryActionMsg == null) && (mSuggestActionMsg == null) && (mSuggestActionMsgColumn == null)) { throw new IllegalArgumentException("No message information."); } } /** * Instantiate a new ActionKeyInfo from the data in a Parcel that was * previously written with {@link #writeToParcel(Parcel, int)}. * * @param in The Parcel containing the previously written ActionKeyInfo, * positioned at the location in the buffer where it was written. */ public ActionKeyInfo(Parcel in) { mKeyCode = in.readInt(); mQueryActionMsg = in.readString(); mSuggestActionMsg = in.readString(); mSuggestActionMsgColumn = in.readString(); } public int getKeyCode() { return mKeyCode; } public String getQueryActionMsg() { return mQueryActionMsg; } public String getSuggestActionMsg() { return mSuggestActionMsg; } public String getSuggestActionMsgColumn() { return mSuggestActionMsgColumn; } public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { dest.writeInt(mKeyCode); dest.writeString(mQueryActionMsg); dest.writeString(mSuggestActionMsg); dest.writeString(mSuggestActionMsgColumn); } } /** * If any action keys were defined for this searchable activity, look up and return. * * @param keyCode The key that was pressed * @return Returns the ActionKeyInfo record, or null if none defined */ public ActionKeyInfo findActionKey(int keyCode) { if (mActionKeys == null) { return null; } return mActionKeys.get(keyCode); } private void addActionKey(ActionKeyInfo keyInfo) { if (mActionKeys == null) { mActionKeys = new HashMap<Integer,ActionKeyInfo>(); } mActionKeys.put(keyInfo.getKeyCode(), keyInfo); } /** * Gets search information for the given activity. * * @param context Context to use for reading activity resources. * @param activityInfo Activity to get search information from. * @return Search information about the given activity, or {@code null} if * the activity has no or invalid searchability meta-data. */ public static SearchableInfo getActivityMetaData(Context context, ActivityInfo activityInfo) { // for each component, try to find metadata XmlResourceParser xml = activityInfo.loadXmlMetaData(context.getPackageManager(), MD_LABEL_SEARCHABLE); if (xml == null) { return null; } ComponentName cName = new ComponentName(activityInfo.packageName, activityInfo.name); SearchableInfo searchable = getActivityMetaData(context, xml, cName); xml.close(); if (DBG) { if (searchable != null) { Log.d(LOG_TAG, "Checked " + activityInfo.name + ",label=" + searchable.getLabelId() + ",icon=" + searchable.getIconId() + ",suggestAuthority=" + searchable.getSuggestAuthority() + ",target=" + searchable.getSearchActivity().getClassName() + ",global=" + searchable.shouldIncludeInGlobalSearch() + ",settingsDescription=" + searchable.getSettingsDescription() + ",threshold=" + searchable.getSuggestThreshold()); } else { Log.d(LOG_TAG, "Checked " + activityInfo.name + ", no searchable meta-data"); } } return searchable; } /** * Get the metadata for a given activity * * @param context runtime context * @param xml XML parser for reading attributes * @param cName The component name of the searchable activity * * @result A completely constructed SearchableInfo, or null if insufficient XML data for it */ private static SearchableInfo getActivityMetaData(Context context, XmlPullParser xml, final ComponentName cName) { SearchableInfo result = null; Context activityContext = createActivityContext(context, cName); // in order to use the attributes mechanism, we have to walk the parser // forward through the file until it's reading the tag of interest. try { int tagType = xml.next(); while (tagType != XmlPullParser.END_DOCUMENT) { if (tagType == XmlPullParser.START_TAG) { if (xml.getName().equals(MD_XML_ELEMENT_SEARCHABLE)) { AttributeSet attr = Xml.asAttributeSet(xml); if (attr != null) { try { result = new SearchableInfo(activityContext, attr, cName); } catch (IllegalArgumentException ex) { Log.w(LOG_TAG, "Invalid searchable metadata for " + cName.flattenToShortString() + ": " + ex.getMessage()); return null; } } } else if (xml.getName().equals(MD_XML_ELEMENT_SEARCHABLE_ACTION_KEY)) { if (result == null) { // Can't process an embedded element if we haven't seen the enclosing return null; } AttributeSet attr = Xml.asAttributeSet(xml); if (attr != null) { try { result.addActionKey(new ActionKeyInfo(activityContext, attr)); } catch (IllegalArgumentException ex) { Log.w(LOG_TAG, "Invalid action key for " + cName.flattenToShortString() + ": " + ex.getMessage()); return null; } } } } tagType = xml.next(); } } catch (XmlPullParserException e) { Log.w(LOG_TAG, "Reading searchable metadata for " + cName.flattenToShortString(), e); return null; } catch (IOException e) { Log.w(LOG_TAG, "Reading searchable metadata for " + cName.flattenToShortString(), e); return null; } return result; } /** * Return the "label" (user-visible name) of this searchable context. This must be * accessed using the target (searchable) Activity's resources, not simply the context of the * caller. * * @return Returns the resource Id */ public int getLabelId() { return mLabelId; } /** * Return the resource Id of the hint text. This must be * accessed using the target (searchable) Activity's resources, not simply the context of the * caller. * * @return Returns the resource Id, or 0 if not specified by this package. */ public int getHintId() { return mHintId; } /** * Return the icon Id specified by the Searchable_icon meta-data entry. This must be * accessed using the target (searchable) Activity's resources, not simply the context of the * caller. * * @return Returns the resource id. */ public int getIconId() { return mIconId; } /** * @return true if android:voiceSearchMode="showVoiceSearchButton" */ public boolean getVoiceSearchEnabled() { return 0 != (mVoiceSearchMode & VOICE_SEARCH_SHOW_BUTTON); } /** * @return true if android:voiceSearchMode="launchWebSearch" */ public boolean getVoiceSearchLaunchWebSearch() { return 0 != (mVoiceSearchMode & VOICE_SEARCH_LAUNCH_WEB_SEARCH); } /** * @return true if android:voiceSearchMode="launchRecognizer" */ public boolean getVoiceSearchLaunchRecognizer() { return 0 != (mVoiceSearchMode & VOICE_SEARCH_LAUNCH_RECOGNIZER); } /** * @return the resource Id of the language model string, if specified in the searchable * activity's metadata, or 0 if not specified. */ public int getVoiceLanguageModeId() { return mVoiceLanguageModeId; } /** * @return the resource Id of the voice prompt text string, if specified in the searchable * activity's metadata, or 0 if not specified. */ public int getVoicePromptTextId() { return mVoicePromptTextId; } /** * @return the resource Id of the spoken langauge, if specified in the searchable * activity's metadata, or 0 if not specified. */ public int getVoiceLanguageId() { return mVoiceLanguageId; } /** * @return the max results count, if specified in the searchable * activity's metadata, or 0 if not specified. */ public int getVoiceMaxResults() { return mVoiceMaxResults; } /** * Return the resource Id of replacement text for the "Search" button. * * @return Returns the resource Id, or 0 if not specified by this package. */ public int getSearchButtonText() { return mSearchButtonText; } /** * Return the input type as specified in the searchable attributes. This will default to * InputType.TYPE_CLASS_TEXT if not specified (which is appropriate for free text input). * * @return the input type */ public int getInputType() { return mSearchInputType; } /** * Return the input method options specified in the searchable attributes. * This will default to EditorInfo.ACTION_SEARCH if not specified (which is * appropriate for a search box). * * @return the input type */ public int getImeOptions() { return mSearchImeOptions; } /** * Checks whether the searchable is exported. * * @return The value of the <code>exported</code> attribute, * or <code>false</code> if the attribute is not set. */ public boolean shouldIncludeInGlobalSearch() { return mIncludeInGlobalSearch; } /** * Checks whether this searchable activity should be invoked after a query returned zero * results. * * @return The value of the <code>queryAfterZeroResults</code> attribute, * or <code>false</code> if the attribute is not set. */ public boolean queryAfterZeroResults() { return mQueryAfterZeroResults; } /** * Checks whether this searchable activity has auto URL detect turned on. * * @return The value of the <code>autoUrlDetect</code> attribute, * or <code>false</code> if the attribute is not set. */ public boolean autoUrlDetect() { return mAutoUrlDetect; } /** * Support for parcelable and aidl operations. */ public static final Parcelable.Creator<SearchableInfo> CREATOR = new Parcelable.Creator<SearchableInfo>() { public SearchableInfo createFromParcel(Parcel in) { return new SearchableInfo(in); } public SearchableInfo[] newArray(int size) { return new SearchableInfo[size]; } }; /** * Instantiate a new SearchableInfo from the data in a Parcel that was * previously written with {@link #writeToParcel(Parcel, int)}. * * @param in The Parcel containing the previously written SearchableInfo, * positioned at the location in the buffer where it was written. */ public SearchableInfo(Parcel in) { mLabelId = in.readInt(); mSearchActivity = ComponentName.readFromParcel(in); mHintId = in.readInt(); mSearchMode = in.readInt(); mIconId = in.readInt(); mSearchButtonText = in.readInt(); mSearchInputType = in.readInt(); mSearchImeOptions = in.readInt(); mIncludeInGlobalSearch = in.readInt() != 0; mQueryAfterZeroResults = in.readInt() != 0; mAutoUrlDetect = in.readInt() != 0; mSettingsDescription = in.readString(); mSuggestAuthority = in.readString(); mSuggestPath = in.readString(); mSuggestSelection = in.readString(); mSuggestIntentAction = in.readString(); mSuggestIntentData = in.readString(); mSuggestThreshold = in.readInt(); for (int count = in.readInt(); count > 0; count--) { addActionKey(new ActionKeyInfo(in)); } mSuggestProviderPackage = in.readString(); mVoiceSearchMode = in.readInt(); mVoiceLanguageModeId = in.readInt(); mVoicePromptTextId = in.readInt(); mVoiceLanguageId = in.readInt(); mVoiceMaxResults = in.readInt(); } public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { dest.writeInt(mLabelId); mSearchActivity.writeToParcel(dest, flags); dest.writeInt(mHintId); dest.writeInt(mSearchMode); dest.writeInt(mIconId); dest.writeInt(mSearchButtonText); dest.writeInt(mSearchInputType); dest.writeInt(mSearchImeOptions); dest.writeInt(mIncludeInGlobalSearch ? 1 : 0); dest.writeInt(mQueryAfterZeroResults ? 1 : 0); dest.writeInt(mAutoUrlDetect ? 1 : 0); dest.writeString(mSettingsDescription); dest.writeString(mSuggestAuthority); dest.writeString(mSuggestPath); dest.writeString(mSuggestSelection); dest.writeString(mSuggestIntentAction); dest.writeString(mSuggestIntentData); dest.writeInt(mSuggestThreshold); if (mActionKeys == null) { dest.writeInt(0); } else { dest.writeInt(mActionKeys.size()); for (ActionKeyInfo actionKey : mActionKeys.values()) { actionKey.writeToParcel(dest, flags); } } dest.writeString(mSuggestProviderPackage); dest.writeInt(mVoiceSearchMode); dest.writeInt(mVoiceLanguageModeId); dest.writeInt(mVoicePromptTextId); dest.writeInt(mVoiceLanguageId); dest.writeInt(mVoiceMaxResults); } }
false
false
null
null
diff --git a/OsmAnd/src/net/osmand/plus/voice/TTSCommandPlayerImpl.java b/OsmAnd/src/net/osmand/plus/voice/TTSCommandPlayerImpl.java index 5ffc2850..29c8246c 100644 --- a/OsmAnd/src/net/osmand/plus/voice/TTSCommandPlayerImpl.java +++ b/OsmAnd/src/net/osmand/plus/voice/TTSCommandPlayerImpl.java @@ -1,175 +1,178 @@ package net.osmand.plus.voice; import java.io.File; import java.util.List; import java.util.Locale; import net.osmand.Algoritms; import net.osmand.plus.R; import net.osmand.plus.activities.SettingsActivity; import alice.tuprolog.Struct; import alice.tuprolog.Term; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnInitListener; public class TTSCommandPlayerImpl extends AbstractPrologCommandPlayer { private final class IntentStarter implements DialogInterface.OnClickListener { private final Activity ctx; private final String intentAction; private final Uri intentData; private IntentStarter(Activity ctx, String intentAction) { this(ctx,intentAction, null); } private IntentStarter(Activity ctx, String intentAction, Uri intentData) { this.ctx = ctx; this.intentAction = intentAction; this.intentData = intentData; } @Override public void onClick(DialogInterface dialog, int which) { Intent installIntent = new Intent(); installIntent.setAction(intentAction); if (intentData != null) { installIntent.setData(intentData); } ctx.startActivity(installIntent); } } private static final String CONFIG_FILE = "_ttsconfig.p"; private static final int TTS_VOICE_VERSION = 100; private TextToSpeech mTts; private Context mTtsContext; private String language; protected TTSCommandPlayerImpl(Activity ctx, String voiceProvider) throws CommandPlayerException { super(ctx, voiceProvider, CONFIG_FILE, TTS_VOICE_VERSION); final Term langVal = solveSimplePredicate("language"); if (langVal instanceof Struct) { language = ((Struct) langVal).getName(); } if (Algoritms.isEmpty(language)) { throw new CommandPlayerException( ctx.getString(R.string.voice_data_corrupted)); } onActivityInit(ctx); } @Override public void playCommands(CommandBuilder builder) { if (mTts != null) { final List<String> execute = builder.execute(); //list of strings, the speech text, play it StringBuilder bld = new StringBuilder(); for (String s : execute) { bld.append(s).append(' '); } mTts.speak(bld.toString(), TextToSpeech.QUEUE_ADD, null); } } @Override public void onActivityInit(final Activity ctx) { if (mTts != null && mTtsContext != ctx) { //clear only, if the mTts was initialized in another context. //Unfortunately, for example from settings to map first the map is initialized than //the settingsactivity is destroyed... internalClear(); } if (mTts == null) { mTtsContext = ctx; mTts = new TextToSpeech(ctx, new OnInitListener() { @Override public void onInit(int status) { if (status != TextToSpeech.SUCCESS) { internalClear(); } else { switch (mTts.isLanguageAvailable(new Locale(language))) { case TextToSpeech.LANG_MISSING_DATA: - internalClear(); - Builder builder = createAlertDialog( - R.string.tts_missing_language_data_title, - R.string.tts_missing_language_data, - new IntentStarter( - ctx, - TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA), - ctx); - builder.show(); + if (isSettingsActivity(ctx)) { + Builder builder = createAlertDialog( + R.string.tts_missing_language_data_title, + R.string.tts_missing_language_data, + new IntentStarter( + ctx, + TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA), + ctx); + builder.show(); + } break; case TextToSpeech.LANG_AVAILABLE: mTts.setLanguage(new Locale(language)); break; case TextToSpeech.LANG_NOT_SUPPORTED: //maybe weird, but I didn't want to introduce parameter in around 5 methods just to do //this if condition - if (ctx instanceof SettingsActivity) { - builder = createAlertDialog( + if (isSettingsActivity(ctx)) { + Builder builder = createAlertDialog( R.string.tts_language_not_supported_title, R.string.tts_language_not_supported, new IntentStarter( ctx, Intent.ACTION_VIEW, Uri.parse("market://search?q=text to speech engine" )), ctx); builder.show(); } break; } } } - + private boolean isSettingsActivity(final Activity ctx) { + return ctx instanceof SettingsActivity; + } }); } } private Builder createAlertDialog(int titleResID, int messageResID, IntentStarter intentStarter, final Activity ctx) { Builder builder = new AlertDialog.Builder(ctx); builder.setCancelable(true); builder.setNegativeButton(R.string.default_buttons_no, null); builder.setPositiveButton(R.string.default_buttons_yes, intentStarter); builder.setTitle(titleResID); builder.setMessage(messageResID); return builder; } @Override public void onActvitiyStop(Context ctx) { //stop only when the context is the same if (mTtsContext == ctx) { internalClear(); } } private void internalClear() { if (mTts != null) { mTts.shutdown(); mTtsContext = null; mTts = null; } } @Override public void clear() { super.clear(); internalClear(); } public static boolean isMyData(File voiceDir) throws CommandPlayerException { return new File(voiceDir, CONFIG_FILE).exists(); } }
false
false
null
null
diff --git a/elastic-runtime2/src/main/java/com/vmware/vhadoop/vhm/ClusterMapImpl.java b/elastic-runtime2/src/main/java/com/vmware/vhadoop/vhm/ClusterMapImpl.java index 773317c..f670573 100644 --- a/elastic-runtime2/src/main/java/com/vmware/vhadoop/vhm/ClusterMapImpl.java +++ b/elastic-runtime2/src/main/java/com/vmware/vhadoop/vhm/ClusterMapImpl.java @@ -1,833 +1,840 @@ /*************************************************************************** * Copyright (c) 2013 VMware, Inc. 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.vmware.vhadoop.vhm; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.vmware.vhadoop.api.vhm.ClusterMap; import com.vmware.vhadoop.api.vhm.HadoopActions.HadoopClusterInfo; import com.vmware.vhadoop.api.vhm.events.ClusterScaleCompletionEvent; import com.vmware.vhadoop.api.vhm.events.ClusterScaleEvent; import com.vmware.vhadoop.api.vhm.events.ClusterStateChangeEvent; import com.vmware.vhadoop.api.vhm.events.ClusterStateChangeEvent.SerengetiClusterConstantData; import com.vmware.vhadoop.api.vhm.events.ClusterStateChangeEvent.SerengetiClusterVariableData; import com.vmware.vhadoop.api.vhm.events.ClusterStateChangeEvent.VMConstantData; import com.vmware.vhadoop.api.vhm.events.ClusterStateChangeEvent.VMVariableData; import com.vmware.vhadoop.api.vhm.events.ClusterStateChangeEvent.VmType; import com.vmware.vhadoop.api.vhm.strategy.ScaleStrategy; import com.vmware.vhadoop.util.VhmLevel; import com.vmware.vhadoop.vhm.events.ClusterUpdateEvent; import com.vmware.vhadoop.vhm.events.MasterVmUpdateEvent; import com.vmware.vhadoop.vhm.events.NewMasterVMEvent; import com.vmware.vhadoop.vhm.events.NewVmEvent; import com.vmware.vhadoop.vhm.events.VmRemovedFromClusterEvent; import com.vmware.vhadoop.vhm.events.VmUpdateEvent; /* Note that this class allows multiple readers and a single writer * All of the methods in ClusterMap can be accessed by multiple threads, but should only ever read and are idempotent * The writer of ClusterMap will block until the readers have finished reading and will block new readers until it has finished updating * VHM controls the multi-threaded access to ClusterMap through ClusterMapAccess. * There should be no need for synchronization in this class provided this model is adhered to */ public class ClusterMapImpl implements ClusterMap { private static final Logger _log = Logger.getLogger(ClusterMap.class.getName()); private final Map<String, ClusterInfo> _clusters = new HashMap<String, ClusterInfo>(); private final Map<String, VMInfo> _vms = new HashMap<String, VMInfo>(); private final Map<String, ScaleStrategy> _scaleStrategies = new HashMap<String, ScaleStrategy>(); private final ExtraInfoToClusterMapper _extraInfoMapper; // private final Random _random = new Random(); /* Uncomment to do random failure testing */ // private final int FAILURE_FACTOR = 20; ClusterMapImpl(ExtraInfoToClusterMapper mapper) { _extraInfoMapper = mapper; } private class VMInfo { final String _moRef; final VMConstantData _constantData; final VMVariableData _variableData; final String _clusterId; /* VMInfo is created with a completed VMConstantData and a potentially incomplete or even null variableData * moRef and clusterId must not be null */ VMInfo(String moRef, VMConstantData constantData, VMVariableData variableData, String clusterId) { _moRef = moRef; _constantData = constantData; /* Provide an empty variableData if a null one is passed in */ _variableData = (variableData != null) ? variableData : new VMVariableData(); _clusterId = clusterId; - if ((_variableData._powerState != null) && (_variableData._powerState)) { - _powerOnTime = System.currentTimeMillis(); - } + if (_variableData._powerState != null) { + if (_variableData._powerState) { + _powerOnTime = System.currentTimeMillis(); + } else { + _variableData._dnsName = null; /* VC may give us stale values for a powered-off VM on init */ + _variableData._ipAddr = null; + } + } + _log.log(Level.FINE, "Creating new VMInfo <%%V%s%%V>(%s) for cluster <%%C%s%%C>. %s. %s", new String[]{moRef, moRef, clusterId, _constantData.toString(), _variableData.toString()}); } long _powerOnTime; // most recent timestamp when VHM learned VM is on } class ClusterInfo { final String _masterUUID; final SerengetiClusterConstantData _constantData; public ClusterInfo(String clusterId, SerengetiClusterConstantData constantData) { this._masterUUID = clusterId; this._constantData = constantData; _completionEvents = new LinkedList<ClusterScaleCompletionEvent>(); _log.log(Level.FINE, "Creating new ClusterInfo <%%C%s%%C>(%s). %s", new String[]{clusterId, clusterId, constantData.toString()}); } Integer _jobTrackerPort; String _discoveredFolderName; /* Note this field is only set by SerengetiLimitEvents */ String _scaleStrategyKey; LinkedList<ClusterScaleCompletionEvent> _completionEvents; Long _incompleteSince; Map<String, String> _extraInfo; } private boolean assertHasData(Set<? extends Object> toTest) { return (toTest != null && (toTest.size() > 0)); } private boolean assertHasData(Map<? extends Object, ? extends Object> toTest) { return (toTest != null && (toTest.keySet().size() > 0)); } private boolean assertHasData(String data) { return ((data != null) && !data.trim().isEmpty()); } private ClusterInfo getCluster(String clusterId) { return _clusters.get(clusterId); } private boolean createCluster(String clusterId, SerengetiClusterConstantData constantData) { if (getCluster(clusterId) != null) { return false; } if ((clusterId != null) && (constantData != null)) { ClusterInfo cluster = new ClusterInfo(clusterId, constantData); _log.log(VhmLevel.USER, "<%C"+clusterId+"%C>: recording existence of cluster"); _clusters.put(clusterId, cluster); } return true; } private String removeVM(String vmMoRef) { VMInfo vmInfo = _vms.get(vmMoRef); String clusterId = null; if (vmInfo != null) { clusterId = vmInfo._clusterId; if (vmInfo._constantData._vmType.equals(VmType.MASTER)) { _log.log(VhmLevel.USER, "<%C"+clusterId+"%C>: removing record of cluster"); _clusters.remove(clusterId); } _log.log(VhmLevel.USER, "<%C"+clusterId+"%C>: removing record of VM <%V"+vmMoRef+"%V>"); _vms.remove(vmMoRef); } dumpState(Level.FINEST); return clusterId; } /* Returns clusterId of the cluster affected or null if no update occurred (possibly an error) */ /* May also return any implied scale events of the cluster state change */ public String handleClusterEvent(ClusterStateChangeEvent event, Set<ClusterScaleEvent> impliedScaleEventsResultSet) { String clusterId = null; if (event instanceof NewVmEvent) { return addNewVM((NewVmEvent)event, impliedScaleEventsResultSet); } else if (event instanceof VmUpdateEvent) { return updateVMState((VmUpdateEvent)event, impliedScaleEventsResultSet); } else if (event instanceof ClusterUpdateEvent) { return updateClusterState((ClusterUpdateEvent)event, impliedScaleEventsResultSet, false); } else if (event instanceof VmRemovedFromClusterEvent) { return removeVMFromCluster((VmRemovedFromClusterEvent)event); } return clusterId; } private String addNewVM(NewVmEvent event, Set<ClusterScaleEvent> impliedScaleEventsResultSet) { VMConstantData constantData = event.getConstantData(); if (constantData == null) { _log.severe("VHM: the data expected to be associated with a discovered or new VM is missing"); return null; } VMVariableData variableData = event.getVariableData(); /* Can be null */ String vmId = event.getVmId(); String clusterId = event.getClusterId(); if (clusterId == null) { _log.severe("VHM: the cluster id associated with a discovered or new VM must not be null"); return null; } if (event instanceof NewMasterVMEvent) { SerengetiClusterConstantData clusterConstantData = ((NewMasterVMEvent)event).getClusterConstantData(); /* Should not be null */ SerengetiClusterVariableData clusterVariableData = ((NewMasterVMEvent)event).getClusterVariableData(); /* Should not be null */ if (!createCluster(clusterId, clusterConstantData)) { _log.severe("<%C"+clusterId+"%C>: cluster already exists in cluster map"); return null; } updateClusterVariableData(clusterId, clusterVariableData, impliedScaleEventsResultSet, true); } VMInfo vi = createNewVM(vmId, constantData, variableData, clusterId); if (vi == null) { _log.severe("<%C"+clusterId+"%C>: <%V:"+vmId+"%V> - already known VM added a second time as a newly discovered VM"); return null; } _log.log(VhmLevel.USER, "<%C"+clusterId+"%C>: adding record for VM <%V"+vmId+"%V>"); return clusterId; } private VMInfo createNewVM(String vmId, VMConstantData constantData, VMVariableData variableData, String clusterId) { if (_vms.get(vmId) != null) { return null; } VMInfo vi = new VMInfo(vmId, constantData, variableData, clusterId); _vms.put(vmId, vi); return vi; } private String updateVMState(VmUpdateEvent event, Set<ClusterScaleEvent> impliedScaleEventsResultSet) { VMVariableData variableData = event.getVariableData(); if (event instanceof MasterVmUpdateEvent) { String clusterId = getClusterIdForVm(event.getVmId()); updateClusterVariableData(clusterId, ((MasterVmUpdateEvent)event).getClusterVariableData(), impliedScaleEventsResultSet, false); } return updateVMVariableData(event.getVmId(), variableData); } private boolean testForUpdate(Object toSet, Object newValue, String id, String fieldName, String prefix, String postfix) { if ((newValue != null) && ((toSet == null) || !toSet.equals(newValue))) { _log.log(Level.FINE, "Updating %s for %s%s%s to %s", new Object[]{fieldName, prefix, id, postfix, newValue}); return true; } return false; } private boolean testForVMUpdate(Object toSet, Object newValue, String vmId, String fieldName) { return testForUpdate(toSet, newValue, vmId, fieldName, "<%V", "%V>"); } private boolean testForClusterUpdate(Object toSet, Object newValue, String clusterId, String fieldName) { return testForUpdate(toSet, newValue, clusterId, fieldName, "<%C", "%C>"); } private String updateVMVariableData(String vmId, VMVariableData variableData) { VMInfo vi = _vms.get(vmId); String clusterId = null; if (vi != null) { String dnsName = variableData._dnsName; String hostMoRef = variableData._hostMoRef; String ipAddr = variableData._ipAddr; String myName = variableData._myName; Boolean powerState = variableData._powerState; Integer vCPUs = variableData._vCPUs; VMVariableData toSet = vi._variableData; - if (testForVMUpdate(toSet._dnsName, dnsName, vmId, "dnsName")) { - toSet._dnsName = dnsName; - } if (testForVMUpdate(toSet._hostMoRef, hostMoRef, vmId, "hostMoRef")) { toSet._hostMoRef = hostMoRef; } - if (testForVMUpdate(toSet._ipAddr, ipAddr, vmId, "ipAddr")) { - toSet._ipAddr = ipAddr; - } if (testForVMUpdate(toSet._myName, myName, vmId, "myName")) { toSet._myName = myName; - } + } if (testForVMUpdate(toSet._powerState, powerState, vmId, "powerState")) { toSet._powerState = powerState; if (powerState) { vi._powerOnTime = System.currentTimeMillis(); } else { - vi._variableData._dnsName = null; /* Not safe to cache - it might change */ - vi._variableData._ipAddr = null; /* Not safe to cache - it might change */ vi._powerOnTime = 0; } if (vi._clusterId != null) { _log.log(VhmLevel.USER, "<%C"+vi._clusterId+"%C>: VM <%V"+vmId+"%V> - powered "+(powerState?"on":"off")); } else { _log.log(VhmLevel.USER, "VM <%V"+vmId+"%V>: powered "+(powerState?"on":"off")); } - } + } + if ((toSet._powerState != null) && (!toSet._powerState)) { + dnsName = ipAddr = ""; /* Any time we know the VM is powered off, remove stale values */ + } + if (testForVMUpdate(toSet._dnsName, dnsName, vmId, "dnsName")) { + toSet._dnsName = dnsName; + } + if (testForVMUpdate(toSet._ipAddr, ipAddr, vmId, "ipAddr")) { + toSet._ipAddr = ipAddr; + } if (testForVMUpdate(toSet._vCPUs, vCPUs, vmId, "vCPUs")) { toSet._vCPUs = vCPUs; } if (vi._clusterId != null) { clusterId = vi._clusterId; } } return clusterId; } /* Note that in most cases, the information in variableData will represent deltas - real changes to state. * However, this may not always be the case, so this should not be assumed - note testForUpdate methods */ private void updateClusterVariableData(String clusterId, SerengetiClusterVariableData variableData, Set<ClusterScaleEvent> impliedScaleEventsResultSet, boolean isNewVm) { boolean variableDataChanged = false; ClusterInfo ci = getCluster(clusterId); if (ci != null) { Boolean enableAutomation = variableData._enableAutomation; Integer jobTrackerPort = variableData._jobTrackerPort; if (enableAutomation != null) { String scaleStrategyKey = _extraInfoMapper.getStrategyKey(variableData, clusterId); if (testForClusterUpdate(ci._scaleStrategyKey, scaleStrategyKey, clusterId, "scaleStrategyKey")) { _log.log(VhmLevel.USER, "<%C"+clusterId+"%C>: cluster scale strategy set to "+scaleStrategyKey); ci._scaleStrategyKey = scaleStrategyKey; variableDataChanged = true; } } if (testForClusterUpdate(ci._jobTrackerPort, jobTrackerPort, clusterId, "jobTrackerPort")) { ci._jobTrackerPort = jobTrackerPort; variableDataChanged = true; } if (ci._extraInfo == null) { ci._extraInfo = _extraInfoMapper.parseExtraInfo(variableData, clusterId); if (ci._extraInfo != null) { _log.fine("Setting extraInfo in <%C"+clusterId+"%C> to "+ci._extraInfo); variableDataChanged = true; } } else { Map<String, String> toAdd = _extraInfoMapper.parseExtraInfo(variableData, clusterId); if (toAdd != null) { if (toAdd != null) { for (String key : toAdd.keySet()) { String newValue = toAdd.get(key); String origValue = ci._extraInfo.get(key); if (testForClusterUpdate(origValue, newValue, clusterId, "extraInfo."+key)) { ci._extraInfo.put(key, newValue); variableDataChanged = true; } } } } } /* Don't try to generate implied events for existing clusters that are not viable */ if (variableDataChanged) { Set<ClusterScaleEvent> impliedScaleEvents = _extraInfoMapper.getImpliedScaleEventsForUpdate(variableData, clusterId, isNewVm, isClusterViable(clusterId)); if ((impliedScaleEvents != null) && (impliedScaleEventsResultSet != null)) { impliedScaleEventsResultSet.addAll(impliedScaleEvents); } } } } /* If the JobTracker is powered off, we may consider the cluster complete, but the cluster is obviously not viable */ private boolean isClusterViable(String clusterId) { if (assertHasData(_clusters) && assertHasData(_vms)) { Boolean clusterComplete = validateClusterCompleteness(clusterId, 0); if ((clusterComplete == null) || !clusterComplete) { return false; } ClusterInfo ci = _clusters.get(clusterId); if (ci != null) { VMInfo vi = getMasterVmForCluster(clusterId); if ((vi == null) || !vi._variableData._powerState) { return false; } } return true; } return false; } private VMInfo getMasterVmForCluster(String clusterId) { for (VMInfo vmInfo : _vms.values()) { if (vmInfo._constantData._vmType.equals(VmType.MASTER) && vmInfo._clusterId.equals(clusterId)) { return vmInfo; } } return null; } private String updateClusterState(ClusterUpdateEvent event, Set<ClusterScaleEvent> impliedScaleEventsResultSet, boolean isNewVm) { SerengetiClusterVariableData variableData = event.getClusterVariableData(); String clusterId = getClusterIdForVm(event.getVmId()); updateClusterVariableData(clusterId, variableData, impliedScaleEventsResultSet, isNewVm); return clusterId; } private String removeVMFromCluster(VmRemovedFromClusterEvent event) { return removeVM(event.getVmId()); } public void handleCompletionEvent(ClusterScaleCompletionEvent event) { ClusterInfo cluster = getCluster(event.getClusterId()); if (cluster != null) { Set<String> enableVMs = event.getVMsForDecision(ClusterScaleCompletionEvent.ENABLE); Set<String> disableVMs = event.getVMsForDecision(ClusterScaleCompletionEvent.DISABLE); if (enableVMs != null) { _log.log(VhmLevel.USER, "<%C"+event.getClusterId()+"%C>: expansion completed"); } if (disableVMs != null) { _log.log(VhmLevel.USER, "<%C"+event.getClusterId()+"%C>: shrinking completed"); } cluster._completionEvents.addFirst(event); } } @Override /* Return null if a cluster is not viable as there's no scaling we can do with it */ public String getScaleStrategyKey(String clusterId) { //if ((_random != null) && ((_random.nextInt() % FAILURE_FACTOR) == 0)) {return null;} ClusterInfo ci = getCluster(clusterId); if ((ci != null) && isClusterViable(clusterId)) { return ci._scaleStrategyKey; } return null; } protected ScaleStrategy getScaleStrategyForCluster(String clusterId) { String key = getScaleStrategyKey(clusterId); if (key != null) { return _scaleStrategies.get(getScaleStrategyKey(clusterId)); } return null; } protected void registerScaleStrategy(ScaleStrategy strategy) { _scaleStrategies.put(strategy.getKey(), strategy); } @Override public Set<String> listComputeVMsForClusterHostAndPowerState(String clusterId, String hostId, boolean powerState) { //if ((_random != null) && ((_random.nextInt() % FAILURE_FACTOR) == 0)) {return null;} if ((clusterId != null) && (hostId != null)) { return generateComputeVMList(clusterId, hostId, powerState); } return null; } private Set<String> generateComputeVMList(final String clusterId, String hostId, Boolean powerState) { Set<String> result = new HashSet<String>(); for (VMInfo vminfo : _vms.values()) { try { boolean hostTest = (hostId == null) ? true : (hostId.equals(vminfo._variableData._hostMoRef)); boolean clusterTest = (clusterId == null) ? true : (vminfo._clusterId.equals(clusterId)); boolean powerStateTest = (powerState == null) ? true : (vminfo._variableData._powerState == powerState); _log.finest("Testing "+vminfo._variableData._myName+" h="+hostTest+", c="+clusterTest+", p="+powerStateTest); if ((vminfo._constantData._vmType.equals(VmType.COMPUTE)) && hostTest && clusterTest && powerStateTest) { result.add(vminfo._moRef); } } catch (NullPointerException e) { /* vmInfo._constantData should never be null or have null values. * vmInfo._clusterId and vmInfo._moRef should never be null * vmInfo._variableData should never be null, but may have null values */ VMVariableData variableInfo = vminfo._variableData; VMConstantData constantInfo = vminfo._constantData; _log.fine("Null pointer checking for matching vm (name: "+variableInfo._myName+ ", uuid: "+constantInfo._myUUID+ ", vmType: "+constantInfo._vmType+ ", host: "+variableInfo._hostMoRef+ ". powerState: "+variableInfo._powerState+ ", cluster: <%C"+vminfo._clusterId+ "%C>, moRef: "+vminfo._moRef+")"); } } return (result.size() == 0) ? null : result; } @Override public Set<String> listComputeVMsForClusterAndPowerState(String clusterId, boolean powerState) { //if ((_random != null) && ((_random.nextInt() % FAILURE_FACTOR) == 0)) {return null;} if (clusterId != null) { return generateComputeVMList(clusterId, null, powerState); } return null; } @Override public Set<String> listComputeVMsForPowerState(boolean powerState) { //if ((_random != null) && ((_random.nextInt() % FAILURE_FACTOR) == 0)) {return null;} return generateComputeVMList(null, null, powerState); } @Override public Set<String> listComputeVMsForCluster(String clusterId) { //if ((_random != null) && ((_random.nextInt() % FAILURE_FACTOR) == 0)) {return null;} return generateComputeVMList(clusterId, null, null); } @Override public Set<String> listHostsWithComputeVMsForCluster(String clusterId) { //if ((_random != null) && ((_random.nextInt() % FAILURE_FACTOR) == 0)) {return null;} if (assertHasData(_vms)) { Set<String> result = new HashSet<String>(); for (VMInfo vminfo : _vms.values()) { if ((vminfo._constantData._vmType.equals(VmType.COMPUTE)) && vminfo._clusterId.equals(clusterId)) { String hostMoRef = vminfo._variableData._hostMoRef; if (assertHasData(hostMoRef)) { result.add(hostMoRef); } } } return (result.size() == 0) ? null : result; } return null; } public void dumpState(Level logLevel) { for (ClusterInfo ci : _clusters.values()) { _log.log(logLevel, "<%C"+ci._masterUUID+"%C>: strategy=" + ci._scaleStrategyKey + " extraInfoMap= "+ ci._extraInfo + " uuid= " + ci._masterUUID + " jobTrackerPort= "+ci._jobTrackerPort); } for (VMInfo vmInfo : _vms.values()) { VMVariableData variableData = vmInfo._variableData; String powerState = variableData._powerState ? " ON" : " OFF"; String vCPUs = " vCPUs=" + ((variableData._vCPUs == null) ? "N/A" : variableData._vCPUs); String host = (variableData._hostMoRef == null) ? "N/A" : variableData._hostMoRef; String masterUUID = (vmInfo._clusterId == null) ? "N/A" : vmInfo._clusterId; String role = vmInfo._constantData._vmType.name(); String ipAddr = (variableData._ipAddr == null) ? "N/A" : variableData._ipAddr; String dnsName = (variableData._dnsName == null) ? "N/A" : variableData._dnsName; String jtPort = ""; _log.log(logLevel, "<%C"+masterUUID+"%C>: <%V"+vmInfo._moRef+"%V> - vm state: " + role + powerState + vCPUs + " host=" + host + " IP=" + ipAddr + "(" + dnsName + ")" + jtPort); } } void associateFolderWithCluster(String clusterId, String folderName) { ClusterInfo ci = getCluster(clusterId); if (ci != null) { ci._discoveredFolderName = folderName; } } String getClusterIdFromVMs(List<String> vms) { String clusterId = null; if (vms != null) { for (String moRef : vms) { try { clusterId = _vms.get(moRef)._clusterId; break; } catch (NullPointerException e) {} } } return clusterId; } /* Returns true, false or null * - True == is complete * - False == is not complete, but has become incomplete since graceTimeMillis * - Null == is not complete and has been not complete for longer than graceTimeMillis - cluster is possibly broken or invalid * - == clusterId not found * If graceTimeMillis == 0 this implies infinite time */ Boolean validateClusterCompleteness(String clusterId, long graceTimeMillis) { boolean isComplete = true; Boolean result = null; ClusterInfo ci = getCluster(clusterId); if (ci == null) { return null; } if ((ci._jobTrackerPort == null) || (ci._masterUUID == null) || (ci._scaleStrategyKey == null)) { isComplete = false; } if (isComplete) { Set<String> computeVMs = listComputeVMsForCluster(clusterId); isComplete = ((computeVMs != null) && (computeVMs.size() > 0)); } if (isComplete) { if (ci._incompleteSince != null) { ci._incompleteSince = null; } result = true; } else { long currentTime = System.currentTimeMillis(); if (ci._incompleteSince == null) { ci._incompleteSince = currentTime; result = false; } else if ((ci._incompleteSince > (currentTime - graceTimeMillis) || (graceTimeMillis == 0))) { result = false; } } return result; } @Override public String getClusterIdForFolder(String clusterFolderName) { //if ((_random != null) && ((_random.nextInt() % FAILURE_FACTOR) == 0)) {return null;} if (assertHasData(_clusters)) { for (ClusterInfo ci : _clusters.values()) { String constantFolder = ci._constantData._serengetiFolder; /* Set when cluster is created by Serengeti */ String discoveredFolder = ci._discoveredFolderName; /* Discovered from SerengetiLimitInstruction */ if (((constantFolder != null) && (constantFolder.equals(clusterFolderName))) || ((discoveredFolder != null) && (discoveredFolder.equals(clusterFolderName)))) { return ci._masterUUID; } } } return null; } @Override public String getHostIdForVm(String vmId) { //if ((_random != null) && ((_random.nextInt() % FAILURE_FACTOR) == 0)) {return null;} if (assertHasData(_vms)) { VMInfo vmInfo = _vms.get(vmId); if (vmInfo != null) { return vmInfo._variableData._hostMoRef; } } return null; } @Override public String getClusterIdForVm(String vmId) { //if ((_random != null) && ((_random.nextInt() % FAILURE_FACTOR) == 0)) {return null;} if (assertHasData(_vms)) { VMInfo vmInfo = _vms.get(vmId); if (vmInfo != null) { return vmInfo._clusterId; } } return null; } @Override public ClusterScaleCompletionEvent getLastClusterScaleCompletionEvent(String clusterId) { //if ((_random != null) && ((_random.nextInt() % FAILURE_FACTOR) == 0)) {return null;} if (assertHasData(_clusters)) { ClusterInfo info = getCluster(clusterId); if (info != null) { if (info._completionEvents.size() > 0) { return info._completionEvents.getFirst(); } } } return null; } @Override public Boolean checkPowerStateOfVms(Set<String> vmIds, boolean expectedPowerState) { //if ((_random != null) && ((_random.nextInt() % FAILURE_FACTOR) == 0)) {return null;} if (assertHasData(vmIds) && assertHasData(_vms)) { for (String vmId : vmIds) { Boolean result = checkPowerStateOfVm(vmId, expectedPowerState); if ((result == null) || (result == false)) { return result; } } return true; } return null; } @Override public Boolean checkPowerStateOfVm(String vmId, boolean expectedPowerState) { //if ((_random != null) && ((_random.nextInt() % FAILURE_FACTOR) == 0)) {return null;} if (assertHasData(_vms)) { VMInfo vm = _vms.get(vmId); if (vm != null) { if (vm._variableData._powerState == null) { return null; } return vm._variableData._powerState == expectedPowerState; } else { _log.warning("VHM: <%V"+vmId+"%V> - vm does not exist in cluster map"); return null; } } return null; } @Override public Map<String, String> getHostIdsForVMs(Set<String> vmIds) { //if ((_random != null) && ((_random.nextInt() % FAILURE_FACTOR) == 0)) {return null;} if (assertHasData(vmIds) && assertHasData(_vms)) { Map<String, String> results = new HashMap<String, String>(); for (String vmId : vmIds) { VMInfo vminfo = _vms.get(vmId); if ((vminfo != null) && assertHasData(vminfo._variableData._hostMoRef)) { results.put(vmId, vminfo._variableData._hostMoRef); } } if (results.size() > 0) { return results; } } return null; } @Override public String[] getAllKnownClusterIds() { //if ((_random != null) && ((_random.nextInt() % FAILURE_FACTOR) == 0)) {return null;} if (assertHasData(_clusters)) { return _clusters.keySet().toArray(new String[0]); } return null; } @Override /* HadoopClusterInfo returned may contain null values for any of its fields except for clusterId * This method will return null if a JobTracker representing the cluster is powered off */ public HadoopClusterInfo getHadoopInfoForCluster(String clusterId) { //if ((_random != null) && ((_random.nextInt() % FAILURE_FACTOR) == 0)) {return null;} if (assertHasData(_clusters)) { ClusterInfo ci = getCluster(clusterId); HadoopClusterInfo result = null; if (ci != null) { VMInfo vi = _vms.get(ci._constantData._masterMoRef); Boolean powerState = checkPowerStateOfVm(vi._moRef, true); if ((vi != null) && (powerState != null) && powerState) { /* Constant and Variable data references are guaranteed to be non-null. iPAddress or dnsName may be null */ result = new HadoopClusterInfo(ci._masterUUID, vi._variableData._dnsName, vi._variableData._ipAddr, ci._jobTrackerPort); } } return result; } return null; } @Override /* Note that the method returns all valid input VM ids, even if they have null DNS names */ public Map<String, String> getDnsNamesForVMs(Set<String> vmIds) { //if ((_random != null) && ((_random.nextInt() % FAILURE_FACTOR) == 0)) {return null;} if (assertHasData(vmIds) && assertHasData(_vms)) { Map<String, String> results = new HashMap<String, String>(); for (String vmId : vmIds) { if (_vms.get(vmId) != null) { results.put(vmId, getDnsNameForVM(vmId)); } } if (results.size() > 0) { return results; } } return null; } @Override public String getDnsNameForVM(String vmId) { //if ((_random != null) && ((_random.nextInt() % FAILURE_FACTOR) == 0)) {return null;} if (assertHasData(_vms)) { VMInfo vminfo = _vms.get(vmId); if (vminfo != null) { String dnsName = vminfo._variableData._dnsName; if (assertHasData(dnsName)) { return dnsName; } } } return null; } @Override public Map<String, String> getVmIdsForDnsNames(Set<String> dnsNames) { //if ((_random != null) && ((_random.nextInt() % FAILURE_FACTOR) == 0)) {return null;} if (assertHasData(dnsNames) && assertHasData(_vms)) { Map<String, String> results = new HashMap<String, String>(); for (VMInfo vminfo : _vms.values()) { String dnsNameToTest = vminfo._variableData._dnsName; if (assertHasData(dnsNameToTest) && dnsNames.contains(dnsNameToTest)) { results.put(dnsNameToTest, vminfo._moRef); } } if (results.size() > 0) { return results; } } return null; } @Override public String getVmIdForDnsName(String dnsName) { //if ((_random != null) && ((_random.nextInt() % FAILURE_FACTOR) == 0)) {return null;} if (assertHasData(_vms)) { for (VMInfo vminfo : _vms.values()) { String dnsNameToTest = vminfo._variableData._dnsName; if (assertHasData(dnsNameToTest) && (dnsName != null) && dnsNameToTest.equals(dnsName)) { return vminfo._moRef; } } } return null; } @Override public Integer getNumVCPUsForVm(String vmId) { //if ((_random != null) && ((_random.nextInt() % FAILURE_FACTOR) == 0)) {return null;} if (assertHasData(_vms)) { VMInfo vm = _vms.get(vmId); if (vm != null) { return vm._variableData._vCPUs; } } return null; } @Override public Long getPowerOnTimeForVm(String vmId) { //if ((_random != null) && ((_random.nextInt() % FAILURE_FACTOR) == 0)) {return null;} if (assertHasData(_vms)) { VMInfo vm = _vms.get(vmId); if (vm != null) { return vm._powerOnTime; } } return null; } @Override public String getExtraInfo(String clusterId, String key) { //if ((_random != null) && ((_random.nextInt() % FAILURE_FACTOR) == 0)) {return null;} ClusterInfo info = getCluster(clusterId); if (info != null) { if (info._extraInfo != null) { return info._extraInfo.get(key); } } return null; } @Override public String[] getAllClusterIdsForScaleStrategyKey(String key) { //if ((_random != null) && ((_random.nextInt() % FAILURE_FACTOR) == 0)) {return null;} if (assertHasData(_clusters) && (key != null)) { Set<String> result = new HashSet<String>(); for (String clusterId : _clusters.keySet()) { ScaleStrategy scaleStrategy = getScaleStrategyForCluster(clusterId); if ((scaleStrategy != null) && (scaleStrategy.getKey().equals(key))) { result.add(clusterId); } } if (result.size() > 0) { return result.toArray(new String[]{}); } } return null; } }
false
false
null
null
diff --git a/src/com/android/gallery3d/filtershow/FilterShowActivity.java b/src/com/android/gallery3d/filtershow/FilterShowActivity.java index 4198da020..d91cfb6c1 100644 --- a/src/com/android/gallery3d/filtershow/FilterShowActivity.java +++ b/src/com/android/gallery3d/filtershow/FilterShowActivity.java @@ -1,1129 +1,1129 @@ /* * Copyright (C) 2012 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.gallery3d.filtershow; import android.annotation.TargetApi; import android.app.ActionBar; import android.app.Activity; import android.app.ProgressDialog; import android.app.WallpaperManager; import android.content.ContentValues; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.Point; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.provider.MediaStore; import android.util.DisplayMetrics; import android.util.Log; import android.util.TypedValue; import android.view.Display; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.SeekBar; import android.widget.ShareActionProvider; import android.widget.ShareActionProvider.OnShareTargetSelectedListener; import android.widget.Toast; import com.android.gallery3d.R; import com.android.gallery3d.data.LocalAlbum; import com.android.gallery3d.filtershow.cache.ImageLoader; import com.android.gallery3d.filtershow.filters.ImageFilter; import com.android.gallery3d.filtershow.filters.ImageFilterBorder; import com.android.gallery3d.filtershow.filters.ImageFilterBwFilter; import com.android.gallery3d.filtershow.filters.ImageFilterContrast; import com.android.gallery3d.filtershow.filters.ImageFilterCurves; import com.android.gallery3d.filtershow.filters.ImageFilterDownsample; import com.android.gallery3d.filtershow.filters.ImageFilterEdge; import com.android.gallery3d.filtershow.filters.ImageFilterExposure; import com.android.gallery3d.filtershow.filters.ImageFilterFx; import com.android.gallery3d.filtershow.filters.ImageFilterHue; import com.android.gallery3d.filtershow.filters.ImageFilterKMeans; import com.android.gallery3d.filtershow.filters.ImageFilterNegative; import com.android.gallery3d.filtershow.filters.ImageFilterParametricBorder; import com.android.gallery3d.filtershow.filters.ImageFilterRS; import com.android.gallery3d.filtershow.filters.ImageFilterSaturated; import com.android.gallery3d.filtershow.filters.ImageFilterShadows; import com.android.gallery3d.filtershow.filters.ImageFilterSharpen; import com.android.gallery3d.filtershow.filters.ImageFilterTinyPlanet; import com.android.gallery3d.filtershow.filters.ImageFilterVibrance; import com.android.gallery3d.filtershow.filters.ImageFilterVignette; import com.android.gallery3d.filtershow.filters.ImageFilterWBalance; import com.android.gallery3d.filtershow.imageshow.ImageBorder; import com.android.gallery3d.filtershow.imageshow.ImageCrop; import com.android.gallery3d.filtershow.imageshow.ImageFlip; import com.android.gallery3d.filtershow.imageshow.ImageRedEyes; import com.android.gallery3d.filtershow.imageshow.ImageRotate; import com.android.gallery3d.filtershow.imageshow.ImageShow; import com.android.gallery3d.filtershow.imageshow.ImageSmallBorder; import com.android.gallery3d.filtershow.imageshow.ImageSmallFilter; import com.android.gallery3d.filtershow.imageshow.ImageStraighten; import com.android.gallery3d.filtershow.imageshow.ImageTinyPlanet; import com.android.gallery3d.filtershow.imageshow.ImageZoom; import com.android.gallery3d.filtershow.presets.ImagePreset; import com.android.gallery3d.filtershow.provider.SharedImageProvider; import com.android.gallery3d.filtershow.tools.SaveCopyTask; import com.android.gallery3d.filtershow.ui.FramedTextButton; import com.android.gallery3d.filtershow.ui.ImageButtonTitle; import com.android.gallery3d.filtershow.ui.ImageCurves; import com.android.gallery3d.filtershow.ui.Spline; import com.android.gallery3d.util.GalleryUtils; import java.io.File; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.Vector; @TargetApi(16) public class FilterShowActivity extends Activity implements OnItemClickListener, OnShareTargetSelectedListener { // fields for supporting crop action public static final String CROP_ACTION = "com.android.camera.action.CROP"; private CropExtras mCropExtras = null; public static final String TINY_PLANET_ACTION = "com.android.camera.action.TINY_PLANET"; public static final String LAUNCH_FULLSCREEN = "launch-fullscreen"; public static final int MAX_BMAP_IN_INTENT = 990000; private final PanelController mPanelController = new PanelController(); private ImageLoader mImageLoader = null; private ImageShow mImageShow = null; private ImageCurves mImageCurves = null; private ImageBorder mImageBorders = null; private ImageRedEyes mImageRedEyes = null; private ImageStraighten mImageStraighten = null; private ImageZoom mImageZoom = null; private ImageCrop mImageCrop = null; private ImageRotate mImageRotate = null; private ImageFlip mImageFlip = null; private ImageTinyPlanet mImageTinyPlanet = null; private View mListFx = null; private View mListBorders = null; private View mListGeometry = null; private View mListColors = null; private View mListFilterButtons = null; private View mSaveButton = null; private ImageButton mFxButton = null; private ImageButton mBorderButton = null; private ImageButton mGeometryButton = null; private ImageButton mColorsButton = null; private ImageSmallFilter mCurrentImageSmallFilter = null; private static final int SELECT_PICTURE = 1; private static final String LOGTAG = "FilterShowActivity"; protected static final boolean ANIMATE_PANELS = true; private static int mImageBorderSize = 4; // in percent private boolean mShowingHistoryPanel = false; private boolean mShowingImageStatePanel = false; private final Vector<ImageShow> mImageViews = new Vector<ImageShow>(); private final Vector<View> mListViews = new Vector<View>(); private final Vector<ImageButton> mBottomPanelButtons = new Vector<ImageButton>(); private ShareActionProvider mShareActionProvider; private File mSharedOutputFile = null; private boolean mSharingImage = false; private WeakReference<ProgressDialog> mSavingProgressDialog; private static final int SEEK_BAR_MAX = 600; private LoadBitmapTask mLoadBitmapTask; private ImageSmallFilter mNullFxFilter; private ImageSmallFilter mNullBorderFilter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ImageFilterRS.setRenderScriptContext(this); ImageShow.setDefaultBackgroundColor(getResources().getColor(R.color.background_screen)); ImageSmallFilter.setDefaultBackgroundColor(getResources().getColor( R.color.background_main_toolbar)); // TODO: get those values from XML. ImageZoom.setZoomedSize(getPixelsFromDip(256)); FramedTextButton.setTextSize((int) getPixelsFromDip(14)); FramedTextButton.setTrianglePadding((int) getPixelsFromDip(4)); FramedTextButton.setTriangleSize((int) getPixelsFromDip(10)); ImageShow.setTextSize((int) getPixelsFromDip(12)); ImageShow.setTextPadding((int) getPixelsFromDip(10)); ImageShow.setOriginalTextMargin((int) getPixelsFromDip(4)); ImageShow.setOriginalTextSize((int) getPixelsFromDip(18)); ImageShow.setOriginalText(getResources().getString(R.string.original_picture_text)); ImageButtonTitle.setTextSize((int) getPixelsFromDip(12)); ImageButtonTitle.setTextPadding((int) getPixelsFromDip(10)); ImageSmallFilter.setMargin((int) getPixelsFromDip(3)); ImageSmallFilter.setTextMargin((int) getPixelsFromDip(4)); Drawable curveHandle = getResources().getDrawable(R.drawable.camera_crop); int curveHandleSize = (int) getResources().getDimension(R.dimen.crop_indicator_size); Spline.setCurveHandle(curveHandle, curveHandleSize); Spline.setCurveWidth((int) getPixelsFromDip(3)); setContentView(R.layout.filtershow_activity); ActionBar actionBar = getActionBar(); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); actionBar.setCustomView(R.layout.filtershow_actionbar); mSaveButton = actionBar.getCustomView(); mSaveButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { saveImage(); } }); mImageLoader = new ImageLoader(this, getApplicationContext()); LinearLayout listFilters = (LinearLayout) findViewById(R.id.listFilters); LinearLayout listBorders = (LinearLayout) findViewById(R.id.listBorders); LinearLayout listColors = (LinearLayout) findViewById(R.id.listColorsFx); mImageShow = (ImageShow) findViewById(R.id.imageShow); mImageCurves = (ImageCurves) findViewById(R.id.imageCurves); mImageBorders = (ImageBorder) findViewById(R.id.imageBorder); mImageStraighten = (ImageStraighten) findViewById(R.id.imageStraighten); mImageZoom = (ImageZoom) findViewById(R.id.imageZoom); mImageCrop = (ImageCrop) findViewById(R.id.imageCrop); mImageRotate = (ImageRotate) findViewById(R.id.imageRotate); mImageFlip = (ImageFlip) findViewById(R.id.imageFlip); mImageTinyPlanet = (ImageTinyPlanet) findViewById(R.id.imageTinyPlanet); mImageRedEyes = (ImageRedEyes) findViewById(R.id.imageRedEyes); mImageCrop.setAspectTextSize((int) getPixelsFromDip(18)); ImageCrop.setTouchTolerance((int) getPixelsFromDip(25)); ImageCrop.setMinCropSize((int) getPixelsFromDip(55)); mImageViews.add(mImageShow); mImageViews.add(mImageCurves); mImageViews.add(mImageBorders); mImageViews.add(mImageStraighten); mImageViews.add(mImageZoom); mImageViews.add(mImageCrop); mImageViews.add(mImageRotate); mImageViews.add(mImageFlip); mImageViews.add(mImageTinyPlanet); mImageViews.add(mImageRedEyes); for (ImageShow imageShow : mImageViews) { mImageLoader.addCacheListener(imageShow); } mListFx = findViewById(R.id.fxList); mListBorders = findViewById(R.id.bordersList); mListGeometry = findViewById(R.id.geometryList); mListFilterButtons = findViewById(R.id.filterButtonsList); mListColors = findViewById(R.id.colorsFxList); mListViews.add(mListFx); mListViews.add(mListBorders); mListViews.add(mListGeometry); mListViews.add(mListFilterButtons); mListViews.add(mListColors); mFxButton = (ImageButton) findViewById(R.id.fxButton); mBorderButton = (ImageButton) findViewById(R.id.borderButton); mGeometryButton = (ImageButton) findViewById(R.id.geometryButton); mColorsButton = (ImageButton) findViewById(R.id.colorsButton); mBottomPanelButtons.add(mFxButton); mBottomPanelButtons.add(mBorderButton); mBottomPanelButtons.add(mGeometryButton); mBottomPanelButtons.add(mColorsButton); mImageShow.setImageLoader(mImageLoader); mImageCurves.setImageLoader(mImageLoader); mImageCurves.setMaster(mImageShow); mImageBorders.setImageLoader(mImageLoader); mImageBorders.setMaster(mImageShow); mImageStraighten.setImageLoader(mImageLoader); mImageStraighten.setMaster(mImageShow); mImageZoom.setImageLoader(mImageLoader); mImageZoom.setMaster(mImageShow); mImageCrop.setImageLoader(mImageLoader); mImageCrop.setMaster(mImageShow); mImageRotate.setImageLoader(mImageLoader); mImageRotate.setMaster(mImageShow); mImageFlip.setImageLoader(mImageLoader); mImageFlip.setMaster(mImageShow); mImageTinyPlanet.setImageLoader(mImageLoader); mImageTinyPlanet.setMaster(mImageShow); mImageRedEyes.setImageLoader(mImageLoader); mImageRedEyes.setMaster(mImageShow); mPanelController.setActivity(this); mPanelController.addImageView(findViewById(R.id.imageShow)); mPanelController.addImageView(findViewById(R.id.imageCurves)); mPanelController.addImageView(findViewById(R.id.imageBorder)); mPanelController.addImageView(findViewById(R.id.imageStraighten)); mPanelController.addImageView(findViewById(R.id.imageCrop)); mPanelController.addImageView(findViewById(R.id.imageRotate)); mPanelController.addImageView(findViewById(R.id.imageFlip)); mPanelController.addImageView(findViewById(R.id.imageZoom)); mPanelController.addImageView(findViewById(R.id.imageTinyPlanet)); mPanelController.addImageView(findViewById(R.id.imageRedEyes)); mPanelController.addPanel(mFxButton, mListFx, 0); mPanelController.addPanel(mBorderButton, mListBorders, 1); mPanelController.addPanel(mGeometryButton, mListGeometry, 2); mPanelController.addComponent(mGeometryButton, findViewById(R.id.straightenButton)); mPanelController.addComponent(mGeometryButton, findViewById(R.id.cropButton)); mPanelController.addComponent(mGeometryButton, findViewById(R.id.rotateButton)); mPanelController.addComponent(mGeometryButton, findViewById(R.id.flipButton)); mPanelController.addComponent(mGeometryButton, findViewById(R.id.redEyeButton)); mPanelController.addPanel(mColorsButton, mListColors, 3); ImageFilter[] filters = { new ImageFilterTinyPlanet(), new ImageFilterWBalance(), new ImageFilterExposure(), new ImageFilterVignette(), new ImageFilterContrast(), new ImageFilterShadows(), new ImageFilterVibrance(), new ImageFilterSharpen(), new ImageFilterCurves(), new ImageFilterHue(), new ImageFilterSaturated(), new ImageFilterBwFilter(), new ImageFilterNegative(), new ImageFilterEdge(), new ImageFilterKMeans(), - new ImageFilterDownsample() + new ImageFilterDownsample(mImageLoader) }; for (int i = 0; i < filters.length; i++) { ImageSmallFilter fView = new ImageSmallFilter(this); filters[i].setParameter(filters[i].getPreviewParameter()); filters[i].setName(getString(filters[i].getTextId())); fView.setImageFilter(filters[i]); fView.setController(this); fView.setImageLoader(mImageLoader); fView.setId(filters[i].getButtonId()); if (filters[i].getOverlayBitmaps() != 0) { Bitmap bitmap = BitmapFactory.decodeResource(getResources(), filters[i].getOverlayBitmaps()); fView.setOverlayBitmap(bitmap); } mPanelController.addComponent(mColorsButton, fView); mPanelController.addFilter(filters[i]); listColors.addView(fView); } mPanelController.addView(findViewById(R.id.applyEffect)); mPanelController.addView(findViewById(R.id.pickCurvesChannel)); mPanelController.addView(findViewById(R.id.aspect)); findViewById(R.id.resetOperationsButton).setOnClickListener( createOnClickResetOperationsButton()); ListView operationsList = (ListView) findViewById(R.id.operationsList); operationsList.setAdapter(mImageShow.getHistory()); operationsList.setOnItemClickListener(this); ListView imageStateList = (ListView) findViewById(R.id.imageStateList); imageStateList.setAdapter(mImageShow.getImageStateAdapter()); mImageLoader.setAdapter(mImageShow.getHistory()); fillListImages(listFilters); fillListBorders(listBorders); SeekBar seekBar = (SeekBar) findViewById(R.id.filterSeekBar); seekBar.setMax(SEEK_BAR_MAX); mImageShow.setSeekBar(seekBar); mImageZoom.setSeekBar(seekBar); mImageTinyPlanet.setSeekBar(seekBar); mPanelController.setRowPanel(findViewById(R.id.secondRowPanel)); mPanelController.setUtilityPanel(this, findViewById(R.id.filterButtonsList), findViewById(R.id.applyEffect), findViewById(R.id.aspect), findViewById(R.id.pickCurvesChannel)); mPanelController.setMasterImage(mImageShow); mPanelController.setCurrentPanel(mFxButton); Intent intent = getIntent(); if (intent.getBooleanExtra(LAUNCH_FULLSCREEN, false)) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (intent.getData() != null) { startLoadBitmap(intent.getData()); } else { pickImage(); } // Handle behavior for various actions String action = intent.getAction(); if (action.equalsIgnoreCase(CROP_ACTION)) { Bundle extras = intent.getExtras(); if (extras != null) { mCropExtras = new CropExtras(extras.getInt(CropExtras.KEY_OUTPUT_X, 0), extras.getInt(CropExtras.KEY_OUTPUT_Y, 0), extras.getBoolean(CropExtras.KEY_SCALE, true) && extras.getBoolean(CropExtras.KEY_SCALE_UP_IF_NEEDED, false), extras.getInt(CropExtras.KEY_ASPECT_X, 0), extras.getInt(CropExtras.KEY_ASPECT_Y, 0), extras.getBoolean(CropExtras.KEY_SET_AS_WALLPAPER, false), extras.getBoolean(CropExtras.KEY_RETURN_DATA, false), (Uri) extras.getParcelable(MediaStore.EXTRA_OUTPUT), extras.getString(CropExtras.KEY_OUTPUT_FORMAT), extras.getBoolean(CropExtras.KEY_SHOW_WHEN_LOCKED, false), extras.getFloat(CropExtras.KEY_SPOTLIGHT_X), extras.getFloat(CropExtras.KEY_SPOTLIGHT_Y)); if (mCropExtras.getShowWhenLocked()) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); } mImageShow.getImagePreset().mGeoData.setCropExtras(mCropExtras); mImageCrop.setExtras(mCropExtras); String s = getString(R.string.Fixed); mImageCrop.setAspectString(s); mImageCrop.setCropActionFlag(true); mPanelController.setFixedAspect(mCropExtras.getAspectX() > 0 && mCropExtras.getAspectY() > 0); } mPanelController.showComponent(findViewById(R.id.cropButton)); } else if (action.equalsIgnoreCase(TINY_PLANET_ACTION)) { mPanelController.showComponent(findViewById(R.id.tinyplanetButton)); } } private void startLoadBitmap(Uri uri) { final View filters = findViewById(R.id.filtersPanel); final View loading = findViewById(R.id.loading); loading.setVisibility(View.VISIBLE); filters.setVisibility(View.INVISIBLE); View tinyPlanetView = findViewById(R.id.tinyplanetButton); if (tinyPlanetView != null) { tinyPlanetView.setVisibility(View.GONE); } mLoadBitmapTask = new LoadBitmapTask(tinyPlanetView); mLoadBitmapTask.execute(uri); } private class LoadBitmapTask extends AsyncTask<Uri, Boolean, Boolean> { View mTinyPlanetButton; int mBitmapSize; public LoadBitmapTask(View button) { mTinyPlanetButton = button; mBitmapSize = getScreenImageSize(); } @Override protected Boolean doInBackground(Uri... params) { if (!mImageLoader.loadBitmap(params[0], mBitmapSize)) { return false; } publishProgress(mImageLoader.queryLightCycle360()); return true; } @Override protected void onProgressUpdate(Boolean... values) { super.onProgressUpdate(values); if (isCancelled()) { return; } final View filters = findViewById(R.id.filtersPanel); final View loading = findViewById(R.id.loading); loading.setVisibility(View.GONE); filters.setVisibility(View.VISIBLE); if (values[0]) { mTinyPlanetButton.setVisibility(View.VISIBLE); } } @Override protected void onPostExecute(Boolean result) { if (isCancelled()) { return; } if (!result) { cannotLoadImage(); } mLoadBitmapTask = null; super.onPostExecute(result); } } @Override protected void onDestroy() { if (mLoadBitmapTask != null) { mLoadBitmapTask.cancel(false); } super.onDestroy(); } private int translateMainPanel(View viewPanel) { int accessoryPanelWidth = viewPanel.getWidth(); int mainViewWidth = findViewById(R.id.mainView).getWidth(); int mainPanelWidth = mImageShow.getDisplayedImageBounds().width(); if (mainPanelWidth == 0) { mainPanelWidth = mainViewWidth; } int filtersPanelWidth = findViewById(R.id.filtersPanel).getWidth(); if (mainPanelWidth < filtersPanelWidth) { mainPanelWidth = filtersPanelWidth; } int leftOver = mainViewWidth - mainPanelWidth - accessoryPanelWidth; if (leftOver < 0) { return -accessoryPanelWidth; } return 0; } private int getScreenImageSize() { DisplayMetrics metrics = new DisplayMetrics(); Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); display.getMetrics(metrics); int msize = Math.min(size.x, size.y); return (133 * msize) / metrics.densityDpi; } private void showSavingProgress(String albumName) { ProgressDialog progress; if (mSavingProgressDialog != null) { progress = mSavingProgressDialog.get(); if (progress != null) { progress.show(); return; } } // TODO: Allow cancellation of the saving process String progressText; if (albumName == null) { progressText = getString(R.string.saving_image); } else { progressText = getString(R.string.filtershow_saving_image, albumName); } progress = ProgressDialog.show(this, "", progressText, true, false); mSavingProgressDialog = new WeakReference<ProgressDialog>(progress); } private void hideSavingProgress() { if (mSavingProgressDialog != null) { ProgressDialog progress = mSavingProgressDialog.get(); if (progress != null) progress.dismiss(); } } public void completeSaveImage(Uri saveUri) { if (mSharingImage && mSharedOutputFile != null) { // Image saved, we unblock the content provider Uri uri = Uri.withAppendedPath(SharedImageProvider.CONTENT_URI, Uri.encode(mSharedOutputFile.getAbsolutePath())); ContentValues values = new ContentValues(); values.put(SharedImageProvider.PREPARE, false); getContentResolver().insert(uri, values); } setResult(RESULT_OK, new Intent().setData(saveUri)); hideSavingProgress(); finish(); } @Override public boolean onShareTargetSelected(ShareActionProvider arg0, Intent arg1) { // First, let's tell the SharedImageProvider that it will need to wait // for the image Uri uri = Uri.withAppendedPath(SharedImageProvider.CONTENT_URI, Uri.encode(mSharedOutputFile.getAbsolutePath())); ContentValues values = new ContentValues(); values.put(SharedImageProvider.PREPARE, true); getContentResolver().insert(uri, values); mSharingImage = true; // Process and save the image in the background. showSavingProgress(null); mImageShow.saveImage(this, mSharedOutputFile); return true; } private Intent getDefaultShareIntent() { Intent intent = new Intent(Intent.ACTION_SEND); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setType(SharedImageProvider.MIME_TYPE); mSharedOutputFile = SaveCopyTask.getNewFile(this, mImageLoader.getUri()); Uri uri = Uri.withAppendedPath(SharedImageProvider.CONTENT_URI, Uri.encode(mSharedOutputFile.getAbsolutePath())); intent.putExtra(Intent.EXTRA_STREAM, uri); return intent; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.filtershow_activity_menu, menu); MenuItem showHistory = menu.findItem(R.id.operationsButton); if (mShowingHistoryPanel) { showHistory.setTitle(R.string.hide_history_panel); } else { showHistory.setTitle(R.string.show_history_panel); } MenuItem showState = menu.findItem(R.id.showImageStateButton); if (mShowingImageStatePanel) { showState.setTitle(R.string.hide_imagestate_panel); } else { showState.setTitle(R.string.show_imagestate_panel); } mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.menu_share) .getActionProvider(); mShareActionProvider.setShareIntent(getDefaultShareIntent()); mShareActionProvider.setOnShareTargetSelectedListener(this); MenuItem undoItem = menu.findItem(R.id.undoButton); MenuItem redoItem = menu.findItem(R.id.redoButton); MenuItem resetItem = menu.findItem(R.id.resetHistoryButton); mImageShow.getHistory().setMenuItems(undoItem, redoItem, resetItem); return true; } @Override public void onPause() { super.onPause(); if (mShareActionProvider != null) { mShareActionProvider.setOnShareTargetSelectedListener(null); } } @Override public void onResume() { super.onResume(); if (mShareActionProvider != null) { mShareActionProvider.setOnShareTargetSelectedListener(this); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.undoButton: { HistoryAdapter adapter = mImageShow.getHistory(); int position = adapter.undo(); mImageShow.onItemClick(position); mImageShow.showToast("Undo"); invalidateViews(); return true; } case R.id.redoButton: { HistoryAdapter adapter = mImageShow.getHistory(); int position = adapter.redo(); mImageShow.onItemClick(position); mImageShow.showToast("Redo"); invalidateViews(); return true; } case R.id.resetHistoryButton: { resetHistory(); return true; } case R.id.showImageStateButton: { toggleImageStatePanel(); return true; } case R.id.operationsButton: { toggleHistoryPanel(); return true; } case android.R.id.home: { saveImage(); return true; } } return false; } public void enableSave(boolean enable) { if (mSaveButton != null) mSaveButton.setEnabled(enable); } private void fillListImages(LinearLayout listFilters) { // TODO: use listview // TODO: load the filters straight from the filesystem ImageFilterFx[] fxArray = new ImageFilterFx[18]; int p = 0; int[] drawid = { R.drawable.filtershow_fx_0005_punch, R.drawable.filtershow_fx_0000_vintage, R.drawable.filtershow_fx_0004_bw_contrast, R.drawable.filtershow_fx_0002_bleach, R.drawable.filtershow_fx_0001_instant, R.drawable.filtershow_fx_0007_washout, R.drawable.filtershow_fx_0003_blue_crush, R.drawable.filtershow_fx_0008_washout_color, R.drawable.filtershow_fx_0006_x_process }; int[] fxNameid = { R.string.ffx_punch, R.string.ffx_vintage, R.string.ffx_bw_contrast, R.string.ffx_bleach, R.string.ffx_instant, R.string.ffx_washout, R.string.ffx_blue_crush, R.string.ffx_washout_color, R.string.ffx_x_process }; ImagePreset preset = new ImagePreset(getString(R.string.history_original)); // empty preset.setImageLoader(mImageLoader); mNullFxFilter = new ImageSmallFilter(this); mNullFxFilter.setSelected(true); mCurrentImageSmallFilter = mNullFxFilter; mNullFxFilter.setImageFilter(new ImageFilterFx(null, getString(R.string.none))); mNullFxFilter.setController(this); mNullFxFilter.setImageLoader(mImageLoader); listFilters.addView(mNullFxFilter); ImageSmallFilter previousFilter = mNullFxFilter; BitmapFactory.Options o = new BitmapFactory.Options(); o.inScaled = false; for (int i = 0; i < drawid.length; i++) { Bitmap b = BitmapFactory.decodeResource(getResources(), drawid[i], o); fxArray[p++] = new ImageFilterFx(b, getString(fxNameid[i])); } ImageSmallFilter filter; for (int i = 0; i < p; i++) { filter = new ImageSmallFilter(this); filter.setImageFilter(fxArray[i]); filter.setController(this); filter.setNulfilter(mNullFxFilter); filter.setImageLoader(mImageLoader); listFilters.addView(filter); previousFilter = filter; } // Default preset (original) mImageShow.setImagePreset(preset); } private void fillListBorders(LinearLayout listBorders) { // TODO: use listview // TODO: load the borders straight from the filesystem int p = 0; ImageFilter[] borders = new ImageFilter[12]; borders[p++] = new ImageFilterBorder(null); Drawable npd1 = getResources().getDrawable(R.drawable.filtershow_border_4x5); borders[p++] = new ImageFilterBorder(npd1); Drawable npd2 = getResources().getDrawable(R.drawable.filtershow_border_brush); borders[p++] = new ImageFilterBorder(npd2); Drawable npd3 = getResources().getDrawable(R.drawable.filtershow_border_grunge); borders[p++] = new ImageFilterBorder(npd3); Drawable npd4 = getResources().getDrawable(R.drawable.filtershow_border_sumi_e); borders[p++] = new ImageFilterBorder(npd4); Drawable npd5 = getResources().getDrawable(R.drawable.filtershow_border_tape); borders[p++] = new ImageFilterBorder(npd5); borders[p++] = new ImageFilterParametricBorder(Color.BLACK, mImageBorderSize, 0); borders[p++] = new ImageFilterParametricBorder(Color.BLACK, mImageBorderSize, mImageBorderSize); borders[p++] = new ImageFilterParametricBorder(Color.WHITE, mImageBorderSize, 0); borders[p++] = new ImageFilterParametricBorder(Color.WHITE, mImageBorderSize, mImageBorderSize); int creamColor = Color.argb(255, 237, 237, 227); borders[p++] = new ImageFilterParametricBorder(creamColor, mImageBorderSize, 0); borders[p++] = new ImageFilterParametricBorder(creamColor, mImageBorderSize, mImageBorderSize); ImageSmallFilter previousFilter = null; for (int i = 0; i < p; i++) { ImageSmallBorder filter = new ImageSmallBorder(this); if (i == 0) { // save the first to reset it mNullBorderFilter = filter; } else { filter.setNulfilter(mNullBorderFilter); } borders[i].setName(getString(R.string.borders)); filter.setImageFilter(borders[i]); filter.setController(this); filter.setBorder(true); filter.setImageLoader(mImageLoader); filter.setShowTitle(false); listBorders.addView(filter); previousFilter = filter; } } // ////////////////////////////////////////////////////////////////////////////// // Some utility functions // TODO: finish the cleanup. public void showOriginalViews(boolean value) { for (ImageShow views : mImageViews) { views.showOriginal(value); } } public void invalidateViews() { for (ImageShow views : mImageViews) { views.invalidate(); views.updateImage(); } } public void hideListViews() { for (View view : mListViews) { view.setVisibility(View.GONE); } } public void hideImageViews() { mImageShow.setShowControls(false); // reset for (View view : mImageViews) { view.setVisibility(View.GONE); } } public void unselectBottomPanelButtons() { for (ImageButton button : mBottomPanelButtons) { button.setSelected(false); } } public void unselectPanelButtons(Vector<ImageButton> buttons) { for (ImageButton button : buttons) { button.setSelected(false); } } public void disableFilterButtons() { for (ImageButton b : mBottomPanelButtons) { b.setEnabled(false); b.setClickable(false); b.setAlpha(0.4f); } } public void enableFilterButtons() { for (ImageButton b : mBottomPanelButtons) { b.setEnabled(true); b.setClickable(true); b.setAlpha(1.0f); } } // ////////////////////////////////////////////////////////////////////////////// // imageState panel... public boolean isShowingHistoryPanel() { return mShowingHistoryPanel; } private void toggleImageStatePanel() { final View view = findViewById(R.id.mainPanel); final View viewList = findViewById(R.id.imageStatePanel); if (mShowingHistoryPanel) { findViewById(R.id.historyPanel).setVisibility(View.INVISIBLE); mShowingHistoryPanel = false; } int translate = translateMainPanel(viewList); if (!mShowingImageStatePanel) { mShowingImageStatePanel = true; view.animate().setDuration(200).x(translate) .withLayer().withEndAction(new Runnable() { @Override public void run() { viewList.setAlpha(0); viewList.setVisibility(View.VISIBLE); viewList.animate().setDuration(100) .alpha(1.0f).start(); } }).start(); } else { mShowingImageStatePanel = false; viewList.setVisibility(View.INVISIBLE); view.animate().setDuration(200).x(0).withLayer() .start(); } invalidateOptionsMenu(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (mShowingHistoryPanel) { toggleHistoryPanel(); } } // ////////////////////////////////////////////////////////////////////////////// // history panel... public void toggleHistoryPanel() { final View view = findViewById(R.id.mainPanel); final View viewList = findViewById(R.id.historyPanel); if (mShowingImageStatePanel) { findViewById(R.id.imageStatePanel).setVisibility(View.INVISIBLE); mShowingImageStatePanel = false; } int translate = translateMainPanel(viewList); if (!mShowingHistoryPanel) { mShowingHistoryPanel = true; view.animate().setDuration(200).x(translate) .withLayer().withEndAction(new Runnable() { @Override public void run() { viewList.setAlpha(0); viewList.setVisibility(View.VISIBLE); viewList.animate().setDuration(100) .alpha(1.0f).start(); } }).start(); } else { mShowingHistoryPanel = false; viewList.setVisibility(View.INVISIBLE); view.animate().setDuration(200).x(0).withLayer() .start(); } invalidateOptionsMenu(); } void resetHistory() { mNullFxFilter.onClick(mNullFxFilter); mNullBorderFilter.onClick(mNullBorderFilter); HistoryAdapter adapter = mImageShow.getHistory(); adapter.reset(); ImagePreset original = new ImagePreset(adapter.getItem(0)); mImageShow.setImagePreset(original); mPanelController.resetParameters(); invalidateViews(); } // reset button in the history panel. private OnClickListener createOnClickResetOperationsButton() { return new View.OnClickListener() { @Override public void onClick(View v) { resetHistory(); } }; } @Override public void onBackPressed() { if (mPanelController.onBackPressed()) { saveImage(); } } public void cannotLoadImage() { CharSequence text = getString(R.string.cannot_load_image); Toast toast = Toast.makeText(this, text, Toast.LENGTH_SHORT); toast.show(); finish(); } // ////////////////////////////////////////////////////////////////////////////// public float getPixelsFromDip(float value) { Resources r = getResources(); return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, r.getDisplayMetrics()); } public void useImagePreset(ImageSmallFilter imageSmallFilter, ImagePreset preset) { if (preset == null) { return; } if (mCurrentImageSmallFilter != null) { mCurrentImageSmallFilter.setSelected(false); } mCurrentImageSmallFilter = imageSmallFilter; mCurrentImageSmallFilter.setSelected(true); ImagePreset copy = new ImagePreset(preset); mImageShow.setImagePreset(copy); if (preset.isFx()) { // if it's an FX we rest the curve adjustment too mImageCurves.resetCurve(); } invalidateViews(); } public void useImageFilter(ImageSmallFilter imageSmallFilter, ImageFilter imageFilter, boolean setBorder) { if (imageFilter == null) { return; } if (mCurrentImageSmallFilter != null) { mCurrentImageSmallFilter.setSelected(false); } mCurrentImageSmallFilter = imageSmallFilter; mCurrentImageSmallFilter.setSelected(true); ImagePreset oldPreset = mImageShow.getImagePreset(); ImagePreset copy = new ImagePreset(oldPreset); // TODO: use a numerical constant instead. copy.add(imageFilter); mImageShow.setImagePreset(copy); invalidateViews(); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mImageShow.onItemClick(position); invalidateViews(); } public void pickImage() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, getString(R.string.select_image)), SELECT_PICTURE); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { Log.v(LOGTAG, "onActivityResult"); if (resultCode == RESULT_OK) { if (requestCode == SELECT_PICTURE) { Uri selectedImageUri = data.getData(); startLoadBitmap(selectedImageUri); } } } private boolean mSaveToExtraUri = false; private boolean mSaveAsWallpaper = false; private boolean mReturnAsExtra = false; private boolean outputted = false; public void saveImage() { // boolean outputted = false; if (mCropExtras != null) { if (mCropExtras.getExtraOutput() != null) { mSaveToExtraUri = true; outputted = true; } if (mCropExtras.getSetAsWallpaper()) { mSaveAsWallpaper = true; outputted = true; } if (mCropExtras.getReturnData()) { mReturnAsExtra = true; outputted = true; } if (outputted) { mImageShow.getImagePreset().mGeoData.setUseCropExtrasFlag(true); showSavingProgress(null); mImageShow.returnFilteredResult(this); } } if (!outputted) { if (mImageShow.hasModifications()) { // Get the name of the album, to which the image will be saved File saveDir = SaveCopyTask.getFinalSaveDirectory(this, mImageLoader.getUri()); int bucketId = GalleryUtils.getBucketId(saveDir.getPath()); String albumName = LocalAlbum.getLocalizedName(getResources(), bucketId, null); showSavingProgress(albumName); mImageShow.saveImage(this, null); } else { done(); } } } public void onFilteredResult(Bitmap filtered) { Intent intent = new Intent(); intent.putExtra(CropExtras.KEY_CROPPED_RECT, mImageShow.getImageCropBounds()); if (mSaveToExtraUri) { mImageShow.saveToUri(filtered, mCropExtras.getExtraOutput(), mCropExtras.getOutputFormat(), this); } if (mSaveAsWallpaper) { try { WallpaperManager.getInstance(this).setBitmap(filtered); } catch (IOException e) { Log.w(LOGTAG, "fail to set wall paper", e); } } if (mReturnAsExtra) { if (filtered != null) { int bmapSize = filtered.getRowBytes() * filtered.getHeight(); /* * Max size of Binder transaction buffer is 1Mb, so constrain * Bitmap to be somewhat less than this, otherwise we get * TransactionTooLargeExceptions. */ if (bmapSize > MAX_BMAP_IN_INTENT) { Log.w(LOGTAG, "Bitmap too large to be returned via intent"); } else { intent.putExtra(CropExtras.KEY_DATA, filtered); } } } setResult(RESULT_OK, intent); if (!mSaveToExtraUri) { done(); } } public void done() { if (outputted) { hideSavingProgress(); } finish(); } static { System.loadLibrary("jni_filtershow_filters"); } } diff --git a/src/com/android/gallery3d/filtershow/filters/ImageFilterDownsample.java b/src/com/android/gallery3d/filtershow/filters/ImageFilterDownsample.java index fa2293ca7..60a18b701 100644 --- a/src/com/android/gallery3d/filtershow/filters/ImageFilterDownsample.java +++ b/src/com/android/gallery3d/filtershow/filters/ImageFilterDownsample.java @@ -1,68 +1,81 @@ /* * Copyright (C) 2012 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.gallery3d.filtershow.filters; import android.graphics.Bitmap; +import android.graphics.Rect; import com.android.gallery3d.R; +import com.android.gallery3d.filtershow.cache.ImageLoader; public class ImageFilterDownsample extends ImageFilter { + private ImageLoader mImageLoader; - public ImageFilterDownsample() { + public ImageFilterDownsample(ImageLoader loader) { mName = "Downsample"; mMaxParameter = 100; - mMinParameter = 5; - mPreviewParameter = 10; + mMinParameter = 1; + mPreviewParameter = 3; mDefaultParameter = 50; mParameter = 50; + mImageLoader = loader; } @Override public int getButtonId() { return R.id.downsampleButton; } @Override public int getTextId() { return R.string.downsample; } @Override public boolean isNil() { return false; } @Override public Bitmap apply(Bitmap bitmap, float scaleFactor, boolean highQuality) { int w = bitmap.getWidth(); int h = bitmap.getHeight(); int p = mParameter; + + // size of original precached image + Rect size = mImageLoader.getOriginalBounds(); + int orig_w = size.width(); + int orig_h = size.height(); + if (p > 0 && p < 100) { - int newWidth = w * p / 100; - int newHeight = h * p / 100; - if (newWidth <= 0 || newHeight <= 0) { + // scale preview to same size as the resulting bitmap from a "save" + int newWidth = orig_w * p / 100; + int newHeight = orig_h * p / 100; + + // only scale preview if preview isn't already scaled enough + if (newWidth <= 0 || newHeight <= 0 || newWidth >= w || newHeight >= h) { return bitmap; } Bitmap ret = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true); if (ret != bitmap) { bitmap.recycle(); } return ret; } return bitmap; } }
false
false
null
null
diff --git a/org.eclipse.gmf.runtime/plugins/org.eclipse.gmf.runtime.emf.core/src/org/eclipse/gmf/runtime/emf/core/resources/GMFHandler.java b/org.eclipse.gmf.runtime/plugins/org.eclipse.gmf.runtime.emf.core/src/org/eclipse/gmf/runtime/emf/core/resources/GMFHandler.java index eda01469..38defe59 100644 --- a/org.eclipse.gmf.runtime/plugins/org.eclipse.gmf.runtime.emf.core/src/org/eclipse/gmf/runtime/emf/core/resources/GMFHandler.java +++ b/org.eclipse.gmf.runtime/plugins/org.eclipse.gmf.runtime.emf.core/src/org/eclipse/gmf/runtime/emf/core/resources/GMFHandler.java @@ -1,152 +1,160 @@ /****************************************************************************** - * Copyright (c) 2004, 2006 IBM Corporation and others. + * Copyright (c) 2004, 2008 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.gmf.runtime.emf.core.resources; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EFactory; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.impl.ResourceImpl; +import org.eclipse.emf.ecore.xmi.UnresolvedReferenceException; import org.eclipse.emf.ecore.xmi.XMIException; import org.eclipse.emf.ecore.xmi.XMLHelper; import org.eclipse.emf.ecore.xmi.XMLResource; import org.eclipse.emf.ecore.xmi.impl.SAXXMIHandler; import org.eclipse.emf.ecore.xml.type.AnyType; /** * The SAX handler for MSL resources. Updates demand-created packages with their * namespace prefixes and schema locations. * * @author khussey */ public class GMFHandler extends SAXXMIHandler { protected final Map urisToProxies; protected boolean abortOnError; /** * Constructs a new MSL handler for the specified resource with the * specified helper and options. * * @param xmiResource * The resource for the new handler. * @param helper * The helper for the new handler. * @param options * The load options for the new handler. */ public GMFHandler(XMLResource xmiResource, XMLHelper helper, Map options) { super(xmiResource, helper, options); urisToProxies = new HashMap(); if (Boolean.TRUE.equals(options.get(GMFResource.OPTION_ABORT_ON_ERROR))) { abortOnError = true; } } /** * @see org.eclipse.emf.ecore.xmi.impl.XMLHandler#endDocument() */ public void endDocument() { super.endDocument(); if (null != extendedMetaData) { for (Iterator demandedPackages = extendedMetaData .demandedPackages().iterator(); demandedPackages.hasNext();) { EPackage ePackage = (EPackage) demandedPackages.next(); String nsURI = ePackage.getNsURI(); if (null != nsURI) { if (null != urisToLocations) { URI locationURI = (URI) urisToLocations.get(nsURI); if (null != locationURI) { // set the schema location Resource resource = new ResourceImpl(); resource.setURI(locationURI); resource.getContents().add(ePackage); } } for (Iterator entries = helper.getPrefixToNamespaceMap() .iterator(); entries.hasNext();) { Map.Entry entry = (Map.Entry) entries.next(); if (nsURI.equals(entry.getValue())) { // set the namespace prefix ePackage.setNsPrefix((String) entry.getKey()); } } } } } } /** * @see org.eclipse.emf.ecore.xmi.impl.XMLHandler#validateCreateObjectFromFactory(org.eclipse.emf.ecore.EFactory, * java.lang.String, org.eclipse.emf.ecore.EObject, * org.eclipse.emf.ecore.EStructuralFeature) */ protected EObject validateCreateObjectFromFactory(EFactory factory, String typeName, EObject newObject, EStructuralFeature feature) { if (!(objects.peek() instanceof AnyType) && null != newObject && newObject.eIsProxy() && !sameDocumentProxies.contains(newObject)) { URI proxyURI = ((InternalEObject) newObject).eProxyURI(); Map typeNamesToProxies = (Map) urisToProxies.get(proxyURI); if (null == typeNamesToProxies) { urisToProxies.put(proxyURI, typeNamesToProxies = new HashMap()); } EObject proxy = (EObject) typeNamesToProxies.get(typeName); if (null == proxy) { typeNamesToProxies.put(typeName, proxy = newObject); } // canonicalize proxies newObject = proxy; } return super.validateCreateObjectFromFactory(factory, typeName, newObject, feature); } /** * @see org.eclipse.emf.ecore.xmi.impl.XMLHandler#error(org.eclipse.emf.ecore.xmi.XMIException) */ public void error(XMIException e) { super.error(e); if (abortOnError) { - if (e.getCause() != null) { - throw new AbortResourceLoadException(e.getCause()); + /* + * Ignore UnresolvedReferenceException, since unresolved references + * are not a fatal error. We will continue to attempt to load the + * model and log UnresolvedReferenceException. + */ + if (!(e instanceof UnresolvedReferenceException)) { + if (e.getCause() != null) { + throw new AbortResourceLoadException(e.getCause()); + } + throw new AbortResourceLoadException(e); } - throw new AbortResourceLoadException(e); } } }
false
false
null
null
diff --git a/src/main/java/hudson/plugins/sctmexecutor/publisher/xunit/SCTMInputMetric.java b/src/main/java/hudson/plugins/sctmexecutor/publisher/xunit/SCTMInputMetric.java index 4a691d4..0e70191 100644 --- a/src/main/java/hudson/plugins/sctmexecutor/publisher/xunit/SCTMInputMetric.java +++ b/src/main/java/hudson/plugins/sctmexecutor/publisher/xunit/SCTMInputMetric.java @@ -1,40 +1,35 @@ package hudson.plugins.sctmexecutor.publisher.xunit; import com.thalesgroup.dtkit.junit.model.JUnitModel; -import com.thalesgroup.dtkit.metrics.api.InputMetricXSL; -import com.thalesgroup.dtkit.metrics.api.InputType; -import com.thalesgroup.dtkit.metrics.api.OutputMetric; +import com.thalesgroup.dtkit.metrics.model.InputMetricXSL; +import com.thalesgroup.dtkit.metrics.model.InputType; +import com.thalesgroup.dtkit.metrics.model.OutputMetric; public final class SCTMInputMetric extends InputMetricXSL { private static final long serialVersionUID = -38720636581583520L; @Override public String getXslName() { return "sctm-to-junit.xsl"; //$NON-NLS-1$ } @Override - public String getInputXsd() { - return null; - } - - @Override public String getToolName() { return "SilkCentral TestManager"; } @Override public String getToolVersion() { return " >2008R2"; } @Override public InputType getToolType() { return InputType.TEST; } @Override public OutputMetric getOutputFormatType() { return JUnitModel.OUTPUT_JUNIT_1_0; } } diff --git a/src/main/java/hudson/plugins/sctmexecutor/publisher/xunit/SCTMTestType.java b/src/main/java/hudson/plugins/sctmexecutor/publisher/xunit/SCTMTestType.java index d08bcee..777819d 100644 --- a/src/main/java/hudson/plugins/sctmexecutor/publisher/xunit/SCTMTestType.java +++ b/src/main/java/hudson/plugins/sctmexecutor/publisher/xunit/SCTMTestType.java @@ -1,36 +1,36 @@ package hudson.plugins.sctmexecutor.publisher.xunit; import hudson.Extension; import org.kohsuke.stapler.DataBoundConstructor; import com.thalesgroup.dtkit.metrics.hudson.api.descriptor.TestTypeDescriptor; import com.thalesgroup.dtkit.metrics.hudson.api.type.TestType; public class SCTMTestType extends TestType { private static final long serialVersionUID = 1L; @DataBoundConstructor public SCTMTestType(String pattern, boolean faildedIfNotNew, boolean deleteJUnitFiles) { super(pattern, faildedIfNotNew, deleteJUnitFiles); } @Override public TestTypeDescriptor<SCTMTestType> getDescriptor() { - return new SCTMTestType.DescriptorImpl(); + return null; //new SCTMTestType.DescriptorImpl(); } @Extension public static class DescriptorImpl extends TestTypeDescriptor<SCTMTestType> { public DescriptorImpl() { super(SCTMTestType.class, SCTMInputMetric.class); } @Override public String getId() { return SCTMTestType.class.getCanonicalName(); } } }
false
false
null
null
diff --git a/src/main/java/uk/co/m4numbers/EyeSpy/EyeSpy.java b/src/main/java/uk/co/m4numbers/EyeSpy/EyeSpy.java index 1ec7481..be9f12f 100644 --- a/src/main/java/uk/co/m4numbers/EyeSpy/EyeSpy.java +++ b/src/main/java/uk/co/m4numbers/EyeSpy/EyeSpy.java @@ -1,163 +1,169 @@ package uk.co.m4numbers.EyeSpy; //import uk.co.m4numbers.EyeSpy.Listeners.BlockListener; Excluded for this build import uk.co.m4numbers.EyeSpy.Listeners.ChatListener; import uk.co.m4numbers.EyeSpy.Listeners.CommandListener; import uk.co.m4numbers.EyeSpy.Logging.Logging; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.PluginManager; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; import java.util.logging.Logger; /** * Base class for EyeSpy. Main parts are the onEnable(), onDisable(), and the print areas at the moment. * @author Matthew Ball * */ public class EyeSpy extends JavaPlugin{ public EyeSpy plugin; public Logger log = Logger.getLogger("Minecraft"); + private int runner; public static String version; public static String name; public static String Server; public static EyeSpy self = null; Logging db; public static String host; public static String username; public static String password ; + public static int port; public static String database; public static String prefix; public static Properties props = new Properties(); /** * This is the onEnable class for when the plugin starts up. Basic checks are run for the version, name and information of the plugin, then startup occurs. */ @Override public void onEnable(){ //Lets get the basics ready. version = this.getDescription().getVersion(); name = this.getDescription().getName(); Server = this.getServer().getName(); self = this; log.info(name + " version " + version + " has started..."); //Start up the managers and the configs and all that PluginManager pm = getServer().getPluginManager(); getConfig().options().copyDefaults(true); saveConfig(); //Load in the properties for the IRC channels and store them in the respective file. props.setProperty("#mine", "Global"); props.setProperty("#dev", "Dev"); props.setProperty("#help", "Support"); props.setProperty("#mods", "Mods"); props.setProperty("#new", "New"); props.setProperty("#trade", "Trade"); try { props.store(new FileOutputStream("chan.properties"), null); printInfo("Properties stored."); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //Collect Database information host = getConfig().getString("EyeSpy.database.host"); + port = getConfig().getInt("EyeSpy.database.port"); username = getConfig().getString("EyeSpy.database.username"); password = getConfig().getString("EyeSpy.database.password"); database = getConfig().getString("EyeSpy.database.database"); prefix = getConfig().getString("EyeSpy.database.prefix"); //Bring in the logging stuffs and start it all up Logging sqldb = new Logging(); sqldb.startSql(); if (!Logging.sql) { printSevere("SQL database NOT activated!"); } + runner = getServer().getScheduler().scheduleSyncRepeatingTask(this, sqldb.new maintainConnection(), 2400L, 2400L); + printInfo("EyeSpy has been enabled!"); //Register the listeners. pm.registerEvents(new ChatListener(), this); pm.registerEvents(new CommandListener(), this); //pm.registerEvents(new BlockListener(), this); Excluded for this build } /** * The routine to kill the connection cleanly and show that it has been done. */ @Override public void onDisable() { Logging.killConnection(); + getServer().getScheduler().cancelTask(runner); printInfo("EyeSpy has been disabled!"); } /** * Prints a SEVERE warning to the console. * @param line : This is the error message */ public static void printSevere(String line) { self.log.severe("[EyeSpy] " + line); } /** * Prints a WARNING to the console. * @param line : This is the error message */ public static void printWarning(String line) { self.log.warning("[EyeSpy] " + line); } /** * Prints INFO to the console * @param line : This is the information */ public static void printInfo(String line) { self.log.info("[EyeSpy] " + line); } /** * Prints DEBUG info to the console * @param line : This contains the information to be outputted */ public static void printDebug(String line) { self.log.info("[EyeSpy DEBUG] " + line); } /** * This function will convert the IRC channel names into their herochat equivalents. * @param channel : This is the IRC channel that we're inputting * @return String : This is the Herochat equivalent of the channel. */ public static String ircToGame( String channel ) { try { props.load( new FileInputStream("chan.properties") ); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return props.getProperty(channel); } } diff --git a/src/main/java/uk/co/m4numbers/EyeSpy/Logging/Logging.java b/src/main/java/uk/co/m4numbers/EyeSpy/Logging/Logging.java index 08af8bb..4ddaa65 100644 --- a/src/main/java/uk/co/m4numbers/EyeSpy/Logging/Logging.java +++ b/src/main/java/uk/co/m4numbers/EyeSpy/Logging/Logging.java @@ -1,522 +1,523 @@ package uk.co.m4numbers.EyeSpy.Logging; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import uk.co.m4numbers.EyeSpy.EyeSpy; import uk.co.m4numbers.EyeSpy.Util.ArgProcessing; /** * Main logging class... logs stuff. * @author M477h3w1012 * */ /* Notes for creation * TODO Create a class for adding chest entries */ public class Logging { //Start with all the usual variables to maintain a connection public static Connection conn; private static String host; private static String database; + private static int port; public static boolean sql; //List all the prepared statements that we're going to be using at one point or another private static PreparedStatement Maintain; private static PreparedStatement InsertChat; private static PreparedStatement SelectChannel; private static PreparedStatement InsertChannel; private static PreparedStatement SelectPlayer; private static PreparedStatement InsertPlayer; private static PreparedStatement SelectServer; private static PreparedStatement InsertServer; private static PreparedStatement SelectWorld; private static PreparedStatement InsertWorld; private static PreparedStatement InsertCommand; private static PreparedStatement InsertBlock; /** * Gets the information required for connecting. */ public Logging() { Logging.host = EyeSpy.host; Logging.database = EyeSpy.database; + Logging.port = EyeSpy.port; } /** * This is called once, upon startup of the server, and performs the checks to make sure that the plugin is ready to go. */ public void startSql() { String prefix = EyeSpy.prefix; startConnection(); if (sql) { createTables( prefix ); } prepareStatements( prefix ); - } /** * This is called upon startup and logs into the database using the information found in the config file. */ protected void startConnection() { sql = true; - String sqlUrl = String.format("jdbc:mysql://%s/%s", host, database); + String sqlUrl = String.format("jdbc:mysql://%s/%s", host, port, database); String username = EyeSpy.username; String password = EyeSpy.password; Properties sqlStr = new Properties(); sqlStr.put("user", username); sqlStr.put("password", password); sqlStr.put("autoReconnect", "true"); try { conn = DriverManager.getConnection(sqlUrl, sqlStr); } catch (SQLException e) { EyeSpy.printSevere("A MySQL connection could not be made"); e.printStackTrace(); sql = false; } } /** * Kill the connection cleanly. Basically just the one command, but hey... gotta do something. */ public static void killConnection() { if ( sql ) { EyeSpy.printInfo("Closing the connection..."); try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } EyeSpy.printInfo("Connection has been closed."); } } /** * Alright, we have all the statements, lets build them up and create usable commands from them. * @param prefix : Use this to build the statements, affixing it to all the table descriptors. */ protected void prepareStatements( String prefix ) { try { Maintain = conn.prepareStatement("SELECT count(*) FROM `" + prefix + "chat` limit 1;"); InsertChat = conn.prepareStatement("INSERT INTO `" + prefix + "chat` (`player_id`, `ch_id`, `ser_id`, `date`, `message`) VALUES (?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); SelectChannel = conn.prepareStatement("SELECT * FROM `" + prefix + "chatchannels` WHERE (ch_name = ?)", Statement.RETURN_GENERATED_KEYS); InsertChannel = conn.prepareStatement("INSERT INTO `" + prefix + "chatchannels` (`ch_name`) VALUES ( ? )", Statement.RETURN_GENERATED_KEYS); SelectPlayer = conn.prepareStatement("SELECT * FROM `" + prefix + "players` WHERE (pl_name = ?)", Statement.RETURN_GENERATED_KEYS); InsertPlayer = conn.prepareStatement("INSERT INTO `" + prefix + "players` (`pl_name`) VALUES ( ? )", Statement.RETURN_GENERATED_KEYS); SelectServer = conn.prepareStatement("SELECT * FROM `" + prefix + "servers` WHERE (ser_name = ?)", Statement.RETURN_GENERATED_KEYS); InsertServer = conn.prepareStatement("INSERT INTO `" + prefix + "servers` (`ser_name`) VALUES ( ? )", Statement.RETURN_GENERATED_KEYS); SelectWorld = conn.prepareStatement("SELECT `wld_name` FROM `" + prefix + "world` WHERE (wld_name = ?)", Statement.RETURN_GENERATED_KEYS); InsertWorld = conn.prepareStatement("INSERT INTO `" + prefix + "world` (`wld_name`) VALUES ( ? )", Statement.RETURN_GENERATED_KEYS); InsertCommand = conn.prepareStatement("INSERT INTO `" + prefix + "commands` (`player_id`, `ser_id`, `date`, `command`) VALUES (?,?,?,?)", Statement.RETURN_GENERATED_KEYS); InsertBlock = conn.prepareStatement("INSERT INTO `" + prefix + "blocks` ( `date`, `player_id`, `world_id`, `blockname`, `blockdata`, `x`, `y`, `z`, `place/break` ) VALUES (?,?,?,?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); } catch (SQLException e) { e.printStackTrace(); } } /** * This is called whenever the plugin runs from startup, it will systematically run through the database, making sure that all tables exist, if it finds a missing table, it will add it. */ protected void createTables( String prefix ) { ResultSet rs; try { //Players EyeSpy.printInfo("Searching for players table"); rs = conn.getMetaData().getTables(null, null, prefix + "players", null); if (!rs.next()) { EyeSpy.printWarning("No 'players' table found, attempting to create one..."); PreparedStatement ps = conn .prepareStatement("CREATE TABLE IF NOT EXISTS `" + prefix + "players` ( " + "`player_id` mediumint unsigned not null auto_increment, " + "`pl_name` varchar(30) not null, " + "primary key (`player_id`));" ); ps.executeUpdate(); ps.close(); EyeSpy.printWarning("'players' table created!"); } else { EyeSpy.printInfo("Table found"); } rs.close(); //Servers EyeSpy.printInfo("Searching for Servers table"); rs = conn.getMetaData().getTables(null, null, prefix + "servers", null); if (!rs.next()) { EyeSpy.printWarning("No 'servers' table found, attempting to create one..."); PreparedStatement ps = conn .prepareStatement("CREATE TABLE IF NOT EXISTS `" + prefix + "servers` ( " + "`ser_id` mediumint unsigned not null auto_increment, " + "`ser_name` varchar(50) not null, " + "primary key (`ser_id`) )"); ps.executeUpdate(); ps.close(); EyeSpy.printWarning("'servers' table created!"); } else { EyeSpy.printInfo("Table found"); } rs.close(); //Chat Channels EyeSpy.printInfo("Searching for Chat Channels table"); rs = conn.getMetaData().getTables(null, null, prefix + "chatchannels", null); if (!rs.next()) { EyeSpy.printWarning("No 'chatchannels' table found, attempting to create one..."); PreparedStatement ps = conn .prepareStatement("CREATE TABLE IF NOT EXISTS `" + prefix + "chatchannels` ( " + "`ch_id` tinyint unsigned not null auto_increment, " + "`ch_name` varchar(30) not null, " + "primary key (`ch_id`));" ); ps.executeUpdate(); ps.close(); EyeSpy.printWarning("'chatchannels' table created!"); } else { EyeSpy.printInfo("Table found"); } rs.close(); /*Blocks Removed from this build EyeSpy.printInfo("Searching for Blocks table"); rs = conn.getMetaData().getTables(null, null, prefix + "blocks", null); if (!rs.next()) { EyeSpy.printWarning("No 'blocks' table found, attempting to create one..."); PreparedStatement ps = conn .prepareStatement("CREATE TABLE IF NOT EXISTS `" + prefix + "blocks` ( " + "`spy_id` int unsigned not null auto_increment, " + "`date` DATETIME not null, " + "`player_id` mediumint unsigned not null, " + "`world_id` tinyint not null, " + "`blockname` mediumint unsigned not null, " + "`blockdata` tinyint unsigned not null, " + "`x` mediumint signed not null, " + "`y` mediumint unsigned not null, " + "`z` mediumint signed not null, " + "`place/break` boolean, " + "primary key (`spy_id`));" ); ps.executeUpdate(); ps.close(); EyeSpy.printWarning("'blocks' table created!"); } else { EyeSpy.printInfo("Table found"); } rs.close();*/ //Chat EyeSpy.printInfo("Searching for Chat table"); rs = conn.getMetaData().getTables(null, null, prefix + "chat", null); if (!rs.next()) { EyeSpy.printWarning("No 'chat' table found, attempting to create one..."); PreparedStatement ps = conn .prepareStatement("CREATE TABLE IF NOT EXISTS `" + prefix + "chat` ( " + "`chat_id` mediumint unsigned not null auto_increment, " + "`player_id` mediumint unsigned not null, " + "`date` int(11) unsigned not null, " + "`ch_id` tinyint unsigned not null, " + "`ser_id` mediumint unsigned not null, " + "`message` text not null, " + "primary key (`chat_id`), " + "foreign key (`player_id`) REFERENCES " + prefix + "players(`player_id`), " + "foreign key (`ser_id`) REFERENCES " + prefix + "servers(`ser_id`), " + "foreign key (`ch_id`) REFERENCES " + prefix + "chatchannels(`ch_id`) );" ); ps.executeUpdate(); ps.close(); EyeSpy.printWarning("'chat' table created!"); } else { EyeSpy.printInfo("Table found"); } rs.close(); /*Chests Removed from this build EyeSpy.printInfo("Searching for Chests table"); rs = conn.getMetaData().getTables(null, null, prefix + "chests", null); if (!rs.next()) { EyeSpy.printWarning("No 'chests' table found, attempting to create one..."); PreparedStatement ps = conn .prepareStatement("CREATE TABLE IF NOT EXISTS `" + prefix + "chests` ( " + "`access_id` mediumint unsigned not null auto_increment, " + "`date` mediumint not null, " + "`player_id` mediumint unsigned not null, " + "`x` mediumint signed not null, " + "`y` mediumint unsigned not null, " + "`z` mediumint signed not null, " + "`blockchanged` mediumint unsigned not null, " + "`quantity` mediumint signed not null, " + "primary key (`access_id`));" ); ps.executeUpdate(); ps.close(); EyeSpy.printWarning("'chest' table created!"); } else { EyeSpy.printInfo("Table found"); } rs.close(); */ //Commands EyeSpy.printInfo("Searching for Commands table"); rs = conn.getMetaData().getTables(null, null, prefix + "commands", null); if (!rs.next()) { EyeSpy.printWarning("No 'command' table found, attempting to create one..."); PreparedStatement ps = conn .prepareStatement("CREATE TABLE IF NOT EXISTS `" + prefix + "commands` ( " + "`cmd_id` mediumint unsigned not null auto_increment, " + "`player_id` mediumint unsigned not null, " + "`ser_id` mediumint unsigned not null, " + "`date` int(11) unsigned not null, " + "`command` varchar(255) not null, " + "primary key (`cmd_id`), " + "foreign key (`player_id`) REFERENCES " + prefix + "players(`player_id`), " + "foreign key (`ser_id`) REFERENCES " + prefix + "servers(`ser_id`) )" ); ps.executeUpdate(); ps.close(); EyeSpy.printWarning("'command' table created!"); } else { EyeSpy.printInfo("Table found"); } rs.close(); /*World Removed from this build EyeSpy.printInfo("Searching for Worlds table"); rs = conn.getMetaData().getTables(null, null, prefix + "world", null); if (!rs.next()) { EyeSpy.printWarning("No 'world' table found, attempting to create one..."); PreparedStatement ps = conn .prepareStatement("CREATE TABLE IF NOT EXISTS `" + prefix + "world` ( " + "`world_id` tinyint unsigned not null auto_increment, " + "`wld_name` varchar(30) not null, " + "primary key (`world_id`));" ); ps.executeUpdate(); ps.close(); EyeSpy.printWarning("'world' table created!"); } else { EyeSpy.printInfo("Table found"); } rs.close(); */ } catch (SQLException e) { e.printStackTrace(); } } /** * Get the runnable stuff sorted. */ - public Runnable maintainConnection = new Runnable() { + public class maintainConnection implements Runnable { public void run() { try { Maintain.executeQuery(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } EyeSpy.printInfo("EyeSpy has checked in with database"); } }; /** * Adds the new block events found in the uk.co.m4numbers.EyeSpy.Listeners.BlockListener class. Each one fulfils the requirements for a standard SQL string. * @param name The name of the entity that triggered the block change * @param type The block that was changed, in ID form. This will be translated within the website * @param data Any additional data that the block possesses, such as direction * @param broken The state of the block, 0 is broken, 1 is placed, 2 is ignited, 3 is moved * @param x X Co-ordinate of the block * @param y Y Co-ordinate of the block * @param z Z Co-ordinate of the block * @param world The world that the block resides in * @throws e.printStackTrace should the SQL string fail * @deprecated For this build */ public static void addNewBlock(String name, int type, byte data, byte broken, int x, int y, int z, String world) { try { InsertBlock.setLong( 1, ArgProcessing.getDateTime() ); InsertBlock.setInt( 2, playerExists(name) ); InsertBlock.setInt( 3, worldExists(world) ); InsertBlock.setInt( 4, type ); InsertBlock.setInt( 5, data ); InsertBlock.setInt( 6, x ); InsertBlock.setInt( 7, y ); InsertBlock.setInt( 8, z ); InsertBlock.setInt( 9, broken ); InsertBlock.executeUpdate(); InsertBlock.clearParameters(); EyeSpy.printInfo("Block Added!"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Adds any chatter that occurs on the server into the database. This requires that the server is running HeroChat * @param name The name of the player sending the chatter * @param ch_name The name of the channel the chatter is occurring within * @param Server The name of the server that everything is being sent on * @param Message The actual chatter * @throws e.printStackTrace If the command fails */ public static void addNewChat(String name, String ch_name, String Server, String Message) { try { InsertChat.setInt( 1, playerExists(name) ); InsertChat.setInt( 2, channelExists(ch_name) ); InsertChat.setInt( 3, ServerExists(Server) ); InsertChat.setLong( 4, ArgProcessing.getDateTime() ); InsertChat.setString( 5, Message ); InsertChat.executeUpdate(); InsertChat.clearParameters(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Adds any commands used on the server into the database. * @param name This is the name of the entity sending the command * @param Server The name of the server that the commands are being executed on * @param Message This is the command itself * @throws e.printStackTrace If the command should fail */ public static void addNewCommand(String name, String Server, String Message) { try { InsertCommand.setInt( 1, playerExists(name) ); InsertCommand.setInt(2, ServerExists( Server ) ); InsertCommand.setLong( 3, ArgProcessing.getDateTime() ); InsertCommand.setString( 4, Message ); InsertCommand.executeUpdate(); InsertCommand.clearParameters(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Checks within the chatchannels database for any existing channels of that name. If it doesn't find it, it will add it to the table, and return the id no matter what * @param ch_name The name of the channel that is being checked * @return chId This is the ID of the channel in the chatchannel table, passed back to the chat table * @throws e.printStackTrace If the command should fail */ public static int channelExists(String ch_name) { ResultSet rs = null; int chId = 0; try { SelectChannel.setString(1, ch_name); rs = SelectChannel.executeQuery(); if (!rs.next()) { InsertChannel.setString(1, ch_name); InsertChannel.executeUpdate(); InsertChannel.clearParameters(); } rs = SelectChannel.executeQuery(); rs.first(); SelectChannel.clearParameters(); chId = rs.getInt("ch_id"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return chId; } /** * Checks within the players table for any existing players that match the parameter. If there are no matching names, the player will be added and their ID returned no matter what. * @param name This is the players name which is being checked * @return plId This is the ID of the player that was checked * @throws e.printStackTrace If the command should fail */ public static int playerExists(String name) { ResultSet rs = null; int plId = 0; try { SelectPlayer.setString(1, name); rs = SelectPlayer.executeQuery(); if (!rs.next()) { InsertPlayer.setString(1, name); InsertPlayer.executeUpdate(); InsertPlayer.clearParameters(); } rs = SelectPlayer.executeQuery(); rs.first(); SelectPlayer.clearParameters(); plId = rs.getInt("player_id"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return plId; } /** * Lets look at the servers we have available and give the log a server reference. * @param Server The server * @return serId : The ID number of the server that we're working with */ public static int ServerExists(String Server) { ResultSet rs = null; int serId = 0; try { SelectServer.setString(1, Server); rs = SelectServer.executeQuery(); if (!rs.next()) { InsertServer.setString(1, Server); InsertServer.executeUpdate(); InsertServer.clearParameters(); } rs = SelectServer.executeQuery(); rs.first(); SelectServer.clearParameters(); serId = rs.getInt("ser_id"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return serId; } /** * This checks the worlds table for any existing worlds with that name. If no worlds are found which match the parameter, a new row will be inserted into the table, the ID will be returned no matter what. * @param world This is the name of the world that is to be checked * @return wlId This is the ID of the world that was checked * @throws e.printStackTrace If the command should fail */ public static int worldExists(String world) { ResultSet rs = null; int wlId = 0; try { SelectWorld.setString(1, world); rs = SelectWorld.executeQuery(); if (!rs.next()) { InsertWorld.setString(1, world); InsertWorld.executeUpdate(); InsertWorld.clearParameters(); EyeSpy.printInfo(world + " added to the worlds table"); } rs = SelectWorld.executeQuery(); rs.first(); SelectWorld.clearParameters(); wlId = rs.getInt("world_id"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return wlId; } }
false
false
null
null
diff --git a/src/java/org/apache/hadoop/fs/FsShell.java b/src/java/org/apache/hadoop/fs/FsShell.java index 9676c7b494..6f7d6b059e 100644 --- a/src/java/org/apache/hadoop/fs/FsShell.java +++ b/src/java/org/apache/hadoop/fs/FsShell.java @@ -1,2010 +1,2012 @@ /** * 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.fs; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.text.SimpleDateFormat; import java.util.*; import java.util.zip.GZIPInputStream; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.shell.CommandFormat; import org.apache.hadoop.fs.shell.Count; import org.apache.hadoop.io.DataInputBuffer; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.ipc.RPC; import org.apache.hadoop.ipc.RemoteException; import org.apache.hadoop.util.ReflectionUtils; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.apache.hadoop.util.StringUtils; /** Provide command line access to a FileSystem. */ public class FsShell extends Configured implements Tool { protected FileSystem fs; private Trash trash; public static final SimpleDateFormat dateForm = new SimpleDateFormat("yyyy-MM-dd HH:mm"); protected static final SimpleDateFormat modifFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); static final int BORDER = 2; static { modifFmt.setTimeZone(TimeZone.getTimeZone("UTC")); } static final String SETREP_SHORT_USAGE="-setrep [-R] [-w] <rep> <path/file>"; static final String GET_SHORT_USAGE = "-get [-ignoreCrc] [-crc] <src> <localdst>"; static final String COPYTOLOCAL_SHORT_USAGE = GET_SHORT_USAGE.replace( "-get", "-copyToLocal"); static final String TAIL_USAGE="-tail [-f] <file>"; static final String DU_USAGE="-du [-s] [-h] <paths...>"; /** */ public FsShell() { this(null); } public FsShell(Configuration conf) { super(conf); fs = null; trash = null; } protected void init() throws IOException { getConf().setQuietMode(true); if (this.fs == null) { this.fs = FileSystem.get(getConf()); } if (this.trash == null) { this.trash = new Trash(getConf()); } } /** * Copies from stdin to the indicated file. */ private void copyFromStdin(Path dst, FileSystem dstFs) throws IOException { if (dstFs.isDirectory(dst)) { throw new IOException("When source is stdin, destination must be a file."); } if (dstFs.exists(dst)) { throw new IOException("Target " + dst.toString() + " already exists."); } FSDataOutputStream out = dstFs.create(dst); try { IOUtils.copyBytes(System.in, out, getConf(), false); } finally { out.close(); } } /** * Print from src to stdout. */ private void printToStdout(InputStream in) throws IOException { try { IOUtils.copyBytes(in, System.out, getConf(), false); } finally { in.close(); } } /** * Add local files to the indicated FileSystem name. src is kept. */ void copyFromLocal(Path[] srcs, String dstf) throws IOException { Path dstPath = new Path(dstf); FileSystem dstFs = dstPath.getFileSystem(getConf()); if (srcs.length == 1 && srcs[0].toString().equals("-")) copyFromStdin(dstPath, dstFs); else dstFs.copyFromLocalFile(false, false, srcs, dstPath); } /** * Add local files to the indicated FileSystem name. src is removed. */ void moveFromLocal(Path[] srcs, String dstf) throws IOException { Path dstPath = new Path(dstf); FileSystem dstFs = dstPath.getFileSystem(getConf()); dstFs.moveFromLocalFile(srcs, dstPath); } /** * Add a local file to the indicated FileSystem name. src is removed. */ void moveFromLocal(Path src, String dstf) throws IOException { moveFromLocal((new Path[]{src}), dstf); } /** * Obtain the indicated files that match the file pattern <i>srcf</i> * and copy them to the local name. srcf is kept. * When copying multiple files, the destination must be a directory. * Otherwise, IOException is thrown. * @param argv: arguments * @param pos: Ignore everything before argv[pos] * @exception: IOException * @see org.apache.hadoop.fs.FileSystem.globStatus */ void copyToLocal(String[]argv, int pos) throws IOException { CommandFormat cf = new CommandFormat("copyToLocal", 2,2,"crc","ignoreCrc"); String srcstr = null; String dststr = null; try { List<String> parameters = cf.parse(argv, pos); srcstr = parameters.get(0); dststr = parameters.get(1); } catch(IllegalArgumentException iae) { System.err.println("Usage: java FsShell " + GET_SHORT_USAGE); throw iae; } boolean copyCrc = cf.getOpt("crc"); final boolean verifyChecksum = !cf.getOpt("ignoreCrc"); if (dststr.equals("-")) { if (copyCrc) { System.err.println("-crc option is not valid when destination is stdout."); } cat(srcstr, verifyChecksum); } else { File dst = new File(dststr); Path srcpath = new Path(srcstr); FileSystem srcFS = getSrcFileSystem(srcpath, verifyChecksum); if (copyCrc && !(srcFS instanceof ChecksumFileSystem)) { System.err.println("-crc option is not valid when source file system " + "does not have crc files. Automatically turn the option off."); copyCrc = false; } FileStatus[] srcs = srcFS.globStatus(srcpath); boolean dstIsDir = dst.isDirectory(); if (srcs.length > 1 && !dstIsDir) { throw new IOException("When copying multiple files, " + "destination should be a directory."); } for (FileStatus status : srcs) { Path p = status.getPath(); File f = dstIsDir? new File(dst, p.getName()): dst; copyToLocal(srcFS, status, f, copyCrc); } } } /** * Return the {@link FileSystem} specified by src and the conf. * It the {@link FileSystem} supports checksum, set verifyChecksum. */ private FileSystem getSrcFileSystem(Path src, boolean verifyChecksum ) throws IOException { FileSystem srcFs = src.getFileSystem(getConf()); srcFs.setVerifyChecksum(verifyChecksum); return srcFs; } /** * The prefix for the tmp file used in copyToLocal. * It must be at least three characters long, required by * {@link java.io.File#createTempFile(String, String, File)}. */ static final String COPYTOLOCAL_PREFIX = "_copyToLocal_"; /** * Copy a source file from a given file system to local destination. * @param srcFS source file system * @param src source path * @param dst destination * @param copyCrc copy CRC files? * @exception IOException If some IO failed */ private void copyToLocal(final FileSystem srcFS, final FileStatus srcStatus, final File dst, final boolean copyCrc) throws IOException { /* Keep the structure similar to ChecksumFileSystem.copyToLocal(). * Ideal these two should just invoke FileUtil.copy() and not repeat * recursion here. Of course, copy() should support two more options : * copyCrc and useTmpFile (may be useTmpFile need not be an option). */ Path src = srcStatus.getPath(); if (!srcStatus.isDir()) { if (dst.exists()) { // match the error message in FileUtil.checkDest(): throw new IOException("Target " + dst + " already exists"); } // use absolute name so that tmp file is always created under dest dir File tmp = FileUtil.createLocalTempFile(dst.getAbsoluteFile(), COPYTOLOCAL_PREFIX, true); if (!FileUtil.copy(srcFS, src, tmp, false, srcFS.getConf())) { throw new IOException("Failed to copy " + src + " to " + dst); } if (!tmp.renameTo(dst)) { throw new IOException("Failed to rename tmp file " + tmp + " to local destination \"" + dst + "\"."); } if (copyCrc) { if (!(srcFS instanceof ChecksumFileSystem)) { throw new IOException("Source file system does not have crc files"); } ChecksumFileSystem csfs = (ChecksumFileSystem) srcFS; File dstcs = FileSystem.getLocal(srcFS.getConf()) .pathToFile(csfs.getChecksumFile(new Path(dst.getCanonicalPath()))); FileSystem fs = csfs.getRawFileSystem(); FileStatus status = csfs.getFileStatus(csfs.getChecksumFile(src)); copyToLocal(fs, status, dstcs, false); } } else { // once FileUtil.copy() supports tmp file, we don't need to mkdirs(). if (!dst.mkdirs()) { throw new IOException("Failed to create local destination \"" + dst + "\"."); } for(FileStatus status : srcFS.listStatus(src)) { copyToLocal(srcFS, status, new File(dst, status.getPath().getName()), copyCrc); } } } /** * Get all the files in the directories that match the source file * pattern and merge and sort them to only one file on local fs * srcf is kept. * @param srcf: a file pattern specifying source files * @param dstf: a destination local file/directory * @exception: IOException * @see org.apache.hadoop.fs.FileSystem.globStatus */ void copyMergeToLocal(String srcf, Path dst) throws IOException { copyMergeToLocal(srcf, dst, false); } /** * Get all the files in the directories that match the source file pattern * and merge and sort them to only one file on local fs * srcf is kept. * * Also adds a string between the files (useful for adding \n * to a text file) * @param srcf: a file pattern specifying source files * @param dstf: a destination local file/directory * @param endline: if an end of line character is added to a text file * @exception: IOException * @see org.apache.hadoop.fs.FileSystem.globStatus */ void copyMergeToLocal(String srcf, Path dst, boolean endline) throws IOException { Path srcPath = new Path(srcf); FileSystem srcFs = srcPath.getFileSystem(getConf()); Path [] srcs = FileUtil.stat2Paths(srcFs.globStatus(srcPath), srcPath); for(int i=0; i<srcs.length; i++) { if (endline) { FileUtil.copyMerge(srcFs, srcs[i], FileSystem.getLocal(getConf()), dst, false, getConf(), "\n"); } else { FileUtil.copyMerge(srcFs, srcs[i], FileSystem.getLocal(getConf()), dst, false, getConf(), null); } } } /** * Obtain the indicated file and copy to the local name. * srcf is removed. */ void moveToLocal(String srcf, Path dst) throws IOException { System.err.println("Option '-moveToLocal' is not implemented yet."); } /** * Fetch all files that match the file pattern <i>srcf</i> and display * their content on stdout. * @param srcf: a file pattern specifying source files * @exception: IOException * @see org.apache.hadoop.fs.FileSystem.globStatus */ void cat(String src, boolean verifyChecksum) throws IOException { //cat behavior in Linux // [~/1207]$ ls ?.txt // x.txt z.txt // [~/1207]$ cat x.txt y.txt z.txt // xxx // cat: y.txt: No such file or directory // zzz Path srcPattern = new Path(src); new DelayedExceptionThrowing() { @Override void process(Path p, FileSystem srcFs) throws IOException { if (srcFs.getFileStatus(p).isDir()) { throw new IOException("Source must be a file."); } printToStdout(srcFs.open(p)); } }.globAndProcess(srcPattern, getSrcFileSystem(srcPattern, verifyChecksum)); } private class TextRecordInputStream extends InputStream { SequenceFile.Reader r; WritableComparable key; Writable val; DataInputBuffer inbuf; DataOutputBuffer outbuf; public TextRecordInputStream(FileStatus f) throws IOException { - r = new SequenceFile.Reader(fs, f.getPath(), getConf()); - key = ReflectionUtils.newInstance(r.getKeyClass().asSubclass(WritableComparable.class), - getConf()); - val = ReflectionUtils.newInstance(r.getValueClass().asSubclass(Writable.class), - getConf()); + final Path fpath = f.getPath(); + final Configuration lconf = getConf(); + r = new SequenceFile.Reader(fpath.getFileSystem(lconf), fpath, lconf); + key = ReflectionUtils.newInstance( + r.getKeyClass().asSubclass(WritableComparable.class), lconf); + val = ReflectionUtils.newInstance( + r.getValueClass().asSubclass(Writable.class), lconf); inbuf = new DataInputBuffer(); outbuf = new DataOutputBuffer(); } public int read() throws IOException { int ret; if (null == inbuf || -1 == (ret = inbuf.read())) { if (!r.next(key, val)) { return -1; } byte[] tmp = key.toString().getBytes(); outbuf.write(tmp, 0, tmp.length); outbuf.write('\t'); tmp = val.toString().getBytes(); outbuf.write(tmp, 0, tmp.length); outbuf.write('\n'); inbuf.reset(outbuf.getData(), outbuf.getLength()); outbuf.reset(); ret = inbuf.read(); } return ret; } } private InputStream forMagic(Path p, FileSystem srcFs) throws IOException { FSDataInputStream i = srcFs.open(p); switch(i.readShort()) { case 0x1f8b: // RFC 1952 i.seek(0); return new GZIPInputStream(i); case 0x5345: // 'S' 'E' if (i.readByte() == 'Q') { i.close(); return new TextRecordInputStream(srcFs.getFileStatus(p)); } break; } i.seek(0); return i; } void text(String srcf) throws IOException { Path srcPattern = new Path(srcf); new DelayedExceptionThrowing() { @Override void process(Path p, FileSystem srcFs) throws IOException { if (srcFs.isDirectory(p)) { throw new IOException("Source must be a file."); } printToStdout(forMagic(p, srcFs)); } }.globAndProcess(srcPattern, srcPattern.getFileSystem(getConf())); } /** * Parse the incoming command string * @param cmd * @param pos ignore anything before this pos in cmd * @throws IOException */ private void setReplication(String[] cmd, int pos) throws IOException { CommandFormat c = new CommandFormat("setrep", 2, 2, "R", "w"); String dst = null; short rep = 0; try { List<String> parameters = c.parse(cmd, pos); rep = Short.parseShort(parameters.get(0)); dst = parameters.get(1); } catch (NumberFormatException nfe) { System.err.println("Illegal replication, a positive integer expected"); throw nfe; } catch(IllegalArgumentException iae) { System.err.println("Usage: java FsShell " + SETREP_SHORT_USAGE); throw iae; } if (rep < 1) { System.err.println("Cannot set replication to: " + rep); throw new IllegalArgumentException("replication must be >= 1"); } List<Path> waitList = c.getOpt("w")? new ArrayList<Path>(): null; setReplication(rep, dst, c.getOpt("R"), waitList); if (waitList != null) { waitForReplication(waitList, rep); } } /** * Wait for all files in waitList to have replication number equal to rep. * @param waitList The files are waited for. * @param rep The new replication number. * @throws IOException IOException */ void waitForReplication(List<Path> waitList, int rep) throws IOException { for(Path f : waitList) { System.out.print("Waiting for " + f + " ..."); System.out.flush(); boolean printWarning = false; FileStatus status = fs.getFileStatus(f); long len = status.getLen(); for(boolean done = false; !done; ) { BlockLocation[] locations = fs.getFileBlockLocations(status, 0, len); int i = 0; for(; i < locations.length && locations[i].getHosts().length == rep; i++) if (!printWarning && locations[i].getHosts().length > rep) { System.out.println("\nWARNING: the waiting time may be long for " + "DECREASING the number of replication."); printWarning = true; } done = i == locations.length; if (!done) { System.out.print("."); System.out.flush(); try {Thread.sleep(10000);} catch (InterruptedException e) {} } } System.out.println(" done"); } } /** * Set the replication for files that match file pattern <i>srcf</i> * if it's a directory and recursive is true, * set replication for all the subdirs and those files too. * @param newRep new replication factor * @param srcf a file pattern specifying source files * @param recursive if need to set replication factor for files in subdirs * @throws IOException * @see org.apache.hadoop.fs.FileSystem#globStatus(Path) */ void setReplication(short newRep, String srcf, boolean recursive, List<Path> waitingList) throws IOException { Path srcPath = new Path(srcf); FileSystem srcFs = srcPath.getFileSystem(getConf()); Path[] srcs = FileUtil.stat2Paths(srcFs.globStatus(srcPath), srcPath); for(int i=0; i<srcs.length; i++) { setReplication(newRep, srcFs, srcs[i], recursive, waitingList); } } private void setReplication(short newRep, FileSystem srcFs, Path src, boolean recursive, List<Path> waitingList) throws IOException { if (!srcFs.getFileStatus(src).isDir()) { setFileReplication(src, srcFs, newRep, waitingList); return; } FileStatus items[] = srcFs.listStatus(src); try { items = srcFs.listStatus(src); } catch (FileNotFoundException fnfe) { throw new IOException("Could not get listing for " + src); } for (int i = 0; i < items.length; i++) { if (!items[i].isDir()) { setFileReplication(items[i].getPath(), srcFs, newRep, waitingList); } else if (recursive) { setReplication(newRep, srcFs, items[i].getPath(), recursive, waitingList); } } } /** * Actually set the replication for this file * If it fails either throw IOException or print an error msg * @param file: a file/directory * @param newRep: new replication factor * @throws IOException */ private void setFileReplication(Path file, FileSystem srcFs, short newRep, List<Path> waitList) throws IOException { if (srcFs.setReplication(file, newRep)) { if (waitList != null) { waitList.add(file); } System.out.println("Replication " + newRep + " set: " + file); } else { System.err.println("Could not set replication for: " + file); } } /** * Get a listing of all files in that match the file pattern <i>srcf</i>. * @param srcf a file pattern specifying source files * @param recursive if need to list files in subdirs * @throws IOException * @see org.apache.hadoop.fs.FileSystem#globStatus(Path) */ private int ls(String srcf, boolean recursive) throws IOException { Path srcPath = new Path(srcf); FileSystem srcFs = srcPath.getFileSystem(this.getConf()); FileStatus[] srcs = srcFs.globStatus(srcPath); if (srcs==null || srcs.length==0) { throw new FileNotFoundException("Cannot access " + srcf + ": No such file or directory."); } boolean printHeader = (srcs.length == 1) ? true: false; int numOfErrors = 0; for(int i=0; i<srcs.length; i++) { numOfErrors += ls(srcs[i], srcFs, recursive, printHeader); } return numOfErrors == 0 ? 0 : -1; } /* list all files under the directory <i>src</i> * ideally we should provide "-l" option, that lists like "ls -l". */ private int ls(FileStatus src, FileSystem srcFs, boolean recursive, boolean printHeader) throws IOException { final String cmd = recursive? "lsr": "ls"; final FileStatus[] items = shellListStatus(cmd, srcFs, src); if (items == null) { return 1; } else { int numOfErrors = 0; if (!recursive && printHeader) { if (items.length != 0) { System.out.println("Found " + items.length + " items"); } } int maxReplication = 3, maxLen = 10, maxOwner = 0,maxGroup = 0; for(int i = 0; i < items.length; i++) { FileStatus stat = items[i]; int replication = String.valueOf(stat.getReplication()).length(); int len = String.valueOf(stat.getLen()).length(); int owner = String.valueOf(stat.getOwner()).length(); int group = String.valueOf(stat.getGroup()).length(); if (replication > maxReplication) maxReplication = replication; if (len > maxLen) maxLen = len; if (owner > maxOwner) maxOwner = owner; if (group > maxGroup) maxGroup = group; } for (int i = 0; i < items.length; i++) { FileStatus stat = items[i]; Path cur = stat.getPath(); String mdate = dateForm.format(new Date(stat.getModificationTime())); System.out.print((stat.isDir() ? "d" : "-") + stat.getPermission() + " "); System.out.printf("%"+ maxReplication + "s ", (!stat.isDir() ? stat.getReplication() : "-")); if (maxOwner > 0) System.out.printf("%-"+ maxOwner + "s ", stat.getOwner()); if (maxGroup > 0) System.out.printf("%-"+ maxGroup + "s ", stat.getGroup()); System.out.printf("%"+ maxLen + "d ", stat.getLen()); System.out.print(mdate + " "); System.out.println(cur.toUri().getPath()); if (recursive && stat.isDir()) { numOfErrors += ls(stat,srcFs, recursive, printHeader); } } return numOfErrors; } } /** * Show the size of a partition in the filesystem that contains * the specified <i>path</i>. * @param path a path specifying the source partition. null means /. * @throws IOException */ void df(String path) throws IOException { if (path == null) path = "/"; final Path srcPath = new Path(path); final FileSystem srcFs = srcPath.getFileSystem(getConf()); if (! srcFs.exists(srcPath)) { throw new FileNotFoundException("Cannot access "+srcPath.toString()); } final FsStatus stats = srcFs.getStatus(srcPath); final int PercentUsed = (int)(100.0f * (float)stats.getUsed() / (float)stats.getCapacity()); System.out.println("Filesystem\t\tSize\tUsed\tAvail\tUse%"); System.out.printf("%s\t\t%d\t%d\t%d\t%d%%\n", path, stats.getCapacity(), stats.getUsed(), stats.getRemaining(), PercentUsed); } /** * Show the size of all files that match the file pattern <i>src</i> * @param cmd * @param pos ignore anything before this pos in cmd * @throws IOException * @see org.apache.hadoop.fs.FileSystem#globStatus(Path) */ void du(String[] cmd, int pos) throws IOException { CommandFormat c = new CommandFormat( "du", 0, Integer.MAX_VALUE, "h", "s"); List<String> params; try { params = c.parse(cmd, pos); } catch (IllegalArgumentException iae) { System.err.println("Usage: java FsShell " + DU_USAGE); throw iae; } boolean humanReadable = c.getOpt("h"); boolean summary = c.getOpt("s"); // Default to cwd if (params.isEmpty()) { params.add("."); } List<UsagePair> usages = new ArrayList<UsagePair>(); for (String src : params) { Path srcPath = new Path(src); FileSystem srcFs = srcPath.getFileSystem(getConf()); FileStatus globStatus[] = srcFs.globStatus(srcPath); FileStatus statusToPrint[]; if (summary) { statusToPrint = globStatus; } else { Path statPaths[] = FileUtil.stat2Paths(globStatus, srcPath); try { statusToPrint = srcFs.listStatus(statPaths); } catch(FileNotFoundException fnfe) { statusToPrint = null; } } if ((statusToPrint == null) || ((statusToPrint.length == 0) && (!srcFs.exists(srcPath)))){ throw new FileNotFoundException("Cannot access " + src + ": No such file or directory."); } if (!summary) { System.out.println("Found " + statusToPrint.length + " items"); } for (FileStatus stat : statusToPrint) { long length; if (summary || stat.isDir()) { length = srcFs.getContentSummary(stat.getPath()).getLength(); } else { length = stat.getLen(); } usages.add(new UsagePair(String.valueOf(stat.getPath()), length)); } } printUsageSummary(usages, humanReadable); } /** * Show the summary disk usage of each dir/file * that matches the file pattern <i>src</i> * @param cmd * @param pos ignore anything before this pos in cmd * @throws IOException * @see org.apache.hadoop.fs.FileSystem#globStatus(Path) */ void dus(String[] cmd, int pos) throws IOException { String newcmd[] = new String[cmd.length + 1]; System.arraycopy(cmd, 0, newcmd, 0, cmd.length); newcmd[cmd.length] = "-s"; du(newcmd, pos); } private void printUsageSummary(List<UsagePair> usages, boolean humanReadable) { int maxColumnWidth = 0; for (UsagePair usage : usages) { String toPrint = humanReadable ? StringUtils.humanReadableInt(usage.bytes) : String.valueOf(usage.bytes); if (toPrint.length() > maxColumnWidth) { maxColumnWidth = toPrint.length(); } } for (UsagePair usage : usages) { String toPrint = humanReadable ? StringUtils.humanReadableInt(usage.bytes) : String.valueOf(usage.bytes); System.out.printf("%-"+ (maxColumnWidth + BORDER) +"s", toPrint); System.out.println(usage.path); } } /** * Create the given dir */ void mkdir(String src) throws IOException { Path f = new Path(src); FileSystem srcFs = f.getFileSystem(getConf()); FileStatus fstatus = null; try { fstatus = srcFs.getFileStatus(f); if (fstatus.isDir()) { throw new IOException("cannot create directory " + src + ": File exists"); } else { throw new IOException(src + " exists but " + "is not a directory"); } } catch(FileNotFoundException e) { if (!srcFs.mkdirs(f)) { throw new IOException("failed to create " + src); } } } /** * (Re)create zero-length file at the specified path. * This will be replaced by a more UNIX-like touch when files may be * modified. */ void touchz(String src) throws IOException { Path f = new Path(src); FileSystem srcFs = f.getFileSystem(getConf()); FileStatus st; if (srcFs.exists(f)) { st = srcFs.getFileStatus(f); if (st.isDir()) { // TODO: handle this throw new IOException(src + " is a directory"); } else if (st.getLen() != 0) throw new IOException(src + " must be a zero-length file"); } FSDataOutputStream out = srcFs.create(f); out.close(); } /** * Check file types. */ int test(String argv[], int i) throws IOException { if (!argv[i].startsWith("-") || argv[i].length() > 2) throw new IOException("Not a flag: " + argv[i]); char flag = argv[i].toCharArray()[1]; Path f = new Path(argv[++i]); FileSystem srcFs = f.getFileSystem(getConf()); switch(flag) { case 'e': return srcFs.exists(f) ? 0 : 1; case 'z': return srcFs.getFileStatus(f).getLen() == 0 ? 0 : 1; case 'd': return srcFs.getFileStatus(f).isDir() ? 0 : 1; default: throw new IOException("Unknown flag: " + flag); } } /** * Print statistics about path in specified format. * Format sequences: * %b: Size of file in blocks * %n: Filename * %o: Block size * %r: replication * %y: UTC date as &quot;yyyy-MM-dd HH:mm:ss&quot; * %Y: Milliseconds since January 1, 1970 UTC */ void stat(char[] fmt, String src) throws IOException { Path srcPath = new Path(src); FileSystem srcFs = srcPath.getFileSystem(getConf()); FileStatus glob[] = srcFs.globStatus(srcPath); if (null == glob) throw new IOException("cannot stat `" + src + "': No such file or directory"); for (FileStatus f : glob) { StringBuilder buf = new StringBuilder(); for (int i = 0; i < fmt.length; ++i) { if (fmt[i] != '%') { buf.append(fmt[i]); } else { if (i + 1 == fmt.length) break; switch(fmt[++i]) { case 'b': buf.append(f.getLen()); break; case 'F': buf.append(f.isDir() ? "directory" : "regular file"); break; case 'n': buf.append(f.getPath().getName()); break; case 'o': buf.append(f.getBlockSize()); break; case 'r': buf.append(f.getReplication()); break; case 'y': buf.append(modifFmt.format(new Date(f.getModificationTime()))); break; case 'Y': buf.append(f.getModificationTime()); break; default: buf.append(fmt[i]); break; } } } System.out.println(buf.toString()); } } /** * Move files that match the file pattern <i>srcf</i> * to a destination file. * When moving mutiple files, the destination must be a directory. * Otherwise, IOException is thrown. * @param srcf a file pattern specifying source files * @param dstf a destination local file/directory * @throws IOException * @see org.apache.hadoop.fs.FileSystem#globStatus(Path) */ void rename(String srcf, String dstf) throws IOException { Path srcPath = new Path(srcf); Path dstPath = new Path(dstf); FileSystem fs = srcPath.getFileSystem(getConf()); URI srcURI = fs.getUri(); URI dstURI = dstPath.getFileSystem(getConf()).getUri(); if (srcURI.compareTo(dstURI) != 0) { throw new IOException("src and destination filesystems do not match."); } Path[] srcs = FileUtil.stat2Paths(fs.globStatus(srcPath), srcPath); Path dst = new Path(dstf); if (srcs.length > 1 && !fs.isDirectory(dst)) { throw new IOException("When moving multiple files, " + "destination should be a directory."); } for(int i=0; i<srcs.length; i++) { if (!fs.rename(srcs[i], dst)) { FileStatus srcFstatus = null; FileStatus dstFstatus = null; try { srcFstatus = fs.getFileStatus(srcs[i]); } catch(FileNotFoundException e) { throw new FileNotFoundException(srcs[i] + ": No such file or directory"); } try { dstFstatus = fs.getFileStatus(dst); } catch(IOException e) { } if((srcFstatus!= null) && (dstFstatus!= null)) { if (srcFstatus.isDir() && !dstFstatus.isDir()) { throw new IOException("cannot overwrite non directory " + dst + " with directory " + srcs[i]); } } throw new IOException("Failed to rename " + srcs[i] + " to " + dst); } } } /** * Move/rename file(s) to a destination file. Multiple source * files can be specified. The destination is the last element of * the argvp[] array. * If multiple source files are specified, then the destination * must be a directory. Otherwise, IOException is thrown. * @exception: IOException */ private int rename(String argv[], Configuration conf) throws IOException { int i = 0; int exitCode = 0; String cmd = argv[i++]; String dest = argv[argv.length-1]; // // If the user has specified multiple source files, then // the destination has to be a directory // if (argv.length > 3) { Path dst = new Path(dest); FileSystem dstFs = dst.getFileSystem(getConf()); if (!dstFs.isDirectory(dst)) { throw new IOException("When moving multiple files, " + "destination " + dest + " should be a directory."); } } // // for each source file, issue the rename // for (; i < argv.length - 1; i++) { try { // // issue the rename to the fs // rename(argv[i], dest); } catch (RemoteException e) { // // This is a error returned by hadoop server. Print // out the first line of the error mesage. // exitCode = -1; try { String[] content; content = e.getLocalizedMessage().split("\n"); System.err.println(cmd.substring(1) + ": " + content[0]); } catch (Exception ex) { System.err.println(cmd.substring(1) + ": " + ex.getLocalizedMessage()); } } catch (IOException e) { // // IO exception encountered locally. // exitCode = -1; System.err.println(cmd.substring(1) + ": " + e.getLocalizedMessage()); } } return exitCode; } /** * Copy files that match the file pattern <i>srcf</i> * to a destination file. * When copying mutiple files, the destination must be a directory. * Otherwise, IOException is thrown. * @param srcf a file pattern specifying source files * @param dstf a destination local file/directory * @throws IOException * @see org.apache.hadoop.fs.FileSystem#globStatus(Path) */ void copy(String srcf, String dstf, Configuration conf) throws IOException { Path srcPath = new Path(srcf); FileSystem srcFs = srcPath.getFileSystem(getConf()); Path dstPath = new Path(dstf); FileSystem dstFs = dstPath.getFileSystem(getConf()); Path [] srcs = FileUtil.stat2Paths(srcFs.globStatus(srcPath), srcPath); if (srcs.length > 1 && !dstFs.isDirectory(dstPath)) { throw new IOException("When copying multiple files, " + "destination should be a directory."); } for(int i=0; i<srcs.length; i++) { FileUtil.copy(srcFs, srcs[i], dstFs, dstPath, false, conf); } } /** * Copy file(s) to a destination file. Multiple source * files can be specified. The destination is the last element of * the argvp[] array. * If multiple source files are specified, then the destination * must be a directory. Otherwise, IOException is thrown. * @exception: IOException */ private int copy(String argv[], Configuration conf) throws IOException { int i = 0; int exitCode = 0; String cmd = argv[i++]; String dest = argv[argv.length-1]; // // If the user has specified multiple source files, then // the destination has to be a directory // if (argv.length > 3) { Path dst = new Path(dest); if (!fs.isDirectory(dst)) { throw new IOException("When copying multiple files, " + "destination " + dest + " should be a directory."); } } // // for each source file, issue the copy // for (; i < argv.length - 1; i++) { try { // // issue the copy to the fs // copy(argv[i], dest, conf); } catch (RemoteException e) { // // This is a error returned by hadoop server. Print // out the first line of the error mesage. // exitCode = -1; try { String[] content; content = e.getLocalizedMessage().split("\n"); System.err.println(cmd.substring(1) + ": " + content[0]); } catch (Exception ex) { System.err.println(cmd.substring(1) + ": " + ex.getLocalizedMessage()); } } catch (IOException e) { // // IO exception encountered locally. // exitCode = -1; System.err.println(cmd.substring(1) + ": " + e.getLocalizedMessage()); } } return exitCode; } /** * Delete all files that match the file pattern <i>srcf</i>. * @param srcf a file pattern specifying source files * @param recursive if need to delete subdirs * @param skipTrash Should we skip the trash, if it's enabled? * @throws IOException * @see org.apache.hadoop.fs.FileSystem#globStatus(Path) */ void delete(String srcf, final boolean recursive, final boolean skipTrash) throws IOException { //rm behavior in Linux // [~/1207]$ ls ?.txt // x.txt z.txt // [~/1207]$ rm x.txt y.txt z.txt // rm: cannot remove `y.txt': No such file or directory Path srcPattern = new Path(srcf); new DelayedExceptionThrowing() { @Override void process(Path p, FileSystem srcFs) throws IOException { delete(p, srcFs, recursive, skipTrash); } }.globAndProcess(srcPattern, srcPattern.getFileSystem(getConf())); } /* delete a file */ private void delete(Path src, FileSystem srcFs, boolean recursive, boolean skipTrash) throws IOException { FileStatus fs = null; try { fs = srcFs.getFileStatus(src); } catch (FileNotFoundException fnfe) { // Have to re-throw so that console output is as expected throw new FileNotFoundException("cannot remove " + src + ": No such file or directory."); } if (fs.isDir() && !recursive) { throw new IOException("Cannot remove directory \"" + src + "\", use -rmr instead"); } if(!skipTrash) { try { Trash trashTmp = new Trash(srcFs, getConf()); if (trashTmp.moveToTrash(src)) { System.out.println("Moved to trash: " + src); return; } } catch (IOException e) { Exception cause = (Exception) e.getCause(); String msg = ""; if(cause != null) { msg = cause.getLocalizedMessage(); } System.err.println("Problem with Trash." + msg +". Consider using -skipTrash option"); throw e; } } if (srcFs.delete(src, true)) { System.out.println("Deleted " + src); } else { throw new IOException("Delete failed " + src); } } private void expunge() throws IOException { trash.expunge(); trash.checkpoint(); } /** * Returns the Trash object associated with this shell. */ public Path getCurrentTrashDir() { return trash.getCurrentTrashDir(); } /** * Parse the incoming command string * @param cmd * @param pos ignore anything before this pos in cmd * @throws IOException */ private void tail(String[] cmd, int pos) throws IOException { CommandFormat c = new CommandFormat("tail", 1, 1, "f"); String src = null; Path path = null; try { List<String> parameters = c.parse(cmd, pos); src = parameters.get(0); } catch(IllegalArgumentException iae) { System.err.println("Usage: java FsShell " + TAIL_USAGE); throw iae; } boolean foption = c.getOpt("f") ? true: false; path = new Path(src); FileSystem srcFs = path.getFileSystem(getConf()); FileStatus fileStatus = srcFs.getFileStatus(path); if (fileStatus.isDir()) { throw new IOException("Source must be a file."); } long fileSize = fileStatus.getLen(); long offset = (fileSize > 1024) ? fileSize - 1024: 0; while (true) { FSDataInputStream in = srcFs.open(path); try { in.seek(offset); IOUtils.copyBytes(in, System.out, 1024); offset = in.getPos(); } finally { in.close(); } if (!foption) { break; } fileSize = srcFs.getFileStatus(path).getLen(); offset = (fileSize > offset) ? offset: fileSize; try { Thread.sleep(5000); } catch (InterruptedException e) { break; } } } /** * This class runs a command on a given FileStatus. This can be used for * running various commands like chmod, chown etc. */ static abstract class CmdHandler { protected int errorCode = 0; protected boolean okToContinue = true; protected String cmdName; int getErrorCode() { return errorCode; } boolean okToContinue() { return okToContinue; } String getName() { return cmdName; } protected CmdHandler(String cmdName, FileSystem fs) { this.cmdName = cmdName; } public abstract void run(FileStatus file, FileSystem fs) throws IOException; } /** helper returns listStatus() */ private static FileStatus[] shellListStatus(String cmd, FileSystem srcFs, FileStatus src) { if (!src.isDir()) { FileStatus[] files = { src }; return files; } Path path = src.getPath(); try { FileStatus[] files = srcFs.listStatus(path); return files; } catch(FileNotFoundException fnfe) { System.err.println(cmd + ": could not get listing for '" + path + "'"); } catch (IOException e) { System.err.println(cmd + ": could not get get listing for '" + path + "' : " + e.getMessage().split("\n")[0]); } return null; } /** * Runs the command on a given file with the command handler. * If recursive is set, command is run recursively. */ private static int runCmdHandler(CmdHandler handler, FileStatus stat, FileSystem srcFs, boolean recursive) throws IOException { int errors = 0; handler.run(stat, srcFs); if (recursive && stat.isDir() && handler.okToContinue()) { FileStatus[] files = shellListStatus(handler.getName(), srcFs, stat); if (files == null) { return 1; } for(FileStatus file : files ) { errors += runCmdHandler(handler, file, srcFs, recursive); } } return errors; } ///top level runCmdHandler int runCmdHandler(CmdHandler handler, String[] args, int startIndex, boolean recursive) throws IOException { int errors = 0; for (int i=startIndex; i<args.length; i++) { Path srcPath = new Path(args[i]); FileSystem srcFs = srcPath.getFileSystem(getConf()); Path[] paths = FileUtil.stat2Paths(srcFs.globStatus(srcPath), srcPath); for(Path path : paths) { try { FileStatus file = srcFs.getFileStatus(path); if (file == null) { System.err.println(handler.getName() + ": could not get status for '" + path + "'"); errors++; } else { errors += runCmdHandler(handler, file, srcFs, recursive); } } catch (IOException e) { String msg = (e.getMessage() != null ? e.getLocalizedMessage() : (e.getCause().getMessage() != null ? e.getCause().getLocalizedMessage() : "null")); System.err.println(handler.getName() + ": could not get status for '" + path + "': " + msg.split("\n")[0]); } } } return (errors > 0 || handler.getErrorCode() != 0) ? 1 : 0; } /** * Return an abbreviated English-language desc of the byte length * @deprecated Consider using {@link org.apache.hadoop.util.StringUtils#byteDesc} instead. */ @Deprecated public static String byteDesc(long len) { return StringUtils.byteDesc(len); } /** * @deprecated Consider using {@link org.apache.hadoop.util.StringUtils#limitDecimalTo2} instead. */ @Deprecated public static synchronized String limitDecimalTo2(double d) { return StringUtils.limitDecimalTo2(d); } private void printHelp(String cmd) { String summary = "hadoop fs is the command to execute fs commands. " + "The full syntax is: \n\n" + "hadoop fs [-fs <local | file system URI>] [-conf <configuration file>]\n\t" + "[-D <property=value>] [-ls <path>] [-lsr <path>] [-df [<path>]] [-du <path>]\n\t" + "[-dus <path>] [-mv <src> <dst>] [-cp <src> <dst>] [-rm [-skipTrash] <src>]\n\t" + "[-rmr [-skipTrash] <src>] [-put <localsrc> ... <dst>] [-copyFromLocal <localsrc> ... <dst>]\n\t" + "[-moveFromLocal <localsrc> ... <dst>] [" + GET_SHORT_USAGE + "\n\t" + "[-getmerge <src> <localdst> [addnl]] [-cat <src>]\n\t" + "[" + COPYTOLOCAL_SHORT_USAGE + "] [-moveToLocal <src> <localdst>]\n\t" + "[-mkdir <path>] [-report] [" + SETREP_SHORT_USAGE + "]\n\t" + "[-touchz <path>] [-test -[ezd] <path>] [-stat [format] <path>]\n\t" + "[-tail [-f] <path>] [-text <path>]\n\t" + "[" + FsShellPermissions.CHMOD_USAGE + "]\n\t" + "[" + FsShellPermissions.CHOWN_USAGE + "]\n\t" + "[" + FsShellPermissions.CHGRP_USAGE + "]\n\t" + "[" + Count.USAGE + "]\n\t" + "[-help [cmd]]\n"; String conf ="-conf <configuration file>: Specify an application configuration file."; String D = "-D <property=value>: Use value for given property."; String fs = "-fs [local | <file system URI>]: \tSpecify the file system to use.\n" + "\t\tIf not specified, the current configuration is used, \n" + "\t\ttaken from the following, in increasing precedence: \n" + "\t\t\tcore-default.xml inside the hadoop jar file \n" + "\t\t\tcore-site.xml in $HADOOP_CONF_DIR \n" + "\t\t'local' means use the local file system as your DFS. \n" + "\t\t<file system URI> specifies a particular file system to \n" + "\t\tcontact. This argument is optional but if used must appear\n" + "\t\tappear first on the command line. Exactly one additional\n" + "\t\targument must be specified. \n"; String ls = "-ls <path>: \tList the contents that match the specified file pattern. If\n" + "\t\tpath is not specified, the contents of /user/<currentUser>\n" + "\t\twill be listed. Directory entries are of the form \n" + "\t\t\tdirName (full path) <dir> \n" + "\t\tand file entries are of the form \n" + "\t\t\tfileName(full path) <r n> size \n" + "\t\twhere n is the number of replicas specified for the file \n" + "\t\tand size is the size of the file, in bytes.\n"; String lsr = "-lsr <path>: \tRecursively list the contents that match the specified\n" + "\t\tfile pattern. Behaves very similarly to hadoop fs -ls,\n" + "\t\texcept that the data is shown for all the entries in the\n" + "\t\tsubtree.\n"; String df = "-df [<path>]: \tShows the capacity, free and used space of the filesystem.\n"+ "\t\tIf the filesystem has multiple partitions, and no path to a particular partition\n"+ "\t\tis specified, then the status of the root partitions will be shown.\n"; String du = "-du <path>: \tShow the amount of space, in bytes, used by the files that \n" + "\t\tmatch the specified file pattern. Equivalent to the unix\n" + "\t\tcommand \"du -sb <path>/*\" in case of a directory, \n" + "\t\tand to \"du -b <path>\" in case of a file.\n" + "\t\tThe output is in the form \n" + "\t\t\tname(full path) size (in bytes)\n"; String dus = "-dus <path>: \tShow the amount of space, in bytes, used by the files that \n" + "\t\tmatch the specified file pattern. Equivalent to the unix\n" + "\t\tcommand \"du -sb\" The output is in the form \n" + "\t\t\tname(full path) size (in bytes)\n"; String mv = "-mv <src> <dst>: Move files that match the specified file pattern <src>\n" + "\t\tto a destination <dst>. When moving multiple files, the \n" + "\t\tdestination must be a directory. \n"; String cp = "-cp <src> <dst>: Copy files that match the file pattern <src> to a \n" + "\t\tdestination. When copying multiple files, the destination\n" + "\t\tmust be a directory. \n"; String rm = "-rm [-skipTrash] <src>: \tDelete all files that match the specified file pattern.\n" + "\t\tEquivalent to the Unix command \"rm <src>\"\n" + "\t\t-skipTrash option bypasses trash, if enabled, and immediately\n" + "deletes <src>"; String rmr = "-rmr [-skipTrash] <src>: \tRemove all directories which match the specified file \n" + "\t\tpattern. Equivalent to the Unix command \"rm -rf <src>\"\n" + "\t\t-skipTrash option bypasses trash, if enabled, and immediately\n" + "deletes <src>"; String put = "-put <localsrc> ... <dst>: \tCopy files " + "from the local file system \n\t\tinto fs. \n"; String copyFromLocal = "-copyFromLocal <localsrc> ... <dst>:" + " Identical to the -put command.\n"; String moveFromLocal = "-moveFromLocal <localsrc> ... <dst>:" + " Same as -put, except that the source is\n\t\tdeleted after it's copied.\n"; String get = GET_SHORT_USAGE + ": Copy files that match the file pattern <src> \n" + "\t\tto the local name. <src> is kept. When copying mutiple, \n" + "\t\tfiles, the destination must be a directory. \n"; String getmerge = "-getmerge <src> <localdst>: Get all the files in the directories that \n" + "\t\tmatch the source file pattern and merge and sort them to only\n" + "\t\tone file on local fs. <src> is kept.\n"; String cat = "-cat <src>: \tFetch all files that match the file pattern <src> \n" + "\t\tand display their content on stdout.\n"; String text = "-text <src>: \tTakes a source file and outputs the file in text format.\n" + "\t\tThe allowed formats are zip and TextRecordInputStream.\n"; String copyToLocal = COPYTOLOCAL_SHORT_USAGE + ": Identical to the -get command.\n"; String moveToLocal = "-moveToLocal <src> <localdst>: Not implemented yet \n"; String mkdir = "-mkdir <path>: \tCreate a directory in specified location. \n"; String setrep = SETREP_SHORT_USAGE + ": Set the replication level of a file. \n" + "\t\tThe -R flag requests a recursive change of replication level \n" + "\t\tfor an entire tree.\n"; String touchz = "-touchz <path>: Write a timestamp in yyyy-MM-dd HH:mm:ss format\n" + "\t\tin a file at <path>. An error is returned if the file exists with non-zero length\n"; String test = "-test -[ezd] <path>: If file { exists, has zero length, is a directory\n" + "\t\tthen return 0, else return 1.\n"; String stat = "-stat [format] <path>: Print statistics about the file/directory at <path>\n" + "\t\tin the specified format. Format accepts filesize in blocks (%b), filename (%n),\n" + "\t\tblock size (%o), replication (%r), modification date (%y, %Y)\n"; String tail = TAIL_USAGE + ": Show the last 1KB of the file. \n" + "\t\tThe -f option shows apended data as the file grows. \n"; String chmod = FsShellPermissions.CHMOD_USAGE + "\n" + "\t\tChanges permissions of a file.\n" + "\t\tThis works similar to shell's chmod with a few exceptions.\n\n" + "\t-R\tmodifies the files recursively. This is the only option\n" + "\t\tcurrently supported.\n\n" + "\tMODE\tMode is same as mode used for chmod shell command.\n" + "\t\tOnly letters recognized are 'rwxXt'. E.g. +t,a+r,g-w,+rwx,o=r\n\n" + "\tOCTALMODE Mode specifed in 3 or 4 digits. If 4 digits, the first may\n" + "\tbe 1 or 0 to turn the sticky bit on or off, respectively. Unlike " + "\tshell command, it is not possible to specify only part of the mode\n" + "\t\tE.g. 754 is same as u=rwx,g=rx,o=r\n\n" + "\t\tIf none of 'augo' is specified, 'a' is assumed and unlike\n" + "\t\tshell command, no umask is applied.\n"; String chown = FsShellPermissions.CHOWN_USAGE + "\n" + "\t\tChanges owner and group of a file.\n" + "\t\tThis is similar to shell's chown with a few exceptions.\n\n" + "\t-R\tmodifies the files recursively. This is the only option\n" + "\t\tcurrently supported.\n\n" + "\t\tIf only owner or group is specified then only owner or\n" + "\t\tgroup is modified.\n\n" + "\t\tThe owner and group names may only cosists of digits, alphabet,\n"+ "\t\tand any of '-_.@/' i.e. [-_.@/a-zA-Z0-9]. The names are case\n" + "\t\tsensitive.\n\n" + "\t\tWARNING: Avoid using '.' to separate user name and group though\n" + "\t\tLinux allows it. If user names have dots in them and you are\n" + "\t\tusing local file system, you might see surprising results since\n" + "\t\tshell command 'chown' is used for local files.\n"; String chgrp = FsShellPermissions.CHGRP_USAGE + "\n" + "\t\tThis is equivalent to -chown ... :GROUP ...\n"; String help = "-help [cmd]: \tDisplays help for given command or all commands if none\n" + "\t\tis specified.\n"; if ("fs".equals(cmd)) { System.out.println(fs); } else if ("conf".equals(cmd)) { System.out.println(conf); } else if ("D".equals(cmd)) { System.out.println(D); } else if ("ls".equals(cmd)) { System.out.println(ls); } else if ("lsr".equals(cmd)) { System.out.println(lsr); } else if ("df".equals(cmd)) { System.out.println(df); } else if ("du".equals(cmd)) { System.out.println(du); } else if ("dus".equals(cmd)) { System.out.println(dus); } else if ("rm".equals(cmd)) { System.out.println(rm); } else if ("rmr".equals(cmd)) { System.out.println(rmr); } else if ("mkdir".equals(cmd)) { System.out.println(mkdir); } else if ("mv".equals(cmd)) { System.out.println(mv); } else if ("cp".equals(cmd)) { System.out.println(cp); } else if ("put".equals(cmd)) { System.out.println(put); } else if ("copyFromLocal".equals(cmd)) { System.out.println(copyFromLocal); } else if ("moveFromLocal".equals(cmd)) { System.out.println(moveFromLocal); } else if ("get".equals(cmd)) { System.out.println(get); } else if ("getmerge".equals(cmd)) { System.out.println(getmerge); } else if ("copyToLocal".equals(cmd)) { System.out.println(copyToLocal); } else if ("moveToLocal".equals(cmd)) { System.out.println(moveToLocal); } else if ("cat".equals(cmd)) { System.out.println(cat); } else if ("get".equals(cmd)) { System.out.println(get); } else if ("setrep".equals(cmd)) { System.out.println(setrep); } else if ("touchz".equals(cmd)) { System.out.println(touchz); } else if ("test".equals(cmd)) { System.out.println(test); } else if ("text".equals(cmd)) { System.out.println(text); } else if ("stat".equals(cmd)) { System.out.println(stat); } else if ("tail".equals(cmd)) { System.out.println(tail); } else if ("chmod".equals(cmd)) { System.out.println(chmod); } else if ("chown".equals(cmd)) { System.out.println(chown); } else if ("chgrp".equals(cmd)) { System.out.println(chgrp); } else if (Count.matches(cmd)) { System.out.println(Count.DESCRIPTION); } else if ("help".equals(cmd)) { System.out.println(help); } else { System.out.println(summary); System.out.println(fs); System.out.println(ls); System.out.println(lsr); System.out.println(df); System.out.println(du); System.out.println(dus); System.out.println(mv); System.out.println(cp); System.out.println(rm); System.out.println(rmr); System.out.println(put); System.out.println(copyFromLocal); System.out.println(moveFromLocal); System.out.println(get); System.out.println(getmerge); System.out.println(cat); System.out.println(copyToLocal); System.out.println(moveToLocal); System.out.println(mkdir); System.out.println(setrep); System.out.println(tail); System.out.println(touchz); System.out.println(test); System.out.println(text); System.out.println(stat); System.out.println(chmod); System.out.println(chown); System.out.println(chgrp); System.out.println(Count.DESCRIPTION); System.out.println(help); } } /** * Apply operation specified by 'cmd' on all parameters * starting from argv[startindex]. */ private int doall(String cmd, String argv[], int startindex) { int exitCode = 0; int i = startindex; boolean rmSkipTrash = false; // Check for -skipTrash option in rm/rmr if(("-rm".equals(cmd) || "-rmr".equals(cmd)) && "-skipTrash".equals(argv[i])) { rmSkipTrash = true; i++; } // // for each source file, issue the command // for (; i < argv.length; i++) { try { // // issue the command to the fs // if ("-cat".equals(cmd)) { cat(argv[i], true); } else if ("-mkdir".equals(cmd)) { mkdir(argv[i]); } else if ("-rm".equals(cmd)) { delete(argv[i], false, rmSkipTrash); } else if ("-rmr".equals(cmd)) { delete(argv[i], true, rmSkipTrash); } else if ("-df".equals(cmd)) { df(argv[i]); } else if (Count.matches(cmd)) { new Count(argv, i, getConf()).runAll(); } else if ("-ls".equals(cmd)) { exitCode = ls(argv[i], false); } else if ("-lsr".equals(cmd)) { exitCode = ls(argv[i], true); } else if ("-touchz".equals(cmd)) { touchz(argv[i]); } else if ("-text".equals(cmd)) { text(argv[i]); } } catch (RemoteException e) { // // This is a error returned by hadoop server. Print // out the first line of the error message. // exitCode = -1; try { String[] content; content = e.getLocalizedMessage().split("\n"); System.err.println(cmd.substring(1) + ": " + content[0]); } catch (Exception ex) { System.err.println(cmd.substring(1) + ": " + ex.getLocalizedMessage()); } } catch (IOException e) { // // IO exception encountered locally. // exitCode = -1; String content = e.getLocalizedMessage(); if (content != null) { content = content.split("\n")[0]; } System.err.println(cmd.substring(1) + ": " + content); } } return exitCode; } /** * Displays format of commands. * */ private static void printUsage(String cmd) { String prefix = "Usage: java " + FsShell.class.getSimpleName(); if ("-fs".equals(cmd)) { System.err.println("Usage: java FsShell" + " [-fs <local | file system URI>]"); } else if ("-conf".equals(cmd)) { System.err.println("Usage: java FsShell" + " [-conf <configuration file>]"); } else if ("-D".equals(cmd)) { System.err.println("Usage: java FsShell" + " [-D <[property=value>]"); } else if ("-ls".equals(cmd) || "-lsr".equals(cmd) || "-du".equals(cmd) || "-dus".equals(cmd) || "-touchz".equals(cmd) || "-mkdir".equals(cmd) || "-text".equals(cmd)) { System.err.println("Usage: java FsShell" + " [" + cmd + " <path>]"); } else if ("-df".equals(cmd) ) { System.err.println("Usage: java FsShell" + " [" + cmd + " [<path>]]"); } else if (Count.matches(cmd)) { System.err.println(prefix + " [" + Count.USAGE + "]"); } else if ("-rm".equals(cmd) || "-rmr".equals(cmd)) { System.err.println("Usage: java FsShell [" + cmd + " [-skipTrash] <src>]"); } else if ("-mv".equals(cmd) || "-cp".equals(cmd)) { System.err.println("Usage: java FsShell" + " [" + cmd + " <src> <dst>]"); } else if ("-put".equals(cmd) || "-copyFromLocal".equals(cmd) || "-moveFromLocal".equals(cmd)) { System.err.println("Usage: java FsShell" + " [" + cmd + " <localsrc> ... <dst>]"); } else if ("-get".equals(cmd)) { System.err.println("Usage: java FsShell [" + GET_SHORT_USAGE + "]"); } else if ("-copyToLocal".equals(cmd)) { System.err.println("Usage: java FsShell [" + COPYTOLOCAL_SHORT_USAGE+ "]"); } else if ("-moveToLocal".equals(cmd)) { System.err.println("Usage: java FsShell" + " [" + cmd + " [-crc] <src> <localdst>]"); } else if ("-cat".equals(cmd)) { System.err.println("Usage: java FsShell" + " [" + cmd + " <src>]"); } else if ("-setrep".equals(cmd)) { System.err.println("Usage: java FsShell [" + SETREP_SHORT_USAGE + "]"); } else if ("-test".equals(cmd)) { System.err.println("Usage: java FsShell" + " [-test -[ezd] <path>]"); } else if ("-stat".equals(cmd)) { System.err.println("Usage: java FsShell" + " [-stat [format] <path>]"); } else if ("-tail".equals(cmd)) { System.err.println("Usage: java FsShell [" + TAIL_USAGE + "]"); } else { System.err.println("Usage: java FsShell"); System.err.println(" [-ls <path>]"); System.err.println(" [-lsr <path>]"); System.err.println(" [-df [<path>]]"); System.err.println(" [-du <path>]"); System.err.println(" [-dus <path>]"); System.err.println(" [" + Count.USAGE + "]"); System.err.println(" [-mv <src> <dst>]"); System.err.println(" [-cp <src> <dst>]"); System.err.println(" [-rm [-skipTrash] <path>]"); System.err.println(" [-rmr [-skipTrash] <path>]"); System.err.println(" [-expunge]"); System.err.println(" [-put <localsrc> ... <dst>]"); System.err.println(" [-copyFromLocal <localsrc> ... <dst>]"); System.err.println(" [-moveFromLocal <localsrc> ... <dst>]"); System.err.println(" [" + GET_SHORT_USAGE + "]"); System.err.println(" [-getmerge <src> <localdst> [addnl]]"); System.err.println(" [-cat <src>]"); System.err.println(" [-text <src>]"); System.err.println(" [" + COPYTOLOCAL_SHORT_USAGE + "]"); System.err.println(" [-moveToLocal [-crc] <src> <localdst>]"); System.err.println(" [-mkdir <path>]"); System.err.println(" [" + SETREP_SHORT_USAGE + "]"); System.err.println(" [-touchz <path>]"); System.err.println(" [-test -[ezd] <path>]"); System.err.println(" [-stat [format] <path>]"); System.err.println(" [" + TAIL_USAGE + "]"); System.err.println(" [" + FsShellPermissions.CHMOD_USAGE + "]"); System.err.println(" [" + FsShellPermissions.CHOWN_USAGE + "]"); System.err.println(" [" + FsShellPermissions.CHGRP_USAGE + "]"); System.err.println(" [-help [cmd]]"); System.err.println(); ToolRunner.printGenericCommandUsage(System.err); } } /** * run */ public int run(String argv[]) throws Exception { if (argv.length < 1) { printUsage(""); return -1; } int exitCode = -1; int i = 0; String cmd = argv[i++]; // // verify that we have enough command line parameters // if ("-put".equals(cmd) || "-test".equals(cmd) || "-copyFromLocal".equals(cmd) || "-moveFromLocal".equals(cmd)) { if (argv.length < 3) { printUsage(cmd); return exitCode; } } else if ("-get".equals(cmd) || "-copyToLocal".equals(cmd) || "-moveToLocal".equals(cmd)) { if (argv.length < 3) { printUsage(cmd); return exitCode; } } else if ("-mv".equals(cmd) || "-cp".equals(cmd)) { if (argv.length < 3) { printUsage(cmd); return exitCode; } } else if ("-rm".equals(cmd) || "-rmr".equals(cmd) || "-cat".equals(cmd) || "-mkdir".equals(cmd) || "-touchz".equals(cmd) || "-stat".equals(cmd) || "-text".equals(cmd)) { if (argv.length < 2) { printUsage(cmd); return exitCode; } } // initialize FsShell try { init(); } catch (RPC.VersionMismatch v) { System.err.println("Version Mismatch between client and server" + "... command aborted."); return exitCode; } catch (IOException e) { System.err.println("Bad connection to FS. command aborted."); return exitCode; } exitCode = 0; try { if ("-put".equals(cmd) || "-copyFromLocal".equals(cmd)) { Path[] srcs = new Path[argv.length-2]; for (int j=0 ; i < argv.length-1 ;) srcs[j++] = new Path(argv[i++]); copyFromLocal(srcs, argv[i++]); } else if ("-moveFromLocal".equals(cmd)) { Path[] srcs = new Path[argv.length-2]; for (int j=0 ; i < argv.length-1 ;) srcs[j++] = new Path(argv[i++]); moveFromLocal(srcs, argv[i++]); } else if ("-get".equals(cmd) || "-copyToLocal".equals(cmd)) { copyToLocal(argv, i); } else if ("-getmerge".equals(cmd)) { if (argv.length>i+2) copyMergeToLocal(argv[i++], new Path(argv[i++]), Boolean.parseBoolean(argv[i++])); else copyMergeToLocal(argv[i++], new Path(argv[i++])); } else if ("-cat".equals(cmd)) { exitCode = doall(cmd, argv, i); } else if ("-text".equals(cmd)) { exitCode = doall(cmd, argv, i); } else if ("-moveToLocal".equals(cmd)) { moveToLocal(argv[i++], new Path(argv[i++])); } else if ("-setrep".equals(cmd)) { setReplication(argv, i); } else if ("-chmod".equals(cmd) || "-chown".equals(cmd) || "-chgrp".equals(cmd)) { FsShellPermissions.changePermissions(fs, cmd, argv, i, this); } else if ("-ls".equals(cmd)) { if (i < argv.length) { exitCode = doall(cmd, argv, i); } else { exitCode = ls(Path.CUR_DIR, false); } } else if ("-lsr".equals(cmd)) { if (i < argv.length) { exitCode = doall(cmd, argv, i); } else { exitCode = ls(Path.CUR_DIR, true); } } else if ("-mv".equals(cmd)) { exitCode = rename(argv, getConf()); } else if ("-cp".equals(cmd)) { exitCode = copy(argv, getConf()); } else if ("-rm".equals(cmd)) { exitCode = doall(cmd, argv, i); } else if ("-rmr".equals(cmd)) { exitCode = doall(cmd, argv, i); } else if ("-expunge".equals(cmd)) { expunge(); } else if ("-df".equals(cmd)) { if (argv.length-1 > 0) { exitCode = doall(cmd, argv, i); } else { df(null); } } else if ("-du".equals(cmd)) { du(argv, i); } else if ("-dus".equals(cmd)) { dus(argv, i); } else if (Count.matches(cmd)) { exitCode = new Count(argv, i, getConf()).runAll(); } else if ("-mkdir".equals(cmd)) { exitCode = doall(cmd, argv, i); } else if ("-touchz".equals(cmd)) { exitCode = doall(cmd, argv, i); } else if ("-test".equals(cmd)) { exitCode = test(argv, i); } else if ("-stat".equals(cmd)) { if (i + 1 < argv.length) { stat(argv[i++].toCharArray(), argv[i++]); } else { stat("%y".toCharArray(), argv[i]); } } else if ("-help".equals(cmd)) { if (i < argv.length) { printHelp(argv[i]); } else { printHelp(""); } } else if ("-tail".equals(cmd)) { tail(argv, i); } else { exitCode = -1; System.err.println(cmd.substring(1) + ": Unknown command"); printUsage(""); } } catch (IllegalArgumentException arge) { exitCode = -1; System.err.println(cmd.substring(1) + ": " + arge.getLocalizedMessage()); printUsage(cmd); } catch (RemoteException e) { // // This is a error returned by hadoop server. Print // out the first line of the error mesage, ignore the stack trace. exitCode = -1; try { String[] content; content = e.getLocalizedMessage().split("\n"); System.err.println(cmd.substring(1) + ": " + content[0]); } catch (Exception ex) { System.err.println(cmd.substring(1) + ": " + ex.getLocalizedMessage()); } } catch (IOException e) { // // IO exception encountered locally. // exitCode = -1; System.err.println(cmd.substring(1) + ": " + e.getLocalizedMessage()); } catch (Exception re) { exitCode = -1; System.err.println(cmd.substring(1) + ": " + re.getLocalizedMessage()); } finally { } return exitCode; } public void close() throws IOException { if (fs != null) { fs.close(); fs = null; } } /** * main() has some simple utility methods */ public static void main(String argv[]) throws Exception { FsShell shell = new FsShell(); int res; try { res = ToolRunner.run(shell, argv); } finally { shell.close(); } System.exit(res); } /** * Accumulate exceptions if there is any. Throw them at last. */ private abstract class DelayedExceptionThrowing { abstract void process(Path p, FileSystem srcFs) throws IOException; final void globAndProcess(Path srcPattern, FileSystem srcFs ) throws IOException { List<IOException> exceptions = new ArrayList<IOException>(); for(Path p : FileUtil.stat2Paths(srcFs.globStatus(srcPattern), srcPattern)) try { process(p, srcFs); } catch(IOException ioe) { exceptions.add(ioe); } if (!exceptions.isEmpty()) if (exceptions.size() == 1) throw exceptions.get(0); else throw new IOException("Multiple IOExceptions: " + exceptions); } } /** * Utility class for a line of du output */ private static class UsagePair { public String path; public long bytes; public UsagePair(String path, long bytes) { this.path = path; this.bytes = bytes; } } }
true
false
null
null
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ToggleBreakpointAdapter.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ToggleBreakpointAdapter.java index 39ca61d56..15019c6d6 100644 --- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ToggleBreakpointAdapter.java +++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ToggleBreakpointAdapter.java @@ -1,1152 +1,1162 @@ /******************************************************************************* * Copyright (c) 2000, 2007 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.jdt.internal.debug.ui.actions; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.IBreakpointManager; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.debug.ui.actions.IToggleBreakpointsTargetExtension; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageDeclaration; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeParameter; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.debug.core.IJavaBreakpoint; import org.eclipse.jdt.debug.core.IJavaClassPrepareBreakpoint; import org.eclipse.jdt.debug.core.IJavaFieldVariable; import org.eclipse.jdt.debug.core.IJavaLineBreakpoint; import org.eclipse.jdt.debug.core.IJavaMethodBreakpoint; import org.eclipse.jdt.debug.core.IJavaType; import org.eclipse.jdt.debug.core.IJavaWatchpoint; import org.eclipse.jdt.debug.core.JDIDebugModel; import org.eclipse.jdt.internal.debug.core.JavaDebugUtils; import org.eclipse.jdt.internal.debug.ui.BreakpointUtils; import org.eclipse.jdt.internal.debug.ui.DebugWorkingCopyManager; import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.IEditorStatusLine; import org.eclipse.ui.texteditor.ITextEditor; /** * Toggles a line breakpoint in a Java editor. * * @since 3.0 */ public class ToggleBreakpointAdapter implements IToggleBreakpointsTargetExtension { private static final String EMPTY_STRING = ""; //$NON-NLS-1$ /** * Constructor */ public ToggleBreakpointAdapter() { // initialize helper in UI thread ActionDelegateHelper.getDefault(); } /** * Convenience method for printing messages to the status line * @param message the message to be displayed * @param part the currently active workbench part */ protected void report(final String message, final IWorkbenchPart part) { JDIDebugUIPlugin.getStandardDisplay().asyncExec(new Runnable() { public void run() { IEditorStatusLine statusLine = (IEditorStatusLine) part.getAdapter(IEditorStatusLine.class); if (statusLine != null) { if (message != null) { statusLine.setMessage(true, message, null); } else { statusLine.setMessage(true, null, null); } } if (message != null && JDIDebugUIPlugin.getActiveWorkbenchShell() != null) { JDIDebugUIPlugin.getActiveWorkbenchShell().getDisplay().beep(); } } }); } /** * Returns the <code>IType</code> for the given selection * @param selection the current text selection * @return the <code>IType</code> for the text selection or <code>null</code> */ protected IType getType(ITextSelection selection) { IMember member = ActionDelegateHelper.getDefault().getCurrentMember(selection); IType type = null; if (member instanceof IType) { type = (IType) member; } else if (member != null) { type = member.getDeclaringType(); } // bug 52385: we don't want local and anonymous types from compilation // unit, // we are getting 'not-always-correct' names for them. try { while (type != null && !type.isBinary() && type.isLocal()) { type = type.getDeclaringType(); } } catch (JavaModelException e) { JDIDebugUIPlugin.log(e); } return type; } /** * Returns the IType associated with the <code>IJavaElement</code> passed in * @param element the <code>IJavaElement</code> to get the type from * @return the corresponding <code>IType</code> for the <code>IJavaElement</code>, or <code>null</code> if there is not one. * @since 3.3 */ protected IType getType(IJavaElement element) { switch(element.getElementType()) { case IJavaElement.FIELD: { return ((IField)element).getDeclaringType(); } case IJavaElement.METHOD: { return ((IMethod)element).getDeclaringType(); } case IJavaElement.TYPE: { return (IType)element; } default: { return null; } } } /* (non-Javadoc) * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#toggleLineBreakpoints(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection) */ public void toggleLineBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException { toggleLineBreakpoints(part, selection, false); } /** * Toggles a line breakpoint. * @param part the currently active workbench part * @param selection the current selection * @param bestMatch if we should make a best match or not */ public void toggleLineBreakpoints(final IWorkbenchPart part, final ISelection selection, final boolean bestMatch) { Job job = new Job("Toggle Line Breakpoint") { //$NON-NLS-1$ protected IStatus run(IProgressMonitor monitor) { ITextEditor editor = getTextEditor(part); if (editor != null && selection instanceof ITextSelection) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } try { report(null, part); ISelection sel = selection; if(!(selection instanceof IStructuredSelection)) { sel = translateToMembers(part, selection); } if(isInterface(sel, part)) { report(ActionMessages.ToggleBreakpointAdapter_6, part); return Status.OK_STATUS; } if(sel instanceof IStructuredSelection) { IMember member = (IMember) ((IStructuredSelection)sel).getFirstElement(); IType type = null; if(member.getElementType() == IJavaElement.TYPE) { type = (IType) member; } else { type = member.getDeclaringType(); } String tname = createQualifiedTypeName(type); IResource resource = BreakpointUtils.getBreakpointResource(type); int lnumber = ((ITextSelection) selection).getStartLine() + 1; IJavaLineBreakpoint existingBreakpoint = JDIDebugModel.lineBreakpointExists(resource, tname, lnumber); if (existingBreakpoint != null) { DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint(existingBreakpoint, true); return Status.OK_STATUS; } Map attributes = new HashMap(10); IDocumentProvider documentProvider = editor.getDocumentProvider(); if (documentProvider == null) { return Status.CANCEL_STATUS; } IDocument document = documentProvider.getDocument(editor.getEditorInput()); try { IRegion line = document.getLineInformation(lnumber - 1); int start = line.getOffset(); int end = start + line.getLength() - 1; BreakpointUtils.addJavaBreakpointAttributesWithMemberDetails(attributes, type, start, end); } catch (BadLocationException ble) {JDIDebugUIPlugin.log(ble);} IJavaLineBreakpoint breakpoint = JDIDebugModel.createLineBreakpoint(resource, tname, lnumber, -1, -1, 0, true, attributes); new BreakpointLocationVerifierJob(document, breakpoint, lnumber, bestMatch, tname, type, resource, editor).schedule(); } else { report(ActionMessages.ToggleBreakpointAdapter_3, part); return Status.OK_STATUS; } } catch (CoreException ce) {return ce.getStatus();} } return Status.OK_STATUS; } }; job.setSystem(true); job.schedule(); } /* * (non-Javadoc) * * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#canToggleLineBreakpoints(IWorkbenchPart, * ISelection) */ public boolean canToggleLineBreakpoints(IWorkbenchPart part, ISelection selection) { if (isRemote(part, selection)) { return false; } return selection instanceof ITextSelection; } /* * (non-Javadoc) * * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#toggleMethodBreakpoints(org.eclipse.ui.IWorkbenchPart, * org.eclipse.jface.viewers.ISelection) */ public void toggleMethodBreakpoints(final IWorkbenchPart part, final ISelection finalSelection) { Job job = new Job("Toggle Method Breakpoints") { //$NON-NLS-1$ protected IStatus run(IProgressMonitor monitor) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } try { report(null, part); ISelection selection = finalSelection; if(!(selection instanceof IStructuredSelection)) { selection = translateToMembers(part, selection); } if(isInterface(selection, part)) { report(ActionMessages.ToggleBreakpointAdapter_7, part); return Status.OK_STATUS; } if (selection instanceof IStructuredSelection) { IMethod[] members = getMethods((IStructuredSelection) selection); if (members.length == 0) { report(ActionMessages.ToggleBreakpointAdapter_9, part); return Status.OK_STATUS; } IJavaBreakpoint breakpoint = null; ISourceRange range = null; Map attributes = null; IType type = null; String signature = null; String mname = null; for (int i = 0, length = members.length; i < length; i++) { breakpoint = getMethodBreakpoint(members[i]); if (breakpoint == null) { int start = -1; int end = -1; range = members[i].getNameRange(); if (range != null) { start = range.getOffset(); end = start + range.getLength(); } attributes = new HashMap(10); BreakpointUtils.addJavaBreakpointAttributes(attributes, members[i]); type = members[i].getDeclaringType(); signature = members[i].getSignature(); mname = members[i].getElementName(); if (members[i].isConstructor()) { mname = "<init>"; //$NON-NLS-1$ if (type.isEnum()) { signature = "(Ljava.lang.String;I" + signature.substring(1); //$NON-NLS-1$ } } if (!type.isBinary()) { signature = resolveMethodSignature(type, signature); if (signature == null) { report(ActionMessages.ManageMethodBreakpointActionDelegate_methodNonAvailable, part); return Status.OK_STATUS; } } JDIDebugModel.createMethodBreakpoint(BreakpointUtils.getBreakpointResource(members[i]), createQualifiedTypeName(type), mname, signature, true, false, false, -1, start, end, 0, true, attributes); } else { DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint(breakpoint, true); } } } else { report(ActionMessages.ToggleBreakpointAdapter_4, part); return Status.OK_STATUS; } } catch (CoreException e) { return e.getStatus(); } return Status.OK_STATUS; } }; job.setSystem(true); job.schedule(); } /** * Toggles a class load breakpoint * @param part the part * @param selection the current selection * @since 3.3 */ public void toggleClassBreakpoints(final IWorkbenchPart part, final ISelection selection) { Job job = new Job("Toggle Class Load Breakpoints") { //$NON-NLS-1$ protected IStatus run(IProgressMonitor monitor) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } try { report(null, part); ISelection sel = selection; if(!(selection instanceof IStructuredSelection)) { sel = translateToMembers(part, selection); } if(isInterface(sel, part)) { report(ActionMessages.ToggleBreakpointAdapter_1, part); return Status.OK_STATUS; } if(sel instanceof IStructuredSelection) { IMember member = (IMember)((IStructuredSelection)sel).getFirstElement(); IType type = (IType) member; IBreakpoint existing = getClassLoadBreakpoint(type); if (existing != null) { existing.delete(); } else { HashMap map = new HashMap(10); BreakpointUtils.addJavaBreakpointAttributes(map, type); ISourceRange range= type.getNameRange(); int start = -1; int end = -1; if (range != null) { start = range.getOffset(); end = start + range.getLength(); } JDIDebugModel.createClassPrepareBreakpoint(BreakpointUtils.getBreakpointResource(member), createQualifiedTypeName(type), IJavaClassPrepareBreakpoint.TYPE_CLASS, start, end, true, map); } } else { report(ActionMessages.ToggleBreakpointAdapter_0, part); return Status.OK_STATUS; } } catch (CoreException e) { return e.getStatus(); } return Status.OK_STATUS; } }; job.setSystem(true); job.schedule(); } /** * Returns the class load breakpoint for the specified type or null if none found * @param type the type to search for a class load breakpoint for * @return the existing class load breakpoint, or null if none * @throws CoreException * @since 3.3 */ protected IBreakpoint getClassLoadBreakpoint(IType type) throws CoreException { IBreakpoint[] breakpoints = DebugPlugin.getDefault().getBreakpointManager().getBreakpoints(JDIDebugModel.getPluginIdentifier()); IBreakpoint existing = null; IJavaBreakpoint breakpoint = null; for (int i = 0; i < breakpoints.length; i++) { breakpoint = (IJavaBreakpoint) breakpoints[i]; if (breakpoint instanceof IJavaClassPrepareBreakpoint && createQualifiedTypeName(type).equals(breakpoint.getTypeName())) { existing = breakpoint; break; } } return existing; } /** * Returns the package qualified name, while accounting for the fact that a source file might * not have a project * @param type the type to ensure the package qualified name is created for * @return the package qualified name * @since 3.3 */ private String createQualifiedTypeName(IType type) { String tname = type.getFullyQualifiedName(); try { if(!type.getJavaProject().exists()) { String packName = null; if (type.isBinary()) { packName = type.getPackageFragment().getElementName(); } else { IPackageDeclaration[] pd = type.getCompilationUnit().getPackageDeclarations(); if(pd.length > 0) { packName = pd[0].getElementName(); } } if(packName != null && !packName.equals(EMPTY_STRING)) { tname = packName+"."+tname; //$NON-NLS-1$ } } if(type.isAnonymous()) { //prune the $# from the name int idx = tname.indexOf('$'); if(idx > -1) { tname = tname.substring(0, idx); } } } catch (JavaModelException e) {} return tname; } /** * gets the <code>IJavaElement</code> from the editor input * @param input the current editor input * @return the corresponding <code>IJavaElement</code> * @since 3.3 */ private IJavaElement getJavaElement(IEditorInput input) { IJavaElement je = JavaUI.getEditorInputJavaElement(input); if(je != null) { return je; } //try to get from the working copy manager return DebugWorkingCopyManager.getWorkingCopy(input, false); } /* * (non-Javadoc) * * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#canToggleMethodBreakpoints(org.eclipse.ui.IWorkbenchPart, * org.eclipse.jface.viewers.ISelection) */ public boolean canToggleMethodBreakpoints(IWorkbenchPart part, ISelection selection) { if (isRemote(part, selection)) { return false; } if (selection instanceof IStructuredSelection) { IStructuredSelection ss = (IStructuredSelection) selection; return getMethods(ss).length > 0; } return (selection instanceof ITextSelection) && isMethod((ITextSelection) selection, part); } /** * Returns whether the given part/selection is remote (viewing a repository) * * @param part * @param selection * @return */ protected boolean isRemote(IWorkbenchPart part, ISelection selection) { if (selection instanceof IStructuredSelection) { IStructuredSelection ss = (IStructuredSelection) selection; Object element = ss.getFirstElement(); if(element instanceof IMember) { IMember member = (IMember) element; return !member.getJavaProject().getProject().exists(); } } ITextEditor editor = getTextEditor(part); if (editor != null) { IEditorInput input = editor.getEditorInput(); Object adapter = Platform.getAdapterManager().getAdapter(input, "org.eclipse.team.core.history.IFileRevision"); //$NON-NLS-1$ return adapter != null; } return false; } /** * Returns the text editor associated with the given part or <code>null</code> * if none. In case of a multi-page editor, this method should be used to retrieve * the correct editor to perform the breakpoint operation on. * * @param part workbench part * @return text editor part or <code>null</code> */ protected ITextEditor getTextEditor(IWorkbenchPart part) { if (part instanceof ITextEditor) { return (ITextEditor) part; } return (ITextEditor) part.getAdapter(ITextEditor.class); } /** * Returns the methods from the selection, or an empty array * @param selection the selection to get the methods from * @return an array of the methods from the selection or an empty array */ protected IMethod[] getMethods(IStructuredSelection selection) { if (selection.isEmpty()) { return new IMethod[0]; } List methods = new ArrayList(selection.size()); Iterator iterator = selection.iterator(); while (iterator.hasNext()) { Object thing = iterator.next(); try { if (thing instanceof IMethod) { IMethod method = (IMethod) thing; if (!Flags.isAbstract(method.getFlags())) { methods.add(method); } } } catch (JavaModelException e) {} } return (IMethod[]) methods.toArray(new IMethod[methods.size()]); } /** * Returns if the text selection is a valid method or not * @param selection the text selection * @param part the associated workbench part * @return true if the selection is a valid method, false otherwise */ private boolean isMethod(ITextSelection selection, IWorkbenchPart part) { ITextEditor editor = getTextEditor(part); if(editor != null) { IJavaElement element = getJavaElement(editor.getEditorInput()); if(element != null) { try { if(element instanceof ICompilationUnit) { element = ((ICompilationUnit) element).getElementAt(selection.getOffset()); } else if(element instanceof IClassFile) { element = ((IClassFile) element).getElementAt(selection.getOffset()); } return element != null && element.getElementType() == IJavaElement.METHOD; } catch (JavaModelException e) {return false;} } } return false; } /** * Returns a list of <code>IField</code> and <code>IJavaFieldVariable</code> in the given selection. * When an <code>IField</code> can be resolved for an <code>IJavaFieldVariable</code>, it is * returned in favour of the variable. * * @param selection * @return list of <code>IField</code> and <code>IJavaFieldVariable</code>, possibly empty * @throws CoreException */ protected List getFields(IStructuredSelection selection) throws CoreException { if (selection.isEmpty()) { return Collections.EMPTY_LIST; } List fields = new ArrayList(selection.size()); Iterator iterator = selection.iterator(); while (iterator.hasNext()) { Object thing = iterator.next(); if (thing instanceof IField) { fields.add(thing); } else if (thing instanceof IJavaFieldVariable) { IField field = getField((IJavaFieldVariable) thing); if (field == null) { fields.add(thing); } else { fields.add(field); } } } return fields; } /** * Returns if the structured selection is itself or is part of an interface * @param selection the current selection * @return true if the selection is part of an interface, false otherwise * @since 3.2 */ private boolean isInterface(ISelection selection, IWorkbenchPart part) { try { ISelection sel = selection; if(!(sel instanceof IStructuredSelection)) { sel = translateToMembers(part, selection); } if(sel instanceof IStructuredSelection) { Object obj = ((IStructuredSelection)sel).getFirstElement(); if(obj instanceof IMember) { IMember member = (IMember) ((IStructuredSelection)sel).getFirstElement(); if(member.getElementType() == IJavaElement.TYPE) { return ((IType)member).isInterface(); } return member.getDeclaringType().isInterface(); } else if(obj instanceof IJavaFieldVariable) { IJavaFieldVariable var = (IJavaFieldVariable) obj; IType type = JavaDebugUtils.resolveType(var.getDeclaringType()); return type != null && type.isInterface(); } } } catch (CoreException e1) {} return false; } /** * Returns if the text selection is a field selection or not * @param selection the text selection * @param part the associated workbench part * @return true if the text selection is a valid field for a watchpoint, false otherwise * @since 3.3 */ private boolean isField(ITextSelection selection, IWorkbenchPart part) { ITextEditor editor = getTextEditor(part); if(editor != null) { IJavaElement element = getJavaElement(editor.getEditorInput()); if(element != null) { try { if(element instanceof ICompilationUnit) { element = ((ICompilationUnit) element).getElementAt(selection.getOffset()); } else if(element instanceof IClassFile) { element = ((IClassFile) element).getElementAt(selection.getOffset()); } return element != null && element.getElementType() == IJavaElement.FIELD; } catch (JavaModelException e) {return false;} } } return false; } /** * Determines if the selection is a field or not * @param selection the current selection * @return true if the selection is a field false otherwise */ private boolean isFields(IStructuredSelection selection) { if (!selection.isEmpty()) { try { Iterator iterator = selection.iterator(); while (iterator.hasNext()) { Object thing = iterator.next(); if (thing instanceof IField) { int flags = ((IField)thing).getFlags(); return !Flags.isFinal(flags) & !(Flags.isFinal(flags) & Flags.isStatic(flags)); } else if(thing instanceof IJavaFieldVariable) { IJavaFieldVariable fv = (IJavaFieldVariable)thing; return !fv.isFinal() & !(fv.isFinal() & fv.isStatic()); } } } catch(JavaModelException e) {return false;} catch(DebugException de) {return false;} } return false; } /* * (non-Javadoc) * * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#toggleWatchpoints(org.eclipse.ui.IWorkbenchPart, * org.eclipse.jface.viewers.ISelection) */ public void toggleWatchpoints(final IWorkbenchPart part, final ISelection finalSelection) { Job job = new Job("Toggle Watchpoints") { //$NON-NLS-1$ protected IStatus run(IProgressMonitor monitor) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } try { report(null, part); ISelection selection = finalSelection; if(!(selection instanceof IStructuredSelection)) { selection = translateToMembers(part, finalSelection); } if(isInterface(selection, part)) { report(ActionMessages.ToggleBreakpointAdapter_5, part); return Status.OK_STATUS; } boolean allowed = false; if (selection instanceof IStructuredSelection) { List fields = getFields((IStructuredSelection) selection); if (fields.isEmpty()) { report(ActionMessages.ToggleBreakpointAdapter_10, part); return Status.OK_STATUS; } Iterator theFields = fields.iterator(); IField javaField = null; IResource resource = null; String typeName = null; String fieldName = null; Object element = null; Map attributes = null; IJavaBreakpoint breakpoint = null; while (theFields.hasNext()) { element = theFields.next(); if (element instanceof IField) { javaField = (IField) element; IType type = javaField.getDeclaringType(); typeName = createQualifiedTypeName(type); fieldName = javaField.getElementName(); int f = javaField.getFlags(); boolean fin = Flags.isFinal(f); allowed = !(fin) & !(Flags.isStatic(f) & fin); + } else if (element instanceof IJavaFieldVariable) { + IJavaFieldVariable var = (IJavaFieldVariable) element; + typeName = var.getDeclaringType().getName(); + fieldName = var.getName(); + boolean fin = var.isFinal(); + allowed = !(fin) & !(var.isStatic() & fin); } breakpoint = getWatchpoint(typeName, fieldName); if (breakpoint == null) { if(!allowed) { toggleLineBreakpoints(part, finalSelection); return Status.OK_STATUS; } int start = -1; int end = -1; attributes = new HashMap(10); - IType type = javaField.getDeclaringType(); - ISourceRange range = javaField.getNameRange(); - if (range != null) { - start = range.getOffset(); - end = start + range.getLength(); - } - BreakpointUtils.addJavaBreakpointAttributes(attributes, javaField); - resource = BreakpointUtils.getBreakpointResource(type); + if (javaField == null) { + resource = ResourcesPlugin.getWorkspace().getRoot(); + } else { + IType type = javaField.getDeclaringType(); + ISourceRange range = javaField.getNameRange(); + if (range != null) { + start = range.getOffset(); + end = start + range.getLength(); + } + BreakpointUtils.addJavaBreakpointAttributes(attributes, javaField); + resource = BreakpointUtils.getBreakpointResource(type); + } JDIDebugModel.createWatchpoint(resource, typeName, fieldName, -1, start, end, 0, true, attributes); } else { DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint(breakpoint, true); } } } else { report(ActionMessages.ToggleBreakpointAdapter_2, part); return Status.OK_STATUS; } } catch (CoreException e) {return e.getStatus();} return Status.OK_STATUS; } }; job.setSystem(true); job.schedule(); } /** * Returns any existing watchpoint for the given field, or <code>null</code> if none. * * @param typeName fully qualified type name on which watchpoint may exist * @param fieldName field name * @return any existing watchpoint for the given field, or <code>null</code> if none * @throws CoreException */ private IJavaWatchpoint getWatchpoint(String typeName, String fieldName) throws CoreException { IBreakpointManager breakpointManager = DebugPlugin.getDefault().getBreakpointManager(); IBreakpoint[] breakpoints = breakpointManager.getBreakpoints(JDIDebugModel.getPluginIdentifier()); for (int i = 0; i < breakpoints.length; i++) { IBreakpoint breakpoint = breakpoints[i]; if (breakpoint instanceof IJavaWatchpoint) { IJavaWatchpoint watchpoint = (IJavaWatchpoint) breakpoint; if (typeName.equals(watchpoint.getTypeName()) && fieldName.equals(watchpoint.getFieldName())) { return watchpoint; } } } return null; } /** * Returns the resolved method signature for the specified type * @param type the declaring type the method is contained in * @param methodSignature the method signature to resolve * @return the resolved method signature * @throws JavaModelException */ public static String resolveMethodSignature(IType type, String methodSignature) throws JavaModelException { String[] parameterTypes = Signature.getParameterTypes(methodSignature); int length = parameterTypes.length; String[] resolvedParameterTypes = new String[length]; for (int i = 0; i < length; i++) { resolvedParameterTypes[i] = resolveType(type, parameterTypes[i]); if (resolvedParameterTypes[i] == null) { return null; } } String resolvedReturnType = resolveType(type, Signature.getReturnType(methodSignature)); if (resolvedReturnType == null) { return null; } return Signature.createMethodSignature(resolvedParameterTypes, resolvedReturnType); } /** * Resolves the the type for its given signature * @param type the type * @param typeSignature the types signature * @return the resolved type name * @throws JavaModelException */ private static String resolveType(IType type, String typeSignature) throws JavaModelException { int count = Signature.getArrayCount(typeSignature); String elementTypeSignature = Signature.getElementType(typeSignature); if (elementTypeSignature.length() == 1) { // no need to resolve primitive types return typeSignature; } String elementTypeName = Signature.toString(elementTypeSignature); String[][] resolvedElementTypeNames = type.resolveType(elementTypeName); if (resolvedElementTypeNames == null || resolvedElementTypeNames.length != 1) { // check if type parameter ITypeParameter[] typeParameters = type.getTypeParameters(); for (int i = 0; i < typeParameters.length; i++) { ITypeParameter parameter = typeParameters[i]; if (parameter.getElementName().equals(elementTypeName)) { String[] bounds = parameter.getBounds(); if (bounds.length == 0) { return "Ljava/lang/Object;"; //$NON-NLS-1$ } else { String bound = Signature.createTypeSignature(bounds[0], false); return resolveType(type, bound); } } } // the type name cannot be resolved return null; } String[] types = resolvedElementTypeNames[0]; types[1] = types[1].replace('.', '$'); String resolvedElementTypeName = Signature.toQualifiedName(types); String resolvedElementTypeSignature = EMPTY_STRING; if(types[0].equals(EMPTY_STRING)) { resolvedElementTypeName = resolvedElementTypeName.substring(1); resolvedElementTypeSignature = Signature.createTypeSignature(resolvedElementTypeName, true); } else { resolvedElementTypeSignature = Signature.createTypeSignature(resolvedElementTypeName, true).replace('.', '/'); } return Signature.createArraySignature(resolvedElementTypeSignature, count); } /** * Returns the resource associated with the specified editor part * @param editor the currently active editor part * @return the corresponding <code>IResource</code> from the editor part */ protected static IResource getResource(IEditorPart editor) { IEditorInput editorInput = editor.getEditorInput(); IResource resource = (IResource) editorInput.getAdapter(IFile.class); if (resource == null) { resource = ResourcesPlugin.getWorkspace().getRoot(); } return resource; } /** * Returns a handle to the specified method or <code>null</code> if none. * * @param editorPart * the editor containing the method * @param typeName * @param methodName * @param signature * @return handle or <code>null</code> */ protected IMethod getMethodHandle(IEditorPart editorPart, String typeName, String methodName, String signature) throws CoreException { IJavaElement element = (IJavaElement) editorPart.getEditorInput().getAdapter(IJavaElement.class); IType type = null; if (element instanceof ICompilationUnit) { IType[] types = ((ICompilationUnit) element).getAllTypes(); for (int i = 0; i < types.length; i++) { if (types[i].getFullyQualifiedName().equals(typeName)) { type = types[i]; break; } } } else if (element instanceof IClassFile) { type = ((IClassFile) element).getType(); } if (type != null) { String[] sigs = Signature.getParameterTypes(signature); return type.getMethod(methodName, sigs); } return null; } /** * Returns the <code>IJavaBreakpoint</code> from the specified <code>IMember</code> * @param element the element to get the breakpoint from * @return the current breakpoint from the element or <code>null</code> */ protected IJavaBreakpoint getMethodBreakpoint(IMember element) { IBreakpointManager breakpointManager = DebugPlugin.getDefault().getBreakpointManager(); IBreakpoint[] breakpoints = breakpointManager.getBreakpoints(JDIDebugModel.getPluginIdentifier()); if (element instanceof IMethod) { IMethod method = (IMethod) element; for (int i = 0; i < breakpoints.length; i++) { IBreakpoint breakpoint = breakpoints[i]; if (breakpoint instanceof IJavaMethodBreakpoint) { IJavaMethodBreakpoint methodBreakpoint = (IJavaMethodBreakpoint) breakpoint; IMember container = null; try { container = BreakpointUtils.getMember(methodBreakpoint); } catch (CoreException e) { JDIDebugUIPlugin.log(e); return null; } if (container == null) { try { if (method.getDeclaringType().getFullyQualifiedName().equals(methodBreakpoint.getTypeName()) && method.getElementName().equals(methodBreakpoint.getMethodName()) && methodBreakpoint.getMethodSignature().equals(resolveMethodSignature(method.getDeclaringType(), method.getSignature()))) { return methodBreakpoint; } } catch (CoreException e) { JDIDebugUIPlugin.log(e); } } else { if (container instanceof IMethod) { if(method.getDeclaringType().equals(container.getDeclaringType())) { if (method.getDeclaringType().getFullyQualifiedName().equals(container.getDeclaringType().getFullyQualifiedName())) { if (method.isSimilar((IMethod) container)) { return methodBreakpoint; } } } } } } } } return null; } /** * Returns the compilation unit from the editor * @param editor the editor to get the compilation unit from * @return the compilation unit or <code>null</code> * @throws CoreException */ protected CompilationUnit parseCompilationUnit(ITextEditor editor) throws CoreException { IEditorInput editorInput = editor.getEditorInput(); IDocumentProvider documentProvider = editor.getDocumentProvider(); if (documentProvider == null) { throw new CoreException(Status.CANCEL_STATUS); } IDocument document = documentProvider.getDocument(editorInput); ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setSource(document.get().toCharArray()); return (CompilationUnit) parser.createAST(null); } /* * (non-Javadoc) * * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#canToggleWatchpoints(org.eclipse.ui.IWorkbenchPart, * org.eclipse.jface.viewers.ISelection) */ public boolean canToggleWatchpoints(IWorkbenchPart part, ISelection selection) { if (isRemote(part, selection)) { return false; } if (selection instanceof IStructuredSelection) { IStructuredSelection ss = (IStructuredSelection) selection; return isFields(ss); } return (selection instanceof ITextSelection) && isField((ITextSelection) selection, part); } /** * Returns a selection of the member in the given text selection, or the * original selection if none. * * @param part * @param selection * @return a structured selection of the member in the given text selection, * or the original selection if none * @exception CoreException * if an exception occurs */ protected ISelection translateToMembers(IWorkbenchPart part, ISelection selection) throws CoreException { ITextEditor textEditor = getTextEditor(part); if (textEditor != null && selection instanceof ITextSelection) { ITextSelection textSelection = (ITextSelection) selection; IEditorInput editorInput = textEditor.getEditorInput(); IDocumentProvider documentProvider = textEditor.getDocumentProvider(); if (documentProvider == null) { throw new CoreException(Status.CANCEL_STATUS); } IDocument document = documentProvider.getDocument(editorInput); int offset = textSelection.getOffset(); if (document != null) { try { IRegion region = document.getLineInformationOfOffset(offset); int end = region.getOffset() + region.getLength(); while (Character.isWhitespace(document.getChar(offset)) && offset < end) { offset++; } } catch (BadLocationException e) {} } IMember m = null; IClassFile classFile = (IClassFile) editorInput.getAdapter(IClassFile.class); if (classFile != null) { IJavaElement e = classFile.getElementAt(offset); if (e instanceof IMember) { m = (IMember) e; } } else { IWorkingCopyManager manager = JavaUI.getWorkingCopyManager(); ICompilationUnit unit = manager.getWorkingCopy(editorInput); if (unit != null) { synchronized (unit) { unit.reconcile(ICompilationUnit.NO_AST , false, null, null); } } else { unit = DebugWorkingCopyManager.getWorkingCopy(editorInput, false); if(unit != null) { synchronized (unit) { unit.reconcile(ICompilationUnit.NO_AST, false, null, null); } } } IJavaElement e = unit.getElementAt(offset); if (e instanceof IMember) { m = (IMember) e; } } if (m != null) { return new StructuredSelection(m); } } return selection; } /** * Return the associated IField (Java model) for the given * IJavaFieldVariable (JDI model) */ private IField getField(IJavaFieldVariable variable) throws CoreException { String varName = null; try { varName = variable.getName(); } catch (DebugException x) { JDIDebugUIPlugin.log(x); return null; } IField field; IJavaType declaringType = variable.getDeclaringType(); IType type = JavaDebugUtils.resolveType(declaringType); if (type != null) { field = type.getField(varName); if (field.exists()) { return field; } } return null; } /* * (non-Javadoc) * * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTargetExtension#toggleBreakpoints(org.eclipse.ui.IWorkbenchPart, * org.eclipse.jface.viewers.ISelection) */ public void toggleBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException { ISelection sel = translateToMembers(part, selection); if(sel instanceof IStructuredSelection) { IMember member = (IMember) ((IStructuredSelection)sel).getFirstElement(); int mtype = member.getElementType(); if(mtype == IJavaElement.FIELD || mtype == IJavaElement.METHOD) { // remove line breakpoint if present first if (selection instanceof ITextSelection) { ITextSelection ts = (ITextSelection) selection; IType declaringType = member.getDeclaringType(); IResource resource = BreakpointUtils.getBreakpointResource(declaringType); IJavaLineBreakpoint breakpoint = JDIDebugModel.lineBreakpointExists(resource, createQualifiedTypeName(declaringType), ts.getStartLine() + 1); if (breakpoint != null) { breakpoint.delete(); return; } CompilationUnit unit = parseCompilationUnit(getTextEditor(part)); ValidBreakpointLocationLocator loc = new ValidBreakpointLocationLocator(unit, ts.getStartLine()+1, true, true); unit.accept(loc); if(loc.getLocationType() == ValidBreakpointLocationLocator.LOCATION_METHOD) { toggleMethodBreakpoints(part, sel); } else if(loc.getLocationType() == ValidBreakpointLocationLocator.LOCATION_FIELD) { toggleWatchpoints(part, ts); } else if(loc.getLocationType() == ValidBreakpointLocationLocator.LOCATION_LINE) { toggleLineBreakpoints(part, ts); } } } else if(member.getElementType() == IJavaElement.TYPE) { toggleClassBreakpoints(part, sel); } else { //fall back to old behavior, always create a line breakpoint toggleLineBreakpoints(part, selection, true); } } } /* * (non-Javadoc) * * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTargetExtension#canToggleBreakpoints(org.eclipse.ui.IWorkbenchPart, * org.eclipse.jface.viewers.ISelection) */ public boolean canToggleBreakpoints(IWorkbenchPart part, ISelection selection) { if (isRemote(part, selection)) { return false; } return canToggleLineBreakpoints(part, selection); } }
false
true
public void toggleWatchpoints(final IWorkbenchPart part, final ISelection finalSelection) { Job job = new Job("Toggle Watchpoints") { //$NON-NLS-1$ protected IStatus run(IProgressMonitor monitor) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } try { report(null, part); ISelection selection = finalSelection; if(!(selection instanceof IStructuredSelection)) { selection = translateToMembers(part, finalSelection); } if(isInterface(selection, part)) { report(ActionMessages.ToggleBreakpointAdapter_5, part); return Status.OK_STATUS; } boolean allowed = false; if (selection instanceof IStructuredSelection) { List fields = getFields((IStructuredSelection) selection); if (fields.isEmpty()) { report(ActionMessages.ToggleBreakpointAdapter_10, part); return Status.OK_STATUS; } Iterator theFields = fields.iterator(); IField javaField = null; IResource resource = null; String typeName = null; String fieldName = null; Object element = null; Map attributes = null; IJavaBreakpoint breakpoint = null; while (theFields.hasNext()) { element = theFields.next(); if (element instanceof IField) { javaField = (IField) element; IType type = javaField.getDeclaringType(); typeName = createQualifiedTypeName(type); fieldName = javaField.getElementName(); int f = javaField.getFlags(); boolean fin = Flags.isFinal(f); allowed = !(fin) & !(Flags.isStatic(f) & fin); } breakpoint = getWatchpoint(typeName, fieldName); if (breakpoint == null) { if(!allowed) { toggleLineBreakpoints(part, finalSelection); return Status.OK_STATUS; } int start = -1; int end = -1; attributes = new HashMap(10); IType type = javaField.getDeclaringType(); ISourceRange range = javaField.getNameRange(); if (range != null) { start = range.getOffset(); end = start + range.getLength(); } BreakpointUtils.addJavaBreakpointAttributes(attributes, javaField); resource = BreakpointUtils.getBreakpointResource(type); JDIDebugModel.createWatchpoint(resource, typeName, fieldName, -1, start, end, 0, true, attributes); } else { DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint(breakpoint, true); } } } else { report(ActionMessages.ToggleBreakpointAdapter_2, part); return Status.OK_STATUS; } } catch (CoreException e) {return e.getStatus();} return Status.OK_STATUS; } }; job.setSystem(true); job.schedule(); }
public void toggleWatchpoints(final IWorkbenchPart part, final ISelection finalSelection) { Job job = new Job("Toggle Watchpoints") { //$NON-NLS-1$ protected IStatus run(IProgressMonitor monitor) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } try { report(null, part); ISelection selection = finalSelection; if(!(selection instanceof IStructuredSelection)) { selection = translateToMembers(part, finalSelection); } if(isInterface(selection, part)) { report(ActionMessages.ToggleBreakpointAdapter_5, part); return Status.OK_STATUS; } boolean allowed = false; if (selection instanceof IStructuredSelection) { List fields = getFields((IStructuredSelection) selection); if (fields.isEmpty()) { report(ActionMessages.ToggleBreakpointAdapter_10, part); return Status.OK_STATUS; } Iterator theFields = fields.iterator(); IField javaField = null; IResource resource = null; String typeName = null; String fieldName = null; Object element = null; Map attributes = null; IJavaBreakpoint breakpoint = null; while (theFields.hasNext()) { element = theFields.next(); if (element instanceof IField) { javaField = (IField) element; IType type = javaField.getDeclaringType(); typeName = createQualifiedTypeName(type); fieldName = javaField.getElementName(); int f = javaField.getFlags(); boolean fin = Flags.isFinal(f); allowed = !(fin) & !(Flags.isStatic(f) & fin); } else if (element instanceof IJavaFieldVariable) { IJavaFieldVariable var = (IJavaFieldVariable) element; typeName = var.getDeclaringType().getName(); fieldName = var.getName(); boolean fin = var.isFinal(); allowed = !(fin) & !(var.isStatic() & fin); } breakpoint = getWatchpoint(typeName, fieldName); if (breakpoint == null) { if(!allowed) { toggleLineBreakpoints(part, finalSelection); return Status.OK_STATUS; } int start = -1; int end = -1; attributes = new HashMap(10); if (javaField == null) { resource = ResourcesPlugin.getWorkspace().getRoot(); } else { IType type = javaField.getDeclaringType(); ISourceRange range = javaField.getNameRange(); if (range != null) { start = range.getOffset(); end = start + range.getLength(); } BreakpointUtils.addJavaBreakpointAttributes(attributes, javaField); resource = BreakpointUtils.getBreakpointResource(type); } JDIDebugModel.createWatchpoint(resource, typeName, fieldName, -1, start, end, 0, true, attributes); } else { DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint(breakpoint, true); } } } else { report(ActionMessages.ToggleBreakpointAdapter_2, part); return Status.OK_STATUS; } } catch (CoreException e) {return e.getStatus();} return Status.OK_STATUS; } }; job.setSystem(true); job.schedule(); }
diff --git a/java/marytts/util/math/Histogram.java b/java/marytts/util/math/Histogram.java index 207ff8d00..c370d1b15 100644 --- a/java/marytts/util/math/Histogram.java +++ b/java/marytts/util/math/Histogram.java @@ -1,323 +1,327 @@ package marytts.util.math; import java.io.*; import java.text.*; public class Histogram { // private data used internally by this class. private double[] m_hist; private double[] m_data; private double[] m_binCenters; private String m_name; private double m_min; private double m_max; private int m_nbins; private int m_entries; private double m_overflow; private double m_underflow; private boolean m_debug; private double m_bandwidth; public Histogram(double[] data){ double min = MathUtils.min(data); double max = MathUtils.max(data); setHistogram(data, 15, min, max); } /** * A simple constructor * @param data * @param nbins */ public Histogram(double[] data, int nbins){ double min = MathUtils.min(data); double max = MathUtils.max(data); setHistogram(data, nbins, min, max); } /** * Constructor which sets name, number of bins, and range. * @param data samples * @param nbins the number of bins the histogram should have. The * range specified by min and max will be divided up into this * many bins. * @param min the minimum of the range covered by the histogram bins * @param max the maximum value of the range covered by the histogram bins */ public Histogram(double[] data, int nbins, double min, double max){ setHistogram(data, nbins, min, max); } /** * Settings to Histogram * @param data * @param nbins * @param min * @param max */ public void setHistogram(double[] data, int nbins, double min, double max){ m_nbins = nbins; m_min = min; m_max = max; m_data = data; m_hist = new double[m_nbins]; m_binCenters = new double[m_nbins]; m_underflow = 0; m_overflow = 0; setBandWidth(); for(double x: m_data){ fill(x); } - dataProcess(); + m_binCenters = this.setSampleArray(); } public void changeSettings(int nbins){ m_nbins = nbins; m_binCenters = new double[m_nbins]; m_hist = new double[m_nbins]; setBandWidth(); for(double x: m_data){ fill(x); } - dataProcess(); + m_binCenters = this.setSampleArray(); } - private void dataProcess(){ - double binWidth = this.getBandWidth(); - for (int i=0; i<m_nbins; i++){ - m_binCenters[i] = m_min + (double)((i+1) * binWidth) / 2.0; - } - } - /** Enter data into the histogram. The fill method takes the given * value, works out which bin this corresponds to, and increments * this bin by one. * @param x is the value to add in to the histogram */ public void fill(double x){ // use findBin method to work out which bin x falls in BinInfo bin = findBin(x); // check the result of findBin in case it was an overflow or underflow if (bin.isUnderflow){ m_underflow++; } if (bin.isOverflow){ m_overflow++; } if (bin.isInRange){ m_hist[bin.index]++; } // print out some debug information if the flag is set if (m_debug) { System.out.println("debug: fill: value " + x + " # underflows " + m_underflow + " # overflows " + m_overflow + " bin index " + bin.index); } // count the number of entries made by the fill method m_entries++; } /** Private class used internally to store info about which bin of * the histogram to use for a number to be filled. */ private class BinInfo { public int index; public boolean isUnderflow; public boolean isOverflow; public boolean isInRange; } /** Private internal utility method to figure out which bin of the * histogram a number falls in. * @return info on which bin x falls in. */ private BinInfo findBin(double x){ BinInfo bin = new BinInfo(); bin.isInRange = false; bin.isUnderflow = false; bin.isOverflow = false; // first check if x is outside the range of the normal histogram bins if (x < m_min){ bin.isUnderflow = true; } else if (x > m_max){ bin.isOverflow = true; } else { // search for histogram bin into which x falls double binWidth = this.getBandWidth(); // (m_max - m_min)/m_nbins; for (int i=0; i<m_nbins; i++){ double highEdge = m_min + (i+1) * binWidth; if (x <= highEdge) { bin.isInRange = true; bin.index = i; break; } } } return bin; } public void setBandWidth(){ m_bandwidth = (m_max - m_min) / m_nbins; } public double getBandWidth(){ return m_bandwidth; } /** Save the histogram data to a file. The file format is very * simple, human-readable text so it can be imported into Excel or * cut & pasted into other applications. * @param fileName name of the file to write the histogram to. * Note this must be valid for your operating system, * e.g. a unix filename might not work under windows * @exception IOException if file cannot be opened or written to. */ public void writeToFile(String fileName) throws IOException { PrintWriter outfile = new PrintWriter(new FileOutputStream(fileName)); outfile.println("// Output from Histogram class"); outfile.println("// metaData: "); //outfile.println("name \"" + m_name + "\""); outfile.println("bins " + m_nbins); outfile.println("min " + m_min); outfile.println("max " + m_max); outfile.println("totalEntries " + m_entries); outfile.println("underflow " + m_underflow); outfile.println("overflow " + m_overflow); outfile.println("// binData:"); for (int i=0; i<m_nbins; i++){ outfile.println(i+" "+m_binCenters[i]+" "+m_hist[i]); } outfile.println("// end."); outfile.close(); } /** * Print the histogram data to the console. Output is only basic, * intended for debugging purposes. A good example of formatted output. */ public void show(){ DecimalFormat df = new DecimalFormat(" ##0.00;-##0.00"); double binWidth = (m_max - m_min)/m_nbins; //System.out.println ("Histogram \"" + m_name + // "\", " + m_entries + " entries"); System.out.println (" bin range height" ); for (int i=0; i<m_nbins; i++){ double binLowEdge = m_min + i * binWidth; double binHighEdge = binLowEdge + binWidth; System.out.println( df.format(binLowEdge) + " to " + df.format(binHighEdge) + " " + df.format(m_hist[i]) ); } } - + + public double[] setSampleArray(){ + double[] binCenters = new double[m_nbins]; + double binWidth = (m_max - m_min)/m_nbins; + for (int i=0; i<m_nbins; i++){ + double binLowEdge = m_min + i * binWidth; + double binHighEdge = binLowEdge + binWidth; + binCenters[i] = (binLowEdge + binHighEdge) / 2.0 ; + } + return binCenters; + } + /** Get number of entries in the histogram. This should correspond * to the number of times the fill method has been used. * @return number of entries */ public int entries(){ return m_entries; } /** Get the name of the histogram. The name is an arbitrary label for the user, and is set by the constructor. * @return histogram name */ public String name(){ return m_name; } /** Get the number of bins in the histogram. The range of the * histogram defined by min and max is divided into this many * bins. * @return number of bins */ public int numberOfBins(){ return m_nbins; } /** Get lower end of histogram range * @return minimum x value covered by histogram */ public double min(){ return m_min; } public double mean(){ return MathUtils.mean(m_data); } public double variance(){ return MathUtils.variance(m_data); } /** Get upper end of histogram range * @return maximum x value covered by histogram */ public double max(){ return m_max; } /** Get the height of the overflow bin. Any value passed to the * fill method which falls above the range of the histogram will * be counted in the overflow bin. * @return number of overflows */ public double overflow(){ return m_overflow; } /** Get the height of the underflow bin. Any value passed to the * fill method which falls below the range of the histogram will * be counted in the underflow bin. * @return number of underflows */ public double underflow(){ return m_underflow; } /** This method gives you the bin contents in the form of an * array. It might be useful for example if you want to use the * histogram in some other way, for example to pass to a plotting * package. * @return array of bin heights */ public double[] getHistArray(){ return m_hist; } public double[] getSampleArray(){ return m_binCenters; } public double[] getDataArray(){ return m_data; } /** Set debug flag. * @param flag debug flag (true or false) */ public void setDebug(boolean flag){ m_debug = flag; } /** Get debug flag. * @return value of debug flag (true or false) */ public boolean getDebug(){ return m_debug; } }
false
false
null
null
diff --git a/dspace-stats/src/main/java/org/dspace/statistics/Dataset.java b/dspace-stats/src/main/java/org/dspace/statistics/Dataset.java index 78e1184e8..5121dbce3 100644 --- a/dspace-stats/src/main/java/org/dspace/statistics/Dataset.java +++ b/dspace-stats/src/main/java/org/dspace/statistics/Dataset.java @@ -1,270 +1,274 @@ /** * $Id$ * $URL$ * ************************************************************************* * Copyright (c) 2002-2009, DuraSpace. All rights reserved * Licensed under the DuraSpace Foundation License. * * A copy of the DuraSpace License has been included in this * distribution and is available at: http://scm.dspace.org/svn/repo/licenses/LICENSE.txt */ package org.dspace.statistics; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.text.DecimalFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.Ostermiller.util.ExcelCSVPrinter; /** * * @author kevinvandevelde at atmire.com * Date: 21-jan-2009 * Time: 13:44:48 * */ public class Dataset { private int nbRows; private int nbCols; /* The labels shown in our columns */ private List<String> colLabels; /* The labels shown in our rows */ private List<String> rowLabels; private String colTitle; private String rowTitle; /* The attributes for the colls */ private List<Map<String, String>> colLabelsAttrs; /* The attributes for the rows */ private List<Map<String, String>> rowLabelsAttrs; /* The data in a matrix */ private float[][]matrix; /* The format in which we format our floats */ private String format = "0"; public Dataset(int rows, int cols){ matrix = new float[rows][cols]; nbRows = rows; nbCols = cols; initColumnLabels(cols); initRowLabels(rows); } public Dataset(float[][] matrix){ this.matrix = matrix; nbRows = matrix.length; if(0 < matrix.length && 0 < matrix[0].length) nbCols = matrix[0].length; initColumnLabels(nbCols); initRowLabels(nbRows); } private void initRowLabels(int rows) { rowLabels = new ArrayList<String>(rows); rowLabelsAttrs = new ArrayList<Map<String, String>>(); for (int i = 0; i < rows; i++) { rowLabels.add("Row " + (i+1)); rowLabelsAttrs.add(new HashMap<String, String>()); } } private void initColumnLabels(int nbCols) { colLabels = new ArrayList<String>(nbCols); colLabelsAttrs = new ArrayList<Map<String, String>>(); for (int i = 0; i < nbCols; i++) { colLabels.add("Column " + (i+1)); colLabelsAttrs.add(new HashMap<String, String>()); } } public void setColLabel(int n, String label){ colLabels.set(n, label); } public void setRowLabel(int n, String label){ rowLabels.set(n, label); } public String getRowTitle() { return rowTitle; } public String getColTitle() { return colTitle; } public void setColTitle(String colTitle) { this.colTitle = colTitle; } public void setRowTitle(String rowTitle) { this.rowTitle = rowTitle; } public void setRowLabelAttr(int pos, String attrName, String attr){ Map<String, String> attrs = rowLabelsAttrs.get(pos); attrs.put(attrName, attr); rowLabelsAttrs.set(pos, attrs); } public void setRowLabelAttr(int pos, Map<String, String> attrMap){ rowLabelsAttrs.set(pos, attrMap); } public void setColLabelAttr(int pos, String attrName, String attr){ Map<String, String> attrs = colLabelsAttrs.get(pos); attrs.put(attrName, attr); colLabelsAttrs.set(pos, attrs); } public void setColLabelAttr(int pos, Map<String, String> attrMap) { colLabelsAttrs.set(pos, attrMap); } public List<Map<String, String>> getColLabelsAttrs() { return colLabelsAttrs; } public List<Map<String, String>> getRowLabelsAttrs() { return rowLabelsAttrs; } public List<String> getColLabels() { return colLabels; } public List<String> getRowLabels() { return rowLabels; } public float[][] getMatrix() { return matrix; } public int getNbRows() { return nbRows; } public int getNbCols() { return nbCols; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public String[][] getMatrixFormatted(){ DecimalFormat decimalFormat = new DecimalFormat(format); - String [][]strMatrix = new String[matrix.length][matrix[0].length]; - for (int i = 0; i < matrix.length; i++) { - for (int j = 0; j < matrix[i].length; j++) { - strMatrix[i][j] = decimalFormat.format(matrix[i][j]); + if (matrix.length == 0) { + return new String[0][0]; + } else { + String[][] strMatrix = new String[matrix.length][matrix[0].length]; + for (int i = 0; i < matrix.length; i++) { + for (int j = 0; j < matrix[i].length; j++) { + strMatrix[i][j] = decimalFormat.format(matrix[i][j]); + } } + return strMatrix; } - return strMatrix; } public void addValueToMatrix(int row, int coll, float value) { matrix[row][coll] = value; } public void addValueToMatrix(int row, int coll, String value) throws ParseException { DecimalFormat decimalFormat = new DecimalFormat(format); Number number = decimalFormat.parse(value); matrix[row][coll] = number.floatValue(); } /** * Returns false if this dataset only contains zero's. */ public boolean containsNonZeroValues(){ if (matrix != null) { for (float[] vector : matrix) { for (float v : vector) { if (v != 0) return true; } } } return false; } public void flipRowCols(){ //Lets make sure we at least have something to flip if(0 < matrix.length && 0 < matrix[0].length){ //Flip the data first float[][] newMatrix = new float[matrix[0].length][matrix.length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { newMatrix[j][i] = matrix[i][j]; } } //Flip the rows & column labels List<String> backup = colLabels; colLabels = rowLabels; rowLabels = backup; //Also flip the links List<Map<String, String>> backList = colLabelsAttrs; colLabelsAttrs = rowLabelsAttrs; rowLabelsAttrs = backList; matrix = newMatrix; } //Also flip these sizes int backUp = nbRows; nbRows = nbCols; nbCols = backUp; //Also flip the title's String backup = rowTitle; rowTitle = colTitle; colTitle = backup; } public ByteArrayOutputStream exportAsCSV() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ExcelCSVPrinter ecsvp = new ExcelCSVPrinter(baos); ecsvp.changeDelimiter(';'); ecsvp.setAlwaysQuote(true); //Generate the item row List<String> colLabels = getColLabels(); ecsvp.write(""); for (String colLabel : colLabels) { ecsvp.write(colLabel); } ecsvp.writeln(); List<String> rowLabels = getRowLabels(); String[][] matrix = getMatrixFormatted(); for (int i = 0; i < rowLabels.size(); i++) { String rowLabel = rowLabels.get(i); ecsvp.write(rowLabel); for (int j = 0; j < matrix[i].length; j++) { ecsvp.write(matrix[i][j]); } ecsvp.writeln(); } ecsvp.flush(); ecsvp.close(); return baos; } } diff --git a/dspace-stats/src/main/java/org/dspace/statistics/util/LocationUtils.java b/dspace-stats/src/main/java/org/dspace/statistics/util/LocationUtils.java index 89efa5b6a..e837a0bbe 100644 --- a/dspace-stats/src/main/java/org/dspace/statistics/util/LocationUtils.java +++ b/dspace-stats/src/main/java/org/dspace/statistics/util/LocationUtils.java @@ -1,819 +1,828 @@ /** * $Id$ * $URL$ * ************************************************************************* * Copyright (c) 2002-2009, DuraSpace. All rights reserved * Licensed under the DuraSpace Foundation License. * * A copy of the DuraSpace License has been included in this * distribution and is available at: http://scm.dspace.org/svn/repo/licenses/LICENSE.txt */ package org.dspace.statistics.util; import java.util.ArrayList; import java.util.Vector; import java.util.Arrays; import java.util.List; import java.lang.reflect.Array; +import org.dspace.core.I18nUtil; /** * Mapping between Country codes, English Country names, * Continent Codes, and English Continent names * * @author kevinvandevelde at atmire.com * @author ben at atmire.com */ public class LocationUtils { // TODO: put lists below in a file ? Although this will not get changed often if it does we need to adjust code..... private static String[] countryNames = new String[]{ "Afghanistan, Islamic Republic of", "Åland Islands", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Bouvet Island (Bouvetoya)", "Brazil", "British Indian Ocean Territory (Chagos Archipelago)", "British Virgin Islands", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Congo", "Cook Islands", "Costa Rica", "Cote d'Ivoire", "Croatia", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Faroe Islands", "Falkland Islands (Malvinas)", "Fiji", "Finland", "France", "French Guiana", "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guernsey", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard Island and McDonald Islands", "Holy See (Vatican City State)", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Isle of Man", "Israel", "Italy", "Jamaica", "Japan", "Jersey", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea", "Korea", "Kuwait", "Kyrgyz Republic", "Lao People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania", "Luxembourg", "Macao, Special Administrative Region of China", "Macedonia", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova", "Monaco", "Mongolia", "Montenegro", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands Antilles", "Netherlands", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Palestinian Territory", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russian Federation", "Rwanda", "Saint Barthelemy", "Saint Helena", "Saint Kitts and Nevis", "Saint Lucia", "Saint Martin", "Saint Pierre and Miquelon", "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Serbia", "Seychelles", "Sierra Leone", "Singapore", "Slovakia (Slovak Republic)", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard & Jan Mayen Islands", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "Timor-Leste", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States of America", "United States Minor Outlying Islands", "United States Virgin Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara", "Yemen", "Zambia", "Zimbabwe" }; private static String[] countryCodes = new String[]{ "AF", "AX", "AL", "DZ", "AS", "AD", "AO", "AI", "AQ", "AG", "AR", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB", "BY", "BE", "BZ", "BJ", "BM", "BT", "BO", "BA", "BW", "BV", "BR", "IO", "VG", "BN", "BG", "BF", "BI", "KH", "CM", "CA", "CV", "KY", "CF", "TD", "CL", "CN", "CX", "CC", "CO", "KM", "CD", "CG", "CK", "CR", "CI", "HR", "CU", "CY", "CZ", "DK", "DJ", "DM", "DO", "EC", "EG", "SV", "GQ", "ER", "EE", "ET", "FO", "FK", "FJ", "FI", "FR", "GF", "PF", "TF", "GA", "GM", "GE", "DE", "GH", "GI", "GR", "GL", "GD", "GP", "GU", "GT", "GG", "GN", "GW", "GY", "HT", "HM", "VA", "HN", "HK", "HU", "IS", "IN", "ID", "IR", "IQ", "IE", "IM", "IL", "IT", "JM", "JP", "JE", "JO", "KZ", "KE", "KI", "KP", "KR", "KW", "KG", "LA", "LV", "LB", "LS", "LR", "LY", "LI", "LT", "LU", "MO", "MK", "MG", "MW", "MY", "MV", "ML", "MT", "MH", "MQ", "MR", "MU", "YT", "MX", "FM", "MD", "MC", "MN", "ME", "MS", "MA", "MZ", "MM", "NA", "NR", "NP", "AN", "NL", "NC", "NZ", "NI", "NE", "NG", "NU", "NF", "MP", "NO", "OM", "PK", "PW", "PS", "PA", "PG", "PY", "PE", "PH", "PN", "PL", "PT", "PR", "QA", "RE", "RO", "RU", "RW", "BL", "SH", "KN", "LC", "MF", "PM", "VC", "WS", "SM", "ST", "SA", "SN", "RS", "SC", "SL", "SG", "SK", "SI", "SB", "SO", "ZA", "GS", "ES", "LK", "SD", "SR", "SJ", "SZ", "SE", "CH", "SY", "TW", "TJ", "TZ", "TH", "TL", "TG", "TK", "TO", "TT", "TN", "TR", "TM", "TC", "TV", "UG", "UA", "AE", "GB", "US", "UM", "VI", "UY", "UZ", "VU", "VE", "VN", "WF", "EH", "YE", "ZM", "ZW" }; private static String[] continentCodes = new String[]{ "AS", "EU", "EU", "AF", "OC", "EU", "AF", "NA", "AN", "NA", "SA", "AS", "NA", "OC", "EU", "AS", "NA", "AS", "AS", "NA", "EU", "EU", "NA", "AF", "NA", "AS", "SA", "EU", "AF", "AN", "SA", "AS", "NA", "AS", "EU", "AF", "AF", "AS", "AF", "NA", "AF", "NA", "AF", "AF", "SA", "AS", "AS", "AS", "SA", "AF", "AF", "AF", "OC", "NA", "AF", "EU", "NA", "AS", "EU", "EU", "AF", "NA", "NA", "SA", "AF", "NA", "AF", "AF", "EU", "AF", "EU", "SA", "OC", "EU", "EU", "SA", "OC", "AN", "AF", "AF", "AS", "EU", "AF", "EU", "EU", "NA", "NA", "NA", "OC", "NA", "EU", "AF", "AF", "SA", "NA", "AN", "EU", "NA", "AS", "EU", "EU", "AS", "AS", "AS", "AS", "EU", "EU", "AS", "EU", "NA", "AS", "EU", "AS", "AS", "AF", "OC", "AS", "AS", "AS", "AS", "AS", "EU", "AS", "AF", "AF", "AF", "EU", "EU", "EU", "AS", "EU", "AF", "AF", "AS", "AS", "AF", "EU", "OC", "NA", "AF", "AF", "AF", "NA", "OC", "EU", "EU", "AS", "EU", "NA", "AF", "AF", "AS", "AF", "OC", "AS", "NA", "EU", "OC", "OC", "NA", "AF", "AF", "OC", "OC", "OC", "EU", "AS", "AS", "OC", "AS", "NA", "OC", "SA", "SA", "AS", "OC", "EU", "EU", "NA", "AS", "AF", "EU", "EU", "AF", "NA", "AF", "NA", "NA", "NA", "NA", "NA", "OC", "EU", "AF", "AS", "AF", "EU", "AF", "AF", "AS", "EU", "EU", "OC", "AF", "AF", "AN", "EU", "AS", "AF", "SA", "EU", "AF", "EU", "EU", "AS", "AS", "AS", "AF", "AS", "AS", "AF", "OC", "OC", "NA", "AF", "AS", "AS", "NA", "OC", "AF", "EU", "AS", "EU", "NA", "OC", "NA", "SA", "AS", "OC", "SA", "AS", "OC", "AF", "AS", "AF", "AF", }; private static List continentCodeList; private static List countryCodeList; private static List countryNameList; static { if(countryCodeList == null) countryCodeList = Arrays.asList(countryCodes); if(continentCodeList == null) continentCodeList = Arrays.asList(continentCodes); if(countryNameList == null) countryNameList = Arrays.asList(countryNames); } private static String[][] continentCodeToName = new String[][]{ {"NA", "North America"}, {"SA", "South America"}, {"AN", "Antarctica"}, {"AF", "Africa"}, {"EU", "Europe"}, {"AS", "Asia"}, {"OC", "Oceania"}}; public static String getCountryName(String countryCode){ - int index = countryCodeList.indexOf(countryCode); - return countryNameList.get(index).toString(); + if (countryCode.length() > 0 && countryCodeList.contains(countryCode)) { + int index = countryCodeList.indexOf(countryCode); + return countryNameList.get(index).toString(); + } else { + return I18nUtil.getMessage("org.dspace.statistics.util.LocationUtils.unknown-country"); + } } public static String getContinentCode(String countryCode){ - int index = countryCodeList.indexOf(countryCode); - return continentCodeList.get(index).toString(); + if(countryCode.length() > 0 && countryCodeList.contains(countryCode)) { + int index = countryCodeList.indexOf(countryCode); + return continentCodeList.get(index).toString(); + } else { + return I18nUtil.getMessage("org.dspace.statistics.util.LocationUtils.unknown-continent"); + } } public static String getContinentName(String continentCode){ // String continentCode = getContinentCode(countryCode); for (String[] contCodeName : continentCodeToName) { if (contCodeName[0].equals(continentCode)) return contCodeName[1]; } return continentCode; } }
false
false
null
null
diff --git a/java/code/src/org/keyczar/PkcsKeyReader.java b/java/code/src/org/keyczar/PkcsKeyReader.java index 5bf3112..b192400 100644 --- a/java/code/src/org/keyczar/PkcsKeyReader.java +++ b/java/code/src/org/keyczar/PkcsKeyReader.java @@ -1,235 +1,235 @@ /* * Copyright 2011 Google 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 org.keyczar; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.interfaces.DSAPrivateKey; import java.security.interfaces.RSAPrivateCrtKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.crypto.Cipher; import javax.crypto.EncryptedPrivateKeyInfo; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEParameterSpec; import org.keyczar.enums.KeyPurpose; import org.keyczar.enums.KeyStatus; import org.keyczar.enums.KeyType; import org.keyczar.enums.RsaPadding; import org.keyczar.exceptions.KeyczarException; import org.keyczar.i18n.Messages; import org.keyczar.interfaces.KeyczarReader; import org.keyczar.util.Base64Coder; import org.keyczar.util.Util; /** * Keyczar Reader that reads from a PKCS#8 private key file, optionally * passphrase-encrypted. * * @author [email protected] (Shawn Willden) */ public class PkcsKeyReader implements KeyczarReader { private static final Pattern PEM_HEADER_PATTERN = Pattern.compile("-----BEGIN ([A-Z ]+)-----"); private static final Pattern PEM_FOOTER_PATTERN = Pattern.compile("-----END ([A-Z ]+)-----"); private final KeyPurpose purpose; private final InputStream pkcs8Stream; private final RsaPadding rsaPadding; private final String passphrase; private KeyMetadata meta; private KeyczarKey key; /** * Creates a PkcsKeyReader. * * @param purpose The purpose that will be specified for this key. PKCS#8 doesn't specify * a purpose, so it must be provided. * @param pkcs8Stream The input stream from which the PKCS#8-formatted key data will be read. * @param rsaPadding If the PKCS#8 stream contains an RSA key, padding may be specified. If * null, OAEP will be assumed. If the stream contains a DSA key, padding must be null. * @param passphrase The passphrase that will be used to decrypt the encrypted private key. If * the key is not encrypted, this should be null or the empty string. */ public PkcsKeyReader(KeyPurpose purpose, InputStream pkcs8Stream, RsaPadding rsaPadding, String passphrase) throws KeyczarException { if (purpose == null) { throw new KeyczarException("Key purpose must not be null"); } if (pkcs8Stream == null) { throw new KeyczarException("PKCS8 stream must not be null"); } this.purpose = purpose; this.pkcs8Stream = pkcs8Stream; this.rsaPadding = rsaPadding; this.passphrase = passphrase; } @Override public String getKey(int version) throws KeyczarException { ensureKeyRead(); return key.toString(); } @Override public String getKey() throws KeyczarException { ensureKeyRead(); return key.toString(); } @Override public String getMetadata() throws KeyczarException { ensureKeyRead(); return meta.toString(); } private void ensureKeyRead() throws KeyczarException { try { if (key == null) { key = parseKeyStream(pkcs8Stream, passphrase, rsaPadding); meta = constructMetadata(key, purpose); } } catch (IOException e) { throw new KeyczarException("Error Reading key", e); } } private static KeyMetadata constructMetadata(KeyczarKey key, KeyPurpose purpose) throws KeyczarException { validatePurpose(key, purpose); KeyMetadata meta = new KeyMetadata("imported from PKCS8 file", purpose, key.getType()); meta.addVersion(new KeyVersion(1, KeyStatus.PRIMARY, true /* exportable */)); return meta; } private static void validatePurpose(KeyczarKey key, KeyPurpose purpose) throws KeyczarException { if (purpose == KeyPurpose.ENCRYPT && key.getType() == KeyType.DSA_PUB) { throw new KeyczarException(Messages.getString("Keyczartool.InvalidUseOfDsaKey")); } } private static KeyczarKey parseKeyStream(InputStream pkcs8Stream, String passphrase, RsaPadding padding) throws IOException, KeyczarException { byte[] pkcs8Data = convertPemToDer(Util.readStreamFully(pkcs8Stream)); pkcs8Data = decryptPbeEncryptedKey(pkcs8Data, passphrase); PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(pkcs8Data); // There's no way to ask the kspec what type of key it contains, so we have to try each // type in turn. try { return new RsaPrivateKey( (RSAPrivateCrtKey) PkcsKeyReader.extractPrivateKey(kspec, "RSA"), padding); } catch (InvalidKeySpecException e) { // Not a valid RSA key, fall through. } try { KeyczarKey key = new DsaPrivateKey( (DSAPrivateKey) PkcsKeyReader.extractPrivateKey(kspec, "DSA")); if (padding != null) { throw new KeyczarException(Messages.getString("InvalidPadding", padding.name())); } return key; } catch (InvalidKeySpecException e) { //Not a valid DSA key, fall through. } throw new KeyczarException(Messages.getString("KeyczarTool.InvalidPkcs8Stream")); } private static PrivateKey extractPrivateKey(PKCS8EncodedKeySpec kspec, String algorithm) throws KeyczarException, InvalidKeySpecException { try { return KeyFactory.getInstance(algorithm).generatePrivate(kspec); } catch (NoSuchAlgorithmException e) { throw new KeyczarException(e); } } private static byte[] decryptPbeEncryptedKey(final byte[] pkcs8Data, final String passphrase) throws KeyczarException { - if (passphrase == null || passphrase.isEmpty()) { + if (passphrase == null || passphrase.length() == 0) { return pkcs8Data; } try { final EncryptedPrivateKeyInfo encryptedKeyInfo = new EncryptedPrivateKeyInfo(pkcs8Data); final PBEParameterSpec pbeParamSpec = encryptedKeyInfo.getAlgParameters().getParameterSpec(PBEParameterSpec.class); final String algName = encryptedKeyInfo.getAlgName(); final Cipher pbeCipher = Cipher.getInstance(algName); pbeCipher.init(Cipher.DECRYPT_MODE, computeDecryptionKey(passphrase, algName), pbeParamSpec); return pbeCipher.doFinal(encryptedKeyInfo.getEncryptedData()); } catch (NullPointerException e) { throw new KeyczarException(Messages.getString("KeyczarTool.UnknownKeyEncryption")); } catch (GeneralSecurityException e) { throw new KeyczarException(Messages.getString("KeyczarTool.UnknownKeyEncryption")); } catch (IOException e) { throw new KeyczarException(Messages.getString("KeyczarTool.UnknownKeyEncryption")); } } private static SecretKey computeDecryptionKey(final String passphrase, final String pbeAlgorithmName) throws NoSuchAlgorithmException, InvalidKeySpecException { final PBEKeySpec pbeKeySpec = new PBEKeySpec(passphrase.toCharArray()); final SecretKeyFactory pbeKeyFactory = SecretKeyFactory.getInstance(pbeAlgorithmName); return pbeKeyFactory.generateSecret(pbeKeySpec); } private static byte[] convertPemToDer(byte[] data) throws IOException, KeyczarException { BufferedReader bis = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(data))); String firstLine = bis.readLine(); Matcher headerMatcher = PEM_HEADER_PATTERN.matcher(firstLine); if (!headerMatcher.matches()) { // No properly-formatted header? Assume it's DER format. return data; } else { String header = headerMatcher.group(1); return decodeBase64(bis, header); } } private static byte[] decodeBase64(BufferedReader inputStream, String expectedFooter) throws IOException, KeyczarException { String line; ByteArrayOutputStream tempStream = new ByteArrayOutputStream(); while ((line = inputStream.readLine()) != null) { Matcher footerMatcher = PEM_FOOTER_PATTERN.matcher(line); if (!footerMatcher.matches()) { tempStream.write(Base64Coder.decodeMime(line)); } else if (footerMatcher.group(1).equals(expectedFooter)) { return tempStream.toByteArray(); } else { break; } } throw new KeyczarException(Messages.getString("KeyczarTool.InvalidPemFile")); } }
true
false
null
null
diff --git a/source/ictrobot/gems/magnetic/item/ItemRing.java b/source/ictrobot/gems/magnetic/item/ItemRing.java index 108ac8e..5581d8f 100644 --- a/source/ictrobot/gems/magnetic/item/ItemRing.java +++ b/source/ictrobot/gems/magnetic/item/ItemRing.java @@ -1,128 +1,142 @@ package ictrobot.gems.magnetic.item; import java.util.List; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import ictrobot.core.Core; public class ItemRing extends Item { int Level; public ItemRing(int id) { super(id); setTextureName(Core.ModID + ":" + "ItemRing"); setUnlocalizedName("ItemRing"); setCreativeTab(CreativeTabs.tabTools); setMaxStackSize(1); } @SuppressWarnings({ "rawtypes", "unchecked" }) public void onUpdate(ItemStack itemStack, World world, Entity entity, int par4, boolean par5) { if (Core.isServer()) { if( itemStack.getTagCompound() == null ) { itemStack.setTagCompound( new NBTTagCompound( )); itemStack.getTagCompound().setInteger("Delay", 10); } NBTTagCompound tag = itemStack.getTagCompound(); EntityPlayer player; if (tag.getBoolean("Enabled") && ((entity instanceof EntityPlayer))) { float radius = 10; player = (EntityPlayer)entity; final List<EntityItem> list = (List<EntityItem>)world.getEntitiesWithinAABB((Class)EntityItem.class, player.boundingBox.expand(radius, radius, radius)); for (final EntityItem e : list) { if (e.age >= tag.getInteger("Delay")) { if (Core.isServer() && player.inventory.addItemStackToInventory(e.getEntityItem())) { world.removeEntity(e); tag.setInteger("Pnum", tag.getInteger("Pnum")+1); tag.setDouble("P" + tag.getInteger("Pnum")+"x", e.posX); tag.setDouble("P" + tag.getInteger("Pnum")+"y", e.posY); tag.setDouble("P" + tag.getInteger("Pnum")+"z", e.posZ); tag.setInteger("P" + tag.getInteger("Pnum") + "t", 1); + tag.setBoolean("P" + tag.getInteger("Pnum") + "e", true); } } } - //System.out.println(tag.getInteger("Pnum")); - for(int i=1; i<=tag.getInteger("Pnum"); i++){ - int time = tag.getInteger("P" + i + "t"); - time++; - //System.out.println("t " + tag.getInteger("P" + 1 + "t") + "x " + tag.getDouble("P" + 1 + "x") + "y " + tag.getDouble("P" + 1 + "y") + "z " + tag.getDouble("P" + 1 + "z")); - if (time>20) { - tag.removeTag("P" + i + "t"); - tag.removeTag("P" + i + "x"); - tag.removeTag("P" + i + "y"); - tag.removeTag("P" + i + "z"); - } else { - tag.setInteger("P" + i + "t", time); + if (tag.getInteger("Pnum")>0) { + boolean shouldReset = true; + for(int i=1; i<=tag.getInteger("Pnum"); i++){ + if (tag.getInteger("P" + i + "t")!=0) { + int time = tag.getInteger("P" + i + "t"); + time++; + if (time>20) { + tag.removeTag("P" + i + "t"); + tag.removeTag("P" + i + "x"); + tag.removeTag("P" + i + "y"); + tag.removeTag("P" + i + "z"); + tag.setBoolean("P" + i + "e", false); + } else { + tag.setInteger("P" + i + "t", time); + } + } + if (tag.getBoolean("P" + i + "e")) { + shouldReset=false; + } + } + if (shouldReset) { + for(int i=1; i<=tag.getInteger("Pnum"); i++){ + tag.removeTag("P" + i + "e"); + } + tag.setInteger("Pnum", 0); } } } } else { NBTTagCompound tag = itemStack.getTagCompound(); if (tag!=null) { if (tag.getInteger("Pnum")>0) { for(int i=1; i<=tag.getInteger("Pnum"); i++){ world.spawnParticle("largesmoke", tag.getDouble("P" + i + "x"), tag.getDouble("P" + i + "y"), tag.getDouble("P" + i + "z"), 0, 0.1, 0); } } } } } public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player) { if (Core.isServer()) { if( itemStack.getTagCompound() == null ) { itemStack.setTagCompound( new NBTTagCompound( ) ); itemStack.getTagCompound().setInteger("Delay", 10); } NBTTagCompound tag = itemStack.getTagCompound(); if (player.isSneaking()) { if (!tag.getBoolean("Enabled")) { tag.setBoolean("Enabled", true); player.addChatMessage("\u00A73\u00A7lFlight Ring:\u00A7r\u00A77 Enabled"); } double time = tag.getInteger("Delay"); time = time / 20; time = time + 0.5; if (time>5) { time=0.5; } double ticks = time*20; int t = (int)ticks; tag.setInteger("Delay", t); player.addChatMessage("\u00A73\u00A7lItem Ring:\u00A7r\u00A77 Delay " + time); } else { if (tag.getBoolean("Enabled")) { tag.setBoolean("Enabled", false); player.addChatMessage("\u00A73\u00A7lItem Ring:\u00A7r\u00A77 Disabled"); } else { tag.setBoolean("Enabled", true); player.addChatMessage("\u00A73\u00A7lItem Ring:\u00A7r\u00A77 Enabled"); } } } return itemStack; } @SuppressWarnings({ "rawtypes", "unchecked" }) public void addInformation(ItemStack itemStack, EntityPlayer player, List par3List, boolean par4) { if( itemStack.getTagCompound() != null ) { NBTTagCompound tag = itemStack.getTagCompound(); if (tag.getBoolean("Enabled")) { par3List.add("\u00A77Enabled"); double time = tag.getInteger("Delay"); double delay = time/20; par3List.add("\u00A77Delay - " + delay + " seconds"); } else { par3List.add("\u00A77Disabled"); } } } }
false
true
public void onUpdate(ItemStack itemStack, World world, Entity entity, int par4, boolean par5) { if (Core.isServer()) { if( itemStack.getTagCompound() == null ) { itemStack.setTagCompound( new NBTTagCompound( )); itemStack.getTagCompound().setInteger("Delay", 10); } NBTTagCompound tag = itemStack.getTagCompound(); EntityPlayer player; if (tag.getBoolean("Enabled") && ((entity instanceof EntityPlayer))) { float radius = 10; player = (EntityPlayer)entity; final List<EntityItem> list = (List<EntityItem>)world.getEntitiesWithinAABB((Class)EntityItem.class, player.boundingBox.expand(radius, radius, radius)); for (final EntityItem e : list) { if (e.age >= tag.getInteger("Delay")) { if (Core.isServer() && player.inventory.addItemStackToInventory(e.getEntityItem())) { world.removeEntity(e); tag.setInteger("Pnum", tag.getInteger("Pnum")+1); tag.setDouble("P" + tag.getInteger("Pnum")+"x", e.posX); tag.setDouble("P" + tag.getInteger("Pnum")+"y", e.posY); tag.setDouble("P" + tag.getInteger("Pnum")+"z", e.posZ); tag.setInteger("P" + tag.getInteger("Pnum") + "t", 1); } } } //System.out.println(tag.getInteger("Pnum")); for(int i=1; i<=tag.getInteger("Pnum"); i++){ int time = tag.getInteger("P" + i + "t"); time++; //System.out.println("t " + tag.getInteger("P" + 1 + "t") + "x " + tag.getDouble("P" + 1 + "x") + "y " + tag.getDouble("P" + 1 + "y") + "z " + tag.getDouble("P" + 1 + "z")); if (time>20) { tag.removeTag("P" + i + "t"); tag.removeTag("P" + i + "x"); tag.removeTag("P" + i + "y"); tag.removeTag("P" + i + "z"); } else { tag.setInteger("P" + i + "t", time); } } } } else { NBTTagCompound tag = itemStack.getTagCompound(); if (tag!=null) { if (tag.getInteger("Pnum")>0) { for(int i=1; i<=tag.getInteger("Pnum"); i++){ world.spawnParticle("largesmoke", tag.getDouble("P" + i + "x"), tag.getDouble("P" + i + "y"), tag.getDouble("P" + i + "z"), 0, 0.1, 0); } } } } }
public void onUpdate(ItemStack itemStack, World world, Entity entity, int par4, boolean par5) { if (Core.isServer()) { if( itemStack.getTagCompound() == null ) { itemStack.setTagCompound( new NBTTagCompound( )); itemStack.getTagCompound().setInteger("Delay", 10); } NBTTagCompound tag = itemStack.getTagCompound(); EntityPlayer player; if (tag.getBoolean("Enabled") && ((entity instanceof EntityPlayer))) { float radius = 10; player = (EntityPlayer)entity; final List<EntityItem> list = (List<EntityItem>)world.getEntitiesWithinAABB((Class)EntityItem.class, player.boundingBox.expand(radius, radius, radius)); for (final EntityItem e : list) { if (e.age >= tag.getInteger("Delay")) { if (Core.isServer() && player.inventory.addItemStackToInventory(e.getEntityItem())) { world.removeEntity(e); tag.setInteger("Pnum", tag.getInteger("Pnum")+1); tag.setDouble("P" + tag.getInteger("Pnum")+"x", e.posX); tag.setDouble("P" + tag.getInteger("Pnum")+"y", e.posY); tag.setDouble("P" + tag.getInteger("Pnum")+"z", e.posZ); tag.setInteger("P" + tag.getInteger("Pnum") + "t", 1); tag.setBoolean("P" + tag.getInteger("Pnum") + "e", true); } } } if (tag.getInteger("Pnum")>0) { boolean shouldReset = true; for(int i=1; i<=tag.getInteger("Pnum"); i++){ if (tag.getInteger("P" + i + "t")!=0) { int time = tag.getInteger("P" + i + "t"); time++; if (time>20) { tag.removeTag("P" + i + "t"); tag.removeTag("P" + i + "x"); tag.removeTag("P" + i + "y"); tag.removeTag("P" + i + "z"); tag.setBoolean("P" + i + "e", false); } else { tag.setInteger("P" + i + "t", time); } } if (tag.getBoolean("P" + i + "e")) { shouldReset=false; } } if (shouldReset) { for(int i=1; i<=tag.getInteger("Pnum"); i++){ tag.removeTag("P" + i + "e"); } tag.setInteger("Pnum", 0); } } } } else { NBTTagCompound tag = itemStack.getTagCompound(); if (tag!=null) { if (tag.getInteger("Pnum")>0) { for(int i=1; i<=tag.getInteger("Pnum"); i++){ world.spawnParticle("largesmoke", tag.getDouble("P" + i + "x"), tag.getDouble("P" + i + "y"), tag.getDouble("P" + i + "z"), 0, 0.1, 0); } } } } }
diff --git a/src/com/android/launcher2/AppsCustomizePagedView.java b/src/com/android/launcher2/AppsCustomizePagedView.java index 9000049d..6667f7cc 100644 --- a/src/com/android/launcher2/AppsCustomizePagedView.java +++ b/src/com/android/launcher2/AppsCustomizePagedView.java @@ -1,1475 +1,1479 @@ /* * Copyright (C) 2011 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.launcher2; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProviderInfo; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.MaskFilter; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Bitmap.Config; import android.graphics.TableMaskFilter; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Process; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.AccelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.widget.GridLayout; import android.widget.ImageView; import android.widget.Toast; import com.android.launcher.R; import com.android.launcher2.DropTarget.DragObject; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * A simple callback interface which also provides the results of the task. */ interface AsyncTaskCallback { void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data); } /** * The data needed to perform either of the custom AsyncTasks. */ class AsyncTaskPageData { enum Type { LoadWidgetPreviewData, LoadHolographicIconsData } AsyncTaskPageData(int p, ArrayList<Object> l, ArrayList<Bitmap> si, AsyncTaskCallback bgR, AsyncTaskCallback postR) { page = p; items = l; sourceImages = si; generatedImages = new ArrayList<Bitmap>(); cellWidth = cellHeight = -1; doInBackgroundCallback = bgR; postExecuteCallback = postR; } AsyncTaskPageData(int p, ArrayList<Object> l, int cw, int ch, int ccx, AsyncTaskCallback bgR, AsyncTaskCallback postR) { page = p; items = l; generatedImages = new ArrayList<Bitmap>(); cellWidth = cw; cellHeight = ch; cellCountX = ccx; doInBackgroundCallback = bgR; postExecuteCallback = postR; } void cleanup(boolean cancelled) { // Clean up any references to source/generated bitmaps if (sourceImages != null) { if (cancelled) { for (Bitmap b : sourceImages) { b.recycle(); } } sourceImages.clear(); } if (generatedImages != null) { if (cancelled) { for (Bitmap b : generatedImages) { b.recycle(); } } generatedImages.clear(); } } int page; ArrayList<Object> items; ArrayList<Bitmap> sourceImages; ArrayList<Bitmap> generatedImages; int cellWidth; int cellHeight; int cellCountX; AsyncTaskCallback doInBackgroundCallback; AsyncTaskCallback postExecuteCallback; } /** * A generic template for an async task used in AppsCustomize. */ class AppsCustomizeAsyncTask extends AsyncTask<AsyncTaskPageData, Void, AsyncTaskPageData> { AppsCustomizeAsyncTask(int p, AsyncTaskPageData.Type ty) { page = p; threadPriority = Process.THREAD_PRIORITY_DEFAULT; dataType = ty; } @Override protected AsyncTaskPageData doInBackground(AsyncTaskPageData... params) { if (params.length != 1) return null; // Load each of the widget previews in the background params[0].doInBackgroundCallback.run(this, params[0]); return params[0]; } @Override protected void onPostExecute(AsyncTaskPageData result) { // All the widget previews are loaded, so we can just callback to inflate the page result.postExecuteCallback.run(this, result); } void setThreadPriority(int p) { threadPriority = p; } void syncThreadPriority() { Process.setThreadPriority(threadPriority); } // The page that this async task is associated with AsyncTaskPageData.Type dataType; int page; int threadPriority; } /** * The Apps/Customize page that displays all the applications, widgets, and shortcuts. */ public class AppsCustomizePagedView extends PagedViewWithDraggableItems implements AllAppsView, View.OnClickListener, DragSource { static final String LOG_TAG = "AppsCustomizePagedView"; /** * The different content types that this paged view can show. */ public enum ContentType { Applications, Widgets } // Refs private Launcher mLauncher; private DragController mDragController; private final LayoutInflater mLayoutInflater; private final PackageManager mPackageManager; // Save and Restore private int mSaveInstanceStateItemIndex = -1; // Content private ArrayList<ApplicationInfo> mApps; private ArrayList<Object> mWidgets; // Cling private int mClingFocusedX; private int mClingFocusedY; // Caching private Canvas mCanvas; private Drawable mDefaultWidgetBackground; private IconCache mIconCache; private int mDragViewMultiplyColor; // Dimens private int mContentWidth; private int mAppIconSize; + private int mMaxAppCellCountX, mMaxAppCellCountY; private int mWidgetCountX, mWidgetCountY; private int mWidgetWidthGap, mWidgetHeightGap; private final int mWidgetPreviewIconPaddedDimension; private final float sWidgetPreviewIconPaddingPercentage = 0.25f; private PagedViewCellLayout mWidgetSpacingLayout; private int mNumAppsPages; private int mNumWidgetPages; // Relating to the scroll and overscroll effects Workspace.ZInterpolator mZInterpolator = new Workspace.ZInterpolator(0.5f); private static float CAMERA_DISTANCE = 6500; private static float TRANSITION_SCALE_FACTOR = 0.74f; private static float TRANSITION_PIVOT = 0.65f; private static float TRANSITION_MAX_ROTATION = 22; private static final boolean PERFORM_OVERSCROLL_ROTATION = true; private AccelerateInterpolator mAlphaInterpolator = new AccelerateInterpolator(0.9f); private DecelerateInterpolator mLeftScreenAlphaInterpolator = new DecelerateInterpolator(4); // Previews & outlines ArrayList<AppsCustomizeAsyncTask> mRunningTasks; private HolographicOutlineHelper mHolographicOutlineHelper; private static final int sPageSleepDelay = 150; public AppsCustomizePagedView(Context context, AttributeSet attrs) { super(context, attrs); mLayoutInflater = LayoutInflater.from(context); mPackageManager = context.getPackageManager(); mApps = new ArrayList<ApplicationInfo>(); mWidgets = new ArrayList<Object>(); mIconCache = ((LauncherApplication) context.getApplicationContext()).getIconCache(); mHolographicOutlineHelper = new HolographicOutlineHelper(); mCanvas = new Canvas(); mRunningTasks = new ArrayList<AppsCustomizeAsyncTask>(); // Save the default widget preview background Resources resources = context.getResources(); mDefaultWidgetBackground = resources.getDrawable(R.drawable.default_widget_preview_holo); mAppIconSize = resources.getDimensionPixelSize(R.dimen.app_icon_size); mDragViewMultiplyColor = resources.getColor(R.color.drag_view_multiply_color); - TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PagedView, 0, 0); - // TODO-APPS_CUSTOMIZE: remove these unnecessary attrs after - mCellCountX = a.getInt(R.styleable.PagedView_cellCountX, 6); - mCellCountY = a.getInt(R.styleable.PagedView_cellCountY, 4); - a.recycle(); - a = context.obtainStyledAttributes(attrs, R.styleable.AppsCustomizePagedView, 0, 0); + TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AppsCustomizePagedView, 0, 0); + mMaxAppCellCountX = a.getInt(R.styleable.AppsCustomizePagedView_maxAppCellCountX, -1); + mMaxAppCellCountY = a.getInt(R.styleable.AppsCustomizePagedView_maxAppCellCountY, -1); mWidgetWidthGap = a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellWidthGap, 0); mWidgetHeightGap = a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellHeightGap, 0); mWidgetCountX = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountX, 2); mWidgetCountY = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountY, 2); mClingFocusedX = a.getInt(R.styleable.AppsCustomizePagedView_clingFocusedX, 0); mClingFocusedY = a.getInt(R.styleable.AppsCustomizePagedView_clingFocusedY, 0); a.recycle(); mWidgetSpacingLayout = new PagedViewCellLayout(getContext()); // The padding on the non-matched dimension for the default widget preview icons // (top + bottom) mWidgetPreviewIconPaddedDimension = (int) (mAppIconSize * (1 + (2 * sWidgetPreviewIconPaddingPercentage))); mFadeInAdjacentScreens = false; } @Override protected void init() { super.init(); mCenterPagesVertically = false; Context context = getContext(); Resources r = context.getResources(); setDragSlopeThreshold(r.getInteger(R.integer.config_appsCustomizeDragSlopeThreshold)/100f); } @Override protected void onUnhandledTap(MotionEvent ev) { if (LauncherApplication.isScreenLarge()) { // Dismiss AppsCustomize if we tap mLauncher.showWorkspace(true); } } /** Returns the item index of the center item on this page so that we can restore to this * item index when we rotate. */ private int getMiddleComponentIndexOnCurrentPage() { int i = -1; if (getPageCount() > 0) { int currentPage = getCurrentPage(); if (currentPage < mNumAppsPages) { PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(currentPage); PagedViewCellLayoutChildren childrenLayout = layout.getChildrenLayout(); int numItemsPerPage = mCellCountX * mCellCountY; int childCount = childrenLayout.getChildCount(); if (childCount > 0) { i = (currentPage * numItemsPerPage) + (childCount / 2); } } else { int numApps = mApps.size(); PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(currentPage); int numItemsPerPage = mWidgetCountX * mWidgetCountY; int childCount = layout.getChildCount(); if (childCount > 0) { i = numApps + ((currentPage - mNumAppsPages) * numItemsPerPage) + (childCount / 2); } } } return i; } /** Get the index of the item to restore to if we need to restore the current page. */ int getSaveInstanceStateIndex() { if (mSaveInstanceStateItemIndex == -1) { mSaveInstanceStateItemIndex = getMiddleComponentIndexOnCurrentPage(); } return mSaveInstanceStateItemIndex; } /** Returns the page in the current orientation which is expected to contain the specified * item index. */ int getPageForComponent(int index) { if (index < 0) return 0; if (index < mApps.size()) { int numItemsPerPage = mCellCountX * mCellCountY; return (index / numItemsPerPage); } else { int numItemsPerPage = mWidgetCountX * mWidgetCountY; return mNumAppsPages + ((index - mApps.size()) / numItemsPerPage); } } /** * This differs from isDataReady as this is the test done if isDataReady is not set. */ private boolean testDataReady() { // We only do this test once, and we default to the Applications page, so we only really // have to wait for there to be apps. // TODO: What if one of them is validly empty return !mApps.isEmpty() && !mWidgets.isEmpty(); } /** Restores the page for an item at the specified index */ void restorePageForIndex(int index) { if (index < 0) return; mSaveInstanceStateItemIndex = index; } private void updatePageCounts() { mNumWidgetPages = (int) Math.ceil(mWidgets.size() / (float) (mWidgetCountX * mWidgetCountY)); mNumAppsPages = (int) Math.ceil((float) mApps.size() / (mCellCountX * mCellCountY)); } protected void onDataReady(int width, int height) { // Note that we transpose the counts in portrait so that we get a similar layout boolean isLandscape = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; int maxCellCountX = Integer.MAX_VALUE; int maxCellCountY = Integer.MAX_VALUE; if (LauncherApplication.isScreenLarge()) { maxCellCountX = (isLandscape ? LauncherModel.getCellCountX() : LauncherModel.getCellCountY()); maxCellCountY = (isLandscape ? LauncherModel.getCellCountY() : LauncherModel.getCellCountX()); } + if (mMaxAppCellCountX > -1) { + maxCellCountX = Math.min(maxCellCountX, mMaxAppCellCountX); + } + if (mMaxAppCellCountY > -1) { + maxCellCountY = Math.min(maxCellCountY, mMaxAppCellCountY); + } // Now that the data is ready, we can calculate the content width, the number of cells to // use for each page mWidgetSpacingLayout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap); mWidgetSpacingLayout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop, mPageLayoutPaddingRight, mPageLayoutPaddingBottom); mWidgetSpacingLayout.calculateCellCount(width, height, maxCellCountX, maxCellCountY); mCellCountX = mWidgetSpacingLayout.getCellCountX(); mCellCountY = mWidgetSpacingLayout.getCellCountY(); updatePageCounts(); // Force a measure to update recalculate the gaps int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST); int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST); mWidgetSpacingLayout.measure(widthSpec, heightSpec); mContentWidth = mWidgetSpacingLayout.getContentWidth(); // Restore the page int page = getPageForComponent(mSaveInstanceStateItemIndex); invalidatePageData(Math.max(0, page)); // Calculate the position for the cling punch through int[] offset = new int[2]; int[] pos = mWidgetSpacingLayout.estimateCellPosition(mClingFocusedX, mClingFocusedY); mLauncher.getDragLayer().getLocationInDragLayer(this, offset); pos[0] += (getMeasuredWidth() - mWidgetSpacingLayout.getMeasuredWidth()) / 2 + offset[0]; pos[1] += (getMeasuredHeight() - mWidgetSpacingLayout.getMeasuredHeight()) / 2 + offset[1]; mLauncher.showFirstRunAllAppsCling(pos); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = MeasureSpec.getSize(widthMeasureSpec); int height = MeasureSpec.getSize(heightMeasureSpec); if (!isDataReady()) { if (testDataReady()) { setDataIsReady(); setMeasuredDimension(width, height); onDataReady(width, height); } } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } /** Removes and returns the ResolveInfo with the specified ComponentName */ private ResolveInfo removeResolveInfoWithComponentName(List<ResolveInfo> list, ComponentName cn) { Iterator<ResolveInfo> iter = list.iterator(); while (iter.hasNext()) { ResolveInfo rinfo = iter.next(); ActivityInfo info = rinfo.activityInfo; ComponentName c = new ComponentName(info.packageName, info.name); if (c.equals(cn)) { iter.remove(); return rinfo; } } return null; } public void onPackagesUpdated() { // TODO: this isn't ideal, but we actually need to delay here. This call is triggered // by a broadcast receiver, and in order for it to work correctly, we need to know that // the AppWidgetService has already received and processed the same broadcast. Since there // is no guarantee about ordering of broadcast receipt, we just delay here. Ideally, // we should have a more precise way of ensuring the AppWidgetService is up to date. postDelayed(new Runnable() { public void run() { updatePackages(); } }, 500); } public void updatePackages() { // Get the list of widgets and shortcuts boolean wasEmpty = mWidgets.isEmpty(); mWidgets.clear(); List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(mLauncher).getInstalledProviders(); Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); List<ResolveInfo> shortcuts = mPackageManager.queryIntentActivities(shortcutsIntent, 0); mWidgets.addAll(widgets); mWidgets.addAll(shortcuts); Collections.sort(mWidgets, new LauncherModel.WidgetAndShortcutNameComparator(mPackageManager)); updatePageCounts(); if (wasEmpty) { // The next layout pass will trigger data-ready if both widgets and apps are set, so request // a layout to do this test and invalidate the page data when ready. if (testDataReady()) requestLayout(); } else { cancelAllTasks(); invalidatePageData(); } } @Override public void onClick(View v) { // When we have exited all apps or are in transition, disregard clicks if (!mLauncher.isAllAppsCustomizeOpen() || mLauncher.getWorkspace().isSwitchingState()) return; if (v instanceof PagedViewIcon) { // Animate some feedback to the click final ApplicationInfo appInfo = (ApplicationInfo) v.getTag(); animateClickFeedback(v, new Runnable() { @Override public void run() { mLauncher.startActivitySafely(appInfo.intent, appInfo); } }); } else if (v instanceof PagedViewWidget) { // Let the user know that they have to long press to add a widget Toast.makeText(getContext(), R.string.long_press_widget_to_add, Toast.LENGTH_SHORT).show(); // Create a little animation to show that the widget can move float offsetY = getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY); final ImageView p = (ImageView) v.findViewById(R.id.widget_preview); AnimatorSet bounce = new AnimatorSet(); ValueAnimator tyuAnim = ObjectAnimator.ofFloat(p, "translationY", offsetY); tyuAnim.setDuration(125); ValueAnimator tydAnim = ObjectAnimator.ofFloat(p, "translationY", 0f); tydAnim.setDuration(100); bounce.play(tyuAnim).before(tydAnim); bounce.setInterpolator(new AccelerateInterpolator()); bounce.start(); } } /* * PagedViewWithDraggableItems implementation */ @Override protected void determineDraggingStart(android.view.MotionEvent ev) { // Disable dragging by pulling an app down for now. } private void beginDraggingApplication(View v) { mLauncher.getWorkspace().onDragStartedWithItem(v); mLauncher.getWorkspace().beginDragShared(v, this); } private void beginDraggingWidget(View v) { // Get the widget preview as the drag representation ImageView image = (ImageView) v.findViewById(R.id.widget_preview); PendingAddItemInfo createItemInfo = (PendingAddItemInfo) v.getTag(); // Compose the drag image Bitmap b; Drawable preview = image.getDrawable(); RectF mTmpScaleRect = new RectF(0f,0f,1f,1f); image.getImageMatrix().mapRect(mTmpScaleRect); float scale = mTmpScaleRect.right; int w = (int) (preview.getIntrinsicWidth() * scale); int h = (int) (preview.getIntrinsicHeight() * scale); if (createItemInfo instanceof PendingAddWidgetInfo) { PendingAddWidgetInfo createWidgetInfo = (PendingAddWidgetInfo) createItemInfo; int[] spanXY = mLauncher.getSpanForWidget(createWidgetInfo, null); createItemInfo.spanX = spanXY[0]; createItemInfo.spanY = spanXY[1]; b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); renderDrawableToBitmap(preview, b, 0, 0, w, h, scale, mDragViewMultiplyColor); } else { // Workaround for the fact that we don't keep the original ResolveInfo associated with // the shortcut around. To get the icon, we just render the preview image (which has // the shortcut icon) to a new drag bitmap that clips the non-icon space. b = Bitmap.createBitmap(mWidgetPreviewIconPaddedDimension, mWidgetPreviewIconPaddedDimension, Bitmap.Config.ARGB_8888); mCanvas.setBitmap(b); mCanvas.save(); preview.draw(mCanvas); mCanvas.restore(); mCanvas.drawColor(mDragViewMultiplyColor, PorterDuff.Mode.MULTIPLY); mCanvas.setBitmap(null); createItemInfo.spanX = createItemInfo.spanY = 1; } // We use a custom alpha clip table for the default widget previews Paint alphaClipPaint = null; if (createItemInfo instanceof PendingAddWidgetInfo) { if (((PendingAddWidgetInfo) createItemInfo).hasDefaultPreview) { MaskFilter alphaClipTable = TableMaskFilter.CreateClipTable(0, 255); alphaClipPaint = new Paint(); alphaClipPaint.setMaskFilter(alphaClipTable); } } // Start the drag mLauncher.lockScreenOrientationOnLargeUI(); mLauncher.getWorkspace().onDragStartedWithItemSpans(createItemInfo.spanX, createItemInfo.spanY, b, alphaClipPaint); mDragController.startDrag(image, b, this, createItemInfo, DragController.DRAG_ACTION_COPY, null); b.recycle(); } @Override protected boolean beginDragging(View v) { // Dismiss the cling mLauncher.dismissAllAppsCling(null); if (!super.beginDragging(v)) return false; // Go into spring loaded mode (must happen before we startDrag()) mLauncher.enterSpringLoadedDragMode(); if (v instanceof PagedViewIcon) { beginDraggingApplication(v); } else if (v instanceof PagedViewWidget) { beginDraggingWidget(v); } return true; } private void endDragging(View target, boolean success) { mLauncher.getWorkspace().onDragStopped(success); if (!success || (target != mLauncher.getWorkspace() && !(target instanceof DeleteDropTarget))) { // Exit spring loaded mode if we have not successfully dropped or have not handled the // drop in Workspace mLauncher.exitSpringLoadedDragMode(); } mLauncher.unlockScreenOrientationOnLargeUI(); } @Override public void onDropCompleted(View target, DragObject d, boolean success) { endDragging(target, success); // Display an error message if the drag failed due to there not being enough space on the // target layout we were dropping on. if (!success) { boolean showOutOfSpaceMessage = false; if (target instanceof Workspace) { int currentScreen = mLauncher.getCurrentWorkspaceScreen(); Workspace workspace = (Workspace) target; CellLayout layout = (CellLayout) workspace.getChildAt(currentScreen); ItemInfo itemInfo = (ItemInfo) d.dragInfo; if (layout != null) { layout.calculateSpans(itemInfo); showOutOfSpaceMessage = !layout.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY); } } if (showOutOfSpaceMessage) { mLauncher.showOutOfSpaceMessage(); } } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); cancelAllTasks(); } private void cancelAllTasks() { // Clean up all the async tasks Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator(); while (iter.hasNext()) { AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next(); task.cancel(false); iter.remove(); } } public void setContentType(ContentType type) { if (type == ContentType.Widgets) { invalidatePageData(mNumAppsPages, true); } else if (type == ContentType.Applications) { invalidatePageData(0, true); } } protected void snapToPage(int whichPage, int delta, int duration) { super.snapToPage(whichPage, delta, duration); updateCurrentTab(whichPage); } private void updateCurrentTab(int currentPage) { AppsCustomizeTabHost tabHost = getTabHost(); String tag = tabHost.getCurrentTabTag(); if (tag != null) { if (currentPage >= mNumAppsPages && !tag.equals(tabHost.getTabTagForContentType(ContentType.Widgets))) { tabHost.setCurrentTabFromContent(ContentType.Widgets); } else if (currentPage < mNumAppsPages && !tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) { tabHost.setCurrentTabFromContent(ContentType.Applications); } } } /* * Apps PagedView implementation */ private void setVisibilityOnChildren(ViewGroup layout, int visibility) { int childCount = layout.getChildCount(); for (int i = 0; i < childCount; ++i) { layout.getChildAt(i).setVisibility(visibility); } } private void setupPage(PagedViewCellLayout layout) { layout.setCellCount(mCellCountX, mCellCountY); layout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap); layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop, mPageLayoutPaddingRight, mPageLayoutPaddingBottom); // Note: We force a measure here to get around the fact that when we do layout calculations // immediately after syncing, we don't have a proper width. That said, we already know the // expected page width, so we can actually optimize by hiding all the TextView-based // children that are expensive to measure, and let that happen naturally later. setVisibilityOnChildren(layout, View.GONE); int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST); int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST); layout.setMinimumWidth(getPageContentWidth()); layout.measure(widthSpec, heightSpec); setVisibilityOnChildren(layout, View.VISIBLE); } public void syncAppsPageItems(int page, boolean immediate) { // ensure that we have the right number of items on the pages int numCells = mCellCountX * mCellCountY; int startIndex = page * numCells; int endIndex = Math.min(startIndex + numCells, mApps.size()); PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(page); layout.removeAllViewsOnPage(); ArrayList<Object> items = new ArrayList<Object>(); ArrayList<Bitmap> images = new ArrayList<Bitmap>(); for (int i = startIndex; i < endIndex; ++i) { ApplicationInfo info = mApps.get(i); PagedViewIcon icon = (PagedViewIcon) mLayoutInflater.inflate( R.layout.apps_customize_application, layout, false); icon.applyFromApplicationInfo(info, true, mHolographicOutlineHelper); icon.setOnClickListener(this); icon.setOnLongClickListener(this); icon.setOnTouchListener(this); int index = i - startIndex; int x = index % mCellCountX; int y = index / mCellCountX; layout.addViewToCellLayout(icon, -1, i, new PagedViewCellLayout.LayoutParams(x,y, 1,1)); items.add(info); images.add(info.iconBitmap); } layout.createHardwareLayers(); /* TEMPORARILY DISABLE HOLOGRAPHIC ICONS if (mFadeInAdjacentScreens) { prepareGenerateHoloOutlinesTask(page, items, images); } */ } /** * Return the appropriate thread priority for loading for a given page (we give the current * page much higher priority) */ private int getThreadPriorityForPage(int page) { // TODO-APPS_CUSTOMIZE: detect number of cores and set thread priorities accordingly below int pageDiff = Math.abs(page - mCurrentPage); if (pageDiff <= 0) { // return Process.THREAD_PRIORITY_DEFAULT; return Process.THREAD_PRIORITY_MORE_FAVORABLE; } else if (pageDiff <= 1) { // return Process.THREAD_PRIORITY_BACKGROUND; return Process.THREAD_PRIORITY_DEFAULT; } else { // return Process.THREAD_PRIORITY_LOWEST; return Process.THREAD_PRIORITY_DEFAULT; } } private int getSleepForPage(int page) { int pageDiff = Math.abs(page - mCurrentPage) - 1; return Math.max(0, pageDiff * sPageSleepDelay); } /** * Creates and executes a new AsyncTask to load a page of widget previews. */ private void prepareLoadWidgetPreviewsTask(int page, ArrayList<Object> widgets, int cellWidth, int cellHeight, int cellCountX) { // Prune all tasks that are no longer needed Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator(); while (iter.hasNext()) { AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next(); int taskPage = task.page; if ((taskPage == page) || taskPage < getAssociatedLowerPageBound(mCurrentPage - mNumAppsPages) || taskPage > getAssociatedUpperPageBound(mCurrentPage - mNumAppsPages)) { task.cancel(false); iter.remove(); } else { task.setThreadPriority(getThreadPriorityForPage(taskPage + mNumAppsPages)); } } // We introduce a slight delay to order the loading of side pages so that we don't thrash final int sleepMs = getSleepForPage(page + mNumAppsPages); AsyncTaskPageData pageData = new AsyncTaskPageData(page, widgets, cellWidth, cellHeight, cellCountX, new AsyncTaskCallback() { @Override public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) { try { try { Thread.sleep(sleepMs); } catch (Exception e) {} loadWidgetPreviewsInBackground(task, data); } finally { if (task.isCancelled()) { data.cleanup(true); } } } }, new AsyncTaskCallback() { @Override public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) { try { mRunningTasks.remove(task); if (task.isCancelled()) return; onSyncWidgetPageItems(data); } finally { data.cleanup(task.isCancelled()); } } }); // Ensure that the task is appropriately prioritized and runs in parallel AppsCustomizeAsyncTask t = new AppsCustomizeAsyncTask(page, AsyncTaskPageData.Type.LoadWidgetPreviewData); t.setThreadPriority(getThreadPriorityForPage(page)); t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageData); mRunningTasks.add(t); } /** * Creates and executes a new AsyncTask to load the outlines for a page of content. */ private void prepareGenerateHoloOutlinesTask(int page, ArrayList<Object> items, ArrayList<Bitmap> images) { // Prune old tasks for this page Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator(); while (iter.hasNext()) { AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next(); int taskPage = task.page; if ((taskPage == page) && (task.dataType == AsyncTaskPageData.Type.LoadHolographicIconsData)) { task.cancel(false); iter.remove(); } } AsyncTaskPageData pageData = new AsyncTaskPageData(page, items, images, new AsyncTaskCallback() { @Override public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) { try { // Ensure that this task starts running at the correct priority task.syncThreadPriority(); ArrayList<Bitmap> images = data.generatedImages; ArrayList<Bitmap> srcImages = data.sourceImages; int count = srcImages.size(); Canvas c = new Canvas(); for (int i = 0; i < count && !task.isCancelled(); ++i) { // Before work on each item, ensure that this task is running at the correct // priority task.syncThreadPriority(); Bitmap b = srcImages.get(i); Bitmap outline = Bitmap.createBitmap(b.getWidth(), b.getHeight(), Bitmap.Config.ARGB_8888); c.setBitmap(outline); c.save(); c.drawBitmap(b, 0, 0, null); c.restore(); c.setBitmap(null); images.add(outline); } } finally { if (task.isCancelled()) { data.cleanup(true); } } } }, new AsyncTaskCallback() { @Override public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) { try { mRunningTasks.remove(task); if (task.isCancelled()) return; onHolographicPageItemsLoaded(data); } finally { data.cleanup(task.isCancelled()); } } }); // Ensure that the outline task always runs in the background, serially AppsCustomizeAsyncTask t = new AppsCustomizeAsyncTask(page, AsyncTaskPageData.Type.LoadHolographicIconsData); t.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); t.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, pageData); mRunningTasks.add(t); } /* * Widgets PagedView implementation */ private void setupPage(PagedViewGridLayout layout) { layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop, mPageLayoutPaddingRight, mPageLayoutPaddingBottom); // Note: We force a measure here to get around the fact that when we do layout calculations // immediately after syncing, we don't have a proper width. int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST); int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST); layout.setMinimumWidth(getPageContentWidth()); layout.measure(widthSpec, heightSpec); } private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h) { renderDrawableToBitmap(d, bitmap, x, y, w, h, 1f, 0xFFFFFFFF); } private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h, float scale) { renderDrawableToBitmap(d, bitmap, x, y, w, h, scale, 0xFFFFFFFF); } private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h, float scale, int multiplyColor) { if (bitmap != null) { Canvas c = new Canvas(bitmap); c.scale(scale, scale); Rect oldBounds = d.copyBounds(); d.setBounds(x, y, x + w, y + h); d.draw(c); d.setBounds(oldBounds); // Restore the bounds if (multiplyColor != 0xFFFFFFFF) { c.drawColor(mDragViewMultiplyColor, PorterDuff.Mode.MULTIPLY); } c.setBitmap(null); } } private Bitmap getShortcutPreview(ResolveInfo info, int cellWidth, int cellHeight) { // Render the background int offset = 0; int bitmapSize = mAppIconSize; Bitmap preview = Bitmap.createBitmap(bitmapSize, bitmapSize, Config.ARGB_8888); // Render the icon Drawable icon = mIconCache.getFullResIcon(info); renderDrawableToBitmap(icon, preview, offset, offset, mAppIconSize, mAppIconSize); return preview; } private Bitmap getWidgetPreview(AppWidgetProviderInfo info, int cellHSpan, int cellVSpan, int cellWidth, int cellHeight) { // Load the preview image if possible String packageName = info.provider.getPackageName(); Drawable drawable = null; Bitmap preview = null; if (info.previewImage != 0) { drawable = mPackageManager.getDrawable(packageName, info.previewImage, null); if (drawable == null) { Log.w(LOG_TAG, "Can't load icon drawable 0x" + Integer.toHexString(info.icon) + " for provider: " + info.provider); } else { // Map the target width/height to the cell dimensions int targetWidth = mWidgetSpacingLayout.estimateCellWidth(cellHSpan); int targetHeight = mWidgetSpacingLayout.estimateCellHeight(cellVSpan); int targetCellWidth; int targetCellHeight; if (targetWidth >= targetHeight) { targetCellWidth = Math.min(targetWidth, cellWidth); targetCellHeight = (int) (cellHeight * ((float) targetCellWidth / cellWidth)); } else { targetCellHeight = Math.min(targetHeight, cellHeight); targetCellWidth = (int) (cellWidth * ((float) targetCellHeight / cellHeight)); } // Map the preview to the target cell dimensions int bitmapWidth = Math.min(targetCellWidth, drawable.getIntrinsicWidth()); int bitmapHeight = (int) (drawable.getIntrinsicHeight() * ((float) bitmapWidth / drawable.getIntrinsicWidth())); preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.ARGB_8888); renderDrawableToBitmap(drawable, preview, 0, 0, bitmapWidth, bitmapHeight); } } // Generate a preview image if we couldn't load one if (drawable == null) { Resources resources = mLauncher.getResources(); // TODO: This actually uses the apps customize cell layout params, where as we make want // the Workspace params for more accuracy. int targetWidth = mWidgetSpacingLayout.estimateCellWidth(cellHSpan); int targetHeight = mWidgetSpacingLayout.estimateCellHeight(cellVSpan); int bitmapWidth = targetWidth; int bitmapHeight = targetHeight; int minOffset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage); float iconScale = 1f; // Determine the size of the bitmap we want to draw if (cellHSpan == cellVSpan) { // For square widgets, we just have a fixed size for 1x1 and larger-than-1x1 if (cellHSpan <= 1) { bitmapWidth = bitmapHeight = mAppIconSize + 2 * minOffset; } else { bitmapWidth = bitmapHeight = mAppIconSize + 4 * minOffset; } } else { // Otherwise, ensure that we are properly sized within the cellWidth/Height if (targetWidth >= targetHeight) { bitmapWidth = Math.min(targetWidth, cellWidth); bitmapHeight = (int) (targetHeight * ((float) bitmapWidth / targetWidth)); iconScale = Math.min((float) bitmapHeight / (mAppIconSize + 2 * minOffset), 1f); } else { bitmapHeight = Math.min(targetHeight, cellHeight); bitmapWidth = (int) (targetWidth * ((float) bitmapHeight / targetHeight)); iconScale = Math.min((float) bitmapWidth / (mAppIconSize + 2 * minOffset), 1f); } } preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.ARGB_8888); if (cellHSpan != 1 || cellVSpan != 1) { renderDrawableToBitmap(mDefaultWidgetBackground, preview, 0, 0, bitmapWidth, bitmapHeight); } // Draw the icon in the top left corner try { Drawable icon = null; int hoffset = (int) (bitmapWidth / 2 - mAppIconSize * iconScale / 2); int yoffset = (int) (bitmapHeight / 2 - mAppIconSize * iconScale / 2); if (info.icon > 0) icon = mIconCache.getFullResIcon(packageName, info.icon); if (icon == null) icon = resources.getDrawable(R.drawable.ic_launcher_application); renderDrawableToBitmap(icon, preview, hoffset, yoffset, (int) (mAppIconSize * iconScale), (int) (mAppIconSize * iconScale)); } catch (Resources.NotFoundException e) {} } return preview; } public void syncWidgetPageItems(int page, boolean immediate) { int numItemsPerPage = mWidgetCountX * mWidgetCountY; int contentWidth = mWidgetSpacingLayout.getContentWidth(); int contentHeight = mWidgetSpacingLayout.getContentHeight(); // Calculate the dimensions of each cell we are giving to each widget ArrayList<Object> items = new ArrayList<Object>(); int cellWidth = ((contentWidth - mPageLayoutPaddingLeft - mPageLayoutPaddingRight - ((mWidgetCountX - 1) * mWidgetWidthGap)) / mWidgetCountX); int cellHeight = ((contentHeight - mPageLayoutPaddingTop - mPageLayoutPaddingBottom - ((mWidgetCountY - 1) * mWidgetHeightGap)) / mWidgetCountY); // Prepare the set of widgets to load previews for in the background int offset = page * numItemsPerPage; for (int i = offset; i < Math.min(offset + numItemsPerPage, mWidgets.size()); ++i) { items.add(mWidgets.get(i)); } // Prepopulate the pages with the other widget info, and fill in the previews later PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page + mNumAppsPages); layout.setColumnCount(layout.getCellCountX()); for (int i = 0; i < items.size(); ++i) { Object rawInfo = items.get(i); PendingAddItemInfo createItemInfo = null; PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate( R.layout.apps_customize_widget, layout, false); if (rawInfo instanceof AppWidgetProviderInfo) { // Fill in the widget information AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo; createItemInfo = new PendingAddWidgetInfo(info, null, null); int[] cellSpans = mLauncher.getSpanForWidget(info, null); widget.applyFromAppWidgetProviderInfo(info, -1, cellSpans, mHolographicOutlineHelper); widget.setTag(createItemInfo); } else if (rawInfo instanceof ResolveInfo) { // Fill in the shortcuts information ResolveInfo info = (ResolveInfo) rawInfo; createItemInfo = new PendingAddItemInfo(); createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; createItemInfo.componentName = new ComponentName(info.activityInfo.packageName, info.activityInfo.name); widget.applyFromResolveInfo(mPackageManager, info, mHolographicOutlineHelper); widget.setTag(createItemInfo); } widget.setOnClickListener(this); widget.setOnLongClickListener(this); widget.setOnTouchListener(this); // Layout each widget int ix = i % mWidgetCountX; int iy = i / mWidgetCountX; GridLayout.LayoutParams lp = new GridLayout.LayoutParams( GridLayout.spec(iy, GridLayout.LEFT), GridLayout.spec(ix, GridLayout.TOP)); lp.width = cellWidth; lp.height = cellHeight; lp.setGravity(Gravity.TOP | Gravity.LEFT); if (ix > 0) lp.leftMargin = mWidgetWidthGap; if (iy > 0) lp.topMargin = mWidgetHeightGap; layout.addView(widget, lp); } // Load the widget previews if (immediate) { AsyncTaskPageData data = new AsyncTaskPageData(page, items, cellWidth, cellHeight, mWidgetCountX, null, null); loadWidgetPreviewsInBackground(null, data); onSyncWidgetPageItems(data); } else { prepareLoadWidgetPreviewsTask(page, items, cellWidth, cellHeight, mWidgetCountX); } } private void loadWidgetPreviewsInBackground(AppsCustomizeAsyncTask task, AsyncTaskPageData data) { if (task != null) { // Ensure that this task starts running at the correct priority task.syncThreadPriority(); } // Load each of the widget/shortcut previews ArrayList<Object> items = data.items; ArrayList<Bitmap> images = data.generatedImages; int count = items.size(); int cellWidth = data.cellWidth; int cellHeight = data.cellHeight; for (int i = 0; i < count; ++i) { if (task != null) { // Ensure we haven't been cancelled yet if (task.isCancelled()) break; // Before work on each item, ensure that this task is running at the correct // priority task.syncThreadPriority(); } Object rawInfo = items.get(i); if (rawInfo instanceof AppWidgetProviderInfo) { AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo; int[] cellSpans = mLauncher.getSpanForWidget(info, null); images.add(getWidgetPreview(info, cellSpans[0],cellSpans[1], cellWidth, cellHeight)); } else if (rawInfo instanceof ResolveInfo) { // Fill in the shortcuts information ResolveInfo info = (ResolveInfo) rawInfo; images.add(getShortcutPreview(info, cellWidth, cellHeight)); } } } private void onSyncWidgetPageItems(AsyncTaskPageData data) { int page = data.page; PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page + mNumAppsPages); ArrayList<Object> items = data.items; int count = items.size(); for (int i = 0; i < count; ++i) { PagedViewWidget widget = (PagedViewWidget) layout.getChildAt(i); if (widget != null) { Bitmap preview = data.generatedImages.get(i); boolean scale = (preview.getWidth() >= data.cellWidth || preview.getHeight() >= data.cellHeight); widget.applyPreview(new FastBitmapDrawable(preview), i, scale); } } layout.createHardwareLayer(); invalidate(); /* TEMPORARILY DISABLE HOLOGRAPHIC ICONS if (mFadeInAdjacentScreens) { prepareGenerateHoloOutlinesTask(data.page, data.items, data.generatedImages); } */ } private void onHolographicPageItemsLoaded(AsyncTaskPageData data) { // Invalidate early to short-circuit children invalidates invalidate(); int page = data.page; ViewGroup layout = (ViewGroup) getPageAt(page); if (layout instanceof PagedViewCellLayout) { PagedViewCellLayout cl = (PagedViewCellLayout) layout; int count = cl.getPageChildCount(); if (count != data.generatedImages.size()) return; for (int i = 0; i < count; ++i) { PagedViewIcon icon = (PagedViewIcon) cl.getChildOnPageAt(i); icon.setHolographicOutline(data.generatedImages.get(i)); } } else { int count = layout.getChildCount(); if (count != data.generatedImages.size()) return; for (int i = 0; i < count; ++i) { View v = layout.getChildAt(i); ((PagedViewWidget) v).setHolographicOutline(data.generatedImages.get(i)); } } } @Override public void syncPages() { removeAllViews(); cancelAllTasks(); Context context = getContext(); for (int j = 0; j < mNumWidgetPages; ++j) { PagedViewGridLayout layout = new PagedViewGridLayout(context, mWidgetCountX, mWidgetCountY); setupPage(layout); addView(layout, new PagedViewGridLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } for (int i = 0; i < mNumAppsPages; ++i) { PagedViewCellLayout layout = new PagedViewCellLayout(context); setupPage(layout); addView(layout); } } @Override public void syncPageItems(int page, boolean immediate) { if (page < mNumAppsPages) { syncAppsPageItems(page, immediate); } else { syncWidgetPageItems(page - mNumAppsPages, immediate); } } // We want our pages to be z-ordered such that the further a page is to the left, the higher // it is in the z-order. This is important to insure touch events are handled correctly. View getPageAt(int index) { return getChildAt(getChildCount() - index - 1); } @Override protected int indexToPage(int index) { return getChildCount() - index - 1; } // In apps customize, we have a scrolling effect which emulates pulling cards off of a stack. @Override protected void screenScrolled(int screenCenter) { super.screenScrolled(screenCenter); for (int i = 0; i < getChildCount(); i++) { View v = getPageAt(i); if (v != null) { float scrollProgress = getScrollProgress(screenCenter, v, i); float interpolatedProgress = mZInterpolator.getInterpolation(Math.abs(Math.min(scrollProgress, 0))); float scale = (1 - interpolatedProgress) + interpolatedProgress * TRANSITION_SCALE_FACTOR; float translationX = Math.min(0, scrollProgress) * v.getMeasuredWidth(); float alpha; if (!LauncherApplication.isScreenLarge() || scrollProgress < 0) { alpha = scrollProgress < 0 ? mAlphaInterpolator.getInterpolation( 1 - Math.abs(scrollProgress)) : 1.0f; } else { // On large screens we need to fade the page as it nears its leftmost position alpha = mLeftScreenAlphaInterpolator.getInterpolation(1 - scrollProgress); } v.setCameraDistance(mDensity * CAMERA_DISTANCE); int pageWidth = v.getMeasuredWidth(); int pageHeight = v.getMeasuredHeight(); if (PERFORM_OVERSCROLL_ROTATION) { if (i == 0 && scrollProgress < 0) { // Overscroll to the left v.setPivotX(TRANSITION_PIVOT * pageWidth); v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress); scale = 1.0f; alpha = 1.0f; // On the first page, we don't want the page to have any lateral motion translationX = getScrollX(); } else if (i == getChildCount() - 1 && scrollProgress > 0) { // Overscroll to the right v.setPivotX((1 - TRANSITION_PIVOT) * pageWidth); v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress); scale = 1.0f; alpha = 1.0f; // On the last page, we don't want the page to have any lateral motion. translationX = getScrollX() - mMaxScrollX; } else { v.setPivotY(pageHeight / 2.0f); v.setPivotX(pageWidth / 2.0f); v.setRotationY(0f); } } v.setTranslationX(translationX); v.setScaleX(scale); v.setScaleY(scale); v.setAlpha(alpha); } } } protected void overScroll(float amount) { acceleratedOverScroll(amount); } /** * Used by the parent to get the content width to set the tab bar to * @return */ public int getPageContentWidth() { return mContentWidth; } @Override protected void onPageEndMoving() { super.onPageEndMoving(); // We reset the save index when we change pages so that it will be recalculated on next // rotation mSaveInstanceStateItemIndex = -1; } /* * AllAppsView implementation */ @Override public void setup(Launcher launcher, DragController dragController) { mLauncher = launcher; mDragController = dragController; } @Override public void zoom(float zoom, boolean animate) { // TODO-APPS_CUSTOMIZE: Call back to mLauncher.zoomed() } @Override public boolean isVisible() { return (getVisibility() == VISIBLE); } @Override public boolean isAnimating() { return false; } @Override public void setApps(ArrayList<ApplicationInfo> list) { mApps = list; Collections.sort(mApps, LauncherModel.APP_NAME_COMPARATOR); updatePageCounts(); // The next layout pass will trigger data-ready if both widgets and apps are set, so // request a layout to do this test and invalidate the page data when ready. if (testDataReady()) requestLayout(); } private void addAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) { // We add it in place, in alphabetical order int count = list.size(); for (int i = 0; i < count; ++i) { ApplicationInfo info = list.get(i); int index = Collections.binarySearch(mApps, info, LauncherModel.APP_NAME_COMPARATOR); if (index < 0) { mApps.add(-(index + 1), info); } } } @Override public void addApps(ArrayList<ApplicationInfo> list) { addAppsWithoutInvalidate(list); updatePageCounts(); invalidatePageData(); } private int findAppByComponent(List<ApplicationInfo> list, ApplicationInfo item) { ComponentName removeComponent = item.intent.getComponent(); int length = list.size(); for (int i = 0; i < length; ++i) { ApplicationInfo info = list.get(i); if (info.intent.getComponent().equals(removeComponent)) { return i; } } return -1; } private void removeAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) { // loop through all the apps and remove apps that have the same component int length = list.size(); for (int i = 0; i < length; ++i) { ApplicationInfo info = list.get(i); int removeIndex = findAppByComponent(mApps, info); if (removeIndex > -1) { mApps.remove(removeIndex); } } } @Override public void removeApps(ArrayList<ApplicationInfo> list) { removeAppsWithoutInvalidate(list); updatePageCounts(); invalidatePageData(); } @Override public void updateApps(ArrayList<ApplicationInfo> list) { // We remove and re-add the updated applications list because it's properties may have // changed (ie. the title), and this will ensure that the items will be in their proper // place in the list. removeAppsWithoutInvalidate(list); addAppsWithoutInvalidate(list); updatePageCounts(); invalidatePageData(); } @Override public void reset() { AppsCustomizeTabHost tabHost = getTabHost(); String tag = tabHost.getCurrentTabTag(); if (tag != null) { if (!tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) { tabHost.setCurrentTabFromContent(ContentType.Applications); } } if (mCurrentPage != 0) { invalidatePageData(0); } } private AppsCustomizeTabHost getTabHost() { return (AppsCustomizeTabHost) mLauncher.findViewById(R.id.apps_customize_pane); } @Override public void dumpState() { // TODO: Dump information related to current list of Applications, Widgets, etc. ApplicationInfo.dumpApplicationInfoList(LOG_TAG, "mApps", mApps); dumpAppWidgetProviderInfoList(LOG_TAG, "mWidgets", mWidgets); } private void dumpAppWidgetProviderInfoList(String tag, String label, ArrayList<Object> list) { Log.d(tag, label + " size=" + list.size()); for (Object i: list) { if (i instanceof AppWidgetProviderInfo) { AppWidgetProviderInfo info = (AppWidgetProviderInfo) i; Log.d(tag, " label=\"" + info.label + "\" previewImage=" + info.previewImage + " resizeMode=" + info.resizeMode + " configure=" + info.configure + " initialLayout=" + info.initialLayout + " minWidth=" + info.minWidth + " minHeight=" + info.minHeight); } else if (i instanceof ResolveInfo) { ResolveInfo info = (ResolveInfo) i; Log.d(tag, " label=\"" + info.loadLabel(mPackageManager) + "\" icon=" + info.icon); } } } @Override public void surrender() { // TODO: If we are in the middle of any process (ie. for holographic outlines, etc) we // should stop this now. // Stop all background tasks cancelAllTasks(); } /* * We load an extra page on each side to prevent flashes from scrolling and loading of the * widget previews in the background with the AsyncTasks. */ protected int getAssociatedLowerPageBound(int page) { return Math.max(0, page - 2); } protected int getAssociatedUpperPageBound(int page) { final int count = getChildCount(); return Math.min(page + 2, count - 1); } @Override protected String getCurrentPageDescription() { int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage; int stringId = R.string.default_scroll_format; int count = 0; if (page < mNumAppsPages) { stringId = R.string.apps_customize_apps_scroll_format; count = mNumAppsPages; } else { page -= mNumAppsPages; stringId = R.string.apps_customize_widgets_scroll_format; count = mNumWidgetPages; } return String.format(mContext.getString(stringId), page + 1, count); } } diff --git a/src/com/android/launcher2/PagedViewCellLayout.java b/src/com/android/launcher2/PagedViewCellLayout.java index 2ef7e296..6266ca26 100644 --- a/src/com/android/launcher2/PagedViewCellLayout.java +++ b/src/com/android/launcher2/PagedViewCellLayout.java @@ -1,517 +1,516 @@ /* * Copyright (C) 2010 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.launcher2; import android.content.Context; import android.content.res.Resources; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewDebug; import android.view.ViewGroup; import com.android.launcher.R; /** * An abstraction of the original CellLayout which supports laying out items * which span multiple cells into a grid-like layout. Also supports dimming * to give a preview of its contents. */ public class PagedViewCellLayout extends ViewGroup implements Page { static final String TAG = "PagedViewCellLayout"; private int mCellCountX; private int mCellCountY; private int mOriginalCellWidth; private int mOriginalCellHeight; private int mCellWidth; private int mCellHeight; private int mOriginalWidthGap; private int mOriginalHeightGap; private int mWidthGap; private int mHeightGap; private int mMaxGap; protected PagedViewCellLayoutChildren mChildren; public PagedViewCellLayout(Context context) { this(context, null); } public PagedViewCellLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public PagedViewCellLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setAlwaysDrawnWithCacheEnabled(false); // setup default cell parameters Resources resources = context.getResources(); mOriginalCellWidth = mCellWidth = resources.getDimensionPixelSize(R.dimen.apps_customize_cell_width); mOriginalCellHeight = mCellHeight = resources.getDimensionPixelSize(R.dimen.apps_customize_cell_height); mCellCountX = LauncherModel.getCellCountX(); mCellCountY = LauncherModel.getCellCountY(); - mOriginalHeightGap = mOriginalHeightGap = mWidthGap = mHeightGap = -1; + mOriginalWidthGap = mOriginalHeightGap = mWidthGap = mHeightGap = -1; mMaxGap = resources.getDimensionPixelSize(R.dimen.apps_customize_max_gap); mChildren = new PagedViewCellLayoutChildren(context); mChildren.setCellDimensions(mCellWidth, mCellHeight); mChildren.setGap(mWidthGap, mHeightGap); addView(mChildren); } public int getCellWidth() { return mCellWidth; } public int getCellHeight() { return mCellHeight; } @Override public void setAlpha(float alpha) { mChildren.setAlpha(alpha); } void destroyHardwareLayers() { // called when a page is no longer visible (triggered by loadAssociatedPages -> // removeAllViewsOnPage) mChildren.destroyHardwareLayer(); } void createHardwareLayers() { // called when a page is visible (triggered by loadAssociatedPages -> syncPageItems) mChildren.createHardwareLayer(); } @Override public void cancelLongPress() { super.cancelLongPress(); // Cancel long press for all children final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); child.cancelLongPress(); } } public boolean addViewToCellLayout(View child, int index, int childId, PagedViewCellLayout.LayoutParams params) { final PagedViewCellLayout.LayoutParams lp = params; // Generate an id for each view, this assumes we have at most 256x256 cells // per workspace screen if (lp.cellX >= 0 && lp.cellX <= (mCellCountX - 1) && lp.cellY >= 0 && (lp.cellY <= mCellCountY - 1)) { // If the horizontal or vertical span is set to -1, it is taken to // mean that it spans the extent of the CellLayout if (lp.cellHSpan < 0) lp.cellHSpan = mCellCountX; if (lp.cellVSpan < 0) lp.cellVSpan = mCellCountY; child.setId(childId); mChildren.addView(child, index, lp); if (child instanceof PagedViewIcon) { PagedViewIcon pagedViewIcon = (PagedViewIcon) child; pagedViewIcon.disableCache(); } return true; } return false; } @Override public void removeAllViewsOnPage() { mChildren.removeAllViews(); destroyHardwareLayers(); } @Override public void removeViewOnPageAt(int index) { mChildren.removeViewAt(index); } @Override public int getPageChildCount() { return mChildren.getChildCount(); } public PagedViewCellLayoutChildren getChildrenLayout() { return mChildren; } @Override public View getChildOnPageAt(int i) { return mChildren.getChildAt(i); } @Override public int indexOfChildOnPage(View v) { return mChildren.indexOfChild(v); } public int getCellCountX() { return mCellCountX; } public int getCellCountY() { return mCellCountY; } protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec); int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec); if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) { throw new RuntimeException("CellLayout cannot have UNSPECIFIED dimensions"); } int numWidthGaps = mCellCountX - 1; int numHeightGaps = mCellCountY - 1; if (mOriginalWidthGap < 0 || mOriginalHeightGap < 0) { int hSpace = widthSpecSize - mPaddingLeft - mPaddingRight; int vSpace = heightSpecSize - mPaddingTop - mPaddingBottom; int hFreeSpace = hSpace - (mCellCountX * mOriginalCellWidth); int vFreeSpace = vSpace - (mCellCountY * mOriginalCellHeight); mWidthGap = Math.min(mMaxGap, numWidthGaps > 0 ? (hFreeSpace / numWidthGaps) : 0); mHeightGap = Math.min(mMaxGap,numHeightGaps > 0 ? (vFreeSpace / numHeightGaps) : 0); mChildren.setGap(mWidthGap, mHeightGap); } else { mWidthGap = mOriginalWidthGap; mHeightGap = mOriginalHeightGap; } // Initial values correspond to widthSpecMode == MeasureSpec.EXACTLY int newWidth = widthSpecSize; int newHeight = heightSpecSize; if (widthSpecMode == MeasureSpec.AT_MOST) { newWidth = mPaddingLeft + mPaddingRight + (mCellCountX * mCellWidth) + ((mCellCountX - 1) * mWidthGap); newHeight = mPaddingTop + mPaddingBottom + (mCellCountY * mCellHeight) + ((mCellCountY - 1) * mHeightGap); setMeasuredDimension(newWidth, newHeight); } final int count = getChildCount(); for (int i = 0; i < count; i++) { View child = getChildAt(i); int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(newWidth - mPaddingLeft - mPaddingRight, MeasureSpec.EXACTLY); int childheightMeasureSpec = MeasureSpec.makeMeasureSpec(newHeight - mPaddingTop - mPaddingBottom, MeasureSpec.EXACTLY); child.measure(childWidthMeasureSpec, childheightMeasureSpec); } setMeasuredDimension(newWidth, newHeight); } int getContentWidth() { return getWidthBeforeFirstLayout() + mPaddingLeft + mPaddingRight; } int getContentHeight() { if (mCellCountY > 0) { return mCellCountY * mCellHeight + (mCellCountY - 1) * Math.max(0, mHeightGap); } return 0; } int getWidthBeforeFirstLayout() { if (mCellCountX > 0) { return mCellCountX * mCellWidth + (mCellCountX - 1) * Math.max(0, mWidthGap); } return 0; } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int count = getChildCount(); for (int i = 0; i < count; i++) { View child = getChildAt(i); child.layout(mPaddingLeft, mPaddingTop, r - l - mPaddingRight, b - t - mPaddingBottom); } } @Override public boolean onTouchEvent(MotionEvent event) { boolean result = super.onTouchEvent(event); int count = getPageChildCount(); if (count > 0) { // We only intercept the touch if we are tapping in empty space after the final row View child = getChildOnPageAt(count - 1); int bottom = child.getBottom(); int numRows = (int) Math.ceil((float) getPageChildCount() / getCellCountX()); if (numRows < getCellCountY()) { // Add a little bit of buffer if there is room for another row bottom += mCellHeight / 2; } result = result || (event.getY() < bottom); } return result; } public void enableCenteredContent(boolean enabled) { mChildren.enableCenteredContent(enabled); } @Override protected void setChildrenDrawingCacheEnabled(boolean enabled) { mChildren.setChildrenDrawingCacheEnabled(enabled); } public void setCellCount(int xCount, int yCount) { mCellCountX = xCount; mCellCountY = yCount; requestLayout(); } public void setGap(int widthGap, int heightGap) { - mWidthGap = widthGap; - mHeightGap = heightGap; + mOriginalWidthGap = mWidthGap = widthGap; + mOriginalHeightGap = mHeightGap = heightGap; mChildren.setGap(widthGap, heightGap); } public int[] getCellCountForDimensions(int width, int height) { // Always assume we're working with the smallest span to make sure we // reserve enough space in both orientations int smallerSize = Math.min(mCellWidth, mCellHeight); // Always round up to next largest cell int spanX = (width + smallerSize) / smallerSize; int spanY = (height + smallerSize) / smallerSize; return new int[] { spanX, spanY }; } /** * Start dragging the specified child * * @param child The child that is being dragged */ void onDragChild(View child) { PagedViewCellLayout.LayoutParams lp = (PagedViewCellLayout.LayoutParams) child.getLayoutParams(); lp.isDragging = true; } /** * Estimates the number of cells that the specified width would take up. */ public int estimateCellHSpan(int width) { - // The space for a page assuming that we want to show half of a column of the previous and - // next pages is the width - left padding (current & next page) - right padding (previous & - // current page) - half cell width (for previous and next pages) - int availWidth = (int) (width - (2 * mPaddingLeft + 2 * mPaddingRight)); + // We don't show the next/previous pages any more, so we use the full width, minus the + // padding + int availWidth = width - (mPaddingLeft + mPaddingRight); // We know that we have to fit N cells with N-1 width gaps, so we just juggle to solve for N int n = Math.max(1, (availWidth + mWidthGap) / (mCellWidth + mWidthGap)); // We don't do anything fancy to determine if we squeeze another row in. return n; } /** * Estimates the number of cells that the specified height would take up. */ public int estimateCellVSpan(int height) { // The space for a page is the height - top padding (current page) - bottom padding (current // page) int availHeight = height - (mPaddingTop + mPaddingBottom); // We know that we have to fit N cells with N-1 height gaps, so we juggle to solve for N int n = Math.max(1, (availHeight + mHeightGap) / (mCellHeight + mHeightGap)); // We don't do anything fancy to determine if we squeeze another row in. return n; } /** Returns an estimated center position of the cell at the specified index */ public int[] estimateCellPosition(int x, int y) { return new int[] { mPaddingLeft + (x * mCellWidth) + (x * mWidthGap) + (mCellWidth / 2), mPaddingTop + (y * mCellHeight) + (y * mHeightGap) + (mCellHeight / 2) }; } public void calculateCellCount(int width, int height, int maxCellCountX, int maxCellCountY) { mCellCountX = Math.min(maxCellCountX, estimateCellHSpan(width)); mCellCountY = Math.min(maxCellCountY, estimateCellVSpan(height)); requestLayout(); } /** * Estimates the width that the number of hSpan cells will take up. */ public int estimateCellWidth(int hSpan) { // TODO: we need to take widthGap into effect return hSpan * mCellWidth; } /** * Estimates the height that the number of vSpan cells will take up. */ public int estimateCellHeight(int vSpan) { // TODO: we need to take heightGap into effect return vSpan * mCellHeight; } @Override public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { return new PagedViewCellLayout.LayoutParams(getContext(), attrs); } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { return p instanceof PagedViewCellLayout.LayoutParams; } @Override protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { return new PagedViewCellLayout.LayoutParams(p); } public static class LayoutParams extends ViewGroup.MarginLayoutParams { /** * Horizontal location of the item in the grid. */ @ViewDebug.ExportedProperty public int cellX; /** * Vertical location of the item in the grid. */ @ViewDebug.ExportedProperty public int cellY; /** * Number of cells spanned horizontally by the item. */ @ViewDebug.ExportedProperty public int cellHSpan; /** * Number of cells spanned vertically by the item. */ @ViewDebug.ExportedProperty public int cellVSpan; /** * Is this item currently being dragged */ public boolean isDragging; // a data object that you can bind to this layout params private Object mTag; // X coordinate of the view in the layout. @ViewDebug.ExportedProperty int x; // Y coordinate of the view in the layout. @ViewDebug.ExportedProperty int y; public LayoutParams() { super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); cellHSpan = 1; cellVSpan = 1; } public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); cellHSpan = 1; cellVSpan = 1; } public LayoutParams(ViewGroup.LayoutParams source) { super(source); cellHSpan = 1; cellVSpan = 1; } public LayoutParams(LayoutParams source) { super(source); this.cellX = source.cellX; this.cellY = source.cellY; this.cellHSpan = source.cellHSpan; this.cellVSpan = source.cellVSpan; } public LayoutParams(int cellX, int cellY, int cellHSpan, int cellVSpan) { super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); this.cellX = cellX; this.cellY = cellY; this.cellHSpan = cellHSpan; this.cellVSpan = cellVSpan; } public void setup(int cellWidth, int cellHeight, int widthGap, int heightGap, int hStartPadding, int vStartPadding) { final int myCellHSpan = cellHSpan; final int myCellVSpan = cellVSpan; final int myCellX = cellX; final int myCellY = cellY; width = myCellHSpan * cellWidth + ((myCellHSpan - 1) * widthGap) - leftMargin - rightMargin; height = myCellVSpan * cellHeight + ((myCellVSpan - 1) * heightGap) - topMargin - bottomMargin; if (LauncherApplication.isScreenLarge()) { x = hStartPadding + myCellX * (cellWidth + widthGap) + leftMargin; y = vStartPadding + myCellY * (cellHeight + heightGap) + topMargin; } else { x = myCellX * (cellWidth + widthGap) + leftMargin; y = myCellY * (cellHeight + heightGap) + topMargin; } } public Object getTag() { return mTag; } public void setTag(Object tag) { mTag = tag; } public String toString() { return "(" + this.cellX + ", " + this.cellY + ", " + this.cellHSpan + ", " + this.cellVSpan + ")"; } } } interface Page { public int getPageChildCount(); public View getChildOnPageAt(int i); public void removeAllViewsOnPage(); public void removeViewOnPageAt(int i); public int indexOfChildOnPage(View v); }
false
false
null
null
diff --git a/org.eclipse.scout.rt.ui.rap/src/org/eclipse/scout/rt/ui/rap/AbstractStandaloneRwtEnvironment.java b/org.eclipse.scout.rt.ui.rap/src/org/eclipse/scout/rt/ui/rap/AbstractStandaloneRwtEnvironment.java index 9a64fc2b74..fab2c142ec 100644 --- a/org.eclipse.scout.rt.ui.rap/src/org/eclipse/scout/rt/ui/rap/AbstractStandaloneRwtEnvironment.java +++ b/org.eclipse.scout.rt.ui.rap/src/org/eclipse/scout/rt/ui/rap/AbstractStandaloneRwtEnvironment.java @@ -1,251 +1,258 @@ /******************************************************************************* * Copyright (c) 2011 BSI Business Systems Integration AG. * 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: * BSI Business Systems Integration AG - initial API and implementation *******************************************************************************/ package org.eclipse.scout.rt.ui.rap; import java.lang.reflect.Field; import java.security.AccessController; import javax.security.auth.Subject; import org.eclipse.rwt.RWT; import org.eclipse.rwt.lifecycle.UICallBack; import org.eclipse.rwt.service.SettingStoreException; import org.eclipse.scout.commons.LocaleThreadLocal; import org.eclipse.scout.commons.StringUtility; +import org.eclipse.scout.commons.logger.IScoutLogger; import org.eclipse.scout.commons.logger.ScoutLogManager; import org.eclipse.scout.rt.client.IClientSession; import org.eclipse.scout.rt.client.ui.form.IForm; import org.eclipse.scout.rt.ui.rap.util.RwtUtility; import org.eclipse.scout.rt.ui.rap.window.IRwtScoutPart; import org.eclipse.scout.rt.ui.rap.window.desktop.RwtScoutDesktop; import org.eclipse.scout.rt.ui.rap.window.desktop.nonmodalFormBar.RwtScoutFormButtonBar; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; import org.osgi.framework.Bundle; public abstract class AbstractStandaloneRwtEnvironment extends AbstractRwtEnvironment implements IRwtStandaloneEnvironment { + private static final IScoutLogger LOG = ScoutLogManager.getLogger(AbstractStandaloneRwtEnvironment.class); private Display m_display; private RwtScoutDesktop m_uiDesktop; private RwtScoutFormButtonBar m_uiButtonArea; public AbstractStandaloneRwtEnvironment(Bundle applicationBundle, Class<? extends IClientSession> clientSessionClazz) { super(applicationBundle, clientSessionClazz); } @Override public int createUI() { if (getSubject() == null) { Subject subject = Subject.getSubject(AccessController.getContext()); if (subject == null) { throw new SecurityException("/rap request is not authenticated with a Subject"); } setSubject(subject); } if (RwtUtility.getBrowserInfo().isDesktop()) { //Necessary for client notifications. Disabled on mobile devices to avoid having a constant circle of doom. //TODO: Make it dependent on client notification enabled state. Should actually also be enabled for mobile devices so that client notifications works. UICallBack.activate(getClass().getName() + getClass().hashCode()); } m_display = Display.getDefault(); if (m_display == null) { m_display = new Display(); } m_display.setData(IRwtEnvironment.class.getName(), this); //XXX Workaround for rwt npe try { final Object wb = PlatformUI.getWorkbench(); final Field f = wb.getClass().getDeclaredField("display"); f.setAccessible(true); f.set(wb, m_display); m_display.addListener(SWT.Dispose, new Listener() { private static final long serialVersionUID = 1L; @Override public void handleEvent(Event event) { try { // WORKAROUND for memory leaks // workbench should be closed instead, but NPEs are thrown f.set(wb, null); } catch (Throwable t1) { // nop } } }); } catch (Throwable t) { //nop } //XXX end Workaround for rwt npe try { RWT.getSettingStore().setAttribute("SessionID", RWT.getRequest().getSession().getId()); } catch (SettingStoreException e) { //nop } Shell shell = new Shell(m_display, SWT.NO_TRIM); createApplicationContent(shell); createNonmodalFormButtonArea(shell); //layout GridLayout shellLayout = new GridLayout(1, true); shellLayout.horizontalSpacing = 0; shellLayout.marginHeight = 0; shellLayout.marginWidth = 0; shellLayout.verticalSpacing = 0; shell.setLayout(shellLayout); GridData desktopLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); m_uiDesktop.getUiContainer().setLayoutData(desktopLayoutData); GridData nonmodalFormsLayoutData = new GridData(SWT.FILL, SWT.FILL, true, false); nonmodalFormsLayoutData.exclude = true; m_uiButtonArea.getUiContainer().setLayoutData(nonmodalFormsLayoutData); shell.setMaximized(true); shell.open(); shell.layout(true, true); shell.addDisposeListener(new DisposeListener() { private static final long serialVersionUID = 1L; @Override public void widgetDisposed(DisposeEvent event) { String sessionID = RWT.getSettingStore().getAttribute("SessionID"); if (StringUtility.isNullOrEmpty(sessionID) || !sessionID.equals(RWT.getRequest().getSession().getId())) { Runnable t = new Runnable() { @Override public void run() { getScoutDesktop().getUIFacade().fireGuiDetached(); getScoutDesktop().getUIFacade().fireDesktopClosingFromUI(); } }; invokeScoutLater(t, 0); } } }); while (!shell.isDisposed()) { if (getClientSession() != null) { LocaleThreadLocal.set(getClientSession().getLocale()); } if (!m_display.readAndDispatch()) { m_display.sleep(); } } m_display.dispose(); return 0; } protected void createApplicationContent(Composite parent) { m_uiDesktop = createUiDesktop(); ensureInitialized(); if (!isInitialized()) { throw new SecurityException("Cannot initialize application"); } getKeyStrokeManager().setGlobalKeyStrokesActivated(true); m_uiDesktop.createUiField(parent, getScoutDesktop(), this); } protected void createNonmodalFormButtonArea(Composite parent) { m_uiButtonArea = new RwtScoutFormButtonBar(); m_uiButtonArea.createUiField(parent, m_uiDesktop.getScoutObject(), this); } protected RwtScoutDesktop createUiDesktop() { return new RwtScoutDesktop(); } @Override public RwtScoutDesktop getUiDesktop() { return m_uiDesktop; } @Override public Display getDisplay() { Display current = null; try { current = Display.getCurrent(); } catch (Exception e) { // NOP } if (current != null && m_display != current) { ScoutLogManager.getLogger(AbstractStandaloneRwtEnvironment.class).error( "Different Display.\n" + "m_display: {0}\n" + "cur_displ: {1}", new Object[]{m_display, current}); } Display defdisp = null; try { defdisp = Display.getDefault(); } catch (Exception e) { // NOP } if (defdisp != null && m_display != defdisp) { ScoutLogManager.getLogger(AbstractStandaloneRwtEnvironment.class).error( "Different Display.\n" + "m_display: {0}\n" + "defdisp : {1}", new Object[]{m_display, defdisp}); } return m_display; } @Override public void showFormPart(IForm form) { if (form == null) { return; } if (form.getDisplayHint() == IForm.DISPLAY_HINT_VIEW) { IRwtScoutPart part = m_uiDesktop.addForm(form); - putPart(form, part); - part.showPart(); + if (part != null) { + putPart(form, part); + part.showPart(); + } + else { + LOG.error("Form '" + form.getFormId() + "' cannot be displayed because no corresponding UI part could be found."); + } } super.showFormPart(form); if (form.getDisplayHint() == IForm.DISPLAY_HINT_DIALOG && !form.isModal()) { int buttonCount = m_uiButtonArea.getFormButtonBarCount(); m_uiButtonArea.addFormButton(form); if (buttonCount != m_uiButtonArea.getFormButtonBarCount()) { m_uiButtonArea.getUiContainer().setVisible(true); ((GridData) m_uiButtonArea.getUiContainer().getLayoutData()).exclude = false; m_uiButtonArea.getUiContainer().getParent().layout(true, true); } } } @Override public void hideFormPart(IForm form) { super.hideFormPart(form); if (form.getDisplayHint() == IForm.DISPLAY_HINT_DIALOG && !form.isModal()) { m_uiButtonArea.removeFormButton(form); if (m_uiButtonArea.getFormButtonBarCount() == 0) { m_uiButtonArea.getUiContainer().setVisible(false); ((GridData) m_uiButtonArea.getUiContainer().getLayoutData()).exclude = true; m_uiButtonArea.getUiContainer().getParent().layout(true, true); } } } } diff --git a/org.eclipse.scout.rt.ui.rap/src/org/eclipse/scout/rt/ui/rap/window/desktop/RwtScoutDesktop.java b/org.eclipse.scout.rt.ui.rap/src/org/eclipse/scout/rt/ui/rap/window/desktop/RwtScoutDesktop.java index cd861f4e89..9e6611eab8 100644 --- a/org.eclipse.scout.rt.ui.rap/src/org/eclipse/scout/rt/ui/rap/window/desktop/RwtScoutDesktop.java +++ b/org.eclipse.scout.rt.ui.rap/src/org/eclipse/scout/rt/ui/rap/window/desktop/RwtScoutDesktop.java @@ -1,156 +1,161 @@ /******************************************************************************* * Copyright (c) 2011 BSI Business Systems Integration AG. * 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: * BSI Business Systems Integration AG - initial API and implementation *******************************************************************************/ package org.eclipse.scout.rt.ui.rap.window.desktop; import org.eclipse.rwt.lifecycle.WidgetUtil; import org.eclipse.scout.commons.logger.IScoutLogger; import org.eclipse.scout.commons.logger.ScoutLogManager; import org.eclipse.scout.rt.client.ui.desktop.IDesktop; import org.eclipse.scout.rt.client.ui.form.IForm; import org.eclipse.scout.rt.ui.rap.IRwtStandaloneEnvironment; import org.eclipse.scout.rt.ui.rap.basic.RwtScoutComposite; import org.eclipse.scout.rt.ui.rap.util.RwtLayoutUtility; import org.eclipse.scout.rt.ui.rap.window.IRwtScoutPart; import org.eclipse.scout.rt.ui.rap.window.desktop.toolbar.RwtScoutToolbar; import org.eclipse.scout.rt.ui.rap.window.desktop.viewarea.ILayoutListener; import org.eclipse.scout.rt.ui.rap.window.desktop.viewarea.ViewArea; import org.eclipse.scout.rt.ui.rap.window.desktop.viewarea.ViewArea.SashKey; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Sash; /** * <h3>RwtScoutDesktop</h3> ... * * @author Andreas Hoegger * @since 3.7.0 June 2011 */ public class RwtScoutDesktop extends RwtScoutComposite<IDesktop> implements IRwtDesktop { private static final IScoutLogger LOG = ScoutLogManager.getLogger(RwtScoutDesktop.class); private static final String VARIANT_VIEWS_AREA = "viewsArea"; private ViewArea m_viewArea; private RwtScoutToolbar m_uiToolbar; public RwtScoutDesktop() { } @Override protected void attachScout() { super.attachScout(); } @Override protected void detachScout() { super.detachScout(); } @Override protected void initializeUi(Composite parent) { try { Composite desktopComposite = parent; Control toolbar = createToolBar(desktopComposite); Control viewsArea = createViewsArea(desktopComposite); viewsArea.setData(WidgetUtil.CUSTOM_VARIANT, getViewsAreaVariant()); initLayout(desktopComposite, toolbar, viewsArea); setUiContainer(desktopComposite); } catch (Throwable t) { LOG.error("Exception occured while creating ui desktop.", t); } } protected String getViewsAreaVariant() { return VARIANT_VIEWS_AREA; } protected void initLayout(Composite container, Control toolbar, Control viewsArea) { GridLayout layout = RwtLayoutUtility.createGridLayoutNoSpacing(1, true); container.setLayout(layout); if (toolbar != null) { GridData toolbarData = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL); toolbar.setLayoutData(toolbarData); } if (viewsArea != null) { GridData viewsAreaData = new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.FILL_BOTH); viewsArea.setLayoutData(viewsAreaData); } } protected Control createToolBar(Composite parent) { m_uiToolbar = new RwtScoutToolbar(); m_uiToolbar.createUiField(parent, getScoutObject(), getUiEnvironment()); return m_uiToolbar.getUiContainer(); } protected Control createViewsArea(Composite parent) { m_viewArea = createViewArea(parent); m_viewArea.getLayout().addLayoutListener(new ILayoutListener() { @Override public void handleCompositeLayouted() { int xOffset = -1; Sash sash = m_viewArea.getSash(SashKey.VERTICAL_RIGHT); if (sash != null && sash.getVisible()) { Rectangle sashBounds = sash.getBounds(); xOffset = sashBounds.x + sashBounds.width; } if (getUiToolbar() != null) { getUiToolbar().handleRightViewPositionChanged(xOffset); } } }); return m_viewArea; } protected ViewArea createViewArea(Composite parent) { return new ViewArea(parent); } @Override public IRwtStandaloneEnvironment getUiEnvironment() { return (IRwtStandaloneEnvironment) super.getUiEnvironment(); } @Override public IRwtScoutPart addForm(IForm form) { IRwtScoutViewStack stack = getViewArea().getStackForForm(form); + if (stack == null) { + LOG.error("No view stack for the form '" + form.getFormId() + "' with the display view id '" + form.getDisplayViewId() + "' found. Please check your view configuration. See class ViewArea for details."); + return null; + } + IRwtScoutPart rwtForm = stack.addForm(form); m_viewArea.updateSashPositionForViewStack(stack); updateLayout(); return rwtForm; } @Override public void updateLayout() { getViewArea().layout(); } @Override public IRwtScoutToolbar getUiToolbar() { return m_uiToolbar; } @Override public IViewArea getViewArea() { return m_viewArea; } }
false
false
null
null
diff --git a/trunk/java/src/com/google/i18n/phonenumbers/geocoding/PhoneNumberOfflineGeocoder.java b/trunk/java/src/com/google/i18n/phonenumbers/geocoding/PhoneNumberOfflineGeocoder.java index dd7cd594..2e4fa141 100644 --- a/trunk/java/src/com/google/i18n/phonenumbers/geocoding/PhoneNumberOfflineGeocoder.java +++ b/trunk/java/src/com/google/i18n/phonenumbers/geocoding/PhoneNumberOfflineGeocoder.java @@ -1,184 +1,187 @@ /* * Copyright (C) 2011 The Libphonenumber Authors * * 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.i18n.phonenumbers.geocoding; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * An offline geocoder which provides geographical information related to a phone number. * * @author Shaopeng Jia */ public class PhoneNumberOfflineGeocoder { private static PhoneNumberOfflineGeocoder instance = null; private static final String MAPPING_DATA_DIRECTORY = "/com/google/i18n/phonenumbers/geocoding/data/"; private static final Logger LOGGER = Logger.getLogger(PhoneNumberOfflineGeocoder.class.getName()); private final PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance(); private final String phonePrefixDataDirectory; // The mappingFileProvider knows for which combination of countryCallingCode and language a phone // prefix mapping file is available in the file system, so that a file can be loaded when needed. private MappingFileProvider mappingFileProvider = new MappingFileProvider(); // A mapping from countryCallingCode_lang to the corresponding phone prefix map that has been // loaded. private Map<String, AreaCodeMap> availablePhonePrefixMaps = new HashMap<String, AreaCodeMap>(); // @VisibleForTesting PhoneNumberOfflineGeocoder(String phonePrefixDataDirectory) { this.phonePrefixDataDirectory = phonePrefixDataDirectory; loadMappingFileProvider(); } private void loadMappingFileProvider() { InputStream source = PhoneNumberOfflineGeocoder.class.getResourceAsStream(phonePrefixDataDirectory + "config"); ObjectInputStream in; try { in = new ObjectInputStream(source); mappingFileProvider.readExternal(in); } catch (IOException e) { LOGGER.log(Level.WARNING, e.toString()); } } private AreaCodeMap getPhonePrefixDescriptions( int countryCallingCode, String language, String script, String region) { String fileName = mappingFileProvider.getFileName(countryCallingCode, language, script, region); if (fileName.length() == 0) { return null; } if (!availablePhonePrefixMaps.containsKey(fileName)) { loadAreaCodeMapFromFile(fileName); } return availablePhonePrefixMaps.get(fileName); } private void loadAreaCodeMapFromFile(String fileName) { InputStream source = PhoneNumberOfflineGeocoder.class.getResourceAsStream(phonePrefixDataDirectory + fileName); ObjectInputStream in; try { in = new ObjectInputStream(source); AreaCodeMap map = new AreaCodeMap(); map.readExternal(in); availablePhonePrefixMaps.put(fileName, map); } catch (IOException e) { LOGGER.log(Level.WARNING, e.toString()); } } /** * Gets a {@link PhoneNumberOfflineGeocoder} instance to carry out international phone number * geocoding. * * <p> The {@link PhoneNumberOfflineGeocoder} is implemented as a singleton. Therefore, calling * this method multiple times will only result in one instance being created. * * @return a {@link PhoneNumberOfflineGeocoder} instance */ public static synchronized PhoneNumberOfflineGeocoder getInstance() { if (instance == null) { instance = new PhoneNumberOfflineGeocoder(MAPPING_DATA_DIRECTORY); } return instance; } /** * Returns the customary display name in the given language for the given territory the phone * number is from. */ private String getCountryNameForNumber(PhoneNumber number, Locale language) { String regionCode = phoneUtil.getRegionCodeForNumber(number); return (regionCode == null || regionCode.equals("ZZ")) ? "" : new Locale("", regionCode).getDisplayCountry(language); } /** * Returns a text description for the given language code for the given phone number. The * description might consist of the name of the country where the phone number is from and/or the * name of the geographical area the phone number is from. This method assumes the validity of the * number passed in has already been checked. * * @param number a valid phone number for which we want to get a text description * @param languageCode the language code for which the description should be written * @return a text description for the given language code for the given phone number */ public String getDescriptionForValidNumber(PhoneNumber number, Locale languageCode) { String langStr = languageCode.getLanguage(); String scriptStr = ""; // No script is specified String regionStr = languageCode.getCountry(); String areaDescription = getAreaDescriptionForNumber(number, langStr, scriptStr, regionStr); return (areaDescription.length() > 0) ? areaDescription : getCountryNameForNumber(number, languageCode); } /** * Returns a text description for the given language code for the given phone number. The * description might consist of the name of the country where the phone number is from and/or the * name of the geographical area the phone number is from. This method explictly checkes the * validity of the number passed in. * * @param number the phone number for which we want to get a text description * @param languageCode the language code for which the description should be written * @return a text description for the given language code for the given phone number, or empty * string if the number passed in is invalid */ public String getDescriptionForNumber(PhoneNumber number, Locale languageCode) { if (!phoneUtil.isValidNumber(number)) { return ""; } return getDescriptionForValidNumber(number, languageCode); } /** * Returns an area-level text description in the given language for the given phone number. * * @param number the phone number for which we want to get a text description * @param lang two-letter lowercase ISO language codes as defined by ISO 639-1 * @param script four-letter titlecase (the first letter is uppercase and the rest of the letters * are lowercase) ISO script codes as defined in ISO 15924 * @param region two-letter uppercase ISO country codes as defined by ISO 3166-1 * @return an area-level text description in the given language for the given phone number, or an * empty string if such a description is not available */ private String getAreaDescriptionForNumber( PhoneNumber number, String lang, String script, String region) { int countryCallingCode = number.getCountryCode(); // As the NANPA data is split into multiple files covering 3-digit areas, use a phone number // prefix of 4 digits for NANPA instead, e.g. 1650. int phonePrefix = (countryCallingCode != 1) ? countryCallingCode : (1000 + (int) (number.getNationalNumber() / 10000000)); AreaCodeMap phonePrefixDescriptions = getPhonePrefixDescriptions(phonePrefix, lang, script, region); - return (phonePrefixDescriptions != null) ? phonePrefixDescriptions.lookup(number) : ""; + String description = phonePrefixDescriptions != null + ? phonePrefixDescriptions.lookup(number) + : ""; + return description == null ? "" : description; } } diff --git a/trunk/java/test/com/google/i18n/phonenumbers/geocoding/PhoneNumberOfflineGeocoderTest.java b/trunk/java/test/com/google/i18n/phonenumbers/geocoding/PhoneNumberOfflineGeocoderTest.java index 2721c8d1..a75b3270 100644 --- a/trunk/java/test/com/google/i18n/phonenumbers/geocoding/PhoneNumberOfflineGeocoderTest.java +++ b/trunk/java/test/com/google/i18n/phonenumbers/geocoding/PhoneNumberOfflineGeocoderTest.java @@ -1,102 +1,111 @@ /* * Copyright (C) 2011 The Libphonenumber Authors * * 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.i18n.phonenumbers.geocoding; import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber; import junit.framework.TestCase; import java.util.Locale; /** * Unit tests for PhoneNumberOfflineGeocoder.java * * @author Shaopeng Jia */ public class PhoneNumberOfflineGeocoderTest extends TestCase { private final PhoneNumberOfflineGeocoder geocoder = new PhoneNumberOfflineGeocoder(TEST_MAPPING_DATA_DIRECTORY); private static final String TEST_MAPPING_DATA_DIRECTORY = "/com/google/i18n/phonenumbers/geocoding/testing_data/"; // Set up some test numbers to re-use. private static final PhoneNumber KO_NUMBER1 = new PhoneNumber().setCountryCode(82).setNationalNumber(22123456L); private static final PhoneNumber KO_NUMBER2 = new PhoneNumber().setCountryCode(82).setNationalNumber(322123456L); private static final PhoneNumber KO_NUMBER3 = new PhoneNumber().setCountryCode(82).setNationalNumber(6421234567L); private static final PhoneNumber KO_INVALID_NUMBER = new PhoneNumber().setCountryCode(82).setNationalNumber(1234L); private static final PhoneNumber US_NUMBER1 = new PhoneNumber().setCountryCode(1).setNationalNumber(6502530000L); private static final PhoneNumber US_NUMBER2 = new PhoneNumber().setCountryCode(1).setNationalNumber(6509600000L); private static final PhoneNumber US_NUMBER3 = new PhoneNumber().setCountryCode(1).setNationalNumber(2128120000L); + private static final PhoneNumber US_NUMBER4 = + new PhoneNumber().setCountryCode(1).setNationalNumber(6174240000L); private static final PhoneNumber US_INVALID_NUMBER = new PhoneNumber().setCountryCode(1).setNationalNumber(123456789L); private static final PhoneNumber BS_NUMBER1 = new PhoneNumber().setCountryCode(1).setNationalNumber(2423651234L); private static final PhoneNumber AU_NUMBER = new PhoneNumber().setCountryCode(61).setNationalNumber(236618300L); private static final PhoneNumber NUMBER_WITH_INVALID_COUNTRY_CODE = new PhoneNumber().setCountryCode(999).setNationalNumber(2423651234L); public void testGetDescriptionForNumberWithNoDataFile() { // No data file containing mappings for US numbers is available in Chinese for the unittests. As // a result, the country name of United States in simplified Chinese is returned. assertEquals("\u7F8E\u56FD", geocoder.getDescriptionForNumber(US_NUMBER1, Locale.SIMPLIFIED_CHINESE)); assertEquals("Stati Uniti", geocoder.getDescriptionForNumber(US_NUMBER1, Locale.ITALIAN)); assertEquals("Bahamas", geocoder.getDescriptionForNumber(BS_NUMBER1, new Locale("en", "US"))); assertEquals("Australia", geocoder.getDescriptionForNumber(AU_NUMBER, new Locale("en", "US"))); assertEquals("", geocoder.getDescriptionForNumber(NUMBER_WITH_INVALID_COUNTRY_CODE, new Locale("en", "US"))); } + public void testGetDescriptionForNumberWithMissingPrefix() { + // Test that the name of the country is returned when the number passed in is valid but not + // covered by the geocoding data file. + assertEquals("United States", + geocoder.getDescriptionForNumber(US_NUMBER4, new Locale("en", "US"))); + } + public void testGetDescriptionForNumber_en_US() { assertEquals("CA", geocoder.getDescriptionForNumber(US_NUMBER1, new Locale("en", "US"))); assertEquals("Mountain View, CA", geocoder.getDescriptionForNumber(US_NUMBER2, new Locale("en", "US"))); assertEquals("New York, NY", geocoder.getDescriptionForNumber(US_NUMBER3, new Locale("en", "US"))); } public void testGetDescriptionForKoreanNumber() { assertEquals("Seoul", geocoder.getDescriptionForNumber(KO_NUMBER1, Locale.ENGLISH)); assertEquals("Incheon", geocoder.getDescriptionForNumber(KO_NUMBER2, Locale.ENGLISH)); assertEquals("Jeju", geocoder.getDescriptionForNumber(KO_NUMBER3, Locale.ENGLISH)); assertEquals("\uC11C\uC6B8", geocoder.getDescriptionForNumber(KO_NUMBER1, Locale.KOREAN)); assertEquals("\uC778\uCC9C", geocoder.getDescriptionForNumber(KO_NUMBER2, Locale.KOREAN)); assertEquals("\uC81C\uC8FC", geocoder.getDescriptionForNumber(KO_NUMBER3, Locale.KOREAN)); } public void testGetDescriptionForInvalidNumber() { assertEquals("", geocoder.getDescriptionForNumber(KO_INVALID_NUMBER, Locale.ENGLISH)); assertEquals("", geocoder.getDescriptionForNumber(US_INVALID_NUMBER, Locale.ENGLISH)); } }
false
false
null
null
diff --git a/blogracy/src/it/unipr/aotlab/blogracy/Blogracy.java b/blogracy/src/it/unipr/aotlab/blogracy/Blogracy.java index 439b1de..33f3fa6 100755 --- a/blogracy/src/it/unipr/aotlab/blogracy/Blogracy.java +++ b/blogracy/src/it/unipr/aotlab/blogracy/Blogracy.java @@ -1,304 +1,304 @@ /* * Copyright (c) 2011 Enrico Franchi, Michele Tomaiuolo and University of Parma. * * 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 it.unipr.aotlab.blogracy; import it.unipr.aotlab.blogracy.errors.ServerConfigurationError; import it.unipr.aotlab.blogracy.errors.URLMappingError; import it.unipr.aotlab.blogracy.logging.Logger; import it.unipr.aotlab.blogracy.web.resolvers.ErrorPageResolver; import it.unipr.aotlab.blogracy.web.resolvers.RequestResolver; import it.unipr.aotlab.blogracy.web.url.URLMapper; import org.apache.velocity.app.Velocity; import org.gudy.azureus2.core3.config.COConfigurationManager; import org.gudy.azureus2.core3.config.impl.ConfigurationDefaults; import org.gudy.azureus2.core3.util.SystemProperties; import org.gudy.azureus2.plugins.PluginException; import org.gudy.azureus2.plugins.PluginInterface; import org.gudy.azureus2.plugins.tracker.web.TrackerWebPageRequest; import org.gudy.azureus2.plugins.tracker.web.TrackerWebPageResponse; import org.gudy.azureus2.plugins.ui.config.ConfigSection; import org.gudy.azureus2.plugins.ui.config.HyperlinkParameter; import org.gudy.azureus2.plugins.ui.model.BasicPluginConfigModel; import org.gudy.azureus2.ui.webplugin.WebPlugin; import java.io.File; import java.io.IOException; import java.net.HttpURLConnection; import java.util.Properties; public class Blogracy extends WebPlugin { private URLMapper mapper = new URLMapper(); private static final String BLOGRACY = "blogracy"; private HyperlinkParameter test_param; static private Blogracy singleton; static class Accesses { static String ALL = "all"; static String LOCAL = "local"; } static private PluginInterface plugin; // Velocity configuration keys private static final String VELOCITY_RESOURCE_LOADER_PATH_KEY = "file.resource.loader.path"; // Misc Keys private static final String MESSAGES_BLOGRACY_URL_KEY = "blogracy.url"; private static final String PLUGIN_NAME_KEY = "blogracy.name"; // blogracy.internal. keys private static final String CONFIG_ACCESS_KEY = "blogracy.internal.config.access"; private static final String CONFIG_PORT_KEY = "blogracy.internal.config.port"; private static final String DEVICE_ACCESS_KEY = "blogracy.internal.config.access"; private static final String INTERNAL_URL_KEY = "blogracy.internal.test.url"; private static final String DID_MIGRATE_KEY = "blogracy.internal.migrated"; // blogracy default keys private static final String DEVICE_PORT_KEY = "Plugin.default.device.blogracy.port"; private static final String DEVICE_LOCALONLY_KEY = "Plugin.default.device.blogracy.localonly"; private static final String DEVICE_BLOGRACY_ENABLE_KEY = "Plugin.default.device.blogracy.enable"; private static Properties defaults = new Properties(); public static final String DSNS_PLUGIN_CHANNEL_NAME = "DSNS"; final static int DEFAULT_PORT = 32674; final static String DEFAULT_ACCESS = Accesses.ALL; private static boolean loaded; static { ConfigurationDefaults cd = ConfigurationDefaults.getInstance(); cd.addParameter(DID_MIGRATE_KEY, Boolean.TRUE); cd.addParameter(DEVICE_LOCALONLY_KEY, Boolean.TRUE); cd.addParameter(DEVICE_BLOGRACY_ENABLE_KEY, Boolean.TRUE); } public static Blogracy getSingleton() { return (singleton); } @Override protected void initStage(int num) { if (num == 1) { BasicPluginConfigModel config = getConfigModel(); test_param = config.addHyperlinkParameter2(INTERNAL_URL_KEY, ""); test_param.setEnabled(isPluginEnabled()); test_param.setLabelKey(MESSAGES_BLOGRACY_URL_KEY); } } /** * This method is effectively called when a new instance of this plugin should be created. * <p/> * We found this feature not documented. Perhaps we should not rely on that. * We also ensure that Blogracy is a singleton. * * @param pluginInterface is the same old access point for plugins */ public static void load(PluginInterface pluginInterface) { if (singletonShouldReturnImmediately()) return; File root_dir = createRootDirectoryIfMissingAndGetPath(); if (COConfigurationManager.getBooleanParameter(DID_MIGRATE_KEY)) { configureIfMigratedKey(root_dir); } else { configureIfNotMigrateKey(root_dir); } } private static void configureIfNotMigrateKey(final File root_dir) { final Integer blogracy_port = COConfigurationManager.getIntParameter(DEVICE_PORT_KEY, DEFAULT_PORT); final String blogracy_access; if (blogracy_port != DEFAULT_PORT) { COConfigurationManager.setParameter(CONFIG_PORT_KEY, blogracy_port); } boolean local = COConfigurationManager.getBooleanParameter(DEVICE_LOCALONLY_KEY); blogracy_access = local ? Accesses.LOCAL : Accesses.ALL; if (!blogracy_access.equals(DEFAULT_ACCESS)) { COConfigurationManager.setParameter(DEVICE_ACCESS_KEY, blogracy_access); } COConfigurationManager.setParameter(DID_MIGRATE_KEY, Boolean.TRUE); final boolean blogracyEnable = COConfigurationManager.getBooleanParameter(DEVICE_BLOGRACY_ENABLE_KEY); setDefaultsProperties(blogracy_port, blogracy_access, root_dir, blogracyEnable); } private static void configureIfMigratedKey(final File root_dir) { final Integer blogracy_port = COConfigurationManager.getIntParameter(CONFIG_PORT_KEY, DEFAULT_PORT); final String blogracy_access = COConfigurationManager.getStringParameter(CONFIG_ACCESS_KEY, DEFAULT_ACCESS); final boolean blogracyEnable = COConfigurationManager.getBooleanParameter(DEVICE_BLOGRACY_ENABLE_KEY); setDefaultsProperties(blogracy_port, blogracy_access, root_dir, blogracyEnable); } private static boolean singletonShouldReturnImmediately() { synchronized (Blogracy.class) { if (loaded) { return true; } else { loaded = true; } } return false; } private static void setDefaultsProperties(final Integer blogracy_port, final String blogracy_access, final File root_dir, final boolean blogracyEnable) { defaults.put(WebPlugin.PR_ENABLE, blogracyEnable); defaults.put(WebPlugin.PR_DISABLABLE, Boolean.TRUE); defaults.put(WebPlugin.PR_PORT, blogracy_port); defaults.put(WebPlugin.PR_ACCESS, blogracy_access); defaults.put(WebPlugin.PR_ROOT_DIR, root_dir.getAbsolutePath()); defaults.put(WebPlugin.PR_ENABLE_KEEP_ALIVE, Boolean.TRUE); defaults.put(WebPlugin.PR_HIDE_RESOURCE_CONFIG, Boolean.TRUE); defaults.put(WebPlugin.PR_PAIRING_SID, BLOGRACY); defaults.put(WebPlugin.PR_CONFIG_MODEL_PARAMS, new String[]{ConfigSection.SECTION_ROOT, BLOGRACY}); } private static File createRootDirectoryIfMissingAndGetPath() { File root_dir = getRootDirectory(); return createDirIfMissing(root_dir); } public static File getRootDirectory() { File userPath = new File(SystemProperties.getUserPath()); File pluginsDirectoryPath = new File(userPath, "plugins"); return new File(pluginsDirectoryPath, BLOGRACY); } public static File getTemplateDirectory() { return new File(getRootDirectory(), "templates"); } public static File getStaticFilesDirectory() { return new File(getRootDirectory(), "static"); } private static File createDirIfMissing(File dir) { if (!dir.exists()) { boolean createdDir = dir.mkdir(); assert (createdDir); } return dir; } public Blogracy() { super(defaults); } public String getURL() { return (getProtocol() + "://127.0.0.1:" + getPort() + "/"); } @Override public boolean generateSupport(TrackerWebPageRequest request, TrackerWebPageResponse response) throws IOException { String url = request.getURL(); try { final RequestResolver resolver = mapper.getResolver(url); resolver.resolve(request, response); } catch (URLMappingError e) { final ErrorPageResolver errorResolver = new ErrorPageResolver(e); errorResolver.resolve(request, response); } catch (ServerConfigurationError serverConfigurationError) { final ErrorPageResolver errorResolver = new ErrorPageResolver( serverConfigurationError, HttpURLConnection.HTTP_FORBIDDEN ); errorResolver.resolve(request, response); } return true; } @Override protected void setupServer() { super.setupServer(); if (test_param != null) { test_param.setEnabled(isPluginEnabled()); test_param.setHyperlink(getURL()); } } @Override protected boolean isPluginEnabled() { return true; } @Override public void initialize(PluginInterface pluginInterface) throws PluginException { initializePluginInterface(pluginInterface); initializeLogger(); initializeURLMapper(); initVelocity(); initializeSingleton(); super.initialize(pluginInterface); } private void initVelocity() { Properties velocityProperties = new Properties(); velocityProperties.setProperty( VELOCITY_RESOURCE_LOADER_PATH_KEY, getTemplateDirectory().getAbsolutePath() ); Velocity.init(velocityProperties); } private void initializeSingleton() { singleton = this; } private void initializePluginInterface(final PluginInterface pluginInterface) { plugin = pluginInterface; } private void initializeLogger() { Logger.initialize(plugin, DSNS_PLUGIN_CHANNEL_NAME); } private void initializeURLMapper() throws PluginException { try { Object[] staticFileResolverParameters = new Object[]{getStaticFilesDirectory().getAbsolutePath()}; mapper.configure( "^/$", "it.unipr.aotlab.blogracy.web.resolvers.IndexResolver", null, - "^/css/(:?.*)$", "it.unipr.aotlab.blogracy.web.resolvers.StaticFileResolver", staticFileResolverParameters, - "^/scripts/(:?.*)$", "it.unipr.aotlab.blogracy.web.resolvers.StaticFileResolver", staticFileResolverParameters, + "^/css/(?:.*)$", "it.unipr.aotlab.blogracy.web.resolvers.StaticFileResolver", staticFileResolverParameters, + "^/scripts/(?:.*)$", "it.unipr.aotlab.blogracy.web.resolvers.StaticFileResolver", staticFileResolverParameters, "^/followers$", "it.unipr.aotlab.blogracy.web.resolvers.Followers", null ); } catch (ServerConfigurationError serverConfigurationError) { throw new PluginException(serverConfigurationError); } } }
true
false
null
null
diff --git a/core/java/src/net/i2p/client/naming/NamingService.java b/core/java/src/net/i2p/client/naming/NamingService.java index 327e0655b..38e772ddc 100644 --- a/core/java/src/net/i2p/client/naming/NamingService.java +++ b/core/java/src/net/i2p/client/naming/NamingService.java @@ -1,477 +1,480 @@ /* * free (adj.): unencumbered; not under the control of others * Written by mihi in 2004 and released into the public domain * with no warranty of any kind, either expressed or implied. * It probably won't make your computer catch on fire, or eat * your children, but it might. Use at your own risk. */ package net.i2p.client.naming; import java.lang.reflect.Constructor; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import net.i2p.I2PAppContext; import net.i2p.data.DataFormatException; import net.i2p.data.Destination; import net.i2p.data.Hash; import net.i2p.util.Log; /** * Naming services create a subclass of this class. */ public abstract class NamingService { protected final Log _log; protected final I2PAppContext _context; protected final Set<NamingServiceListener> _listeners; protected final Set<NamingServiceUpdater> _updaters; + private static NamingService instance; + /** what classname should be used as the naming service impl? */ public static final String PROP_IMPL = "i2p.naming.impl"; private static final String DEFAULT_IMPL = "net.i2p.client.naming.BlockfileNamingService"; private static final String BACKUP_IMPL = "net.i2p.client.naming.HostsTxtNamingService"; /** * The naming service should only be constructed and accessed through the * application context. This constructor should only be used by the * appropriate application context itself. * */ protected NamingService(I2PAppContext context) { _context = context; _log = context.logManager().getLog(getClass()); _listeners = new CopyOnWriteArraySet(); _updaters = new CopyOnWriteArraySet(); } /** * Look up a host name. * @return the Destination for this host name, or * <code>null</code> if name is unknown. */ public Destination lookup(String hostname) { return lookup(hostname, null, null); } /** * Reverse lookup a destination * @param dest non-null * @return a host name for this Destination, or <code>null</code> * if none is known. It is safe for subclasses to always return * <code>null</code> if no reverse lookup is possible. */ public String reverseLookup(Destination dest) { return reverseLookup(dest, null); } /** * Reverse lookup a hash * @param h non-null * @return a host name for this hash, or <code>null</code> * if none is known. It is safe for subclasses to always return * <code>null</code> if no reverse lookup is possible. */ public String reverseLookup(Hash h) { return null; } /** * Check if host name is valid Base64 encoded dest and return this * dest in that case. Useful as a "fallback" in custom naming * implementations. * This is misnamed as it isn't a "lookup" at all, but * a simple conversion from a Base64 string to a Destination. * * @param hostname 516+ character Base 64 * @return Destination or null on error */ protected Destination lookupBase64(String hostname) { try { Destination result = new Destination(); result.fromBase64(hostname); return result; } catch (DataFormatException dfe) { if (_log.shouldLog(Log.WARN)) _log.warn("Bad B64 dest [" + hostname + "]", dfe); return null; } } @Override public String toString() { return getClass().getSimpleName(); } ///// New API Starts Here /** * @return Class simple name by default * @since 0.8.7 */ public String getName() { return getClass().getSimpleName(); } /** * Warning - unimplemented in any subclass. * * @return NamingService-specific options or null * @since 0.8.7 */ public Properties getConfiguration() { return null; } /** * Warning - unimplemented in any subclass. * * @return success * @since 0.8.7 */ public boolean setConfiguration(Properties p) { return true; } // These are for daisy chaining (MetaNamingService) /** * @return chained naming services or null * @since 0.8.7 */ public List<NamingService> getNamingServices() { return null; } /** * @return parent naming service or null if this is the root * @since 0.8.7 */ public NamingService getParent() { return null; } /** * Only for chaining-capable NamingServices. Add to end of the list. * @return success */ public boolean addNamingService(NamingService ns) { return addNamingService(ns, false); } /** * Only for chaining-capable NamingServices * @param head or tail * @return success */ public boolean addNamingService(NamingService ns, boolean head) { return false; } /** * Only for chaining-capable NamingServices * @return success * @since 0.8.7 */ public boolean removeNamingService(NamingService ns) { return false; } // options would be used to specify public / private / master ... // or should we just daisy chain 3 HostsTxtNamingServices ? // that might be better... then addressbook only talks to the 'router' HostsTxtNamingService /** * @return number of entries or -1 if unknown * @since 0.8.7 */ public int size() { return size(null); } /** * @param options NamingService-specific, can be null * @return number of entries (matching the options if non-null) or -1 if unknown * @since 0.8.7 */ public int size(Properties options) { return -1; } /** * Warning - This obviously brings the whole database into memory, * so use is discouraged. * * @return all mappings * or empty Map if none; * Returned Map is not necessarily sorted, implementation dependent * @since 0.8.7 */ public Map<String, Destination> getEntries() { return getEntries(null); } /** * Warning - This will bring the whole database into memory * if options is null, empty, or unsupported, use with caution. * * @param options NamingService-specific, can be null * @return all mappings (matching the options if non-null) * or empty Map if none; * Returned Map is not necessarily sorted, implementation dependent * @since 0.8.7 */ public Map<String, Destination> getEntries(Properties options) { return Collections.EMPTY_MAP; } /** * This may be more or less efficient than getEntries(), * depending on the implementation. * Warning - This will bring the whole database into memory * if options is null, empty, or unsupported, use with caution. * * @param options NamingService-specific, can be null * @return all mappings (matching the options if non-null) * or empty Map if none; * Returned Map is not necessarily sorted, implementation dependent * @since 0.8.7 */ public Map<String, String> getBase64Entries(Properties options) { return Collections.EMPTY_MAP; } /** * @return all known host names * or empty Set if none; * Returned Set is not necessarily sorted, implementation dependent * @since 0.8.7 */ public Set<String> getNames() { return getNames(null); } /** * @param options NamingService-specific, can be null * @return all known host names (matching the options if non-null) * or empty Set if none; * Returned Set is not necessarily sorted, implementation dependent * @since 0.8.7 */ public Set<String> getNames(Properties options) { return Collections.EMPTY_SET; } /** * @return success * @since 0.8.7 */ public boolean put(String hostname, Destination d) { return put(hostname, d, null); } /** * @param options NamingService-specific, can be null * @return success * @since 0.8.7 */ public boolean put(String hostname, Destination d, Properties options) { return false; } /** * Fails if entry previously exists * @return success * @since 0.8.7 */ public boolean putIfAbsent(String hostname, Destination d) { return putIfAbsent(hostname, d, null); } /** * Fails if entry previously exists * @param options NamingService-specific, can be null * @return success * @since 0.8.7 */ public boolean putIfAbsent(String hostname, Destination d, Properties options) { return false; } /** * @param options NamingService-specific, can be null * @return success * @since 0.8.7 */ public boolean putAll(Map<String, Destination> entries, Properties options) { boolean rv = true; for (Map.Entry<String, Destination> entry : entries.entrySet()) { if (!put(entry.getKey(), entry.getValue(), options)) rv = false; } return rv; } /** * Fails if entry did not previously exist. * Warning - unimplemented in any subclass. * * @param d may be null if only options are changing * @param options NamingService-specific, can be null * @return success * @since 0.8.7 */ public boolean update(String hostname, Destination d, Properties options) { return false; } /** * @return success * @since 0.8.7 */ public boolean remove(String hostname) { return remove(hostname, null); } /** * @param options NamingService-specific, can be null * @return success * @since 0.8.7 */ public boolean remove(String hostname, Properties options) { return false; } /** * Ask any registered updaters to update now * @param options NamingService- or updater-specific, may be null * @since 0.8.7 */ public void requestUpdate(Properties options) { for (NamingServiceUpdater nsu : _updaters) { nsu.update(options); } } /** * @since 0.8.7 */ public void registerListener(NamingServiceListener nsl) { _listeners.add(nsl); } /** * @since 0.8.7 */ public void unregisterListener(NamingServiceListener nsl) { _listeners.remove(nsl); } /** * @since 0.8.7 */ public void registerUpdater(NamingServiceUpdater nsu) { _updaters.add(nsu); } /** * @since 0.8.7 */ public void unregisterUpdater(NamingServiceUpdater nsu) { _updaters.remove(nsu); } /** * Same as lookup(hostname) but with in and out options * Note that whether this (and lookup(hostname)) resolve B32 addresses is * NamingService-specific. * @param lookupOptions input parameter, NamingService-specific, can be null * @param storedOptions output parameter, NamingService-specific, any stored properties will be added if non-null * @return dest or null * @since 0.8.7 */ public abstract Destination lookup(String hostname, Properties lookupOptions, Properties storedOptions); /** * Same as reverseLookup(dest) but with options * @param d non-null * @param options NamingService-specific, can be null * @return host name or null * @since 0.8.7 */ public String reverseLookup(Destination d, Properties options) { return null; } /** * Lookup a Base 32 address. This may require the router to fetch the LeaseSet, * which may take quite a while. * @param hostname must be {52 chars}.b32.i2p * @param timeout in seconds; <= 0 means use router default * @return dest or null * @since 0.8.7 */ public Destination lookupBase32(String hostname, int timeout) { return null; } /** * Same as lookupB32 but with the SHA256 Hash precalculated * @param timeout in seconds; <= 0 means use router default * @return dest or null * @since 0.8.7 */ public Destination lookup(Hash hash, int timeout) { return null; } /** * Parent will call when added. * If this is the root naming service, the core will start it. * Should not be called by others. * @since 0.8.7 */ public void start() {} /** * Parent will call when removed. * If this is the root naming service, the core will stop it. * Should not be called by others. * @since 0.8.7 */ public void shutdown() {} //// End New API /** * Get a naming service instance. This method ensures that there * will be only one naming service instance (singleton) as well as * choose the implementation from the "i2p.naming.impl" system * property. * - * FIXME Actually, it doesn't ensure that. Only call this once!!! */ public static final synchronized NamingService createInstance(I2PAppContext context) { - NamingService instance = null; - String impl = context.getProperty(PROP_IMPL, DEFAULT_IMPL); + if (instance instanceof NamingService) { + return instance; + } + String impl = context.getProperty(PROP_IMPL, DEFAULT_IMPL); try { Class cls = Class.forName(impl); Constructor con = cls.getConstructor(new Class[] { I2PAppContext.class }); instance = (NamingService)con.newInstance(new Object[] { context }); - } catch (Exception ex) { - Log log = context.logManager().getLog(NamingService.class); - // Blockfile may throw RuntimeException but HostsTxt won't - if (!impl.equals(BACKUP_IMPL)) { - log.error("Cannot load naming service " + impl + ", using HostsTxtNamingService", ex); - instance = new HostsTxtNamingService(context); - } else { - log.error("Cannot load naming service " + impl + ", only .b32.i2p lookups will succeed", ex); - instance = new DummyNamingService(context); - } - } + } catch (Exception ex) { + Log log = context.logManager().getLog(NamingService.class); + // Blockfile may throw RuntimeException but HostsTxt won't + if (!impl.equals(BACKUP_IMPL)) { + log.error("Cannot load naming service " + impl + ", using HostsTxtNamingService", ex); + instance = new HostsTxtNamingService(context); + } else { + log.error("Cannot load naming service " + impl + ", only .b32.i2p lookups will succeed", ex); + instance = new DummyNamingService(context); + } + } return instance; } }
false
false
null
null
diff --git a/src/FE_SRC_COMMON/com/ForgeEssentials/util/BlockSaveable.java b/src/FE_SRC_COMMON/com/ForgeEssentials/util/BlockSaveable.java index 9512a35f6..61580f1f4 100644 --- a/src/FE_SRC_COMMON/com/ForgeEssentials/util/BlockSaveable.java +++ b/src/FE_SRC_COMMON/com/ForgeEssentials/util/BlockSaveable.java @@ -1,84 +1,84 @@ package com.ForgeEssentials.util; //Depreciated import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; public class BlockSaveable { private int x; private int y; private int z; private short blockID; private byte metadata; private NBTTagCompound tile; /** * generates the block from the world. * @param world * @param x * @param y * @param z */ public BlockSaveable(World world, int x, int y, int z) { this.x = x; this.y = y; this.z = z; blockID = (short) world.getBlockId(x, y, z); metadata = (byte) world.getBlockMetadata(x, y, z); TileEntity entity = world.getBlockTileEntity(x, y, z); if (entity != null) { try { NBTTagCompound compound = new NBTTagCompound(); entity.writeToNBT(compound); tile = compound; } catch (Exception e) { } } } @Override public boolean equals(Object object) { if (object == null) return false; if (object instanceof BlockSaveable) { BlockSaveable block = (BlockSaveable) object; return blockID == block.blockID && metadata == block.metadata && tile.equals(block.tile); } return false; } /** * @param world * @return if the block was actually set. */ public boolean setinWorld(World world) { if (equals(new BlockSaveable(world, x, y, z))) return false; - world.setBlock(x, y, z, blockID, metadata, 1); + world.setBlock(x, y, z, blockID, metadata, 3); TileEntity entity = world.getBlockTileEntity(x, y, z); if (entity != null && tile != null) { entity.readFromNBT(tile); } return true; } public boolean isAir() { return blockID == 0; } }
true
false
null
null
diff --git a/testing/src/test/java/acceptance/loan/AdminUserCanDeleteLoanProductStory.java b/testing/src/test/java/acceptance/loan/AdminUserCanDeleteLoanProductStory.java index 0692a9b..1ae40e6 100644 --- a/testing/src/test/java/acceptance/loan/AdminUserCanDeleteLoanProductStory.java +++ b/testing/src/test/java/acceptance/loan/AdminUserCanDeleteLoanProductStory.java @@ -1,112 +1,120 @@ /* * Copyright (c) 2005-2008 Grameen Foundation USA * 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. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package acceptance.loan; import java.io.IOException; +import java.io.StringReader; +import java.sql.Connection; import java.sql.SQLException; +import org.dbunit.Assertion; +import org.dbunit.DataSourceDatabaseTester; import org.dbunit.DatabaseUnitException; +import org.dbunit.IDatabaseTester; +import org.dbunit.database.IDatabaseConnection; import org.dbunit.dataset.DataSetException; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.ITable; +import org.dbunit.dataset.xml.FlatXmlDataSet; import org.mifos.test.framework.util.DatabaseTestUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.datasource.DataSourceUtils; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.test.context.ContextConfiguration; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import framework.pageobjects.DeleteLoanProductPage; import framework.pageobjects.LoginPage; import framework.pageobjects.ViewLoanProductDetailsPage; import framework.test.UiTestCaseBase; /* * Corresponds to story 681 in Mingle * {@link http://mingle.mifos.org:7070/projects/cheetah/cards/681 } */ @ContextConfiguration(locations={"classpath:ui-test-context.xml"}) @Test(groups={"DeleteLoanProductStory","acceptance","ui", "workInProgress"}) public class AdminUserCanDeleteLoanProductStory extends UiTestCaseBase { private LoginPage loginPage; @Autowired private DriverManagerDataSource dataSource; private static final DatabaseTestUtils dbTestUtils = new DatabaseTestUtils(); private static final String loanProductWithNoLoansDataSetXml = "<dataset>\n" + " <loanproducts id=\"1\" longName=\"long1\" maxInterestRate=\"2.0\" minInterestRate=\"1.0\" shortName=\"short1\" status=\"0\"/>\n" + " <loans/>\n" + "</dataset>\n"; private static final String loanProductWithLoansDataSetXml = "<dataset>\n" + " <loanproducts id=\"1\" longName=\"long1\" maxInterestRate=\"2.0\" minInterestRate=\"1.0\" shortName=\"short1\" status=\"0\"/>\n" + " <loans id=\"1\" amount=\"10.1\" clientId=\"1\" interestRate=\"10\" loanProductId=\"1\" disbursalDate=\"2007-01-01\" />\n " + "</dataset>\n"; @BeforeMethod @SuppressWarnings("PMD.SignatureDeclareThrowsException") // signature of superclass method public void setUp() throws Exception { super.setUp(); loginPage = new LoginPage(selenium); } @AfterMethod public void logOut() { loginPage.logout(); } public void testDeleteLoanProductWithoutLoans() throws DataSetException, IOException, SQLException, DatabaseUnitException { insertDataSetAndDeleteProduct(loanProductWithNoLoansDataSetXml); Assert.assertEquals(selenium.getText("id=deleteLoanProduct.successMessage"), "Successfully deleted loan product 'long1'."); } public void testDeleteLoanProductWithLoans() throws DataSetException, IOException, SQLException, DatabaseUnitException { insertDataSetAndDeleteProduct(loanProductWithLoansDataSetXml); Assert.assertEquals(selenium.getText("id=deleteLoanProduct.errorMessage"), "Could not delete loan product 'long1' because there are loans that use this product."); } private void insertDataSetAndDeleteProduct(String dataSetXml) throws IOException, DataSetException, SQLException, DatabaseUnitException { dbTestUtils.cleanAndInsertDataSet(dataSetXml, dataSource); ViewLoanProductDetailsPage viewLoanProductDetailsPage = navigateToViewLoanProductDetailsPage("short1"); DeleteLoanProductPage deleteLoanProductPage = viewLoanProductDetailsPage.navigateToDeleteLoanProductPage(); deleteLoanProductPage.verifyPage(); deleteLoanProductPage.deleteLoanProduct(); } private ViewLoanProductDetailsPage navigateToViewLoanProductDetailsPage (String linkName){ return loginPage .loginAs("mifos", "testmifos") .navigateToAdminPage() .navigateToViewLoanProductsPage() .navigateToViewLoanProductDetailsPage(linkName); } - - }
false
false
null
null
diff --git a/src/main/java/com/philihp/weblabora/model/CommandSettle.java b/src/main/java/com/philihp/weblabora/model/CommandSettle.java index 57259da..4fb3e8a 100644 --- a/src/main/java/com/philihp/weblabora/model/CommandSettle.java +++ b/src/main/java/com/philihp/weblabora/model/CommandSettle.java @@ -1,64 +1,74 @@ package com.philihp.weblabora.model; import static com.philihp.weblabora.model.TerrainTypeEnum.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.List; import com.philihp.weblabora.model.building.*; public class CommandSettle implements MoveCommand { + + private Integer grokParam(String num, String name, String param) throws WeblaboraException { + try { + return new Integer(param); + } + catch(NumberFormatException e) { + throw new WeblaboraException(num+" parameter, "+name+"=\""+param+"\" needs to be a number"); + } + } @Override public void execute(Board board, CommandParameters params) throws WeblaboraException { execute(board, params.get(0), - Integer.parseInt(params.get(1)), - Integer.parseInt(params.get(2)), + grokParam("Second", "x", params.get(1)), + grokParam("Third", "y", params.get(2)), new UsageParam(params.get(3)) ); + System.out.println("Settling "+params.get(0)+" at ("+params.get(1)+","+params.get(2)+")"); } public static void execute(Board board, String settlementId, int x, int y, UsageParam payment) throws WeblaboraException { Player player = board.getPlayer(board.getActivePlayer()); Terrain location = player.getLandscape().getTerrain().get(y, x); Settlement settlement = findSettlement(player.getUnbuiltSettlements(), settlementId); if(location.getErection() != null) { throw new WeblaboraException("There is already an erection at ("+x+","+y+"): "+location.getErection()); } if(settlement.getTerrains().contains(location.getTerrainType()) == false) { throw new WeblaboraException("The location at ("+x+","+y+") has a terrain of "+location.getTerrainType()+", which is not appropriate for "+settlement.getName()); } if(payment.getEnergy() < settlement.getEnergyCost()) { throw new WeblaboraException(settlement.getName()+" costs "+settlement.getEnergyCost()+" energy but player only supplied "+payment.getEnergy()); } if(payment.getFood() < settlement.getFoodCost()) { throw new WeblaboraException(settlement.getName()+" costs "+settlement.getFoodCost()+" food but player only supplied "+payment.getFood()); } player.subtractAll(payment); location.setErection(settlement); } private static Settlement findSettlement( List<Settlement> unbuiltSettlements, String settlementId) throws WeblaboraException { for(Settlement settlement : unbuiltSettlements) { if(settlement.getId().equals(settlementId)) { unbuiltSettlements.remove(settlement); return settlement; } } throw new WeblaboraException("Settlement "+settlementId +" was not be found in unsettled settlements"); } }
false
false
null
null
diff --git a/common/logisticspipes/proxy/ic2/ElectricItemProxy.java b/common/logisticspipes/proxy/ic2/ElectricItemProxy.java index 9bb4c431..a6f7f512 100644 --- a/common/logisticspipes/proxy/ic2/ElectricItemProxy.java +++ b/common/logisticspipes/proxy/ic2/ElectricItemProxy.java @@ -1,94 +1,120 @@ package logisticspipes.proxy.ic2; import ic2.api.IElectricItem; import ic2.api.Ic2Recipes; import ic2.api.Items; import logisticspipes.LogisticsPipes; import logisticspipes.items.ItemModule; import logisticspipes.proxy.interfaces.IElectricItemProxy; import net.minecraft.src.Item; import net.minecraft.src.ItemStack; import buildcraft.BuildCraftCore; import buildcraft.BuildCraftSilicon; public class ElectricItemProxy implements IElectricItemProxy { public boolean isElectricItem(ItemStack stack) { return stack != null && stack.getItem() instanceof IElectricItem; } public int getCharge(ItemStack stack) { if (stack.getItem() instanceof IElectricItem && stack.hasTagCompound()) return stack.getTagCompound().getInteger("charge"); else return 0; } public int getMaxCharge(ItemStack stack) { if (stack.getItem() instanceof IElectricItem) return ((IElectricItem) stack.getItem()).getMaxCharge(); else return 0; } public boolean isDischarged(ItemStack stack, boolean partial) { return isDischarged(stack, partial, stack.getItem()); } public boolean isCharged(ItemStack stack, boolean partial) { return isCharged(stack, partial, stack.getItem()); } public boolean isDischarged(ItemStack stack, boolean partial, Item electricItem) { if (electricItem instanceof IElectricItem && (((IElectricItem)electricItem).getChargedItemId() == stack.itemID || ((IElectricItem)electricItem).getEmptyItemId() == stack.itemID)) { if (partial) return getCharge(stack) < getMaxCharge(stack); else return getCharge(stack) == 0; } return false; } public boolean isCharged(ItemStack stack, boolean partial, Item electricItem) { if (electricItem instanceof IElectricItem && ((IElectricItem)electricItem).getChargedItemId() == stack.itemID) { if (partial) return getCharge(stack) > 0; else return getCharge(stack) == getMaxCharge(stack); } return false; } public void addCraftingRecipes() { Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { "CGD", "rBr", "DrC", Character.valueOf('C'), Items.getItem("electronicCircuit"), Character.valueOf('D'), Items.getItem("reBattery"), Character.valueOf('G'), BuildCraftCore.goldGearItem, Character.valueOf('r'), Item.redstone, Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); + Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { "CGD", "rBr", "DrC", + Character.valueOf('C'), Items.getItem("electronicCircuit"), + Character.valueOf('D'), Items.getItem("chargedReBattery"), + Character.valueOf('G'), BuildCraftCore.goldGearItem, + Character.valueOf('r'), Item.redstone, + Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); + Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { "CGc", "rBr", "DrC", + Character.valueOf('C'), Items.getItem("electronicCircuit"), + Character.valueOf('c'), Items.getItem("reBattery"), + Character.valueOf('D'), Items.getItem("chargedReBattery"), + Character.valueOf('G'), BuildCraftCore.goldGearItem, + Character.valueOf('r'), Item.redstone, + Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); + Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { "CGc", "rBr", "DrC", + Character.valueOf('C'), Items.getItem("electronicCircuit"), + Character.valueOf('c'), Items.getItem("chargedReBattery"), + Character.valueOf('D'), Items.getItem("reBattery"), + Character.valueOf('G'), BuildCraftCore.goldGearItem, + Character.valueOf('r'), Item.redstone, + Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { " G ", "rBr", "DrC", Character.valueOf('C'), Items.getItem("electronicCircuit"), Character.valueOf('D'), Items.getItem("reBattery"), Character.valueOf('G'), new ItemStack(BuildCraftSilicon.redstoneChipset, 1, 2), Character.valueOf('r'), Item.redstone, Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); + Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { " G ", "rBr", "DrC", + Character.valueOf('C'), Items.getItem("electronicCircuit"), + Character.valueOf('D'), Items.getItem("chargedReBattery"), + Character.valueOf('G'), new ItemStack(BuildCraftSilicon.redstoneChipset, 1, 2), + Character.valueOf('r'), Item.redstone, + Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); } @Override public boolean hasIC2() { return true; } }
false
true
public void addCraftingRecipes() { Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { "CGD", "rBr", "DrC", Character.valueOf('C'), Items.getItem("electronicCircuit"), Character.valueOf('D'), Items.getItem("reBattery"), Character.valueOf('G'), BuildCraftCore.goldGearItem, Character.valueOf('r'), Item.redstone, Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { " G ", "rBr", "DrC", Character.valueOf('C'), Items.getItem("electronicCircuit"), Character.valueOf('D'), Items.getItem("reBattery"), Character.valueOf('G'), new ItemStack(BuildCraftSilicon.redstoneChipset, 1, 2), Character.valueOf('r'), Item.redstone, Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); }
public void addCraftingRecipes() { Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { "CGD", "rBr", "DrC", Character.valueOf('C'), Items.getItem("electronicCircuit"), Character.valueOf('D'), Items.getItem("reBattery"), Character.valueOf('G'), BuildCraftCore.goldGearItem, Character.valueOf('r'), Item.redstone, Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { "CGD", "rBr", "DrC", Character.valueOf('C'), Items.getItem("electronicCircuit"), Character.valueOf('D'), Items.getItem("chargedReBattery"), Character.valueOf('G'), BuildCraftCore.goldGearItem, Character.valueOf('r'), Item.redstone, Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { "CGc", "rBr", "DrC", Character.valueOf('C'), Items.getItem("electronicCircuit"), Character.valueOf('c'), Items.getItem("reBattery"), Character.valueOf('D'), Items.getItem("chargedReBattery"), Character.valueOf('G'), BuildCraftCore.goldGearItem, Character.valueOf('r'), Item.redstone, Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { "CGc", "rBr", "DrC", Character.valueOf('C'), Items.getItem("electronicCircuit"), Character.valueOf('c'), Items.getItem("chargedReBattery"), Character.valueOf('D'), Items.getItem("reBattery"), Character.valueOf('G'), BuildCraftCore.goldGearItem, Character.valueOf('r'), Item.redstone, Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { " G ", "rBr", "DrC", Character.valueOf('C'), Items.getItem("electronicCircuit"), Character.valueOf('D'), Items.getItem("reBattery"), Character.valueOf('G'), new ItemStack(BuildCraftSilicon.redstoneChipset, 1, 2), Character.valueOf('r'), Item.redstone, Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { " G ", "rBr", "DrC", Character.valueOf('C'), Items.getItem("electronicCircuit"), Character.valueOf('D'), Items.getItem("chargedReBattery"), Character.valueOf('G'), new ItemStack(BuildCraftSilicon.redstoneChipset, 1, 2), Character.valueOf('r'), Item.redstone, Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); }
diff --git a/src/edgruberman/bukkit/doorman/commands/History.java b/src/edgruberman/bukkit/doorman/commands/History.java index cf37a06..48c9722 100644 --- a/src/edgruberman/bukkit/doorman/commands/History.java +++ b/src/edgruberman/bukkit/doorman/commands/History.java @@ -1,60 +1,60 @@ package edgruberman.bukkit.doorman.commands; import java.util.List; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import edgruberman.bukkit.doorman.Main; import edgruberman.bukkit.doorman.RecordKeeper; import edgruberman.bukkit.doorman.RecordKeeper.Message; public class History implements CommandExecutor { - private static final int PAGE_SIZE = 10; + private static final int PAGE_SIZE = 5; private final RecordKeeper records; public History(final RecordKeeper records) { this.records = records; } // usage: /<command>[ <Page>] @Override public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { final long lastPlayed = ( sender instanceof Player ? ((Player) sender).getLastPlayed() : System.currentTimeMillis() ); final List<Message> history = this.records.getHistory(); - final int bodySize = History.PAGE_SIZE - Main.courier.compose("history|footer").size(); + final int bodySize = History.PAGE_SIZE - (Main.courier.getBase().getString("history|footer").split("\\n").length); final int pageTotal = (history.size() / bodySize) + ( history.size() % bodySize > 0 ? 1 : 0 ); final int pageCurrent = ( args.length >= 1 ? History.parseInt(args[0], 1) : 1 ); if (pageCurrent <= 0 || pageCurrent > pageTotal) { Main.courier.send(sender, "unknown-page", pageCurrent); return false; } final int first = (pageCurrent - 1) * bodySize; final int last = Math.min(first + bodySize, history.size()); int index = first; for (final Message message : history.subList(first, last)) { Main.courier.send(sender, "history|body", ( message.set > lastPlayed ? 1 : 0 ) , message.set, message.from, message.text , RecordKeeper.duration(System.currentTimeMillis() - message.set) , index); index++; } - Main.courier.send(sender, "history|footer", pageCurrent, pageTotal); + Main.courier.send(sender, "history|footer", pageCurrent, pageTotal, ( pageCurrent < pageTotal ? pageCurrent + 1 : 1 )); return true; } private static Integer parseInt(final String s, final Integer def) { try { return Integer.parseInt(s); } catch (final NumberFormatException e) { return def; } } }
false
false
null
null
diff --git a/src/main/java/be/valuya/jbooks/Winbooks.java b/src/main/java/be/valuya/jbooks/Winbooks.java index fd8d4fd..ebbec7b 100644 --- a/src/main/java/be/valuya/jbooks/Winbooks.java +++ b/src/main/java/be/valuya/jbooks/Winbooks.java @@ -1,995 +1,1008 @@ package be.valuya.jbooks; import be.valuya.csv.CsvHandler; import be.valuya.jbooks.exception.WinbooksError; import be.valuya.jbooks.exception.WinbooksException; import be.valuya.jbooks.exception.WinbooksInitException; import be.valuya.jbooks.exception.WinbooksLoginException; import be.valuya.jbooks.exception.WinbooksOpenBookyearException; import be.valuya.jbooks.exception.WinbooksOpenDossierException; import be.valuya.jbooks.model.WbBookYear; import be.valuya.jbooks.model.WbClientSupplier; import be.valuya.jbooks.model.WbClientSupplierType; import be.valuya.jbooks.model.WbCustomClientAttribute; import be.valuya.jbooks.model.WbDbkType; import be.valuya.jbooks.model.WbDocOrderType; import be.valuya.jbooks.model.WbDocStatus; import be.valuya.jbooks.model.WbDocType; import static be.valuya.jbooks.model.WbDocType.IMPUT_CLIENT; import static be.valuya.jbooks.model.WbDocType.IMPUT_SUPPLIER; import be.valuya.jbooks.model.WbEntry; import be.valuya.jbooks.model.WbImport; import be.valuya.jbooks.model.WbImportResult; import be.valuya.jbooks.model.WbInvoice; import be.valuya.jbooks.model.WbInvoiceLine; import be.valuya.jbooks.model.WbLanguage; import be.valuya.jbooks.model.WbMemoType; import be.valuya.jbooks.model.WbMitigation; import be.valuya.jbooks.model.WbPeriod; import be.valuya.jbooks.model.WbVatCat; import be.valuya.jbooks.model.WbVatCode; import be.valuya.jbooks.model.WbWarning; import be.valuya.jbooks.model.WbWarningResolution; import be.valuya.jbooks.util.WbFatalError; import be.valuya.jbooks.util.WbValueFormat; import be.valuya.winbooks.ClassFactory; import be.valuya.winbooks.LangueforVat; import be.valuya.winbooks.TypeSolution; import be.valuya.winbooks.WinbooksObject___v0; import be.valuya.winbooks._BookYear; import be.valuya.winbooks._BookYears; +import be.valuya.winbooks._Comptes; import be.valuya.winbooks._ErrorCode; import be.valuya.winbooks._FatalError; import be.valuya.winbooks._FatalErrors; import be.valuya.winbooks._Field; import be.valuya.winbooks._Fields; import be.valuya.winbooks._Import; import be.valuya.winbooks._Param; import be.valuya.winbooks._Period; import be.valuya.winbooks._Periods; -import be.valuya.winbooks._Tables; -import be.valuya.winbooks._TablesUser; +import be.valuya.winbooks._Transactions; import be.valuya.winbooks._Warning; import be.valuya.winbooks._Warnings; import com4j.Holder; import java.io.IOException; import java.math.BigDecimal; import java.nio.file.Files; import java.nio.file.Path; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.Format; import java.text.MessageFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; /** * Hello world! * */ public class Winbooks { private final WinbooksObject___v0 winbooksCom; /** * Book year override, will replace book year for dates, period, ... (e.g. demo is limited to some book years). */ private Integer bookYearOverride; private String bookYearNameOverride; private String dossierOverride; public Winbooks() { winbooksCom = ClassFactory.createWinbooksObject(); short result = winbooksCom.init(); String lastErrorMessage = winbooksCom.lastErrorMessage(); switch (result) { case 0: case 3: break; case 1: throw new WinbooksInitException(WinbooksError.USER_FILE_ERROR, lastErrorMessage); default: throw new WinbooksInitException(WinbooksError.UNKNOWN_ERROR, lastErrorMessage); } } public void login(String userName, String userPassword, WbLanguage WbLanguage) { String languangeStr = WbLanguage.getValue(); short result = winbooksCom.login(userName, userPassword, languangeStr); String lastErrorMessage = winbooksCom.lastErrorMessage(); switch (result) { case 0: break; case 1: throw new WinbooksLoginException(WinbooksError.NOT_INITIALIZED, lastErrorMessage); case 2: throw new WinbooksLoginException(WinbooksError.USER_FILE_ERROR, lastErrorMessage); default: throw new WinbooksLoginException(WinbooksError.UNKNOWN_ERROR, lastErrorMessage); } } public void close() { winbooksCom.closeDossier(); } public short openDossier(String shortName) { short result; if (dossierOverride != null) { result = winbooksCom.openDossier(dossierOverride); } else { result = winbooksCom.openDossier(shortName); } String lastErrorMessage = winbooksCom.lastErrorMessage(); switch (result) { case 0: break; case 1: throw new WinbooksOpenDossierException(WinbooksError.NO_DOSSIER, lastErrorMessage); case 2: throw new WinbooksOpenDossierException(WinbooksError.NOT_INITIALIZED, lastErrorMessage); case 3: throw new WinbooksOpenDossierException(WinbooksError.NOT_LOGGED_IN, lastErrorMessage); case 4: throw new WinbooksOpenDossierException(WinbooksError.BAD_PASSWORD, lastErrorMessage); case 5: throw new WinbooksOpenDossierException(WinbooksError.DOSSIER_NOT_FOUND, lastErrorMessage); case 6: throw new WinbooksOpenDossierException(WinbooksError.DOSSIER_LOCKED, lastErrorMessage); case 7: throw new WinbooksOpenDossierException(WinbooksError.API_UNLICENSED, lastErrorMessage); case 8: throw new WinbooksOpenDossierException(WinbooksError.DEMO, lastErrorMessage); default: throw new WinbooksInitException(WinbooksError.UNKNOWN_ERROR, lastErrorMessage); } return result; } public short openBookYear(String bookYearShortName) { short result; if (bookYearNameOverride != null) { result = winbooksCom.openBookYear(bookYearNameOverride); } else { result = winbooksCom.openBookYear(bookYearShortName); } String lastErrorMessage = winbooksCom.lastErrorMessage(); switch (result) { case 0: break; case 1: throw new WinbooksOpenBookyearException(WinbooksError.NO_DOSSIER, lastErrorMessage); case 2: throw new WinbooksOpenBookyearException(WinbooksError.NO_BOOKYEAR, lastErrorMessage); case 3: throw new WinbooksOpenBookyearException(WinbooksError.BOOKYEAR_NOT_FOUND, lastErrorMessage); case 4: throw new WinbooksOpenBookyearException(WinbooksError.CANNOT_OPEN_DOSSIER, lastErrorMessage); default: throw new WinbooksInitException(WinbooksError.UNKNOWN_ERROR, lastErrorMessage); } return result; } public WbImportResult importDataTest(WbImport wbImport) { _Import internalImport = testImportInternal(wbImport); WbImportResult wbImportResult = createImportResult(internalImport); return wbImportResult; } public WbImportResult importData(WbImport wbImport, List<WbMitigation> wbMitigations) { return importData(wbImport, wbMitigations, false); } public WbImportResult importData(WbImport wbImport, List<WbMitigation> wbMitigations, boolean throwException) { _Import internalImport = testImportInternal(wbImport); // mitigation mitigateWarnings(internalImport, wbMitigations); // import short executeResult = internalImport.execute(); // process result WinbooksError winbooksError = getWinbooksErrorForInternalImportResult(executeResult); String errorMessage = winbooksCom.lastErrorMessage(); if (winbooksError != null && throwException) { throw new WinbooksException(winbooksError, errorMessage); } WbImportResult wbImportResult = createImportResult(internalImport); wbImportResult.setWinbooksError(winbooksError); wbImportResult.setErrorMessage(errorMessage); return wbImportResult; } private WinbooksError getWinbooksErrorForInternalImportResult(short internalImportResult) { WinbooksError winbooksError; switch (internalImportResult) { case 0: winbooksError = null; case 1: winbooksError = WinbooksError.UNTESTED; case 2: winbooksError = WinbooksError.UNRESOLVED_WARNINGS; case 3: winbooksError = WinbooksError.FATAL_ERRORS; case 4: winbooksError = WinbooksError.RESOLUTION_UNSYCHRONIZED; default: winbooksError = WinbooksError.UNKNOWN_ERROR; } return winbooksError; } private void checkBooleanResult(boolean result) { if (!result) { String lastErrorMessage = winbooksCom.lastErrorMessage(); throw new WinbooksException(WinbooksError.UNKNOWN_ERROR, lastErrorMessage); } } private Path generateDataFilesInTempDirectory(WbImport wbImport) { try { Path tempPath = Files.createTempDirectory("Wb"); List<WbClientSupplier> wbClients = wbImport.getWbClientSupplierList(); List<WbEntry> wbEntries = wbImport.getWbEntries(); generateDataFiles(tempPath, wbClients, wbEntries); return tempPath; } catch (IOException ioException) { throw new RuntimeException("Could not create temporary directory", ioException); } } private void generateDataFiles(Path path, List<WbClientSupplier> wbClientSupplierList, List<WbEntry> wbEntries) throws IOException { generateClientSupplierCsv(wbClientSupplierList, path); generateEntriesCsv(wbEntries, path); } private List<WbWarning> getWarnings(_Import wbImport) { List<WbWarning> wbWarnings = new ArrayList<>(); _Warnings internalWarnings = wbImport.warnings(); short warningCount = internalWarnings.count(); for (short i = 1; i <= warningCount; i++) { _Warning internalWarning = internalWarnings.item(i); WbWarning wbWarning = convertInternalWarning(internalWarning, wbImport); wbWarnings.add(wbWarning); } return wbWarnings; } private List<WbFatalError> getFatalErrors(_Import wbImport) { List<WbFatalError> wbFatalErrors = new ArrayList<>(); _FatalErrors internalFatalErrors = wbImport.fatalErrors(); short errorCount = internalFatalErrors.count(); for (short i = 1; i <= errorCount; i++) { _FatalError internalFatalError = internalFatalErrors.item(i); WbFatalError wbFatalError = convertInternalFatalError(internalFatalError, wbImport); wbFatalErrors.add(wbFatalError); } return wbFatalErrors; } private void mitigateWarnings(_Import wbImport, List<WbMitigation> wbMitigations) { // generic mitigation (not invoice-specific) if (wbMitigations != null) { for (WbMitigation wbMitigation : wbMitigations) { String target = wbMitigation.getTarget(); if (target != null) { // specific mitigation, skip now continue; } String code = wbMitigation.getCode(); TypeSolution typeSolution = wbMitigation.getTypeSolution(); _ErrorCode internalErrorCode = wbImport.errorCodes(code); internalErrorCode.setResolution(typeSolution); } } // create a map of specific mitigations // key type has code+target as identity Map<WbWarning, TypeSolution> specificWarningResolutionMap = new HashMap<>(); if (wbMitigations != null) { for (WbMitigation wbMitigation : wbMitigations) { String code = wbMitigation.getCode(); String target = wbMitigation.getTarget(); WbWarning wbWarning = new WbWarning(code, target); TypeSolution typeSolution = wbMitigation.getTypeSolution(); specificWarningResolutionMap.put(wbWarning, typeSolution); } } // iterate over warnings and apply specific resolutions _Warnings internalWarnings = wbImport.warnings(); short warningCount = internalWarnings.count(); for (short i = 0; i < warningCount; i++) { _Warning internalWarning = internalWarnings.item(i); WbWarning wbWarning = convertInternalWarning(internalWarning, wbImport); TypeSolution typeSolution = specificWarningResolutionMap.get(wbWarning); Holder<TypeSolution> typeSolutionHolder = new Holder<>(typeSolution); internalWarning.setResolution(typeSolutionHolder); } } private WbFatalError convertInternalFatalError(_FatalError internalFatalError, _Import wbImport) { String code = internalFatalError.code(); String param = internalFatalError.param(); _ErrorCode internalErrorCode = wbImport.errorCodes(code); String description = internalErrorCode.description(); WbFatalError wbFatalError = new WbFatalError(); wbFatalError.setCode(code); wbFatalError.setTarget(param); wbFatalError.setDescription(description); return wbFatalError; } private WbWarning convertInternalWarning(_Warning internalWarning, _Import wbImport) { String code = internalWarning.code(); String param = internalWarning.param(); _ErrorCode internalErrorCode = wbImport.errorCodes(code); List<WbWarningResolution> wbWarningResolutions = new ArrayList<>(); List<TypeSolution> typesSolutions = getTypesSolutions(internalErrorCode); for (TypeSolution typeSolution : typesSolutions) { WbWarningResolution wbWarningResolution = convertTypeSolution(typeSolution); wbWarningResolutions.add(wbWarningResolution); } String description = internalErrorCode.description(); WbWarning wbWarning = new WbWarning(); wbWarning.setCode(code); wbWarning.setTarget(param); wbWarning.setWbWarningResolutions(wbWarningResolutions); wbWarning.setDescription(description); return wbWarning; } private List<TypeSolution> getTypesSolutions(_ErrorCode internalErrorCode) { String concatenedAllowableAction = internalErrorCode.allowableActions(); String[] allowableActionArray = concatenedAllowableAction.split(" "); List<String> allowableActions = Arrays.asList(allowableActionArray); List<TypeSolution> typesSolutions = new ArrayList<>(); for (String allowableAction : allowableActions) { if (!allowableAction.isEmpty()) { TypeSolution typeSolution = TypeSolution.valueOf(allowableAction); typesSolutions.add(typeSolution); } } if (!typesSolutions.contains(TypeSolution.wbReplace)) { typesSolutions.add(TypeSolution.wbReplace); } return typesSolutions; } public WbVatCode getInternalVatCode(BigDecimal vatRate, WbClientSupplierType wbClientSupplierType, WbLanguage wbLanguage) { _Param param = winbooksCom.param(); int vatRateInt = vatRate.intValue(); String vatRateStr = Integer.toString(vatRateInt); String clientSupplierTypeStr = wbClientSupplierType.getValue(); String langStr = wbLanguage.getValue(); // ATTENTION: Winbooks DLL sometimes crashes (then works again randomly) when putting anythig else here Holder<String> langHolder = new Holder<>(); String internalVatCode = param.vatInternalCode(vatRateStr, clientSupplierTypeStr, langHolder).trim(); String vatAcc1 = param.vatAcc1(internalVatCode).trim(); String vatAcc2 = param.vatAcc2(internalVatCode).trim(); LangueforVat langueforVat = wbLanguage.getLangueforVat(); String externalVatCode = (String) param.vatExternalCode(internalVatCode, langueforVat); Double vatRateDouble = (Double) param.vatRate(internalVatCode); BigDecimal internalVatRate = BigDecimal.valueOf(vatRateDouble); WbVatCode wbVatCode = new WbVatCode(); wbVatCode.setInternalVatCode(internalVatCode); wbVatCode.setAccount1(vatAcc1); wbVatCode.setAccount2(vatAcc2); wbVatCode.setExternalVatCode(externalVatCode); wbVatCode.setVatRate(internalVatRate); return wbVatCode; } public String getDllVersion() { String dllVersion = winbooksCom.getDllVersion(); return dllVersion; } public Date getDllCompilDate() { try { String dllCompilDateStr = winbooksCom.getDllCompilDate(); DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); Date dllCompilDate = dateFormat.parse(dllCompilDateStr); return dllCompilDate; } catch (ParseException parseException) { throw new RuntimeException(parseException); } } public List<WbBookYear> getBookYears() { List<WbBookYear> wbBookYears = new ArrayList<>(); _BookYears bookYears = winbooksCom.bookYear(); short bookYearCount = bookYears.count(); for (short yearIndex = 1; yearIndex <= bookYearCount; yearIndex++) { _BookYear bookYear = bookYears.item(yearIndex); String shortName = bookYear.shortName(); String longName = bookYear.longName(); WbBookYear wbBookYear = new WbBookYear(); wbBookYear.setShortName(shortName); wbBookYear.setLongName(longName); wbBookYear.setIndex(yearIndex); wbBookYears.add(wbBookYear); } return wbBookYears; } public List<WbPeriod> getBookYearPeriods(WbBookYear wbBookYear) { List<WbPeriod> wbPeriods = new ArrayList<>(); int index = wbBookYear.getIndex(); _BookYear internalBookYear = winbooksCom.bookYear((short) index); _Periods internalPeriods = internalBookYear.periods(); short periodCount = internalPeriods.count(); for (short periodIndex = 1; periodIndex <= periodCount; periodIndex++) { _Period internalPeriod = internalBookYear.periods(periodIndex); String periodName = internalPeriod.name(); String numOfPeriod = internalPeriod.numOfPeriod(periodName); WbPeriod wbPeriod = new WbPeriod(); wbPeriod.setName(periodName); wbPeriod.setNum(numOfPeriod); wbPeriods.add(wbPeriod); } return wbPeriods; } public void doStuff() { - _Tables tables = winbooksCom.tables(); - _TablesUser catCustomer = tables.zipCode(); - _Fields fields2 = catCustomer.fields(); - short fieldCount = fields2.count(); +// _Dossiers dossiers = winbooksCom.companies(); +// short dossierCount = dossiers.count(); +// for (short dossierIndex = 0; dossierIndex < dossierCount; dossierIndex++) { +// _Dossier dossier = dossiers.item(dossierIndex); +// System.out.println(dossier.name()); +// } + + _Transactions accountTrans = winbooksCom.accountTrans(); + _Fields fields = accountTrans.fields(); + + _Comptes comptes = winbooksCom.customers(); +// _Fields fields = comptes.fields(); + +// _Tables tables = winbooksCom.tables(); +// _TablesUser catCustomer = tables.diaries(); +// _Fields fields = catCustomer.fields(); + short fieldCount = fields.count(); for (short fieldIndex = 0; fieldIndex < fieldCount; fieldIndex++) { - _Field field = fields2.item(Short.toString(fieldIndex)); + _Field field = fields.item(Short.toString(fieldIndex)); String name = field.name(); System.out.println("field: " + name); } } public CsvHandler generateClientSupplierCsv(List<WbClientSupplier> wbClientSupplierList) { Format wbValueFormat = new WbValueFormat(); DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH); CsvHandler csvHandler = new CsvHandler(); for (WbClientSupplier wbClientSupplier : wbClientSupplierList) { String number = wbClientSupplier.getNumber(); if (number == null || number.isEmpty()) { throw new WinbooksException(WinbooksError.USER_FILE_ERROR, "La référence client ne peut pas être vide"); } if (!number.matches("[a-zA-Z0-9_]+")) { String message = MessageFormat.format("La référence client ne peut contenir que des chiffres et des lettres - ''{0}''", number); throw new WinbooksException(WinbooksError.USER_FILE_ERROR, message); } String address1 = wbClientSupplier.getAddress1(); String address2 = wbClientSupplier.getAddress2(); String bankAccount = wbClientSupplier.getBankAccount(); String category = wbClientSupplier.getCategory(); String central = wbClientSupplier.getCentral(); String city = wbClientSupplier.getCity(); String civName1 = wbClientSupplier.getCivName1(); String civName2 = wbClientSupplier.getCivName2(); String countryCode = wbClientSupplier.getCountryCode(); String currency = wbClientSupplier.getCurrency(); String defltPost = wbClientSupplier.getDefltPost(); String faxNumber = wbClientSupplier.getFaxNumber(); String lang = wbClientSupplier.getLang(); Date lastRemDat = wbClientSupplier.getLastRemDat(); String lastRemLev = wbClientSupplier.getLastRemLev(); String name1 = wbClientSupplier.getName1(); String name2 = wbClientSupplier.getName2(); String payCode = wbClientSupplier.getPayCode(); String telNumber = wbClientSupplier.getTelNumber(); String vatCode = wbClientSupplier.getVatCode(); String vatNumber = wbClientSupplier.getVatNumber(); WbClientSupplierType wbClientSupplierType = wbClientSupplier.getWbClientSupplierType(); WbMemoType wbMemoType = wbClientSupplier.getWbMemoType(); WbVatCat wbVatCat = wbClientSupplier.getWbVatCat(); List<WbCustomClientAttribute> WbCustomClientAttributes = wbClientSupplier.getWbCustomClientAttributes(); String zipCode = wbClientSupplier.getZipCode(); csvHandler.addCsvLine(); csvHandler.putValue("NUMBER", number); csvHandler.putValue("TYPE", wbValueFormat, wbClientSupplierType); csvHandler.putValue("NAME1", name1); csvHandler.putValue("NAME2", name2); csvHandler.putValue("CIVNAME1", civName1); csvHandler.putValue("CIVNAME2", civName2); csvHandler.putValue("ADDRESS1", address1); csvHandler.putValue("ADDRESS2", address2); csvHandler.putValue("VATCAT", wbValueFormat, wbVatCat); csvHandler.putValue("COUNTRY", countryCode); csvHandler.putValue("VATNUMBER", vatNumber); csvHandler.putValue("PAYCODE", payCode); csvHandler.putValue("TELNUMBER", telNumber); csvHandler.putValue("FAXNUMBER", faxNumber); csvHandler.putValue("BNKACCNT", bankAccount); csvHandler.putValue("ZIPCODE", zipCode); csvHandler.putValue("CITY", city); csvHandler.putValue("DELFTPOST", defltPost); csvHandler.putValue("LANG", lang); csvHandler.putValue("CATEGORY", category); csvHandler.putValue("CENTRAL", central); csvHandler.putValue("VATCODE", vatCode); csvHandler.putValue("CURRENCY", currency); csvHandler.putValue("LASTREMLEV", lastRemLev); csvHandler.putValue("LASTREMDAT", dateFormat, lastRemDat); csvHandler.putValue("MEMOTYPE", wbValueFormat, wbMemoType); for (WbCustomClientAttribute wbCustomClientAttribute : WbCustomClientAttributes) { String name = wbCustomClientAttribute.getName(); String value = wbCustomClientAttribute.getValue(); csvHandler.putValue(name, value); } } return csvHandler; } public void generateClientSupplierCsv(List<WbClientSupplier> wbClientSupplierList, Path path) throws IOException { CsvHandler clientSupplierCsvHandler = generateClientSupplierCsv(wbClientSupplierList); Path clientSupplierPath = path.resolve("csf.txt"); clientSupplierCsvHandler.setWriteHeaders(false); clientSupplierCsvHandler.dumpToFile(clientSupplierPath); } private CsvHandler generateEntriesCsv(List<WbEntry> wbEntries) { Format wbValueFormat = new WbValueFormat(); DecimalFormat vatRateFormat = new DecimalFormat("0.00"); DecimalFormat moneyFormat = new DecimalFormat("0.00"); DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(Locale.ENGLISH); vatRateFormat.setDecimalFormatSymbols(decimalFormatSymbols); moneyFormat.setDecimalFormatSymbols(decimalFormatSymbols); DecimalFormat docOrderFormat = new DecimalFormat("000"); DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH); CsvHandler csvHandler = new CsvHandler(); for (WbEntry wbEntry : wbEntries) { String accountGl = wbEntry.getAccountGl(); String accountRp = wbEntry.getAccountRp(); BigDecimal amount = wbEntry.getAmount(); BigDecimal amountEur = wbEntry.getAmountEur(); String bookYear = wbEntry.getBookYear(); String comment = wbEntry.getComment(); String commentExt = wbEntry.getCommentExt(); BigDecimal curEurBase = wbEntry.getCurEurBase(); BigDecimal curRate = wbEntry.getCurRate(); BigDecimal currAmount = wbEntry.getCurrAmount(); String currCode = wbEntry.getCurrCode(); Date date = wbEntry.getDate(); Date dateDoc = wbEntry.getDateDoc(); WbDocOrderType wbDocOrderType = wbEntry.getWbDocOrderType(); String docOrderStr = wbDocOrderType.getValue(); if (docOrderStr == null) { Integer docOrder = wbEntry.getDocOrder(); docOrderStr = docOrderFormat.format(docOrder); } String docNumber = wbEntry.getDocNumber(); WbDocStatus docStatus = wbEntry.getDocStatus(); Date dueDate = wbEntry.getDueDate(); String matchNo = wbEntry.getMatchNo(); WbMemoType memoType = wbEntry.getMemoType(); Date oldDate = wbEntry.getOldDate(); String period = wbEntry.getPeriod(); BigDecimal vatBase = wbEntry.getVatBase(); String vatCode = wbEntry.getVatCode(); String vatImput = wbEntry.getVatImput(); BigDecimal vatTax = wbEntry.getVatTax(); String dbkCode = wbEntry.getDbkCode(); WbDbkType wbDbkType = wbEntry.getWbDbkType(); WbDocType wbDocType = wbEntry.getWbDocType(); csvHandler.addCsvLine(); csvHandler.putValue("DOCTYPE", wbValueFormat, wbDocType); csvHandler.putValue("DBKCODE", dbkCode); csvHandler.putValue("DBKTYPE", wbValueFormat, wbDbkType); csvHandler.putValue("DOCNUMBER", docNumber); csvHandler.putValue("DOCORDER", docOrderStr); csvHandler.putValue("OPCODE", null); csvHandler.putValue("ACCOUNTGL", accountGl); csvHandler.putValue("ACCOUNTRP", accountRp); csvHandler.putValue("BOOKYEAR", bookYear); csvHandler.putValue("PERIOD", period); csvHandler.putValue("DATE", dateFormat, date); csvHandler.putValue("DATEDOC", dateFormat, dateDoc); csvHandler.putValue("DUEDATE", dateFormat, dueDate); csvHandler.putValue("COMMENT", comment); csvHandler.putValue("COMMENTEXT", commentExt); csvHandler.putValue("AMOUNT", moneyFormat, amount); csvHandler.putValue("AMOUNTEUR", moneyFormat, amountEur); csvHandler.putValue("VATBASE", vatRateFormat, vatBase); csvHandler.putValue("VATCODE", vatCode); csvHandler.putValue("CURRAMOUNT", moneyFormat, currAmount); csvHandler.putValue("CURRCODE", currCode); csvHandler.putValue("CUREURBASE", moneyFormat, curEurBase); csvHandler.putValue("VATTAX", moneyFormat, vatTax); csvHandler.putValue("VATIMPUT", vatImput); csvHandler.putValue("CURRATE", moneyFormat, curRate); csvHandler.putValue("REMINDLEV", null); csvHandler.putValue("MATCHNO", matchNo); csvHandler.putValue("OLDDATE", dateFormat, oldDate); csvHandler.putValue("ISMATCHED", null); csvHandler.putValue("ISLOCKED", null); csvHandler.putValue("ISIMPORTED", null); csvHandler.putValue("ISPOSITIVE", null); csvHandler.putValue("ISTEMP", null); csvHandler.putValue("MEMOTYPE", wbValueFormat, memoType); csvHandler.putValue("ISDOC", null); csvHandler.putValue("DOCSTATUS", wbValueFormat, docStatus); csvHandler.putValue("DICFROM", null); csvHandler.putValue("CODAKEY", null); } return csvHandler; } private void generateEntriesCsv(List<WbEntry> wbEntries, Path path) throws IOException { CsvHandler entriesCsvHandler = generateEntriesCsv(wbEntries); Path entriesPath = path.resolve("act.txt"); entriesCsvHandler.setWriteHeaders(false); entriesCsvHandler.dumpToFile(entriesPath); } public List<WbEntry> convertInvoiceToEntries(WbInvoice wbInvoice, boolean singleLine) { List<WbEntry> wbEntries = new ArrayList<>(); // ajustement montants List<WbInvoiceLine> invoiceLines = wbInvoice.getInvoiceLines(); List<WbInvoiceLine> regroupedInvoiceLines = regroupInvoiceLines(invoiceLines); List<WbInvoiceLine> effectiveInvoiceLines; if (singleLine) { effectiveInvoiceLines = regroupedInvoiceLines; } else { effectiveInvoiceLines = wbInvoice.getInvoiceLines(); } WbClientSupplier wbClientSupplier = wbInvoice.getWbClientSupplier(); String accountGl = wbInvoice.getAccountGl(); if (accountGl == null || accountGl.isEmpty()) { accountGl = wbClientSupplier.getCentral(); } WbDocType wbDocType = wbInvoice.getWbDocType(); String accountRp = wbClientSupplier.getNumber(); Date invoiceDate = wbInvoice.getDate(); Date dueDate = wbInvoice.getDueDate(); if (dueDate == null) { dueDate = invoiceDate; wbInvoice.setDueDate(dueDate); } String dbkCode = wbInvoice.getDbkCode(); WbDbkType wbDbkType; switch (wbDocType) { case IMPUT_CLIENT: { wbDbkType = WbDbkType.SALE; break; } case IMPUT_SUPPLIER: { wbDbkType = WbDbkType.PURCHASE; break; } default: { wbDbkType = WbDbkType.MISC; } } WbClientSupplierType wbClientSupplierType = wbClientSupplier.getWbClientSupplierType(); // main accounting entry WbEntry mainEntry = new WbEntry(); mainEntry.setAccountGl(accountGl); mainEntry.setWbDocType(wbDocType); mainEntry.setAccountRp(accountRp); mainEntry.setDate(invoiceDate); mainEntry.setDateDoc(invoiceDate); mainEntry.setDueDate(dueDate); String invoiceDescription = wbInvoice.getDescription(); String invoiceRef = wbInvoice.getRef(); mainEntry.setComment(invoiceDescription); mainEntry.setDoc(true); mainEntry.setDbkCode(dbkCode); mainEntry.setWbDbkType(wbDbkType); Date periodDate = wbInvoice.getPeriodDate(); if (periodDate == null) { periodDate = invoiceDate; } int bookYear; if (periodDate == null) { periodDate = invoiceDate; } if (periodDate == null) { String message = MessageFormat.format("Pas de période pour facture {0}", invoiceRef); throw new WinbooksException(WinbooksError.NO_PERIOD, message); } String periodInternalCode = getPeriodInternalCode(periodDate); WbBookYear wbBookYear = getBookYear(periodDate); if (wbBookYear == null) { - String message = MessageFormat.format("Pas d'exercice pour cette année: {0,date,short}, facture {1}", periodDate, invoiceRef); + String message = MessageFormat.format("Pas d''exercice pour cette année: {0,date,short}, facture {1}", periodDate, invoiceRef); throw new WinbooksException(WinbooksError.NO_BOOKYEAR, message); } bookYear = wbBookYear.getIndex(); mainEntry.setBookYear(Integer.toString(bookYear)); mainEntry.setPeriod(periodInternalCode); mainEntry.setDocNumber(invoiceRef); mainEntry.setDocOrder(1); String commStruct = wbInvoice.getCommStruct(); if (commStruct != null && !commStruct.isEmpty()) { mainEntry.setCommentExt(commStruct); } wbEntries.add(mainEntry); BigDecimal eVatTot = BigDecimal.ZERO; BigDecimal vatTot = BigDecimal.ZERO; int docOrder = 2; for (WbInvoiceLine wbInvoiceLine : effectiveInvoiceLines) { String operationAccountGl = wbInvoiceLine.getAccountGl(); BigDecimal eVat = wbInvoiceLine.getEVat(); BigDecimal vatRate = wbInvoiceLine.getVatRate(); BigDecimal vat = wbInvoiceLine.getVat(); BigDecimal newEvatTot = eVatTot.add(eVat); System.out.println(eVatTot + " + " + eVat + " = " + newEvatTot); eVatTot = newEvatTot; vatTot = vatTot.add(vat); WbEntry clientWbEntry = mainEntry.clone(); if (operationAccountGl != null && !operationAccountGl.isEmpty()) { clientWbEntry.setAccountGl(operationAccountGl); } clientWbEntry.setDoc(false); clientWbEntry.setWbDocType(WbDocType.IMPUT_GENERAL); BigDecimal minEVat = eVat.negate(); clientWbEntry.setAmountEur(minEVat); clientWbEntry.setVatBase(BigDecimal.ZERO); clientWbEntry.setVatTax(BigDecimal.ZERO); WbVatCode wbVatCode = getInternalVatCode(vatRate, wbClientSupplierType, WbLanguage.FRENCH); String internalVatCode = wbVatCode.getInternalVatCode(); clientWbEntry.setVatImput(internalVatCode); clientWbEntry.setDocOrder(docOrder); String lineDescription = wbInvoiceLine.getDescription(); if (lineDescription == null || lineDescription.isEmpty()) { lineDescription = invoiceDescription + "+"; } clientWbEntry.setComment(lineDescription); wbEntries.add(clientWbEntry); docOrder++; } for (WbInvoiceLine wbInvoiceLine : regroupedInvoiceLines) { BigDecimal eVat = wbInvoiceLine.getEVat(); BigDecimal vat = wbInvoiceLine.getVat(); BigDecimal minVat = vat.negate(); BigDecimal vatRate = wbInvoiceLine.getVatRate(); WbVatCode wbVatCode = getInternalVatCode(vatRate, wbClientSupplierType, WbLanguage.FRENCH); String internalVatCode = wbVatCode.getInternalVatCode(); String vatAccount = wbVatCode.getAccount1(); String description = wbInvoice.getDescription(); WbEntry vatWbEntry = mainEntry.clone(); vatWbEntry.setDoc(false); vatWbEntry.setWbDocType(WbDocType.IMPUT_GENERAL); vatWbEntry.setWbDocOrderType(WbDocOrderType.VAT); vatWbEntry.setVatBase(eVat); vatWbEntry.setAmountEur(minVat); vatWbEntry.setVatTax(BigDecimal.ZERO); vatWbEntry.setVatCode(internalVatCode); vatWbEntry.setComment(MessageFormat.format("{0} (tva)", description)); vatWbEntry.setAccountGl(vatAccount); vatWbEntry.setWbDocType(WbDocType.IMPUT_GENERAL); wbEntries.add(vatWbEntry); } // adjust main BigDecimal tot = eVatTot.add(vatTot); mainEntry.setAmountEur(tot); mainEntry.setVatBase(eVatTot); mainEntry.setVatTax(vatTot); return wbEntries; } private String getPeriodInternalCode(Date periodDate) { String periodInternalCode; _Param param = winbooksCom.param(); Date effectiveDate; if (this.bookYearOverride != null) { Calendar calendar = Calendar.getInstance(); calendar.setTime(periodDate); calendar.set(Calendar.YEAR, bookYearOverride); effectiveDate = calendar.getTime(); } else { effectiveDate = periodDate; } periodInternalCode = param.periodInternalCode(effectiveDate); return periodInternalCode; } public List<WbEntry> convertInvoicesToEntries(List<WbInvoice> wbInvoices, boolean singleLine) { List<WbEntry> allWbEntries = new ArrayList<>(); for (WbInvoice wbInvoice : wbInvoices) { List<WbEntry> wbEntries = convertInvoiceToEntries(wbInvoice, singleLine); allWbEntries.addAll(wbEntries); } return allWbEntries; } public WbBookYear getBookYear(Date periodDate) { Calendar calendar = GregorianCalendar.getInstance(); calendar.setTime(periodDate); int year; if (bookYearOverride == null) { year = calendar.get(Calendar.YEAR); } else { year = bookYearOverride; } String yearStr = Integer.toString(year); List<WbBookYear> bookYears = getBookYears(); for (WbBookYear wbBookYear : bookYears) { String shortName = wbBookYear.getShortName(); if (shortName.contains(yearStr)) { return wbBookYear; } } return null; } private List<WbInvoiceLine> regroupInvoiceLines(List<WbInvoiceLine> wbInvoiceLines) { Map<BigDecimal, WbInvoiceLine> vatRateInvoiceLineMap = new LinkedHashMap<>(); for (WbInvoiceLine wbInvoiceLine : wbInvoiceLines) { BigDecimal vatRate = wbInvoiceLine.getVatRate(); WbInvoiceLine groupWbInvoiceLine = vatRateInvoiceLineMap.get(vatRate); if (groupWbInvoiceLine == null) { String accountGl = wbInvoiceLine.getAccountGl(); String description = MessageFormat.format("Total TVA {0} %", vatRate); groupWbInvoiceLine = new WbInvoiceLine(); groupWbInvoiceLine.setAccountGl(accountGl); groupWbInvoiceLine.setDescription(description); groupWbInvoiceLine.setEVat(BigDecimal.ZERO); groupWbInvoiceLine.setVatRate(vatRate); groupWbInvoiceLine.setVat(BigDecimal.ZERO); vatRateInvoiceLineMap.put(vatRate, groupWbInvoiceLine); } BigDecimal groupEVat = groupWbInvoiceLine.getEVat(); BigDecimal eVat = wbInvoiceLine.getEVat(); BigDecimal newGroupEvat = groupEVat.add(eVat); BigDecimal groupVat = groupWbInvoiceLine.getVat(); BigDecimal vat = wbInvoiceLine.getVat(); BigDecimal newVat = groupVat.add(vat); groupWbInvoiceLine.setEVat(newGroupEvat); groupWbInvoiceLine.setVat(newVat); } Collection<WbInvoiceLine> wbInvoiceLineCollection = vatRateInvoiceLineMap.values(); List<WbInvoiceLine> regroupedInvoiceLines = new ArrayList<>(wbInvoiceLineCollection); return regroupedInvoiceLines; } private _Import testImportInternal(WbImport wbImport) { _Import internalImport = winbooksCom._import(); boolean fileFormatResult = internalImport.fileFormat("TXT"); checkBooleanResult(fileFormatResult); Path tempPath = generateDataFilesInTempDirectory(wbImport); String tempPathStr = tempPath.toString(); System.out.println(tempPath); boolean directoryResult = internalImport.directory(tempPathStr); checkBooleanResult(directoryResult); boolean testResult = internalImport.test(); checkBooleanResult(testResult); return internalImport; } private WbImportResult createImportResult(_Import internalImport) { List<WbWarning> wbWarnings = getWarnings(internalImport); List<WbFatalError> wbFatalErrors = getFatalErrors(internalImport); // return results WbImportResult wbImportResult = new WbImportResult(); wbImportResult.setWbFatalErrors(wbFatalErrors); wbImportResult.setWbWarnings(wbWarnings); return wbImportResult; } // TODO: i18n private WbWarningResolution convertTypeSolution(TypeSolution typeSolution) { String description; switch (typeSolution) { case wbToResolve: description = "Résoudre"; break; case wbAccept: description = "Accepter"; break; case wbReplace: description = "Remplacer"; break; case wbBlankRecord: description = "Mise à blanc"; break; case wbIgnore: description = "Ignorer"; break; case WbDontCopy: description = "Ne pas copier"; break; case wbEraseAll: description = "Tout effacer"; break; case wbInformation: description = "Information"; break; default: throw new AssertionError(typeSolution.name()); } WbWarningResolution wbWarningResolution = new WbWarningResolution(); wbWarningResolution.setTypeSolution(typeSolution); wbWarningResolution.setDescription(description); return wbWarningResolution; } public Integer getBookYearOverride() { return bookYearOverride; } public void setBookYearOverride(Integer bookYearOverride) { this.bookYearOverride = bookYearOverride; } public String getBookYearNameOverride() { return bookYearNameOverride; } public void setBookYearNameOverride(String bookYearNameOverride) { this.bookYearNameOverride = bookYearNameOverride; } public String getDossierOverride() { return dossierOverride; } public void setDossierOverride(String dossierOverride) { this.dossierOverride = dossierOverride; } }
false
false
null
null
diff --git a/src/kelsos/mbremote/Models/MainDataModel.java b/src/kelsos/mbremote/Models/MainDataModel.java index ca060d8a..8aa00981 100644 --- a/src/kelsos/mbremote/Models/MainDataModel.java +++ b/src/kelsos/mbremote/Models/MainDataModel.java @@ -1,253 +1,245 @@ package kelsos.mbremote.Models; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.util.Base64; import kelsos.mbremote.Events.ProtocolDataType; import kelsos.mbremote.Events.ModelDataEvent; import kelsos.mbremote.Events.ModelDataEventListener; import kelsos.mbremote.Events.ModelDataEventSource; import kelsos.mbremote.Others.Const; public class MainDataModel { private static MainDataModel _instance; private ModelDataEventSource _source; private MainDataModel(){ _source = new ModelDataEventSource(); _title=""; _artist=""; _album=""; _year = ""; _volume = 100; _isConnectionActive=false; _isRepeatButtonActive=false; _isShuffleButtonActive=false; _isScrobbleButtonActive=false; _isMuteButtonActive=false; _isDeviceOnline=false; _playState = PlayState.Stopped; } public void addEventListener(ModelDataEventListener listener) { _source.addEventListener(listener); } public void removeEventListener(ModelDataEventListener listener) { _source.removeEventListener(listener); } public static synchronized MainDataModel getInstance() { if(_instance==null) _instance = new MainDataModel(); return _instance; } private String _title; private String _artist; private String _album; private String _year; private int _volume; private Bitmap _albumCover; private boolean _isConnectionActive; private boolean _isRepeatButtonActive; private boolean _isShuffleButtonActive; private boolean _isScrobbleButtonActive; private boolean _isMuteButtonActive; private boolean _isDeviceOnline; private PlayState _playState; public void setTitle(String title) { if(title.equals(_title)) return; _title=title; _source.dispatchEvent(new ModelDataEvent(this, ProtocolDataType.Title)); } public String getTitle() { return _title; } public void setAlbum(String album) { if(album.equals(_album)) return; _album = album; _source.dispatchEvent(new ModelDataEvent(this, ProtocolDataType.Album)); } public String getAlbum() { return _album; } public void setArtist(String artist) { if(artist.equals(_artist)) return; _artist = artist; _source.dispatchEvent(new ModelDataEvent(this, ProtocolDataType.Artist)); } public String getArtist() { return _artist; } public void setYear(String year) { if(year.equals(_year)) return; _year=year; _source.dispatchEvent(new ModelDataEvent(this, ProtocolDataType.Year)); } public String getYear() { return _year; } public void setVolume(String volume) { int newVolume = Integer.parseInt(volume); - if(newVolume==_volume) return; _volume = newVolume; _source.dispatchEvent(new ModelDataEvent(this, ProtocolDataType.Volume)); } public int getVolume() { return _volume; } public void setAlbumCover(String base64format) { new ImageDecodeTask().execute(base64format); } private void setAlbumCover(Bitmap cover) { _albumCover = cover; _source.dispatchEvent(new ModelDataEvent(this, ProtocolDataType.AlbumCover)); } public Bitmap getAlbumCover() { return _albumCover; } public void setConnectionState(String connectionActive) { boolean newStatus = Boolean.parseBoolean(connectionActive); - if(newStatus==_isConnectionActive) return; _isConnectionActive=newStatus; _source.dispatchEvent(new ModelDataEvent(this, ProtocolDataType.ConnectionState)); } public boolean getIsConnectionActive() { return _isConnectionActive; } public void setRepeatState(String repeatButtonActive) { boolean newStatus = (repeatButtonActive.equals("All")); - if(newStatus== _isRepeatButtonActive) return; _isRepeatButtonActive = newStatus; _source.dispatchEvent(new ModelDataEvent(this, ProtocolDataType.RepeatState)); } public boolean getIsRepeatButtonActive() { return _isRepeatButtonActive; } public void setShuffleState(String shuffleButtonActive) { boolean newStatus = Boolean.parseBoolean(shuffleButtonActive); - if(newStatus == _isShuffleButtonActive) return; _isShuffleButtonActive = newStatus; _source.dispatchEvent(new ModelDataEvent(this, ProtocolDataType.ShuffleState)); } public boolean getIsShuffleButtonActive() { return _isShuffleButtonActive; } public void setScrobbleState(String scrobbleButtonActive) { boolean newStatus = Boolean.parseBoolean(scrobbleButtonActive); - if(newStatus == _isScrobbleButtonActive) return; _isScrobbleButtonActive = newStatus; _source.dispatchEvent(new ModelDataEvent(this, ProtocolDataType.ScrobbleState)); } public boolean getIsScrobbleButtonActive() { return _isScrobbleButtonActive; } public void setMuteState(String muteButtonActive) { boolean newStatus = Boolean.parseBoolean(muteButtonActive); - if(newStatus == _isMuteButtonActive) return; _isMuteButtonActive = newStatus; _source.dispatchEvent(new ModelDataEvent(this, ProtocolDataType.MuteState)); } public boolean getIsMuteButtonActive() { return _isMuteButtonActive; } public void setPlayState(String playState) { PlayState newState = PlayState.Undefined; if(playState.equalsIgnoreCase(Const.PLAYING)) newState = PlayState.Playing; else if (playState.equalsIgnoreCase(Const.STOPPED)) newState = PlayState.Stopped; else if (playState.equalsIgnoreCase(Const.PAUSED)) newState = PlayState.Paused; - if(_playState==newState) return; _playState = newState; _source.dispatchEvent(new ModelDataEvent(this, ProtocolDataType.PlayState)); } public PlayState getPlayState() { return _playState; } public void setIsDeviceOnline(boolean value) { - if(value==_isDeviceOnline) return; _isDeviceOnline = value; _source.dispatchEvent(new ModelDataEvent(this, ProtocolDataType.OnlineStatus)); } public boolean getIsDeviceOnline() { return _isDeviceOnline; } private class ImageDecodeTask extends AsyncTask<String, Void, Bitmap> { @Override protected Bitmap doInBackground(String... params) { byte[] decodedImage = Base64.decode(params[0] , Base64.DEFAULT); return BitmapFactory.decodeByteArray(decodedImage, 0, decodedImage.length); } @Override protected void onPostExecute(Bitmap result) { setAlbumCover(result); } } }
false
false
null
null
diff --git a/src/de/schildbach/pte/AbstractEfaProvider.java b/src/de/schildbach/pte/AbstractEfaProvider.java index 16e1ddb..3027be1 100644 --- a/src/de/schildbach/pte/AbstractEfaProvider.java +++ b/src/de/schildbach/pte/AbstractEfaProvider.java @@ -1,2257 +1,2253 @@ /* * Copyright 2010, 2011 the original author or authors. * * 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 de.schildbach.pte; import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Currency; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import de.schildbach.pte.dto.Connection; import de.schildbach.pte.dto.Departure; import de.schildbach.pte.dto.Fare; import de.schildbach.pte.dto.Fare.Type; import de.schildbach.pte.dto.GetConnectionDetailsResult; import de.schildbach.pte.dto.Line; import de.schildbach.pte.dto.LineDestination; import de.schildbach.pte.dto.Location; import de.schildbach.pte.dto.LocationType; import de.schildbach.pte.dto.NearbyStationsResult; import de.schildbach.pte.dto.Point; import de.schildbach.pte.dto.QueryConnectionsResult; import de.schildbach.pte.dto.QueryDeparturesResult; import de.schildbach.pte.dto.ResultHeader; import de.schildbach.pte.dto.StationDepartures; import de.schildbach.pte.dto.Stop; import de.schildbach.pte.exception.ParserException; import de.schildbach.pte.exception.ProtocolException; import de.schildbach.pte.exception.SessionExpiredException; import de.schildbach.pte.util.ParserUtils; import de.schildbach.pte.util.XmlPullUtil; /** * @author Andreas Schildbach */ public abstract class AbstractEfaProvider extends AbstractNetworkProvider { protected final static String SERVER_PRODUCT = "efa"; private final String apiBase; private final String departureMonitorEndpoint; private final String tripEndpoint; private final String additionalQueryParameter; private final boolean canAcceptPoiID; private final boolean needsSpEncId; private final XmlPullParserFactory parserFactory; public AbstractEfaProvider() { this(null, null); } public AbstractEfaProvider(final String apiBase, final String additionalQueryParameter) { this(apiBase, additionalQueryParameter, false); } public AbstractEfaProvider(final String apiBase, final String additionalQueryParameter, final boolean canAcceptPoiID) { this(apiBase, null, null, additionalQueryParameter, false, false); } public AbstractEfaProvider(final String apiBase, final String departureMonitorEndpoint, final String tripEndpoint, final String additionalQueryParameter, final boolean canAcceptPoiID, final boolean needsSpEncId) { try { parserFactory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); } catch (final XmlPullParserException x) { throw new RuntimeException(x); } this.apiBase = apiBase; this.departureMonitorEndpoint = departureMonitorEndpoint != null ? departureMonitorEndpoint : "XSLT_DM_REQUEST"; this.tripEndpoint = tripEndpoint != null ? tripEndpoint : "XSLT_TRIP_REQUEST2"; this.additionalQueryParameter = additionalQueryParameter; this.canAcceptPoiID = canAcceptPoiID; this.needsSpEncId = needsSpEncId; } protected TimeZone timeZone() { return TimeZone.getTimeZone("Europe/Berlin"); } private final void appendCommonRequestParams(final StringBuilder uri, final String outputFormat) { uri.append("?outputFormat=").append(outputFormat); uri.append("&coordOutputFormat=WGS84"); if (additionalQueryParameter != null) uri.append('&').append(additionalQueryParameter); } protected List<Location> jsonStopfinderRequest(final Location constraint) throws IOException { final StringBuilder uri = new StringBuilder(apiBase); uri.append("XML_STOPFINDER_REQUEST"); appendCommonRequestParams(uri, "JSON"); uri.append("&locationServerActive=1"); uri.append("&regionID_sf=1"); // prefer own region appendLocation(uri, constraint, "sf"); if (constraint.type == LocationType.ANY) // 1=place 2=stop 4=street 8=address 16=crossing 32=poi 64=postcode uri.append("&anyObjFilter_sf=").append(2 + 4 + 8 + 16 + 32 + 64); // System.out.println(uri.toString()); final CharSequence page = ParserUtils.scrape(uri.toString(), false, null, "UTF-8", null); try { final JSONObject head = new JSONObject(page.toString()); final JSONArray stops = head.getJSONArray("stopFinder"); final int nStops = stops.length(); final List<Location> results = new ArrayList<Location>(); for (int i = 0; i < nStops; i++) { final JSONObject stop = stops.optJSONObject(i); String type = stop.getString("type"); if ("any".equals(type)) type = stop.getString("anyType"); final String name = stop.getString("object"); final JSONObject ref = stop.getJSONObject("ref"); String place = ref.getString("place"); if (place != null && place.length() == 0) place = null; final String coords = ref.optString("coords", null); final int lat; final int lon; if (coords != null) { final String[] coordParts = coords.split(","); lat = Math.round(Float.parseFloat(coordParts[1])); lon = Math.round(Float.parseFloat(coordParts[0])); } else { lat = 0; lon = 0; } if ("stop".equals(type)) results.add(new Location(LocationType.STATION, stop.getInt("stateless"), lat, lon, place, name)); else if ("poi".equals(type)) results.add(new Location(LocationType.POI, 0, lat, lon, place, name)); - else if ("street".equals(type)) - results.add(new Location(LocationType.ADDRESS, 0, lat, lon, place, name)); + else if ("street".equals(type) || "address".equals(type) || "singlehouse".equals(type)) + results.add(new Location(LocationType.ADDRESS, 0, lat, lon, place, stop.getString("name"))); else throw new IllegalArgumentException("unknown type: " + type); } return results; } catch (final JSONException x) { x.printStackTrace(); throw new RuntimeException("cannot parse: '" + page + "' on " + uri, x); } } protected List<Location> xmlStopfinderRequest(final Location constraint) throws IOException { final StringBuilder uri = new StringBuilder(apiBase); uri.append("XML_STOPFINDER_REQUEST"); appendCommonRequestParams(uri, "XML"); uri.append("&locationServerActive=1"); appendLocation(uri, constraint, "sf"); if (constraint.type == LocationType.ANY) { if (needsSpEncId) uri.append("&SpEncId=0"); // 1=place 2=stop 4=street 8=address 16=crossing 32=poi 64=postcode uri.append("&anyObjFilter_sf=").append(2 + 4 + 8 + 16 + 32 + 64); uri.append("&reducedAnyPostcodeObjFilter_sf=64&reducedAnyTooManyObjFilter_sf=2"); uri.append("&useHouseNumberList=true&regionID_sf=1"); } // System.out.println(uri.toString()); InputStream is = null; try { is = ParserUtils.scrapeInputStream(uri.toString()); final XmlPullParser pp = parserFactory.newPullParser(); pp.setInput(is, null); enterItdRequest(pp); final List<Location> results = new ArrayList<Location>(); XmlPullUtil.enter(pp, "itdStopFinderRequest"); XmlPullUtil.require(pp, "itdOdv"); if (!"sf".equals(pp.getAttributeValue(null, "usage"))) throw new IllegalStateException("cannot find <itdOdv usage=\"sf\" />"); XmlPullUtil.enter(pp, "itdOdv"); XmlPullUtil.require(pp, "itdOdvPlace"); XmlPullUtil.next(pp); XmlPullUtil.require(pp, "itdOdvName"); final String nameState = pp.getAttributeValue(null, "state"); XmlPullUtil.enter(pp, "itdOdvName"); if (XmlPullUtil.test(pp, "itdMessage")) XmlPullUtil.next(pp); if ("identified".equals(nameState) || "list".equals(nameState)) { while (XmlPullUtil.test(pp, "odvNameElem")) results.add(processOdvNameElem(pp, null)); } else if ("notidentified".equals(nameState)) { // do nothing } else { throw new RuntimeException("unknown nameState '" + nameState + "' on " + uri); } XmlPullUtil.exit(pp, "itdOdvName"); XmlPullUtil.exit(pp, "itdOdv"); XmlPullUtil.exit(pp, "itdStopFinderRequest"); return results; } catch (final XmlPullParserException x) { throw new ParserException(x); } finally { if (is != null) is.close(); } } protected NearbyStationsResult xmlCoordRequest(final int lat, final int lon, final int maxDistance, final int maxStations) throws IOException { final StringBuilder uri = new StringBuilder(apiBase); uri.append("XML_COORD_REQUEST"); appendCommonRequestParams(uri, "XML"); uri.append("&coord=").append(String.format(Locale.ENGLISH, "%2.6f:%2.6f:WGS84", latLonToDouble(lon), latLonToDouble(lat))); uri.append("&coordListOutputFormat=STRING"); uri.append("&max=").append(maxStations != 0 ? maxStations : 50); uri.append("&inclFilter=1&radius_1=").append(maxDistance != 0 ? maxDistance : 1320); uri.append("&type_1=STOP"); // ENTRANCE, BUS_POINT, POI_POINT InputStream is = null; try { is = ParserUtils.scrapeInputStream(uri.toString()); final XmlPullParser pp = parserFactory.newPullParser(); pp.setInput(is, null); final ResultHeader header = enterItdRequest(pp); XmlPullUtil.enter(pp, "itdCoordInfoRequest"); XmlPullUtil.enter(pp, "itdCoordInfo"); XmlPullUtil.enter(pp, "coordInfoRequest"); XmlPullUtil.exit(pp, "coordInfoRequest"); final List<Location> stations = new ArrayList<Location>(); if (XmlPullUtil.test(pp, "coordInfoItemList")) { XmlPullUtil.enter(pp, "coordInfoItemList"); while (XmlPullUtil.test(pp, "coordInfoItem")) { if (!"STOP".equals(pp.getAttributeValue(null, "type"))) throw new RuntimeException("unknown type"); final int id = XmlPullUtil.intAttr(pp, "id"); final String name = normalizeLocationName(XmlPullUtil.attr(pp, "name")); final String place = normalizeLocationName(XmlPullUtil.attr(pp, "locality")); XmlPullUtil.enter(pp, "coordInfoItem"); // FIXME this is always only one coordinate final Point coord = processItdPathCoordinates(pp).get(0); XmlPullUtil.exit(pp, "coordInfoItem"); stations.add(new Location(LocationType.STATION, id, coord.lat, coord.lon, place, name)); } XmlPullUtil.exit(pp, "coordInfoItemList"); } return new NearbyStationsResult(header, stations); } catch (final XmlPullParserException x) { throw new ParserException(x); } finally { if (is != null) is.close(); } } public abstract List<Location> autocompleteStations(final CharSequence constraint) throws IOException; private String processItdOdvPlace(final XmlPullParser pp) throws XmlPullParserException, IOException { if (!XmlPullUtil.test(pp, "itdOdvPlace")) throw new IllegalStateException("expecting <itdOdvPlace />"); final String placeState = XmlPullUtil.attr(pp, "state"); XmlPullUtil.enter(pp, "itdOdvPlace"); String place = null; if ("identified".equals(placeState)) { if (XmlPullUtil.test(pp, "odvPlaceElem")) { XmlPullUtil.enter(pp, "odvPlaceElem"); place = normalizeLocationName(pp.getText()); XmlPullUtil.exit(pp, "odvPlaceElem"); } } XmlPullUtil.exit(pp, "itdOdvPlace"); return place; } private Location processOdvNameElem(final XmlPullParser pp, final String defaultPlace) throws XmlPullParserException, IOException { if (!XmlPullUtil.test(pp, "odvNameElem")) throw new IllegalStateException("expecting <odvNameElem />"); final String anyType = pp.getAttributeValue(null, "anyType"); final String idStr = pp.getAttributeValue(null, "id"); final String stopIdStr = pp.getAttributeValue(null, "stopID"); final String poiIdStr = pp.getAttributeValue(null, "poiID"); final String streetIdStr = pp.getAttributeValue(null, "streetID"); final String place = !"loc".equals(anyType) ? normalizeLocationName(pp.getAttributeValue(null, "locality")) : null; final String name = normalizeLocationName(pp.getAttributeValue(null, "objectName")); int lat = 0, lon = 0; if ("WGS84".equals(pp.getAttributeValue(null, "mapName"))) { lat = Math.round(XmlPullUtil.floatAttr(pp, "y")); lon = Math.round(XmlPullUtil.floatAttr(pp, "x")); } LocationType type; int id; if ("stop".equals(anyType)) { type = LocationType.STATION; id = Integer.parseInt(idStr); } else if ("poi".equals(anyType) || "poiHierarchy".equals(anyType)) { type = LocationType.POI; id = Integer.parseInt(idStr); } else if ("loc".equals(anyType)) { type = LocationType.ANY; id = 0; } else if ("postcode".equals(anyType) || "street".equals(anyType) || "crossing".equals(anyType) || "address".equals(anyType) || "singlehouse".equals(anyType) || "buildingname".equals(anyType)) { type = LocationType.ADDRESS; id = 0; } else if (stopIdStr != null) { type = LocationType.STATION; id = Integer.parseInt(stopIdStr); } else if (poiIdStr != null) { type = LocationType.POI; id = Integer.parseInt(poiIdStr); } else if (stopIdStr == null && idStr == null && (lat != 0 || lon != 0)) { type = LocationType.ADDRESS; id = 0; } else if (streetIdStr != null) { type = LocationType.ADDRESS; id = Integer.parseInt(streetIdStr); } else { throw new IllegalArgumentException("unknown type: " + anyType + " " + idStr + " " + stopIdStr); } XmlPullUtil.enter(pp, "odvNameElem"); final String longName = normalizeLocationName(pp.getText()); XmlPullUtil.exit(pp, "odvNameElem"); return new Location(type, id, lat, lon, place != null ? place : defaultPlace, name != null ? name : longName); } private Location processItdOdvAssignedStop(final XmlPullParser pp) throws XmlPullParserException, IOException { final int id = Integer.parseInt(pp.getAttributeValue(null, "stopID")); int lat = 0, lon = 0; if ("WGS84".equals(pp.getAttributeValue(null, "mapName"))) { lat = Math.round(XmlPullUtil.floatAttr(pp, "y")); lon = Math.round(XmlPullUtil.floatAttr(pp, "x")); } final String place = normalizeLocationName(XmlPullUtil.attr(pp, "place")); XmlPullUtil.enter(pp, "itdOdvAssignedStop"); final String name = normalizeLocationName(pp.getText()); XmlPullUtil.exit(pp, "itdOdvAssignedStop"); return new Location(LocationType.STATION, id, lat, lon, place, name); } protected abstract String nearbyStationUri(int stationId); public NearbyStationsResult queryNearbyStations(final Location location, final int maxDistance, final int maxStations) throws IOException { if (location.hasLocation()) return xmlCoordRequest(location.lat, location.lon, maxDistance, maxStations); if (location.type != LocationType.STATION) throw new IllegalArgumentException("cannot handle: " + location.type); if (!location.hasId()) throw new IllegalArgumentException("at least one of stationId or lat/lon must be given"); final String uri = nearbyStationUri(location.id); InputStream is = null; try { is = ParserUtils.scrapeInputStream(uri); final XmlPullParser pp = parserFactory.newPullParser(); pp.setInput(is, null); final ResultHeader header = enterItdRequest(pp); if (!XmlPullUtil.jumpToStartTag(pp, null, "itdOdv") || !"dm".equals(pp.getAttributeValue(null, "usage"))) throw new IllegalStateException("cannot find <itdOdv usage=\"dm\" />"); XmlPullUtil.enter(pp, "itdOdv"); final String place = processItdOdvPlace(pp); XmlPullUtil.require(pp, "itdOdvName"); final String nameState = pp.getAttributeValue(null, "state"); XmlPullUtil.enter(pp, "itdOdvName"); if ("identified".equals(nameState)) { final Location ownLocation = processOdvNameElem(pp, place); final Location ownStation = ownLocation.type == LocationType.STATION ? ownLocation : null; final List<Location> stations = new ArrayList<Location>(); if (XmlPullUtil.jumpToStartTag(pp, null, "itdOdvAssignedStops")) { XmlPullUtil.enter(pp, "itdOdvAssignedStops"); while (XmlPullUtil.test(pp, "itdOdvAssignedStop")) { final String parsedMapName = pp.getAttributeValue(null, "mapName"); if (parsedMapName != null) { final int parsedLocationId = XmlPullUtil.intAttr(pp, "stopID"); // final String parsedLongName = normalizeLocationName(XmlPullUtil.attr(pp, // "nameWithPlace")); final String parsedPlace = normalizeLocationName(XmlPullUtil.attr(pp, "place")); final int parsedLon = Math.round(XmlPullUtil.floatAttr(pp, "x")); final int parsedLat = Math.round(XmlPullUtil.floatAttr(pp, "y")); XmlPullUtil.enter(pp, "itdOdvAssignedStop"); final String parsedName = normalizeLocationName(pp.getText()); XmlPullUtil.exit(pp, "itdOdvAssignedStop"); if (!"WGS84".equals(parsedMapName)) throw new IllegalStateException("unknown mapName: " + parsedMapName); final Location newStation = new Location(LocationType.STATION, parsedLocationId, parsedLat, parsedLon, parsedPlace, parsedName); if (!stations.contains(newStation)) stations.add(newStation); } else { if (!pp.isEmptyElementTag()) { XmlPullUtil.enter(pp, "itdOdvAssignedStop"); XmlPullUtil.exit(pp, "itdOdvAssignedStop"); } else { XmlPullUtil.next(pp); } } } } if (ownStation != null && !stations.contains(ownStation)) stations.add(ownStation); if (maxStations == 0 || maxStations >= stations.size()) return new NearbyStationsResult(header, stations); else return new NearbyStationsResult(header, stations.subList(0, maxStations)); } else if ("list".equals(nameState)) { final List<Location> stations = new ArrayList<Location>(); if (XmlPullUtil.test(pp, "itdMessage")) XmlPullUtil.next(pp); while (XmlPullUtil.test(pp, "odvNameElem")) { final Location newLocation = processOdvNameElem(pp, place); if (newLocation.type == LocationType.STATION && !stations.contains(newLocation)) stations.add(newLocation); } return new NearbyStationsResult(header, stations); } else if ("notidentified".equals(nameState)) { return new NearbyStationsResult(header, NearbyStationsResult.Status.INVALID_STATION); } else { throw new RuntimeException("unknown nameState '" + nameState + "' on " + uri); } // XmlPullUtil.exit(pp, "itdOdvName"); } catch (final XmlPullParserException x) { throw new ParserException(x); } finally { if (is != null) is.close(); } } private static final Pattern P_LINE_IRE = Pattern.compile("IRE\\d+"); private static final Pattern P_LINE_RE = Pattern.compile("RE\\d+"); private static final Pattern P_LINE_RB = Pattern.compile("RB\\d+"); private static final Pattern P_LINE_VB = Pattern.compile("VB\\d+"); private static final Pattern P_LINE_OE = Pattern.compile("OE\\d+"); private static final Pattern P_LINE_R = Pattern.compile("R\\d+(/R\\d+|\\(z\\))?"); private static final Pattern P_LINE_U = Pattern.compile("U\\d+"); private static final Pattern P_LINE_S = Pattern.compile("^(?:%)?(S\\d+)"); private static final Pattern P_LINE_NUMBER = Pattern.compile("\\d+"); private static final Pattern P_LINE_Y = Pattern.compile("\\d+Y"); protected String parseLine(final String mot, final String name, final String longName, final String noTrainName) { if (mot == null) { if (noTrainName != null) { final String str = name != null ? name : ""; if (noTrainName.equals("S-Bahn")) return 'S' + str; if (noTrainName.equals("U-Bahn")) return 'U' + str; if (noTrainName.equals("Straßenbahn")) return 'T' + str; if (noTrainName.equals("Badner Bahn")) return 'T' + str; if (noTrainName.equals("Stadtbus")) return 'B' + str; if (noTrainName.equals("Citybus")) return 'B' + str; if (noTrainName.equals("Regionalbus")) return 'B' + str; if (noTrainName.equals("ÖBB-Postbus")) return 'B' + str; if (noTrainName.equals("Autobus")) return 'B' + str; if (noTrainName.equals("Discobus")) return 'B' + str; if (noTrainName.equals("Nachtbus")) return 'B' + str; if (noTrainName.equals("Anrufsammeltaxi")) return 'B' + str; if (noTrainName.equals("Ersatzverkehr")) return 'B' + str; if (noTrainName.equals("Vienna Airport Lines")) return 'B' + str; } throw new IllegalStateException("cannot normalize mot '" + mot + "' name '" + name + "' long '" + longName + "' noTrainName '" + noTrainName + "'"); } final int t = Integer.parseInt(mot); if (t == 0) { final String[] parts = longName.split(" ", 3); final String type = parts[0]; final String num = parts.length >= 2 ? parts[1] : null; final String str = type + (num != null ? num : ""); if (type.equals("EC")) // Eurocity return 'I' + str; if (type.equals("EN")) // Euronight return 'I' + str; if (type.equals("IC")) // Intercity return 'I' + str; if (type.equals("ICE")) // Intercity Express return 'I' + str; if (type.equals("X")) // InterConnex return 'I' + str; if (type.equals("CNL")) // City Night Line return 'I' + str; if (type.equals("THA")) // Thalys return 'I' + str; if (type.equals("TGV")) // TGV return 'I' + str; if (type.equals("RJ")) // railjet return 'I' + str; if (type.equals("OEC")) // ÖBB-EuroCity return 'I' + str; if (type.equals("OIC")) // ÖBB-InterCity return 'I' + str; if (type.equals("HT")) // First Hull Trains, GB return 'I' + str; if (type.equals("MT")) // Müller Touren, Schnee Express return 'I' + str; if (type.equals("HKX")) // Hamburg-Koeln-Express return 'I' + str; if (type.equals("DNZ")) // Nachtzug Basel-Moskau return 'I' + str; if ("Eurocity".equals(noTrainName)) // Liechtenstein return 'I' + name; if ("INT".equals(type)) // SVV return 'I' + name; if ("IXB".equals(type)) // ICE International return 'I' + name; if (type.equals("IR")) // Interregio return 'R' + str; if (type.equals("IRE")) // Interregio-Express return 'R' + str; if (P_LINE_IRE.matcher(type).matches()) return 'R' + str; if (type.equals("RE")) // Regional-Express return 'R' + str; if (type.equals("R-Bahn")) // Regional-Express, VRR return 'R' + str; if (type.equals("REX")) // RegionalExpress, Österreich return 'R' + str; if ("EZ".equals(type)) // ÖBB ErlebnisBahn return 'R' + str; if (P_LINE_RE.matcher(type).matches()) return 'R' + str; if (type.equals("RB")) // Regionalbahn return 'R' + str; if (P_LINE_RB.matcher(type).matches()) return 'R' + str; if (type.equals("R")) // Regionalzug return 'R' + str; if (P_LINE_R.matcher(type).matches()) return 'R' + str; if (type.equals("Bahn")) return 'R' + str; if (type.equals("Regionalbahn")) return 'R' + str; if (type.equals("D")) // Schnellzug return 'R' + str; if (type.equals("E")) // Eilzug return 'R' + str; if (type.equals("S")) // ~Innsbruck return 'R' + str; if (type.equals("WFB")) // Westfalenbahn return 'R' + str; if ("Westfalenbahn".equals(type)) // Westfalenbahn return 'R' + name; if (type.equals("NWB")) // NordWestBahn return 'R' + str; if (type.equals("NordWestBahn")) return 'R' + str; if (type.equals("ME")) // Metronom return 'R' + str; if (type.equals("ERB")) // eurobahn return 'R' + str; if (type.equals("CAN")) // cantus return 'R' + str; if (type.equals("HEX")) // Veolia Verkehr Sachsen-Anhalt return 'R' + str; if (type.equals("EB")) // Erfurter Bahn return 'R' + str; if (type.equals("MRB")) // Mittelrheinbahn return 'R' + str; if (type.equals("ABR")) // ABELLIO Rail NRW return 'R' + str; if (type.equals("NEB")) // Niederbarnimer Eisenbahn return 'R' + str; if (type.equals("OE")) // Ostdeutsche Eisenbahn return 'R' + str; if (P_LINE_OE.matcher(type).matches()) return 'R' + str; if (type.equals("MR")) // Märkische Regiobahn return 'R' + str; if (type.equals("OLA")) // Ostseeland Verkehr return 'R' + str; if (type.equals("UBB")) // Usedomer Bäderbahn return 'R' + str; if (type.equals("EVB")) // Elbe-Weser return 'R' + str; if (type.equals("PEG")) // Prignitzer Eisenbahngesellschaft return 'R' + str; if (type.equals("RTB")) // Rurtalbahn return 'R' + str; if (type.equals("STB")) // Süd-Thüringen-Bahn return 'R' + str; if (type.equals("HTB")) // Hellertalbahn return 'R' + str; if (type.equals("VBG")) // Vogtlandbahn return 'R' + str; if (type.equals("VB")) // Vogtlandbahn return 'R' + str; if (P_LINE_VB.matcher(type).matches()) return 'R' + str; if (type.equals("VX")) // Vogtland Express return 'R' + str; if (type.equals("CB")) // City-Bahn Chemnitz return 'R' + str; if (type.equals("VEC")) // VECTUS Verkehrsgesellschaft return 'R' + str; if (type.equals("HzL")) // Hohenzollerische Landesbahn return 'R' + str; if (type.equals("OSB")) // Ortenau-S-Bahn return 'R' + str; if (type.equals("SBB")) // SBB return 'R' + str; if (type.equals("MBB")) // Mecklenburgische Bäderbahn Molli return 'R' + str; if (type.equals("OS")) // Regionalbahn return 'R' + str; if (type.equals("SP")) return 'R' + str; if (type.equals("Dab")) // Daadetalbahn return 'R' + str; if (type.equals("FEG")) // Freiberger Eisenbahngesellschaft return 'R' + str; if (type.equals("ARR")) // ARRIVA return 'R' + str; if (type.equals("HSB")) // Harzer Schmalspurbahn return 'R' + str; if (type.equals("SBE")) // Sächsisch-Böhmische Eisenbahngesellschaft return 'R' + str; if (type.equals("ALX")) // Arriva-Länderbahn-Express return 'R' + str; if (type.equals("EX")) // ALX verwandelt sich return 'R' + str; if (type.equals("MEr")) // metronom regional return 'R' + str; if (type.equals("AKN")) // AKN Eisenbahn return 'R' + str; if (type.equals("ZUG")) // Regionalbahn return 'R' + str; if (type.equals("SOE")) // Sächsisch-Oberlausitzer Eisenbahngesellschaft return 'R' + str; if (type.equals("VIA")) // VIAS return 'R' + str; if (type.equals("BRB")) // Bayerische Regiobahn return 'R' + str; if (type.equals("BLB")) // Berchtesgadener Land Bahn return 'R' + str; if (type.equals("HLB")) // Hessische Landesbahn return 'R' + str; if (type.equals("NOB")) // NordOstseeBahn return 'R' + str; if (type.equals("WEG")) // Wieslauftalbahn return 'R' + str; if (type.equals("NBE")) // Nordbahn Eisenbahngesellschaft return 'R' + str; if (type.equals("VEN")) // Rhenus Veniro return 'R' + str; if (type.equals("DPN")) // Nahreisezug return 'R' + str; if (type.equals("SHB")) // Schleswig-Holstein-Bahn return 'R' + str; if (type.equals("RBG")) // Regental Bahnbetriebs GmbH return 'R' + str; if (type.equals("BOB")) // Bayerische Oberlandbahn return 'R' + str; if (type.equals("SWE")) // Südwestdeutsche Verkehrs AG return 'R' + str; if (type.equals("VE")) // Vetter return 'R' + str; if (type.equals("SDG")) // Sächsische Dampfeisenbahngesellschaft return 'R' + str; if (type.equals("PRE")) // Pressnitztalbahn return 'R' + str; if (type.equals("VEB")) // Vulkan-Eifel-Bahn return 'R' + str; if (type.equals("neg")) // Norddeutsche Eisenbahn Gesellschaft return 'R' + str; if (type.equals("AVG")) // Felsenland-Express return 'R' + str; if (type.equals("ABG")) // Anhaltische Bahngesellschaft return 'R' + str; if (type.equals("LGB")) // Lößnitzgrundbahn return 'R' + str; if (type.equals("LEO")) // Chiemgauer Lokalbahn return 'R' + str; if (type.equals("WTB")) // Weißeritztalbahn return 'R' + str; if (type.equals("P")) // Kasbachtalbahn, Wanderbahn im Regental, Rhön-Zügle return 'R' + str; if (type.equals("ÖBA")) // Eisenbahn-Betriebsgesellschaft Ochsenhausen return 'R' + str; if (type.equals("MBS")) // Montafonerbahn return 'R' + str; if (type.equals("EGP")) // EGP - die Städtebahn GmbH return 'R' + str; if (type.equals("SBS")) // EGP - die Städtebahn GmbH return 'R' + str; if (type.equals("SES")) // EGP - die Städtebahn GmbH return 'R' + str; if (type.equals("SB")) // Städtebahn Sachsen return 'R' + str; if (type.equals("agi")) // agilis return 'R' + str; if (type.equals("ag")) // agilis return 'R' + str; if (type.equals("TLX")) // Trilex (Vogtlandbahn) return 'R' + str; if (type.equals("BE")) // Grensland-Express, Niederlande return 'R' + str; if (type.equals("MEL")) // Museums-Eisenbahn Losheim return 'R' + str; if (type.equals("Abellio-Zug")) // Abellio return 'R' + str; if ("erx".equals(type)) // erixx return 'R' + str; if ("SWEG-Zug".equals(type)) // Südwestdeutschen Verkehrs-Aktiengesellschaft, evtl. S-Bahn? return 'R' + str; if (type.equals("KBS")) // Kursbuchstrecke return 'R' + str; if (type.equals("Zug")) return 'R' + str; if (type.equals("ÖBB")) return 'R' + str; if (type.equals("CAT")) // City Airport Train Wien return 'R' + str; if (type.equals("DZ")) // Dampfzug, STV return 'R' + str; if (type.equals("CD")) return 'R' + str; if (type.equals("PR")) return 'R' + str; if (type.equals("KD")) // Koleje Dolnośląskie (Niederschlesische Eisenbahn) return 'R' + str; if (type.equals("VIAMO")) return 'R' + str; if (type.equals("SE")) // Southeastern, GB return 'R' + str; if (type.equals("SW")) // South West Trains, GB return 'R' + str; if (type.equals("SN")) // Southern, GB return 'R' + str; if (type.equals("NT")) // Northern Rail, GB return 'R' + str; if (type.equals("CH")) // Chiltern Railways, GB return 'R' + str; if (type.equals("EA")) // National Express East Anglia, GB return 'R' + str; if (type.equals("FC")) // First Capital Connect, GB return 'R' + str; if (type.equals("GW")) // First Great Western, GB return 'R' + str; if (type.equals("XC")) // Cross Country, GB, evtl. auch highspeed? return 'R' + str; if (type.equals("HC")) // Heathrow Connect, GB return 'R' + str; if (type.equals("HX")) // Heathrow Express, GB return 'R' + str; if (type.equals("GX")) // Gatwick Express, GB return 'R' + str; if (type.equals("C2C")) // c2c, GB return 'R' + str; if (type.equals("LM")) // London Midland, GB return 'R' + str; if (type.equals("EM")) // East Midlands Trains, GB return 'R' + str; if (type.equals("VT")) // Virgin Trains, GB, evtl. auch highspeed? return 'R' + str; if (type.equals("SR")) // ScotRail, GB, evtl. auch long-distance? return 'R' + str; if (type.equals("AW")) // Arriva Trains Wales, GB return 'R' + str; if (type.equals("WS")) // Wrexham & Shropshire, GB return 'R' + str; if (type.equals("TP")) // First TransPennine Express, GB, evtl. auch long-distance? return 'R' + str; if (type.equals("GC")) // Grand Central, GB return 'R' + str; if (type.equals("IL")) // Island Line, GB return 'R' + str; if ("FCC".equals(type)) // First Capital Connect, GB return 'R' + str; if (type.equals("BR")) // ??, GB return 'R' + str; if (type.equals("OO")) // ??, GB return 'R' + str; if (type.equals("XX")) // ??, GB return 'R' + str; if (type.equals("XZ")) // ??, GB return 'R' + str; if (type.equals("DB-Zug")) // VRR return 'R' + name; if (type.equals("Regionalexpress")) // VRR return 'R' + name; if ("CAPITOL".equals(name)) // San Francisco return 'R' + name; if ("Train".equals(noTrainName) || "Train".equals(type)) // San Francisco return "R" + name; if ("Regional Train :".equals(longName)) return "R"; if ("Regional Train".equals(noTrainName)) // Melbourne return "R" + name; if ("Regional".equals(type)) // Melbourne return "R" + name; if (type.equals("ATB")) // Autoschleuse Tauernbahn return 'R' + name; if ("Chiemsee-Bahn".equals(type)) return 'R' + name; if ("Regionalzug".equals(noTrainName)) // Liechtenstein return 'R' + name; if ("RegionalExpress".equals(noTrainName)) // Liechtenstein return 'R' + name; if ("Ostdeutsche".equals(type)) // Bayern return 'R' + type; if ("Südwestdeutsche".equals(type)) // Bayern return 'R' + type; if ("Mitteldeutsche".equals(type)) // Bayern return 'R' + type; if ("Norddeutsche".equals(type)) // Bayern return 'R' + type; if ("Hellertalbahn".equals(type)) // Bayern return 'R' + type; if ("Veolia".equals(type)) // Bayern return 'R' + type; if ("vectus".equals(type)) // Bayern return 'R' + type; if ("Hessische".equals(type)) // Bayern return 'R' + type; if ("Niederbarnimer".equals(type)) // Bayern return 'R' + type; if ("Rurtalbahn".equals(type)) // Bayern return 'R' + type; if ("Rhenus".equals(type)) // Bayern return 'R' + type; if ("Mittelrheinbahn".equals(type)) // Bayern return 'R' + type; if ("Hohenzollerische".equals(type)) // Bayern return 'R' + type; if ("Städtebahn".equals(type)) // Bayern return 'R' + type; if ("Ortenau-S-Bahn".equals(type)) // Bayern return 'R' + type; if ("Daadetalbahn".equals(type)) // Bayern return 'R' + type; if ("Mainschleifenbahn".equals(type)) // Bayern return 'R' + type; if ("Nordbahn".equals(type)) // Bayern return 'R' + type; if ("Harzer".equals(type)) // Bayern return 'R' + type; if ("cantus".equals(type)) // Bayern return 'R' + type; if ("DPF".equals(type)) // Bayern, Vogtland-Express return 'R' + type; if ("Freiberger".equals(type)) // Bayern return 'R' + type; if ("metronom".equals(type)) // Bayern return 'R' + type; if ("Prignitzer".equals(type)) // Bayern return 'R' + type; if ("Sächsisch-Oberlausitzer".equals(type)) // Bayern return 'R' + type; if ("Ostseeland".equals(type)) // Bayern return 'R' + type; if ("NordOstseeBahn".equals(type)) // Bayern return 'R' + type; if ("ELBE-WESER".equals(type)) // Bayern return 'R' + type; if ("TRILEX".equals(type)) // Bayern return 'R' + type; if ("Schleswig-Holstein-Bahn".equals(type)) // Bayern return 'R' + type; if ("Vetter".equals(type)) // Bayern return 'R' + type; if ("Dessau-Wörlitzer".equals(type)) // Bayern return 'R' + type; if ("NATURPARK-EXPRESS".equals(type)) // Bayern return 'R' + type; if ("Usedomer".equals(type)) // Bayern return 'R' + type; if ("Märkische".equals(type)) // Bayern return 'R' + type; if ("Vulkan-Eifel-Bahn".equals(type)) // Bayern return 'R' + type; if ("Kandertalbahn".equals(type)) // Bayern return 'R' + type; if ("RAD-WANDER-SHUTTLE".equals(type)) // Bayern, Hohenzollerische Landesbahn return 'R' + type; if ("RADEXPRESS".equals(type)) // Bayern, RADEXPRESS EYACHTÄLER return 'R' + type; if ("Dampfzug".equals(type)) // Bayern return 'R' + type; if ("Wutachtalbahn".equals(type)) // Bayern return 'R' + type; if ("Grensland-Express".equals(type)) // Bayern return 'R' + type; if ("Mecklenburgische".equals(type)) // Bayern return 'R' + type; if ("Bentheimer".equals(type)) // Bayern return 'R' + type; if ("Pressnitztalbahn".equals(type)) // Bayern return 'R' + type; if ("Regental".equals(type)) // Bayern return 'R' + type; if ("Döllnitzbahn".equals(type)) // Bayern return 'R' + type; if ("Schneeberg".equals(type)) // VOR return 'R' + type; if ("DWE".equals(type)) // Dessau-Wörlitzer Eisenbahn return 'R' + type; if ("KTB".equals(type)) // Kandertalbahn return 'R' + type; if ("Regionalzug".equals(type)) return 'R' + type; if ("BSB".equals(type)) // Breisgau-S-Bahn return 'S' + str; if ("BSB-Zug".equals(type)) // Breisgau-S-Bahn return 'S' + str; if ("Breisgau-S-Bahn".equals(type)) // Bayern return 'S' + type; if ("RER".equals(type)) // Réseau Express Régional, Frankreich return 'S' + str; if ("LO".equals(type)) // London Overground, GB return 'S' + str; if ("A".equals(name) || "B".equals(name) || "C".equals(name)) // SES return 'S' + str; final Matcher m = P_LINE_S.matcher(name); if (m.find()) return 'S' + m.group(1); if (P_LINE_U.matcher(type).matches()) return 'U' + str; if ("Underground".equals(type)) // London Underground, GB return 'U' + str; if ("Millbrae / Richmond".equals(name)) // San Francisco, BART return 'U' + name; if ("Richmond / Millbrae".equals(name)) // San Francisco, BART return 'U' + name; if ("Fremont / RIchmond".equals(name)) // San Francisco, BART return 'U' + name; if ("Richmond / Fremont".equals(name)) // San Francisco, BART return 'U' + name; if ("Pittsburg Bay Point / SFO".equals(name)) // San Francisco, BART return 'U' + name; if ("SFO / Pittsburg Bay Point".equals(name)) // San Francisco, BART return 'U' + name; if ("Dublin Pleasanton / Daly City".equals(name)) // San Francisco, BART return 'U' + name; if ("Daly City / Dublin Pleasanton".equals(name)) // San Francisco, BART return 'U' + name; if ("Fremont / Daly City".equals(name)) // San Francisco, BART return 'U' + name; if ("Daly City / Fremont".equals(name)) // San Francisco, BART return 'U' + name; if (type.equals("RT")) // RegioTram return 'T' + str; if (type.equals("STR")) // Nordhausen return 'T' + str; if ("California Cable Car".equals(name)) // San Francisco return 'T' + name; if ("Muni".equals(type)) // San Francisco return 'T' + name; if ("Cable".equals(type)) // San Francisco return 'T' + name; if ("Muni Rail".equals(noTrainName)) // San Francisco return 'T' + name; if ("Cable Car".equals(noTrainName)) // San Francisco return 'T' + name; if (type.equals("BUS")) return 'B' + str; if ("SEV-Bus".equals(type)) return 'B' + str; if ("Bex".equals(type)) // Bayern Express return 'B' + str; if (type.length() == 0) return "?"; if (P_LINE_NUMBER.matcher(type).matches()) return "?"; if (P_LINE_Y.matcher(name).matches()) return "?" + name; throw new IllegalStateException("cannot normalize mot '" + mot + "' name '" + name + "' long '" + longName + "' noTrainName '" + noTrainName + "' type '" + type + "' str '" + str + "'"); } if (t == 1) { final Matcher m = P_LINE_S.matcher(name); if (m.find()) return 'S' + m.group(1); else return 'S' + name; } if (t == 2) return 'U' + name; if (t == 3 || t == 4) return 'T' + name; if (t == 5 || t == 6 || t == 7 || t == 10) { if (name.equals("Schienenersatzverkehr")) return "BSEV"; else return 'B' + name; } if (t == 8) return 'C' + name; if (t == 9) return 'F' + name; if (t == 11 || t == -1) return '?' + name; throw new IllegalStateException("cannot normalize mot '" + mot + "' name '" + name + "' long '" + longName + "' noTrainName '" + noTrainName + "'"); } public QueryDeparturesResult queryDepartures(final int stationId, final int maxDepartures, final boolean equivs) throws IOException { final StringBuilder uri = new StringBuilder(apiBase); uri.append(departureMonitorEndpoint); appendCommonRequestParams(uri, "XML"); uri.append("&type_dm=stop&useRealtime=1&mode=direct"); uri.append("&name_dm=").append(stationId); uri.append("&deleteAssignedStops_dm=").append(equivs ? '0' : '1'); uri.append("&mergeDep=1"); // merge departures if (maxDepartures > 0) uri.append("&limit=").append(maxDepartures); InputStream is = null; try { is = ParserUtils.scrapeInputStream(uri.toString()); final XmlPullParser pp = parserFactory.newPullParser(); pp.setInput(is, null); final ResultHeader header = enterItdRequest(pp); XmlPullUtil.enter(pp, "itdDepartureMonitorRequest"); if (!XmlPullUtil.test(pp, "itdOdv") || !"dm".equals(XmlPullUtil.attr(pp, "usage"))) throw new IllegalStateException("cannot find <itdOdv usage=\"dm\" />"); XmlPullUtil.enter(pp, "itdOdv"); final String place = processItdOdvPlace(pp); XmlPullUtil.require(pp, "itdOdvName"); final String nameState = pp.getAttributeValue(null, "state"); XmlPullUtil.enter(pp, "itdOdvName"); if ("identified".equals(nameState)) { final QueryDeparturesResult result = new QueryDeparturesResult(header); final Location location = processOdvNameElem(pp, place); result.stationDepartures.add(new StationDepartures(location, new LinkedList<Departure>(), new LinkedList<LineDestination>())); XmlPullUtil.exit(pp, "itdOdvName"); if (XmlPullUtil.test(pp, "itdOdvAssignedStops")) { XmlPullUtil.enter(pp, "itdOdvAssignedStops"); while (XmlPullUtil.test(pp, "itdOdvAssignedStop")) { final Location assignedLocation = processItdOdvAssignedStop(pp); if (findStationDepartures(result.stationDepartures, assignedLocation.id) == null) result.stationDepartures.add(new StationDepartures(assignedLocation, new LinkedList<Departure>(), new LinkedList<LineDestination>())); } XmlPullUtil.exit(pp, "itdOdvAssignedStops"); } XmlPullUtil.exit(pp, "itdOdv"); if (XmlPullUtil.test(pp, "itdDateTime")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "itdDMDateTime")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "itdDateRange")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "itdTripOptions")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "itdMessage")) XmlPullUtil.next(pp); final Calendar plannedDepartureTime = new GregorianCalendar(timeZone()); final Calendar predictedDepartureTime = new GregorianCalendar(timeZone()); XmlPullUtil.require(pp, "itdServingLines"); if (!pp.isEmptyElementTag()) { XmlPullUtil.enter(pp, "itdServingLines"); while (XmlPullUtil.test(pp, "itdServingLine")) { final String assignedStopIdStr = pp.getAttributeValue(null, "assignedStopID"); final int assignedStopId = assignedStopIdStr != null ? Integer.parseInt(assignedStopIdStr) : 0; final String destination = normalizeLocationName(pp.getAttributeValue(null, "direction")); final String destinationIdStr = pp.getAttributeValue(null, "destID"); final int destinationId = (destinationIdStr != null && destinationIdStr.length() > 0) ? Integer.parseInt(destinationIdStr) : 0; final LineDestination line = new LineDestination(processItdServingLine(pp), destinationId, destination); StationDepartures assignedStationDepartures; if (assignedStopId == 0) assignedStationDepartures = result.stationDepartures.get(0); else assignedStationDepartures = findStationDepartures(result.stationDepartures, assignedStopId); if (assignedStationDepartures == null) assignedStationDepartures = new StationDepartures(new Location(LocationType.STATION, assignedStopId), new LinkedList<Departure>(), new LinkedList<LineDestination>()); if (!assignedStationDepartures.lines.contains(line)) assignedStationDepartures.lines.add(line); } XmlPullUtil.exit(pp, "itdServingLines"); } else { XmlPullUtil.next(pp); } XmlPullUtil.require(pp, "itdDepartureList"); if (!pp.isEmptyElementTag()) { XmlPullUtil.enter(pp, "itdDepartureList"); while (XmlPullUtil.test(pp, "itdDeparture")) { final int assignedStopId = XmlPullUtil.intAttr(pp, "stopID"); StationDepartures assignedStationDepartures = findStationDepartures(result.stationDepartures, assignedStopId); if (assignedStationDepartures == null) { final String mapName = pp.getAttributeValue(null, "mapName"); if (mapName == null || !"WGS84".equals(mapName)) throw new IllegalStateException("unknown mapName: " + mapName); final int lon = Math.round(XmlPullUtil.floatAttr(pp, "x")); final int lat = Math.round(XmlPullUtil.floatAttr(pp, "y")); // final String name = normalizeLocationName(XmlPullUtil.attr(pp, "nameWO")); assignedStationDepartures = new StationDepartures(new Location(LocationType.STATION, assignedStopId, lat, lon), new LinkedList<Departure>(), new LinkedList<LineDestination>()); } final String position = normalizePlatform(pp.getAttributeValue(null, "platform"), pp.getAttributeValue(null, "platformName")); XmlPullUtil.enter(pp, "itdDeparture"); XmlPullUtil.require(pp, "itdDateTime"); plannedDepartureTime.clear(); processItdDateTime(pp, plannedDepartureTime); predictedDepartureTime.clear(); if (XmlPullUtil.test(pp, "itdRTDateTime")) processItdDateTime(pp, predictedDepartureTime); if (XmlPullUtil.test(pp, "itdFrequencyInfo")) XmlPullUtil.next(pp); XmlPullUtil.require(pp, "itdServingLine"); final boolean isRealtime = pp.getAttributeValue(null, "realtime").equals("1"); final String destination = normalizeLocationName(pp.getAttributeValue(null, "direction")); final String destinationIdStr = pp.getAttributeValue(null, "destID"); final int destinationId = destinationIdStr != null ? Integer.parseInt(destinationIdStr) : 0; final Line line = processItdServingLine(pp); if (isRealtime && !predictedDepartureTime.isSet(Calendar.HOUR_OF_DAY)) predictedDepartureTime.setTimeInMillis(plannedDepartureTime.getTimeInMillis()); final Departure departure = new Departure(plannedDepartureTime.getTime(), predictedDepartureTime.isSet(Calendar.HOUR_OF_DAY) ? predictedDepartureTime.getTime() : null, line, position, destinationId, destination, null, null); assignedStationDepartures.departures.add(departure); XmlPullUtil.exit(pp, "itdDeparture"); } XmlPullUtil.exit(pp, "itdDepartureList"); } return result; } else if ("notidentified".equals(nameState) || "list".equals(nameState)) { return new QueryDeparturesResult(header, QueryDeparturesResult.Status.INVALID_STATION); } else { throw new RuntimeException("unknown nameState '" + nameState + "' on " + uri); } } catch (final XmlPullParserException x) { throw new ParserException(x); } finally { if (is != null) is.close(); } } private StationDepartures findStationDepartures(final List<StationDepartures> stationDepartures, final int id) { for (final StationDepartures stationDeparture : stationDepartures) if (stationDeparture.location.id == id) return stationDeparture; return null; } private Location processItdPointAttributes(final XmlPullParser pp) { final int id = Integer.parseInt(pp.getAttributeValue(null, "stopID")); final String place = normalizeLocationName(pp.getAttributeValue(null, "locality")); String name = normalizeLocationName(pp.getAttributeValue(null, "nameWO")); if (name == null) name = normalizeLocationName(pp.getAttributeValue(null, "name")); final int lat, lon; if ("WGS84".equals(pp.getAttributeValue(null, "mapName"))) { lat = Math.round(XmlPullUtil.floatAttr(pp, "y")); lon = Math.round(XmlPullUtil.floatAttr(pp, "x")); } else { lat = 0; lon = 0; } return new Location(LocationType.STATION, id, lat, lon, place, name); } private boolean processItdDateTime(final XmlPullParser pp, final Calendar calendar) throws XmlPullParserException, IOException { XmlPullUtil.enter(pp); calendar.clear(); final boolean success = processItdDate(pp, calendar); if (success) processItdTime(pp, calendar); XmlPullUtil.exit(pp); return success; } private boolean processItdDate(final XmlPullParser pp, final Calendar calendar) throws XmlPullParserException, IOException { XmlPullUtil.require(pp, "itdDate"); final int year = Integer.parseInt(pp.getAttributeValue(null, "year")); final int month = Integer.parseInt(pp.getAttributeValue(null, "month")) - 1; final int day = Integer.parseInt(pp.getAttributeValue(null, "day")); XmlPullUtil.next(pp); if (year == 0) return false; if (year < 1900 || year > 2100) throw new IllegalArgumentException("invalid year: " + year); if (month < 0 || month > 11) throw new IllegalArgumentException("invalid month: " + month); if (day < 1 || day > 31) throw new IllegalArgumentException("invalid day: " + day); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, day); return true; } private void processItdTime(final XmlPullParser pp, final Calendar calendar) throws XmlPullParserException, IOException { XmlPullUtil.require(pp, "itdTime"); calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(pp.getAttributeValue(null, "hour"))); calendar.set(Calendar.MINUTE, Integer.parseInt(pp.getAttributeValue(null, "minute"))); XmlPullUtil.next(pp); } private Line processItdServingLine(final XmlPullParser pp) throws XmlPullParserException, IOException { XmlPullUtil.require(pp, "itdServingLine"); final String motType = pp.getAttributeValue(null, "motType"); final String number = pp.getAttributeValue(null, "number"); final String id = pp.getAttributeValue(null, "stateless"); XmlPullUtil.enter(pp, "itdServingLine"); String noTrainName = null; if (XmlPullUtil.test(pp, "itdNoTrain")) noTrainName = pp.getAttributeValue(null, "name"); XmlPullUtil.exit(pp, "itdServingLine"); final String label = parseLine(motType, number, number, noTrainName); return new Line(id, label, lineColors(label)); } private static final Pattern P_STATION_NAME_WHITESPACE = Pattern.compile("\\s+"); protected String normalizeLocationName(final String name) { if (name == null || name.length() == 0) return null; return P_STATION_NAME_WHITESPACE.matcher(name).replaceAll(" "); } protected static double latLonToDouble(final int value) { return (double) value / 1000000; } protected String xsltTripRequest2Uri(final Location from, final Location via, final Location to, final Date date, final boolean dep, final String products, final WalkSpeed walkSpeed, final Accessibility accessibility) { final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd"); final DateFormat TIME_FORMAT = new SimpleDateFormat("HHmm"); final StringBuilder uri = new StringBuilder(apiBase); uri.append(tripEndpoint); appendCommonRequestParams(uri, "XML"); uri.append("&sessionID=0"); uri.append("&requestID=0"); uri.append("&language=de"); appendCommonXsltTripRequest2Params(uri); appendLocation(uri, from, "origin"); appendLocation(uri, to, "destination"); if (via != null) appendLocation(uri, via, "via"); uri.append("&itdDate=").append(ParserUtils.urlEncode(DATE_FORMAT.format(date))); uri.append("&itdTime=").append(ParserUtils.urlEncode(TIME_FORMAT.format(date))); uri.append("&itdTripDateTimeDepArr=").append(dep ? "dep" : "arr"); uri.append("&ptOptionsActive=1"); uri.append("&changeSpeed=").append(WALKSPEED_MAP.get(walkSpeed)); if (accessibility == Accessibility.BARRIER_FREE) uri.append("&imparedOptionsActive=1").append("&wheelchair=on").append("&noSolidStairs=on"); else if (accessibility == Accessibility.LIMITED) uri.append("&imparedOptionsActive=1").append("&wheelchair=on").append("&lowPlatformVhcl=on").append("&noSolidStairs=on"); if (products != null) { uri.append("&includedMeans=checkbox"); boolean hasI = false; for (final char p : products.toCharArray()) { if (p == 'I' || p == 'R') { uri.append("&inclMOT_0=on"); if (p == 'I') hasI = true; } if (p == 'S') uri.append("&inclMOT_1=on"); if (p == 'U') uri.append("&inclMOT_2=on"); if (p == 'T') uri.append("&inclMOT_3=on&inclMOT_4=on"); if (p == 'B') uri.append("&inclMOT_5=on&inclMOT_6=on&inclMOT_7=on"); if (p == 'P') uri.append("&inclMOT_10=on"); if (p == 'F') uri.append("&inclMOT_9=on"); if (p == 'C') uri.append("&inclMOT_8=on"); uri.append("&inclMOT_11=on"); // TODO always show 'others', for now } // workaround for highspeed trains: fails when you want highspeed, but not regional if (!hasI) uri.append("&lineRestriction=403"); // means: all but ice } uri.append("&locationServerActive=1"); uri.append("&useRealtime=1"); uri.append("&useProxFootSearch=1"); // walk if it makes journeys quicker return uri.toString(); } private String commandLink(final String sessionId, final String requestId, final String command) { final StringBuilder uri = new StringBuilder(apiBase); uri.append(tripEndpoint); uri.append("?sessionID=").append(sessionId); uri.append("&requestID=").append(requestId); appendCommonXsltTripRequest2Params(uri); uri.append("&command=").append(command); return uri.toString(); } private static final void appendCommonXsltTripRequest2Params(final StringBuilder uri) { uri.append("&coordListOutputFormat=STRING"); uri.append("&calcNumberOfTrips=4"); } public QueryConnectionsResult queryConnections(final Location from, final Location via, final Location to, final Date date, final boolean dep, final String products, final WalkSpeed walkSpeed, final Accessibility accessibility) throws IOException { final String uri = xsltTripRequest2Uri(from, via, to, date, dep, products, walkSpeed, accessibility); InputStream is = null; try { is = ParserUtils.scrapeInputStream(uri, null, "NSC_", 3); return queryConnections(uri, is); } catch (final XmlPullParserException x) { throw new ParserException(x); } finally { if (is != null) is.close(); } } public QueryConnectionsResult queryMoreConnections(final String uri) throws IOException { InputStream is = null; try { is = ParserUtils.scrapeInputStream(uri, null, "NSC_", 3); return queryConnections(uri, is); } catch (final XmlPullParserException x) { if (x.getMessage().startsWith("expected: START_TAG {null}itdRequest")) throw new SessionExpiredException(); else throw new ParserException(x); } finally { if (is != null) is.close(); } } private QueryConnectionsResult queryConnections(final String uri, final InputStream is) throws XmlPullParserException, IOException { // System.out.println(uri); final XmlPullParser pp = parserFactory.newPullParser(); pp.setInput(is, null); final ResultHeader header = enterItdRequest(pp); final String context = header.context; if (XmlPullUtil.test(pp, "itdLayoutParams")) XmlPullUtil.next(pp); XmlPullUtil.require(pp, "itdTripRequest"); final String requestId = XmlPullUtil.attr(pp, "requestID"); XmlPullUtil.enter(pp, "itdTripRequest"); if (XmlPullUtil.test(pp, "itdMessage")) { final int code = XmlPullUtil.intAttr(pp, "code"); if (code == -4000) // no connection return new QueryConnectionsResult(header, QueryConnectionsResult.Status.NO_CONNECTIONS); XmlPullUtil.next(pp); } if (XmlPullUtil.test(pp, "itdPrintConfiguration")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "itdAddress")) XmlPullUtil.next(pp); // parse odv name elements List<Location> ambiguousFrom = null, ambiguousTo = null, ambiguousVia = null; Location from = null, via = null, to = null; while (XmlPullUtil.test(pp, "itdOdv")) { final String usage = XmlPullUtil.attr(pp, "usage"); XmlPullUtil.enter(pp, "itdOdv"); final String place = processItdOdvPlace(pp); if (!XmlPullUtil.test(pp, "itdOdvName")) throw new IllegalStateException("cannot find <itdOdvName /> inside " + usage); final String nameState = XmlPullUtil.attr(pp, "state"); XmlPullUtil.enter(pp, "itdOdvName"); if (XmlPullUtil.test(pp, "itdMessage")) XmlPullUtil.next(pp); if ("list".equals(nameState)) { if ("origin".equals(usage)) { ambiguousFrom = new ArrayList<Location>(); while (XmlPullUtil.test(pp, "odvNameElem")) ambiguousFrom.add(processOdvNameElem(pp, place)); } else if ("via".equals(usage)) { ambiguousVia = new ArrayList<Location>(); while (XmlPullUtil.test(pp, "odvNameElem")) ambiguousVia.add(processOdvNameElem(pp, place)); } else if ("destination".equals(usage)) { ambiguousTo = new ArrayList<Location>(); while (XmlPullUtil.test(pp, "odvNameElem")) ambiguousTo.add(processOdvNameElem(pp, place)); } else { throw new IllegalStateException("unknown usage: " + usage); } } else if ("identified".equals(nameState)) { if (!XmlPullUtil.test(pp, "odvNameElem")) throw new IllegalStateException("cannot find <odvNameElem /> inside " + usage); if ("origin".equals(usage)) from = processOdvNameElem(pp, place); else if ("via".equals(usage)) via = processOdvNameElem(pp, place); else if ("destination".equals(usage)) to = processOdvNameElem(pp, place); else throw new IllegalStateException("unknown usage: " + usage); } XmlPullUtil.exit(pp, "itdOdvName"); XmlPullUtil.exit(pp, "itdOdv"); } if (ambiguousFrom != null || ambiguousTo != null || ambiguousVia != null) return new QueryConnectionsResult(header, ambiguousFrom, ambiguousVia, ambiguousTo); XmlPullUtil.enter(pp, "itdTripDateTime"); XmlPullUtil.enter(pp, "itdDateTime"); if (!XmlPullUtil.test(pp, "itdDate")) throw new IllegalStateException("cannot find <itdDate />"); if (!pp.isEmptyElementTag()) { XmlPullUtil.enter(pp, "itdDate"); if (XmlPullUtil.test(pp, "itdMessage")) { final String message = pp.nextText(); if ("invalid date".equals(message)) return new QueryConnectionsResult(header, QueryConnectionsResult.Status.INVALID_DATE); else throw new IllegalStateException("unknown message: " + message); } XmlPullUtil.exit(pp, "itdDate"); } XmlPullUtil.exit(pp, "itdDateTime"); final Calendar time = new GregorianCalendar(timeZone()); final List<Connection> connections = new ArrayList<Connection>(); - System.out.println("====================== bis hier"); - if (XmlPullUtil.jumpToStartTag(pp, null, "itdRouteList")) { XmlPullUtil.enter(pp, "itdRouteList"); while (XmlPullUtil.test(pp, "itdRoute")) { final String id = pp.getAttributeValue(null, "routeIndex") + "-" + pp.getAttributeValue(null, "routeTripIndex"); XmlPullUtil.enter(pp, "itdRoute"); while (XmlPullUtil.test(pp, "itdDateTime")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "itdMapItemList")) XmlPullUtil.next(pp); XmlPullUtil.enter(pp, "itdPartialRouteList"); final List<Connection.Part> parts = new LinkedList<Connection.Part>(); Location firstDeparture = null; Location lastArrival = null; while (XmlPullUtil.test(pp, "itdPartialRoute")) { XmlPullUtil.enter(pp, "itdPartialRoute"); XmlPullUtil.test(pp, "itdPoint"); if (!"departure".equals(pp.getAttributeValue(null, "usage"))) throw new IllegalStateException(); final Location departure = processItdPointAttributes(pp); if (firstDeparture == null) firstDeparture = departure; final String departurePosition = normalizePlatform(pp.getAttributeValue(null, "platform"), pp.getAttributeValue(null, "platformName")); XmlPullUtil.enter(pp, "itdPoint"); if (XmlPullUtil.test(pp, "itdMapItemList")) XmlPullUtil.next(pp); XmlPullUtil.require(pp, "itdDateTime"); processItdDateTime(pp, time); final Date departureTime = time.getTime(); final Date departureTargetTime; if (XmlPullUtil.test(pp, "itdDateTimeTarget")) { processItdDateTime(pp, time); departureTargetTime = time.getTime(); } else { departureTargetTime = null; } XmlPullUtil.exit(pp, "itdPoint"); XmlPullUtil.test(pp, "itdPoint"); if (!"arrival".equals(pp.getAttributeValue(null, "usage"))) throw new IllegalStateException(); final Location arrival = processItdPointAttributes(pp); lastArrival = arrival; final String arrivalPosition = normalizePlatform(pp.getAttributeValue(null, "platform"), pp.getAttributeValue(null, "platformName")); XmlPullUtil.enter(pp, "itdPoint"); if (XmlPullUtil.test(pp, "itdMapItemList")) XmlPullUtil.next(pp); XmlPullUtil.require(pp, "itdDateTime"); processItdDateTime(pp, time); final Date arrivalTime = time.getTime(); final Date arrivalTargetTime; if (XmlPullUtil.test(pp, "itdDateTimeTarget")) { processItdDateTime(pp, time); arrivalTargetTime = time.getTime(); } else { arrivalTargetTime = null; } XmlPullUtil.exit(pp, "itdPoint"); XmlPullUtil.test(pp, "itdMeansOfTransport"); final String productName = pp.getAttributeValue(null, "productName"); if ("Fussweg".equals(productName) || "Taxi".equals(productName)) { final int min = (int) (arrivalTime.getTime() - departureTime.getTime()) / 1000 / 60; XmlPullUtil.enter(pp, "itdMeansOfTransport"); XmlPullUtil.exit(pp, "itdMeansOfTransport"); if (XmlPullUtil.test(pp, "itdStopSeq")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "itdFootPathInfo")) XmlPullUtil.next(pp); List<Point> path = null; if (XmlPullUtil.test(pp, "itdPathCoordinates")) path = processItdPathCoordinates(pp); if (parts.size() > 0 && parts.get(parts.size() - 1) instanceof Connection.Footway) { final Connection.Footway lastFootway = (Connection.Footway) parts.remove(parts.size() - 1); if (path != null && lastFootway.path != null) path.addAll(0, lastFootway.path); parts.add(new Connection.Footway(lastFootway.min + min, lastFootway.departure, arrival, path)); } else { parts.add(new Connection.Footway(min, departure, arrival, path)); } } else if ("gesicherter Anschluss".equals(productName) || "nicht umsteigen".equals(productName)) // type97 { // ignore XmlPullUtil.enter(pp, "itdMeansOfTransport"); XmlPullUtil.exit(pp, "itdMeansOfTransport"); } else { final String destinationIdStr = pp.getAttributeValue(null, "destID"); final String destinationName = normalizeLocationName(pp.getAttributeValue(null, "destination")); final Location destination = destinationIdStr.length() > 0 ? new Location(LocationType.STATION, Integer.parseInt(destinationIdStr), null, destinationName) : new Location(LocationType.ANY, 0, null, destinationName); final String lineLabel; if ("AST".equals(pp.getAttributeValue(null, "symbol"))) lineLabel = "BAST"; else lineLabel = parseLine(pp.getAttributeValue(null, "motType"), pp.getAttributeValue(null, "shortname"), pp.getAttributeValue(null, "name"), null); XmlPullUtil.enter(pp, "itdMeansOfTransport"); XmlPullUtil.require(pp, "motDivaParams"); final String lineId = XmlPullUtil.attr(pp, "network") + ':' + XmlPullUtil.attr(pp, "line") + ':' + XmlPullUtil.attr(pp, "supplement") + ':' + XmlPullUtil.attr(pp, "direction") + ':' + XmlPullUtil.attr(pp, "project"); XmlPullUtil.exit(pp, "itdMeansOfTransport"); if (XmlPullUtil.test(pp, "itdRBLControlled")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "itdInfoTextList")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "itdFootPathInfo")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "infoLink")) XmlPullUtil.next(pp); List<Stop> intermediateStops = null; if (XmlPullUtil.test(pp, "itdStopSeq")) { XmlPullUtil.enter(pp, "itdStopSeq"); intermediateStops = new LinkedList<Stop>(); while (XmlPullUtil.test(pp, "itdPoint")) { final Location stopLocation = processItdPointAttributes(pp); final String stopPosition = normalizePlatform(pp.getAttributeValue(null, "platform"), pp.getAttributeValue(null, "platformName")); XmlPullUtil.enter(pp, "itdPoint"); XmlPullUtil.require(pp, "itdDateTime"); final boolean success1 = processItdDateTime(pp, time); final boolean success2 = XmlPullUtil.test(pp, "itdDateTime") ? processItdDateTime(pp, time) : false; XmlPullUtil.exit(pp, "itdPoint"); if (success1 || success2) intermediateStops.add(new Stop(stopLocation, stopPosition, time.getTime())); } XmlPullUtil.exit(pp, "itdStopSeq"); // remove first and last, because they are not intermediate final int size = intermediateStops.size(); if (size >= 2) { if (intermediateStops.get(size - 1).location.id != arrival.id) throw new IllegalStateException(); intermediateStops.remove(size - 1); if (intermediateStops.get(0).location.id != departure.id) throw new IllegalStateException(); intermediateStops.remove(0); } } List<Point> path = null; if (XmlPullUtil.test(pp, "itdPathCoordinates")) path = processItdPathCoordinates(pp); final Set<Line.Attr> lineAttrs = new HashSet<Line.Attr>(); if (XmlPullUtil.test(pp, "genAttrList")) { XmlPullUtil.enter(pp, "genAttrList"); while (XmlPullUtil.test(pp, "genAttrElem")) { XmlPullUtil.enter(pp, "genAttrElem"); XmlPullUtil.enter(pp, "name"); final String name = pp.getText(); XmlPullUtil.exit(pp, "name"); XmlPullUtil.enter(pp, "value"); final String value = pp.getText(); XmlPullUtil.exit(pp, "value"); XmlPullUtil.exit(pp, "genAttrElem"); // System.out.println("genAttrElem: name='" + name + "' value='" + value + "'"); if ("PlanWheelChairAccess".equals(name) && "1".equals(value)) lineAttrs.add(Line.Attr.WHEEL_CHAIR_ACCESS); } XmlPullUtil.exit(pp, "genAttrList"); } final Line line = new Line(lineId, lineLabel, lineColors(lineLabel), lineAttrs); parts.add(new Connection.Trip(line, destination, departureTargetTime != null ? departureTargetTime : departureTime, departureTargetTime, departurePosition, departure, arrivalTargetTime != null ? arrivalTargetTime : arrivalTime, arrivalTargetTime, arrivalPosition, arrival, intermediateStops, path)); } XmlPullUtil.exit(pp, "itdPartialRoute"); } XmlPullUtil.exit(pp, "itdPartialRouteList"); final List<Fare> fares = new ArrayList<Fare>(2); if (XmlPullUtil.test(pp, "itdFare") && !pp.isEmptyElementTag()) { XmlPullUtil.enter(pp, "itdFare"); if (XmlPullUtil.test(pp, "itdSingleTicket")) { final String net = XmlPullUtil.attr(pp, "net"); final Currency currency = parseCurrency(XmlPullUtil.attr(pp, "currency")); final String fareAdult = XmlPullUtil.attr(pp, "fareAdult"); final String fareChild = XmlPullUtil.attr(pp, "fareChild"); final String unitName = XmlPullUtil.attr(pp, "unitName"); final String unitsAdult = XmlPullUtil.attr(pp, "unitsAdult"); final String unitsChild = XmlPullUtil.attr(pp, "unitsChild"); final String levelAdult = pp.getAttributeValue(null, "levelAdult"); final boolean hasLevelAdult = levelAdult != null && levelAdult.length() > 0; final String levelChild = pp.getAttributeValue(null, "levelChild"); final boolean hasLevelChild = levelChild != null && levelChild.length() > 0; if (fareAdult != null && fareAdult.length() > 0) fares.add(new Fare(net, Type.ADULT, currency, Float.parseFloat(fareAdult), hasLevelAdult ? null : unitName, hasLevelAdult ? levelAdult : unitsAdult)); if (fareChild != null && fareChild.length() > 0) fares.add(new Fare(net, Type.CHILD, currency, Float.parseFloat(fareChild), hasLevelChild ? null : unitName, hasLevelChild ? levelChild : unitsChild)); if (!pp.isEmptyElementTag()) { XmlPullUtil.enter(pp, "itdSingleTicket"); if (XmlPullUtil.test(pp, "itdGenericTicketList")) { XmlPullUtil.enter(pp, "itdGenericTicketList"); while (XmlPullUtil.test(pp, "itdGenericTicketGroup")) { final Fare fare = processItdGenericTicketGroup(pp, net, currency); if (fare != null) fares.add(fare); } XmlPullUtil.exit(pp, "itdGenericTicketList"); } XmlPullUtil.exit(pp, "itdSingleTicket"); } } XmlPullUtil.exit(pp, "itdFare"); } connections.add(new Connection(id, uri, firstDeparture, lastArrival, parts, fares.isEmpty() ? null : fares, null)); XmlPullUtil.exit(pp, "itdRoute"); } XmlPullUtil.exit(pp, "itdRouteList"); - System.out.println("=== ready"); - return new QueryConnectionsResult(header, uri, from, via, to, commandLink(context, requestId, "tripNext"), connections); } else { return new QueryConnectionsResult(header, QueryConnectionsResult.Status.NO_CONNECTIONS); } } private List<Point> processItdPathCoordinates(final XmlPullParser pp) throws XmlPullParserException, IOException { final List<Point> path = new LinkedList<Point>(); XmlPullUtil.enter(pp, "itdPathCoordinates"); XmlPullUtil.enter(pp, "coordEllipsoid"); final String ellipsoid = pp.getText(); XmlPullUtil.exit(pp, "coordEllipsoid"); if (!"WGS84".equals(ellipsoid)) throw new IllegalStateException("unknown ellipsoid: " + ellipsoid); XmlPullUtil.enter(pp, "coordType"); final String type = pp.getText(); XmlPullUtil.exit(pp, "coordType"); if (!"GEO_DECIMAL".equals(type)) throw new IllegalStateException("unknown type: " + type); XmlPullUtil.enter(pp, "itdCoordinateString"); for (final String coordStr : pp.getText().split(" +")) { final String[] coordsStr = coordStr.split(","); path.add(new Point(Math.round(Float.parseFloat(coordsStr[1])), Math.round(Float.parseFloat(coordsStr[0])))); } XmlPullUtil.exit(pp, "itdCoordinateString"); XmlPullUtil.exit(pp, "itdPathCoordinates"); return path; } private Fare processItdGenericTicketGroup(final XmlPullParser pp, final String net, final Currency currency) throws XmlPullParserException, IOException { XmlPullUtil.enter(pp, "itdGenericTicketGroup"); Type type = null; float fare = 0; while (XmlPullUtil.test(pp, "itdGenericTicket")) { XmlPullUtil.enter(pp, "itdGenericTicket"); XmlPullUtil.enter(pp, "ticket"); final String key = pp.getText().trim(); XmlPullUtil.exit(pp, "ticket"); String value = null; XmlPullUtil.require(pp, "value"); if (!pp.isEmptyElementTag()) { XmlPullUtil.enter(pp, "value"); value = pp.getText(); if (value != null) value = value.trim(); XmlPullUtil.exit(pp, "value"); } if (key.equals("FOR_RIDER")) { final String typeStr = value.split(" ")[0].toUpperCase(); if (typeStr.equals("REGULAR")) type = Type.ADULT; else type = Type.valueOf(typeStr); } else if (key.equals("PRICE")) { fare = Float.parseFloat(value) * (currency.getCurrencyCode().equals("USD") ? 0.01f : 1); } XmlPullUtil.exit(pp, "itdGenericTicket"); } XmlPullUtil.exit(pp, "itdGenericTicketGroup"); if (type != null) return new Fare(net, type, currency, fare, null, null); else return null; } private Currency parseCurrency(final String currencyStr) { if (currencyStr.equals("US$")) return Currency.getInstance("USD"); if (currencyStr.equals("Dirham")) return Currency.getInstance("AED"); return Currency.getInstance(currencyStr); } private static final Pattern P_PLATFORM = Pattern.compile("#?(\\d+)", Pattern.CASE_INSENSITIVE); private static final Pattern P_PLATFORM_NAME = Pattern.compile("(?:Gleis|Gl\\.|Bstg\\.)?\\s*" + // "(\\d+)\\s*" + // "(?:([A-Z])\\s*(?:-\\s*([A-Z]))?)?", Pattern.CASE_INSENSITIVE); private static final String normalizePlatform(final String platform, final String platformName) { if (platform != null && platform.length() > 0) { final Matcher m = P_PLATFORM.matcher(platform); if (m.matches()) { return Integer.toString(Integer.parseInt(m.group(1))); } else { return platform; } } if (platformName != null && platformName.length() > 0) { final Matcher m = P_PLATFORM_NAME.matcher(platformName); if (m.matches()) { final String simple = Integer.toString(Integer.parseInt(m.group(1))); if (m.group(2) != null && m.group(3) != null) return simple + m.group(2) + "-" + m.group(3); else if (m.group(2) != null) return simple + m.group(2); else return simple; } else { return platformName; } } return null; } public GetConnectionDetailsResult getConnectionDetails(final String connectionUri) throws IOException { throw new UnsupportedOperationException(); } private void appendLocation(final StringBuilder uri, final Location location, final String paramSuffix) { if (canAcceptPoiID && location.type == LocationType.POI && location.hasId()) { uri.append("&type_").append(paramSuffix).append("=poiID"); uri.append("&name_").append(paramSuffix).append("=").append(location.id); } else if ((location.type == LocationType.POI || location.type == LocationType.ADDRESS) && location.hasLocation()) { uri.append("&type_").append(paramSuffix).append("=coord"); uri.append("&name_").append(paramSuffix).append("=") .append(String.format(Locale.ENGLISH, "%.6f:%.6f", location.lon / 1E6, location.lat / 1E6)).append(":WGS84"); } else { uri.append("&type_").append(paramSuffix).append("=").append(locationTypeValue(location)); uri.append("&name_").append(paramSuffix).append("=").append(ParserUtils.urlEncode(locationValue(location), "ISO-8859-1")); } } protected static final String locationTypeValue(final Location location) { final LocationType type = location.type; if (type == LocationType.STATION) return "stop"; if (type == LocationType.ADDRESS) return "any"; // strange, matches with anyObjFilter if (type == LocationType.POI) return "poi"; if (type == LocationType.ANY) return "any"; throw new IllegalArgumentException(type.toString()); } protected static final String locationValue(final Location location) { if ((location.type == LocationType.STATION || location.type == LocationType.POI) && location.hasId()) return Integer.toString(location.id); else return location.name; } protected static final Map<WalkSpeed, String> WALKSPEED_MAP = new HashMap<WalkSpeed, String>(); static { WALKSPEED_MAP.put(WalkSpeed.SLOW, "slow"); WALKSPEED_MAP.put(WalkSpeed.NORMAL, "normal"); WALKSPEED_MAP.put(WalkSpeed.FAST, "fast"); } private ResultHeader enterItdRequest(final XmlPullParser pp) throws XmlPullParserException, IOException { if (pp.getEventType() == XmlPullParser.START_DOCUMENT) pp.next(); if (XmlPullUtil.test(pp, "html")) throw new ProtocolException("html"); XmlPullUtil.require(pp, "itdRequest"); final String serverVersion = XmlPullUtil.attr(pp, "version"); final String now = XmlPullUtil.attr(pp, "now"); final String sessionId = XmlPullUtil.attr(pp, "sessionID"); final Calendar serverTime = new GregorianCalendar(timeZone()); ParserUtils.parseIsoDate(serverTime, now.substring(0, 10)); ParserUtils.parseEuropeanTime(serverTime, now.substring(11)); final ResultHeader header = new ResultHeader(SERVER_PRODUCT, serverVersion, serverTime.getTimeInMillis(), sessionId); XmlPullUtil.enter(pp, "itdRequest"); if (XmlPullUtil.test(pp, "clientHeaderLines")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "itdVersionInfo")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "itdInfoLinkList")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "serverMetaInfo")) XmlPullUtil.next(pp); return header; } }
false
false
null
null
diff --git a/src/de/ub0r/android/smsdroid/AsyncHelper.java b/src/de/ub0r/android/smsdroid/AsyncHelper.java index 6e10bb8..b2d0ecf 100644 --- a/src/de/ub0r/android/smsdroid/AsyncHelper.java +++ b/src/de/ub0r/android/smsdroid/AsyncHelper.java @@ -1,279 +1,286 @@ /* * Copyright (C) 2010 Felix Bechstein * * This file is part of SMSdroid. * * 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 de.ub0r.android.smsdroid; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.util.Log; /** * @author flx */ public final class AsyncHelper extends AsyncTask<Void, Void, Void> { /** Tag for logging. */ static final String TAG = "SMSdroid.ash"; /** Pattern to clean up numbers. */ private static final Pattern PATTERN_CLEAN_NUMBER = Pattern .compile("<(\\+?[0-9]+)>"); /** Length of a international prefix, + notation. */ private static final int MIN_LEN_PLUS = "+49x".length(); /** Length of a international prefix, 00 notation. */ private static final int MIN_LEN_ZERO = "0049x".length(); /** Wrapper to use for contacts API. */ private static final ContactsWrapper WRAPPER = ContactsWrapper .getInstance(); /** {@link ConversationsAdapter} to invalidate on new data. */ private static ConversationsAdapter adapter = null; /** {@link Context}. */ private final Context context; /** {@link Conversation}. */ private final Conversation mConversation; /** * Fill {@link Conversation}. * * @param c * {@link Context} * @param conv * {@link Conversation} */ private AsyncHelper(final Context c, final Conversation conv) { this.context = c; this.mConversation = conv; } /** * Fill Conversations data. If needed: spawn threads. * * @param context * {@link Context} * @param c * {@link Conversation} * @param sync * fetch of information */ public static void fillConversation(final Context context, final Conversation c, final boolean sync) { Log.d(TAG, "fillConversation(ctx, conv, " + sync + ")"); if (context == null || c == null || c.getThreadId() < 0) { return; } AsyncHelper helper = new AsyncHelper(context, c); if (sync) { helper.doInBackground((Void) null); } else { helper.execute((Void) null); } } /** * {@inheritDoc} */ @Override protected Void doInBackground(final Void... arg0) { ContentValues cv = new ContentValues(); Uri uri = this.mConversation.getUri(); Cursor cursor = this.context.getContentResolver().query(uri, Message.PROJECTION_JOIN, null, null, null); // count this.mConversation.setCount(cursor.getCount()); // address String address = this.mConversation.getAddress(); Log.d(TAG, "address: " + address); if (address == null) { if (cursor.moveToLast()) { do { address = cursor.getString(Message.INDEX_ADDRESS); } while (address == null && cursor.moveToPrevious()); } if (address != null) { this.mConversation.setAddress(address); Log.d(TAG, "new address: " + address); cv.put(ConversationProvider.PROJECTION[// . ConversationProvider.INDEX_ADDRESS], address); } } if (this.mConversation.getBody() == null && cursor.moveToLast()) { final Message m = Message.getMessage(this.context, cursor); final CharSequence b = m.getBody(); if (b != null) { this.mConversation.setBody(b.toString()); } } // contact int pid = this.mConversation.getPersonId(); if (pid == 0 && address != null) { Cursor contact = getContact(this.context, address); if (contact != null) { pid = contact.getInt(ContactsWrapper.FILTER_INDEX_ID); String n = contact.getString(ContactsWrapper.FILTER_INDEX_NAME); this.mConversation.setPersonId(pid); this.mConversation.setName(n); cv.put(ConversationProvider.PROJECTION[// . ConversationProvider.INDEX_PID], pid); cv.put(ConversationProvider.PROJECTION[// . ConversationProvider.INDEX_NAME], n); } else { this.mConversation.setPersonId(-1); } } // read cursor = this.context.getContentResolver().query(uri, Message.PROJECTION, Message.PROJECTION[Message.INDEX_READ] + " = 0", null, null); if (cursor.getCount() == 0) { this.mConversation.setRead(1); } else { this.mConversation.setRead(0); } // update changes if (cv.size() > 0) { this.context.getContentResolver().update( this.mConversation.getInternalUri(), cv, null, null); } cursor.close(); cursor = null; // photo if (SMSdroid.showContactPhoto && // . this.mConversation.getPhoto() == null && pid > 0) { this.mConversation.setPhoto(getPictureForPerson(this.context, pid)); } return null; } /** * {@inheritDoc} */ @Override protected void onPostExecute(final Void result) { if (adapter != null) { adapter.notifyDataSetChanged(); } } /** * Set {@link ConversationsAdapter} to invalidate data after refreshing. * * @param a * {@link ConversationsAdapter} */ public static void setAdapter(final ConversationsAdapter a) { adapter = a; } /** * Get a contact's name by address. * * @param context * {@link Context} * @param address * address * @return name */ public static String getContactName(final Context context, final String address) { + Log.d(TAG, "getContactName(ctx, " + address + ")"); + if (address == null) { + return null; + } Cursor cursor = getContact(context, address); if (cursor == null) { return null; } return cursor.getString(ContactsWrapper.FILTER_INDEX_NAME); } /** * Get (id, name) for address. * * @param context * {@link Context} * @param address * address * @return {@link Cursor} */ private static synchronized Cursor getContact(final Context context, final String address) { Log.d(TAG, "getContact(ctx, " + address + ")"); + if (address == null) { + return null; + } // clean up number String realAddress = address; final Matcher m = PATTERN_CLEAN_NUMBER.matcher(realAddress); if (m.find()) { realAddress = m.group(1); } final int l = realAddress.length(); if (l > MIN_LEN_PLUS && realAddress.startsWith("+")) { realAddress = "%" + realAddress.substring(MIN_LEN_PLUS); } else if (l > MIN_LEN_ZERO && realAddress.startsWith("00")) { realAddress = "%" + realAddress.substring(MIN_LEN_ZERO); } else if (realAddress.startsWith("0")) { realAddress = "%" + realAddress.substring(1); } // address contains the phone number final String[] proj = WRAPPER.getProjectionFilter(); final Uri uri = WRAPPER.getUriFilter(); final String where = proj[ContactsWrapper.FILTER_INDEX_NUMBER] + " like '" + realAddress + "'"; Log.d(TAG, "query: " + uri + " WHERE " + where); try { final Cursor cursor = context.getContentResolver().query(uri, proj, where, null, null); if (cursor != null && cursor.moveToFirst()) { return cursor; } } catch (Exception e) { Log.e(TAG, "failed to fetch contact", e); } return null; } /** * Get picture for contact. * * @param context * {@link Context} * @param pid * contact * @return {@link Bitmap} */ private static Bitmap getPictureForPerson(final Context context, final int pid) { Bitmap b = WRAPPER.loadContactPhoto(context, pid); if (b == null) { return Conversation.NO_PHOTO; } else { return b; } } }
false
false
null
null
diff --git a/src/main/java/de/thatsich/bachelor/prediction/intern/command/commands/InitBinaryPredictionListCommand.java b/src/main/java/de/thatsich/bachelor/prediction/intern/command/commands/InitBinaryPredictionListCommand.java index 0248e53..9ad9779 100644 --- a/src/main/java/de/thatsich/bachelor/prediction/intern/command/commands/InitBinaryPredictionListCommand.java +++ b/src/main/java/de/thatsich/bachelor/prediction/intern/command/commands/InitBinaryPredictionListCommand.java @@ -1,69 +1,70 @@ package de.thatsich.bachelor.prediction.intern.command.commands; import java.io.IOException; import java.nio.file.DirectoryIteratorException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import javafx.collections.FXCollections; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import de.thatsich.bachelor.prediction.api.entities.BinaryPrediction; import de.thatsich.bachelor.prediction.intern.service.BinaryPredictionFileStorageService; import de.thatsich.core.javafx.ACommand; public class InitBinaryPredictionListCommand extends ACommand<List<BinaryPrediction>> { // Fields private final Path binaryPredictionFolderPath; // Injects @Inject BinaryPredictionFileStorageService fileStorage; @Inject protected InitBinaryPredictionListCommand(@Assisted Path binaryPredictionFolderPath) { this.binaryPredictionFolderPath = binaryPredictionFolderPath; } + @SuppressWarnings("unused") @Override protected List<BinaryPrediction> call() throws Exception { final List<BinaryPrediction> binaryPredictionList = FXCollections.observableArrayList(); final String GLOB_PATTERN = "*.{png}"; // traverse whole directory and search for yaml files // try to open them // and parse the correct classifier try (DirectoryStream<Path> stream = Files.newDirectoryStream(binaryPredictionFolderPath, GLOB_PATTERN)) { for (Path child : stream) { // split the file name // and check if has 5 members // and extract them final String fileName = child.getFileName().toString(); final String[] fileNameSplit = fileName.split("_"); // if (fileNameSplit.length != 5) throw new WrongNumberArgsException("Expected 5 encoded information but found " + fileNameSplit.length); log.info("Split FileNmae."); final String classificationName = fileNameSplit[0]; final String extractorName = fileNameSplit[1]; final int frameSize = Integer.parseInt(fileNameSplit[2]); final String errorName = fileNameSplit[3]; final String id = fileNameSplit[4]; log.info("Prepared SubInformation."); final BinaryPrediction prediction = fileStorage.load(child); binaryPredictionList.add(prediction); } } catch (IOException | DirectoryIteratorException e) { e.printStackTrace(); } log.info("All BinaryClassification extracted."); return binaryPredictionList; } } \ No newline at end of file diff --git a/src/main/java/de/thatsich/bachelor/prediction/intern/control/TestInputPresenter.java b/src/main/java/de/thatsich/bachelor/prediction/intern/control/TestInputPresenter.java index 736abdc..8779b3b 100644 --- a/src/main/java/de/thatsich/bachelor/prediction/intern/control/TestInputPresenter.java +++ b/src/main/java/de/thatsich/bachelor/prediction/intern/control/TestInputPresenter.java @@ -1,126 +1,126 @@ package de.thatsich.bachelor.prediction.intern.control; import java.nio.file.Path; import javafx.concurrent.WorkerStateEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.control.Button; import com.google.inject.Inject; +import de.thatsich.bachelor.classification.api.core.IBinaryClassifications; import de.thatsich.bachelor.classification.api.entities.IBinaryClassification; -import de.thatsich.bachelor.classification.intern.model.BinaryClassifications; +import de.thatsich.bachelor.errorgeneration.api.core.IErrorGenerators; import de.thatsich.bachelor.errorgeneration.api.entities.IErrorGenerator; -import de.thatsich.bachelor.errorgeneration.restricted.model.ErrorGenerators; +import de.thatsich.bachelor.featureextraction.api.core.IFeatureExtractors; import de.thatsich.bachelor.featureextraction.restricted.command.extractor.IFeatureExtractor; -import de.thatsich.bachelor.featureextraction.restricted.models.FeatureExtractors; +import de.thatsich.bachelor.imageprocessing.api.core.IImageEntries; import de.thatsich.bachelor.imageprocessing.api.entities.ImageEntry; -import de.thatsich.bachelor.imageprocessing.restricted.model.ImageEntries; import de.thatsich.bachelor.prediction.api.entities.BinaryPrediction; import de.thatsich.bachelor.prediction.intern.command.BinaryPredictionCommandProvider; import de.thatsich.bachelor.prediction.intern.command.commands.TestBinaryClassificationCommand; import de.thatsich.bachelor.prediction.intern.model.BinaryPredictions; import de.thatsich.bachelor.prediction.intern.model.PredictionState; import de.thatsich.core.javafx.AFXMLPresenter; public class TestInputPresenter extends AFXMLPresenter { // Nodes @FXML private Button nodeButtonTestBinaryClassification; // Injects - @Inject private ImageEntries imageEntries; - @Inject private ErrorGenerators errorGenerators; - @Inject private FeatureExtractors featureExtractors; - @Inject private BinaryClassifications binaryClassifications; + @Inject private IImageEntries imageEntries; + @Inject private IErrorGenerators errorGenerators; + @Inject private IFeatureExtractors featureExtractors; + @Inject private IBinaryClassifications binaryClassifications; @Inject private PredictionState predictionState; @Inject private BinaryPredictions binaryPredictions; @Inject private BinaryPredictionCommandProvider provider; // ================================================== // Initialization Implementation // ================================================== @Override protected void initComponents() { } @Override protected void bindComponents() { this.bindButtons(); } // ================================================== // Bindings Implementation // ================================================== private void bindButtons() { this.nodeButtonTestBinaryClassification.disableProperty().bind(this.imageEntries.selectedImageEntryProperty().isNull().or(this.binaryClassifications.getSelectedBinaryClassificationProperty().isNull())); } // ================================================== // GUI Implementation // ================================================== /** * */ @FXML private void onTestBinaryClassifierAction() { final Path predictionFolderPath = this.predictionState.getPredictionFolderPathProperty().get(); final IBinaryClassification binaryClassification = this.binaryClassifications.getSelectedBinaryClassificationProperty().get(); final String errorGeneratorName = binaryClassification.getErrorNameProperty().get(); final String featureExtractorName = binaryClassification.getExtractorNameProperty().get(); this.log.info("Prepared all information."); final ImageEntry imageEntry = this.imageEntries.selectedImageEntryProperty().get(); final int frameSize = binaryClassification.getFrameSizeProperty().get(); final IErrorGenerator errorGenerator = this.getErrorGenerator(errorGeneratorName); final IFeatureExtractor featureExtractor = this.getFeatureExtractor(featureExtractorName); this.log.info("Prepared all Tools."); final TestBinaryClassificationSucceededHandler handler = new TestBinaryClassificationSucceededHandler(); final TestBinaryClassificationCommand command = this.provider.createTestBinaryClassificationCommand(predictionFolderPath, imageEntry, frameSize, errorGenerator, featureExtractor, binaryClassification); command.setOnSucceeded(handler); command.start(); this.log.info("Initiated testing the binary classification."); } private IErrorGenerator getErrorGenerator(String errorGeneratorName) { for (IErrorGenerator generator : this.errorGenerators.getErrorGeneratorListProperty()) { if (errorGeneratorName.equals(generator.getName())) { return generator; } } throw new IllegalStateException("ErrorGenerator not found: " + errorGeneratorName); } private IFeatureExtractor getFeatureExtractor(String featureExtractorName) { for (IFeatureExtractor extractor : this.featureExtractors.getFeatureExtractorsProperty()) { if (featureExtractorName.equals(extractor.getName())) { return extractor; } } throw new IllegalStateException("FeatureExtractor not found: " + featureExtractorName); } /** * Handler for what should happen if the Command was successfull * for testing the binary classification * * @author Minh */ private class TestBinaryClassificationSucceededHandler implements EventHandler<WorkerStateEvent> { @Override public void handle(WorkerStateEvent event) { final BinaryPrediction prediction = (BinaryPrediction) event.getSource().getValue(); binaryPredictions.getBinaryPredictionListProperty().add(prediction); log.info("Added BinaryPrediction to Database."); binaryPredictions.getSelectedBinaryPredictionProperty().set(prediction); log.info("Set current to selected BinaryPrediction."); } } }
false
false
null
null
diff --git a/src/com/oresomecraft/maps/battles/maps/Equator.java b/src/com/oresomecraft/maps/battles/maps/Equator.java index b911af7..ba8c4a6 100644 --- a/src/com/oresomecraft/maps/battles/maps/Equator.java +++ b/src/com/oresomecraft/maps/battles/maps/Equator.java @@ -1,109 +1,110 @@ package com.oresomecraft.maps.battles.maps; import com.oresomecraft.OresomeBattles.api.BattlePlayer; import com.oresomecraft.OresomeBattles.api.Gamemode; import com.oresomecraft.OresomeBattles.api.InvUtils; import com.oresomecraft.OresomeBattles.api.Team; import com.oresomecraft.maps.MapConfig; import com.oresomecraft.maps.battles.BattleMap; import com.oresomecraft.maps.battles.IBattleMap; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; @MapConfig public class Equator extends BattleMap implements IBattleMap, Listener { public Equator() { super.initiate(this, name, fullName, creators, modes); setTDMTime(8); setAllowBuild(false); disableDrops(new Material[]{Material.STAINED_GLASS, Material.LEATHER_HELMET, Material.STONE_SWORD, Material.WOOL}); setAutoSpawnProtection(4); } String name = "equator"; String fullName = "Equator"; String creators = "Afridge1O1, SuperDuckFace, Numinex, XUHAVON, beadycottonwood and ViolentShadow"; Gamemode[] modes = {Gamemode.TDM, Gamemode.CTF}; public void readyTDMSpawns() { redSpawns.add(new Location(w, 53, 75, -24)); redSpawns.add(new Location(w, 26, 74, -50)); redSpawns.add(new Location(w, 60, 75, 12)); blueSpawns.add(new Location(w, -53, 75, 24)); blueSpawns.add(new Location(w, -26, 74, 50)); blueSpawns.add(new Location(w, -60, 74, -12)); Location redFlag = new Location(w, 75, 76, -4); Location blueFlag = new Location(w, -75, 76, 4); setCTFFlags(name, redFlag, blueFlag); setKoTHMonument(new Location(w, 0, 69, 0)); } public void readyFFASpawns() { FFASpawns.add(new Location(w, 2, 84, -48)); FFASpawns.add(new Location(w, -3, 84, 58)); } public void applyInventory(final BattlePlayer p) { Inventory i = p.getInventory(); ItemStack BLUE_GLASS = new ItemStack(Material.STAINED_GLASS, 1, (short) 11); ItemStack RED_GLASS = new ItemStack(Material.STAINED_GLASS, 1, (short) 14); ItemStack LEATHER_CHESTPLATE = new ItemStack(Material.LEATHER_CHESTPLATE, 1); ItemStack LEATHER_PANTS = new ItemStack(Material.LEATHER_LEGGINGS, 1); ItemStack LEATHER_BOOTS = new ItemStack(Material.LEATHER_BOOTS, 1); ItemStack SWORD = new ItemStack(Material.STONE_SWORD, 1); ItemStack BOW = new ItemStack(Material.BOW, 1); ItemStack STEAK = new ItemStack(Material.COOKED_BEEF, 5); ItemStack EXP = new ItemStack(Material.EXP_BOTTLE, 5); ItemStack HEALTH = new ItemStack(Material.GOLDEN_APPLE, 3); ItemStack ARROWS = new ItemStack(Material.ARROW, 64); InvUtils.colourArmourAccordingToTeam(p, new ItemStack[]{LEATHER_CHESTPLATE, LEATHER_PANTS, LEATHER_BOOTS}); p.getInventory().setBoots(LEATHER_BOOTS); p.getInventory().setLeggings(LEATHER_PANTS); p.getInventory().setChestplate(LEATHER_CHESTPLATE); if (p.getTeamType() == Team.TDM_RED) p.getInventory().setHelmet(RED_GLASS); if (p.getTeamType() == Team.TDM_BLUE) p.getInventory().setHelmet(BLUE_GLASS); i.setItem(0, SWORD); i.setItem(1, BOW); i.setItem(2, STEAK); i.setItem(3, HEALTH); i.setItem(4, EXP); i.setItem(10, ARROWS); } // Region. (Top corner block and bottom corner block. // Top left corner. public int x1 = 103; public int y1 = 115; public int z1 = 103; //Bottom right corner. public int x2 = -103; public int y2 = 0; public int z2 = -103; @EventHandler(ignoreCancelled = false) public void onBlockBreak(BlockBreakEvent event) { if (event.getBlock().getLocation().getWorld().getName().equals(name)) { + event.setCancelled(true); if (event.getBlock().getType().equals(Material.WOOL)) { event.getBlock().getDrops().clear(); } } } } diff --git a/src/com/oresomecraft/maps/battles/maps/Mantle.java b/src/com/oresomecraft/maps/battles/maps/Mantle.java index 5de1ee3..ae8f787 100755 --- a/src/com/oresomecraft/maps/battles/maps/Mantle.java +++ b/src/com/oresomecraft/maps/battles/maps/Mantle.java @@ -1,92 +1,93 @@ package com.oresomecraft.maps.battles.maps; import com.oresomecraft.OresomeBattles.api.BattlePlayer; import com.oresomecraft.OresomeBattles.api.Gamemode; import com.oresomecraft.maps.MapConfig; import com.oresomecraft.maps.battles.BattleMap; import com.oresomecraft.maps.battles.IBattleMap; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; @MapConfig public class Mantle extends BattleMap implements IBattleMap, Listener { public Mantle() { super.initiate(this, name, fullName, creators, modes); setAllowBuild(false); setAutoSpawnProtection(3); disableDrops(new Material[]{Material.WOOL}); } String name = "mantle"; String fullName = "The Mantle"; String creators = "__R3, eli12310987, chillhill3, MiCkEyMiCE and FaazM"; Gamemode[] modes = {Gamemode.CTF}; public void readyTDMSpawns() { redSpawns.add(new Location(w, -34, 84, 169)); blueSpawns.add(new Location(w, -34, 84, -29)); Location redFlag = new Location(w, -35, 86, 121); Location blueFlag = new Location(w, -35, 86, 17); setCTFFlags(name, redFlag, blueFlag); } public void readyFFASpawns() { FFASpawns.add(new Location(w, -16, 84, 128)); FFASpawns.add(new Location(w, -50, 84, 11)); } public void applyInventory(final BattlePlayer p) { Inventory i = p.getInventory(); ItemStack HEALTH_POTION = new ItemStack(Material.GOLDEN_APPLE, 1); ItemStack STEAK = new ItemStack(Material.COOKED_BEEF, 3); ItemStack BOW = new ItemStack(Material.BOW, 1); ItemStack ARROWS = new ItemStack(Material.ARROW, 64); ItemStack IRON_HELMET = new ItemStack(Material.IRON_HELMET, 1); ItemStack IRON_CHESTPLATE = new ItemStack(Material.IRON_CHESTPLATE, 1); ItemStack IRON_PANTS = new ItemStack(Material.IRON_LEGGINGS, 1); ItemStack IRON_BOOTS = new ItemStack(Material.IRON_BOOTS, 1); ItemStack IRON_SWORD = new ItemStack(Material.IRON_SWORD, 1); p.getInventory().setBoots(IRON_BOOTS); p.getInventory().setLeggings(IRON_PANTS); p.getInventory().setChestplate(IRON_CHESTPLATE); p.getInventory().setHelmet(IRON_HELMET); i.setItem(0, IRON_SWORD); i.setItem(1, BOW); i.setItem(2, STEAK); i.setItem(3, HEALTH_POTION); i.setItem(10, ARROWS); } // Region. (Top corner block and bottom corner block. // Top left corner. public int x1 = -85; public int y1 = 65; public int z1 = 0; //Bottom right corner. public int x2 = 15; public int y2 = 108; public int z2 = 138; - @EventHandler + @EventHandler(ignoreCancelled = false) public void onWoolDrop(BlockBreakEvent event) { if (event.getBlock().getLocation().getWorld().getName().equals(name)) { + event.setCancelled(true); if (event.getBlock().getType().equals(Material.WOOL)) { event.getBlock().getDrops().clear(); } } } }
false
false
null
null
diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/jmx/ConnectionView.java b/activemq-core/src/main/java/org/apache/activemq/broker/jmx/ConnectionView.java index 4b2978d7a..17ac3da48 100755 --- a/activemq-core/src/main/java/org/apache/activemq/broker/jmx/ConnectionView.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/jmx/ConnectionView.java @@ -1,80 +1,84 @@ /** * 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.activemq.broker.jmx; import org.apache.activemq.broker.Connection; public class ConnectionView implements ConnectionViewMBean { private final Connection connection; public ConnectionView(Connection connection) { this.connection = connection; } public void start() throws Exception { connection.start(); } public void stop() throws Exception { connection.stop(); } /** * @return true if the Connection is slow */ public boolean isSlow() { return connection.isSlow(); } /** * @return if after being marked, the Connection is still writing */ public boolean isBlocked() { return connection.isBlocked(); } /** * @return true if the Connection is connected */ public boolean isConnected() { return connection.isConnected(); } /** * @return true if the Connection is active */ public boolean isActive() { return connection.isActive(); } + public int getDispatchQueueSize() { + return connection.getDispatchQueueSize(); + } + /** * Resets the statistics */ public void resetStatistics() { connection.getStatistics().reset(); } public String getRemoteAddress() { return connection.getRemoteAddress(); } public String getConnectionId() { return connection.getConnectionId(); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/jmx/ConnectionViewMBean.java b/activemq-core/src/main/java/org/apache/activemq/broker/jmx/ConnectionViewMBean.java index af1027e10..64bfd0cbb 100755 --- a/activemq-core/src/main/java/org/apache/activemq/broker/jmx/ConnectionViewMBean.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/jmx/ConnectionViewMBean.java @@ -1,60 +1,67 @@ /** * 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.activemq.broker.jmx; import org.apache.activemq.Service; public interface ConnectionViewMBean extends Service { /** * @return true if the Connection is slow */ @MBeanInfo("Connection is slow.") boolean isSlow(); /** * @return if after being marked, the Connection is still writing */ @MBeanInfo("Connection is blocked.") boolean isBlocked(); /** * @return true if the Connection is connected */ @MBeanInfo("Connection is connected to the broker.") boolean isConnected(); /** * @return true if the Connection is active */ @MBeanInfo("Connection is active (both connected and receiving messages).") boolean isActive(); /** * Resets the statistics */ @MBeanInfo("Resets the statistics") void resetStatistics(); /** * Returns the source address for this connection * - * @return the souce address for this connection + * @return the source address for this connection */ @MBeanInfo("Source address for this connection") String getRemoteAddress(); + /** + * Returns the number of messages to be dispatched to this connection + * @return the number of messages pending dispatch + */ + @MBeanInfo("The number of messages pending dispatch") + public int getDispatchQueueSize(); + }
false
false
null
null
diff --git a/jersey/src/impl/com/sun/jersey/impl/provider/header/CacheControlProvider.java b/jersey/src/impl/com/sun/jersey/impl/provider/header/CacheControlProvider.java index 75b819a34..698f98ec8 100644 --- a/jersey/src/impl/com/sun/jersey/impl/provider/header/CacheControlProvider.java +++ b/jersey/src/impl/com/sun/jersey/impl/provider/header/CacheControlProvider.java @@ -1,135 +1,138 @@ /* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can obtain * a copy of the License at https://jersey.dev.java.net/CDDL+GPL.html * or jersey/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at jersey/legal/LICENSE.txt. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: "Portions Copyrighted [year] * [name of copyright owner]" * * Contributor(s): * * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package com.sun.jersey.impl.provider.header; import com.sun.jersey.spi.HeaderDelegateProvider; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.ws.rs.core.CacheControl; /** * * @author [email protected] */ public final class CacheControlProvider implements HeaderDelegateProvider<CacheControl> { private static Pattern WHITESPACE = Pattern.compile("\\s"); public boolean supports(Class<?> type) { return type == CacheControl.class; } public String toString(CacheControl header) { StringBuffer b = new StringBuffer(); if (header.isPublic()) appendWithSeparator(b, "public"); if (header.isPrivate()) appendQuotedWithSeparator(b, "private", buildListValue(header.getPrivateFields())); if (header.isNoCache()) appendQuotedWithSeparator(b, "no-cache", buildListValue(header.getNoCacheFields())); if (header.isNoStore()) appendWithSeparator(b, "no-store"); if (header.isNoTransform()) appendWithSeparator(b, "no-transform"); if (header.isMustRevalidate()) appendWithSeparator(b, "must-revalidate"); if (header.isProxyRevalidate()) appendWithSeparator(b, "proxy-revalidate"); if (header.getMaxAge() != -1) appendWithSeparator(b, "max-age", header.getMaxAge()); if (header.getSMaxAge() != -1) appendWithSeparator(b, "s-maxage", header.getSMaxAge()); for (Map.Entry<String, String> e : header.getCacheExtension().entrySet()) { appendWithSeparator(b, e.getKey(), quoteIfWhitespace(e.getValue())); } return b.toString(); } public CacheControl fromString(String header) { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException( + "The CacheControl type is designed only for Cache-Control response headers. " + + "It is not required that such a header be parsed by an end-user application " + + "to an instance of CacheControl"); } private void appendWithSeparator(StringBuffer b, String field) { if (b.length()>0) b.append(", "); b.append(field); } private void appendQuotedWithSeparator(StringBuffer b, String field, String value) { appendWithSeparator(b, field); if (value != null && value.length() > 0) { b.append("=\""); b.append(value); b.append("\""); } } private void appendWithSeparator(StringBuffer b, String field, String value) { appendWithSeparator(b, field); if (value != null && value.length() > 0) { b.append("="); b.append(value); } } private void appendWithSeparator(StringBuffer b, String field, int value) { appendWithSeparator(b, field); b.append("="); b.append(value); } private String buildListValue(List<String> values) { StringBuffer b = new StringBuffer(); for (String value: values) appendWithSeparator(b, value); return b.toString(); } private String quoteIfWhitespace(String value) { if (value==null) return null; Matcher m = WHITESPACE.matcher(value); if (m.find()) { return "\""+value+"\""; } return value; } }
true
false
null
null