answer
stringlengths
17
10.2M
package com.yahoo.vespa.hosted.controller.rotation; import com.yahoo.collections.Pair; import com.yahoo.config.provision.ClusterSpec; import com.yahoo.config.provision.Environment; import com.yahoo.vespa.hosted.controller.Application; import com.yahoo.vespa.hosted.controller.ApplicationController; import com.yahoo.vespa.hosted.controller.application.AssignedRotation; import com.yahoo.vespa.hosted.controller.application.Endpoint; import com.yahoo.vespa.hosted.controller.application.EndpointId; import com.yahoo.vespa.hosted.controller.persistence.CuratorDb; import com.yahoo.vespa.hosted.rotation.config.RotationsConfig; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Function; import java.util.logging.Logger; import java.util.stream.Collectors; import static java.util.stream.Collectors.collectingAndThen; /** * The rotation repository offers global rotations to Vespa applications. * * The list of rotations comes from RotationsConfig, which is set in the controller's services.xml. * * @author Oyvind Gronnesby * @author mpolden */ public class RotationRepository { private static final Logger log = Logger.getLogger(RotationRepository.class.getName()); private final Map<RotationId, Rotation> allRotations; private final ApplicationController applications; private final CuratorDb curator; public RotationRepository(RotationsConfig rotationsConfig, ApplicationController applications, CuratorDb curator) { this.allRotations = from(rotationsConfig); this.applications = applications; this.curator = curator; } /** Acquire a exclusive lock for this */ public RotationLock lock() { return new RotationLock(curator.lockRotations()); } /** Get rotation for given application */ public Optional<Rotation> getRotation(Application application) { return application.rotations().stream().map(allRotations::get).findFirst(); } /** Get rotation for the given rotationId */ public Optional<Rotation> getRotation(RotationId rotationId) { return Optional.of(allRotations.get(rotationId)); } /** * Returns a rotation for the given application * * If a rotation is already assigned to the application, that rotation will be returned. * If no rotation is assigned, return an available rotation. The caller is responsible for assigning the rotation. * * @param application The application requesting a rotation * @param lock Lock which must be acquired by the caller */ public Rotation getOrAssignRotation(Application application, RotationLock lock) { if (! application.rotations().isEmpty()) { return allRotations.get(application.rotations().get(0)); } if (application.deploymentSpec().globalServiceId().isEmpty()) { throw new IllegalArgumentException("global-service-id is not set in deployment spec"); } long productionZones = application.deploymentSpec().zones().stream() .filter(zone -> zone.deploysTo(Environment.prod)) .count(); if (productionZones < 2) { throw new IllegalArgumentException("global-service-id is set but less than 2 prod zones are defined"); } return findAvailableRotation(application, lock); } public List<AssignedRotation> getOrAssignRotations(Application application, RotationLock lock) { if (application.deploymentSpec().globalServiceId().isPresent() && ! application.deploymentSpec().endpoints().isEmpty()) { throw new IllegalArgumentException("Cannot provision rotations with both global-service-id and 'endpoints'"); } // Support the older case of setting global-service-id if (application.deploymentSpec().globalServiceId().isPresent()) { final var regions = application.deploymentSpec().zones().stream() .flatMap(zone -> zone.region().stream()) .collect(Collectors.toSet()); final var rotation = getOrAssignRotation(application, lock); return List.of( new AssignedRotation( new ClusterSpec.Id(application.deploymentSpec().globalServiceId().get()), EndpointId.default_(), rotation.id(), regions ) ); } final var availableRotations = new ArrayList<>(availableRotations(lock).values()); final var assignments = application.assignedRotations().stream() .collect( Collectors.toMap( AssignedRotation::endpointId, Function.identity(), (a, b) -> { throw new IllegalStateException("Duplicate entries: " + a + ", " + b); }, LinkedHashMap::new ) ); application.deploymentSpec().endpoints().stream() .filter(endpoint -> ! assignments.containsKey(new EndpointId(endpoint.endpointId()))) .map(endpoint -> { return new AssignedRotation( new ClusterSpec.Id(endpoint.containerId()), EndpointId.of(endpoint.endpointId()), availableRotations.remove(0).id(), endpoint.regions() ); }) .forEach(assignment -> { assignments.put(assignment.endpointId(), assignment); }); return List.copyOf(assignments.values()); } /** * Returns all unassigned rotations * @param lock Lock which must be acquired by the caller */ public Map<RotationId, Rotation> availableRotations(@SuppressWarnings("unused") RotationLock lock) { List<RotationId> assignedRotations = applications.asList().stream() .filter(application -> ! application.rotations().isEmpty()) .flatMap(application -> application.rotations().stream()) .collect(Collectors.toList()); Map<RotationId, Rotation> unassignedRotations = new LinkedHashMap<>(this.allRotations); assignedRotations.forEach(unassignedRotations::remove); return Collections.unmodifiableMap(unassignedRotations); } private Rotation findAvailableRotation(Application application, RotationLock lock) { Map<RotationId, Rotation> availableRotations = availableRotations(lock); if (availableRotations.isEmpty()) { throw new IllegalStateException("Unable to assign global rotation to " + application.id() + " - no rotations available"); } // Return first available rotation RotationId rotation = availableRotations.keySet().iterator().next(); log.info(String.format("Offering %s to application %s", rotation, application.id())); return allRotations.get(rotation); } /** Returns a immutable map of rotation ID to rotation sorted by rotation ID */ private static Map<RotationId, Rotation> from(RotationsConfig rotationConfig) { return rotationConfig.rotations().entrySet().stream() .map(entry -> new Rotation(new RotationId(entry.getKey()), entry.getValue().trim())) .sorted(Comparator.comparing(rotation -> rotation.id().asString())) .collect(collectingAndThen(Collectors.toMap(Rotation::id, rotation -> rotation, (k, v) -> v, LinkedHashMap::new), Collections::unmodifiableMap)); } }
package com.jayway.maven.plugins.android.common; import com.google.common.io.PatternFilenameFilter; import com.jayway.maven.plugins.android.AbstractAndroidMojo; import com.jayway.maven.plugins.android.AndroidNdk; import com.jayway.maven.plugins.android.phase09package.ApklibMojo; import org.apache.commons.io.FileUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.resolver.filter.AndArtifactFilter; import org.apache.maven.artifact.resolver.filter.ArtifactFilter; import org.apache.maven.artifact.resolver.filter.ExcludesArtifactFilter; import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter; import org.apache.maven.model.Dependency; import org.apache.maven.model.Exclusion; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import org.apache.maven.shared.dependency.graph.DependencyGraphBuilder; import org.apache.maven.shared.dependency.graph.DependencyNode; import org.apache.maven.shared.dependency.graph.traversal.CollectingDependencyNodeVisitor; import java.io.File; import java.io.FileNotFoundException; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; import java.util.Scanner; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.jayway.maven.plugins.android.common.AndroidExtension.APKLIB; /** * @author Johan Lindquist */ public class NativeHelper { public static final int NDK_REQUIRED_VERSION = 7; private MavenProject project; private DependencyGraphBuilder dependencyGraphBuilder; private Log log; public NativeHelper( MavenProject project, DependencyGraphBuilder dependencyGraphBuilder, Log log ) { this.project = project; this.dependencyGraphBuilder = dependencyGraphBuilder; this.log = log; } public static boolean hasStaticNativeLibraryArtifact( Set<Artifact> resolveNativeLibraryArtifacts, File unpackDirectory, String ndkArchitecture ) { for ( Artifact resolveNativeLibraryArtifact : resolveNativeLibraryArtifacts ) { if ( Const.ArtifactType.NATIVE_IMPLEMENTATION_ARCHIVE.equals( resolveNativeLibraryArtifact.getType() ) ) { return true; } if ( APKLIB.equals( resolveNativeLibraryArtifact.getType() ) ) { File[] aFiles = listNativeFiles( resolveNativeLibraryArtifact, unpackDirectory, ndkArchitecture, true ); if ( aFiles != null && aFiles.length > 0 ) { return true; } } } return false; } public static boolean hasSharedNativeLibraryArtifact( Set<Artifact> resolveNativeLibraryArtifacts, File unpackDirectory, String ndkArchitecture ) { for ( Artifact resolveNativeLibraryArtifact : resolveNativeLibraryArtifacts ) { if ( Const.ArtifactType.NATIVE_SYMBOL_OBJECT.equals( resolveNativeLibraryArtifact.getType() ) ) { return true; } if ( APKLIB.equals( resolveNativeLibraryArtifact.getType() ) ) { File[] soFiles = listNativeFiles( resolveNativeLibraryArtifact, unpackDirectory, ndkArchitecture, false ); if ( soFiles != null && soFiles.length > 0 ) { return true; } } } return false; } public static File[] listNativeFiles( Artifact a, File unpackDirectory, final String ndkArchitecture, final boolean staticLibrary ) { File libsFolder = new File( AbstractAndroidMojo.getLibraryUnpackDirectory( unpackDirectory, a ), ApklibMojo.NATIVE_LIBRARIES_FOLDER + File.separator + ndkArchitecture ); if ( libsFolder.exists() ) { File[] libFiles = libsFolder.listFiles( new FilenameFilter() { public boolean accept( final File dir, final String name ) { return name.startsWith( "lib" ) && name.endsWith( ( staticLibrary ? ".a" : ".so" ) ); } } ); return libFiles; } return null; } public Set<Artifact> getNativeDependenciesArtifacts( File unpackDirectory, boolean sharedLibraries ) throws MojoExecutionException { log.debug( "Finding native dependencies. UnpackFolder=" + unpackDirectory + " shared=" + sharedLibraries ); final Set<Artifact> filteredArtifacts = new LinkedHashSet<Artifact>(); final Set<Artifact> allArtifacts = new LinkedHashSet<Artifact>(); // Add all dependent artifacts declared in the pom file // Note: The result of project.getDependencyArtifacts() can be an UnmodifiableSet so we // have created our own above and add to that. allArtifacts.addAll( project.getDependencyArtifacts() ); // Add all attached artifacts as well - this could come from the NDK mojo for example allArtifacts.addAll( project.getAttachedArtifacts() ); for ( Artifact artifact : allArtifacts ) { log.debug( "Checking artifact : " + artifact ); // A null value in the scope indicates that the artifact has been attached // as part of a previous build step (NDK mojo) if ( isNativeLibrary( sharedLibraries, artifact.getType() ) && artifact.getScope() == null ) { // Including attached artifact log.debug( "Including attached artifact: " + artifact + ". Artifact scope is not set." ); filteredArtifacts.add( artifact ); } else { if ( isNativeLibrary( sharedLibraries, artifact.getType() ) && ( Artifact.SCOPE_COMPILE.equals( artifact.getScope() ) || Artifact.SCOPE_RUNTIME .equals( artifact.getScope() ) ) ) { log.debug( "Including attached artifact: " + artifact + ". Artifact scope is Compile or Runtime." ); filteredArtifacts.add( artifact ); } else { if ( APKLIB.equals( artifact.getType() ) ) { // Check if the artifact contains a libs folder - if so, include it in the list File libsFolder = new File( AbstractAndroidMojo.getLibraryUnpackDirectory( unpackDirectory, artifact ), "libs" ); // make sure we ignore libs folders that only contain JARs // The regular expression filters out all file paths ending with '.jar' or '.JAR', // so all native libs remain if ( libsFolder.exists() && libsFolder.list( new PatternFilenameFilter( "^.*(?<!(?i)\\.jar)$" ) ).length > 0 ) { log.debug( "Including attached artifact: " + artifact + ". Artifact is APKLIB." ); filteredArtifacts.add( artifact ); } } } } } Set<Artifact> transitiveArtifacts = processTransitiveDependencies( project.getDependencies(), sharedLibraries ); filteredArtifacts.addAll( transitiveArtifacts ); return filteredArtifacts; } private boolean isNativeLibrary( boolean sharedLibraries, String artifactType ) { return ( sharedLibraries ? Const.ArtifactType.NATIVE_SYMBOL_OBJECT.equals( artifactType ) : Const.ArtifactType.NATIVE_IMPLEMENTATION_ARCHIVE.equals( artifactType ) ); } private Set<Artifact> processTransitiveDependencies( List<Dependency> dependencies, boolean sharedLibraries ) throws MojoExecutionException { final Set<Artifact> transitiveArtifacts = new LinkedHashSet<Artifact>(); for ( Dependency dependency : dependencies ) { if ( ! Artifact.SCOPE_PROVIDED.equals( dependency.getScope() ) && ! dependency.isOptional() ) { transitiveArtifacts.addAll( processTransitiveDependencies( dependency, sharedLibraries ) ); } } return transitiveArtifacts; } private Set<Artifact> processTransitiveDependencies( Dependency dependency, boolean sharedLibraries ) throws MojoExecutionException { log.debug( "Processing transitive dependencies for : " + dependency ); try { final Set<Artifact> artifacts = new LinkedHashSet<Artifact>(); final List<String> exclusionPatterns = new ArrayList<String>(); if ( dependency.getExclusions() != null && ! dependency.getExclusions().isEmpty() ) { for ( final Exclusion exclusion : dependency.getExclusions() ) { exclusionPatterns.add( exclusion.getGroupId() + ":" + exclusion.getArtifactId() ); } } final ArtifactFilter optionalFilter = new ArtifactFilter() { @Override public boolean include( Artifact artifact ) { return !artifact.isOptional(); } }; final ArtifactFilter filter = new AndArtifactFilter( Arrays.asList( new ExcludesArtifactFilter( exclusionPatterns ), new AndArtifactFilter( Arrays.asList( new ScopeArtifactFilter( "compile" ), new ScopeArtifactFilter( "runtime" ), new ScopeArtifactFilter( "test" ), optionalFilter ) ) ) ); final DependencyNode node = dependencyGraphBuilder.buildDependencyGraph( project, filter ); final CollectingDependencyNodeVisitor collectingVisitor = new CollectingDependencyNodeVisitor(); collectingVisitor.visit( node ); final List<DependencyNode> dependencies = collectingVisitor.getNodes(); for ( final DependencyNode dep : dependencies ) { final boolean isNativeLibrary = isNativeLibrary( sharedLibraries, dep.getArtifact().getType() ); log.debug( "Processing library : " + dep.getArtifact() + " isNative=" + isNativeLibrary ); if ( isNativeLibrary ) { artifacts.add( dep.getArtifact() ); } } return artifacts; } catch ( Exception e ) { throw new MojoExecutionException( "Error while processing transitive dependencies", e ); } } public static void validateNDKVersion( File ndkHomeDir ) throws MojoExecutionException { final File ndkVersionFile = new File( ndkHomeDir, "RELEASE.TXT" ); if ( ! ndkVersionFile.exists() ) { throw new MojoExecutionException( "Could not locate RELEASE.TXT in the Android NDK base directory '" + ndkHomeDir.getAbsolutePath() + "'. Please verify your setup! " + AndroidNdk.PROPER_NDK_HOME_DIRECTORY_MESSAGE ); } try { String versionStr = FileUtils.readFileToString( ndkVersionFile ); validateNDKVersion( NDK_REQUIRED_VERSION, versionStr ); } catch ( Exception e ) { throw new MojoExecutionException( "Error while extracting NDK version from '" + ndkVersionFile.getAbsolutePath() + "'. Please verify your setup! " + AndroidNdk.PROPER_NDK_HOME_DIRECTORY_MESSAGE ); } } public static void validateNDKVersion( int desiredVersion, String versionStr ) throws MojoExecutionException { int version = 0; if ( versionStr != null ) { versionStr = versionStr.trim(); Pattern pattern = Pattern.compile( "[r]([0-9]{1,3})([a-z]{0,1}).*" ); Matcher m = pattern.matcher( versionStr ); if ( m.matches() ) { final String group = m.group( 1 ); version = Integer.parseInt( group ); } } if ( version < desiredVersion ) { throw new MojoExecutionException( "You are running an old NDK (version " + versionStr + "), please update " + "to at least r'" + desiredVersion + "' or later" ); } } public static String[] getAppAbi( File applicationMakefile ) { Scanner scanner = null; try { if ( applicationMakefile != null && applicationMakefile.exists() ) { scanner = new Scanner( applicationMakefile ); while ( scanner.hasNextLine( ) ) { String line = scanner.nextLine().trim(); if ( line.startsWith( "APP_ABI" ) ) { return line.substring( line.indexOf( ":=" ) + 2 ).trim().split( " " ); } } } } catch ( FileNotFoundException e ) { // do nothing } finally { if ( scanner != null ) { scanner.close(); } } return null; } /** Extracts, if embedded correctly, the artifacts architecture from its classifier. The format of the * classifier, if including the architecture is &lt;architecture&gt;-&lt;classifier&gt;. If no * architecture is embedded in the classifier, 'armeabi' will be returned. * * * @param artifact The artifact to retrieve the classifier from. * @param defaultArchitecture The architecture to return if can't be resolved from the classifier * @return The retrieved architecture, or <code>defaulArchitecture</code> if not resolveable */ public static String extractArchitectureFromArtifact( Artifact artifact, final String defaultArchitecture ) { String classifier = artifact.getClassifier(); if ( classifier != null ) { // We loop backwards to catch the case where the classifier is // potentially armeabi-v7a - this collides with armeabi if looping // through this loop in the other direction for ( int i = AndroidNdk.NDK_ARCHITECTURES.length - 1; i >= 0; i { String ndkArchitecture = AndroidNdk.NDK_ARCHITECTURES[i]; if ( classifier.startsWith( ndkArchitecture ) ) { return ndkArchitecture; } } } // Default case is to return the default architecture return defaultArchitecture; } /** Attempts to extract, from various sources, the applicable list of NDK architectures to support * as part of the build. * <br/> * <br/> * It retrieves the list from the following places: * <ul> * <li>ndkArchitecture parameter</li> * <li>projects Application.mk - currently only a single architecture is supported by this method</li> * </ul> * * * @param ndkArchitectures Space separated list of architectures. This may be from configuration or otherwise * @param applicationMakefile The makefile (Application.mk) to retrieve the list from. * @param basedir Directory the build is running from (to resolve files) * * @return List of architectures to be supported by build. * * @throws MojoExecutionException */ public static String[] getNdkArchitectures( final String ndkArchitectures, final String applicationMakefile, final File basedir ) throws MojoExecutionException { // if there is a specified ndk architecture, return it if ( ndkArchitectures != null ) { return ndkArchitectures.split( " " ); } // if there is no application makefile specified, let's use the default one String applicationMakefileToUse = applicationMakefile; if ( applicationMakefileToUse == null ) { applicationMakefileToUse = "jni/Application.mk"; } // now let's see if the application file exists File appMK = new File( basedir, applicationMakefileToUse ); if ( appMK.exists() ) { String[] foundNdkArchitectures = getAppAbi( appMK ); if ( foundNdkArchitectures != null ) { return foundNdkArchitectures; } } // return a default ndk architecture return new String[] { "armeabi" }; } /** Helper method for determining whether the specified architecture is a match for the * artifact using its classifier. When used for architecture matching, the classifier must be * formed by &lt;architecture&gt;-&lt;classifier&gt;. * If the artifact is legacy and defines no valid architecture, the artifact architecture will * default to <strong>armeabi</strong>. * * @param ndkArchitecture Architecture to check for match * @param artifact Artifact to check the classifier match for * @return True if the architecture matches, otherwise false */ public static boolean artifactHasHardwareArchitecture( Artifact artifact, String ndkArchitecture, String defaultArchitecture ) { return Const.ArtifactType.NATIVE_SYMBOL_OBJECT.equals( artifact.getType() ) && ndkArchitecture.equals( extractArchitectureFromArtifact( artifact, defaultArchitecture ) ); } }
package org.onetwo.boot.core.web.mvc.exception; import java.util.Collections; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Set; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.apache.commons.lang.builder.ReflectionToStringBuilder; import org.onetwo.boot.core.web.service.impl.ExceptionMessageAccessor; import org.onetwo.boot.utils.BootUtils; import org.onetwo.common.exception.AuthenticationException; import org.onetwo.common.exception.BaseException; import org.onetwo.common.exception.ExceptionCodeMark; import org.onetwo.common.exception.HeaderableException; import org.onetwo.common.exception.NoAuthorizationException; import org.onetwo.common.exception.NotLoginException; import org.onetwo.common.exception.ServiceException; import org.onetwo.common.exception.SystemErrorCode; import org.onetwo.common.log.JFishLoggerFactory; import org.onetwo.common.spring.validator.ValidatorUtils; import org.onetwo.common.utils.LangUtils; import org.onetwo.common.utils.StringUtils; import org.onetwo.common.web.utils.WebHolder; import org.onetwo.dbm.exception.DbmException; import org.slf4j.Logger; import org.springframework.beans.TypeMismatchException; import org.springframework.http.HttpStatus; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.web.bind.MethodArgumentNotValidException; /**** * TODO: ExceptionCodeMarkErrorType * ErrorTypemessage * SystemErrorCode * @author wayshall * */ public interface ExceptionMessageFinder { default ErrorMessage getErrorMessage(Exception throwable, boolean alwaysLogErrorDetail){ String errorCode = ""; String errorMsg = ""; Object[] errorArgs = null; // String defaultViewName = ExceptionView.UNDEFINE; boolean detail = true; // boolean authentic = false; ErrorMessage error = new ErrorMessage(throwable); boolean findMsgByCode = true; Exception ex = throwable; if(isInternalError(ex)){ ex = LangUtils.getCauseException(ex, ServiceException.class); } /*if(ex instanceof MaxUploadSizeExceededException){ defaultViewName = ExceptionView.UNDEFINE; errorCode = MAX_UPLOAD_SIZE_ERROR;//MvcError.MAX_UPLOAD_SIZE_ERROR; // errorArgs = new Object[]{this.mvcSetting.getMaxUploadSize()}; }else */ if(ex instanceof ExceptionCodeMark){//serviceException && businessException ExceptionCodeMark codeMark = (ExceptionCodeMark) ex; errorCode = codeMark.getCode(); errorArgs = codeMark.getArgs(); Optional<Integer> statusCode = codeMark.getStatusCode(); if(statusCode.isPresent()){ error.setHttpStatus(HttpStatus.valueOf(statusCode.get())); }else if(ex instanceof AuthenticationException){ detail = false; error.setHttpStatus(HttpStatus.UNAUTHORIZED); }else if(ex instanceof ServiceException){ detail = ((ServiceException)ex).getCause()!=null; //ServiceException error.setHttpStatus(HttpStatus.OK); }else{ //ExceptionCodeMark error.setHttpStatus(HttpStatus.OK); } findMsgByCode = StringUtils.isNotBlank(errorCode);// && !codeMark.isDefaultErrorCode(); }else if(BootUtils.isDmbPresent() && DbmException.class.isInstance(ex)){ // defaultViewName = ExceptionView.UNDEFINE; // errorCode = JFishErrorCode.ORM_ERROR;//find message from resouce error.setHttpStatus(HttpStatus.INTERNAL_SERVER_ERROR); // Throwable t = LangUtils.getFirstNotJFishThrowable(ex); }else if(ex instanceof BaseException){ // defaultViewName = ExceptionView.UNDEFINE; // errorCode = SystemErrorCode.DEFAULT_SYSTEM_ERROR_CODE;//find message from resouce error.setHttpStatus(HttpStatus.INTERNAL_SERVER_ERROR); // Throwable t = LangUtils.getFirstNotJFishThrowable(ex); }else if(TypeMismatchException.class.isInstance(ex)){ // errorCode = SystemErrorCode.DEFAULT_SYSTEM_ERROR_CODE; errorMsg = "parameter convert error!"; errorCode = SystemErrorCode.ERR_PARAMETER_CONVERT; error.setHttpStatus(HttpStatus.BAD_REQUEST); }else if(ex instanceof ConstraintViolationException){ ConstraintViolationException cex = (ConstraintViolationException) ex; Set<ConstraintViolation<?>> constrants = cex.getConstraintViolations(); errorMsg = ValidatorUtils.toMessages(constrants); findMsgByCode = false; error.setHttpStatus(HttpStatus.BAD_REQUEST); }else if(ex instanceof BindException){ // ModelAttributeMethodProcessor#resolveArgumentBindException, ErrorsBindingResultBindException BindingResult br = ((BindException)ex).getBindingResult(); errorMsg = ValidatorUtils.asString(br); findMsgByCode = false; detail = false; errorCode = SystemErrorCode.ERR_PARAMETER_VALIDATE; error.setHttpStatus(HttpStatus.BAD_REQUEST); }*//*else if(BeanCreationException.class.isInstance(ex)){ }/*else if(ex instanceof ObjectOptimisticLockingFailureException){ errorCode = ObjectOptimisticLockingFailureException.class.getSimpleName(); }*/else if(ex instanceof MethodArgumentNotValidException){ MethodArgumentNotValidException mve = (MethodArgumentNotValidException) ex; BindingResult br = mve.getBindingResult(); errorMsg = ValidatorUtils.asString(br); findMsgByCode = false; detail = false; errorCode = SystemErrorCode.ERR_PARAMETER_VALIDATE; error.setHttpStatus(HttpStatus.BAD_REQUEST); }else{ errorCode = SystemErrorCode.UNKNOWN; error.setHttpStatus(HttpStatus.INTERNAL_SERVER_ERROR); } detail = alwaysLogErrorDetail?true:detail; // error.setMesage(errorMsg); error.setDetail(detail); if(StringUtils.isBlank(errorCode)){ errorCode = SystemErrorCode.UNKNOWN;//ex.getClass().getName(); } //codefindMessage error.setCode(errorCode); if(findMsgByCode){ errorMsg = findMessage(findMsgByCode, error, errorArgs); } if(StringUtils.isBlank(errorMsg)){ errorMsg = LangUtils.getCauseServiceException(ex).getMessage(); } if(ex instanceof HeaderableException){ Optional<HttpServletResponse> reponse = WebHolder.getResponse(); HeaderableException he = (HeaderableException)ex; if(reponse.isPresent() && he.getHeaders().isPresent()){ he.getHeaders().get().forEach((name, value)->{ reponse.get().setHeader(name, value.toString()); }); } } error.setCode(errorCode); // detail = product?detail:true; error.setMesage(errorMsg); // error.setDetail(detail); // error.setViewName(viewName); // error.setAuthentic(authentic); return error; } default String findMessage(boolean findMsgByCode, ErrorMessage error, Object[] errorArgs){ String errorMsg = null; String errorCode = error.getCode(); Exception ex = error.getException(); // errorMsg = getMessage(errorCode, errorArgs, "", getLocale()); if(isInternalError(ex)){ errorMsg = findMessageByThrowable(ex, errorArgs)+" "+LangUtils.getCauseServiceException(ex).getMessage(); }else if(SystemErrorCode.UNKNOWN.equals(errorCode)){ errorMsg = findMessageByThrowable(ex, errorArgs); }else{ errorMsg = findMessageByErrorCode(errorCode, errorArgs); } // defaultViewName = ExceptionView.CODE_EXCEPTON; // defaultViewName = ExceptionView.UNDEFINE; return errorMsg; } default boolean isInternalError(Exception ex){ if(BootUtils.isHystrixErrorPresent()){ String name = ex.getClass().getName(); return name.endsWith("HystrixRuntimeException") || name.endsWith("HystrixBadRequestException"); } return false; } default Locale getLocale(){ return BootUtils.getDefaultLocale(); } default String findMessageByErrorCode(String errorCode, Object...errorArgs){ String errorMsg = getMessage(errorCode, errorArgs, "", getLocale()); return errorMsg; } default String findMessageByThrowable(Throwable e, Object...errorArgs){ String errorMsg = findMessageByErrorCode(e.getClass().getName(), errorArgs); if(StringUtils.isBlank(errorMsg)){ errorMsg = findMessageByErrorCode(e.getClass().getSimpleName(), errorArgs); } return errorMsg; } default String getMessage(String code, Object[] args, String defaultMessage, Locale locale){ ExceptionMessageAccessor exceptionMessageAccessor = getExceptionMessageAccessor(); if(exceptionMessageAccessor==null) return ""; try { // return exceptionMessage.getMessage(code, args, defaultMessage, locale); return exceptionMessageAccessor.getMessage(code, args, defaultMessage, locale); } catch (Exception e) { hanldeFindMessageError(e); } return SystemErrorCode.DEFAULT_SYSTEM_ERROR_CODE; } default String getMessage(String code, Object[] args){ ExceptionMessageAccessor exceptionMessageAccessor = getExceptionMessageAccessor(); if(exceptionMessageAccessor==null) return ""; try { return exceptionMessageAccessor.getMessage(code, args); } catch (Exception e) { hanldeFindMessageError(e); } return SystemErrorCode.DEFAULT_SYSTEM_ERROR_CODE; } default void hanldeFindMessageError(Exception e) { JFishLoggerFactory.getCommonLogger().error("getMessage error :" + e.getMessage()); } ExceptionMessageAccessor getExceptionMessageAccessor(); public static class ErrorMessage { private String code; private String mesage; boolean detail; private HttpStatus httpStatus; // private boolean authentic = false; private String viewName; final private Exception exception; public ErrorMessage(Exception throwable) { super(); this.exception = throwable; } public void logErrorContext(Logger logger){ Map<String, Object> ctx = getErrorContext(); if(!ctx.isEmpty()){ logger.error("error context: {}", ctx); } } public Map<String, Object> getErrorContext(){ Map<String, Object> ctx = null; if(exception instanceof SystemErrorCode){ ctx = ((SystemErrorCode)exception).getErrorContext(); }else{ ctx = Collections.emptyMap(); } return ctx; } /*public ErrorMessage(String code, String mesage, boolean detail) { super(); this.code = code; this.mesage = mesage; this.detail = detail; }*/ public String getCode() { return code; } public String getMesage() { return mesage; } public boolean isDetail() { return detail; } public String getViewName() { return viewName; } public void setViewName(String viewName) { this.viewName = viewName; } public Exception getException() { return exception; } public void setCode(String code) { this.code = code; } public void setMesage(String mesage) { this.mesage = mesage; } public void setDetail(boolean detail) { this.detail = detail; } public boolean isNotLoginException() { return NotLoginException.class.isInstance(exception); } public boolean isNoPermissionException() { return NoAuthorizationException.class.isInstance(exception); } public HttpStatus getHttpStatus() { return httpStatus; } public void setHttpStatus(HttpStatus httpStatus) { this.httpStatus = httpStatus; } /* public void setAuthentic(boolean authentic) { this.authentic = authentic; }*/ public String toString(){ return ReflectionToStringBuilder.toString(this); } } }
package com.kaltura.client.utils.request; import com.kaltura.client.Client; import com.kaltura.client.Params; import com.kaltura.client.types.APIException; import com.kaltura.client.utils.APIConstants; public class ServeRequestBuilder extends RequestBuilder<String> { public ServeRequestBuilder() { super(String.class); } public ServeRequestBuilder(String service, String action, Params params) { super(String.class, service, action, params); } @Override public String getMethod() { return "GET"; } @Override public String getBody() { return null; } @Override public RequestElement build(final Client client, boolean addSignature) { Params kParams = prepareParams(client, true); prepareHeaders(client.getConnectionConfiguration()); String endPoint = client.getConnectionConfiguration().getEndpoint().replaceAll("/$", ""); StringBuilder urlBuilder = new StringBuilder(endPoint) .append("/") .append(APIConstants.UrlApiVersion) .append("/service/") .append(service) .append("/action/") .append(action) .append("?") .append(kParams.toQueryString()); return this; } @Override protected Object parse(String response) throws APIException { return response; } }
package com.kurento.apps.android.content.demo.rtp; import java.io.IOException; import java.net.URL; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import javax.sdp.SdpException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import android.content.Context; import com.kurento.apps.android.content.demo.rtp.jsonrpc.AsyncJsonRpcClient; import com.kurento.apps.android.content.demo.rtp.jsonrpc.AsyncJsonRpcClient.JsonRpcRequestHandler; import com.kurento.commons.media.format.conversor.SdpConversor; import com.kurento.kmf.content.jsonrpc.Constraints; import com.kurento.kmf.content.jsonrpc.JsonRpcRequest; import com.kurento.kmf.content.jsonrpc.JsonRpcResponse; import com.kurento.kmf.content.jsonrpc.JsonRpcResponseError; import com.kurento.kmf.content.jsonrpc.param.JsonRpcConstraints; import com.kurento.kmf.content.jsonrpc.result.JsonRpcResponseResult; import com.kurento.mediaspec.SessionSpec; import com.kurento.mscontrol.commons.EventType; import com.kurento.mscontrol.commons.MediaErr; import com.kurento.mscontrol.commons.MediaEventListener; import com.kurento.mscontrol.commons.MsControlException; import com.kurento.mscontrol.commons.networkconnection.NetworkConnection; import com.kurento.mscontrol.commons.networkconnection.SdpPortManagerEvent; import com.kurento.mscontrol.kas.MediaSessionAndroid; public class RtpSession { private static final Logger log = LoggerFactory.getLogger(RtpSession.class .getSimpleName()); public interface SessionExceptionHandler { public void onSessionException(RtpSession session, Exception e); } public interface SessionEstablishedHandler { public void onEstablishedSession(RtpSession session); } private final LooperThread looperThread = new LooperThread(); private final Context context; private static final AtomicInteger sequenceNumber = new AtomicInteger(0); private String uuid; private String sessionId = null; private NetworkConnection nc; private String serverAddres; private int serverPort; private String demoUrl; private boolean request2Terminate = false; private SessionExceptionHandler sessionExceptionHandler; private SessionEstablishedHandler sessionEstablishedHandler; RtpSession(Context context, MediaSessionAndroid mediaSession) throws MsControlException { this.context = context; this.uuid = UUID.randomUUID().toString(); this.nc = mediaSession.createNetworkConnection(); serverAddres = Preferences.getServerAddress(context); serverPort = Preferences.getServerPort(context); demoUrl = Preferences.getDemoUrl(context); createDefaultHandlers(); looperThread.start(); } public String getUuid() { return uuid; } public synchronized String getSessionId() { return sessionId; } public synchronized void setSessionId(String sessionId) { this.sessionId = sessionId; } public NetworkConnection getNetworkConnection() { return nc; } public void setSessionEstablishedHandler( SessionEstablishedHandler sessionEstablishedHandler) { this.sessionEstablishedHandler = sessionEstablishedHandler; } public void setSessionExceptionHandler( SessionExceptionHandler sessionExceptionHandler) { this.sessionExceptionHandler = sessionExceptionHandler; } private void startSync() throws MsControlException { nc.getSdpPortManager().addListener(generateOfferListener); nc.getSdpPortManager().generateSdpOffer(); } public void start() { looperThread.post(new Runnable() { @Override public void run() { try { startSync(); } catch (MsControlException e) { log.error("Cannot start", e); sessionExceptionHandler.onSessionException(RtpSession.this, e); } } }); } private void terminateSync() { nc.release(); synchronized (this) { request2Terminate = true; if (sessionId == null) { log.info("The session with " + uuid + " is not stablished yet"); return; } try { JsonRpcRequest req = JsonRpcRequest.newTerminateRequest(0, "Terminate RTP session", sessionId, sequenceNumber.getAndIncrement()); URL url = new URL( context.getString(R.string.preference_server_standard_protocol_default), serverAddres, serverPort, demoUrl); AsyncJsonRpcClient.sendRequest(url, req, new JsonRpcRequestHandler() { @Override public void onSuccess(JsonRpcResponse resp) { log.debug("Terminate on success"); } @Override public void onError(Exception e) { log.error("Exception sending request", e); } }); } catch (IOException e) { log.error("error: " + e.getMessage(), e); } looperThread.quit(); } } public void terminate() { looperThread.post(new Runnable() { @Override public void run() { terminateSync(); } }); } private MediaEventListener<SdpPortManagerEvent> generateOfferListener = new MediaEventListener<SdpPortManagerEvent>() { @Override public void onEvent(SdpPortManagerEvent event) { event.getSource().removeListener(this); MediaErr error = event.getError(); if (!MediaErr.NO_ERROR.equals(error)) { terminate(); sessionExceptionHandler.onSessionException(RtpSession.this, new MsControlException("Cannot generate offer. " + error)); return; } EventType eventType = event.getEventType(); if (SdpPortManagerEvent.OFFER_GENERATED.equals(eventType)) { log.debug("SdpPortManager successfully generated a SDP to be send to remote peer"); try { String sdpOffer = SdpConversor.sessionSpec2Sdp(event .getMediaServerSdp()); log.debug("generated SDP: " + sdpOffer); sendRpcStart(sdpOffer); } catch (SdpException e) { log.error("error: " + e.getMessage(), e); terminate(); sessionExceptionHandler.onSessionException(RtpSession.this, e); } catch (IOException e) { log.error("error: " + e.getMessage(), e); terminate(); sessionExceptionHandler.onSessionException(RtpSession.this, e); } } } }; private void sendRpcStart(String sdpOffer) throws IOException { // TODO: configure from media session JsonRpcRequest req = JsonRpcRequest.newStartRequest(sdpOffer, new JsonRpcConstraints(Constraints.SENDRECV.toString(), Constraints.INACTIVE.toString()), sequenceNumber .getAndIncrement()); URL url = new URL( context.getString(R.string.preference_server_standard_protocol_default), serverAddres, serverPort, demoUrl); AsyncJsonRpcClient.sendRequest(url, req, new JsonRpcRequestHandler() { @Override public void onSuccess(JsonRpcResponse resp) { if (resp.isError()) { JsonRpcResponseError error = resp.getResponseError(); String msg = "Error in JSON-RPC response: " + error.getMessage() + "(" + error.getCode() + ")"; terminate(); sessionExceptionHandler.onSessionException(RtpSession.this, new MsControlException(msg)); return; } JsonRpcResponseResult result = resp.getResponseResult(); String sdpAnswer = result.getSdp(); log.debug("SDP answer: " + sdpAnswer); setSessionId(result.getSessionId()); log.debug("Session ID: " + getSessionId()); try { nc.getSdpPortManager().addListener(processAnswerListener); nc.getSdpPortManager().processSdpAnswer( SdpConversor.sdp2SessionSpec(sdpAnswer)); } catch (SdpException e) { log.error("error: " + e.getMessage(), e); terminate(); sessionExceptionHandler.onSessionException(RtpSession.this, e); } catch (MsControlException e) { log.error("error: " + e.getMessage(), e); terminate(); sessionExceptionHandler.onSessionException(RtpSession.this, e); } } @Override public void onError(Exception e) { log.error("Exception sending request", e); terminate(); sessionExceptionHandler.onSessionException(RtpSession.this, e); } }); } private MediaEventListener<SdpPortManagerEvent> processAnswerListener = new MediaEventListener<SdpPortManagerEvent>() { @Override public void onEvent(SdpPortManagerEvent event) { event.getSource().removeListener(this); MediaErr error = event.getError(); if (!MediaErr.NO_ERROR.equals(error)) { terminate(); sessionExceptionHandler.onSessionException(RtpSession.this, new MsControlException("Cannot generate offer. " + error)); return; } EventType eventType = event.getEventType(); if (SdpPortManagerEvent.ANSWER_PROCESSED.equals(eventType)) { try { synchronized (this) { if (request2Terminate) { terminate(); return; } nc.confirm(); sessionEstablishedHandler .onEstablishedSession(RtpSession.this); } SessionSpec localSdp = nc.getSdpPortManager() .getMediaServerSessionDescription(); log.debug("local SDP: " + SdpConversor.sessionSpec2Sdp(localSdp)); SessionSpec remoteSdp = nc.getSdpPortManager() .getUserAgentSessionDescription(); log.debug("remote SDP: " + SdpConversor.sessionSpec2Sdp(remoteSdp)); } catch (SdpException e) { log.error("error: " + e.getMessage(), e); terminate(); sessionExceptionHandler.onSessionException(RtpSession.this, e); } catch (MsControlException e) { log.error("Error confirming nc"); terminate(); sessionExceptionHandler.onSessionException(RtpSession.this, e); } } else { log.warn("Event received: " + eventType); terminate(); sessionExceptionHandler.onSessionException(RtpSession.this, new MsControlException("Cannot process answer")); } } }; private void createDefaultHandlers() { sessionEstablishedHandler = new SessionEstablishedHandler() { @Override public void onEstablishedSession(RtpSession session) { log.info("Default onEstablishedSession"); } }; sessionExceptionHandler = new SessionExceptionHandler() { @Override public void onSessionException(RtpSession session, Exception e) { log.info("Default onSessionException"); } }; } }
// This source code is available under agreement available at // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France package org.talend.dataprep.preparation.service; import static java.lang.Integer.MAX_VALUE; import static java.util.Collections.emptyList; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; import static org.talend.daikon.exception.ExceptionContext.build; import static org.talend.dataprep.api.folder.FolderContentType.PREPARATION; import static org.talend.dataprep.exception.error.PreparationErrorCodes.*; import static org.talend.dataprep.folder.store.FoldersRepositoriesConstants.PATH_SEPARATOR; import static org.talend.dataprep.i18n.DataprepBundle.message; import static org.talend.dataprep.preparation.service.PreparationSearchCriterion.filterPreparation; import static org.talend.dataprep.util.SortAndOrderHelper.getPreparationComparator; import static org.talend.tql.api.TqlBuilder.*; import java.text.DecimalFormat; import java.util.*; import java.util.function.Function; import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import javax.validation.ConstraintViolation; import javax.validation.Validator; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.talend.daikon.exception.ExceptionContext; import org.talend.dataprep.api.action.ActionDefinition; import org.talend.dataprep.api.dataset.DataSetMetadata; import org.talend.dataprep.api.dataset.RowMetadata; import org.talend.dataprep.api.folder.Folder; import org.talend.dataprep.api.folder.FolderEntry; import org.talend.dataprep.api.preparation.*; import org.talend.dataprep.api.service.info.VersionService; import org.talend.dataprep.command.dataset.DataSetGetMetadata; import org.talend.dataprep.conversions.BeanConversionService; import org.talend.dataprep.exception.TDPException; import org.talend.dataprep.exception.error.PreparationErrorCodes; import org.talend.dataprep.exception.json.JsonErrorCodeDescription; import org.talend.dataprep.folder.store.FolderRepository; import org.talend.dataprep.lock.store.LockedResourceRepository; import org.talend.dataprep.preparation.store.PreparationRepository; import org.talend.dataprep.security.Security; import org.talend.dataprep.transformation.actions.common.ActionFactory; import org.talend.dataprep.transformation.actions.common.ImplicitParameters; import org.talend.dataprep.transformation.actions.common.RunnableAction; import org.talend.dataprep.transformation.actions.datablending.Lookup; import org.talend.dataprep.transformation.api.action.ActionParser; import org.talend.dataprep.transformation.api.action.validation.ActionMetadataValidation; import org.talend.dataprep.transformation.pipeline.ActionRegistry; import org.talend.dataprep.util.SortAndOrderHelper.Order; import org.talend.dataprep.util.SortAndOrderHelper.Sort; import org.talend.tql.api.TqlBuilder; import org.talend.tql.model.Expression; @Service public class PreparationService { private static final Logger LOGGER = LoggerFactory.getLogger(PreparationService.class); private static final String STEP_ID = "stepId"; /** * Where preparation are stored. */ @Autowired protected PreparationRepository preparationRepository; /** * DataPrep abstraction to the underlying security (whether it's enabled or not). */ @Autowired protected Security security; private final ActionFactory factory = new ActionFactory(); @Autowired private org.springframework.context.ApplicationContext springContext; /** * Where the folders are stored. */ @Autowired private FolderRepository folderRepository; /** * Action validator. */ @Autowired private ActionMetadataValidation validator; /** * Version service. */ @Autowired private VersionService versionService; /** * Where all the actions are registered. */ @Autowired private ActionRegistry actionRegistry; @Autowired private LockedResourceRepository lockedResourceRepository; @Autowired private MetadataChangesOnActionsGenerator stepDiffDelegate; @Autowired private ReorderStepsUtils reorderStepsUtils; @Autowired private ActionParser actionParser; @Autowired private BeanConversionService beanConversionService; @Autowired private PreparationUtils preparationUtils; @Autowired private Set<Validator> validators; /** * Create a preparation from the http request body. * * @param preparation the preparation to create. * @param folderId where to store the preparation. * @return the created preparation id. */ public String create(final Preparation preparation, String folderId) { LOGGER.debug("Create new preparation for data set {} in {}", preparation.getDataSetId(), folderId); Preparation toCreate = new Preparation(UUID.randomUUID().toString(), versionService.version().getVersionId()); toCreate.setHeadId(Step.ROOT_STEP.id()); toCreate.setAuthor(security.getUserId()); toCreate.setName(preparation.getName()); toCreate.setDataSetId(preparation.getDataSetId()); toCreate.setRowMetadata(preparation.getRowMetadata()); preparationRepository.add(toCreate); final String id = toCreate.id(); // create associated folderEntry FolderEntry folderEntry = new FolderEntry(PREPARATION, id); folderRepository.addFolderEntry(folderEntry, folderId); LOGGER.info("New preparation {} created and stored in {} ", preparation, folderId); return id; } /** * List all preparation details. * * @param name of the preparation. * @param folderPath filter on the preparation path. * @param path preparation full path in the form folder_path/preparation_name. Overrides folderPath and name if present. * @param sort how to sort the preparations. * @param order how to order the sort. * @return the preparation details. */ public Stream<UserPreparation> listAll(String name, String folderPath, String path, Sort sort, Order order) { if (path != null) { // Transform path argument into folder path + preparation name if (path.contains(PATH_SEPARATOR.toString())) { // Special case the path should start with / if (!path.startsWith(PATH_SEPARATOR.toString())) { path = PATH_SEPARATOR.toString().concat(path); } folderPath = org.apache.commons.lang3.StringUtils.substringBeforeLast(path, PATH_SEPARATOR.toString()); // Special case if the preparation is in the root folder if (org.apache.commons.lang3.StringUtils.isEmpty(folderPath)) { folderPath = PATH_SEPARATOR.toString(); } name = org.apache.commons.lang3.StringUtils.substringAfterLast(path, PATH_SEPARATOR.toString()); } else { // the preparation is in the root folder folderPath = PATH_SEPARATOR.toString(); name = path; LOGGER.warn("Using path argument without '{}'. {} filter has been transformed into {}{}.", PATH_SEPARATOR, path, PATH_SEPARATOR, name); } } return listAll(filterPreparation().byName(name).withNameExactMatch(true).byFolderPath(folderPath), sort, order); } public Stream<UserPreparation> listAll(PreparationSearchCriterion searchCriterion, Sort sort, Order order) { LOGGER.debug("Get list of preparations (with details)."); Stream<Preparation> preparationStream; if (searchCriterion.getName() == null && searchCriterion.getDataSetId() == null) { preparationStream = preparationRepository.list(Preparation.class); } else { Expression filter = null; if (searchCriterion.getName() != null) { filter = getNameFilter(searchCriterion.getName(), searchCriterion.isNameExactMatch()); } if (searchCriterion.getDataSetId() != null) { Expression dataSetFilter = eq("dataSetId", searchCriterion.getDataSetId()); filter = filter == null ? dataSetFilter : and(filter, dataSetFilter); } preparationStream = preparationRepository.list(Preparation.class, filter); } // filter on path if (searchCriterion.getFolderPath() != null || searchCriterion.getFolderId() != null) { Map<String, Folder> preparationsFolder = folderRepository.getPreparationsFolderPaths(); if (searchCriterion.getFolderPath() != null) { preparationStream = preparationStream .filter(p -> preparationsFolder.get(p.getId()).getPath().equals(searchCriterion.getFolderPath())); } if (searchCriterion.getFolderId() != null) { preparationStream = preparationStream .filter(p -> preparationsFolder.get(p.getId()).getId().equals(searchCriterion.getFolderId())); } } return preparationStream.map(p -> beanConversionService.convert(p, UserPreparation.class)) // Needed to order on // preparation size .sorted(getPreparationComparator(sort, order, p -> getDatasetMetadata(p.getDataSetId()))); } /** * List all preparation summaries. * * @return the preparation summaries, sorted by descending last modification date. */ public Stream<PreparationSummary> listSummary(String name, String folderPath, String path, Sort sort, Order order) { return listAll(name, folderPath, path, sort, order).map(p -> beanConversionService.convert(p, PreparationSummary.class)); } /** * <p> * Search preparation entry point. * </p> * <p> * <p> * So far at least one search criteria can be processed at a time among the following ones : * <ul> * <li>dataset id</li> * <li>preparation name & exact match</li> * <li>folderId path</li> * </ul> * </p> * * @param dataSetId to search all preparations based on this dataset id. * @param folderId to search all preparations located in this folderId. * @param name to search all preparations that match this name. * @param exactMatch if true, the name matching must be exact. * @param path * @param sort Sort key (by name, creation date or modification date). * @param order Order for sort key (desc or asc). */ public Stream<UserPreparation> searchPreparations(String dataSetId, String folderId, String name, boolean exactMatch, String path, Sort sort, Order order) { return listAll( filterPreparation() .byDataSetId(dataSetId) .byFolderId(folderId) .byName(name) .withNameExactMatch(exactMatch) .byFolderPath(path), sort, order); } /** * List all the preparations that matches the given name. * * @param name the wanted preparation name. * @param exactMatch true if the name must match exactly. * @return all the preparations that matches the given name. */ private Expression getNameFilter(String name, boolean exactMatch) { LOGGER.debug("looking for preparations with the name '{}' exact match is {}.", name, exactMatch); final String regex; // Add case insensitive and escape special characters in name final String regexMainPart = "(?i)" + Pattern.quote(name); if (exactMatch) { regex = "^" + regexMainPart + "$"; } else { regex = "^.*" + regexMainPart + ".*$"; } return match("name", regex); } /** * Copy the given preparation to the given name / folder ans returns the new if in the response. * * @param name the name of the copied preparation, if empty, the name is "orginal-preparation-name Copy" * @param destination the folder path where to copy the preparation, if empty, the copy is in the same folder. * @return The new preparation id. */ public String copy(String preparationId, String name, String destination) { LOGGER.debug("copy {} to folder {} with {} as new name"); Preparation original = preparationRepository.get(preparationId, Preparation.class); // if no preparation, there's nothing to copy if (original == null) { throw new TDPException(PREPARATION_DOES_NOT_EXIST, build().put("id", preparationId)); } // use a default name if empty (original name + " Copy" ) final String newName; if (StringUtils.isBlank(name)) { newName = message("preparation.copy.newname", original.getName()); } else { newName = name; } checkIfPreparationNameIsAvailable(destination, newName); // copy the Preparation : constructor set HeadId and Preparation copy = new Preparation(original); copy.setId(UUID.randomUUID().toString()); copy.setName(newName); final long now = System.currentTimeMillis(); copy.setCreationDate(now); copy.setLastModificationDate(now); copy.setAuthor(security.getUserId()); cloneStepsListBetweenPreparations(original, copy); // Save preparation to repository preparationRepository.add(copy); String newId = copy.getId(); // add the preparation into the folder FolderEntry folderEntry = new FolderEntry(PREPARATION, newId); folderRepository.addFolderEntry(folderEntry, destination); LOGGER.debug("copy {} to folder {} with {} as new name", preparationId, destination, name); return newId; } /** * Duplicate the list of steps and set it to the new preparation * * @param originalPrep the original preparation. * @param targetPrep the created preparation. */ private void cloneStepsListBetweenPreparations(Preparation originalPrep, Preparation targetPrep) { // copy the preparation's steps List<Step> copyListSteps = new ArrayList<>(); // in order to save the previous step final Deque<Step> previousSteps = new ArrayDeque<>(1); previousSteps.push(Step.ROOT_STEP); copyListSteps.add(Step.ROOT_STEP); copyListSteps.addAll(originalPrep.getSteps().stream() .skip(1) // Skip root step .map(originalStep -> { final StepDiff diff = new StepDiff(); diff.setCreatedColumns(Collections.emptyList()); final Step createdStep = new Step(previousSteps.pop().id(), originalStep.getContent(), originalStep.getAppVersion(), diff); previousSteps.push(createdStep); return createdStep; }) .collect(Collectors.toList())); targetPrep.setSteps(copyListSteps); targetPrep.setHeadId(previousSteps.pop().id()); } /** * Check if the name is available in the given folderId. * * @param folderId where to look for the name. * @param name the wanted preparation name. * @throws TDPException Preparation name already used (409) if there's already a preparation with this name in the * folderId. */ private void checkIfPreparationNameIsAvailable(String folderId, String name) { // make sure the preparation does not already exist in the target folderId try (final Stream<FolderEntry> entries = folderRepository.entries(folderId, PREPARATION)) { entries.forEach(folderEntry -> { Preparation preparation = preparationRepository.get(folderEntry.getContentId(), Preparation.class); if (preparation != null && StringUtils.equals(name, preparation.getName())) { final ExceptionContext context = build() .put("id", folderEntry.getContentId()) .put("folderId", folderId) .put("name", name); throw new TDPException(PREPARATION_NAME_ALREADY_USED, context); } }); } } /** * Move a preparation to an other folder. * * @param folder The original folder of the preparation. * @param destination The new folder of the preparation. * @param newName The new preparation name. */ public void move(String preparationId, String folder, String destination, String newName) { //@formatter:on LOGGER.debug("moving {} from {} to {} with the new name '{}'", preparationId, folder, destination, newName); // get and lock the preparation to move final Preparation original = lockPreparation(preparationId); try { // set the target name final String targetName = StringUtils.isEmpty(newName) ? original.getName() : newName; // first check if the name is already used in the target folder checkIfPreparationNameIsAvailable(destination, targetName); // rename the dataset only if we received a new name if (!targetName.equals(original.getName())) { original.setName(newName); preparationRepository.add(original); } // move the preparation FolderEntry folderEntry = new FolderEntry(PREPARATION, preparationId); folderRepository.moveFolderEntry(folderEntry, folder, destination); LOGGER.info("preparation {} moved from {} to {} with the new name {}", preparationId, folder, destination, targetName); } finally { unlockPreparation(preparationId); } } /** * Delete the preparation that match the given id. * * @param preparationId the preparation id to delete. */ public void delete(String preparationId) { LOGGER.debug("Deletion of preparation #{} requested.", preparationId); final Preparation preparationToDelete = lockPreparation(preparationId); try { preparationRepository.remove(preparationToDelete); for (Step step : preparationToDelete.getSteps()) { if (!Step.ROOT_STEP.id().equals(step.id())) { // Remove step metadata final StepRowMetadata rowMetadata = new StepRowMetadata(); rowMetadata.setId(step.getRowMetadata()); preparationRepository.remove(rowMetadata); // Remove preparation action (if it's the only step using these actions) final Stream<Step> steps = preparationRepository.list(Step.class, eq("contentId", step.getContent())); if (steps.count() == 1) { // Remove action final PreparationActions preparationActions = new PreparationActions(); preparationActions.setId(step.getContent()); preparationRepository.remove(preparationActions); } // Remove step preparationRepository.remove(step); } } // delete the associated folder entries try (final Stream<FolderEntry> entries = folderRepository.findFolderEntries(preparationId, PREPARATION)) { entries.forEach(e -> folderRepository.removeFolderEntry(e.getFolderId(), preparationId, PREPARATION)); LOGGER.info("Deletion of preparation #{} done.", preparationId); } } finally { // Just in case remove failed unlockPreparation(preparationId); } } /** * Update a preparation. * * @param preparationId the preparation id to update. * @param preparation the updated preparation. * @return the updated preparation id. */ public String update(String preparationId, final Preparation preparation) { final Preparation previousPreparation = lockPreparation(preparationId); try { LOGGER.debug("Updating preparation with id {}: {}", preparation.getId(), previousPreparation); Preparation updated = previousPreparation.merge(preparation); validatePreparation(updated); if (!updated.id().equals(preparationId)) { preparationRepository.remove(previousPreparation); } updated.setAppVersion(versionService.version().getVersionId()); updated.setLastModificationDate(System.currentTimeMillis()); preparationRepository.add(updated); LOGGER.info("Preparation {} updated -> {}", preparationId, updated); return updated.id(); } finally { unlockPreparation(preparationId); } } private void validatePreparation(Preparation updated) { Set<ConstraintViolation<Preparation>> collect = validators.stream().flatMap(v -> v.validate(updated).stream()) .collect(toSet()); if (!collect.isEmpty()) { throw new TDPException(INVALID_PREPARATION, build().put("message", collect)); } } /** * Copy the steps from the another preparation to this one. * <p> * This is only allowed if this preparation has no steps. * * @param id the preparation id to update. * @param from the preparation id to copy the steps from. */ public void copyStepsFrom(String id, String from) { LOGGER.debug("copy steps from {} to {}", from, id); final Preparation preparationToUpdate = preparationRepository.get(id, Preparation.class); if (preparationToUpdate == null) { LOGGER.error("cannot update {} steps --> preparation not found in repository", id); throw new TDPException(PREPARATION_DOES_NOT_EXIST, build().put("id", id)); } // if the preparation is not empty (head != root step) --> 409 if (!StringUtils.equals(preparationToUpdate.getHeadId(), Step.ROOT_STEP.id())) { LOGGER.error("cannot update {} steps --> preparation has already steps."); throw new TDPException(PREPARATION_NOT_EMPTY, build().put("id", id)); } final Preparation referencePreparation = preparationRepository.get(from, Preparation.class); if (referencePreparation == null) { LOGGER.warn("cannot copy steps from {} to {} because the original preparation is not found", from, id); return; } cloneStepsListBetweenPreparations(referencePreparation, preparationToUpdate); preparationToUpdate.setLastModificationDate(new Date().getTime()); preparationRepository.add(preparationToUpdate); LOGGER.info("clone steps from {} to {} done --> {}", from, id, preparationToUpdate); } /** * Return a preparation details. * * @param id the wanted preparation id. * @param stepId the optional step id. * @return the preparation details. */ public PreparationMessage getPreparationDetails(String id, String stepId) { LOGGER.debug("Get content of preparation details for final Preparation preparation = preparationRepository.get(id, Preparation.class); if (preparation == null) { throw new TDPException(PreparationErrorCodes.PREPARATION_DOES_NOT_EXIST, ExceptionContext.build().put("id", id)); } ensurePreparationConsistency(preparation); // specify the step id if provided if (!StringUtils.equals("head", stepId)) { // just make sure the step does exist if (Step.ROOT_STEP.id().equals(stepId)) { preparation.setSteps(Collections.singletonList(Step.ROOT_STEP)); preparation.setHeadId(Step.ROOT_STEP.id()); } else if (preparationRepository.exist(Step.class, TqlBuilder.eq("id", stepId))) { preparation.setSteps(preparationUtils.listSteps(stepId, preparationRepository)); preparation.setHeadId(stepId); } else { throw new TDPException(PREPARATION_STEP_DOES_NOT_EXIST, build().put("id", preparation).put(STEP_ID, stepId)); } } final PreparationMessage details = beanConversionService.convert(preparation, PreparationMessage.class); LOGGER.info("returning details for {} -> {}", id, details); return details; } /** * This method ensures the consistency of a preparation .i.e. makes sure that a non-empty head step of a preparation * has its corresponding actions available. If it is not the case, we walk recursively on the steps from the current head * to the root step until we reach a step having its actions accessible or we reach the root step. * * @param preparation the specified preparation */ private void ensurePreparationConsistency(Preparation preparation) { final String headId = preparation.getHeadId(); Step head = preparationRepository.get(headId, Step.class); if (head != null) { PreparationActions prepActions = preparationRepository.get(head.getContent(), PreparationActions.class); boolean inconsistentPreparation = false; while (prepActions == null && head != Step.ROOT_STEP) { LOGGER.info( "Head step {} is inconsistent. Its corresponding action is unavailable. for the sake of safety new head is set to {}", head.getId(), head.getParent()); inconsistentPreparation = true; deleteAction(preparation, head.getId()); head = preparationRepository.get(head.getParent(), Step.class); prepActions = preparationRepository.get(head.getContent(), PreparationActions.class); } if (inconsistentPreparation) { setPreparationHead(preparation, head); } } } /** * Return the folder that holds this preparation. * * @param id the wanted preparation id. * @return the folder that holds this preparation. */ public Folder searchLocation(String id) { LOGGER.debug("looking the folder for {}", id); final Folder folder = folderRepository.locateEntry(id, PREPARATION); if (folder == null) { throw new TDPException(PREPARATION_DOES_NOT_EXIST, build().put("id", id)); } LOGGER.info("found where {} is stored : {}", id, folder); return folder; } public List<String> getSteps(String id) { LOGGER.debug("Get steps of preparation for final Step step = getStep(id); return preparationUtils.listStepsIds(step.id(), preparationRepository); } public void addPreparationAction(final String preparationId, final AppendStep step) { LOGGER.debug("Adding action to preparation..."); Preparation preparation = getPreparation(preparationId); List<Action> actions = getVersionedAction(preparationId, "head"); StepDiff actionCreatedColumns = stepDiffDelegate.computeCreatedColumns(preparation.getRowMetadata(), buildActions(actions), buildActions(step.getActions())); step.setDiff(actionCreatedColumns); appendSteps(preparationId, Collections.singletonList(step)); LOGGER.debug("Added action to preparation."); } /** * Given a list of actions recreate but with the Spring Context {@link ActionDefinition}. It is mandatory to use any * action parsed from JSON. */ private List<RunnableAction> buildActions(List<Action> allActions) { final List<RunnableAction> builtActions = new ArrayList<>(allActions.size() + 1); for (Action parsedAction : allActions) { if (parsedAction != null && parsedAction.getName() != null) { String actionNameLowerCase = parsedAction.getName().toLowerCase(); final ActionDefinition metadata = actionRegistry.get(actionNameLowerCase); builtActions.add(factory.create(metadata, parsedAction.getParameters())); } } return builtActions; } /** * Append step(s) in a preparation. */ public void appendSteps(String preparationId, final List<AppendStep> stepsToAppend) { stepsToAppend.forEach(this::checkActionStepConsistency); LOGGER.debug("Adding actions to preparation #{}", preparationId); final Preparation preparation = lockPreparation(preparationId); try { LOGGER.debug("Current head for preparation #{}: {}", preparationId, preparation.getHeadId()); // rebuild history from head replaceHistory(preparation, preparation.getHeadId(), stepsToAppend); LOGGER.debug("Added head to preparation #{}: head is now {}", preparationId, preparation.getHeadId()); } finally { unlockPreparation(preparationId); } } public void updateAction(final String preparationId, final String stepToModifyId, final AppendStep newStep) { checkActionStepConsistency(newStep); LOGGER.debug("Modifying actions in preparation #{}", preparationId); final Preparation preparation = lockPreparation(preparationId); try { LOGGER.debug("Current head for preparation #{}: {}", preparationId, preparation.getHeadId()); // Get steps from "step to modify" to the head final List<String> steps = extractSteps(preparation, stepToModifyId); // throws an exception if stepId is not in // the preparation LOGGER.debug("Rewriting history for {} steps.", steps.size()); // Extract created columns ids diff info final Step stm = getStep(stepToModifyId); final List<String> originalCreatedColumns = stm.getDiff().getCreatedColumns(); final List<String> updatedCreatedColumns = newStep.getDiff().getCreatedColumns(); final List<String> deletedColumns = originalCreatedColumns.stream() // columns that the step was creating but // not anymore .filter(id -> !updatedCreatedColumns.contains(id)).collect(toList()); final int columnsDiffNumber = updatedCreatedColumns.size() - originalCreatedColumns.size(); final int maxCreatedColumnIdBeforeUpdate = !originalCreatedColumns.isEmpty() ? originalCreatedColumns.stream().mapToInt(Integer::parseInt).max().getAsInt() : MAX_VALUE; final List<AppendStep> actionsSteps = getStepsWithShiftedColumnIds(steps, stepToModifyId, deletedColumns, maxCreatedColumnIdBeforeUpdate, columnsDiffNumber); actionsSteps.add(0, newStep); // Rebuild history from modified step final Step stepToModify = getStep(stepToModifyId); replaceHistory(preparation, stepToModify.getParent(), actionsSteps); LOGGER.debug("Modified head of preparation #{}: head is now {}", preparation.getHeadId()); } finally { unlockPreparation(preparationId); } } public void deleteAction(final String id, final String stepToDeleteId) { if (Step.ROOT_STEP.getId().equals(stepToDeleteId)) { throw new TDPException(PREPARATION_ROOT_STEP_CANNOT_BE_DELETED); } final Preparation preparation = lockPreparation(id); try { deleteAction(preparation, stepToDeleteId); } finally { unlockPreparation(id); } } public void setPreparationHead(final String preparationId, final String headId) { final Step head = getStep(headId); if (head == null) { throw new TDPException(PREPARATION_STEP_DOES_NOT_EXIST, build().put("id", preparationId).put(STEP_ID, headId)); } final Preparation preparation = lockPreparation(preparationId); try { setPreparationHead(preparation, head); } finally { unlockPreparation(preparationId); } } /** * Get all the actions of a preparation at given version. * * @param id the wanted preparation id. * @param version the wanted preparation version. * @return the list of actions. */ public List<Action> getVersionedAction(final String id, final String version) { LOGGER.debug("Get list of actions of preparation #{} at version {}.", id, version); final Preparation preparation = preparationRepository.get(id, Preparation.class); if (preparation != null) { final String stepId = getStepId(version, preparation); final Step step = getStep(stepId); if (step == null) { LOGGER.warn("Step '{}' no longer exist for preparation #{} at version '{}'", stepId, preparation.getId(), version); } return getActions(step); } else { throw new TDPException(PREPARATION_DOES_NOT_EXIST, build().put("id", id)); } } /** * List all preparation related error codes. */ public Iterable<JsonErrorCodeDescription> listErrors() { // need to cast the typed dataset errors into mock ones to use json parsing List<JsonErrorCodeDescription> errors = new ArrayList<>(PreparationErrorCodes.values().length); for (PreparationErrorCodes code : PreparationErrorCodes.values()) { errors.add(new JsonErrorCodeDescription(code)); } return errors; } public boolean isDatasetUsedInPreparation(final String datasetId) { final boolean preparationUseDataSet = isDatasetBaseOfPreparation(datasetId); final boolean dataSetUsedInLookup = isDatasetUsedToLookupInPreparationHead(datasetId); return preparationUseDataSet || dataSetUsedInLookup; } private boolean isDatasetBaseOfPreparation(String datasetId) { return preparationRepository.exist(Preparation.class, eq("dataSetId", datasetId)); } /** Check if the preparation uses this dataset in its head version. */ private boolean isDatasetUsedToLookupInPreparationHead(String datasetId) { final String datasetParamName = Lookup.Parameters.LOOKUP_DS_ID.getKey(); return preparationRepository.list(Preparation.class).flatMap(p -> getVersionedAction(p.getId(), "head").stream()) .filter(Objects::nonNull).filter(a -> Objects.equals(a.getName(), Lookup.LOOKUP_ACTION_NAME)) .anyMatch(a -> Objects.equals(datasetId, a.getParameters().get(datasetParamName))); } /** * Moves the step with specified <i>stepId</i> just after the step with <i>parentStepId</i> as identifier within the specified * preparation. * * @param preparationId the id of the preparation containing the step to move * @param stepId the id of the step to move * @param parentStepId the id of the step which wanted as the parent of the step to move */ public void moveStep(final String preparationId, String stepId, String parentStepId) { LOGGER.debug("Moving step {} after step {}, within preparation {}", stepId, parentStepId, preparationId); final Preparation preparation = lockPreparation(preparationId); try { reorderSteps(preparation, stepId, parentStepId); } finally { unlockPreparation(preparationId); } } /** * Get the actual step id by converting "head" and "origin" to the hash * * @param version The version to convert to step id * @param preparation The preparation * @return The converted step Id */ protected String getStepId(final String version, final Preparation preparation) { if ("head".equalsIgnoreCase(version)) { //$NON-NLS-1$ return preparation.getHeadId(); } else if ("origin".equalsIgnoreCase(version)) { //$NON-NLS-1$ return Step.ROOT_STEP.id(); } return version; } /** * Get actions list from root to the provided step * * @param step The step * @return The list of actions */ protected List<Action> getActions(final Step step) { if (step == null) { // TDP-3893: Make code more resilient to deleted steps return Collections.emptyList(); } final PreparationActions preparationActions = preparationRepository.get(step.getContent(), PreparationActions.class); if (preparationActions != null) { return new ArrayList<>(preparationActions.getActions()); } else { return Collections.emptyList(); } } /** * Get the step from id * * @param stepId The step id * @return The step with the provided id, might return <code>null</code> is step does not exist. * @see PreparationRepository#get(String, Class) */ public Step getStep(final String stepId) { return preparationRepository.get(stepId, Step.class); } /** * Get preparation from id with null result check. * * @param preparationId The preparation id. * @return The preparation with the provided id * @throws TDPException when no preparation has the provided id */ public Preparation getPreparation(final String preparationId) { final Preparation preparation = preparationRepository.get(preparationId, Preparation.class); if (preparation == null) { LOGGER.error("Preparation #{} does not exist", preparationId); throw new TDPException(PREPARATION_DOES_NOT_EXIST, build().put("id", preparationId)); } return preparation; } /** * Extract all actions after a provided step * * @param stepsIds The steps list * @param afterStep The (excluded) step id where to start the extraction * @return The actions after 'afterStep' to the end of the list */ private List<AppendStep> extractActionsAfterStep(final List<String> stepsIds, final String afterStep) { final int stepIndex = stepsIds.indexOf(afterStep); if (stepIndex == -1) { return emptyList(); } final List<Step> steps; try (IntStream range = IntStream.range(stepIndex, stepsIds.size())) { steps = range.mapToObj(index -> getStep(stepsIds.get(index))).collect(toList()); } final List<List<Action>> stepActions = steps.stream().map(this::getActions).collect(toList()); try (IntStream filteredActions = IntStream.range(1, steps.size())) { return filteredActions.mapToObj(index -> { final List<Action> previous = stepActions.get(index - 1); final List<Action> current = stepActions.get(index); final Step step = steps.get(index); final AppendStep appendStep = new AppendStep(); appendStep.setDiff(step.getDiff()); appendStep.setActions(current.subList(previous.size(), current.size())); return appendStep; }).collect(toList()); } } /** * Get the steps ids from a specific step to the head. The specific step MUST be defined as an existing step of the * preparation * * @param preparation The preparation * @param fromStepId The starting step id * @return The steps ids from 'fromStepId' to the head * @throws TDPException If 'fromStepId' is not a step of the provided preparation */ private List<String> extractSteps(final Preparation preparation, final String fromStepId) { final List<String> steps = preparationUtils.listStepsIds(preparation.getHeadId(), fromStepId, preparationRepository); if (!fromStepId.equals(steps.get(0))) { throw new TDPException(PREPARATION_STEP_DOES_NOT_EXIST, build().put("id", preparation.getId()).put(STEP_ID, fromStepId)); } return steps; } /** * Marks the specified preparation (identified by <i>preparationId</i>) as locked by the user identified by the * specified user (identified by <i>userId</i>). * * @param preparationId the specified preparation identifier * @throws TDPException if the lock is hold by another user */ public Preparation lockPreparation(String preparationId) { return lockedResourceRepository.tryLock(preparationId, security.getUserId(), security.getUserDisplayName()); } /** * Marks the specified preparation (identified by <i>preparationId</i>) as unlocked by the user identified by the * specified user (identified by <i>userId</i>). * * @param preparationId the specified preparation identifier * @throws TDPException if the lock is hold by another user */ public void unlockPreparation(String preparationId) { lockedResourceRepository.unlock(preparationId, security.getUserId()); } /** * Test if the stepId is the preparation head. Null, "head", "origin" and the actual step id are considered to be * the head * * @param preparation The preparation to test * @param stepId The step id to test * @return True if 'stepId' is considered as the preparation head */ private boolean isPreparationHead(final Preparation preparation, final String stepId) { return stepId == null || "head".equals(stepId) || "origin".equals(stepId) || preparation.getHeadId().equals(stepId); } /** * Check the action parameters consistency * * @param step the step to check */ private void checkActionStepConsistency(final AppendStep step) { for (final Action stepAction : step.getActions()) { validator.checkScopeConsistency(actionRegistry.get(stepAction.getName()), stepAction.getParameters()); } } /** * Currently, the columns ids are generated sequentially. There are 2 cases where those ids change in a step : * <ul> * <li>1. when a step that creates columns is deleted (ex1 : columns '0009' and '0010').</li> * <li>2. when a step that creates columns is updated : it can create more (add) or less (remove) columns. (ex2 : * add column '0009', '0010' + '0011' --> add 1 column)</li> * </ul> * In those cases, we have to * <ul> * <li>remove all steps that has action on a deleted column</li> * <li>shift all columns created after this step (ex1: columns > '0010', ex2: columns > '0011') by the number of * columns diff (ex1: remove 2 columns --> shift -2, ex2: add 1 column --> shift +1)</li> * <li>shift all actions that has one of the deleted columns as parameter (ex1: columns > '0010', ex2: columns > * '0011') by the number of columns diff (ex1: remove 2 columns --> shift -2, ex2: add 1 column --> shift +1)</li> * </ul> * <p> * 1. Get the steps with ids after 'afterStepId' 2. Rule 1 : Remove (filter) the steps which action is on one of the * 'deletedColumns' 3. Rule 2 : For all actions on columns ids > 'shiftColumnAfterId', we shift the column_id * parameter with a 'columnShiftNumber' value. (New_column_id = column_id + columnShiftNumber, only if column_id > * 'shiftColumnAfterId') 4. Rule 3 : The columns created AFTER 'shiftColumnAfterId' are shifted with the same rules * as rule 2. (New_created_column_id = created_column_id + columnShiftNumber, only if created_column_id > * 'shiftColumnAfterId') * * @param stepsIds The steps ids * @param afterStepId The (EXCLUDED) step where the extraction starts * @param deletedColumns The column ids that will be removed * @param shiftColumnAfterId The (EXCLUDED) column id where we start the shift * @param shiftNumber The shift number. new_column_id = old_columns_id + columnShiftNumber * @return The adapted steps */ private List<AppendStep> getStepsWithShiftedColumnIds(final List<String> stepsIds, final String afterStepId, final List<String> deletedColumns, final int shiftColumnAfterId, final int shiftNumber) { Stream<AppendStep> stream = extractActionsAfterStep(stepsIds, afterStepId).stream(); // rule 1 : remove all steps that modify one of the created columns if (!deletedColumns.isEmpty()) { stream = stream.filter(stepColumnIsNotIn(deletedColumns)); } // when there is nothing to shift, we just return the filtered steps to avoid extra code if (shiftNumber == 0) { return stream.collect(toList()); } // rule 2 : we have to shift all columns ids created after the step to delete/modify, in the column_id // parameters // For example, if the step to delete/modify creates columns 0010 and 0011, all steps that apply to column 0012 // should now apply to 0012 - (2 created columns) = 0010 stream = stream.map(shiftStepParameter(shiftColumnAfterId, shiftNumber)); // rule 3 : we have to shift all columns ids created after the step to delete, in the steps diff stream = stream.map(shiftCreatedColumns(shiftColumnAfterId, shiftNumber)); return stream.collect(toList()); } /** * When the step diff created column ids > 'shiftColumnAfterId', we shift it by +columnShiftNumber (that wan be * negative) * * @param shiftColumnAfterId The shift is performed if created column id > shiftColumnAfterId * @param shiftNumber The number to shift (can be negative) * @return The same step but modified */ private Function<AppendStep, AppendStep> shiftCreatedColumns(final int shiftColumnAfterId, final int shiftNumber) { final DecimalFormat format = new DecimalFormat("0000"); //$NON-NLS-1$ return step -> { final List<String> stepCreatedCols = step.getDiff().getCreatedColumns(); final List<String> shiftedStepCreatedCols = stepCreatedCols.stream().map(colIdStr -> { final int columnId = Integer.parseInt(colIdStr); if (columnId > shiftColumnAfterId) { return format.format(columnId + (long) shiftNumber); } return colIdStr; }).collect(toList()); step.getDiff().setCreatedColumns(shiftedStepCreatedCols); return step; }; } /** * When the step column_id parameter > 'shiftColumnAfterId', we shift it by +columnShiftNumber (that wan be * negative) * * @param shiftColumnAfterId The shift is performed if column id > shiftColumnAfterId * @param shiftNumber The number to shift (can be negative) * @return The same step but modified */ private Function<AppendStep, AppendStep> shiftStepParameter(final int shiftColumnAfterId, final int shiftNumber) { final DecimalFormat format = new DecimalFormat("0000"); //$NON-NLS-1$ return step -> { final Action firstAction = step.getActions().get(0); final Map<String, String> parameters = firstAction.getParameters(); final int columnId = Integer.parseInt(parameters.get(ImplicitParameters.COLUMN_ID.getKey())); if (columnId > shiftColumnAfterId) { parameters.put("column_id", format.format(columnId + (long) shiftNumber)); //$NON-NLS-1$ } return step; }; } /*** * Predicate that returns if a step action is NOT on one of the columns list * * @param columns The columns ids list */ private Predicate<AppendStep> stepColumnIsNotIn(final List<String> columns) { return step -> { final String columnId = step.getActions().get(0).getParameters().get("column_id"); //$NON-NLS-1$ return columnId == null || !columns.contains(columnId); }; } /** * Update the head step of a preparation * * @param preparation The preparation to update * @param head The head step */ private void setPreparationHead(final Preparation preparation, final Step head) { preparation.setHeadId(head.id()); preparation.updateLastModificationDate(); preparationRepository.add(preparation); } /** * Rewrite the preparation history from a specific step, with the provided actions * * @param preparation The preparation * @param startStepId The step id to start the (re)write. The following steps will be erased * @param actionsSteps The actions to perform */ private void replaceHistory(final Preparation preparation, final String startStepId, final List<AppendStep> actionsSteps) { // move preparation head to the starting step if (!isPreparationHead(preparation, startStepId)) { final Step startingStep = getStep(startStepId); setPreparationHead(preparation, startingStep); } actionsSteps.forEach(step -> appendStepToHead(preparation, step)); } /** * Append a single appendStep after the preparation head * * @param preparation The preparation. * @param appendStep The appendStep to apply. */ private void appendStepToHead(final Preparation preparation, final AppendStep appendStep) { // Add new actions after head final String headId = preparation.getHeadId(); final Step head = preparationRepository.get(headId, Step.class); final PreparationActions headActions = preparationRepository.get(head.getContent(), PreparationActions.class); final PreparationActions newContent = new PreparationActions(); if (headActions == null) { LOGGER.info("Cannot retrieve the action corresponding to step {}. Therefore it will be skipped.", head); return; } final List<Action> newActions = new ArrayList<>(headActions.getActions()); newActions.addAll(appendStep.getActions()); newContent.setActions(newActions); // Create new step from new content final Step newHead = new Step(headId, newContent.id(), versionService.version().getVersionId(), appendStep.getDiff()); preparationRepository.add(newHead); preparationRepository.add(newContent); // TODO Could we get the new step id? // Update preparation head step setPreparationHead(preparation, newHead); } /** * Deletes the step of specified id of the specified preparation * * @param preparation the specified preparation * @param stepToDeleteId the specified step id to delete */ private void deleteAction(Preparation preparation, String stepToDeleteId) { final List<String> steps = extractSteps(preparation, stepToDeleteId); // throws an exception if stepId is not in // get created columns by step to delete final Step std = getStep(stepToDeleteId); final List<String> deletedColumns = std.getDiff().getCreatedColumns(); final int columnsDiffNumber = -deletedColumns.size(); final int maxCreatedColumnIdBeforeUpdate = deletedColumns.isEmpty() ? MAX_VALUE : deletedColumns.stream().mapToInt(Integer::parseInt).max().getAsInt(); LOGGER.debug("Deleting actions in preparation #{} at step #{}", preparation.getId(), stepToDeleteId); //$NON-NLS-1$ // get new actions to rewrite history from deleted step final List<AppendStep> actions = getStepsWithShiftedColumnIds(steps, stepToDeleteId, deletedColumns, maxCreatedColumnIdBeforeUpdate, columnsDiffNumber); // rewrite history final Step stepToDelete = getStep(stepToDeleteId); replaceHistory(preparation, stepToDelete.getParent(), actions); } /** * Moves the step with specified <i>stepId</i> just after the step with <i>parentStepId</i> as identifier within the * specified preparation. * * @param preparation the preparation containing the step to move * @param stepId the id of the step to move * @param parentStepId the id of the step which wanted as the parent of the step to move */ private void reorderSteps(final Preparation preparation, final String stepId, final String parentStepId) { final List<String> steps = extractSteps(preparation, Step.ROOT_STEP.getId()); // extract all appendStep final List<AppendStep> allAppendSteps = extractActionsAfterStep(steps, steps.get(0)); final int stepIndex = steps.indexOf(stepId); final int parentIndex = steps.indexOf(parentStepId); if (stepIndex < 0) { throw new TDPException(PREPARATION_STEP_DOES_NOT_EXIST, build().put("id", preparation.getId()).put(STEP_ID, stepId)); } if (parentIndex < 0) { throw new TDPException(PREPARATION_STEP_DOES_NOT_EXIST, build().put("id", preparation.getId()).put(STEP_ID, parentStepId)); } if (stepIndex - 1 == parentIndex) { LOGGER.debug("No need to Move step {} after step {}, within preparation {}: already at the wanted position.", stepId, parentStepId, preparation.getId()); } else { final int lastUnchangedIndex; if (parentIndex < stepIndex) { lastUnchangedIndex = parentIndex; } else { lastUnchangedIndex = stepIndex - 1; } final AppendStep removedStep = allAppendSteps.remove(stepIndex - 1); allAppendSteps.add(lastUnchangedIndex == stepIndex - 1 ? parentIndex - 1 : parentIndex, removedStep); if (!reorderStepsUtils.isStepOrderValid(allAppendSteps)) { throw new TDPException(PREPARATION_STEP_CANNOT_BE_REORDERED, build()); } // rename created columns to conform to the way the transformation are performed reorderStepsUtils.renameCreatedColumns(allAppendSteps); final List<AppendStep> result = allAppendSteps.subList(lastUnchangedIndex, allAppendSteps.size()); replaceHistory(preparation, steps.get(lastUnchangedIndex), result); } } public void updatePreparationStep(String stepId, RowMetadata rowMetadata) { final Step step = preparationRepository.get(stepId, Step.class); if (step.getRowMetadata() != null) { // Delete previous one... final StepRowMetadata previousStepRowMetadata = new StepRowMetadata(); previousStepRowMetadata.setId(step.getRowMetadata()); preparationRepository.remove(previousStepRowMetadata); } // ...and create new one for step final StepRowMetadata stepRowMetadata = new StepRowMetadata(rowMetadata); preparationRepository.add(stepRowMetadata); step.setRowMetadata(stepRowMetadata.id()); preparationRepository.add(step); } public RowMetadata getPreparationStep(String stepId) { final Step step = preparationRepository.get(stepId, Step.class); if (step != null) { final StepRowMetadata stepRowMetadata = preparationRepository.get(step.getRowMetadata(), StepRowMetadata.class); if (stepRowMetadata != null) { return stepRowMetadata.getRowMetadata(); } } return null; } private DataSetMetadata getDatasetMetadata(String datasetId) { return springContext.getBean(DataSetGetMetadata.class, datasetId).execute(); } }
package com.stratio.connector.deep.connection; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import com.stratio.connector.commons.connection.Connection; import com.stratio.connector.commons.connection.exceptions.HandlerConnectionException; import com.stratio.connector.deep.configuration.ConnectionConfiguration; import com.stratio.connector.deep.configuration.ExtractorConnectConstants; import com.stratio.deep.commons.config.ExtractorConfig; import com.stratio.deep.commons.entity.Cells; import com.stratio.deep.core.context.DeepSparkContext; import com.stratio.meta.common.connector.ConnectorClusterConfig; import com.stratio.meta.common.security.ICredentials; import com.stratio.meta2.common.data.ClusterName; public class DeepConnection extends Connection { private final DeepSparkContext deepSparkContext; private boolean isConnect = false; private final ExtractorConfig extractorConfig; /** * Constructor. * * @param credentials * the credentials. * @param config * The cluster configuration. */ public DeepConnection(ICredentials credentials, ConnectorClusterConfig config) { ClusterName clusterName = config.getName(); Map<String, String> clusterOptions = config.getOptions(); // Creating a configuration for the Extractor and initialize it ExtractorConfig<Cells> extractorconfig = new ExtractorConfig<>(Cells.class); Map<String, Serializable> values = new HashMap<String, Serializable>(); values.put(ExtractorConnectConstants.PORT, clusterOptions.get(ExtractorConnectConstants.PORT)); String[] hosts = clusterOptions.get(ExtractorConnectConstants.HOSTS) .substring(1, clusterOptions.get(ExtractorConnectConstants.HOSTS).length() - 1).split(","); values.put(ExtractorConnectConstants.HOST, hosts[0]); values.put( ExtractorConnectConstants.HOSTS, clusterOptions.get(ExtractorConnectConstants.HOSTS).substring(1, clusterOptions.get(ExtractorConnectConstants.HOSTS).length() - 1)); extractorconfig.setValues(values); extractorConfig = extractorconfig; deepSparkContext = ConnectionConfiguration.getDeepContext(); } @Override public void close() { if (deepSparkContext != null) { // deepSparkContext.stop(); isConnect = false; } } @Override public boolean isConnect() { return isConnect; } @Override public DeepSparkContext getNativeConnection() { return deepSparkContext; } public ExtractorConfig getExtractorConfig() { return extractorConfig; } public void forceShutDown() throws HandlerConnectionException { deepSparkContext.stop(); } }
// File generated from our OpenAPI spec package com.stripe.net; import com.google.gson.TypeAdapterFactory; import com.stripe.model.BalanceTransactionSourceTypeAdapterFactory; import com.stripe.model.ExternalAccountTypeAdapterFactory; import com.stripe.model.PaymentSourceTypeAdapterFactory; import java.util.ArrayList; import java.util.List; /** * Provider for all {@link TypeAdapterFactory} required for deserializing subtypes of an interface. */ final class ApiResourceTypeAdapterFactoryProvider { private static final List<TypeAdapterFactory> factories = new ArrayList<>(); static { factories.add(new BalanceTransactionSourceTypeAdapterFactory()); factories.add(new ExternalAccountTypeAdapterFactory()); factories.add(new PaymentSourceTypeAdapterFactory()); } public static List<TypeAdapterFactory> getAll() { return factories; } }
package com.thanple.gameserver.framework.common.util; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Semaphore; import java.util.concurrent.locks.ReentrantLock; public class LockKey <K> { private static class LockInfo { private final Semaphore current; private int lockCount; private LockInfo(Semaphore current) { this.current = current; this.lockCount = 1; } } // KEY private final ConcurrentMap<K, Semaphore> map = new ConcurrentHashMap<K, Semaphore>(); // KEY private final ThreadLocal<Map<K, LockInfo>> local = new ThreadLocal<Map<K, LockInfo>>() { @Override protected Map<K, LockInfo> initialValue() { return new HashMap<K, LockInfo>(); } }; /** * keykey{@link #unlock(K)} * hashcodeequalskeykey{@link #hashCode()} * {@link #equals(Object)} * * @param key */ public void lock(K key) { if (key == null) return; LockInfo info = local.get().get(key); if (info == null) { Semaphore current = new Semaphore(1); current.acquireUninterruptibly(); Semaphore previous = map.put(key, current); if (previous != null) previous.acquireUninterruptibly(); local.get().put(key, new LockInfo(current)); } else { info.lockCount++; } } /** * keykey * @param key */ public void unlock(K key) { if (key == null) return; LockInfo info = local.get().get(key); if (info != null && --info.lockCount == 0) { info.current.release(); map.remove(key, info.current); local.get().remove(key); } } /** * key * keys * @param keys */ public void lock(K[] keys) { if (keys == null) return; for (K key : keys) { lock(key); } } /** * key * @param keys */ public void unlock(K[] keys) { if (keys == null) return; for (K key : keys) { unlock(key); } } /** * * key * */ public void unlockInThread(){ for(Map.Entry<K,LockInfo> entry : local.get().entrySet()){ K key = entry.getKey(); LockInfo lockInfo = entry.getValue(); lockInfo.current.release(); map.remove(key,lockInfo.current); } //local local.get().clear(); } public static void main(String[] args) throws InterruptedException { ReentrantLock lock = new ReentrantLock(); lock.lockInterruptibly(); System.out.println("1"); lock.lockInterruptibly(); System.out.println("2"); lock.unlock(); new Thread(){ @Override public void run() { try { lock.lockInterruptibly(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("3"); } }.start(); } }
package nl.tudelft.dnainator.javafx.controllers; import java.util.List; import nl.tudelft.dnainator.javafx.widgets.Propertyable; import nl.tudelft.dnainator.javafx.widgets.animations.LeftSlideAnimation; import nl.tudelft.dnainator.javafx.widgets.animations.SlidingAnimation; import nl.tudelft.dnainator.javafx.widgets.animations.TransitionAnimation.Position; import nl.tudelft.dnainator.javafx.widgets.ClusterProperties; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.Tooltip; import javafx.scene.layout.VBox; /** * Controls the property pane on the right side of the application. * It provides information about selected strain data. */ public class PropertyPaneController { private SlidingAnimation animation; private static final int WIDTH = 300; private static final int ANIM_DURATION = 250; @SuppressWarnings("unused") @FXML private VBox propertyPane; @SuppressWarnings("unused") @FXML private VBox vbox; @SuppressWarnings("unused") @FXML private Label propertyTitle; /* * Sets up the services, filechooser and treeproperty. */ @SuppressWarnings("unused") @FXML private void initialize() { propertyPane.getStyleClass().add("property-pane"); propertyTitle.setId("properties-label"); animation = new LeftSlideAnimation(propertyPane, WIDTH, ANIM_DURATION, Position.RIGHT); } /** * Updates the displayed information. * @param p The new {@link Propertyable} whose information to display. */ public void update(Propertyable p) { propertyTitle.setText(p.getType()); vbox.getChildren().clear(); if (p instanceof ClusterProperties) { ClusterProperties cs = (ClusterProperties) p; updateIds(cs); updateStartRefs(cs); updateEndRefs(cs); updateSequences(cs); } updateSources(p); } private void updateSources(Propertyable p) { List<String> sources = p.getSources(); if (sources == null) { return; } Label id = new Label("Sources"); id.getStyleClass().add("property-header"); vbox.getChildren().add(id); sources.forEach(source -> { Label sourceLabel = new Label(source); Tooltip t = new Tooltip(source); Tooltip.install(sourceLabel, t); vbox.getChildren().add(sourceLabel); }); } private void updateIds(ClusterProperties cp) { List<String> ids = cp.getIds(); if (ids == null) { return; } Label idLabel = new Label("Id(s)"); idLabel.getStyleClass().add("property-header"); vbox.getChildren().add(idLabel); StringBuilder sb = new StringBuilder(); ids.forEach(id -> sb.append(id + ", ")); vbox.getChildren().add(new Label(sb.toString().substring(0, sb.toString().length() - 2))); } private void updateStartRefs(ClusterProperties cp) { List<Integer> sRefs = cp.getStartRefs(); if (sRefs == null) { return; } Label srLabel = new Label("Start Reference(s)"); srLabel.getStyleClass().add("property-header"); vbox.getChildren().add(srLabel); StringBuilder sb = new StringBuilder(); sRefs.forEach(sRef -> sb.append(sRef + ", ")); vbox.getChildren().add(new Label(sb.toString().substring(0, sb.toString().length() - 2))); } private void updateEndRefs(ClusterProperties cp) { List<Integer> eRefs = cp.getEndRefs(); if (eRefs == null) { return; } Label erLabel = new Label("End Reference(s)"); erLabel.getStyleClass().add("property-header"); vbox.getChildren().add(erLabel); StringBuilder sb = new StringBuilder(); eRefs.forEach(eRef -> sb.append(eRef + ", ")); vbox.getChildren().add(new Label(sb.toString().substring(0, sb.toString().length() - 2))); } private void updateSequences(ClusterProperties cp) { List<String> seqs = cp.getSequences(); if (seqs == null) { return; } Label seqLabel = new Label("Sequence(s)"); seqLabel.getStyleClass().add("property-header"); vbox.getChildren().add(seqLabel); StringBuilder sb = new StringBuilder(); seqs.forEach(seq -> sb.append(seq + ", ")); String res = sb.toString().substring(0, sb.toString().length() - 2); Label seqLabels = new Label(res); Tooltip t = new Tooltip(res); Tooltip.install(seqLabels, t); vbox.getChildren().add(seqLabels); } /** * Toggle the sliding animation on the {@link PropertyPane}. */ public void toggle() { animation.toggle(); } }
// of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // 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.uber.jenkins.phabricator; import com.google.common.annotations.VisibleForTesting; import com.uber.jenkins.phabricator.conduit.ConduitAPIClient; import com.uber.jenkins.phabricator.conduit.ConduitAPIException; import com.uber.jenkins.phabricator.conduit.Differential; import com.uber.jenkins.phabricator.conduit.DifferentialClient; import com.uber.jenkins.phabricator.credentials.ConduitCredentials; import com.uber.jenkins.phabricator.tasks.ApplyPatchTask; import com.uber.jenkins.phabricator.tasks.SendHarbormasterResultTask; import com.uber.jenkins.phabricator.tasks.SendHarbormasterUriTask; import com.uber.jenkins.phabricator.tasks.Task; import com.uber.jenkins.phabricator.utils.CommonUtils; import com.uber.jenkins.phabricator.utils.Logger; import hudson.EnvVars; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.BuildListener; import hudson.model.Cause; import hudson.model.CauseAction; import hudson.model.Executor; import hudson.model.Job; import hudson.model.ParameterValue; import hudson.model.ParametersAction; import hudson.model.Result; import hudson.model.Run; import hudson.tasks.BuildWrapper; import hudson.util.RunList; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class PhabricatorBuildWrapper extends BuildWrapper { private static final String CONDUIT_TAG = "conduit"; private static final String DEFAULT_GIT_PATH = "git"; private static final String DIFFERENTIAL_SUMMARY = "PHABRICATOR_DIFFERENTIAL_SUMMARY"; private static final String DIFFERENTIAL_AUTHOR = "PHABRICATOR_DIFFERENTIAL_AUTHOR"; private static final String DIFFERENTIAL_BASE_COMMIT = "PHABRICATOR_DIFFERENTIAL_BASE_COMMIT"; private static final String DIFFERENTIAL_BRANCH = "PHABRICATOR_DIFFERENTIAL_BRANCH"; private final boolean createCommit; private final boolean applyToMaster; private final boolean skipForcedClean; private final boolean createBranch; private final boolean patchWithForceFlag; private String workDir; private String scmType; @DataBoundConstructor public PhabricatorBuildWrapper(boolean createCommit, boolean applyToMaster, boolean skipForcedClean, boolean createBranch, boolean patchWithForceFlag) { this.createCommit = createCommit; this.applyToMaster = applyToMaster; this.skipForcedClean = skipForcedClean; this.createBranch = createBranch; this.patchWithForceFlag = patchWithForceFlag; this.workDir = null; this.scmType = "git"; } @DataBoundSetter public void setWorkDir(final String workDir) { this.workDir = workDir; } @DataBoundSetter public void setScmType(final String scmType) { this.scmType = scmType; } /** {@inheritDoc} */ @Override public Environment setUp(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { EnvVars environment = build.getEnvironment(listener); Logger logger = new Logger(listener.getLogger()); if (environment == null) { return this.ignoreBuild(logger, "No environment variables found?!"); } final Map<String, String> envAdditions = new HashMap<String, String>(); String phid = environment.get(PhabricatorPlugin.PHID_FIELD); String diffID = environment.get(PhabricatorPlugin.DIFFERENTIAL_ID_FIELD); if (CommonUtils.isBlank(diffID)) { this.addShortText(build); this.ignoreBuild(logger, "No differential ID found."); return new Environment(){}; } FilePath arcWorkPath; if (this.workDir != null && this.workDir.length() > 0) { arcWorkPath = build.getWorkspace().child(workDir); } else { arcWorkPath = build.getWorkspace(); } LauncherFactory starter = new LauncherFactory(launcher, environment, listener.getLogger(), arcWorkPath); ConduitAPIClient conduitClient; try { conduitClient = getConduitClient(build.getParent(), logger); } catch (ConduitAPIException e) { e.printStackTrace(logger.getStream()); logger.warn(CONDUIT_TAG, e.getMessage()); return null; } DifferentialClient diffClient = new DifferentialClient(diffID, conduitClient); if (!CommonUtils.isBlank(phid)) { logger.info("harbormaster", "Sending Harbormaster BUILD_URL via PHID: " + phid); String buildUrl = environment.get("BUILD_URL"); Task.Result sendUriResult = new SendHarbormasterUriTask(logger, diffClient, phid, buildUrl).run(); if (sendUriResult != Task.Result.SUCCESS) { logger.info("harbormaster", "Unable to send BUILD_URL to Harbormaster"); } } Differential diff; try { diff = new Differential(diffClient.fetchDiff()); diff.setCommitMessage(diffClient.getCommitMessage(diff.getRevisionID(false))); diff.decorate(build, this.getPhabricatorURL(build.getParent())); logger.info(CONDUIT_TAG, "Fetching differential from Conduit API"); envAdditions.put(DIFFERENTIAL_AUTHOR, diff.getAuthorEmail()); envAdditions.put(DIFFERENTIAL_BASE_COMMIT, diff.getBaseCommit()); envAdditions.put(DIFFERENTIAL_BRANCH, diff.getBranch()); envAdditions.put(DIFFERENTIAL_SUMMARY, diff.getCommitMessage()); } catch (ConduitAPIException e) { e.printStackTrace(logger.getStream()); logger.warn(CONDUIT_TAG, "Unable to fetch differential from Conduit API"); logger.warn(CONDUIT_TAG, e.getMessage()); return null; } String baseCommit = "origin/master"; if (!applyToMaster) { baseCommit = diff.getBaseCommit(); } final String conduitToken = this.getConduitToken(build.getParent(), logger); Task.Result result = new ApplyPatchTask( logger, starter, baseCommit, diffID, conduitToken, getArcPath(), DEFAULT_GIT_PATH, createCommit, skipForcedClean, createBranch, patchWithForceFlag, scmType ).run(); if (result != Task.Result.SUCCESS) { logger.warn("arcanist", "Error applying arc patch; got non-zero exit code " + result); Task.Result failureResult = new SendHarbormasterResultTask(logger, diffClient, phid, false, null, null, null).run(); if (failureResult != Task.Result.SUCCESS) { // such failure, very broke logger.warn("arcanist", "Unable to notify harbormaster of patch failure"); } // Indicate failure return null; } return new Environment(){ @Override public void buildEnvVars(Map<String, String> env) { EnvVars envVars = new EnvVars(env); envVars.putAll(envAdditions); env.putAll(envVars); } }; } /** * Abort running builds when new build referencing same revision is scheduled to run */ @Override public void preCheckout(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { String abortOnRevisionId = getAbortOnRevisionId(build); // If ABORT_ON_REVISION_ID is available if (!CommonUtils.isBlank(abortOnRevisionId)) { // Create a cause of interruption PhabricatorCauseOfInterruption causeOfInterruption = new PhabricatorCauseOfInterruption(build.getUrl()); Run upstreamRun = getUpstreamRun(build); // Get the running builds that were scheduled before the current one RunList<AbstractBuild> runningBuilds = (RunList<AbstractBuild>) build.getProject().getBuilds(); for (AbstractBuild runningBuild : runningBuilds) { Executor executor = runningBuild.getExecutor(); Run runningBuildUpstreamRun = getUpstreamRun(runningBuild); // Ignore builds that were triggered by the same upstream build // Find builds triggered with the same ABORT_ON_REVISION_ID_FIELD if (runningBuild.isBuilding() && runningBuild.number < build.number && abortOnRevisionId.equals(getAbortOnRevisionId(runningBuild)) && (upstreamRun == null || runningBuildUpstreamRun == null || !upstreamRun.equals(runningBuildUpstreamRun)) && executor != null) { // Abort the builds executor.interrupt(Result.ABORTED, causeOfInterruption); } } } } protected Object readResolve() { if (scmType == null) { scmType = "git"; } return this; } private void addShortText(final AbstractBuild build) { build.addAction(PhabricatorPostbuildAction.createShortText("master", null)); } private Environment ignoreBuild(Logger logger, String message) { logger.info("ignore-build", message); return new Environment(){}; } private ConduitAPIClient getConduitClient(Job owner, Logger logger) throws ConduitAPIException { ConduitCredentials credentials = getConduitCredentials(owner); if (credentials == null) { throw new ConduitAPIException("No credentials configured for conduit"); } return new ConduitAPIClient(credentials.getGateway(), getConduitToken(owner, logger)); } private ConduitCredentials getConduitCredentials(Job owner) { return getDescriptor().getCredentials(owner); } @SuppressWarnings("UnusedDeclaration") public boolean isCreateCommit() { return createCommit; } @SuppressWarnings("UnusedDeclaration") public boolean isApplyToMaster() { return applyToMaster; } @SuppressWarnings("UnusedDeclaration") public boolean isCreateBranch() { return createBranch; } @SuppressWarnings("unused") public boolean isPatchWithForceFlag() { return patchWithForceFlag; } @SuppressWarnings("unused") public String getWorkDir() { return workDir; } @SuppressWarnings("unused") public String getScmType() { return scmType; } private String getPhabricatorURL(Job owner) { ConduitCredentials credentials = getConduitCredentials(owner); if (credentials != null) { return credentials.getUrl(); } return null; } private String getConduitToken(Job owner, Logger logger) { ConduitCredentials credentials = getConduitCredentials(owner); if (credentials != null) { return credentials.getToken().getPlainText(); } logger.warn("credentials", "No credentials configured."); return null; } /** * Return the path to the arcanist executable * @return a string, fully-qualified or not, could just be "arc" */ private String getArcPath() { final String providedPath = getDescriptor().getArcPath(); if (CommonUtils.isBlank(providedPath)) { return "arc"; } return providedPath; } // Overridden for better type safety. @Override public PhabricatorBuildWrapperDescriptor getDescriptor() { return (PhabricatorBuildWrapperDescriptor)super.getDescriptor(); } @VisibleForTesting static String getAbortOnRevisionId(AbstractBuild build) { ParametersAction parameters = build.getAction(ParametersAction.class); if (parameters != null) { ParameterValue parameterValue = parameters.getParameter( PhabricatorPlugin.ABORT_ON_REVISION_ID_FIELD); if (parameterValue != null) { return (String) parameterValue.getValue(); } } return null; } @VisibleForTesting static Run<?, ?> getUpstreamRun(AbstractBuild build) { CauseAction action = build.getAction(hudson.model.CauseAction.class); if (action != null) { Cause.UpstreamCause upstreamCause = action.findCause(hudson.model.Cause.UpstreamCause.class); if (upstreamCause != null) { return upstreamCause.getUpstreamRun(); } } return null; } }
package com.witchworks.common.brew; import com.witchworks.api.brew.IBrew; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntityCow; import net.minecraft.entity.passive.EntityMooshroom; import net.minecraft.init.Blocks; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; public class MycologicalCorruptionBrew extends BlockHitBrew implements IBrew { private final Map<Block, IBlockState> stateMap = new HashMap<>(); public MycologicalCorruptionBrew() { stateMap.put(Blocks.GRASS, Blocks.MYCELIUM.getDefaultState()); stateMap.put(Blocks.DIRT, Blocks.MYCELIUM.getDefaultState()); stateMap.put(Blocks.TALLGRASS, Blocks.RED_MUSHROOM.getDefaultState()); stateMap.put(Blocks.DEADBUSH, Blocks.BROWN_MUSHROOM.getDefaultState()); stateMap.put(Blocks.SAND, Blocks.DIRT.getDefaultState()); } @Override public void apply(World world, BlockPos pos, EntityLivingBase entity, int amplifier, int tick) { if (entity instanceof EntityCow) { EntityMooshroom mooshroom = new EntityMooshroom(world); EntityCow cow = new EntityCow(world); mooshroom.setPosition(pos.getX(), pos.getY(), pos.getZ()); cow.setPosition(pos.getX(), pos.getY(), pos.getZ()); world.removeEntity(cow); world.spawnEntity(mooshroom); } } @Override public int getColor() { return 0xFF80DC; } @Override public String getName() { return "mycological_corruption"; } @Override public void safeImpact(BlockPos pos, @Nullable EnumFacing side, World world, int amplifier) { int box = 1 + (int) ((float) amplifier / 2F); BlockPos posI = pos.add(box, box, box); BlockPos posF = pos.add(-box, -box, -box); Iterable<BlockPos> spots = BlockPos.getAllInBox(posI, posF); for (BlockPos spot : spots) { Block block = world.getBlockState(spot).getBlock(); boolean place = amplifier > 2 || world.rand.nextBoolean(); if (place && stateMap.containsKey(block)) { world.setBlockState(spot, stateMap.get(block), 3); } } } }
package com.witchworks.common.crafting.kettle; import com.witchworks.api.BrewRegistry; import com.witchworks.api.KettleRegistry; import com.witchworks.api.recipe.IEffectModifier; import com.witchworks.api.recipe.PotionHolder; import com.witchworks.common.block.ModBlocks; import com.witchworks.common.item.ModItems; import com.witchworks.common.potions.BrewUtils; import com.witchworks.common.potions.ModBrews; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.init.MobEffects; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.potion.Potion; import java.util.HashMap; import java.util.Map; @SuppressWarnings ("WeakerAccess") public final class KettleCrafting { private KettleCrafting() { } public static void init() { //Others KettleRegistry.registerKettleRecipe(new HoneyKettleCrafting()); //Exchanges KettleRegistry.addKettleExchange(getStack(ModItems.EMPTY_HONEYCOMB), getStack(ModItems.WAX), false); KettleRegistry.addKettleExchange(getStack(Items.BEEF), getStack(Items.COOKED_BEEF), false); KettleRegistry.addKettleExchange(getStack(Items.FISH, 3), getStack(Items.COOKED_FISH), true); KettleRegistry.addKettleExchange(getStack(Items.CHICKEN), getStack(Items.COOKED_CHICKEN), false); KettleRegistry.addKettleExchange(getStack(Items.MUTTON), getStack(Items.COOKED_MUTTON), false); KettleRegistry.addKettleExchange(getStack(Items.PORKCHOP), getStack(Items.COOKED_PORKCHOP), false); KettleRegistry.addKettleExchange(getStack(Items.RABBIT), getStack(Items.COOKED_RABBIT), false); KettleRegistry.addKettleExchange(getStack(Items.POTATO), getStack(Items.BAKED_POTATO), false); //Item Recipes //Potion Recipes KettleRegistry.registerKettlePotionRecipe(BrewUtils.createBrew(ModItems.BREW_PHIAL_DRINK //FIXME: Test , BrewRegistry.getDefault(ModBrews.SHELL_ARMOR)) , Items.IRON_INGOT, ModItems.SALT, ModBlocks.COQUINA, Items.FERMENTED_SPIDER_EYE, new ItemStack(Items.FISH, 1, 3), ModItems.KELP); KettleRegistry.registerKettlePotionRecipe(BrewUtils.createBrew(ModItems.BREW_PHIAL_DRINK //FIXME: Test , BrewRegistry.getDefault(ModBrews.INNER_FIRE)) , Items.BLAZE_POWDER, ModItems.SALT, ModItems.TIGERS_EYE, Items.MAGMA_CREAM, Items.FLINT, Blocks.NETHER_WART); KettleRegistry.registerKettlePotionRecipe(BrewUtils.createBrew(ModItems.BREW_PHIAL_DRINK //FIXME: Test , BrewRegistry.getDefault(ModBrews.SPIDER_NIGHTMARE)) , Items.SPIDER_EYE, Blocks.WEB, Items.FERMENTED_SPIDER_EYE, ModItems.BELLADONNA, Items.STRING, Items.SLIME_BALL); // - > Custom Brewing //Custom Effects KettleRegistry.addKettleEffectTo(getStack(Items.GOLDEN_CARROT), new PotionHolder(MobEffects.NIGHT_VISION, 500)); KettleRegistry.addKettleEffectTo(getStack(Items.MAGMA_CREAM), new PotionHolder(MobEffects.FIRE_RESISTANCE, 500)); KettleRegistry.addKettleEffectTo(getStack(Items.RABBIT_FOOT), new PotionHolder(MobEffects.JUMP_BOOST, 500)); KettleRegistry.addKettleEffectTo(getStack(Items.SUGAR), new PotionHolder(MobEffects.SPEED, 500)); KettleRegistry.addKettleEffectTo(getStack(Items.FISH, 3), new PotionHolder(MobEffects.WATER_BREATHING, 500)); KettleRegistry.addKettleEffectTo(getStack(Items.SPECKLED_MELON), new PotionHolder(MobEffects.INSTANT_HEALTH, 0)); KettleRegistry.addKettleEffectTo(getStack(Items.SPIDER_EYE), new PotionHolder(MobEffects.POISON, 500)); KettleRegistry.addKettleEffectTo(getStack(Items.GHAST_TEAR), new PotionHolder(MobEffects.REGENERATION, 500)); KettleRegistry.addKettleEffectTo(getStack(Items.BLAZE_POWDER), new PotionHolder(MobEffects.STRENGTH, 500)); KettleRegistry.addKettleEffectTo(getStack(Items.GOLDEN_APPLE), new PotionHolder(MobEffects.HEALTH_BOOST, 500)); KettleRegistry.addKettleEffectTo(getStack(Blocks.MELON_BLOCK), new PotionHolder(MobEffects.SATURATION, 500)); //TODO: Belladonna gives hallucinations not paralysis //KettleRegistry.addKettleEffectTo(getStack(ModItems.BELLADONNA), new PotionHolder(ModBrews.PARALYSIS_BREW, 240)); KettleRegistry.addKettleEffectTo(getStack(Items.BREAD), new PotionHolder(MobEffects.SATURATION, 600)); KettleRegistry.addKettleEffectTo(getStack(ModItems.BLOODSTONE), new PotionHolder(MobEffects.ABSORPTION, 600)); KettleRegistry.addKettleEffectTo(getStack(Blocks.RED_FLOWER), new PotionHolder(MobEffects.LUCK, 600)); KettleRegistry.addKettleEffectTo(getStack(ModItems.ASPHODEL), new PotionHolder(MobEffects.UNLUCK, 600)); KettleRegistry.addKettleEffectTo(getStack(ModItems.JASPER), new PotionHolder(MobEffects.RESISTANCE, 600)); KettleRegistry.addKettleEffectTo(getStack(Items.WHEAT), new PotionHolder(MobEffects.NAUSEA, 600)); KettleRegistry.addKettleEffectTo(getStack(Items.CHORUS_FRUIT), new PotionHolder(MobEffects.LEVITATION, 600)); KettleRegistry.addKettleEffectTo(getStack(Items.PRISMARINE_CRYSTALS), new PotionHolder(MobEffects.GLOWING, 600)); KettleRegistry.addKettleEffectTo(getStack(Items.NETHER_STAR), new PotionHolder(MobEffects.WITHER, 1000)); //Custom Modifiers KettleRegistry.addKettleModifierTo(getStack(Items.REDSTONE), effect -> effect.alter(10, 0)); KettleRegistry.addKettleModifierTo(getStack(Blocks.REDSTONE_BLOCK), effect -> effect.alter(90, 0)); KettleRegistry.addKettleModifierTo(getStack(Items.GLOWSTONE_DUST), effect -> effect.alter(-90, 1)); KettleRegistry.addKettleModifierTo(getStack(Blocks.GLOWSTONE), effect -> effect.alter(-100, 2)); KettleRegistry.addKettleModifierTo(getStack(Items.FERMENTED_SPIDER_EYE), new FermentedEyeModifier()); KettleRegistry.addKettleModifierTo(getStack(ModItems.QUARTZ), effect -> effect.alter(400, 0)); KettleRegistry.addKettleModifierTo(getStack(ModItems.NUUMMITE), effect -> effect.alter(-150, 3)); } /** * Who needs to write the whole thing? * @param item The item to make an ItemStack out of * @return An ItemStack */ private static ItemStack getStack(Item item) { return getStack(item, 0); } /** * Who needs to write the whole thing? * @param item The block to make an ItemStack out of * @param meta Meta of ItemStack * @return An ItemStack */ private static ItemStack getStack(Item item, int meta) { return new ItemStack(item, 1, meta); } /** * Who needs to write the whole thing? * @param block The block to make an ItemStack out of * @return An ItemStack */ @SuppressWarnings ("ConstantConditions") private static ItemStack getStack(Block block) { return getStack(Item.getItemFromBlock(block), 0); } /** * Who needs to write the whole thing? * @param block The block to make an ItemStack out of * @return An ItemStack */ @SuppressWarnings ("ConstantConditions") private static ItemStack getStack(Block block, int meta) { return getStack(Item.getItemFromBlock(block), meta); } private static class FermentedEyeModifier implements IEffectModifier { private Map<Potion, Potion> potionMap = new HashMap<>(); FermentedEyeModifier() { potionMap.put(MobEffects.NIGHT_VISION, MobEffects.INVISIBILITY); potionMap.put(MobEffects.JUMP_BOOST, MobEffects.SLOWNESS); potionMap.put(MobEffects.SPEED, MobEffects.SLOWNESS); potionMap.put(MobEffects.INSTANT_HEALTH, MobEffects.INSTANT_DAMAGE); potionMap.put(MobEffects.REGENERATION, MobEffects.POISON); potionMap.put(MobEffects.POISON, MobEffects.INSTANT_DAMAGE); potionMap.put(MobEffects.STRENGTH, MobEffects.WEAKNESS); } @Override public PotionHolder apply(PotionHolder effect) { if (potionMap.containsKey(effect.getPotion())) { effect.setPotion(potionMap.get(effect.getPotion())); } return effect; } } }
package digital.loom.rhizome.authentication; import javax.inject.Inject; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.context.SecurityContextPersistenceFilter; import com.auth0.Auth0; import com.auth0.authentication.AuthenticationAPIClient; import com.auth0.jwt.Algorithm; import com.auth0.spring.security.api.Auth0AuthenticationEntryPoint; import com.auth0.spring.security.api.Auth0AuthenticationFilter; import com.auth0.spring.security.api.Auth0AuthenticationProvider; import com.auth0.spring.security.api.Auth0AuthorityStrategy; import com.auth0.spring.security.api.Auth0CORSFilter; import com.auth0.spring.security.api.authority.AuthorityStrategy; import com.kryptnostic.rhizome.core.JettyAnnotationConfigurationHack; import com.kryptnostic.rhizome.core.RhizomeSecurity; import digital.loom.rhizome.configuration.auth0.Auth0Configuration; /** * Including this pod will enable using Auth0 as an authentication source. It based off the one provided by auth0 in the * spring-mvc pod, but differs in that it enables {@code @Secured} annotations, disables debug, and allows configuration * using properties file. * * @author Matthew Tamayo-Rios &lt;matthew@kryptnostic.com&gt; * */ @EnableGlobalMethodSecurity( securedEnabled = true, prePostEnabled = true ) @EnableWebSecurity( debug = false ) public class Auth0SecurityPod extends WebSecurityConfigurerAdapter { @Inject private Auth0Configuration configuration; @Inject private Auth0 auth0; static { JettyAnnotationConfigurationHack.registerInitializer( RhizomeSecurity.class.getCanonicalName() ); } @Bean( name = "auth0AuthenticationManager" ) public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Bean public Auth0CORSFilter simpleCORSFilter() { return new Auth0CORSFilter(); } @Bean( name = "authorityStrategy" ) public AuthorityStrategy authorityStrategy() { if ( !Auth0AuthorityStrategy.contains( configuration.getAuthorityStrategy() ) ) { throw new IllegalStateException( "Configuration error, illegal authority strategy" ); } return Auth0AuthorityStrategy.valueOf( configuration.getAuthorityStrategy() ).getStrategy(); } @Bean( name = "auth0AuthenticationProvider" ) public Auth0AuthenticationProvider auth0AuthenticationProvider() { final ConfigurableAuth0AuthenticationProvider authenticationProvider = getAuthenticationProvider(); authenticationProvider.setDomain( configuration.getDomain() ); authenticationProvider.setIssuer( configuration.getIssuer() ); authenticationProvider.setClientId( configuration.getClientId() ); authenticationProvider.setClientSecret( configuration.getClientSecret() ); authenticationProvider.setSecuredRoute( configuration.getSecuredRoute() ); authenticationProvider.setAuthorityStrategy( authorityStrategy() ); authenticationProvider.setBase64EncodedSecret( configuration.isBase64EncodedSecret() ); authenticationProvider.setSigningAlgorithm( Algorithm.valueOf( configuration.getSigningAlgorithm() ) ); return authenticationProvider; } @Bean( name = "auth0EntryPoint" ) public AuthenticationEntryPoint auth0AuthenticationEntryPoint() { return new Auth0AuthenticationEntryPoint(); } @Bean( name = "auth0Filter" ) public Auth0AuthenticationFilter auth0AuthenticationFilter( final AuthenticationEntryPoint entryPoint ) { final Auth0AuthenticationFilter filter = new CookieReadingAuth0AuthenticationFilter(); filter.setEntryPoint( entryPoint ); return filter; } @Override protected void configure( final AuthenticationManagerBuilder auth ) throws Exception { auth.authenticationProvider( auth0AuthenticationProvider() ); } @Override public void configure( WebSecurity web ) throws Exception { /** * Lightweight default configuration that offers basic authorization checks for authenticated users on secured * endpoint, and sets up a Principal user object with granted authorities * <p> * For simple apps, this is sufficient, however for applications wishing to specify fine-grained endpoint access * restrictions, use Role / Group level endpoint authorization etc, then this configuration should be disabled and a * copy, augmented with your own requirements provided. See Sample app for example * * Override this function in subclass to apply custom authentication / authorization strategies to your application * endpoints */ protected void authorizeRequests( HttpSecurity http ) throws Exception { http.authorizeRequests() /** * Override this to modify the type of ConfigurableAuthenticationProvider for performing authentication. * @return The Auth0AuthenticationProvider to use for performing authentications. */ protected ConfigurableAuth0AuthenticationProvider getAuthenticationProvider() { return new ConfigurableAuth0AuthenticationProvider( getAuthenticationApiClient() ); } protected AuthenticationAPIClient getAuthenticationApiClient() { return auth0.newAuthenticationAPIClient(); } }
package example; //-*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: //@homepage@ import java.awt.*; import java.awt.event.*; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.List; import javax.swing.*; import javax.swing.event.*; public final class MainPanel extends JPanel { private final JPopupMenu popup = new JPopupMenu(); public MainPanel() { super(new BorderLayout()); add(new JLabel("SystemTray.isSupported(): " + SystemTray.isSupported()), BorderLayout.NORTH); ButtonGroup group = new ButtonGroup(); Box box = Box.createVerticalBox(); for (LookAndFeelEnum lnf: LookAndFeelEnum.values()) { JRadioButton rb = new JRadioButton(new ChangeLookAndFeelAction(lnf, Arrays.asList(popup))); group.add(rb); box.add(rb); } box.add(Box.createVerticalGlue()); box.setBorder(BorderFactory.createEmptyBorder(5, 25, 5, 25)); add(box); setPreferredSize(new Dimension(320, 240)); EventQueue.invokeLater(() -> { Container c = getTopLevelAncestor(); if (c instanceof JFrame) { initPopupMenu((JFrame) c); } }); } private void initPopupMenu(JFrame frame) { // This code is inspired from: //JWindow dummy = new JWindow(); //Ubuntu? JDialog dummy = new JDialog(); dummy.setUndecorated(true); //dummy.setAlwaysOnTop(true); Image image = new ImageIcon(getClass().getResource("16x16.png")).getImage(); TrayIcon icon = new TrayIcon(image, "TRAY", null); icon.addMouseListener(new TrayIconPopupMenuHandler(popup, dummy)); try { SystemTray.getSystemTray().add(icon); } catch (AWTException ex) { ex.printStackTrace(); } //init JPopupMenu popup.addPopupMenuListener(new PopupMenuListener() { @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { /* not needed */ } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { dummy.setVisible(false); } @Override public void popupMenuCanceled(PopupMenuEvent e) { dummy.setVisible(false); } }); popup.add(new JCheckBoxMenuItem("JCheckBoxMenuItem")); popup.add(new JRadioButtonMenuItem("JRadioButtonMenuItem")); popup.add(new JRadioButtonMenuItem("JRadioButtonMenuItem aaaaaaaaaaa")); popup.add("Open").addActionListener(e -> { frame.setExtendedState(Frame.NORMAL); frame.setVisible(true); }); popup.add("Exit").addActionListener(e -> { SystemTray tray = SystemTray.getSystemTray(); for (TrayIcon ti: tray.getTrayIcons()) { tray.remove(ti); } for (Frame f: Frame.getFrames()) { f.dispose(); } //tray.remove(icon); //frame.dispose(); //dummy.dispose(); }); } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("@title@"); if (SystemTray.isSupported()) { frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); frame.addWindowStateListener(e -> { if (e.getNewState() == Frame.ICONIFIED) { e.getWindow().dispose(); } }); } else { frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } final class TrayIconPopupMenuUtil { private TrayIconPopupMenuUtil() { /* Singleton */ } // Try to find GraphicsConfiguration, that includes mouse pointer position private static GraphicsConfiguration getGraphicsConfiguration(Point p) { GraphicsConfiguration gc = null; for (GraphicsDevice gd: GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()) { if (gd.getType() == GraphicsDevice.TYPE_RASTER_SCREEN) { GraphicsConfiguration dgc = gd.getDefaultConfiguration(); if (dgc.getBounds().contains(p)) { gc = dgc; break; } } } return gc; } //Copied from JPopupMenu.java: JPopupMenu#adjustPopupLocationToFitScreen(...) public static Point adjustPopupLocation(JPopupMenu popup, int xposition, int yposition) { Point p = new Point(xposition, yposition); if (GraphicsEnvironment.isHeadless()) { return p; } Rectangle screenBounds; GraphicsConfiguration gc = getGraphicsConfiguration(p); // If not found and popup have invoker, ask invoker about his gc if (Objects.isNull(gc) && Objects.nonNull(popup.getInvoker())) { gc = popup.getInvoker().getGraphicsConfiguration(); } if (Objects.isNull(gc)) { // If we don't have GraphicsConfiguration use primary screen screenBounds = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); } else { // If we have GraphicsConfiguration use it to get // screen bounds screenBounds = gc.getBounds(); } Dimension size = popup.getPreferredSize(); // Use long variables to prevent overflow long pw = (long) p.x + (long) size.width; long ph = (long) p.y + (long) size.height; if (pw > screenBounds.x + screenBounds.width) { p.x -= size.width; } if (ph > screenBounds.y + screenBounds.height) { p.y -= size.height; } // Change is made to the desired (X, Y) values, when the // PopupMenu is too tall OR too wide for the screen p.x = Math.max(p.x, screenBounds.x); p.y = Math.max(p.y, screenBounds.y); return p; } } class TrayIconPopupMenuHandler extends MouseAdapter { private final JPopupMenu popup; private final Window dummy; protected TrayIconPopupMenuHandler(JPopupMenu popup, Window dummy) { super(); this.popup = popup; this.dummy = dummy; } private void showJPopupMenu(MouseEvent e) { if (e.isPopupTrigger()) { Point p = TrayIconPopupMenuUtil.adjustPopupLocation(popup, e.getX(), e.getY()); dummy.setLocation(p); dummy.setVisible(true); //dummy.toFront(); popup.show(dummy, 0, 0); } } @Override public void mouseReleased(MouseEvent e) { showJPopupMenu(e); } @Override public void mousePressed(MouseEvent e) { showJPopupMenu(e); } } enum LookAndFeelEnum { Metal("javax.swing.plaf.metal.MetalLookAndFeel"), Mac("com.sun.java.swing.plaf.mac.MacLookAndFeel"), Motif("com.sun.java.swing.plaf.motif.MotifLookAndFeel"), Windows("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"), GTK("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"), Nimbus("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); private final String clazz; LookAndFeelEnum(String clazz) { this.clazz = clazz; } public String getClassName() { return clazz; } } class ChangeLookAndFeelAction extends AbstractAction { private final String lnf; private final List<? extends JComponent> list; protected ChangeLookAndFeelAction(LookAndFeelEnum lnfe, List<? extends JComponent> list) { super(lnfe.toString()); this.list = list; this.lnf = lnfe.getClassName(); this.setEnabled(isAvailableLookAndFeel(lnf)); } private static boolean isAvailableLookAndFeel(String laf) { try { Class<?> lnfClass = Class.forName(laf); LookAndFeel newLAF = (LookAndFeel) lnfClass.getConstructor().newInstance(); return newLAF.isSupportedLookAndFeel(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException ex) { return false; } } @Override public void actionPerformed(ActionEvent e) { try { UIManager.setLookAndFeel(lnf); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); System.out.println("Failed loading L&F: " + lnf); } for (Frame f: Frame.getFrames()) { SwingUtilities.updateComponentTreeUI(f); f.pack(); } list.forEach(SwingUtilities::updateComponentTreeUI); } }
package edu.wright.hendrix11.d3.wordCloud; import edu.wright.hendrix11.d3.MasterComponent; import javax.faces.application.ResourceDependencies; import javax.faces.application.ResourceDependency; import javax.faces.component.FacesComponent; import java.util.Map; /** * @author Joe Hendrix */ @FacesComponent(value = WordCloudComponent.COMPONENT_TYPE) @ResourceDependencies({ @ResourceDependency(library = "js", name = "d3.min.js"), @ResourceDependency(library = "js", name = "d3.layout.cloud.js") }) public class WordCloudComponent extends MasterComponent { public static final String COMPONENT_FAMILY = "edu.wright.hendrix11.d3"; public static final String COMPONENT_TYPE = "edu.wright.hendrix11.d3.wordCloud.WordCloudComponent"; public static final String DEFAULT_RENDERER = "edu.wright.hendrix11.d3.chart.WordCloudRenderer"; public WordCloudComponent() { setRendererType(DEFAULT_RENDERER); } @Override public String getFamily() { return COMPONENT_FAMILY; } /** * Returns the width of the entire cloud. * * @return the width of the entire cloud */ public Integer getWidth() { return (Integer) getStateHelper().eval(PropertyKeys.width, null); } /** * Sets the width of the entire cloud. * * @param width the width of the entire cloud */ public void setWidth(Integer width) { getStateHelper().put(PropertyKeys.width, width); } /** * Returns the height of the entire cloud. * * @return the height of the entire cloud */ public Integer getHeight() { return (Integer) getStateHelper().eval(PropertyKeys.height, null); } /** * Sets the height of the entire cloud. * * @param height the height of the entire cloud */ public void setHeight(Integer height) { getStateHelper().put(PropertyKeys.height, height); } /** * Returns the numerical padding for each word / String. * * @return the numerical padding for each word / String */ public Integer getPadding() { return (Integer) getStateHelper().eval(PropertyKeys.padding, null); } /** * Sets the numerical padding for each word / String. * * @param padding the numerical padding for each word / String */ public void setPadding(Integer padding) { getStateHelper().put(PropertyKeys.padding, padding); } /** * Returns the font face for each word. * * @return the font face for each word */ public String getFont() { return (String) getStateHelper().eval(PropertyKeys.font, null); } /** * Sets the font face for each word. * * @param font the font face for each word */ public void setFont(String font) { getStateHelper().put(PropertyKeys.font, font); } /** * Returns the map of words (or rather, Strings, as they can have spaces) to the * font size of that word. Typcially the size will be the number of occurences, * but that is not a requirement. * * @return the map of words to the font size of that word */ public Map<String, Integer> getWords() { return (Map<String, Integer>) getStateHelper().eval(PropertyKeys.words, null); } /** * Sets the map of words (or rather, Strings, as they can have spaces) to the * font size of that word. Typcially the size will be the number of occurences, * but that is not a requirement. * * @param words the map of words to the font size of that word */ public void setWords(Map<String, Integer> words) { getStateHelper().put(PropertyKeys.words, words); } protected enum PropertyKeys { width, height, padding, font, words } }
package eu.amidst.core.modelstructure; import eu.amidst.core.database.statics.readers.DistType; import eu.amidst.core.distribution.*; import eu.amidst.core.header.dynamics.DynamicModelHeader; import eu.amidst.core.header.Variable; import java.util.ArrayList; import java.util.List; public class DynamicBayesianNetwork{ private ParentSet[] parentSetTime0; private ParentSet[] parentSetTimeT; private Distribution[] distributionsTime0; private Distribution[] distributionsTimeT; private DynamicModelHeader modelHeader; private DynamicBayesianNetwork(DynamicModelHeader modelHeader){ this.modelHeader = modelHeader; this.parentSetTime0 = new ParentSet[modelHeader.getNumberOfVars()]; this.parentSetTimeT = new ParentSet[modelHeader.getNumberOfVars()]; this.distributionsTime0 = new Distribution[modelHeader.getNumberOfVars()]; this.distributionsTimeT = new Distribution[modelHeader.getNumberOfVars()]; for (int i=0;i<modelHeader.getNumberOfVars();i++) { parentSetTime0[i] = ParentSet.newParentSet(); parentSetTimeT[i] = ParentSet.newParentSet(); } } public static DynamicBayesianNetwork newDynamicBayesianNetwork(DynamicModelHeader modelHeader){ return new DynamicBayesianNetwork(modelHeader); } public void initializeDistributions() { //Parents should have been assigned before calling this method (from dynamicmodelling.models) for (Variable var : modelHeader.getVariables()) { /* Distributions at time t */ initializeDistributionsFor(var, distributionsTimeT, parentSetTimeT); /* Distributions at time 0 */ initializeDistributionsFor(var, distributionsTime0, parentSetTime0); } } private void initializeDistributionsFor(Variable var, Distribution[] distributionsTimeX, ParentSet[] parentSetTimeX){ int varID = var.getVarID(); if (parentSetTimeT[varID].getNumberOfParents() == 0) { switch (var.getDistributionType()) { case MULTINOMIAL: distributionsTimeX[varID] = new Multinomial(var); break; case GAUSSIAN: distributionsTimeX[varID] = new Normal(var); break; default: throw new IllegalArgumentException("Error in variable distribution"); } } else { List<Variable> multinomialParents = new ArrayList<Variable>(); List<Variable> normalParents = new ArrayList<Variable>(); switch (var.getDistributionType()) { case MULTINOMIAL: /* The parents of a multinomial variable should always be multinomial */ distributionsTimeX[varID] = new Multinomial_MultinomialParents(var, parentSetTimeX[varID].getParents()); case GAUSSIAN: /* The parents of a gaussian variable are either multinomial and/or normal */ for (Variable v : parentSetTimeT[varID].getParents()) { if (v.getDistributionType().compareTo(DistType.MULTINOMIAL) == 0) { multinomialParents.add(v); } else { normalParents.add(v); } } if (normalParents.size() == 0) { distributionsTimeX[varID] = new Normal_MultinomialParents(var, parentSetTimeX[varID].getParents()); } else if (multinomialParents.size() == 0){ distributionsTimeX[varID] = new CLG(var, parentSetTimeX[varID].getParents()); } else{ distributionsTimeX[varID] = new Normal_MultinomialNormalParents(var, parentSetTimeX[varID].getParents()); } default: throw new IllegalArgumentException("Error in variable distribution"); } } } /* Methods accessing the variables in the modelHeader*/ public int getNumberOfNodes() { return this.modelHeader.getNumberOfVars(); } public DynamicModelHeader getDynamicModelHeader() { return this.modelHeader; } public Variable getVariableById(int varID) { return this.modelHeader.getVariableById(varID); } public Variable getTemporalCloneById(int varID) { return this.modelHeader.getTemporalCloneById(varID); } public Variable getTemporalCloneFromVariable(Variable variable) { return this.modelHeader.getTemporalCloneFromVariable(variable); } /* Methods accessing structure at time T*/ public ParentSet getParentSetTimeT(Variable var) { return this.parentSetTimeT[var.getVarID()]; } public Distribution getDistributionTimeT(Variable var) { return this.distributionsTimeT[var.getVarID()]; } /* Methods accessing structure at time 0*/ public ParentSet getParentSetTime0(Variable var) { return this.parentSetTime0[var.getVarID()]; } public Distribution getDistributionTime0(Variable var) { return this.distributionsTime0[var.getVarID()]; } }
package org.jboss.arquillian.performance.ejb; import javax.ejb.EJB; import org.jboss.arquillian.api.Deployment; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(org.jboss.arquillian.junit.Arquillian.class) public class WorkHardEjbTestCase { @EJB private WorkHard hardWorker; @Deployment public static JavaArchive createTestArchive() { return ShrinkWrap.create(JavaArchive.class, "test.jar") .addPackage( WorkHard.class.getPackage() ); } @Test public void testHardWorker() { Assert.assertEquals(21d, hardWorker.workHard(), 0d); } }
package mcjty.rftoolsdim.dimensions.dimlets; import mcjty.lib.varia.WeightedRandomSelector; import mcjty.rftoolsdim.config.DimletConfiguration; import mcjty.rftoolsdim.config.Settings; import mcjty.rftoolsdim.dimensions.dimlets.types.DimletType; import mcjty.rftoolsdim.dimensions.types.ControllerType; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.world.biome.Biome; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Random; public class DimletRandomizer { public static final int RARITY_0 = 0; public static final int RARITY_1 = 1; public static final int RARITY_2 = 2; public static final int RARITY_3 = 3; public static final int RARITY_4 = 4; public static final int RARITY_5 = 5; public static final int RARITY_6 = 6; // All dimlet ids in a weighted random selector based on rarity. private static WeightedRandomSelector<Integer,DimletKey> randomDimlets; private static WeightedRandomSelector<Integer,DimletKey> randomUncraftableDimlets; private static WeightedRandomSelector<Integer,DimletKey> randomMaterialDimlets; private static WeightedRandomSelector<Integer,DimletKey> randomLiquidDimlets; private static WeightedRandomSelector<Integer,DimletKey> randomMobDimlets; private static WeightedRandomSelector<Integer,DimletKey> randomStructureDimlets; private static WeightedRandomSelector<Integer,DimletKey> randomEffectDimlets; private static WeightedRandomSelector<Integer,DimletKey> randomFeatureDimlets; private static WeightedRandomSelector<Integer,DimletKey> randomTerrainDimlets; private static WeightedRandomSelector<Integer,DimletKey> randomSkyDimlets; private static WeightedRandomSelector<Integer,DimletKey> randomSkyBodyDimlets; private static WeightedRandomSelector<Integer,DimletKey> randomWeatherDimlets; public static void init() { randomDimlets = null; randomUncraftableDimlets = null; randomMaterialDimlets = null; randomLiquidDimlets = null; randomMobDimlets = null; randomStructureDimlets = null; randomEffectDimlets = null; randomFeatureDimlets = null; randomTerrainDimlets = null; randomSkyDimlets = null; randomSkyBodyDimlets = null; randomWeatherDimlets = null; } private static void setupWeightedRandomList() { if (randomDimlets != null) { return; } Map<DimletKey, Settings> knownDimlets = KnownDimletConfiguration.getKnownDimlets(); float rarity0 = DimletConfiguration.rarity0; float rarity1 = DimletConfiguration.rarity1; float rarity2 = DimletConfiguration.rarity2; float rarity3 = DimletConfiguration.rarity3; float rarity4 = DimletConfiguration.rarity4; float rarity5 = DimletConfiguration.rarity5; float rarity6 = DimletConfiguration.rarity6; randomDimlets = new WeightedRandomSelector<>(); setupRarity(randomDimlets, rarity0, rarity1, rarity2, rarity3, rarity4, rarity5, rarity6); randomUncraftableDimlets = new WeightedRandomSelector<>(); setupRarity(randomUncraftableDimlets, rarity0, rarity1, rarity2, rarity3, rarity4, rarity5, rarity6); for (Map.Entry<DimletKey, Settings> entry : knownDimlets.entrySet()) { DimletKey key = entry.getKey(); Settings settings = KnownDimletConfiguration.getSettings(key); if (settings == null) { continue; } if (!settings.isWorldgen()) { continue; } randomDimlets.addItem(entry.getValue().getRarity(), key); if (key.getType() == DimletType.DIMLET_MATERIAL) { if (randomMaterialDimlets == null) { randomMaterialDimlets = new WeightedRandomSelector<>(); setupRarity(randomMaterialDimlets, rarity0, rarity1, rarity2, rarity3, rarity4, rarity5, rarity6); } randomMaterialDimlets.addItem(entry.getValue().getRarity(), key); } else if (key.getType() == DimletType.DIMLET_LIQUID) { if (randomLiquidDimlets == null) { randomLiquidDimlets = new WeightedRandomSelector<>(); setupRarity(randomLiquidDimlets, rarity0, rarity1, rarity2, rarity3, rarity4, rarity5, rarity6); } randomLiquidDimlets.addItem(entry.getValue().getRarity(), key); } else if (key.getType() == DimletType.DIMLET_MOB) { if (randomMobDimlets == null) { randomMobDimlets = new WeightedRandomSelector<>(); setupRarity(randomMobDimlets, rarity0, rarity1, rarity2, rarity3, rarity4, rarity5, rarity6); } randomMobDimlets.addItem(entry.getValue().getRarity(), key); } else if (key.getType() == DimletType.DIMLET_EFFECT) { if (randomEffectDimlets == null) { randomEffectDimlets = new WeightedRandomSelector<>(); setupRarity(randomEffectDimlets, rarity0, rarity1, rarity2, rarity3, rarity4, rarity5, rarity6); } randomEffectDimlets.addItem(entry.getValue().getRarity(), key); randomUncraftableDimlets.addItem(entry.getValue().getRarity(), key); } else if (key.getType() == DimletType.DIMLET_FEATURE) { if (randomFeatureDimlets == null) { randomFeatureDimlets = new WeightedRandomSelector<>(); setupRarity(randomFeatureDimlets, rarity0, rarity1, rarity2, rarity3, rarity4, rarity5, rarity6); } randomFeatureDimlets.addItem(entry.getValue().getRarity(), key); randomUncraftableDimlets.addItem(entry.getValue().getRarity(), key); } else if (key.getType() == DimletType.DIMLET_STRUCTURE) { if (randomStructureDimlets == null) { randomStructureDimlets = new WeightedRandomSelector<>(); setupRarity(randomStructureDimlets, rarity0, rarity1, rarity2, rarity3, rarity4, rarity5, rarity6); } randomStructureDimlets.addItem(entry.getValue().getRarity(), key); randomUncraftableDimlets.addItem(entry.getValue().getRarity(), key); } else if (key.getType() == DimletType.DIMLET_TERRAIN) { if (randomTerrainDimlets == null) { randomTerrainDimlets = new WeightedRandomSelector<>(); setupRarity(randomTerrainDimlets, rarity0, rarity1, rarity2, rarity3, rarity4, rarity5, rarity6); } randomTerrainDimlets.addItem(entry.getValue().getRarity(), key); randomUncraftableDimlets.addItem(entry.getValue().getRarity(), key); } else if (key.getType() == DimletType.DIMLET_WEATHER) { if (randomWeatherDimlets == null) { randomWeatherDimlets = new WeightedRandomSelector<>(); setupRarity(randomWeatherDimlets, rarity0, rarity1, rarity2, rarity3, rarity4, rarity5, rarity6); } randomWeatherDimlets.addItem(entry.getValue().getRarity(), key); randomUncraftableDimlets.addItem(entry.getValue().getRarity(), key); } else if (key.getType() == DimletType.DIMLET_SKY) { if (randomSkyDimlets == null) { randomSkyDimlets = new WeightedRandomSelector<>(); setupRarity(randomSkyDimlets, rarity0, rarity1, rarity2, rarity3, rarity4, rarity5, rarity6); } randomSkyDimlets.addItem(entry.getValue().getRarity(), key); if (SkyRegistry.isSkyBody(key)) { if (randomSkyBodyDimlets == null) { randomSkyBodyDimlets = new WeightedRandomSelector<>(); setupRarity(randomSkyBodyDimlets, rarity0, rarity1, rarity2, rarity3, rarity4, rarity5, rarity6); } randomSkyBodyDimlets.addItem(entry.getValue().getRarity(), key); } randomUncraftableDimlets.addItem(entry.getValue().getRarity(), key); } } } private static void setupRarity(WeightedRandomSelector<Integer,DimletKey> randomDimlets, float rarity0, float rarity1, float rarity2, float rarity3, float rarity4, float rarity5, float rarity6) { randomDimlets.addRarity(RARITY_0, rarity0); randomDimlets.addRarity(RARITY_1, rarity1); randomDimlets.addRarity(RARITY_2, rarity2); randomDimlets.addRarity(RARITY_3, rarity3); randomDimlets.addRarity(RARITY_4, rarity4); randomDimlets.addRarity(RARITY_5, rarity5); randomDimlets.addRarity(RARITY_6, rarity6); } public static DimletKey getRandomTerrain(Random random) { setupWeightedRandomList(); return randomTerrainDimlets == null ? null : randomTerrainDimlets.select(random); } public static DimletKey getRandomFeature(Random random) { setupWeightedRandomList(); return randomFeatureDimlets == null ? null : randomFeatureDimlets.select(random); } public static DimletKey getRandomEffect(Random random) { setupWeightedRandomList(); return randomEffectDimlets == null ? null : randomEffectDimlets.select(random); } public static DimletKey getRandomStructure(Random random) { setupWeightedRandomList(); return randomStructureDimlets == null ? null : randomStructureDimlets.select(random); } public static DimletKey getRandomFluidBlock(Random random) { setupWeightedRandomList(); return randomLiquidDimlets == null ? null : randomLiquidDimlets.select(random); } public static DimletKey getRandomMaterialBlock(Random random) { setupWeightedRandomList(); return randomMaterialDimlets == null ? null : randomMaterialDimlets.select(random); } public static DimletKey getRandomSky(Random random) { setupWeightedRandomList(); return randomSkyDimlets == null ? null : randomSkyDimlets.select(random); } public static DimletKey getRandomWeather(Random random) { setupWeightedRandomList(); return randomWeatherDimlets == null ? null : randomWeatherDimlets.select(random); } public static DimletKey getRandomSkyBody(Random random) { setupWeightedRandomList(); return randomSkyBodyDimlets == null ? null : randomSkyBodyDimlets.select(random); } public static DimletKey getRandomController(Random random) { ControllerType type = ControllerType.values()[random.nextInt(ControllerType.values().length)]; return new DimletKey(DimletType.DIMLET_CONTROLLER, type.getId()); } public static DimletKey getRandomBiome(Random random) { List<ResourceLocation> keys = new ArrayList<>(Biome.REGISTRY.getKeys()); int size = keys.size(); while(true) { Biome biome = Biome.REGISTRY.getObject(keys.get(random.nextInt(size))); if (biome != null) { return new DimletKey(DimletType.DIMLET_BIOME, biome.getBiomeName()); } } } public static DimletKey getRandomMob(Random random) { setupWeightedRandomList(); return randomMobDimlets == null ? null : randomMobDimlets.select(random); } public static WeightedRandomSelector<Integer, DimletKey> getRandomDimlets() { setupWeightedRandomList(); return randomDimlets; } public static WeightedRandomSelector<Integer, DimletKey> getRandomUncraftableDimlets() { setupWeightedRandomList(); return randomUncraftableDimlets; } private static WeightedRandomSelector<Integer, ItemStack> dimletPartDistribution; // Get a random part item public static ItemStack getRandomPart(Random random) { if (dimletPartDistribution == null) { dimletPartDistribution = new WeightedRandomSelector<>(); dimletPartDistribution.addRarity(RARITY_0, DimletConfiguration.rarity0); dimletPartDistribution.addRarity(RARITY_1, DimletConfiguration.rarity1); dimletPartDistribution.addRarity(RARITY_2, DimletConfiguration.rarity2); dimletPartDistribution.addRarity(RARITY_3, DimletConfiguration.rarity3); dimletPartDistribution.addRarity(RARITY_4, DimletConfiguration.rarity4); dimletPartDistribution.addRarity(RARITY_5, DimletConfiguration.rarity5); dimletPartDistribution.addRarity(RARITY_6, DimletConfiguration.rarity6); List<List<ItemStack>> stacks = KnownDimletConfiguration.getRandomPartLists(); for (int i = 0 ; i < stacks.size() ; i++) { final int finalI = i; stacks.get(i).stream().forEach(s -> dimletPartDistribution.addItem(finalI, s)); } } return dimletPartDistribution.select(random).copy(); } }
package me.nallar.javatransformer.internal; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.ImportDeclaration; import com.github.javaparser.ast.Node; import com.github.javaparser.ast.TypeParameter; import com.github.javaparser.ast.type.ClassOrInterfaceType; import com.github.javaparser.ast.type.PrimitiveType; import com.github.javaparser.ast.type.VoidType; import lombok.NonNull; import lombok.val; import me.nallar.javatransformer.api.TransformationException; import me.nallar.javatransformer.api.Type; import me.nallar.javatransformer.internal.util.JVMUtil; import me.nallar.javatransformer.internal.util.NodeUtil; import java.util.*; public class ResolutionContext { @NonNull private final String packageName; @NonNull private final List<ImportDeclaration> imports; @NonNull private final Iterable<TypeParameter> typeParameters; private ResolutionContext(String packageName, List<ImportDeclaration> imports, Iterable<TypeParameter> typeParameters) { this.packageName = packageName; this.imports = imports; this.typeParameters = typeParameters; } public static ResolutionContext of(String packageName, List<ImportDeclaration> imports, Iterable<TypeParameter> typeParameters) { return new ResolutionContext(packageName, imports, typeParameters); } public static ResolutionContext of(Node node) { CompilationUnit cu = NodeUtil.getParentNode(node, CompilationUnit.class); String packageName = NodeUtil.qualifiedName(cu.getPackage().getName()); List<TypeParameter> typeParameters = NodeUtil.getTypeParameters(node); return new ResolutionContext(packageName, cu.getImports(), typeParameters); } static boolean hasPackages(String name) { // Guesses whether input name includes packages or is just classes return !Character.isUpperCase(name.charAt(0)) && name.indexOf('.') != -1; } static String extractGeneric(String name) { int leftBracket = name.indexOf('<'); int rightBracket = name.indexOf('>'); if (leftBracket == -1 && rightBracket == -1) return null; if (rightBracket == name.length() - 1 && leftBracket != -1 && leftBracket < rightBracket) return name.substring(leftBracket + 1, rightBracket); throw new TransformationException("Mismatched angled brackets in: " + name); } static String extractReal(String name) { int bracket = name.indexOf('<'); return bracket == -1 ? name : name.substring(0, bracket); } static Type sanityCheck(Type type) { if (type.isClassType() && (type.getClassName().endsWith(".") || !type.getClassName().contains("."))) { throw new TransformationException("Unexpected class name (incorrect dots) in type: " + type); } return type; } private static String classOf(ImportDeclaration importDeclaration) { return NodeUtil.qualifiedName(importDeclaration.getName()); } public Type resolve(com.github.javaparser.ast.type.Type type) { if (type instanceof ClassOrInterfaceType) { return resolve(((ClassOrInterfaceType) type).getName()); } else if (type instanceof PrimitiveType) { return new Type(JVMUtil.primitiveTypeToDescriptor(((PrimitiveType) type).getType().name().toLowerCase())); } else if (type instanceof VoidType) { return new Type("V"); } else { // TODO: 23/01/2016 Is this behaviour correct? return resolve(type.toStringWithoutComments()); } } /** * Resolves a given name to a JVM type string. * <p> * EG: * ArrayList -> Ljava/util/ArrayList; * T -> TT; * boolean -> Z * * @param name Name to resolve * @return Type containing resolved name with descriptor/signature */ public Type resolve(String name) { if (name == null) return null; String real = extractReal(name); Type type = resolveReal(real); String generic = extractGeneric(name); Type genericType = resolve(generic); if (type == null || (generic != null && genericType == null)) throw new TransformationException("Couldn't resolve name: " + name + "\nFound real type: " + type + "\nGeneric type: " + genericType + "\nImports:" + imports.stream().map(ResolutionContext::classOf) ); if (generic == null) { return sanityCheck(type); } return sanityCheck(type.withTypeArgument(genericType)); } private Type resolveReal(String name) { Type result = resolveTypeParameterType(name); if (result != null) return result; result = resolveClassType(name); if (result != null) return result; return null; } private Type resolveClassType(String name) { String dotName = name.contains(".") ? name : '.' + name; for (ImportDeclaration anImport : imports) { String importName = classOf(anImport); if (importName.endsWith(dotName)) { return Type.of(importName); } } Type type = resolveIfExists(packageName + '.' + name); if (type != null) { return type; } for (ImportDeclaration anImport : imports) { String importName = classOf(anImport); if (importName.endsWith(".*")) { type = resolveIfExists(importName.replace(".*", ".") + name); if (type != null) { return type; } } } type = resolveIfExists("java.lang." + name); if (type != null) { return type; } if (!hasPackages(name) && !Objects.equals(System.getProperty("JarTransformer.allowDefaultPackage"), "true")) { return null; } return Type.of(name); } private Type resolveIfExists(String s) { if (s.startsWith("java.") || s.startsWith("javax.")) { try { return Type.of(Class.forName(s).getName()); } catch (ClassNotFoundException ignored) { } } // TODO: 23/01/2016 Move to separate class, do actual searching for files return null; } /** * If we have the type parameter "A extends StringBuilder", * then "A" is resolved to a type with: * descriptor: Ljava/lang/StringBuilder; * signature: TA; */ private Type resolveTypeParameterType(String name) { for (TypeParameter typeParameter : typeParameters) { String typeName = typeParameter.getName(); if (typeName.equals(name)) { val bounds = typeParameter.getTypeBound(); String extends_ = "Ljava/lang/Object;"; if (bounds != null) { if (bounds.size() == 1) { ClassOrInterfaceType scope = bounds.get(0).getScope(); if (scope != null) { extends_ = resolve(scope.getName()).descriptor; } } else { throw new TransformationException("Bounds must have one object, found: " + bounds); } } return new Type(extends_, "T" + typeName + ";"); } } return null; } public String typeToString(Type t) { return typeToString(t, true); } public String typeToString(Type t, boolean unresolve) { if (t.isTypeParameter()) { return t.getTypeParameterName(); } if (t.isPrimitiveType()) { return t.getPrimitiveTypeName(); } String className = t.getClassName(); if (unresolve) for (ImportDeclaration anImport : imports) { String importName = NodeUtil.qualifiedName(anImport.getName()); if (className.startsWith(importName)) { return className.replace(importName + ".", ""); } } return className; } }
package uk.ac.ebi.spot.goci.curation.builder; import uk.ac.ebi.spot.goci.model.Association; import uk.ac.ebi.spot.goci.model.DiseaseTrait; import uk.ac.ebi.spot.goci.model.EfoTrait; import uk.ac.ebi.spot.goci.model.Ethnicity; import uk.ac.ebi.spot.goci.model.Event; import uk.ac.ebi.spot.goci.model.Housekeeping; import uk.ac.ebi.spot.goci.model.Platform; import uk.ac.ebi.spot.goci.model.Study; import java.util.Collection; import java.util.Date; public class StudyBuilder { private Study study = new Study(); public StudyBuilder setId(Long id) { study.setId(id); return this; } public StudyBuilder setAuthor(String author) { study.setAuthor(author); return this; } public StudyBuilder setPublicationDate(Date publicationDate) { study.setPublicationDate(publicationDate); return this; } public StudyBuilder setPublication(String publication) { study.setPublication(publication); return this; } public StudyBuilder setTitle(String title) { study.setTitle(title); return this; } public StudyBuilder setInitialSampleSize(String initialSampleSize) { study.setInitialSampleSize(initialSampleSize); return this; } public StudyBuilder setReplicateSampleSize(String replicateSampleSize) { study.setReplicateSampleSize(replicateSampleSize); return this; } public StudyBuilder setPubmedId(String pubmedId) { study.setPubmedId(pubmedId); return this; } public StudyBuilder setCnv(Boolean cnv) { study.setCnv(cnv); return this; } public StudyBuilder setGxe(Boolean gxe) { study.setGxe(gxe); return this; } public StudyBuilder setGxg(Boolean gxg) { study.setGxg(gxg); return this; } public StudyBuilder setGenomewideArray(Boolean genomewideArray) { study.setGenomewideArray(genomewideArray); return this; } public StudyBuilder setTargetedArray(Boolean targetedArray) { study.setTargetedArray(targetedArray); return this; } public StudyBuilder setDiseaseTrait(DiseaseTrait diseaseTrait) { study.setDiseaseTrait(diseaseTrait); return this; } public StudyBuilder setEfoTraits(Collection<EfoTrait> efoTraits) { study.setEfoTraits(efoTraits); return this; } public StudyBuilder setEthnicities(Collection<Ethnicity> ethnicities) { study.setEthnicities(ethnicities); return this; } public StudyBuilder setHousekeeping(Housekeeping housekeeping) { study.setHousekeeping(housekeeping); return this; } public StudyBuilder setAssociations(Collection<Association> associations) { study.setAssociations(associations); return this; } public StudyBuilder setPooled(Boolean pooled) { study.setPooled(pooled); return this; } public StudyBuilder setSnpCount(Integer snpCount) { study.setSnpCount(snpCount); return this; } public StudyBuilder setQualifer(String qualifer) { study.setQualifier(qualifer); return this; } public StudyBuilder setImputed(Boolean imputed) { study.setImputed(imputed); return this; } public StudyBuilder setStudyDesignComment(String studyDesignComment) { study.setStudyDesignComment(studyDesignComment); return this; } public StudyBuilder setPlatforms(Collection<Platform> platforms) { study.setPlatforms(platforms); return this; } public StudyBuilder setEvents(Collection<Event> events) { study.setEvents(events); return this; } public Study build() { return study; } }
package net.imagej.legacy.plugin; import java.awt.event.MouseEvent; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import net.imagej.legacy.IJ1Helper; import org.fife.ui.autocomplete.BasicCompletion; import org.fife.ui.autocomplete.Completion; import org.fife.ui.autocomplete.DefaultCompletionProvider; import org.fife.ui.autocomplete.SortByRelevanceComparator; import org.fife.ui.rtextarea.RTextArea; import org.fife.ui.rtextarea.ToolTipSupplier; import org.scijava.module.ModuleInfo; import org.scijava.module.ModuleService; import javax.swing.text.BadLocationException; import javax.swing.text.JTextComponent; /** * Creates the list of auto-completion suggestions from functions.html * documentation. * * @author Robert Haase */ class MacroAutoCompletionProvider extends DefaultCompletionProvider implements ToolTipSupplier { private ModuleService moduleService; private MacroExtensionAutoCompletionService macroExtensionAutoCompletionService; private static MacroAutoCompletionProvider instance = null; private boolean sorted = false; private final int maximumSearchResults = 100; private MacroAutoCompletionProvider() { parseFunctionsHtmlDoc("/doc/ij1macro/functions.html"); parseFunctionsHtmlDoc("/doc/ij1macro/functions_extd.html"); } public static synchronized MacroAutoCompletionProvider getInstance() { if (instance == null) { instance = new MacroAutoCompletionProvider(); } return instance; } private boolean parseFunctionsHtmlDoc(final String filename) { InputStream resourceAsStream; sorted = false; try { if (filename.startsWith("http")) { final URL url = new URL(filename); resourceAsStream = url.openStream(); } else { resourceAsStream = getClass().getResourceAsStream(filename); } if (resourceAsStream == null) return false; final BufferedReader br = new BufferedReader(new InputStreamReader(resourceAsStream)); String name = ""; String headline = ""; String description = ""; String line; while ((line = br.readLine()) != null) { line = line.trim(); line = line.replace("<a name=\"", "<a name=").replace("\"></a>", "></a>"); if (line.contains("<a name=")) { if (checkCompletion(headline, name, description)) { addCompletion(makeListEntry(this, headline, name, description)); } name = htmlToText(line.split("<a name=")[1].split("></a>")[0]); description = ""; headline = ""; } else { if (headline.length() == 0) { headline = htmlToText(line); } else { description = description + line + "\n"; } } } if (checkCompletion(headline, name, description)) { addCompletion(makeListEntry(this, headline, name, description)); } } catch (final javax.net.ssl.SSLHandshakeException e) { return false; } catch (final UnknownHostException e) { return false; } catch (final IOException e) { e.printStackTrace(); return false; } return true; } void addModuleCompletions(ModuleService moduleService) { if (this.moduleService == moduleService) { return; } sorted = false; this.moduleService = moduleService; for (ModuleInfo info : moduleService.getModules()) { if(info.getMenuPath().getLeaf() != null) { String name = info.getMenuPath().getLeaf().getName().trim(); String headline = "run(\"" + name +"\")"; String description = "<b>" + headline + "</b><p>" + "<a href=\"https://imagej.net/Special:Search/" + name.replace(" ", "%20") + "\">Search imagej wiki for help</a>"; addCompletion(makeListEntry(this, headline, null, description)); } } } public void addMacroExtensionAutoCompletions(MacroExtensionAutoCompletionService macroExtensionAutoCompletionService) { if (this.macroExtensionAutoCompletionService != null) { return; } sorted = false; this.macroExtensionAutoCompletionService = macroExtensionAutoCompletionService; List<BasicCompletion> completions = macroExtensionAutoCompletionService.getCompletions(this); for (BasicCompletion completion : completions) { addCompletion(completion); } } public void sort() { if (!sorted) { Collections.sort(completions, new SortByRelevanceComparator()); sorted = true; } } private boolean checkCompletion(final String headline, final String name, final String description) { return headline.length() > 0 && name.length() > 1 && !name.trim().startsWith("<") && !name.trim().startsWith("-") && name.compareTo("Top") != 0 && name.compareTo("IJ") != 0 && name.compareTo("Stack") != 0 && name.compareTo("Array") != 0 && name.compareTo("file") != 0 && name.compareTo("Fit") != 0 && name.compareTo("List") != 0 && name.compareTo("Overlay") != 0 && name.compareTo("Plot") != 0 && name.compareTo("Roi") != 0 && name.compareTo("String") != 0 && name.compareTo("Table") != 0 && name.compareTo("Ext") != 0 && name.compareTo("ext") != 0 && name.compareTo("alphabar") != 0 && name.compareTo("ext") != 0; } private String htmlToText(final String text) { return text .replace("&quot;", "\"") .replace("&amp;", "&") .replace("<b>", "") .replace("</b>", "") .replace("<i>", "") .replace("</i>", "") .replace("<br>", "\n"); } private BasicCompletion makeListEntry( final MacroAutoCompletionProvider provider, String headline, final String name, String description) { if (!headline.startsWith("run(\"")) { final String link = "https://imagej.net/developer/macro/functions.html#" + name; description = "<a href=\"" + link + "\">" + headline + "</a><br>" + description; } if (headline.trim().endsWith("-")) { headline = headline.trim(); headline = headline.substring(0, headline.length() - 2); } return new BasicCompletion(provider, headline, null, description); } /** * Returns the tool tip to display for a mouse event. * <p> * For this method to be called, the <tt>RSyntaxTextArea</tt> must be * registered with the <tt>javax.swing.ToolTipManager</tt> like so: * </p> * * <pre> * ToolTipManager.sharedInstance().registerComponent(textArea); * </pre> * * @param textArea The text area. * @param e The mouse event. * @return The tool tip text, or <code>null</code> if none. */ @Override public String getToolTipText(final RTextArea textArea, final MouseEvent e) { String tip = null; final List<Completion> completions = getCompletionsAt(textArea, e.getPoint()); if (completions != null && completions.size() > 0) { // Only ever 1 match for us in C... final Completion c = completions.get(0); tip = c.getToolTipText(); } return tip; } protected boolean isValidChar(char ch) { return Character.isLetterOrDigit(ch) || ch == '_' || ch == '.' || ch == '"'; } /** * Returns a list of <tt>Completion</tt>s in this provider with the * specified input text. * * @param inputText The input text to search for. * @return A list of {@link Completion}s, or <code>null</code> if there * are no matching <tt>Completion</tt>s. */ @SuppressWarnings("unchecked") @Override public List<Completion> getCompletionByInputText(String inputText) { inputText = inputText.toLowerCase(); ArrayList<Completion> result = new ArrayList<Completion>(); int count = 0; int secondaryCount = 0; for (Completion completion : completions) { String text = completion.getInputText().toLowerCase(); if (text.contains(inputText)) { if (text.startsWith(inputText)) { result.add(count, completion); count++; } else { result.add(completion); secondaryCount++; } } if (secondaryCount + count > maximumSearchResults) { break; // if too many results are found, exit to not annoy the user } } return result; } private void appendMacroSpecificCompletions(String input, List<Completion> result, JTextComponent comp) { List<Completion> completions = new ArrayList<Completion>(); String lcaseinput = input.toLowerCase(); String text = null; try { text = comp.getDocument().getText(0, comp.getDocument().getLength()); } catch (BadLocationException e) { e.printStackTrace(); return; } text = text + "\n" + IJ1Helper.getAdditionalMacroFunctions(); int linecount = 0; String[] textArray = text.split("\n"); for (String line : textArray){ String trimmedline = line.trim(); String lcaseline = trimmedline.toLowerCase(); if (lcaseline.startsWith("function ")) { String command = trimmedline.substring(8).trim().replace("{", ""); String lcasecommand = command.toLowerCase(); if (lcasecommand.contains(lcaseinput)) { String description = findDescription(textArray, linecount, "User defined function " + command + "\n as specified in line " + (linecount + 1)); completions.add(new BasicCompletion(this, command, null, description)); } } if (lcaseline.contains("=")) { String command = trimmedline.substring(0, lcaseline.indexOf("=")).trim(); if(command.startsWith("var ")) command=command.substring(4).trim(); String lcasecommand = command.toLowerCase(); if (lcasecommand.contains(lcaseinput) && command.matches("[_a-zA-Z]+")) { String description = "User defined variable " + command + "\n as specified in line " + (linecount + 1); completions.add(new BasicCompletion(this, command, null, description)); } } linecount++; } Collections.sort(completions, new SortByRelevanceComparator()); result.addAll(0, completions); } private String findDescription(String[] textArray, int linecount, String defaultDescription) { String resultDescription = ""; int l = linecount - 1; while (l > 0) { String lineBefore = textArray[l].trim(); System.out.println("Scanning B " + lineBefore); if (lineBefore.startsWith(" resultDescription = lineBefore.substring(2) + "\n" + resultDescription; } else { break; } l } l = linecount + 1; while (l < textArray.length - 1) { String lineAfter = textArray[l].trim(); System.out.println("Scanning A " + lineAfter); if (lineAfter.startsWith(" resultDescription = resultDescription + "\n" + lineAfter.substring(2); } else { break; } l++; } if (resultDescription.length() > 0) { resultDescription = resultDescription + "<br><br>"; } resultDescription = resultDescription + defaultDescription; return resultDescription; } /** * {@inheritDoc} */ @Override @SuppressWarnings("unchecked") protected List<Completion> getCompletionsImpl(JTextComponent comp) { List<Completion> retVal = new ArrayList<Completion>(); String text = getAlreadyEnteredText(comp); if (text != null) { retVal = getCompletionByInputText(text); appendMacroSpecificCompletions(text, retVal, comp); } return retVal; } @Override public List<Completion> getCompletions(JTextComponent comp) { List<Completion> completions = this.getCompletionsImpl(comp); return completions; } }
package net.iponweb.disthene.service.store; import com.datastax.driver.core.*; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.StoreErrorEvent; import net.iponweb.disthene.events.StoreSuccessEvent; import org.apache.log4j.Logger; import java.util.*; import java.util.concurrent.Executor; /** * @author Andrei Ivanov */ class BatchWriterThread extends WriterThread { //todo: do we really need this? private static final int RF = 2; //todo: interval via config? private static final long INTERVAL = 60_000; private Logger logger = Logger.getLogger(BatchWriterThread.class); private int batchSize; private BatchStatement batch = new BatchStatement(); private List<Statement> statements = new LinkedList<>(); private long lastFlushTimestamp = System.currentTimeMillis(); BatchWriterThread(String name, MBassador<DistheneEvent> bus, Session session, PreparedStatement statement, Queue<Metric> metrics, Executor executor, int batchSize) { super(name, bus, session, statement, metrics, executor); this.batchSize = batchSize; } @Override public void run() { while (!shutdown) { Metric metric = metrics.poll(); if (metric != null) { addToBatch(metric); } else { try { Thread.sleep(100); } catch (InterruptedException ignored) { } } } if (batch.size() > 0) { flush(); // flushTokenAware(); } } private void addToBatch(Metric metric) { statements.add(statement.bind( metric.getRollup() * metric.getPeriod(), Collections.singletonList(metric.getValue()), metric.getTenant(), metric.getRollup(), metric.getPeriod(), metric.getPath(), metric.getTimestamp() ) ); batch.add(statement.bind( metric.getRollup() * metric.getPeriod(), Collections.singletonList(metric.getValue()), metric.getTenant(), metric.getRollup(), metric.getPeriod(), metric.getPath(), metric.getTimestamp() ) ); if (statements.size() >= batchSize || (lastFlushTimestamp < System.currentTimeMillis() - INTERVAL)) { lastFlushTimestamp = System.currentTimeMillis(); flush(); // flushTokenAware(); } } private void flushTokenAware() { List<List<Statement>> batches = splitByToken(); for (List<Statement> batchStatements : batches) { BatchStatement batch = new BatchStatement(); final int batchSize = batchStatements.size(); for (Statement s : batchStatements) { batch.add(s); } ResultSetFuture future = session.executeAsync(batch); Futures.addCallback(future, new FutureCallback<ResultSet>() { @Override public void onSuccess(ResultSet result) { bus.post(new StoreSuccessEvent(batchSize)).now(); } @Override public void onFailure(Throwable t) { bus.post(new StoreErrorEvent(batchSize)).now(); logger.error(t); } }, executor ); } } private List<List<Statement>> splitByToken() { Map<Set<Host>,List<Statement>> batches = new HashMap<>(); for (Statement statement : statements) { Set<Host> hosts = new HashSet<>(); int replicas = 0; Iterator<Host> it = session.getCluster().getConfiguration().getPolicies(). getLoadBalancingPolicy().newQueryPlan(statement.getKeyspace(), statement); while (it.hasNext() && replicas < RF) { hosts.add(it.next()); replicas++; } List<Statement> tokenBatch = batches.get(hosts); if (tokenBatch == null) { tokenBatch = new ArrayList<>(); batches.put(hosts, tokenBatch); } tokenBatch.add(statement); } return new ArrayList<>(batches.values()); } private void flush() { final int batchSize = batch.size(); ResultSetFuture future = session.executeAsync(batch); Futures.addCallback(future, new FutureCallback<ResultSet>() { @Override public void onSuccess(ResultSet result) { bus.post(new StoreSuccessEvent(batchSize)).now(); } @Override public void onFailure(Throwable t) { bus.post(new StoreErrorEvent(batchSize)).now(); logger.error(t); } }, executor ); batch = new BatchStatement(); } }
package net.sf.mzmine.modules.visualization.twod; import java.awt.Color; import java.awt.Insets; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JToolBar; import net.sf.mzmine.util.GUIUtils; /** * 2D visualizer's toolbar class */ class TwoDToolBar extends JToolBar { static final Icon paletteIcon = new ImageIcon("icons/colorbaricon.png"); static final Icon dataPointsIcon = new ImageIcon("icons/datapointsicon.png"); static final Icon axesIcon = new ImageIcon("icons/axesicon.png"); static final Icon centroidIcon = new ImageIcon("icons/centroidicon.png"); static final Icon continuousIcon = new ImageIcon("icons/continuousicon.png"); static final Icon tooltipsIcon = new ImageIcon( "icons/tooltips2dploticon.png"); static final Icon notooltipsIcon = new ImageIcon( "icons/notooltips2dploticon.png"); static final Icon logScaleIcon = new ImageIcon("icons/logicon.png"); private JButton centroidContinuousButton, toggleContinuousModeButton, toggleTooltipButton; TwoDToolBar(TwoDVisualizerWindow masterFrame) { super(JToolBar.VERTICAL); setFloatable(false); setFocusable(false); setMargin(new Insets(5, 5, 5, 5)); setBackground(Color.white); GUIUtils.addButton(this, null, paletteIcon, masterFrame, "SWITCH_PALETTE", "Switch palette"); addSeparator(); toggleContinuousModeButton = GUIUtils.addButton(this, null, dataPointsIcon, masterFrame, "SHOW_DATA_POINTS", "Toggle displaying of data points in continuous mode"); addSeparator(); GUIUtils.addButton(this, null, axesIcon, masterFrame, "SETUP_AXES", "Setup ranges for axes"); addSeparator(); centroidContinuousButton = GUIUtils.addButton(this, null, centroidIcon, masterFrame, "SWITCH_PLOTMODE", "Switch between continuous and centroided mode"); addSeparator(); toggleTooltipButton = GUIUtils.addButton(this, null, tooltipsIcon, masterFrame, "SWITCH_TOOLTIPS", "Toggle displaying of tool tips on the peaks"); addSeparator(); GUIUtils.addButton(this, null, logScaleIcon, masterFrame, "SWITCH_LOG_SCALE", "Set Log Scale"); } void setCentroidButton(boolean centroid) { if (centroid) { centroidContinuousButton.setIcon(centroidIcon); } else { centroidContinuousButton.setIcon(continuousIcon); } } void toggleContinuousModeButtonSetEnable(boolean enable) { toggleContinuousModeButton.setEnabled(enable); } void setTooltipButton(boolean tooltip) { if (tooltip) { toggleTooltipButton.setIcon(tooltipsIcon); } else { toggleTooltipButton.setIcon(notooltipsIcon); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package nz.co.gregs.dbvolution.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import nz.co.gregs.dbvolution.DBTableRow; /** * * @author gregory.graham */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface DBTableForeignKey { Class<? extends DBTableRow> dbTableRow(); }
package org.jfree.chart.util; import java.text.DecimalFormat; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.TestUtilities; /** * Tests for the {@link LogFormat} class. */ public class LogFormatTest extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(LogFormatTest.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public LogFormatTest(String name) { super(name); } /** * Check that the equals() method distinguishes all fields. */ public void testEquals() { LogFormat f1 = new LogFormat(10.0, "10", true); LogFormat f2 = new LogFormat(10.0, "10", true); assertEquals(f1, f2); f1 = new LogFormat(11.0, "10", true); assertFalse(f1.equals(f2)); f2 = new LogFormat(11.0, "10", true); assertTrue(f1.equals(f2)); f1 = new LogFormat(11.0, "11", true); assertFalse(f1.equals(f2)); f2 = new LogFormat(11.0, "11", true); assertTrue(f1.equals(f2)); f1 = new LogFormat(11.0, "11", false); assertFalse(f1.equals(f2)); f2 = new LogFormat(11.0, "11", false); assertTrue(f1.equals(f2)); f1.setExponentFormat(new DecimalFormat("0.000")); assertFalse(f1.equals(f2)); f2.setExponentFormat(new DecimalFormat("0.000")); assertTrue(f1.equals(f2)); } /** * Two objects that are equal are required to return the same hashCode. */ public void testHashcode() { LogFormat f1 = new LogFormat(10.0, "10", true); LogFormat f2 = new LogFormat(10.0, "10", true); assertTrue(f1.equals(f2)); int h1 = f1.hashCode(); int h2 = f2.hashCode(); assertEquals(h1, h2); } /** * Confirm that cloning works. */ public void testCloning() { LogFormat f1 = new LogFormat(10.0, "10", true); LogFormat f2 = (LogFormat) f1.clone(); assertTrue(f1 != f2); assertTrue(f1.getClass() == f2.getClass()); assertTrue(f1.equals(f2)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { LogFormat f1 = new LogFormat(10.0, "10", true); LogFormat f2 = (LogFormat) TestUtilities.serialised(f1); assertEquals(f1, f2); } }
package navClasses; /** * @author Matt * * Serves to create and format all objects * on the map. Will eventually interact with * dashboard and an external picture class * to create a graphical representation of the * field */ public class Map extends primitiveRegion{ //Initializes defense objects for the known field configuration private Defense d0; private Defense d1; private Defense d2; private Defense d3; private Defense d4; private Defense d5; private Defense d6; private Defense d7; private Defense d8; private Defense d9; private double defense0 = 9, defense1 = 9, defense2 = 9, defense3 = 9, defense4 = 9, defense5 = 9, defense6 = 9, defense7 = 9, defense8 = 9, defense9 = 9; /** * The initial bottom-left coordinates * of the two series of defenses */ private double defenseOffsetXFriendly = 0; //TODO private double defenseOffsetYFriendly = 0; //TODO private double defenseOffsetXOpposing = 0; //TODO private double defenseOffsetYOpposing = 0; //TODO /** * Defense attributes */ private double defenseHeightY; //TODO private double defenseHeightX; //TODO public Map(double xStart, double yStart, double xLength, double yLength) { super(xStart, yStart, xLength, yLength); } /** * Initializes the locations of all the defenses * These shouldn't change */ public void initializeObjects(){ d0 = new Defense(defenseOffsetXFriendly,defenseOffsetYFriendly,defenseHeightX,defenseHeightY, defense0); d1 = new Defense(defenseOffsetXFriendly + 1 * defenseHeightX,defenseOffsetYFriendly,defenseHeightX,defenseHeightY, defense1); d2 = new Defense(defenseOffsetXFriendly + 2 * defenseHeightX,defenseOffsetYFriendly,defenseHeightX,defenseHeightY, defense2); d3 = new Defense(defenseOffsetXFriendly + 3 * defenseHeightX,defenseOffsetYFriendly,defenseHeightX,defenseHeightY, defense3); d4 = new Defense(defenseOffsetXFriendly + 4 * defenseHeightX,defenseOffsetYFriendly,defenseHeightX,defenseHeightY, defense4); d5 = new Defense(defenseOffsetXOpposing,defenseOffsetYOpposing,defenseHeightX,defenseHeightY, defense5); d6 = new Defense(defenseOffsetXOpposing + 1 * defenseHeightX,defenseOffsetYOpposing,defenseHeightX,defenseHeightY, defense6); d7 = new Defense(defenseOffsetXOpposing + 2 * defenseHeightX,defenseOffsetYOpposing,defenseHeightX,defenseHeightY, defense7); d8 = new Defense(defenseOffsetXOpposing + 3 * defenseHeightX,defenseOffsetYOpposing,defenseHeightX,defenseHeightY, defense8); d9 = new Defense(defenseOffsetXOpposing + 4 * defenseHeightX,defenseOffsetYOpposing,defenseHeightX,defenseHeightY, defense9); } }
package org.asteriskjava.manager.event; public class AttendedTransferEvent extends AbstractBridgeEvent { private static final long serialVersionUID = 1L; private String origTransfererChannel; private String origTransfererChannelState; private String origTransfererChannelStateDesc; private String origTransfererCallerIDNum; private String origTransfererCallerIDName; private String origTransfererConnectedLineNum; private String origTransfererConnectedLineName; private String origTransfererAccountCode; private String origTransfererContext; private String origTransfererExten; private String origTransfererPriority; private String origTransfererUniqueid; private String origBridgeUniqueid; private String origBridgeType; private String origBridgeTechnology; private String origBridgeCreator; private String origBridgeName; private String origBridgeNumChannels; private String secondTransfererChannel; private String secondTransfererChannelState; private String secondTransfererChannelStateDesc; private String secondTransfererCallerIDNum; private String secondTransfererCallerIDName; private String secondTransfererConnectedLineNum; private String secondTransfererConnectedLineName; private String secondTransfererAccountCode; private String secondTransfererContext; private String secondTransfererExten; private String secondTransfererPriority; private String secondTransfererUniqueid; private String secondBridgeUniqueid; private String secondBridgeType; private String secondBridgeTechnology; private String secondBridgeCreator; private String secondBridgeName; private String secondBridgeNumChannels; private String destType; private String destBridgeUniqueid; private String destApp; private String localOneChannel; private String localOneChannelState; private String localOneChannelStateDesc; private String localOneCallerIDNum; private String localOneCallerIDName; private String localOneConnectedLineNum; private String localOneConnectedLineName; private String localOneAccountCode; private String localOneContext; private String localOneExten; private String localOnePriority; private String localOneUniqueid; private String localTwoChannel; private String localTwoChannelState; private String localTwoChannelStateDesc; private String localTwoCallerIDNum; private String localTwoCallerIDName; private String localTwoConnectedLineNum; private String localTwoConnectedLineName; private String localTwoAccountCode; private String localTwoContext; private String localTwoExten; private String localTwoPriority; private String localTwoUniqueid; private String destTransfererChannel; private String transfereeChannel; private String transfereeChannelState; private String transfereeChannelStateDesc; private String transfereeCallerIDNum; private String transfereeCallerIDName; private String transfereeConnectedLineNum; private String transfereeConnectedLineName; private String transfereeAccountCode; private String transfereeContext; private String transfereeExten; private String transfereePriority; private String transfereeUniqueid; private String transferTargetUniqueID; private String transferTargetCallerIDName; private String secondBridgeVideoSourceMode; private String transferTargetLinkedID; private String transferTargetPriority; private String transferTargetCallerIDNum; private String origBridgeVideoSourceMode; private String transferTargetConnectedLineNum; private String transferTargetChannel; private String transferTargetContext; private String transferTargetConnectedLineName; private String transferTargetExten; private String transferTargetChannelState; private String transferTargetLanguage; private String transferTargetAccountCode; private String transferTargetChannelStateDesc; private String transfereeLinkedId; private String transfereeLanguage; private String origTransfererLinkedId; private String secondTransfererLanguage; private String isexternal; private String result; private String secondTransfererLinkedId; private String origTransfererLanguage; public AttendedTransferEvent(Object source) { super(source); } public String getOrigTransfererChannel() { return origTransfererChannel; } public void setOrigTransfererChannel(String origTransfererChannel) { this.origTransfererChannel = origTransfererChannel; } public String getOrigTransfererChannelState() { return origTransfererChannelState; } public void setOrigTransfererChannelState(String origTransfererChannelState) { this.origTransfererChannelState = origTransfererChannelState; } public String getOrigTransfererChannelStateDesc() { return origTransfererChannelStateDesc; } public void setOrigTransfererChannelStateDesc(String origTransfererChannelStateDesc) { this.origTransfererChannelStateDesc = origTransfererChannelStateDesc; } public String getOrigTransfererCallerIDNum() { return origTransfererCallerIDNum; } public void setOrigTransfererCallerIDNum(String origTransfererCallerIDNum) { this.origTransfererCallerIDNum = origTransfererCallerIDNum; } public String getOrigTransfererCallerIDName() { return origTransfererCallerIDName; } public void setOrigTransfererCallerIDName(String origTransfererCallerIDName) { this.origTransfererCallerIDName = origTransfererCallerIDName; } public String getOrigTransfererConnectedLineNum() { return origTransfererConnectedLineNum; } public void setOrigTransfererConnectedLineNum(String origTransfererConnectedLineNum) { this.origTransfererConnectedLineNum = origTransfererConnectedLineNum; } public String getOrigTransfererConnectedLineName() { return origTransfererConnectedLineName; } public void setOrigTransfererConnectedLineName(String origTransfererConnectedLineName) { this.origTransfererConnectedLineName = origTransfererConnectedLineName; } public String getOrigTransfererAccountCode() { return origTransfererAccountCode; } public void setOrigTransfererAccountCode(String origTransfererAccountCode) { this.origTransfererAccountCode = origTransfererAccountCode; } public String getOrigTransfererContext() { return origTransfererContext; } public void setOrigTransfererContext(String origTransfererContext) { this.origTransfererContext = origTransfererContext; } public String getOrigTransfererExten() { return origTransfererExten; } public void setOrigTransfererExten(String origTransfererExten) { this.origTransfererExten = origTransfererExten; } public String getOrigTransfererPriority() { return origTransfererPriority; } public void setOrigTransfererPriority(String origTransfererPriority) { this.origTransfererPriority = origTransfererPriority; } public String getOrigTransfererUniqueid() { return origTransfererUniqueid; } public void setOrigTransfererUniqueid(String origTransfererUniqueid) { this.origTransfererUniqueid = origTransfererUniqueid; } public String getOrigBridgeUniqueid() { return origBridgeUniqueid; } public void setOrigBridgeUniqueid(String origBridgeUniqueid) { this.origBridgeUniqueid = origBridgeUniqueid; } public String getOrigBridgeType() { return origBridgeType; } public void setOrigBridgeType(String origBridgeType) { this.origBridgeType = origBridgeType; } public String getOrigBridgeTechnology() { return origBridgeTechnology; } public void setOrigBridgeTechnology(String origBridgeTechnology) { this.origBridgeTechnology = origBridgeTechnology; } public String getOrigBridgeCreator() { return origBridgeCreator; } public void setOrigBridgeCreator(String origBridgeCreator) { this.origBridgeCreator = origBridgeCreator; } public String getOrigBridgeName() { return origBridgeName; } public void setOrigBridgeName(String origBridgeName) { this.origBridgeName = origBridgeName; } public String getOrigBridgeNumChannels() { return origBridgeNumChannels; } public void setOrigBridgeNumChannels(String origBridgeNumChannels) { this.origBridgeNumChannels = origBridgeNumChannels; } public String getSecondTransfererChannel() { return secondTransfererChannel; } public void setSecondTransfererChannel(String secondTransfererChannel) { this.secondTransfererChannel = secondTransfererChannel; } public String getSecondTransfererChannelState() { return secondTransfererChannelState; } public void setSecondTransfererChannelState(String secondTransfererChannelState) { this.secondTransfererChannelState = secondTransfererChannelState; } public String getSecondTransfererChannelStateDesc() { return secondTransfererChannelStateDesc; } public void setSecondTransfererChannelStateDesc(String secondTransfererChannelStateDesc) { this.secondTransfererChannelStateDesc = secondTransfererChannelStateDesc; } public String getSecondTransfererCallerIDNum() { return secondTransfererCallerIDNum; } public void setSecondTransfererCallerIDNum(String secondTransfererCallerIDNum) { this.secondTransfererCallerIDNum = secondTransfererCallerIDNum; } public String getSecondTransfererCallerIDName() { return secondTransfererCallerIDName; } public void setSecondTransfererCallerIDName(String secondTransfererCallerIDName) { this.secondTransfererCallerIDName = secondTransfererCallerIDName; } public String getSecondTransfererConnectedLineNum() { return secondTransfererConnectedLineNum; } public void setSecondTransfererConnectedLineNum(String secondTransfererConnectedLineNum) { this.secondTransfererConnectedLineNum = secondTransfererConnectedLineNum; } public String getSecondTransfererConnectedLineName() { return secondTransfererConnectedLineName; } public void setSecondTransfererConnectedLineName(String secondTransfererConnectedLineName) { this.secondTransfererConnectedLineName = secondTransfererConnectedLineName; } public String getSecondTransfererAccountCode() { return secondTransfererAccountCode; } public void setSecondTransfererAccountCode(String secondTransfererAccountCode) { this.secondTransfererAccountCode = secondTransfererAccountCode; } public String getSecondTransfererContext() { return secondTransfererContext; } public void setSecondTransfererContext(String secondTransfererContext) { this.secondTransfererContext = secondTransfererContext; } public String getSecondTransfererExten() { return secondTransfererExten; } public void setSecondTransfererExten(String secondTransfererExten) { this.secondTransfererExten = secondTransfererExten; } public String getSecondTransfererPriority() { return secondTransfererPriority; } public void setSecondTransfererPriority(String secondTransfererPriority) { this.secondTransfererPriority = secondTransfererPriority; } public String getSecondTransfererUniqueid() { return secondTransfererUniqueid; } public void setSecondTransfererUniqueid(String secondTransfererUniqueid) { this.secondTransfererUniqueid = secondTransfererUniqueid; } public String getSecondBridgeUniqueid() { return secondBridgeUniqueid; } public void setSecondBridgeUniqueid(String secondBridgeUniqueid) { this.secondBridgeUniqueid = secondBridgeUniqueid; } public String getSecondBridgeType() { return secondBridgeType; } public void setSecondBridgeType(String secondBridgeType) { this.secondBridgeType = secondBridgeType; } public String getSecondBridgeTechnology() { return secondBridgeTechnology; } public void setSecondBridgeTechnology(String secondBridgeTechnology) { this.secondBridgeTechnology = secondBridgeTechnology; } public String getSecondBridgeCreator() { return secondBridgeCreator; } public void setSecondBridgeCreator(String secondBridgeCreator) { this.secondBridgeCreator = secondBridgeCreator; } public String getSecondBridgeName() { return secondBridgeName; } public void setSecondBridgeName(String secondBridgeName) { this.secondBridgeName = secondBridgeName; } public String getSecondBridgeNumChannels() { return secondBridgeNumChannels; } public void setSecondBridgeNumChannels(String secondBridgeNumChannels) { this.secondBridgeNumChannels = secondBridgeNumChannels; } public String getDestType() { return destType; } public void setDestType(String destType) { this.destType = destType; } public String getDestBridgeUniqueid() { return destBridgeUniqueid; } public void setDestBridgeUniqueid(String destBridgeUniqueid) { this.destBridgeUniqueid = destBridgeUniqueid; } public String getDestApp() { return destApp; } public void setDestApp(String destApp) { this.destApp = destApp; } public String getLocalOneChannel() { return localOneChannel; } public void setLocalOneChannel(String localOneChannel) { this.localOneChannel = localOneChannel; } public String getLocalOneChannelState() { return localOneChannelState; } public void setLocalOneChannelState(String localOneChannelState) { this.localOneChannelState = localOneChannelState; } public String getLocalOneChannelStateDesc() { return localOneChannelStateDesc; } public void setLocalOneChannelStateDesc(String localOneChannelStateDesc) { this.localOneChannelStateDesc = localOneChannelStateDesc; } public String getLocalOneCallerIDNum() { return localOneCallerIDNum; } public void setLocalOneCallerIDNum(String localOneCallerIDNum) { this.localOneCallerIDNum = localOneCallerIDNum; } public String getLocalOneCallerIDName() { return localOneCallerIDName; } public void setLocalOneCallerIDName(String localOneCallerIDName) { this.localOneCallerIDName = localOneCallerIDName; } public String getLocalOneConnectedLineNum() { return localOneConnectedLineNum; } public void setLocalOneConnectedLineNum(String localOneConnectedLineNum) { this.localOneConnectedLineNum = localOneConnectedLineNum; } public String getLocalOneConnectedLineName() { return localOneConnectedLineName; } public void setLocalOneConnectedLineName(String localOneConnectedLineName) { this.localOneConnectedLineName = localOneConnectedLineName; } public String getLocalOneAccountCode() { return localOneAccountCode; } public void setLocalOneAccountCode(String localOneAccountCode) { this.localOneAccountCode = localOneAccountCode; } public String getLocalOneContext() { return localOneContext; } public void setLocalOneContext(String localOneContext) { this.localOneContext = localOneContext; } public String getLocalOneExten() { return localOneExten; } public void setLocalOneExten(String localOneExten) { this.localOneExten = localOneExten; } public String getLocalOnePriority() { return localOnePriority; } public void setLocalOnePriority(String localOnePriority) { this.localOnePriority = localOnePriority; } public String getLocalOneUniqueid() { return localOneUniqueid; } public void setLocalOneUniqueid(String localOneUniqueid) { this.localOneUniqueid = localOneUniqueid; } public String getLocalTwoChannel() { return localTwoChannel; } public void setLocalTwoChannel(String localTwoChannel) { this.localTwoChannel = localTwoChannel; } public String getLocalTwoChannelState() { return localTwoChannelState; } public void setLocalTwoChannelState(String localTwoChannelState) { this.localTwoChannelState = localTwoChannelState; } public String getLocalTwoChannelStateDesc() { return localTwoChannelStateDesc; } public void setLocalTwoChannelStateDesc(String localTwoChannelStateDesc) { this.localTwoChannelStateDesc = localTwoChannelStateDesc; } public String getLocalTwoCallerIDNum() { return localTwoCallerIDNum; } public void setLocalTwoCallerIDNum(String localTwoCallerIDNum) { this.localTwoCallerIDNum = localTwoCallerIDNum; } public String getLocalTwoCallerIDName() { return localTwoCallerIDName; } public void setLocalTwoCallerIDName(String localTwoCallerIDName) { this.localTwoCallerIDName = localTwoCallerIDName; } public String getLocalTwoConnectedLineNum() { return localTwoConnectedLineNum; } public void setLocalTwoConnectedLineNum(String localTwoConnectedLineNum) { this.localTwoConnectedLineNum = localTwoConnectedLineNum; } public String getLocalTwoConnectedLineName() { return localTwoConnectedLineName; } public void setLocalTwoConnectedLineName(String localTwoConnectedLineName) { this.localTwoConnectedLineName = localTwoConnectedLineName; } public String getLocalTwoAccountCode() { return localTwoAccountCode; } public void setLocalTwoAccountCode(String localTwoAccountCode) { this.localTwoAccountCode = localTwoAccountCode; } public String getLocalTwoContext() { return localTwoContext; } public void setLocalTwoContext(String localTwoContext) { this.localTwoContext = localTwoContext; } public String getLocalTwoExten() { return localTwoExten; } public void setLocalTwoExten(String localTwoExten) { this.localTwoExten = localTwoExten; } public String getLocalTwoPriority() { return localTwoPriority; } public void setLocalTwoPriority(String localTwoPriority) { this.localTwoPriority = localTwoPriority; } public String getLocalTwoUniqueid() { return localTwoUniqueid; } public void setLocalTwoUniqueid(String localTwoUniqueid) { this.localTwoUniqueid = localTwoUniqueid; } public String getDestTransfererChannel() { return destTransfererChannel; } public void setDestTransfererChannel(String destTransfererChannel) { this.destTransfererChannel = destTransfererChannel; } public String getTransfereeChannel() { return transfereeChannel; } public void setTransfereeChannel(String transfereeChannel) { this.transfereeChannel = transfereeChannel; } public String getTransfereeChannelState() { return transfereeChannelState; } public void setTransfereeChannelState(String transfereeChannelState) { this.transfereeChannelState = transfereeChannelState; } public String getTransfereeChannelStateDesc() { return transfereeChannelStateDesc; } public void setTransfereeChannelStateDesc(String transfereeChannelStateDesc) { this.transfereeChannelStateDesc = transfereeChannelStateDesc; } public String getTransfereeCallerIDNum() { return transfereeCallerIDNum; } public void setTransfereeCallerIDNum(String transfereeCallerIDNum) { this.transfereeCallerIDNum = transfereeCallerIDNum; } public String getTransfereeCallerIDName() { return transfereeCallerIDName; } public void setTransfereeCallerIDName(String transfereeCallerIDName) { this.transfereeCallerIDName = transfereeCallerIDName; } public String getTransfereeConnectedLineNum() { return transfereeConnectedLineNum; } public void setTransfereeConnectedLineNum(String transfereeConnectedLineNum) { this.transfereeConnectedLineNum = transfereeConnectedLineNum; } public String getTransfereeConnectedLineName() { return transfereeConnectedLineName; } public void setTransfereeConnectedLineName(String transfereeConnectedLineName) { this.transfereeConnectedLineName = transfereeConnectedLineName; } public String getTransfereeAccountCode() { return transfereeAccountCode; } public void setTransfereeAccountCode(String transfereeAccountCode) { this.transfereeAccountCode = transfereeAccountCode; } public String getTransfereeContext() { return transfereeContext; } public void setTransfereeContext(String transfereeContext) { this.transfereeContext = transfereeContext; } public String getTransfereeExten() { return transfereeExten; } public void setTransfereeExten(String transfereeExten) { this.transfereeExten = transfereeExten; } public String getTransfereePriority() { return transfereePriority; } public void setTransfereePriority(String transfereePriority) { this.transfereePriority = transfereePriority; } public String getTransfereeUniqueid() { return transfereeUniqueid; } public void setTransfereeUniqueid(String transfereeUniqueid) { this.transfereeUniqueid = transfereeUniqueid; } public String getTransfereeLinkedId() { return transfereeLinkedId; } public void setTransfereeLinkedId(String transfereeLinkedId) { this.transfereeLinkedId = transfereeLinkedId; } public String getTransfereeLanguage() { return transfereeLanguage; } public void setTransfereeLanguage(String transfereeLanguage) { this.transfereeLanguage = transfereeLanguage; } public String getOrigTransfererLinkedId() { return origTransfererLinkedId; } public void setOrigTransfererLinkedId(String origTransfererLinkedId) { this.origTransfererLinkedId = origTransfererLinkedId; } public String getSecondTransfererLanguage() { return secondTransfererLanguage; } public void setSecondTransfererLanguage(String secondTransfererLanguage) { this.secondTransfererLanguage = secondTransfererLanguage; } public String getIsexternal() { return isexternal; } public void setIsexternal(String isexternal) { this.isexternal = isexternal; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public String getSecondTransfererLinkedId() { return secondTransfererLinkedId; } public void setSecondTransfererLinkedId(String secondTransfererLinkedId) { this.secondTransfererLinkedId = secondTransfererLinkedId; } public String getOrigTransfererLanguage() { return origTransfererLanguage; } public void setOrigTransfererLanguage(String origTransfererLanguage) { this.origTransfererLanguage = origTransfererLanguage; } public String getTransferTargetUniqueID() { return transferTargetUniqueID; } public void setTransferTargetUniqueID(String transferTargetUniqueID) { this.transferTargetUniqueID = transferTargetUniqueID; } public String getTransferTargetCallerIDName() { return transferTargetCallerIDName; } public void setTransferTargetCallerIDName(String transferTargetCallerIDName) { this.transferTargetCallerIDName = transferTargetCallerIDName; } public String getSecondBridgeVideoSourceMode() { return secondBridgeVideoSourceMode; } public void setSecondBridgeVideoSourceMode(String secondBridgeVideoSourceMode) { this.secondBridgeVideoSourceMode = secondBridgeVideoSourceMode; } public String getTransferTargetLinkedID() { return transferTargetLinkedID; } public void setTransferTargetLinkedID(String transferTargetLinkedID) { this.transferTargetLinkedID = transferTargetLinkedID; } public String getTransferTargetPriority() { return transferTargetPriority; } public void setTransferTargetPriority(String transferTargetPriority) { this.transferTargetPriority = transferTargetPriority; } public String getTransferTargetCallerIDNum() { return transferTargetCallerIDNum; } public void setTransferTargetCallerIDNum(String transferTargetCallerIDNum) { this.transferTargetCallerIDNum = transferTargetCallerIDNum; } public String getOrigBridgeVideoSourceMode() { return origBridgeVideoSourceMode; } public void setOrigBridgeVideoSourceMode(String origBridgeVideoSourceMode) { this.origBridgeVideoSourceMode = origBridgeVideoSourceMode; } public String getTransferTargetConnectedLineNum() { return transferTargetConnectedLineNum; } public void setTransferTargetConnectedLineNum(String transferTargetConnectedLineNum) { this.transferTargetConnectedLineNum = transferTargetConnectedLineNum; } public String getTransferTargetChannel() { return transferTargetChannel; } public void setTransferTargetChannel(String transferTargetChannel) { this.transferTargetChannel = transferTargetChannel; } public String getTransferTargetContext() { return transferTargetContext; } public void setTransferTargetContext(String transferTargetContext) { this.transferTargetContext = transferTargetContext; } public String getTransferTargetConnectedLineName() { return transferTargetConnectedLineName; } public void setTransferTargetConnectedLineName(String transferTargetConnectedLineName) { this.transferTargetConnectedLineName = transferTargetConnectedLineName; } public String getTransferTargetExten() { return transferTargetExten; } public void setTransferTargetExten(String transferTargetExten) { this.transferTargetExten = transferTargetExten; } public String getTransferTargetChannelState() { return transferTargetChannelState; } public void setTransferTargetChannelState(String transferTargetChannelState) { this.transferTargetChannelState = transferTargetChannelState; } public String getTransferTargetLanguage() { return transferTargetLanguage; } public void setTransferTargetLanguage(String transferTargetLanguage) { this.transferTargetLanguage = transferTargetLanguage; } public String getTransferTargetAccountCode() { return transferTargetAccountCode; } public void setTransferTargetAccountCode(String transferTargetAccountCode) { this.transferTargetAccountCode = transferTargetAccountCode; } public String getTransferTargetChannelStateDesc() { return transferTargetChannelStateDesc; } public void setTransferTargetChannelStateDesc(String transferTargetChannelStateDesc) { this.transferTargetChannelStateDesc = transferTargetChannelStateDesc; } }
package org.folio.cataloging.integration; import com.fasterxml.jackson.databind.node.ObjectNode; import org.folio.cataloging.Global; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Profile; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import java.util.Objects; import static java.util.Arrays.stream; import static java.util.stream.Collectors.joining; import static org.folio.cataloging.F.safe; import static org.springframework.web.util.UriComponentsBuilder.fromUriString; /** * Mod Cataloging configuration subsystem facade. * * @author agazzarini * @since 1.0 */ @Component @Profile({"!test"}) public class RemoteConfiguration implements Configuration { private final static String BASE_CQUERY = "module==CATALOGING and configName == "; private final static int LIMIT = 100; private final RestTemplate client; @Value("${configuration.client:http://192.168.0.158:8085/configurations/entries}") private String endpoint; /** * Builds a new configuration with the given http client. * * @param client the HTTP / REST client. */ public RemoteConfiguration(final RestTemplate client) { this.client = client; } @Override public ObjectNode attributes(final String tenant, final boolean withDatasource, final String... configurationSets) { final HttpHeaders headers = new HttpHeaders(); headers.add(Global.OKAPI_TENANT_HEADER_NAME, tenant); return client.exchange( fromUriString(endpoint) .queryParam(cQuery(withDatasource, safe(configurationSets))) .build() .toUri(), HttpMethod.GET, new HttpEntity <>("parameters", headers), ObjectNode.class) .getBody(); } /** * Returns the selection criteria that will be used by the current service for gathering the required configuration. * * @param configurationsSets the configuration groups. * @return the selection criteria that will be used by the current service for gathering the required configuration. */ private String cQuery(boolean withDatasource, final String... configurationsSets) { final String[] values = safe(configurationsSets); return (values.length == 0 && withDatasource) ? BASE_CQUERY + "datasource" : BASE_CQUERY + stream(values) .filter(Objects::nonNull) .collect(joining( " or ", values.length != 0 ? withDatasource ? "(datasource or " : "(" : "", ")&limit=" + LIMIT)); } }
package org.sakaiproject.evaluation.logic.test; import java.util.Date; import java.util.List; import org.sakaiproject.evaluation.logic.EvalEvaluationService; import org.sakaiproject.evaluation.logic.EvalSettings; import org.sakaiproject.evaluation.logic.impl.EvalEmailsLogicImpl; import org.sakaiproject.evaluation.logic.impl.EvalEvaluationSetupServiceImpl; import org.sakaiproject.evaluation.logic.impl.EvalSecurityChecks; import org.sakaiproject.evaluation.model.EvalAssignGroup; import org.sakaiproject.evaluation.model.EvalEmailTemplate; import org.sakaiproject.evaluation.model.EvalEvaluation; import org.sakaiproject.evaluation.model.constant.EvalConstants; import org.sakaiproject.evaluation.test.EvalTestDataLoad; import org.sakaiproject.evaluation.test.mocks.MockEvalExternalLogic; import org.sakaiproject.evaluation.test.mocks.MockEvalJobLogic; /** * Test class for EvalEvaluationSetupServiceImpl * * @author Aaron Zeckoski (aaronz@vt.edu) */ public class EvalEvaluationSetupServiceImplTest extends BaseTestEvalLogic { protected EvalEvaluationSetupServiceImpl evaluationSetupService; private EvalEvaluationService evaluationService; // run this before each test starts protected void onSetUpBeforeTransaction() throws Exception { super.onSetUpBeforeTransaction(); // load up any other needed spring beans EvalSettings settings = (EvalSettings) applicationContext.getBean("org.sakaiproject.evaluation.logic.EvalSettings"); if (settings == null) { throw new NullPointerException("EvalSettings could not be retrieved from spring context"); } EvalSecurityChecks securityChecks = (EvalSecurityChecks) applicationContext.getBean("org.sakaiproject.evaluation.logic.impl.EvalSecurityChecks"); if (securityChecks == null) { throw new NullPointerException("EvalSecurityChecks could not be retrieved from spring context"); } evaluationService = (EvalEvaluationService) applicationContext.getBean("org.sakaiproject.evaluation.logic.EvalEvaluationService"); if (evaluationService == null) { throw new NullPointerException("EvalEvaluationService could not be retrieved from spring context"); } // setup the mock objects if needed EvalEmailsLogicImpl emailsLogicImpl = new EvalEmailsLogicImpl(); emailsLogicImpl.setEvaluationService(evaluationService); emailsLogicImpl.setExternalLogic( new MockEvalExternalLogic() ); emailsLogicImpl.setSettings(settings); // create and setup the object to be tested evaluationSetupService = new EvalEvaluationSetupServiceImpl(); evaluationSetupService.setDao(evaluationDao); evaluationSetupService.setExternalLogic( new MockEvalExternalLogic() ); evaluationSetupService.setSettings(settings); evaluationSetupService.setSecurityChecks(securityChecks); evaluationSetupService.setEvaluationService(evaluationService); evaluationSetupService.setEvalJobLogic( new MockEvalJobLogic() ); // set to the mock object evaluationSetupService.setEmails(emailsLogicImpl); } /** * ADD unit tests below here, use testMethod as the name of the unit test, * Note that if a method is overloaded you should include the arguments in the * test name like so: testMethodClassInt (for method(Class, int); */ /** * Test method for {@link org.sakaiproject.evaluation.logic.impl.EvalEvaluationSetupServiceImpl#saveEvaluation(org.sakaiproject.evaluation.model.EvalEvaluation)}. */ public void testSaveEvaluation() { EvalEvaluation eval = null; // fail( // " -15 days: " + etdl.fifteenDaysAgo + // ", -4days: " + etdl.fourDaysAgo + // ", -3days: " + etdl.threeDaysAgo + // ", yesterday: " + etdl.yesterday + // ", today: " + etdl.today + // ", tomorrow:" + etdl.tomorrow + // ", 3days:" + etdl.threeDaysFuture + // ", 4days:" + etdl.fourDaysFuture // save a valid evaluation (all dates separate) eval = new EvalEvaluation( new Date(), EvalTestDataLoad.MAINT_USER_ID, "Eval valid title", etdl.today, etdl.tomorrow, etdl.threeDaysFuture, etdl.fourDaysFuture, EvalConstants.EVALUATION_STATE_INQUEUE, Integer.valueOf(1), etdl.templatePublic); evaluationSetupService.saveEvaluation( eval, EvalTestDataLoad.MAINT_USER_ID ); EvalEvaluation checkEval = evaluationService.getEvaluationById(eval.getId()); assertNotNull(checkEval); // check that entity equality works (no longer using this check) //assertEquals(eval, checkEval); // save a valid evaluation (due and stop date identical) evaluationSetupService.saveEvaluation( new EvalEvaluation( new Date(), EvalTestDataLoad.MAINT_USER_ID, "Eval valid title", etdl.today, etdl.tomorrow, etdl.tomorrow, etdl.threeDaysFuture, EvalConstants.EVALUATION_STATE_INQUEUE, Integer.valueOf(1), etdl.templatePublic), EvalTestDataLoad.MAINT_USER_ID ); // try to save invalid evaluationSetupService // try save evaluation with dates that are unset (null) // test stop date must be set try { evaluationSetupService.saveEvaluation( new EvalEvaluation( new Date(), EvalTestDataLoad.MAINT_USER_ID, "Eval valid title", etdl.today, etdl.tomorrow, null, etdl.fourDaysFuture, EvalConstants.EVALUATION_STATE_INQUEUE, Integer.valueOf(1), etdl.templatePublic), EvalTestDataLoad.MAINT_USER_ID ); fail("Should have thrown exception"); } catch (NullPointerException e) { assertNotNull(e); //fail("Exception: " + e.getMessage()); // see why failing } // test due date must be set try { evaluationSetupService.saveEvaluation( new EvalEvaluation( new Date(), EvalTestDataLoad.MAINT_USER_ID, "Eval valid title", etdl.today, null, etdl.threeDaysFuture, etdl.fourDaysFuture, EvalConstants.EVALUATION_STATE_INQUEUE, Integer.valueOf(1), etdl.templatePublic), EvalTestDataLoad.MAINT_USER_ID ); fail("Should have thrown exception"); } catch (NullPointerException e) { assertNotNull(e); //fail("Exception: " + e.getMessage()); // see why failing } // try save evaluation with dates that are out of order // test due date must be after start date try { evaluationSetupService.saveEvaluation( new EvalEvaluation( new Date(), EvalTestDataLoad.MAINT_USER_ID, "Eval valid title", etdl.threeDaysFuture, etdl.tomorrow, etdl.tomorrow, etdl.fourDaysFuture, EvalConstants.EVALUATION_STATE_INQUEUE, Integer.valueOf(1), etdl.templatePublic), EvalTestDataLoad.MAINT_USER_ID ); fail("Should have thrown exception"); } catch (IllegalArgumentException e) { assertNotNull(e); //fail("Exception: " + e.getMessage()); // see why failing } try { evaluationSetupService.saveEvaluation( new EvalEvaluation( new Date(), EvalTestDataLoad.MAINT_USER_ID, "Eval valid title", etdl.tomorrow, etdl.tomorrow, etdl.tomorrow, etdl.fourDaysFuture, EvalConstants.EVALUATION_STATE_INQUEUE, Integer.valueOf(1), etdl.templatePublic), EvalTestDataLoad.MAINT_USER_ID ); fail("Should have thrown exception"); } catch (IllegalArgumentException e) { assertNotNull(e); //fail("Exception: " + e.getMessage()); // see why failing } // test stop date must be same as or after due date try { evaluationSetupService.saveEvaluation( new EvalEvaluation( new Date(), EvalTestDataLoad.MAINT_USER_ID, "Eval valid title", etdl.today, etdl.threeDaysFuture, etdl.tomorrow, etdl.fourDaysFuture, EvalConstants.EVALUATION_STATE_INQUEUE, Integer.valueOf(1), etdl.templatePublic), EvalTestDataLoad.MAINT_USER_ID ); fail("Should have thrown exception"); } catch (IllegalArgumentException e) { assertNotNull(e); //fail("Exception: " + e.getMessage()); // see why failing } // test view date must be after stop date and due date try { evaluationSetupService.saveEvaluation( new EvalEvaluation( new Date(), EvalTestDataLoad.MAINT_USER_ID, "Eval valid title", etdl.today, etdl.tomorrow, etdl.tomorrow, etdl.tomorrow, EvalConstants.EVALUATION_STATE_INQUEUE, Integer.valueOf(1), etdl.templatePublic), EvalTestDataLoad.MAINT_USER_ID ); fail("Should have thrown exception"); } catch (IllegalArgumentException e) { assertNotNull(e); //fail("Exception: " + e.getMessage()); // see why failing } // try save new evaluation with dates that are in the past // test start date in the past EvalEvaluation testStartEval = new EvalEvaluation( new Date(), EvalTestDataLoad.MAINT_USER_ID, "Eval valid title", etdl.yesterday, etdl.tomorrow, etdl.threeDaysFuture, etdl.fourDaysFuture, EvalConstants.EVALUATION_STATE_INQUEUE, Integer.valueOf(1), etdl.templatePublic); evaluationSetupService.saveEvaluation( testStartEval, EvalTestDataLoad.MAINT_USER_ID ); assertNotNull(testStartEval.getId()); assertTrue(testStartEval.getStartDate().compareTo(new Date()) <= 0); // test due date in the past try { evaluationSetupService.saveEvaluation( new EvalEvaluation( new Date(), EvalTestDataLoad.MAINT_USER_ID, "Eval valid title", etdl.yesterday, etdl.yesterday, etdl.tomorrow, etdl.fourDaysFuture, EvalConstants.EVALUATION_STATE_INQUEUE, Integer.valueOf(1), etdl.templatePublic), EvalTestDataLoad.MAINT_USER_ID ); fail("Should have thrown exception"); } catch (IllegalArgumentException e) { assertNotNull(e); //fail("Exception: " + e.getMessage()); // see why failing } try { evaluationSetupService.saveEvaluation( new EvalEvaluation( new Date(), EvalTestDataLoad.MAINT_USER_ID, "Eval valid title", etdl.today, etdl.tomorrow, etdl.threeDaysFuture, etdl.fourDaysFuture, EvalConstants.EVALUATION_STATE_INQUEUE, Integer.valueOf(1), etdl.templatePublic), EvalTestDataLoad.USER_ID ); fail("Should have thrown exception"); } catch (SecurityException e) { assertNotNull(e); //fail("Exception: " + e.getMessage()); // see why failing } // test saving an evaluation with an empty template fails try { evaluationSetupService.saveEvaluation( new EvalEvaluation( new Date(), EvalTestDataLoad.ADMIN_USER_ID, "Eval valid title", etdl.today, etdl.tomorrow, etdl.tomorrow, etdl.threeDaysFuture, EvalConstants.EVALUATION_STATE_INQUEUE, Integer.valueOf(1), etdl.templateAdminNoItems), EvalTestDataLoad.ADMIN_USER_ID ); fail("Should have thrown exception"); } catch (IllegalArgumentException e) { assertNotNull(e); //fail("Exception: " + e.getMessage()); // see why failing } try { evaluationSetupService.saveEvaluation( new EvalEvaluation( new Date(), EvalTestDataLoad.ADMIN_USER_ID, "Eval valid title", etdl.today, etdl.tomorrow, etdl.tomorrow, etdl.threeDaysFuture, EvalConstants.EVALUATION_STATE_INQUEUE, Integer.valueOf(1), null), EvalTestDataLoad.ADMIN_USER_ID ); fail("Should have thrown exception"); } catch (IllegalArgumentException e) { assertNotNull(e); //fail("Exception: " + e.getMessage()); // see why failing } } /** * Test method for {@link org.sakaiproject.evaluation.logic.impl.EvalEvaluationSetupServiceImpl#deleteEvaluation(org.sakaiproject.evaluation.model.EvalEvaluation)}. */ public void testDeleteEvaluation() { // remove evaluation which has not started (uses 2 email templates) Long availableId = etdl.evaluationNew.getAvailableEmailTemplate().getId(); Long reminderId = etdl.evaluationNew.getReminderEmailTemplate().getId(); int countEmailTemplates = evaluationDao.countByProperties(EvalEmailTemplate.class, new String[] { "id" }, new Object[] { new Long[] {availableId, reminderId} }); assertEquals(2, countEmailTemplates); evaluationSetupService.deleteEvaluation(etdl.evaluationNew.getId(), EvalTestDataLoad.MAINT_USER_ID); EvalEvaluation eval = evaluationService.getEvaluationById(etdl.evaluationNew.getId()); assertNull(eval); // check to make sure the associated email templates were also removed countEmailTemplates = evaluationDao.countByProperties(EvalEmailTemplate.class, new String[] { "id" }, new Object[] { new Long[] {availableId, reminderId} }); assertEquals(0, countEmailTemplates); // attempt to remove evaluation which is not owned try { evaluationSetupService.deleteEvaluation(etdl.evaluationNewAdmin.getId(), EvalTestDataLoad.MAINT_USER_ID); fail("Should have thrown exception"); } catch (RuntimeException e) { assertNotNull(e); } // attempt to remove evaluation with assigned contexts (check for cleanup) int countACs = evaluationDao.countByProperties(EvalAssignGroup.class, new String[] { "evaluation.id" }, new Object[] { etdl.evaluationNewAdmin.getId() }); assertEquals(3, countACs); evaluationSetupService.deleteEvaluation(etdl.evaluationNewAdmin.getId(), EvalTestDataLoad.ADMIN_USER_ID); eval = evaluationService.getEvaluationById(etdl.evaluationNewAdmin.getId()); assertNull(eval); countACs = evaluationDao.countByProperties(EvalAssignGroup.class, new String[] { "evaluation.id" }, new Object[] { etdl.evaluationNewAdmin.getId() }); assertEquals(0, countACs); // attempt to remove evaluation which is active try { evaluationSetupService.deleteEvaluation(etdl.evaluationActive.getId(), EvalTestDataLoad.MAINT_USER_ID); fail("Should have thrown exception"); } catch (RuntimeException e) { assertNotNull(e); } // attempt to remove evaluation which is completed try { evaluationSetupService.deleteEvaluation(etdl.evaluationClosed.getId(), EvalTestDataLoad.MAINT_USER_ID); fail("Should have thrown exception"); } catch (RuntimeException e) { assertNotNull(e); } // test for an invalid Eval that it does not cause an exception evaluationSetupService.deleteEvaluation( EvalTestDataLoad.INVALID_LONG_ID, EvalTestDataLoad.MAINT_USER_ID); } /** * Test method for {@link org.sakaiproject.evaluation.logic.impl.EvalEvaluationSetupServiceImpl#getEvaluationsForUser(String, boolean, boolean)}. */ public void testGetEvaluationsForUser() { List<EvalEvaluation> evals = null; List<Long> ids = null; // get all evaluationSetupService for user evals = evaluationSetupService.getEvaluationsForUser(EvalTestDataLoad.USER_ID, false, false); assertNotNull(evals); assertEquals(5, evals.size()); ids = EvalTestDataLoad.makeIdList(evals); assertTrue(ids.contains( etdl.evaluationNewAdmin.getId() )); assertTrue(ids.contains( etdl.evaluationActive.getId() )); assertTrue(ids.contains( etdl.evaluationActiveUntaken.getId() )); assertTrue(ids.contains( etdl.evaluationClosed.getId() )); assertTrue(ids.contains( etdl.evaluationViewable.getId() )); // check sorting Date lastDate = null; for (int i=0; i<evals.size(); i++) { EvalEvaluation eval = (EvalEvaluation) evals.get(i); if (lastDate == null) { lastDate = eval.getDueDate(); } else { if (lastDate.compareTo(eval.getDueDate()) <= 0) { lastDate = eval.getDueDate(); } else { fail("Order failure:" + lastDate + " less than " + eval.getDueDate()); } } } // test get for another user evals = evaluationSetupService.getEvaluationsForUser(EvalTestDataLoad.STUDENT_USER_ID, false, false); assertNotNull(evals); assertEquals(4, evals.size()); ids = EvalTestDataLoad.makeIdList(evals); assertTrue(ids.contains( etdl.evaluationNewAdmin.getId() )); assertTrue(ids.contains( etdl.evaluationClosed.getId() )); assertTrue(ids.contains( etdl.evaluationViewable.getId() )); assertTrue(ids.contains( etdl.evaluationActiveUntaken.getId() )); // get all active evaluationSetupService for user evals = evaluationSetupService.getEvaluationsForUser(EvalTestDataLoad.USER_ID, true, false); assertNotNull(evals); assertEquals(2, evals.size()); ids = EvalTestDataLoad.makeIdList(evals); assertTrue(ids.contains( etdl.evaluationActive.getId() )); assertTrue(ids.contains( etdl.evaluationActiveUntaken.getId() )); // test active evals for another user evals = evaluationSetupService.getEvaluationsForUser(EvalTestDataLoad.STUDENT_USER_ID, true, false); assertNotNull(evals); assertEquals(1, evals.size()); ids = EvalTestDataLoad.makeIdList(evals); assertTrue(ids.contains( etdl.evaluationActiveUntaken.getId() )); // don't include taken evaluationSetupService evals = evaluationSetupService.getEvaluationsForUser(EvalTestDataLoad.USER_ID, true, true); assertNotNull(evals); assertEquals(1, evals.size()); ids = EvalTestDataLoad.makeIdList(evals); assertTrue(ids.contains( etdl.evaluationActiveUntaken.getId() )); // try to get for invalid user evals = evaluationSetupService.getEvaluationsForUser(EvalTestDataLoad.INVALID_USER_ID, false, false); assertNotNull(evals); assertEquals(1, evals.size()); ids = EvalTestDataLoad.makeIdList(evals); assertTrue(ids.contains( etdl.evaluationActiveUntaken.getId() )); } /** * Test method for {@link org.sakaiproject.evaluation.logic.impl.EvalEvaluationSetupServiceImpl#getVisibleEvaluationsForUser(java.lang.String, boolean, boolean)}. */ public void testGetVisibleEvaluationsForUser() { // test getting visible evals for the maint user List<EvalEvaluation> evals = null; List<Long> ids = null; evals = evaluationSetupService.getVisibleEvaluationsForUser(EvalTestDataLoad.MAINT_USER_ID, false, false); assertNotNull(evals); assertEquals(4, evals.size()); ids = EvalTestDataLoad.makeIdList(evals); assertTrue(ids.contains( etdl.evaluationNew.getId() )); assertTrue(ids.contains( etdl.evaluationActive.getId() )); assertTrue(ids.contains( etdl.evaluationActiveUntaken.getId() )); assertTrue(ids.contains( etdl.evaluationProvided.getId() )); // test getting visible evals for the admin user (should be all) evals = evaluationSetupService.getVisibleEvaluationsForUser(EvalTestDataLoad.ADMIN_USER_ID, false, false); assertNotNull(evals); assertEquals(7, evals.size()); // test getting recent closed evals for the admin user evals = evaluationSetupService.getVisibleEvaluationsForUser(EvalTestDataLoad.ADMIN_USER_ID, true, false); assertNotNull(evals); assertEquals(6, evals.size()); ids = EvalTestDataLoad.makeIdList(evals); assertTrue(! ids.contains( etdl.evaluationViewable.getId() )); // test getting visible evals for the normal user (should be none) evals = evaluationSetupService.getVisibleEvaluationsForUser(EvalTestDataLoad.USER_ID, false, false); assertNotNull(evals); assertEquals(0, evals.size()); } /** * Test method for {@link org.sakaiproject.evaluation.logic.impl.EvalEvaluationSetupServiceImpl#getEvalCategories(java.lang.String)}. */ public void testGetEvalCategories() { String[] cats = null; // get all categories in the system cats = evaluationSetupService.getEvalCategories(null); assertNotNull(cats); assertEquals(2, cats.length); assertEquals(EvalTestDataLoad.EVAL_CATEGORY_1, cats[0]); assertEquals(EvalTestDataLoad.EVAL_CATEGORY_2, cats[1]); // get all categories for a user cats = evaluationSetupService.getEvalCategories(EvalTestDataLoad.ADMIN_USER_ID); assertNotNull(cats); assertEquals(2, cats.length); assertEquals(EvalTestDataLoad.EVAL_CATEGORY_1, cats[0]); assertEquals(EvalTestDataLoad.EVAL_CATEGORY_2, cats[1]); cats = evaluationSetupService.getEvalCategories(EvalTestDataLoad.MAINT_USER_ID); assertNotNull(cats); assertEquals(1, cats.length); assertEquals(EvalTestDataLoad.EVAL_CATEGORY_1, cats[0]); // get no categories for user with none cats = evaluationSetupService.getEvalCategories(EvalTestDataLoad.USER_ID); assertNotNull(cats); assertEquals(0, cats.length); } /** * Test method for {@link org.sakaiproject.evaluation.logic.impl.EvalEvaluationSetupServiceImpl#getEvaluationsByCategory(java.lang.String, java.lang.String)}. */ public void testGetEvaluationsByCategory() { List<EvalEvaluation> evals = null; List<Long> ids = null; // get all evaluationSetupService for a category evals = evaluationSetupService.getEvaluationsByCategory(EvalTestDataLoad.EVAL_CATEGORY_1, null); assertNotNull(evals); assertEquals(2, evals.size()); ids = EvalTestDataLoad.makeIdList(evals); assertTrue(ids.contains( etdl.evaluationNewAdmin.getId() )); assertTrue(ids.contains( etdl.evaluationActiveUntaken.getId() )); evals = evaluationSetupService.getEvaluationsByCategory(EvalTestDataLoad.EVAL_CATEGORY_2, null); assertNotNull(evals); assertEquals(1, evals.size()); ids = EvalTestDataLoad.makeIdList(evals); assertTrue(ids.contains( etdl.evaluationClosed.getId() )); // get evaluationSetupService for a category and user evals = evaluationSetupService.getEvaluationsByCategory(EvalTestDataLoad.EVAL_CATEGORY_1, EvalTestDataLoad.USER_ID); assertNotNull(evals); assertEquals(1, evals.size()); ids = EvalTestDataLoad.makeIdList(evals); assertTrue(ids.contains( etdl.evaluationActiveUntaken.getId() )); evals = evaluationSetupService.getEvaluationsByCategory(EvalTestDataLoad.EVAL_CATEGORY_2, EvalTestDataLoad.USER_ID); assertNotNull(evals); assertEquals(0, evals.size()); // get evaluationSetupService for invalid or non-existent category evals = evaluationSetupService.getEvaluationsByCategory(EvalTestDataLoad.INVALID_CONSTANT_STRING, null); assertNotNull(evals); assertEquals(0, evals.size()); // get evaluationSetupService for invalid or non-existent user evals = evaluationSetupService.getEvaluationsByCategory(EvalTestDataLoad.EVAL_CATEGORY_1, null); assertNotNull(evals); } public void testSaveEmailTemplate() { // test valid new saves evaluationSetupService.saveEmailTemplate( new EvalEmailTemplate( new Date(), EvalTestDataLoad.MAINT_USER_ID, "subject", "a message"), EvalTestDataLoad.MAINT_USER_ID); evaluationSetupService.saveEmailTemplate( new EvalEmailTemplate( new Date(), EvalTestDataLoad.ADMIN_USER_ID, "subject", "another message"), EvalTestDataLoad.ADMIN_USER_ID); // test saving new always nulls out the defaultType // the defaultType cannot be changed when saving // (default templates can only be set in the preloaded data for now) EvalEmailTemplate testTemplate = new EvalEmailTemplate( new Date(), EvalTestDataLoad.ADMIN_USER_ID, "subject", "a message", EvalConstants.EMAIL_TEMPLATE_DEFAULT_AVAILABLE); evaluationSetupService.saveEmailTemplate( testTemplate, EvalTestDataLoad.ADMIN_USER_ID); assertNotNull( testTemplate.getId() ); assertNull( testTemplate.getDefaultType() ); // test invalid update to default template EvalEmailTemplate defaultTemplate = evaluationService.getDefaultEmailTemplate( EvalConstants.EMAIL_TEMPLATE_AVAILABLE ); try { defaultTemplate.setMessage("new message for default"); evaluationSetupService.saveEmailTemplate( defaultTemplate, EvalTestDataLoad.ADMIN_USER_ID); fail("Should have thrown exception"); } catch (RuntimeException e) { assertNotNull(e); } // test valid updates etdl.emailTemplate1.setMessage("new message 1"); evaluationSetupService.saveEmailTemplate( etdl.emailTemplate1, EvalTestDataLoad.ADMIN_USER_ID); etdl.emailTemplate2.setMessage("new message 2"); evaluationSetupService.saveEmailTemplate( etdl.emailTemplate2, EvalTestDataLoad.MAINT_USER_ID); try { etdl.emailTemplate1.setMessage("new message 1"); evaluationSetupService.saveEmailTemplate( etdl.emailTemplate1, EvalTestDataLoad.MAINT_USER_ID); fail("Should have thrown exception"); } catch (RuntimeException e) { assertNotNull(e); } try { etdl.emailTemplate2.setMessage("new message 2"); evaluationSetupService.saveEmailTemplate( etdl.emailTemplate2, EvalTestDataLoad.USER_ID); fail("Should have thrown exception"); } catch (RuntimeException e) { assertNotNull(e); } // test associated eval is not in queue (is active) so cannot update try { etdl.emailTemplate3.setMessage("new message 3"); evaluationSetupService.saveEmailTemplate( etdl.emailTemplate3, EvalTestDataLoad.MAINT_USER_ID); fail("Should have thrown exception"); } catch (RuntimeException e) { assertNotNull(e); } } // GROUP ASSIGNMENTS @SuppressWarnings("unchecked") public void testSaveAssignGroup() { // test adding evalGroupId to inqueue eval EvalAssignGroup eacNew = new EvalAssignGroup(new Date(), EvalTestDataLoad.MAINT_USER_ID, EvalTestDataLoad.SITE1_REF, EvalConstants.GROUP_TYPE_SITE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, etdl.evaluationNew); evaluationSetupService.saveAssignGroup(eacNew, EvalTestDataLoad.MAINT_USER_ID); // check save worked List<EvalAssignGroup> l = evaluationDao.findByProperties(EvalAssignGroup.class, new String[] {"evaluation.id"}, new Object[] {etdl.evaluationNew.getId()}); assertNotNull(l); assertEquals(1, l.size()); assertTrue(l.contains(eacNew)); // test adding evalGroupId to active eval EvalAssignGroup eacActive = new EvalAssignGroup(new Date(), EvalConstants.GROUP_TYPE_SITE, EvalTestDataLoad.MAINT_USER_ID, EvalTestDataLoad.SITE2_REF, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, etdl.evaluationActive); evaluationSetupService.saveAssignGroup(eacActive, EvalTestDataLoad.MAINT_USER_ID); // check save worked l = evaluationDao.findByProperties(EvalAssignGroup.class, new String[] {"evaluation.id"}, new Object[] {etdl.evaluationActive.getId()}); assertNotNull(l); assertEquals(2, l.size()); assertTrue(l.contains(eacActive)); // test modify safe part while active EvalAssignGroup testEac1 = (EvalAssignGroup) evaluationDao. findById( EvalAssignGroup.class, etdl.assign1.getId() ); testEac1.setStudentsViewResults( Boolean.TRUE ); evaluationSetupService.saveAssignGroup(testEac1, EvalTestDataLoad.MAINT_USER_ID); // test modify safe part while closed EvalAssignGroup testEac2 = (EvalAssignGroup) evaluationDao. findById( EvalAssignGroup.class, etdl.assign4.getId() ); testEac2.setStudentsViewResults( Boolean.TRUE ); evaluationSetupService.saveAssignGroup(testEac2, EvalTestDataLoad.MAINT_USER_ID); // test admin can modify un-owned evalGroupId EvalAssignGroup testEac3 = (EvalAssignGroup) evaluationDao. findById( EvalAssignGroup.class, etdl.assign6.getId() ); testEac3.setStudentsViewResults( Boolean.TRUE ); evaluationSetupService.saveAssignGroup(testEac3, EvalTestDataLoad.ADMIN_USER_ID); // test cannot add duplicate evalGroupId to in-queue eval try { evaluationSetupService.saveAssignGroup( new EvalAssignGroup(new Date(), EvalTestDataLoad.MAINT_USER_ID, EvalTestDataLoad.SITE1_REF, EvalConstants.GROUP_TYPE_SITE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, etdl.evaluationNew), EvalTestDataLoad.MAINT_USER_ID); fail("Should have thrown exception"); } catch (RuntimeException e) { assertNotNull(e); } // test cannot add duplicate evalGroupId to active eval try { evaluationSetupService.saveAssignGroup( new EvalAssignGroup(new Date(), EvalTestDataLoad.MAINT_USER_ID, EvalTestDataLoad.SITE1_REF, EvalConstants.GROUP_TYPE_SITE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, etdl.evaluationActive), EvalTestDataLoad.MAINT_USER_ID); fail("Should have thrown exception"); } catch (RuntimeException e) { assertNotNull(e); } // test user without perm cannot add evalGroupId to eval try { evaluationSetupService.saveAssignGroup( new EvalAssignGroup(new Date(), EvalTestDataLoad.USER_ID, EvalTestDataLoad.SITE1_REF, EvalConstants.GROUP_TYPE_SITE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, etdl.evaluationNew), EvalTestDataLoad.USER_ID); fail("Should have thrown exception"); } catch (RuntimeException e) { assertNotNull(e); } // test cannot add evalGroupId to closed eval try { evaluationSetupService.saveAssignGroup( new EvalAssignGroup(new Date(), EvalTestDataLoad.MAINT_USER_ID, EvalTestDataLoad.SITE1_REF, EvalConstants.GROUP_TYPE_SITE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, etdl.evaluationViewable), EvalTestDataLoad.MAINT_USER_ID); fail("Should have thrown exception"); } catch (RuntimeException e) { assertNotNull(e); } // test cannot modify non-owned evalGroupId try { etdl.assign7.setStudentsViewResults( Boolean.TRUE ); evaluationSetupService.saveAssignGroup(etdl.assign7, EvalTestDataLoad.MAINT_USER_ID); fail("Should have thrown exception"); } catch (RuntimeException e) { assertNotNull(e); } // TODO - these tests cannot pass right now because of hibernate screwing us -AZ // // test modify evalGroupId while new eval // try { // EvalAssignContext testEac4 = (EvalAssignContext) evaluationDao. // findById( EvalAssignContext.class, etdl.assign6.getId() ); // testEac4.setContext( EvalTestDataLoad.CONTEXT3 ); // evaluationSetupService.saveAssignContext(testEac4, EvalTestDataLoad.MAINT_USER_ID); // fail("Should have thrown exception"); // } catch (RuntimeException e) { // assertNotNull(e); // // test modify evalGroupId while active eval // try { // EvalAssignContext testEac5 = (EvalAssignContext) evaluationDao. // findById( EvalAssignContext.class, etdl.assign1.getId() ); // testEac5.setContext( EvalTestDataLoad.CONTEXT2 ); // evaluationSetupService.saveAssignContext(testEac5, EvalTestDataLoad.MAINT_USER_ID); // fail("Should have thrown exception"); // } catch (RuntimeException e) { // assertNotNull(e); // // test modify evalGroupId while closed eval // try { // EvalAssignContext testEac6 = (EvalAssignContext) evaluationDao. // findById( EvalAssignContext.class, etdl.assign4.getId() ); // testEac6.setContext( EvalTestDataLoad.CONTEXT1 ); // evaluationSetupService.saveAssignContext(testEac6, EvalTestDataLoad.MAINT_USER_ID); // fail("Should have thrown exception"); // } catch (RuntimeException e) { // assertNotNull(e); // TODO - test that evaluation cannot be changed } /** * Test method for {@link org.sakaiproject.evaluation.logic.impl.EvalEvaluationSetupServiceImpl#deleteAssignGroup(java.lang.Long, java.lang.String)}. */ @SuppressWarnings("unchecked") public void testDeleteAssignGroup() { // save some ACs to test removing EvalAssignGroup eac1 = new EvalAssignGroup(new Date(), EvalTestDataLoad.MAINT_USER_ID, EvalTestDataLoad.SITE1_REF, EvalConstants.GROUP_TYPE_SITE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, etdl.evaluationNew); EvalAssignGroup eac2 = new EvalAssignGroup(new Date(), EvalTestDataLoad.ADMIN_USER_ID, EvalTestDataLoad.SITE2_REF, EvalConstants.GROUP_TYPE_SITE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, etdl.evaluationNew); evaluationDao.save(eac1); evaluationDao.save(eac2); // check save worked List<EvalAssignGroup> l = evaluationDao.findByProperties(EvalAssignGroup.class, new String[] {"evaluation.id"}, new Object[] {etdl.evaluationNew.getId()}); assertNotNull(l); assertEquals(2, l.size()); assertTrue(l.contains(eac1)); assertTrue(l.contains(eac2)); // test can remove contexts from new Evaluation Long eacId = eac1.getId(); evaluationSetupService.deleteAssignGroup( eacId, EvalTestDataLoad.MAINT_USER_ID ); evaluationSetupService.deleteAssignGroup( etdl.assign6.getId(), EvalTestDataLoad.MAINT_USER_ID ); // check save worked l = evaluationDao.findByProperties(EvalAssignGroup.class, new String[] {"evaluation.id"}, new Object[] {etdl.evaluationNew.getId()}); assertNotNull(l); assertEquals(1, l.size()); assertTrue(! l.contains(eac1)); // test cannot remove evalGroupId from active eval try { evaluationSetupService.deleteAssignGroup( etdl.assign1.getId(), EvalTestDataLoad.MAINT_USER_ID ); fail("Should have thrown exception"); } catch (RuntimeException e) { assertNotNull(e); } // test cannot remove evalGroupId from closed eval try { evaluationSetupService.deleteAssignGroup( etdl.assign4.getId(), EvalTestDataLoad.MAINT_USER_ID ); fail("Should have thrown exception"); } catch (RuntimeException e) { assertNotNull(e); } try { evaluationSetupService.deleteAssignGroup( eac2.getId(), EvalTestDataLoad.USER_ID ); fail("Should have thrown exception"); } catch (RuntimeException e) { assertNotNull(e); } // test cannot remove evalGroupId without ownership try { evaluationSetupService.deleteAssignGroup( etdl.assign7.getId(), EvalTestDataLoad.MAINT_USER_ID ); fail("Should have thrown exception"); } catch (RuntimeException e) { assertNotNull(e); } // test remove invalid eac try { evaluationSetupService.deleteAssignGroup( EvalTestDataLoad.INVALID_LONG_ID, EvalTestDataLoad.MAINT_USER_ID ); fail("Should have thrown exception"); } catch (RuntimeException e) { assertNotNull(e); } } }
package org.graylog2.plugins.slack.output; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import org.graylog2.plugin.Message; import org.graylog2.plugin.configuration.Configuration; import org.graylog2.plugin.configuration.ConfigurationException; import org.graylog2.plugin.configuration.ConfigurationRequest; import org.graylog2.plugin.inputs.annotations.ConfigClass; import org.graylog2.plugin.inputs.annotations.FactoryClass; import org.graylog2.plugin.outputs.MessageOutput; import org.graylog2.plugin.outputs.MessageOutputConfigurationException; import org.graylog2.plugin.streams.Stream; import org.graylog2.plugins.slack.SlackClient; import org.graylog2.plugins.slack.SlackMessage; import org.graylog2.plugins.slack.SlackPluginBase; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormat; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import static com.google.common.base.Strings.isNullOrEmpty; public class SlackMessageOutput extends SlackPluginBase implements MessageOutput { private AtomicBoolean running = new AtomicBoolean(false); private final Configuration configuration; private final Stream stream; private final SlackClient client; @Inject public SlackMessageOutput(@Assisted Stream stream, @Assisted Configuration configuration) throws MessageOutputConfigurationException { this.configuration = configuration; this.stream = stream; // Check configuration. try { checkConfiguration(configuration); } catch (ConfigurationException e) { throw new MessageOutputConfigurationException("Missing configuration: " + e.getMessage()); } this.client = new SlackClient(configuration); running.set(true); } @Override public void stop() { running.set(false); } @Override public boolean isRunning() { return running.get(); } @Override public void write(Message msg) throws Exception { SlackMessage slackMessage = new SlackMessage( configuration.getString(CK_COLOR), configuration.getString(CK_ICON_EMOJI), configuration.getString(CK_ICON_URL), buildMessage(stream, msg), configuration.getString(CK_USER_NAME), configuration.getString(CK_CHANNEL), configuration.getBoolean(CK_LINK_NAMES) ); // Add attachments if requested. if (!configuration.getBoolean(CK_SHORT_MODE) && configuration.getBoolean(CK_ADD_ATTACHMENT)) { slackMessage.addAttachment(new SlackMessage.AttachmentField("Stream Description", stream.getDescription(), false)); slackMessage.addAttachment(new SlackMessage.AttachmentField("Source", msg.getSource(), true)); for (Map.Entry<String, Object> field : msg.getFields().entrySet()) { if (Message.RESERVED_FIELDS.contains(field.getKey())) { continue; } slackMessage.addAttachment(new SlackMessage.AttachmentField(field.getKey(), field.getValue().toString(), true)); } } try { client.send(slackMessage); } catch (SlackClient.SlackClientException e) { throw new RuntimeException("Could not send message to Slack.", e); } } public String buildMessage(Stream stream, Message msg) { if (configuration.getBoolean(CK_SHORT_MODE)) { return msg.getTimestamp().toDateTime(DateTimeZone.getDefault()).toString(DateTimeFormat.shortTime()) + ": " + msg.getMessage(); } String graylogUri = configuration.getString(CK_GRAYLOG2_URL); boolean notifyChannel = configuration.getBoolean(CK_NOTIFY_CHANNEL); String streamLink; if (!isNullOrEmpty(graylogUri)) { streamLink = "<" + buildStreamLink(graylogUri, stream) + "|" + stream.getTitle() + ">"; } else { streamLink = "_" + stream.getTitle() + "_"; } String messageLink; if (!isNullOrEmpty(graylogUri)) { String index = "graylog_deflector"; // would use msg.getFieldAs(String.class, "_index"), but it returns null messageLink = "<" + buildMessageLink(graylogUri, index, msg.getId()) + "|New message>"; } else { messageLink = "New message"; } return (notifyChannel ? "@channel " : "") + "*" + messageLink + " in Graylog stream " + streamLink + "*:\n" + "> " + msg.getMessage(); } @Override public void write(List<Message> list) throws Exception { for (Message message : list) { write(message); } } public Map<String, Object> getConfiguration() { return configuration.getSource(); } @FactoryClass public interface Factory extends MessageOutput.Factory<SlackMessageOutput> { @Override SlackMessageOutput create(Stream stream, Configuration configuration); @Override Config getConfig(); @Override Descriptor getDescriptor(); } @ConfigClass public static class Config extends MessageOutput.Config { @Override public ConfigurationRequest getRequestedConfiguration() { return configuration(); } } public static class Descriptor extends MessageOutput.Descriptor { public Descriptor() { super("Slack Output", false, "", "Writes messages to a Slack chat room."); } } }
package edu.kit.iti.formal.pse.worthwhile.prover; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Stack; import edu.kit.iti.formal.pse.worthwhile.model.ast.Assertion; import edu.kit.iti.formal.pse.worthwhile.model.ast.Assignment; import edu.kit.iti.formal.pse.worthwhile.model.ast.Assumption; import edu.kit.iti.formal.pse.worthwhile.model.ast.AstFactory; import edu.kit.iti.formal.pse.worthwhile.model.ast.Axiom; import edu.kit.iti.formal.pse.worthwhile.model.ast.Block; import edu.kit.iti.formal.pse.worthwhile.model.ast.BooleanLiteral; import edu.kit.iti.formal.pse.worthwhile.model.ast.Conditional; import edu.kit.iti.formal.pse.worthwhile.model.ast.Conjunction; import edu.kit.iti.formal.pse.worthwhile.model.ast.Expression; import edu.kit.iti.formal.pse.worthwhile.model.ast.FunctionDeclaration; import edu.kit.iti.formal.pse.worthwhile.model.ast.Implication; import edu.kit.iti.formal.pse.worthwhile.model.ast.Invariant; import edu.kit.iti.formal.pse.worthwhile.model.ast.Loop; import edu.kit.iti.formal.pse.worthwhile.model.ast.Negation; import edu.kit.iti.formal.pse.worthwhile.model.ast.Program; import edu.kit.iti.formal.pse.worthwhile.model.ast.ReturnStatement; import edu.kit.iti.formal.pse.worthwhile.model.ast.Statement; import edu.kit.iti.formal.pse.worthwhile.model.ast.VariableDeclaration; import edu.kit.iti.formal.pse.worthwhile.model.ast.util.AstNodeCloneHelper; import edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.ASTNodeVisitor; import edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor; /** * Applies the Weakest Precondition calculus to a {@link Program}. */ class WPStrategy extends HierarchialASTNodeVisitor implements FormulaGenerator { /** * The stack of weakest preconditions that implies the correctness of the remainder {@link Block}. */ private Stack<Expression> weakestPreconditionStack; /** * Construct a new weakest precondition strategy object. */ public WPStrategy() { this.weakestPreconditionStack = new Stack<Expression>(); } /** * @return the weakestPrecondition */ public Expression getWeakestPrecondition() { return this.weakestPreconditionStack.get(0); } /** * @param program * the {@link Program} to calculate the weakest precondition for * @return the weakest precondition that implies the correctness of <code>program</code> * @see FormulaGenerator#transformProgram(Program program) */ public Expression transformProgram(final Program program) { // clear weakestPrecondition state from a previous transformation this.weakestPreconditionStack.clear(); // initialize the weakest precondition to true BooleanLiteral trueLiteral = AstFactory.init().createBooleanLiteral(); trueLiteral.setValue(true); this.weakestPreconditionStack.push(trueLiteral); /* * pass us as visitor from statement to statement: * * 1. get the weakest precondition, 2. apply the appropriate calculus rule, 3. set the weakest * precondition, 4. forward us to the next statement * * finally the weakest precondition implies the correctness of the whole program */ program.accept(this); return this.getWeakestPrecondition(); } /** * Visit a {@link Assertion}. * * @param assertion * the {@link Assertion} to visit */ public void visit(final Assertion assertion) { Conjunction conjunction = AstFactory.init().createConjunction(); conjunction.setRight(this.weakestPreconditionStack.pop()); conjunction.setLeft(AstNodeCloneHelper.clone(assertion.getExpression())); this.weakestPreconditionStack.push(conjunction); } /** * Visit a {@link Assignment} to generate the weakest precondition. * * @param assignment * the {@link Assignment} to visit */ public void visit(final Assignment assignment) { VariableDeclaration variableDeclaration = assignment.getVariable().getVariable(); this.getWeakestPrecondition().accept( new VariableSubstitution(variableDeclaration, assignment.getValue(), new VariableSubstitution.SubstituteCommand() { @Override void substitute() { /* * In case the current postcondition only consists of a * VariableReference that has to be replaced, substitute * it directly */ WPStrategy.this.weakestPreconditionStack.pop(); WPStrategy.this.weakestPreconditionStack .push(assignment.getValue()); } })); } /** * Visit an {@link Assumption}. * * <code><pre> * _assume assumption * </pre></code> * * to * * <code><pre> * assumption => wp * </pre></code> * * @param assumption * the <code>Assumption</code> to visit */ public void visit(final Assumption assumption) { Implication implication = AstFactory.init().createImplication(); implication.setLeft(AstNodeCloneHelper.clone(assumption.getExpression())); implication.setRight(this.weakestPreconditionStack.pop()); this.weakestPreconditionStack.push(implication); } /** * Visit a {@link Axiom}. * * @param axiom * the {@link Axiom} to visit */ public void visit(final Axiom axiom) { // begin-user-code // TODO Auto-generated method stub // end-user-code } /** * Visit a {@link Block} to generate the weakest precondition. * * @param block * the {@link Block} to visit */ public void visit(final Block block) { // visit all block statements in the order they were parsed reversed List<Statement> stmts = new ArrayList<Statement>(block.getStatements()); Collections.reverse(stmts); for (Statement stmt : stmts) { stmt.accept(this); } } /** * Visit a {@link Conditional} to generate the weakest precondition. * * Transforms * * <pre> * if condition * if-block * else * else-block * </pre> * * to * * <pre> * condition => wp(if-block, wp) && !condition => wp(else-block, wp) * </pre> * * If a <code>else-block</code> is missing <code>wp(else-block, wp)</code> is <code>true</code>. * * @param conditional * the {@link Conditional} to visit */ public void visit(final Conditional conditional) { // the updated weakest precondition Conjunction conjunction = AstFactory.init().createConjunction(); // build first implication: condition => wp(if-block, wp) Implication implication = AstFactory.init().createImplication(); implication.setLeft(AstNodeCloneHelper.clone(conditional.getCondition())); Expression wp = this.weakestPreconditionStack.peek(); // will calculate new wp for if-block and replace wp on top of stack with it conditional.getTrueBlock().accept(this); implication.setRight(this.weakestPreconditionStack.pop()); conjunction.setLeft(implication); // build second implication: !condition => wp(else-block, wp) implication = AstFactory.init().createImplication(); Negation negation = AstFactory.init().createNegation(); negation.setOperand(AstNodeCloneHelper.clone(conditional.getCondition())); implication.setLeft(negation); if (conditional.getFalseBlock() != null) { this.weakestPreconditionStack.push(wp); // will calculate new wp for else-block and replace wp on top of stack with it conditional.getFalseBlock().accept(this); implication.setRight(this.weakestPreconditionStack.pop()); } else { BooleanLiteral trueLiteral = AstFactory.init().createBooleanLiteral(); trueLiteral.setValue(true); implication.setRight(trueLiteral); } conjunction.setRight(implication); // put updated weakest precondition on top of stack this.weakestPreconditionStack.push(conjunction); } /** * Visit a {@link FunctionDeclaration}. * * @param functionDeclaration * the {@link FunctionDeclaration} to visit */ public void visit(final FunctionDeclaration functionDeclaration) { // begin-user-code // TODO Auto-generated method stub // end-user-code } /** * Visit a {@link Loop} to generate the weakest precondition. * * @param loop * the {@link Loop} to visit */ public void visit(final Loop loop) { AstFactory factory = AstFactory.init(); // and all the loop invariants BooleanLiteral trueLiteral = factory.createBooleanLiteral(); trueLiteral.setValue(true); Expression invariant = trueLiteral; for (Invariant i : loop.getInvariants()) { Conjunction conj = factory.createConjunction(); conj.setLeft(invariant); conj.setRight(i.getExpression()); invariant = conj; } // (condition and invariant) implies wp(body, invariant) Conjunction conditionAndInvariant = factory.createConjunction(); conditionAndInvariant.setLeft(AstNodeCloneHelper.clone(loop.getCondition())); conditionAndInvariant.setRight(AstNodeCloneHelper.clone(invariant)); // generate weakest precondition for the body given the invariant as the postcondition this.weakestPreconditionStack.push(invariant); loop.getBody().accept(this); Expression bodyPrecondition = this.weakestPreconditionStack.pop(); Implication conditionAndInvariantImpliesBodyPrecondition = factory.createImplication(); conditionAndInvariantImpliesBodyPrecondition.setLeft(conditionAndInvariant); conditionAndInvariantImpliesBodyPrecondition.setRight(AstNodeCloneHelper .clone(bodyPrecondition)); // ((not condition) and invariant) implies postcondition Negation notCondition = factory.createNegation(); notCondition.setOperand(AstNodeCloneHelper.clone(loop.getCondition())); Conjunction notConditionAndInvariant = factory.createConjunction(); notConditionAndInvariant.setLeft(notCondition); notConditionAndInvariant.setRight(AstNodeCloneHelper.clone(invariant)); Implication notConditionAndInvariantImpliesPostcondition = factory.createImplication(); notConditionAndInvariantImpliesPostcondition.setLeft(notConditionAndInvariant); notConditionAndInvariantImpliesPostcondition.setRight(this.getWeakestPrecondition()); // refresh variables ASTNodeVisitor refreshVisitor = new FreshVariableSetVisitor(); conditionAndInvariantImpliesBodyPrecondition.accept(refreshVisitor); refreshVisitor = new FreshVariableSetVisitor(); notConditionAndInvariantImpliesPostcondition.accept(refreshVisitor); // assemble the weakest precondition from the three conditions Conjunction invariantAndConditionTrueCase = factory.createConjunction(); invariantAndConditionTrueCase.setLeft(AstNodeCloneHelper.clone(invariant)); invariantAndConditionTrueCase.setRight(conditionAndInvariantImpliesBodyPrecondition); Conjunction loopPrecondition = factory.createConjunction(); loopPrecondition.setLeft(invariantAndConditionTrueCase); loopPrecondition.setRight(notConditionAndInvariantImpliesPostcondition); // replace the weakest precondition on the stack this.weakestPreconditionStack.pop(); this.weakestPreconditionStack.push(loopPrecondition); } /** * Visit a {@link Program} to generate the weakest precondition. * * @param program * the {@link Program} to visit */ public void visit(final Program program) { // visit program's main block program.getMainBlock().accept(this); } /** * Visit a {@link ReturnStatement}. * * @param returnStatement * the {@link ReturnStatement} to visit */ public void visit(final ReturnStatement returnStatement) { // begin-user-code // TODO Auto-generated method stub // end-user-code } /** * Visit a {@link VariableDeclaration} to generate the weakest precondition. * * @param variableDeclaration * the {@link VariableDeclaration} to visit */ public void visit(final VariableDeclaration variableDeclaration) { this.getWeakestPrecondition().accept( new VariableSubstitution(variableDeclaration, variableDeclaration.getInitialValue(), new VariableSubstitution.SubstituteCommand() { @Override void substitute() { /* * In case the current postcondition only consists of a * VariableReference that has to be replaced, substitute * it directly */ WPStrategy.this.weakestPreconditionStack.pop(); WPStrategy.this.weakestPreconditionStack .push(variableDeclaration .getInitialValue()); } })); } }
package org.jbpm.simulation.impl; import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.drools.definition.process.Node; import org.eclipse.bpmn2.Definitions; import org.eclipse.bpmn2.ExtensionAttributeValue; import org.eclipse.bpmn2.FlowElement; import org.eclipse.bpmn2.FlowElementsContainer; import org.eclipse.bpmn2.Relationship; import org.eclipse.emf.ecore.util.FeatureMap; import org.jboss.drools.CostParameters; import org.jboss.drools.DecimalParameterType; import org.jboss.drools.DroolsPackage; import org.jboss.drools.ElementParametersType; import org.jboss.drools.FloatingParameterType; import org.jboss.drools.NormalDistributionType; import org.jboss.drools.Parameter; import org.jboss.drools.ParameterValue; import org.jboss.drools.ProcessAnalysisDataType; import org.jboss.drools.RandomDistributionType; import org.jboss.drools.ResourceParameters; import org.jboss.drools.Scenario; import org.jboss.drools.UniformDistributionType; import org.jbpm.simulation.SimulationDataProvider; import org.jbpm.simulation.util.BPMN2Utils; import org.jbpm.simulation.util.SimulationConstants; import org.jbpm.simulation.util.SimulationUtils; public class BPMN2SimulationDataProvider implements SimulationDataProvider { private Definitions def; public BPMN2SimulationDataProvider(Definitions def) { this.def = def; } public BPMN2SimulationDataProvider(String bpmn2xml) { this.def = BPMN2Utils.getDefinitions(new ByteArrayInputStream(getBytes(bpmn2xml))); } public Map<String, Object> getSimulationDataForNode(Node node) { String nodeId = (String) node.getMetaData().get("UniqueId"); return getSimulationDataForNode(nodeId); } public Map<String, Object> getSimulationDataForNode( String nodeId) { Map<String, Object> properties = new HashMap<String, Object>(); Scenario scenario = getDefaultScenario(def); if(scenario != null) { String baseTimeUnitValue = ""; String baseCurrencyUnitValue = ""; if(scenario.getScenarioParameters() != null) { baseCurrencyUnitValue = scenario.getScenarioParameters().getBaseCurrencyUnit(); baseTimeUnitValue = scenario.getScenarioParameters().getBaseTimeUnit().getName(); } if(scenario.getElementParameters() != null) { for(ElementParametersType eleType : scenario.getElementParameters()) { if(eleType.getElementId().equals(nodeId)) { if(eleType.getControlParameters() != null && eleType.getControlParameters().getProbability() != null) { FloatingParameterType valType = (FloatingParameterType) eleType.getControlParameters().getProbability().getParameterValue().get(0); properties.put("probability", valType.getValue()); } if(eleType.getTimeParameters() != null) { if(eleType.getTimeParameters().getProcessingTime() != null) { Parameter processingTime = eleType.getTimeParameters().getProcessingTime(); ParameterValue paramValue = processingTime.getParameterValue().get(0); if(paramValue instanceof NormalDistributionType) { NormalDistributionType ndt = (NormalDistributionType) paramValue; properties.put("standarddeviation", ndt.getStandardDeviation()); properties.put("distributiontype", "normal"); } else if(paramValue instanceof UniformDistributionType) { UniformDistributionType udt = (UniformDistributionType) paramValue; properties.put("max", udt.getMax()); properties.put("min", udt.getMin()); properties.put("distributiontype", "uniform"); } else if(paramValue instanceof RandomDistributionType) { RandomDistributionType rdt = (RandomDistributionType) paramValue; properties.put("max", rdt.getMax()); properties.put("min", rdt.getMin()); properties.put("distributiontype", "random"); } if(eleType.getTimeParameters().getTimeUnit() != null) { properties.put("timeunit", eleType.getTimeParameters().getTimeUnit().getName()); } else { properties.put("timeunit", baseTimeUnitValue); } } } if(eleType.getCostParameters() != null) { CostParameters costParams = eleType.getCostParameters(); if(costParams.getUnitCost() != null) { DecimalParameterType unitCostVal = (DecimalParameterType) costParams.getUnitCost().getParameterValue().get(0); properties.put("unitcost", unitCostVal.getValue().toString()); } properties.put("currency", costParams.getCurrencyUnit() == null ? baseCurrencyUnitValue : costParams.getCurrencyUnit()); } if(eleType.getResourceParameters() != null) { ResourceParameters resourceParams = eleType.getResourceParameters(); if(resourceParams.getQuantity() != null) { FloatingParameterType quantityVal = (FloatingParameterType) resourceParams.getQuantity().getParameterValue().get(0); properties.put("quantity", quantityVal.getValue()); } if(resourceParams.getWorkinghours() != null) { FloatingParameterType workingHoursVal = (FloatingParameterType) resourceParams.getWorkinghours().getParameterValue().get(0); properties.put("workinghours", workingHoursVal.getValue()); } } } } } } return properties; } protected FlowElement findElementInContainer(FlowElementsContainer container, String id) { List<FlowElement> currentContainerElems = container.getFlowElements(); for (FlowElement fElement : currentContainerElems) { if (fElement.getId().equals(id) ) { return fElement; } else if (fElement instanceof FlowElementsContainer) { FlowElement fe = findElementInContainer((FlowElementsContainer) fElement, id); if (fe != null) { return fe; } } } return null; } public double calculatePathProbability(SimulationPath path) { double probability = 100; for (String sequenceFlowId : path.getSequenceFlowsIds()) { String probabilityFromElement = (String) getSimulationDataForNode(sequenceFlowId).get(SimulationConstants.PROBABILITY); if (probabilityFromElement != null) { double transitionProbability = SimulationUtils.asDouble(probabilityFromElement); if (transitionProbability > 0) { probability = probability * (transitionProbability / 100); } } } double result = probability / 100; path.setProbability(result); return result; } private static byte[] getBytes(String string) { try { return string.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e.getMessage()); } } private Scenario getDefaultScenario(Definitions def) { if(def.getRelationships() != null && def.getRelationships().size() > 0) { // current support for single relationship Relationship relationship = def.getRelationships().get(0); for(ExtensionAttributeValue extattrval : relationship.getExtensionValues()) { FeatureMap extensionElements = extattrval.getValue(); @SuppressWarnings("unchecked") List<ProcessAnalysisDataType> processAnalysisExtensions = (List<ProcessAnalysisDataType>) extensionElements.get(DroolsPackage.Literals.DOCUMENT_ROOT__PROCESS_ANALYSIS_DATA, true); if(processAnalysisExtensions != null && processAnalysisExtensions.size() > 0) { ProcessAnalysisDataType processAnalysis = processAnalysisExtensions.get(0); if(processAnalysis.getScenario() != null && processAnalysis.getScenario().size() > 0) { return processAnalysis.getScenario().get(0); } } } } return null; } }
package org.jnosql.diana.api.column.query; public final class ColumnQueryBuilder { private ColumnQueryBuilder() { } }
package org.keycloak.admin.client.resource; import org.keycloak.representations.idm.MappingsRepresentation; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; /** * @author rodrigo.sasaki@icarros.com.br */ @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public interface RoleMappingResource { @GET public MappingsRepresentation getAll(); @Path("realm") public RoleScopeResource realmLevel(); @Path("clients/{clientId}") public RoleScopeResource clientLevel(@PathParam("clientId") String clientId); }
package org.ligoj.app.plugin.prov.dao; import java.util.List; import javax.cache.annotation.CacheKey; import javax.cache.annotation.CacheResult; import org.ligoj.app.plugin.prov.model.ProvLocation; import org.ligoj.bootstrap.core.dao.RestRepository; import org.springframework.data.jpa.repository.Query; /** * {@link ProvLocation} repository. */ public interface ProvLocationRepository extends RestRepository<ProvLocation, Integer> { /** * Return all {@link ProvLocation} related to given node identifier. * * @param node * The node identifier to match. * @return All locations linked to this node. */ @Query("SELECT pl FROM ProvLocation pl INNER JOIN pl.node n WHERE" + " (:node = n.id OR :node LIKE CONCAT(n.id, ':%'))" + " AND EXISTS (SELECT 1 FROM ProvInstancePrice ip WHERE ip.location = pl)") List<ProvLocation> findAll(String node); /** * Return the {@link ProvLocation} by it's name, ignoring the case. * * @param node * The node identifier to match. * @param name * The name to match. * * @return The entity or <code>null</code>. */ @Query("SELECT pl FROM ProvLocation pl INNER JOIN pl.node n WHERE" + " (:node = n.id OR :node LIKE CONCAT(n.id, ':%')) AND UPPER(pl.name) = UPPER(:name)") ProvLocation findByName(String node, String name); /** * Return the {@link ProvLocation} identifier by it's name, ignoring the case. * * @param node * The node identifier to match. * @param name * The name to match. * * @return The entity identifier or <code>null</code>. */ @CacheResult(cacheName = "prov-location") @Query("SELECT pl.id FROM ProvLocation pl INNER JOIN pl.node n WHERE" + " (:node = n.id OR :node LIKE CONCAT(n.id, ':%')) AND UPPER(pl.name) = UPPER(:name)") Integer toId(@CacheKey String node, @CacheKey String name); }
package org.opentripplanner.analyst.broker; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.io.ByteStreams; import org.glassfish.grizzly.http.Method; import org.glassfish.grizzly.http.server.HttpHandler; import org.glassfish.grizzly.http.server.Request; import org.glassfish.grizzly.http.server.Response; import org.glassfish.grizzly.http.util.HttpStatus; import org.opentripplanner.analyst.cluster.AnalystClusterRequest; import org.opentripplanner.api.model.AgencyAndIdSerializer; import org.opentripplanner.api.model.JodaLocalDateSerializer; import java.io.IOException; import java.util.List; class BrokerHttpHandler extends HttpHandler { // TODO we should really just make one static mapper somewhere and use it throughout OTP private ObjectMapper mapper = new ObjectMapper() .registerModule(AgencyAndIdSerializer.makeModule()) .registerModule(JodaLocalDateSerializer.makeModule()) .setSerializationInclusion(JsonInclude.Include.NON_NULL);; private Broker broker; public BrokerHttpHandler(Broker broker) { this.broker = broker; } @Override public void service(Request request, Response response) throws Exception { response.setContentType("application/json"); // request.getRequestURI(); // without protocol or server, only request path // request.getPathInfo(); // without handler base path String[] pathComponents = request.getPathInfo().split("/"); // Path component 0 is empty since the path always starts with a slash. if (pathComponents.length < 2) { response.setStatus(HttpStatus.BAD_REQUEST_400); response.setDetailMessage("path should have at least one part"); } try { if (request.getMethod() == Method.HEAD) { /* Let the client know server is alive and URI + request are valid. */ mapper.readTree(request.getInputStream()); response.setStatus(HttpStatus.OK_200); return; } else if (request.getMethod() == Method.GET) { /* Return a chunk of tasks for a particular graph. */ String graphAffinity = pathComponents[1]; request.getRequest().getConnection().addCloseListener((closeable, iCloseType) -> { broker.removeSuspendedResponse(graphAffinity, response); }); response.suspend(); // The request should survive after the handler function exits. broker.registerSuspendedResponse(graphAffinity, response); } else if (request.getMethod() == Method.POST) { /* Enqueue new messages. */ String context = pathComponents[1]; if ("priority".equals(context)) { if (pathComponents.length == 2) { // Enqueue a single priority task AnalystClusterRequest task = mapper.readValue(request.getInputStream(), AnalystClusterRequest.class); broker.enqueuePriorityTask(task, response); // Enqueueing the priority task has set its internal taskId. // TODO move all removal listener registration into the broker functions. request.getRequest().getConnection().addCloseListener((closeable, iCloseType) -> { broker.deletePriorityTask(task.taskId); }); response.suspend(); // The request should survive after the handler function exits. } else { // Mark a specific high-priority task as completed, and record its result. // We were originally planning to do this with a DELETE request that has a body, // but that is nonstandard enough to anger many libraries including Grizzly. int taskId = Integer.parseInt(pathComponents[2]); Response suspendedProducerResponse = broker.deletePriorityTask(taskId); if (suspendedProducerResponse == null) { response.setStatus(HttpStatus.NOT_FOUND_404); return; } // Copy the result back to the connection that was the source of the task. try { ByteStreams.copy(request.getInputStream(), suspendedProducerResponse.getOutputStream()); } catch (IOException ioex) { // Apparently the task producer did not wait to retrieve its result. Priority task result delivery // is not guaranteed, we don't need to retry, this is not considered an error by the worker. } response.setStatus(HttpStatus.OK_200); suspendedProducerResponse.setStatus(HttpStatus.OK_200); suspendedProducerResponse.resume(); return; } } else if ("jobs".equals(context)) { // Enqueue a list of tasks that belong to jobs List<AnalystClusterRequest> tasks = mapper.readValue(request.getInputStream(), new TypeReference<List<AnalystClusterRequest>>(){}); // Pre-validate tasks checking that they are all on the same job AnalystClusterRequest exemplar = tasks.get(0); for (AnalystClusterRequest task : tasks) { if (task.jobId != exemplar.jobId || task.graphId != exemplar.graphId) { response.setStatus(HttpStatus.BAD_REQUEST_400); response.setDetailMessage("All tasks must be for the same graph and job."); } } broker.enqueueTasks(tasks); response.setStatus(HttpStatus.ACCEPTED_202); } else { response.setStatus(HttpStatus.NOT_FOUND_404); response.setDetailMessage("Context not found; should be either 'jobs' or 'priority'"); } } else if (request.getMethod() == Method.DELETE) { /* Acknowledge completion of a task and remove it from queues, avoiding re-delivery. */ if ("tasks".equalsIgnoreCase(pathComponents[1])) { int taskId = Integer.parseInt(pathComponents[2]); // This must not have been a priority task. Try to delete it as a normal job task. if (broker.deleteJobTask(taskId)) { response.setStatus(HttpStatus.OK_200); } else { response.setStatus(HttpStatus.NOT_FOUND_404); } } else { response.setStatus(HttpStatus.BAD_REQUEST_400); response.setDetailMessage("Delete is only allowed for tasks."); } } else { response.setStatus(HttpStatus.BAD_REQUEST_400); response.setDetailMessage("Unrecognized HTTP method."); } } catch (JsonProcessingException jpex) { response.setStatus(HttpStatus.BAD_REQUEST_400); response.setDetailMessage("Could not decode/encode JSON payload. " + jpex.getMessage()); jpex.printStackTrace(); } catch (Exception ex) { response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500); response.setDetailMessage(ex.toString()); ex.printStackTrace(); } } public void writeJson (Response response, Object object) throws IOException { mapper.writeValue(response.getOutputStream(), object); } }
package org.sagebionetworks.web.client.widget; import org.gwtbootstrap3.client.ui.constants.AlertType; import org.sagebionetworks.web.client.context.SynapseContextPropsProvider; import org.sagebionetworks.web.client.context.SynapseContextPropsProviderImpl; import org.sagebionetworks.web.client.jsinterop.FullWidthAlertProps; import org.sagebionetworks.web.client.jsinterop.React; import org.sagebionetworks.web.client.jsinterop.ReactDOM; import org.sagebionetworks.web.client.jsinterop.ReactElement; import org.sagebionetworks.web.client.jsinterop.SRC; import com.google.gwt.core.shared.GWT; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Widget; public class FullWidthAlert implements IsWidget { ReactComponentDiv container; String title, message, primaryButtonText, secondaryButtonText, secondaryButtonHref, alertType; FullWidthAlertProps.Callback onPrimaryClick; FullWidthAlertProps.Callback onClose = new FullWidthAlertProps.Callback() { @Override public void run() { setVisible(false); } }; Boolean isGlobal = true; /** * This is a full width info Alert component, with an icon, message and link. * */ public FullWidthAlert() { container = new ReactComponentDiv(); } private void rerender() { Double autoCloseAfterDelayInSeconds = null; FullWidthAlertProps props = FullWidthAlertProps.create(title, message, primaryButtonText, onPrimaryClick, secondaryButtonText, secondaryButtonHref, onClose, autoCloseAfterDelayInSeconds, isGlobal, alertType); ReactElement component = React.createElement(SRC.SynapseComponents.FullWidthAlert, props); ReactDOM.render(component, container.getElement()); } @Override public Widget asWidget() { return container; } public void setVisible(boolean visible) { container.setVisible(visible); } public void setAddStyleNames(String styleNames) { container.addStyleName(styleNames); } public boolean isVisible() { return container.isVisible(); } public boolean isAttached() { return container.isAttached(); } public void setMessageTitle(String title) { this.title = title; rerender(); } public void setMessage(String message) { this.message = message; rerender(); } public void setPrimaryCTAHref(String href) { setPrimaryCTAHref(href, "_blank"); } public void setPrimaryCTAHrefTargetSelf(String href) { setPrimaryCTAHref(href, "_self"); } private void setPrimaryCTAHref(String href, String target) { addPrimaryCTAClickHandler(event -> { Window.open(href, target, ""); }); } public void addPrimaryCTAClickHandler(ClickHandler c) { this.onPrimaryClick = new FullWidthAlertProps.Callback() { @Override public void run() { c.onClick(null); } }; rerender(); } public void setPrimaryCTAText(String text) { String newText = text != null ? text.toUpperCase() : null; this.primaryButtonText = newText; rerender(); } public void setSecondaryCTAText(String text) { String newText = text != null ? text.toUpperCase() : null; this.secondaryButtonText = newText; rerender(); } public void setSecondaryCTAHref(String href) { this.secondaryButtonHref = href; rerender(); } public void setAlertType(AlertType type) { this.alertType = type.name().toLowerCase(); rerender(); } public void setGlobal(boolean isGlobal) { this.isGlobal = isGlobal; } }
package org.spongepowered.common.event.tracking; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import co.aikar.timings.Timing; import com.flowpowered.math.vector.Vector3i; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import net.minecraft.block.Block; import net.minecraft.block.BlockEventData; import net.minecraft.block.BlockRedstoneLight; import net.minecraft.block.BlockRedstoneRepeater; import net.minecraft.block.BlockRedstoneTorch; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.item.EntityItem; import net.minecraft.init.Blocks; import net.minecraft.util.ITickable; import net.minecraft.util.math.BlockPos; import net.minecraft.world.WorldProvider; import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.Chunk; import org.apache.logging.log4j.Level; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.block.tileentity.TileEntity; import org.spongepowered.api.data.Transaction; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.living.player.User; import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.api.event.block.ChangeBlockEvent; import org.spongepowered.api.event.block.TickBlockEvent; import org.spongepowered.api.event.cause.Cause; import org.spongepowered.api.event.cause.NamedCause; import org.spongepowered.api.event.cause.entity.spawn.BlockSpawnCause; import org.spongepowered.api.event.item.inventory.DropItemEvent; import org.spongepowered.api.item.inventory.ItemStackSnapshot; import org.spongepowered.api.world.BlockChangeFlag; import org.spongepowered.api.world.LocatableBlock; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.World; import org.spongepowered.asm.util.PrettyPrinter; import org.spongepowered.common.SpongeImpl; import org.spongepowered.common.block.SpongeBlockSnapshot; import org.spongepowered.common.entity.EntityUtil; import org.spongepowered.common.event.InternalNamedCauses; import org.spongepowered.common.event.ShouldFire; import org.spongepowered.common.event.tracking.phase.block.BlockPhase; import org.spongepowered.common.event.tracking.phase.general.GeneralPhase; import org.spongepowered.common.event.tracking.phase.tick.TickPhase; import org.spongepowered.common.interfaces.IMixinChunk; import org.spongepowered.common.interfaces.block.IMixinBlock; import org.spongepowered.common.interfaces.block.IMixinBlockEventData; import org.spongepowered.common.interfaces.block.tile.IMixinTileEntity; import org.spongepowered.common.interfaces.entity.IMixinEntity; import org.spongepowered.common.interfaces.world.IMixinLocation; import org.spongepowered.common.interfaces.world.IMixinWorldServer; import org.spongepowered.common.interfaces.world.gen.IMixinChunkProviderServer; import org.spongepowered.common.item.inventory.util.ItemStackUtil; import org.spongepowered.common.mixin.plugin.blockcapturing.IModData_BlockCapturing; import org.spongepowered.common.registry.type.event.InternalSpawnTypes; import org.spongepowered.common.util.SpongeHooks; import org.spongepowered.common.world.BlockChange; import org.spongepowered.common.world.SpongeProxyBlockAccess; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Random; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; /** * A simple utility for aiding in tracking, either with resolving notifiers * and owners, or proxying out the logic for ticking a block, entity, etc. */ public final class TrackingUtil { public static final int BREAK_BLOCK_INDEX = 0; public static final int PLACE_BLOCK_INDEX = 1; public static final int DECAY_BLOCK_INDEX = 2; public static final int CHANGE_BLOCK_INDEX = 3; public static final int MULTI_CHANGE_INDEX = 4; public static final Function<ImmutableList.Builder<Transaction<BlockSnapshot>>[], Consumer<Transaction<BlockSnapshot>>> TRANSACTION_PROCESSOR = builders -> transaction -> { final BlockChange blockChange = ((SpongeBlockSnapshot) transaction.getOriginal()).blockChange; builders[blockChange.ordinal()].add(transaction); builders[MULTI_CHANGE_INDEX].add(transaction); } ; public static final int EVENT_COUNT = 5; public static final BiFunction<WorldServer, BlockSnapshot, Transaction<BlockSnapshot>> TRANSACTION_CREATION = ((worldServer, blockSnapshot) -> { final BlockPos blockPos = ((IMixinLocation) (Object) blockSnapshot.getLocation().get()).getBlockPos(); final IBlockState newState = worldServer.getBlockState(blockPos); final IBlockState newActualState = newState.getActualState(worldServer, blockPos); final BlockSnapshot newSnapshot = ((IMixinWorldServer) worldServer).createSpongeBlockSnapshot(newState, newActualState, blockPos, 0); return new Transaction<>(blockSnapshot, newSnapshot); }); public static void tickEntity(CauseTracker causeTracker, net.minecraft.entity.Entity entityIn) { checkArgument(entityIn instanceof Entity, "Entity %s is not an instance of SpongeAPI's Entity!", entityIn); checkNotNull(entityIn, "Cannot capture on a null ticking entity!"); final net.minecraft.world.chunk.Chunk chunk = ((IMixinChunkProviderServer) ((WorldServer) entityIn.world).getChunkProvider()).getLoadedChunkWithoutMarkingActive(entityIn.getPosition().getX() >> 4, entityIn.getPosition().getZ() >> 4); if (chunk == null || (chunk.unloaded && !((IMixinChunk) chunk).isPersistedChunk())) { // Don't tick entities in chunks queued for unload return; } final PhaseContext phaseContext = PhaseContext.start() .add(NamedCause.source(entityIn)) .addEntityCaptures() .addBlockCaptures(); final IMixinEntity mixinEntity = EntityUtil.toMixin(entityIn); mixinEntity.getNotifierUser() .ifPresent(phaseContext::notifier); mixinEntity.getCreatorUser() .ifPresent(phaseContext::owner); causeTracker.switchToPhase(TickPhase.Tick.ENTITY, phaseContext .complete()); final Timing entityTiming = mixinEntity.getTimingsHandler(); entityTiming.startTiming(); entityIn.onUpdate(); entityTiming.stopTiming(); causeTracker.completePhase(); } public static void tickRidingEntity(CauseTracker causeTracker, net.minecraft.entity.Entity entity) { checkArgument(entity instanceof Entity, "Entity %s is not an instance of SpongeAPI's Entity!", entity); checkNotNull(entity, "Cannot capture on a null ticking entity!"); final net.minecraft.world.chunk.Chunk chunk = ((IMixinChunkProviderServer) ((WorldServer) entity.world).getChunkProvider()).getLoadedChunkWithoutMarkingActive(entity.getPosition().getX() >> 4, entity.getPosition().getZ() >> 4); if (chunk == null || (chunk.unloaded && !((IMixinChunk) chunk).isPersistedChunk())) { // Don't tick entity in chunks queued for unload return; } final PhaseContext phaseContext = PhaseContext.start() .add(NamedCause.source(entity)) .addEntityCaptures() .addBlockCaptures(); final IMixinEntity mixinEntity = EntityUtil.toMixin(entity); mixinEntity.getNotifierUser() .ifPresent(phaseContext::notifier); mixinEntity.getCreatorUser() .ifPresent(phaseContext::owner); causeTracker.switchToPhase(TickPhase.Tick.ENTITY, phaseContext .complete()); final Timing entityTiming = mixinEntity.getTimingsHandler(); entityTiming.startTiming(); entity.updateRidden(); entityTiming.stopTiming(); causeTracker.completePhase(); } public static void tickTileEntity(CauseTracker causeTracker, ITickable tile) { checkArgument(tile instanceof TileEntity, "ITickable %s is not a TileEntity!", tile); checkNotNull(tile, "Cannot capture on a null ticking tile entity!"); final net.minecraft.tileentity.TileEntity tileEntity = (net.minecraft.tileentity.TileEntity) tile; final WorldServer worldServer = causeTracker.getMinecraftWorld(); final BlockPos pos = tileEntity.getPos(); final net.minecraft.world.chunk.Chunk chunk = ((IMixinChunkProviderServer) worldServer.getChunkProvider()).getLoadedChunkWithoutMarkingActive(pos.getX() >> 4, pos.getZ() >> 4); if (chunk == null || (chunk.unloaded && !((IMixinChunk) chunk).isPersistedChunk())) { // Don't tick TE's in chunks queued for unload return; } final PhaseContext phaseContext = PhaseContext.start() .add(NamedCause.source(tile)) .addEntityCaptures() .addBlockCaptures(); final IMixinChunk mixinChunk = (IMixinChunk) chunk; // Add notifier and owner so we don't have to perform lookups during the phases and other processing mixinChunk.getBlockNotifier(pos) .ifPresent(phaseContext::notifier); mixinChunk.getBlockOwner(pos) .ifPresent(phaseContext::owner); final IMixinTileEntity mixinTileEntity = (IMixinTileEntity) tile; // Add the block snapshot of the tile entity for caches to avoid creating multiple snapshots during processing // This is a lazy evaluating snapshot to avoid the overhead of snapshot creation causeTracker.switchToPhase(TickPhase.Tick.TILE_ENTITY, phaseContext .complete()); mixinTileEntity.getTimingsHandler().startTiming(); tile.update(); mixinTileEntity.getTimingsHandler().stopTiming(); causeTracker.completePhase(); } public static void updateTickBlock(CauseTracker causeTracker, Block block, BlockPos pos, IBlockState state, Random random) { final IMixinWorldServer mixinWorld = causeTracker.getMixinWorld(); final WorldServer minecraftWorld = causeTracker.getMinecraftWorld(); if (ShouldFire.TICK_BLOCK_EVENT) { BlockSnapshot snapshot = mixinWorld.createSpongeBlockSnapshot(state, state, pos, 0); final TickBlockEvent event = SpongeEventFactory.createTickBlockEventScheduled(Cause.of(NamedCause.source(minecraftWorld)), snapshot); SpongeImpl.postEvent(event); if(event.isCancelled()) { return; } } final LocatableBlock locatable = LocatableBlock.builder() .location(new Location<World>((World) minecraftWorld, pos.getX(), pos.getY(), pos.getZ())) .state((BlockState) state) .build(); final PhaseContext phaseContext = PhaseContext.start() .add(NamedCause.source(locatable)) .addBlockCaptures() .addEntityCaptures(); checkAndAssignBlockTickConfig(block, minecraftWorld, phaseContext); // We have to associate any notifiers in case of scheduled block updates from other sources final PhaseData current = causeTracker.getCurrentPhaseData(); final IPhaseState currentState = current.state; currentState.getPhase().appendNotifierPreBlockTick(causeTracker, pos, currentState, current.context, phaseContext); // Now actually switch to the new phase if (((IMixinBlock) block).requiresBlockCapture()) { causeTracker.switchToPhase(TickPhase.Tick.BLOCK, phaseContext.complete()); } else { causeTracker.switchToPhase(TickPhase.Tick.NO_CAPTURE_BLOCK, phaseContext.complete()); } block.updateTick(minecraftWorld, pos, state, random); causeTracker.completePhase(); } public static void randomTickBlock(CauseTracker causeTracker, Block block, BlockPos pos, IBlockState state, Random random) { final IMixinWorldServer mixinWorld = causeTracker.getMixinWorld(); final WorldServer minecraftWorld = causeTracker.getMinecraftWorld(); if (ShouldFire.TICK_BLOCK_EVENT) { final BlockSnapshot currentTickBlock = mixinWorld.createSpongeBlockSnapshot(state, state, pos, 0); final TickBlockEvent event = SpongeEventFactory.createTickBlockEventRandom(Cause.of(NamedCause.source(minecraftWorld)), currentTickBlock); SpongeImpl.postEvent(event); if(event.isCancelled()) { return; } } final LocatableBlock locatable = LocatableBlock.builder() .location(new Location<World>((World) minecraftWorld, pos.getX(), pos.getY(), pos.getZ())) .state((BlockState) state) .build(); final PhaseContext phaseContext = PhaseContext.start() .add(NamedCause.source(locatable)) .addEntityCaptures() .addBlockCaptures(); checkAndAssignBlockTickConfig(block, minecraftWorld, phaseContext); // We have to associate any notifiers in case of scheduled block updates from other sources final PhaseData current = causeTracker.getCurrentPhaseData(); final IPhaseState currentState = current.state; currentState.getPhase().appendNotifierPreBlockTick(causeTracker, pos, currentState, current.context, phaseContext); // Now actually switch to the new phase if (((IMixinBlock) block).requiresBlockCapture()) { causeTracker.switchToPhase(TickPhase.Tick.RANDOM_BLOCK, phaseContext.complete()); } else { causeTracker.switchToPhase(TickPhase.Tick.NO_CAPTURE_BLOCK, phaseContext.complete()); } block.randomTick(minecraftWorld, pos, state, random); causeTracker.completePhase(); } private static void checkAndAssignBlockTickConfig(Block block, WorldServer minecraftWorld, PhaseContext phaseContext) { if (block instanceof IModData_BlockCapturing) { IModData_BlockCapturing capturingBlock = (IModData_BlockCapturing) block; if (capturingBlock.requiresBlockCapturingRefresh()) { capturingBlock.initializeBlockCapturingState(minecraftWorld); capturingBlock.requiresBlockCapturingRefresh(false); } phaseContext.add(NamedCause.of(InternalNamedCauses.Tracker.PROCESS_IMMEDIATELY, ((IModData_BlockCapturing) block).processTickChangesImmediately())); } else { phaseContext.add(NamedCause.of(InternalNamedCauses.Tracker.PROCESS_IMMEDIATELY, false)); } } public static void tickWorldProvider(IMixinWorldServer worldServer) { final CauseTracker causeTracker = worldServer.getCauseTracker(); final WorldProvider worldProvider = ((WorldServer) worldServer).provider; causeTracker.switchToPhase(TickPhase.Tick.DIMENSION, PhaseContext.start() .add(NamedCause.source(worldProvider)) .addBlockCaptures() .addEntityCaptures() .addEntityDropCaptures() .complete()); worldProvider.onWorldUpdateEntities(); causeTracker.completePhase(); } public static boolean fireMinecraftBlockEvent(CauseTracker causeTracker, WorldServer worldIn, BlockEventData event) { IBlockState currentState = worldIn.getBlockState(event.getPosition()); final IMixinBlockEventData blockEvent = (IMixinBlockEventData) event; final PhaseContext phaseContext = PhaseContext.start() .addBlockCaptures() .addEntityCaptures(); Object source = blockEvent.getTickBlock() != null ? blockEvent.getTickBlock() : blockEvent.getTickTileEntity(); if (source != null) { phaseContext.add(NamedCause.source(source)); } else { // No source present which means we are ignoring the phase state boolean result = currentState.onBlockEventReceived(worldIn, event.getPosition(), event.getEventID(), event.getEventParameter()); return result; } if (blockEvent.getSourceUser() != null) { phaseContext.add(NamedCause.notifier(blockEvent.getSourceUser())); } if (blockEvent.getCaptureBlocks()) { causeTracker.switchToPhase(TickPhase.Tick.BLOCK_EVENT, phaseContext.complete()); } else { causeTracker.switchToPhase(TickPhase.Tick.NO_CAPTURE_BLOCK, phaseContext.complete()); } boolean result = currentState.onBlockEventReceived(worldIn, event.getPosition(), event.getEventID(), event.getEventParameter()); causeTracker.completePhase(); return result; } public static void performBlockDrop(Block block, IMixinWorldServer mixinWorld, BlockPos pos, IBlockState state, float chance, int fortune) { final CauseTracker causeTracker = mixinWorld.getCauseTracker(); final IPhaseState currentState = causeTracker.getCurrentState(); final boolean shouldEnterBlockDropPhase = !currentState.getPhase().alreadyCapturingItemSpawns(currentState); if (shouldEnterBlockDropPhase) { PhaseContext context = PhaseContext.start() .add(NamedCause.source(mixinWorld.createSpongeBlockSnapshot(state, state, pos, 4))) .addBlockCaptures() .addEntityCaptures(); // unused, to be removed and re-located when phase context is cleaned up //.add(NamedCause.of(InternalNamedCauses.General.BLOCK_BREAK_FORTUNE, fortune)) //.add(NamedCause.of(InternalNamedCauses.General.BLOCK_BREAK_POSITION, pos)); // use current notifier and owner if available context.notifier = causeTracker.getCurrentContext().notifier; context.owner = causeTracker.getCurrentContext().owner; context.complete(); causeTracker.switchToPhase(BlockPhase.State.BLOCK_DROP_ITEMS, context); } block.dropBlockAsItemWithChance((WorldServer) mixinWorld, pos, state, chance, fortune); if (shouldEnterBlockDropPhase) { causeTracker.completePhase(); } } static boolean trackBlockChange(CauseTracker causeTracker, Chunk chunk, IBlockState currentState, IBlockState newState, BlockPos pos, int flags, PhaseContext phaseContext, IPhaseState phaseState) { final SpongeBlockSnapshot originalBlockSnapshot; final WorldServer minecraftWorld = causeTracker.getMinecraftWorld(); if (phaseState.shouldCaptureBlockChangeOrSkip(phaseContext, pos)) { //final IBlockState actualState = currentState.getActualState(minecraftWorld, pos); originalBlockSnapshot = causeTracker.getMixinWorld().createSpongeBlockSnapshot(currentState, currentState, pos, flags); final List<BlockSnapshot> capturedSnapshots = phaseContext.getCapturedBlocks(); final Block newBlock = newState.getBlock(); associateBlockChangeWithSnapshot(phaseState, newBlock, currentState, originalBlockSnapshot, capturedSnapshots); final IMixinChunk mixinChunk = (IMixinChunk) chunk; final IBlockState originalBlockState = mixinChunk.setBlockState(pos, newState, currentState, originalBlockSnapshot); if (originalBlockState == null) { capturedSnapshots.remove(originalBlockSnapshot); return false; } phaseState.postTrackBlock(originalBlockSnapshot, causeTracker, phaseContext); } else { originalBlockSnapshot = (SpongeBlockSnapshot) BlockSnapshot.NONE; final IMixinChunk mixinChunk = (IMixinChunk) chunk; final IBlockState originalBlockState = mixinChunk.setBlockState(pos, newState, currentState, originalBlockSnapshot); if (originalBlockState == null) { return false; } } if (newState.getLightOpacity() != currentState.getLightOpacity() || newState.getLightValue() != currentState.getLightValue()) { minecraftWorld.theProfiler.startSection("checkLight"); minecraftWorld.checkLight(pos); minecraftWorld.theProfiler.endSection(); } return true; } private static void associateBlockChangeWithSnapshot(IPhaseState phaseState, Block newBlock, IBlockState currentState, SpongeBlockSnapshot snapshot, List<BlockSnapshot> capturedSnapshots) { Block originalBlock = currentState.getBlock(); if (phaseState == BlockPhase.State.BLOCK_DECAY) { if (newBlock == Blocks.AIR) { snapshot.blockChange = BlockChange.DECAY; capturedSnapshots.add(snapshot); } } else if (newBlock == Blocks.AIR) { snapshot.blockChange = BlockChange.BREAK; capturedSnapshots.add(snapshot); } else if (newBlock != originalBlock && !forceModify(originalBlock, newBlock)) { snapshot.blockChange = BlockChange.PLACE; capturedSnapshots.add(snapshot); } else { snapshot.blockChange = BlockChange.MODIFY; capturedSnapshots.add(snapshot); } } private static boolean forceModify(Block originalBlock, Block newBlock) { if (originalBlock instanceof BlockRedstoneRepeater && newBlock instanceof BlockRedstoneRepeater) { return true; } if (originalBlock instanceof BlockRedstoneTorch && newBlock instanceof BlockRedstoneTorch) { return true; } if (originalBlock instanceof BlockRedstoneLight && newBlock instanceof BlockRedstoneLight) { return true; } return false; } private TrackingUtil() { } public static User getNotifierOrOwnerFromBlock(Location<World> location) { final BlockPos blockPos = ((IMixinLocation) (Object) location).getBlockPos(); return getNotifierOrOwnerFromBlock((WorldServer) location.getExtent(), blockPos); } public static User getNotifierOrOwnerFromBlock(net.minecraft.world.WorldServer world, BlockPos blockPos) { final IMixinChunk mixinChunk = (IMixinChunk) ((WorldServer) world).getChunkFromBlockCoords(blockPos); User notifier = mixinChunk.getBlockNotifier(blockPos).orElse(null); if (notifier != null) { return notifier; } User owner = mixinChunk.getBlockOwner(blockPos).orElse(null); return owner; } public static Supplier<IllegalStateException> throwWithContext(String s, PhaseContext phaseContext) { return () -> { final PrettyPrinter printer = new PrettyPrinter(60); printer.add("Exception trying to process over a phase!").centre().hr(); printer.addWrapped(40, "%s :", "PhaseContext"); CauseTracker.CONTEXT_PRINTER.accept(printer, phaseContext); printer.add("Stacktrace:"); final IllegalStateException exception = new IllegalStateException(s + " Please analyze the current phase context. "); printer.add(exception); printer.trace(System.err, SpongeImpl.getLogger(), Level.TRACE); return exception; }; } /** * Processes the given list of {@link BlockSnapshot}s and creates and throws and processes * the {@link ChangeBlockEvent}s as appropriately determined based on the {@link BlockChange} * for each snapshot. If any transactions are invalid or events cancelled, this event * returns {@code false} to signify a transaction was cancelled. This return value * is used for portal creation. * * @param snapshots The snapshots to process * @param causeTracker The cause tracker for the world * @param state The phase state that is being processed, used to handle marking notifiers * and block owners * @param context The phase context, only used by the phase for handling processes. * @return True if no events or transactions were cancelled */ @SuppressWarnings({"unchecked", "rawtypes"}) public static boolean processBlockCaptures(List<BlockSnapshot> snapshots, CauseTracker causeTracker, IPhaseState state, PhaseContext context) { if (snapshots.isEmpty()) { return false; } ImmutableList<Transaction<BlockSnapshot>>[] transactionArrays = new ImmutableList[EVENT_COUNT]; ImmutableList.Builder<Transaction<BlockSnapshot>>[] transactionBuilders = new ImmutableList.Builder[EVENT_COUNT]; for (int i = 0; i < EVENT_COUNT; i++) { transactionBuilders[i] = new ImmutableList.Builder<>(); } final List<ChangeBlockEvent> blockEvents = new ArrayList<>(); final WorldServer minecraftWorld = causeTracker.getMinecraftWorld(); for (BlockSnapshot snapshot : snapshots) { // This processes each snapshot to assign them to the correct event in the next area, with the // correct builder array entry. TRANSACTION_PROCESSOR.apply(transactionBuilders).accept(TRANSACTION_CREATION.apply(minecraftWorld, snapshot)); } for (int i = 0; i < EVENT_COUNT; i++) { // Build each event array transactionArrays[i] = transactionBuilders[i].build(); } final ChangeBlockEvent[] mainEvents = new ChangeBlockEvent[BlockChange.values().length]; // This likely needs to delegate to the phase in the event we don't use the source object as the main object causing the block changes // case in point for WorldTick event listeners since the players are captured non-deterministically final Cause.Builder builder = Cause.source(context.getSource(Object.class) .orElseThrow(throwWithContext("There was no root source object for this phase!", context)) ); context.getNotifier().ifPresent(builder::notifier); context.getOwner().ifPresent(builder::owner); try { state.getPhase().associateAdditionalCauses(state, context, builder, causeTracker); } catch (Exception e) { // TODO - this should be a thing to associate additional objects in the cause, or context, but for now it's just a simple // try catch to avoid bombing on performing block changes. } final org.spongepowered.api.world.World world = causeTracker.getWorld(); // Creates the block events accordingly to the transaction arrays iterateChangeBlockEvents(transactionArrays, blockEvents, mainEvents, builder, world); // Needs to throw events // We create the post event and of course post it in the method, regardless whether any transactions are invalidated or not final ChangeBlockEvent.Post postEvent = throwMultiEventsAndCreatePost(transactionArrays, blockEvents, mainEvents, builder, world); if (postEvent == null) { // Means that we have had no actual block changes apparently? return false; } final List<Transaction<BlockSnapshot>> invalid = new ArrayList<>(); boolean noCancelledTransactions = true; // Iterate through the block events to mark any transactions as invalid to accumilate after (since the post event contains all // transactions of the preceeding block events) for (ChangeBlockEvent blockEvent : blockEvents) { // Need to only check if the event is cancelled, If it is, restore if (blockEvent.isCancelled()) { noCancelledTransactions = false; // Don't restore the transactions just yet, since we're just marking them as invalid for now for (Transaction<BlockSnapshot> transaction : Lists.reverse(blockEvent.getTransactions())) { transaction.setValid(false); } } } // Finally check the post event if (postEvent.isCancelled()) { // Of course, if post is cancelled, just mark all transactions as invalid. noCancelledTransactions = false; for (Transaction<BlockSnapshot> transaction : postEvent.getTransactions()) { transaction.setValid(false); } } // Now we can gather the invalid transactions that either were marked as invalid from an event listener - OR - cancelled. // Because after, we will restore all the invalid transactions in reverse order. for (Transaction<BlockSnapshot> transaction : postEvent.getTransactions()) { if (!transaction.isValid()) { invalid.add(transaction); // Cancel any block drops performed, avoids any item drops, regardless context.getBlockItemDropSupplier().ifPresentAndNotEmpty(map -> { final BlockPos blockPos = ((IMixinLocation) (Object) transaction.getOriginal().getLocation().get()).getBlockPos(); map.get(blockPos).clear(); }); } } if (!invalid.isEmpty()) { // We need to set this value and return it to signify that some transactions were cancelled noCancelledTransactions = false; // NOW we restore the invalid transactions (remember invalid transactions are from either plugins marking them as invalid // or the events were cancelled), again in reverse order of which they were received. for (Transaction<BlockSnapshot> transaction : Lists.reverse(invalid)) { transaction.getOriginal().restore(true, BlockChangeFlag.NONE); if (state.tracksBlockSpecificDrops()) { // Cancel any block drops or harvests for the block change. // This prevents unnecessary spawns. final BlockPos position = ((IMixinLocation) (Object) transaction.getOriginal().getLocation().get()).getBlockPos(); context.getBlockDropSupplier().ifPresentAndNotEmpty(map -> { // Check if the mapping actually has the position to avoid unnecessary // collection creation if (map.containsKey(position)) { map.get(position).clear(); } }); } } } return performBlockAdditions(causeTracker, postEvent.getTransactions(), builder, state, context, noCancelledTransactions); } public static void iterateChangeBlockEvents(ImmutableList<Transaction<BlockSnapshot>>[] transactionArrays, List<ChangeBlockEvent> blockEvents, ChangeBlockEvent[] mainEvents, Cause.Builder builder, org.spongepowered.api.world.World world) { for (BlockChange blockChange : BlockChange.values()) { if (blockChange == BlockChange.DECAY) { // Decay takes place after. continue; } if (!transactionArrays[blockChange.ordinal()].isEmpty()) { final ChangeBlockEvent event = blockChange.createEvent(builder.build(), world, transactionArrays[blockChange.ordinal()]); mainEvents[blockChange.ordinal()] = event; if (event != null) { SpongeImpl.postEvent(event); blockEvents.add(event); } } } if (!transactionArrays[BlockChange.DECAY.ordinal()].isEmpty()) { // Needs to be placed into iterateChangeBlockEvents final ChangeBlockEvent event = BlockChange.DECAY.createEvent(builder.build(), world, transactionArrays[BlockChange.DECAY.ordinal()]); mainEvents[BlockChange.DECAY.ordinal()] = event; if (event != null) { SpongeImpl.postEvent(event); blockEvents.add(event); } } } public static boolean performBlockAdditions(CauseTracker causeTracker, List<Transaction<BlockSnapshot>> transactions, Cause.Builder builder, IPhaseState phaseState, PhaseContext phaseContext, boolean noCancelledTransactions) { // We have to use a proxy so that our pending changes are notified such that any accessors from block // classes do not fail on getting the incorrect block state from the IBlockAccess final WorldServer minecraftWorld = causeTracker.getMinecraftWorld(); final SpongeProxyBlockAccess proxyBlockAccess = new SpongeProxyBlockAccess(minecraftWorld, transactions); final CapturedMultiMapSupplier<BlockPos, ItemDropData> capturedBlockDrops = phaseContext.getBlockDropSupplier(); final CapturedMultiMapSupplier<BlockPos, EntityItem> capturedBlockItemEntityDrops = phaseContext.getBlockItemDropSupplier(); for (Transaction<BlockSnapshot> transaction : transactions) { if (!transaction.isValid()) { // Rememver that this value needs to be set to false to return because of the fact that // a transaction was marked as invalid or cancelled. This is used primarily for // things like portal creation, and if false, removes the portal from the cache noCancelledTransactions = false; continue; // Don't use invalidated block transactions during notifications, these only need to be restored } // Handle custom replacements if (transaction.getCustom().isPresent()) { transaction.getFinal().restore(true, BlockChangeFlag.NONE); } final SpongeBlockSnapshot oldBlockSnapshot = (SpongeBlockSnapshot) transaction.getOriginal(); final SpongeBlockSnapshot newBlockSnapshot = (SpongeBlockSnapshot) transaction.getFinal(); // Handle item drops captured final BlockPos pos = ((IMixinLocation) (Object) oldBlockSnapshot.getLocation().get()).getBlockPos(); // This is for pre-merged items capturedBlockDrops.ifPresentAndNotEmpty(map -> spawnItemDataForBlockDrops(map.containsKey(pos) ? map.get(pos) : Collections.emptyList(), newBlockSnapshot, causeTracker, phaseContext, phaseState)); // And this is for un-pre-merged items, these will be EntityItems, not ItemDropDatas. capturedBlockItemEntityDrops.ifPresentAndNotEmpty(map -> spawnItemEntitiesForBlockDrops(map.containsKey(pos) ? map.get(pos) : Collections.emptyList(), newBlockSnapshot, causeTracker, phaseContext, phaseState)); SpongeHooks.logBlockAction(builder, minecraftWorld, oldBlockSnapshot.blockChange, transaction); final BlockChangeFlag changeFlag = oldBlockSnapshot.getChangeFlag(); final IBlockState originalState = (IBlockState) oldBlockSnapshot.getState(); final IBlockState newState = (IBlockState) newBlockSnapshot.getState(); // We call onBlockAdded here for both TE blocks (BlockContainer's) and other blocks. // MixinChunk#setBlockState will only call onBlockAdded for BlockContainers when it's passed a null newBlockSnapshot, // which only happens when capturing is not being done. if (changeFlag.performBlockPhysics() && originalState.getBlock() != newState.getBlock()) { newState.getBlock().onBlockAdded(minecraftWorld, pos, newState); final PhaseData peek = causeTracker.getCurrentPhaseData(); if (peek.state == GeneralPhase.Post.UNWINDING) { peek.state.getPhase().unwind(causeTracker, peek.state, peek.context); } } proxyBlockAccess.proceed(); phaseState.handleBlockChangeWithUser(oldBlockSnapshot.blockChange, minecraftWorld, transaction, phaseContext); final int minecraftChangeFlag = oldBlockSnapshot.getUpdateFlag(); if (((minecraftChangeFlag & 2) != 0)) { // Always try to notify clients of the change. causeTracker.getMinecraftWorld().notifyBlockUpdate(pos, originalState, newState, minecraftChangeFlag); } if (changeFlag.updateNeighbors()) { // Notify neighbors only if the change flag allowed it. causeTracker.getMixinWorld().spongeNotifyNeighborsPostBlockChange(pos, originalState, newState, oldBlockSnapshot.getUpdateFlag()); } else if ((minecraftChangeFlag & 16) == 0) { causeTracker.getMinecraftWorld().updateObservingBlocksAt(pos, newState.getBlock()); } final PhaseData peek = causeTracker.getCurrentPhaseData(); if (peek.state == GeneralPhase.Post.UNWINDING) { peek.state.getPhase().unwind(causeTracker, peek.state, peek.context); } } return noCancelledTransactions; } public static void spawnItemEntitiesForBlockDrops(Collection<EntityItem> entityItems, SpongeBlockSnapshot newBlockSnapshot, CauseTracker causeTracker, PhaseContext phaseContext, IPhaseState phaseState) { // Now we can spawn the entity items appropriately final List<Entity> itemDrops = entityItems.stream() .map(EntityUtil::fromNative) .collect(Collectors.toList()); final Cause.Builder builder = Cause.source(BlockSpawnCause.builder() .block(newBlockSnapshot) .type(InternalSpawnTypes.DROPPED_ITEM) .build()); final Optional<User> owner = phaseContext.getOwner(); final Optional<User> notifier = phaseContext.getNotifier(); notifier.ifPresent(builder::notifier); final User entityCreator = notifier.orElseGet(() -> owner.orElse(null)); final Cause spawnCauses = builder.build(); final DropItemEvent.Destruct destruct = SpongeEventFactory.createDropItemEventDestruct(spawnCauses, itemDrops, causeTracker.getWorld()); SpongeImpl.postEvent(destruct); if (!destruct.isCancelled()) { for (Entity entity : destruct.getEntities()) { if (entityCreator != null) { EntityUtil.toMixin(entity).setCreator(entityCreator.getUniqueId()); } causeTracker.getMixinWorld().forceSpawnEntity(entity); } } } public static void spawnItemDataForBlockDrops(Collection<ItemDropData> itemStacks, SpongeBlockSnapshot oldBlockSnapshot, CauseTracker causeTracker, PhaseContext phaseContext, IPhaseState state) { final Vector3i position = oldBlockSnapshot.getPosition(); final List<ItemStackSnapshot> itemSnapshots = itemStacks.stream() .map(ItemDropData::getStack) .map(ItemStackUtil::createSnapshot) .collect(Collectors.toList()); final ImmutableList<ItemStackSnapshot> originalSnapshots = ImmutableList.copyOf(itemSnapshots); final Cause cause = Cause.source(oldBlockSnapshot).build(); final DropItemEvent.Pre dropItemEventPre = SpongeEventFactory.createDropItemEventPre(cause, originalSnapshots, itemSnapshots); SpongeImpl.postEvent(dropItemEventPre); if (dropItemEventPre.isCancelled()) { itemStacks.clear(); } if (itemStacks.isEmpty()) { return; } // Now we can spawn the entity items appropriately final List<Entity> itemDrops = itemStacks.stream().map(itemStack -> { final net.minecraft.item.ItemStack minecraftStack = itemStack.getStack(); final WorldServer minecraftWorld = causeTracker.getMinecraftWorld(); float f = 0.5F; double offsetX = (double) (minecraftWorld.rand.nextFloat() * f) + (double) (1.0F - f) * 0.5D; double offsetY = (double) (minecraftWorld.rand.nextFloat() * f) + (double) (1.0F - f) * 0.5D; double offsetZ = (double) (minecraftWorld.rand.nextFloat() * f) + (double) (1.0F - f) * 0.5D; final double x = (double) position.getX() + offsetX; final double y = (double) position.getY() + offsetY; final double z = (double) position.getZ() + offsetZ; EntityItem entityitem = new EntityItem(minecraftWorld, x, y, z, minecraftStack); entityitem.setDefaultPickupDelay(); return entityitem; }) .map(EntityUtil::fromNative) .collect(Collectors.toList()); final Cause.Builder builder = Cause.source(BlockSpawnCause.builder() .block(oldBlockSnapshot) .type(InternalSpawnTypes.DROPPED_ITEM) .build()); phaseContext.getNotifier().ifPresent(builder::notifier); final User entityCreator = phaseContext.getNotifier().orElseGet(() -> phaseContext.getOwner().orElse(null)); final Cause spawnCauses = builder.build(); final DropItemEvent.Destruct destruct = SpongeEventFactory.createDropItemEventDestruct(spawnCauses, itemDrops, causeTracker.getWorld()); SpongeImpl.postEvent(destruct); if (!destruct.isCancelled()) { for (Entity entity : destruct.getEntities()) { if (entityCreator != null) { EntityUtil.toMixin(entity).setCreator(entityCreator.getUniqueId()); } causeTracker.getMixinWorld().forceSpawnEntity(entity); } } } public static ChangeBlockEvent.Post throwMultiEventsAndCreatePost(ImmutableList<Transaction<BlockSnapshot>>[] transactionArrays, List<ChangeBlockEvent> blockEvents, ChangeBlockEvent[] mainEvents, Cause.Builder builder, org.spongepowered.api.world.World world) { if (!blockEvents.isEmpty()) { for (BlockChange blockChange : BlockChange.values()) { final ChangeBlockEvent mainEvent = mainEvents[blockChange.ordinal()]; if (mainEvent != null) { blockChange.suggestNamed(builder, mainEvent); } } final ImmutableList<Transaction<BlockSnapshot>> transactions = transactionArrays[MULTI_CHANGE_INDEX]; final ChangeBlockEvent.Post post = SpongeEventFactory.createChangeBlockEventPost(builder.build(), world, transactions); SpongeImpl.postEvent(post); return post; } return null; } }
package org.eclipse.kura.web.client.ui.Network; import java.util.ArrayList; import java.util.Set; import java.util.logging.Logger; import org.eclipse.kura.web.client.messages.Messages; import org.eclipse.kura.web.client.util.FailureHandler; import org.eclipse.kura.web.client.util.GwtSafeHtmlUtils; import org.eclipse.kura.web.client.util.MessageUtils; import org.eclipse.kura.web.shared.model.GwtGroupedNVPair; import org.eclipse.kura.web.shared.model.GwtNetIfStatus; import org.eclipse.kura.web.shared.model.GwtNetInterfaceConfig; import org.eclipse.kura.web.shared.model.GwtSession; import org.eclipse.kura.web.shared.model.GwtWifiBgscanModule; import org.eclipse.kura.web.shared.model.GwtWifiChannelModel; import org.eclipse.kura.web.shared.model.GwtWifiCiphers; import org.eclipse.kura.web.shared.model.GwtWifiConfig; import org.eclipse.kura.web.shared.model.GwtWifiHotspotEntry; import org.eclipse.kura.web.shared.model.GwtWifiNetInterfaceConfig; import org.eclipse.kura.web.shared.model.GwtWifiRadioMode; import org.eclipse.kura.web.shared.model.GwtWifiWirelessMode; import org.eclipse.kura.web.shared.model.GwtWifiSecurity; import org.eclipse.kura.web.shared.model.GwtXSRFToken; import org.eclipse.kura.web.shared.service.GwtDeviceService; import org.eclipse.kura.web.shared.service.GwtDeviceServiceAsync; import org.eclipse.kura.web.shared.service.GwtNetworkService; import org.eclipse.kura.web.shared.service.GwtNetworkServiceAsync; import org.eclipse.kura.web.shared.service.GwtSecurityTokenService; import org.eclipse.kura.web.shared.service.GwtSecurityTokenServiceAsync; import org.gwtbootstrap3.client.ui.Alert; import org.gwtbootstrap3.client.ui.Button; import org.gwtbootstrap3.client.ui.FormGroup; import org.gwtbootstrap3.client.ui.FormLabel; import org.gwtbootstrap3.client.ui.HelpBlock; import org.gwtbootstrap3.client.ui.Input; import org.gwtbootstrap3.client.ui.ListBox; import org.gwtbootstrap3.client.ui.Modal; import org.gwtbootstrap3.client.ui.PanelBody; import org.gwtbootstrap3.client.ui.PanelHeader; import org.gwtbootstrap3.client.ui.RadioButton; import org.gwtbootstrap3.client.ui.TextBox; import org.gwtbootstrap3.client.ui.constants.ValidationState; import org.gwtbootstrap3.client.ui.gwt.CellTable; import org.gwtbootstrap3.client.ui.gwt.DataGrid; import org.gwtbootstrap3.client.ui.html.Span; import com.google.gwt.cell.client.CheckboxCell; import com.google.gwt.cell.client.FieldUpdater; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Document; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.DomEvent; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.event.dom.client.MouseOutEvent; import com.google.gwt.event.dom.client.MouseOutHandler; import com.google.gwt.event.dom.client.MouseOverEvent; import com.google.gwt.event.dom.client.MouseOverHandler; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.cellview.client.Column; import com.google.gwt.user.cellview.client.TextColumn; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.view.client.ListDataProvider; import com.google.gwt.view.client.SelectionChangeEvent; import com.google.gwt.view.client.SingleSelectionModel; public class TabWirelessUi extends Composite implements NetworkTab { private static final String WIFI_MODE_STATION = GwtWifiWirelessMode.netWifiWirelessModeStation.name(); private static final String WIFI_MODE_STATION_MESSAGE = MessageUtils.get(WIFI_MODE_STATION); private static final String WIFI_SECURITY_WEP_MESSAGE = MessageUtils.get(GwtWifiSecurity.netWifiSecurityWEP.name()); private static final String WIFI_SECURITY_WPA_MESSAGE = MessageUtils.get(GwtWifiSecurity.netWifiSecurityWPA.name()); private static final String WIFI_SECURITY_WPA2_MESSAGE = MessageUtils.get(GwtWifiSecurity.netWifiSecurityWPA2.name()); private static final String WIFI_BGSCAN_NONE_MESSAGE = MessageUtils.get(GwtWifiBgscanModule.netWifiBgscanMode_NONE.name()); private static final String WIFI_CIPHERS_CCMP_TKIP_MESSAGE = MessageUtils.get(GwtWifiCiphers.netWifiCiphers_CCMP_TKIP.name()); private static final String WIFI_RADIO_BGN_MESSAGE = MessageUtils.get(GwtWifiRadioMode.netWifiRadioModeBGN.name()); private static final String WIFI_SECURITY_NONE_MESSAGE = MessageUtils.get(GwtWifiSecurity.netWifiSecurityNONE.name()); private static final String IPV4_STATUS_WAN_MESSAGE = MessageUtils.get(GwtNetIfStatus.netIPv4StatusEnabledWAN.name()); private static final String WIFI_MODE_ACCESS_POINT_MESSAGE = MessageUtils.get(GwtWifiWirelessMode.netWifiWirelessModeAccessPoint.name()); private static TabWirelessUiUiBinder uiBinder = GWT.create(TabWirelessUiUiBinder.class); private static final Logger logger = Logger.getLogger(TabWirelessUi.class.getSimpleName()); interface TabWirelessUiUiBinder extends UiBinder<Widget, TabWirelessUi> { } private static final Messages MSGS = GWT.create(Messages.class); private final GwtSecurityTokenServiceAsync gwtXSRFService = GWT.create(GwtSecurityTokenService.class); private final GwtNetworkServiceAsync gwtNetworkService = GWT.create(GwtNetworkService.class); private final GwtDeviceServiceAsync gwtDeviceService = GWT.create(GwtDeviceService.class); private static final String REGEX_PASSWORD_ANY = ".*"; private static final String REGEX_PASSWORD_WPA = "^[ -~]{8,63}$"; // Match // all // ASCII // printable // characters private static final String REGEX_PASSWORD_WEP = "^(?:\\w{5}|\\w{13}|[a-fA-F0-9]{10}|[a-fA-F0-9]{26})$"; private static final int MAX_WIFI_CHANNEL = 13; private static final int MAX_SSID_LENGTH = 32; GwtSession session; TabTcpIpUi tcpTab; NetworkTabsUi netTabs; boolean dirty, ssidInit; GwtWifiNetInterfaceConfig selectedNetIfConfig; GwtWifiConfig activeConfig; @UiField CellTable<GwtWifiChannelModel> channelGrid = new CellTable<GwtWifiChannelModel>(); private ListDataProvider<GwtWifiChannelModel> channelDataProvider = new ListDataProvider<GwtWifiChannelModel>(); final SingleSelectionModel<GwtWifiChannelModel> selectionModel = new SingleSelectionModel<GwtWifiChannelModel>(); @UiField Alert noChannels; @UiField FormLabel labelWireless, labelSsid, labelRadio, labelSecurity, labelPassword, labelVerify, labelPairwise, labelGroup, labelBgscan, labelRssi, labelShortI, labelLongI, labelPing, labelIgnore; @UiField RadioButton radio1, radio2, radio3, radio4; @UiField ListBox wireless, radio, security, pairwise, group, bgscan; @UiField TextBox ssid, shortI, longI; @UiField Input password, verify; @UiField TextBox rssi; @UiField PanelHeader helpTitle; @UiField PanelBody helpText; @UiField Button buttonSsid, buttonPassword; @UiField FormGroup groupVerify, groupRssi, groupPassword, groupWireless, groupShortI, groupLongI; @UiField HelpBlock helpWireless, helpPassword, helpVerify; @UiField Modal ssidModal; @UiField PanelHeader ssidTitle; @UiField DataGrid<GwtWifiHotspotEntry> ssidGrid = new DataGrid<GwtWifiHotspotEntry>(); private ListDataProvider<GwtWifiHotspotEntry> ssidDataProvider = new ListDataProvider<GwtWifiHotspotEntry>(); final SingleSelectionModel<GwtWifiHotspotEntry> ssidSelectionModel = new SingleSelectionModel<GwtWifiHotspotEntry>(); @UiField Alert noSsid, scanFail; String passwordRegex, passwordError, tcpStatus; public TabWirelessUi(GwtSession currentSession, TabTcpIpUi tcp, NetworkTabsUi tabs) { ssidInit = false; initWidget(uiBinder.createAndBindUi(this)); session = currentSession; tcpTab = tcp; netTabs = tabs; initForm(); setPasswordValidation(); tcpTab.status.addChangeHandler(new ChangeHandler(){ @Override public void onChange(ChangeEvent event) { if(selectedNetIfConfig!=null){ //set the default values for wireless mode if tcp/ip status was changed String tcpIpStatus=tcpTab.getStatus(); if(!tcpIpStatus.equals(tcpStatus)){ if(GwtNetIfStatus.netIPv4StatusEnabledLAN.name().equals(tcpIpStatus)){ activeConfig= selectedNetIfConfig.getAccessPointWifiConfig(); }else{ activeConfig= selectedNetIfConfig.getStationWifiConfig(); } tcpStatus=tcpIpStatus; netTabs.adjustInterfaceTabs(); } } update(); }}); } @UiHandler(value = { "wireless", "ssid", "radio", "security", "password", "verify", "pairwise", "group", "bgscan", "longI", "shortI", "radio1", "radio2", "radio3", "radio4", "rssi" }) public void onFormBlur(BlurEvent e) { setDirty(true); } /* @UiHandler(value={"rssi"}) public void onValueChange(ValueChangeEvent<Double> event){ setDirty(true); }*/ public GwtWifiWirelessMode getWirelessMode() { if (wireless != null) { for (GwtWifiWirelessMode mode : GwtWifiWirelessMode.values()) { if (wireless.getSelectedItemText().equals(MessageUtils.get(mode.name()))) { return mode; } } } else { if (activeConfig != null) { return GwtWifiWirelessMode.valueOf(activeConfig.getWirelessMode()); } } return null; } @Override public void setDirty(boolean flag) { dirty = flag; } @Override public boolean isDirty() { return dirty; } public boolean isValid(){ if( groupWireless.getValidationState().equals(ValidationState.ERROR) || groupPassword.getValidationState().equals(ValidationState.ERROR) || groupVerify.getValidationState().equals(ValidationState.ERROR) || groupRssi.getValidationState().equals(ValidationState.ERROR) || groupShortI.getValidationState().equals(ValidationState.ERROR) || groupLongI.getValidationState().equals(ValidationState.ERROR)){ return false; }else{ return true; } } @Override public void setNetInterface(GwtNetInterfaceConfig config) { setDirty(true); if(tcpStatus==null || selectedNetIfConfig!=config){ tcpStatus=tcpTab.getStatus(); } if (config instanceof GwtWifiNetInterfaceConfig) { selectedNetIfConfig = (GwtWifiNetInterfaceConfig) config; activeConfig = selectedNetIfConfig.getActiveWifiConfig(); } } @Override public void refresh() { if (isDirty()) { setDirty(false); if (selectedNetIfConfig == null) { reset(); } else { update(); } } } public void getUpdatedNetInterface(GwtNetInterfaceConfig updatedNetIf) { GwtWifiNetInterfaceConfig updatedWifiNetIf = (GwtWifiNetInterfaceConfig) updatedNetIf; if(session!=null){ GwtWifiConfig updatedWifiConfig = getGwtWifiConfig(); updatedWifiNetIf.setWirelessMode(updatedWifiConfig.getWirelessMode()); //update the wifi config updatedWifiNetIf.setWifiConfig(updatedWifiConfig); }else{ if(selectedNetIfConfig!=null){ updatedWifiNetIf.setAccessPointWifiConfig(selectedNetIfConfig.getAccessPointWifiConfigProps()); updatedWifiNetIf.setStationWifiConfig(selectedNetIfConfig.getStationWifiConfigProps()); //select the correct mode for(GwtWifiWirelessMode mode: GwtWifiWirelessMode.values()){ if(mode.name().equals(selectedNetIfConfig.getWirelessMode())){ updatedWifiNetIf.setWirelessMode(mode.name()); } } } } } private void update() { setValues(true); refreshForm(); } private void setValues(boolean b) { if (activeConfig == null) { return; } for (int i = 0; i < wireless.getItemCount(); i++) { if (wireless.getItemText(i).equals(MessageUtils.get(activeConfig.getWirelessMode()))) { wireless.setSelectedIndex(i); } } ssid.setValue(activeConfig.getWirelessSsid()); String activeRadioMode= activeConfig.getRadioMode(); if (activeRadioMode != null) { for (int i = 0; i < radio.getItemCount(); i++) { if (radio.getItemText(i).equals(MessageUtils.get(activeRadioMode))) { radio.setSelectedIndex(i); break; } } } ArrayList<Integer> alChannels = activeConfig.getChannels(); int channelListSize= channelDataProvider.getList().size(); int maxIndex= Math.min(channelListSize, MAX_WIFI_CHANNEL); if (alChannels != null && alChannels.size() > 0) { // deselect all channels for (int channel = 1; channel <= maxIndex; channel++) { selectionModel.setSelected(channelDataProvider.getList().get(channel - 1), false); } // select proper channels for (int channel : alChannels) { if (channel <= maxIndex) { selectionModel.setSelected(channelDataProvider.getList().get(channel - 1), true); } } } else { logger.info("No channels specified, selecting all ..."); for (int channel = 1; channel <= maxIndex; channel++) { selectionModel.setSelected(channelDataProvider.getList().get(channel - 1), true); } } String activeSecurity= activeConfig.getSecurity(); if (activeSecurity != null) { for (int i = 0; i < security.getItemCount(); i++) { if (security.getItemText(i).equals(MessageUtils.get(activeSecurity))) { security.setSelectedIndex(i); break; } } } String activePairwiseCiphers= activeConfig.getPairwiseCiphers(); if (activePairwiseCiphers != null) { for (int i = 0; i < pairwise.getItemCount(); i++) { if (pairwise.getItemText(i).equals(MessageUtils.get(activePairwiseCiphers))) { pairwise.setSelectedIndex(i); break; } } } String activeGroupCiphers= activeConfig.getPairwiseCiphers(); if (activeGroupCiphers != null) { for (int i = 0; i < group.getItemCount(); i++) { if (group.getItemText(i).equals(MessageUtils.get(activeGroupCiphers))) { //activeConfig.getGroupCiphers() group.setSelectedIndex(i); break; } } } String activeBgscanModule= activeConfig.getBgscanModule(); if (activeBgscanModule != null) { for (int i = 0; i < bgscan.getItemCount(); i++) { if (bgscan.getItemText(i).equals(MessageUtils.get(activeBgscanModule))) { bgscan.setSelectedIndex(i); break; } } } //rssi.setValue((double) activeConfig.getBgscanRssiThreshold()); rssi.setValue("90"); shortI.setValue(String.valueOf(activeConfig.getBgscanShortInterval())); longI.setValue(String.valueOf(activeConfig.getBgscanLongInterval())); password.setValue(activeConfig.getPassword()); verify.setValue(activeConfig.getPassword()); radio1.setActive(activeConfig.pingAccessPoint()); radio2.setActive(!activeConfig.pingAccessPoint()); radio3.setActive(activeConfig.ignoreSSID()); radio4.setActive(!activeConfig.ignoreSSID()); } private void refreshForm() { logger.info("refreshForm()"); String tcpipStatus = tcpTab.getStatus(); //resetValidations(); // Tcp/IP disabled if (tcpipStatus.equals(GwtNetIfStatus.netIPv4StatusDisabled)) { setForm(false); } else { setForm(true); // Station mode if (WIFI_MODE_STATION_MESSAGE.equals(wireless.getSelectedItemText())) { //TODO: take a look at the logic here and at next if: couldn't it be unified? radio.setEnabled(false); groupVerify.setVisible(false); } else if (WIFI_MODE_ACCESS_POINT_MESSAGE.equals(wireless.getSelectedItemText())) { // access point mode // disable access point when TCP/IP is set to WAN if (tcpipStatus.equals(IPV4_STATUS_WAN_MESSAGE)) { setForm(false); } radio.setEnabled(true); groupVerify.setVisible(true); } // disable Password if security is none if (security.getSelectedItemText().equals(WIFI_SECURITY_NONE_MESSAGE)) { password.setEnabled(false); verify.setEnabled(false); buttonPassword.setEnabled(false); } if (WIFI_MODE_STATION_MESSAGE.equals(wireless.getSelectedItemText())) { ssid.setEnabled(true); if (!security.getSelectedItemText().equals(WIFI_SECURITY_NONE_MESSAGE)) { if ( password.getValue() != null && password.getValue().length() > 0 ) { password.setEnabled(true); buttonPassword.setEnabled(true); } else { password.setEnabled(true); buttonPassword.setEnabled(false); } } bgscan.setEnabled(true); if ( bgscan.getSelectedItemText().equals(MessageUtils.get(GwtWifiBgscanModule.netWifiBgscanMode_SIMPLE.name())) || bgscan.getSelectedItemText().equals(MessageUtils.get(GwtWifiBgscanModule.netWifiBgscanMode_LEARN.name())) ) { shortI.setEnabled(true); longI.setEnabled(true); //rssi.setEnabled(true); } else { shortI.setEnabled(false); longI.setEnabled(false); //rssi.setEnabled(false); } } else { ssid.setEnabled(true); buttonSsid.setEnabled(false); if (!security.getSelectedItemText().equals(WIFI_SECURITY_NONE_MESSAGE)) { password.setEnabled(true); buttonPassword.setEnabled(false); } bgscan.setEnabled(false); rssi.setEnabled(false); shortI.setEnabled(false); longI.setEnabled(false); radio1.setEnabled(false); radio2.setEnabled(false); } if ( security.getSelectedItemText().equals(WIFI_SECURITY_WPA2_MESSAGE) || security.getSelectedItemText().equals(WIFI_SECURITY_WPA_MESSAGE) || security.getSelectedItemText().equals(MessageUtils.get(GwtWifiSecurity.netWifiSecurityWPA_WPA2.name())) ) { if ( WIFI_MODE_STATION_MESSAGE.equals(wireless.getSelectedItemText()) ) { pairwise.setEnabled(true); group.setEnabled(true); } else { pairwise.setEnabled(true); group.setEnabled(false); } } else { pairwise.setEnabled(false); group.setEnabled(false); } } //loadChannelData(); netTabs.adjustInterfaceTabs(); } private void reset() { for (int i = 0; i < wireless.getItemCount(); i++) { if (wireless.getSelectedItemText().equals(WIFI_MODE_STATION_MESSAGE)) { wireless.setSelectedIndex(i); } } ssid.setText(""); for (int i = 0; i < radio.getItemCount(); i++) { if (radio.getItemText(i).equals(WIFI_RADIO_BGN_MESSAGE)) { radio.setSelectedIndex(i); } } for (int i = 0; i < security.getItemCount(); i++) { if (security.getItemText(i).equals(WIFI_SECURITY_WPA2_MESSAGE)) { security.setSelectedIndex(i); } } password.setText(""); verify.setText(""); for (int i = 0; i < pairwise.getItemCount(); i++) { if (pairwise.getItemText(i).equals(WIFI_CIPHERS_CCMP_TKIP_MESSAGE)) { pairwise.setSelectedIndex(i); } } for (int i = 0; i < group.getItemCount(); i++) { if (group.getItemText(i).equals(WIFI_CIPHERS_CCMP_TKIP_MESSAGE)) { group.setSelectedIndex(i); } } for (int i = 0; i < bgscan.getItemCount(); i++) { if (bgscan.getItemText(i).equals(WIFI_BGSCAN_NONE_MESSAGE)) { bgscan.setSelectedIndex(i); } } rssi.setValue("0.0"); shortI.setValue(""); longI.setValue(""); radio2.setActive(true); radio4.setActive(true); update(); } private void initForm() { // Wireless Mode labelWireless.setText(MSGS.netWifiWirelessMode()); wireless.addItem(MessageUtils.get("netWifiWirelessModeStation")); wireless.addItem(MessageUtils.get("netWifiWirelessModeAccessPoint")); wireless.addMouseOverHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent event) { if (wireless.getSelectedItemText().equals(MessageUtils.get("netWifiWirelessModeStation"))) { helpText.clear(); helpText.add(new Span(MSGS.netWifiToolTipWirelessModeStation())); } else { helpText.clear(); helpText.add(new Span(MSGS.netWifiToolTipWirelessModeAccessPoint())); } } }); wireless.addMouseOutHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent event) { resetHelp(); } }); wireless.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { String accessPointName= WIFI_MODE_ACCESS_POINT_MESSAGE; String stationModeName= WIFI_MODE_STATION_MESSAGE; if (tcpTab.getStatus().equals(GwtNetIfStatus.netIPv4StatusEnabledWAN) && wireless.getSelectedItemText().equals(accessPointName)) { helpWireless.setText(MSGS.netWifiWirelessEnabledForWANError()); groupWireless.setValidationState(ValidationState.ERROR); }else{ helpWireless.setText(""); groupWireless.setValidationState(ValidationState.NONE); } if (wireless.getSelectedItemText().equals(stationModeName)) { // Use Values from station config activeConfig = selectedNetIfConfig.getStationWifiConfig(); } else { // use values from access point config activeConfig = selectedNetIfConfig.getAccessPointWifiConfig(); } setPasswordValidation(); refreshForm(); } }); // SSID labelSsid.setText(MSGS.netWifiNetworkName()); ssid.setMaxLength(MAX_SSID_LENGTH); ssid.addMouseOverHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent event) { if (ssid.isEnabled()) { helpText.clear(); helpText.add(new Span(MSGS.netWifiToolTipNetworkName())); } } }); ssid.addMouseOutHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent event) { resetHelp(); } }); buttonSsid.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { if (!ssidInit) { initSsid(); ssidDataProvider.getList().clear(); noSsid.setVisible(true); ssidGrid.setVisible(false); scanFail.setVisible(false); } initModal(); loadSsidData(); } }); // Radio Mode labelRadio.setText(MSGS.netWifiRadioMode()); radio.addMouseOverHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent event) { if (radio.isEnabled()) { helpText.clear(); helpText.add(new Span(MSGS.netWifiToolTipRadioMode())); } } }); radio.addMouseOutHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent event) { resetHelp(); } }); for (GwtWifiRadioMode mode : GwtWifiRadioMode.values()) { if (mode != GwtWifiRadioMode.netWifiRadioModeA) { // We don't support 802.11a yet radio.addItem(MessageUtils.get(mode.name())); } } // Wireless Security labelSecurity.setText(MSGS.netWifiWirelessSecurity()); security.addMouseOverHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent event) { if (security.isEnabled()) { helpText.clear(); helpText.add(new Span(MSGS.netWifiToolTipSecurity())); } } }); security.addMouseOutHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent event) { resetHelp(); } }); for (GwtWifiSecurity mode : GwtWifiSecurity.values()) { security.addItem(MessageUtils.get(mode.name())); } security.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { setPasswordValidation(); refreshForm(); checkPassword(); } }); // Password labelPassword.setText(MSGS.netWifiWirelessPassword()); password.addMouseOverHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent event) { if (password.isEnabled()) { helpText.clear(); helpText.add(new Span(MSGS.netWifiToolTipPassword())); } } }); password.addMouseOutHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent event) { resetHelp(); } }); buttonPassword.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { buttonPassword.setEnabled(false); final GwtWifiConfig gwtWifiConfig = getGwtWifiConfig(); gwtXSRFService.generateSecurityToken(new AsyncCallback<GwtXSRFToken> () { @Override public void onFailure(Throwable ex) { FailureHandler.handle(ex); } @Override public void onSuccess(GwtXSRFToken token) { gwtNetworkService.verifyWifiCredentials(token, selectedNetIfConfig.getName(), gwtWifiConfig, new AsyncCallback<Boolean>() { @Override public void onFailure(Throwable caught) { FailureHandler.handle(caught); buttonPassword.setEnabled(true); } @Override public void onSuccess(Boolean result) { if (!result.booleanValue()) { password.setText(""); } buttonPassword.setEnabled(true); } }); } }); } }); password.addKeyUpHandler(new KeyUpHandler() { @Override public void onKeyUp(KeyUpEvent event) { if (groupVerify.isVisible() && !verify.getText().equals(password.getText())) { groupVerify.setValidationState(ValidationState.ERROR); } else { groupVerify.setValidationState(ValidationState.NONE); } } }); password.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { refreshForm(); checkPassword(); } }); // Verify Password labelVerify.setText(MSGS.netWifiWirelessVerifyPassword()); verify.addMouseOverHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent event) { if (verify.isEnabled()) { helpText.clear(); helpText.add(new Span(MSGS.netWifiToolTipPassword())); } } }); verify.addMouseOutHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent event) { resetHelp(); } }); verify.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { if (password != null && !verify.getText().equals(password.getText())) { helpVerify.setText(MSGS.netWifiWirelessPasswordDoesNotMatch()); groupVerify.setValidationState(ValidationState.ERROR); } else { helpVerify.setText(""); groupVerify.setValidationState(ValidationState.NONE); } } }); // Pairwise ciphers labelPairwise.setText(MSGS.netWifiWirelessPairwiseCiphers()); pairwise.addMouseOverHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent event) { if (pairwise.isEnabled()) { helpText.clear(); helpText.add(new Span(MSGS.netWifiToolTipPairwiseCiphers())); } } }); pairwise.addMouseOutHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent event) { resetHelp(); } }); for (GwtWifiCiphers ciphers : GwtWifiCiphers.values()) { pairwise.addItem(MessageUtils.get(ciphers.name())); } pairwise.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { refreshForm(); } }); // Groupwise Ciphers labelGroup.setText(MSGS.netWifiWirelessGroupCiphers()); group.addMouseOverHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent event) { if (group.isEnabled()) { helpText.clear(); helpText.add(new Span(MSGS.netWifiWirelessGroupCiphers())); } } }); group.addMouseOutHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent event) { resetHelp(); } }); for (GwtWifiCiphers ciphers : GwtWifiCiphers.values()) { group.addItem(MessageUtils.get(ciphers.name())); } group.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { refreshForm(); } }); // Bgscan module labelBgscan.setText(MSGS.netWifiWirelessBgscanModule()); bgscan.addMouseOverHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent event) { if (bgscan.isEnabled()) { helpText.clear(); helpText.add(new Span(MSGS.netWifiToolTipBgScan())); } } }); bgscan.addMouseOutHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent event) { resetHelp(); } }); for (GwtWifiBgscanModule module : GwtWifiBgscanModule.values()) { bgscan.addItem(MessageUtils.get(module.name())); } bgscan.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { refreshForm(); } }); // BgScan RSSI threshold labelRssi.setText(MSGS.netWifiWirelessBgscanSignalStrengthThreshold()); //TODO: DW - RSSI slider /*rssi.addSlideStartHandler(new SlideStartHandler<Double>() { @Override public void onSlideStart(SlideStartEvent<Double> event) { if (rssi.isEnabled()) { helpText.clear(); helpText.add(new Span(MSGS.netWifiToolTipBgScanStrength())); } } }); rssi.addSlideStopHandler(new SlideStopHandler<Double>() { @Override public void onSlideStop(SlideStopEvent<Double> event) { resetHelp(); } });*/ // Bgscan short Interval labelShortI.setText(MSGS.netWifiWirelessBgscanShortInterval()); shortI.addMouseOverHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent event) { if (shortI.isEnabled()) { helpText.clear(); helpText.add(new Span(MSGS.netWifiToolTipBgScanShortInterval())); } } }); shortI.addMouseOutHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent event) { resetHelp(); } }); shortI.addChangeHandler(new ChangeHandler(){ @Override public void onChange(ChangeEvent event){ if( shortI.getText().trim().contains(".") || shortI.getText().trim().contains("-") || !shortI.getText().trim().matches("[0-9]+") ){ groupShortI.setValidationState(ValidationState.ERROR); }else{ groupShortI.setValidationState(ValidationState.NONE); } } }); // Bgscan long interval labelLongI.setText(MSGS.netWifiWirelessBgscanLongInterval()); longI.addMouseOverHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent event) { if (longI.isEnabled()) { helpText.clear(); helpText.add(new Span(MSGS.netWifiToolTipBgScanLongInterval())); } } }); longI.addMouseOutHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent event) { resetHelp(); } }); longI.addChangeHandler(new ChangeHandler(){ @Override public void onChange(ChangeEvent event){ if( longI.getText().trim().contains(".") || longI.getText().trim().contains("-") || !longI.getText().trim().matches("[0-9]+") ){ groupLongI.setValidationState(ValidationState.ERROR); }else{ groupLongI.setValidationState(ValidationState.NONE); } } }); labelPing.setText(MSGS.netWifiWirelessPingAccessPoint()); radio1.setText(MSGS.trueLabel()); radio1.addMouseOverHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent event) { if (radio1.isEnabled()) { helpText.clear(); helpText.add(new Span(MSGS.netWifiToolTipPingAccessPoint())); } } }); radio1.addMouseOutHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent event) { resetHelp(); } }); radio2.setText(MSGS.falseLabel()); radio2.addMouseOverHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent event) { if (radio2.isEnabled()) { helpText.clear(); helpText.add(new Span(MSGS.netWifiToolTipPingAccessPoint())); } } }); radio2.addMouseOutHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent event) { resetHelp(); } }); // Ignore Broadcast SSID labelIgnore.setText(MSGS.netWifiWirelessIgnoreSSID()); radio3.setText(MSGS.trueLabel()); radio3.addMouseOverHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent event) { if (radio3.isEnabled()) { helpText.clear(); helpText.add(new Span(MSGS.netWifiToolTipIgnoreSSID())); } } }); radio3.addMouseOutHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent event) { resetHelp(); } }); radio4.setText(MSGS.falseLabel()); radio4.addMouseOverHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent event) { if (radio4.isEnabled()) { helpText.clear(); helpText.add(new Span(MSGS.netWifiToolTipIgnoreSSID())); } } }); radio4.addMouseOutHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent event) { resetHelp(); } }); // Channel Grid initGrid(); helpTitle.setText("Help Text"); } private void resetHelp() { helpText.clear(); helpText.add(new Span("Mouse over enabled items on the left to see help text.")); } private void initGrid() { // CHECKBOXES Column<GwtWifiChannelModel, Boolean> checkColumn = new Column<GwtWifiChannelModel, Boolean>(new CheckboxCell()) { @Override public Boolean getValue(GwtWifiChannelModel object) { return channelGrid.getSelectionModel().isSelected(object); } }; checkColumn.setFieldUpdater(new FieldUpdater<GwtWifiChannelModel, Boolean>() { @Override public void update(int index, GwtWifiChannelModel object, Boolean value) { channelGrid.getSelectionModel().setSelected(object, value); channelDataProvider.refresh(); } }); checkColumn.setCellStyleNames("status-table-row"); channelGrid.addColumn(checkColumn); // ALL AVAILABLE CHANNELS TextColumn<GwtWifiChannelModel> col1 = new TextColumn<GwtWifiChannelModel>() { @Override public String getValue(GwtWifiChannelModel object) { return object.getName(); } }; col1.setCellStyleNames("status-table-row"); channelGrid.addColumn(col1, "All Available Channels"); // FREQUENCY TextColumn<GwtWifiChannelModel> col2 = new TextColumn<GwtWifiChannelModel>() { @Override public String getValue(GwtWifiChannelModel object) { return String.valueOf(object.getFrequency()); } }; col2.setCellStyleNames("status-table-row"); channelGrid.addColumn(col2, "Frequency (MHz)"); // SPECTRUM BAND TextColumn<GwtWifiChannelModel> col3 = new TextColumn<GwtWifiChannelModel>() { @Override public String getValue(GwtWifiChannelModel object) { return String.valueOf(object.getBand()); } }; col3.setCellStyleNames("status-table-row"); channelGrid.addColumn(col3, "Frequency (MHz)"); channelGrid.setSelectionModel(selectionModel); channelDataProvider.addDataDisplay(channelGrid); loadChannelData(); } private void loadChannelData() { channelDataProvider.getList().clear(); channelDataProvider.setList(GwtWifiChannelModel.getChannels()); gwtXSRFService.generateSecurityToken(new AsyncCallback<GwtXSRFToken> () { @Override public void onFailure(Throwable ex) { FailureHandler.handle(ex); } @Override public void onSuccess(GwtXSRFToken token) { gwtDeviceService.findDeviceConfiguration(token, new AsyncCallback<ArrayList<GwtGroupedNVPair>>() { @Override public void onFailure(Throwable caught) { channelGrid.setVisible(false); FailureHandler.handle(caught); } @Override public void onSuccess(ArrayList<GwtGroupedNVPair> result) { if (result != null) { channelGrid.setVisible(true); for (GwtGroupedNVPair pair : result) { String name = pair.getName(); if (name != null && name.equals("devLastWifiChannel")) { int topChannel = Integer.parseInt(pair.getValue()); // Remove channels 12 and 13 if (topChannel < MAX_WIFI_CHANNEL) { try { channelDataProvider.getList().remove(MAX_WIFI_CHANNEL - 1); channelDataProvider.getList().remove(MAX_WIFI_CHANNEL - 2); } catch (UnsupportedOperationException e) { logger.info(e.getLocalizedMessage()); } catch (IndexOutOfBoundsException e) { logger.info(e.getLocalizedMessage()); } } } } channelDataProvider.flush(); } } }); } }); if (channelDataProvider.getList().size() > 0) { noChannels.setVisible(false); channelGrid.setVisible(true); } else { channelGrid.setVisible(false); noChannels.setVisible(true); } } private void setPasswordValidation() { if (security.getSelectedItemText().equals(WIFI_SECURITY_WPA_MESSAGE)) { passwordRegex = REGEX_PASSWORD_WPA; passwordError = MSGS.netWifiWirelessInvalidWPAPassword(); } else if (security.getSelectedItemText().equals(WIFI_SECURITY_WPA2_MESSAGE)) { passwordRegex = REGEX_PASSWORD_WPA; passwordError = MSGS.netWifiWirelessInvalidWPAPassword(); } else if (security.getSelectedItemText().equals(WIFI_SECURITY_WEP_MESSAGE)) { passwordRegex = REGEX_PASSWORD_WEP; passwordError = MSGS.netWifiWirelessInvalidWEPPassword(); } else { passwordRegex = REGEX_PASSWORD_ANY; } if ( password.getText() != null && !password.getText().matches(passwordRegex) ) { groupPassword.setValidationState(ValidationState.ERROR); } else { groupPassword.setValidationState(ValidationState.NONE); } if ( password.getText() != null && groupVerify.isVisible() && verify.getText() != null && !password.getText().equals(verify.getText()) ) { groupVerify.setValidationState(ValidationState.ERROR); } else { groupVerify.setValidationState(ValidationState.NONE); } } private void initModal() { ssidModal.setTitle("Wireless Networks"); ssidTitle.setText("Available Networks in the Range"); ssidModal.show(); } private void initSsid() { ssidInit = true; TextColumn<GwtWifiHotspotEntry> col1 = new TextColumn<GwtWifiHotspotEntry>() { @Override public String getValue(GwtWifiHotspotEntry object) { return object.getSSID(); } }; col1.setCellStyleNames("status-table-row"); ssidGrid.addColumn(col1, "SSID"); ssidGrid.setColumnWidth(col1, "240px"); TextColumn<GwtWifiHotspotEntry> col2 = new TextColumn<GwtWifiHotspotEntry>() { @Override public String getValue(GwtWifiHotspotEntry object) { return object.getMacAddress(); } }; col2.setCellStyleNames("status-table-row"); ssidGrid.addColumn(col2, "MAC Address"); ssidGrid.setColumnWidth(col2, "140px"); TextColumn<GwtWifiHotspotEntry> col3 = new TextColumn<GwtWifiHotspotEntry>() { @Override public String getValue(GwtWifiHotspotEntry object) { return String.valueOf(object.getSignalStrength()); } }; col3.setCellStyleNames("status-table-row"); ssidGrid.addColumn(col3, "Signal Strength (dBm)"); ssidGrid.setColumnWidth(col3, "70px"); TextColumn<GwtWifiHotspotEntry> col4 = new TextColumn<GwtWifiHotspotEntry>() { @Override public String getValue(GwtWifiHotspotEntry object) { return String.valueOf(object.getChannel()); } }; col4.setCellStyleNames("status-table-row"); ssidGrid.addColumn(col4, "Channel"); ssidGrid.setColumnWidth(col4, "70px"); TextColumn<GwtWifiHotspotEntry> col5 = new TextColumn<GwtWifiHotspotEntry>() { @Override public String getValue(GwtWifiHotspotEntry object) { return String.valueOf(object.getFrequency()); } }; col5.setCellStyleNames("status-table-row"); ssidGrid.addColumn(col5, "Frequency"); ssidGrid.setColumnWidth(col5, "70px"); TextColumn<GwtWifiHotspotEntry> col6 = new TextColumn<GwtWifiHotspotEntry>() { @Override public String getValue(GwtWifiHotspotEntry object) { return object.getSecurity(); } }; col6.setCellStyleNames("status-table-row"); ssidGrid.addColumn(col6, "Security"); ssidGrid.setColumnWidth(col6, "70px"); ssidDataProvider.addDataDisplay(ssidGrid); ssidGrid.setSelectionModel(ssidSelectionModel); ssidSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() { @Override public void onSelectionChange(SelectionChangeEvent event) { GwtWifiHotspotEntry wifiHotspotEntry = ssidSelectionModel.getSelectedObject(); if (wifiHotspotEntry != null) { ssid.setValue(wifiHotspotEntry.getSSID()); String sec = wifiHotspotEntry.getSecurity(); for (int i = 0; i < security.getItemCount(); i++) { if (sec.equals(security.getItemText(i))) { security.setSelectedIndex(i); DomEvent.fireNativeEvent(Document.get().createChangeEvent(), security); break; } } String pairwiseCiphers = wifiHotspotEntry.getPairwiseCiphersEnum().name(); for (int i = 0; i < pairwise.getItemCount(); i++) { if (MessageUtils.get(pairwiseCiphers).equals(pairwise.getItemText(i))) { pairwise.setSelectedIndex(i); break; } } String groupCiphers = wifiHotspotEntry.getGroupCiphersEnum().name(); for (int i = 0; i < group.getItemCount(); i++) { if (MessageUtils.get(groupCiphers).equals(group.getItemText(i))) { group.setSelectedIndex(i); break; } } int channelListSize= channelDataProvider.getList().size(); int maxIndex= Math.min(channelListSize, MAX_WIFI_CHANNEL); // deselect all channels for (int channel = 1; channel <= maxIndex; channel++) { selectionModel.setSelected(channelDataProvider.getList().get(channel - 1), false); } selectionModel.setSelected(channelDataProvider.getList().get(wifiHotspotEntry.getChannel() - 1), true); ssidModal.hide(); } } }); // double customWidth = 900; // ssidModal.setWidth(customWidth+"px"); // // half, minus 30 on left for scroll bar // double customMargin = -1*(customWidth/2); // ssidModal.getElement().getStyle().setMarginLeft(customMargin, Unit.PX); // ssidModal.getElement().getStyle().setMarginRight(customMargin, Unit.PX); //loadSsidData(); } private void loadSsidData() { ssidDataProvider.getList().clear(); noSsid.setVisible(true); ssidGrid.setVisible(false); scanFail.setVisible(false); //EntryClassUi.showWaitModal(); if (selectedNetIfConfig != null) { gwtXSRFService.generateSecurityToken(new AsyncCallback<GwtXSRFToken> () { @Override public void onFailure(Throwable ex) { FailureHandler.handle(ex); //EntryClassUi.hideWaitModal(); } @Override public void onSuccess(GwtXSRFToken token) { gwtNetworkService.findWifiHotspots(token, selectedNetIfConfig.getName(), new AsyncCallback<ArrayList<GwtWifiHotspotEntry>>() { @Override public void onFailure(Throwable caught) { //EntryClassUi.hideWaitModal(); //FailureHandler.handle(caught); noSsid.setVisible(false); ssidGrid.setVisible(false); scanFail.setVisible(true); } @Override public void onSuccess(ArrayList<GwtWifiHotspotEntry> result) { for (GwtWifiHotspotEntry pair : result) { ssidDataProvider.getList().add(pair); } ssidDataProvider.flush(); if (ssidDataProvider.getList().size() > 0) { noSsid.setVisible(false); ssidGrid.setVisible(true); scanFail.setVisible(false); } else { noSsid.setVisible(true); ssidGrid.setVisible(false); scanFail.setVisible(false); } //EntryClassUi.hideWaitModal(); } }); } }); } } private GwtWifiConfig getGwtWifiConfig() { GwtWifiConfig gwtWifiConfig = new GwtWifiConfig(); // mode GwtWifiWirelessMode wifiMode; if (wireless.getSelectedItemText().equals(MessageUtils.get(WIFI_MODE_STATION))) { wifiMode = GwtWifiWirelessMode.netWifiWirelessModeStation; } else { wifiMode = GwtWifiWirelessMode.netWifiWirelessModeAccessPoint; } gwtWifiConfig.setWirelessMode(wifiMode.name()); // ssid gwtWifiConfig.setWirelessSsid(GwtSafeHtmlUtils.htmlUnescape(ssid.getText().trim())); // driver String driver = ""; if (GwtWifiWirelessMode.netWifiWirelessModeAccessPoint.equals(wifiMode)) { driver = selectedNetIfConfig.getAccessPointWifiConfig().getDriver(); } else if (GwtWifiWirelessMode.netWifiWirelessModeAdHoc.equals(wifiMode)) { driver = selectedNetIfConfig.getAdhocWifiConfig().getDriver(); } else if (GwtWifiWirelessMode.netWifiWirelessModeStation.equals(wifiMode)) { driver = selectedNetIfConfig.getStationWifiConfig().getDriver(); } gwtWifiConfig.setDriver(driver); // use previous value // radio mode String radioValue = radio.getSelectedItemText(); for (GwtWifiRadioMode mode : GwtWifiRadioMode.values()) { if (MessageUtils.get(mode.name()).equals(radioValue)) { gwtWifiConfig.setRadioMode(mode.name()); } } // channels Set<GwtWifiChannelModel> lSelectedChannels = selectionModel.getSelectedSet(); ArrayList<Integer> alChannels = new ArrayList<Integer>(); for (GwtWifiChannelModel item : lSelectedChannels) { alChannels.add(new Integer(item.getChannel())); } if (alChannels.isEmpty()) { alChannels.add(1); } gwtWifiConfig.setChannels(alChannels); // security String secValue = security.getSelectedItemText(); for (GwtWifiSecurity sec : GwtWifiSecurity.values()) { if (MessageUtils.get(sec.name()).equals(secValue)) { gwtWifiConfig.setSecurity(sec.name()); } } // Pairwise Ciphers String pairWiseCiphersValue = pairwise.getSelectedItemText(); for (GwtWifiCiphers ciphers : GwtWifiCiphers.values()) { if (MessageUtils.get(ciphers.name()).equals(pairWiseCiphersValue)) { gwtWifiConfig.setPairwiseCiphers(ciphers.name()); } } // Group Ciphers value String groupCiphersValue = group.getSelectedItemText(); for (GwtWifiCiphers ciphers : GwtWifiCiphers.values()) { if (MessageUtils.get(ciphers.name()).equals(groupCiphersValue)) { gwtWifiConfig.setGroupCiphers(ciphers.name()); } } // bgscan String bgscanModuleValue = bgscan.getSelectedItemText(); for (GwtWifiBgscanModule module : GwtWifiBgscanModule.values()) { if (MessageUtils.get(module.name()).equals(bgscanModuleValue)) { gwtWifiConfig.setBgscanModule(module.name()); } } //gwtWifiConfig.setBgscanRssiThreshold(rssi.getValue().intValue()); gwtWifiConfig.setBgscanShortInterval(Integer.parseInt(shortI.getText())); gwtWifiConfig.setBgscanLongInterval(Integer.parseInt(longI.getText())); // password if (groupPassword.getValidationState().equals(ValidationState.NONE)) { gwtWifiConfig.setPassword(password.getText()); } // ping access point gwtWifiConfig.setPingAccessPoint(radio1.getValue()); // ignore SSID gwtWifiConfig.setIgnoreSSID(radio3.getValue()); return gwtWifiConfig; } private void setForm(boolean b) { channelGrid.setVisible(b); wireless.setEnabled(b); ssid.setEnabled(b); buttonSsid.setEnabled(b); radio.setEnabled(b); security.setEnabled(b); password.setEnabled(b); buttonPassword.setEnabled(b); verify.setEnabled(b); pairwise.setEnabled(b); group.setEnabled(b); bgscan.setEnabled(b); //rssi.setEnabled(b); shortI.setEnabled(b); longI.setEnabled(b); radio1.setEnabled(b); radio2.setEnabled(b); radio3.setEnabled(b); radio4.setEnabled(b); groupVerify.setVisible(b); } private void checkPassword() { if (!password.getText().matches(passwordRegex)) { groupPassword.setValidationState(ValidationState.ERROR); helpPassword.setText(passwordError); } else { groupPassword.setValidationState(ValidationState.NONE); helpPassword.setText(""); } } }
package info.tregmine.teleport; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import info.tregmine.Tregmine; //import info.tregmine.api.TregminePlayer; import info.tregmine.database.ConnectionPool; public class Teleport extends JavaPlugin { public final Logger log = Logger.getLogger("Minecraft"); public Tregmine tregmine = null; public Player from = null; @Override public void onEnable(){ Plugin test = this.getServer().getPluginManager().getPlugin("Tregmine"); if(this.tregmine == null) { if(test != null) { this.tregmine = ((Tregmine)test); } else { log.info(this.getDescription().getName() + " " + this.getDescription().getVersion() + " - could not find Tregmine"); this.getServer().getPluginManager().disablePlugin(this); } } } @Override public void onDisable(){ } @Override public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { String commandName = command.getName().toLowerCase(); if(!(sender instanceof Player)) { return false; } else { from = (Player) sender; } info.tregmine.api.TregminePlayer tregminePlayer = this.tregmine.tregminePlayer.get(from.getName()); if(commandName.equals("tpto") && tregminePlayer.isAdmin()) { Location loc = new Location(from.getWorld(), Integer.parseInt(args[0]), Integer.parseInt(args[1]),Integer.parseInt(args[2]) ); loc.getWorld().loadChunk(loc.getWorld().getChunkAt(loc)); if (loc.getWorld().isChunkLoaded(loc.getWorld().getChunkAt(loc))){ from.teleport(loc); } return true; } if(commandName.equals("home") && tregminePlayer.isDonator()) { Home home = new Home(from.getName(), getServer()); if (args.length == 0) { Location loc = home.get(); if (loc == null) { from.sendMessage(ChatColor.RED + "Telogric lift malfunctioned. Teleportation failed."); return true; } loc.getWorld().loadChunk(loc.getWorld().getChunkAt(loc)); if (loc.getWorld().isChunkLoaded(loc.getWorld().getChunkAt(loc))){ from.teleport(loc); from.sendMessage(ChatColor.AQUA + "Hoci poci, little gnome. Magic worked, you're in your home!"); } else { from.sendMessage(ChatColor.RED + "Loading your home chunk failed, try /home again."); } } else if ("save".matches(args[0])) { if (from.getLocation().getWorld().getName().matches("world_the_end")) { from.sendMessage(ChatColor.RED + "You can't set your home in The End"); return true; } home.save(from.getLocation()); from.sendMessage(ChatColor.AQUA + "Home saved!"); } else if ("to".equals(args[0]) && (tregminePlayer.getMetaBoolean("mentor") || tregminePlayer.isAdmin())) { if (args.length < 2) { from.sendMessage(ChatColor.RED + "Usage: /home to <player>."); return true; } String playerName = args[1]; Home playersHome = new Home(playerName, getServer()); Location loc = playersHome.get(); if (loc == null) { from.sendMessage(ChatColor.RED + "Telogric lift malfunctioned. Teleportation failed."); return true; } loc.getWorld().loadChunk(loc.getWorld().getChunkAt(loc)); if (loc.getWorld().isChunkLoaded(loc.getWorld().getChunkAt(loc))){ from.teleport(loc); from.sendMessage(ChatColor.AQUA + "Like a drunken gnome, you fly across the world to " + playerName + "'s home. Try not to hit any birds."); } else { from.sendMessage(ChatColor.RED + "Loading of home chunk failed, try /home again"); } } return true; } if(commandName.equals("makewarp") && tregminePlayer.isAdmin()) { Connection conn = null; PreparedStatement stmt = null; try { conn = ConnectionPool.getConnection(); stmt = conn.prepareStatement("insert into warps (name, x, y, z, yaw, pitch, world) values (?, ?, ?, ?, ?, ?, ?)"); Location loc = tregminePlayer.getLocation(); stmt.setString(1, args[0]); stmt.setDouble(2, loc.getX()); stmt.setDouble(3, loc.getY()); stmt.setDouble(4, loc.getZ()); stmt.setFloat(5, loc.getYaw()); stmt.setFloat(6, loc.getPitch()); stmt.setString(7, loc.getWorld().getName()); stmt.execute(); tregminePlayer.sendMessage("Warp "+ args[0] +" created"); this.log.info("WARPCREATE: " + args[0] + " by " + tregminePlayer.getName()); } catch (SQLException e) { tregminePlayer.sendMessage("Warp creation error"); throw new RuntimeException(e); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) {} } if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } return true; } if(commandName.equals("tp") && tregminePlayer.isTrusted()) { try { List<Player> to = this.getServer().matchPlayer(args[0]); Tp tp = new Tp(from, to.get(0), this); tp.hashCode(); return true; } catch (Exception e) { return false; } } if(commandName.equals("s") && tregminePlayer.isAdmin()) { Player victim = this.getServer().matchPlayer(args[0]).get(0); if (victim != null ){ if (victim.getName().matches("einand")) { from.sendMessage(ChatColor.RED + "Forbidden command."); victim.sendMessage(from.getName() + " tried to summon you."); return true; } info.tregmine.api.TregminePlayer victimPlayer = this.tregmine.tregminePlayer.get(victim.getName()); victim.setNoDamageTicks(200); victim.teleport(from.getLocation()); victim.sendMessage(tregminePlayer.getChatName() + ChatColor.AQUA + " summoned you."); from.sendMessage(ChatColor.AQUA + "You summoned " + victimPlayer.getChatName() + ChatColor.AQUA + " to yourself."); } else { from.sendMessage(ChatColor.RED + "Can't find user."); } return true; } if(commandName.equals("warp")) { Warp warp = new Warp(this, from, args); warp.run(); return true; } if (commandName.matches("spawn")) { if(tregminePlayer.getServer().getPort() == 1337) { tregminePlayer.teleport(tregminePlayer.getWorld().getSpawnLocation()); return true; } long delay = 0; if (tregminePlayer.isAdmin()) { delay = 0; } from.sendMessage(ChatColor.AQUA + "You must now stand still and wait " + delay + " seconds for the stars to align, allowing you to teleport"); final Player tempfrom = from; this.getServer().getScheduler().scheduleSyncDelayedTask(this,new Runnable() { @Override public void run() { tempfrom.teleport(getServer().getWorld("world").getSpawnLocation()); }},20*delay); return true; } return false; } @Override public void onLoad() { } }
package org.iatrix.widgets; import java.util.Hashtable; import java.util.List; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.forms.widgets.FormToolkit; import org.iatrix.data.KonsTextLock; import org.iatrix.dialogs.ChooseKonsRevisionDialog; import org.iatrix.util.Heartbeat; import org.iatrix.util.Heartbeat.IatrixHeartListener; import org.iatrix.util.Helpers; import org.iatrix.views.JournalView; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.elexis.core.data.activator.CoreHub; import ch.elexis.core.data.events.ElexisEventDispatcher; import ch.elexis.core.data.util.Extensions; import ch.elexis.core.text.model.Samdas; import ch.elexis.core.ui.UiDesk; import ch.elexis.core.ui.constants.ExtensionPointConstantsUi; import ch.elexis.core.ui.icons.Images; import ch.elexis.core.ui.text.EnhancedTextField; import ch.elexis.core.ui.util.IKonsExtension; import ch.elexis.core.ui.util.IKonsMakro; import ch.elexis.core.ui.util.SWTHelper; import ch.elexis.data.Anwender; import ch.elexis.data.Konsultation; import ch.elexis.data.Mandant; import ch.elexis.data.Patient; import ch.elexis.data.PersistentObject; import ch.rgw.tools.TimeTool; import ch.rgw.tools.VersionedResource; import ch.rgw.tools.VersionedResource.ResourceItem; public class KonsText implements IJournalArea { private static Konsultation actKons = null; private static int konsTextSaverCount = 0; private static Logger log = LoggerFactory.getLogger(org.iatrix.widgets.KonsText.class); private static EnhancedTextField text; private static Label lVersion = null; private static Label lKonsLock = null; private static KonsTextLock konsTextLock = null; private static String unable_to_save_kons_id = ""; int displayedVersion; private Action purgeAction; private IAction saveAction; private Action chooseVersionAction; private Action versionFwdAction; private Action versionBackAction; private final FormToolkit tk; private Composite parent; private Hashtable<String, IKonsExtension> hXrefs; public KonsText(Composite parentComposite){ parent = parentComposite; tk = UiDesk.getToolkit(); SashForm konsultationSash = new SashForm(parent, SWT.HORIZONTAL); konsultationSash.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true)); Composite konsultationTextComposite = tk.createComposite(konsultationSash); konsultationTextComposite.setLayout(new GridLayout(1, true)); text = new EnhancedTextField(konsultationTextComposite); hXrefs = new Hashtable<>(); @SuppressWarnings("unchecked") List<IKonsExtension> listKonsextensions = Extensions.getClasses( Extensions.getExtensions(ExtensionPointConstantsUi.KONSEXTENSION), "KonsExtension", //$NON-NLS-1$ //$NON-NLS-2$ false); for (IKonsExtension x : listKonsextensions) { String provider = x.connect(text); hXrefs.put(provider, x); } text.setXrefHandlers(hXrefs); @SuppressWarnings("unchecked") List<IKonsMakro> makros = Extensions.getClasses( Extensions.getExtensions(ExtensionPointConstantsUi.KONSEXTENSION), "KonsMakro", false); //$NON-NLS-1$ text.setExternalMakros(makros); text.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true)); makeActions(); text.getControl().addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e){ logEvent("widgetDisposed removeKonsTextLock"); updateEintrag(); removeKonsTextLock(); } }); tk.adapt(text); lVersion = tk.createLabel(konsultationTextComposite, "<aktuell>"); lVersion.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false)); lKonsLock = tk.createLabel(konsultationTextComposite, ""); lKonsLock.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false)); lKonsLock.setForeground(lKonsLock.getDisplay().getSystemColor(SWT.COLOR_RED)); lKonsLock.setVisible(false); registerUpdateHeartbeat(); } public Action getPurgeAction(){ return purgeAction; } public IAction getSaveAction(){ return saveAction; } public Action getChooseVersionAction(){ return chooseVersionAction; } public Action getVersionForwardAction(){ return versionFwdAction; } public Action getVersionBackAction(){ return versionBackAction; } private void showUnableToSaveKons(String plain, String errMsg) { logEvent("showUnableToSaveKons errMsg: " + errMsg + " plain: " + plain); if (plain.length() == 0 ) { log.warn("showUnableToSaveKons Inhalt war leer"); return; } boolean added = false; try { Clipboard clipboard = new Clipboard(UiDesk.getDisplay()); TextTransfer textTransfer = TextTransfer.getInstance(); Transfer[] transfers = new Transfer[] { textTransfer }; Object[] data = new Object[] { plain }; clipboard.setContents(data, transfers); clipboard.dispose(); added = true; } catch (Exception ex) { log.error("Fehlerhaftes clipboard " + plain); } StringBuilder sb = new StringBuilder(); if (plain.length() > 0 && added) { sb.append("Inhalt wurde in die Zwischenablage aufgenommen\n"); } sb.append("Patient: " + actKons.getFall().getPatient().getPersonalia()+ "\n"); sb.append("\nInhalt ist:\n sb.append(plain); sb.append("\n SWTHelper.alert("Konnte Konsultationstext nicht abspeichern", sb.toString()); } public synchronized void updateEintrag(){ if (actKons != null) { if (actKons.getFall() == null) { return; } if (text.isDirty() || textChanged()) { int old_version = actKons.getHeadVersion(); String plain = text.getContentsPlaintext(); logEvent("updateEintrag old_version " + old_version + " " + actKons.getId() + " dirty " + text.isDirty() + " changed " + textChanged()); if (hasKonsTextLock()) { if (!actKons.isEditable(false)) { String notEditable = "Aktuelle Konsultation kannn nicht editiert werden"; showUnableToSaveKons(plain, notEditable); } else { actKons.updateEintrag(text.getContentsAsXML(), false); int new_version = actKons.getHeadVersion(); String samdasText = (new Samdas(actKons.getEintrag().getHead()).getRecordText()); if (new_version <= old_version || !plain.equals(samdasText)) { if (!unable_to_save_kons_id.equals(actKons.getId())) { String errMsg = "Unable to update: old_version " + old_version + " " + plain + " new_version " + new_version + " " + samdasText ; logEvent("updateEintrag " + errMsg + plain); showUnableToSaveKons(plain, errMsg); unable_to_save_kons_id = actKons.getId(); } } else { unable_to_save_kons_id = ""; logEvent(String.format("updateEintrag saved rev. %s changed %s plain: %s", new_version, textChanged(), plain )); // TODO: Warum merkt das KonsListView trotzdem nicht ?? ElexisEventDispatcher.fireSelectionEvent(actKons); } } } else { // should never happen... String errMsg = "Konsultation gesperrt old_version " + old_version + "konsTextLock " + (konsTextLock == null ? "null" : "key " + konsTextLock.getKey() + " lock " + konsTextLock.getLockValue()); showUnableToSaveKons(plain, errMsg); } } } text.setDirty(false); updateKonsVersionLabel(); } /** * Check whether the text in the text field has changed compared to the database entry. * * @return true, if the text changed, false else */ private boolean textChanged(){ if (actKons == null || text == null) { return false; } String dbEintrag = actKons.getEintrag().getHead(); String textEintrag = text.getContentsAsXML(); if (textEintrag != null) { if (!textEintrag.equals(dbEintrag)) { // text differs from db entry logEvent(String.format("%s: saved text != db entry", actKons.getId())); return true; } } return false; } private void updateKonsLockLabel(){ if (konsTextLock == null || hasKonsTextLock()) { lKonsLock.setVisible(false); lKonsLock.setText(""); } else { Anwender user = konsTextLock.getLockValue().getUser(); StringBuilder text = new StringBuilder(); if (user != null && user.exists()) { text.append( "Konsultation wird von Benutzer \"" + user.getLabel() + "\" bearbeitet."); } else { text.append("Konsultation wird von anderem Benutzer bearbeitet."); } text.append(" Rechner \"" + konsTextLock.getLockValue().getHost() + "\"."); log.debug("updateKonsLockLabel: " + text.toString()); lKonsLock.setText(text.toString()); lKonsLock.setVisible(true); } lKonsLock.getParent().layout(); } // helper method to create a KonsTextLock object in a save way // should be called when a new konsultation is set private synchronized void createKonsTextLock(){ // remove old lock removeKonsTextLock(); if (actKons != null && CoreHub.actUser != null) { konsTextLock = new KonsTextLock(actKons, CoreHub.actUser); } else { konsTextLock = null; } if (konsTextLock != null) { konsTextLock.lock(); // boolean success = konsTextLock.lock(); // logEvent( // "createKonsTextLock: konsText locked (" + success + ")" + konsTextLock.getKey()); } } // helper method to release a KonsTextLock // should be called before a new konsultation is set // or the program/view exits private synchronized void removeKonsTextLock(){ if (konsTextLock != null) { konsTextLock.unlock(); // boolean success = konsTextLock.unlock(); // logEvent( // "removeKonsTextLock: konsText unlocked (" + success + ") " + konsTextLock.getKey()); konsTextLock = null; } } /** * Check whether we own the lock * * @return true, if we own the lock, false else */ private synchronized boolean hasKonsTextLock(){ return (konsTextLock != null && konsTextLock.isLocked()); } @Override public synchronized void visible(boolean mode){ } private void makeActions(){ // Konsultationstext purgeAction = new Action("Alte Eintragsversionen entfernen") { @Override public void run(){ actKons.purgeEintrag(); ElexisEventDispatcher.fireSelectionEvent(actKons); } }; versionBackAction = new Action("Vorherige Version") { @Override public void run(){ if (MessageDialog.openConfirm( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Konsultationstext ersetzen", "Wollen Sie wirklich den aktuellen Konsultationstext gegen eine frühere Version desselben Eintrags ersetzen?")) { setKonsText(actKons, displayedVersion - 1, false); } } }; versionFwdAction = new Action("nächste Version") { @Override public void run(){ if (MessageDialog.openConfirm( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Konsultationstext ersetzen", "Wollen Sie wirklich den aktuellen Konsultationstext gegen eine spätere Version desselben Eintrags ersetzen?")) { setKonsText(actKons, displayedVersion + 1, false); } } }; chooseVersionAction = new Action("Version wählen...") { @Override public void run(){ ChooseKonsRevisionDialog dlg = new ChooseKonsRevisionDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), actKons); if (dlg.open() == ChooseKonsRevisionDialog.OK) { int selectedVersion = dlg.getSelectedVersion(); if (MessageDialog.openConfirm( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Konsultationstext ersetzen", "Wollen Sie wirklich den aktuellen Konsultationstext gegen die Version " + selectedVersion + " desselben Eintrags ersetzen?")) { setKonsText(actKons, selectedVersion, false); } } } }; saveAction = new Action("Konstext sichern") { { setImageDescriptor(Images.IMG_DISK.getImageDescriptor()); setToolTipText("Konsultationstext explizit speichern"); } @Override public void run(){ logEvent("saveAction: "); updateEintrag(); JournalView.updateAllKonsAreas(actKons.getFall().getPatient(), actKons, KonsActions.SAVE_KONS); } }; }; private void updateKonsultation(boolean updateText){ if (actKons != null) { if (updateText) { setKonsText(actKons, actKons.getHeadVersion(), true); } logEvent("updateKonsultation: " + actKons.getId()); } else { setKonsText(null, 0, true); logEvent("updateKonsultation: null"); } } /** * Aktuelle Konsultation setzen. * * Wenn eine Konsultation gesetzt wird stellen wir sicher, dass der gesetzte Patient zu dieser * Konsultation gehoert. Falls nicht, wird ein neuer Patient gesetzt. * @param putCaretToEnd * if true, activate text field ant put caret to the end */ @Override public synchronized void setKons(Patient newPatient, Konsultation k, KonsActions op){ Helpers.checkActPatKons(newPatient, k); if (op == KonsActions.SAVE_KONS) { if (text.isDirty() || textChanged()) { logEvent("setKons.SAVE_KONS text.isDirty or changed saving Kons from " + actKons.getDatum() + " is '" + text.getContentsPlaintext() + "' by " + actKons.getAuthor()); updateEintrag(); } else { if (actKons != null && text != null) { logEvent("setKons.SAVE_KONS nothing to save for Kons from " + actKons.getDatum() + " is '" + text.getContentsPlaintext() + "' by"+ actKons.getAuthor()); } } return; } boolean hasTextChanges = false; // make sure to unlock the kons edit field and release the lock if (text != null && actKons != null) { hasTextChanges = textChanged() ; logEvent(String.format("setKons.ACTIVATE_KONS same? %s text.isDirty %s hasTextChanges %s actKons vom: %s", Helpers.twoKonsEqual(actKons, k), text.isDirty(), hasTextChanges, actKons.getDatum())); if (hasTextChanges) { updateEintrag(); } } if (!Helpers.twoKonsEqual(actKons, k)) { removeKonsTextLock(); } if (k == null) { actKons = k; logEvent("setKons null"); } else { logEvent("setKons " + (actKons == null ? "null" : actKons.getId()) + " => " + k.getId()); actKons = k; setKonsText(actKons, actKons.getHeadVersion(), true); boolean konsEditable = Helpers.hasRightToChangeConsultations(actKons, false); if (!konsEditable) { // isEditable(true) would give feedback to user why consultation // cannot be edited, but this often very shortlived as we create/switch // to a newly created kons of today logEvent("setKons actKons is not editable"); updateKonsultation(true); updateKonsLockLabel(); updateKonsVersionLabel(); lVersion.setText(lVersion.getText() + " Nicht editierbar. (Keine Zugriffsrechte oder schon verrechnet)"); return; } else if (actKons.getMandant().getId().contentEquals(CoreHub.actMandant.getId())) { createKonsTextLock(); } } updateKonsultation(true); updateKonsLockLabel(); updateKonsVersionLabel(); saveAction.setEnabled(konsTextLock == null || hasKonsTextLock()); } /** * Set the version label to reflect the current kons' latest version Called by: updateEintrag() */ private void updateKonsVersionLabel(){ text.setEnabled(false); if (actKons != null) { Mandant m = actKons.getMandant(); int version = actKons.getHeadVersion(); VersionedResource vr = actKons.getEintrag(); ResourceItem entry = vr.getVersion(version); StringBuilder sb = new StringBuilder(); if (entry == null) { sb.append(actKons.getLabel() + " (neu)"); } else { String revisionTime = new TimeTool(entry.timestamp).toString(TimeTool.FULL_GER); String revisionDate = new TimeTool(entry.timestamp).toString(TimeTool.DATE_GER); if (!actKons.getDatum().equals(revisionDate)) { sb.append("Kons vom " + actKons.getDatum() + ": "); } sb.append("rev. ").append(version).append(" vom ") .append(revisionTime).append(" (") .append(entry.remark).append(")"); TimeTool konsDate = new TimeTool(actKons.getDatum()); if (version == -1 && konsDate.isSameDay(new TimeTool())) { sb.append(" (NEU)"); } } sb.append(Helpers.hasRightToChangeConsultations(actKons, false) ? "" : " Kein Recht "); // TODO: Allow administrators to change the konsText if (Helpers.userMayEditKons(actKons)) { sb.append(" editierbar"); text.setEnabled(actKons.isEditable(false)); } else { sb.append(" NICHT editierbar"); text.setEnabled(false); } lVersion.setText(sb.toString()); logEvent(String.format("UpdateVersionLabel: %s author <%s> >actUser <%s> editable? %s dirty? %s", sb.toString(), actKons.getAuthor(),CoreHub.actUser.getLabel(), actKons.isEditable(false), text.isDirty())); } else { lVersion.setText(""); } if (text.isEnabled() && text.isDirty()) { text.getControl().setBackground(text.getDisplay().getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW)); } else { text.getControl().setBackground(text.getDisplay().getSystemColor(SWT.COLOR_WHITE)); } } private synchronized void setKonsText(Konsultation aNewKons, int version, boolean putCaretToEnd){ if (aNewKons != null) { String ntext = ""; if ((version >= 0) && (version <= aNewKons.getHeadVersion())) { VersionedResource vr = aNewKons.getEintrag(); ResourceItem entry = vr.getVersion(version); ntext = entry.data; StringBuilder sb = new StringBuilder(); sb.append("rev. ").append(version).append(" vom ") .append(new TimeTool(entry.timestamp).toString(TimeTool.FULL_GER)).append(" (") .append(entry.remark).append(")"); lVersion.setText(sb.toString()); } else { lVersion.setText(""); } text.setText(PersistentObject.checkNull(ntext)); text.setKons(aNewKons); displayedVersion = version; versionBackAction.setEnabled(version != 0); versionFwdAction.setEnabled(version != aNewKons.getHeadVersion()); boolean locked = hasKonsTextLock(); int strlen = text.getContentsPlaintext().length(); int maxLen = strlen < 120 ? strlen : 120; String label = (konsTextLock == null) ? "null " : konsTextLock.getLabel(); if (!locked) logEvent("setKonsText available " + aNewKons.getId() + " " + label + " putCaretToEnd " + putCaretToEnd + " " + lVersion.getText() + " '" + text.getContentsPlaintext().substring(0, maxLen) + "'"); else logEvent("setKonsText (locked) " + aNewKons.getId() + " " + label + " putCaretToEnd " + putCaretToEnd + " " + lVersion.getText() + " '" + text.getContentsPlaintext().substring(0, maxLen) + "'"); if (putCaretToEnd) { // set focus and put caret at end of text text.putCaretToEnd(); } } else { lVersion.setText(""); text.setText(""); text.setKons(null); displayedVersion = -1; updateKonsVersionLabel(); versionBackAction.setEnabled(false); versionFwdAction.setEnabled(false); logEvent("setKonsText null " + lVersion.getText() + " " + text.getContentsPlaintext()); } } private void logEvent(String msg){ StringBuilder sb = new StringBuilder(msg + ": "); if (actKons == null) { sb.append("actKons null"); } else { sb.append(actKons.getId()); sb.append(" kons rev. " + actKons.getHeadVersion()); sb.append(" vom " + actKons.getDatum()); if (actKons.getFall() != null) { sb.append(" " + actKons.getFall().getPatient().getPersonalia()); } } log.debug(sb.toString()); } @Override public synchronized void activation(boolean mode, Patient selectedPat, Konsultation selectedKons){ logEvent("activation: " + mode); if (mode == false) { // save entry on deactivation if text was edited if (actKons != null && (text.isDirty())) { actKons.updateEintrag(text.getContentsAsXML(), false); text.setDirty(false); } } else { // load newest version on activation, if there are no local changes if (actKons != null && !text.isDirty()) { setKonsText(actKons, actKons.getHeadVersion(), true); } } } public synchronized void registerUpdateHeartbeat(){ Heartbeat heat = Heartbeat.getInstance(); heat.addListener(new IatrixHeartListener() { @Override public void heartbeat(){ int konsTextSaverPeriod = Heartbeat.getKonsTextSaverPeriod(); logEvent("Period: " + konsTextSaverPeriod + " dirty? " + text.isDirty()); if (!(konsTextSaverPeriod > 0)) { // auto-save disabled return; } // inv: konsTextSaverPeriod > 0 // increment konsTextSaverCount, but stay inside period konsTextSaverCount++; konsTextSaverCount %= konsTextSaverPeriod; logEvent("konsTextSaverCount = " + konsTextSaverCount); if (konsTextSaverCount == 0) { logEvent("Auto Save Kons Text"); updateEintrag(); } } }); } public String getPlainText(){ if (text == null ) { return ""; } return text.getContentsPlaintext(); } }
package org.spongepowered.common.event.tracking; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import co.aikar.timings.Timing; import com.flowpowered.math.vector.Vector3i; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import net.minecraft.block.Block; import net.minecraft.block.BlockEventData; import net.minecraft.block.BlockRedstoneLight; import net.minecraft.block.BlockRedstoneRepeater; import net.minecraft.block.BlockRedstoneTorch; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.item.EntityFallingBlock; import net.minecraft.entity.item.EntityItem; import net.minecraft.init.Blocks; import net.minecraft.util.ITickable; import net.minecraft.util.math.BlockPos; import net.minecraft.world.WorldProvider; import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.Chunk; import org.apache.logging.log4j.Level; import org.spongepowered.api.Sponge; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.block.tileentity.TileEntity; import org.spongepowered.api.data.Transaction; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.living.player.User; import org.spongepowered.api.event.CauseStackManager; import org.spongepowered.api.event.CauseStackManager.StackFrame; import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.api.event.block.ChangeBlockEvent; import org.spongepowered.api.event.block.TickBlockEvent; import org.spongepowered.api.event.cause.EventContextKeys; import org.spongepowered.api.event.cause.entity.spawn.SpawnTypes; import org.spongepowered.api.event.item.inventory.DropItemEvent; import org.spongepowered.api.item.inventory.ItemStackSnapshot; import org.spongepowered.api.world.BlockChangeFlag; import org.spongepowered.api.world.BlockChangeFlags; import org.spongepowered.api.world.LocatableBlock; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.World; import org.spongepowered.asm.util.PrettyPrinter; import org.spongepowered.common.SpongeImpl; import org.spongepowered.common.SpongeImplHooks; import org.spongepowered.common.block.SpongeBlockSnapshot; import org.spongepowered.common.entity.EntityUtil; import org.spongepowered.common.event.ShouldFire; import org.spongepowered.common.event.SpongeCommonEventFactory; import org.spongepowered.common.event.tracking.context.CapturedMultiMapSupplier; import org.spongepowered.common.event.tracking.context.ItemDropData; import org.spongepowered.common.event.tracking.phase.block.BlockPhase; import org.spongepowered.common.event.tracking.phase.general.GeneralPhase; import org.spongepowered.common.event.tracking.phase.tick.BlockTickContext; import org.spongepowered.common.event.tracking.phase.tick.DimensionContext; import org.spongepowered.common.event.tracking.phase.tick.EntityTickContext; import org.spongepowered.common.event.tracking.phase.tick.TickPhase; import org.spongepowered.common.event.tracking.phase.tick.TileEntityTickContext; import org.spongepowered.common.interfaces.IMixinChunk; import org.spongepowered.common.interfaces.block.IMixinBlock; import org.spongepowered.common.interfaces.block.IMixinBlockEventData; import org.spongepowered.common.interfaces.block.tile.IMixinTileEntity; import org.spongepowered.common.interfaces.entity.IMixinEntity; import org.spongepowered.common.interfaces.world.IMixinLocation; import org.spongepowered.common.interfaces.world.IMixinWorldServer; import org.spongepowered.common.item.inventory.util.ItemStackUtil; import org.spongepowered.common.mixin.plugin.blockcapturing.IModData_BlockCapturing; import org.spongepowered.common.util.SpongeHooks; import org.spongepowered.common.world.BlockChange; import org.spongepowered.common.world.SpongeBlockChangeFlag; import org.spongepowered.common.world.WorldUtil; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.Random; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import javax.annotation.Nullable; /** * A simple utility for aiding in tracking, either with resolving notifiers * and owners, or proxying out the logic for ticking a block, entity, etc. */ @SuppressWarnings("unchecked") public final class TrackingUtil { public static final int BREAK_BLOCK_INDEX = 0; public static final int PLACE_BLOCK_INDEX = 1; public static final int DECAY_BLOCK_INDEX = 2; public static final int CHANGE_BLOCK_INDEX = 3; public static final int MULTI_CHANGE_INDEX = 4; public static final Function<ImmutableList.Builder<Transaction<BlockSnapshot>>[], Consumer<Transaction<BlockSnapshot>>> TRANSACTION_PROCESSOR = builders -> transaction -> { final BlockChange blockChange = ((SpongeBlockSnapshot) transaction.getOriginal()).blockChange; builders[blockChange.ordinal()].add(transaction); builders[MULTI_CHANGE_INDEX].add(transaction); } ; public static final int EVENT_COUNT = 5; public static final Function<BlockSnapshot, Transaction<BlockSnapshot>> TRANSACTION_CREATION = (blockSnapshot) -> { final Location<World> originalLocation = blockSnapshot.getLocation().get(); final WorldServer worldServer = (WorldServer) originalLocation.getExtent(); final BlockPos blockPos = ((IMixinLocation) (Object) originalLocation).getBlockPos(); final IBlockState newState = worldServer.getBlockState(blockPos); final IBlockState newActualState = newState.getActualState(worldServer, blockPos); final BlockSnapshot newSnapshot = ((IMixinWorldServer) worldServer).createSpongeBlockSnapshot(newState, newActualState, blockPos, BlockChangeFlags.NONE); return new Transaction<>(blockSnapshot, newSnapshot); }; public static void tickEntity(net.minecraft.entity.Entity entityIn) { checkArgument(entityIn instanceof Entity, "Entity %s is not an instance of SpongeAPI's Entity!", entityIn); checkNotNull(entityIn, "Cannot capture on a null ticking entity!"); final IMixinEntity mixinEntity = EntityUtil.toMixin(entityIn); if (!mixinEntity.shouldTick()) { return; } final EntityTickContext tickContext = TickPhase.Tick.ENTITY.createPhaseContext() .source(entityIn); try (final StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame(); final EntityTickContext context = tickContext; final Timing entityTiming = mixinEntity.getTimingsHandler() ) { mixinEntity.getNotifierUser() .ifPresent(notifier -> { frame.addContext(EventContextKeys.NOTIFIER, notifier); context.notifier(notifier); }); mixinEntity.getCreatorUser() .ifPresent(owner -> { if (mixinEntity instanceof EntityFallingBlock) { frame.pushCause(owner); } frame.addContext(EventContextKeys.OWNER, owner); context.owner(owner); }); context.buildAndSwitch(); entityTiming.startTiming(); entityIn.onUpdate(); } catch (Exception | NoClassDefFoundError e) { PhaseTracker.getInstance().printExceptionFromPhase(e, tickContext); } } public static void tickRidingEntity(net.minecraft.entity.Entity entity) { checkArgument(entity instanceof Entity, "Entity %s is not an instance of SpongeAPI's Entity!", entity); checkNotNull(entity, "Cannot capture on a null ticking entity!"); final IMixinEntity mixinEntity = EntityUtil.toMixin(entity); if (!mixinEntity.shouldTick()) { return; } final Optional<User> notifierUser = mixinEntity.getNotifierUser(); final Optional<User> creatorUser = mixinEntity.getCreatorUser(); final EntityTickContext tickContext = TickPhase.Tick.ENTITY.createPhaseContext() .source(entity); try (final StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame(); final EntityTickContext context = tickContext; final Timing entityTiming = mixinEntity.getTimingsHandler() ) { entityTiming.startTiming(); frame.pushCause(entity); mixinEntity.getNotifierUser() .ifPresent(notifier -> { frame.addContext(EventContextKeys.NOTIFIER, notifier); context.notifier(notifier); }); mixinEntity.getCreatorUser() .ifPresent(creator -> { frame.addContext(EventContextKeys.OWNER, creator); context.owner(creator); }); context.buildAndSwitch(); entity.updateRidden(); } catch (Exception | NoClassDefFoundError e) { PhaseTracker.getInstance().printExceptionFromPhase(e, tickContext); } } @SuppressWarnings({"unused", "try"}) public static void tickTileEntity(IMixinWorldServer mixinWorldServer, ITickable tile) { checkArgument(tile instanceof TileEntity, "ITickable %s is not a TileEntity!", tile); checkNotNull(tile, "Cannot capture on a null ticking tile entity!"); final net.minecraft.tileentity.TileEntity tileEntity = (net.minecraft.tileentity.TileEntity) tile; final IMixinTileEntity mixinTileEntity = (IMixinTileEntity) tile; final BlockPos pos = tileEntity.getPos(); final IMixinChunk chunk = ((IMixinTileEntity) tile).getActiveChunk(); if (!mixinTileEntity.shouldTick()) { return; } final TileEntityTickContext context = TickPhase.Tick.TILE_ENTITY.createPhaseContext().source(tile); try (final StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame(); final PhaseContext<?> phaseContext = context) { frame.pushCause(tile); // Add notifier and owner so we don't have to perform lookups during the phases and other processing chunk.getBlockNotifier(pos) .ifPresent(notifier -> { frame.addContext(EventContextKeys.NOTIFIER, notifier); phaseContext.notifier(notifier); }); // Allow the tile entity to validate the owner of itself. As long as the tile entity // chunk is already loaded and activated, and the tile entity has already loaded // the owner of itself. final Optional<User> blockOwner = mixinTileEntity.getSpongeOwner(); blockOwner.ifPresent(owner -> { frame.addContext(EventContextKeys.OWNER, blockOwner.get()); phaseContext.owner(blockOwner.get()); }); // Add the block snapshot of the tile entity for caches to avoid creating multiple snapshots during processing // This is a lazy evaluating snapshot to avoid the overhead of snapshot creation // Finally, switch the context now that we have the owner and notifier phaseContext.buildAndSwitch(); try (Timing timing = mixinTileEntity.getTimingsHandler().startTiming()) { tile.update(); } } catch (Exception e) { PhaseTracker.getInstance().printExceptionFromPhase(e, context); } } @SuppressWarnings("rawtypes") public static void updateTickBlock(IMixinWorldServer mixinWorld, Block block, BlockPos pos, IBlockState state, Random random) { final WorldServer world = WorldUtil.asNative(mixinWorld); final World apiWorld = WorldUtil.fromNative(world); try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { frame.pushCause(world); if (ShouldFire.TICK_BLOCK_EVENT) { BlockSnapshot snapshot = mixinWorld.createSpongeBlockSnapshot(state, state, pos, BlockChangeFlags.NONE); final TickBlockEvent event = SpongeEventFactory.createTickBlockEventScheduled(frame.getCurrentCause(), snapshot); SpongeImpl.postEvent(event); if(event.isCancelled()) { return; } } final LocatableBlock locatable = LocatableBlock.builder() .location(new Location<>(apiWorld, pos.getX(), pos.getY(), pos.getZ())) .state((BlockState) state) .build(); frame.pushCause(locatable); IPhaseState<BlockTickContext> phase = ((IMixinBlock) block).requiresBlockCapture() ? TickPhase.Tick.BLOCK : TickPhase.Tick.NO_CAPTURE_BLOCK; final BlockTickContext phaseContext = phase.createPhaseContext() .source(locatable); checkAndAssignBlockTickConfig(block, world, phaseContext); final PhaseTracker phaseTracker = PhaseTracker.getInstance(); // We have to associate any notifiers in case of scheduled block updates from other sources final PhaseData current = phaseTracker.getCurrentPhaseData(); final IPhaseState<?> currentState = current.state; ((IPhaseState) currentState).appendNotifierPreBlockTick(mixinWorld, pos, current.context, phaseContext); // Now actually switch to the new phase try (PhaseContext<?> context = phaseContext) { context.buildAndSwitch(); block.updateTick(world, pos, state, random); } catch (Exception | NoClassDefFoundError e) { phaseTracker.printExceptionFromPhase(e, phaseContext); } } } @SuppressWarnings("rawtypes") public static void randomTickBlock(PhaseTracker phaseTracker, IMixinWorldServer mixinWorld, Block block, BlockPos pos, IBlockState state, Random random) { final WorldServer world = WorldUtil.asNative(mixinWorld); final World apiWorld = WorldUtil.fromNative(world); try (final StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { frame.pushCause(world); if (ShouldFire.TICK_BLOCK_EVENT) { final BlockSnapshot currentTickBlock = mixinWorld.createSpongeBlockSnapshot(state, state, pos, BlockChangeFlags.NONE); final TickBlockEvent event = SpongeEventFactory.createTickBlockEventRandom(frame.getCurrentCause(), currentTickBlock); SpongeImpl.postEvent(event); if(event.isCancelled()) { return; } } final LocatableBlock locatable = LocatableBlock.builder() .location(new Location<>(apiWorld, pos.getX(), pos.getY(), pos.getZ())) .state((BlockState) state) .build(); frame.pushCause(locatable); IPhaseState<BlockTickContext> phase = ((IMixinBlock) block).requiresBlockCapture() ? TickPhase.Tick.RANDOM_BLOCK : TickPhase.Tick.NO_CAPTURE_BLOCK; final BlockTickContext phaseContext = phase.createPhaseContext() .source(locatable); checkAndAssignBlockTickConfig(block, world, phaseContext); // We have to associate any notifiers in case of scheduled block updates from other sources final PhaseData current = phaseTracker.getCurrentPhaseData(); final IPhaseState<?> currentState = current.state; ((IPhaseState) currentState).appendNotifierPreBlockTick(mixinWorld, pos, current.context, phaseContext); // Now actually switch to the new phase try (PhaseContext<?> context = phaseContext) { context.buildAndSwitch(); block.randomTick(world, pos, state, random); } catch (Exception | NoClassDefFoundError e) { phaseTracker.printExceptionFromPhase(e, phaseContext); } } } private static void checkAndAssignBlockTickConfig(Block block, WorldServer minecraftWorld, PhaseContext<?> phaseContext) { if (block instanceof IModData_BlockCapturing) { IModData_BlockCapturing capturingBlock = (IModData_BlockCapturing) block; if (capturingBlock.requiresBlockCapturingRefresh()) { capturingBlock.initializeBlockCapturingState(minecraftWorld); capturingBlock.requiresBlockCapturingRefresh(false); } } } public static void tickWorldProvider(IMixinWorldServer worldServer) { final WorldProvider worldProvider = ((WorldServer) worldServer).provider; try (DimensionContext context = TickPhase.Tick.DIMENSION.createPhaseContext().source(worldProvider)) { context.buildAndSwitch(); worldProvider.onWorldUpdateEntities(); } } public static boolean fireMinecraftBlockEvent(WorldServer worldIn, BlockEventData event) { IBlockState currentState = worldIn.getBlockState(event.getPosition()); final IMixinBlockEventData blockEvent = (IMixinBlockEventData) event; IPhaseState<?> phase = blockEvent.getCaptureBlocks() ? TickPhase.Tick.BLOCK_EVENT : TickPhase.Tick.NO_CAPTURE_BLOCK; final PhaseContext<?> phaseContext = phase.createPhaseContext(); Object source = blockEvent.getTickBlock() != null ? blockEvent.getTickBlock() : blockEvent.getTickTileEntity(); if (source != null) { phaseContext.source(source); } else { // No source present which means we are ignoring the phase state return currentState.onBlockEventReceived(worldIn, event.getPosition(), event.getEventID(), event.getEventParameter()); } if (blockEvent.getSourceUser() != null) { phaseContext.notifier(blockEvent.getSourceUser()); } try (PhaseContext<?> o = phaseContext) { o.buildAndSwitch(); return currentState.onBlockEventReceived(worldIn, event.getPosition(), event.getEventID(), event.getEventParameter()); } } @SuppressWarnings("rawtypes") static boolean trackBlockChange(PhaseTracker phaseTracker, IMixinWorldServer mixinWorld, Chunk chunk, IBlockState currentState, IBlockState newState, BlockPos pos, BlockChangeFlag flags, PhaseContext<?> phaseContext, IPhaseState<?> phaseState) { final SpongeBlockSnapshot originalBlockSnapshot; final WorldServer world = WorldUtil.asNative(mixinWorld); if (((IPhaseState) phaseState).shouldCaptureBlockChangeOrSkip(phaseContext, pos)) { //final IBlockState actualState = currentState.getActualState(world, pos); originalBlockSnapshot = mixinWorld.createSpongeBlockSnapshot(currentState, currentState, pos, flags); final List<BlockSnapshot> capturedSnapshots = phaseContext.getCapturedBlocks(); final Block newBlock = newState.getBlock(); associateBlockChangeWithSnapshot(phaseState, newBlock, currentState, originalBlockSnapshot, capturedSnapshots); final IMixinChunk mixinChunk = (IMixinChunk) chunk; final IBlockState originalBlockState = mixinChunk.setBlockState(pos, newState, currentState, originalBlockSnapshot); if (originalBlockState == null) { capturedSnapshots.remove(originalBlockSnapshot); return false; } ((IPhaseState) phaseState).postTrackBlock(originalBlockSnapshot, phaseTracker, phaseContext); } else { originalBlockSnapshot = (SpongeBlockSnapshot) BlockSnapshot.NONE; final IMixinChunk mixinChunk = (IMixinChunk) chunk; final IBlockState originalBlockState = mixinChunk.setBlockState(pos, newState, currentState, originalBlockSnapshot); if (originalBlockState == null) { return false; } } if (newState.getLightOpacity() != currentState.getLightOpacity() || newState.getLightValue() != currentState.getLightValue()) { // world.profiler.startSection("checkLight"); world.checkLight(pos); // world.profiler.endSection(); } return true; } private static void associateBlockChangeWithSnapshot(IPhaseState<?> phaseState, Block newBlock, IBlockState currentState, SpongeBlockSnapshot snapshot, List<BlockSnapshot> capturedSnapshots) { Block originalBlock = currentState.getBlock(); if (phaseState == BlockPhase.State.BLOCK_DECAY) { if (newBlock == Blocks.AIR) { snapshot.blockChange = BlockChange.DECAY; capturedSnapshots.add(snapshot); } } else if (newBlock == Blocks.AIR) { snapshot.blockChange = BlockChange.BREAK; capturedSnapshots.add(snapshot); } else if (newBlock != originalBlock && !forceModify(originalBlock, newBlock)) { snapshot.blockChange = BlockChange.PLACE; capturedSnapshots.add(snapshot); } else { snapshot.blockChange = BlockChange.MODIFY; capturedSnapshots.add(snapshot); } } private static boolean forceModify(Block originalBlock, Block newBlock) { if (originalBlock instanceof BlockRedstoneRepeater && newBlock instanceof BlockRedstoneRepeater) { return true; } else if (originalBlock instanceof BlockRedstoneTorch && newBlock instanceof BlockRedstoneTorch) { return true; } else return originalBlock instanceof BlockRedstoneLight && newBlock instanceof BlockRedstoneLight; } private TrackingUtil() { } @SuppressWarnings("ConstantConditions") @Nullable public static User getNotifierOrOwnerFromBlock(Location<World> location) { final BlockPos blockPos = ((IMixinLocation) (Object) location).getBlockPos(); return getNotifierOrOwnerFromBlock((WorldServer) location.getExtent(), blockPos); } @Nullable public static User getNotifierOrOwnerFromBlock(WorldServer world, BlockPos blockPos) { final IMixinChunk mixinChunk = (IMixinChunk) world.getChunkFromBlockCoords(blockPos); User notifier = mixinChunk.getBlockNotifier(blockPos).orElse(null); if (notifier != null) { return notifier; } return mixinChunk.getBlockOwner(blockPos).orElse(null); } public static Supplier<IllegalStateException> throwWithContext(String s, PhaseContext<?> phaseContext) { return () -> { final PrettyPrinter printer = new PrettyPrinter(60); printer.add("Exception trying to process over a phase!").centre().hr(); printer.addWrapped(40, "%s :", "PhaseContext"); PhaseTracker.CONTEXT_PRINTER.accept(printer, phaseContext); printer.add("Stacktrace:"); final IllegalStateException exception = new IllegalStateException(s + " Please analyze the current phase context. "); printer.add(exception); printer.trace(System.err, SpongeImpl.getLogger(), Level.ERROR); return exception; }; } /** * Processes the given list of {@link BlockSnapshot}s and creates and throws and processes * the {@link ChangeBlockEvent}s as appropriately determined based on the {@link BlockChange} * for each snapshot. If any transactions are invalid or events cancelled, this event * returns {@code false} to signify a transaction was cancelled. This return value * is used for portal creation. * * @param snapshots The snapshots to process * @param state The phase state that is being processed, used to handle marking notifiers * and block owners * @param context The phase context, only used by the phase for handling processes. * @return True if no events or transactions were cancelled */ @SuppressWarnings({"unchecked", "ConstantConditions", "rawtypes"}) public static boolean processBlockCaptures(List<BlockSnapshot> snapshots, IPhaseState<?> state, PhaseContext<?> context) { if (snapshots.isEmpty()) { return false; } ImmutableList<Transaction<BlockSnapshot>>[] transactionArrays = new ImmutableList[EVENT_COUNT]; ImmutableList.Builder<Transaction<BlockSnapshot>>[] transactionBuilders = new ImmutableList.Builder[EVENT_COUNT]; for (int i = 0; i < EVENT_COUNT; i++) { transactionBuilders[i] = new ImmutableList.Builder<>(); } final List<ChangeBlockEvent> blockEvents = new ArrayList<>(); for (BlockSnapshot snapshot : snapshots) { // This processes each snapshot to assign them to the correct event in the next area, with the // correct builder array entry. TRANSACTION_PROCESSOR.apply(transactionBuilders).accept(TRANSACTION_CREATION.apply(snapshot)); } for (int i = 0; i < EVENT_COUNT; i++) { // Build each event array transactionArrays[i] = transactionBuilders[i].build(); } // Clear captured snapshots after processing them context.getCapturedBlocksOrEmptyList().clear(); final ChangeBlockEvent[] mainEvents = new ChangeBlockEvent[BlockChange.values().length]; // This likely needs to delegate to the phase in the event we don't use the source object as the main object causing the block changes // case in point for WorldTick event listeners since the players are captured non-deterministically try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { context.getNotifier().ifPresent(user -> frame.addContext(EventContextKeys.NOTIFIER, user)); context.getOwner().ifPresent(user -> frame.addContext(EventContextKeys.OWNER, user)); try { state.associateAdditionalCauses(state, context, frame); } catch (Exception e) { // TODO - this should be a thing to associate additional objects in the cause, or context, but for now it's just a simple // try catch to avoid bombing on performing block changes. } // Creates the block events accordingly to the transaction arrays iterateChangeBlockEvents(transactionArrays, blockEvents, mainEvents); // Needs to throw events // We create the post event and of course post it in the method, regardless whether any transactions are invalidated or not final ChangeBlockEvent.Post postEvent = throwMultiEventsAndCreatePost(transactionArrays, blockEvents, mainEvents); if (postEvent == null) { // Means that we have had no actual block changes apparently? return false; } final List<Transaction<BlockSnapshot>> invalid = new ArrayList<>(); boolean noCancelledTransactions = true; // Iterate through the block events to mark any transactions as invalid to accumilate after (since the post event contains all // transactions of the preceeding block events) for (ChangeBlockEvent blockEvent : blockEvents) { // Need to only check if the event is cancelled, If it is, restore if (blockEvent.isCancelled()) { noCancelledTransactions = false; // Don't restore the transactions just yet, since we're just marking them as invalid for now for (Transaction<BlockSnapshot> transaction : Lists.reverse(blockEvent.getTransactions())) { transaction.setValid(false); } } } // Finally check the post event if (postEvent.isCancelled()) { // Of course, if post is cancelled, just mark all transactions as invalid. noCancelledTransactions = false; for (Transaction<BlockSnapshot> transaction : postEvent.getTransactions()) { transaction.setValid(false); } } // Now we can gather the invalid transactions that either were marked as invalid from an event listener - OR - cancelled. // Because after, we will restore all the invalid transactions in reverse order. for (Transaction<BlockSnapshot> transaction : postEvent.getTransactions()) { if (!transaction.isValid()) { invalid.add(transaction); // Cancel any block drops performed, avoids any item drops, regardless final Location<World> location = transaction.getOriginal().getLocation().orElse(null); if (location != null) { final BlockPos pos = ((IMixinLocation) (Object) location).getBlockPos(); context.getBlockItemDropSupplier().removeAllIfNotEmpty(pos); context.getPerBlockEntitySpawnSuppplier().removeAllIfNotEmpty(pos); context.getPerBlockEntitySpawnSuppplier().removeAllIfNotEmpty(pos); } } } if (!invalid.isEmpty()) { // We need to set this value and return it to signify that some transactions were cancelled noCancelledTransactions = false; // NOW we restore the invalid transactions (remember invalid transactions are from either plugins marking them as invalid // or the events were cancelled), again in reverse order of which they were received. for (Transaction<BlockSnapshot> transaction : Lists.reverse(invalid)) { transaction.getOriginal().restore(true, BlockChangeFlags.NONE); if (state.tracksBlockSpecificDrops()) { // Cancel any block drops or harvests for the block change. // This prevents unnecessary spawns. final Location<World> location = transaction.getOriginal().getLocation().orElse(null); if (location != null) { final BlockPos pos = ((IMixinLocation) (Object) location).getBlockPos(); context.getBlockDropSupplier().removeAllIfNotEmpty(pos); } } } } return performBlockAdditions(postEvent.getTransactions(), state, context, noCancelledTransactions); } } public static void iterateChangeBlockEvents(ImmutableList<Transaction<BlockSnapshot>>[] transactionArrays, List<ChangeBlockEvent> blockEvents, ChangeBlockEvent[] mainEvents) { for (BlockChange blockChange : BlockChange.values()) { if (blockChange == BlockChange.DECAY) { // Decay takes place after. continue; } if (!transactionArrays[blockChange.ordinal()].isEmpty()) { final ChangeBlockEvent event = blockChange.createEvent(Sponge.getCauseStackManager().getCurrentCause(), transactionArrays[blockChange.ordinal()]); mainEvents[blockChange.ordinal()] = event; if (event != null) { SpongeImpl.postEvent(event); blockEvents.add(event); } } } if (!transactionArrays[BlockChange.DECAY.ordinal()].isEmpty()) { // Needs to be placed into iterateChangeBlockEvents final ChangeBlockEvent event = BlockChange.DECAY.createEvent(Sponge.getCauseStackManager().getCurrentCause(), transactionArrays[BlockChange.DECAY.ordinal()]); mainEvents[BlockChange.DECAY.ordinal()] = event; if (event != null) { SpongeImpl.postEvent(event); blockEvents.add(event); } } } @SuppressWarnings({"rawtypes", "ConstantConditions"}) public static boolean performBlockAdditions(List<Transaction<BlockSnapshot>> transactions, IPhaseState<?> phaseState, PhaseContext<?> phaseContext, boolean noCancelledTransactions) { // We have to use a proxy so that our pending changes are notified such that any accessors from block // classes do not fail on getting the incorrect block state from the IBlockAccess // final SpongeProxyBlockAccess proxyBlockAccess = new SpongeProxyBlockAccess(transactions); final CapturedMultiMapSupplier<BlockPos, ItemDropData> capturedBlockDrops = phaseContext.getBlockDropSupplier(); final CapturedMultiMapSupplier<BlockPos, EntityItem> capturedBlockItemEntityDrops = phaseContext.getBlockItemDropSupplier(); final CapturedMultiMapSupplier<BlockPos, net.minecraft.entity.Entity> capturedBlockEntitySpawns = phaseContext.getPerBlockEntitySpawnSuppplier(); for (Transaction<BlockSnapshot> transaction : transactions) { if (!transaction.isValid()) { // Rememver that this value needs to be set to false to return because of the fact that // a transaction was marked as invalid or cancelled. This is used primarily for // things like portal creation, and if false, removes the portal from the cache noCancelledTransactions = false; continue; // Don't use invalidated block transactions during notifications, these only need to be restored } // Handle custom replacements if (transaction.getCustom().isPresent()) { transaction.getFinal().restore(true, BlockChangeFlags.NONE); } final SpongeBlockSnapshot oldBlockSnapshot = (SpongeBlockSnapshot) transaction.getOriginal(); final SpongeBlockSnapshot newBlockSnapshot = (SpongeBlockSnapshot) transaction.getFinal(); final Location<World> worldLocation = oldBlockSnapshot.getLocation().get(); final IMixinWorldServer mixinWorld = (IMixinWorldServer) worldLocation.getExtent(); // Handle item drops captured final BlockPos pos = ((IMixinLocation) (Object) oldBlockSnapshot.getLocation().get()).getBlockPos(); // This is for pre-merged items capturedBlockDrops.acceptAndRemoveIfPresent(pos, items -> spawnItemDataForBlockDrops(items, oldBlockSnapshot, phaseContext)); // And this is for un-pre-merged items, these will be EntityItems, not ItemDropDatas. capturedBlockItemEntityDrops.acceptAndRemoveIfPresent(pos, items -> spawnItemEntitiesForBlockDrops(items, oldBlockSnapshot, phaseContext)); // This is for entities actually spawned capturedBlockEntitySpawns.acceptAndRemoveIfPresent(pos, items -> spawnEntitiesForBlock(items, phaseContext)); final WorldServer world = WorldUtil.asNative(mixinWorld); SpongeHooks.logBlockAction(world, oldBlockSnapshot.blockChange, transaction); final SpongeBlockChangeFlag changeFlag = oldBlockSnapshot.getChangeFlag(); final IBlockState originalState = (IBlockState) oldBlockSnapshot.getState(); final IBlockState newState = (IBlockState) newBlockSnapshot.getState(); // We call onBlockAdded here for blocks without a TileEntity. // MixinChunk#setBlockState will call onBlockAdded for blocks // with a TileEntity or when capturing is not being done. final PhaseTracker phaseTracker = PhaseTracker.getInstance(); if (!SpongeImplHooks.hasBlockTileEntity(newState.getBlock(), newState) && changeFlag.performBlockPhysics() && originalState.getBlock() != newState.getBlock()) { newState.getBlock().onBlockAdded(world, pos, newState); final PhaseData peek = phaseTracker.getCurrentPhaseData(); if (peek.state == GeneralPhase.Post.UNWINDING) { ((IPhaseState) peek.state).unwind(peek.context); } } //proxyBlockAccess.proceed(); ((IPhaseState) phaseState).handleBlockChangeWithUser(oldBlockSnapshot.blockChange, transaction, phaseContext); if (changeFlag.isNotifyClients()) { // Always try to notify clients of the change. world.notifyBlockUpdate(pos, originalState, newState, changeFlag.getRawFlag()); } if (changeFlag.updateNeighbors()) { // Notify neighbors only if the change flag allowed it. mixinWorld.spongeNotifyNeighborsPostBlockChange(pos, originalState, newState, changeFlag); } else if (changeFlag.notifyObservers()) { world.updateObservingBlocksAt(pos, newState.getBlock()); } final PhaseData peek = phaseTracker.getCurrentPhaseData(); if (peek.state == GeneralPhase.Post.UNWINDING) { ((IPhaseState) peek.state).unwind(peek.context); } } return noCancelledTransactions; } public static void spawnItemEntitiesForBlockDrops(Collection<EntityItem> entityItems, BlockSnapshot newBlockSnapshot, PhaseContext<?> phaseContext) { // Now we can spawn the entity items appropriately final List<Entity> itemDrops = entityItems.stream() .map(EntityUtil::fromNative) .collect(Collectors.toList()); try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { frame.pushCause(newBlockSnapshot); frame.addContext(EventContextKeys.SPAWN_TYPE, SpawnTypes.DROPPED_ITEM); final Optional<User> notifier = phaseContext.getNotifier(); notifier.ifPresent(user -> frame.addContext(EventContextKeys.NOTIFIER, user)); SpongeCommonEventFactory.callDropItemDestruct(itemDrops, phaseContext); } } public static void spawnItemDataForBlockDrops(Collection<ItemDropData> itemStacks, BlockSnapshot oldBlockSnapshot, PhaseContext<?> phaseContext) { final Vector3i position = oldBlockSnapshot.getPosition(); final List<ItemStackSnapshot> itemSnapshots = itemStacks.stream() .map(ItemDropData::getStack) .map(ItemStackUtil::snapshotOf) .collect(Collectors.toList()); final ImmutableList<ItemStackSnapshot> originalSnapshots = ImmutableList.copyOf(itemSnapshots); try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { frame.pushCause(oldBlockSnapshot); final DropItemEvent.Pre dropItemEventPre = SpongeEventFactory.createDropItemEventPre(frame.getCurrentCause(), originalSnapshots, itemSnapshots); SpongeImpl.postEvent(dropItemEventPre); if (dropItemEventPre.isCancelled()) { return; } } Location<World> worldLocation = oldBlockSnapshot.getLocation().get(); final World world = worldLocation.getExtent(); final WorldServer worldServer = (WorldServer) world; // Now we can spawn the entity items appropriately final List<Entity> itemDrops = itemStacks.stream().map(itemStack -> { final net.minecraft.item.ItemStack minecraftStack = itemStack.getStack(); float f = 0.5F; double offsetX = worldServer.rand.nextFloat() * f + (1.0F - f) * 0.5D; double offsetY = worldServer.rand.nextFloat() * f + (1.0F - f) * 0.5D; double offsetZ = worldServer.rand.nextFloat() * f + (1.0F - f) * 0.5D; final double x = position.getX() + offsetX; final double y = position.getY() + offsetY; final double z = position.getZ() + offsetZ; EntityItem entityitem = new EntityItem(worldServer, x, y, z, minecraftStack); entityitem.setDefaultPickupDelay(); return entityitem; }) .map(EntityUtil::fromNative) .collect(Collectors.toList()); try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { frame.pushCause(oldBlockSnapshot); frame.addContext(EventContextKeys.SPAWN_TYPE, SpawnTypes.DROPPED_ITEM); if(phaseContext.getNotifier().isPresent()) { frame.addContext(EventContextKeys.NOTIFIER, phaseContext.getNotifier().get()); } SpongeCommonEventFactory.callDropItemDestruct(itemDrops, phaseContext); } } private static void spawnEntitiesForBlock(Collection<net.minecraft.entity.Entity> entities, PhaseContext<?> phaseContext) { // Now we can spawn the entity items appropriately final List<Entity> entitiesSpawned = entities.stream() .map(EntityUtil::fromNative) .collect(Collectors.toList()); try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { frame.addContext(EventContextKeys.SPAWN_TYPE, SpawnTypes.BLOCK_SPAWNING); SpongeCommonEventFactory.callSpawnEntity(entitiesSpawned, phaseContext); } } @Nullable public static ChangeBlockEvent.Post throwMultiEventsAndCreatePost(ImmutableList<Transaction<BlockSnapshot>>[] transactionArrays, List<ChangeBlockEvent> blockEvents, ChangeBlockEvent[] mainEvents) { if (!blockEvents.isEmpty()) { try (StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { for (BlockChange blockChange : BlockChange.values()) { final ChangeBlockEvent mainEvent = mainEvents[blockChange.ordinal()]; if (mainEvent != null) { frame.pushCause(mainEvent); } } final ImmutableList<Transaction<BlockSnapshot>> transactions = transactionArrays[MULTI_CHANGE_INDEX]; final ChangeBlockEvent.Post post = SpongeEventFactory.createChangeBlockEventPost(Sponge.getCauseStackManager().getCurrentCause(), transactions); SpongeImpl.postEvent(post); return post; } } return null; } }
package com.example.testapp; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import android.util.Log; /** Runs the client code for a socket. */ public class ClientSocket { // Default to localhost private String serverIpAddress = "127.0.0.1"; private int serverPort = 3490; private String message = ""; public void setServerIpAddress(String ip) { serverIpAddress = ip; } public void setServerPort(int port) { serverPort = port; } public String getServerIpAddress() { return serverIpAddress; } public int getServerPort() { return serverPort; } public void sendData(String s) { message = s; if (!serverIpAddress.equals("")) { Thread cThread = new Thread(new ClientThread()); cThread.start(); } } public class ClientThread implements Runnable { public void run() { try { InetAddress serverAddr = InetAddress.getByName(serverIpAddress); Log.d("ClientActivity", "C: Connecting..."); Socket socket = new Socket(serverAddr, serverPort); try { Log.d("ClientActivity", "C: Sending command."); PrintWriter out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())), true); out.print(message); // Need to flush since no newline is forced out.flush(); Log.d("ClientActivity", "C: Sent message: " + message); } catch (Exception e) { Log.e("ClientActivity", "S: Error", e); } // wait to receive confirmation from server before closing BufferedReader in = new BufferedReader(new InputStreamReader( socket.getInputStream())); String receive; while ((receive = in.readLine()) != null) { Log.d("ClientActivity", "echo: " + receive); } // close socket socket.close(); Log.d("ClientActivity", "C: Closed."); } catch (Exception e) { Log.e("ClientActivity", "C: Error", e); } } } }
package org.spongepowered.common.service.user; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.Sets; import com.mojang.authlib.GameProfile; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.server.MinecraftServer; import net.minecraft.server.management.BanEntry; import net.minecraft.server.management.PlayerProfileCache; import net.minecraft.server.management.ServerConfigurationManager; import net.minecraft.server.management.UserListBans; import net.minecraft.server.management.UserListBansEntry; import net.minecraft.server.management.UserListWhitelist; import net.minecraft.server.management.UserListWhitelistEntry; import net.minecraft.world.storage.SaveHandler; import org.spongepowered.api.Sponge; import org.spongepowered.api.entity.living.player.User; import org.spongepowered.common.SpongeImpl; import org.spongepowered.common.entity.player.SpongeUser; import org.spongepowered.common.interfaces.IMixinEntityPlayerMP; import org.spongepowered.common.util.SpongeHooks; import org.spongepowered.common.world.DimensionManager; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Locale; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; class UserDiscoverer { private static final Cache<UUID, User> userCache = CacheBuilder.newBuilder() .expireAfterAccess(1, TimeUnit.DAYS) .build(); static User create(GameProfile profile) { User user = (User) new SpongeUser(profile); userCache.put(profile.getId(), user); return user; } /** * Searches for user data from a variety of places, in order of preference. * A user that has data in sponge may not necessarily have been online * before. A user added to the ban/whitelist that has not been on the server * before should be discover-able. * * @param uniqueId The user's UUID * @return The user data, or null if not found */ static User findByUuid(UUID uniqueId) { User user = userCache.getIfPresent(uniqueId); if (user != null) { return user; } user = getOnlinePlayer(uniqueId); if (user != null) { return user; } user = getFromStoredData(uniqueId); if (user != null) { return user; } user = getFromWhitelist(uniqueId); if (user != null) { return user; } user = getFromBanlist(uniqueId); return user; } static User findByUsername(String username) { PlayerProfileCache cache = MinecraftServer.getServer().getPlayerProfileCache(); HashSet<String> names = Sets.newHashSet(cache.getUsernames()); if (names.contains(username.toLowerCase(Locale.ROOT))) { GameProfile profile = cache.getGameProfileForUsername(username); if (profile != null) { return findByUuid(profile.getId()); } } return null; } @SuppressWarnings("unchecked") static Collection<org.spongepowered.api.profile.GameProfile> getAllProfiles() { Set<org.spongepowered.api.profile.GameProfile> profiles = Sets.newHashSet(); // Add all cached profiles for (User user : userCache.asMap().values()) { profiles.add(user.getProfile()); } // Add all known profiles from the data files SaveHandler saveHandler = (SaveHandler) DimensionManager.getWorldFromDimId(0).getSaveHandler(); String[] uuids = saveHandler.getAvailablePlayerDat(); for (String playerUuid : uuids) { // Some mods store other files in the 'playerdata' folder, so // we need to ensure that the filename is a valid UUID if (playerUuid.split("-").length != 5) { continue; } GameProfile profile = MinecraftServer.getServer().getPlayerProfileCache().getProfileByUUID(UUID.fromString(playerUuid)); if (profile != null) { profiles.add((org.spongepowered.api.profile.GameProfile) profile); } } // Add all whitelisted users UserListWhitelist whiteList = MinecraftServer.getServer().getConfigurationManager().getWhitelistedPlayers(); for (UserListWhitelistEntry entry : (Collection<UserListWhitelistEntry>) whiteList.getValues().values()) { profiles.add((org.spongepowered.api.profile.GameProfile) entry.value); } // Add all banned users UserListBans banList = MinecraftServer.getServer().getConfigurationManager().getBannedPlayers(); for (BanEntry entry : banList.getValues().values()) { if (entry instanceof UserListBansEntry) { profiles.add((org.spongepowered.api.profile.GameProfile) entry.value); } } return profiles; } static boolean delete(UUID uniqueId) { if (getOnlinePlayer(uniqueId) != null) { // Don't delete online player's data return false; } boolean success = deleteStoredPlayerData(uniqueId); success = success && deleteWhitelistEntry(uniqueId); success = success && deleteBanlistEntry(uniqueId); return success; } private static User getOnlinePlayer(UUID uniqueId) { ServerConfigurationManager confMgr = MinecraftServer.getServer().getConfigurationManager(); if (confMgr == null) { // Server not started yet return null; } // Although the player itself could be returned here (as Player extends // User), a plugin is more likely to cache the User object and we don't // want the player entity to be cached. IMixinEntityPlayerMP player = (IMixinEntityPlayerMP) confMgr.getPlayerByUUID(uniqueId); if (player != null) { User user = player.getUserObject(); userCache.put(uniqueId, user); return user; } return null; } private static User getFromStoredData(UUID uniqueId) { // Note: Uses the overworld's player data File dataFile = getPlayerDataFile(uniqueId); if (dataFile == null) { return null; } Optional<org.spongepowered.api.profile.GameProfile> profile = getProfileFromServer(uniqueId); if (profile.isPresent()) { User user = create((GameProfile) profile.get()); try { ((SpongeUser) user).readFromNbt(CompressedStreamTools.readCompressed(new FileInputStream(dataFile))); } catch (IOException e) { SpongeHooks.logWarning("Corrupt user file {}. {}", dataFile, e); } return user; } else { return null; } } private static Optional<org.spongepowered.api.profile.GameProfile> getProfileFromServer(UUID uuid) { CompletableFuture<org.spongepowered.api.profile.GameProfile> gameProfile = Sponge.getServer().getGameProfileManager().get(uuid); try { org.spongepowered.api.profile.GameProfile profile = gameProfile.get(); if (profile != null) { return Optional.of(profile); } else { return Optional.empty(); } } catch (InterruptedException | ExecutionException e) { SpongeImpl.getLogger().warn("Error while getting profile for {}", uuid, e); return Optional.empty(); } } private static User getFromWhitelist(UUID uniqueId) { GameProfile profile = null; UserListWhitelist whiteList = MinecraftServer.getServer().getConfigurationManager().getWhitelistedPlayers(); UserListWhitelistEntry whiteListData = (UserListWhitelistEntry) whiteList.getEntry(new GameProfile(uniqueId, "")); if (whiteListData != null) { profile = (GameProfile) whiteListData.value; } if (profile != null) { return create(profile); } return null; } private static User getFromBanlist(UUID uniqueId) { GameProfile profile = null; UserListBans banList = MinecraftServer.getServer().getConfigurationManager().getBannedPlayers(); BanEntry banData = (BanEntry) banList.getEntry(new GameProfile(uniqueId, "")); if (banData instanceof UserListBansEntry) { profile = (GameProfile) banData.value; } if (profile != null) { return create(profile); } return null; } private static File getPlayerDataFile(UUID uniqueId) { // Note: Uses the overworld's player data SaveHandler saveHandler = (SaveHandler) DimensionManager.getWorldFromDimId(0).getSaveHandler(); String[] uuids = saveHandler.getAvailablePlayerDat(); for (String playerUuid : uuids) { if (uniqueId.toString().equals(playerUuid)) { return new File(saveHandler.playersDirectory, playerUuid + ".dat"); } } return null; } private static boolean deleteStoredPlayerData(UUID uniqueId) { File dataFile = getPlayerDataFile(uniqueId); if (dataFile != null) { try { return dataFile.delete(); } catch (SecurityException e) { SpongeHooks.logWarning("Unable to delete file {} due to a security error. {}", dataFile, e); return false; } } return true; } private static boolean deleteWhitelistEntry(UUID uniqueId) { UserListWhitelist whiteList = MinecraftServer.getServer().getConfigurationManager().getWhitelistedPlayers(); whiteList.removeEntry(new GameProfile(uniqueId, "")); return true; } private static boolean deleteBanlistEntry(UUID uniqueId) { UserListBans banList = MinecraftServer.getServer().getConfigurationManager().getBannedPlayers(); banList.removeEntry(new GameProfile(uniqueId, "")); return true; } }
package org.zeroturnaround.javarebel.maven; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Plugin; import org.apache.maven.model.Resource; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.DirectoryScanner; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.interpolation.ObjectBasedValueSource; import org.codehaus.plexus.util.interpolation.RegexBasedInterpolator; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.sonatype.plexus.build.incremental.BuildContext; import org.zeroturnaround.javarebel.maven.model.RebelClasspath; import org.zeroturnaround.javarebel.maven.model.RebelClasspathResource; import org.zeroturnaround.javarebel.maven.model.RebelResource; import org.zeroturnaround.javarebel.maven.model.RebelWar; import org.zeroturnaround.javarebel.maven.model.RebelWeb; import org.zeroturnaround.javarebel.maven.model.RebelWebResource; /** * Generate rebel.xml * * @goal generate * @phase process-resources * @threadSafe true */ public class GenerateRebelMojo extends AbstractMojo { private static final String[] DEFAULT_INCLUDES = {"**/**"}; private static final Set JAR_PACKAGING = new HashSet(); private static final Set WAR_PACKAGING = new HashSet(); private static final String POM_PACKAGING = "pom"; static { JAR_PACKAGING.addAll(Arrays.asList("jar", "ejb", "ejb3", "nbm", "hk2-jar", "bundle", "eclipse-plugin", "atlassian-plugin")); WAR_PACKAGING.addAll(Arrays.asList("war", "grails-app")); } /** * The maven project. * * @parameter expression="${project}" * @required * @readonly */ private MavenProject project; /** * Packaging of project. * * @parameter expression="${project.packaging}" * @required */ private String packaging; /** * The directory containing generated classes. * * @parameter expression="${project.build.outputDirectory}" * @required */ private File classesDirectory; /** * Root directory for all html/jsp etc files. * * @parameter expression="${basedir}/src/main/webapp" * @required */ private File warSourceDirectory; /** * The directory where the webapp is built. * * @parameter expression="${project.build.directory}/${project.build.finalName}" * @required */ private File webappDirectory; /** * Rebel classpath configuration. * * @parameter */ private RebelClasspath classpath; /** * Rebel war configuration. * * @parameter */ private RebelWar war; /** * Rebel web configuration. * * @parameter */ private RebelWeb web; /** * Root path of maven projects. * * @parameter */ private String rootPath; /** * Relative path to root of current project. * * @parameter */ private String relativePath; /** * Root relative path. * * @parameter */ private String rootRelativePath; /** * Target directory for generated rebel.xml * * @parameter expression="${rebel.xml.dir}" default-value="${project.build.outputDirectory}" * @required */ private File rebelXmlDirectory; /** * If set to true rebel plugin will write generated xml at info level. * * @parameter expression="${rebel.generate.show}" default-value="false" */ private boolean showGenerated; /** * If set to true rebel plugin will add resources directories to rebel.xml classpath. * * @parameter default-value="false" */ private boolean addResourcesDirToRebelXml; /** * If set to true rebel plugin will generate rebel.xml on each build, otherwise the timestamps of rebel.xml and pom.xml are compared. * * @parameter default-value="false" */ private boolean alwaysGenerate; /** * Indicates whether the default web element will be generated or not. This parameter has effect only when {@link #generateDefaultElements} is <code>true</code>. * * @parameter default-value="true" */ private boolean generateDefaultWeb; /** * Indicates whether the default classpath element will be generated or not. This parameter has effect only when {@link #generateDefaultElements} is <code>true</code>. * * @parameter default-value="true" */ private boolean generateDefaultClasspath; /** * If set to false rebel plugin will not generate default elements in rebel.xml. * * @parameter default-value="true" */ private boolean generateDefaultElements; /** * If set to true rebel plugin execution will be skipped. * * @parameter default-value="false" */ private boolean skip; /** @component */ private BuildContext buildContext; /** @parameter default-value="${mojoExecution}" */ private MojoExecution execution; /** @parameter default-value="${session}" */ private MavenSession session; public void execute() throws MojoExecutionException { if (this.rootPath == null) { // relative paths generation is OFF this.rootPath = project.getBasedir().getAbsolutePath(); this.relativePath = "."; } else { if (this.rootRelativePath == null) { // manual config mode if (this.relativePath == null) { // have <relativePath> point up to maven root directory this.relativePath = "."; } } else { // use auto-detection & ignore all <relativePath> variables try { this.relativePath = calculateRelativePath(calculatePathToRoot(findBaseDirOfMainProject(), this.project.getBasedir()), rootRelativePath); getLog().info("auto-detected relative path to main project : " + this.relativePath); } catch (IOException ex) { getLog().debug("Error during relative path calculation", ex); getLog().error("ERROR! Path defined in <rootRelativePath> is not a valid relative path with regard to root module's path. Falling back to absolute paths."); } } } // do not generate rebel.xml file if skip parameter or 'performRelease' system property is set to true try { if (this.skip || Boolean.getBoolean("performRelease")) { getLog().info("Skipped generating rebel.xml."); return; } } catch (SecurityException ignore) { // ignore exception which potentially can be thrown by Boolean.getBoolean for security options } // if generateDefaultElements is set to false, then disable default classpath and web elements no matter what are their initial values. if (!this.generateDefaultElements) { this.generateDefaultClasspath = false; this.generateDefaultWeb = false; } final File rebelXmlFile = new File(rebelXmlDirectory, "rebel.xml").getAbsoluteFile(); final File pomXmlFile = getProject().getFile(); if (!alwaysGenerate && rebelXmlFile.exists() && pomXmlFile.exists() && rebelXmlFile.lastModified() > pomXmlFile.lastModified()) { return; } getLog().info("Processing " + getProject().getGroupId() + ":" + getProject().getArtifactId() + " with packaging " + packaging); RebelXmlBuilder builder = null; if (WAR_PACKAGING.contains(packaging)) { builder = buildWar(); } else if (JAR_PACKAGING.contains(packaging)) { builder = buildJar(); } else if (POM_PACKAGING.equals(packaging)) { getLog().info("Skipped generating rebel.xml for parent."); } else { getLog().warn("Unsupported packaging type: " + packaging); } if (builder != null) { Writer w = null; if (this.showGenerated) { try { w = new StringWriter(); builder.writeXml(w); getLog().info(w.toString()); } catch (IOException e) { getLog().debug("Detected exception during 'showGenerated' : ", e); } } try { rebelXmlDirectory.mkdirs(); w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(rebelXmlFile), "UTF-8")); builder.writeXml(w); } catch (IOException e) { throw new MojoExecutionException("Failed writing rebel.xml", e); } finally { IOUtils.closeQuietly(w); if (this.buildContext != null) { // safeguard for null buildContext. Can it be null, actually? E.g when field is not injected. this.buildContext.refresh(rebelXmlFile); } } } } /** * Build war configuration. * * @return * @throws MojoExecutionException */ private RebelXmlBuilder buildWar() throws MojoExecutionException { RebelXmlBuilder builder = createXmlBuilder(); buildWeb(builder); buildClasspath(builder); if (war != null) { war.setPath(fixFilePath(war.getPath())); builder.setWar(war); } return builder; } /** * Build jar configuration. * * @return * @throws MojoExecutionException */ private RebelXmlBuilder buildJar() throws MojoExecutionException { RebelXmlBuilder builder = createXmlBuilder(); buildClasspath(builder); // if user has specified any web elements, then let's generate these in the result file. if (web != null && web.getResources() != null && web.getResources().length != 0) { generateDefaultWeb = false; // but don't generate default web element because this folder is most likely missing. buildWeb(builder); } return builder; } /** * Create a new instance of RebelXmlBuilder with the version of maven and JRebel plugin used during build * * @return new instance of RebelXmlBuilder */ private RebelXmlBuilder createXmlBuilder() { return new RebelXmlBuilder(session.getSystemProperties().getProperty("maven.version"), execution.getVersion()); } private void buildClasspath(RebelXmlBuilder builder) throws MojoExecutionException { boolean addDefaultAsFirst = true; RebelClasspathResource defaultClasspath = null; // check if there is a element with no dir/jar/dirset/jarset set. if there // is then don't put default classpath as // first but put it where this element was. if (classpath != null) { final RebelClasspathResource[] resources = classpath.getResources(); if (resources != null && resources.length > 0) { for (final RebelClasspathResource r : resources) { if (!r.isTargetSet()) { addDefaultAsFirst = false; defaultClasspath = r; break; } } } } if (addDefaultAsFirst) { buildDefaultClasspath(builder, defaultClasspath); } if (classpath != null) { builder.setFallbackClasspath(classpath.getFallback()); final RebelClasspathResource[] resources = classpath.getResources(); if (resources != null && resources.length > 0) { for (final RebelClasspathResource r : resources) { if (r.isTargetSet()) { if (r.getDirectory() != null) { r.setDirectory(fixFilePath(r.getDirectory())); builder.addClasspathDir(r); } if (r.getJar() != null) { r.setJar(fixFilePath(r.getJar())); builder.addClasspathJar(r); } if (r.getJarset() != null) { r.setJarset(fixFilePath(r.getJarset())); builder.addClasspathJarset(r); } if (r.getDirset() != null) { r.setDirset(fixFilePath(r.getDirset())); builder.addClasspathDirset(r); } } else { buildDefaultClasspath(builder, r); } } } } } private void buildDefaultClasspath(RebelXmlBuilder builder, RebelClasspathResource defaultClasspath) throws MojoExecutionException { if (!generateDefaultClasspath) { return; } if (addResourcesDirToRebelXml) { buildDefaultClasspathResources(builder); } // project output directory RebelClasspathResource r = new RebelClasspathResource(); r.setDirectory(fixFilePath(classesDirectory)); if (defaultClasspath != null) { r.setIncludes(defaultClasspath.getIncludes()); r.setExcludes(defaultClasspath.getExcludes()); } builder.addClasspathDir(r); } private void buildDefaultClasspathResources(RebelXmlBuilder builder) throws MojoExecutionException { final boolean overwrite = Boolean.valueOf(getPluginSetting(getProject(), "org.apache.maven.plugins:maven-resources-plugin", "overwrite", "false")); RebelClasspathResource rebelClassPathResource; List resources = getProject().getResources(); //if resources plugin is set to overwrite then reverse the order of resources if (overwrite) { Collections.reverse(resources); } for (Iterator i = resources.iterator(); i.hasNext(); ) { Resource resource = (Resource) i.next(); File dir = new File(resource.getDirectory()); if (!dir.isAbsolute()) { dir = new File(getProject().getBasedir(), resource.getDirectory()); } //skip directories that don't exist if (!dir.exists() || !dir.isDirectory()) { continue; } rebelClassPathResource = new RebelClasspathResource(); if (resource.isFiltering() || resource.getTargetPath() != null) { if (!handleResourceAsInclude(rebelClassPathResource, resource)) { continue; } //point filtered resources to target directory rebelClassPathResource.setDirectory(fixFilePath(classesDirectory)); //add target path as prefix to includes if (resource.getTargetPath() != null) { setIncludePrefix(rebelClassPathResource.getIncludes(), resource.getTargetPath()); } } else { rebelClassPathResource.setDirectory(fixFilePath(resource.getDirectory())); rebelClassPathResource.setExcludes(resource.getExcludes()); rebelClassPathResource.setIncludes(resource.getIncludes()); } builder.addClasspathDir(rebelClassPathResource); } } private void setIncludePrefix(List includes, String prefix) { if (!prefix.endsWith("/")) { prefix = prefix + "/"; } for (int i = 0; i < includes.size(); i++) { includes.set(i, prefix + includes.get(i)); } } /** * Set includes & excludes for filtered resources. */ private boolean handleResourceAsInclude(RebelResource rebelResouce, Resource resource) { File dir = new File(resource.getDirectory()); if (!dir.isAbsolute()) { dir = new File(getProject().getBasedir(), resource.getDirectory()); } //if directory does not exist then exclude all if (!dir.exists() || !dir.isDirectory()) { return false; } resource.setDirectory(dir.getAbsolutePath()); String[] files = getFilesToCopy(resource); if (files.length > 0) { //only include files that come from this directory List includedFiles = new ArrayList(); for (final String file : files) { includedFiles.add(StringUtils.replace(file, '\\', '/')); } rebelResouce.setIncludes(includedFiles); } else { //there weren't any matching files return false; } return true; } /** * Taken from war plugin. * * @param resource * @return array of file names that would be copied from specified resource */ private String[] getFilesToCopy(Resource resource) { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(resource.getDirectory()); if (resource.getIncludes() != null && !resource.getIncludes().isEmpty()) { scanner.setIncludes(resource.getIncludes().toArray(new String[resource.getIncludes().size()])); } else { scanner.setIncludes(DEFAULT_INCLUDES); } if (resource.getExcludes() != null && !resource.getExcludes().isEmpty()) { scanner.setExcludes(resource.getExcludes().toArray(new String[resource.getExcludes().size()])); } scanner.addDefaultExcludes(); scanner.scan(); return scanner.getIncludedFiles(); } private void buildWeb(RebelXmlBuilder builder) throws MojoExecutionException { boolean addDefaultAsFirst = true; RebelWebResource defaultWeb = null; if (web != null) { final RebelWebResource[] resources = web.getResources(); if (resources != null && resources.length > 0) { for (final RebelWebResource r : resources) { if (r.getDirectory() == null && r.getTarget() == null) { defaultWeb = r; addDefaultAsFirst = false; break; } } } } if (addDefaultAsFirst) { buildDefaultWeb(builder, defaultWeb); } if (web != null) { final RebelWebResource[] resources = web.getResources(); if (resources != null && resources.length > 0) { for (final RebelWebResource r : resources) { if (r.getDirectory() == null && r.getTarget() == null) { buildDefaultWeb(builder, r); continue; } r.setDirectory(fixFilePath(r.getDirectory())); builder.addWebresource(r); } } } } private void buildDefaultWeb(final RebelXmlBuilder builder, final RebelWebResource defaultWeb) throws MojoExecutionException { if (!generateDefaultWeb) { return; } Xpp3Dom warPluginConf = getPluginConfigurationDom(getProject(), "org.apache.maven.plugins:maven-war-plugin"); if (warPluginConf != null) { //override defaults with configuration from war plugin Xpp3Dom warSourceNode = warPluginConf.getChild("warSourceDirectory"); if (warSourceNode != null && warSourceNode.getValue() != null) { warSourceDirectory = new File(getValue(getProject(), warSourceNode)); } Xpp3Dom webappDirNode = warPluginConf.getChild("webappDirectory"); if (webappDirNode != null && webappDirNode.getValue() != null) { webappDirectory = new File(getValue(getProject(), webappDirNode)); } //handle web resources configured for war plugin Xpp3Dom wr = warPluginConf.getChild("webResources"); if (wr != null) { List resources = parseWarResources(wr); //web resources overwrite each other Collections.reverse(resources); for (Iterator i = resources.iterator(); i.hasNext(); ) { Resource resource = (Resource) i.next(); File dir = new File(resource.getDirectory()); if (!dir.isAbsolute()) { dir = new File(getProject().getBasedir(), resource.getDirectory()); } //skip directories that don't exist if (!dir.exists() || !dir.isDirectory()) { continue; } if (resource.getTargetPath() == null) { resource.setTargetPath("/"); } if (!resource.getTargetPath().endsWith("/")) { resource.setTargetPath(resource.getTargetPath() + "/"); } //web resources that go under WEB-INF/classes should be placed to classpath if (resource.getTargetPath().startsWith("WEB-INF/classes/")) { if (addResourcesDirToRebelXml) { String target = resource.getTargetPath().substring("WEB-INF/classes/".length()); RebelClasspathResource rc = new RebelClasspathResource(); if (resource.isFiltering() || StringUtils.isNotEmpty(target)) { if (!handleResourceAsInclude(rc, resource)) { continue; } rc.setDirectory(fixFilePath(new File(webappDirectory, "WEB-INF/classes"))); if (StringUtils.isNotEmpty(target)) { setIncludePrefix(rc.getIncludes(), target); } } else { rc.setDirectory(fixFilePath(resource.getDirectory())); rc.setExcludes(resource.getExcludes()); rc.setIncludes(resource.getIncludes()); } builder.addClasspathDir(rc); } } else { RebelWebResource r = new RebelWebResource(); r.setTarget(resource.getTargetPath()); if (resource.isFiltering()) { r.setDirectory(fixFilePath(new File(webappDirectory, resource.getTargetPath()))); if (!handleResourceAsInclude(r, resource)) { continue; } } else { r.setDirectory(fixFilePath(resource.getDirectory())); r.setExcludes(resource.getExcludes()); r.setIncludes(resource.getIncludes()); } builder.addWebresource(r); } } } } RebelWebResource r = new RebelWebResource(); r.setTarget("/"); r.setDirectory(fixFilePath(warSourceDirectory)); if (defaultWeb != null) { r.setIncludes(defaultWeb.getIncludes()); r.setExcludes(defaultWeb.getExcludes()); } builder.addWebresource(r); } /** * Parse resources node content. * * @param warResourcesNode * @return */ private List parseWarResources(Xpp3Dom warResourcesNode) { final List resources = new ArrayList(); final Xpp3Dom[] resourceNodes = warResourcesNode.getChildren("resource"); for (final Xpp3Dom resourceNode : resourceNodes) { if (resourceNode == null || resourceNode.getChild("directory") == null) { continue; } resources.add(parseResourceNode(resourceNode)); } return resources; } /** * Parse resouce node content. * * @param rn resource node content * @return resource parsed */ private Resource parseResourceNode(Xpp3Dom rn) { Resource r = new Resource(); if (rn.getChild("directory") != null) { r.setDirectory(getValue(getProject(), rn.getChild("directory"))); } if (rn.getChild("filtering") != null) { r.setFiltering((Boolean.valueOf(getValue(getProject(), rn.getChild("filtering"))))); } if (rn.getChild("targetPath") != null) { r.setTargetPath(rn.getChild("targetPath").getValue()); } if (rn.getChild("excludes") != null) { final List excludes = new ArrayList(); final Xpp3Dom[] excludeNodes = rn.getChild("excludes").getChildren("exclude"); for (final Xpp3Dom excludeNode : excludeNodes) { if (excludeNode != null && excludeNode.getValue() != null) { excludes.add(getValue(getProject(), excludeNode)); } } r.setExcludes(excludes); } if (rn.getChild("includes") != null) { final List includes = new ArrayList(); final Xpp3Dom[] includeNodes = rn.getChild("includes").getChildren("include"); for (final Xpp3Dom includeNode : includeNodes) { if (includeNode != null && includeNode.getValue() != null) { includes.add(getValue(getProject(), includeNode)); } } r.setIncludes(includes); } return r; } /** * Taken from eclipse plugin. Search for the configuration Xpp3 dom of an other plugin. * * @param project the current maven project to get the configuration from. * @param pluginId the group id and artifact id of the plugin to search for * @return the value of the plugin configuration */ private static Xpp3Dom getPluginConfigurationDom(MavenProject project, String pluginId) { Plugin plugin = project.getBuild().getPluginsAsMap().get(pluginId); if (plugin != null) { return (Xpp3Dom) plugin.getConfiguration(); } return null; } /** * Search for a configuration setting of an other plugin. * * @param project the current maven project to get the configuration from. * @param pluginId the group id and artifact id of the plugin to search for * @param optionName the option to get from the configuration * @param defaultValue the default value if the configuration was not found * @return the value of the option configured in the plugin configuration */ private String getPluginSetting(MavenProject project, String pluginId, String optionName, String defaultValue) { Xpp3Dom dom = getPluginConfigurationDom(project, pluginId); if (dom != null && dom.getChild(optionName) != null) { return getValue(project, dom.getChild(optionName)); } return defaultValue; } private String getValue(MavenProject project, Xpp3Dom dom) { String value = dom.getValue(); return getValue(project, value); } private String getValue(MavenProject project, String value) { if (value != null && value.contains("$")) { return getInterpolatorValue(project, value); } return value; } /** * Maven versions prior to 2.0.9 don't interpolate all ${project.*} values, so we'll need to do it ourself. * * @param project * @param value * @return */ private String getInterpolatorValue(MavenProject project, String value) { RegexBasedInterpolator interpolator = new RegexBasedInterpolator(); interpolator.addValueSource(new ObjectBasedValueSource(project)); try { return interpolator.interpolate(value, "project"); } catch (Exception e) { getLog().debug("Detected exception during 'getInterpolatorValue' : ", e); e.printStackTrace(); } return value; } protected String fixFilePath(String path) throws MojoExecutionException { return fixFilePath(new File(path)); } /** * Returns path expressed through rootPath and relativePath. * * @param file to be fixed * @return fixed path * @throws MojoExecutionException if something goes wrong */ protected String fixFilePath(File file) throws MojoExecutionException { File baseDir = getProject().getFile().getParentFile(); if (file.isAbsolute() && !isRelativeToPath(new File(baseDir, getRelativePath()), file)) { return StringUtils.replace(getCanonicalPath(file), '\\', '/'); } if (!file.isAbsolute()) { file = new File(baseDir, file.getPath()); } String relative = getRelativePath(new File(baseDir, getRelativePath()), file); if (!(new File(relative)).isAbsolute()) { return StringUtils.replace(getRootPath(), '\\', '/') + "/" + relative; } //relative path was outside baseDir //if root path is absolute then try to get a path relative to root if ((new File(getRootPath())).isAbsolute()) { String s = getRelativePath(new File(getRootPath()), file); if (!(new File(s)).isAbsolute()) { return StringUtils.replace(getRootPath(), '\\', '/') + "/" + s; } else { // root path and the calculated path are absolute, so // just return calculated path return s; } } //return absolute path to file return StringUtils.replace(file.getAbsolutePath(), '\\', '/'); } private static String getRelativePath(File baseDir, File file) throws MojoExecutionException { // Avoid the common prefix problem (see case 17005) // baseDir = /myProject/web-module/. // file = /myProject/web-module-shared/something/something/something // then basedirpath cannot be a prefix of the absolutePath, or the relative path will be calculated incorrectly! // This problem is avoided by adding a trailing slash to basedirpath. String basedirpath = getCanonicalPath(baseDir) + File.separator; String absolutePath = getCanonicalPath(file); String relative; if (absolutePath.equals(basedirpath)) { relative = "."; } else if (absolutePath.startsWith(basedirpath)) { relative = absolutePath.substring(basedirpath.length()); } else { relative = absolutePath; } relative = StringUtils.replace(relative, '\\', '/'); return relative; } private static boolean isRelativeToPath(File baseDir, File file) throws MojoExecutionException { String basedirpath = getCanonicalPath(baseDir); String absolutePath = getCanonicalPath(file); return absolutePath.startsWith(basedirpath); } private static String getCanonicalPath(File file) throws MojoExecutionException { try { return file.getCanonicalPath(); } catch (IOException e) { throw new MojoExecutionException("Failed to get canonical path of " + file.getAbsolutePath(), e); } } public void setProject(MavenProject project) { this.project = project; } public MavenProject getProject() { return project; } public void setRelativePath(String relativePath) { this.relativePath = relativePath; } public String getRelativePath() { return relativePath; } public void setRootPath(String rootPath) { this.rootPath = rootPath; } public String getRootPath() { return rootPath; } String calculatePathToRoot(File root, File folder) throws IOException { String result = "."; if (root != null && !folder.equals(root)) { String normalizedBase = FilenameUtils.normalizeNoEndSeparator(folder.getCanonicalPath()); String normalizedMain = FilenameUtils.normalizeNoEndSeparator(root.getCanonicalPath()); if (normalizedMain.length() > normalizedBase.length()) { throw new IOException("Can't find main project folder, module folder = " + normalizedBase + ", calculated main folder = " + normalizedMain); } String diff = normalizedBase.substring(normalizedMain.length()); if (diff.length() != 0) { StringBuilder buffer = new StringBuilder(); for (char c : diff.toCharArray()) { if (c == '/' || c == '\\') { buffer.append("..").append(File.separatorChar); } } result = buffer.toString(); } } getLog().debug("root:" + root + " folder:" + folder + " result:" + result); return result; } String calculateRelativePath(String relativePathToRoot, String rootRelativePath) { getLog().debug("relativePathToRoot:" + relativePathToRoot + " rootRelativePath:" + rootRelativePath); if (".".equals(relativePathToRoot)) { if (".".equals(rootRelativePath)) { return "."; } else { return rootRelativePath; } } else if (".".equals(rootRelativePath)) { return relativePathToRoot; } return relativePathToRoot + rootRelativePath; } private File findBaseDirOfMainProject() { MavenProject current = this.project; while (current.hasParent() && current.getParent().getBasedir() != null) { current = current.getParent(); } getLog().debug("project:" + this.project + " baseDir:" + current.getBasedir()); return current.getBasedir(); } }
package com.mikepenz.fastadapter_extensions.dialog; import android.content.Context; import android.content.DialogInterface; import android.support.annotation.NonNull; import android.support.annotation.StringRes; import android.support.v7.app.AlertDialog; import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import com.mikepenz.fastadapter.AbstractAdapter; import com.mikepenz.fastadapter.FastAdapter; import com.mikepenz.fastadapter.IItem; import com.mikepenz.fastadapter.adapters.FastItemAdapter; import java.util.ArrayList; import java.util.List; public class FastAdapterDialog<Item extends IItem> extends AlertDialog { private RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private FastItemAdapter<Item> mFastItemAdapter; private RecyclerView.LayoutManager mLayoutManager; private List<RecyclerView.OnScrollListener> mOnScrollListener; public FastAdapterDialog(Context context) { super(context); } public FastAdapterDialog(Context context, int theme) { super(context, theme); } /** * Set the title text for this dialog's window. * * @param title The text to display in the title. */ public FastAdapterDialog<Item> withTitle(String title) { setTitle(title); return this; } /** * Set the title text for this dialog's window. * * @param titleRes The resource id of the text to display in the title. */ public FastAdapterDialog<Item> withTitle(@StringRes int titleRes) { setTitle(titleRes); return this; } public FastAdapterDialog<Item> withFastItemAdapter(@NonNull FastItemAdapter<Item> fastItemAdapter) { this.mFastItemAdapter = fastItemAdapter; mFastItemAdapter.setHasStableIds(false); return this; } public FastAdapterDialog<Item> withItems(@NonNull ArrayList<Item> items) { if (mFastItemAdapter == null) { mFastItemAdapter = new FastItemAdapter<>(); } mFastItemAdapter.set(items); return this; } public FastAdapterDialog<Item> withItems(@NonNull Item... items) { if (mFastItemAdapter == null) { mFastItemAdapter = new FastItemAdapter<>(); } mFastItemAdapter.add(items); return this; } public FastAdapterDialog<Item> withAdapter(AbstractAdapter<Item> adapter) { this.mAdapter = adapter; return this; } /** * Set the {@link RecyclerView.LayoutManager} that the RecyclerView will use. * * @param layoutManager LayoutManager to use */ public FastAdapterDialog<Item> withLayoutManager(RecyclerView.LayoutManager layoutManager) { this.mLayoutManager = layoutManager; return this; } /** * Add a listener that will be notified of any changes in scroll state or position of the * RecyclerView. * * @param listener listener to set or null to clear */ public FastAdapterDialog<Item> withOnScrollListener(RecyclerView.OnScrollListener listener) { if (mOnScrollListener == null) { mOnScrollListener = new ArrayList<>(); } this.mOnScrollListener.add(listener); return this; } /** * Set a listener to be invoked when the positive button of the dialog is pressed. * * @param text The text to display in the positive button * @param listener The {@link DialogInterface.OnClickListener} to use. * @return This Builder object to allow for chaining of calls to set methods */ public FastAdapterDialog<Item> withPositiveButton(String text, OnClickListener listener) { return withButton(BUTTON_POSITIVE, text, listener); } /** * Set a listener to be invoked when the positive button of the dialog is pressed. * * @param textRes The resource id of the text to display in the positive button * @param listener The {@link DialogInterface.OnClickListener} to use. * @return This Builder object to allow for chaining of calls to set methods */ public FastAdapterDialog<Item> withPositiveButton(@StringRes int textRes, OnClickListener listener) { return withButton(BUTTON_POSITIVE, textRes, listener); } /** * Set a listener to be invoked when the negative button of the dialog is pressed. * * @param text The text to display in the negative button * @param listener The {@link DialogInterface.OnClickListener} to use. * @return This Builder object to allow for chaining of calls to set methods */ public FastAdapterDialog<Item> withNegativeButton(String text, OnClickListener listener) { return withButton(BUTTON_NEGATIVE, text, listener); } /** * Set a listener to be invoked when the negative button of the dialog is pressed. * * @param textRes The resource id of the text to display in the negative button * @param listener The {@link DialogInterface.OnClickListener} to use. * @return This Builder object to allow for chaining of calls to set methods */ public FastAdapterDialog<Item> withNegativeButton(@StringRes int textRes, OnClickListener listener) { return withButton(BUTTON_NEGATIVE, textRes, listener); } /** * Adds a negative button to the dialog. The button click will close the dialog. * * @param textRes The resource id of the text to display in the negative button * @return This Builder object to allow for chaining of calls to set methods */ public FastAdapterDialog<Item> withNegativeButton(@StringRes int textRes) { return withButton(BUTTON_NEGATIVE, textRes, null); } /** * Adds a negative button to the dialog. The button click will close the dialog. * * @param text The text to display in the negative button * @return This Builder object to allow for chaining of calls to set methods */ public FastAdapterDialog<Item> withNegativeButton(String text) { return withButton(BUTTON_NEGATIVE, text, null); } /** * Set a listener to be invoked when the neutral button of the dialog is pressed. * * @param text The text to display in the neutral button * @param listener The {@link DialogInterface.OnClickListener} to use. * @return This Builder object to allow for chaining of calls to set methods */ public FastAdapterDialog<Item> withNeutralButton(String text, OnClickListener listener) { return withButton(BUTTON_NEUTRAL, text, listener); } /** * Set a listener to be invoked when the neutral button of the dialog is pressed. * * @param textRes The resource id of the text to display in the neutral button * @param listener The {@link DialogInterface.OnClickListener} to use. * @return This Builder object to allow for chaining of calls to set methods */ public FastAdapterDialog<Item> withNeutralButton(@StringRes int textRes, OnClickListener listener) { return withButton(BUTTON_NEUTRAL, textRes, listener); } /** * Sets a listener to be invoked when the positive button of the dialog is pressed. This method * has no effect if called after {@link #show()}. * * @param whichButton Which button to set the listener on, can be one of * {@link DialogInterface#BUTTON_POSITIVE}, * {@link DialogInterface#BUTTON_NEGATIVE}, or * {@link DialogInterface#BUTTON_NEUTRAL} * @param text The text to display in positive button. * @param listener The {@link DialogInterface.OnClickListener} to use. */ public FastAdapterDialog<Item> withButton(int whichButton, String text, OnClickListener listener) { setButton(whichButton, text, listener); return this; } /** * Sets a listener to be invoked when the positive button of the dialog is pressed. This method * has no effect if called after {@link #show()}. * * @param whichButton Which button to set the listener on, can be one of * {@link DialogInterface#BUTTON_POSITIVE}, * {@link DialogInterface#BUTTON_NEGATIVE}, or * {@link DialogInterface#BUTTON_NEUTRAL} * @param textRes The text to display in positive button. * @param listener The {@link DialogInterface.OnClickListener} to use. */ public FastAdapterDialog<Item> withButton(int whichButton, @StringRes int textRes, OnClickListener listener) { setButton(whichButton, getContext().getString(textRes), listener); return this; } /** * Start the dialog and display it on screen. The window is placed in the * application layer and opaque. Note that you should not override this * method to do initialization when the dialog is shown, instead implement * that in {@link #onStart}. */ public void show() { if (mFastItemAdapter == null && mAdapter == null) { mFastItemAdapter = new FastItemAdapter<>(); mFastItemAdapter.setHasStableIds(false); } this.mRecyclerView = createRecyclerView(getContext(), mLayoutManager, mAdapter == null ? mFastItemAdapter : mAdapter); if (mOnScrollListener != null) { for (RecyclerView.OnScrollListener onScrollListener : mOnScrollListener) { mRecyclerView.addOnScrollListener(onScrollListener); } } setView(mRecyclerView); super.show(); } private RecyclerView createRecyclerView(Context context, RecyclerView.LayoutManager layoutManager, RecyclerView.Adapter adapter) { RecyclerView recyclerView = new RecyclerView(context); RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); recyclerView.setLayoutParams(params); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); return recyclerView; } public RecyclerView getRecyclerView() { return mRecyclerView; } /** * Define the OnClickListener which will be used for a single item * * @param onClickListener the OnClickListener which will be used for a single item * @return this */ public FastAdapterDialog<Item> withOnClickListener(FastAdapter.OnClickListener<Item> onClickListener) { this.mFastItemAdapter.withOnClickListener(onClickListener); return this; } /** * Define the OnPreClickListener which will be used for a single item and is called after all internal methods are done * * @param onPreClickListener the OnPreClickListener which will be called after a single item was clicked and all internal methods are done * @return this */ public FastAdapterDialog<Item> withOnPreClickListener(FastAdapter.OnClickListener<Item> onPreClickListener) { this.mFastItemAdapter.withOnPreClickListener(onPreClickListener); return this; } /** * Define the OnLongClickListener which will be used for a single item * * @param onLongClickListener the OnLongClickListener which will be used for a single item * @return this */ public FastAdapterDialog<Item> withOnLongClickListener(FastAdapter.OnLongClickListener<Item> onLongClickListener) { this.mFastItemAdapter.withOnLongClickListener(onLongClickListener); return this; } /** * Define the OnLongClickListener which will be used for a single item and is called after all internal methods are done * * @param onPreLongClickListener the OnLongClickListener which will be called after a single item was clicked and all internal methods are done * @return this */ public FastAdapterDialog<Item> withOnPreLongClickListener(FastAdapter.OnLongClickListener<Item> onPreLongClickListener) { this.mFastItemAdapter.withOnPreLongClickListener(onPreLongClickListener); return this; } /** * Define the TouchListener which will be used for a single item * * @param onTouchListener the TouchListener which will be used for a single item * @return this */ public FastAdapterDialog<Item> withOnTouchListener(FastAdapter.OnTouchListener<Item> onTouchListener) { this.mFastItemAdapter.withOnTouchListener(onTouchListener); return this; } /** * set a new list of items and apply it to the existing list (clear - add) for this adapter * * @param items the new items to set */ public FastAdapterDialog<Item> set(List<Item> items) { mFastItemAdapter.set(items); return this; } /** * sets a complete new list of items onto this adapter, using the new list. Calls notifyDataSetChanged * * @param items the new items to set */ public FastAdapterDialog<Item> setNewList(List<Item> items) { mFastItemAdapter.setNewList(items); return this; } /** * add an array of items to the end of the existing items * * @param items the items to add */ @SafeVarargs public final FastAdapterDialog<Item> add(Item... items) { mFastItemAdapter.add(items); return this; } /** * add a list of items to the end of the existing items * * @param items the items to add */ public FastAdapterDialog<Item> add(List<Item> items) { mFastItemAdapter.add(items); return this; } /** * add an array of items at the given position within the existing items * * @param position the global position * @param items the items to add */ @SafeVarargs public final FastAdapterDialog<Item> add(int position, Item... items) { mFastItemAdapter.add(position, items); return this; } /** * add a list of items at the given position within the existing items * * @param position the global position * @param items the items to add */ public FastAdapterDialog<Item> add(int position, List<Item> items) { mFastItemAdapter.add(position, items); return this; } /** * sets an item at the given position, overwriting the previous item * * @param position the global position * @param item the item to set */ public FastAdapterDialog<Item> set(int position, Item item) { mFastItemAdapter.set(position, item); return this; } /** * add an item at the end of the existing items * * @param item the item to add */ public FastAdapterDialog<Item> add(Item item) { mFastItemAdapter.add(item); return this; } /** * add an item at the given position within the existing icons * * @param position the global position * @param item the item to add */ public FastAdapterDialog<Item> add(int position, Item item) { mFastItemAdapter.add(position, item); return this; } /** * moves an item within the list from a position to a position * * @param fromPosition the position global from which we want to move * @param toPosition the global position to which to move * @return this */ public FastAdapterDialog<Item> move(int fromPosition, int toPosition) { mFastItemAdapter.move(fromPosition, toPosition); return this; } /** * removes an item at the given position within the existing icons * * @param position the global position */ public FastAdapterDialog<Item> remove(int position) { mFastItemAdapter.remove(position); return this; } /** * removes a range of items starting with the given position within the existing icons * * @param position the global position * @param itemCount the count of items removed */ public FastAdapterDialog<Item> removeItemRange(int position, int itemCount) { mFastItemAdapter.removeItemRange(position, itemCount); return this; } /** * removes all items of this adapter */ public FastAdapterDialog<Item> clear() { mFastItemAdapter.clear(); return this; } }
package techreborn.blockentity.machine.misc; import net.minecraft.block.*; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.fluid.Fluid; import net.minecraft.fluid.Fluids; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import org.jetbrains.annotations.Nullable; import reborncore.api.IToolDrop; import reborncore.common.blockentity.MachineBaseBlockEntity; import reborncore.common.fluid.FluidValue; import reborncore.common.fluid.container.FluidInstance; import reborncore.common.fluid.container.ItemFluidInfo; import reborncore.common.util.Tank; import techreborn.TechReborn; import techreborn.config.TechRebornConfig; import techreborn.init.TRBlockEntities; import techreborn.init.TRContent; public class DrainBlockEntity extends MachineBaseBlockEntity implements IToolDrop { protected Tank internalTank = new Tank("tank", FluidValue.BUCKET, this); public DrainBlockEntity(BlockPos pos, BlockState state) { super(TRBlockEntities.DRAIN, pos, state); } @Override public void tick(World world, BlockPos pos, BlockState state, MachineBaseBlockEntity blockEntity) { super.tick(world, pos, state, blockEntity); if (world == null || world.isClient) { return; } int ticks = TechRebornConfig.ticksUntilNextDrainAttempt; if (ticks > 0 && world.getTime() % ticks == 0) { if (internalTank.isEmpty()) { tryDrain(); } } } @Nullable @Override public Tank getTank() { return internalTank; } private void tryDrain() { // Position above drain BlockPos above = this.getPos().up(); // Block and state above drain BlockState aboveBlockState = world.getBlockState(above); Block aboveBlock = aboveBlockState.getBlock(); if (aboveBlock instanceof FluidDrainable) { ItemStack fluidContainer = ((FluidDrainable) aboveBlock).tryDrainFluid(world, above, aboveBlockState); if (fluidContainer.getItem() instanceof ItemFluidInfo) { Fluid drainFluid = ((ItemFluidInfo) fluidContainer.getItem()).getFluid(fluidContainer); internalTank.setFluidInstance(new FluidInstance(drainFluid, FluidValue.BUCKET)); } else { TechReborn.LOGGER.debug("Could not get Fluid from ItemStack " + fluidContainer.getItem()); } } if (aboveBlock instanceof LeveledCauldronBlock && aboveBlockState.isOf(Blocks.WATER_CAULDRON)) { //ensure Water cauldron Fluid drainFluid = Fluids.WATER; int level; if (aboveBlockState.contains(LeveledCauldronBlock.LEVEL)){ level = aboveBlockState.get(LeveledCauldronBlock.LEVEL); } else { return; } world.setBlockState(above, Blocks.CAULDRON.getDefaultState()); internalTank.setFluidInstance( new FluidInstance(drainFluid, FluidValue.BUCKET.fraction(3).multiply(level)) ); } if (aboveBlock instanceof LavaCauldronBlock){ world.setBlockState(above, Blocks.CAULDRON.getDefaultState()); internalTank.setFluidInstance( new FluidInstance(Fluids.LAVA, FluidValue.BUCKET) ); } } @Override public ItemStack getToolDrop(PlayerEntity p0) { return TRContent.Machine.DRAIN.getStack(); } }
package us.myles.ViaVersion.transformers; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import io.netty.buffer.ByteBuf; import org.bukkit.Material; import org.bukkit.entity.EntityType; import org.spacehq.opennbt.tag.builtin.CompoundTag; import org.spacehq.opennbt.tag.builtin.StringTag; import us.myles.ViaVersion.CancelException; import us.myles.ViaVersion.ConnectionInfo; import us.myles.ViaVersion.ViaVersionPlugin; import us.myles.ViaVersion.api.ViaVersion; import us.myles.ViaVersion.api.boss.BossBar; import us.myles.ViaVersion.api.boss.BossColor; import us.myles.ViaVersion.api.boss.BossStyle; import us.myles.ViaVersion.chunks.Chunk; import us.myles.ViaVersion.chunks.ChunkManager; import us.myles.ViaVersion.metadata.MetaIndex; import us.myles.ViaVersion.metadata.MetadataRewriter; import us.myles.ViaVersion.metadata.MetadataRewriter.Entry; import us.myles.ViaVersion.packets.PacketType; import us.myles.ViaVersion.packets.State; import us.myles.ViaVersion.slot.ItemSlotRewriter; import us.myles.ViaVersion.sounds.SoundEffect; import us.myles.ViaVersion.util.EntityUtil; import us.myles.ViaVersion.util.PacketUtil; import java.io.IOException; import java.util.*; import static us.myles.ViaVersion.util.PacketUtil.*; public class OutgoingTransformer { private static Gson gson = new GsonBuilder().create(); private final ViaVersionPlugin plugin = (ViaVersionPlugin) ViaVersion.getInstance(); private final ConnectionInfo info; private final Map<Integer, UUID> uuidMap = new HashMap<>(); private final Map<Integer, EntityType> clientEntityTypes = new HashMap<>(); private final Map<Integer, Integer> vehicleMap = new HashMap<>(); private final Set<Integer> validBlocking = new HashSet<>(); private final Set<Integer> knownHolograms = new HashSet<>(); private final Map<Integer, BossBar> bossBarMap = new HashMap<>(); private boolean autoTeam = false; private boolean teamExists = false; public OutgoingTransformer(ConnectionInfo info) { this.info = info; } public static String fixJson(String line) { if (line == null || line.equalsIgnoreCase("null")) { line = "{\"text\":\"\"}"; } else { if ((!line.startsWith("\"") || !line.endsWith("\"")) && (!line.startsWith("{") || !line.endsWith("}"))) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("text", line); return gson.toJson(jsonObject); } if (line.startsWith("\"") && line.endsWith("\"")) { line = "{\"text\":" + line + "}"; } } try { gson.fromJson(line, JsonObject.class); } catch (Exception e) { System.out.println("Invalid JSON String: \"" + line + "\" Please report this issue to the ViaVersion Github: " + e.getMessage()); return "{\"text\":\"\"}"; } return line; } public void transform(int packetID, ByteBuf input, ByteBuf output) throws CancelException { PacketType packet = PacketType.getOutgoingPacket(info.getState(), packetID); int original = packetID; if (packet == null) { throw new RuntimeException("Outgoing Packet not found? " + packetID + " State: " + info.getState() + " Version: " + info.getProtocol()); } if (packet.getPacketID() != -1) { packetID = packet.getNewPacketID(); } if (ViaVersion.getInstance().isDebug()) { if (packet != PacketType.PLAY_CHUNK_DATA && packet != PacketType.PLAY_KEEP_ALIVE && packet != PacketType.PLAY_TIME_UPDATE && (!packet.name().toLowerCase().contains("move") && !packet.name().toLowerCase().contains("look"))) { System.out.println("Direction " + packet.getDirection().name() + " Packet Type: " + packet + " New ID: " + packetID + " Original: " + original + " Size: " + input.readableBytes()); } } // By default no transform PacketUtil.writeVarInt(packetID, output); if (packet == PacketType.PLAY_NAMED_SOUND_EFFECT) { String name = PacketUtil.readString(input); SoundEffect effect = SoundEffect.getByName(name); int catid = 0; String newname = name; if (effect != null) { if (effect.isBreaksound()) { throw new CancelException(); } catid = effect.getCategory().getId(); newname = effect.getNewName(); } PacketUtil.writeString(newname, output); PacketUtil.writeVarInt(catid, output); output.writeBytes(input); } if (packet == PacketType.PLAY_EFFECT) { int effectid = input.readInt(); if (effectid >= 1000 && effectid < 2000 && effectid != 1005) //Sound effect throw new CancelException(); if (effectid == 1005) //Fix jukebox effectid = 1010; output.writeInt(effectid); } if (packet == PacketType.PLAY_ATTACH_ENTITY) { int passenger = input.readInt(); int vehicle = input.readInt(); boolean lead = input.readBoolean(); if (!lead) { output.clear(); writeVarInt(PacketType.PLAY_SET_PASSENGERS.getNewPacketID(), output); if (vehicle == -1) { if (!vehicleMap.containsKey(passenger)) throw new CancelException(); vehicle = vehicleMap.remove(passenger); writeVarInt(vehicle, output); writeVarIntArray(Collections.<Integer>emptyList(), output); } else { writeVarInt(vehicle, output); writeVarIntArray(Collections.singletonList(passenger), output); vehicleMap.put(passenger, vehicle); } return; } output.writeInt(passenger); output.writeInt(vehicle); return; } if (packet == PacketType.PLAY_PLUGIN_MESSAGE) { String name = PacketUtil.readString(input); PacketUtil.writeString(name, output); byte[] b = new byte[input.readableBytes()]; input.readBytes(b); // patch books if (name.equals("MC|BOpen")) { PacketUtil.writeVarInt(0, output); } output.writeBytes(b); } if (packet == PacketType.PLAY_DISCONNECT) { String reason = readString(input); writeString(fixJson(reason), output); return; } if (packet == PacketType.PLAY_TITLE) { int action = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(action, output); if (action == 0 || action == 1) { String text = PacketUtil.readString(input); PacketUtil.writeString(fixJson(text), output); } output.writeBytes(input); return; } if (packet == PacketType.PLAY_PLAYER_LIST_ITEM) { int action = readVarInt(input); writeVarInt(action, output); int players = readVarInt(input); writeVarInt(players, output); // loop through players for (int i = 0; i < players; i++) { UUID uuid = readUUID(input); writeUUID(uuid, output); if (action == 0) { // add player writeString(readString(input), output); // name int properties = readVarInt(input); writeVarInt(properties, output); // loop through properties for (int j = 0; j < properties; j++) { writeString(readString(input), output); // name writeString(readString(input), output); // value boolean isSigned = input.readBoolean(); output.writeBoolean(isSigned); if (isSigned) { writeString(readString(input), output); // signature } } writeVarInt(readVarInt(input), output); // gamemode writeVarInt(readVarInt(input), output); // ping boolean hasDisplayName = input.readBoolean(); output.writeBoolean(hasDisplayName); if (hasDisplayName) { writeString(fixJson(readString(input)), output); // display name } } else if ((action == 1) || (action == 2)) { // update gamemode || update latency writeVarInt(readVarInt(input), output); } else if (action == 3) { // update display name boolean hasDisplayName = input.readBoolean(); output.writeBoolean(hasDisplayName); if (hasDisplayName) { writeString(fixJson(readString(input)), output); // display name } } else if (action == 4) { // remove player // no fields } } return; } if (packet == PacketType.PLAY_PLAYER_LIST_HEADER_FOOTER) { String header = readString(input); String footer = readString(input); writeString(fixJson(header), output); writeString(fixJson(footer), output); return; } if (packet == PacketType.PLAY_ENTITY_TELEPORT) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); int x = input.readInt(); output.writeDouble(x / 32D); int y = input.readInt(); if (plugin.isHologramPatch() & knownHolograms.contains(id)) { y = (int) ((y) + (plugin.getHologramYOffset() * 32D)); } output.writeDouble(y / 32D); int z = input.readInt(); output.writeDouble(z / 32D); byte yaw = input.readByte(); output.writeByte(yaw); byte pitch = input.readByte(); output.writeByte(pitch); boolean onGround = input.readBoolean(); output.writeBoolean(onGround); return; } if (packet == PacketType.PLAY_ENTITY_LOOK_MOVE) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); int x = input.readByte(); output.writeShort(x * 128); int y = input.readByte(); output.writeShort(y * 128); int z = input.readByte(); output.writeShort(z * 128); byte yaw = input.readByte(); output.writeByte(yaw); byte pitch = input.readByte(); output.writeByte(pitch); boolean onGround = input.readBoolean(); output.writeBoolean(onGround); return; } if (packet == PacketType.PLAY_ENTITY_RELATIVE_MOVE) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); short x = (short) (input.readByte()); output.writeShort(x * 128); short y = (short) (input.readByte()); output.writeShort(y * 128); short z = (short) (input.readByte()); output.writeShort(z * 128); boolean onGround = input.readBoolean(); output.writeBoolean(onGround); return; } if (packet == PacketType.LOGIN_SETCOMPRESSION) { int factor = PacketUtil.readVarInt(input); info.setCompression(factor); PacketUtil.writeVarInt(factor, output); return; } if (packet == PacketType.STATUS_RESPONSE) { String originalStatus = PacketUtil.readString(input); try { JsonObject jsonObject = gson.fromJson(originalStatus, JsonObject.class); JsonObject version = jsonObject.get("version").getAsJsonObject(); if (version.get("protocol").getAsInt() != 9999) //Fix ServerListPlus custom outdated message version.addProperty("protocol", info.getProtocol()); PacketUtil.writeString(gson.toJson(jsonObject), output); } catch (Exception e) { e.printStackTrace(); } return; } if (packet == PacketType.LOGIN_SUCCESS) { info.setState(State.PLAY); String uuid = PacketUtil.readString(input); PacketUtil.writeString(uuid, output); UUID uniqueId = UUID.fromString(uuid); info.setUUID(uniqueId); plugin.addPortedClient(info); String username = PacketUtil.readString(input); info.setUsername(username); PacketUtil.writeString(username, output); return; } if (packet == PacketType.PLAY_PLAYER_POSITION_LOOK) { output.writeBytes(input); PacketUtil.writeVarInt(0, output); return; } if (packet == PacketType.PLAY_ENTITY_EQUIPMENT) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); short slot = input.readShort(); if (slot > 0) { slot += 1; // add 1 so it's now 2-5 } PacketUtil.writeVarInt(slot, output); if (slot == 0) { // Read aheat for sword input.markReaderIndex(); short itemID = input.readShort(); if (itemID != -1) { Material m = Material.getMaterial(itemID); if (m != null) { if (m.name().endsWith("SWORD")) { validBlocking.add(id); } else { validBlocking.remove(id); } } } else { validBlocking.remove(id); } input.resetReaderIndex(); } ItemSlotRewriter.rewrite1_8To1_9(input, output); return; } if (packet == PacketType.PLAY_ENTITY_METADATA) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); transformMetadata(id, input, output); return; } if (packet == PacketType.PLAY_SPAWN_GLOBAL_ENTITY) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); // only used for lightning byte type = input.readByte(); clientEntityTypes.put(id, EntityType.LIGHTNING); output.writeByte(type); double x = input.readInt(); output.writeDouble(x / 32D); double y = input.readInt(); output.writeDouble(y / 32D); double z = input.readInt(); output.writeDouble(z / 32D); return; } if (packet == PacketType.PLAY_DESTROY_ENTITIES) { int count = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(count, output); int[] toDestroy = PacketUtil.readVarInts(count, input); for (int entityID : toDestroy) { clientEntityTypes.remove(entityID); knownHolograms.remove(entityID); PacketUtil.writeVarInt(entityID, output); // Remvoe boss bar BossBar bar = bossBarMap.remove(entityID); if (bar != null) { bar.hide(); } } return; } if (packet == PacketType.PLAY_SPAWN_OBJECT) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); PacketUtil.writeUUID(getUUID(id), output); byte type = input.readByte(); clientEntityTypes.put(id, EntityUtil.getTypeFromID(type, true)); output.writeByte(type); double x = input.readInt(); output.writeDouble(x / 32D); double y = input.readInt(); output.writeDouble(y / 32D); double z = input.readInt(); output.writeDouble(z / 32D); byte pitch = input.readByte(); output.writeByte(pitch); byte yaw = input.readByte(); output.writeByte(yaw); int data = input.readInt(); output.writeInt(data); short vX = 0, vY = 0, vZ = 0; if (data > 0) { vX = input.readShort(); vY = input.readShort(); vZ = input.readShort(); } output.writeShort(vX); output.writeShort(vY); output.writeShort(vZ); return; } if (packet == PacketType.PLAY_SPAWN_XP_ORB) { int id = PacketUtil.readVarInt(input); clientEntityTypes.put(id, EntityType.EXPERIENCE_ORB); PacketUtil.writeVarInt(id, output); double x = input.readInt(); output.writeDouble(x / 32D); double y = input.readInt(); output.writeDouble(y / 32D); double z = input.readInt(); output.writeDouble(z / 32D); short data = input.readShort(); output.writeShort(data); return; } if (packet == PacketType.PLAY_SPAWN_PAINTING) { int id = PacketUtil.readVarInt(input); clientEntityTypes.put(id, EntityType.PAINTING); PacketUtil.writeVarInt(id, output); PacketUtil.writeUUID(getUUID(id), output); String title = PacketUtil.readString(input); PacketUtil.writeString(title, output); long[] position = PacketUtil.readBlockPosition(input); PacketUtil.writeBlockPosition(output, position[0], position[1], position[2]); byte direction = input.readByte(); output.writeByte(direction); return; } if (packet == PacketType.PLAY_WINDOW_PROPERTY) { int windowId = input.readUnsignedByte(); output.writeByte(windowId); short property = input.readShort(); short value = input.readShort(); if (info.getOpenWindow() != null) { if (info.getOpenWindow().equalsIgnoreCase("minecraft:enchanting_table")) { if (property > 3 && property < 7) { short level = (short) (value >> 8); short enchantID = (short) (value & 0xFF); // Property 1 ByteBuf buf1 = info.getChannel().alloc().buffer(); PacketUtil.writeVarInt(PacketType.PLAY_WINDOW_PROPERTY.getNewPacketID(), buf1); buf1.writeByte(windowId); buf1.writeShort(property); buf1.writeShort(enchantID); info.sendRawPacket(buf1); property = (short) (property + 3); value = level; } } } output.writeShort(property); output.writeShort(value); } if (packet == PacketType.PLAY_OPEN_WINDOW) { int windowId = input.readUnsignedByte(); String type = readString(input); info.setOpenWindow(type); String windowTitle = readString(input); output.writeByte(windowId); writeString(type, output); writeString(fixJson(windowTitle), output); int slots = input.readUnsignedByte(); if (type.equals("minecraft:brewing_stand")) { slots = slots + 1; // new slot } output.writeByte(slots); output.writeBytes(input); return; } if (packet == PacketType.PLAY_CLOSE_WINDOW) { info.closeWindow(); } if (packet == PacketType.PLAY_SET_SLOT) { int windowId = input.readUnsignedByte(); output.writeByte(windowId); short slot = input.readShort(); if (info.getOpenWindow() != null) { if (info.getOpenWindow().equals("minecraft:brewing_stand")) { if (slot >= 4) slot = (short) (slot + 1); } } output.writeShort(slot); ItemSlotRewriter.rewrite1_8To1_9(input, output); return; } if (packet == PacketType.PLAY_WINDOW_ITEMS) { int windowId = input.readUnsignedByte(); output.writeByte(windowId); short count = input.readShort(); boolean brewing = false; if (info.getOpenWindow() != null && windowId > 0) { if (info.getOpenWindow().equals("minecraft:brewing_stand")) { brewing = true; } } output.writeShort(brewing ? (count + 1) : count); for (int i = 0; i < count; i++) { ItemSlotRewriter.rewrite1_8To1_9(input, output); // write "fuel" slot if (brewing && i == 3) { output.writeShort(-1); // empty slot } } return; } if (packet == PacketType.PLAY_SPAWN_MOB) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); PacketUtil.writeUUID(getUUID(id), output); short type = input.readUnsignedByte(); clientEntityTypes.put(id, EntityUtil.getTypeFromID(type, false)); output.writeByte(type); double x = input.readInt(); output.writeDouble(x / 32D); double y = input.readInt(); output.writeDouble(y / 32D); double z = input.readInt(); output.writeDouble(z / 32D); byte yaw = input.readByte(); output.writeByte(yaw); byte pitch = input.readByte(); output.writeByte(pitch); byte headPitch = input.readByte(); output.writeByte(headPitch); short vX = input.readShort(); output.writeShort(vX); short vY = input.readShort(); output.writeShort(vY); short vZ = input.readShort(); output.writeShort(vZ); transformMetadata(id, input, output); return; } if (packet == PacketType.PLAY_UPDATE_SIGN) { Long location = input.readLong(); output.writeLong(location); for (int i = 0; i < 4; i++) { String line = PacketUtil.readString(input); PacketUtil.writeString(fixJson(line), output); } } if (packet == PacketType.PLAY_CHAT_MESSAGE) { String chat = PacketUtil.readString(input); PacketUtil.writeString(fixJson(chat), output); byte pos = input.readByte(); output.writeByte(pos); return; } if (packet == PacketType.PLAY_JOIN_GAME) { int id = input.readInt(); clientEntityTypes.put(id, EntityType.PLAYER); info.setEntityID(id); output.writeInt(id); int gamemode = input.readUnsignedByte(); output.writeByte(gamemode); int dimension = input.readByte(); output.writeByte(dimension); int difficulty = input.readUnsignedByte(); if (info.getProtocol() >= 108) { // 1.8.1 Pre 2 output.writeInt(difficulty); } else { output.writeByte(difficulty); } int maxPlayers = input.readUnsignedByte(); output.writeByte(maxPlayers); String level = PacketUtil.readString(input); PacketUtil.writeString(level, output); boolean reducedDebug = input.readBoolean(); output.writeBoolean(reducedDebug); return; } if (packet == PacketType.PLAY_SERVER_DIFFICULTY) { if (plugin.isAutoTeam()) { autoTeam = true; sendTeamPacket(true); } } if (packet == PacketType.PLAY_SPAWN_PLAYER) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); clientEntityTypes.put(id, EntityType.PLAYER); UUID playerUUID = PacketUtil.readUUID(input); PacketUtil.writeUUID(playerUUID, output); double x = input.readInt(); output.writeDouble(x / 32D); double y = input.readInt(); output.writeDouble(y / 32D); double z = input.readInt(); output.writeDouble(z / 32D); byte pitch = input.readByte(); output.writeByte(pitch); byte yaw = input.readByte(); output.writeByte(yaw); // next field is Current Item, this was removed in 1.9 so we'll ignore it input.readShort(); transformMetadata(id, input, output); return; } if (packet == PacketType.PLAY_MAP) { int damage = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(damage, output); byte scale = input.readByte(); output.writeByte(scale); output.writeBoolean(true); output.writeBytes(input); return; } if (packet == PacketType.PLAY_ENTITY_EFFECT) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); byte effectID = input.readByte(); output.writeByte(effectID); byte amplifier = input.readByte(); output.writeByte(amplifier); int duration = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(duration, output); // we need to write as a byte instead of boolean boolean hideParticles = input.readBoolean(); output.writeByte(hideParticles ? plugin.isNewEffectIndicator() ? 2 : 1 : 0); return; } if (packet == PacketType.PLAY_TEAM) { String teamName = PacketUtil.readString(input); PacketUtil.writeString(teamName, output); byte mode = input.readByte(); output.writeByte(mode); if (mode == 0 || mode == 2) { PacketUtil.writeString(PacketUtil.readString(input), output); PacketUtil.writeString(PacketUtil.readString(input), output); PacketUtil.writeString(PacketUtil.readString(input), output); output.writeByte(input.readByte()); PacketUtil.writeString(PacketUtil.readString(input), output); PacketUtil.writeString(plugin.isPreventCollision() ? "never" : "", output); // collission rule :) output.writeByte(input.readByte()); } if (mode == 0 || mode == 3 || mode == 4) { // add players int count = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(count, output); for (int i = 0; i < count; i++) { String name = PacketUtil.readString(input); if (autoTeam && name.equalsIgnoreCase(info.getUsername())) { if (mode == 4) { // since removing add to auto team plugin.run(new Runnable() { @Override public void run() { sendTeamPacket(true); } }, false); } else { // since adding remove from auto team sendTeamPacket(false); } } PacketUtil.writeString(name, output); } } output.writeBytes(input); return; } if (packet == PacketType.PLAY_UPDATE_BLOCK_ENTITY) { long[] pos = PacketUtil.readBlockPosition(input); PacketUtil.writeBlockPosition(output, pos[0], pos[1], pos[2]); int action = input.readUnsignedByte(); output.writeByte(action); if (action == 1) { // update spawner try { int index = input.readerIndex(); CompoundTag tag = PacketUtil.readNBT(input); if (tag != null && tag.contains("EntityId")) { String entity = (String) tag.get("EntityId").getValue(); CompoundTag spawn = new CompoundTag("SpawnData"); spawn.put(new StringTag("id", entity)); tag.put(spawn); PacketUtil.writeNBT(output, tag); } else if (tag != null) { // EntityID does not exist CompoundTag spawn = new CompoundTag("SpawnData"); spawn.put(new StringTag("id", "AreaEffectCloud")); //Make spawners show up as empty when no EntityId is given. tag.put(spawn); PacketUtil.writeNBT(output, spawn); } else { //There doesn't exist any NBT tag input.readerIndex(index); output.writeBytes(input, input.readableBytes()); } } catch (IOException e) { e.printStackTrace(); } return; } if (action == 2) { //Update commandblock throw new CancelException(); //Only update if player interact with commandblock (The commandblock window will update every time this packet is sent, this would prevent you from change things that update every tick) } output.writeBytes(input, input.readableBytes()); return; } if (packet == PacketType.PLAY_CHUNK_DATA) { // Read chunk ChunkManager chunkManager = info.getChunkManager(); Chunk chunk = chunkManager.readChunk(input); if (chunk == null) { throw new CancelException(); } // Write chunk chunkManager.writeChunk(chunk, output); return; } output.writeBytes(input); } private void sendTeamPacket(boolean b) { ByteBuf buf = info.getChannel().alloc().buffer(); PacketUtil.writeVarInt(PacketType.PLAY_TEAM.getNewPacketID(), buf); PacketUtil.writeString("viaversion", buf); // Use viaversion as name if (b) { // add if (!teamExists) { buf.writeByte(0); // make team PacketUtil.writeString("viaversion", buf); PacketUtil.writeString("", buf); // prefix PacketUtil.writeString("", buf); // suffix buf.writeByte(0); // friendly fire PacketUtil.writeString("", buf); // nametags PacketUtil.writeString("never", buf); // collision rule :) buf.writeByte(0); // color } else buf.writeByte(3); PacketUtil.writeVarInt(1, buf); // player count PacketUtil.writeString(info.getUsername(), buf); } else { buf.writeByte(1); // remove team } teamExists = b; info.sendRawPacket(buf); } private void transformMetadata(int entityID, ByteBuf input, ByteBuf output) throws CancelException { EntityType type = clientEntityTypes.get(entityID); if (type == null) { System.out.println("Unable to get entity for ID: " + entityID); output.writeByte(255); return; } List<MetadataRewriter.Entry> list = MetadataRewriter.readMetadata1_8(type, input); for (MetadataRewriter.Entry entry : list) { handleMetadata(entityID, entry, type); } // Fix: wither (crash fix) if (type == EntityType.WITHER) { // Remove custom value if already exist Iterator<Entry> it = list.iterator(); while (it.hasNext()) { Entry e = it.next(); if (e.getOldID() == 10) { it.remove(); } } list.add(new Entry(MetaIndex.WITHER_PROPERTIES, (byte) 0, 10)); } // Fix: Dragon (crash fix) if (type == EntityType.ENDER_DRAGON) { // Remove custom value if already exist Iterator<Entry> it = list.iterator(); while (it.hasNext()) { Entry e = it.next(); if (e.getOldID() == 11) { it.remove(); } } list.add(new Entry(MetaIndex.ENDERDRAGON_PHASE, (byte) 0, 11)); } MetadataRewriter.writeMetadata1_9(type, list, output); } private void handleMetadata(int entityID, MetadataRewriter.Entry entry, EntityType type) { // This handles old IDs if (type == EntityType.PLAYER) { if (entry.getOldID() == 0) { // Byte byte data = (byte) entry.getValue(); if (entityID != info.getEntityID() && plugin.isShieldBlocking()) { if ((data & 0x10) == 0x10) { if (validBlocking.contains(entityID)) { ItemSlotRewriter.ItemStack shield = new ItemSlotRewriter.ItemStack(); shield.id = 442; shield.amount = 1; shield.data = 0; sendSecondHandItem(entityID, shield); } } else { sendSecondHandItem(entityID, null); } } } } if (type == EntityType.ARMOR_STAND && plugin.isHologramPatch()) { if (entry.getOldID() == 0) { byte data = (byte) entry.getValue(); if ((data & 0x20) == 0x20) { if (!knownHolograms.contains(entityID)) { knownHolograms.add(entityID); // Send movement ByteBuf buf = info.getChannel().alloc().buffer(); PacketUtil.writeVarInt(PacketType.PLAY_ENTITY_RELATIVE_MOVE.getNewPacketID(), buf); PacketUtil.writeVarInt(entityID, buf); buf.writeShort(0); buf.writeShort((short) (128D * (plugin.getHologramYOffset() * 32D))); buf.writeShort(0); buf.writeBoolean(true); info.sendRawPacket(buf, false); } } } } // Boss bar if (plugin.isBossbarPatch()) { if (type == EntityType.ENDER_DRAGON || type == EntityType.WITHER) { if (entry.getOldID() == 2) { BossBar bar = bossBarMap.get(entityID); String title = (String) entry.getValue(); title = title.isEmpty() ? (type == EntityType.ENDER_DRAGON ? "Ender Dragon" : "Wither") : title; if (bar == null) { bar = ViaVersion.getInstance().createBossBar(title, BossColor.PINK, BossStyle.SOLID); bossBarMap.put(entityID, bar); bar.addPlayer(info.getPlayer()); bar.show(); } else { bar.setTitle(title); } } else if (entry.getOldID() == 6 && !plugin.isBossbarAntiflicker()) { // If anti flicker is enabled, don't update health BossBar bar = bossBarMap.get(entityID); // Make health range between 0 and 1 float maxHealth = type == EntityType.ENDER_DRAGON ? 200.0f : 300.0f; float health = Math.max(0.0f, Math.min(((float) entry.getValue()) / maxHealth, 1.0f)); if (bar == null) { String title = type == EntityType.ENDER_DRAGON ? "Ender Dragon" : "Wither"; bar = ViaVersion.getInstance().createBossBar(title, health, BossColor.PINK, BossStyle.SOLID); bossBarMap.put(entityID, bar); bar.addPlayer(info.getPlayer()); bar.show(); } else { bar.setHealth(health); } } } } } private UUID getUUID(int id) { if (uuidMap.containsKey(id)) { return uuidMap.get(id); } else { UUID uuid = UUID.randomUUID(); uuidMap.put(id, uuid); return uuid; } } private void sendSecondHandItem(int entityID, ItemSlotRewriter.ItemStack o) { ByteBuf buf = info.getChannel().alloc().buffer(); PacketUtil.writeVarInt(PacketType.PLAY_ENTITY_EQUIPMENT.getNewPacketID(), buf); PacketUtil.writeVarInt(entityID, buf); PacketUtil.writeVarInt(1, buf); // slot // write shield try { ItemSlotRewriter.writeItemStack(o, buf); } catch (IOException e) { e.printStackTrace(); } info.sendRawPacket(buf, true); } }
package us.myles.ViaVersion.transformers; import com.google.gson.Gson; import com.google.gson.JsonObject; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import org.bukkit.Bukkit; import org.bukkit.entity.Entity; import org.spacehq.mc.protocol.data.game.chunk.Column; import org.spacehq.mc.protocol.util.NetUtil; import us.myles.ViaVersion.*; import us.myles.ViaVersion.handlers.ViaVersionInitializer; import us.myles.ViaVersion.metadata.MetaIndex; import us.myles.ViaVersion.metadata.NewType; import us.myles.ViaVersion.metadata.SoundEffect; import us.myles.ViaVersion.metadata.Type; import us.myles.ViaVersion.packets.PacketType; import us.myles.ViaVersion.packets.State; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.charset.Charset; import java.util.*; public class OutgoingTransformer { private static Gson gson = new Gson(); private final Channel channel; private final ConnectionInfo info; private final ViaVersionInitializer init; private boolean cancel = false; private Map<Integer, UUID> uuidMap = new HashMap<Integer, UUID>(); public OutgoingTransformer(Channel channel, ConnectionInfo info, ViaVersionInitializer init) { this.channel = channel; this.info = info; this.init = init; } public void transform(int packetID, ByteBuf input, ByteBuf output) throws CancelException { if (cancel) { throw new CancelException(); } PacketType packet = PacketType.getOutgoingPacket(info.getState(), packetID); if (packet == null) { throw new RuntimeException("Outgoing Packet not found? " + packetID + " State: " + info.getState() + " Version: " + info.getProtocol()); } // if (packet != PacketType.PLAY_CHUNK_DATA && packet != PacketType.PLAY_KEEP_ALIVE && packet != PacketType.PLAY_TIME_UPDATE && (!packet.name().toLowerCase().contains("move") && !packet.name().contains("look"))) // System.out.println("Packet Type: " + packet + " Original ID: " + packetID + " State:" + info.getState()); if (packet.getPacketID() != -1) { packetID = packet.getNewPacketID(); } // By default no transform PacketUtil.writeVarInt(packetID, output); if (packet == PacketType.PLAY_NAMED_SOUND_EFFECT) { String name = PacketUtil.readString(input); SoundEffect effect = SoundEffect.getByName(name); int catid = 0; String newname = name; if(effect != null) { catid = effect.getCategory().getId(); newname = effect.getNewName(); } PacketUtil.writeString(newname, output); PacketUtil.writeVarInt(catid, output); output.writeBytes(input); } if (packet == PacketType.PLAY_ATTACH_ENTITY) { int id = input.readInt(); output.writeInt(id); int target = input.readInt(); output.writeInt(target); return; } if (packet == PacketType.PLAY_ENTITY_TELEPORT) { // Port this so that it relative moves :P int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); int x = input.readInt(); output.writeDouble(x / 32D); int y = input.readInt(); output.writeDouble(y / 32D); int z = input.readInt(); output.writeDouble(z / 32D); byte yaw = input.readByte(); output.writeByte(yaw); byte pitch = input.readByte(); output.writeByte(pitch); boolean onGround = input.readBoolean(); output.writeBoolean(onGround); return; } if (packet == PacketType.PLAY_ENTITY_LOOK_MOVE) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); int x = input.readByte(); output.writeShort(x * 128); int y = input.readByte(); output.writeShort(y * 128); int z = input.readByte(); output.writeShort(z * 128); byte yaw = input.readByte(); output.writeByte(yaw); byte pitch = input.readByte(); output.writeByte(pitch); boolean onGround = input.readBoolean(); output.writeBoolean(onGround); return; } if (packet == PacketType.PLAY_ENTITY_RELATIVE_MOVE) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); short x = (short) (input.readByte()); output.writeShort(x * 128); short y = (short) (input.readByte()); output.writeShort(y * 128); short z = (short) (input.readByte()); output.writeShort(z * 128); boolean onGround = input.readBoolean(); output.writeBoolean(onGround); return; } // If login success if (packet == PacketType.LOGIN_SUCCESS) { info.setState(State.PLAY); } if (packet == PacketType.LOGIN_SETCOMPRESSION) { int factor = PacketUtil.readVarInt(input); info.setCompression(factor); PacketUtil.writeVarInt(factor, output); return; } if (packet == PacketType.STATUS_RESPONSE) { String original = PacketUtil.readString(input); JsonObject object = gson.fromJson(original, JsonObject.class); object.get("version").getAsJsonObject().addProperty("protocol", info.getProtocol()); PacketUtil.writeString(gson.toJson(object), output); return; } if (packet == PacketType.LOGIN_SUCCESS) { String uu = PacketUtil.readString(input); PacketUtil.writeString(uu, output); info.setUUID(UUID.fromString(uu)); output.writeBytes(input); return; } if (packet == PacketType.PLAY_PLAYER_POSITION_LOOK) { output.writeBytes(input); PacketUtil.writeVarInt(0, output); return; } if (packet == PacketType.PLAY_ENTITY_EQUIPMENT) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); short slot = input.readShort(); if (slot > 0) { slot += 1; // add 1 so it's now 2-5 } PacketUtil.writeVarInt(slot, output); output.writeBytes(input); } if (packet == PacketType.PLAY_ENTITY_METADATA) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); try { List dw = ReflectionUtil.get(info.getLastPacket(), "b", List.class); // get entity via entityID, not preferred but we need it. Entity entity = Core.getEntity(info.getUUID(), id); if (entity != null) { transformMetadata(entity, dw, output); } else { // Died before we could get to it. rip throw new CancelException(); } } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return; } if (packet == PacketType.PLAY_SPAWN_OBJECT) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); PacketUtil.writeUUID(getUUID(id), output); byte type = input.readByte(); output.writeByte(type); double x = input.readInt(); output.writeDouble(x / 32D); double y = input.readInt(); output.writeDouble(y / 32D); double z = input.readInt(); output.writeDouble(z / 32D); byte pitch = input.readByte(); output.writeByte(pitch); byte yaw = input.readByte(); output.writeByte(yaw); int data = input.readInt(); output.writeInt(data); short vX = input.readableBytes() >= 16 ? input.readShort() : 0; output.writeShort(vX); short vY = input.readableBytes() >= 16 ? input.readShort() : 0; output.writeShort(vY); short vZ = input.readableBytes() >= 16 ? input.readShort() : 0; output.writeShort(vZ); return; } if (packet == PacketType.PLAY_SPAWN_XP_ORB) { // TODO: Verify int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); double x = input.readInt(); output.writeDouble(x / 32D); double y = input.readInt(); output.writeDouble(y / 32D); double z = input.readInt(); output.writeDouble(z / 32D); short data = input.readShort(); output.writeShort(data); return; } if (packet == PacketType.PLAY_SPAWN_MOB) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); PacketUtil.writeUUID(getUUID(id), output); short type = input.readUnsignedByte(); output.writeByte(type); double x = input.readInt(); output.writeDouble(x / 32D); double y = input.readInt(); output.writeDouble(y / 32D); double z = input.readInt(); output.writeDouble(z / 32D); byte yaw = input.readByte(); output.writeByte(yaw); byte pitch = input.readByte(); output.writeByte(pitch); byte headPitch = input.readByte(); output.writeByte(headPitch); short vX = input.readShort(); output.writeShort(vX); short vY = input.readShort(); output.writeShort(vY); short vZ = input.readShort(); output.writeShort(vZ); try { Object dataWatcher = ReflectionUtil.get(info.getLastPacket(), "l", ReflectionUtil.nms("DataWatcher")); transformMetadata(dataWatcher, output); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return; } if (packet == PacketType.PLAY_UPDATE_SIGN) { Long location = input.readLong(); output.writeLong(location); for (int i = 0; i < 4; i++) { String line = PacketUtil.readString(input); if (line == null || line.equalsIgnoreCase("null")) { line = "{\"text\":\"\"}"; } else { if (!line.startsWith("\"") && !line.startsWith("{")) line = "\"" + line + "\""; if (line.startsWith("\"")) line = "{\"text\":" + line + "}"; } PacketUtil.writeString(line, output); } } if (packet == PacketType.PLAY_SPAWN_PLAYER) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); UUID playerUUID = PacketUtil.readUUID(input); PacketUtil.writeUUID(playerUUID, output); double x = input.readInt(); output.writeDouble(x / 32D); double y = input.readInt(); output.writeDouble(y / 32D); double z = input.readInt(); output.writeDouble(z / 32D); byte pitch = input.readByte(); output.writeByte(pitch); byte yaw = input.readByte(); output.writeByte(yaw); try { Object dataWatcher = ReflectionUtil.get(info.getLastPacket(), "i", ReflectionUtil.nms("DataWatcher")); transformMetadata(dataWatcher, output); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return; } if(packet == PacketType.PLAY_MAP) { int damage = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(damage, output); byte scale = input.readByte(); output.writeByte(scale); output.writeBoolean(true); output.writeBytes(input); return; } if (packet == PacketType.PLAY_TEAM) { String teamName = PacketUtil.readString(input); PacketUtil.writeString(teamName, output); byte mode = input.readByte(); output.writeByte(mode); if (mode == 0 || mode == 2) { PacketUtil.writeString(PacketUtil.readString(input), output); PacketUtil.writeString(PacketUtil.readString(input), output); PacketUtil.writeString(PacketUtil.readString(input), output); output.writeByte(input.readByte()); PacketUtil.writeString(PacketUtil.readString(input), output); PacketUtil.writeString("", output); // collission rule :) } output.writeBytes(input); return; } if (packet == PacketType.PLAY_CHUNK_DATA) { // We need to catch unloading chunk packets as defined by wiki.vg // To unload chunks, send this packet with Ground-Up Continuous=true and no 16^3 chunks (eg. Primary Bit Mask=0) int chunkX = input.readInt(); int chunkZ = input.readInt(); output.writeInt(chunkX); output.writeInt(chunkZ); boolean groundUp = input.readBoolean(); output.writeBoolean(groundUp); int bitMask = input.readUnsignedShort(); if (bitMask == 0) { output.clear(); PacketUtil.writeVarInt(PacketType.PLAY_UNLOAD_CHUNK.getNewPacketID(), output); output.writeInt(chunkX); output.writeInt(chunkZ); return; } int size = PacketUtil.readVarInt(input); byte[] data = new byte[size]; input.readBytes(data); boolean sk = false; if (info.getLastPacket().getClass().getName().endsWith("PacketPlayOutMapChunkBulk")) { try { sk = ReflectionUtil.get(info.getLastPacket(), "d", boolean.class); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } Column read = NetUtil.readOldChunkData(chunkX, chunkZ, groundUp, bitMask, data, true, sk); // Write chunk section array :(( ByteBuf temp = output.alloc().buffer(); try { int bitmask = NetUtil.writeNewColumn(temp, read, groundUp, sk); PacketUtil.writeVarInt(bitmask, output); PacketUtil.writeVarInt(temp.readableBytes(), output); output.writeBytes(temp); } catch (IOException e) { e.printStackTrace(); } return; } output.writeBytes(input); } private void transformMetadata(Object dw, ByteBuf output) { // get entity try { Class<?> nmsClass = ReflectionUtil.nms("Entity"); Object nmsEntity = ReflectionUtil.get(dw, "a", nmsClass); Class<?> craftClass = ReflectionUtil.obc("entity.CraftEntity"); Method bukkitMethod = craftClass.getDeclaredMethod("getEntity", ReflectionUtil.obc("CraftServer"), nmsClass); Object entity = bukkitMethod.invoke(null, Bukkit.getServer(), nmsEntity); transformMetadata((Entity) entity, (List) ReflectionUtil.invoke(dw, "b"), output); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void transformMetadata(Entity entity, List dw, ByteBuf output) { if (dw != null) { short id = -1; int data = -1; Iterator iterator = dw.iterator(); while (iterator.hasNext()) { Object watchableObj = iterator.next(); MetaIndex metaIndex = null; try { metaIndex = MetaIndex.getIndex(entity, (int) ReflectionUtil.invoke(watchableObj, "a")); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } try { if (metaIndex.getNewType() != NewType.Discontinued) { if (metaIndex.getNewType() != NewType.BlockID || id != -1 && data == -1 || id == -1 && data != -1) { // block ID is only written if we have both parts output.writeByte(metaIndex.getNewIndex()); output.writeByte(metaIndex.getNewType().getTypeID()); } Object value = ReflectionUtil.invoke(watchableObj, "b"); switch (metaIndex.getNewType()) { case Byte: // convert from int, byte if (metaIndex.getOldType() == Type.Byte) { output.writeByte(((Byte) value).byteValue()); } if (metaIndex.getOldType() == Type.Int) { output.writeByte(((Integer) value).byteValue()); } break; case OptUUID: String owner = (String) value; UUID toWrite = null; if (owner.length() != 0) { try { toWrite = UUID.fromString(owner); } catch (Exception ignored) { } } output.writeBoolean(toWrite != null); if (toWrite != null) PacketUtil.writeUUID((UUID) value, output); break; case BlockID: // if we have both sources :)) if (metaIndex.getOldType() == Type.Byte) { data = ((Byte) value).byteValue(); } if (metaIndex.getOldType() == Type.Short) { id = ((Short) value).shortValue(); } if (id != -1 && data != -1) { int combined = id << 4 | data; data = -1; id = -1; PacketUtil.writeVarInt(combined, output); } break; case VarInt: // convert from int, short, byte if (metaIndex.getOldType() == Type.Byte) { PacketUtil.writeVarInt(((Byte) value).intValue(), output); } if (metaIndex.getOldType() == Type.Short) { PacketUtil.writeVarInt(((Short) value).intValue(), output); } if (metaIndex.getOldType() == Type.Int) { PacketUtil.writeVarInt(((Integer) value).intValue(), output); } break; case Float: output.writeFloat(((Float) value).floatValue()); break; case String: PacketUtil.writeString((String) value, output); break; case Boolean: output.writeBoolean(((Byte) value).byteValue() != 0); break; case Slot: PacketUtil.writeItem(value, output); break; case Position: output.writeInt((int) ReflectionUtil.invoke(value, "getX")); output.writeInt((int) ReflectionUtil.invoke(value, "getY")); output.writeInt((int) ReflectionUtil.invoke(value, "getZ")); break; case Vector3F: output.writeFloat((float) ReflectionUtil.invoke(value, "getX")); output.writeFloat((float) ReflectionUtil.invoke(value, "getY")); output.writeFloat((float) ReflectionUtil.invoke(value, "getZ")); } } } catch (Exception e) { if (entity != null) { System.out.println("An error occurred with entity meta data for " + entity.getType()); System.out.println("Old ID: " + metaIndex.getIndex() + " New ID: " + metaIndex.getNewIndex()); System.out.println("Old Type: " + metaIndex.getOldType() + " New Type: " + metaIndex.getNewType()); } e.printStackTrace(); } } } output.writeByte(255); } private UUID getUUID(int id) { if (uuidMap.containsKey(id)) { return uuidMap.get(id); } else { UUID uuid = UUID.randomUUID(); uuidMap.put(id, uuid); return uuid; } } }
package zmaster587.advancedRocketry.event; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.lwjgl.opengl.GL11; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ActiveRenderInfo; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer.EnumStatus; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.server.MinecraftServer; import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.Chunk; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent; import net.minecraftforge.event.entity.living.LivingFallEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.entity.player.PlayerSleepInBedEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action; import net.minecraftforge.event.entity.player.PlayerOpenContainerEvent; import net.minecraftforge.event.terraingen.PopulateChunkEvent; import net.minecraftforge.event.world.ChunkEvent; import net.minecraftforge.event.world.WorldEvent; import zmaster587.advancedRocketry.achievements.ARAchivements; import zmaster587.advancedRocketry.api.AdvancedRocketryBiomes; import zmaster587.advancedRocketry.api.AdvancedRocketryBlocks; import zmaster587.advancedRocketry.api.AdvancedRocketryItems; import zmaster587.advancedRocketry.api.Configuration; import zmaster587.advancedRocketry.api.IPlanetaryProvider; import zmaster587.advancedRocketry.api.stations.ISpaceObject; import zmaster587.advancedRocketry.atmosphere.AtmosphereHandler; import zmaster587.advancedRocketry.dimension.DimensionManager; import zmaster587.advancedRocketry.dimension.DimensionProperties; import zmaster587.advancedRocketry.network.PacketDimInfo; import zmaster587.advancedRocketry.network.PacketSpaceStationInfo; import zmaster587.advancedRocketry.network.PacketStellarInfo; import zmaster587.advancedRocketry.stations.SpaceObjectManager; import zmaster587.advancedRocketry.util.BiomeHandler; import zmaster587.advancedRocketry.util.TransitionEntity; import zmaster587.advancedRocketry.world.provider.WorldProviderPlanet; import zmaster587.advancedRocketry.world.util.TeleporterNoPortal; import zmaster587.libVulpes.LibVulpes; import zmaster587.libVulpes.api.IModularArmor; import zmaster587.libVulpes.api.LibVulpesItems; import zmaster587.libVulpes.network.PacketHandler; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.eventhandler.Event.Result; import cpw.mods.fml.common.gameevent.PlayerEvent; import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerRespawnEvent; import cpw.mods.fml.common.gameevent.TickEvent; import cpw.mods.fml.common.network.FMLNetworkEvent; import cpw.mods.fml.common.network.FMLNetworkEvent.ClientDisconnectionFromServerEvent; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class PlanetEventHandler { public static long time = 0; private static long endTime, duration; private static Map<Long,TransitionEntity> transitionMap = new HashMap<Long,TransitionEntity>(); public static void addDelayedTransition(long tick, TransitionEntity entity) { transitionMap.put(tick, entity); } @SubscribeEvent public void sleepEvent(PlayerSleepInBedEvent event) { if(event.entity.worldObj.provider instanceof WorldProviderPlanet && AtmosphereHandler.hasAtmosphereHandler(event.entity.worldObj.provider.dimensionId) && !AtmosphereHandler.getOxygenHandler(event.entity.worldObj.provider.dimensionId).getAtmosphereType(event.x, event.y, event.z).isBreathable()) { event.result = EnumStatus.OTHER_PROBLEM; } } @SubscribeEvent public void onCrafting(PlayerEvent.ItemCraftedEvent event) { if(event.crafting != null) { Item item = event.crafting.getItem(); if(item == LibVulpesItems.itemHoloProjector) event.player.triggerAchievement(ARAchivements.holographic); else if(item == Item.getItemFromBlock(AdvancedRocketryBlocks.blockRollingMachine)) event.player.triggerAchievement(ARAchivements.rollin); else if(item == Item.getItemFromBlock(AdvancedRocketryBlocks.blockCrystallizer)) event.player.triggerAchievement(ARAchivements.crystalline); else if(item == Item.getItemFromBlock(AdvancedRocketryBlocks.blockLathe)) event.player.triggerAchievement(ARAchivements.spinDoctor); else if(item ==Item.getItemFromBlock(AdvancedRocketryBlocks.blockElectrolyser)) event.player.triggerAchievement(ARAchivements.electrifying); else if(item == Item.getItemFromBlock(AdvancedRocketryBlocks.blockArcFurnace)) event.player.triggerAchievement(ARAchivements.feelTheHeat); else if(item == Item.getItemFromBlock(AdvancedRocketryBlocks.blockWarpCore)) event.player.triggerAchievement(ARAchivements.feelTheHeat); } } @SubscribeEvent public void onPickup(PlayerEvent.ItemPickupEvent event) { if(event.pickedUp != null) { Item item = event.pickedUp.getEntityItem().getItem(); zmaster587.libVulpes.api.material.Material mat = LibVulpes.materialRegistry.getMaterialFromItemStack( event.pickedUp.getEntityItem()); if(mat != null && mat.getUnlocalizedName().contains("Dilithium")) event.player.triggerAchievement(ARAchivements.dilithiumCrystals); } } //Handle gravity @SubscribeEvent public void playerTick(LivingUpdateEvent event) { if(event.entity.worldObj.isRemote && event.entity.posY > 260 && event.entity.posY < 270 && event.entity.motionY < -.1) { RocketEventHandler.destroyOrbitalTextures(event.entity.worldObj); } if(event.entity.worldObj.provider instanceof IPlanetaryProvider && !event.entity.isInWater()) { IPlanetaryProvider planet = (IPlanetaryProvider)event.entity.worldObj.provider; if(!(event.entity instanceof EntityPlayer) || !((EntityPlayer)event.entity).capabilities.isFlying) { //event.entity.motionY += 0.075f - planet.getGravitationalMultiplier((int)event.entity.posX, (int)event.entity.posZ)*0.075f; } } else if(event.entity.worldObj.provider.dimensionId == 0) { if(!(event.entity instanceof EntityPlayer) || !((EntityPlayer)event.entity).capabilities.isFlying) { //event.entity.motionY += 0.075f - DimensionManager.overworldProperties.gravitationalMultiplier*0.075f; } } if(!event.entity.worldObj.isRemote && event.entity.worldObj.getTotalWorldTime() % 20 ==0 && event.entity instanceof EntityPlayer) { if(DimensionManager.getInstance().getDimensionProperties(event.entity.worldObj.provider.dimensionId).getName().equals("Luna") && event.entity.getDistanceSq(67, 80, 2347) < 512 ) { ((EntityPlayer)event.entity).triggerAchievement(ARAchivements.weReallyWentToTheMoon); } } } @SubscribeEvent public void blockPlaceEvent(PlayerInteractEvent event) { ForgeDirection direction = ForgeDirection.getOrientation(event.face); if(!event.world.isRemote && Action.RIGHT_CLICK_BLOCK == event.action && event.entityPlayer != null && AtmosphereHandler.getOxygenHandler(event.world.provider.dimensionId) != null && !AtmosphereHandler.getOxygenHandler(event.world.provider.dimensionId).getAtmosphereType(event.x + direction.offsetX, event.y + direction.offsetY, event.z + direction.offsetZ).allowsCombustion()) { if(event.entityPlayer.getCurrentEquippedItem() != null) { if(event.entityPlayer.getCurrentEquippedItem().getItem() == Item.getItemFromBlock(Blocks.torch) && event.world.getBlock(event.x, event.y, event.z).isSideSolid(event.world, event.x, event.y, event.z, direction)) { event.setCanceled(true); event.world.setBlock(event.x + direction.offsetX, event.y + direction.offsetY, event.z + direction.offsetZ, AdvancedRocketryBlocks.blockUnlitTorch); } else if(event.entityPlayer.getCurrentEquippedItem().getItem() == Items.flint_and_steel || event.entityPlayer.getCurrentEquippedItem().getItem() == Items.fire_charge || event.entityPlayer.getCurrentEquippedItem().getItem() == Items.blaze_powder || event.entityPlayer.getCurrentEquippedItem().getItem() == Items.blaze_rod || event.entityPlayer.getCurrentEquippedItem().getItem() == Items.lava_bucket) event.setCanceled(true); } } if(!event.world.isRemote && event.entityPlayer != null && event.entityPlayer.getCurrentEquippedItem() != null && event.entityPlayer.getCurrentEquippedItem().getItem() == Item.getItemFromBlock(AdvancedRocketryBlocks.blockGenericSeat) && event.world.getBlock(event.x, event.y, event.z) == Blocks.tnt) { event.entityPlayer.triggerAchievement(ARAchivements.beerOnTheSun); } } @EventHandler public void disconnected(ClientDisconnectionFromServerEvent event) { zmaster587.advancedRocketry.dimension.DimensionManager.getInstance().unregisterAllDimensions(); } /*@SubscribeEvent public void entityRegister(EntityConstructing event) { if(event.entity instanceof EntityPlayer) { event.entity.registerExtendedProperties(PlayerDataHandler.IDENTIFIER, new PlayerDataHandler()); } }*/ //TODO move //Has weak refs so if the player gets killed/logsout etc the entry doesnt stay trapped in RAM private static HashSet<WeakReference<EntityPlayer>> inventoryCheckPlayerBypassMap = new HashSet<WeakReference<EntityPlayer>>(); public static void addPlayerToInventoryBypass(EntityPlayer player) { inventoryCheckPlayerBypassMap.add(new WeakReference<>(player)); } public static void removePlayerFromInventoryBypass(EntityPlayer player) { Iterator<WeakReference<EntityPlayer>> iter = inventoryCheckPlayerBypassMap.iterator(); while(iter.hasNext()) { WeakReference<EntityPlayer> player2 = iter.next(); if(player2.get() == player || player2.get() == null) iter.remove(); } } public static boolean canPlayerBypassInvChecks(EntityPlayer player) { Iterator<WeakReference<EntityPlayer>> iter = inventoryCheckPlayerBypassMap.iterator(); while(iter.hasNext()) { WeakReference<EntityPlayer> player2 = iter.next(); if(player2.get() == player) return true; } return false; } @SubscribeEvent public void containerOpen(PlayerOpenContainerEvent event) { //event.entityPlayer.openContainer if(canPlayerBypassInvChecks(event.entityPlayer)) if(event.entityPlayer.openContainer.windowId == 0) removePlayerFromInventoryBypass(event.entityPlayer); else event.setResult(Result.ALLOW); } //Tick dimensions, needed for satellites, and guis @SubscribeEvent public void tick(TickEvent.ServerTickEvent event) { //Tick satellites if(event.phase == event.phase.END) { DimensionManager.getInstance().tickDimensions(); time++; if(!transitionMap.isEmpty()) { Iterator<Entry<Long, TransitionEntity>> itr = transitionMap.entrySet().iterator(); while(itr.hasNext()) { Entry<Long, TransitionEntity> entry = itr.next(); TransitionEntity ent = entry.getValue(); if(ent.entity.worldObj.getTotalWorldTime() >= entry.getKey()) { ent.entity.setLocationAndAngles(ent.location.x, ent.location.y, ent.location.z, ent.entity.rotationYaw, ent.entity.rotationPitch); MinecraftServer.getServer().getConfigurationManager().transferPlayerToDimension((EntityPlayerMP)ent.entity, ent.dimId, new TeleporterNoPortal(MinecraftServer.getServer().worldServerForDimension(ent.dimId))); ent.entity.mountEntity(ent.entity2); itr.remove(); } } } } } @SubscribeEvent public void tickClient(TickEvent.ClientTickEvent event) { if(event.phase == event.phase.END) DimensionManager.getInstance().tickDimensionsClient(); } //Make sure the player receives data about the dimensions @SubscribeEvent public void playerLoggedInEvent(FMLNetworkEvent.ServerConnectionFromClientEvent event) { //Make sure stars are sent first for(int i : DimensionManager.getInstance().getStarIds()) { PacketHandler.sendToDispatcher(new PacketStellarInfo(i, DimensionManager.getInstance().getStar(i)), event.manager); } for(int i : DimensionManager.getInstance().getregisteredDimensions()) { PacketHandler.sendToDispatcher(new PacketDimInfo(i, DimensionManager.getInstance().getDimensionProperties(i)), event.manager); } for(ISpaceObject obj : SpaceObjectManager.getSpaceManager().getSpaceObjects()) { PacketHandler.sendToDispatcher(new PacketSpaceStationInfo(obj.getId(), obj), event.manager); } PacketHandler.sendToDispatcher(new PacketDimInfo(0, DimensionManager.getInstance().getDimensionProperties(0)), event.manager); } // Used to save extra biome data /*@SubscribeEvent public void worldLoadEvent(WorldEvent.Load event) { if(event.world.provider instanceof ProviderPlanet && DimensionManager.getInstance().getDimensionProperties(event.world.provider.dimensionId).biomeProperties == null) { DimensionManager.getInstance().getDimensionProperties(event.world.provider.dimensionId).biomeProperties = new ExtendedBiomeProperties(event.world); } } // Used to load extra biome data @SubscribeEvent public void saveExtraData(ChunkDataEvent.Save event) { if(event.world.provider instanceof ProviderPlanet) { NBTTagCompound nbt = event.getData(); int xPos = event.getChunk().xPosition;//nbt.getInteger("xPos"); int zPos = event.getChunk().zPosition;//nbt.getInteger("zPos"); ChunkProperties properties = DimensionManager.getInstance().getDimensionProperties(event.world.provider.dimensionId).biomeProperties.getChunkPropertiesFromChunkCoords(xPos, zPos); nbt.setIntArray("ExtendedBiomeArray", properties.getBlockBiomeArray()); } } @SubscribeEvent public void loadExtraData(ChunkDataEvent.Load event) { if(event.world.provider instanceof ProviderPlanet) { NBTTagCompound nbt = event.getData(); int xPos = event.getChunk().xPosition;//nbt.getInteger("xPos"); int zPos = event.getChunk().zPosition;//nbt.getInteger("zPos"); ChunkProperties properties = DimensionManager.getInstance().getDimensionProperties(event.world.provider.dimensionId).biomeProperties.getChunkPropertiesFromChunkCoords(xPos, zPos); properties.setBlockBiomeArray(event.getData().getIntArray("ExtendedBiomeArray")); } } */ @SubscribeEvent public void worldLoadEvent(WorldEvent.Load event) { if(!event.world.isRemote) AtmosphereHandler.registerWorld(event.world.provider.dimensionId); } @SubscribeEvent public void worldUnloadEvent(WorldEvent.Unload event) { if(!event.world.isRemote) AtmosphereHandler.unregisterWorld(event.world.provider.dimensionId); } /** * Starts a burst, used for move to warp effect * @param endTime * @param duration */ @SideOnly(Side.CLIENT) public static void runBurst(long endTime, long duration) { PlanetEventHandler.endTime = endTime; PlanetEventHandler.duration = duration; } //Handle fog density and color @SubscribeEvent @SideOnly(Side.CLIENT) public void fogColor(net.minecraftforge.client.event.EntityViewRenderEvent.FogColors event) { Block block = ActiveRenderInfo.getBlockAtEntityViewpoint(event.entity.worldObj, event.entity, (float)event.renderPartialTicks); if(block.getMaterial() == Material.water) return; DimensionProperties properties = DimensionManager.getInstance().getDimensionProperties(event.entity.dimension); if(properties != null) { float fog = properties.getAtmosphereDensityAtHeight(event.entity.posY); if(event.entity.worldObj.provider instanceof IPlanetaryProvider) { Vec3 color = event.entity.worldObj.provider.getSkyColor(event.entity, 0f); event.red = (float) Math.min(color.xCoord*1.4f,1f); event.green = (float) Math.min(color.yCoord*1.4f, 1f); event.blue = (float) Math.min(color.zCoord*1.4f, 1f); } if(endTime > 0) { double amt = (endTime - Minecraft.getMinecraft().theWorld.getTotalWorldTime()) / (double)duration; if(amt < 0) { endTime = 0; } else event.green = event.blue = event.red = (float)amt; } else { event.red *= fog; event.green *= fog; event.blue *= fog; } } } @SubscribeEvent public void serverTickEvent(TickEvent.WorldTickEvent event) { if(zmaster587.advancedRocketry.api.Configuration.allowTerraforming && event.world.provider.getClass() == WorldProviderPlanet.class) { if(DimensionManager.getInstance().getDimensionProperties(event.world.provider.dimensionId).isTerraformed()) { List<Chunk> list = ((WorldServer)event.world).theChunkProviderServer.loadedChunks; if(list.size() > 0) { for(int i = 0; i < Configuration.terraformingBlockSpeed; i++) { Chunk chunk = list.get(event.world.rand.nextInt(list.size())); int coord = event.world.rand.nextInt(256); int x = (coord & 0xF) + chunk.xPosition*16; int z = (coord >> 4) + chunk.zPosition*16; BiomeHandler.changeBiome(event.world, ((WorldProviderPlanet)event.world.provider).chunkMgrTerraformed.getBiomeGenAt(x,z).biomeID, x, z); } } } } } @SubscribeEvent public void chunkLoadEvent(PopulateChunkEvent.Post event) { if(zmaster587.advancedRocketry.api.Configuration.allowTerraforming && event.world.provider.getClass() == WorldProviderPlanet.class) { if(DimensionManager.getInstance().getDimensionProperties(event.world.provider.dimensionId).isTerraformed()) { Chunk chunk = event.world.getChunkFromChunkCoords(event.chunkX, event.chunkZ); modifyChunk(event.world, (WorldProviderPlanet) event.world.provider, chunk); } } } @SubscribeEvent public void chunkLoadEvent(ChunkEvent.Load event) { } public static void modifyChunk(World world ,WorldProviderPlanet provider, Chunk chunk) { for(int x = 0; x < 16; x++) { for(int z = 0; z < 16; z++) { BiomeHandler.changeBiome(world, provider.chunkMgrTerraformed.getBiomeGenAt(x + chunk.xPosition*16,z + chunk.zPosition*16).biomeID, chunk, x + chunk.xPosition* 16, z + chunk.zPosition*16); } } } static final ItemStack component = new ItemStack(AdvancedRocketryItems.itemUpgrade, 1, 4); @SubscribeEvent @SideOnly(Side.CLIENT) public void fogColor(net.minecraftforge.client.event.EntityViewRenderEvent.RenderFogEvent event) { if(false || event.fogMode == -1) { return; } DimensionProperties properties = DimensionManager.getInstance().getDimensionProperties(event.entity.dimension); if(properties != null && event.block != Blocks.water && event.block != Blocks.lava) {//& properties.atmosphereDensity > 125) { float fog = properties.getAtmosphereDensityAtHeight(event.entity.posY); //GL11.glFogi(GL11.GL_FOG_MODE, GL11.GL_EXP); GL11.glFogi(GL11.GL_FOG_MODE, GL11.GL_LINEAR); float f1 = event.farPlaneDistance; float near; float far; int atmosphere = properties.getAtmosphereDensity(); ItemStack armor = Minecraft.getMinecraft().thePlayer.getCurrentArmor(3); if(armor != null && armor.getItem() instanceof IModularArmor) { for(ItemStack i : ((IModularArmor)armor.getItem()).getComponents(armor)) { if(i.isItemEqual(component)) { atmosphere = Math.min(atmosphere, 100); break; } } } //Check environment if(AtmosphereHandler.currentPressure != -1) { atmosphere = AtmosphereHandler.currentPressure; } if(atmosphere > 100) { near = 0.75f*f1*(2.00f - atmosphere*atmosphere/10000f); far = f1; } else { near = 0.75f*f1*(2.00f -atmosphere/100f); far = f1*(2.002f - atmosphere/100f); } GL11.glFogf(GL11.GL_FOG_START, near); GL11.glFogf(GL11.GL_FOG_END, far); GL11.glFogf(GL11.GL_FOG_DENSITY, 0); //event.setCanceled(false); } } //Saves NBT data @SubscribeEvent public void worldSaveEvent(WorldEvent.Save event) { //TODO: save only the one dimension if(event.world.provider.dimensionId == 0) //DimensionManager.getInstance().getDimensionProperties(event.world.provider.dimensionId). DimensionManager.getInstance().saveDimensions(DimensionManager.filePath); } //Make sure the player doesnt die on low gravity worlds @SubscribeEvent public void fallEvent(LivingFallEvent event) { if(event.entity.worldObj.provider instanceof IPlanetaryProvider) { IPlanetaryProvider planet = (IPlanetaryProvider)event.entity.worldObj.provider; event.distance *= planet.getGravitationalMultiplier((int)event.entity.posX, (int)event.entity.posZ); } } }
package org.fedorahosted.flies.entity.resources; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import org.fedorahosted.flies.entity.Person; import org.hibernate.validator.NotNull; @Entity public class TextUnitCandidate extends AbstractTextUnit{ public static enum Type {Suggestion} public static enum Source {Web,PreviousVersion} private Type type = Type.Suggestion; private Source source = Source.Web; private TextUnitTarget target; private Person translator; public TextUnitCandidate() {} public TextUnitCandidate(TextUnitTarget target) { this.target = target; } @NotNull public Type getType() { return type; } public void setType(Type type) { this.type = type; } public Source getSource() { return source; } @NotNull public void setSource(Source source) { this.source = source; } @ManyToOne @JoinColumn(name="target_id") public TextUnitTarget getTarget() { return target; } public void setTarget(TextUnitTarget target) { this.target = target; } @ManyToOne @JoinColumn(name="translator_id") public Person getTranslator() { return translator; } public void setTranslator(Person translator) { this.translator = translator; } }
package liquibase.diff.output.changelog.core; import liquibase.change.Change; import liquibase.change.ColumnConfig; import liquibase.change.ConstraintsConfig; import liquibase.change.core.CreateTableChange; import liquibase.database.Database; import liquibase.database.core.InformixDatabase; import liquibase.database.core.MSSQLDatabase; import liquibase.database.core.MySQLDatabase; import liquibase.database.core.PostgresDatabase; import liquibase.datatype.DataTypeFactory; import liquibase.datatype.DatabaseDataType; import liquibase.datatype.LiquibaseDataType; import liquibase.datatype.core.DateTimeType; import liquibase.diff.output.DiffOutputControl; import liquibase.diff.output.changelog.AbstractChangeGenerator; import liquibase.diff.output.changelog.ChangeGeneratorChain; import liquibase.diff.output.changelog.MissingObjectChangeGenerator; import liquibase.statement.DatabaseFunction; import liquibase.structure.DatabaseObject; import liquibase.structure.core.Column; import liquibase.structure.core.PrimaryKey; import liquibase.structure.core.Table; import liquibase.structure.core.UniqueConstraint; import liquibase.util.StringUtils; import java.math.BigInteger; import java.util.*; public class MissingTableChangeGenerator extends AbstractChangeGenerator implements MissingObjectChangeGenerator { public static void setDefaultValue(ColumnConfig columnConfig, Column column, Database database) { LiquibaseDataType dataType = DataTypeFactory.getInstance().from(column.getType(), database); Object defaultValue = column.getDefaultValue(); if (defaultValue == null) { // do nothing } else if (column.isAutoIncrement()) { // do nothing } else if (defaultValue instanceof Date) { columnConfig.setDefaultValueDate((Date) defaultValue); } else if (defaultValue instanceof Boolean) { columnConfig.setDefaultValueBoolean(((Boolean) defaultValue)); } else if (defaultValue instanceof Number) { columnConfig.setDefaultValueNumeric(((Number) defaultValue)); } else if (defaultValue instanceof DatabaseFunction) { DatabaseFunction function = (DatabaseFunction) defaultValue; if ("current".equals(function.getValue())) { if (database instanceof InformixDatabase) { if (dataType instanceof DateTimeType) { if ((dataType.getAdditionalInformation() == null) || dataType.getAdditionalInformation() .isEmpty()) { if ((dataType.getParameters() != null) && (dataType.getParameters().length > 0)) { String parameter = String.valueOf(dataType.getParameters()[0]); if ("4365".equals(parameter)) { function = new DatabaseFunction("current year to fraction(3)"); } if ("3594".equals(parameter)) { function = new DatabaseFunction("current year to second"); } if ("3080".equals(parameter)) { function = new DatabaseFunction("current year to minute"); } if ("2052".equals(parameter)) { function = new DatabaseFunction("current year to day"); } } } } } } columnConfig.setDefaultValueComputed(function); } else { String defaultValueString = null; try { defaultValueString = DataTypeFactory.getInstance().from(column.getType(), database).objectToSql(defaultValue, database); } catch (NullPointerException e) { throw e; } if (defaultValueString != null) { defaultValueString = defaultValueString.replaceFirst("'", "").replaceAll("'$", ""); } columnConfig.setDefaultValue(defaultValueString); } columnConfig.setDefaultValueConstraintName(column.getDefaultValueConstraintName()); } @Override public int getPriority(Class<? extends DatabaseObject> objectType, Database database) { if (Table.class.isAssignableFrom(objectType)) { return PRIORITY_DEFAULT; } return PRIORITY_NONE; } @Override public Class<? extends DatabaseObject>[] runAfterTypes() { return null; } @Override public Class<? extends DatabaseObject>[] runBeforeTypes() { return null; } @Override public Change[] fixMissing(DatabaseObject missingObject, DiffOutputControl control, Database referenceDatabase, Database comparisonDatabase, ChangeGeneratorChain chain) { Table missingTable = (Table) missingObject; PrimaryKey primaryKey = missingTable.getPrimaryKey(); List<String> pkColumnList = ((primaryKey != null) ? primaryKey.getColumnNamesAsList() : null); Map<Column, UniqueConstraint> singleUniqueConstraints = getSingleColumnUniqueConstraints(missingTable); CreateTableChange change = createCreateTableChange(); change.setTableName(missingTable.getName()); if (control.getIncludeCatalog()) { change.setCatalogName(missingTable.getSchema().getCatalogName()); } if (control.getIncludeSchema()) { change.setSchemaName(missingTable.getSchema().getName()); } if (missingTable.getRemarks() != null) { change.setRemarks(missingTable.getRemarks()); } if ((missingTable.getTablespace() != null) && comparisonDatabase.supportsTablespaces()) { change.setTablespace(missingTable.getTablespace()); } for (Column column : missingTable.getColumns()) { ColumnConfig columnConfig = new ColumnConfig(); columnConfig.setName(column.getName()); LiquibaseDataType ldt = DataTypeFactory.getInstance().from(column.getType(), referenceDatabase); DatabaseDataType ddt = ldt.toDatabaseDataType(comparisonDatabase); String typeString = ddt.toString(); if (comparisonDatabase instanceof MSSQLDatabase) { typeString = comparisonDatabase.unescapeDataTypeString(typeString); } columnConfig.setType(typeString); if (column.isAutoIncrement()) { columnConfig.setAutoIncrement(true); } boolean primaryKeyOrderMatchesTableOrder = checkPrimaryKeyOrderMatchesTableOrder(missingTable, pkColumnList); ConstraintsConfig constraintsConfig = null; // In MySQL, the primary key must be specified at creation for an autoincrement column if ((pkColumnList != null) && primaryKeyOrderMatchesTableOrder && pkColumnList.contains(column.getName())) { if ((referenceDatabase instanceof MSSQLDatabase) && (primaryKey.getBackingIndex() != null) && (primaryKey.getBackingIndex().getClustered() != null) && !primaryKey.getBackingIndex() .getClustered()) { // have to handle PK as a separate statement } else if ((referenceDatabase instanceof PostgresDatabase) && (primaryKey.getBackingIndex() != null) && (primaryKey.getBackingIndex().getClustered() != null) && primaryKey.getBackingIndex() .getClustered()) { // have to handle PK as a separate statement } else { constraintsConfig = new ConstraintsConfig(); if (shouldAddPrimarykeyToConstraints(missingObject, control, referenceDatabase, comparisonDatabase)) { constraintsConfig.setPrimaryKey(true); constraintsConfig.setPrimaryKeyTablespace(primaryKey.getTablespace()); // MySQL sets some primary key names as PRIMARY which is invalid if ((comparisonDatabase instanceof MySQLDatabase) && "PRIMARY".equals(primaryKey.getName())) { constraintsConfig.setPrimaryKeyName(null); } else { constraintsConfig.setPrimaryKeyName(primaryKey.getName()); } control.setAlreadyHandledMissing(primaryKey); control.setAlreadyHandledMissing(primaryKey.getBackingIndex()); } else { constraintsConfig.setNullable(false); } } } else if ((column.isNullable() != null) && !column.isNullable()) { constraintsConfig = new ConstraintsConfig(); constraintsConfig.setNullable(false); if (!column.shouldValidateNullable()) { constraintsConfig.setShouldValidateNullable(false); } constraintsConfig.setNotNullConstraintName(column.getAttribute("notNullConstraintName", String.class)); } if (referenceDatabase instanceof MySQLDatabase) { UniqueConstraint uniqueConstraint = singleUniqueConstraints.get(column); if (uniqueConstraint != null) { if (!control.alreadyHandledMissing(uniqueConstraint, referenceDatabase)) { if (constraintsConfig == null) { constraintsConfig = new ConstraintsConfig(); } constraintsConfig.setUnique(true); control.setAlreadyHandledMissing(uniqueConstraint); control.setAlreadyHandledMissing(uniqueConstraint.getBackingIndex()); } } } if (constraintsConfig != null) { columnConfig.setConstraints(constraintsConfig); } setDefaultValue(columnConfig, column, referenceDatabase); if (column.getRemarks() != null) { columnConfig.setRemarks(column.getRemarks()); } Column.AutoIncrementInformation autoIncrementInfo = column.getAutoIncrementInformation(); if (autoIncrementInfo != null) { BigInteger startWith = autoIncrementInfo.getStartWith(); BigInteger incrementBy = autoIncrementInfo.getIncrementBy(); String generationType = autoIncrementInfo.getGenerationType(); Boolean defaultOnNull = autoIncrementInfo.getDefaultOnNull(); if ((startWith != null) && !startWith.equals(BigInteger.ONE)) { columnConfig.setStartWith(startWith); } if ((incrementBy != null) && !incrementBy.equals(BigInteger.ONE)) { columnConfig.setIncrementBy(incrementBy); } if (StringUtils.isNotEmpty(generationType)) { columnConfig.setGenerationType(generationType); if (defaultOnNull != null) { columnConfig.setDefaultOnNull(defaultOnNull); } } } change.addColumn(columnConfig); control.setAlreadyHandledMissing(column); } // In SQLite, we must specify the PRIMARY KEY at table creation time return new Change[]{ change }; } private boolean checkPrimaryKeyOrderMatchesTableOrder(Table missingTable, List<String> pkColumnList) { if (pkColumnList == null) { return false; } int lastTableOrder = -1; final List<Column> tableColumnList = missingTable.getColumns(); for (String pkColumnName : pkColumnList) { for (int i = 0; i < tableColumnList.size(); i++) { final Column tableColumn = tableColumnList.get(i); if (Objects.equals(tableColumn.getName(), pkColumnName)) { if (i < lastTableOrder) { return false; } lastTableOrder = i; } } } return true; } private Map<Column, UniqueConstraint> getSingleColumnUniqueConstraints(Table missingTable) { Map<Column, UniqueConstraint> map = new HashMap<>(); List<UniqueConstraint> constraints = missingTable.getUniqueConstraints() == null ? null : missingTable.getUniqueConstraints(); for (UniqueConstraint constraint : constraints) { if (constraint.getColumns().size() == 1) { map.put(constraint.getColumns().get(0), constraint); } } return map; } protected CreateTableChange createCreateTableChange() { return new CreateTableChange(); } public boolean shouldAddPrimarykeyToConstraints(DatabaseObject missingObject, DiffOutputControl control, Database referenceDatabase, Database comparisonDatabase) { return true; } }
package liquibase.diff.output.changelog.core; import liquibase.change.Change; import liquibase.change.ColumnConfig; import liquibase.change.ConstraintsConfig; import liquibase.change.core.CreateTableChange; import liquibase.database.Database; import liquibase.database.core.InformixDatabase; import liquibase.database.core.MSSQLDatabase; import liquibase.database.core.MySQLDatabase; import liquibase.database.core.PostgresDatabase; import liquibase.datatype.DataTypeFactory; import liquibase.datatype.DatabaseDataType; import liquibase.datatype.LiquibaseDataType; import liquibase.datatype.core.DateTimeType; import liquibase.diff.output.DiffOutputControl; import liquibase.diff.output.changelog.AbstractChangeGenerator; import liquibase.diff.output.changelog.ChangeGeneratorChain; import liquibase.diff.output.changelog.MissingObjectChangeGenerator; import liquibase.statement.DatabaseFunction; import liquibase.structure.DatabaseObject; import liquibase.structure.core.Column; import liquibase.structure.core.PrimaryKey; import liquibase.structure.core.Table; import java.math.BigInteger; import java.util.Date; import java.util.List; public class MissingTableChangeGenerator extends AbstractChangeGenerator implements MissingObjectChangeGenerator { public static void setDefaultValue(ColumnConfig columnConfig, Column column, Database database) { LiquibaseDataType dataType = DataTypeFactory.getInstance().from(column.getType(), database); Object defaultValue = column.getDefaultValue(); if (defaultValue == null) { // do nothing } else if (column.isAutoIncrement()) { // do nothing } else if (defaultValue instanceof Date) { columnConfig.setDefaultValueDate((Date) defaultValue); } else if (defaultValue instanceof Boolean) { columnConfig.setDefaultValueBoolean(((Boolean) defaultValue)); } else if (defaultValue instanceof Number) { columnConfig.setDefaultValueNumeric(((Number) defaultValue)); } else if (defaultValue instanceof DatabaseFunction) { DatabaseFunction function = (DatabaseFunction) defaultValue; if ("current".equals(function.getValue())) { if (database instanceof InformixDatabase) { if (dataType instanceof DateTimeType) { if (dataType.getAdditionalInformation() == null || dataType.getAdditionalInformation().length() == 0) { if (dataType.getParameters() != null && dataType.getParameters().length > 0) { String parameter = String.valueOf(dataType.getParameters()[0]); if ("4365".equals(parameter)) { function = new DatabaseFunction("current year to fraction(3)"); } if ("3594".equals(parameter)) { function = new DatabaseFunction("current year to second"); } if ("3080".equals(parameter)) { function = new DatabaseFunction("current year to minute"); } if ("2052".equals(parameter)) { function = new DatabaseFunction("current year to day"); } } } } } } columnConfig.setDefaultValueComputed(function); } else { String defaultValueString = null; try { defaultValueString = DataTypeFactory.getInstance().from(column.getType(), database).objectToSql(defaultValue, database); } catch (NullPointerException e) { throw e; } if (defaultValueString != null) { defaultValueString = defaultValueString.replaceFirst("'", "").replaceAll("'$", ""); } columnConfig.setDefaultValue(defaultValueString); } columnConfig.setDefaultValueConstraintName(column.getDefaultValueConstraintName()); } @Override public int getPriority(Class<? extends DatabaseObject> objectType, Database database) { if (Table.class.isAssignableFrom(objectType)) { return PRIORITY_DEFAULT; } return PRIORITY_NONE; } @Override public Class<? extends DatabaseObject>[] runAfterTypes() { return null; } @Override public Class<? extends DatabaseObject>[] runBeforeTypes() { return null; } @Override public Change[] fixMissing(DatabaseObject missingObject, DiffOutputControl control, Database referenceDatabase, Database comparisonDatabase, ChangeGeneratorChain chain) { Table missingTable = (Table) missingObject; PrimaryKey primaryKey = missingTable.getPrimaryKey(); List<String> pkColumnList = (primaryKey != null ? primaryKey.getColumnNamesAsList() : null); CreateTableChange change = createCreateTableChange(); change.setTableName(missingTable.getName()); if (control.getIncludeCatalog()) { change.setCatalogName(missingTable.getSchema().getCatalogName()); } if (control.getIncludeSchema()) { change.setSchemaName(missingTable.getSchema().getName()); } if (missingTable.getRemarks() != null) { change.setRemarks(missingTable.getRemarks()); } if (missingTable.getTablespace() != null && comparisonDatabase.supportsTablespaces()) { change.setTablespace(missingTable.getTablespace()); } for (Column column : missingTable.getColumns()) { ColumnConfig columnConfig = new ColumnConfig(); columnConfig.setName(column.getName()); LiquibaseDataType ldt = DataTypeFactory.getInstance().from(column.getType(), referenceDatabase); DatabaseDataType ddt = ldt.toDatabaseDataType(comparisonDatabase); String typeString = ddt.toString(); if (comparisonDatabase instanceof MSSQLDatabase) { typeString = comparisonDatabase.unescapeDataTypeString(typeString); } columnConfig.setType(typeString); if (column.isAutoIncrement()) { columnConfig.setAutoIncrement(true); } ConstraintsConfig constraintsConfig = null; // In MySQL, the primary key must be specified at creation for an autoincrement column if (pkColumnList != null && pkColumnList.contains(column.getName())) { if (referenceDatabase instanceof MSSQLDatabase && primaryKey.getBackingIndex() != null && primaryKey.getBackingIndex().getClustered() != null && !primaryKey.getBackingIndex().getClustered()) { // have to handle PK as a separate statement } else if (referenceDatabase instanceof PostgresDatabase && primaryKey.getBackingIndex() != null && primaryKey.getBackingIndex().getClustered() != null && primaryKey.getBackingIndex().getClustered()) { // have to handle PK as a separate statement } else { constraintsConfig = new ConstraintsConfig(); constraintsConfig.setPrimaryKey(true); constraintsConfig.setPrimaryKeyTablespace(primaryKey.getTablespace()); // MySQL sets some primary key names as PRIMARY which is invalid if (comparisonDatabase instanceof MySQLDatabase && "PRIMARY".equals(primaryKey.getName())) { constraintsConfig.setPrimaryKeyName(null); } else { constraintsConfig.setPrimaryKeyName(primaryKey.getName()); } control.setAlreadyHandledMissing(primaryKey); control.setAlreadyHandledMissing(primaryKey.getBackingIndex()); } } else if (column.isNullable() != null && !column.isNullable()) { constraintsConfig = new ConstraintsConfig(); constraintsConfig.setNullable(false); } if (constraintsConfig != null) { columnConfig.setConstraints(constraintsConfig); } setDefaultValue(columnConfig, column, referenceDatabase); if (column.getRemarks() != null) { columnConfig.setRemarks(column.getRemarks()); } if (column.getAutoIncrementInformation() != null) { BigInteger startWith = column.getAutoIncrementInformation().getStartWith(); BigInteger incrementBy = column.getAutoIncrementInformation().getIncrementBy(); if (startWith != null && !startWith.equals(BigInteger.ONE)) { columnConfig.setStartWith(startWith); } if (incrementBy != null && !incrementBy.equals(BigInteger.ONE)) { columnConfig.setIncrementBy(incrementBy); } } change.addColumn(columnConfig); control.setAlreadyHandledMissing(column); } // In SQLite, we must specify the PRIMARY KEY at table creation time return new Change[]{ change }; } protected CreateTableChange createCreateTableChange() { return new CreateTableChange(); } }
package org.jboss.aerogear.unifiedpush.cassandra.dao.model; import java.io.Serializable; import java.util.UUID; public class DatabaseQueryKey implements Serializable { private static final long serialVersionUID = 3613590444329269400L; private UUID pushApplicationId; private String database; public DatabaseQueryKey(Database db) { super(); this.pushApplicationId = db.getKey().getPushApplicationId(); this.database = db.getDatabase(); } public DatabaseQueryKey(DocumentContent doc) { super(); this.pushApplicationId = doc.getKey().getPushApplicationId(); this.database = doc.getKey().getDatabase(); } public DatabaseQueryKey(String pushApplicationId, String database) { super(); this.pushApplicationId = UUID.fromString(pushApplicationId); this.database = database; } public UUID getPushApplicationId() { return pushApplicationId; } public void setPushApplicationId(UUID pushApplicationId) { this.pushApplicationId = pushApplicationId; } public String getDatabase() { return database; } public void setDatabase(String database) { this.database = database; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((database == null) ? 0 : database.hashCode()); result = prime * result + ((pushApplicationId == null) ? 0 : pushApplicationId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DatabaseQueryKey other = (DatabaseQueryKey) obj; if (database == null) { if (other.database != null) return false; } else if (!database.equals(other.database)) return false; if (pushApplicationId == null) { if (other.pushApplicationId != null) return false; } else if (!pushApplicationId.equals(other.pushApplicationId)) return false; return true; } }
package net.java.sip.communicator.plugin.sipaccregwizz; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import net.java.sip.communicator.service.gui.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.util.swing.*; /** * The <tt>FirstWizardPage</tt> is the page, where user could enter the uin * and the password of the account. * * @author Yana Stamcheva * @author Damian Minkov */ @SuppressWarnings("serial") public class FirstWizardPage extends TransparentPanel implements WizardPage, DocumentListener, ItemListener { public static final String FIRST_PAGE_IDENTIFIER = "FirstPageIdentifier"; public static final String USER_NAME_EXAMPLE = "Ex: john@voiphone.net or simply \"john\" for no server"; private JPanel firstTabPanel = new TransparentPanel(new BorderLayout()); private JPanel uinPassPanel = new TransparentPanel(new BorderLayout(10, 10)); private JPanel labelsPanel = new TransparentPanel(); private JPanel valuesPanel = new TransparentPanel(); private JLabel uinLabel = new JLabel(Resources.getString("plugin.sipaccregwizz.USERNAME")); private JLabel passLabel = new JLabel(Resources.getString("service.gui.PASSWORD")); private JPanel emptyPanel = new TransparentPanel(); private JLabel uinExampleLabel = new JLabel(USER_NAME_EXAMPLE); private JLabel existingAccountLabel = new JLabel(Resources.getString("service.gui.EXISTING_ACCOUNT_ERROR")); private JTextField uinField = new JTextField(); private JPasswordField passField = new JPasswordField(); private JCheckBox rememberPassBox = new SIPCommCheckBox( Resources.getString("service.gui.REMEMBER_PASSWORD")); private JPanel advancedOpPanel = new TransparentPanel(new BorderLayout(10, 10)); private JPanel labelsAdvOpPanel = new TransparentPanel(new GridLayout(0, 1, 10, 10)); private JPanel valuesAdvOpPanel = new TransparentPanel(new GridLayout(0, 1, 10, 10)); private JCheckBox enableAdvOpButton = new SIPCommCheckBox(Resources.getString( "plugin.sipaccregwizz.OVERRIDE_SERVER_DEFAULT_OPTIONS"), false); private JLabel serverLabel = new JLabel(Resources.getString("plugin.sipaccregwizz.REGISTRAR")); private JCheckBox enableDefaultEncryption = new SIPCommCheckBox(Resources .getString("plugin.sipaccregwizz.ENABLE_DEFAULT_ENCRYPTION"), true); private JLabel proxyLabel = new JLabel(Resources.getString("plugin.sipaccregwizz.PROXY")); private JLabel serverPortLabel = new JLabel(Resources.getString("plugin.sipaccregwizz.SERVER_PORT")); private JLabel proxyPortLabel = new JLabel(Resources.getString("plugin.sipaccregwizz.PROXY_PORT")); private JLabel transportLabel = new JLabel(Resources.getString( "plugin.sipaccregwizz.PREFERRED_TRANSPORT")); private JTextField serverField = new JTextField(); private JTextField proxyField = new JTextField(); private JTextField serverPortField = new JTextField(SIPAccountRegistration.DEFAULT_PORT); private JTextField proxyPortField = new JTextField(SIPAccountRegistration.DEFAULT_PORT); private JComboBox transportCombo = new JComboBox(new Object[] { "UDP", "TCP", "TLS" }); private JPanel presenceOpPanel = new TransparentPanel(new BorderLayout(10, 10)); private JPanel buttonsPresOpPanel = new TransparentPanel(new GridLayout(0, 1, 10, 10)); private JPanel labelsPresOpPanel = new TransparentPanel(new GridLayout(0, 1, 10, 10)); private JPanel valuesPresOpPanel = new TransparentPanel(new GridLayout(0, 1, 10, 10)); private JCheckBox enablePresOpButton = new SIPCommCheckBox(Resources .getString("plugin.sipaccregwizz.ENABLE_PRESENCE"), true); private JCheckBox forceP2PPresOpButton = new SIPCommCheckBox(Resources .getString("plugin.sipaccregwizz.FORCE_P2P_PRESENCE"), true); private JLabel pollPeriodLabel = new JLabel( Resources.getString("plugin.sipaccregwizz.OFFLINE_CONTACT_POLLING_PERIOD")); private JLabel subscribeExpiresLabel = new JLabel( Resources.getString("plugin.sipaccregwizz.SUBSCRIPTION_EXPIRATION")); private JTextField pollPeriodField = new JTextField(SIPAccountRegistration.DEFAULT_POLL_PERIOD); private JTextField subscribeExpiresField = new JTextField(SIPAccountRegistration.DEFAULT_SUBSCRIBE_EXPIRES); private JPanel keepAlivePanel = new TransparentPanel(new BorderLayout(10, 10)); private JPanel keepAliveLabels = new TransparentPanel(new GridLayout(0, 1, 5, 5)); private JPanel keepAliveValues = new TransparentPanel(new GridLayout(0, 1, 5, 5)); private JLabel keepAliveMethodLabel = new JLabel( Resources.getString("plugin.sipaccregwizz.KEEP_ALIVE_METHOD")); private JLabel keepAliveIntervalLabel = new JLabel( Resources.getString("plugin.sipaccregwizz.KEEP_ALIVE_INTERVAL")); private JLabel keepAliveIntervalExampleLabel = new JLabel( Resources.getString("plugin.sipaccregwizz.KEEP_ALIVE_INTERVAL_INFO")); private JComboBox keepAliveMethodBox = new JComboBox(new Object [] { "REGISTER", "OPTIONS" }); private JTextField keepAliveIntervalValue = new JTextField(); private JTabbedPane tabbedPane = new SIPCommTabbedPane(false, false); private JPanel advancedPanel = new TransparentPanel(); private Object nextPageIdentifier = WizardPage.SUMMARY_PAGE_IDENTIFIER; private SIPAccountRegistrationWizard wizard; private boolean isCommitted = false; /** * Creates an instance of <tt>FirstWizardPage</tt>. * * @param wizard the parent wizard */ public FirstWizardPage(SIPAccountRegistrationWizard wizard) { super(new BorderLayout()); this.wizard = wizard; advancedPanel.setLayout(new BoxLayout(advancedPanel, BoxLayout.Y_AXIS)); this.init(); this.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); this.labelsPanel .setLayout(new BoxLayout(labelsPanel, BoxLayout.Y_AXIS)); this.valuesPanel .setLayout(new BoxLayout(valuesPanel, BoxLayout.Y_AXIS)); } /** * Initializes all panels, buttons, etc. */ private void init() { this.labelsPanel.setOpaque(false); this.valuesPanel.setOpaque(false); this.uinPassPanel.setOpaque(false); this.emptyPanel.setOpaque(false); this.uinField.getDocument().addDocumentListener(this); this.transportCombo.addItemListener(this); this.rememberPassBox.setSelected(true); existingAccountLabel.setForeground(Color.RED); this.uinExampleLabel.setForeground(Color.GRAY); this.uinExampleLabel.setFont(uinExampleLabel.getFont().deriveFont(8)); this.emptyPanel.setMaximumSize(new Dimension(40, 35)); this.uinExampleLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 8, 0)); labelsPanel.add(uinLabel); labelsPanel.add(emptyPanel); labelsPanel.add(passLabel); valuesPanel.add(uinField); valuesPanel.add(uinExampleLabel); valuesPanel.add(passField); uinPassPanel.add(labelsPanel, BorderLayout.WEST); uinPassPanel.add(valuesPanel, BorderLayout.CENTER); uinPassPanel.add(rememberPassBox, BorderLayout.SOUTH); uinPassPanel.setBorder(BorderFactory.createTitledBorder(Resources .getString("plugin.sipaccregwizz.USERNAME_AND_PASSWORD"))); firstTabPanel.add(uinPassPanel, BorderLayout.NORTH); tabbedPane.addTab( Resources.getString("service.gui.SUMMARY"), firstTabPanel); serverField.setEnabled(false); serverPortField.setEnabled(false); proxyField.setEnabled(false); proxyPortField.setEnabled(false); transportCombo.setEnabled(false); enableAdvOpButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { // Perform action JCheckBox cb = (JCheckBox) evt.getSource(); if (!wizard.isModification()) serverField.setEnabled(cb.isSelected()); serverPortField.setEnabled(cb.isSelected()); proxyField.setEnabled(cb.isSelected()); proxyPortField.setEnabled(cb.isSelected()); transportCombo.setEnabled(cb.isSelected()); if(!cb.isSelected()) { setServerFieldAccordingToUIN(); serverPortField .setText(SIPAccountRegistration.DEFAULT_PORT); proxyPortField .setText(SIPAccountRegistration.DEFAULT_PORT); transportCombo .setSelectedItem(SIPAccountRegistration.DEFAULT_TRANSPORT); } } }); transportCombo .setSelectedItem(SIPAccountRegistration.DEFAULT_TRANSPORT); labelsAdvOpPanel.add(serverLabel); labelsAdvOpPanel.add(serverPortLabel); labelsAdvOpPanel.add(proxyLabel); labelsAdvOpPanel.add(proxyPortLabel); labelsAdvOpPanel.add(transportLabel); valuesAdvOpPanel.add(serverField); valuesAdvOpPanel.add(serverPortField); valuesAdvOpPanel.add(proxyField); valuesAdvOpPanel.add(proxyPortField); valuesAdvOpPanel.add(transportCombo); advancedOpPanel.add(enableAdvOpButton, BorderLayout.NORTH); advancedOpPanel.add(labelsAdvOpPanel, BorderLayout.WEST); advancedOpPanel.add(valuesAdvOpPanel, BorderLayout.CENTER); advancedOpPanel.add(enableDefaultEncryption, BorderLayout.SOUTH); advancedOpPanel.setBorder(BorderFactory.createTitledBorder(Resources .getString("plugin.aimaccregwizz.ADVANCED_OPTIONS"))); advancedPanel.add(advancedOpPanel); enablePresOpButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { // Perform action JCheckBox cb = (JCheckBox) evt.getSource(); forceP2PPresOpButton.setEnabled(cb.isSelected()); pollPeriodField.setEnabled(cb.isSelected()); subscribeExpiresField.setEnabled(cb.isSelected()); } }); labelsPresOpPanel.add(pollPeriodLabel); labelsPresOpPanel.add(subscribeExpiresLabel); valuesPresOpPanel.add(pollPeriodField); valuesPresOpPanel.add(subscribeExpiresField); buttonsPresOpPanel.add(enablePresOpButton); buttonsPresOpPanel.add(forceP2PPresOpButton); presenceOpPanel.add(buttonsPresOpPanel, BorderLayout.NORTH); presenceOpPanel.add(labelsPresOpPanel, BorderLayout.WEST); presenceOpPanel.add(valuesPresOpPanel, BorderLayout.CENTER); presenceOpPanel.setBorder(BorderFactory.createTitledBorder( Resources.getString("plugin.sipaccregwizz.PRESENCE_OPTIONS"))); advancedPanel.add(presenceOpPanel); JPanel emptyLabelPanel = new TransparentPanel(); emptyLabelPanel.setMaximumSize(new Dimension(40, 35)); keepAliveLabels.add(keepAliveMethodLabel); keepAliveLabels.add(keepAliveIntervalLabel); keepAliveLabels.add(emptyLabelPanel); this.keepAliveIntervalExampleLabel.setForeground(Color.GRAY); this.keepAliveIntervalExampleLabel .setFont(uinExampleLabel.getFont().deriveFont(8)); this.keepAliveIntervalExampleLabel .setMaximumSize(new Dimension(40, 35)); this.keepAliveIntervalExampleLabel .setBorder(BorderFactory.createEmptyBorder(0, 0, 8, 0)); keepAliveIntervalValue .setText(SIPAccountRegistration.DEFAULT_KEEP_ALIVE_INTERVAL); keepAliveMethodBox.setSelectedItem( SIPAccountRegistration.DEFAULT_KEEP_ALIVE_METHOD); keepAliveValues.add(keepAliveMethodBox); keepAliveValues.add(keepAliveIntervalValue); keepAliveValues.add(keepAliveIntervalExampleLabel); keepAlivePanel.add(keepAliveLabels, BorderLayout.WEST); keepAlivePanel.add(keepAliveValues, BorderLayout.CENTER); keepAlivePanel.setBorder(BorderFactory.createTitledBorder( Resources.getString("plugin.sipaccregwizz.KEEP_ALIVE"))); advancedPanel.add(keepAlivePanel); tabbedPane.addTab( Resources.getString("service.gui.ADVANCED"), advancedPanel); this.add(tabbedPane, BorderLayout.NORTH); } /** * Implements the <code>WizardPage.getIdentifier</code> to return this * page identifier. */ public Object getIdentifier() { return FIRST_PAGE_IDENTIFIER; } /** * Implements the <code>WizardPage.getNextPageIdentifier</code> to return * the next page identifier - the summary page. */ public Object getNextPageIdentifier() { return nextPageIdentifier; } /** * Implements the <code>WizardPage.getBackPageIdentifier</code> to return * the next back identifier - the default page. */ public Object getBackPageIdentifier() { return WizardPage.DEFAULT_PAGE_IDENTIFIER; } /** * Implements the <code>WizardPage.getWizardForm</code> to return this * panel. */ public Object getWizardForm() { return this; } /** * Before this page is displayed enables or disables the "Next" wizard * button according to whether the UIN field is empty. */ public void pageShowing() { this.setNextButtonAccordingToUIN(); wizard.getWizardContainer().setBackButtonEnabled(false); } /** * Saves the user input when the "Next" wizard buttons is clicked. */ public void commitPage() { String uin = uinField.getText(); int indexOfSeparator = uin.indexOf('@'); if (indexOfSeparator > -1) { uin = uin.substring(0, indexOfSeparator); } String server = serverField.getText(); if (!wizard.isModification() && isExistingAccount(uin, server)) { nextPageIdentifier = FIRST_PAGE_IDENTIFIER; uinPassPanel.add(existingAccountLabel, BorderLayout.NORTH); this.revalidate(); } else { nextPageIdentifier = SUMMARY_PAGE_IDENTIFIER; uinPassPanel.remove(existingAccountLabel); SIPAccountRegistration registration = wizard.getRegistration(); registration.setId(uinField.getText()); if (passField.getPassword() != null) registration.setPassword(new String(passField.getPassword())); registration.setRememberPassword(rememberPassBox.isSelected()); registration.setServerAddress(serverField.getText()); registration.setServerPort(serverPortField.getText()); registration.setProxy(proxyField.getText()); registration.setProxyPort(proxyPortField.getText()); registration.setPreferredTransport(transportCombo.getSelectedItem() .toString()); registration.setEnablePresence(enablePresOpButton.isSelected()); registration.setForceP2PMode(forceP2PPresOpButton.isSelected()); registration.setDefaultEncryption(enableDefaultEncryption.isSelected()); registration.setPollingPeriod(pollPeriodField.getText()); registration.setSubscriptionExpiration(subscribeExpiresField .getText()); registration.setKeepAliveMethod( keepAliveMethodBox.getSelectedItem().toString()); registration.setKeepAliveInterval(keepAliveIntervalValue.getText()); } wizard.getWizardContainer().setBackButtonEnabled(true); this.isCommitted = true; } /** * Enables or disables the "Next" wizard button according to whether the UIN * field is empty. */ private void setNextButtonAccordingToUIN() { if (uinField.getText() == null || uinField.getText().equals("")) { wizard.getWizardContainer().setNextFinishButtonEnabled(false); } else { wizard.getWizardContainer().setNextFinishButtonEnabled(true); } } /** * Handles the <tt>DocumentEvent</tt> triggered when user types in the UIN * field. Enables or disables the "Next" wizard button according to whether * the UIN field is empty. */ public void insertUpdate(DocumentEvent e) { this.setNextButtonAccordingToUIN(); this.setServerFieldAccordingToUIN(); } /** * Handles the <tt>DocumentEvent</tt> triggered when user deletes letters * from the UIN field. Enables or disables the "Next" wizard button * according to whether the UIN field is empty. */ public void removeUpdate(DocumentEvent e) { this.setNextButtonAccordingToUIN(); this.setServerFieldAccordingToUIN(); } public void changedUpdate(DocumentEvent e) { } public void pageHiding() { } public void pageShown() { } public void pageBack() { } /** * Fills the UIN and Password fields in this panel with the data coming from * the given protocolProvider. * * @param protocolProvider The <tt>ProtocolProviderService</tt> to load * the data from. */ public void loadAccount(ProtocolProviderService protocolProvider) { AccountID accountID = protocolProvider.getAccountID(); String password = (String) accountID.getAccountProperties().get( ProtocolProviderFactory.PASSWORD); String serverAddress = (String) accountID.getAccountProperties().get( ProtocolProviderFactory.SERVER_ADDRESS); String serverPort = (String) accountID.getAccountProperties().get( ProtocolProviderFactory.SERVER_PORT); String proxyAddress = (String) accountID.getAccountProperties().get( ProtocolProviderFactory.PROXY_ADDRESS); String proxyPort = (String) accountID.getAccountProperties().get( ProtocolProviderFactory.PROXY_PORT); String preferredTransport = (String) accountID.getAccountProperties().get( ProtocolProviderFactory.PREFERRED_TRANSPORT); boolean enablePresence = new Boolean( (String) accountID.getAccountProperties().get( ProtocolProviderFactory.IS_PRESENCE_ENABLED)).booleanValue(); boolean forceP2P = new Boolean( (String) accountID.getAccountProperties().get( ProtocolProviderFactory.FORCE_P2P_MODE)).booleanValue(); boolean enabledDefaultEncryption = new Boolean( (String) accountID.getAccountProperties().get( ProtocolProviderFactory.DEFAULT_ENCRYPTION)).booleanValue(); String pollingPeriod = (String) accountID.getAccountProperties().get( ProtocolProviderFactory.POLLING_PERIOD); String subscriptionPeriod = (String) accountID.getAccountProperties().get( ProtocolProviderFactory.SUBSCRIPTION_EXPIRATION); String keepAliveMethod = (String) accountID.getAccountProperties() .get("KEEP_ALIVE_METHOD"); String keepAliveInterval = (String) accountID.getAccountProperties() .get("KEEP_ALIVE_INTERVAL"); uinField.setEnabled(false); this.uinField.setText((serverAddress == null) ? accountID.getUserID() : (accountID.getUserID() + "@" + serverAddress)); if (password != null) { this.passField.setText(password); this.rememberPassBox.setSelected(true); } serverField.setText(serverAddress); serverField.setEnabled(false); serverPortField.setText(serverPort); proxyField.setText(proxyAddress); // The order of the next two fields is important, as a changelister of // the transportCombo sets the proxyPortField to its default transportCombo.setSelectedItem(preferredTransport); proxyPortField.setText(proxyPort); if (!(SIPAccountRegistration.DEFAULT_PORT.equals(serverPort) || SIPAccountRegistration.DEFAULT_TLS_PORT.equals(serverPort)) || !(SIPAccountRegistration.DEFAULT_PORT.equals(proxyPort) || SIPAccountRegistration.DEFAULT_TLS_PORT.equals(proxyPort)) || !transportCombo.getSelectedItem() .equals(SIPAccountRegistration.DEFAULT_TRANSPORT)) { enableAdvOpButton.setSelected(true); // The server field should stay disabled in modification mode, // because the user should not be able to change anything concerning // the account identifier and server name is part of it. serverField.setEnabled(false); serverPortField.setEnabled(true); proxyField.setEnabled(true); proxyPortField.setEnabled(true); transportCombo.setEnabled(true); } enablePresOpButton.setSelected(enablePresence); forceP2PPresOpButton.setSelected(forceP2P); enableDefaultEncryption.setSelected(enabledDefaultEncryption); pollPeriodField.setText(pollingPeriod); subscribeExpiresField.setText(subscriptionPeriod); if (!enablePresence) { pollPeriodField.setEnabled(false); subscribeExpiresField.setEnabled(false); } keepAliveMethodBox.setSelectedItem(keepAliveMethod); keepAliveIntervalValue.setText(keepAliveInterval); } /** * Parse the server part from the sip id and set it to server as default * value. If Advanced option is enabled Do nothing. */ private void setServerFieldAccordingToUIN() { if (!enableAdvOpButton.isSelected()) { String serverAddress = wizard.getServerFromUserName(uinField.getText()); serverField.setText(serverAddress); proxyField.setText(serverAddress); } } /** * Disables Next Button if Port field value is incorrect */ private void setNextButtonAccordingToPort() { try { wizard.getWizardContainer().setNextFinishButtonEnabled(true); } catch (NumberFormatException ex) { wizard.getWizardContainer().setNextFinishButtonEnabled(false); } } public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED && e.getItem().equals("TLS")) { serverPortField.setText(SIPAccountRegistration.DEFAULT_TLS_PORT); proxyPortField.setText(SIPAccountRegistration.DEFAULT_TLS_PORT); } else { serverPortField.setText(SIPAccountRegistration.DEFAULT_PORT); proxyPortField.setText(SIPAccountRegistration.DEFAULT_PORT); } } private boolean isExistingAccount(String accountName, String serverName) { ProtocolProviderFactory factory = SIPAccRegWizzActivator.getSIPProtocolProviderFactory(); java.util.List<AccountID> registeredAccounts = factory.getRegisteredAccounts(); for (AccountID accountID : registeredAccounts) { if (accountName.equalsIgnoreCase(accountID.getUserID()) && serverName.equalsIgnoreCase(accountID.getService())) return true; } return false; } public Object getSimpleForm() { return uinPassPanel; } public boolean isCommitted() { return isCommitted; } }
/* * MutableBitNucleotideAlignmentHDF5 */ package net.maizegenetics.pal.alignment; import ch.systemsx.cisd.hdf5.HDF5Factory; import ch.systemsx.cisd.hdf5.HDF5FloatStorageFeatures; import ch.systemsx.cisd.hdf5.HDF5IntStorageFeatures; import ch.systemsx.cisd.hdf5.HDF5LinkInformation; import ch.systemsx.cisd.hdf5.IHDF5Reader; import ch.systemsx.cisd.hdf5.IHDF5Writer; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import static net.maizegenetics.pal.alignment.Alignment.UNKNOWN_DIPLOID_ALLELE; import net.maizegenetics.pal.ids.IdGroup; import net.maizegenetics.pal.ids.Identifier; import net.maizegenetics.pal.ids.SimpleIdGroup; import net.maizegenetics.util.BitSet; import net.maizegenetics.util.ProgressListener; import org.apache.log4j.Logger; /** * MutableNucleotideAlignmentHDF5 is a byte based HDF5 mutable alignment. The mutability * only allows for the addition and deletion of taxa, and for the modification of genotypes. * It does NOT permit the insertion or deletion of sites (although it does allow merging of * alignments). Deletion may be possible in the future. * <p> * The class uses a local cache to provide performance. The default cache is defined by * defaultCacheSize, and is set 4096 chunks. The genotypes in the cache are chunked based * on defaultSiteCache also set to default of 4096 sites (4096 * 4096 = 16M sites). * The cache be filled with any balance of chunks, and the first added are the first * removed if the cache fills. If there will be lots of reading from the alignment, set the * defaultCacheSize > the number of taxa. If you will only be writing to the object, * then set the defaultCacheSize small. * <p> * This class is very speed efficient at most operations, but it is slow at setBase() because it * does not cache the bases being written for thread safety. Write genotypes in bulk with * setBaseRange(). * <p> * To create this file format use: * ExportUtils.writeToMutableHDF5(Alignment a, String newHDF5file, boolean includeGenotypes) * To instantiate it: * MutableNucleotideAlignmentHDF5. * <p> * If you use this in a research publication - cite Bradbury et al * * <p> * TODO: * <li>Add support for bit encoding - but just two states (Major/Minor) or (Ref/Alt) * <li>Add efficient support for merging chromosomes * * @author Ed Buckler & Terry Casstevens */ public class MutableNucleotideAlignmentHDF5 extends AbstractAlignment implements MutableAlignment { private static final Logger myLogger = Logger.getLogger(MutableNucleotideAlignmentHDF5.class); private String fileName; private boolean myIsDirty = true; private List<Identifier> myIdentifiers = new ArrayList<Identifier>(); private final int myMaxNumSites; //try to delete private int myNumSitesStagedToRemove = 0; //try to delete protected int[] myVariableSites; private List<Locus> myLocusList = new ArrayList<Locus>(); protected int[] myLocusIndices; //consider changing to byte or short to save memory, generally on 10 chromosomes private int[] myLociOffsets = null; //Site descriptor in memory private byte[][] myAlleleFreqOrder=null; //we probably need all these in memory for rapid bit conversions // protected String[] mySNPIDs; //perhaps don't keep in memory, consider compressed private LoadingCache<Integer,SiteAnnotation> mySiteAnnoCache; //key = site private CacheLoader<Integer,SiteAnnotation> siteAnnotLoader = new CacheLoader<Integer,SiteAnnotation>() { int lastCachedStartSite=Integer.MIN_VALUE; int[][] af; byte[][] afOrder; float[] maf; float[] paf; String[] snpIDs; public SiteAnnotation load(Integer key) { int startSite=key&hdf5GenoBlockMask; if(startSite!=lastCachedStartSite) { int length=((myNumSites-startSite)<hdf5GenoBlock)?myNumSites-startSite:hdf5GenoBlock; System.out.println("Reading from HDF5 site anno:"+startSite); System.out.println(""); synchronized(myWriter) { af= myWriter.readIntMatrixBlockWithOffset(HapMapHDF5Constants.ALLELE_CNT, 6, length, 0l, startSite); afOrder = myWriter.readByteMatrixBlockWithOffset(HapMapHDF5Constants.ALLELE_FREQ_ORD, 6, length, 0l, startSite); maf= myWriter.readFloatArrayBlockWithOffset(HapMapHDF5Constants.MAF,length, startSite); paf= myWriter.readFloatArrayBlockWithOffset(HapMapHDF5Constants.SITECOV,length, startSite); snpIDs=myWriter.readStringArrayBlockWithOffset(HapMapHDF5Constants.SNP_IDS,length, startSite); //TODO cache SNPIDs lastCachedStartSite=startSite; } //perhaps kickoff a process to load the rest } int offset=key-startSite; int numAlleles=0; for (int i = 0; i < af.length; i++) { if(afOrder[i][offset]!=Alignment.UNKNOWN_ALLELE) numAlleles++; } int[] theAf=new int[numAlleles]; byte[] theAfOrder=new byte[numAlleles]; for (int i = 0; i < numAlleles; i++) { theAfOrder[i] = afOrder[i][offset]; theAf[i] = af[theAfOrder[i]][offset]; } //TODO add SNPIDs SiteAnnotation sa=new SiteAnnotation(myVariableSites[key], theAfOrder, theAf, maf[offset], paf[offset], snpIDs[offset]); return sa; } }; IHDF5Writer myWriter=null; HDF5IntStorageFeatures genoFeatures = HDF5IntStorageFeatures.createDeflation(2); HDF5FloatStorageFeatures floatFeatures = HDF5FloatStorageFeatures.createDeflation(2); private int defaultCacheSize=1<<16; private int defaultSiteCache=1<<16; /*Byte representations of DNA sequences are stored in blocks of 65536 sites*/ public static final int hdf5GenoBlock=1<<16; public static final int hdf5GenoBlockMask=~(hdf5GenoBlock-1); // public boolean favorCachingOfEntireTaxon=true; private LoadingCache<Long,byte[]> myGenoCache; //key (taxa <<< 33)+BLOCK private CacheLoader<Long,byte[]> genoLoader = new CacheLoader<Long,byte[]>() { public byte[] load(Long key) { int[] taxonSite=getTaxonSiteFromKey(key); long offset=taxonSite[1]<<16; byte[] data=new byte[0]; synchronized(myWriter) { data=myWriter.readAsByteArrayBlockWithOffset(getTaxaGenoPath(taxonSite[0]),1<<16,offset);} return data; } }; private boolean cacheDepth=false; private LRUCache<Long,byte[][]> myDepthCache=null; //key (taxa <<< 32)+startSite private LoadingCache<Integer,BitSet[]> tBitCache; //taxon id number, Bitset[2] = {MajorBitSet, MinorBitSet} private CacheLoader<Integer,BitSet[]> tBitLoader = new CacheLoader<Integer,BitSet[]>() { public BitSet[] load(Integer key) { BitSet[] bs=AlignmentUtils.calcBitPresenceFromGenotype(getBaseRow(key), myAlleleFreqOrder[0], myAlleleFreqOrder[1]); return bs; } }; private IdGroup myIdGroup; //set to null whenever dirty protected MutableNucleotideAlignmentHDF5(String fileName, IHDF5Writer reader, List<Identifier> idGroup, int[] variableSites, List<Locus> locusList, int[] locusIndices, String[] siteNames, int defaultCacheSize) { super(NucleotideAlignmentConstants.NUCLEOTIDE_ALLELES); myMaxNumAlleles=NucleotideAlignmentConstants.NUMBER_NUCLEOTIDE_ALLELES; this.fileName=fileName; this.defaultCacheSize=defaultCacheSize; if (variableSites.length != siteNames.length) { throw new IllegalArgumentException("MutableBitNucleotideAlignmentHDF5: init: number variable sites, loci, and site names must be same."); } if (variableSites.length != siteNames.length) { throw new IllegalArgumentException("MutableBitNucleotideAlignmentHDF5: init: number variable sites, loci, and site names must be same."); } myWriter=reader; myMaxNumSites = siteNames.length; myNumSites = siteNames.length; this.defaultSiteCache=(myNumSites<defaultSiteCache)?myNumSites:defaultSiteCache; myVariableSites = variableSites; myLocusList = locusList; myLocusIndices = locusIndices; // mySNPIDs = siteNames; myReference = new byte[myMaxNumSites]; Arrays.fill(myReference, Alignment.UNKNOWN_DIPLOID_ALLELE); Collections.sort(idGroup); myIdentifiers = idGroup; recalcLocusCoordinates(); initAllDataSupport(); loadSiteDescriptorsToMemory(); initGenotypeCache(); myIsDirty=false; } public static MutableNucleotideAlignmentHDF5 getInstance(String filename) { return MutableNucleotideAlignmentHDF5.getInstance(filename, 1<<16); } public static boolean isMutableNucleotideAlignmentHDF5(String filename) { IHDF5Reader reader = HDF5Factory.open(filename); boolean result=reader.exists(HapMapHDF5Constants.GENOTYPES); reader.close(); return result; } public static MutableNucleotideAlignmentHDF5 getInstance(String filename, int defaultCacheSize) { IHDF5Writer reader = HDF5Factory.open(filename); //derive the taxa list on the fly List<HDF5LinkInformation> fields=reader.getAllGroupMemberInformation(HapMapHDF5Constants.GENOTYPES, true); ArrayList<Identifier> taxaList=new ArrayList<Identifier>(); for (HDF5LinkInformation is : fields) { if(is.isDataSet()==false) continue; taxaList.add(new Identifier(is.getName())); } //TODO this is a good idea, it should be passed into the constructor and stored // byte[][] alleles = reader.readByteMatrix(HapMapHDF5Constants.ALLELES); int[] variableSites = reader.readIntArray(HapMapHDF5Constants.POSITIONS); String[] lociStrings = reader.readStringArray(HapMapHDF5Constants.LOCI); ArrayList<Locus> loci=new ArrayList<Locus>(); for (String lS : lociStrings) {loci.add(new Locus(lS));} int[] locusIndices; if(reader.exists(HapMapHDF5Constants.LOCUS_INDICES)) { locusIndices = reader.readIntArray(HapMapHDF5Constants.LOCUS_INDICES);} else {locusIndices = new int[variableSites.length]; //this to support an old format. Arrays.fill(locusIndices, 0); //fill with zero } String[] snpIds = reader.readStringArray(HapMapHDF5Constants.SNP_IDS); return new MutableNucleotideAlignmentHDF5(filename, reader, taxaList, variableSites, loci, locusIndices, snpIds, defaultCacheSize); } private void initAllDataSupport() { if(!myWriter.exists(HapMapHDF5Constants.SBIT)) myWriter.createGroup(HapMapHDF5Constants.SBIT); if(!myWriter.exists(HapMapHDF5Constants.TBIT)) myWriter.createGroup(HapMapHDF5Constants.TBIT); if(!myWriter.exists(HapMapHDF5Constants.DEPTH)) myWriter.createGroup(HapMapHDF5Constants.DEPTH); if(!myWriter.exists(HapMapHDF5Constants.SITE_DESC)) { myWriter.createGroup(HapMapHDF5Constants.SITE_DESC); clean(); } } private void initGenotypeCache() { int minLoad=(3*getSequenceCount())/2; myGenoCache= CacheBuilder.newBuilder() .maximumSize(minLoad) .build(genoLoader); tBitCache = CacheBuilder.newBuilder() .maximumSize(1024) .build(tBitLoader); mySiteAnnoCache= CacheBuilder.newBuilder() .maximumSize(2000000) .build(siteAnnotLoader); } private void initDepthCache() { myDepthCache=new LRUCache<Long, byte[][]>(defaultCacheSize); // int minLoad=(defaultCacheSize<getSequenceCount())?defaultCacheSize:getSequenceCount(); // int start=(0/defaultSiteCache)*defaultSiteCache; // int realSiteCache=(myNumSites-start<defaultSiteCache)?myNumSites-start:defaultSiteCache; // // int xSizeCache=3000; // for (int i = 0; i<minLoad; i++) { //// byte[][] test2=myWriter.readByteMatrix(getTaxaDepthPath(i)); //// System.out.println(Arrays.deepToString(test2)); //// byte[][] test=myWriter.readByteMatrixBlockWithOffset(getTaxaDepthPath(i), 6, xSizeCache, 0, start); //// System.out.println(Arrays.deepToString(test)); // myDepthCache.put(getCacheKey(i,0), myWriter.readByteMatrixBlockWithOffset(getTaxaDepthPath(i), 6, realSiteCache, 0, start)); } protected static long getCacheKey(int taxon, int site) { return ((long)taxon<<33)+(site/hdf5GenoBlock); } protected static int[] getTaxonSiteFromKey(long key) { return new int[]{(int)(key>>>33),(int)((key<<32)>>>32)}; } public void clearGenotypeCache() { //myGenoCache.clear(); myGenoCache.invalidateAll(); } // private byte[] cacheTaxonSiteBlock(int taxon, int site) { // return cacheTaxonSiteBlock(taxon, site, getCacheKey(taxon, site)); private byte[][] cacheDepthBlock(int taxon, int site, long key) { int start=(site/defaultSiteCache)*defaultSiteCache; int realSiteCache=(myNumSites-start<defaultSiteCache)?myNumSites-start:defaultSiteCache; byte[][] data=myWriter.readByteMatrixBlockWithOffset(getTaxaDepthPath(taxon), 6, realSiteCache, 0, start); if(data==null) return null; myDepthCache.put(key, data); return data; } private byte[][] cacheDepthBlock(int taxon, int site) { return cacheDepthBlock(taxon, site, getCacheKey(taxon, site)); } public int getCacheSize() { return (int)myGenoCache.size(); } protected String getTaxaGenoPath(int taxon) { return HapMapHDF5Constants.GENOTYPES + "/" + getFullTaxaName(taxon); } protected String getTaxaDepthPath(int taxon) { return HapMapHDF5Constants.DEPTH + "/" + getFullTaxaName(taxon); } @Override public byte getBase(int taxon, int site) { long key=getCacheKey(taxon,site); try{ byte[] data=myGenoCache.get(key); return data[site%hdf5GenoBlock]; } catch(ExecutionException e) { e.printStackTrace(); throw new UnsupportedOperationException("Error in getBase from cache"); } } @Override public byte[] getBaseRow(int taxon) { return getBaseRange(taxon, 0, myNumSites); } @Override public byte[] getBaseRange(int taxon, int startSite, int endSite) { byte[] result = new byte[endSite - startSite]; ByteBuffer bbR=ByteBuffer.wrap(result); for (int blockStart = startSite&hdf5GenoBlockMask; blockStart < endSite; blockStart+=hdf5GenoBlock) { long key=getCacheKey(taxon,blockStart); byte[] data; try{data=myGenoCache.get(key); } catch(ExecutionException e) { e.printStackTrace(); throw new UnsupportedOperationException("Error in getBaseRange from cache"); } if(data==null) return null; int blockEnd=blockStart+data.length; // int blockStart=site&hdf5GenoBlockMask; int offset=(blockStart<startSite)?(startSite-blockStart):0; // int length=(endSite-site>hdf5GenoBlock)?data.length:(endSite-site); int length=0; if(blockEnd>endSite) { length=endSite-(blockStart+offset); } else { length=blockEnd-(blockStart+offset); } //int length=(endSite>data.length+blockStart)?data.length:(endSite-blockStart-offset); try{bbR.put(data, offset, length);} catch(IndexOutOfBoundsException e) { e.printStackTrace(); System.err.printf("Error getBaseRange for taxon:%d startSite:%d endSite:%d %n",taxon, startSite, endSite); } } if(bbR.position()!=result.length) System.err.printf("Error getBaseRange Length not right"); return result; } @Override public String getBaseAsString(int taxon, int site) { return NucleotideAlignmentConstants.getNucleotideIUPAC(getBase(taxon,site)); } @Override public String getBaseAsStringRange(int taxon, int startSite, int endSite) { StringBuilder builder = new StringBuilder(); for (int i = startSite; i < endSite; i++) { builder.append(getBaseAsString(taxon, i)); } return builder.toString(); } @Override public byte[] getDepthForAlleles(int taxon, int site) { if(myDepthCache==null) initDepthCache(); long key=getCacheKey(taxon,site); byte[][] data=myDepthCache.get(key); if(data==null) {data=cacheDepthBlock(taxon, site, key);} byte[] result=new byte[6]; for (int i = 0; i < 6; i++) { result[i]=data[i][site%defaultSiteCache]; } return result; } public byte[][] getDepthForAlleles(int taxon) { if(myDepthCache==null) initDepthCache(); byte[][]result= new byte[6][myNumSites]; for (int site = 0; site < myNumSites; site++) { long key=getCacheKey(taxon,site); byte[][] data=myDepthCache.get(key); if(data==null) {data=cacheDepthBlock(taxon, site, key);} for (int i = 0; i < 6; i++) { result[i][site]=data[i][site%defaultSiteCache]; } } return result; } @Override public BitSet getAllelePresenceForAllSites(int taxon, int alleleNumber) { if(alleleNumber>1) throw new UnsupportedOperationException("Will not be supported. Only top two allele reported"); try { BitSet[] bs=tBitCache.get(taxon); return bs[alleleNumber]; } catch (ExecutionException e) { e.printStackTrace(); } return null; } @Override public long[] getAllelePresenceForSitesBlock(int taxon, int alleleNumber, int startBlock, int endBlock) { BitSet result=getAllelePresenceForAllSites(taxon, alleleNumber); return result.getBits(startBlock, endBlock-1); } @Override public void optimizeForTaxa(ProgressListener listener) { //do nothing now, later setup } @Override public boolean isSBitFriendly() { return false; } @Override public boolean isTBitFriendly() { return true; } @Override public int getTotalNumAlleles() { return 6; } @Override public int getSiteCount() { return myNumSites; } @Override public int getSequenceCount() { return myIdentifiers.size(); } @Override public IdGroup getIdGroup() { if(myIdGroup==null) { Identifier[] ids = new Identifier[myIdentifiers.size()]; myIdentifiers.toArray(ids); myIdGroup=new SimpleIdGroup(ids); } return myIdGroup; } @Override public String getTaxaName(int index) { return myIdentifiers.get(index).getName(); } @Override public String getFullTaxaName(int index) { return myIdentifiers.get(index).getFullName(); } @Override public boolean isPhased() { return false; } @Override public boolean isPositiveStrand(int site) { return true; } @Override public String getGenomeAssembly() { return "AGPV2"; } @Override public int[] getPhysicalPositions() { return myVariableSites.clone(); } @Override public int getPositionInLocus(int site) { try { if (myVariableSites[site] < 0) { return site; } return myVariableSites[site]; } catch (Exception e) { return site; } } private void recalcLocusCoordinates() { myLociOffsets=new int[myLocusList.size()]; int currStart=0; int currLIndex=myLocusIndices[currStart]; myLociOffsets[0]=currStart; for (int s = 0; s < myNumSites; s++) { if(currLIndex!=myLocusIndices[s]) { String name=getLocus(currStart).getName(); myLocusList.set(currLIndex, new Locus(name, name, currStart, s-1, null, null)); currStart=s; currLIndex=myLocusIndices[s]; myLociOffsets[currLIndex]=currStart; } } String name=getLocus(currStart).getName(); myLocusList.set(currLIndex, new Locus(name, name, currStart, myNumSites-1, null, null)); } @Override public Locus[] getLoci() { Locus[] result = new Locus[myLocusList.size()]; for (int i = 0; i < myLocusList.size(); i++) result[i] = myLocusList.get(i); return result; } @Override public int getNumLoci() { return myLocusList.size(); } @Override public Locus getLocus(int site) { return myLocusList.get(myLocusIndices[site]); } @Override public int[] getLociOffsets() { return myLociOffsets; } @Override public int[] getStartAndEndOfLocus(Locus locus) { for (Locus mL : myLocusList) { if(mL.getName().equals(locus.getName())) return new int[]{mL.getStart(),mL.getEnd()}; } return null; } @Override public String[] getSNPIDs() { String[] rsi=new String[myNumSites]; for (int i = 0; i < rsi.length; i++) { rsi[i]=getSNPID(i); } return rsi; } @Override public String getSNPID(int site) { try{ SiteAnnotation sa=mySiteAnnoCache.get(site); if(sa.mySNPIDs!=null) return sa.mySNPIDs; } catch(ExecutionException e) { return "S" + getLocus(site).getChromosomeName() + "_" + getPositionInLocus(site); } return "S" + getLocus(site).getChromosomeName() + "_" + getPositionInLocus(site); } @Override public int getSiteOfPhysicalPosition(int physicalPosition, Locus locus) { if (isDirty()) { throw new IllegalStateException("MutableBitNucleotideAlignmentHDF5: getSiteOfPhysicalPosition: this alignment is dirty."); } if (myVariableSites == null) { return physicalPosition; } try { if (locus == null) { locus = myLocusList.get(0); } int[] startEnd = getStartAndEndOfLocus(locus); return Arrays.binarySearch(myVariableSites, startEnd[0], startEnd[1], physicalPosition); } catch (Exception e) { e.printStackTrace(); return -1; } } @Override public int getSiteOfPhysicalPosition(int physicalPosition, Locus locus, String snpID) { if (isDirty()) { throw new IllegalStateException("MutableBitNucleotideAlignmentHDF5: getSiteOfPhysicalPosition: this alignment is dirty."); } if (myVariableSites == null) { return physicalPosition; } if (locus == null) { locus = myLocusList.get(0); } int[] startEnd = getStartAndEndOfLocus(locus); int result = Arrays.binarySearch(myVariableSites, startEnd[0], startEnd[1], physicalPosition); if (result < 0) { return result; } else { if (snpID.equals(getSNPID(result))) { return result; } else { int index = result - 1; while ((index >= startEnd[0]) && (getPositionInLocus(index) == physicalPosition)) { if (snpID.equals(getSNPID(index))) { return index; } index } index = result + 1; while ((index < startEnd[1]) && (getPositionInLocus(index) == physicalPosition)) { if (snpID.equals(getSNPID(index))) { return index; } index++; } return -result - 1; } } } @Override public boolean retainsRareAlleles() { return false; } @Override public byte[] getAlleles(int site) { try{ SiteAnnotation sa=mySiteAnnoCache.get(site); return sa.myAlleleFreqOrder; } catch(ExecutionException e) { e.printStackTrace(); throw new UnsupportedOperationException("Error in getMinorAlleleFrequency from cache"); } } @Override public int[][] getAllelesSortedByFrequency(int site) { try{ SiteAnnotation sa=mySiteAnnoCache.get(site); return sa.getAllelesSortedByFrequency(); } catch(ExecutionException e) { e.printStackTrace(); throw new UnsupportedOperationException("Error in getMinorAlleleFrequency from cache"); } } @Override public int getTotalGametesNotMissing(int site) { try{ SiteAnnotation sa=mySiteAnnoCache.get(site); return sa.getAlleleTotal(); } catch(ExecutionException e) { e.printStackTrace(); throw new UnsupportedOperationException("Error in getMinorAlleleFrequency from cache"); } } public void setCacheHints(int numberOfTaxa, int numberOfSites) { //Number of taxa to keep in the cache //size of the block of sequence to cache. //linkedHashList <Taxon, <startSite,byte[]>> } // Mutable Methods... public void setBase(int taxon, int site, byte newBase) { throw new UnsupportedOperationException("Not supported. Set all genotypes at once using setAllBases."); //this.myWriter.writeByteArrayBlock(getTaxaGenoPath(taxon),new byte[]{newBase},site); //cacheTaxonSiteBlock(taxon, site); } public void setBase(Identifier taxon, String siteName, Locus locus, int physicalPosition, byte newBase) { throw new UnsupportedOperationException("Not supported. Set all genotypes at once using setAllBases."); } public synchronized void setBaseRange(int taxon, int startSite, byte[] newBases) { throw new UnsupportedOperationException("Not supported. Set all genotypes at once using setAllBases."); } public synchronized void setAllBases(int taxon, byte[] newBases) { setAllBases(getTaxaGenoPath(taxon), newBases); } private synchronized void setAllBases(String taxonGenoPath, byte[] newBases) { writeHDF5EntireArray(taxonGenoPath, newBases, newBases.length); myGenoCache.invalidateAll(); myIsDirty=true; } public synchronized void setAllDepth(int taxon, byte[][] depth) { if(depth.length!=6) throw new IllegalStateException("Just set A, C, G, T, -, + all at once"); if(depth[0].length!=myNumSites) throw new IllegalStateException("Setting all depth. Wrong number of sites"); myWriter.writeByteMatrix(getTaxaDepthPath(taxon), depth, genoFeatures); // for (int site = 0; site < newBases.length; site+=defaultSiteCache) { // cacheTaxonSiteBlock(taxon, site); //myIsDirty=true; } @Override public void setDepthForAlleles(int taxon, int site, byte[] values) { throw new UnsupportedOperationException("Not supported. Set all depths at once using setAllDepth."); } @Override public void setReferenceAllele(int site, byte diploidAllele) { myReference[site] = diploidAllele; } @Override public synchronized void addTaxon(Identifier id) { byte[] unkArray=new byte[getSiteCount()]; Arrays.fill(unkArray, UNKNOWN_DIPLOID_ALLELE); addTaxon(id, unkArray, null); } public synchronized void addTaxon(Identifier id, byte[] genotype, byte[][] depth) { int chunk=1<<16; if(myNumSites<chunk) chunk=myNumSites; String basesPath = HapMapHDF5Constants.GENOTYPES + "/" + id.getFullName(); if(myWriter.exists(basesPath)) throw new IllegalStateException("Taxa Name Already Exists:"+basesPath); if(genotype.length!=myNumSites) throw new IllegalStateException("Setting all genotypes in addTaxon. Wrong number of sites"); myWriter.createByteArray(basesPath, myNumSites, chunk, genoFeatures); setAllBases(basesPath, genotype); int taxonIndex=myIdentifiers.size(); myIdentifiers.add(id); myIdGroup=null; if(depth!=null) { if(depth.length!=6) throw new IllegalStateException("Just set A, C, G, T, -, + all at once"); if(depth[0].length!=myNumSites) throw new IllegalStateException("Setting all depth in addTaxon. Wrong number of sites"); myWriter.writeByteMatrix(getTaxaDepthPath(taxonIndex), depth, genoFeatures); } myIsDirty=true; } @Override public synchronized void setTaxonName(int taxon, Identifier id) { if (taxon >= myIdentifiers.size()) { throw new IllegalStateException("MutableBitNucleotideAlignmentHDF5: setTaxonName: this taxa index does not exist: " + taxon); } String currentPath = getTaxaGenoPath(taxon); String newPath = HapMapHDF5Constants.GENOTYPES + "/" + id.getFullName(); myWriter.move(currentPath, newPath); myIdentifiers.set(taxon, id); myIdGroup=null; myIsDirty=true; } @Override public synchronized void removeTaxon(int taxon) { String currentPath = getTaxaGenoPath(taxon); // System.out.println(currentPath); myWriter.delete(currentPath); myIdGroup=null; myIdentifiers.remove(taxon); // System.out.println(getTaxaGenoPath(taxon)); myGenoCache.invalidateAll(); myIsDirty=true; } private void loadSiteDescriptorsToMemory() { // myAlleleCnt=myWriter.readIntMatrix(HapMapHDF5Constants.ALLELE_CNT); myAlleleFreqOrder=myWriter.readByteMatrix(HapMapHDF5Constants.ALLELE_FREQ_ORD); // maf=myWriter.readFloatArray(HapMapHDF5Constants.MAF); // siteCov=myWriter.readFloatArray(HapMapHDF5Constants.SITECOV); } @Override public void clean() { long time=System.currentTimeMillis(); System.out.print("Starting clean ..."); recalcLocusCoordinates(); int chunk=(myNumSites<hdf5GenoBlock)?myNumSites:hdf5GenoBlock; myWriter.createIntMatrix(HapMapHDF5Constants.ALLELE_CNT, 6, myNumSites, 1, chunk, genoFeatures); myWriter.createByteMatrix(HapMapHDF5Constants.ALLELE_FREQ_ORD, 6, myNumSites, 1, chunk, genoFeatures); myWriter.createFloatArray(HapMapHDF5Constants.MAF, myNumSites, chunk, floatFeatures); myWriter.createFloatArray(HapMapHDF5Constants.SITECOV, myNumSites, chunk, floatFeatures); chunk=(getSequenceCount()<hdf5GenoBlock)?getSequenceCount():hdf5GenoBlock; myWriter.createFloatArray(HapMapHDF5Constants.TAXACOV, getSequenceCount(), chunk, floatFeatures); myWriter.createFloatArray(HapMapHDF5Constants.TAXAHET, getSequenceCount(), chunk, floatFeatures); if(myIdentifiers.size()>0) { HDF5AlignmentAnnotator faCalc=new HDF5AlignmentAnnotator(this, fileName, HDF5AlignmentAnnotator.AnnoType.ALLELEFreq); faCalc.run(); } System.out.printf("finished in %dms%n",System.currentTimeMillis()-time); myIsDirty = false; myNumSites -= myNumSitesStagedToRemove; myNumSitesStagedToRemove = 0; //save the out cache to file //re-sort the taxa names } @Override public double getMajorAlleleFrequency(int site) { return 1-getMinorAlleleFrequency(site); } @Override public double getMinorAlleleFrequency(int site) { try{ SiteAnnotation sa=mySiteAnnoCache.get(site); return sa.maf; } catch(ExecutionException e) { e.printStackTrace(); throw new UnsupportedOperationException("Error in getMinorAlleleFrequency from cache"); } } @Override public byte getMajorAllele(int site) { return myAlleleFreqOrder[0][site]; } @Override public byte getMinorAllele(int site) { return myAlleleFreqOrder[1][site]; } public float getSiteCoverage(int site) { try{ SiteAnnotation sa=mySiteAnnoCache.get(site); return sa.siteCov; } catch(ExecutionException e) { e.printStackTrace(); throw new UnsupportedOperationException("Error in getMinorAlleleFrequency from cache"); } } @Override public boolean isDirty() { return myIsDirty; } private void setDirty() { myIsDirty = true; } private void setClean() { myIsDirty = false; } public int getDefaultCacheSize() { return defaultCacheSize; } public void setDefaultCacheSize(int defaultCacheSize) { this.defaultCacheSize = defaultCacheSize; initGenotypeCache(); } public int getDefaultSiteCache() { return defaultSiteCache; } public void setDefaultSiteCache(int defaultSiteCache) { this.defaultSiteCache = defaultSiteCache; initGenotypeCache(); } public void setCommonAlleles(int site, byte[] values) { throw new UnsupportedOperationException("Not supported yet."); } /** * Set annotations of sites and taxa. The sites annotations should probably be * set by block in general and not by all. * @param af * @param afOrder * @param maf * @param paf * @param coverage * @param hets */ protected void setCalcAlleleFreq(int[][] af, byte[][] afOrder, float[] maf, float[] paf, float[] coverage, float[] hets) { if(af[0].length>0) writeHDF5EntireArray(HapMapHDF5Constants.ALLELE_CNT,af, af[0].length); if(afOrder[0].length>0) writeHDF5EntireArray(HapMapHDF5Constants.ALLELE_FREQ_ORD,afOrder, afOrder[0].length); if(maf.length>0) writeHDF5EntireArray(HapMapHDF5Constants.MAF,maf, maf.length); if(paf.length>0) writeHDF5EntireArray(HapMapHDF5Constants.SITECOV,paf, paf.length); if(coverage.length>0) writeHDF5EntireArray(HapMapHDF5Constants.TAXACOV,coverage, coverage.length); if(hets.length>0) { System.out.println("Hets Length:"+hets.length); writeHDF5EntireArray(HapMapHDF5Constants.TAXAHET,hets, hets.length); } } protected void writeHDF5EntireArray(String objectPath, Object val, int objMaxLength) { writeHDF5EntireArray(objectPath, myWriter, objMaxLength, hdf5GenoBlock, val); } protected void writeHDF5Block(String objectPath, int block, Object val) { writeHDF5Block(objectPath, myWriter, hdf5GenoBlock, block, val); } /** * Needs to go the a JHDF5 Utils. */ public static void writeHDF5EntireArray(String objectPath, IHDF5Writer myWriter, int objMaxLength, int blockSize, Object val) { int blocks=((objMaxLength-1)/blockSize)+1; for (int block = 0; block < blocks; block++) { int startPos=block*blockSize; int length=((objMaxLength-startPos)>blockSize)?blockSize:objMaxLength-startPos; if(val instanceof byte[][]) { byte[][] oval=(byte[][])val; byte[][] sval=new byte[oval.length][length]; for (int j = 0; j < oval.length; j++) { sval[j]=Arrays.copyOfRange(oval[j], startPos, startPos+length); } writeHDF5Block(objectPath, myWriter, blockSize, block, sval); } else if(val instanceof int[][]) { int[][] oval=(int[][])val; int[][] sval=new int[oval.length][length]; for (int j = 0; j < oval.length; j++) { sval[j]=Arrays.copyOfRange(oval[j], startPos, startPos+length); } writeHDF5Block(objectPath, myWriter, blockSize, block, sval); } else if(val instanceof byte[]) { writeHDF5Block(objectPath, myWriter, blockSize, block, Arrays.copyOfRange((byte[])val, startPos, startPos+length)); } else if(val instanceof float[]) { writeHDF5Block(objectPath, myWriter, blockSize, block, Arrays.copyOfRange((float[])val, startPos, startPos+length)); } else if(val instanceof int[]) { writeHDF5Block(objectPath, myWriter, blockSize, block, Arrays.copyOfRange((int[])val, startPos, startPos+length)); } else if(val instanceof String[]) { writeHDF5Block(objectPath, myWriter, blockSize, block, Arrays.copyOfRange((String[])val, startPos, startPos+length)); } } } /** * Needs to go the a JHDF5 Utils. */ public static void writeHDF5Block(String objectPath, IHDF5Writer myWriter, int blockSize, int block, Object val) { int startPos=block*blockSize; if(val instanceof byte[]) { byte[] fval=(byte[])val; myWriter.writeByteArrayBlockWithOffset(objectPath, fval, fval.length, (long)startPos); } else if(val instanceof float[]) { float[] fval=(float[])val; myWriter.writeFloatArrayBlockWithOffset(objectPath, fval, fval.length, (long)startPos); } else if(val instanceof int[]) { int[] fval=(int[])val; myWriter.writeIntArrayBlockWithOffset(objectPath, fval, fval.length, (long)startPos); } else if(val instanceof int[][]) { int[][] ival=(int[][])val; myWriter.writeIntMatrixBlockWithOffset(objectPath, ival, ival.length, ival[0].length, 0l, (long)startPos); } else if(val instanceof byte[][]) { byte[][] bval=(byte[][])val; myWriter.writeByteMatrixBlockWithOffset(objectPath, bval, bval.length, bval[0].length, 0l, (long)startPos); } else if(val instanceof String[]) { String[] sval=(String[])val; myWriter.writeStringArrayBlockWithOffset(objectPath, sval, sval.length, (long)startPos); } } @Override public void addSite(int site) { throw new UnsupportedOperationException("Will not be supported"); } @Override public void removeSite(int site) { throw new UnsupportedOperationException("Will not be supported."); } @Override public void clearSiteForRemoval(int site) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void setPositionOfSite(int site, int position) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void setLocusOfSite(int site, Locus locus) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void setSNPID(int site, String name) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } } class LRUCache<K, V> extends LinkedHashMap<K, V> { private final int limit; public LRUCache(int limit) { super(16, 0.75f, true); this.limit = limit; } @Override protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { return size() > limit; } }
package org.bitbucket.mlopatkin.android.logviewer; import java.util.Date; import java.util.List; import javax.swing.table.AbstractTableModel; import org.bitbucket.mlopatkin.android.liblogcat.LogRecord; import org.bitbucket.mlopatkin.android.liblogcat.LogRecord.Priority; public class LogRecordsTableModel extends AbstractTableModel { private List<LogRecord> records; private static final int COLUMNS_COUNT = 6; public static final int COLUMN_TIME = 0; public static final int COLUMN_PID = 1; public static final int COLUMN_TID = 2; public static final int COLUMN_PRIORITY = 3; public static final int COLUMN_TAG = 4; public static final int COLUMN_MSG = 5; public LogRecordsTableModel(List<LogRecord> records) { this.records = records; } @Override public int getColumnCount() { return COLUMNS_COUNT; } @Override public int getRowCount() { return records.size(); } @Override public Object getValueAt(int rowIndex, int columnIndex) { LogRecord record = records.get(rowIndex); switch (columnIndex) { case COLUMN_TIME: return record.getTime(); case COLUMN_PID: return record.getPid(); case COLUMN_TID: return record.getTid(); case COLUMN_PRIORITY: return record.getPriority(); case COLUMN_TAG: return record.getTag(); case COLUMN_MSG: return record.getMessage(); default: throw new IllegalArgumentException("Incorrect column number"); } } @Override public Class<?> getColumnClass(int columnIndex) { switch (columnIndex) { case COLUMN_TIME: return Date.class; case COLUMN_PRIORITY: return Priority.class; default: return super.getColumnClass(columnIndex); } } }
package org.opendaylight.netvirt.natservice.internal; import static org.opendaylight.genius.infra.Datastore.CONFIGURATION; import com.google.common.base.Optional; import java.math.BigInteger; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutionException; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.inject.Singleton; import org.eclipse.jdt.annotation.Nullable; import org.opendaylight.controller.md.sal.binding.api.DataBroker; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.genius.datastoreutils.AsyncDataTreeChangeListenerBase; import org.opendaylight.genius.datastoreutils.SingleTransactionDataBroker; import org.opendaylight.genius.infra.Datastore.Configuration; import org.opendaylight.genius.infra.ManagedNewTransactionRunner; import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl; import org.opendaylight.genius.infra.TypedReadWriteTransaction; import org.opendaylight.genius.mdsalutil.ActionInfo; import org.opendaylight.genius.mdsalutil.FlowEntity; import org.opendaylight.genius.mdsalutil.InstructionInfo; import org.opendaylight.genius.mdsalutil.MDSALUtil; import org.opendaylight.genius.mdsalutil.MatchInfo; import org.opendaylight.genius.mdsalutil.MetaDataUtil; import org.opendaylight.genius.mdsalutil.NwConstants; import org.opendaylight.genius.mdsalutil.actions.ActionNxLoadInPort; import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit; import org.opendaylight.genius.mdsalutil.actions.ActionSetDestinationIp; import org.opendaylight.genius.mdsalutil.actions.ActionSetFieldEthernetSource; import org.opendaylight.genius.mdsalutil.actions.ActionSetSourceIp; import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions; import org.opendaylight.genius.mdsalutil.instructions.InstructionGotoTable; import org.opendaylight.genius.mdsalutil.instructions.InstructionWriteMetadata; import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager; import org.opendaylight.genius.mdsalutil.matches.MatchEthernetDestination; import org.opendaylight.genius.mdsalutil.matches.MatchEthernetType; import org.opendaylight.genius.mdsalutil.matches.MatchIpv4Destination; import org.opendaylight.genius.mdsalutil.matches.MatchIpv4Source; import org.opendaylight.genius.mdsalutil.matches.MatchMetadata; import org.opendaylight.infrautils.jobcoordinator.JobCoordinator; import org.opendaylight.infrautils.utils.concurrent.ListenableFutures; import org.opendaylight.netvirt.natservice.api.CentralizedSwitchScheduler; import org.opendaylight.netvirt.natservice.api.NatSwitchCache; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id.VpnInstance; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ExternalNetworks; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.FloatingIpInfo; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ProviderTypes; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.external.networks.Networks; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.external.networks.NetworksKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.floating.ip.info.RouterPorts; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.floating.ip.info.router.ports.Ports; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.floating.ip.info.router.ports.PortsBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.floating.ip.info.router.ports.PortsKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.floating.ip.info.router.ports.ports.InternalToExternalPortMap; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.floating.ip.info.router.ports.ports.InternalToExternalPortMapBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.floating.ip.info.router.ports.ports.InternalToExternalPortMapKey; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.opendaylight.yangtools.yang.common.Uint32; import org.opendaylight.yangtools.yang.common.Uint64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public class FloatingIPListener extends AsyncDataTreeChangeListenerBase<InternalToExternalPortMap, FloatingIPListener> { private static final Logger LOG = LoggerFactory.getLogger(FloatingIPListener.class); private final DataBroker dataBroker; private final ManagedNewTransactionRunner txRunner; private final IMdsalApiManager mdsalManager; private final OdlInterfaceRpcService interfaceManager; private final FloatingIPHandler floatingIPHandler; private final SNATDefaultRouteProgrammer defaultRouteProgrammer; private final JobCoordinator coordinator; private final CentralizedSwitchScheduler centralizedSwitchScheduler; private final NatSwitchCache natSwitchCache; @Inject public FloatingIPListener(final DataBroker dataBroker, final IMdsalApiManager mdsalManager, final OdlInterfaceRpcService interfaceManager, final FloatingIPHandler floatingIPHandler, final SNATDefaultRouteProgrammer snatDefaultRouteProgrammer, final JobCoordinator coordinator, final CentralizedSwitchScheduler centralizedSwitchScheduler, final NatSwitchCache natSwitchCache) { super(InternalToExternalPortMap.class, FloatingIPListener.class); this.dataBroker = dataBroker; this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker); this.mdsalManager = mdsalManager; this.interfaceManager = interfaceManager; this.floatingIPHandler = floatingIPHandler; this.defaultRouteProgrammer = snatDefaultRouteProgrammer; this.coordinator = coordinator; this.centralizedSwitchScheduler = centralizedSwitchScheduler; this.natSwitchCache = natSwitchCache; } @Override @PostConstruct public void init() { LOG.info("{} init", getClass().getSimpleName()); registerListener(LogicalDatastoreType.CONFIGURATION, dataBroker); } @Override protected InstanceIdentifier<InternalToExternalPortMap> getWildCardPath() { return InstanceIdentifier.create(FloatingIpInfo.class).child(RouterPorts.class).child(Ports.class) .child(InternalToExternalPortMap.class); } @Override protected FloatingIPListener getDataTreeChangeListener() { return FloatingIPListener.this; } @Override protected void add(final InstanceIdentifier<InternalToExternalPortMap> identifier, final InternalToExternalPortMap mapping) { LOG.trace("FloatingIPListener add ip mapping method - key: {} value: {}",mapping.key(), mapping); processFloatingIPAdd(identifier, mapping); } @Override protected void remove(InstanceIdentifier<InternalToExternalPortMap> identifier, InternalToExternalPortMap mapping) { LOG.trace("FloatingIPListener remove ip mapping method - kkey: {} value: {}",mapping.key(), mapping); processFloatingIPDel(identifier, mapping); } @Override protected void update(InstanceIdentifier<InternalToExternalPortMap> identifier, InternalToExternalPortMap original, InternalToExternalPortMap update) { LOG.trace("FloatingIPListener update ip mapping method - key: {}, original: {}, update: {}", update.key(), original, update); } @Nullable private FlowEntity buildPreDNATFlowEntity(Uint64 dpId, InternalToExternalPortMap mapping, Uint32 routerId, Uint32 associatedVpn) { String externalIp = mapping.getExternalIp(); Uuid floatingIpId = mapping.getExternalId(); //Get the FIP MAC address for DNAT String floatingIpPortMacAddress = NatUtil.getFloatingIpPortMacFromFloatingIpId(dataBroker, floatingIpId); if (floatingIpPortMacAddress == null) { LOG.error("buildPreDNATFlowEntity : Unable to retrieve floatingIpPortMacAddress from floating IP UUID {} " + "for floating IP {}", floatingIpId, externalIp); return null; } LOG.debug("buildPreDNATFlowEntity : Bulding DNAT Flow entity for ip {} ", externalIp); Uint32 segmentId = associatedVpn == NatConstants.INVALID_ID ? routerId : associatedVpn; LOG.debug("buildPreDNATFlowEntity : Segment id {} in build preDNAT Flow", segmentId); List<MatchInfo> matches = new ArrayList<>(); matches.add(MatchEthernetType.IPV4); matches.add(new MatchIpv4Destination(externalIp, "32")); //Match Destination Floating IP MAC Address on table = 25 (PDNAT_TABLE) matches.add(new MatchEthernetDestination(new MacAddress(floatingIpPortMacAddress))); // matches.add(new MatchMetadata( // BigInteger.valueOf(vpnId), MetaDataUtil.METADATA_MASK_VRFID)); List<ActionInfo> actionsInfos = new ArrayList<>(); String internalIp = mapping.getInternalIp(); actionsInfos.add(new ActionSetDestinationIp(internalIp, "32")); List<InstructionInfo> instructions = new ArrayList<>(); instructions.add(new InstructionWriteMetadata(MetaDataUtil.getVpnIdMetadata(segmentId.longValue()), MetaDataUtil.METADATA_MASK_VRFID)); instructions.add(new InstructionApplyActions(actionsInfos)); instructions.add(new InstructionGotoTable(NwConstants.DNAT_TABLE)); String flowRef = NatUtil.getFlowRef(dpId, NwConstants.PDNAT_TABLE, routerId, externalIp); FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.PDNAT_TABLE, flowRef, NatConstants.DEFAULT_DNAT_FLOW_PRIORITY, flowRef, 0, 0, NwConstants.COOKIE_DNAT_TABLE, matches, instructions); return flowEntity; } private FlowEntity buildDNATFlowEntity(Uint64 dpId, InternalToExternalPortMap mapping, Uint32 routerId, Uint32 associatedVpn) { String externalIp = mapping.getExternalIp(); LOG.info("buildDNATFlowEntity : Bulding DNAT Flow entity for ip {} ", externalIp); Uint32 segmentId = associatedVpn == NatConstants.INVALID_ID ? routerId : associatedVpn; LOG.debug("buildDNATFlowEntity : Segment id {} in build DNAT", segmentId); List<MatchInfo> matches = new ArrayList<>(); matches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(segmentId.longValue()), MetaDataUtil.METADATA_MASK_VRFID)); matches.add(MatchEthernetType.IPV4); String internalIp = mapping.getInternalIp(); matches.add(new MatchIpv4Destination(internalIp, "32")); List<ActionInfo> actionsInfos = new ArrayList<>(); // actionsInfos.add(new ActionSetDestinationIp(internalIp, "32")); List<InstructionInfo> instructions = new ArrayList<>(); // instructions.add(new InstructionWriteMetadata(Uint64.valueOf // (routerId), MetaDataUtil.METADATA_MASK_VRFID)); actionsInfos.add(new ActionNxLoadInPort(Uint64.valueOf(BigInteger.ZERO))); actionsInfos.add(new ActionNxResubmit(NwConstants.L3_FIB_TABLE)); instructions.add(new InstructionApplyActions(actionsInfos)); //instructions.add(new InstructionGotoTable(NatConstants.L3_FIB_TABLE)); String flowRef = NatUtil.getFlowRef(dpId, NwConstants.DNAT_TABLE, routerId, internalIp); FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.DNAT_TABLE, flowRef, NatConstants.DEFAULT_DNAT_FLOW_PRIORITY, flowRef, 0, 0, NwConstants.COOKIE_DNAT_TABLE, matches, instructions); return flowEntity; } private FlowEntity buildPreSNATFlowEntity(Uint64 dpId, String internalIp, String externalIp, Uint32 vpnId, Uint32 routerId, Uint32 associatedVpn) { LOG.debug("buildPreSNATFlowEntity : Building PSNAT Flow entity for ip {} ", internalIp); Uint32 segmentId = associatedVpn == NatConstants.INVALID_ID ? routerId : associatedVpn; LOG.debug("buildPreSNATFlowEntity : Segment id {} in build preSNAT flow", segmentId); List<MatchInfo> matches = new ArrayList<>(); matches.add(MatchEthernetType.IPV4); matches.add(new MatchIpv4Source(internalIp, "32")); matches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(segmentId.longValue()), MetaDataUtil.METADATA_MASK_VRFID)); List<ActionInfo> actionsInfos = new ArrayList<>(); actionsInfos.add(new ActionSetSourceIp(externalIp, "32")); List<InstructionInfo> instructions = new ArrayList<>(); instructions.add( new InstructionWriteMetadata(MetaDataUtil.getVpnIdMetadata(vpnId.longValue()), MetaDataUtil.METADATA_MASK_VRFID)); instructions.add(new InstructionApplyActions(actionsInfos)); instructions.add(new InstructionGotoTable(NwConstants.SNAT_TABLE)); String flowRef = NatUtil.getFlowRef(dpId, NwConstants.PSNAT_TABLE, routerId, internalIp); FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.PSNAT_TABLE, flowRef, NatConstants.DEFAULT_DNAT_FLOW_PRIORITY, flowRef, 0, 0, NwConstants.COOKIE_DNAT_TABLE, matches, instructions); return flowEntity; } @Nullable private FlowEntity buildSNATFlowEntity(Uint64 dpId, InternalToExternalPortMap mapping, Uint32 vpnId, Uuid externalNetworkId) { String internalIp = mapping.getInternalIp(); LOG.debug("buildSNATFlowEntity : Building SNAT Flow entity for ip {} ", internalIp); ProviderTypes provType = NatUtil.getProviderTypefromNetworkId(dataBroker, externalNetworkId); if (provType == null) { LOG.error("buildSNATFlowEntity : Unable to get Network Provider Type for network {}", externalNetworkId); return null; } List<MatchInfo> matches = new ArrayList<>(); matches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(vpnId.longValue()), MetaDataUtil.METADATA_MASK_VRFID)); matches.add(MatchEthernetType.IPV4); String externalIp = mapping.getExternalIp(); matches.add(new MatchIpv4Source(externalIp, "32")); List<ActionInfo> actionsInfo = new ArrayList<>(); actionsInfo.add(new ActionNxLoadInPort(Uint64.valueOf(BigInteger.ZERO))); Uuid floatingIpId = mapping.getExternalId(); String macAddress = NatUtil.getFloatingIpPortMacFromFloatingIpId(dataBroker, floatingIpId); if (macAddress != null) { actionsInfo.add(new ActionSetFieldEthernetSource(new MacAddress(macAddress))); } else { LOG.warn("buildSNATFlowEntity : No MAC address found for floating IP {}", externalIp); } LOG.trace("buildSNATFlowEntity : External Network Provider Type is {}, resubmit to FIB", provType.toString()); actionsInfo.add(new ActionNxResubmit(NwConstants.L3_FIB_TABLE)); List<InstructionInfo> instructions = new ArrayList<>(); instructions.add(new InstructionApplyActions(actionsInfo)); String flowRef = NatUtil.getFlowRef(dpId, NwConstants.SNAT_TABLE, vpnId, externalIp); FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.SNAT_TABLE, flowRef, NatConstants.DEFAULT_DNAT_FLOW_PRIORITY, flowRef, 0, 0, NwConstants.COOKIE_DNAT_TABLE, matches, instructions); return flowEntity; } private void createDNATTblEntry(Uint64 dpnId, InternalToExternalPortMap mapping, Uint32 routerId, Uint32 associatedVpnId, TypedReadWriteTransaction<Configuration> confTx) { FlowEntity preFlowEntity = buildPreDNATFlowEntity(dpnId, mapping, routerId, associatedVpnId); if (preFlowEntity == null) { LOG.error("createDNATTblEntry : Flow entity received as NULL. " + "Cannot proceed with installation of Pre-DNAT flow table {} --> table {} on DpnId {}", NwConstants.PDNAT_TABLE, NwConstants.DNAT_TABLE, dpnId); } else { mdsalManager.addFlow(confTx, preFlowEntity); FlowEntity flowEntity = buildDNATFlowEntity(dpnId, mapping, routerId, associatedVpnId); if (flowEntity != null) { mdsalManager.addFlow(confTx, flowEntity); } } } private void removeDNATTblEntry(Uint64 dpnId, String internalIp, String externalIp, Uint32 routerId, TypedReadWriteTransaction<Configuration> confTx) throws ExecutionException, InterruptedException { FlowEntity preFlowEntity = buildPreDNATDeleteFlowEntity(dpnId, externalIp, routerId); mdsalManager.removeFlow(confTx, preFlowEntity); FlowEntity flowEntity = buildDNATDeleteFlowEntity(dpnId, internalIp, routerId); if (flowEntity != null) { mdsalManager.removeFlow(confTx, flowEntity); } } private void createSNATTblEntry(Uint64 dpnId, InternalToExternalPortMap mapping, Uint32 vpnId, Uint32 routerId, Uint32 associatedVpnId, Uuid externalNetworkId, TypedReadWriteTransaction<Configuration> confTx) { FlowEntity preFlowEntity = buildPreSNATFlowEntity(dpnId, mapping.getInternalIp(), mapping.getExternalIp(), vpnId, routerId, associatedVpnId); mdsalManager.addFlow(confTx, preFlowEntity); FlowEntity flowEntity = buildSNATFlowEntity(dpnId, mapping, vpnId, externalNetworkId); if (flowEntity != null) { mdsalManager.addFlow(confTx, flowEntity); } } private void removeSNATTblEntry(Uint64 dpnId, String internalIp, String externalIp, Uint32 routerId, Uint32 vpnId, TypedReadWriteTransaction<Configuration> removeFlowInvTx) throws ExecutionException, InterruptedException { FlowEntity preFlowEntity = buildPreSNATDeleteFlowEntity(dpnId, internalIp, routerId); mdsalManager.removeFlow(removeFlowInvTx, preFlowEntity); FlowEntity flowEntity = buildSNATDeleteFlowEntity(dpnId, externalIp, vpnId); if (flowEntity != null) { mdsalManager.removeFlow(removeFlowInvTx, flowEntity); } } @Nullable private Uuid getExtNetworkId(final InstanceIdentifier<RouterPorts> portIid, LogicalDatastoreType dataStoreType) { Optional<RouterPorts> rtrPort = SingleTransactionDataBroker.syncReadOptionalAndTreatReadFailedExceptionAsAbsentOptional(dataBroker, dataStoreType, portIid); if (!rtrPort.isPresent()) { LOG.error("getExtNetworkId : Unable to read router port entry for {}", portIid); return null; } return rtrPort.get().getExternalNetworkId(); } private Uuid getVpnUuid(Uuid extNwId, Uuid floatingIpExternalId) { InstanceIdentifier<Networks> nwId = InstanceIdentifier.builder(ExternalNetworks.class).child(Networks.class, new NetworksKey(extNwId)).build(); Optional<Networks> nw = SingleTransactionDataBroker.syncReadOptionalAndTreatReadFailedExceptionAsAbsentOptional(dataBroker, LogicalDatastoreType.CONFIGURATION, nwId); if (!nw.isPresent()) { LOG.error("getVpnId : Unable to read external network for {}", extNwId); return null; } ProviderTypes providerType = nw.get().getProviderNetworkType(); if (providerType == ProviderTypes.FLAT || providerType == ProviderTypes.VLAN) { Uuid subnetId = NatUtil .getFloatingIpPortSubnetIdFromFloatingIpId(dataBroker, floatingIpExternalId); if (subnetId != null) { return subnetId; } } Uuid vpnUuid = nw.get().getVpnid(); if (vpnUuid == null) { LOG.error("getVpnId : Unable to read vpn from External network: {}", extNwId); return null; } return vpnUuid; } private Uint32 getVpnId(Uuid extNwId, Uuid floatingIpExternalId) { Uuid vpnUuid = getVpnUuid(extNwId, floatingIpExternalId); //Get the id using the VPN UUID (also vpn instance name) return vpnUuid != null ? NatUtil.getVpnId(dataBroker, vpnUuid.getValue()) : NatConstants.INVALID_ID; } private void processFloatingIPAdd(final InstanceIdentifier<InternalToExternalPortMap> identifier, final InternalToExternalPortMap mapping) { LOG.trace("processFloatingIPAdd key: {}, value: {}", mapping.key(), mapping); final String routerId = identifier.firstKeyOf(RouterPorts.class).getRouterId(); final PortsKey pKey = identifier.firstKeyOf(Ports.class); String interfaceName = pKey.getPortName(); InstanceIdentifier<RouterPorts> portIid = identifier.firstIdentifierOf(RouterPorts.class); coordinator.enqueueJob(NatConstants.NAT_DJC_PREFIX + mapping.key(), () -> Collections.singletonList( txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION, tx -> createNATFlowEntries(interfaceName, mapping, portIid, routerId, null, tx))), NatConstants.NAT_DJC_MAX_RETRIES); } private void processFloatingIPDel(final InstanceIdentifier<InternalToExternalPortMap> identifier, final InternalToExternalPortMap mapping) { LOG.trace("processFloatingIPDel : key: {}, value: {}", mapping.key(), mapping); final String routerId = identifier.firstKeyOf(RouterPorts.class).getRouterId(); final PortsKey pKey = identifier.firstKeyOf(Ports.class); String interfaceName = pKey.getPortName(); InstanceIdentifier<RouterPorts> portIid = identifier.firstIdentifierOf(RouterPorts.class); coordinator.enqueueJob(NatConstants.NAT_DJC_PREFIX + mapping.key(), () -> Collections.singletonList( txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION, tx -> removeNATFlowEntries(interfaceName, mapping, portIid, routerId, null, tx))), NatConstants.NAT_DJC_MAX_RETRIES); } private InetAddress getInetAddress(String ipAddr) { InetAddress ipAddress = null; try { ipAddress = InetAddress.getByName(ipAddr); } catch (UnknownHostException e) { LOG.error("getInetAddress : UnknowHostException for ip {}", ipAddr, e); } return ipAddress; } private boolean validateIpMapping(InternalToExternalPortMap mapping) { return getInetAddress(mapping.getInternalIp()) != null && getInetAddress(mapping.getExternalIp()) != null; } private Uint64 getAssociatedDpnWithExternalInterface(final String routerName, Uuid extNwId, Uint64 dpnId, String interfaceName) { //Get the DPN on which this interface resides if (dpnId == null) { org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces .state.Interface interfaceState = NatUtil.getInterfaceStateFromOperDS(dataBroker, interfaceName); if (interfaceState != null) { dpnId = NatUtil.getDpIdFromInterface(interfaceState); } } Uint64 updatedDpnId = dpnId; if (updatedDpnId != null && updatedDpnId.equals(Uint64.ZERO)) { LOG.debug("getAssociatedDpnWithExternalInterface : The interface {} is not associated with any dpn", interfaceName); return updatedDpnId; } ProviderTypes providerType = NatEvpnUtil.getExtNwProvTypeFromRouterName(dataBroker, routerName, extNwId); if (providerType == null) { LOG.warn("getAssociatedDpnWithExternalInterface : Provider Network Type for router {} and" + " externalNetwork {} is missing.", routerName, extNwId); return updatedDpnId; } // For FLAT and VLAN provider networks, we have to ensure that dpn hosting the VM has connectivity // to External Network via provider_mappings. In case the dpn does not have the provider mappings, // traffic from the VM has to be forwarded to the NAPT Switch (which is scheduled based on the provider // mappings) and then sent out on the external Network. if (providerType == ProviderTypes.FLAT || providerType == ProviderTypes.VLAN) { String providerNet = NatUtil.getElanInstancePhysicalNetwok(extNwId.getValue(), dataBroker); boolean isDpnConnected = natSwitchCache.isSwitchConnectedToExternal(updatedDpnId, providerNet); if (!isDpnConnected) { updatedDpnId = centralizedSwitchScheduler.getCentralizedSwitch(routerName); } } return updatedDpnId; } void createNATFlowEntries(String interfaceName, final InternalToExternalPortMap mapping, final InstanceIdentifier<RouterPorts> portIid, final String routerName, @Nullable Uint64 dpnId, TypedReadWriteTransaction<Configuration> confTx) throws ExecutionException, InterruptedException { if (!validateIpMapping(mapping)) { LOG.error("createNATFlowEntries : Not a valid ip addresses in the mapping {}", mapping); return; } Uuid extNwId = getExtNetworkId(portIid, LogicalDatastoreType.CONFIGURATION); if (extNwId == null) { LOG.error("createNATFlowEntries : External network associated with interface {} could not be retrieved", interfaceName); return; } // For Overlay Networks, get the DPN on which this interface resides. // For FLAT/VLAN Networks, get the DPN with provider_mappings for external network. dpnId = getAssociatedDpnWithExternalInterface(routerName, extNwId, dpnId, interfaceName); if (dpnId == null || dpnId.equals(Uint64.ZERO)) { LOG.warn("createNATFlowEntries : No DPN for interface {}. NAT flow entries for ip mapping {} will " + "not be installed", interfaceName, mapping); return; } Uint32 routerId = NatUtil.getVpnId(dataBroker, routerName); if (routerId == NatConstants.INVALID_ID) { LOG.error("createNATFlowEntries : Could not retrieve router id for {} to create NAT Flow entries", routerName); return; } //Check if the router to vpn association is present //long associatedVpnId = NatUtil.getAssociatedVpn(dataBroker, routerName); Uuid associatedVpn = NatUtil.getVpnForRouter(dataBroker, routerName); Uint32 associatedVpnId = NatConstants.INVALID_ID; if (associatedVpn == null) { LOG.debug("createNATFlowEntries : Router {} is not assicated with any BGP VPN instance", routerName); } else { LOG.debug("createNATFlowEntries : Router {} is associated with VPN Instance with Id {}", routerName, associatedVpn); associatedVpnId = NatUtil.getVpnId(dataBroker, associatedVpn.getValue()); LOG.debug("createNATFlowEntries : vpninstance Id is {} for VPN {}", associatedVpnId, associatedVpn); //routerId = associatedVpnId; } Uuid vpnUuid = getVpnUuid(extNwId, mapping.getExternalId()); LOG.trace("createNATFlowEntries : vpnUuid {} for External Network {}", vpnUuid, extNwId); if (vpnUuid == null) { LOG.error("createNATFlowEntries : No VPN associated with Ext nw {}. Unable to create SNAT table entry " + "for fixed ip {}", extNwId, mapping.getInternalIp()); return; } VpnInstance vpnInstance = NatUtil.getVpnIdToVpnInstance(dataBroker, vpnUuid.getValue()); if (vpnInstance == null || vpnInstance.getVpnId() == null) { LOG.error("createNATFlowEntries : No VPN associated with Ext nw {}. Unable to create SNAT table entry " + "for fixed ip {}", extNwId, mapping.getInternalIp()); return; } //Install the DNAT default FIB flow L3_FIB_TABLE (21) -> PSNAT_TABLE (26) if SNAT is disabled boolean isSnatEnabled = NatUtil.isSnatEnabledForRouterId(dataBroker, routerName); if (!isSnatEnabled) { addOrDelDefaultFibRouteForDnat(dpnId, routerName, routerId, confTx, true); } //Create the DNAT and SNAT table entries Uint32 vpnId = vpnInstance.getVpnId(); String vrfId = vpnInstance.getVrfId(); createDNATTblEntry(dpnId, mapping, routerId, associatedVpnId, confTx); createSNATTblEntry(dpnId, mapping, vpnId, routerId, associatedVpnId, extNwId, confTx); floatingIPHandler.onAddFloatingIp(dpnId, routerName, routerId, extNwId, interfaceName, mapping, vrfId, confTx); } void createNATFlowEntries(Uint64 dpnId, String interfaceName, String routerName, Uuid externalNetworkId, InternalToExternalPortMap mapping, TypedReadWriteTransaction<Configuration> confTx) throws ExecutionException, InterruptedException { Uint32 routerId = NatUtil.getVpnId(dataBroker, routerName); if (routerId == NatConstants.INVALID_ID) { LOG.error("createNATFlowEntries : Could not retrieve router id for {} to create NAT Flow entries", routerName); return; } //Check if the router to vpn association is present Uint32 associatedVpnId = NatUtil.getAssociatedVpn(dataBroker, routerName); if (associatedVpnId == NatConstants.INVALID_ID) { LOG.debug("createNATFlowEntries : Router {} is not assicated with any BGP VPN instance", routerName); } else { LOG.debug("createNATFlowEntries : Router {} is associated with VPN Instance with Id {}", routerName, associatedVpnId); //routerId = associatedVpnId; } Uuid vpnUuid = getVpnUuid(externalNetworkId, mapping.getExternalId()); LOG.trace("createNATFlowEntries : vpnUuid {} for External Network {}", vpnUuid, externalNetworkId); if (vpnUuid == null) { LOG.error("createNATFlowEntries : No vpnUuid associated with Ext nw {}. Unable to create SNAT table entry" + " for fixed ip {}", externalNetworkId, mapping.getInternalIp()); return; } VpnInstance vpnInstance = NatUtil.getVpnIdToVpnInstance(dataBroker, vpnUuid.getValue()); if (vpnInstance == null || vpnInstance.getVpnId() == null) { LOG.error("createNATFlowEntries: VpnInstance associated with Ext nw {}. Unable to create SNAT table entry" + " for fixed ip {}",externalNetworkId, mapping.getInternalIp()); return; } //Install the DNAT default FIB flow L3_FIB_TABLE (21) -> PSNAT_TABLE (26) if SNAT is disabled boolean isSnatEnabled = NatUtil.isSnatEnabledForRouterId(dataBroker, routerName); if (!isSnatEnabled) { addOrDelDefaultFibRouteForDnat(dpnId, routerName, routerId, confTx, true); } //Create the DNAT and SNAT table entries Uint32 vpnId = vpnInstance.getVpnId(); String vrfId = vpnInstance.getVrfId(); createDNATTblEntry(dpnId, mapping, routerId, associatedVpnId, confTx); createSNATTblEntry(dpnId, mapping, vpnId, routerId, associatedVpnId, externalNetworkId, confTx); floatingIPHandler.onAddFloatingIp(dpnId, routerName, routerId, externalNetworkId, interfaceName, mapping, vrfId, confTx); } void createNATOnlyFlowEntries(Uint64 dpnId, String routerName, @Nullable String associatedVPN, Uuid externalNetworkId, InternalToExternalPortMap mapping) throws ExecutionException, InterruptedException { //String segmentId = associatedVPN == null ? routerName : associatedVPN; LOG.debug("createNATOnlyFlowEntries : Retrieving vpn id for VPN {} to proceed with create NAT Flows", routerName); Uint32 routerId = NatUtil.getVpnId(dataBroker, routerName); if (routerId == NatConstants.INVALID_ID) { LOG.error("createNATOnlyFlowEntries : Could not retrieve vpn id for {} to create NAT Flow entries", routerName); return; } Uint32 associatedVpnId = NatUtil.getVpnId(dataBroker, associatedVPN); LOG.debug("createNATOnlyFlowEntries : Associated VPN Id {} for router {}", associatedVpnId, routerName); Uint32 vpnId = getVpnId(externalNetworkId, mapping.getExternalId()); if (vpnId.longValue() < 0) { LOG.error("createNATOnlyFlowEntries : Unable to create SNAT table entry for fixed ip {}", mapping.getInternalIp()); return; } //Install the DNAT default FIB flow L3_FIB_TABLE (21) -> PSNAT_TABLE (26) if SNAT is disabled boolean isSnatEnabled = NatUtil.isSnatEnabledForRouterId(dataBroker, routerName); if (!isSnatEnabled) { addOrDelDefaultFibRouteForDnat(dpnId, routerName, routerId, null, true); } //Create the DNAT and SNAT table entries FlowEntity preFlowEntity = buildPreDNATFlowEntity(dpnId, mapping, routerId, associatedVpnId); mdsalManager.installFlow(preFlowEntity); FlowEntity flowEntity = buildDNATFlowEntity(dpnId, mapping, routerId, associatedVpnId); mdsalManager.installFlow(flowEntity); String externalIp = mapping.getExternalIp(); preFlowEntity = buildPreSNATFlowEntity(dpnId, mapping.getInternalIp(), externalIp, vpnId, routerId, associatedVpnId); mdsalManager.installFlow(preFlowEntity); flowEntity = buildSNATFlowEntity(dpnId, mapping, vpnId, externalNetworkId); if (flowEntity != null) { mdsalManager.installFlow(flowEntity); } } void removeNATFlowEntries(String interfaceName, final InternalToExternalPortMap mapping, InstanceIdentifier<RouterPorts> portIid, final String routerName, @Nullable Uint64 dpnId, TypedReadWriteTransaction<Configuration> removeFlowInvTx) throws ExecutionException, InterruptedException { Uuid extNwId = getExtNetworkId(portIid, LogicalDatastoreType.OPERATIONAL); if (extNwId == null) { LOG.error("removeNATFlowEntries : External network associated with interface {} could not be retrieved", interfaceName); return; } // For Overlay Networks, get the DPN on which this interface resides. // For FLAT/VLAN Networks, get the DPN with provider_mappings for external network. if (dpnId == null) { dpnId = getAssociatedDpnWithExternalInterface(routerName, extNwId, NatUtil.getDpnForInterface(interfaceManager, interfaceName), interfaceName); if (dpnId == null || dpnId.equals(Uint64.ZERO)) { LOG.warn("removeNATFlowEntries: Abort processing Floating ip configuration. No DPN for port: {}", interfaceName); return; } } Uint32 routerId = NatUtil.getVpnId(dataBroker, routerName); if (routerId == NatConstants.INVALID_ID) { LOG.error("removeNATFlowEntries : Could not retrieve router id for {} to remove NAT Flow entries", routerName); return; } String internalIp = mapping.getInternalIp(); String externalIp = mapping.getExternalIp(); //Delete the DNAT and SNAT table entries removeDNATTblEntry(dpnId, internalIp, externalIp, routerId, removeFlowInvTx); Uuid vpnUuid = getVpnUuid(extNwId, mapping.getExternalId()); if (vpnUuid == null) { LOG.error("removeNATFlowEntries : No VPN associated with Ext nw {}. Unable to remove SNAT table entry " + "for fixed ip {}", extNwId, mapping.getInternalIp()); return; } VpnInstance vpnInstance = NatUtil.getVpnIdToVpnInstance(dataBroker, vpnUuid.getValue()); if (vpnInstance == null || vpnInstance.getVpnId() == null) { LOG.error("removeNATFlowEntries: No VPN associated with Ext nw {}. Unable to create SNAT table entry " + "for fixed ip {}", extNwId, mapping.getInternalIp()); return; } Uint32 vpnId = vpnInstance.getVpnId(); String vrfId = vpnInstance.getVrfId(); removeSNATTblEntry(dpnId, internalIp, externalIp, routerId, vpnId, removeFlowInvTx); //Remove the DNAT default FIB flow L3_FIB_TABLE (21) -> PSNAT_TABLE (26) if SNAT is disabled boolean isSnatEnabled = NatUtil.isSnatEnabledForRouterId(dataBroker, routerName); if (!isSnatEnabled) { addOrDelDefaultFibRouteForDnat(dpnId, routerName, routerId, removeFlowInvTx, false); } ProviderTypes provType = NatEvpnUtil.getExtNwProvTypeFromRouterName(dataBroker, routerName, extNwId); if (provType == null) { LOG.error("removeNATFlowEntries : External Network Provider Type missing"); return; } if (provType == ProviderTypes.VXLAN) { floatingIPHandler.onRemoveFloatingIp(dpnId, routerName, routerId, extNwId, mapping, NatConstants.DEFAULT_L3VNI_VALUE, vrfId, removeFlowInvTx); removeOperationalDS(routerName, interfaceName, internalIp); return; } Uint32 label = getOperationalIpMapping(routerName, interfaceName, internalIp); if (label.longValue() < 0) { LOG.error("removeNATFlowEntries : Could not retrieve label for prefix {} in router {}", internalIp, routerId); return; } floatingIPHandler.onRemoveFloatingIp(dpnId, routerName, routerId, extNwId, mapping, label, vrfId, removeFlowInvTx); removeOperationalDS(routerName, interfaceName, internalIp); } void removeNATFlowEntries(Uint64 dpnId, String interfaceName, String vpnName, String routerName, InternalToExternalPortMap mapping, TypedReadWriteTransaction<Configuration> confTx) throws ExecutionException, InterruptedException { String internalIp = mapping.getInternalIp(); String externalIp = mapping.getExternalIp(); Uint32 routerId = NatUtil.getVpnId(dataBroker, routerName); if (routerId == NatConstants.INVALID_ID) { LOG.error("removeNATFlowEntries : Could not retrieve router id for {} to remove NAT Flow entries", routerName); return; } VpnInstance vpnInstance = NatUtil.getVpnIdToVpnInstance(dataBroker, vpnName); if (vpnInstance == null || vpnInstance.getVpnId() == null) { LOG.warn("removeNATFlowEntries: VPN Id not found for {} to remove NAT flow entries {}", vpnName, internalIp); return; } Uint32 vpnId = vpnInstance.getVpnId(); String vrfId = vpnInstance.getVrfId(); //Delete the DNAT and SNAT table entries removeDNATTblEntry(dpnId, internalIp, externalIp, routerId, confTx); removeSNATTblEntry(dpnId, internalIp, externalIp, routerId, vpnId, confTx); //Remove the DNAT default FIB flow L3_FIB_TABLE (21) -> PSNAT_TABLE (26) if SNAT is disabled boolean isSnatEnabled = NatUtil.isSnatEnabledForRouterId(dataBroker, routerName); if (!isSnatEnabled) { addOrDelDefaultFibRouteForDnat(dpnId, routerName, routerId, confTx, false); } Uuid externalNetworkId = NatUtil.getNetworkIdFromRouterName(dataBroker,routerName); ProviderTypes provType = NatEvpnUtil.getExtNwProvTypeFromRouterName(dataBroker, routerName, externalNetworkId); if (provType == null) { LOG.error("removeNATFlowEntries : External Network Provider Type Missing"); return; } if (provType == ProviderTypes.VXLAN) { floatingIPHandler.cleanupFibEntries(dpnId, vpnName, externalIp, NatConstants.DEFAULT_L3VNI_VALUE, vrfId, confTx, provType); removeOperationalDS(routerName, interfaceName, internalIp); return; } Uint32 label = getOperationalIpMapping(routerName, interfaceName, internalIp); if (label != null && label.longValue() < 0) { LOG.error("removeNATFlowEntries : Could not retrieve label for prefix {} in router {}", internalIp, routerId); return; } if (provType == ProviderTypes.VXLAN) { floatingIPHandler.cleanupFibEntries(dpnId, vpnName, externalIp, NatConstants.DEFAULT_L3VNI_VALUE, vrfId, confTx, provType); removeOperationalDS(routerName, interfaceName, internalIp); return; } floatingIPHandler.cleanupFibEntries(dpnId, vpnName, externalIp, label, vrfId, confTx, provType); removeOperationalDS(routerName, interfaceName, internalIp); } protected Uint32 getOperationalIpMapping(String routerId, String interfaceName, String internalIp) { InstanceIdentifier<InternalToExternalPortMap> intExtPortMapIdentifier = NatUtil.getIntExtPortMapIdentifier(routerId, interfaceName, internalIp); return SingleTransactionDataBroker.syncReadOptionalAndTreatReadFailedExceptionAsAbsentOptional(dataBroker, LogicalDatastoreType.OPERATIONAL, intExtPortMapIdentifier).toJavaUtil().map( InternalToExternalPortMap::getLabel).orElse(NatConstants.INVALID_ID); } static void updateOperationalDS(DataBroker dataBroker, String routerId, String interfaceName, Uint32 label, String internalIp, String externalIp) { LOG.info("updateOperationalDS : Updating operational DS for floating ip config : {} with label {}", internalIp, label); InstanceIdentifier<Ports> portsId = NatUtil.getPortsIdentifier(routerId, interfaceName); Optional<Ports> optPorts = SingleTransactionDataBroker.syncReadOptionalAndTreatReadFailedExceptionAsAbsentOptional(dataBroker, LogicalDatastoreType.OPERATIONAL, portsId); InternalToExternalPortMap intExtPortMap = new InternalToExternalPortMapBuilder().withKey(new InternalToExternalPortMapKey(internalIp)).setInternalIp(internalIp).setExternalIp(externalIp) .setLabel(label).build(); if (optPorts.isPresent()) { LOG.debug("updateOperationalDS : Ports {} entry already present. Updating intExtPortMap for internal ip {}", interfaceName, internalIp); MDSALUtil.syncWrite(dataBroker, LogicalDatastoreType.OPERATIONAL, portsId.child(InternalToExternalPortMap .class, new InternalToExternalPortMapKey(internalIp)), intExtPortMap); } else { LOG.debug("updateOperationalDS : Adding Ports entry {} along with intExtPortMap {}", interfaceName, internalIp); List<InternalToExternalPortMap> intExtPortMapList = new ArrayList<>(); intExtPortMapList.add(intExtPortMap); Ports ports = new PortsBuilder().withKey(new PortsKey(interfaceName)).setPortName(interfaceName) .setInternalToExternalPortMap(intExtPortMapList).build(); MDSALUtil.syncWrite(dataBroker, LogicalDatastoreType.OPERATIONAL, portsId, ports); } } void removeOperationalDS(String routerId, String interfaceName, String internalIp) { LOG.info("removeOperationalDS : Remove operational DS for floating ip config: {}", internalIp); InstanceIdentifier<InternalToExternalPortMap> intExtPortMapId = NatUtil.getIntExtPortMapIdentifier(routerId, interfaceName, internalIp); MDSALUtil.syncDelete(dataBroker, LogicalDatastoreType.OPERATIONAL, intExtPortMapId); } private FlowEntity buildPreDNATDeleteFlowEntity(Uint64 dpId, String externalIp, Uint32 routerId) { LOG.info("buildPreDNATDeleteFlowEntity : Bulding Delete DNAT Flow entity for ip {} ", externalIp); String flowRef = NatUtil.getFlowRef(dpId, NwConstants.PDNAT_TABLE, routerId, externalIp); FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.PDNAT_TABLE, flowRef, NatConstants.DEFAULT_DNAT_FLOW_PRIORITY, flowRef, 0, 0, NwConstants.COOKIE_DNAT_TABLE, null, null); return flowEntity; } private FlowEntity buildDNATDeleteFlowEntity(Uint64 dpId, String internalIp, Uint32 routerId) { LOG.info("buildDNATDeleteFlowEntity : Bulding Delete DNAT Flow entity for ip {} ", internalIp); String flowRef = NatUtil.getFlowRef(dpId, NwConstants.DNAT_TABLE, routerId, internalIp); FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.DNAT_TABLE, flowRef, NatConstants.DEFAULT_DNAT_FLOW_PRIORITY, flowRef, 0, 0, NwConstants.COOKIE_DNAT_TABLE, null, null); return flowEntity; } private FlowEntity buildPreSNATDeleteFlowEntity(Uint64 dpId, String internalIp, Uint32 routerId) { LOG.info("buildPreSNATDeleteFlowEntity : Building Delete PSNAT Flow entity for ip {} ", internalIp); String flowRef = NatUtil.getFlowRef(dpId, NwConstants.PSNAT_TABLE, routerId, internalIp); FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.PSNAT_TABLE, flowRef, NatConstants.DEFAULT_DNAT_FLOW_PRIORITY, flowRef, 0, 0, NwConstants.COOKIE_DNAT_TABLE, null, null); return flowEntity; } private FlowEntity buildSNATDeleteFlowEntity(Uint64 dpId, String externalIp, Uint32 routerId) { LOG.info("buildSNATDeleteFlowEntity : Building Delete SNAT Flow entity for ip {} ", externalIp); String flowRef = NatUtil.getFlowRef(dpId, NwConstants.SNAT_TABLE, routerId, externalIp); FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.SNAT_TABLE, flowRef, NatConstants.DEFAULT_DNAT_FLOW_PRIORITY, flowRef, 0, 0, NwConstants.COOKIE_DNAT_TABLE, null, null); return flowEntity; } private void addOrDelDefaultFibRouteForDnat(Uint64 dpnId, String routerName, Uint32 routerId, @Nullable TypedReadWriteTransaction<Configuration> confTx, boolean create) throws ExecutionException, InterruptedException { if (confTx == null) { ListenableFutures.addErrorLogging(txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION, newTx -> addOrDelDefaultFibRouteForDnat(dpnId, routerName, routerId, newTx, create)), LOG, "Error handling default FIB route for DNAT"); return; } //Check if the router to bgp-vpn association is present Uint32 associatedVpnId = NatConstants.INVALID_ID; Uuid associatedVpn = NatUtil.getVpnForRouter(dataBroker, routerName); if (associatedVpn != null) { associatedVpnId = NatUtil.getVpnId(dataBroker, associatedVpn.getValue()); } if (create) { if (associatedVpnId != NatConstants.INVALID_ID) { LOG.debug("addOrDelDefaultFibRouteForDnat: Install NAT default route on DPN {} for the router {} with " + "vpn-id {}", dpnId, routerName, associatedVpnId); defaultRouteProgrammer.installDefNATRouteInDPN(dpnId, associatedVpnId, routerId, confTx); } else { LOG.debug("addOrDelDefaultFibRouteForDnat: Install NAT default route on DPN {} for the router {} with " + "vpn-id {}", dpnId, routerName, routerId); defaultRouteProgrammer.installDefNATRouteInDPN(dpnId, routerId, confTx); } } else { if (associatedVpnId != NatConstants.INVALID_ID) { LOG.debug("addOrDelDefaultFibRouteForDnat: Remove NAT default route on DPN {} for the router {} " + "with vpn-id {}", dpnId, routerName, associatedVpnId); defaultRouteProgrammer.removeDefNATRouteInDPN(dpnId, associatedVpnId, routerId, confTx); } else { LOG.debug("addOrDelDefaultFibRouteForDnat: Remove NAT default route on DPN {} for the router {} " + "with vpn-id {}", dpnId, routerName, routerId); defaultRouteProgrammer.removeDefNATRouteInDPN(dpnId, routerId, confTx); } } } }
package org.skyscreamer.nevado.jms.connector.amazonaws; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.ClientConfiguration; import com.amazonaws.Protocol; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.sns.model.*; import com.amazonaws.services.sqs.model.CreateQueueRequest; import com.amazonaws.services.sqs.model.CreateQueueResult; import com.amazonaws.services.sqs.model.ListQueuesRequest; import com.amazonaws.services.sqs.model.ListQueuesResult; import org.skyscreamer.nevado.jms.connector.AbstractSQSConnector; import org.skyscreamer.nevado.jms.connector.SQSQueue; import org.skyscreamer.nevado.jms.connector.amazonaws.client.NevadoAmazonSNS; import org.skyscreamer.nevado.jms.connector.amazonaws.client.NevadoAmazonSNSAsyncClient; import org.skyscreamer.nevado.jms.connector.amazonaws.client.NevadoAmazonSNSClient; import org.skyscreamer.nevado.jms.connector.amazonaws.client.NevadoAmazonSQS; import org.skyscreamer.nevado.jms.connector.amazonaws.client.NevadoAmazonSQSAsyncClient; import org.skyscreamer.nevado.jms.connector.amazonaws.client.NevadoAmazonSQSClient; import org.skyscreamer.nevado.jms.destination.NevadoDestination; import org.skyscreamer.nevado.jms.destination.NevadoQueue; import org.skyscreamer.nevado.jms.destination.NevadoTopic; import javax.jms.JMSException; import javax.jms.JMSSecurityException; import javax.jms.ResourceAllocationException; import javax.net.ssl.SSLException; import java.net.UnknownHostException; import java.util.Collection; import java.util.HashSet; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Connector for SQS-only implementation of the Nevado JMS driver. * * @author Carter Page <carter@skyscreamer.org> */ public class AmazonAwsSQSConnector extends AbstractSQSConnector { private final NevadoAmazonSQS _amazonSQS; private final NevadoAmazonSNS _amazonSNS; public AmazonAwsSQSConnector(String awsAccessKey, String awsSecretKey, boolean isSecure, long receiveCheckIntervalMs) { this(awsAccessKey, awsSecretKey, isSecure, receiveCheckIntervalMs, false); } public AmazonAwsSQSConnector(String awsAccessKey, String awsSecretKey, boolean isSecure, long receiveCheckIntervalMs, boolean isAsync) { super(receiveCheckIntervalMs, isAsync); AWSCredentials awsCredentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey); ClientConfiguration clientConfiguration = new ClientConfiguration(); clientConfiguration.setProtocol(isSecure ? Protocol.HTTPS : Protocol.HTTP); if (isAsync) { ExecutorService executorService = Executors.newSingleThreadExecutor(); _amazonSQS = new NevadoAmazonSQSAsyncClient(awsCredentials, clientConfiguration, executorService); _amazonSNS = new NevadoAmazonSNSAsyncClient(awsCredentials, clientConfiguration, executorService); } else { _amazonSQS = new NevadoAmazonSQSClient(awsCredentials, clientConfiguration); _amazonSNS = new NevadoAmazonSNSClient(awsCredentials, clientConfiguration); } } @Override protected void sendSNSMessage(NevadoTopic topic, String serializedMessage) throws JMSException { String arn = getTopicARN(topic); try { _amazonSNS.publish(new PublishRequest(arn, serializedMessage)); } catch (AmazonClientException e) { throw handleAWSException("Unable to send message to topic: " + arn, e); } } @Override protected AmazonAwsSQSQueue getSQSQueueImpl(NevadoQueue queue) throws JMSException { try { if (queue.getQueueUrl() == null) { CreateQueueResult result = _amazonSQS.createQueue(new CreateQueueRequest(queue.getQueueName())); queue.setQueueUrl(result.getQueueUrl()); } } catch (AmazonClientException e) { throw handleAWSException("Unable to get message queue '" + queue, e); } return new AmazonAwsSQSQueue(this, queue.getQueueUrl()); } @Override public void test() throws JMSException { try { _amazonSQS.listQueues(); _amazonSNS.listTopics(); } catch (AmazonClientException e) { throw handleAWSException("Connection test failed", e); } } @Override public Collection<NevadoQueue> listQueues(String temporaryQueuePrefix) throws JMSException { Collection<NevadoQueue> queues; ListQueuesResult result; try { result = _amazonSQS.listQueues(new ListQueuesRequest().withQueueNamePrefix(temporaryQueuePrefix)); } catch (AmazonClientException e) { throw handleAWSException("Unable to list queues with prefix '" + temporaryQueuePrefix + "'", e); } queues = new HashSet<NevadoQueue>(result.getQueueUrls().size()); for(String queueUrl : result.getQueueUrls()) { queues.add(new NevadoQueue(queueUrl)); } return queues; } @Override public NevadoTopic createTopic(String topicName) throws JMSException { NevadoTopic topic = new NevadoTopic(topicName); getTopicARN(topic); return topic; } @Override public void deleteTopic(NevadoTopic topic) throws JMSException { try { _amazonSNS.deleteTopic(new DeleteTopicRequest().withTopicArn(getTopicARN(topic))); } catch (AmazonClientException e) { throw handleAWSException("Unable to delete message topic '" + topic, e); } } @Override public Collection<NevadoTopic> listTopics() throws JMSException { Collection<NevadoTopic> topics; ListTopicsResult result; try { result = _amazonSNS.listTopics(); } catch (AmazonClientException e) { throw handleAWSException("Unable to list topics", e); } topics = new HashSet<NevadoTopic>(result.getTopics().size()); for(Topic topic : result.getTopics()) { topics.add(new NevadoTopic(topic.getTopicArn())); } return topics; } @Override public String subscribe(NevadoTopic topic, NevadoQueue topicEndpoint) throws JMSException { String subscriptionArn; try { SQSQueue queue = getSQSQueue((NevadoDestination) topicEndpoint); String sqsArn = queue.getQueueARN(); String snsArn = getTopicARN(topic); queue.setPolicy(getPolicy(snsArn, sqsArn)); subscriptionArn = _amazonSNS.subscribe(new SubscribeRequest().withTopicArn(getTopicARN(topic)) .withProtocol("sqs").withEndpoint(sqsArn)).getSubscriptionArn(); } catch (AmazonClientException e) { throw handleAWSException("Unable to subscripe to topic " + topic, e); } return subscriptionArn; } @Override public void unsubscribe(NevadoTopic topic) throws JMSException { if (topic == null) { throw new NullPointerException(); } if (topic.getSubscriptionArn() == null) { throw new IllegalArgumentException("Topic doesn't have a subscription"); } try { _amazonSNS.unsubscribe(new UnsubscribeRequest().withSubscriptionArn(topic.getSubscriptionArn())); } catch (AmazonClientException e) { throw handleAWSException("Unable to subscribe topic " + topic + " with sub ARN " + topic.getSubscriptionArn(), e); } } public NevadoAmazonSQS getAmazonSQS() { return _amazonSQS; } public NevadoAmazonSNS getAmazonSNS() { return _amazonSNS; } protected String getTopicARN(NevadoTopic topic) throws JMSException { if (topic.getArn() == null) { CreateTopicResult result; try { result = _amazonSNS.createTopic(new CreateTopicRequest(topic.getTopicName())); } catch (AmazonClientException e) { throw handleAWSException("Unable to create/lookup topic: " + topic, e); } topic.setArn(result.getTopicArn()); } return topic.getArn(); } protected JMSException handleAWSException(String message, AmazonClientException e) { JMSException jmsException; String exMessage = message + ": " + e.getMessage(); _log.error(exMessage, e); if (e.getCause() != null && (UnknownHostException.class.equals(e.getCause().getClass()) || SSLException.class.equals((e.getCause().getClass())))) { jmsException = new ResourceAllocationException(exMessage); } else if (isSecurityException(e)) { jmsException = new JMSSecurityException(exMessage); } else { jmsException = new JMSException(exMessage); } return jmsException; } private boolean isSecurityException(AmazonClientException e) { if (e instanceof AmazonServiceException) { return AWS_ERROR_CODE_AUTHENTICATION.equals(((AmazonServiceException)e).getErrorCode()); } else { return false; } } }
package org.helioviewer.jhv.events.gui.info; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.util.ArrayList; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import javax.annotation.Nonnull; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.JScrollPane; import org.helioviewer.jhv.database.EventDatabase; import org.helioviewer.jhv.events.JHVEvent; import org.helioviewer.jhv.events.JHVEventCache; import org.helioviewer.jhv.events.JHVRelatedEvents; import org.helioviewer.jhv.gui.JHVFrame; import org.helioviewer.jhv.log.Log; import org.helioviewer.jhv.threads.EventQueueCallbackExecutor; import com.google.common.util.concurrent.FutureCallback; // Popup displaying informations about a HEK event. // This panel is a JDialog, so that it can be displayed on top of an GLCanvas, // which is not possible for other swing components. @SuppressWarnings("serial") public class SWEKEventInformationDialog extends JDialog implements DataCollapsiblePanelModelListener { private JPanel allTablePanel; private DataCollapsiblePanel standardParameters; private DataCollapsiblePanel allParameters; private DataCollapsiblePanel precedingEventsPanel; private DataCollapsiblePanel followingEventsPanel; private DataCollapsiblePanel otherRelatedEventsPanel; private final JHVEvent event; private final JHVRelatedEvents rEvent; private final DataCollapsiblePanelModel model; public SWEKEventInformationDialog(JHVRelatedEvents revent, JHVEvent _event) { super(JHVFrame.getFrame(), revent.getSupplier().getGroup().getName()); event = _event; rEvent = revent; model = new DataCollapsiblePanelModel(); model.addListener(this); initAllTablePanel(); initParameterCollapsiblePanels(); setCollapsiblePanels(); setLayout(new GridBagLayout()); GridBagConstraints eventDescriptionConstraint = new GridBagConstraints(); eventDescriptionConstraint.gridx = 0; eventDescriptionConstraint.gridy = 0; eventDescriptionConstraint.weightx = 1; eventDescriptionConstraint.weighty = 0; eventDescriptionConstraint.anchor = GridBagConstraints.LINE_START; eventDescriptionConstraint.fill = GridBagConstraints.BOTH; add(new EventDescriptionPanel(revent, event), eventDescriptionConstraint); GridBagConstraints allTablePanelConstraint = new GridBagConstraints(); allTablePanelConstraint.gridx = 0; allTablePanelConstraint.gridy = 1; allTablePanelConstraint.gridwidth = 1; allTablePanelConstraint.weightx = 1; allTablePanelConstraint.weighty = 1; allTablePanelConstraint.fill = GridBagConstraints.BOTH; add(allTablePanel, allTablePanelConstraint); EventQueueCallbackExecutor.pool.submit(new DatabaseCallable(event), new DatabaseCallback()); } private void initAllTablePanel() { allTablePanel = new JPanel(new GridBagLayout()); } private void initParameterCollapsiblePanels() { ParameterTablePanel standardParameterPanel = new ParameterTablePanel(event.getVisibleEventParameters()); standardParameters = new DataCollapsiblePanel("Standard Parameters", standardParameterPanel, true, model); ParameterTablePanel allEventsPanel = new ParameterTablePanel(event.getAllEventParameters()); allParameters = new DataCollapsiblePanel("All Parameters", allEventsPanel, false, model); ArrayList<JHVEvent> precedingEvents = rEvent.getPreviousEvents(event); if (!precedingEvents.isEmpty()) { precedingEventsPanel = createRelatedEventsCollapsiblePane("Preceding Events", rEvent, precedingEvents); } ArrayList<JHVEvent> nextEvents = rEvent.getNextEvents(event); if (!nextEvents.isEmpty()) { followingEventsPanel = createRelatedEventsCollapsiblePane("Following Events", rEvent, nextEvents); } } private void setCollapsiblePanels() { GridBagConstraints gc = new GridBagConstraints(); gc.gridx = 0; gc.gridy = 0; gc.fill = GridBagConstraints.BOTH; gc.weightx = 1; gc.anchor = GridBagConstraints.PAGE_START; gc.weighty = standardParameters.isExpanded() ? 1 : 0; allTablePanel.add(standardParameters, gc); gc.gridy = 1; gc.weighty = allParameters.isExpanded() ? 1 : 0; allTablePanel.add(allParameters, gc); int gridYPosition = 2; if (precedingEventsPanel != null) { gc.gridy = gridYPosition; gc.weighty = precedingEventsPanel.isExpanded() ? 1 : 0; allTablePanel.add(precedingEventsPanel, gc); gridYPosition++; } if (followingEventsPanel != null) { gc.gridy = gridYPosition; gc.weighty = followingEventsPanel.isExpanded() ? 1 : 0; allTablePanel.add(followingEventsPanel, gc); gridYPosition++; } if (otherRelatedEventsPanel != null) { gc.gridy = gridYPosition; gc.weighty = otherRelatedEventsPanel.isExpanded() ? 1 : 0; allTablePanel.add(otherRelatedEventsPanel, gc); //gridYPosition++; } } private DataCollapsiblePanel createRelatedEventsCollapsiblePane(String relation, JHVRelatedEvents rEvents, ArrayList<JHVEvent> relations) { JPanel allPrecedingEvents = new JPanel(); allPrecedingEvents.setLayout(new BoxLayout(allPrecedingEvents, BoxLayout.PAGE_AXIS)); relations.forEach(ev -> allPrecedingEvents.add(createEventPanel(rEvents, ev))); return new DataCollapsiblePanel(relation, new JScrollPane(allPrecedingEvents), false, model); } private DataCollapsiblePanel createOtherRelatedEventsCollapsiblePane(String relation, ArrayList<JHVRelatedEvents> rEvents) { JPanel allPrecedingEvents = new JPanel(); allPrecedingEvents.setLayout(new BoxLayout(allPrecedingEvents, BoxLayout.PAGE_AXIS)); for (JHVRelatedEvents rev : rEvents) { ArrayList<JHVEvent> evs = rev.getEvents(); if (!evs.isEmpty()) { allPrecedingEvents.add(createEventPanel(rev, evs.get(0))); } } return new DataCollapsiblePanel(relation, new JScrollPane(allPrecedingEvents), false, model); } private static JPanel createEventPanel(JHVRelatedEvents rEvents, JHVEvent event) { JButton detailsButton = new JButton("Details"); detailsButton.addActionListener(e -> { SWEKEventInformationDialog dialog = new SWEKEventInformationDialog(rEvents, event); dialog.pack(); dialog.setVisible(true); }); JPanel eventAndButtonPanel = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.fill = GridBagConstraints.BOTH; c.anchor = GridBagConstraints.CENTER; c.weightx = 1; c.weighty = 1; eventAndButtonPanel.add(new EventDescriptionPanel(rEvents, event), c); c.gridy = 1; c.fill = GridBagConstraints.NONE; c.weightx = 0; c.weighty = 0; c.anchor = GridBagConstraints.LINE_END; eventAndButtonPanel.add(detailsButton, c); return eventAndButtonPanel; } @Override public void repack() { allTablePanel.removeAll(); setCollapsiblePanels(); pack(); } private static class DatabaseCallable implements Callable<ArrayList<JHVEvent>> { private final JHVEvent e; DatabaseCallable(JHVEvent _e) { e = _e; } @Override public ArrayList<JHVEvent> call() { return EventDatabase.getOtherRelations(e.getUniqueID(), e.getSupplier(), false, true); } } private class DatabaseCallback implements FutureCallback<ArrayList<JHVEvent>> { @Override public void onSuccess(ArrayList<JHVEvent> result) { result.forEach(JHVEventCache::add); ArrayList<JHVRelatedEvents> rEvents = new ArrayList<>(); int id = event.getUniqueID(); for (JHVEvent jhvEvent : result) { int jid = jhvEvent.getUniqueID(); //if (jid == id) // event = jhvEvent; //else if (jid != id) rEvents.add(JHVEventCache.getRelatedEvents(jid)); } if (!rEvents.isEmpty()) otherRelatedEventsPanel = createOtherRelatedEventsCollapsiblePane("Other Related Events", rEvents); allTablePanel.removeAll(); initParameterCollapsiblePanels(); setCollapsiblePanels(); repack(); repaint(); } @Override public void onFailure(@Nonnull Throwable t) { if (t instanceof InterruptedException || t instanceof ExecutionException) return; // ignore ? Log.error("SWEKEventInformationDialog error", t); } } }
package org.geogit.osm.cli.commands; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.Charset; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; import javax.management.relation.Relation; import jline.console.ConsoleReader; import org.geogit.api.DefaultProgressListener; import org.geogit.api.FeatureBuilder; import org.geogit.api.GeoGIT; import org.geogit.api.NodeRef; import org.geogit.api.ObjectId; import org.geogit.api.ProgressListener; import org.geogit.api.Ref; import org.geogit.api.RevFeature; import org.geogit.api.RevFeatureType; import org.geogit.api.RevTree; import org.geogit.api.SymRef; import org.geogit.api.plumbing.FindTreeChild; import org.geogit.api.plumbing.RefParse; import org.geogit.api.plumbing.ResolveGeogitDir; import org.geogit.api.plumbing.ResolveTreeish; import org.geogit.api.plumbing.RevObjectParse; import org.geogit.api.porcelain.AddOp; import org.geogit.api.porcelain.CommitOp; import org.geogit.cli.AbstractCommand; import org.geogit.cli.CLICommand; import org.geogit.cli.CommandFailedException; import org.geogit.cli.GeogitCLI; import org.geogit.osm.internal.history.Change; import org.geogit.osm.internal.history.Changeset; import org.geogit.osm.internal.history.HistoryDownloader; import org.geogit.osm.internal.history.Node; import org.geogit.osm.internal.history.Primitive; import org.geogit.osm.internal.history.Way; import org.geogit.repository.Repository; import org.geogit.repository.StagingArea; import org.geogit.repository.WorkingTree; import org.geotools.data.DataUtilities; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.referencing.CRS; import org.opengis.feature.Feature; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.referencing.crs.CoordinateReferenceSystem; import com.beust.jcommander.Parameters; import com.beust.jcommander.ParametersDelegate; import com.beust.jcommander.internal.Lists; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import com.google.common.io.Files; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.Point; //import org.geogit.api.Node; @Parameters(commandNames = "import-history", commandDescription = "Import OpenStreetmap history") public class OSMHistoryImport extends AbstractCommand implements CLICommand { /** FeatureType namespace */ private static final String NAMESPACE = "www.openstreetmap.org"; /** NODE */ private static final String NODE_TYPE_NAME = "node"; /** WAY */ private static final String WAY_TYPE_NAME = "way"; private static final GeometryFactory GEOMF = new GeometryFactory(); @ParametersDelegate public HistoryImportArgs args = new HistoryImportArgs(); @Override protected void runInternal(GeogitCLI cli) throws IOException { checkParameter(args.numThreads > 0 && args.numThreads < 7, "numthreads must be between 1 and 6"); ConsoleReader console = cli.getConsole(); final String osmAPIUrl = resolveAPIURL(); final long startIndex; final long endIndex = args.endIndex; if (args.resume) { GeoGIT geogit = cli.getGeogit(); long lastChangeset = getCurrentBranchChangeset(geogit); startIndex = 1 + lastChangeset; } else { startIndex = args.startIndex; } console.println("Obtaining OSM changesets " + startIndex + " to " + args.endIndex + " from " + osmAPIUrl); final ThreadFactory threadFactory = new ThreadFactoryBuilder().setDaemon(true) .setNameFormat("osm-history-fetch-thread-%d").build(); final ExecutorService executor = Executors.newFixedThreadPool(args.numThreads, threadFactory); final File targetDir = resolveTargetDir(); console.println("Downloading to " + targetDir.getAbsolutePath()); console.println("Files will " + (args.keepFiles ? "" : " not ") + "be kept on the download directory."); console.flush(); HistoryDownloader downloader; downloader = new HistoryDownloader(osmAPIUrl, targetDir, startIndex, endIndex, executor, args.keepFiles); try { importOsmHistory(cli, console, downloader); } finally { executor.shutdownNow(); try { executor.awaitTermination(30, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new CommandFailedException(e); } } } private File resolveTargetDir() throws IOException { final File targetDir; if (args.saveFolder == null) { try { File tmp = new File(System.getProperty("java.io.tmpdir"), "changesets.osm"); tmp.mkdirs(); targetDir = tmp; } catch (Exception e) { throw Throwables.propagate(e); } } else { if (!args.saveFolder.exists() && !args.saveFolder.mkdirs()) { throw new IllegalArgumentException("Unable to create directory " + args.saveFolder.getAbsolutePath()); } targetDir = args.saveFolder; } return targetDir; } private String resolveAPIURL() { String osmAPIUrl; if (args.useTestApiEndpoint) { osmAPIUrl = HistoryImportArgs.DEVELOPMENT_API_ENDPOINT; } else if (args.apiUrl.isEmpty()) { osmAPIUrl = HistoryImportArgs.DEFAULT_API_ENDPOINT; } else { osmAPIUrl = args.apiUrl.get(0); } return osmAPIUrl; } private void importOsmHistory(GeogitCLI cli, ConsoleReader console, HistoryDownloader downloader) throws IOException { Optional<Changeset> set; while ((set = downloader.fetchNextChangeset()).isPresent()) { Changeset changeset = set.get(); String desc = "obtaining osm changeset " + changeset.getId() + "..."; console.print(desc); console.flush(); // ProgressListener listener = cli.getProgressListener(); // listener.dispose(); // listener.setCanceled(false); // listener.progress(0f); // listener.setDescription(desc); // listener.started(); Iterator<Change> changes = changeset.getChanges().get(); console.print("applying..."); console.flush(); insertAndAddChanges(cli, changes); // listener.progress(100f); // listener.complete(); commit(cli, changeset); } } /** * @param cli * @param changeset * @throws IOException */ private void commit(GeogitCLI cli, Changeset changeset) throws IOException { ConsoleReader console = cli.getConsole(); console.print("Committing changeset " + changeset.getId() + "..."); console.flush(); GeoGIT geogit = cli.getGeogit(); CommitOp command = geogit.command(CommitOp.class); command.setAllowEmpty(true); String message = ""; if (changeset.getComment().isPresent()) { message = changeset.getComment().get() + "\nchangeset " + changeset.getId(); } else { message = "changeset " + changeset.getId(); } command.setMessage(message); command.setAuthor(changeset.getUserName(), null); command.setAuthorTimestamp(changeset.getClosed()); command.setAuthorTimeZoneOffset(0);// osm timestamps are in GMT ProgressListener listener = cli.getProgressListener(); listener.setProgress(0f); listener.started(); command.setProgressListener(listener); try { command.call(); updateBranchChangeset(geogit, changeset.getId()); listener.complete(); console.println("done."); console.flush(); } catch (Exception e) { throw Throwables.propagate(e); } } /** * @param geogit * @param id * @throws IOException */ private void updateBranchChangeset(GeoGIT geogit, long id) throws IOException { final File branchTrackingChangesetFile = getBranchTrackingFile(geogit); Preconditions.checkState(branchTrackingChangesetFile.exists()); Files.write(String.valueOf(id), branchTrackingChangesetFile, Charset.forName("UTF-8")); } private long getCurrentBranchChangeset(GeoGIT geogit) throws IOException { final File branchTrackingChangesetFile = getBranchTrackingFile(geogit); Preconditions.checkState(branchTrackingChangesetFile.exists()); String line = Files.readFirstLine(branchTrackingChangesetFile, Charset.forName("UTF-8")); if (line == null) { return 0; } long changeset = Long.parseLong(line); return changeset; } private File getBranchTrackingFile(GeoGIT geogit) throws IOException { final SymRef head = getHead(geogit); final String branch = head.getTarget(); final URL geogitDirUrl = geogit.command(ResolveGeogitDir.class).call().get(); File repoDir; try { repoDir = new File(geogitDirUrl.toURI()); } catch (URISyntaxException e) { throw Throwables.propagate(e); } File branchTrackingFile = new File(new File(repoDir, "osm"), branch); Files.createParentDirs(branchTrackingFile); if (!branchTrackingFile.exists()) { Files.touch(branchTrackingFile); } return branchTrackingFile; } private SymRef getHead(GeoGIT geogit) { final Ref currentHead = geogit.command(RefParse.class).setName(Ref.HEAD).call().get(); if (!(currentHead instanceof SymRef)) { throw new CommandFailedException("Cannot run on a dettached HEAD"); } return (SymRef) currentHead; } /** * @param cli * @param changes * @throws IOException */ private void insertAndAddChanges(GeogitCLI cli, final Iterator<Change> changes) throws IOException { if (!changes.hasNext()) { return; } final GeoGIT geogit = cli.getGeogit(); final Repository repository = geogit.getRepository(); final WorkingTree workTree = repository.getWorkingTree(); Map<Long, Coordinate> thisChangePointCache = new LinkedHashMap<Long, Coordinate>() { /** serialVersionUID */ private static final long serialVersionUID = 1277795218777240552L; @Override protected boolean removeEldestEntry(Map.Entry<Long, Coordinate> eldest) { return size() == 10000; } }; int cnt = 0; Set<String> deletes = Sets.newHashSet(); Multimap<String, SimpleFeature> insertsByParent = HashMultimap.create(); while (changes.hasNext()) { Change change = changes.next(); final String featurePath = featurePath(change); if (featurePath == null) { continue;// ignores relations } cnt++; final String parentPath = NodeRef.parentPath(featurePath); if (Change.Type.delete.equals(change.getType())) { deletes.add(featurePath); } else { final Primitive primitive = change.getNode().isPresent() ? change.getNode().get() : change.getWay().get(); final Geometry geom = parseGeometry(geogit, primitive, thisChangePointCache); if (geom instanceof Point) { thisChangePointCache.put(Long.valueOf(primitive.getId()), ((Point) geom).getCoordinate()); } SimpleFeature feature = toFeature(primitive, geom); insertsByParent.put(parentPath, feature); } } for (String parentPath : insertsByParent.keySet()) { Collection<SimpleFeature> features = insertsByParent.get(parentPath); if (features.isEmpty()) { continue; } Iterator<? extends Feature> iterator = features.iterator(); ProgressListener listener = new DefaultProgressListener(); List<org.geogit.api.Node> insertedTarget = null; Integer collectionSize = Integer.valueOf(features.size()); workTree.insert(parentPath, iterator, listener, insertedTarget, collectionSize); } if (!deletes.isEmpty()) { workTree.delete(deletes.iterator()); } ConsoleReader console = cli.getConsole(); console.print("Applied " + cnt + " changes, staging..."); console.flush(); geogit.command(AddOp.class).call(); console.println("done."); console.flush(); } /** * @param primitive * @param thisChangePointCache * @return */ private Geometry parseGeometry(GeoGIT geogit, Primitive primitive, Map<Long, Coordinate> thisChangePointCache) { if (primitive instanceof Relation) { return null; } if (primitive instanceof Node) { Optional<Point> location = ((Node) primitive).getLocation(); return location.orNull(); } final Way way = (Way) primitive; final ImmutableList<Long> nodes = way.getNodes(); StagingArea index = geogit.getRepository().getIndex(); FeatureBuilder featureBuilder = new FeatureBuilder(NODE_REV_TYPE); List<Coordinate> coordinates = Lists.newArrayList(nodes.size()); FindTreeChild findTreeChild = geogit.command(FindTreeChild.class); findTreeChild.setIndex(true); ObjectId rootTreeId = geogit.command(ResolveTreeish.class).setTreeish(Ref.HEAD).call() .get(); if (!rootTreeId.isNull()) { RevTree headTree = geogit.command(RevObjectParse.class).setObjectId(rootTreeId) .call(RevTree.class).get(); findTreeChild.setParent(headTree); } for (Long nodeId : nodes) { Coordinate coord = thisChangePointCache.get(nodeId); if (coord == null) { String fid = String.valueOf(nodeId); String path = NodeRef.appendChild(NODE_TYPE_NAME, fid); Optional<org.geogit.api.Node> ref = index.findStaged(path); if (!ref.isPresent()) { Optional<NodeRef> nodeRef = findTreeChild.setChildPath(path).call(); if (nodeRef.isPresent()) { ref = Optional.of(nodeRef.get().getNode()); } else { ref = Optional.absent(); } } if (ref.isPresent()) { org.geogit.api.Node nodeRef = ref.get(); RevFeature revFeature = index.getDatabase().getFeature(nodeRef.getObjectId()); String id = NodeRef.nodeFromPath(nodeRef.getName()); Feature feature = featureBuilder.build(id, revFeature); Point p = (Point) ((SimpleFeature) feature).getAttribute("location"); if (p != null) { coord = p.getCoordinate(); thisChangePointCache.put(Long.valueOf(nodeId), coord); } } } if (coord != null) { coordinates.add(coord); } } if (coordinates.size() < 2) { return null; } return GEOMF.createLineString(coordinates.toArray(new Coordinate[coordinates.size()])); } /** * @param change * @return */ private String featurePath(Change change) { if (change.getRelation().isPresent()) { return null;// ignore relations for the time being } if (change.getNode().isPresent()) { String fid = String.valueOf(change.getNode().get().getId()); return NodeRef.appendChild(NODE_TYPE_NAME, fid); } String fid = String.valueOf(change.getWay().get().getId()); return NodeRef.appendChild(WAY_TYPE_NAME, fid); } private static SimpleFeatureType NodeType; private static SimpleFeatureType WayType; // private static SimpleFeatureType RelationType; private synchronized static SimpleFeatureType nodeType() { if (NodeType == null) { String typeSpec = "visible:Boolean,version:Integer,timestamp:java.lang.Long,tags:String,location:Point:srid=4326"; try { SimpleFeatureType type = DataUtilities.createType(NAMESPACE, NODE_TYPE_NAME, typeSpec); boolean longitudeFirst = true; CoordinateReferenceSystem forceLonLat = CRS.decode("EPSG:4326", longitudeFirst); NodeType = DataUtilities.createSubType(type, null, forceLonLat); } catch (Exception e) { throw Throwables.propagate(e); } } return NodeType; } private synchronized static SimpleFeatureType wayType() { if (WayType == null) { String typeSpec = "visible:Boolean,version:Integer,timestamp:java.lang.Long,tags:String,way:LineString:srid=4326"; try { SimpleFeatureType type = DataUtilities.createType(NAMESPACE, NODE_TYPE_NAME, typeSpec); boolean longitudeFirst = true; CoordinateReferenceSystem forceLonLat = CRS.decode("EPSG:4326", longitudeFirst); WayType = DataUtilities.createSubType(type, null, forceLonLat); } catch (Exception e) { throw Throwables.propagate(e); } } return WayType; } private static final RevFeatureType NODE_REV_TYPE = RevFeatureType.build(nodeType()); private static final RevFeatureType WAY_REV_TYPE = RevFeatureType.build(wayType()); private static SimpleFeature toFeature(Primitive feature, Geometry geom) { SimpleFeatureType ft = feature instanceof Node ? nodeType() : wayType(); SimpleFeatureBuilder builder = new SimpleFeatureBuilder(ft); builder.set("visible", Boolean.valueOf(feature.isVisible())); builder.set("version", Integer.valueOf(feature.getVersion())); builder.set("timestamp", Long.valueOf(feature.getTimestamp())); String tags = buildTagsString(feature.getTags()); builder.set("tags", tags); if (feature instanceof Node) { builder.set("location", geom); } else if (feature instanceof Way) { builder.set("way", geom); } else { throw new IllegalArgumentException(); } String fid = String.valueOf(feature.getId()); SimpleFeature simpleFeature = builder.buildFeature(fid); return simpleFeature; } /** * @param tags * @return */ @Nullable private static String buildTagsString(Map<String, String> tags) { if (tags.isEmpty()) { return null; } StringBuilder sb = new StringBuilder(); for (Iterator<Map.Entry<String, String>> it = tags.entrySet().iterator(); it.hasNext();) { Entry<String, String> e = it.next(); String key = e.getKey(); if (key == null || key.isEmpty()) { continue; } String value = e.getValue(); sb.append(key).append(':').append(value); if (it.hasNext()) { sb.append(';'); } } return sb.toString(); } }
package org.caleydo.view.tourguide.internal.stratomex; import static org.caleydo.view.tourguide.internal.TourGuideRenderStyle.STRATOMEX_SELECTED_ELEMENTS; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.caleydo.core.data.datadomain.ATableBasedDataDomain; import org.caleydo.core.data.datadomain.DataDomainOracle; import org.caleydo.core.data.datadomain.IDataDomain; import org.caleydo.core.data.perspective.table.TablePerspective; import org.caleydo.core.data.perspective.variable.Perspective; import org.caleydo.core.data.perspective.variable.PerspectiveInitializationData; import org.caleydo.core.data.selection.SelectionType; import org.caleydo.core.data.selection.SelectionTypeEvent; import org.caleydo.core.data.virtualarray.VirtualArray; import org.caleydo.core.data.virtualarray.group.Group; import org.caleydo.core.event.AEvent; import org.caleydo.core.event.EventListenerManager.ListenTo; import org.caleydo.core.event.EventPublisher; import org.caleydo.core.id.IDType; import org.caleydo.core.util.collection.Pair; import org.caleydo.core.view.ITablePerspectiveBasedView; import org.caleydo.view.stratomex.GLStratomex; import org.caleydo.view.stratomex.event.HighlightBrickEvent; import org.caleydo.view.stratomex.event.SelectElementsEvent; import org.caleydo.view.stratomex.tourguide.event.ConfirmedCancelNewColumnEvent; import org.caleydo.view.stratomex.tourguide.event.UpdatePreviewEvent; import org.caleydo.view.tourguide.api.query.EDataDomainQueryMode; import org.caleydo.view.tourguide.internal.TourGuideRenderStyle; import org.caleydo.view.tourguide.internal.model.AScoreRow; import org.caleydo.view.tourguide.internal.model.ITablePerspectiveScoreRow; import org.caleydo.view.tourguide.internal.model.MaxGroupCombiner; import org.caleydo.view.tourguide.spi.score.IScore; import com.google.common.base.Objects; import com.google.common.collect.Lists; /** * facade / adapter to {@link GLStratomex} to hide the communication details * * @author Samuel Gratzl * */ public class StratomexAdapter { private GLStratomex receiver; /** * events that has to be triggered one frame later */ private final List<AEvent> delayedEvents = new ArrayList<>(); private TablePerspective currentPreview = null; private Group currentPreviewGroup = null; private final SelectionType previewSelectionType; public StratomexAdapter() { // Create volatile selection type previewSelectionType = new SelectionType("Tour Guide preview selection type", STRATOMEX_SELECTED_ELEMENTS.getRGBA(), 1, true, 1); previewSelectionType.setManaged(false); triggerEvent(new SelectionTypeEvent(previewSelectionType)); } public void sendDelayedEvents() { for (AEvent event : delayedEvents) triggerEvent(event); delayedEvents.clear(); } public void cleanUp() { cleanupPreview(); SelectionTypeEvent selectionTypeEvent = new SelectionTypeEvent(previewSelectionType); selectionTypeEvent.setRemove(true); triggerEvent(selectionTypeEvent); } private void cleanupPreview() { if (currentPreview != null) { TablePerspective bak = currentPreview; removePreview(); clearHighlightRows(bak.getRecordPerspective().getIdType(), bak.getDataDomain()); } } @ListenTo private void on(ConfirmedCancelNewColumnEvent event) { // remove all temporary stuff if (currentPreview != null) { clearHighlightRows(currentPreview.getRecordPerspective().getIdType(), currentPreview.getDataDomain()); } this.currentPreview = null; this.currentPreviewGroup = null; } /** * binds this adapter to a concrete stratomex instance * * @param receiver * @return */ public boolean setStratomex(GLStratomex receiver) { if (this.receiver == receiver) return false; this.cleanupPreview(); this.receiver = receiver; return true; } public void attach() { // TODO Auto-generated method stub } /** * detach but not close from stratomex, by cleanup up temporary data but keeping them in min */ public void detach() { cleanupPreview(); } /** * whether stratomex currently showing the stratification * * @param stratification * @return */ public boolean contains(TablePerspective stratification) { if (!hasOne()) return false; for (TablePerspective t : receiver.getTablePerspectives()) if (t.equals(stratification)) return true; return false; } public boolean isVisible(AScoreRow row) { if (!hasOne()) return false; for (TablePerspective col : receiver.getTablePerspectives()) { if (row.is(col)) return true; } return false; } /** * central point for updating the current preview in Stratomex * * @param old * @param new_ * @param visibleColumns * the currently visible scores of the new_ element * @param mode */ public void updatePreview(AScoreRow old, AScoreRow new_, Collection<IScore> visibleColumns, EDataDomainQueryMode mode, IScore sortedBy) { if (!hasOne()) return; switch (mode) { case PATHWAYS: // FIXME break; case STRATIFICATIONS: updateTableBased((ITablePerspectiveScoreRow) old, (ITablePerspectiveScoreRow) new_, visibleColumns, sortedBy); break; case NUMERICAL: // FIXME break; } } private void updateTableBased(ITablePerspectiveScoreRow old, ITablePerspectiveScoreRow new_, Collection<IScore> visibleColumns, IScore sortedBy) { TablePerspective strat = new_ == null ? null : new_.asTablePerspective(); Group group = new_ == null ? null : MaxGroupCombiner.getMax(old, sortedBy); // handle stratification changes if (currentPreview != null && strat != null) { // update if (currentPreview.equals(strat)) { if (!Objects.equal(currentPreviewGroup, group)) { unhighlightBrick(currentPreview, currentPreviewGroup); hightlightBrick(currentPreview, group, true); currentPreviewGroup = group; } } else { // not same stratification if (contains(strat)) { // part of stratomex unhighlightBrick(currentPreview, currentPreviewGroup); hightlightBrick(strat, group, true); } else { updatePreview(strat, group); } } } else if (currentPreview != null) { // last removePreview(); } else if (strat != null) { // first updatePreview(strat, group); } // highlight connection band if (strat != null) hightlightRows(new_, visibleColumns, group); else if (old != null) { clearHighlightRows(old.getIdType(), old.getDataDomain()); } } private void updatePreview(TablePerspective strat, Group group) { this.currentPreview = strat; UpdatePreviewEvent event = new UpdatePreviewEvent(strat); event.to(receiver.getTourguide()); triggerEvent(event); if (group != null) { hightlightBrick(strat, group, false); } currentPreviewGroup = group; } private void removePreview() { this.currentPreview = null; this.currentPreviewGroup = null; } private void clearHighlightRows(IDType idType, IDataDomain dataDomain) { AEvent event = new SelectElementsEvent(Collections.<Integer> emptyList(), idType, this.previewSelectionType) .to(receiver); event.setEventSpace(dataDomain.getDataDomainID()); triggerEvent(event); } private void hightlightRows(ITablePerspectiveScoreRow new_, Collection<IScore> visibleColumns, Group new_g) { Pair<Collection<Integer>, IDType> intersection = new_.getIntersection(visibleColumns, new_g); AEvent event = new SelectElementsEvent(intersection.getFirst(), intersection.getSecond(), this.previewSelectionType).to(receiver); event.setEventSpace(new_.getDataDomain().getDataDomainID()); triggerEvent(event); } private void unhighlightBrick(TablePerspective strat, Group g) { if (g == null) return; triggerEvent(new HighlightBrickEvent(strat, g, receiver, this, null)); } private void hightlightBrick(TablePerspective strat, Group g, boolean now) { if (g == null) return; AEvent event = new HighlightBrickEvent(strat, g, receiver, this, TourGuideRenderStyle.STRATOMEX_FOUND_GROUP); if (now) triggerEvent(event); else triggerDelayedEvent(event); } /** * converts the given clinicial Variable using the underlying {@link TablePerspective} * * @param underlying * @param clinicalVariable * @return */ private static TablePerspective asPerspective(TablePerspective underlying, Integer clinicalVariable) { ATableBasedDataDomain dataDomain = DataDomainOracle.getClinicalDataDomain(); Perspective dim = null; for (String id : dataDomain.getDimensionPerspectiveIDs()) { Perspective d = dataDomain.getTable().getDimensionPerspective(id); VirtualArray va = d.getVirtualArray(); if (va.size() == 1 && va.get(0) == clinicalVariable) { dim = d; break; } } if (dim == null) { // not yet existing create a new one dim = new Perspective(dataDomain, dataDomain.getDimensionIDType()); PerspectiveInitializationData data = new PerspectiveInitializationData(); data.setData(Lists.newArrayList(clinicalVariable)); dim.init(data); dim.setLabel(dataDomain.getDimensionLabel(clinicalVariable), false); dataDomain.getTable().registerDimensionPerspective(dim); } Perspective rec = null; Perspective underlyingRP = underlying.getRecordPerspective(); for (String id : dataDomain.getRecordPerspectiveIDs()) { Perspective r = dataDomain.getTable().getRecordPerspective(id); if (r.getDataDomain().equals(underlying.getDataDomain()) && r.isLabelDefault() == underlyingRP.isLabelDefault() && r.getLabel().equals(underlyingRP.getLabel())) { rec = r; break; } } if (rec == null) { // not found create a new one rec = dataDomain.convertForeignPerspective(underlyingRP); dataDomain.getTable().registerRecordPerspective(rec); } return dataDomain.getTablePerspective(rec.getPerspectiveID(), dim.getPerspectiveID(), false); } private void triggerEvent(AEvent event) { if (event == null) return; event.setSender(this); EventPublisher.trigger(event); } private void triggerDelayedEvent(AEvent event) { if (event == null) return; delayedEvents.add(event); } /** * @return whether this adapter is bound to a real stratomex */ public boolean hasOne() { return this.receiver != null; } /** * @return checks if the given receiver is the currently bound stratomex */ public boolean is(ITablePerspectiveBasedView receiver) { return this.receiver == receiver && this.receiver != null; } /** * @return checks if the given receiver is the currently bound stratomex */ public boolean is(Integer receiverID) { return this.receiver != null && this.receiver.getID() == receiverID; } }
package org.eclipse.bpmn2.modeler.ui.wizards; import org.eclipse.bpmn2.modeler.core.utils.ModelUtil.Bpmn2DiagramType; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.Path; import org.eclipse.jface.dialogs.IDialogPage; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.TreePath; import org.eclipse.jface.viewers.TreeSelection; import org.eclipse.jface.window.Window; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.dialogs.ContainerSelectionDialog; public class BPMN2DiagramWizardPage2 extends WizardPage { private Text containerText; private Text fileText; private ISelection selection; private IResource diagramContainer; private Bpmn2DiagramType diagramType = Bpmn2DiagramType.NONE; /** * Constructor for SampleNewWizardPage. * * @param pageName */ public BPMN2DiagramWizardPage2(ISelection selection) { super("wizardPage2"); setTitle("BPMN2 Diagram File"); setDescription("Select file name."); this.selection = selection; } /** * @see IDialogPage#createControl(Composite) */ @Override public void createControl(Composite parent) { Composite container = new Composite(parent, SWT.NULL); GridLayout layout = new GridLayout(); container.setLayout(layout); layout.numColumns = 3; layout.verticalSpacing = 9; Label label = new Label(container, SWT.NULL); label.setText("&Location:"); containerText = new Text(container, SWT.BORDER | SWT.SINGLE); GridData gd = new GridData(GridData.FILL_HORIZONTAL); containerText.setLayoutData(gd); containerText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { dialogChanged(); } }); Button button = new Button(container, SWT.PUSH); button.setText("Browse..."); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleBrowse(); } }); label = new Label(container, SWT.NULL); label.setText("&File name:"); fileText = new Text(container, SWT.BORDER | SWT.SINGLE); gd = new GridData(GridData.FILL_HORIZONTAL); fileText.setLayoutData(gd); fileText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { dialogChanged(); } }); updatePageDescription(); updateFilename(); dialogChanged(); setControl(container); } /** * Tests if the current workbench selection is a suitable diagramContainer to use. */ private void updatePageDescription() { BPMN2DiagramWizardPage1 page1 = (BPMN2DiagramWizardPage1)getWizard().getPage("wizardPage1"); String descriptionType = "Unknown Diagram Type"; switch (page1.getDiagramType()) { case PROCESS: descriptionType = "Process Diagram"; break; case COLLABORATION: descriptionType = "Collaboration Diagram"; break; case CHOREOGRAPHY: descriptionType = "Choreography Diagram"; break; } setDescription("Enter a file name for the new "+descriptionType); } private void updateFilename() { BPMN2DiagramWizardPage1 page1 = (BPMN2DiagramWizardPage1)getWizard().getPage("wizardPage1"); String fileType = "unknown"; String filename = fileType+".bpmn"; switch (page1.getDiagramType()) { case PROCESS: fileType = "process"; break; case COLLABORATION: fileType = "collaboration"; break; case CHOREOGRAPHY: fileType = "choreography"; break; default: return; } IContainer container = getFileContainer(); if (container!=null) { String text = container.getFullPath().toString(); if (text!=null && !text.equals(containerText.getText())) containerText.setText(text); for (int i=1; ; ++i) { filename = fileType+"_" + i + ".bpmn"; IResource file = container.findMember(filename); if (file==null) { break; } } } String oldFileText = fileText.getText(); if (filename!=null && !filename.equals(oldFileText)) fileText.setText(filename); } private IContainer getFileContainer() { if (selection != null && selection.isEmpty() == false && selection instanceof IStructuredSelection) { IStructuredSelection ssel = (IStructuredSelection) selection; if (ssel.size() == 1) { Object obj = ssel.getFirstElement(); if (obj instanceof IAdaptable) { Object res = ((IAdaptable)obj).getAdapter(IResource.class); if (res!=null) obj = res; } if (obj instanceof Path) { obj = ResourcesPlugin.getWorkspace().getRoot().findMember((Path)obj); } if (obj instanceof IResource) { if (obj instanceof IContainer) { return (IContainer) obj; } else { return ((IResource) obj).getParent(); } } } } return null; } @Override public void setVisible(boolean visible) { if (visible) { updatePageDescription(); updateFilename(); } super.setVisible(visible); } /** * Uses the standard diagramContainer selection dialog to choose the new value for the diagramContainer field. */ private void handleBrowse() { ContainerSelectionDialog dialog = new ContainerSelectionDialog(getShell(), ResourcesPlugin.getWorkspace() .getRoot(), false, "Select Folder for the diagram"); if (dialog.open() == Window.OK) { Object[] result = dialog.getResult(); if (result.length == 1) { selection = new TreeSelection(new TreePath(result)); containerText.setText(((Path) result[0]).toString()); } } } /** * Ensures that both text fields are set. */ private void dialogChanged() { diagramContainer = ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(getContainerName())); String fileName = getFileName(); if (getContainerName().length() == 0) { updateStatus("Folder must be specified"); return; } if (diagramContainer == null || (diagramContainer.getType() & (IResource.PROJECT | IResource.FOLDER)) == 0) { updateStatus("Folder must exist"); return; } if (!diagramContainer.isAccessible()) { updateStatus("Project must be writable"); return; } if (fileName.length() == 0) { updateStatus("Name must be specified"); return; } if (fileName.replace('\\', '/').indexOf('/', 1) > 0) { updateStatus("Name must be valid"); return; } int dotLoc = fileName.lastIndexOf('.'); if (dotLoc != -1) { String ext = fileName.substring(dotLoc + 1); if (ext.equalsIgnoreCase("bpmn") == false && ext.equalsIgnoreCase("bpmn2") == false) { updateStatus("File extension must be \"bpmn\" or \"bpmn2\""); return; } } updateStatus(null); } @Override public boolean isPageComplete() { IContainer container = getFileContainer(); if (container!=null) { String filename = fileText.getText(); IResource file = container.findMember(filename); if (file==null) { setErrorMessage(null); return true; } setErrorMessage("The file "+filename+" already exists in this project"); } return false; } private void updateStatus(String message) { setErrorMessage(message); setPageComplete(message == null); } public String getContainerName() { return containerText.getText(); } public String getFileName() { return fileText.getText(); } public IResource getDiagramContainer() { return diagramContainer; } }
package ua.com.fielden.platform.web.resources.webui; import static java.lang.String.format; import java.io.ByteArrayInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.resource.Get; import com.google.common.base.Charsets; import ua.com.fielden.platform.utils.ResourceLoader; import ua.com.fielden.platform.web.app.ISourceController; import ua.com.fielden.platform.web.interfaces.IDeviceProvider; import ua.com.fielden.platform.web.resources.RestServerUtil; /** * Web server resource that searches for file resource among resource paths and returns it to client. * * @author TG Team * */ public class FileResource extends AbstractWebResource { private static final Logger LOGGER = Logger.getLogger(FileResource.class); private final List<String> resourcePaths; private final ISourceController sourceController; /** * Creates an instance of {@link FileResource} with custom resource paths. * * @param resourcePaths * @param context * @param request * @param response */ public FileResource(final ISourceController sourceController, final List<String> resourcePaths, final IDeviceProvider deviceProvider, final Context context, final Request request, final Response response) { super(context, request, response, deviceProvider); this.resourcePaths = resourcePaths; this.sourceController = sourceController; } /** * Invoked on GET request from client. */ @Get public Representation load() { final String originalPath = getReference().getRemainingPart(); final String extension = getReference().getExtensions(); final MediaType mediaType = determineMediaType(extension); final String filePath = generateFileName(resourcePaths, originalPath); if (StringUtils.isEmpty(filePath)) { LOGGER.warn(format("The requested file resource ([%s] + [%s]) wasn't found.", originalPath, extension)); return null; } else { if (MediaType.TEXT_HTML.equals(mediaType)) { final String source = sourceController.loadSourceWithFilePath(filePath, device()); if (source != null) { return RestServerUtil.encodedRepresentation(new ByteArrayInputStream(source.getBytes(Charsets.UTF_8)), mediaType); } else { return null; } } else { final InputStream stream = sourceController.loadStreamWithFilePath(filePath); if (stream != null) { final Representation encodedRepresentation = RestServerUtil.encodedRepresentation(stream, mediaType); LOGGER.debug(format("File resource [%s] generated.", originalPath)); return encodedRepresentation; } else { return null; } } } } /** * Searches for the file resource among resource paths starting from the last one path and generates full file path by concatenating resource path and relative file path. * * @param filePath * - the relative file path for which full file path must be generated. * @return */ public static String generateFileName(final List<String> resourcePaths, final String path) { // this is a preventive stuff: if the server receives additional link parameters -- JUST IGNORE THEM. Was used to run final String filePath = path.contains("?") ? path.substring(0, path.indexOf('?')) : path; for (int pathIndex = 0; pathIndex < resourcePaths.size(); pathIndex++) { final String prepender = resourcePaths.get(pathIndex); if (ResourceLoader.exist(prepender + filePath)) { return prepender + filePath; } } return null; } /** * Determines the media type of the file to return to the client. The determination process is based on file extension. * * @param extension * - the file extension that is used to determine media type. * @return */ private static MediaType determineMediaType(final String extension) { switch (extension) { case "png": return MediaType.IMAGE_PNG; case "js": case "min.js": case "json": return MediaType.TEXT_JAVASCRIPT; case "html": return MediaType.TEXT_HTML; case "css": return MediaType.TEXT_CSS; case "svg": return MediaType.IMAGE_SVG; default: return MediaType.ALL; } } }
package com.redhat.ceylon.eclipse.code.outline; import static com.redhat.ceylon.compiler.typechecker.model.Util.isAbstraction; import static com.redhat.ceylon.eclipse.code.complete.CodeCompletions.getDescriptionFor; import static com.redhat.ceylon.eclipse.code.complete.CodeCompletions.getStyledDescriptionFor; import static com.redhat.ceylon.eclipse.code.complete.CompletionUtil.overloads; import static com.redhat.ceylon.eclipse.code.editor.Navigation.gotoDeclaration; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.PACKAGE_STYLER; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.TYPE_STYLER; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.getImageForDeclaration; import static com.redhat.ceylon.eclipse.code.outline.HierarchyMode.HIERARCHY; import static com.redhat.ceylon.eclipse.code.outline.HierarchyMode.SUBTYPES; import static com.redhat.ceylon.eclipse.code.outline.HierarchyMode.SUPERTYPES; import static com.redhat.ceylon.eclipse.code.resolve.JavaHyperlinkDetector.gotoJavaNode; import static com.redhat.ceylon.eclipse.ui.CeylonPlugin.PLUGIN_ID; import static com.redhat.ceylon.eclipse.ui.CeylonResources.CEYLON_HIER; import static com.redhat.ceylon.eclipse.ui.CeylonResources.CEYLON_INHERITED; import static com.redhat.ceylon.eclipse.ui.CeylonResources.CEYLON_SUB; import static com.redhat.ceylon.eclipse.ui.CeylonResources.CEYLON_SUP; import static com.redhat.ceylon.eclipse.ui.CeylonResources.GOTO; import static com.redhat.ceylon.eclipse.ui.CeylonResources.TYPE_MODE; import static com.redhat.ceylon.eclipse.util.Nodes.findNode; import static com.redhat.ceylon.eclipse.util.Nodes.getReferencedDeclaration; import static org.eclipse.ui.PlatformUI.getWorkbench; import java.util.ArrayList; import java.util.Collection; import org.eclipse.core.resources.IProject; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.StyledCellLabelProvider; import org.eclipse.jface.viewers.StyledString; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TreeSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.ViewForm; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.ControlListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import org.eclipse.swt.widgets.Tree; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.part.ViewPart; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.DeclarationWithProximity; import com.redhat.ceylon.compiler.typechecker.model.Referenceable; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.eclipse.code.editor.CeylonEditor; import com.redhat.ceylon.eclipse.code.parse.CeylonParseController; import com.redhat.ceylon.eclipse.core.model.JavaClassFile; import com.redhat.ceylon.eclipse.ui.CeylonPlugin; public class HierarchyView extends ViewPart { private static final Image GOTO_IMAGE = CeylonPlugin.getInstance() .getImageRegistry().get(GOTO); private static final Image INHERITED_IMAGE = CeylonPlugin.getInstance() .getImageRegistry().get(CEYLON_INHERITED); private static final Image SORT_IMAGE = CeylonPlugin.getInstance() .getImageRegistry().get(TYPE_MODE); private CeylonHierarchyLabelProvider labelProvider; private CeylonHierarchyContentProvider contentProvider; private MembersLabelProvider membersLabelProvider; private MembersContentProvider membersContentProvider; private TreeViewer treeViewer; private TableViewer tableViewer; private ModeAction hierarchyAction = new ModeAction("Hierarchy", "Switch to hierarchy mode", CEYLON_HIER, HIERARCHY); private ModeAction supertypesAction = new ModeAction("Supertypes", "Switch to supertypes mode", CEYLON_SUP, SUPERTYPES); private ModeAction subtypesAction = new ModeAction("Subtypes", "Switch to subtypes mode", CEYLON_SUB, SUBTYPES); private IProject project; private CLabel title; private boolean showInherited; private ViewForm viewForm; void toggle() { showInherited=!showInherited; } private final class MemberSorter extends ViewerSorter { private boolean sortByType; @Override public int compare(Viewer viewer, Object x, Object y) { if (sortByType) { int result = super.compare(viewer, ((Declaration) x).getContainer(), ((Declaration) y).getContainer()); if (result!=0) return result; } return super.compare(viewer, x, y); } public void toggle() { sortByType = !sortByType; } } private final class MembersContentProvider implements IStructuredContentProvider { @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {} @Override public void dispose() {} @Override public Object[] getElements(Object inputElement) { if (inputElement instanceof TypeDeclaration) { TypeDeclaration declaration = (TypeDeclaration) inputElement; ArrayList<Declaration> list = new ArrayList<Declaration>(); if (showInherited) { Collection<DeclarationWithProximity> children = declaration.getMatchingMemberDeclarations(declaration, "", 0) .values(); for (DeclarationWithProximity dwp: children) { for (Declaration dec: overloads(dwp.getDeclaration())) { list.add(dec); } } } else { for (Declaration d: declaration.getMembers()) { if (!isAbstraction(d)) { list.add(d); } } } return list.toArray(); } else { return new Object[0]; } } } class MembersLabelProvider extends StyledCellLabelProvider implements DelegatingStyledCellLabelProvider.IStyledLabelProvider, ILabelProvider { @Override public void addListener(ILabelProviderListener listener) {} @Override public void dispose() {} @Override public boolean isLabelProperty(Object element, String property) { return false; } @Override public void removeListener(ILabelProviderListener listener) {} @Override public Image getImage(Object element) { return getImageForDeclaration((Declaration) element); } @Override public String getText(Object element) { Declaration dec = (Declaration) element; String desc = getDescriptionFor(dec); Scope container = dec.getContainer(); if (showInherited && container instanceof Declaration) { desc += " - " + ((Declaration) container).getName(); } return desc; } @Override public StyledString getStyledText(Object element) { Declaration dec = (Declaration) element; StyledString desc = getStyledDescriptionFor((Declaration) element); Scope container = dec.getContainer(); if (showInherited && container instanceof Declaration) { desc.append(" - ", PACKAGE_STYLER) .append(((Declaration) container).getName(), TYPE_STYLER); } return desc; } @Override public void update(ViewerCell cell) { Object element = cell.getElement(); if (element!=null) { StyledString styledText = getStyledText(element); cell.setText(styledText.toString()); cell.setStyleRanges(styledText.getStyleRanges()); cell.setImage(getImage(element)); super.update(cell); } } } private void gotoCeylonOrJavaDeclaration(Declaration dec) { if (dec.getUnit() instanceof JavaClassFile) { //TODO: is this right?! gotoJavaNode(dec); } else { gotoDeclaration(dec, project); } } @Override public void createPartControl(Composite parent) { setContentDescription(""); final SashForm sash = new SashForm(parent, SWT.HORIZONTAL | SWT.SMOOTH); sash.addControlListener(new ControlListener() { boolean reentrant; @Override public void controlResized(ControlEvent e) { if (reentrant) return; reentrant = true; try { Rectangle bounds = sash.getBounds(); IActionBars actionBars = getViewSite() .getActionBars(); IToolBarManager toolBarManager = actionBars.getToolBarManager(); if (bounds.height>bounds.width) { if (sash.getOrientation()!=SWT.VERTICAL) { sash.setOrientation(SWT.VERTICAL); createMainToolBar(toolBarManager); toolBarManager.update(false); viewForm.setTopLeft(null); } } else { if (sash.getOrientation()!=SWT.HORIZONTAL) { sash.setOrientation(SWT.HORIZONTAL); toolBarManager.removeAll(); toolBarManager.update(false); ToolBarManager tbm = new ToolBarManager(SWT.NONE); createMainToolBar(tbm); tbm.createControl(viewForm); viewForm.setTopLeft(tbm.getControl()); } } actionBars.updateActionBars(); } finally { reentrant = false; } } @Override public void controlMoved(ControlEvent e) {} }); createTreeMenu(createTree(sash)); createTableMenu(createTable(sash)); } private Tree createTree(SashForm sash) { viewForm = new ViewForm(sash, SWT.FLAT); final Tree tree = new Tree(viewForm, SWT.SINGLE); GridData gd = new GridData(GridData.FILL_BOTH); gd.heightHint = tree.getItemHeight() * 12; tree.setLayoutData(gd); viewForm.setContent(tree); treeViewer = new TreeViewer(tree); contentProvider = new CeylonHierarchyContentProvider(getSite()); labelProvider = new CeylonHierarchyLabelProvider() { @Override IProject getProject() { return project; } @Override boolean isShowingRefinements() { return contentProvider.isShowingRefinements(); } }; treeViewer.setContentProvider(contentProvider); treeViewer.setLabelProvider(labelProvider); treeViewer.setAutoExpandLevel(getDefaultLevel()); treeViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { TreeSelection selection = (TreeSelection) event.getSelection(); CeylonHierarchyNode firstElement = (CeylonHierarchyNode) selection.getFirstElement(); if (firstElement!=null) { Declaration dec = firstElement.getDeclaration(project); if (dec!=null) { title.setImage(getImageForDeclaration(dec)); title.setText(dec.getName()); tableViewer.setInput(dec); } } } }); treeViewer.addDoubleClickListener(new IDoubleClickListener() { @Override public void doubleClick(DoubleClickEvent event) { TreeSelection selection = (TreeSelection) event.getSelection(); CeylonHierarchyNode firstElement = (CeylonHierarchyNode) selection.getFirstElement(); firstElement.gotoHierarchyDeclaration(project, null); } }); return tree; } private Table createTable(SashForm sash) { ViewForm viewForm = new ViewForm(sash, SWT.FLAT); tableViewer = new TableViewer(viewForm, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL); GridData gd = new GridData(GridData.FILL_BOTH); // gd.heightHint = tableViewer.getTable().getItemHeight() * 12; tableViewer.getTable().setLayoutData(gd); viewForm.setContent(tableViewer.getTable()); title = new CLabel(viewForm, SWT.NONE); ToolBar toolBar = new ToolBar(viewForm, SWT.NONE); ToolItem toolItem = new ToolItem(toolBar, SWT.CHECK); toolItem.setImage(INHERITED_IMAGE); toolItem.setToolTipText("Show Inherited Members"); toolItem.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { toggle(); tableViewer.refresh(); } @Override public void widgetDefaultSelected(SelectionEvent e) {} }); toolItem = new ToolItem(toolBar, SWT.CHECK); toolItem.setImage(SORT_IMAGE); toolItem.setToolTipText("Sort Members by Declaring Type"); final MemberSorter sorter = new MemberSorter(); tableViewer.setSorter(sorter); toolItem.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { sorter.toggle(); tableViewer.refresh(); } @Override public void widgetDefaultSelected(SelectionEvent e) {} }); viewForm.setTopRight(toolBar); viewForm.setTopLeft(title); viewForm.setTopCenter(title); membersLabelProvider=new MembersLabelProvider(); membersContentProvider=new MembersContentProvider(); tableViewer.setLabelProvider(membersLabelProvider); tableViewer.setContentProvider(membersContentProvider); tableViewer.addDoubleClickListener(new IDoubleClickListener() { @Override public void doubleClick(DoubleClickEvent event) { StructuredSelection selection = (StructuredSelection) event.getSelection(); Declaration firstElement = (Declaration) selection.getFirstElement(); gotoCeylonOrJavaDeclaration(firstElement); } }); return tableViewer.getTable(); } private void createMainToolBar(IToolBarManager tbm) { tbm.add(hierarchyAction); tbm.add(supertypesAction); tbm.add(subtypesAction); updateActions(contentProvider.getMode()); } private void createTreeMenu(final Tree tree) { Menu menu = new Menu(tree); MenuItem item = new MenuItem(menu, SWT.PUSH); item.setText("Focus on Selection"); item.setImage(getTitleImage()); tree.setMenu(menu); item.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { TreeSelection selection = (TreeSelection) treeViewer.getSelection(); Object firstElement = selection.getFirstElement(); if (firstElement instanceof CeylonHierarchyNode) { CeylonHierarchyNode node = (CeylonHierarchyNode) firstElement; Declaration declaration = node.getDeclaration(project); treeViewer.setInput(new HierarchyInput(declaration, project)); setDescription(declaration); } } @Override public void widgetDefaultSelected(SelectionEvent e) {} }); item = new MenuItem(menu, SWT.PUSH); item.setText("Go to Selection"); item.setImage(GOTO_IMAGE); tree.setMenu(menu); item.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { TreeSelection selection = (TreeSelection) treeViewer.getSelection(); Object firstElement = selection.getFirstElement(); if (firstElement instanceof CeylonHierarchyNode) { CeylonHierarchyNode node = (CeylonHierarchyNode) firstElement; Declaration declaration = node.getDeclaration(project); gotoCeylonOrJavaDeclaration(declaration); } } @Override public void widgetDefaultSelected(SelectionEvent e) {} }); } private void createTableMenu(final Table table) { Menu menu = new Menu(table); MenuItem item = new MenuItem(menu, SWT.PUSH); item.setText("Focus on Selection"); item.setImage(getTitleImage()); table.setMenu(menu); item.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { StructuredSelection selection = (StructuredSelection) tableViewer.getSelection(); Object firstElement = selection.getFirstElement(); if (firstElement instanceof Declaration) { Declaration declaration = (Declaration) firstElement; treeViewer.setInput(new HierarchyInput(declaration, project)); setDescription(declaration); } } @Override public void widgetDefaultSelected(SelectionEvent e) {} }); item = new MenuItem(menu, SWT.PUSH); item.setText("Go to Selection"); item.setImage(GOTO_IMAGE); table.setMenu(menu); item.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { StructuredSelection selection = (StructuredSelection) tableViewer.getSelection(); Object firstElement = selection.getFirstElement(); if (firstElement instanceof Declaration) { gotoCeylonOrJavaDeclaration((Declaration) firstElement); } } @Override public void widgetDefaultSelected(SelectionEvent e) {} }); } private int getDefaultLevel() { return 4; } private void updateActions(HierarchyMode mode) { hierarchyAction.setChecked(mode==HIERARCHY); supertypesAction.setChecked(mode==SUPERTYPES); subtypesAction.setChecked(mode==SUBTYPES); } private void update() { setDescription((Declaration) tableViewer.getInput()); treeViewer.getControl().setRedraw(false); // refresh viewer to re-filter treeViewer.refresh(); reveal(); //fTreeViewer.expandAll(); // selectFirstMatch(); //TODO select the main declaration instead! treeViewer.getControl().setRedraw(true); } private void reveal() { treeViewer.expandToLevel(getDefaultLevel()); } @Override public void setFocus() {} public void focusOnSelection(CeylonEditor editor) { CeylonParseController cpc = editor.getParseController(); Node node = findNode(cpc.getRootNode(), editor.getSelection().getOffset()); Referenceable dec = getReferencedDeclaration(node); if (dec instanceof Declaration) { focusOn(cpc.getProject(), (Declaration) dec); } } public void focusOn(IProject project, Declaration dec) { this.project = project; if (dec!=null) { title.setImage(getImageForDeclaration(dec)); title.setText(dec.getName()); tableViewer.setInput(dec); treeViewer.setInput(new HierarchyInput(dec, project)); setDescription(dec); } } private void setDescription(Declaration dec) { // setContentDescription("Displaying " + // contentProvider.getMode().name().toLowerCase() + // " of '" + dec.getName() + "'"); setContentDescription(contentProvider.getDescription()); } public static HierarchyView showHierarchyView() throws PartInitException { IWorkbenchPage page = getWorkbench() .getActiveWorkbenchWindow() .getActivePage(); return (HierarchyView) page.showView(PLUGIN_ID + ".view.HierarchyView"); } /*private class MembersAction extends Action { MembersAction() { super("Show Inherited Members"); setToolTipText("Show inherited members"); setImageDescriptor(CeylonPlugin.getInstance() .getImageRegistry() .getDescriptor(CEYLON_INHERITED)); } @Override public void run() { membersContentProvider.toggle(); update(); setChecked(!isChecked()); } }*/ private class ModeAction extends Action { HierarchyMode mode; ModeAction(String label, String tooltip, String imageKey, HierarchyMode mode) { super(label); setToolTipText(tooltip); setImageDescriptor(CeylonPlugin.getInstance() .getImageRegistry() .getDescriptor(imageKey)); this.mode = mode; } @Override public void run() { contentProvider.setMode(mode); update(); updateActions(mode); } } }
package com.redhat.ceylon.eclipse.core.builder; import static com.redhat.ceylon.cmr.ceylon.CeylonUtils.repoManager; import static com.redhat.ceylon.compiler.java.util.Util.getModuleArchiveName; import static com.redhat.ceylon.compiler.java.util.Util.getModulePath; import static com.redhat.ceylon.compiler.java.util.Util.getSourceArchiveName; import static com.redhat.ceylon.compiler.typechecker.model.Module.LANGUAGE_MODULE_NAME; import static com.redhat.ceylon.eclipse.core.builder.CeylonNature.NATURE_ID; import static com.redhat.ceylon.eclipse.core.classpath.CeylonClasspathUtil.getCeylonClasspathContainers; import static com.redhat.ceylon.eclipse.core.vfs.ResourceVirtualFile.createResourceVirtualFile; import static com.redhat.ceylon.eclipse.ui.CeylonPlugin.PLUGIN_ID; import static org.eclipse.core.resources.IResource.DEPTH_INFINITE; import static org.eclipse.core.resources.IResource.DEPTH_ZERO; import static org.eclipse.core.runtime.SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.lang.ref.WeakReference; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.Callable; import javax.tools.DiagnosticListener; import javax.tools.FileObject; import javax.tools.JavaFileObject; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.exception.ZipException; import org.antlr.runtime.CommonToken; import org.antlr.runtime.CommonTokenStream; import org.eclipse.core.internal.events.NotificationManager; import org.eclipse.core.resources.IBuildConfiguration; import org.eclipse.core.resources.IBuildContext; import org.eclipse.core.resources.ICommand; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IResourceDeltaVisitor; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jdt.core.IClasspathContainer; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaModelMarker; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import com.redhat.ceylon.cmr.api.ArtifactContext; import com.redhat.ceylon.cmr.api.Logger; import com.redhat.ceylon.cmr.api.RepositoryManager; import com.redhat.ceylon.cmr.impl.ShaSigner; import com.redhat.ceylon.common.Constants; import com.redhat.ceylon.compiler.Options; import com.redhat.ceylon.compiler.java.codegen.CeylonFileObject; import com.redhat.ceylon.compiler.java.loader.TypeFactory; import com.redhat.ceylon.compiler.java.loader.UnknownTypeCollector; import com.redhat.ceylon.compiler.java.loader.mirror.JavacClass; import com.redhat.ceylon.compiler.java.tools.CeylonLog; import com.redhat.ceylon.compiler.java.tools.CeyloncFileManager; import com.redhat.ceylon.compiler.java.tools.CeyloncTaskImpl; import com.redhat.ceylon.compiler.java.tools.JarEntryFileObject; import com.redhat.ceylon.compiler.java.tools.LanguageCompiler; import com.redhat.ceylon.compiler.java.util.RepositoryLister; import com.redhat.ceylon.compiler.js.JsCompiler; import com.redhat.ceylon.compiler.loader.AbstractModelLoader; import com.redhat.ceylon.compiler.loader.ModelLoaderFactory; import com.redhat.ceylon.compiler.loader.mirror.ClassMirror; import com.redhat.ceylon.compiler.loader.model.LazyPackage; import com.redhat.ceylon.compiler.typechecker.TypeChecker; import com.redhat.ceylon.compiler.typechecker.TypeCheckerBuilder; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleManager; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleValidator; import com.redhat.ceylon.compiler.typechecker.context.Context; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnits; import com.redhat.ceylon.compiler.typechecker.context.ProducedTypeCache; import com.redhat.ceylon.compiler.typechecker.io.VirtualFile; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.Modules; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.Unit; import com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer; import com.redhat.ceylon.compiler.typechecker.tree.Message; import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompilationUnit; import com.redhat.ceylon.compiler.typechecker.tree.UnexpectedError; import com.redhat.ceylon.compiler.typechecker.util.ModuleManagerFactory; import com.redhat.ceylon.eclipse.code.editor.CeylonTaskUtil; import com.redhat.ceylon.eclipse.core.classpath.CeylonLanguageModuleContainer; import com.redhat.ceylon.eclipse.core.classpath.CeylonProjectModulesContainer; import com.redhat.ceylon.eclipse.core.model.CeylonBinaryUnit; import com.redhat.ceylon.eclipse.core.model.IResourceAware; import com.redhat.ceylon.eclipse.core.model.JDTModelLoader; import com.redhat.ceylon.eclipse.core.model.JDTModule; import com.redhat.ceylon.eclipse.core.model.JDTModuleManager; import com.redhat.ceylon.eclipse.core.model.JavaCompilationUnit; import com.redhat.ceylon.eclipse.core.model.ModuleDependencies; import com.redhat.ceylon.eclipse.core.model.SourceFile; import com.redhat.ceylon.eclipse.core.model.mirror.JDTClass; import com.redhat.ceylon.eclipse.core.model.mirror.SourceClass; import com.redhat.ceylon.eclipse.core.typechecker.CrossProjectPhasedUnit; import com.redhat.ceylon.eclipse.core.typechecker.ProjectPhasedUnit; import com.redhat.ceylon.eclipse.core.vfs.IFileVirtualFile; import com.redhat.ceylon.eclipse.core.vfs.IFolderVirtualFile; import com.redhat.ceylon.eclipse.core.vfs.ResourceVirtualFile; import com.redhat.ceylon.eclipse.ui.CeylonPlugin; import com.redhat.ceylon.eclipse.util.CarUtils; import com.redhat.ceylon.eclipse.util.CeylonSourceParser; import com.redhat.ceylon.eclipse.util.EclipseLogger; import com.sun.source.util.TaskEvent; import com.sun.source.util.TaskListener; import com.sun.tools.javac.file.RelativePath.RelativeFile; import com.sun.tools.javac.file.ZipFileIndexCache; /** * A builder may be activated on a file containing ceylon code every time it has * changed (when "Build automatically" is on), or when the programmer chooses to * "Build" a project. * * TODO This default implementation was generated from a template, it needs to * be completed manually. */ public class CeylonBuilder extends IncrementalProjectBuilder { public static final String CEYLON_CLASSES_FOLDER_NAME = ".exploded"; /** * Extension ID of the Ceylon builder, which matches the ID in the * corresponding extension definition in plugin.xml. */ public static final String BUILDER_ID = PLUGIN_ID + ".ceylonBuilder"; /** * A marker ID that identifies problems */ public static final String PROBLEM_MARKER_ID = PLUGIN_ID + ".ceylonProblem"; /** * A marker ID that identifies tasks */ public static final String TASK_MARKER_ID = PLUGIN_ID + ".ceylonTask"; public static final String SOURCE = "Ceylon"; private static final class CeylonModelCacheEnabler implements ProducedTypeCache.CacheEnabler { // Caches are disabled by default. And only enabled during build and warmup jobs private final ThreadLocal<Object> cachingIsEnabled = new ThreadLocal<>(); public CeylonModelCacheEnabler() { ProducedTypeCache.setCacheEnabler(this); } public void enableCaching() { cachingIsEnabled.set(new Object()); } public void disableCaching() { cachingIsEnabled.set(null); } public boolean isCacheEnabled() { return cachingIsEnabled.get() != null; } } private static CeylonModelCacheEnabler modelCacheEnabler = new CeylonModelCacheEnabler(); public static void doWithCeylonModelCaching(final Runnable action) { modelCacheEnabler.enableCaching(); try { action.run(); } finally { modelCacheEnabler.disableCaching(); } } public static <T> T doWithCeylonModelCaching(final Callable<T> action) throws CoreException { modelCacheEnabler.enableCaching(); try { return action.call(); } catch(CoreException ce) { throw ce; } catch(Exception e) { throw new RuntimeException(e); } finally { modelCacheEnabler.disableCaching(); } } private final class BuildFileManager extends CeyloncFileManager { private final IProject project; final boolean explodeModules; private BuildFileManager(com.sun.tools.javac.util.Context context, boolean register, Charset charset, IProject project) { super(context, register, charset); this.project = project; explodeModules = isExplodeModulesEnabled(project); } @Override protected JavaFileObject getFileForOutput(Location location, final RelativeFile fileName, FileObject sibling) throws IOException { JavaFileObject javaFileObject = super.getFileForOutput(location, fileName, sibling); if (explodeModules && javaFileObject instanceof JarEntryFileObject && sibling instanceof CeylonFileObject) { final File ceylonOutputDirectory = getCeylonClassesOutputDirectory(project); final File classFile = fileName.getFile(ceylonOutputDirectory); classFile.getParentFile().mkdirs(); return new ExplodingJavaFileObject(classFile, fileName, javaFileObject); } return javaFileObject; } @Override protected String getCurrentWorkingDir() { return project.getLocation().toFile().getAbsolutePath(); } } public static enum ModelState { Missing, Parsing, Parsed, TypeChecking, TypeChecked, Compiled }; final static Map<IProject, ModelState> modelStates = new HashMap<IProject, ModelState>(); private final static Map<IProject, TypeChecker> typeCheckers = new HashMap<IProject, TypeChecker>(); private final static Map<IProject, List<IFile>> projectSources = new HashMap<IProject, List<IFile>>(); private static Set<IProject> containersInitialized = new HashSet<IProject>(); private final static Map<IProject, RepositoryManager> projectRepositoryManagers = new HashMap<IProject, RepositoryManager>(); private final static Map<IProject, ModuleDependencies> projectModuleDependencies = new HashMap<IProject, ModuleDependencies>(); public static final String CEYLON_CONSOLE= "Ceylon Build"; //private long startTime; public static ModelState getModelState(IProject project) { ModelState modelState = modelStates.get(project); if (modelState == null) { return ModelState.Missing; } return modelState; } public static boolean isModelTypeChecked(IProject project) { ModelState modelState = getModelState(project); return modelState.ordinal() >= ModelState.TypeChecked.ordinal(); } public static boolean isModelParsed(IProject project) { ModelState modelState = getModelState(project); return modelState.ordinal() >= ModelState.Parsed.ordinal(); } public static List<PhasedUnit> getUnits(IProject project) { if (! isModelParsed(project)) { return Collections.emptyList(); } List<PhasedUnit> result = new ArrayList<PhasedUnit>(); TypeChecker tc = typeCheckers.get(project); if (tc!=null) { for (PhasedUnit pu: tc.getPhasedUnits().getPhasedUnits()) { result.add(pu); } } return result; } public static List<PhasedUnit> getUnits() { List<PhasedUnit> result = new ArrayList<PhasedUnit>(); for (IProject project : typeCheckers.keySet()) { if (isModelParsed(project)) { TypeChecker tc = typeCheckers.get(project); for (PhasedUnit pu: tc.getPhasedUnits().getPhasedUnits()) { result.add(pu); } } } return result; } public static List<PhasedUnit> getUnits(String[] projects) { List<PhasedUnit> result = new ArrayList<PhasedUnit>(); if (projects!=null) { for (Map.Entry<IProject, TypeChecker> me: typeCheckers.entrySet()) { for (String pname: projects) { if (me.getKey().getName().equals(pname)) { IProject project = me.getKey(); if (isModelParsed(project)) { result.addAll(me.getValue().getPhasedUnits().getPhasedUnits()); } } } } } return result; } public String getBuilderID() { return BUILDER_ID; } public static boolean isCeylon(IFile file) { String ext = file.getFileExtension(); return ext!=null && ext.equals("ceylon"); } public static boolean isJava(IFile file) { return JavaCore.isJavaLikeFileName(file.getName()); } public static boolean isCeylonOrJava(IFile file) { return isCeylon(file) || isJava(file); } /** * Decide whether a file needs to be build using this builder. Note that * <code>isNonRootSourceFile()</code> and <code>isSourceFile()</code> should * never return true for the same file. * * @return true iff an arbitrary file is a ceylon source file. */ protected boolean isSourceFile(IFile file) { IPath path = file.getFullPath(); //getProjectRelativePath(); if (path == null) return false; if (!isCeylonOrJava(file)) { return false; } IProject project = file.getProject(); if (project != null) { for (IPath sourceFolder: getSourceFolders(project)) { if (sourceFolder.isPrefixOf(path)) { return true; } } } return false; } public static JDTModelLoader getModelLoader(TypeChecker tc) { return (JDTModelLoader) ((JDTModuleManager) tc.getPhasedUnits() .getModuleManager()).getModelLoader(); } public static JDTModelLoader getProjectModelLoader(IProject project) { TypeChecker typeChecker = getProjectTypeChecker(project); if (typeChecker == null) { return null; } return getModelLoader(typeChecker); } public final static class BooleanHolder { public boolean value; } public static class CeylonBuildHook { protected void startBuild(int kind, @SuppressWarnings("rawtypes") Map args, IProject javaProject, IBuildConfiguration config, IBuildContext context, IProgressMonitor monitor) throws CoreException {} protected void deltasAnalyzed(List<IResourceDelta> currentDeltas, BooleanHolder sourceModified, BooleanHolder mustDoFullBuild, BooleanHolder mustResolveClasspathContainer, boolean mustContinueBuild) {} protected void resolvingClasspathContainer( List<IClasspathContainer> cpContainers) {} protected void setAndRefreshClasspathContainer() {} protected void doFullBuild() {} protected void parseCeylonModel() {} protected void doIncrementalBuild() {} protected void fullTypeCheckDuringIncrementalBuild() {} protected void incrementalBuildChangedSources(Set<IFile> changedSources) {} protected void incrementalBuildSources(Set<IFile> changedSources, List<IFile> filesToRemove, Collection<IFile> sourcesToCompile) {} protected void incrementalBuildResult(List<PhasedUnit> builtPhasedUnits) {} protected void beforeGeneratingBinaries() {} protected void afterGeneratingBinaries() {} protected void scheduleReentrantBuild() {} protected void endBuild() {} }; public static final CeylonBuildHook noOpHook = new CeylonBuildHook(); private static CeylonBuildHook buildHook = new CeylonBuildHook() { List<CeylonBuildHook> contributedHooks = new LinkedList<>(); private synchronized void resetContributedHooks() { contributedHooks.clear(); for (IConfigurationElement confElement : Platform.getExtensionRegistry().getConfigurationElementsFor(CeylonPlugin.PLUGIN_ID + ".ceylonBuildHook")) { try { Object extension = confElement.createExecutableExtension("class"); if (extension instanceof ICeylonBuildHookProvider) { CeylonBuildHook hook = ((ICeylonBuildHookProvider) extension).getHook(); if (hook != null) { contributedHooks.add(hook); } } } catch (CoreException e) { e.printStackTrace(); } } } protected void startBuild(int kind, @SuppressWarnings("rawtypes") Map args, IProject javaProject, IBuildConfiguration config, IBuildContext context, IProgressMonitor monitor) throws CoreException { resetContributedHooks(); for (CeylonBuildHook hook : contributedHooks) { hook.startBuild(kind, args, javaProject, config, context, monitor); } } protected void deltasAnalyzed(List<IResourceDelta> currentDeltas, BooleanHolder sourceModified, BooleanHolder mustDoFullBuild, BooleanHolder mustResolveClasspathContainer, boolean mustContinueBuild) { for (CeylonBuildHook hook : contributedHooks) { hook.deltasAnalyzed(currentDeltas, sourceModified, mustDoFullBuild, mustResolveClasspathContainer, mustContinueBuild); } } protected void resolvingClasspathContainer( List<IClasspathContainer> cpContainers) { for (CeylonBuildHook hook : contributedHooks) { hook.resolvingClasspathContainer(cpContainers); } } protected void setAndRefreshClasspathContainer() { for (CeylonBuildHook hook : contributedHooks) { hook.setAndRefreshClasspathContainer(); } } protected void doFullBuild() { for (CeylonBuildHook hook : contributedHooks) { hook.doFullBuild(); } } protected void parseCeylonModel() { for (CeylonBuildHook hook : contributedHooks) { hook.parseCeylonModel(); } } protected void doIncrementalBuild() { for (CeylonBuildHook hook : contributedHooks) { hook.doIncrementalBuild(); } } protected void fullTypeCheckDuringIncrementalBuild() { for (CeylonBuildHook hook : contributedHooks) { hook.fullTypeCheckDuringIncrementalBuild(); } } protected void incrementalBuildChangedSources(Set<IFile> changedSources) { for (CeylonBuildHook hook : contributedHooks) { hook.incrementalBuildChangedSources(changedSources); } } protected void incrementalBuildSources(Set<IFile> changedSources, List<IFile> filesToRemove, Collection<IFile> sourcesToCompile) { for (CeylonBuildHook hook : contributedHooks) { hook.incrementalBuildSources(changedSources, filesToRemove, sourcesToCompile); } } protected void incrementalBuildResult(List<PhasedUnit> builtPhasedUnits) { for (CeylonBuildHook hook : contributedHooks) { hook.incrementalBuildResult(builtPhasedUnits); } } protected void beforeGeneratingBinaries() { for (CeylonBuildHook hook : contributedHooks) { hook.beforeGeneratingBinaries(); } } protected void afterGeneratingBinaries() { for (CeylonBuildHook hook : contributedHooks) { hook.afterGeneratingBinaries(); } } protected void scheduleReentrantBuild() { for (CeylonBuildHook hook : contributedHooks) { hook.beforeGeneratingBinaries(); } } protected void endBuild() { for (CeylonBuildHook hook : contributedHooks) { hook.endBuild(); } } }; public static CeylonBuildHook replaceHook(CeylonBuildHook hook){ CeylonBuildHook previousHook = buildHook; buildHook = hook; return previousHook; } private static WeakReference<Job> notificationJobReference = null; private static synchronized Job getNotificationJob() { Job job = null; if (notificationJobReference != null) { job = notificationJobReference.get(); } if (job == null) { for (Job j : Job.getJobManager().find(null)) { if (NotificationManager.class.equals(j.getClass().getEnclosingClass())) { job = j; notificationJobReference = new WeakReference<Job>(job); break; } } } return job; } public static void waitForUpToDateJavaModel(long timeout, IProject project, IProgressMonitor monitor) { Job job = getNotificationJob(); if (job == null) { return; } monitor.subTask("Taking in account the resource changes of the previous builds" + project != null ? project.getName() : ""); long timeLimit = System.currentTimeMillis() + timeout; while (job.getState() != Job.NONE) { boolean stopWaiting = false; if (job.isBlocking()) { stopWaiting = true; } try { Thread.sleep(1000); } catch (InterruptedException e) { stopWaiting = true; } if (System.currentTimeMillis() > timeLimit) { stopWaiting = true; } if (stopWaiting) { break; } } } @Override protected IProject[] build(final int kind, @SuppressWarnings("rawtypes") Map args, IProgressMonitor mon) throws CoreException { final IProject project = getProject(); final IJavaProject javaProject = JavaCore.create(project); final SubMonitor monitor = SubMonitor.convert(mon, "Ceylon build of project " + project.getName(), 100); try { buildHook.startBuild(kind, args, project, getBuildConfig(), getContext(), monitor); } catch (CoreException e) { if (e.getStatus().getSeverity() == IStatus.CANCEL) { return project.getReferencedProjects(); } } IMarker[] buildMarkers = project.findMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, true, DEPTH_ZERO); for (IMarker m: buildMarkers) { Object message = m.getAttribute("message"); if (message!=null && message.toString().endsWith("'JDTClasses'")) { //ignore message from JDT about missing JDTClasses dir m.delete(); } else if (message!=null && message.toString().contains("is missing required Java project:")) { return project.getReferencedProjects(); } } List<IClasspathContainer> cpContainers = getCeylonClasspathContainers(javaProject); boolean languageModuleContainerFound = false; boolean applicationModulesContainerFound = false; for (IClasspathContainer container : cpContainers) { if (container instanceof CeylonLanguageModuleContainer) { languageModuleContainerFound = true; } if (container instanceof CeylonProjectModulesContainer) { applicationModulesContainerFound = true; } } if (! languageModuleContainerFound) { //if the ClassPathContainer is missing, add an error IMarker marker = project.createMarker(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER); marker.setAttribute(IMarker.MESSAGE, "The Ceylon classpath container for the language module is not set on the project " + project.getName() + " (try running Enable Ceylon Builder on the project)"); marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); marker.setAttribute(IMarker.LOCATION, "Bytecode generation"); return project.getReferencedProjects(); } if (! applicationModulesContainerFound) { //if the ClassPathContainer is missing, add an error IMarker marker = project.createMarker(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER); marker.setAttribute(IMarker.MESSAGE, "The Ceylon classpath container for application modules is not set on the project " + project.getName() + " (try running Enable Ceylon Builder on the project)"); marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); marker.setAttribute(IMarker.LOCATION, "Bytecode generation"); return project.getReferencedProjects(); } /* Begin issue #471 */ ICommand[] builders = project.getDescription().getBuildSpec(); int javaOrder=0, ceylonOrder = 0; for (int n=0; n<builders.length; n++) { if (builders[n].getBuilderName().equals(JavaCore.BUILDER_ID)) { javaOrder = n; } else if (builders[n].getBuilderName().equals(CeylonBuilder.BUILDER_ID)) { ceylonOrder = n; } } if (ceylonOrder < javaOrder) { //if the build order is not correct, add an error and return IMarker marker = project.createMarker(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER); marker.setAttribute(IMarker.MESSAGE, "The Ceylon Builder should run after the Java Builder. Change order of builders in project properties for project: " + project.getName()); marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); marker.setAttribute(IMarker.LOCATION, "Bytecode generation"); return project.getReferencedProjects(); } /* End issue #471 */ List<PhasedUnit> builtPhasedUnits = Collections.emptyList(); final BooleanHolder mustDoFullBuild = new BooleanHolder(); final BooleanHolder mustResolveClasspathContainer = new BooleanHolder(); final IResourceDelta currentDelta = getDelta(getProject()); List<IResourceDelta> projectDeltas = new ArrayList<IResourceDelta>(); projectDeltas.add(currentDelta); for (IProject requiredProject : project.getReferencedProjects()) { projectDeltas.add(getDelta(requiredProject)); } boolean somethingToDo = chooseBuildTypeFromDeltas(kind, project, projectDeltas, mustDoFullBuild, mustResolveClasspathContainer); if (!somethingToDo && (args==null || !args.containsKey(BUILDER_ID + ".reentrant"))) { return project.getReferencedProjects(); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } if (mustResolveClasspathContainer.value) { if (cpContainers != null) { buildHook.resolvingClasspathContainer(cpContainers); for (IClasspathContainer container: cpContainers) { if (container instanceof CeylonProjectModulesContainer) { CeylonProjectModulesContainer applicationModulesContainer = (CeylonProjectModulesContainer) container; boolean changed = applicationModulesContainer.resolveClasspath(monitor, true); if(changed) { buildHook.setAndRefreshClasspathContainer(); JavaCore.setClasspathContainer(applicationModulesContainer.getPath(), new IJavaProject[]{javaProject}, new IClasspathContainer[]{null} , monitor); applicationModulesContainer.refreshClasspathContainer(monitor); } } } } } boolean mustWarmupCompletionProcessor = false; try { // startTime = System.nanoTime(); /*IBuildConfiguration[] buildConfsBefore = getContext().getAllReferencedBuildConfigs(); if (buildConfsBefore.length == 0) { //don't clear the console unless //we are the first project in //the build invocation findConsole().clearConsole(); }*/ // getConsoleStream().println(timedMessage("Starting Ceylon build on project: " + project.getName())); // boolean binariesGenerationOK; final TypeChecker typeChecker; Collection<IFile> sourcesForBinaryGeneration = Collections.emptyList(); if (mustDoFullBuild.value) { buildHook.doFullBuild(); monitor.subTask("Full Ceylon build of project " + project.getName()); // getConsoleStream().println(timedMessage("Full build of model")); if (monitor.isCanceled()) { throw new OperationCanceledException(); } cleanupModules(monitor, project); cleanupJdtClasses(monitor, project); monitor.subTask("Clearing existing markers of project " + project.getName()); clearProjectMarkers(project); clearMarkersOn(project, true); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } //if (! getModelState(project).equals(ModelState.Parsed)) { if (!mustResolveClasspathContainer.value) { monitor.subTask("Parsing source of project " + project.getName()); //if we already resolved the classpath, the //model has already been freshly-parsed buildHook.parseCeylonModel(); typeChecker = parseCeylonModel(project, monitor.newChild(5, PREPEND_MAIN_LABEL_TO_SUBTASK)); monitor.worked(1); } else { typeChecker = getProjectTypeChecker(project); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.subTask("Typechecking all source files of project " + project.getName()); modelStates.put(project, ModelState.TypeChecking); builtPhasedUnits = doWithCeylonModelCaching(new Callable<List<PhasedUnit>>() { @Override public List<PhasedUnit> call() throws Exception { return fullTypeCheck(project, typeChecker, monitor.newChild(35, PREPEND_MAIN_LABEL_TO_SUBTASK )); } }); modelStates.put(project, ModelState.TypeChecked); monitor.worked(1); sourcesForBinaryGeneration = getProjectSources(project); mustWarmupCompletionProcessor = true; } else { buildHook.doIncrementalBuild(); typeChecker = typeCheckers.get(project); PhasedUnits phasedUnits = typeChecker.getPhasedUnits(); List<IFile> filesToRemove = new ArrayList<IFile>(); Set<IFile> changedSources = new HashSet<IFile>(); monitor.subTask("Scanning deltas of project " + project.getName()); calculateChangedSources(currentDelta, projectDeltas, filesToRemove, changedSources, monitor); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.subTask("Cleaning removed files for project " + project.getName()); cleanRemovedSources(filesToRemove, phasedUnits, project); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } if (!isModelTypeChecked(project)) { buildHook.fullTypeCheckDuringIncrementalBuild(); if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.subTask("Clearing existing markers of project (except backend errors)" + project.getName()); clearProjectMarkers(project); clearMarkersOn(project, false); monitor.worked(1); monitor.subTask("Initial typechecking all source files of project " + project.getName()); modelStates.put(project, ModelState.TypeChecking); builtPhasedUnits = doWithCeylonModelCaching(new Callable<List<PhasedUnit>>() { @Override public List<PhasedUnit> call() throws Exception { return fullTypeCheck(project, typeChecker, monitor.newChild(35, PREPEND_MAIN_LABEL_TO_SUBTASK )); } }); modelStates.put(project, ModelState.TypeChecked); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.subTask("Collecting dependencies of project " + project.getName()); // getConsoleStream().println(timedMessage("Collecting dependencies")); collectDependencies(project, typeChecker, builtPhasedUnits); monitor.worked(1); monitor.subTask("Collecting problems for project " + project.getName()); addProblemAndTaskMarkers(builtPhasedUnits, project); monitor.worked(1); mustWarmupCompletionProcessor = true; } monitor.subTask("Incremental Ceylon build of project " + project.getName()); // getConsoleStream().printlbuiltPhasedUnitsn(timedMessage("Incremental build of model")); monitor.subTask("Scanning dependencies of deltas of project " + project.getName()); final Collection<IFile> sourceToCompile= new HashSet<IFile>(); calculateDependencies(project, sourceToCompile, currentDelta, changedSources, typeChecker, phasedUnits, monitor); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } buildHook.incrementalBuildSources(changedSources, filesToRemove, sourceToCompile); /*if (emitDiags) { getConsoleStream().println("All files to compile:"); dumpSourceList(sourceToCompile); }*/ monitor.subTask("Compiling " + sourceToCompile.size() + " source files in project " + project.getName()); builtPhasedUnits = doWithCeylonModelCaching(new Callable<List<PhasedUnit>>() { @Override public List<PhasedUnit> call() throws Exception { return incrementalBuild(project, sourceToCompile, monitor.newChild(35, PREPEND_MAIN_LABEL_TO_SUBTASK)); } }); if (builtPhasedUnits.isEmpty() && sourceToCompile.isEmpty()) { if (mustWarmupCompletionProcessor) { warmupCompletionProcessor(project, typeChecker); } return project.getReferencedProjects(); } monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } buildHook.incrementalBuildResult(builtPhasedUnits); monitor.subTask("Updating referencing projects of project " + project.getName()); // getConsoleStream().println(timedMessage("Updating model in referencing projects")); // updateExternalPhasedUnitsInReferencingProjects(project, builtPhasedUnits); monitor.worked(1); sourcesForBinaryGeneration = sourceToCompile; } monitor.subTask("Collecting problems for project " + project.getName()); addProblemAndTaskMarkers(builtPhasedUnits, project); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.subTask("Collecting dependencies of project " + project.getName()); // getConsoleStream().println(timedMessage("Collecting dependencies")); collectDependencies(project, typeChecker, builtPhasedUnits); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } buildHook.beforeGeneratingBinaries(); monitor.subTask("Generating binaries for project " + project.getName()); // getConsoleStream().println(timedMessage("Incremental generation of class files...")); // getConsoleStream().println(" ...compiling " + // sourceToCompile.size() + " source files..."); /*binariesGenerationOK =*/ final Collection<IFile> sourcesToProcess = sourcesForBinaryGeneration; doWithCeylonModelCaching(new Callable<Boolean>() { @Override public Boolean call() throws CoreException { return generateBinaries(project, javaProject, sourcesToProcess, typeChecker, monitor.newChild(45, PREPEND_MAIN_LABEL_TO_SUBTASK)); } }); // getConsoleStream().println(successMessage(binariesGenerationOK)); monitor.worked(1); buildHook.afterGeneratingBinaries(); if (monitor.isCanceled()) { throw new OperationCanceledException(); } if (isExplodeModulesEnabled(project)) { monitor.subTask("Rebuilding using exploded modules directory of " + project.getName()); sheduleIncrementalRebuild(args, project, monitor); monitor.worked(1); } monitor.done(); if (mustWarmupCompletionProcessor) { warmupCompletionProcessor(project, typeChecker); } return project.getReferencedProjects(); } finally { buildHook.endBuild(); } } private void warmupCompletionProcessor(final IProject project, final TypeChecker typeChecker) { Job job = new WarmupJob(project.getName(), typeChecker); job.setPriority(Job.BUILD); //job.setSystem(true); job.setRule(project.getWorkspace().getRoot()); job.schedule(); } private void sheduleIncrementalRebuild(@SuppressWarnings("rawtypes") Map args, final IProject project, IProgressMonitor monitor) { try { getCeylonClassesOutputFolder(project).refreshLocal(DEPTH_INFINITE, monitor); } catch (CoreException e) { e.printStackTrace(); }//monitor); if (args==null || !args.containsKey(BUILDER_ID + ".reentrant")) { buildHook.scheduleReentrantBuild(); Job job = new Job("Rebuild with Ceylon classes") { @Override protected IStatus run(IProgressMonitor monitor) { try { //we have already done a build of both the Java and Ceylon classes //so now go back and try to build the both the Java and Ceylon //classes again, using the classes we previously generated - this //is to allow references from Java to Ceylon project.build(INCREMENTAL_BUILD, JavaCore.BUILDER_ID, null, monitor); Map<String,String> map = new HashMap<String,String>(); map.put(BUILDER_ID + ".reentrant", "true"); project.build(INCREMENTAL_BUILD, BUILDER_ID, map, monitor); } catch (CoreException e) { e.printStackTrace(); } return Status.OK_STATUS; } }; job.setRule(project.getWorkspace().getRoot()); job.schedule(); } } private void collectDependencies(IProject project, TypeChecker typeChecker, List<PhasedUnit> builtPhasedUnits) throws CoreException { for (PhasedUnit pu : builtPhasedUnits) { new UnitDependencyVisitor(pu).visit(pu.getCompilationUnit()); } } private void cleanRemovedSources(List<IFile> filesToRemove, PhasedUnits phasedUnits, IProject project) { removeObsoleteClassFiles(filesToRemove, project); for (IFile fileToRemove: filesToRemove) { if(isCeylon(fileToRemove)) { // Remove the ceylon phasedUnit (which will also remove the unit from the package) PhasedUnit phasedUnitToDelete = phasedUnits.getPhasedUnit(createResourceVirtualFile(fileToRemove)); if (phasedUnitToDelete != null) { assert(phasedUnitToDelete instanceof ProjectPhasedUnit); ((ProjectPhasedUnit) phasedUnitToDelete).remove(); } } else if (isJava(fileToRemove)) { // Remove the external unit from the package Package pkg = retrievePackage(fileToRemove.getParent()); if (pkg != null) { for (Unit unitToTest: pkg.getUnits()) { if (unitToTest.getFilename().equals(fileToRemove.getName())) { pkg.removeUnit(unitToTest); assert (pkg.getModule() instanceof JDTModule); JDTModule module = (JDTModule) pkg.getModule(); module.removedOriginalUnit(unitToTest.getRelativePath()); break; } } } } } } private void calculateDependencies(IProject project, Collection<IFile> sourceToCompile, IResourceDelta currentDelta, Set<IFile> fChangedSources, TypeChecker typeChecker, PhasedUnits phasedUnits, IProgressMonitor monitor) { if (!fChangedSources.isEmpty()) { Collection<IFile> changeDependents= new HashSet<IFile>(); changeDependents.addAll(fChangedSources); /*if (emitDiags) { getConsoleStream().println("Changed files:"); dumpSourceList(changeDependents); }*/ boolean changed = false; do { Collection<IFile> additions= new HashSet<IFile>(); for (Iterator<IFile> iter=changeDependents.iterator(); iter.hasNext();) { IFile srcFile= iter.next(); IProject currentFileProject = srcFile.getProject(); TypeChecker currentFileTypeChecker = null; if (currentFileProject == project) { currentFileTypeChecker = typeChecker; } else { currentFileTypeChecker = getProjectTypeChecker(currentFileProject); } Set<String> filesDependingOn = getDependentsOf(srcFile, currentFileTypeChecker, currentFileProject); for (String dependingFile: filesDependingOn) { if (monitor.isCanceled()) { throw new OperationCanceledException(); } //TODO: note that the following is slightly // fragile - it depends on the format // of the path that we use to track // dependents! IPath pathRelativeToProject = new Path(dependingFile); //.makeRelativeTo(project.getLocation()); IFile depFile= (IFile) project.findMember(pathRelativeToProject); if (depFile == null) { depFile= (IFile) currentFileProject.findMember(dependingFile); } if (depFile != null) { additions.add(depFile); } else { System.err.println("could not resolve dependent unit: " + dependingFile); } } } changed = changeDependents.addAll(additions); } while (changed); if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnits.getPhasedUnits()) { Unit unit = phasedUnit.getUnit(); if (!unit.getUnresolvedReferences().isEmpty()) { IFile fileToAdd = ((IFileVirtualFile)(phasedUnit.getUnitFile())).getFile(); if (fileToAdd.exists()) { sourceToCompile.add(fileToAdd); } } Set<Declaration> duplicateDeclarations = unit.getDuplicateDeclarations(); if (!duplicateDeclarations.isEmpty()) { IFile fileToAdd = ((IFileVirtualFile)(phasedUnit.getUnitFile())).getFile(); if (fileToAdd.exists()) { sourceToCompile.add(fileToAdd); } for (Declaration duplicateDeclaration : duplicateDeclarations) { Unit duplicateUnit = duplicateDeclaration.getUnit(); if ((duplicateUnit instanceof SourceFile) && (duplicateUnit instanceof IResourceAware)) { IFile duplicateDeclFile = ((IResourceAware) duplicateUnit).getFileResource(); if (duplicateDeclFile != null && duplicateDeclFile.exists()) { sourceToCompile.add(duplicateDeclFile); } } } } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (IFile f: changeDependents) { if (isSourceFile(f) && f.getProject() == project) { if (f.exists()) { sourceToCompile.add(f); } else { // If the file is moved : add a dependency on the new file if (currentDelta != null) { IResourceDelta removedFile = currentDelta.findMember(f.getProjectRelativePath()); if (removedFile != null && (removedFile.getFlags() & IResourceDelta.MOVED_TO) != 0 && removedFile.getMovedToPath() != null) { sourceToCompile.add(project.getFile(removedFile.getMovedToPath().removeFirstSegments(1))); } } } } } } } private void calculateChangedSources(final IResourceDelta currentDelta, List<IResourceDelta> projectDeltas, final List<IFile> filesToRemove, final Set<IFile> changedSources, IProgressMonitor monitor) throws CoreException { for (final IResourceDelta projectDelta: projectDeltas) { if (projectDelta != null) { IProject p = (IProject) projectDelta.getResource(); List<IPath> deltaSourceFolders = getSourceFolders(p); for (IResourceDelta sourceDelta: projectDelta.getAffectedChildren()) { for (IPath ip: deltaSourceFolders) { if (sourceDelta.getResource().getFullPath().isPrefixOf(ip)) { //a real Ceylon source folder so scan for changes /*if (emitDiags) getConsoleStream().println("==> Scanning resource delta for '" + p.getName() + "'... <==");*/ sourceDelta.accept(new IResourceDeltaVisitor() { public boolean visit(IResourceDelta delta) throws CoreException { IResource resource = delta.getResource(); if (resource instanceof IFile) { IFile file= (IFile) resource; if (isCeylonOrJava(file)) { changedSources.add(file); if (projectDelta == currentDelta) { if (delta.getKind() == IResourceDelta.REMOVED) { filesToRemove.add((IFile) resource); } } } return false; } return true; } }); /*if (emitDiags) getConsoleStream().println("Delta scan completed for project '" + projectDelta.getResource().getName() + "'...");*/ break; } } } } } } public boolean chooseBuildTypeFromDeltas(final int kind, final IProject project, final List<IResourceDelta> currentDeltas, final BooleanHolder mustDoFullBuild, final BooleanHolder mustResolveClasspathContainer) { mustDoFullBuild.value = kind == FULL_BUILD || kind == CLEAN_BUILD || !isModelParsed(project); mustResolveClasspathContainer.value = kind==FULL_BUILD; //false; final BooleanHolder sourceModified = new BooleanHolder(); if (JavaProjectStateMirror.hasClasspathChanged(project)) { mustDoFullBuild.value = true; } if (!mustDoFullBuild.value || !mustResolveClasspathContainer.value) { for (IResourceDelta currentDelta: currentDeltas) { if (currentDelta != null) { try { currentDelta.accept(new DeltaScanner(mustDoFullBuild, project, sourceModified, mustResolveClasspathContainer)); } catch (CoreException e) { e.printStackTrace(); mustDoFullBuild.value = true; mustResolveClasspathContainer.value = true; } } else { mustDoFullBuild.value = true; mustResolveClasspathContainer.value = true; } } } class DecisionMaker { public boolean mustContinueBuild() { return mustDoFullBuild.value || mustResolveClasspathContainer.value || sourceModified.value || ! isModelTypeChecked(project); } }; DecisionMaker decisionMaker = new DecisionMaker(); buildHook.deltasAnalyzed(currentDeltas, sourceModified, mustDoFullBuild, mustResolveClasspathContainer, decisionMaker.mustContinueBuild()); return decisionMaker.mustContinueBuild(); } // private static String successMessage(boolean binariesGenerationOK) { // return " " + (binariesGenerationOK ? // "...binary generation succeeded" : "...binary generation FAILED"); private Set<String> getDependentsOf(IFile srcFile, TypeChecker currentFileTypeChecker, IProject currentFileProject) { if (srcFile.getRawLocation().getFileExtension().equals("ceylon")) { PhasedUnit phasedUnit = currentFileTypeChecker.getPhasedUnits() .getPhasedUnit(ResourceVirtualFile.createResourceVirtualFile(srcFile)); if (phasedUnit != null && phasedUnit.getUnit() != null) { return phasedUnit.getUnit().getDependentsOf(); } } else { Unit unit = getJavaUnit(currentFileProject, srcFile); if (unit instanceof JavaCompilationUnit) { return unit.getDependentsOf(); } } return Collections.emptySet(); } private void updateExternalPhasedUnitsInReferencingProjects(IProject project, List<PhasedUnit> builtPhasedUnits) { for (IProject referencingProject : project.getReferencingProjects()) { TypeChecker referencingTypeChecker = getProjectTypeChecker(referencingProject); if (referencingTypeChecker != null) { List<PhasedUnit> referencingPhasedUnits = new ArrayList<PhasedUnit>(); for (PhasedUnit builtPhasedUnit : builtPhasedUnits) { List<PhasedUnits> phasedUnitsOfDependencies = referencingTypeChecker.getPhasedUnitsOfDependencies(); for (PhasedUnits phasedUnitsOfDependency : phasedUnitsOfDependencies) { String relativePath = builtPhasedUnit.getPathRelativeToSrcDir(); PhasedUnit referencingPhasedUnit = phasedUnitsOfDependency.getPhasedUnitFromRelativePath(relativePath); if (referencingPhasedUnit != null) { phasedUnitsOfDependency.removePhasedUnitForRelativePath(relativePath); PhasedUnit newReferencingPhasedUnit = new CrossProjectPhasedUnit(referencingPhasedUnit.getUnitFile(), referencingPhasedUnit.getSrcDir(), builtPhasedUnit.getCompilationUnit(), referencingPhasedUnit.getPackage(), phasedUnitsOfDependency.getModuleManager(), referencingTypeChecker, builtPhasedUnit.getTokens(), project); phasedUnitsOfDependency.addPhasedUnit(newReferencingPhasedUnit.getUnitFile(), newReferencingPhasedUnit); // replace referencingPhasedUnit referencingPhasedUnits.add(newReferencingPhasedUnit); } } } if (isModelTypeChecked(referencingProject)) { for (PhasedUnit pu : referencingPhasedUnits) { pu.scanDeclarations(); } for (PhasedUnit pu : referencingPhasedUnits) { pu.scanTypeDeclarations(); } for (PhasedUnit pu : referencingPhasedUnits) { pu.validateRefinement(); //TODO: only needed for type hierarchy view in IDE! } } } } } static ProjectPhasedUnit parseFileToPhasedUnit(final ModuleManager moduleManager, final TypeChecker typeChecker, final ResourceVirtualFile file, final ResourceVirtualFile srcDir, final Package pkg) { return new CeylonSourceParser<ProjectPhasedUnit>() { @Override protected String getCharset() { try { return file.getResource().getProject().getDefaultCharset(); } catch (Exception e) { throw new RuntimeException(e); } } @Override protected ProjectPhasedUnit createPhasedUnit(CompilationUnit cu, Package pkg, CommonTokenStream tokenStream) { return new ProjectPhasedUnit(file, srcDir, cu, pkg, moduleManager, typeChecker, tokenStream.getTokens()); } }.parseFileToPhasedUnit(moduleManager, typeChecker, file, srcDir, pkg); } private List<PhasedUnit> incrementalBuild(IProject project, Collection<IFile> sourceToCompile, IProgressMonitor mon) { SubMonitor monitor = SubMonitor.convert(mon, "Typechecking " + sourceToCompile.size() + " source files in project " + project.getName(), sourceToCompile.size()*6); TypeChecker typeChecker = typeCheckers.get(project); PhasedUnits pus = typeChecker.getPhasedUnits(); JDTModuleManager moduleManager = (JDTModuleManager) pus.getModuleManager(); JDTModelLoader modelLoader = getModelLoader(typeChecker); // First refresh the modules that are cross-project references to sources modules // in referenced projects. This will : // - clean the binary declarations and reload the class-to-source mapping file for binary-based modules, // - remove old PhasedUnits and parse new or updated PhasedUnits from the source archive for source-based modules for (Module m : typeChecker.getContext().getModules().getListOfModules()) { if (m instanceof JDTModule) { JDTModule module = (JDTModule) m; if (module.isCeylonArchive()) { module.refresh(); } } } // Secondly typecheck again the changed PhasedUnits in changed external source modules // (those which come from referenced projects) List<PhasedUnits> phasedUnitsOfDependencies = typeChecker.getPhasedUnitsOfDependencies(); List<PhasedUnit> dependencies = new ArrayList<PhasedUnit>(); for (PhasedUnits phasedUnits: phasedUnitsOfDependencies) { for (PhasedUnit phasedUnit: phasedUnits.getPhasedUnits()) { dependencies.add(phasedUnit); } } for (PhasedUnit pu: dependencies) { monitor.subTask("- scanning declarations " + pu.getUnit().getFilename()); pu.scanDeclarations(); monitor.worked(1); } for (PhasedUnit pu: dependencies) { monitor.subTask("- scanning type declarations " + pu.getUnit().getFilename()); pu.scanTypeDeclarations(); monitor.worked(2); } for (PhasedUnit pu: dependencies) { pu.validateRefinement(); //TODO: only needed for type hierarchy view in IDE! } // Then typecheck the changed source of this project Set<String> cleanedPackages = new HashSet<String>(); List<PhasedUnit> phasedUnitsToUpdate = new ArrayList<PhasedUnit>(); for (IFile fileToUpdate : sourceToCompile) { if (monitor.isCanceled()) { throw new OperationCanceledException(); } // skip non-ceylon files if(!isCeylon(fileToUpdate)) { if (isJava(fileToUpdate)) { Unit toRemove = getJavaUnit(project, fileToUpdate); if(toRemove != null) { // If the unit is not null, the package should never be null Package p = toRemove.getPackage(); p.removeUnit(toRemove); assert (p.getModule() instanceof JDTModule); JDTModule module = (JDTModule) p.getModule(); module.removedOriginalUnit(toRemove.getRelativePath()); } else { String packageName = getPackageName(fileToUpdate); if (! cleanedPackages.contains(packageName)) { modelLoader.clearCachesOnPackage(packageName); cleanedPackages.add(packageName); } } continue; } } ResourceVirtualFile file = ResourceVirtualFile.createResourceVirtualFile(fileToUpdate); IPath srcFolderPath = retrieveSourceFolder(fileToUpdate, project); ResourceVirtualFile srcDir = new IFolderVirtualFile(project, srcFolderPath); ProjectPhasedUnit alreadyBuiltPhasedUnit = (ProjectPhasedUnit) pus.getPhasedUnit(file); Package pkg = null; if (alreadyBuiltPhasedUnit!=null) { // Editing an already built file pkg = alreadyBuiltPhasedUnit.getPackage(); } else { IContainer packageFolder = file.getResource().getParent(); pkg = retrievePackage(packageFolder); if (pkg == null) { pkg = createNewPackage(packageFolder); } } PhasedUnit newPhasedUnit = parseFileToPhasedUnit(moduleManager, typeChecker, file, srcDir, pkg); phasedUnitsToUpdate.add(newPhasedUnit); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } if (phasedUnitsToUpdate.size() == 0) { return phasedUnitsToUpdate; } clearProjectMarkers(project); clearMarkersOn(sourceToCompile, true); for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { assert(phasedUnit instanceof ProjectPhasedUnit); ((ProjectPhasedUnit)phasedUnit).install(); } modelLoader.setupSourceFileObjects(phasedUnitsToUpdate); if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { if (! phasedUnit.isDeclarationsScanned()) { phasedUnit.validateTree(); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { if (! phasedUnit.isDeclarationsScanned()) { monitor.subTask("- scanning declarations " + phasedUnit.getUnit().getFilename()); phasedUnit.scanDeclarations(); } monitor.worked(1); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { if (! phasedUnit.isTypeDeclarationsScanned()) { monitor.subTask("- scanning type declarations " + phasedUnit.getUnit().getFilename()); phasedUnit.scanTypeDeclarations(); } monitor.worked(2); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { if (! phasedUnit.isRefinementValidated()) { phasedUnit.validateRefinement(); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { if (! phasedUnit.isFullyTyped()) { monitor.subTask("- typechecking " + phasedUnit.getUnit().getFilename()); phasedUnit.analyseTypes(); if (showWarnings(project)) { phasedUnit.analyseUsage(); } monitor.worked(3); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { phasedUnit.analyseFlow(); } UnknownTypeCollector utc = new UnknownTypeCollector(); for (PhasedUnit pu : phasedUnitsToUpdate) { pu.getCompilationUnit().visit(utc); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.done(); return phasedUnitsToUpdate; } private Unit getJavaUnit(IProject project, IFile fileToUpdate) { IJavaElement javaElement = (IJavaElement) fileToUpdate.getAdapter(IJavaElement.class); if (javaElement instanceof ICompilationUnit) { ICompilationUnit compilationUnit = (ICompilationUnit) javaElement; IJavaElement packageFragment = compilationUnit.getParent(); JDTModelLoader projectModelLoader = getProjectModelLoader(project); // TODO : Why not use the Model Loader cache to get the declaration // instead of iterating through all the packages ? if (projectModelLoader != null) { Package pkg = projectModelLoader.findPackage(packageFragment.getElementName()); if (pkg != null) { for (Declaration decl : pkg.getMembers()) { Unit unit = decl.getUnit(); if (unit.getFilename().equals(fileToUpdate.getName())) { return unit; } } } } } return null; } private List<PhasedUnit> fullTypeCheck(IProject project, TypeChecker typeChecker, IProgressMonitor mon) throws CoreException { List<PhasedUnits> phasedUnitsOfDependencies = typeChecker.getPhasedUnitsOfDependencies(); List<PhasedUnit> dependencies = new ArrayList<PhasedUnit>(); for (PhasedUnits phasedUnits: phasedUnitsOfDependencies) { for (PhasedUnit phasedUnit: phasedUnits.getPhasedUnits()) { dependencies.add(phasedUnit); } } final List<PhasedUnit> listOfUnits = typeChecker.getPhasedUnits().getPhasedUnits(); SubMonitor monitor = SubMonitor.convert(mon, "Typechecking " + listOfUnits.size() + " source files of project " + project.getName(), dependencies.size()*5+listOfUnits.size()*6); monitor.subTask("- typechecking source archives for project " + project.getName()); JDTModelLoader loader = getModelLoader(typeChecker); // loader.reset(); for (PhasedUnit pu: dependencies) { monitor.subTask("- scanning declarations " + pu.getUnit().getFilename()); pu.scanDeclarations(); monitor.worked(1); } for (PhasedUnit pu: dependencies) { monitor.subTask("- scanning type declarations " + pu.getUnit().getFilename()); pu.scanTypeDeclarations(); monitor.worked(2); } for (PhasedUnit pu: dependencies) { pu.validateRefinement(); //TODO: only needed for type hierarchy view in IDE! } Module languageModule = loader.getLanguageModule(); loader.loadPackage(languageModule, "com.redhat.ceylon.compiler.java.metadata", true); loader.loadPackage(languageModule, LANGUAGE_MODULE_NAME, true); loader.loadPackage(languageModule, "ceylon.language.descriptor", true); loader.loadPackageDescriptors(); monitor.subTask("(typechecking source files for project " + project.getName() +")"); for (PhasedUnit pu : listOfUnits) { if (! pu.isDeclarationsScanned()) { monitor.subTask("- scanning declarations " + pu.getUnit().getFilename()); pu.validateTree(); pu.scanDeclarations(); monitor.worked(1); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit pu : listOfUnits) { if (! pu.isTypeDeclarationsScanned()) { monitor.subTask("- scanning types " + pu.getUnit().getFilename()); pu.scanTypeDeclarations(); monitor.worked(2); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit pu: listOfUnits) { if (! pu.isRefinementValidated()) { pu.validateRefinement(); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit pu : listOfUnits) { if (! pu.isFullyTyped()) { monitor.subTask("- typechecking " + pu.getUnit().getFilename()); pu.analyseTypes(); if (showWarnings(project)) { pu.analyseUsage(); } monitor.worked(3); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit pu: listOfUnits) { pu.analyseFlow(); } UnknownTypeCollector utc = new UnknownTypeCollector(); for (PhasedUnit pu : listOfUnits) { pu.getCompilationUnit().visit(utc); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } projectModuleDependencies.get(project).addModulesWithDependencies(typeChecker.getContext().getModules().getListOfModules()); monitor.done(); return typeChecker.getPhasedUnits().getPhasedUnits(); } public static TypeChecker parseCeylonModel(final IProject project, final IProgressMonitor mon) throws CoreException { return doWithCeylonModelCaching(new Callable<TypeChecker>() { @Override public TypeChecker call() throws CoreException { modelStates.put(project, ModelState.Parsing); typeCheckers.remove(project); projectRepositoryManagers.remove(project); projectSources.remove(project); if (projectModuleDependencies.containsKey(project)) { projectModuleDependencies.get(project).reset(); } else { projectModuleDependencies.put(project, new ModuleDependencies(new ModuleDependencies.ErrorListener() { @Override public void moduleNotAvailable(Module module) { System.out.println("WARNING : module " + module.getSignature() + " in project " + project.getName() + " is not available after the Module Validation step !"); } })); } SubMonitor monitor = SubMonitor.convert(mon, "Setting up typechecker for project " + project.getName(), 5); if (monitor.isCanceled()) { throw new OperationCanceledException(); } final IJavaProject javaProject = JavaCore.create(project); TypeChecker typeChecker = buildTypeChecker(project, javaProject); PhasedUnits phasedUnits = typeChecker.getPhasedUnits(); JDTModuleManager moduleManager = (JDTModuleManager) phasedUnits.getModuleManager(); moduleManager.setTypeChecker(typeChecker); Context context = typeChecker.getContext(); JDTModelLoader modelLoader = (JDTModelLoader) moduleManager.getModelLoader(); Module defaultModule = context.getModules().getDefaultModule(); monitor.worked(1); monitor.subTask("- parsing source files for project " + project.getName()); if (monitor.isCanceled()) { throw new OperationCanceledException(); } phasedUnits.getModuleManager().prepareForTypeChecking(); List<IFile> scannedSources = scanSources(project, javaProject, typeChecker, phasedUnits, moduleManager, modelLoader, defaultModule, monitor); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } modelLoader.setupSourceFileObjects(typeChecker.getPhasedUnits().getPhasedUnits()); monitor.worked(1); // Parsing of ALL units in the source folder should have been done if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.subTask("- determining module dependencies for " + project.getName()); phasedUnits.visitModules(); //By now the language module version should be known (as local) //or we should use the default one. Module languageModule = context.getModules().getLanguageModule(); if (languageModule.getVersion() == null) { languageModule.setVersion(TypeChecker.LANGUAGE_MODULE_VERSION); } monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } final ModuleValidator moduleValidator = new ModuleValidator(context, phasedUnits) { @Override protected void executeExternalModulePhases() {} }; moduleValidator.verifyModuleDependencyTree(); typeChecker.setPhasedUnitsOfDependencies(moduleValidator.getPhasedUnitsOfDependencies()); for (PhasedUnits dependencyPhasedUnits: typeChecker.getPhasedUnitsOfDependencies()) { modelLoader.addSourceArchivePhasedUnits(dependencyPhasedUnits.getPhasedUnits()); } if (compileToJs(project)) { for (Module module : typeChecker.getContext().getModules().getListOfModules()) { if (module instanceof JDTModule) { JDTModule jdtModule = (JDTModule) module; if (jdtModule.isCeylonArchive()) { getProjectRepositoryManager(project).getArtifact( new ArtifactContext( jdtModule.getNameAsString(), jdtModule.getVersion(), ArtifactContext.JS)); } } } } monitor.worked(1); typeCheckers.put(project, typeChecker); projectSources.put(project, scannedSources); modelStates.put(project, ModelState.Parsed); monitor.done(); return typeChecker; } }); } private static TypeChecker buildTypeChecker(IProject project, final IJavaProject javaProject) throws CoreException { TypeCheckerBuilder typeCheckerBuilder = new TypeCheckerBuilder() .verbose(false) .moduleManagerFactory(new ModuleManagerFactory(){ @Override public ModuleManager createModuleManager(Context context) { return new JDTModuleManager(context, javaProject); } }); RepositoryManager repositoryManager = getProjectRepositoryManager(project); typeCheckerBuilder.setRepositoryManager(repositoryManager); TypeChecker typeChecker = typeCheckerBuilder.getTypeChecker(); return typeChecker; } private static List<IFile> scanSources(IProject project, IJavaProject javaProject, final TypeChecker typeChecker, final PhasedUnits phasedUnits, final JDTModuleManager moduleManager, final JDTModelLoader modelLoader, final Module defaultModule, IProgressMonitor monitor) throws CoreException { final List<IFile> scannedSources = new ArrayList<IFile>(); final Collection<IPath> sourceFolders = getSourceFolders(javaProject); for (final IPath srcAbsoluteFolderPath : sourceFolders) { final IPath srcFolderPath = srcAbsoluteFolderPath.makeRelativeTo(project.getFullPath()); final ResourceVirtualFile srcDir = new IFolderVirtualFile(project, srcFolderPath); IResource srcDirResource = srcDir.getResource(); if (! srcDirResource.exists()) { continue; } if (monitor.isCanceled()) { throw new OperationCanceledException(); } // First Scan all non-default source modules and attach the contained packages srcDirResource.accept(new ModulesScanner(defaultModule, modelLoader, moduleManager, srcDir, srcFolderPath, typeChecker, scannedSources, phasedUnits)); } for (final IPath srcAbsoluteFolderPath : sourceFolders) { final IPath srcFolderPath = srcAbsoluteFolderPath.makeRelativeTo(project.getFullPath()); final ResourceVirtualFile srcDir = new IFolderVirtualFile(project, srcFolderPath); IResource srcDirResource = srcDir.getResource(); if (! srcDirResource.exists()) { continue; } if (monitor.isCanceled()) { throw new OperationCanceledException(); } // Then scan all source files srcDirResource.accept(new SourceScanner(defaultModule, modelLoader, moduleManager, srcDir, srcFolderPath, typeChecker, scannedSources, phasedUnits)); } return scannedSources; } private static void addProblemAndTaskMarkers(final List<PhasedUnit> units, final IProject project) { for (PhasedUnit phasedUnit: units) { IFile file = getFile(phasedUnit); phasedUnit.getCompilationUnit().visit(new MarkerCreator(file)); addTaskMarkers(file, phasedUnit.getTokens()); } } private boolean generateBinaries(IProject project, IJavaProject javaProject, Collection<IFile> filesToCompile, TypeChecker typeChecker, IProgressMonitor monitor) throws CoreException { List<String> options = new ArrayList<String>(); List<String> js_srcdir = new ArrayList<String>(); List<String> js_repos = new ArrayList<String>(); boolean js_verbose = false; String js_outRepo = null; String srcPath = ""; for (IPath sourceFolder : getSourceFolders(javaProject)) { File sourcePathElement = toFile(project,sourceFolder .makeRelativeTo(project.getFullPath())); if (! srcPath.isEmpty()) { srcPath += File.pathSeparator; } srcPath += sourcePathElement.getAbsolutePath(); js_srcdir.add(sourcePathElement.getAbsolutePath()); } options.add("-src"); options.add(srcPath); options.add("-encoding"); options.add(project.getDefaultCharset()); for (String repository : getUserRepositories(project)) { options.add("-rep"); options.add(repository); js_repos.add(repository); } String verbose = System.getProperty("ceylon.verbose"); if (verbose!=null && "true".equals(verbose)) { options.add("-verbose"); js_verbose = true; } options.add("-g:lines,vars,source"); String systemRepo = getInterpolatedCeylonSystemRepo(project); if(systemRepo != null && !systemRepo.isEmpty()){ options.add("-sysrep"); options.add(systemRepo); } final File modulesOutputDir = getCeylonModulesOutputDirectory(project); if (modulesOutputDir!=null) { options.add("-out"); options.add(modulesOutputDir.getAbsolutePath()); js_outRepo = modulesOutputDir.getAbsolutePath(); } List<File> javaSourceFiles = new ArrayList<File>(); List<File> sourceFiles = new ArrayList<File>(); List<File> moduleFiles = new ArrayList<File>(); for (IFile file : filesToCompile) { if(isCeylon(file)) { sourceFiles.add(file.getRawLocation().toFile()); if (file.getName().equals(ModuleManager.MODULE_FILE)) { moduleFiles.add(file.getRawLocation().toFile()); } } else if(isJava(file)) javaSourceFiles.add(file.getRawLocation().toFile()); } PrintWriter printWriter = new PrintWriter(System.out);//(getConsoleErrorStream(), true); boolean success = true; //Compile JS first if (!sourceFiles.isEmpty() && compileToJs(project)) { success = compileJs(project, typeChecker, js_srcdir, js_repos, js_verbose, js_outRepo, printWriter, ! compileToJava(project)); } if ((!sourceFiles.isEmpty() || !javaSourceFiles.isEmpty()) && compileToJava(project)) { // For Java don't stop compiling when encountering errors options.add("-continue"); // always add the java files, otherwise ceylon code won't see them // and they won't end up in the archives (src/car) sourceFiles.addAll(javaSourceFiles); if (!sourceFiles.isEmpty()){ success = success & compile(project, javaProject, options, sourceFiles, typeChecker, printWriter, monitor); } } return success; } private boolean compileJs(IProject project, TypeChecker typeChecker, List<String> js_srcdir, List<String> js_repos, boolean js_verbose, String js_outRepo, PrintWriter printWriter, boolean generateSourceArchive) throws CoreException { Options jsopts = new Options() .repos(js_repos) .sources(js_srcdir) .systemRepo(getInterpolatedCeylonSystemRepo(project)) .outDir(js_outRepo) .optimize(true) .verbose(js_verbose ? "all" : null) .generateSourceArchive(generateSourceArchive) .encoding(project.getDefaultCharset()) .offline(CeylonProjectConfig.get(project).isOffline()); JsCompiler jsc = new JsCompiler(typeChecker, jsopts) { @Override protected boolean nonCeylonUnit(Unit u) { if (! super.nonCeylonUnit(u)) { return false; } if (u instanceof CeylonBinaryUnit) { CeylonBinaryUnit ceylonBinaryUnit = (CeylonBinaryUnit) u; if (ceylonBinaryUnit.getCeylonSourceRelativePath() != null) { return false; } } return true; } public String getFullPath(PhasedUnit pu) { VirtualFile virtualFile = pu.getUnitFile(); if (virtualFile instanceof ResourceVirtualFile) { return ((IFileVirtualFile) virtualFile).getFile().getLocation().toOSString(); } else { return virtualFile.getPath(); } }; }.stopOnErrors(false); try { if (!jsc.generate()) { CompileErrorReporter errorReporter = null; //Report backend errors for (Message e : jsc.getErrors()) { if (e instanceof UnexpectedError) { if (errorReporter == null) { errorReporter = new CompileErrorReporter(project); } errorReporter.report(new CeylonCompilationError(project, (UnexpectedError)e)); } } if (errorReporter != null) { //System.out.println("Ceylon-JS compiler failed for " + project.getName()); errorReporter.failed(); } return false; } else { //System.out.println("compile ok to js"); return true; } } catch (IOException ex) { ex.printStackTrace(printWriter); return false; } } @SuppressWarnings("deprecation") private boolean compile(final IProject project, IJavaProject javaProject, List<String> options, java.util.List<File> sourceFiles, final TypeChecker typeChecker, PrintWriter printWriter, IProgressMonitor mon) throws VerifyError { final SubMonitor monitor = SubMonitor.convert(mon, "Generating binaries for " + sourceFiles.size() + " source files in project " + project.getName(), sourceFiles.size()); com.redhat.ceylon.compiler.java.tools.CeyloncTool compiler; try { compiler = new com.redhat.ceylon.compiler.java.tools.CeyloncTool(); } catch (VerifyError e) { System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?"); throw e; } CompileErrorReporter errorReporter = new CompileErrorReporter(project); final com.sun.tools.javac.util.Context context = new com.sun.tools.javac.util.Context(); context.put(com.sun.tools.javac.util.Log.outKey, printWriter); context.put(DiagnosticListener.class, errorReporter); CeylonLog.preRegister(context); BuildFileManager fileManager = new BuildFileManager(context, true, null, project); computeCompilerClasspath(project, javaProject, options); Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(sourceFiles); if (reuseEclipseModelInCompilation(project)) { setupJDTModelLoader(project, typeChecker, context); } ZipFileIndexCache.getSharedInstance().clearCache(); CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(printWriter, fileManager, errorReporter, options, null, compilationUnits); task.setTaskListener(new TaskListener() { @Override public void started(TaskEvent ta) { String name = ta.getSourceFile().getName(); name = name.substring(name.lastIndexOf("/")+1); monitor.subTask("- compiling " + name); } @Override public void finished(TaskEvent ta) { monitor.worked(1); } }); boolean success=false; try { success = task.call(); } catch (Exception e) { e.printStackTrace(printWriter); } if (!success) { errorReporter.failed(); } monitor.done(); return success; } private void computeCompilerClasspath(IProject project, IJavaProject javaProject, List<String> options) { List<String> classpathElements = new ArrayList<String>(); // Modules projectModules = getProjectModules(project); // ArtifactContext ctx; // if (projectModules != null) { // Module languageModule = projectModules.getLanguageModule(); // ctx = new ArtifactContext(languageModule.getNameAsString(), // languageModule.getVersion()); // else { // ctx = new ArtifactContext(LANGUAGE_MODULE_NAME, // TypeChecker.LANGUAGE_MODULE_VERSION); // ctx.setSuffix(ArtifactContext.CAR); // RepositoryManager repositoryManager = getProjectRepositoryManager(project); // if (repositoryManager!=null) { // //try { // File languageModuleArchive = repositoryManager.getArtifact(ctx); // classpathElements.add(languageModuleArchive.getAbsolutePath()); // /*} // catch (Exception e) { // e.printStackTrace(); // }*/ addProjectClasspathElements(classpathElements, javaProject); try { for (IProject p: project.getReferencedProjects()) { if(p.isAccessible()){ addProjectClasspathElements(classpathElements, JavaCore.create(p)); } } } catch (CoreException ce) { ce.printStackTrace(); } options.add("-classpath"); // add the compiletime required jars (those used by the language module implicitely) classpathElements.addAll(CeylonPlugin.getCompiletimeRequiredJars()); String classpath = ""; for (String cpElement : classpathElements) { if (! classpath.isEmpty()) { classpath += File.pathSeparator; } classpath += cpElement; } options.add(classpath); } private void setupJDTModelLoader(final IProject project, final TypeChecker typeChecker, final com.sun.tools.javac.util.Context context) { final JDTModelLoader modelLoader = getModelLoader(typeChecker); context.put(LanguageCompiler.ceylonContextKey, typeChecker.getContext()); context.put(TypeFactory.class, modelLoader.getTypeFactory()); context.put(LanguageCompiler.compilerDelegateKey, new JdtCompilerDelegate(modelLoader, project, typeChecker, context)); context.put(TypeFactory.class, modelLoader.getTypeFactory()); context.put(ModelLoaderFactory.class, new ModelLoaderFactory() { @Override public AbstractModelLoader createModelLoader( com.sun.tools.javac.util.Context context) { return modelLoader; } }); } private void addProjectClasspathElements(List<String> classpathElements, IJavaProject javaProj) { try { List<IClasspathContainer> containers = getCeylonClasspathContainers(javaProj); for (IClasspathContainer container : containers) { for (IClasspathEntry cpEntry : container.getClasspathEntries()) { if (!isInCeylonClassesOutputFolder(cpEntry.getPath())) { classpathElements.add(cpEntry.getPath().toOSString()); } } } File outputDir = toFile(javaProj.getProject(), javaProj.getOutputLocation() .makeRelativeTo(javaProj.getProject().getFullPath())); classpathElements.add(outputDir.getAbsolutePath()); for (IClasspathEntry cpEntry : javaProj.getResolvedClasspath(true)) { if (isInCeylonClassesOutputFolder(cpEntry.getPath())) { classpathElements.add(javaProj.getProject().getLocation().append(cpEntry.getPath().lastSegment()).toOSString()); } } } catch (JavaModelException e1) { e1.printStackTrace(); } } public static boolean isExplodeModulesEnabled(IProject project) { Map<String,String> args = getBuilderArgs(project); return args.get("explodeModules")!=null || args.get("enableJdtClasses")!=null; } public static boolean compileWithJDTModel = true; public static boolean reuseEclipseModelInCompilation(IProject project) { return loadDependenciesFromModelLoaderFirst(project) && compileWithJDTModel; } // Keep it false on master until we fix the associated cross-reference and search issues // by correctly managing source to binary links and indexes public static boolean loadBinariesFirst = "true".equals(System.getProperty("ceylon.loadBinariesFirst", "true")); public static boolean loadDependenciesFromModelLoaderFirst(IProject project) { return compileToJava(project) && loadBinariesFirst; } public static boolean showWarnings(IProject project) { return getBuilderArgs(project).get("hideWarnings")==null; } public static boolean compileToJs(IProject project) { return getBuilderArgs(project).get("compileJs")!=null; } public static boolean compileToJava(IProject project) { return CeylonNature.isEnabled(project) && getBuilderArgs(project).get("compileJava")==null; } public static String fileName(ClassMirror c) { if (c instanceof JavacClass) { return ((JavacClass) c).classSymbol.classfile.getName(); } else if (c instanceof JDTClass) { return ((JDTClass) c).getFileName(); } else if (c instanceof SourceClass) { return ((SourceClass) c).getModelDeclaration().getUnit().getFilename(); } else { return "another file"; } } public static List<String> getUserRepositories(IProject project) throws CoreException { List<String> userRepos = getCeylonRepositories(project); userRepos.addAll(getReferencedProjectsOutputRepositories(project)); return userRepos; } public static List<String> getAllRepositories(IProject project) throws CoreException { List<String> allRepos = getUserRepositories(project); allRepos.add(CeylonProjectConfig.get(project).getMergedRepositories().getCacheRepository().getUrl()); return allRepos; } public static List<String> getReferencedProjectsOutputRepositories(IProject project) throws CoreException { List<String> repos = new ArrayList<String>(); if (project != null) { for (IProject referencedProject: project.getReferencedProjects()) { if (referencedProject.isOpen() && referencedProject.hasNature(NATURE_ID)) { repos.add(getCeylonModulesOutputDirectory(referencedProject).getAbsolutePath()); } } } return repos; } private static Map<String,String> getBuilderArgs(IProject project) { if (project!=null) { try { for (ICommand c: project.getDescription().getBuildSpec()) { if (c.getBuilderName().equals(BUILDER_ID)) { return c.getArguments(); } } } catch (CoreException e) { e.printStackTrace(); } } return Collections.emptyMap(); } public static List<String> getCeylonRepositories(IProject project) { CeylonProjectConfig projectConfig = CeylonProjectConfig.get(project); List<String> projectLookupRepos = projectConfig.getProjectLocalRepos(); List<String> globalLookupRepos = projectConfig.getGlobalLookupRepos(); List<String> projectRemoteRepos = projectConfig.getProjectRemoteRepos(); List<String> otherRemoteRepos = projectConfig.getOtherRemoteRepos(); List<String> repos = new ArrayList<String>(); repos.addAll(projectLookupRepos); repos.addAll(globalLookupRepos); repos.addAll(projectRemoteRepos); repos.addAll(otherRemoteRepos); return repos; } private static File toFile(IProject project, IPath path) { return project.getFolder(path).getRawLocation().toFile(); } private static void clearMarkersOn(IResource resource, boolean alsoDeleteBackendErrors) { try { resource.deleteMarkers(TASK_MARKER_ID, false, DEPTH_INFINITE); resource.deleteMarkers(PROBLEM_MARKER_ID, true, DEPTH_INFINITE); if (alsoDeleteBackendErrors) { resource.deleteMarkers(PROBLEM_MARKER_ID + ".backend", true, DEPTH_INFINITE); } //these are actually errors from the Ceylon compiler, but //we did not bother creating a separate annotation type! resource.deleteMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, true, DEPTH_INFINITE); } catch (CoreException e) { e.printStackTrace(); } } private static void clearProjectMarkers(IProject project) { try { //project.deleteMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, true, DEPTH_ZERO); project.deleteMarkers(PROBLEM_MARKER_ID, true, DEPTH_ZERO); project.deleteMarkers(PROBLEM_MARKER_ID + ".backend", true, DEPTH_ZERO); } catch (CoreException e) { e.printStackTrace(); } } private static void clearMarkersOn(Collection<IFile> files, boolean alsoDeleteBackendErrors) { for(IFile file: files) { clearMarkersOn(file, alsoDeleteBackendErrors); } } /*private void dumpSourceList(Collection<IFile> sourcesToCompile) { MessageConsoleStream consoleStream= getConsoleStream(); for(Iterator<IFile> iter= sourcesToCompile.iterator(); iter.hasNext(); ) { IFile srcFile= iter.next(); consoleStream.println(" " + srcFile.getFullPath()); } }*/ // protected static MessageConsoleStream getConsoleStream() { // return findConsole().newMessageStream(); // protected static MessageConsoleStream getConsoleErrorStream() { // final MessageConsoleStream stream = findConsole().newMessageStream(); // //TODO: all this, just to get the color red? can that be right?? // /*try { // getWorkbench().getProgressService().runInUI(getWorkbench().getWorkbenchWindows()[0], // new IRunnableWithProgress() { // // @Override // public void run(IProgressMonitor monitor) throws InvocationTargetException, // InterruptedException { // stream.setColor(getWorkbench().getDisplay().getSystemColor(SWT.COLOR_RED)); // } // }, null); // } // catch (Exception e) { // e.printStackTrace(); // }*/ // return stream; // private String timedMessage(String message) { // long elapsedTimeMs = (System.nanoTime() - startTime) / 1000000; // return String.format("[%1$10d] %2$s", elapsedTimeMs, message); // /** // * Find or create the console with the given name // * @param consoleName // */ // protected static MessageConsole findConsole() { // String consoleName = CEYLON_CONSOLE; // MessageConsole myConsole= null; // final IConsoleManager consoleManager= ConsolePlugin.getDefault().getConsoleManager(); // IConsole[] consoles= consoleManager.getConsoles(); // for(int i= 0; i < consoles.length; i++) { // IConsole console= consoles[i]; // if (console.getName().equals(consoleName)) // myConsole= (MessageConsole) console; // if (myConsole == null) { // myConsole= new MessageConsole(consoleName, // CeylonPlugin.getInstance().getImageRegistry() // .getDescriptor(CeylonResources.BUILDER)); // consoleManager.addConsoles(new IConsole[] { myConsole }); //// consoleManager.showConsoleView(myConsole); // return myConsole; private static void addTaskMarkers(IFile file, List<CommonToken> tokens) { // clearTaskMarkersOn(file); for (CommonToken token : tokens) { if (token.getType() == CeylonLexer.LINE_COMMENT || token.getType() == CeylonLexer.MULTI_COMMENT) { CeylonTaskUtil.addTaskMarkers(token, file); } } } @Override protected void clean(IProgressMonitor monitor) throws CoreException { super.clean(monitor); IProject project = getProject(); // startTime = System.nanoTime(); // getConsoleStream().println(timedMessage("Starting Ceylon clean on project: " + project.getName())); cleanupModules(monitor, project); cleanupJdtClasses(monitor, project); monitor.subTask("Clearing project and source markers for project " + project.getName()); clearProjectMarkers(project); clearMarkersOn(project, true); // getConsoleStream().println(timedMessage("End Ceylon clean on project: " + project.getName())); } private void cleanupJdtClasses(IProgressMonitor monitor, IProject project) { if (isExplodeModulesEnabled(project)) { monitor.subTask("Cleaning exploded modules directory of project " + project.getName()); final File ceylonOutputDirectory = getCeylonClassesOutputDirectory(project); new RepositoryLister(Arrays.asList(".*")).list(ceylonOutputDirectory, new RepositoryLister.Actions() { @Override public void doWithFile(File path) { path.delete(); } public void exitDirectory(File path) { if (path.list().length == 0 && !path.equals(ceylonOutputDirectory)) { path.delete(); } } }); } } private void cleanupModules(IProgressMonitor monitor, IProject project) { final File modulesOutputDirectory = getCeylonModulesOutputDirectory(project); if (modulesOutputDirectory != null) { monitor.subTask("Cleaning existing artifacts of project " + project.getName()); List<String> extensionsToDelete = Arrays.asList(".jar", ".car", ".src", ".sha1"); new RepositoryLister(extensionsToDelete).list(modulesOutputDirectory, new RepositoryLister.Actions() { @Override public void doWithFile(File path) { path.delete(); } public void exitDirectory(File path) { if (path.list().length == 0 && !path.equals(modulesOutputDirectory)) { path.delete(); } } }); } } public static IFile getFile(PhasedUnit phasedUnit) { return ((IFileVirtualFile) phasedUnit.getUnitFile()).getFile(); } // TODO think: doRefresh(file.getParent()); // N.B.: Assumes all // generated files go into parent folder private static List<IFile> getProjectSources(IProject project) { return projectSources.get(project); } public static TypeChecker getProjectTypeChecker(IProject project) { return typeCheckers.get(project); } public static Modules getProjectModules(IProject project) { TypeChecker typeChecker = getProjectTypeChecker(project); if (typeChecker == null) { return null; } return typeChecker.getContext().getModules(); } public static List<Module> getModulesInProject(IProject project) { List<Module> moduleList = new ArrayList<Module>(); Modules modules = getProjectModules(project); if (modules != null) { IJavaProject javaProject = JavaCore.create(project); for (Module module : modules.getListOfModules()) { if (!module.isDefault() && !module.isJava()) { try { for (IPackageFragment pkg : javaProject.getPackageFragments()) { if (pkg.getKind()==IPackageFragmentRoot.K_SOURCE) { if (!pkg.isReadOnly() && pkg.getElementName().equals(module.getNameAsString())) { moduleList.add(module); } } } } catch (JavaModelException e) { e.printStackTrace(); } } } } return moduleList; } public static RepositoryManager getProjectRepositoryManager(IProject project) { RepositoryManager repoManager = projectRepositoryManagers.get(project); if (repoManager == null) { try { repoManager = resetProjectRepositoryManager(project); } catch(CoreException e) { e.printStackTrace(); } } return repoManager; } public static RepositoryManager resetProjectRepositoryManager(IProject project) throws CoreException { RepositoryManager repositoryManager = repoManager() .offline(CeylonProjectConfig.get(project).isOffline()) .cwd(project.getLocation().toFile()) .systemRepo(getInterpolatedCeylonSystemRepo(project)) .extraUserRepos(getReferencedProjectsOutputRepositories(project)) .logger(new EclipseLogger()) .isJDKIncluded(true) .buildManager(); projectRepositoryManagers.put(project, repositoryManager); return repositoryManager; } public static Iterable<IProject> getProjects() { return typeCheckers.keySet(); } public static Iterable<TypeChecker> getTypeCheckers() { return typeCheckers.values(); } public static void removeProject(IProject project) { typeCheckers.remove(project); projectSources.remove(project); modelStates.remove(project); containersInitialized.remove(project); projectRepositoryManagers.remove(project); CeylonProjectConfig.remove(project); JavaProjectStateMirror.cleanup(project); projectModuleDependencies.remove(project); } public static List<IPath> getSourceFolders(IProject project) { //TODO: is the call to JavaCore.create() very expensive?? return getSourceFolders(JavaCore.create(project)); } /** * Read the IJavaProject classpath configuration and populate the ISourceProject's * build path accordingly. */ public static List<IPath> getSourceFolders(IJavaProject javaProject) { if (javaProject.exists()) { try { List<IPath> projectSourceFolders = new ArrayList<IPath>(); for (IClasspathEntry entry: javaProject.getRawClasspath()) { IPath path = entry.getPath(); if (isCeylonSourceEntry(entry)) { projectSourceFolders.add(path); } } return projectSourceFolders; } catch (JavaModelException e) { e.printStackTrace(); } } return Collections.emptyList(); } public static boolean isCeylonSourceEntry(IClasspathEntry entry) { if (entry.getEntryKind()!=IClasspathEntry.CPE_SOURCE) { return false; } /*for (IClasspathAttribute attribute: entry.getExtraAttributes()) { if (attribute.getName().equals("ceylonSource")) { return true; } }*/ for (IPath exclusionPattern : entry.getExclusionPatterns()) { if (exclusionPattern.toString().endsWith(".ceylon")) { return false; } } return true; } private IPath retrieveSourceFolder(IFile file, IProject project) { IPath path = file.getProjectRelativePath(); if (path == null) return null; if (! isCeylonOrJava(file)) return null; return retrieveSourceFolder(path, project); } // path is project-relative private static IPath retrieveSourceFolder(IPath path, IProject project) { if (project != null) { Collection<IPath> sourceFolders = getSourceFolders(project); for (IPath sourceFolderAbsolute : sourceFolders) { IPath sourceFolder = sourceFolderAbsolute.makeRelativeTo(project.getFullPath()); if (sourceFolder.isPrefixOf(path)) { return sourceFolder; } } } return null; } static Package retrievePackage(IResource folder) { IProject project = folder.getProject(); if (project.isOpen()) { String packageName = getPackageName(folder); if (packageName != null) { TypeChecker typeChecker = typeCheckers.get(project); Context context = typeChecker.getContext(); Modules modules = context.getModules(); for (Module module : modules.getListOfModules()) { for (Package p : module.getPackages()) { if (p.getQualifiedNameString().equals(packageName)) { return p; } } } } } return null; } public static String getPackageName(IResource resource) { IProject project = resource.getProject(); IContainer folder = null; if (resource instanceof IFile) { folder = resource.getParent(); } else { folder = (IContainer) resource; } String packageName = null; IPath folderPath = folder.getProjectRelativePath(); IPath sourceFolder = retrieveSourceFolder(folderPath, project); if (sourceFolder != null) { IPath relativeFolderPath = folderPath.makeRelativeTo(sourceFolder); packageName = relativeFolderPath.toString().replace('/', '.'); } return packageName; } private Package createNewPackage(IContainer folder) { IPath folderPath = folder.getProjectRelativePath(); IPath sourceFolder = retrieveSourceFolder(folderPath, getProject()); if (sourceFolder == null) { return null; } IContainer parent = folder.getParent(); IPath packageRelativePath = folder.getProjectRelativePath().makeRelativeTo(parent.getProjectRelativePath()); Package parentPackage = null; while (parentPackage == null && ! parent.equals(folder.getProject())) { packageRelativePath = folder.getProjectRelativePath().makeRelativeTo(parent.getProjectRelativePath()); parentPackage = retrievePackage(parent); parent = parent.getParent(); } Context context = typeCheckers.get(folder.getProject()).getContext(); return createPackage(parentPackage, packageRelativePath, context.getModules()); } private Package createPackage(Package parentPackage, IPath packageRelativePath, Modules modules) { String[] packageSegments = packageRelativePath.segments(); if (packageSegments.length == 1) { Package pkg = new LazyPackage(getProjectModelLoader(getProject())); List<String> parentName = null; if (parentPackage == null) { parentName = Collections.emptyList(); } else { parentName = parentPackage.getName(); } final ArrayList<String> name = new ArrayList<String>(parentName.size() + 1); name.addAll(parentName); name.add(packageRelativePath.segment(0)); pkg.setName(name); Module module = null; if (parentPackage != null) { module = parentPackage.getModule(); } if (module == null) { module = modules.getDefaultModule(); } module.getPackages().add(pkg); pkg.setModule(module); return pkg; } else { Package childPackage = createPackage(parentPackage, packageRelativePath.uptoSegment(1), modules); return createPackage(childPackage, packageRelativePath.removeFirstSegments(1), modules); } } private void removeObsoleteClassFiles(List<IFile> filesToRemove, IProject project) { if (filesToRemove.size() == 0) { return; } Set<File> moduleJars = new HashSet<File>(); for (IFile file : filesToRemove) { IPath filePath = file.getProjectRelativePath(); IPath sourceFolder = retrieveSourceFolder(filePath, project); if (sourceFolder == null) { return; } Package pkg = retrievePackage(file.getParent()); if (pkg == null) { return; } Module module = pkg.getModule(); TypeChecker typeChecker = typeCheckers.get(project); if (typeChecker == null) { return; } final File modulesOutputDirectory = getCeylonModulesOutputDirectory(project); boolean explodeModules = isExplodeModulesEnabled(project); final File ceylonOutputDirectory = explodeModules ? getCeylonClassesOutputDirectory(project) : null; File moduleDir = getModulePath(modulesOutputDirectory, module); //Remove the classes belonging to the source file from the //module archive and from the JDTClasses directory File moduleJar = new File(moduleDir, getModuleArchiveName(module)); if(moduleJar.exists()){ moduleJars.add(moduleJar); String relativeFilePath = filePath.makeRelativeTo(sourceFolder).toString(); try { List<String> entriesToDelete = new ArrayList<String>(); ZipFile zipFile = new ZipFile(moduleJar); Properties mapping = CarUtils.retrieveMappingFile(zipFile); for (String className : mapping.stringPropertyNames()) { String sourceFile = mapping.getProperty(className); if (relativeFilePath.equals(sourceFile)) { entriesToDelete.add(className); } } for (String entryToDelete : entriesToDelete) { zipFile.removeFile(entryToDelete); if (explodeModules) { new File(ceylonOutputDirectory, entryToDelete.replace('/', File.separatorChar)) .delete(); } } } catch (ZipException e) { e.printStackTrace(); } } //Remove the source file from the source archive File moduleSrc = new File(moduleDir, getSourceArchiveName(module)); if(moduleSrc.exists()){ moduleJars.add(moduleSrc); String relativeFilePath = filePath.makeRelativeTo(sourceFolder).toString(); try { new ZipFile(moduleSrc).removeFile(relativeFilePath); } catch (ZipException e) { e.printStackTrace(); } } } // final com.sun.tools.javac.util.Context dummyContext = new com.sun.tools.javac.util.Context(); class ConsoleLog implements Logger { PrintWriter writer; ConsoleLog() { writer = new PrintWriter(System.out); //new PrintWriter(getConsoleStream())); } @Override public void error(String str) { writer.append("Error: " + str + "\n"); } @Override public void warning(String str) { writer.append("Warning: " + str + "\n"); } @Override public void info(String str) { } @Override public void debug(String str) { } } ConsoleLog log = new ConsoleLog(); for (File moduleJar: moduleJars) { ShaSigner.sign(moduleJar, log, false); } } private static File getCeylonClassesOutputDirectory(IProject project) { return getCeylonClassesOutputFolder(project) .getRawLocation().toFile(); } public static IFolder getCeylonClassesOutputFolder(IProject project) { return project.getFolder(CEYLON_CLASSES_FOLDER_NAME); } public static boolean isInCeylonClassesOutputFolder(IPath path) { //TODO: this is crap! return path.lastSegment().equals(CEYLON_CLASSES_FOLDER_NAME); } public static File getCeylonModulesOutputDirectory(IProject project) { return getCeylonModulesOutputFolder(project).getRawLocation().toFile(); } public static IFolder getCeylonModulesOutputFolder(IProject project) { IPath path = CeylonProjectConfig.get(project).getOutputRepoPath(); return project.getFolder(path.removeFirstSegments(1)); } public static String getCeylonSystemRepo(IProject project) { String systemRepo = (String) getBuilderArgs(project).get("systemRepo"); if (systemRepo == null) { systemRepo = "${ceylon.repo}"; } return systemRepo; } public static String getInterpolatedCeylonSystemRepo(IProject project) { return interpolateVariablesInRepositoryPath(getCeylonSystemRepo(project)); } public static String[] getDefaultUserRepositories() { return new String[]{ "${ceylon.repo}", "${user.home}/.ceylon/repo", Constants.REPO_URL_CEYLON }; } public static String interpolateVariablesInRepositoryPath(String repoPath) { String userHomePath = System.getProperty("user.home"); String pluginRepoPath = CeylonPlugin.getInstance().getCeylonRepository().getAbsolutePath(); return repoPath.replace("${user.home}", userHomePath). replace("${ceylon.repo}", pluginRepoPath); } /** * String representation for debugging purposes */ public String toString() { return this.getProject() == null ? "CeylonBuilder for unknown project" : "CeylonBuilder for " + getProject().getName(); } public static void setContainerInitialized(IProject project) { containersInitialized.add(project); } public static boolean isContainerInitialized(IProject project) { return containersInitialized.contains(project); } public static boolean allClasspathContainersInitialized() { for (IProject project : ResourcesPlugin.getWorkspace().getRoot().getProjects()) { if (project.isAccessible() && CeylonNature.isEnabled(project) && ! containersInitialized.contains(project)) { return false; } } return true; } public static ModuleDependencies getModuleDependenciesForProject( IProject project) { return projectModuleDependencies.get(project); } }
package org.jetbrains.plugins.groovy.lang.completion; import com.intellij.codeInsight.completion.*; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.patterns.ElementPattern; import com.intellij.patterns.PlatformPatterns; import com.intellij.patterns.StandardPatterns; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiRecursiveElementWalkingVisitor; import com.intellij.util.ProcessingContext; import com.intellij.util.containers.ContainerUtil; import icons.JetgroovyIcons; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.extensions.GroovyNamedArgumentProvider; import org.jetbrains.plugins.groovy.extensions.NamedArgumentDescriptor; import org.jetbrains.plugins.groovy.extensions.NamedArgumentUtilKt; import org.jetbrains.plugins.groovy.highlighter.GroovySyntaxHighlighter; import org.jetbrains.plugins.groovy.lang.completion.handlers.NamedArgumentInsertHandler; import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression; import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyNamesUtil; import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil; import java.awt.*; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * @author peter */ class MapArgumentCompletionProvider extends CompletionProvider<CompletionParameters> { // @formatter:off // [<caret>] // [<some values, initializers or named arguments>, <caret>] // foo <caret> // foo (<caret>) public static final ElementPattern<PsiElement> IN_ARGUMENT_LIST_OF_CALL = PlatformPatterns .psiElement().withParent(PlatformPatterns.psiElement(GrReferenceExpression.class).withParent( StandardPatterns.or(PlatformPatterns.psiElement(GrArgumentList.class), PlatformPatterns.psiElement(GrListOrMap.class))) ); // [<caret> : ] // [<some values>, <caret> : ] public static final ElementPattern<PsiElement> IN_LABEL = PlatformPatterns.psiElement(GroovyTokenTypes.mIDENT).withParent(GrArgumentLabel.class); // @formatter:on private MapArgumentCompletionProvider() { } public static void register(CompletionContributor contributor) { MapArgumentCompletionProvider instance = new MapArgumentCompletionProvider(); contributor.extend(CompletionType.BASIC, IN_ARGUMENT_LIST_OF_CALL, instance); contributor.extend(CompletionType.BASIC, IN_LABEL, instance); } @Override protected void addCompletions(@NotNull CompletionParameters parameters, @NotNull ProcessingContext context, @NotNull CompletionResultSet result) { PsiElement mapOrArgumentList = findMapOrArgumentList(parameters); if (mapOrArgumentList == null) { return; } if (isMapKeyCompletion(parameters)) { result.stopHere(); } final Map<String, NamedArgumentDescriptor> map = ContainerUtil.newHashMap(calculateNamedArguments(mapOrArgumentList)); for (GrNamedArgument argument : getSiblingNamedArguments(mapOrArgumentList)) { map.remove(argument.getLabelName()); } for (Map.Entry<String, NamedArgumentDescriptor> entry : map.entrySet()) { LookupElementBuilder lookup = LookupElementBuilder.create(entry.getValue(), entry.getKey()) .withInsertHandler(NamedArgumentInsertHandler.INSTANCE) .withTailText(":"); if (entry.getValue().getPriority() == NamedArgumentDescriptor.Priority.UNLIKELY) { TextAttributes defaultAttributes = GroovySyntaxHighlighter.MAP_KEY.getDefaultAttributes(); if (defaultAttributes != null) { Color fg = defaultAttributes.getForegroundColor(); if (fg != null) { lookup = lookup.withItemTextForeground(fg); } } } else { lookup = lookup.withIcon(JetgroovyIcons.Groovy.DynamicProperty); } LookupElement customized = entry.getValue().customizeLookupElement(lookup); result.addElement(customized == null ? lookup : customized); } } public static boolean isMapKeyCompletion(CompletionParameters parameters) { PsiElement mapOrArgumentList = findMapOrArgumentList(parameters); return mapOrArgumentList instanceof GrListOrMap && ((GrListOrMap)mapOrArgumentList).getNamedArguments().length > 0; } @Nullable private static PsiElement findMapOrArgumentList(CompletionParameters parameters) { PsiElement parent = parameters.getPosition().getParent(); if (parent instanceof GrReferenceExpression) { if (((GrReferenceExpression)parent).getQualifier() != null) return null; return parent.getParent(); } if (parent == null || parent.getParent() == null) { return null; } return parent.getParent().getParent(); } @NotNull private static Map<String, NamedArgumentDescriptor> findOtherNamedArgumentsInFile(PsiElement mapOrArgumentList) { final Map<String, NamedArgumentDescriptor> map = new HashMap<>(); mapOrArgumentList.getContainingFile().accept(new PsiRecursiveElementWalkingVisitor() { @Override public void visitElement(PsiElement element) { if (element instanceof GrArgumentLabel) { final String name = ((GrArgumentLabel)element).getName(); if (GroovyNamesUtil.isIdentifier(name)) { map.put(name, NamedArgumentDescriptor.SIMPLE_UNLIKELY); } } super.visitElement(element); } }); return map; } private static GrNamedArgument[] getSiblingNamedArguments(PsiElement mapOrArgumentList) { if (mapOrArgumentList instanceof GrListOrMap) { return ((GrListOrMap)mapOrArgumentList).getNamedArguments(); } PsiElement argumentList = mapOrArgumentList instanceof GrArgumentList ? mapOrArgumentList : mapOrArgumentList.getParent(); if (argumentList instanceof GrArgumentList) { if (argumentList.getParent() instanceof GrCall) { return PsiUtil.getFirstMapNamedArguments((GrCall)argumentList.getParent()); } } return GrNamedArgument.EMPTY_ARRAY; } @NotNull private static Map<String, NamedArgumentDescriptor> calculateNamedArguments(@NotNull PsiElement mapOrArgumentList) { Map<String, NamedArgumentDescriptor> map = calcNamedArgumentsForCall(mapOrArgumentList); if ((map == null || map.isEmpty()) && mapOrArgumentList instanceof GrListOrMap) { map = NamedArgumentUtilKt.getDescriptors((GrListOrMap)mapOrArgumentList); } if (map == null || map.isEmpty()) { map = findOtherNamedArgumentsInFile(mapOrArgumentList); } return map; } @Nullable private static Map<String, NamedArgumentDescriptor> calcNamedArgumentsForCall(@NotNull PsiElement mapOrArgumentList) { PsiElement argumentList = mapOrArgumentList instanceof GrArgumentList ? mapOrArgumentList : mapOrArgumentList.getParent(); if (argumentList instanceof GrArgumentList) { if (mapOrArgumentList instanceof GrListOrMap) { if (((GrArgumentList)argumentList).getNamedArguments().length > 0 || ((GrArgumentList)argumentList).getExpressionArgumentIndex((GrListOrMap)mapOrArgumentList) > 0) { return Collections.emptyMap(); } } if (argumentList.getParent() instanceof GrCall) { return GroovyNamedArgumentProvider.getNamedArgumentsFromAllProviders((GrCall)argumentList.getParent(), null, true); } } return Collections.emptyMap(); } }
package net.sf.taverna.t2.provenance.lineageservice; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import net.sf.taverna.t2.provenance.lineageservice.utils.Arc; import net.sf.taverna.t2.provenance.lineageservice.utils.DDRecord; import net.sf.taverna.t2.provenance.lineageservice.utils.NestedListNode; import net.sf.taverna.t2.provenance.lineageservice.utils.ProcBinding; import net.sf.taverna.t2.provenance.lineageservice.utils.ProvenanceProcessor; import net.sf.taverna.t2.provenance.lineageservice.utils.Var; import net.sf.taverna.t2.provenance.lineageservice.utils.VarBinding; import org.apache.log4j.Logger; import org.jdom.Document; import org.jdom.Element; /** * Handles all the querying of provenance items in the database layer. Uses * standard SQL so all specific instances of this class can extend this writer * to handle all of the db queries * * @author Paolo Missier * @author Ian Dunlop * */ public abstract class ProvenanceQuery { protected Logger logger = Logger.getLogger(ProvenanceQuery.class); protected Connection connection; private String dbURL; public static String DATAFLOW_TYPE = "net.sf.taverna.t2.activities.dataflow.DataflowActivity"; public Connection getConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException { if (connection == null) { openConnection(); } return connection; } protected abstract void openConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException; /** * implements a set of query constraints of the form var = value into a * WHERE clause * * @param q0 * @param queryConstraints * @return */ protected String addWhereClauseToQuery(String q0, Map<String, String> queryConstraints, boolean terminate) { // complete query according to constraints StringBuffer q = new StringBuffer(q0); boolean first = true; if (queryConstraints != null && queryConstraints.size() > 0) { q.append(" where "); for (Entry<String, String> entry : queryConstraints.entrySet()) { if (!first) { q.append(" and "); } q.append(" " + entry.getKey() + " = \'" + entry.getValue() + "\' "); first = false; } } return q.toString(); } protected String addOrderByToQuery(String q0, List<String> orderAttr, boolean terminate) { // complete query according to constraints StringBuffer q = new StringBuffer(q0); boolean first = true; if (orderAttr != null && orderAttr.size() > 0) { q.append(" ORDER BY "); int i = 1; for (String attr : orderAttr) { q.append(attr); if (i++ < orderAttr.size()) q.append(","); } } return q.toString(); } /** * select Var records that satisfy constraints */ public List<Var> getVars(Map<String, String> queryConstraints) throws SQLException { List<Var> result = new ArrayList<Var>(); String q0 = "SELECT * FROM Var V JOIN WfInstance W ON W.wfnameRef = V.wfInstanceRef"; String q = addWhereClauseToQuery(q0, queryConstraints, true); List<String> orderAttr = new ArrayList<String>(); orderAttr.add("V.order"); String q1 = addOrderByToQuery(q, orderAttr, true); // logger.debug("getVars query = "+q1); Statement stmt; try { stmt = getConnection().createStatement(); boolean success = stmt.execute(q1.toString()); if (success) { ResultSet rs = stmt.getResultSet(); while (rs.next()) { Var aVar = new Var(); aVar.setWfInstanceRef(rs.getString("WfInstanceRef")); if (rs.getInt("inputOrOutput") == 1) { aVar.setInput(true); } else { aVar.setInput(false); } aVar.setPName(rs.getString("pnameRef")); aVar.setVName(rs.getString("varName")); aVar.setType(rs.getString("type")); aVar.setTypeNestingLevel(rs.getInt("nestingLevel")); aVar.setActualNestingLevel(rs.getInt("actualNestingLevel")); aVar.setANLset((rs.getInt("anlSet") == 1 ? true : false)); result.add(aVar); } } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } // System.out.println("getVars: executing query\n"+q.toString()); return result; } private List<Var> getVarsNoInstance(Map<String, String> queryConstraints) throws SQLException { List<Var> result = new ArrayList<Var>(); String q0 = "SELECT * FROM Var V"; String q = addWhereClauseToQuery(q0, queryConstraints, true); Statement stmt; try { stmt = getConnection().createStatement(); boolean success = stmt.execute(q.toString()); if (success) { ResultSet rs = stmt.getResultSet(); while (rs.next()) { Var aVar = new Var(); aVar.setWfInstanceRef(rs.getString("WfInstanceRef")); if (rs.getInt("inputOrOutput") == 1) { aVar.setInput(true); } else { aVar.setInput(false); } aVar.setPName(rs.getString("pnameRef")); aVar.setVName(rs.getString("varName")); aVar.setType(rs.getString("type")); aVar.setTypeNestingLevel(rs.getInt("nestingLevel")); aVar.setActualNestingLevel(rs.getInt("actualNestingLevel")); aVar.setANLset((rs.getInt("anlSet") == 1 ? true : false)); result.add(aVar); } } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } // System.out.println("getVars: executing query\n"+q.toString()); return result; } public List<String> getVarValues(String wfInstance, String pname, String vname) throws SQLException { List<String> result = new ArrayList<String>(); String q0 = "SELECT value FROM VarBinding VB"; Map<String, String> queryConstraints = new HashMap<String, String>(); queryConstraints.put("wfInstanceRef", wfInstance); queryConstraints.put("PNameRef", pname); queryConstraints.put("varNameRef", vname); String q = addWhereClauseToQuery(q0, queryConstraints, true); Statement stmt; try { stmt = getConnection().createStatement(); boolean success = stmt.execute(q.toString()); if (success) { ResultSet rs = stmt.getResultSet(); while (rs.next()) { result.add(rs.getString("value")); } } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } // System.out.println("getVars: executing query\n"+q.toString()); return result; } /** * return the input variables for a given processor and a wfInstanceId * * @param pname * @param wfInstanceId * @return list of input variables * @throws SQLException */ public List<Var> getInputVars(String pname, String wfID, String wfInstanceID) throws SQLException { // get (var, proc) from Var to see if it's input/output Map<String, String> varQueryConstraints = new HashMap<String, String>(); varQueryConstraints.put("V.wfInstanceRef", wfID); varQueryConstraints.put("V.pnameRef", pname); varQueryConstraints.put("V.inputOrOutput", "1"); if (wfInstanceID != null) { varQueryConstraints.put("W.instanceID", wfInstanceID); return getVars(varQueryConstraints); } else { return getVarsNoInstance(varQueryConstraints); } } /** * return the output variables for a given processor and a wfInstanceId * * @param pname * @param wfInstanceId * @return list of output variables * @throws SQLException */ public List<Var> getOutputVars(String pname, String wfID, String wfInstanceID) throws SQLException { // get (var, proc) from Var to see if it's input/output Map<String, String> varQueryConstraints = new HashMap<String, String>(); varQueryConstraints.put("V.wfInstanceRef", wfID); varQueryConstraints.put("V.pnameRef", pname); varQueryConstraints.put("V.inputOrOutput", "0"); if (wfInstanceID != null) varQueryConstraints.put("W.instanceID", wfInstanceID); return getVars(varQueryConstraints); } /** * selects all Arcs * * @param queryConstraints * @return * @throws SQLException */ public List<Arc> getArcs(Map<String, String> queryConstraints) throws SQLException { List<Arc> result = new ArrayList<Arc>(); String q0 = "SELECT * FROM Arc A JOIN WfInstance W ON W.wfnameRef = A.wfInstanceRef"; String q = addWhereClauseToQuery(q0, queryConstraints, true); Statement stmt; try { stmt = getConnection().createStatement(); boolean success = stmt.execute(q.toString()); if (success) { ResultSet rs = stmt.getResultSet(); while (rs.next()) { Arc aArc = new Arc(); aArc.setWfInstanceRef(rs.getString("WfInstanceRef")); aArc.setSourcePnameRef(rs.getString("sourcePNameRef")); aArc.setSourceVarNameRef(rs.getString("sourceVarNameRef")); aArc.setSinkPnameRef(rs.getString("sinkPNameRef")); aArc.setSinkVarNameRef(rs.getString("sinkVarNameRef")); result.add(aArc); } } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } // System.out.println("getArcs: executing query\n"+q.toString()); return result; } /** * get the name of the dataflow for an input run ID<br> * this should actually return a list, because one instanceID may encompass all nested workflows for a run * @param wfInstanceID * @return * @throws SQLException */ public String getWfNameRef(String wfInstanceID) throws SQLException { String q = "SELECT wfnameRef FROM WfInstance where instanceID = ?"; PreparedStatement stmt = null; try { stmt = getConnection().prepareStatement(q); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } stmt.setString(1, wfInstanceID); boolean success = stmt.execute(); if (success) { ResultSet rs = stmt.getResultSet(); if (rs.next()) { return rs.getString("wfnameRef"); } } return null; } /** * * @param dataflowID * @return * @throws SQLException */ public List<String> getWFInstanceID(String dataflowID) throws SQLException { // String q = "SELECT instanceID FROM WfInstance where wfnameRef = \'" // + dataflowID + "\'"; PreparedStatement ps = null; // Statement stmt; List<String> result = new ArrayList<String>(); try { ps = getConnection().prepareStatement( "SELECT instanceID FROM WfInstance where wfnameRef = ? order by timestamp desc"); ps.setString(1, dataflowID); // stmt = getConnection().createStatement(); boolean success = ps.execute(); if (success) { ResultSet rs = ps.getResultSet(); while (rs.next()) { result.add(rs.getString("instanceID")); } } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } return result; } /** * all WF instances, in reverse chronological order * * @return * @throws SQLException */ public List<String> getWFInstanceIDs() throws SQLException { List<String> result = new ArrayList<String>(); String q = "SELECT instanceID FROM WfInstance order by timestamp desc"; Statement stmt; try { stmt = getConnection().createStatement(); boolean success = stmt.execute(q); if (success) { ResultSet rs = stmt.getResultSet(); while (rs.next()) { result.add(rs.getString("instanceID")); } } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } return result; } /* * gets all available run instances, most recent first * @return a list of pairs <wfanme, wfinstance> * @see net.sf.taverna.t2.provenance.lineageservice.mysql.ProvenanceQuery# * getWFInstanceIDs() */ public List<String> getWFNamesByTime() throws SQLException { List<String> result = new ArrayList<String>(); String q = "SELECT instanceID, wfnameRef FROM WfInstance order by timestamp desc"; Statement stmt; try { stmt = getConnection().createStatement(); boolean success = stmt.execute(q); if (success) { ResultSet rs = stmt.getResultSet(); while (rs.next()) { result.add(rs.getString("wfnameRef")); } } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } return result; } /** * all ProCBinding records that satisfy the input constraints * * @param constraints * @return * @throws SQLException */ public List<ProcBinding> getProcBindings(Map<String, String> constraints) throws SQLException { List<ProcBinding> result = new ArrayList<ProcBinding>(); String q = "SELECT * FROM ProcBinding PB "; q = addWhereClauseToQuery(q, constraints, true); Statement stmt; try { stmt = getConnection().createStatement(); // System.out.println("getProcBindings: executing: " + q); boolean success = stmt.execute(q); // System.out.println("result: "+success); if (success) { ResultSet rs = stmt.getResultSet(); while (rs.next()) { ProcBinding pb = new ProcBinding(); pb.setActName(rs.getString("actName")); pb.setExecIDRef(rs.getString("execIDRef")); pb.setIterationVector(rs.getString("iteration")); pb.setPNameRef(rs.getString("pnameRef")); result.add(pb); } } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } return result; } /** * TODO this currently returns the data value as a string, which is * incorrect as it is an untyped byte array * * @param constraints * a Map columnName -> value that defines the query constraints. * Note: columnName must be fully qualified. This is not done * well at the moment, i.e., PNameRef should be * VarBinding.PNameRef to avoid ambiguities * @return * @throws SQLException */ public List<VarBinding> getVarBindings(Map<String, String> constraints) throws SQLException { List<VarBinding> result = new ArrayList<VarBinding>(); // String q = "SELECT * FROM VarBinding VB join Var V " // + "on (VB.varNameRef = V.varName and VB.PNameRef = V.PNameRef) " // "JOIN WfInstance W ON VB.wfInstanceRef = W.instanceID and V.wfInstanceRef = wfnameRef "; String q = "SELECT * FROM VarBinding VB join Var V " + "on (VB.varNameRef = V.varName and VB.PNameRef = V.PNameRef) " + "JOIN WfInstance W ON VB.wfInstanceRef = W.instanceID and V.wfInstanceRef = wfnameRef " + "LEFT OUTER JOIN Data D ON D.wfInstanceID = VB.wfInstanceRef and D.dataReference = VB.value"; q = addWhereClauseToQuery(q, constraints, true); // logger.debug("getVarBindings query: \n"+q); Statement stmt; try { stmt = getConnection().createStatement(); boolean success = stmt.execute(q); // System.out.println("result: "+success); if (success) { ResultSet rs = stmt.getResultSet(); while (rs.next()) { VarBinding vb = new VarBinding(); vb.setVarNameRef(rs.getString("varNameRef")); vb.setWfInstanceRef(rs.getString("wfInstanceRef")); vb.setValue(rs.getString("value")); if (rs.getString("collIdRef") == null || rs.getString("collIdRef").equals("null")) vb.setCollIDRef(null); else vb.setCollIDRef(rs.getString("collIdRef")); vb.setIterationVector(rs.getString("iteration")); vb.setPNameRef(rs.getString("PNameRef")); vb.setPositionInColl(rs.getInt("positionInColl")); try { vb.setResolvedValue(rs.getString("D.data")); } catch (Exception e1) { // ignore this since D.data is experimental and will be // removed at some point } result.add(vb); } } } catch (Exception e) { logger.warn("Add VB failed:" + e.getMessage()); } return result; } public List<NestedListNode> getNestedListNodes( Map<String, String> constraints) throws SQLException { List<NestedListNode> result = new ArrayList<NestedListNode>(); String q = "SELECT * FROM Collection C "; q = addWhereClauseToQuery(q, constraints, true); Statement stmt = null; try { stmt = getConnection().createStatement(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } // System.out.println("executing: "+q); boolean success = stmt.execute(q); // System.out.println("result: "+success); if (success) { ResultSet rs = stmt.getResultSet(); while (rs.next()) { VarBinding vb = new VarBinding(); NestedListNode nln = new NestedListNode(); nln.setCollId(rs.getString("collId")); nln.setParentCollIdRef(rs.getString("parentCollIdRef")); nln.setWfInstanceRef(rs.getString("wfInstanceRef")); nln.setPNameRef(rs.getString("PNameRef")); nln.setVarNameRef(rs.getString("varNameRef")); nln.setIteration(rs.getString("iteration")); result.add(nln); } } return result; } public Map<String, Integer> getPredecessorsCount(String wfInstanceID) { PreparedStatement ps = null; Map<String, Integer> result = new HashMap<String, Integer>(); // get all arcs for the entire workflow structure for this particular instance Statement stmt; try { ps = getConnection().prepareStatement( "SELECT A.sourcePNameRef as source , A.sinkPNameRef as sink, A.wfInstanceRef as wfName1, W1.wfName as wfName2, W2.wfName as wfName3 "+ "FROM Arc A join WFInstance I on A.wfInstanceRef = I.wfnameRef "+ "left outer join Workflow W1 on W1.externalName = A.sourcePNameRef "+ "left outer join Workflow W2 on W2.externalName = A.sinkPNameRef "+ "where I.instanceID = ? order by wfInstanceRef"); ps.setString(1, wfInstanceID); boolean success = ps.execute(); if (success) { ResultSet rs = ps.getResultSet(); while (rs.next()) { String sink = rs.getString("sink"); String source = rs.getString("source"); if (result.get(sink) == null) result.put(sink, 0); String name1 = rs.getString("wfName1"); String name2 = rs.getString("wfName2"); String name3 = rs.getString("wfName3"); if (isDataflow(source) && name1.equals(name2)) continue; if (isDataflow(sink) && name1.equals(name3)) continue; result.put(sink, result.get(sink)+1); } } } catch (InstantiationException e1) { logger.warn("Could not execute query: " + e1); } catch (IllegalAccessException e1) { logger.warn("Could not execute query: " + e1); } catch (ClassNotFoundException e1) { logger.warn("Could not execute query: " + e1); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } /** * new impl of getProcessorsIncomingLinks whicih avoids complications due to nesting, and relies on the wfInstanceID * rather than the wfnameRef * @param wfInstanceID * @return */ public Map<String, Integer> getPredecessorsCountOld(String wfInstanceID) { PreparedStatement ps = null; Map<String, Integer> result = new HashMap<String, Integer>(); // get all arcs for the entire workflow structure for this particular instance Statement stmt; try { ps = getConnection().prepareStatement( "SELECT sinkPnameRef, P1.type, count(*) as pred "+ " FROM Arc A join WfInstance I on A.wfInstanceRef = I.wfnameRef "+ " join Processor P1 on P1.pname = A.sinkPnameRef "+ " join Processor P2 on P2.pname = A.sourcePnameRef "+ " where I.instanceID = ? "+ " and P2.type <> 'net.sf.taverna.t2.activities.dataflow.DataflowActivity' "+ " and ((P1.type = 'net.sf.taverna.t2.activities.dataflow.DataflowActivity' and P1.wfInstanceRef = A.wfInstanceRef) or "+ " (P1.type <> 'net.sf.taverna.t2.activities.dataflow.DataflowActivity')) "+ " group by A.sinkPnameRef, type"); ps.setString(1, wfInstanceID); boolean success = ps.execute(); if (success) { ResultSet rs = ps.getResultSet(); while (rs.next()) { int cnt = rs.getInt("pred"); // if (rs.getString("type").equals("net.sf.taverna.t2.activities.dataflow.DataflowActivity")) cnt--; result.put(rs.getString("sinkPnameRef"), new Integer(cnt)); } } } catch (InstantiationException e1) { logger.warn("Could not execute query: " + e1); } catch (IllegalAccessException e1) { logger.warn("Could not execute query: " + e1); } catch (ClassNotFoundException e1) { logger.warn("Could not execute query: " + e1); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } /** * used in the toposort phase -- propagation of anl() values through the * graph * * @param wfnameRef * reference to static wf name * @return a map <processor name> --> <incoming links count> for each * processor, without counting the arcs from the dataflow input to * processors. So a processor is at the root of the graph if it has * no incoming links, or all of its incoming links are from dataflow * inputs.<br/> * Note: this must be checked for processors that are roots of * sub-flows... are these counted as top-level root nodes?? */ public Map<String, Integer> getProcessorsIncomingLinks(String wfnameRef) throws SQLException { Map<String, Integer> result = new HashMap<String, Integer>(); boolean success; String currentWorkflowProcessor = null; PreparedStatement ps = null; // logger.info("getProcessorsIncomingLinks("+wfnameRef+")"); // get all processors and init their incoming links to 0 // String q = "SELECT pName FROM Processor " // + "WHERE wfInstanceRef = \'" + wfnameRef + "\'"; Statement stmt; try { ps = getConnection().prepareStatement( "SELECT pName, type FROM Processor WHERE wfInstanceRef = ?"); ps.setString(1, wfnameRef); // stmt = getConnection().createStatement(); success = ps.execute(); if (success) { ResultSet rs = ps.getResultSet(); while (rs.next()) { // PM CHECK 6/09 if (rs.getString("type").equals("net.sf.taverna.t2.activities.dataflow.DataflowActivity")) { currentWorkflowProcessor = rs.getString("pName"); logger.info("currentWorkflowProcessor = "+currentWorkflowProcessor); } result.put(rs.getString("pName"), new Integer(0)); } } } catch (InstantiationException e1) { logger.warn("Could not execute query: " + e1); } catch (IllegalAccessException e1) { logger.warn("Could not execute query: " + e1); } catch (ClassNotFoundException e1) { logger.warn("Could not execute query: " + e1); } // System.out.println("executing: "+q); // fetch the name of the top-level dataflow. We use this to exclude arcs // outgoing from its inputs // CHECK below -- gets confused on nested workflows String parentWF = getParentOfWorkflow(wfnameRef); if (parentWF == null) parentWF = wfnameRef; // null parent means we are the top logger.debug("parent WF: "+parentWF); // String pNames = "('"+parentWF+"')"; // get nested dataflows -- we want to avoid these in the toposort algorithm List<ProvenanceProcessor> procs = getProcessors( "net.sf.taverna.t2.activities.dataflow.DataflowActivity", parentWF); StringBuffer pNames = new StringBuffer(); pNames.append("("); boolean first = true; for (ProvenanceProcessor p : procs) { if (!first) pNames.append(","); else first = false; pNames.append(" '" + p.getPname() + "' "); } pNames.append(")"); // List<String> pNames = new ArrayList<String>(); // for (ProvenanceProcessor p:procs) { pNames.add(p.getPname()); } // String topLevelFlowName = pNames.get(0); // exclude processors connected to inputs -- those have 0 predecessors // for our purposes // and we add them later // PM 6/09 not sure we need to exclude arcs going into sub-flows?? so commented out the condition String q = "SELECT sinkPNameRef, count(*) as cnt " + "FROM Arc " + "WHERE wfInstanceRef = \'" + wfnameRef + "\' " + "AND sinkPNameRef NOT IN " + pNames + " " // + "AND sourcePNameRef NOT IN " + pNames + " GROUP BY sinkPNameRef"; logger.info("executing \n"+q); try { stmt = getConnection().createStatement(); success = stmt.execute(q); if (success) { ResultSet rs = stmt.getResultSet(); while (rs.next()) { if (!rs.getString("sinkPNameRef").equals(currentWorkflowProcessor)) result.put(rs.getString("sinkPNameRef"), new Integer(rs .getInt("cnt"))); } result.put(currentWorkflowProcessor,0); } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } return result; } public List<Var> getSuccVars(String pName, String vName, String wfInstanceRef) throws SQLException { List<Var> result = new ArrayList<Var>(); PreparedStatement ps = null; try { ps = getConnection() .prepareStatement( "SELECT v.* " + "FROM Arc a JOIN Var v ON a.sinkPNameRef = v.pnameRef " + "AND a.sinkVarNameRef = v.varName " + "AND a.wfInstanceRef = v.wfInstanceRef " + "WHERE sourceVarNameRef = ? AND sourcePNameRef = ?"); ps.setString(1, vName); ps.setString(2, pName); // stmt = getConnection().createStatement(); // logger.debug(ps.toString()); boolean success = ps.execute(); // System.out.println("result: "+success); if (success) { ResultSet rs = ps.getResultSet(); while (rs.next()) { if (wfInstanceRef != null && !rs.getString("v.wfInstanceRef").equals(wfInstanceRef)) { continue; } Var aVar = new Var(); aVar.setWfInstanceRef(rs.getString("WfInstanceRef")); if (rs.getInt("inputOrOutput") == 1) { aVar.setInput(true); } else { aVar.setInput(false); } aVar.setPName(rs.getString("pnameRef")); aVar.setVName(rs.getString("varName")); aVar.setType(rs.getString("type")); aVar.setTypeNestingLevel(rs.getInt("nestingLevel")); aVar.setActualNestingLevel(rs.getInt("actualNestingLevel")); aVar.setANLset((rs.getInt("anlSet") == 1 ? true : false)); result.add(aVar); } } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } // System.out.println("executing: "+q); return result; } public List<String> getSuccProcessors(String pName, String wfNameRef, String wfInstanceId) throws SQLException { List<String> result = new ArrayList<String>(); PreparedStatement ps = null; // String q = "SELECT distinct sinkPNameRef " + "FROM Arc " // + "WHERE wfInstanceRef = \'" + wfInstanceRef + "\' " // + "AND sourcePNameRef = \'" + pName + "\'"; Statement stmt; try { ps = getConnection().prepareStatement( "SELECT distinct sinkPNameRef FROM Arc A JOIN Wfinstance I on A.wfInstanceRef = I.wfnameRef " + "WHERE A.wfInstanceRef = ? and I.instanceID = ? AND sourcePNameRef = ?"); ps.setString(1, wfNameRef); ps.setString(2, wfInstanceId); ps.setString(3, pName); // stmt = getConnection().createStatement(); boolean success = ps.execute(); // System.out.println("result: "+success); if (success) { ResultSet rs = ps.getResultSet(); while (rs.next()) { result.add(rs.getString("sinkPNameRef")); } } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } // System.out.println("executing: "+q); return result; } /** * get all processors of a given type within a structure identified by * wfnameRef (reference to dataflow). type constraint is ignored if value is null * * @param wfnameRef * @param type * @return a list, that contains at most one element * @throws SQLException */ public List<ProvenanceProcessor> getProcessors(String type, String wfnameRef) throws SQLException { Map<String, String> constraints = new HashMap<String, String>(); constraints.put("P.wfInstanceRef", wfnameRef); if (type != null) { constraints.put("P.type", type); } return getProcessors(constraints); } /** * generic method to fetch processors subject to additional query constraints * @param constraints * @return * @throws SQLException */ public List<ProvenanceProcessor> getProcessors( Map<String, String> constraints) throws SQLException { List<ProvenanceProcessor> result = new ArrayList<ProvenanceProcessor>(); String q = "SELECT * FROM Processor P JOIN wfInstance W ON P.wfInstanceRef = W.wfnameRef"; q = addWhereClauseToQuery(q, constraints, true); Statement stmt; try { stmt = getConnection().createStatement(); boolean success = stmt.execute(q); // System.out.println("result: "+success); if (success) { ResultSet rs = stmt.getResultSet(); while (rs.next()) { ProvenanceProcessor proc = new ProvenanceProcessor(); proc.setPname(rs.getString("pname")); proc.setType(rs.getString("type")); proc.setWfInstanceRef(rs.getString("wfInstanceRef")); result.add(proc); } } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } // System.out.println("executing: "+q); return result; } /** * simplest possible pinpoint query. Uses iteration info straight away. Assumes result is in VarBinding not in Collection * * @param wfInstance * @param pname * @param vname * @param iteration * @return */ public LineageSQLQuery simpleLineageQuery(String wfInstance, String pname, String vname, String iteration) { LineageSQLQuery lq = new LineageSQLQuery(); // base query // String q1 = "SELECT * FROM VarBinding VB JOIN WfInstance W ON " // + "VB.wfInstanceRef = W.instanceID " // + "JOIN Var V on " // "V.wfInstanceRef = W.wfnameRef and VB.PNameRef = V.pnameRef and VB.varNameRef = V.varName"; String q1 = "SELECT * FROM VarBinding VB join Var V " + "on (VB.varNameRef = V.varName and VB.PNameRef = V.PNameRef) " + "JOIN WfInstance W ON VB.wfInstanceRef = W.instanceID and V.wfInstanceRef = wfnameRef " + "LEFT OUTER JOIN Data D ON D.wfInstanceID = VB.wfInstanceRef and D.dataReference = VB.value"; // constraints: Map<String, String> lineageQueryConstraints = new HashMap<String, String>(); lineageQueryConstraints.put("W.instanceID", wfInstance); lineageQueryConstraints.put("VB.PNameRef", pname); if (vname != null) lineageQueryConstraints.put("VB.varNameRef", vname); if (iteration != null) { lineageQueryConstraints.put("VB.iteration", iteration); } q1 = addWhereClauseToQuery(q1, lineageQueryConstraints, false); // false: // not // terminate // query // add order by clause List<String> orderAttr = new ArrayList<String>(); orderAttr.add("varNameRef"); orderAttr.add("iteration"); q1 = addOrderByToQuery(q1, orderAttr, true); // System.out.println("generated query: \n"+q1); logger.debug("Query is: " + q1); lq.setVbQuery(q1); return lq; } /** * if var2Path is null this generates a trivial query for the current output * var and current path * * @param wfInstanceID * @param proc * @param var2Path * @param outputVar * @param path * @param returnOutputs * returns inputs *and* outputs if set to true * @return */ public List<LineageSQLQuery> lineageQueryGen(String wfInstanceID, String proc, Map<Var, String> var2Path, Var outputVar, String path, boolean returnOutputs) { // setup StringBuffer effectivePath = new StringBuffer(); // System.out.println("generating SQL for proc ="+proc); // System.out.println("input vars:"); // for (Var v: var2Path.keySet()) { // System.out.println(v.getVName()+ // " with delta-nl "+ // (v.getActualNestingLevel()-v.getTypeNestingLevel())+ // " and path "+var2Path.get(v)); List<LineageSQLQuery> newQueries = new ArrayList<LineageSQLQuery>(); // use the calculated path for each input var boolean isInput = true; for (Var v:var2Path.keySet()) { LineageSQLQuery q = generateSQL2(wfInstanceID, proc, v.getVName(), var2Path.get(v), isInput); if (q != null) newQueries.add(q); } // is returnOutputs is true, then use proc, path for the output var as well if (returnOutputs) { isInput = false; // CHECK not sure this is still valid // if (path != null) { // int outputVarDnl = outputVar.getTypeNestingLevel(); // String pathArray[] = path.split(","); // for (int i = 0; i < pathArray.length - outputVarDnl; i++) { // effectivePath.append(pathArray[i] + ","); // if (effectivePath.length() > 0) // effectivePath.deleteCharAt(effectivePath.length() - 1); LineageSQLQuery q = generateSQL2(wfInstanceID, proc, outputVar.getVName(), path, isInput); // && !var2Path.isEmpty()); if (q != null) newQueries.add(q); } return newQueries; // System.out.println("dnl of output var "+outputVar.getVName()+": "+outputVarDnl); // System.out.println("original path: "+path); // CHECK not sure this is still valid // if (path != null) { // String pathArray[] = path.split(","); // for (int i = 0; i < pathArray.length - outputVarDnl; i++) { // effectivePath.append(pathArray[i] + ","); // if (effectivePath.length() > 0) // effectivePath.deleteCharAt(effectivePath.length() - 1); // generation // if (!var2Path.isEmpty()) { // generate query to retrieve inputs // // returnOutputs => SQL generator will *not* constrain to return // // inputs only // return generateSQL(wfInstance, proc, effectivePath.toString(), // returnOutputs); //// return generateSQL(wfInstance, proc, path, //// returnOutputs); // } else { // generate query to retrieve outputs (this is a special case // // where processor has no inputs) // // System.out.println("lineageQueryGen: proc has no inputs => return output values instead"); //// return generateSQL(wfInstance, proc, path, false); // false -> fetch output vars only // return generateSQL(wfInstance, proc, effectivePath.toString(), false); // false -> fetch output vars only // return generateSQL(wfInstance, proc, effectivePath.toString(), returnOutputs); // && !var2Path.isEmpty()); } protected LineageSQLQuery generateSQL2(String wfInstance, String proc, String var, String path, boolean returnInput) { LineageSQLQuery lq = new LineageSQLQuery(); // constraints: Map<String, String> collQueryConstraints = new HashMap<String, String>(); // base Collection query String collQuery = "SELECT * FROM Collection C JOIN wfInstance W ON " + "C.wfInstanceRef = W.instanceID " + "JOIN Var V on " + "V.wfInstanceRef = W.wfnameRef and C.PNameRef = V.pnameRef and C.varNameRef = V.varName "; collQueryConstraints.put("W.instanceID", wfInstance); collQueryConstraints.put("C.PNameRef", proc); if (path != null && path.length() > 0) { collQueryConstraints.put("C.iteration", "["+ path + "]"); // PM 1/09 -- path } // inputs or outputs? if (returnInput) collQueryConstraints.put("V.inputOrOutput", "1"); else collQueryConstraints.put("V.inputOrOutput", "0"); collQuery = addWhereClauseToQuery(collQuery, collQueryConstraints, false); lq.setCollQuery(collQuery); // vb query Map<String, String> vbQueryConstraints = new HashMap<String, String>(); // base VarBinding query String vbQuery = "SELECT * FROM VarBinding VB JOIN wfInstance W ON " + "VB.wfInstanceRef = W.instanceID " + "JOIN Var V on " + "V.wfInstanceRef = W.wfnameRef and VB.PNameRef = V.pnameRef and VB.varNameRef = V.varName " + "LEFT OUTER JOIN Data D ON D.wfInstanceID = VB.wfInstanceRef and D.dataReference = VB.value"; vbQueryConstraints.put("W.instanceID", wfInstance); vbQueryConstraints.put("VB.PNameRef", proc); vbQueryConstraints.put("VB.varNameRef", var); if (path != null && path.length() > 0) { vbQueryConstraints.put("VB.iteration", "["+ path + "]"); // PM 1/09 -- path } // limit to inputs? if (returnInput) vbQueryConstraints.put("V.inputOrOutput", "1"); else vbQueryConstraints.put("V.inputOrOutput", "0"); vbQuery = addWhereClauseToQuery(vbQuery, vbQueryConstraints, false); List<String> orderAttr = new ArrayList<String>(); orderAttr.add("varNameRef"); orderAttr.add("iteration"); vbQuery = addOrderByToQuery(vbQuery, orderAttr, true); // System.out.println("generated query: \n"+q1); lq.setVbQuery(vbQuery); return lq; } /** * if effectivePath is not null: query varBinding using: wfInstanceRef = * wfInstance, iteration = effectivePath, PNameRef = proc if input vars is * null, then use the output var this returns the bindings for the set of * input vars at the correct iteration if effectivePath is null: fetch * VarBindings for all input vars, without constraint on the iteration<br/> * added outer join with Data<br/> * additionally, try querying the collection table first -- if the query succeeds, it means * the path is pointing to an internal node in the collection, and we just got the right node. * Otherwise, query VarBinding for the leaves * * @param wfInstance * @param proc * @param effectivePath * @param returnOutputs * returns both inputs and outputs if set to true * @return */ public LineageSQLQuery generateSQL(String wfInstance, String proc, String effectivePath, boolean returnOutputs) { LineageSQLQuery lq = new LineageSQLQuery(); // constraints: Map<String, String> collQueryConstraints = new HashMap<String, String>(); // base Collection query String collQuery = "SELECT * FROM Collection C JOIN wfInstance W ON " + "C.wfInstanceRef = W.instanceID " + "JOIN Var V on " + "V.wfInstanceRef = W.wfnameRef and C.PNameRef = V.pnameRef and C.varNameRef = V.varName "; collQueryConstraints.put("W.instanceID", wfInstance); collQueryConstraints.put("C.PNameRef", proc); if (effectivePath != null && effectivePath.length() > 0) { collQueryConstraints.put("C.iteration", "["+ effectivePath.toString() + "]"); // PM 1/09 -- path } // limit to inputs? if (returnOutputs) collQueryConstraints.put("V.inputOrOutput", "1"); collQuery = addWhereClauseToQuery(collQuery, collQueryConstraints, false); lq.setCollQuery(collQuery); // vb query Map<String, String> vbQueryConstraints = new HashMap<String, String>(); // base VarBinding query String vbQuery = "SELECT * FROM VarBinding VB JOIN wfInstance W ON " + "VB.wfInstanceRef = W.instanceID " + "JOIN Var V on " + "V.wfInstanceRef = W.wfnameRef and VB.PNameRef = V.pnameRef and VB.varNameRef = V.varName " + "LEFT OUTER JOIN Data D ON D.wfInstanceID = VB.wfInstanceRef and D.dataReference = VB.value"; vbQueryConstraints.put("W.instanceID", wfInstance); vbQueryConstraints.put("VB.PNameRef", proc); if (effectivePath != null && effectivePath.length() > 0) { vbQueryConstraints.put("VB.iteration", "["+ effectivePath.toString() + "]"); // PM 1/09 -- path } // limit to inputs? if (!returnOutputs) vbQueryConstraints.put("V.inputOrOutput", "1"); vbQuery = addWhereClauseToQuery(vbQuery, vbQueryConstraints, false); List<String> orderAttr = new ArrayList<String>(); orderAttr.add("varNameRef"); orderAttr.add("iteration"); vbQuery = addOrderByToQuery(vbQuery, orderAttr, true); // System.out.println("generated query: \n"+q1); lq.setVbQuery(vbQuery); return lq; } public LineageQueryResult runCollectionQuery(LineageSQLQuery lq) throws SQLException { Statement stmt; String q = lq.getCollQuery(); LineageQueryResult lqr = new LineageQueryResult(); if (q == null) return lqr; logger.debug("running collection query: "+q); try { stmt = getConnection().createStatement(); boolean success = stmt.execute(q); if (success) { ResultSet rs = stmt.getResultSet(); while (rs.next()) { String type = lqr.ATOM_TYPE; // temp -- FIXME String wfInstance = rs.getString("wfInstanceRef"); String proc = rs.getString("PNameRef"); String var = rs.getString("varNameRef"); String it = rs.getString("iteration"); String coll = rs.getString("collID"); String parentColl = rs.getString("parentCollIDRef"); // System.out.println("proc ["+proc+"] var ["+var+"] iteration ["+it+"] collection ["+ // coll+"] value ["+value+"]"); lqr.addLineageQueryResultRecord(proc, var, wfInstance, it, coll, parentColl, null, null, type, false, true); // true -> is a collection } } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } return lqr; } public LineageQueryResult runVBQuery(LineageSQLQuery lq, boolean includeDataValue) throws SQLException { Statement stmt; String q = lq.getVbQuery(); logger.debug("running VB query: "+q); try { stmt = getConnection().createStatement(); boolean success = stmt.execute(q); if (success) { ResultSet rs = stmt.getResultSet(); LineageQueryResult lqr = new LineageQueryResult(); while (rs.next()) { String type = lqr.ATOM_TYPE; // temp -- FIXME String wfInstance = rs.getString("wfInstanceRef"); String proc = rs.getString("PNameRef"); String var = rs.getString("varNameRef"); String it = rs.getString("iteration"); String coll = rs.getString("collIDRef"); String value = rs.getString("value"); boolean isInput = (rs.getInt("inputOrOutput") == 1) ? true : false; // FIXME there is no D and no VB - this is in generateSQL, // not simpleLineageQuery if (includeDataValue) { String resolvedValue = rs.getString("D.data"); // System.out.println("resolved value: "+resolvedValue); lqr.addLineageQueryResultRecord(proc, var, wfInstance, it, coll, null, value, resolvedValue, type, isInput, false); // false -> not a collection } else { // System.out.println("proc ["+proc+"] var ["+var+"] iteration ["+it+"] collection ["+ // coll+"] value ["+value+"]"); // lqr.addLineageQueryResultRecord(proc, var, // wfInstance, // value, resolvedValue, type); // FIXME if the data is required then the query needs // fixing lqr.addLineageQueryResultRecord(proc, var, wfInstance, it, coll, null, value, null, type, isInput, false); } } return lqr; } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } return null; } /** * executes one of the lineage queries produced by the graph visit algorithm. This first executes the collection query, and then * if no result is returned, the varBinding query * * @param lq * a lineage query computed during the graph traversal * @param includeDataValue * if true, then the referenced value is included in the result. * This may only be necessary for testing: the data reference in * field value (which is a misleading field name, and actually * refers to the data reference) should be sufficient * @return * @throws SQLException */ public LineageQueryResult runLineageQuery(LineageSQLQuery lq, boolean includeDataValue) throws SQLException { LineageQueryResult result = runCollectionQuery(lq); if (result.getRecords().size() == 0) // query was really VB return runVBQuery(lq, includeDataValue); return result; } public List<LineageQueryResult> runLineageQueries( List<LineageSQLQuery> lqList, boolean includeDataValue) throws SQLException { List<LineageQueryResult> allResults = new ArrayList<LineageQueryResult>(); if (lqList == null) { logger.warn("lineage queries list is NULL, nothing to evaluate"); return allResults; } for (LineageSQLQuery lq : lqList) { if (lq == null) continue; allResults.add(runLineageQuery(lq, includeDataValue)); } return allResults; } /** * takes an ordered set of records for the same variable with iteration * indexes and builds a collection out of it * * @param lqr * @return a jdom Document with the collection */ public Document recordsToCollection(LineageQueryResult lqr) { // process each var name in turn // lqr ordered by var name and by iteration number Document d = new Document(new Element("list")); String currentVar = null; for (ListIterator<LineageQueryResultRecord> it = lqr.iterator(); it .hasNext();) { LineageQueryResultRecord record = it.next(); if (currentVar != null && record.getVname().equals(currentVar)) { // multiple // occurrences addToCollection(record, d); // adds record to d in the correct // position given by the iteration // vector } if (currentVar == null) { currentVar = record.getVname(); } } return d; } private void addToCollection(LineageQueryResultRecord record, Document d) { Element root = d.getRootElement(); String[] itVector = record.getIteration().split(","); Element currentEl = root; // each element gives us a corresponding child in the tree for (int i = 0; i < itVector.length; i++) { int index = Integer.parseInt(itVector[i]); List<Element> children = currentEl.getChildren(); if (index < children.size()) { // we already have the child, just // descend currentEl = children.get(index); } else { // create child if (i == itVector.length - 1) { // this is a leaf --> atomic // element currentEl.addContent(new Element(record.getValue())); } else { // create internal element currentEl.addContent(new Element("list")); } } } } /** * returns the set of all processors that are structurally contained within * the wf corresponding to the input dataflow name * @param dataflowName the name of a processor of type DataFlowActivity * @return */ public List<String> getContainedProcessors(String dataflowName, String instanceID) { List<String> result = new ArrayList<String>(); // dataflow name -> wfRef String containerDataflow = getWfNameForDataflow(dataflowName, instanceID); // logger.debug("containerDataflow: "+containerDataflow); // get all processors within containerDataflow PreparedStatement ps = null; try { ps = getConnection().prepareStatement( "SELECT pname FROM Processor P join wfInstance I on P.wfInstanceRef = I.wfnameRef "+ "where wfInstanceRef = ? and I.instanceID = ?"); ps.setString(1, containerDataflow); ps.setString(2, instanceID); boolean success = ps.execute(); if (success) { ResultSet rs = ps.getResultSet(); while (rs.next()) { result.add(rs.getString("pname")); } } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } public String getTopLevelDataflowName(String wfInstanceID) { PreparedStatement ps = null; try { ps = getConnection().prepareStatement( "SELECT pname FROM Processor P join wfInstance I on P.wfInstanceRef = I.wfnameRef "+ "where I.instanceID =? and isTopLevel = 1"); ps.setString(1, wfInstanceID); boolean success = ps.execute(); if (success) { ResultSet rs = ps.getResultSet(); if (rs.next()) { return rs.getString("pname"); } } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public String getWfNameForDataflow(String dataflowName, String instanceID) { PreparedStatement ps = null; try { ps = getConnection().prepareStatement( "SELECT wfname FROM Workflow W join WfInstance I on W.wfname = I.wfNameRef WHERE W.externalName = ? and I.instanceID = ?"); ps.setString(1, dataflowName); ps.setString(2, instanceID); // logger.debug(ps.toString()); boolean success = ps.execute(); if (success) { ResultSet rs = ps.getResultSet(); if (rs.next()) { return rs.getString("wfname"); } } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public List<String> getChildrenOfWorkflow(String parentWFName) throws SQLException { List<String> result = new ArrayList<String>(); PreparedStatement ps = null; try { ps = getConnection().prepareStatement( "SELECT wfname FROM Workflow WHERE parentWFname = ? "); ps.setString(1, parentWFName); // stmt = getConnection().createStatement(); boolean success = ps.execute(); if (success) { ResultSet rs = ps.getResultSet(); while (rs.next()) { result.add(rs.getString("wfname")); } } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } return result; } /** * fetch children of parentWFName from the Workflow table * * @return * @param childWFName * @throws SQLException */ public String getParentOfWorkflow(String childWFName) throws SQLException { // String q = "SELECT parentWFname FROM Workflow WHERE wfname = \'" // + childWFName + "\'"; PreparedStatement ps = null; String result = null; String q = "SELECT parentWFname FROM Workflow WHERE wfname = ?"; // Statement stmt; try { ps = getConnection().prepareStatement(q); ps.setString(1, childWFName); logger.debug("getParentOfWorkflow - query: "+q+" with wfname = "+childWFName); // stmt = getConnection().createStatement(); boolean success = ps.execute(); if (success) { ResultSet rs = ps.getResultSet(); while (rs.next()) { result = rs.getString("parentWFname"); logger.debug("result: "+result); break; } } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } return result; } public List<String> getAllWFnames() throws SQLException { List<String> result = new ArrayList<String>(); String q = "SELECT wfname FROM Workflow"; Statement stmt; try { stmt = getConnection().createStatement(); boolean success = stmt.execute(q); if (success) { ResultSet rs = stmt.getResultSet(); while (rs.next()) { result.add(rs.getString("wfname")); } } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } return result; } /** * * @param procName * @return true if procName is the external name of a dataflow, false * otherwise * @throws SQLException */ public boolean isDataflow(String procName) throws SQLException { PreparedStatement ps = null; try { ps = getConnection().prepareStatement( "SELECT type FROM Processor WHERE pname = ?"); ps.setString(1, procName); // stmt = getConnection().createStatement(); boolean success = ps.execute(); if (success) { ResultSet rs = ps.getResultSet(); if (rs.next() && rs.getString("type") != null && rs.getString("type").equals(DATAFLOW_TYPE)) return true; } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } return false; } public String getTopDataflow(String wfInstanceID) { PreparedStatement ps = null; try { ps = getConnection().prepareStatement( "SELECT * FROM Processor P join wfInstance I on P.wfInstanceRef = I.wfNameRef "+ " where I.instanceID = ? "+ " and isTopLevel = 1 "); ps.setString(1, wfInstanceID); boolean success = ps.execute(); if (success) { ResultSet rs = ps.getResultSet(); if (rs.next()) return rs.getString("PName"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** * * @param p * pTo processor * @param var * vTo * @param value * valTo * @return a set of DDRecord * @throws SQLException */ public List<DDRecord> queryDD(String p, String var, String value, String iteration, String wfInstance) throws SQLException { List<DDRecord> result = new ArrayList<DDRecord>(); Map<String, String> queryConstraints = new HashMap<String, String>(); queryConstraints.put("pTo", p); queryConstraints.put("vTo", var); if (value != null) queryConstraints.put("valTo", value); if (iteration != null) queryConstraints.put("iteration", iteration); if (wfInstance != null) queryConstraints.put("wfInstance", wfInstance); String q = "SELECT * FROM DD "; q = addWhereClauseToQuery(q, queryConstraints, true); // true: terminate // SQL statement Statement stmt; try { stmt = getConnection().createStatement(); boolean success = stmt.execute(q); if (success) { ResultSet rs = stmt.getResultSet(); while (rs.next()) { DDRecord aDDrecord = new DDRecord(); aDDrecord.setPFrom(rs.getString("pFrom")); aDDrecord.setVFrom(rs.getString("vFrom")); aDDrecord.setValFrom(rs.getString("valFrom")); aDDrecord.setPTo(rs.getString("pTo")); aDDrecord.setVTo(rs.getString("vTo")); aDDrecord.setValTo(rs.getString("valTo")); result.add(aDDrecord); } return result; } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } return null; } public Set<DDRecord> queryArcsForDD(String p, String v, String val, String wfInstance) throws SQLException { Set<DDRecord> result = new HashSet<DDRecord>(); PreparedStatement ps = null; String q = "SELECT DISTINCT A.sourcePNameRef AS p, A.sourceVarNameRef AS var, VB.value AS val " + "FROM Arc A JOIN VarBinding VB ON VB.varNameRef = A.sinkVarNameRef AND VB.PNameRef = A.sinkPNameRef " + "JOIN WFInstance WF ON WF.wfnameRef = A.wfInstanceRef AND WF.instanceID = VB.wfInstanceRef " + "WHERE WF.instanceID = '" + wfInstance + "' AND A.sinkPNameRef = '" + p + "' AND A.sinkVarNameRef = '" + v + "' AND VB.value = '" + val + "' "; // Statement stmt; try { ps = getConnection() .prepareStatement( "SELECT DISTINCT A.sourcePNameRef AS p, A.sourceVarNameRef AS var, VB.value AS val " + "FROM Arc A JOIN VarBinding VB ON VB.varNameRef = A.sinkVarNameRef AND VB.PNameRef = A.sinkPNameRef " + "JOIN WFInstance WF ON WF.wfnameRef = A.wfInstanceRef AND WF.instanceID = VB.wfInstanceRef " + "WHERE WF.instanceID = ? AND A.sinkPNameRef = ? AND A.sinkVarNameRef = ? AND VB.value = ?"); ps.setString(1, wfInstance); ps.setString(2, p); ps.setString(3, v); ps.setString(4, val); // stmt = getConnection().createStatement(); boolean success = ps.execute(); if (success) { ResultSet rs = ps.getResultSet(); while (rs.next()) { DDRecord aDDrecord = new DDRecord(); aDDrecord.setPTo(rs.getString("p")); aDDrecord.setVTo(rs.getString("var")); aDDrecord.setValTo(rs.getString("val")); result.add(aDDrecord); } return result; } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } return null; } public Set<DDRecord> queryAllFromValues(String wfInstance) throws SQLException { Set<DDRecord> result = new HashSet<DDRecord>(); PreparedStatement ps = null; try { ps = getConnection() .prepareStatement( "SELECT DISTINCT PFrom, vFrom, valFrom FROM DD where wfInstance = ?"); ps.setString(1, wfInstance); // stmt = getConnection().createStatement(); boolean success = ps.execute(); if (success) { ResultSet rs = ps.getResultSet(); while (rs.next()) { DDRecord aDDrecord = new DDRecord(); aDDrecord.setPFrom(rs.getString("PFrom")); aDDrecord.setVFrom(rs.getString("vFrom")); aDDrecord.setValFrom(rs.getString("valFrom")); result.add(aDDrecord); } return result; } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } return null; } public void setDbURL(String dbURL) { this.dbURL = dbURL; } public String getDbURL() { return dbURL; } public boolean isRootProcessorOfWorkflow(String procName, String wfName, String wfInstanceId) { PreparedStatement ps = null; try { ps = getConnection().prepareStatement( "SELECT * FROM Arc A join wfInstance I on A.wfInstanceRef = I.wfnameRef "+ "join Processor P on P.pname = A.sourcePnameRef where sourcePnameRef = ? "+ "and P.wfInstanceRef <> A.wfInstanceRef "+ "and I.instanceID = ? "+ "and sinkPNameRef = ? "); ps.setString(1, wfName); ps.setString(2, wfInstanceId); ps.setString(3, procName); boolean success = ps.execute(); if (success) { ResultSet rs = ps.getResultSet(); if (rs.next()) { return true; } } } catch (InstantiationException e) { logger.warn("Could not execute query: " + e); } catch (IllegalAccessException e) { logger.warn("Could not execute query: " + e); } catch (ClassNotFoundException e) { logger.warn("Could not execute query: " + e); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } }
package no.deichman.services.services.search; import no.deichman.services.testutil.PortSelector; import org.apache.commons.io.FileUtils; import org.apache.http.client.methods.HttpPut; import org.apache.http.impl.client.CloseableHttpClient; import pl.allegro.tech.embeddedelasticsearch.EmbeddedElastic; import pl.allegro.tech.embeddedelasticsearch.IndexSettings; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import static java.lang.ClassLoader.getSystemResourceAsStream; import static java.lang.System.getenv; import static org.apache.http.impl.client.HttpClients.createDefault; /** * Responsibility: An embedded elasticsearch server for test purposes. */ public final class EmbeddedElasticsearchServer { private static final String DEFAULT_DATA_DIRECTORY = "/var/tmp/target/elasticsearch-data"; private static EmbeddedElastic embeddedElastic; private final String dataDirectory; private static int port; public EmbeddedElasticsearchServer() throws Exception { this(DEFAULT_DATA_DIRECTORY); } private EmbeddedElasticsearchServer(String dataDirectory) throws Exception { this.dataDirectory = dataDirectory; this.port = PortSelector.randomFree(); new File(dataDirectory).mkdirs(); IndexSettings idx = IndexSettings.builder() .withSettings(getSystemResourceAsStream("search_index.json")) .withType("person", getSystemResourceAsStream("person_mapping.json")) .withType("work", getSystemResourceAsStream("work_mapping.json")) .withType("corporation", getSystemResourceAsStream("corporation_mapping.json")) .withType("serial", getSystemResourceAsStream("serial_mapping.json")) .withType("workSeries", getSystemResourceAsStream("workSeries_mapping.json")) .withType("subject", getSystemResourceAsStream("subject_mapping.json")) .withType("genre", getSystemResourceAsStream("genre_mapping.json")) .withType("publication", getSystemResourceAsStream("publication_mapping.json")) .withType("instrument", getSystemResourceAsStream("instrument_mapping.json")) .withType("compositionType", getSystemResourceAsStream("compositionType_mapping.json")) .withType("event", getSystemResourceAsStream("event_mapping.json")) .build(); embeddedElastic = EmbeddedElastic.builder() .withElasticVersion("5.2.1") .withSetting("http.port", port) .withSetting("http.enabled", "true") .withSetting("path.home", ".") .withSetting("path.data", dataDirectory) .withStartTimeout(2, TimeUnit.MINUTES) .withEsJavaOpts("-Xms512m -Xmx512m") .withPlugin(getenv().getOrDefault("ES_ICU_PLUGIN_URL", "analysis-icu")) .withIndex("a", idx) .withIndex("b", idx) .build() .start(); try (CloseableHttpClient httpclient = createDefault()) { httpclient.execute(new HttpPut("http://localhost:" + embeddedElastic.getHttpPort() + "/a/_alias/search")); } } public static EmbeddedElastic getClient() { return embeddedElastic; } public static Integer getPort() { return port; } public void shutdown() throws Exception { embeddedElastic.stop(); deleteDataDirectory(); } @Override protected void finalize() throws Throwable { deleteDataDirectory(); super.finalize(); } private void deleteDataDirectory() { try { FileUtils.deleteDirectory(new File(dataDirectory)); } catch (IOException e) { throw new RuntimeException("Could not delete data directory of embedded elasticsearch server", e); } } }
package org.ow2.proactive_grid_cloud_portal.scheduler.client.utils; import static com.google.common.base.Preconditions.checkNotNull; import java.io.*; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.zip.*; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.VFS; import org.apache.log4j.Logger; import org.objectweb.proactive.extensions.dataspaces.vfs.selector.FileSelector; import com.google.common.base.Predicate; import com.google.common.base.Strings; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.io.ByteStreams; import com.google.common.io.Closer; import com.google.common.io.Files; public class Zipper { private static final Logger logger = Logger.getLogger(Zipper.class); private static byte[] MAGIC = { 'P', 'K', 0x3, 0x4 }; private Zipper() { } public static class GZIP { public static void zip(File file, OutputStream os) throws IOException { checkNotNull(file); checkNotNull(os); try (InputStream inputStream = new FileInputStream(file)) { GZIP.zip(inputStream, os); } } public static void zip(InputStream is, OutputStream os) throws IOException { Closer closer = Closer.create(); closer.register(is); try { GZIPOutputStream zos = new GZIPOutputStream(os); closer.register(zos); ByteStreams.copy(is, zos); } catch (IOException ioe) { throw closer.rethrow(ioe); } finally { closer.close(); } } public static void unzip(InputStream is, File file) throws IOException { checkNotNull(is); checkNotNull(file); try (OutputStream outputStream = new FileOutputStream(file)) { GZIP.unzip(is, outputStream); } } public static void unzip(InputStream is, OutputStream os) throws IOException { Closer closer = Closer.create(); closer.register(os); try { GZIPInputStream gis = new GZIPInputStream(is); closer.register(gis); ByteStreams.copy(gis, os); } catch (IOException ioe) { throw closer.rethrow(ioe); } finally { closer.close(); } } } public static class ZIP { private static List<File> findFiles(File root, FileSelector selector) { List<File> listFiles = new ArrayList<>(); try { FileObject rootObject = VFS.getManager().toFileObject(root); FileObject[] fos = rootObject.findFiles(selector); for (FileObject fo : fos) { listFiles.add(new File(fo.getName().getPath())); } } catch (Exception e) { logger.error("An error occurred while zipping files: ", e); } return listFiles; } private static ImmutableList<File> filterNotEmpty(File root, List<String> includes, List<String> excludes) { FileSelector fileSelector = new FileSelector(); fileSelector.addIncludes(includes); fileSelector.addExcludes(excludes); return ImmutableList.copyOf(findFiles(root, fileSelector)); } private static ImmutableList<File> filterEmpty(File root) { FluentIterable<File> fi = Files.fileTreeTraverser().postOrderTraversal(root); return fi.filter(new FilesOnlyPredicate()).toList(); } public static void zip(File root, List<String> includes, List<String> excludes, OutputStream os) throws IOException { List<String> logIncludes = nullOrEmpty(includes) ? new ArrayList<>() : includes; List<String> logExcludes = nullOrEmpty(excludes) ? new ArrayList<>() : excludes; logger.trace("Includes list : " + logIncludes.toString()); logger.trace("Excludes list : " + logExcludes.toString()); checkNotNull(root); checkNotNull(os); ImmutableList<File> fileList = nullOrEmpty(includes) && nullOrEmpty(excludes) ? filterEmpty(root) : filterNotEmpty(root, includes, excludes); logger.trace("Zipping files :" + fileList); zipFiles(fileList, root.getAbsolutePath(), os); } private static boolean nullOrEmpty(List<String> strings) { return strings == null || strings.size() == 0; } private static void zipFiles(List<File> files, String basepath, OutputStream os) throws IOException { Closer closer = Closer.create(); try { ZipOutputStream zos = new ZipOutputStream(os); closer.register(zos); for (File file : files) { if (file.isFile()) { FileInputStream inputStream = new FileInputStream(file); closer.register(inputStream); writeZipEntry(zipEntry(basepath, file), inputStream, zos); } else { ZipEntry ze = zipEntry(basepath, file); logger.trace("Adding directory zip entry: " + ze.toString()); zos.putNextEntry(ze); } } } catch (IOException ioe) { throw closer.rethrow(ioe); } finally { closer.close(); } } public static void writeZipEntry(ZipEntry zipEntry, InputStream is, ZipOutputStream zos) throws IOException { Closer closer = Closer.create(); closer.register(is); try { logger.trace("Adding file zip entry: " + zipEntry.toString()); zos.putNextEntry(zipEntry); ByteStreams.copy(is, zos); zos.flush(); } catch (IOException ioe) { throw closer.rethrow(ioe); } finally { closer.close(); } } public static void unzip(InputStream is, File outFile) throws IOException { Closer closer = Closer.create(); try { ZipInputStream zis = new ZipInputStream(is); closer.register(zis); ZipEntry zipEntry = zis.getNextEntry(); while (zipEntry != null) { File entryFile = new File(outFile, zipEntry.getName()); File entryContainer = entryFile.getParentFile(); if (!entryContainer.exists()) { entryContainer.mkdirs(); } if (!entryFile.isDirectory()) { FileOutputStream outputStream = new FileOutputStream(entryFile); closer.register(outputStream); Zipper.ZIP.unzipEntry(zis, outputStream); } zipEntry = zis.getNextEntry(); } } catch (IOException ioe) { throw closer.rethrow(ioe); } finally { closer.close(); } } public static void unzipEntry(ZipInputStream zis, OutputStream os) throws IOException { Closer closer = Closer.create(); closer.register(os); try { ByteStreams.copy(zis, os); } catch (IOException ioe) { throw closer.rethrow(ioe); } finally { closer.close(); } } private static String getRealRelativeFilePath(String basepath, String absolutePath) throws IOException { String realAbsolutePath = Paths.get(absolutePath).toRealPath().toString(); String realBasePath = Paths.get(basepath).toRealPath().toString(); return basepath.endsWith(File.separator) ? realAbsolutePath.substring(realBasePath.length()) : realAbsolutePath.substring(realBasePath.length() + 1); } private static ZipEntry zipEntry(String basepath, File file) throws IOException { String name = (Strings.isNullOrEmpty(basepath) || basepath.equals(file.getAbsolutePath())) ? file.getPath() : getRealRelativeFilePath(basepath, file.getAbsolutePath()); name = file.isDirectory() ? new File(name, File.separator).toString() : name; return new ZipEntry(name); } } public static boolean isZipFile(File file) throws FileNotFoundException { try (FileInputStream inputStream = new FileInputStream(file)) { return isZipFile(inputStream); } catch (IOException e) { throw new FileNotFoundException("Error when reading file " + file + " " + e.getMessage()); } } public static boolean isZipFile(InputStream is) { if (!is.markSupported()) { is = new BufferedInputStream(is); } boolean isZipStream = true; try { is.mark(MAGIC.length); for (int i = 0; i < MAGIC.length; i++) { if (MAGIC[i] != (byte) is.read()) { isZipStream = false; break; } } is.reset(); } catch (IOException ioe) { isZipStream = false; } return isZipStream; } private static class FilesOnlyPredicate implements Predicate<File> { @Override public boolean apply(File file) { boolean answer = !file.isDirectory(); if (logger.isTraceEnabled()) { logger.trace("Analysing file " + file + " : " + answer); } return answer; } } }
package net.runelite.client.plugins.specialcounter; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.inject.Inject; import net.runelite.api.Actor; import net.runelite.api.Client; import net.runelite.api.EquipmentInventorySlot; import net.runelite.api.GameState; import net.runelite.api.Hitsplat; import net.runelite.api.InventoryID; import net.runelite.api.Item; import net.runelite.api.ItemContainer; import net.runelite.api.NPC; import net.runelite.api.VarPlayer; import net.runelite.api.events.GameStateChanged; import net.runelite.api.events.HitsplatApplied; import net.runelite.api.events.NpcDespawned; import net.runelite.api.events.VarbitChanged; import net.runelite.client.callback.ClientThread; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.game.ItemManager; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.ui.overlay.infobox.InfoBoxManager; import net.runelite.client.ws.PartyService; import net.runelite.client.ws.WSClient; @PluginDescriptor( name = "Special Attack Counter", description = "Track DWH, Arclight, Darklight, and BGS special attacks used on NPCs", tags = {"combat", "npcs", "overlay"}, enabledByDefault = false ) public class SpecialCounterPlugin extends Plugin { private int currentWorld = -1; private int specialPercentage = -1; private NPC specedNPC; private SpecialWeapon specialWeapon; private final Set<Integer> interactedNpcIds = new HashSet<>(); private final SpecialCounter[] specialCounter = new SpecialCounter[SpecialWeapon.values().length]; @Inject private Client client; @Inject private ClientThread clientThread; @Inject private WSClient wsClient; @Inject private PartyService party; @Inject private InfoBoxManager infoBoxManager; @Inject private ItemManager itemManager; @Override protected void startUp() { wsClient.registerMessage(SpecialCounterUpdate.class); } @Override protected void shutDown() { removeCounters(); wsClient.unregisterMessage(SpecialCounterUpdate.class); } @Subscribe public void onGameStateChanged(GameStateChanged event) { if (event.getGameState() == GameState.LOGGED_IN) { if (currentWorld == -1) { currentWorld = client.getWorld(); } else if (currentWorld != client.getWorld()) { currentWorld = client.getWorld(); removeCounters(); } } } @Subscribe public void onVarbitChanged(VarbitChanged event) { int specialPercentage = client.getVar(VarPlayer.SPECIAL_ATTACK_PERCENT); if (this.specialPercentage == -1 || specialPercentage >= this.specialPercentage) { this.specialPercentage = specialPercentage; return; } this.specialPercentage = specialPercentage; this.specialWeapon = usedSpecialWeapon(); Actor interacting = client.getLocalPlayer().getInteracting(); if (interacting instanceof NPC) { specedNPC = (NPC) interacting; } } @Subscribe public void onHitsplatApplied(HitsplatApplied hitsplatApplied) { Actor target = hitsplatApplied.getActor(); Hitsplat hitsplat = hitsplatApplied.getHitsplat(); if (hitsplat.getHitsplatType() != Hitsplat.HitsplatType.DAMAGE_ME || !(target instanceof NPC)) { return; } NPC npc = (NPC) target; int interactingId = npc.getId(); // If this is a new NPC reset the counters if (!interactedNpcIds.contains(interactingId)) { removeCounters(); addInteracting(interactingId); } if (specedNPC == hitsplatApplied.getActor()) { specedNPC = null; if (specialWeapon != null) { int hit = getHit(specialWeapon, hitsplat); updateCounter(specialWeapon, null, hit); if (!party.getMembers().isEmpty()) { final SpecialCounterUpdate specialCounterUpdate = new SpecialCounterUpdate(interactingId, specialWeapon, hit); specialCounterUpdate.setMemberId(party.getLocalMember().getMemberId()); wsClient.send(specialCounterUpdate); } } } } private void addInteracting(int npcId) { interactedNpcIds.add(npcId); // Add alternate forms of bosses final Boss boss = Boss.getBoss(npcId); if (boss != null) { interactedNpcIds.addAll(boss.getIds()); } } @Subscribe public void onNpcDespawned(NpcDespawned npcDespawned) { NPC actor = npcDespawned.getNpc(); // if the NPC despawns before the hitsplat is shown if (specedNPC == actor) { specedNPC = null; } if (actor.isDead() && interactedNpcIds.contains(actor.getId())) { removeCounters(); } } @Subscribe public void onSpecialCounterUpdate(SpecialCounterUpdate event) { if (party.getLocalMember().getMemberId().equals(event.getMemberId())) { return; } String name = party.getMemberById(event.getMemberId()).getName(); if (name == null) { return; } clientThread.invoke(() -> { // If not interacting with any npcs currently, add to interacting list if (interactedNpcIds.isEmpty()) { addInteracting(event.getNpcId()); } // Otherwise we only add the count if it is against a npc we are already tracking if (interactedNpcIds.contains(event.getNpcId())) { updateCounter(event.getWeapon(), name, event.getHit()); } }); } private SpecialWeapon usedSpecialWeapon() { ItemContainer equipment = client.getItemContainer(InventoryID.EQUIPMENT); if (equipment == null) { return null; } Item[] items = equipment.getItems(); int weaponIdx = EquipmentInventorySlot.WEAPON.getSlotIdx(); if (items == null || weaponIdx >= items.length) { return null; } Item weapon = items[weaponIdx]; for (SpecialWeapon specialWeapon : SpecialWeapon.values()) { if (specialWeapon.getItemID() == weapon.getId()) { return specialWeapon; } } return null; } private void updateCounter(SpecialWeapon specialWeapon, String name, int hit) { SpecialCounter counter = specialCounter[specialWeapon.ordinal()]; if (counter == null) { counter = new SpecialCounter(itemManager.getImage(specialWeapon.getItemID()), this, hit, specialWeapon); infoBoxManager.addInfoBox(counter); specialCounter[specialWeapon.ordinal()] = counter; } else { counter.addHits(hit); } // If in a party, add hit to partySpecs for the infobox tooltip Map<String, Integer> partySpecs = counter.getPartySpecs(); if (!party.getMembers().isEmpty()) { if (partySpecs.containsKey(name)) { partySpecs.put(name, hit + partySpecs.get(name)); } else { partySpecs.put(name, hit); } } } private void removeCounters() { interactedNpcIds.clear(); for (int i = 0; i < specialCounter.length; ++i) { SpecialCounter counter = specialCounter[i]; if (counter != null) { infoBoxManager.removeInfoBox(counter); specialCounter[i] = null; } } } private int getHit(SpecialWeapon specialWeapon, Hitsplat hitsplat) { return specialWeapon.isDamage() ? hitsplat.getAmount() : 1; } }
package org.slc.sli.api.security.context.validator; import org.slc.sli.common.constants.EntityNames; import org.slc.sli.common.constants.ParameterConstants; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Set; @Component public class StudentToSubStudentValidator extends AbstractContextValidator { protected static final Set<String> SUB_STUDENT_ENTITIES = new HashSet<String>(Arrays.asList( EntityNames.ATTENDANCE, EntityNames.STUDENT_ACADEMIC_RECORD, EntityNames.STUDENT_ASSESSMENT, EntityNames.STUDENT_GRADEBOOK_ENTRY, EntityNames.GRADE, EntityNames.REPORT_CARD)); @Override public boolean canValidate(String entityType, boolean isTransitive) { return SUB_STUDENT_ENTITIES.contains(entityType) && isStudentOrParent(); } @Override public boolean validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(SUB_ENTITIES_OF_STUDENT, entityType, ids)) { return false; } // Get the Student IDs on the things we want to see, compare with the IDs of yourself Set<String> studentIds = new HashSet<String>(getIdsContainedInFieldOnEntities(entityType, new ArrayList<String>(ids), ParameterConstants.STUDENT_ID)); return getDirectStudentIds().containsAll(studentIds); } }
package org.slc.sli.ingestion.handler; import java.util.Arrays; import java.util.List; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.MessageSource; import org.springframework.dao.DuplicateKeyException; import org.slc.sli.domain.Entity; import org.slc.sli.domain.Repository; import org.slc.sli.ingestion.FileProcessStatus; import org.slc.sli.ingestion.transformation.SimpleEntity; import org.slc.sli.ingestion.util.spring.MessageSourceHelper; import org.slc.sli.ingestion.validation.ErrorReport; import org.slc.sli.validation.EntityValidationException; import org.slc.sli.validation.ValidationError; public class EntityPersistHandler extends AbstractIngestionHandler<SimpleEntity, Entity> implements InitializingBean { private Repository<Entity> entityRepository; private MessageSource messageSource; @Value("${sli.ingestion.mongotemplate.writeConcern}") private String writeConcern; @Override public void afterPropertiesSet() throws Exception { entityRepository.setWriteConcern(writeConcern); } Entity doHandling(SimpleEntity entity, ErrorReport errorReport) { return doHandling(entity, errorReport, null); } @Override protected Entity doHandling(SimpleEntity entity, ErrorReport errorReport, FileProcessStatus fileProcessStatus) { try { return persist(entity); } catch (EntityValidationException ex) { reportErrors(ex.getValidationErrors(), entity, errorReport); } catch (DuplicateKeyException ex) { reportErrors(ex.getRootCause().getMessage(), entity, errorReport); } return null; } /** * Persist entity in the data store. * * @param entity * Entity to be persisted * @return Persisted entity * @throws EntityValidationException * Validation Exception */ private Entity persist(SimpleEntity entity) throws EntityValidationException { String collectionName = entity.getType(); if ((String) entity.getBody().get("collectionName") != null) { collectionName = (String) entity.getBody().get("collectionName"); entity.getBody().remove("collectionName"); entity.setType(collectionName); } if (entity.getEntityId() != null) { if (!entityRepository.update(collectionName, entity)) { // TODO: exception should be replace with some logic. throw new RuntimeException("Record was not updated properly."); } return entity; } else { return entityRepository.create(entity.getType(), entity.getBody(), entity.getMetaData(), collectionName); } } private void reportErrors(List<ValidationError> errors, SimpleEntity entity, ErrorReport errorReport) { for (ValidationError err : errors) { String message = "ERROR: There has been a data validation error when saving an entity" + "\n" + " Error " + err.getType().name() + "\n" + " Entity " + entity.getType() + "\n" + " Field " + err.getFieldName() + "\n" + " Value " + err.getFieldValue() + "\n" + " Expected " + Arrays.toString(err.getExpectedTypes()) + "\n"; errorReport.error(message, this); } } /** * Generic error reporting function. * * @param errorMessage * Error message reported by entity. * @param entity * Entity reporting error. * @param errorReport * Reference to error report to log error message in. */ private void reportErrors(String errorMessage, SimpleEntity entity, ErrorReport errorReport) { String assembledMessage = "Entity (" + entity.getType() + ") reports failure: " + errorMessage; errorReport.error(assembledMessage, this); } protected String getFailureMessage(String code, Object... args) { return MessageSourceHelper.getMessage(messageSource, code, args); } public void setEntityRepository(Repository<Entity> entityRepository) { this.entityRepository = entityRepository; } public MessageSource getMessageSource() { return messageSource; } public void setMessageSource(MessageSource messageSource) { this.messageSource = messageSource; } }
package gov.nih.nci.security.authorization.attributeLevel; import gov.nih.nci.security.AuthorizationManager; import gov.nih.nci.security.util.FileLoader; import gov.nih.nci.security.util.StringUtilities; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheException; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; import org.hibernate.SessionFactory; import org.springframework.dao.DataRetrievalFailureException; public class UserClassAttributeMapCache { //private static HashMap cache = new HashMap(); private static Cache cache=null; private static void initializeCache() { URL url=null; FileLoader fileLoader = FileLoader.getInstance(); try { url = fileLoader.getFileAsURL("csm.ehcache.xml"); } catch (Exception e) { url = null; } CacheManager.create(url); cache = CacheManager.getInstance().getCache("gov.nih.nci.security.attributelevel.ClassAttributeMap"); } public static List getAttributeMap(String userName, String className) { if(cache==null) initializeCache(); List<String> strClassAttributeMapList=null; List<ClassAttributeMap> classAttributeMapList = (List<ClassAttributeMap>)getClassAttributeMapListFromCache(userName); if(null!=classAttributeMapList && !classAttributeMapList.isEmpty()) { strClassAttributeMapList = new ArrayList<String>(); Iterator it = classAttributeMapList.iterator(); while(it.hasNext()) { ClassAttributeMap classAttributeMap = (ClassAttributeMap)it.next(); if(null!= classAttributeMap.getAttributes() && !classAttributeMap.getAttributes().isEmpty()){ if(classAttributeMap.getClassName().equalsIgnoreCase(className) && classAttributeMap.getAttributes()!=null) strClassAttributeMapList.addAll(classAttributeMap.getAttributes()); } } } return strClassAttributeMapList; } @SuppressWarnings("unchecked") public static List getAttributeMapForGroup(String[] groupNames, String className) { List<String> classAttributeMapForGroups =new ArrayList<String>(); for(int i=0;i<groupNames.length;i++) { String groupName = groupNames[i]; if(!StringUtilities.isBlank(groupName)) { List<ClassAttributeMap> gcamList = (List<ClassAttributeMap>)getClassAttributeMapListFromCache(groupName); if(null!=gcamList && !gcamList.isEmpty()) { Iterator it = gcamList.iterator(); while(it.hasNext()) { ClassAttributeMap gcam = (ClassAttributeMap)it.next(); if(null!= gcam.getAttributes() && !gcam.getAttributes().isEmpty()) { if(gcam.getClassName().equalsIgnoreCase(className) && gcam.getAttributes()!=null) classAttributeMapForGroups.addAll(gcam.getAttributes()); } } } } } if(classAttributeMapForGroups.isEmpty()) return null; return classAttributeMapForGroups; } public static void setAttributeMap(String userName, SessionFactory sessionFactory, AuthorizationManager authorizationManager) { if(cache==null) initializeCache(); String privilegeName = "READ"; Map map = sessionFactory.getAllClassMetadata(); Set set = map.keySet(); ArrayList list = new ArrayList(set); List<ClassAttributeMap> classAttributeMapList = new ArrayList<ClassAttributeMap>(); Iterator iterator = list.iterator(); while (iterator.hasNext()) { String className = (String)iterator.next(); ClassAttributeMap classAttributeMap=null; if(!StringUtilities.isBlank(className)) { classAttributeMap = new ClassAttributeMap(className); } List attributeList = authorizationManager.getAttributeMap(userName, className, privilegeName); if (null!= attributeList && attributeList.size() != 0) { if(classAttributeMap!=null) { classAttributeMap.setAttributes(attributeList); } } if(classAttributeMap!=null) classAttributeMapList.add(classAttributeMap); } putClassAttributeMapInCache(userName,classAttributeMapList); } public static void setAttributeMapForGroup(String[] groupNames, SessionFactory sessionFactory, AuthorizationManager authorizationManager) { if(cache==null) initializeCache(); String privilegeName = "READ"; Map map = sessionFactory.getAllClassMetadata(); Set set = map.keySet(); ArrayList list = new ArrayList(set); for(int i=0;i<groupNames.length;i++) { List<ClassAttributeMap> classAttributeMapList = new ArrayList<ClassAttributeMap>(); String groupName = groupNames[i]; Iterator iterator = list.iterator(); while (iterator.hasNext()) { String className = (String)iterator.next(); ClassAttributeMap classAttributeMap=null; if(!StringUtilities.isBlank(className)) { classAttributeMap = new ClassAttributeMap(className); } List attributeList = authorizationManager.getAttributeMapForGroup(groupName, className, privilegeName); if (null!= attributeList && attributeList.size() != 0) { if(classAttributeMap!=null) { classAttributeMap.setAttributes(attributeList); } } if(classAttributeMap!=null) classAttributeMapList.add(classAttributeMap); } putClassAttributeMapInCache(groupName,classAttributeMapList); } } public static void removeAttributeMap(String userName) { cache.remove(userName); } private static List<ClassAttributeMap> getClassAttributeMapListFromCache(String userOrGroupName) { Element element = null; try { element = cache.get(userOrGroupName); } catch (CacheException cacheException) { throw new DataRetrievalFailureException("Cache failure: " + cacheException.getMessage()); } if (element == null) { return null; } else { return (List<ClassAttributeMap>) element.getValue(); } } private static void putClassAttributeMapInCache(String userOrGroupName, List<ClassAttributeMap> groupClassAttributeMapList) { ArrayList arrayList = new ArrayList(groupClassAttributeMapList); Element element = new Element(userOrGroupName, arrayList); cache.put(element); } }
package de.uni_tuebingen.ub.ixTheo.multiLanguageQuery; import java.io.IOException; import java.util.Iterator; import java.util.Set; import org.apache.lucene.index.Term; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.FilteredQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TermRangeQuery; import org.apache.solr.common.params.SolrParams; import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrException.ErrorCode; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.schema.IndexSchema; import org.apache.solr.search.LuceneQParser; import org.apache.solr.search.QParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.servlet.SolrRequestParsers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; public class MultiLanguageQueryParser extends QParser { protected String searchString; protected static Logger logger = LoggerFactory.getLogger(MultiLanguageQueryParser.class); protected String[] SUPPORTED_LANGUAGES = { "de", "en", "fr", "it", "es", "hant", "hans" }; protected SolrQueryRequest newRequest; protected ModifiableSolrParams newParams; public MultiLanguageQueryParser(final String searchString, final SolrParams localParams, final SolrParams params, final SolrQueryRequest request) throws MultiLanguageQueryParserException { super(searchString, localParams, params, request); this.searchString = searchString; newRequest = request; this.newParams = new ModifiableSolrParams(); this.newParams.add(params); IndexSchema schema = request.getSchema(); Boolean useDismax = false; String[] query = newParams.getParams("q"); String[] queryFields; // Check whether we have dismax or edismax String[] queryType = newParams.getParams("qt"); if (queryType != null) { queryFields = newParams.getParams("qf"); useDismax = true; } else { if (query.length != 1) throw new MultiLanguageQueryParserException("Only one q-parameter is supported"); final String[] separatedFields = query[0].split(":"); queryFields = separatedFields; } String[] facetFields = newParams.getParams("facet.field"); String lang = newParams.get("lang", "de"); // Strip language subcode lang = lang.split("-")[0]; // Set default language if we do not directly support the chosen // language lang = ArrayUtils.contains(SUPPORTED_LANGUAGES, lang) ? lang : "de"; // Handling for [e]dismax if (useDismax) handleDismaxParser(queryFields, lang, schema); // Support for Lucene parser else handleLuceneParser(query, request, lang, schema); // Handle Facet Fields if (facetFields != null && facetFields.length > 0) { for (String param : facetFields) { // Replace field used if it exists String newFieldName = param + "_" + lang; if (schema.getFieldOrNull(newFieldName) != null) { newParams.remove("facet.field", param); if (useDismax) newParams.add("facet.field", newFieldName); else { newParams.add("facet.field", "{!key=" + param + "}" + newFieldName); } } } } } protected void handleDismaxParser(String[] queryFields, String lang, IndexSchema schema) { StringBuilder stringBuilder = new StringBuilder(); for (final String param : queryFields) { newParams.remove("qf", param); String[] singleParams = param.split(" "); int i = 0; for (final String singleParam : singleParams) { String newFieldName = singleParam + "_" + lang; newFieldName = (schema.getFieldOrNull(newFieldName) != null) ? newFieldName : singleParam; stringBuilder.append(newFieldName); if (++i < singleParams.length) stringBuilder.append(" "); } } newParams.add("qf", stringBuilder.toString()); } protected void handleLuceneParser(String[] query, SolrQueryRequest request, String lang, IndexSchema schema) throws MultiLanguageQueryParserException { if (query.length == 1) { try { QParser tmpParser = new LuceneQParser(searchString, localParams, params, request); Query myQuery = tmpParser.getQuery(); myQuery = myQuery.rewrite(request.getSearcher().getIndexReader()); if (myQuery instanceof BooleanQuery) { Iterator<BooleanClause> boolIterator = ((BooleanQuery) myQuery).iterator(); BooleanQuery.Builder queryBuilder = new BooleanQuery.Builder(); while (boolIterator.hasNext()) { BooleanClause currentClause = boolIterator.next(); Query termQueryCandidate = currentClause.getQuery(); if (termQueryCandidate instanceof TermQuery){ TermQuery termQuery = (TermQuery) termQueryCandidate; String field = termQuery.getTerm().field(); String newFieldName = field + "_" + lang; if (schema.getFieldOrNull(newFieldName) != null) { termQueryCandidate = new TermQuery(new Term(newFieldName, "\"" + termQuery.getTerm().text() + "\"")); } else termQueryCandidate = new TermQuery(new Term(field, "\"" + termQuery.getTerm().text() + "\"")); } else logger.warn("No appropriate Query in BooleanClause"); queryBuilder.add(termQueryCandidate, currentClause.getOccur()); } myQuery = queryBuilder.build(); } else if (myQuery instanceof TermRangeQuery) { TermRangeQuery termRangeQuery = (TermRangeQuery) myQuery; String field = termRangeQuery.getField(); String newFieldName = field + "_" + lang; if (schema.getFieldOrNull(newFieldName) != null) { termRangeQuery = new TermRangeQuery(newFieldName, termRangeQuery.getLowerTerm(), termRangeQuery.getUpperTerm(), termRangeQuery.includesLower(), termRangeQuery.includesUpper()); myQuery = termRangeQuery; } } else if (myQuery instanceof TermQuery) { TermQuery termQuery = (TermQuery) myQuery; String field = termQuery.getTerm().field(); String newFieldName = field + "_" + lang; if (schema.getFieldOrNull(newFieldName) != null) { field = newFieldName; myQuery = new TermQuery(new Term(newFieldName, "\"" + termQuery.getTerm().text() + "\"")); } else myQuery = new TermQuery(new Term(field, "\"" + termQuery.getTerm().text() + "\"")); } else logger.warn("No rewrite rule did match for " + myQuery.getClass()); this.searchString = myQuery.toString(); newParams.set("q", this.searchString); } catch(SyntaxError|IOException e) { throw new SolrException(ErrorCode.SERVER_ERROR, "Rewriting Lucene support for new languages failed", e); } } else throw new MultiLanguageQueryParserException("Only one q-parameter is supported [1]"); } public Query parse() throws SyntaxError { this.newRequest.setParams(newParams); QParser parser = getParser(this.searchString, "edismax", this.newRequest); return parser.parse(); } }
package fi.metatavu.kuntaapi.server.integrations.ptv.updaters; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.time.OffsetDateTime; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.AccessTimeout; import javax.ejb.Singleton; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import org.apache.commons.lang3.EnumUtils; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.message.BasicNameValuePair; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import fi.metatavu.kuntaapi.server.discover.EntityDiscoverJob; import fi.metatavu.kuntaapi.server.id.OrganizationId; import fi.metatavu.kuntaapi.server.integrations.GenericHttpClient; import fi.metatavu.kuntaapi.server.integrations.GenericHttpClient.Response; import fi.metatavu.kuntaapi.server.integrations.GenericHttpClient.ResultType; import fi.metatavu.kuntaapi.server.integrations.ptv.PtvAuthStrategy; import fi.metatavu.kuntaapi.server.integrations.ptv.PtvConsts; import fi.metatavu.kuntaapi.server.integrations.ptv.tasks.AccessTokenTaskQueue; import fi.metatavu.kuntaapi.server.security.ExternalAccessTokenController; import fi.metatavu.kuntaapi.server.settings.OrganizationSettingController; import fi.metatavu.kuntaapi.server.settings.SystemSettingController; import fi.metatavu.kuntaapi.server.tasks.OrganizationEntityUpdateTask; @ApplicationScoped @Singleton @AccessTimeout (unit = TimeUnit.HOURS, value = 1l) @SuppressWarnings ("squid:S3306") public class PtvAccessTokenDiscoverJob extends EntityDiscoverJob<OrganizationEntityUpdateTask> { private static final long TOKEN_EXPIRE_MAX_TIME = 60l * 60 * 24; @Inject private Logger logger; @Inject private ExternalAccessTokenController externalAccessTokenController; @Inject private SystemSettingController systemSettingController; @Inject private AccessTokenTaskQueue accessTokenTaskQueue; @Inject private OrganizationSettingController organizationSettingController; @Inject private GenericHttpClient genericHttpClient; @Override public String getName() { return "PTV.accessToken"; } @Override public void execute(OrganizationEntityUpdateTask task) { refreshAccessToken(task.getOrganizationId()); } @Override public void timeout() { if (systemSettingController.isNotTestingOrTestRunning()) { OrganizationEntityUpdateTask task = accessTokenTaskQueue.next(); if (task != null) { execute(task); } else { if (accessTokenTaskQueue.isEmptyAndLocalNodeResponsible()) { accessTokenTaskQueue.enqueueTasks(organizationSettingController.listOrganizationIdsWithSetting(PtvConsts.ORGANIZATION_SETTING_API_PASS)); } } } } @SuppressWarnings ("squid:S2068") private void refreshAccessToken(OrganizationId kuntaApiOrganizationId) { OffsetDateTime expires = externalAccessTokenController.getOrganizationExternalAccessTokenExpires(kuntaApiOrganizationId, PtvConsts.PTV_ACCESS_TOKEN_TYPE); OffsetDateTime refreshTime = OffsetDateTime.now().plusHours(6); if (expires != null && !refreshTime.isAfter(expires)) { return; } String baseUrl = systemSettingController.getSettingValue(PtvConsts.SYSTEM_SETTING_STS_BASEURL); String apiUser = organizationSettingController.getSettingValue(kuntaApiOrganizationId, PtvConsts.ORGANIZATION_SETTING_API_USER); String apiPass = organizationSettingController.getSettingValue(kuntaApiOrganizationId, PtvConsts.ORGANIZATION_SETTING_API_PASS); PtvAuthStrategy authStrategy = EnumUtils.getEnum(PtvAuthStrategy.class, systemSettingController.getSettingValue(PtvConsts.SYSTEM_SETTING_AUTH_STRATEGY)); if (authStrategy == null) { authStrategy = PtvAuthStrategy.FORM; } switch (authStrategy) { case FORM: refreshFormAccessToken(kuntaApiOrganizationId,baseUrl, apiUser, apiPass); break; case JSON: refreshJsonAccessToken(kuntaApiOrganizationId,baseUrl, apiUser, apiPass); break; default: if (logger.isLoggable(Level.SEVERE)) { logger.log(Level.SEVERE, String.format("Unknown auth strategy: %s", authStrategy)); } break; } } private void refreshJsonAccessToken(OrganizationId kuntaApiOrganizationId, String baseUrl, String apiUser, String apiPass) { Map<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/json"); URI uri = null; try { uri = new URI(String.format("%s/api/auth/api-login", baseUrl)); } catch (URISyntaxException e) { logger.log(Level.SEVERE, "Failed to construct PTV access token url", e); return; } PtvJsonTokenRequest tokenRequest = new PtvJsonTokenRequest(); tokenRequest.setPassword(apiPass); tokenRequest.setUsername(apiUser); ResultType<PtvJsonAccessToken> resultType = new GenericHttpClient.ResultType<PtvJsonAccessToken>() {}; Response<PtvJsonAccessToken> response = genericHttpClient.doPOSTRequest(uri, resultType, headers, tokenRequest); if (response.isOk()) { PtvJsonAccessToken accessToken = response.getResponseEntity(); Long expiresIn = TOKEN_EXPIRE_MAX_TIME; OffsetDateTime tokenExpires = OffsetDateTime.now().plusSeconds(expiresIn); externalAccessTokenController.setOrganizationExternalAccessToken(kuntaApiOrganizationId, PtvConsts.PTV_ACCESS_TOKEN_TYPE, accessToken.getAccessToken(), tokenExpires); } else { logger.log(Level.SEVERE, () -> String.format("Failed to refresh PTV access token for organization %s: [%d]: %s", kuntaApiOrganizationId, response.getStatus(), response.getMessage())); } } private void refreshFormAccessToken(OrganizationId kuntaApiOrganizationId, String baseUrl, String apiUser, String apiPass) { Map<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/x-www-form-urlencoded"); URI uri = null; try { uri = new URI(String.format("%s/connect/token", baseUrl)); } catch (URISyntaxException e) { logger.log(Level.SEVERE, "Failed to construct PTV access token url", e); return; } try { UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(Arrays.asList( new BasicNameValuePair("grant_type", "password"), new BasicNameValuePair("scope", "dataEventRecords openid"), new BasicNameValuePair("client_id", "ptv_api_client"), new BasicNameValuePair("client_secret", "openapi"), new BasicNameValuePair("username", apiUser), new BasicNameValuePair("password", apiPass) )); ResultType<PtvFormAccessToken> resultType = new GenericHttpClient.ResultType<PtvFormAccessToken>() {}; Response<PtvFormAccessToken> response = genericHttpClient.doPOSTRequest(uri, resultType, headers, formEntity); if (response.isOk()) { PtvFormAccessToken accessToken = response.getResponseEntity(); OffsetDateTime tokenExpires = accessToken.getExpiration(); OffsetDateTime maxExpire = OffsetDateTime.now().plusSeconds(TOKEN_EXPIRE_MAX_TIME); if (tokenExpires == null) { Long expiresIn = accessToken.getExpiresIn(); if (expiresIn != null) { tokenExpires = OffsetDateTime.now().plusSeconds(expiresIn); } } if (tokenExpires == null || tokenExpires.isAfter(maxExpire)) { tokenExpires = maxExpire; } externalAccessTokenController.setOrganizationExternalAccessToken(kuntaApiOrganizationId, PtvConsts.PTV_ACCESS_TOKEN_TYPE, accessToken.getAccessToken(), tokenExpires); } else { logger.log(Level.SEVERE, () -> String.format("Failed to refresh PTV access token for organization %s: [%d]: %s", kuntaApiOrganizationId, response.getStatus(), response.getMessage())); } } catch (UnsupportedEncodingException e) { logger.log(Level.SEVERE, "Failed to construct PTV access token body", e); } } public static class PtvJsonTokenRequest { private String username; private String password; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } } @JsonIgnoreProperties (ignoreUnknown = true) public static class PtvJsonAccessToken { @JsonProperty (value = "ptvToken") private String accessToken; public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } } @JsonIgnoreProperties (ignoreUnknown = true) public static class PtvFormAccessToken { @JsonProperty (value = "access_token") private String accessToken; @JsonProperty (value = "expiration") private OffsetDateTime expiration; @JsonProperty (value = "expires_in") private Long expiresIn; @JsonProperty (value = "token_type") private String tokenType; public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public Long getExpiresIn() { return expiresIn; } public void setExpiresIn(Long expiresIn) { this.expiresIn = expiresIn; } public String getTokenType() { return tokenType; } public void setTokenType(String tokenType) { this.tokenType = tokenType; } public OffsetDateTime getExpiration() { return expiration; } public void setExpiration(OffsetDateTime expiration) { this.expiration = expiration; } } }
package giraudsa.marshall.strategie; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.util.Collection; import java.util.Map; import giraudsa.marshall.annotations.TypeRelation; import utils.champ.FieldInformations; public class StrategieParCompositionOuAgregationEtClasseConcrete extends StrategieDeSerialisation { public StrategieParCompositionOuAgregationEtClasseConcrete() { } @Override public boolean serialiseTout(int profondeur, FieldInformations fieldInformation) { Class<?> type = fieldInformation.getValueType(); if(type.isArray()) type = type.getComponentType(); else if(Collection.class.isAssignableFrom(type)){ type = Object.class; Type[] types = fieldInformation.getParametreType(); if(types != null && types.length > 0) type = (Class<?>) types[0]; }else if(Map.class.isAssignableFrom(type)) type = Object.class; boolean isConcrete = !Modifier.isAbstract(fieldInformation.getValueType().getModifiers()); return fieldInformation.getRelation() == TypeRelation.COMPOSITION || (fieldInformation.getRelation() == TypeRelation.AGGREGATION && isConcrete); } }
package org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.set; import java.util.HashMap; import java.util.concurrent.BlockingQueue; import org.apache.bcel.generic.ACONST_NULL; import org.apache.log4j.Logger; import org.buddycloud.channelserver.channel.ChannelManager; import org.buddycloud.channelserver.channel.Conf; import org.buddycloud.channelserver.channel.node.configuration.NodeConfigurationException; import org.buddycloud.channelserver.channel.node.configuration.field.Owner; import org.buddycloud.channelserver.db.exception.NodeStoreException; import org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.JabberPubsub; import org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.PubSubElementProcessorAbstract; import org.dom4j.Element; import org.dom4j.Namespace; import org.dom4j.dom.DOMElement; import org.xmpp.packet.IQ; import org.xmpp.packet.JID; import org.xmpp.packet.Packet; import org.xmpp.packet.PacketError; public class NodeCreate extends PubSubElementProcessorAbstract { private static final String NODE_REG_EX = "^/user/[^@]+@[^/]+/[^/]+$"; private static final String INVALID_NODE_CONFIGURATION = "Invalid node configuration"; private static final Logger LOGGER = Logger.getLogger(NodeCreate.class); public NodeCreate(BlockingQueue<Packet> outQueue, ChannelManager channelManager) { setChannelManager(channelManager); setOutQueue(outQueue); } public void process(Element elm, JID actorJID, IQ reqIQ, Element rsm) throws Exception { element = elm; response = IQ.createResultIQ(reqIQ); request = reqIQ; actor = actorJID; node = element.attributeValue("node"); if (null == actorJID) { actor = request.getFrom(); } if (false == channelManager.isLocalNode(node)) { makeRemoteRequest(); return; } if ((false == validateNode()) || (true == doesNodeExist()) || (false == actorIsRegistered()) || (false == nodeHandledByThisServer())) { outQueue.put(response); return; } createNode(); } private void createNode() throws InterruptedException { try { channelManager.createNode(actor, node, getNodeConfiguration()); } catch (NodeStoreException e) { logger.error(e); setErrorCondition(PacketError.Type.wait, PacketError.Condition.internal_server_error); outQueue.put(response); return; } catch (NodeConfigurationException e) { logger.error(e); setErrorCondition(PacketError.Type.modify, PacketError.Condition.bad_request); outQueue.put(response); return; } response.setType(IQ.Type.result); outQueue.put(response); } public boolean accept(Element elm) { return elm.getName().equals("create"); } private HashMap<String, String> getNodeConfiguration() { getNodeConfigurationHelper().parse(request); if (false == getNodeConfigurationHelper().isValid()) { throw new NodeConfigurationException(INVALID_NODE_CONFIGURATION); } HashMap<String, String> defConfiguration = Conf.getDefaultChannelConf( new JID(node.split("/")[2]), actor); HashMap<String, String> configuration = getNodeConfigurationHelper() .getValues(); configuration.put(Owner.FIELD_NAME, actor.toBareJID()); defConfiguration.putAll(configuration); return defConfiguration; } private boolean validateNode() { if ((node != null) && !node.trim().equals("")) { return true; } response.setType(IQ.Type.error); Element nodeIdRequired = new DOMElement("nodeid-required", new Namespace("", JabberPubsub.NS_PUBSUB_ERROR)); Element badRequest = new DOMElement( PacketError.Condition.bad_request.toXMPP(), new Namespace("", JabberPubsub.NS_XMPP_STANZAS)); Element error = new DOMElement("error"); error.addAttribute("type", "modify"); error.add(badRequest); error.add(nodeIdRequired); response.setChildElement(error); return false; } private boolean doesNodeExist() throws NodeStoreException { if (false == channelManager.nodeExists(node)) { return false; } setErrorCondition(PacketError.Type.cancel, PacketError.Condition.conflict); return true; } private boolean actorIsRegistered() { if (true == actor.getDomain().equals(getServerDomain())) { return true; } setErrorCondition(PacketError.Type.auth, PacketError.Condition.forbidden); return false; } private boolean nodeHandledByThisServer() { if (false == node.matches(NODE_REG_EX)) { setErrorCondition(PacketError.Type.modify, PacketError.Condition.bad_request); return false; } if ((false == node.contains("@" + getServerDomain())) && (false == node.contains("@" + getTopicsDomain()))) { setErrorCondition(PacketError.Type.modify, PacketError.Condition.not_acceptable); return false; } return true; } private void makeRemoteRequest() throws InterruptedException { request.setTo(new JID(node.split("/")[2]).getDomain()); Element actor = request.getElement() .element("pubsub") .addElement("actor", JabberPubsub.NS_BUDDYCLOUD); actor.addText(request.getFrom().toBareJID()); outQueue.put(request); } }
package com.akiban.server.service.security; import com.akiban.rest.RestService; import com.akiban.rest.RestServiceImpl; import com.akiban.server.service.servicemanager.GuicedServiceManager; import com.akiban.server.test.it.ITBase; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import java.io.IOException; import java.net.Authenticator; import java.net.PasswordAuthentication; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class SecurityServiceIT extends ITBase { @Override protected GuicedServiceManager.BindingsConfigurationProvider serviceBindingsProvider() { return super.serviceBindingsProvider() .bindAndRequire(SecurityService.class, SecurityServiceImpl.class) .bindAndRequire(RestService.class, RestServiceImpl.class); } @Override protected Map<String, String> startupConfigProperties() { Map<String, String> properties = new HashMap<String, String>(); properties.put("akserver.http.login", "basic"); // "digest" properties.put("akserver.postgres.login", "md5"); return properties; } protected SecurityService securityService() { return serviceManager().getServiceByClass(SecurityService.class); } protected String authUser, authPass; @Before public void setUp() { SecurityService securityService = securityService(); securityService.addRole("rest-user"); securityService.addRole("admin"); securityService.addUser("user1", "password", Arrays.asList("rest-user")); Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { if (authUser == null) return null; return new PasswordAuthentication(authUser, authPass.toCharArray()); } }); } @After public void cleanUp() { securityService().clearAll(); Authenticator.setDefault(null); } @Test public void getUser() { SecurityService securityService = securityService(); User user = securityService.getUser("user1"); assertNotNull("user found", user); assertTrue("user has role", user.hasRole("rest-user")); assertFalse("user does not have role", user.hasRole("admin")); } @Test public void authenticate() { assertEquals("user1", securityService().authenticate("user1", "password").getName()); } private void openRestURL() throws Exception { int port = serviceManager().getServiceByClass(com.akiban.http.HttpConductor.class).getPort(); String context = serviceManager().getServiceByClass(com.akiban.rest.RestService.class).getContextPath(); String request = "/security_schema.roles/1"; URL url = new URL("http", "localhost", port, context + request); url.openConnection().getInputStream().close(); } @Test(expected = IOException.class) public void restUnauthenticated() throws Exception { openRestURL(); } @Test public void restAuthenticated() throws Exception { authUser = "user1"; authPass = "password"; openRestURL(); } @Test public void restAuthenticateBadUser() throws Exception { authUser = "user2"; authPass = "none"; openRestURL(); } @Test public void restAuthenticateBadPassword() throws Exception { authUser = "user1"; authPass = "wrong"; openRestURL(); } private void openPostgresConnection(String user, String password) throws Exception { int port = serviceManager().getServiceByClass(com.akiban.sql.pg.PostgresService.class).getPort(); Class.forName("org.postgresql.Driver"); String url = String.format("jdbc:postgresql://localhost:%d/akiban", port); Connection connection = DriverManager.getConnection(url, user, password); connection.close(); } @Test(expected = SQLException.class) public void postgresUnauthenticated() throws Exception { openPostgresConnection(null, null); } @Test public void postgresAuthenticated() throws Exception { openPostgresConnection("user1", "password"); } @Test public void postgresBadUser() throws Exception { openPostgresConnection("user2", "whatever"); } @Test public void postgresBadPassword() throws Exception { openPostgresConnection("user1", "nope"); } }
package com.celements.web.plugin.cmd; import static org.easymock.EasyMock.*; import static org.junit.Assert.*; import java.security.Principal; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.junit.Before; import org.junit.Test; import com.celements.common.test.AbstractBridgedComponentTestCase; import com.celements.web.plugin.CelementsWebPlugin; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.api.User; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.user.api.XWikiAuthService; import com.xpn.xwiki.web.XWikiMessageTool; import com.xpn.xwiki.web.XWikiRequest; public class RemoteUserValidatorTest extends AbstractBridgedComponentTestCase { RemoteUserValidator cmd; XWikiContext context; @Before public void setUp_RemoteUserValidatorTest() throws Exception { cmd = new RemoteUserValidator(); context = getContext(); expect(getWikiMock().isVirtualMode()).andReturn(true).anyTimes(); } @Test public void testIsValidUserJSON_validationNotAllowed() { XWikiRequest request = createMock(XWikiRequest.class); context.setRequest(request); HttpServletRequest httpRequest = createMock(HttpServletRequest.class); expect(request.getHttpServletRequest()).andReturn(httpRequest).once(); expect(httpRequest.getRemoteHost()).andReturn(" "); replay(httpRequest, request); assertEquals("{\"access\" : \"false\", \"error\" : \"access_denied\"}", cmd.isValidUserJSON("", "", "", null, context)); verify(httpRequest, request); } @Test public void testIsValidUserJSON_principalNull() throws XWikiException { XWikiRequest request = createMock(XWikiRequest.class); context.setRequest(request); HttpServletRequest httpRequest = createMock(HttpServletRequest.class); expect(request.getHttpServletRequest()).andReturn(httpRequest).once(); expect(httpRequest.getRemoteHost()).andReturn(" "); XWiki wiki = new XWiki(); context.setWiki(wiki); CelementsWebPlugin celementsweb = createMock(CelementsWebPlugin.class); cmd.injectCelementsWeb(celementsweb); expect(celementsweb.getUsernameForUserData(eq("blabla@mail.com"), eq("loginname"), same(context))).andReturn("").once(); replay(celementsweb, httpRequest, request); // important only call setUser after replayDefault. In unstable-2.0 branch setUser // calls xwiki.isVirtualMode context.setUser("xwiki:XWiki.superadmin"); assertEquals("{\"access\" : \"false\", \"error\" : \"wrong_username_password\"}", cmd.isValidUserJSON("blabla@mail.com", "", "", null, context)); verify(celementsweb, httpRequest, request); } @Test public void testIsValidUserJSON_validUser_wrongGroup() throws XWikiException { XWikiRequest request = createMock(XWikiRequest.class); context.setRequest(request); HttpServletRequest httpRequest = createMock(HttpServletRequest.class); expect(request.getHttpServletRequest()).andReturn(httpRequest).once(); expect(httpRequest.getRemoteHost()).andReturn(" "); XWiki xwiki = getWikiMock(); context.setWiki(xwiki); XWikiAuthService auth = createMock(XWikiAuthService.class); expect(xwiki.getAuthService()).andReturn(auth).once(); Principal principal = createMock(Principal.class); expect(auth.authenticate(eq("XWiki.7sh2lya35"), eq("pwd"), same(context))) .andReturn(principal).once(); expect(principal.getName()).andReturn("XWiki.7sh2lya35").anyTimes(); User user = createMock(User.class); expect(xwiki.getUser(eq("XWiki.7sh2lya35"), same(context))).andReturn(user).once(); expect(user.isUserInGroup(eq("grp"))).andReturn(false); expect(xwiki.getXWikiPreference(eq("cellogin"), eq("loginname"), same(context)) ).andReturn("email,loginname").once(); CelementsWebPlugin celementsweb = createMock(CelementsWebPlugin.class); cmd.injectCelementsWeb(celementsweb); expect(celementsweb.getUsernameForUserData(eq("blabla@mail.com"), eq("email,loginname"), same(context))).andReturn("XWiki.7sh2lya35").once(); replay(auth, celementsweb, httpRequest, principal, request, user, xwiki); // important only call setUser after replayDefault. In unstable-2.0 branch setUser // calls xwiki.isVirtualMode context.setUser("xwiki:XWiki.superadmin"); assertEquals("{\"access\" : \"false\", \"error\" : \"user_not_in_group\"}", cmd.isValidUserJSON("blabla@mail.com", "pwd", "grp", null, context)); verify(auth, celementsweb, httpRequest, principal, request, user, xwiki); } @Test public void testIsValidUserJSON_validUser_isInGroup_inactiveUser() throws XWikiException { XWikiRequest request = createMock(XWikiRequest.class); context.setRequest(request); HttpServletRequest httpRequest = createMock(HttpServletRequest.class); expect(request.getHttpServletRequest()).andReturn(httpRequest).once(); expect(httpRequest.getRemoteHost()).andReturn(" "); XWiki xwiki = getWikiMock(); context.setWiki(xwiki); XWikiAuthService auth = createMock(XWikiAuthService.class); expect(xwiki.getAuthService()).andReturn(auth).once(); Principal principal = createMock(Principal.class); expect(auth.authenticate(eq("XWiki.7sh2lya35"), eq("pwd"), same(context))).andReturn(principal).once(); expect(principal.getName()).andReturn("XWiki.7sh2lya35").anyTimes(); User user = createMock(User.class); expect(xwiki.getUser(eq("XWiki.7sh2lya35"), same(context))).andReturn(user).once(); expect(xwiki.getXWikiPreference(eq("auth_active_check"), same(context))) .andReturn("1").atLeastOnce(); XWikiDocument doc = createMock(XWikiDocument.class); expect(xwiki.getDocument(eq("XWiki.7sh2lya35"), same(context))).andReturn(doc).once(); expect(doc.getIntValue(eq("XWiki.XWikiUsers"), eq("active"))).andReturn(0).once(); expect(user.isUserInGroup(eq("grp"))).andReturn(true); expect(xwiki.getXWikiPreference(eq("cellogin"), eq("loginname"), same(context))) .andReturn("email,loginname").once(); CelementsWebPlugin celementsweb = createMock(CelementsWebPlugin.class); cmd.injectCelementsWeb(celementsweb); expect(celementsweb.getUsernameForUserData(eq("blabla@mail.com"), eq("email,loginname"), same(context))).andReturn("XWiki.7sh2lya35").once(); replay(auth, celementsweb, doc, httpRequest, principal, request, user, xwiki); // important only call setUser after replayDefault. In unstable-2.0 branch setUser // calls xwiki.isVirtualMode context.setUser("xwiki:XWiki.superadmin"); assertEquals("{\"access\" : \"false\", \"error\" : \"useraccount_inactive\"}", cmd.isValidUserJSON("blabla@mail.com", "pwd", "grp", null, context)); verify(auth, celementsweb, doc, httpRequest, principal, request, user, xwiki); } @Test public void testIsValidUserJSON_validUser_isInGroup_noRetGroup() throws XWikiException { XWikiRequest request = createMock(XWikiRequest.class); context.setRequest(request); HttpServletRequest httpRequest = createMock(HttpServletRequest.class); expect(request.getHttpServletRequest()).andReturn(httpRequest).once(); expect(httpRequest.getRemoteHost()).andReturn(" "); XWiki xwiki = getWikiMock(); context.setWiki(xwiki); XWikiAuthService auth = createMock(XWikiAuthService.class); expect(xwiki.getAuthService()).andReturn(auth).once(); Principal principal = createMock(Principal.class); expect(auth.authenticate(eq("XWiki.7sh2lya35"), eq("pwd"), same(context))) .andReturn(principal).once(); expect(principal.getName()).andReturn("XWiki.7sh2lya35").anyTimes(); User user = createMock(User.class); expect(xwiki.getUser(eq("XWiki.7sh2lya35"), same(context))).andReturn(user).once(); expect(xwiki.getXWikiPreference(eq("auth_active_check"), same(context))) .andReturn("1").atLeastOnce(); XWikiDocument doc = createMock(XWikiDocument.class); expect(xwiki.getDocument(eq("XWiki.7sh2lya35"), same(context))).andReturn(doc).once(); expect(doc.getIntValue(eq("XWiki.XWikiUsers"), eq("active"))).andReturn(1).once(); expect(user.isUserInGroup(eq("grp"))).andReturn(true); expect(xwiki.getXWikiPreference(eq("cellogin"), eq("loginname"), same(context))) .andReturn("email,loginname").once(); CelementsWebPlugin celementsweb = createMock(CelementsWebPlugin.class); cmd.injectCelementsWeb(celementsweb); expect(celementsweb.getUsernameForUserData(eq("blabla@mail.com"), eq("email,loginname"), same(context))).andReturn("XWiki.7sh2lya35").once(); replay(auth, celementsweb, doc, httpRequest, principal, request, user, xwiki); // important only call setUser after replayDefault. In unstable-2.0 branch setUser // calls xwiki.isVirtualMode context.setUser("xwiki:XWiki.superadmin"); assertEquals("{\"access\" : \"true\", \"username\" : \"blabla@mail.com\", " + "\"group_membership\" : {}}", cmd.isValidUserJSON("blabla@mail.com", "pwd", "grp", null, context)); verify(auth, celementsweb, doc, httpRequest, principal, request, user, xwiki); } @Test public void testIsValidUserJSON_validUser_isInGroup_retGroup() throws XWikiException { XWikiContext context = createMock(XWikiContext.class); expect(context.getUser()).andReturn("xwiki:XWiki.superadmin").anyTimes(); XWikiRequest request = createMock(XWikiRequest.class); expect(context.getRequest()).andReturn(request).anyTimes(); HttpServletRequest httpRequest = createMock(HttpServletRequest.class); expect(request.getHttpServletRequest()).andReturn(httpRequest).once(); expect(httpRequest.getRemoteHost()).andReturn(" "); XWiki xwiki = getWikiMock(); expect(context.getWiki()).andReturn(xwiki).anyTimes(); XWikiAuthService auth = createMock(XWikiAuthService.class); expect(xwiki.getAuthService()).andReturn(auth).once(); Principal principal = createMock(Principal.class); expect(auth.authenticate(eq("XWiki.7sh2lya35"), eq("pwd"), same(context))) .andReturn(principal).once(); expect(principal.getName()).andReturn("XWiki.7sh2lya35").anyTimes(); User user = createMock(User.class); expect(xwiki.getUser(eq("XWiki.7sh2lya35"), same(context))).andReturn(user) .anyTimes(); expect(xwiki.getXWikiPreference(eq("auth_active_check"), same(context))) .andReturn("1").atLeastOnce(); XWikiDocument doc = createMock(XWikiDocument.class); expect(xwiki.getDocument(eq("XWiki.7sh2lya35"), same(context))).andReturn(doc).once(); expect(doc.getIntValue(eq("XWiki.XWikiUsers"), eq("active"))).andReturn(1).once(); expect(user.isUserInGroup(eq("XWiki.MemOfGroup"))).andReturn(true).anyTimes(); expect(user.isUserInGroup(eq("XWiki.TestGroup1"))).andReturn(true).anyTimes(); expect(user.isUserInGroup(eq("XWiki.TestGroup2"))).andReturn(false).anyTimes(); expect(user.isUserInGroup(eq("XWiki.TestGroup3"))).andReturn(true).anyTimes(); expect(xwiki.getXWikiPreference(eq("cellogin"), eq("loginname"), same(context))) .andReturn("email,loginname").anyTimes(); CelementsWebPlugin celementsweb = createMock(CelementsWebPlugin.class); cmd.injectCelementsWeb(celementsweb); expect(celementsweb.getUsernameForUserData(eq("blabla@mail.com"), eq("email,loginname"), same(context))).andReturn("XWiki.7sh2lya35").anyTimes(); List<String> retGroup = new ArrayList<String>(); retGroup.add("XWiki.TestGroup1"); retGroup.add("XWiki.TestGroup2"); retGroup.add("XWiki.TestGroup3"); XWikiMessageTool messageTool = createMock(XWikiMessageTool.class); expect(context.getMessageTool()).andReturn(messageTool).anyTimes(); expect(messageTool.get(eq("cel_groupname_TestGroup1"))).andReturn("grp1").anyTimes(); expect(messageTool.get(eq("cel_groupname_TestGroup2"))).andReturn("grp2").anyTimes(); expect(messageTool.get(eq("cel_groupname_TestGroup3"))).andReturn("grp3").anyTimes(); replay(auth, celementsweb, context, doc, httpRequest, messageTool, principal, request, user, xwiki); assertEquals("{\"access\" : \"true\", \"username\" : \"blabla@mail.com\", " + "\"group_membership\" : {\"grp1\" : \"true\", \"grp2\"" + " : \"false\", \"grp3\" : \"true\"}}", cmd.isValidUserJSON( "blabla@mail.com", "pwd", "XWiki.MemOfGroup", retGroup, context)); verify(auth, celementsweb, context, doc, httpRequest, messageTool, principal, request, user, xwiki); } @Test public void testIsGroupMember_null() { assertEquals("false", cmd.isGroupMember("blabla@mail.com", null, context)); } @Test public void testIsGroupMember_blackListOtherDB() { assertEquals("false", cmd.isGroupMember("blabla@mail.com", "xwiki:XWiki.Admin", context)); } @Test public void testIsGroupMember_blackListAllGroup() { assertEquals("false", cmd.isGroupMember("blabla@mail.com", "XWiki.XWikiAllGroup", context)); } @Test public void testIsGroupMember_notInGroup() throws XWikiException { XWiki xwiki = getWikiMock(); context.setWiki(xwiki); CelementsWebPlugin celementsweb = createMock(CelementsWebPlugin.class); cmd.injectCelementsWeb(celementsweb); expect(xwiki.getXWikiPreference(eq("cellogin"), eq("loginname"), same(context))) .andReturn("email,loginname").once(); expect(celementsweb.getUsernameForUserData(eq("blabla@mail.com"), eq("email,loginname"), same(context))).andReturn("XWiki.7sh2lya35").once(); User user = createMock(User.class); expect(xwiki.getUser(eq("XWiki.7sh2lya35"), same(context))).andReturn(user).once(); expect(user.isUserInGroup(eq("XWiki.TestGroup"))).andReturn(false).once(); replay(celementsweb, user, xwiki); assertEquals("false", cmd.isGroupMember("blabla@mail.com", "XWiki.TestGroup", context)); verify(celementsweb, user, xwiki); } @Test public void testIsGroupMember_inGroup() throws XWikiException { XWiki xwiki = getWikiMock(); context.setWiki(xwiki); CelementsWebPlugin celementsweb = createMock(CelementsWebPlugin.class); cmd.injectCelementsWeb(celementsweb); expect(xwiki.getXWikiPreference(eq("cellogin"), eq("loginname"), same(context))) .andReturn("email,loginname").once(); expect(celementsweb.getUsernameForUserData(eq("blabla@mail.com"), eq("email,loginname"), same(context))).andReturn("XWiki.7sh2lya35").once(); User user = createMock(User.class); expect(xwiki.getUser(eq("XWiki.7sh2lya35"), same(context))).andReturn(user).once(); expect(user.isUserInGroup(eq("XWiki.TestGroup"))).andReturn(true).once(); replay(celementsweb, user, xwiki); assertEquals("true", cmd.isGroupMember("blabla@mail.com", "XWiki.TestGroup", context)); verify(celementsweb, user, xwiki); } @Test public void testGetResultJSON() { assertEquals("{\"access\" : \"false\", \"error\" : \"access_denied\"}", cmd.getResultJSON(null, false, "access_denied", null, context)); assertEquals("{\"access\" : \"false\", \"error\" : \"access_denied\"}", cmd.getResultJSON(null, true, "access_denied", null, context)); assertEquals("{\"access\" : \"false\", \"error\" : \"access_denied\"}", cmd.getResultJSON("", true, "access_denied", null, context)); assertEquals("{\"access\" : \"false\", \"error\" : \"access_denied\"}", cmd.getResultJSON("haXX0r", true, "access_denied", null, context)); assertEquals("{\"access\" : \"false\", \"error\" : \"wrong_group\"}", cmd.getResultJSON("user@synventis.com", false, "wrong_group", null, context)); assertEquals("{\"access\" : \"true\", \"username\" : \"user@synventis.com\", " + "\"group_membership\" : {}}", cmd.getResultJSON("user@synventis.com", true, "", null, context)); assertEquals("{\"access\" : \"true\", \"username\" : \"user@synventis.com\", " + "\"group_membership\" : {}}", cmd.getResultJSON("user@synventis.com", true, null, null, context)); } @Test public void testGetResultJSON_withReturnGroups() throws XWikiException { XWikiContext context = createMock(XWikiContext.class); XWiki xwiki = getWikiMock(); expect(context.getWiki()).andReturn(xwiki).anyTimes(); CelementsWebPlugin celementsweb = createMock(CelementsWebPlugin.class); cmd.injectCelementsWeb(celementsweb); expect(xwiki.getXWikiPreference(eq("cellogin"), eq("loginname"), same(context))) .andReturn("email,loginname").atLeastOnce(); expect(celementsweb.getUsernameForUserData(eq("user@synventis.com"), eq("email,loginname"), same(context))).andReturn("XWiki.7sh2lya35").atLeastOnce(); User user = createMock(User.class); expect(xwiki.getUser(eq("XWiki.7sh2lya35"), same(context))).andReturn(user) .atLeastOnce(); expect(user.isUserInGroup(eq("XWiki.TestGroup1"))).andReturn(true).atLeastOnce(); expect(user.isUserInGroup(eq("XWiki.TestGroup2"))).andReturn(false).atLeastOnce(); List<String> returnGroups = new ArrayList<String>(); returnGroups.add("XWiki.TestGroup1"); XWikiMessageTool messageTool = createMock(XWikiMessageTool.class); expect(context.getMessageTool()).andReturn(messageTool).anyTimes(); expect(messageTool.get(eq("cel_groupname_TestGroup1"))).andReturn("grp1").anyTimes(); expect(messageTool.get(eq("cel_groupname_TestGroup2"))).andReturn("grp2").anyTimes(); replay(celementsweb, context, messageTool, user, xwiki); assertEquals("{\"access\" : \"true\", \"username\" : \"user@synventis.com\", " + "\"group_membership\" : {\"grp1\" : \"true\"}}", cmd.getResultJSON("user@synventis.com", true, null, returnGroups, context)); returnGroups.add("XWiki.TestGroup2"); assertEquals("{\"access\" : \"true\", \"username\" : \"user@synventis.com\", " + "\"group_membership\" : {\"grp1\" : \"true\", \"grp2\" : \"false\"}}", cmd.getResultJSON("user@synventis.com", true, null, returnGroups, context)); verify(celementsweb, context, messageTool, user, xwiki); } @Test public void testValidationAllowed_superadmin() { XWikiRequest request = createMock(XWikiRequest.class); context.setRequest(request); HttpServletRequest httpRequest = createMock(HttpServletRequest.class); expect(request.getHttpServletRequest()).andReturn(httpRequest).once(); expect(httpRequest.getRemoteHost()).andReturn(" "); replay(httpRequest, request); // important only call setUser after replayDefault. In unstable-2.0 branch setUser // calls xwiki.isVirtualMode context.setUser("xwiki:XWiki.superadmin"); assertTrue(cmd.validationAllowed(context)); verify(httpRequest, request); } @Test public void testValidationAllowed_noHostInRequest_null() { XWikiRequest request = createMock(XWikiRequest.class); context.setRequest(request); HttpServletRequest httpRequest = createMock(HttpServletRequest.class); expect(request.getHttpServletRequest()).andReturn(httpRequest).once(); expect(httpRequest.getRemoteHost()).andReturn(" "); replay(httpRequest, request); assertFalse(cmd.validationAllowed(context)); verify(httpRequest, request); } @Test public void testValidationAllowed_noHostInRequest_empty() { XWikiRequest request = createMock(XWikiRequest.class); context.setRequest(request); HttpServletRequest httpRequest = createMock(HttpServletRequest.class); expect(request.getHttpServletRequest()).andReturn(httpRequest).once(); expect(httpRequest.getRemoteHost()).andReturn(" "); replay(httpRequest, request); assertFalse(cmd.validationAllowed(context)); verify(httpRequest, request); } @Test public void testValidationAllowed_noConfigFound_noObj() { XWikiRequest request = createMock(XWikiRequest.class); context.setRequest(request); HttpServletRequest httpRequest = createMock(HttpServletRequest.class); expect(request.getHttpServletRequest()).andReturn(httpRequest).once(); expect(httpRequest.getRemoteHost()).andReturn("test.synventis.com:10080"); XWikiDocument doc = new XWikiDocument(); context.setDoc(doc); replay(httpRequest, request); assertFalse(cmd.validationAllowed(context)); verify(httpRequest, request); } @Test public void testValidationAllowed_noConfigFound_hasObj() { XWikiRequest request = createMock(XWikiRequest.class); context.setRequest(request); HttpServletRequest httpRequest = createMock(HttpServletRequest.class); expect(request.getHttpServletRequest()).andReturn(httpRequest).once(); expect(httpRequest.getRemoteHost()).andReturn("test.synventis.com:10080"); XWikiDocument doc = new XWikiDocument(); context.setDoc(doc); BaseObject obj = new BaseObject(); obj.setStringValue("host", "another.host.com"); doc.addObject("Classes.RemoteUserValidationClass", obj); replay(httpRequest, request); assertFalse(cmd.validationAllowed(context)); verify(httpRequest, request); } @Test public void testValidationAllowed_secretEmpty() { XWikiRequest request = createMock(XWikiRequest.class); context.setRequest(request); HttpServletRequest httpRequest = createMock(HttpServletRequest.class); expect(request.getHttpServletRequest()).andReturn(httpRequest).once(); expect(httpRequest.getRemoteHost()).andReturn("test.synventis.com:10080"); XWikiDocument doc = new XWikiDocument(); context.setDoc(doc); BaseObject obj = new BaseObject(); obj.setStringValue("host", "test.synventis.com:10080"); obj.setStringValue("serverSecret", ""); expect(request.get(eq("secret"))).andReturn("").once(); doc.addObject("Classes.RemoteUserValidationClass", obj); replay(httpRequest, request); assertFalse(cmd.validationAllowed(context)); verify(httpRequest, request); } @Test public void testValidationAllowed_secretNoMatch() { XWikiRequest request = createMock(XWikiRequest.class); context.setRequest(request); HttpServletRequest httpRequest = createMock(HttpServletRequest.class); expect(request.getHttpServletRequest()).andReturn(httpRequest).once(); expect(request.get(eq("secret"))).andReturn("sn34ky").once(); expect(httpRequest.getRemoteHost()).andReturn("test.synventis.com:10080"); XWikiDocument doc = new XWikiDocument(); context.setDoc(doc); BaseObject obj = new BaseObject(); obj.setStringValue("host", "test.synventis.com:10080"); obj.setStringValue("serverSecret", "s3cr3tC0d3"); doc.addObject("Classes.RemoteUserValidationClass", obj); replay(httpRequest, request); assertFalse(cmd.validationAllowed(context)); verify(httpRequest, request); } @Test public void testValidationAllowed_allowed() { XWikiRequest request = createMock(XWikiRequest.class); context.setRequest(request); HttpServletRequest httpRequest = createMock(HttpServletRequest.class); expect(request.getHttpServletRequest()).andReturn(httpRequest).once(); expect(request.get(eq("secret"))).andReturn("s3cr3tC0d3").once(); expect(httpRequest.getRemoteHost()).andReturn("test.synventis.com:10080"); XWikiDocument doc = new XWikiDocument(); context.setDoc(doc); BaseObject obj = new BaseObject(); obj.setStringValue("host", "test.synventis.com:10080"); obj.setStringValue("secret", "s3cr3tC0d3"); doc.addObject("Classes.RemoteUserValidationClass", obj); replay(httpRequest, request); assertTrue(cmd.validationAllowed(context)); verify(httpRequest, request); } @Test public void testHasValue_false() { assertFalse(cmd.hasValue("")); assertFalse(cmd.hasValue(" ")); assertFalse(cmd.hasValue("\n")); assertFalse(cmd.hasValue("\t")); assertFalse(cmd.hasValue(" ")); } @Test public void testHasValue_true() { assertTrue(cmd.hasValue("a")); assertTrue(cmd.hasValue("a ")); assertTrue(cmd.hasValue(" A")); assertTrue(cmd.hasValue("hi there")); } }
package com.continuuity.data.metadata; import com.continuuity.data.hbase.HBaseTestBase; import com.continuuity.data.operation.executor.OperationExecutor; import com.continuuity.data.runtime.DataFabricDistributedModule; import com.continuuity.data.runtime.DataFabricLocalModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.name.Names; import org.junit.AfterClass; import org.junit.BeforeClass; public abstract class HBaseMetaDataStoreTest extends MetaDataStoreTest { @BeforeClass public static void startService() throws Exception { HBaseTestBase.startHBase(); DataFabricDistributedModule module = new DataFabricDistributedModule(HBaseTestBase.getConfiguration()); Injector injector = Guice.createInjector(module); opex = injector.getInstance(Key.get( OperationExecutor.class, Names.named("DataFabricOperationExecutor"))); } @AfterClass public static void stopHBase() throws Exception { HBaseTestBase.stopHBase(); } }
package com.fincatto.documentofiscal; import org.junit.Assert; import org.junit.Test; public class DFUnidadeFederativaTest { @Test public void deveRepresentarOCodigoCorretamente() { Assert.assertEquals("AC", DFUnidadeFederativa.AC.getCodigo()); Assert.assertEquals("12", DFUnidadeFederativa.AC.getCodigoIbge()); Assert.assertEquals("http://hml.sefaznet.ac.gov.br/nfce/qrcode", DFUnidadeFederativa.AC.getQrCodeHomologacao()); Assert.assertEquals("http://hml.sefaznet.ac.gov.br/nfce/qrcode", DFUnidadeFederativa.AC.getQrCodeProducao()); Assert.assertEquals("AL", DFUnidadeFederativa.AL.getCodigo()); Assert.assertEquals("27", DFUnidadeFederativa.AL.getCodigoIbge()); Assert.assertEquals(null, DFUnidadeFederativa.AL.getQrCodeHomologacao()); Assert.assertEquals(null, DFUnidadeFederativa.AL.getQrCodeProducao()); Assert.assertEquals("AM", DFUnidadeFederativa.AM.getCodigo()); Assert.assertEquals("13", DFUnidadeFederativa.AM.getCodigoIbge()); Assert.assertEquals("http://homnfce.sefaz.am.gov.br/nfceweb/consultarNFCe.jsp", DFUnidadeFederativa.AM.getQrCodeHomologacao()); Assert.assertEquals("http://sistemas.sefaz.am.gov.br/nfceweb/consultarNFCe.jsp", DFUnidadeFederativa.AM.getQrCodeProducao()); Assert.assertEquals("AP", DFUnidadeFederativa.AP.getCodigo()); Assert.assertEquals("16", DFUnidadeFederativa.AP.getCodigoIbge()); Assert.assertEquals("https: Assert.assertEquals("https: Assert.assertEquals("BA", DFUnidadeFederativa.BA.getCodigo()); Assert.assertEquals("29", DFUnidadeFederativa.BA.getCodigoIbge()); Assert.assertEquals("http://hnfe.sefaz.ba.gov.br/servicos/nfce/modulos/geral/NFCEC_consulta_chave_acesso.aspx", DFUnidadeFederativa.BA.getQrCodeHomologacao()); Assert.assertEquals("http://nfe.sefaz.ba.gov.br/servicos/nfce/modulos/geral/NFCEC_consulta_chave_acesso.aspx", DFUnidadeFederativa.BA.getQrCodeProducao()); Assert.assertEquals("CE", DFUnidadeFederativa.CE.getCodigo()); Assert.assertEquals("23", DFUnidadeFederativa.CE.getCodigoIbge()); Assert.assertEquals(null, DFUnidadeFederativa.CE.getQrCodeHomologacao()); Assert.assertEquals(null, DFUnidadeFederativa.CE.getQrCodeProducao()); Assert.assertEquals("DF", DFUnidadeFederativa.DF.getCodigo()); Assert.assertEquals("53", DFUnidadeFederativa.DF.getCodigoIbge()); Assert.assertEquals("http://dec.fazenda.df.gov.br/ConsultarNFCe.aspx", DFUnidadeFederativa.DF.getQrCodeHomologacao()); Assert.assertEquals("http://dec.fazenda.df.gov.br/ConsultarNFCe.aspx", DFUnidadeFederativa.DF.getQrCodeProducao()); Assert.assertEquals("ES", DFUnidadeFederativa.ES.getCodigo()); Assert.assertEquals("32", DFUnidadeFederativa.ES.getCodigoIbge()); Assert.assertEquals("http://homologacao.sefaz.es.gov.br/ConsultaNFCe/qrcode.aspx", DFUnidadeFederativa.ES.getQrCodeHomologacao()); Assert.assertEquals("http://app.sefaz.es.gov.br/ConsultaNFCe/qrcode.aspx", DFUnidadeFederativa.ES.getQrCodeProducao()); Assert.assertEquals("GO", DFUnidadeFederativa.GO.getCodigo()); Assert.assertEquals("52", DFUnidadeFederativa.GO.getCodigoIbge()); Assert.assertEquals("http://homolog.sefaz.go.gov.br/nfeweb/sites/nfce/danfeNFCe", DFUnidadeFederativa.GO.getQrCodeHomologacao()); Assert.assertEquals("http://nfe.sefaz.go.gov.br/nfeweb/sites/nfce/danfeNFCe", DFUnidadeFederativa.GO.getQrCodeProducao()); Assert.assertEquals("MA", DFUnidadeFederativa.MA.getCodigo()); Assert.assertEquals("21", DFUnidadeFederativa.MA.getCodigoIbge()); Assert.assertEquals("http: Assert.assertEquals("http: Assert.assertEquals("MG", DFUnidadeFederativa.MG.getCodigo()); Assert.assertEquals("31", DFUnidadeFederativa.MG.getCodigoIbge()); Assert.assertEquals("http://hnfce.fazenda.mg.gov.br/portalnfce/sistema/consultaarg.xhtml", DFUnidadeFederativa.MG.getConsultaChaveAcessoHomologacao()); Assert.assertEquals("http://nfce.fazenda.mg.gov.br/portalnfce/sistema/consultaarg.xhtml", DFUnidadeFederativa.MG.getConsultaChaveAcessoProducao()); Assert.assertEquals("https://hnfce.fazenda.mg.gov.br/portalnfce/sistema/qrcode.xhtml", DFUnidadeFederativa.MG.getQrCodeHomologacao()); Assert.assertEquals("https://nfce.fazenda.mg.gov.br/portalnfce/sistema/qrcode.xhtml", DFUnidadeFederativa.MG.getQrCodeProducao()); Assert.assertEquals("MS", DFUnidadeFederativa.MS.getCodigo()); Assert.assertEquals("50", DFUnidadeFederativa.MS.getCodigoIbge()); Assert.assertEquals("http: Assert.assertEquals("http: Assert.assertEquals("MT", DFUnidadeFederativa.MT.getCodigo()); Assert.assertEquals("51", DFUnidadeFederativa.MT.getCodigoIbge()); Assert.assertEquals("http://homologacao.sefaz.mt.gov.br/nfce/consultanfce", DFUnidadeFederativa.MT.getQrCodeHomologacao()); Assert.assertEquals("http: Assert.assertEquals("PA", DFUnidadeFederativa.PA.getCodigo()); Assert.assertEquals("15", DFUnidadeFederativa.PA.getCodigoIbge()); Assert.assertEquals("https://appnfc.sefa.pa.gov.br/portal-homologacao/view/consultas/nfce/nfceForm.seam", DFUnidadeFederativa.PA.getQrCodeHomologacao()); Assert.assertEquals("https://appnfc.sefa.pa.gov.br/portal/view/consultas/nfce/nfceForm.seam", DFUnidadeFederativa.PA.getQrCodeProducao()); Assert.assertEquals("PB", DFUnidadeFederativa.PB.getCodigo()); Assert.assertEquals("25", DFUnidadeFederativa.PB.getCodigoIbge()); Assert.assertEquals("http: Assert.assertEquals("http: Assert.assertEquals("PE", DFUnidadeFederativa.PE.getCodigo()); Assert.assertEquals("26", DFUnidadeFederativa.PE.getCodigoIbge()); Assert.assertEquals("http://nfcehomolog.sefaz.pe.gov.br/nfce-web/consultarNFCe", DFUnidadeFederativa.PE.getQrCodeHomologacao()); Assert.assertEquals("http://nfce.sefaz.pe.gov.br/nfce-web/consultarNFCe", DFUnidadeFederativa.PE.getQrCodeProducao()); Assert.assertEquals("PI", DFUnidadeFederativa.PI.getCodigo()); Assert.assertEquals("22", DFUnidadeFederativa.PI.getCodigoIbge()); Assert.assertEquals("http://webas.sefaz.pi.gov.br/nfceweb-homologacao/consultarNFCe.jsf", DFUnidadeFederativa.PI.getQrCodeHomologacao()); Assert.assertEquals("http://webas.sefaz.pi.gov.br/nfceweb/consultarNFCe.jsf", DFUnidadeFederativa.PI.getQrCodeProducao()); Assert.assertEquals("PR", DFUnidadeFederativa.PR.getCodigo()); Assert.assertEquals("41", DFUnidadeFederativa.PR.getCodigoIbge()); Assert.assertEquals("http: Assert.assertEquals("http: Assert.assertEquals("RJ", DFUnidadeFederativa.RJ.getCodigo()); Assert.assertEquals("33", DFUnidadeFederativa.RJ.getCodigoIbge()); Assert.assertEquals("http://www4.fazenda.rj.gov.br/consultaNFCe/QRCode", DFUnidadeFederativa.RJ.getQrCodeHomologacao()); Assert.assertEquals("http://www4.fazenda.rj.gov.br/consultaNFCe/QRCode", DFUnidadeFederativa.RJ.getQrCodeProducao()); Assert.assertEquals("RN", DFUnidadeFederativa.RN.getCodigo()); Assert.assertEquals("24", DFUnidadeFederativa.RN.getCodigoIbge()); Assert.assertEquals("http://hom.nfce.set.rn.gov.br/consultarNFCe.aspx", DFUnidadeFederativa.RN.getQrCodeHomologacao()); Assert.assertEquals("http://nfce.set.rn.gov.br/consultarNFCe.aspx", DFUnidadeFederativa.RN.getQrCodeProducao()); Assert.assertEquals("RO", DFUnidadeFederativa.RO.getCodigo()); Assert.assertEquals("11", DFUnidadeFederativa.RO.getCodigoIbge()); Assert.assertEquals("http: Assert.assertEquals("http: Assert.assertEquals("RR", DFUnidadeFederativa.RR.getCodigo()); Assert.assertEquals("14", DFUnidadeFederativa.RR.getCodigoIbge()); Assert.assertEquals("http://200.174.88.103:8080/nfce/servlet/qrcode", DFUnidadeFederativa.RR.getQrCodeHomologacao()); Assert.assertEquals("https: Assert.assertEquals("RS", DFUnidadeFederativa.RS.getCodigo()); Assert.assertEquals("43", DFUnidadeFederativa.RS.getCodigoIbge()); Assert.assertEquals("https: Assert.assertEquals("https: Assert.assertEquals("SC", DFUnidadeFederativa.SC.getCodigo()); Assert.assertEquals("42", DFUnidadeFederativa.SC.getCodigoIbge()); Assert.assertEquals(null, DFUnidadeFederativa.SC.getQrCodeHomologacao()); Assert.assertEquals(null, DFUnidadeFederativa.SC.getQrCodeProducao()); Assert.assertEquals("SE", DFUnidadeFederativa.SE.getCodigo()); Assert.assertEquals("28", DFUnidadeFederativa.SE.getCodigoIbge()); Assert.assertEquals("http: Assert.assertEquals("http: Assert.assertEquals("SP", DFUnidadeFederativa.SP.getCodigo()); Assert.assertEquals("35", DFUnidadeFederativa.SP.getCodigoIbge()); Assert.assertEquals("https: Assert.assertEquals("https: Assert.assertEquals("TO", DFUnidadeFederativa.TO.getCodigo()); Assert.assertEquals("17", DFUnidadeFederativa.TO.getCodigoIbge()); Assert.assertEquals(null, DFUnidadeFederativa.TO.getQrCodeHomologacao()); Assert.assertEquals(null, DFUnidadeFederativa.TO.getQrCodeProducao()); Assert.assertEquals("NC", DFUnidadeFederativa.NACIONAL.getCodigo()); Assert.assertEquals("90", DFUnidadeFederativa.NACIONAL.getCodigoIbge()); Assert.assertEquals(null, DFUnidadeFederativa.NACIONAL.getQrCodeHomologacao()); Assert.assertEquals(null, DFUnidadeFederativa.NACIONAL.getQrCodeProducao()); Assert.assertEquals("RFB", DFUnidadeFederativa.RFB.getCodigo()); Assert.assertEquals("91", DFUnidadeFederativa.RFB.getCodigoIbge()); Assert.assertEquals(null, DFUnidadeFederativa.RFB.getQrCodeHomologacao()); Assert.assertEquals(null, DFUnidadeFederativa.RFB.getQrCodeProducao()); Assert.assertEquals("EX", DFUnidadeFederativa.EX.getCodigo()); Assert.assertEquals("99", DFUnidadeFederativa.EX.getCodigoIbge()); Assert.assertEquals(null, DFUnidadeFederativa.EX.getQrCodeHomologacao()); Assert.assertEquals(null, DFUnidadeFederativa.EX.getQrCodeProducao()); } @Test(expected = IllegalArgumentException.class) public void deveLancarExcecaoCasoTenteBuscarUmCodigoErrado() { DFUnidadeFederativa.valueOfCodigo("1"); } @Test public void deveSerADescricaoAoInvocaarToString() { Assert.assertEquals("Santa Catarina", DFUnidadeFederativa.SC.toString()); Assert.assertEquals("Rio Grande do Sul", DFUnidadeFederativa.RS.toString()); } @Test public void deveObterAtravesDaSiglaAUF() { Assert.assertEquals(DFUnidadeFederativa.AC, DFUnidadeFederativa.valueOfCodigo("AC")); Assert.assertEquals(DFUnidadeFederativa.AL, DFUnidadeFederativa.valueOfCodigo("AL")); Assert.assertEquals(DFUnidadeFederativa.AM, DFUnidadeFederativa.valueOfCodigo("AM")); Assert.assertEquals(DFUnidadeFederativa.AP, DFUnidadeFederativa.valueOfCodigo("AP")); Assert.assertEquals(DFUnidadeFederativa.BA, DFUnidadeFederativa.valueOfCodigo("BA")); Assert.assertEquals(DFUnidadeFederativa.CE, DFUnidadeFederativa.valueOfCodigo("CE")); Assert.assertEquals(DFUnidadeFederativa.DF, DFUnidadeFederativa.valueOfCodigo("DF")); Assert.assertEquals(DFUnidadeFederativa.ES, DFUnidadeFederativa.valueOfCodigo("ES")); Assert.assertEquals(DFUnidadeFederativa.EX, DFUnidadeFederativa.valueOfCodigo("EX")); Assert.assertEquals(DFUnidadeFederativa.GO, DFUnidadeFederativa.valueOfCodigo("GO")); Assert.assertEquals(DFUnidadeFederativa.MA, DFUnidadeFederativa.valueOfCodigo("MA")); Assert.assertEquals(DFUnidadeFederativa.MG, DFUnidadeFederativa.valueOfCodigo("MG")); Assert.assertEquals(DFUnidadeFederativa.MS, DFUnidadeFederativa.valueOfCodigo("MS")); Assert.assertEquals(DFUnidadeFederativa.MT, DFUnidadeFederativa.valueOfCodigo("MT")); Assert.assertEquals(DFUnidadeFederativa.NACIONAL, DFUnidadeFederativa.valueOfCodigo("NC")); Assert.assertEquals(DFUnidadeFederativa.PA, DFUnidadeFederativa.valueOfCodigo("PA")); Assert.assertEquals(DFUnidadeFederativa.PB, DFUnidadeFederativa.valueOfCodigo("PB")); Assert.assertEquals(DFUnidadeFederativa.PE, DFUnidadeFederativa.valueOfCodigo("PE")); Assert.assertEquals(DFUnidadeFederativa.PI, DFUnidadeFederativa.valueOfCodigo("PI")); Assert.assertEquals(DFUnidadeFederativa.PR, DFUnidadeFederativa.valueOfCodigo("PR")); Assert.assertEquals(DFUnidadeFederativa.RFB, DFUnidadeFederativa.valueOfCodigo("RFB")); Assert.assertEquals(DFUnidadeFederativa.RJ, DFUnidadeFederativa.valueOfCodigo("RJ")); Assert.assertEquals(DFUnidadeFederativa.RN, DFUnidadeFederativa.valueOfCodigo("RN")); Assert.assertEquals(DFUnidadeFederativa.RO, DFUnidadeFederativa.valueOfCodigo("RO")); Assert.assertEquals(DFUnidadeFederativa.RR, DFUnidadeFederativa.valueOfCodigo("RR")); Assert.assertEquals(DFUnidadeFederativa.RS, DFUnidadeFederativa.valueOfCodigo("RS")); Assert.assertEquals(DFUnidadeFederativa.SC, DFUnidadeFederativa.valueOfCodigo("SC")); Assert.assertEquals(DFUnidadeFederativa.SE, DFUnidadeFederativa.valueOfCodigo("SE")); Assert.assertEquals(DFUnidadeFederativa.SP, DFUnidadeFederativa.valueOfCodigo("SP")); Assert.assertEquals(DFUnidadeFederativa.TO, DFUnidadeFederativa.valueOfCodigo("TO")); } }
package com.google.step.snippet.external; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import com.google.step.snippet.data.Card; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public final class W3SchoolsClientTest { private final W3SchoolsClient client = new W3SchoolsClient("CSE_ID"); @Test public void htmlCodeCard() { Card actual = client.search("https: Card expected = new Card( "HTML &lt;img&gt; Tag", "&lt;img src=&quot;img_girl.jpg&quot; alt=&quot;Girl in a jacket&quot;" + " width=&quot;500&quot; height=&quot;600&quot;&gt;", "https: "How to insert an image:", "W3Schools", "https://w3schools.com/favicon.ico"); assertEquals(expected, actual); } @Test public void jsonCodeCard() { Card actual = client.search("https: Card expected = new Card( "JSON - Introduction", "var myObj = {name: \"John\", age: 31, city: \"New York\"}; var myJSON =" + " JSON.stringify(myObj); window.location = \"demo_json.php?x=\" + myJSON;", "https: "JSON: JavaScript Object Notation.", "W3Schools", "https://w3schools.com/favicon.ico"); assertEquals(expected, actual); } @Test public void cssEscaping() { Card actual = client.search("https: Card expected = new Card( "HTML Styles - CSS", "&lt;h1 style=&quot;color:blue;&quot;&gt;A Blue Heading&lt;/h1&gt; &lt;p style=&quot;color:red;&quot;&gt;A red paragraph.&lt;/p&gt;", "https: "CSS stands for Cascading Style Sheets.", "W3Schools", "https://w3schools.com/favicon.ico"); assertEquals(expected, actual); } @Test public void divEscaping() { Card actual = client.search("https: Card expected = new Card( "CSS Flexbox", "&lt;div class=&quot;flex-container&quot;&gt; &lt;div&gt;1&lt;/div&gt; &lt;div&gt;2&lt;/div&gt; &lt;div&gt;3&lt;/div&gt; &lt;/div&gt;", "https: "Try it Yourself &raquo;", "W3Schools", "https://w3schools.com/favicon.ico"); assertEquals(expected, actual); } @Test public void partiallyFilledCard() { Card actual = client.search("https: assertNull(actual); } @Test public void nonexistentLink() { Card actual = client.search("https: assertNull(actual); } @Test public void blankPageLink() { Card actual = client.search("https: assertNull(actual); } }
package com.lambdaworks.redis.cluster; import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import com.google.code.tempusfugit.temporal.Condition; import com.google.code.tempusfugit.temporal.Duration; import com.google.code.tempusfugit.temporal.ThreadSleep; import com.google.code.tempusfugit.temporal.Timeout; import com.google.code.tempusfugit.temporal.WaitFor; import com.google.common.base.Predicate; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.primitives.Ints; import com.lambdaworks.redis.RedisAsyncConnectionImpl; import com.lambdaworks.redis.RedisClient; import com.lambdaworks.redis.RedisClusterAsyncConnection; import com.lambdaworks.redis.RedisFuture; import com.lambdaworks.redis.RedisURI; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class RedisClusterClientTest { public static final String host = "127.0.0.1"; public static final int port1 = 7379; public static final int port2 = 7380; public static final int port3 = 7381; public static final int port4 = 7382; protected static RedisClient client1; protected static RedisClient client2; protected static RedisClient client3; protected static RedisClient client4; protected static RedisClusterClient clusterClient; protected RedisClusterAsyncConnection<String, String> redis1; protected RedisClusterAsyncConnection<String, String> redis2; protected RedisClusterAsyncConnection<String, String> redis3; protected RedisClusterAsyncConnection<String, String> redis4; private static int slots1[]; private static int slots2[]; private static int slots3[]; protected String key = "key"; protected String value = "value"; private static boolean setup = false; @BeforeClass public static void setupClient() throws Exception { client1 = new RedisClient(host, port1); client2 = new RedisClient(host, port2); client3 = new RedisClient(host, port3); client4 = new RedisClient(host, port4); slots1 = createSlots(0, 8000); slots2 = createSlots(8000, 12000); slots3 = createSlots(12000, 16384); slots1[7000] = 12001; slots3[1] = 7000; clusterClient = new RedisClusterClient(ImmutableList.of(RedisURI.Builder.redis(host, port1).build())); } private static int[] createSlots(int from, int to) { int[] result = new int[to - from]; int counter = 0; for (int i = from; i < to; i++) { result[counter++] = i; } return result; } @AfterClass public static void shutdownClient() { client1.shutdown(); client2.shutdown(); client3.shutdown(); client4.shutdown(); } @Before public void before() throws Exception { redis1 = (RedisClusterAsyncConnection) client1.connectAsync(); redis2 = (RedisClusterAsyncConnection) client2.connectAsync(); redis3 = (RedisClusterAsyncConnection) client3.connectAsync(); redis4 = (RedisClusterAsyncConnection) client4.connectAsync(); if (!setup) { String info = redis1.clusterInfo().get(); if (info != null && !info.contains("cluster_state:ok")) { addSlots(); } String nodes = redis1.clusterNodes().get(); if (Splitter.on('\n').trimResults().splitToList(nodes).size() < 3) { redis1.clusterMeet(host, port1).get(); redis1.clusterMeet(host, port2).get(); redis1.clusterMeet(host, port3).get(); redis1.clusterMeet(host, port4).get(); Thread.sleep(500); } setup = true; } redis1.flushall(); redis2.flushall(); redis3.flushall(); redis4.flushall(); WaitFor.waitOrTimeout(new Condition() { @Override public boolean isSatisfied() { try { String info = redis1.clusterInfo().get(); if (info != null && info.contains("cluster_state:ok")) { return true; } } catch (Exception e) { } return false; } }, Timeout.timeout(Duration.seconds(5)), new ThreadSleep(Duration.millis(500))); } @After public void after() throws Exception { redis1.close(); redis2.close(); redis3.close(); redis4.close(); } protected void addSlots() throws InterruptedException, java.util.concurrent.ExecutionException { for (int i : slots1) { redis1.clusterAddSlots(i); } for (int i : slots2) { redis2.clusterAddSlots(i); } for (int i : slots3) { redis3.clusterAddSlots(i); } } public void cleanup() throws Exception { int slots[] = createSlots(1, 16385); List<RedisFuture<?>> futures = Lists.newArrayList(); for (int i = 0; i < slots.length; i++) { futures.add(redis1.clusterDelSlots(i)); futures.add(redis2.clusterDelSlots(i)); futures.add(redis3.clusterDelSlots(i)); futures.add(redis4.clusterDelSlots(i)); } for (int i = 0; i < slots.length; i++) { futures.add(redis1.clusterDelSlots(i)); futures.add(redis2.clusterDelSlots(i)); futures.add(redis3.clusterDelSlots(i)); futures.add(redis4.clusterDelSlots(i)); } for (RedisFuture<?> future : futures) { future.get(); } } @Test public void testClusterInfo() throws Exception { RedisFuture<String> future = redis1.clusterInfo(); String status = future.get(); assertThat(status, containsString("cluster_known_nodes:")); assertThat(status, containsString("cluster_slots_fail:0")); assertThat(status, containsString("cluster_state:")); } @Test public void testClusterNodes() throws Exception { RedisFuture<String> future = redis1.clusterNodes(); String string = future.get(); assertThat(string, containsString("connected")); assertThat(string, containsString("master")); assertThat(string, containsString("myself")); } @Test public void clusterSlaves() throws Exception { Partitions partitions = ClusterPartitionParser.parse(redis1.clusterNodes().get()); final RedisClusterNode node1 = Iterables.find(partitions, new Predicate<RedisClusterNode>() { @Override public boolean apply(RedisClusterNode input) { return input.getFlags().contains(RedisClusterNode.NodeFlag.MYSELF); } }); RedisFuture<String> replicate = redis4.clusterReplicate(node1.getNodeId()); replicate.get(); assertNull(replicate.getError()); assertEquals("OK", replicate.get()); WaitFor.waitOrTimeout(new Condition() { @Override public boolean isSatisfied() { RedisFuture<List<String>> future = redis1.clusterSlaves(node1.getNodeId()); try { List<String> result = future.get(); return result.size() == 1; } catch (Exception e) { e.printStackTrace(); return false; } } }, Timeout.timeout(Duration.seconds(5))); } @Test public void testClusteredOperations() throws Exception { int slot1 = SlotHash.getSlot("b".getBytes()); // 3300 -> Node 1 and Slave (Node 4) int slot2 = SlotHash.getSlot("a".getBytes()); // 15495 -> Node 3 RedisFuture<String> result = redis1.set("b", "value"); assertEquals(null, result.getError()); assertEquals("OK", redis3.set("a", "value").get()); RedisFuture<String> resultMoved = redis1.set("a", "value"); resultMoved.get(); assertThat(resultMoved.getError(), containsString("MOVED 15495")); assertEquals(null, resultMoved.get()); RedisClusterAsyncConnection<String, String> connection = clusterClient.connectClusterAsync(); RedisFuture<String> setA = connection.set("a", "myValue1"); setA.get(); assertNull(setA.getError()); assertEquals("OK", setA.get()); RedisFuture<String> setB = connection.set("b", "myValue2"); assertEquals("OK", setB.get()); RedisFuture<String> setD = connection.set("d", "myValue2"); assertEquals("OK", setD.get()); connection.close(); } @Test public void testClusterRedirection() throws Exception { int slot1 = SlotHash.getSlot("b".getBytes()); // 3300 -> Node 1 and Slave (Node 4) int slot2 = SlotHash.getSlot("a".getBytes()); // 15495 -> Node 3 RedisClusterAsyncConnection<String, String> connection = clusterClient.connectClusterAsync(); Partitions partitions = clusterClient.getPartitions(); for (RedisClusterNode partition : partitions) { partition.getSlots().clear(); if (partition.getFlags().contains(RedisClusterNode.NodeFlag.MYSELF)) { partition.getSlots().addAll(Ints.asList(slots1)); partition.getSlots().addAll(Ints.asList(slots2)); partition.getSlots().addAll(Ints.asList(slots3)); } } // appropriate cluster node RedisFuture<String> setB = connection.set("b", "myValue1"); assertTrue(setB instanceof ClusterCommand); ClusterCommand clusterCommandB = (ClusterCommand) setB; setB.get(); assertNull(setB.getError()); assertEquals(1, clusterCommandB.getExecutions()); assertEquals("OK", setB.get()); assertFalse(clusterCommandB.isMoved()); // gets redirection to node 3 RedisFuture<String> setA = connection.set("a", "myValue1"); assertTrue(setA instanceof ClusterCommand); ClusterCommand clusterCommandA = (ClusterCommand) setA; setA.get(); assertNull(setA.getError()); assertEquals(2, clusterCommandA.getExecutions()); assertEquals(5, clusterCommandA.getExecutionLimit()); assertEquals("OK", setA.get()); assertFalse(clusterCommandA.isMoved()); connection.close(); } @Test public void testClusterConnectionStability() throws Exception { RedisAsyncConnectionImpl<String, String> connection = (RedisAsyncConnectionImpl<String, String>) clusterClient .connectClusterAsync(); connection.set("a", "b"); ClusterDistributionChannelWriter writer = (ClusterDistributionChannelWriter) connection.getChannelWriter(); RedisAsyncConnectionImpl<Object, Object> backendConnection = writer.getClusterConnectionProvider().getConnection( ClusterConnectionProvider.Intent.WRITE, 3300); backendConnection.set("a", "b"); backendConnection.close(); assertTrue(backendConnection.isClosed()); assertFalse(backendConnection.isOpen()); assertTrue(connection.isOpen()); assertFalse(connection.isClosed()); connection.set("a", "b"); RedisAsyncConnectionImpl<Object, Object> backendConnection2 = writer.getClusterConnectionProvider().getConnection( ClusterConnectionProvider.Intent.WRITE, 3300); assertTrue(backendConnection2.isOpen()); assertFalse(backendConnection2.isClosed()); assertNotSame(backendConnection, backendConnection2); connection.close(); } @Test(timeout = 10000) public void massiveClusteredAccess() throws Exception { RedisClusterAsyncConnection<String, String> connection = clusterClient.connectClusterAsync(); for (int i = 0; i < 10000; i++) { connection.set("a" + i, "myValue1" + i).get(); connection.set("b" + i, "myValue2" + i).get(); connection.set("d" + i, "myValue3" + i).get(); } for (int i = 0; i < 10000; i++) { RedisFuture<String> setA = connection.get("a" + i); RedisFuture<String> setB = connection.get("b" + i); RedisFuture<String> setD = connection.get("d" + i); assertEquals("myValue1" + i, setA.get()); assertEquals("myValue2" + i, setB.get()); assertEquals("myValue3" + i, setD.get()); } connection.close(); } }
package org.exist.xquery.xqts; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; import junit.framework.Assert; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DefaultLogger; import org.apache.tools.ant.Project; import org.apache.tools.ant.ProjectHelper; import org.exist.dom.ElementImpl; import org.exist.dom.NodeListImpl; import org.exist.security.xacml.AccessContext; import org.exist.source.FileSource; import org.exist.storage.DBBroker; import org.exist.w3c.tests.TestCase; import org.exist.xmldb.XQueryService; import org.exist.xmldb.XmldbURI; import org.exist.xquery.CompiledXQuery; import org.exist.xquery.XPathException; import org.exist.xquery.XQuery; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.DateTimeValue; import org.exist.xquery.value.Sequence; import org.w3c.dom.Attr; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xmldb.api.DatabaseManager; import org.xmldb.api.base.ResourceSet; import org.xmldb.api.base.XMLDBException; import org.xmldb.api.modules.XMLResource; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * */ public class XQTS_case extends TestCase { protected static final String XQTS_folder = "test/external/XQTS_1_0_3/"; private static Map<String, String> sources = null; private static Map<String, String> moduleSources = null; protected static final XmldbURI XQTS_URI = XmldbURI.DB.append("XQTS"); @Override public void loadTS() throws Exception { testCollection = DatabaseManager.getCollection("xmldb:exist:///db/XQTS", "admin", ""); if (testCollection == null) { File buildFile = new File("webapp/xqts/build.xml"); Project p = new Project(); p.setUserProperty("ant.file", buildFile.getAbsolutePath()); p.setUserProperty("config.basedir", "../../"+XQTS_folder); DefaultLogger consoleLogger = new DefaultLogger(); consoleLogger.setErrorPrintStream(System.err); consoleLogger.setOutputPrintStream(System.out); consoleLogger.setMessageOutputLevel(Project.MSG_INFO); p.addBuildListener(consoleLogger); try { p.fireBuildStarted(); p.init(); ProjectHelper helper = ProjectHelper.getProjectHelper(); p.addReference("ant.projectHelper", helper); helper.parse(p, buildFile); p.executeTarget("store"); p.fireBuildFinished(null); Thread.sleep(60 * 1000); } catch (BuildException e) { p.fireBuildFinished(e); } catch (InterruptedException e) { } } testCollection = DatabaseManager.getCollection("xmldb:exist:///db/XQTS", "admin", ""); if (testCollection == null) throw new Exception("XQTS collection wasn't found"); if (sources == null) { sources = new HashMap<String, String>(); XQueryService service = (XQueryService) testCollection.getService("XQueryService", "1.0"); String query = "declare namespace catalog=\"http: "let $XQTSCatalog := xmldb:document('/db/XQTS/XQTSCatalog.xml') "+ "return $XQTSCatalog//catalog:sources//catalog:source"; ResourceSet results = service.query(query); for (int i = 0; i < results.getSize(); i++) { ElementImpl source = (ElementImpl) ((XMLResource) results.getResource(i)).getContentAsDOM(); sources.put(source.getAttribute("ID"), XQTS_folder + source.getAttribute("FileName")); } } if (moduleSources == null) { moduleSources = new HashMap<String, String>(); XQueryService service = (XQueryService) testCollection.getService("XQueryService", "1.0"); String query = "declare namespace catalog=\"http: "let $XQTSCatalog := xmldb:document('/db/XQTS/XQTSCatalog.xml') "+ "return $XQTSCatalog//catalog:sources//catalog:module"; ResourceSet results = service.query(query); for (int i = 0; i < results.getSize(); i++) { ElementImpl source = (ElementImpl) ((XMLResource) results.getResource(i)).getContentAsDOM(); moduleSources.put(source.getAttribute("ID"), "test/external/XQTS_1_0_3/"+source.getAttribute("FileName")+".xq"); } } } protected void groupCase(String testGroup, String testCase) { //ignore tests // if (testGroup.equals("FunctionCallExpr") && testCase.equals("K-FunctionCallExpr-11")) // return; // else if (testGroup.equals("SeqCollectionFunc")) { // if (testCase.equals("fn-collection-4d") // || testCase.equals("fn-collection-5d") // || testCase.equals("fn-collection-9") // || testCase.equals("fn-collection-10d")) // return; // if (testCase.equals("K2-NodeTest-11")) // return; //Added by p.b. as a quick attempt to work around current blocking code // if (testCase.equals("Constr-cont-document-3")) // return; //Added by p.b. as a quick attempt to work around current blocking code try { XQueryService service = (XQueryService) testCollection.getService( "XQueryService", "1.0"); String query = "declare namespace catalog=\"http: "let $XQTSCatalog := xmldb:document('/db/XQTS/XQTSCatalog.xml')\n"+ "let $tc := $XQTSCatalog/catalog:test-suite//catalog:test-group[@name eq \""+testGroup+"\"]/catalog:test-case[@name eq \""+testCase+"\"]\n"+ "return $tc"; ResourceSet results = service.query(query); Assert.assertFalse("", results.getSize() != 1); ElementImpl TC = (ElementImpl) ((XMLResource) results.getResource(0)).getContentAsDOM(); //collect test case information String folder = ""; String scenario = ""; String script = ""; //DateTimeValue scriptDateTime = null; NodeListImpl inputFiles = new NodeListImpl(); NodeListImpl outputFiles = new NodeListImpl(); ElementImpl contextItem = null; NodeListImpl modules = new NodeListImpl(); String expectedError = ""; String name = null; NodeList childNodes = TC.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node child = childNodes.item(i); switch (child.getNodeType()) { case Node.ATTRIBUTE_NODE: name = ((Attr)child).getName(); if (name.equals("FilePath")) folder = ((Attr)child).getValue(); else if (name.equals("scenario")) scenario = ((Attr)child).getValue(); break; case Node.ELEMENT_NODE: name = ((ElementImpl) child).getLocalName(); if (name.equals("query")) { ElementImpl el = ((ElementImpl) child); script = el.getAttribute("name"); //scriptDateTime = new DateTimeValue(el.getAttribute("date")); } else if (name.equals("input-file")) inputFiles.add(child); else if (name.equals("output-file")) outputFiles.add(child); else if (name.equals("contextItem")) contextItem = (ElementImpl)child; else if (name.equals("module")) modules.add(child); else if (name.equals("expected-error")) expectedError = ((ElementImpl) child).getNodeValue(); break; default : ; } } DBBroker broker = null; Sequence result = null; //compile & evaluate File caseScript = new File(XQTS_folder+"Queries/XQuery/"+folder, script+".xq"); try { XQueryContext context; XQuery xquery; broker = pool.get(pool.getSecurityManager().getSystemSubject()); xquery = broker.getXQueryService(); broker.getConfiguration().setProperty( XQueryContext.PROPERTY_XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL, true); context = xquery.newContext(AccessContext.TEST); //map modules' namespaces to location Map<String, String> moduleMap = (Map<String, String>)broker.getConfiguration().getProperty(XQueryContext.PROPERTY_STATIC_MODULE_MAP); for (int i = 0; i < modules.getLength(); i++) { ElementImpl module = (ElementImpl)modules.item(i); String id = module.getNodeValue(); moduleMap.put(module.getAttribute("namespace"), moduleSources.get(id)); } broker.getConfiguration().setProperty(XQueryContext.PROPERTY_STATIC_MODULE_MAP, moduleMap); //declare variable for (int i = 0; i < inputFiles.getLength(); i++) { ElementImpl inputFile = (ElementImpl)inputFiles.item(i); String id = inputFile.getNodeValue(); //use DocUtils //context.declareVariable( //inputFile.getAttribute("variable"), //DocUtils.getDocument(context, sources.get(id)) //in-memory nodes context.declareVariable(inputFile.getAttribute("variable"), loadVarFromURI(context, sources.get(id))); } Sequence contextSequence = null; //set context item if (contextItem != null) { String id = contextItem.getNodeValue(); contextSequence = loadVarFromURI(context, sources.get(id)); } fixBrokenTests(context, testGroup, testCase); //compare result with one provided by test case boolean ok = false; Exception error = null; if ("runtime-error".equals(scenario)) { try { //compile CompiledXQuery compiled = xquery.compile(context, new FileSource(caseScript, "UTF8", true)); //execute result = xquery.execute(compiled, contextSequence); if (outputFiles.getLength() != 0) { //can be answered for (int i = 0; i < outputFiles.getLength(); i++) { ElementImpl outputFile = (ElementImpl)outputFiles.item(i); String compare = outputFile.getAttribute("compare"); if (compare != null && compare.equalsIgnoreCase("IGNORE")) { ok = true; break; } if (compareResult(script, "XQTS_1_0_3/ExpectedTestResults/"+folder, outputFile, result)) { ok = true; break; } } } else { error = catchError(result); } } catch (Exception e) { error = e; } if (!ok && error != null && expectedError != null) {// error.getMessage().contains(expectedError)) { ok = true; } } else { //compile CompiledXQuery compiled = xquery.compile(context, new FileSource(caseScript, "UTF8", true)); //execute result = xquery.execute(compiled, contextSequence); //check answer for (int i = 0; i < outputFiles.getLength(); i++) { ElementImpl outputFile = (ElementImpl)outputFiles.item(i); String compare = outputFile.getAttribute("compare"); if (compare != null && compare.equalsIgnoreCase("IGNORE")) { ok = true; break; } if (compareResult(script, "XQTS_1_0_3/ExpectedTestResults/"+folder, outputFile, result)) { ok = true; break; } } } //collect information if result is wrong if (!ok) { StringBuilder message = new StringBuilder(); StringBuffer exp = new StringBuffer(); try { for (int i = 0; i < outputFiles.getLength(); i++) { ElementImpl outputFile = (ElementImpl)outputFiles.item(i); String compare = outputFile.getAttribute("compare"); if (compare != null && compare.equalsIgnoreCase("IGNORE")) continue; File expectedResult = new File(XQTS_folder+"ExpectedTestResults/"+folder, outputFile.getNodeValue()); if (!expectedResult.canRead()) Assert.fail("can't read expected result"); //avoid to big output if (expectedResult.length() >= 1024) { exp = new StringBuffer(); exp.append("{TOO BIG}"); break; } else { exp.append("{'"); Reader reader = new BufferedReader(new FileReader(expectedResult)); char ch; while (reader.ready()) { ch = (char)reader.read(); if (ch == '\r') ch = (char)reader.read(); exp.append(String.valueOf(ch)); } exp.append("'}"); } } } catch (Exception e) { exp.append(e.getMessage()); } String res = "{NOTHING}"; if (result != null) res = sequenceToString(result); if (exp.length() == 0) exp.append("error "+ expectedError); StringBuilder data = new StringBuilder(); for (int i = 0; i < inputFiles.getLength(); i++) { ElementImpl inputFile = (ElementImpl)inputFiles.item(i); String id = inputFile.getNodeValue(); data.append(inputFile.getAttribute("variable")); data.append(" = \n"); data.append(readFileAsString(new File(sources.get(id)), 1024)); data.append("\n"); } message.append("\n"); message.append("expected "); message.append("[" + exp + "]"); message.append(" got "); message.append("[" + res + "]\n"); message.append("script:\n"); message.append(readFileAsString(caseScript)); message.append("\n"); message.append("data:\n"); message.append(data); Assert.fail(message.toString()); } } catch (XPathException e) { // String error = e.getMessage(); if (!expectedError.isEmpty()) ; else if (expectedError.equals("*")) ; //TODO:check e.getCode() // else if (error.indexOf(expectedError) != -1) // else { // if (error.startsWith("err:")) error = error.substring(4); // if (error.indexOf(expectedError) == -1) // Assert.fail("expected error is "+expectedError+", got "+error+" ["+e.getMessage()+"]"); } catch (Exception e) { if (e instanceof XMLDBException) { if (e.getMessage().contains("SENR0001")) { if (!expectedError.isEmpty()) return; } } e.printStackTrace(); StringBuilder message = new StringBuilder(); message.append(e.toString()); message.append("\n during script evaluation:\n"); try { message.append(readFileAsString(caseScript)); } catch (IOException e1) { message.append("ERROR - "+e1.getMessage()); } Assert.fail(message.toString()); } finally { pool.release(broker); } } catch (XMLDBException e) { Assert.fail(e.toString()); } } private void fixBrokenTests(XQueryContext context, String group, String test) { try { if (group.equals("ContextImplicitTimezoneFunc")) { TimeZone implicitTimeZone = TimeZone.getTimeZone("GMT-5:00");// getDefault(); //if( implicitTimeZone.inDaylightTime( new Date() ) ) { //implicitTimeZone.setRawOffset( implicitTimeZone.getRawOffset() + implicitTimeZone.getDSTSavings() ); context.setTimeZone(implicitTimeZone); } else if (group.equals("ContextCurrentDatetimeFunc") || group.equals("ContextCurrentDateFunc") || group.equals("ContextCurrentTimeFunc")) { DateTimeValue dt = null; if (test.equals("fn-current-time-4")) dt = new DateTimeValue("2005-12-05T13:38:03.455-05:00"); else if (test.equals("fn-current-time-6")) dt = new DateTimeValue("2005-12-05T13:38:18.059-05:00"); else if (test.equals("fn-current-time-7")) dt = new DateTimeValue("2005-12-05T13:38:18.059-05:00"); else if (test.equals("fn-current-time-10")) dt = new DateTimeValue("2005-12-05T13:38:18.09-05:00"); else if (test.startsWith("fn-current-time-")) dt = new DateTimeValue("2005-12-05T10:15:03.408-05:00"); else if (test.equals("fn-current-dateTime-6")) dt = new DateTimeValue("2005-12-05T17:10:00.312-05:00"); else if (test.equals("fn-current-datetime-7")) dt = new DateTimeValue("2005-12-05T17:10:00.312-05:00"); else if (test.equals("fn-current-dateTime-10")) dt = new DateTimeValue("2005-12-05T17:10:00.344-05:00"); else if (test.equals("fn-current-dateTime-21")) dt = new DateTimeValue("2005-12-05T17:10:00.453-05:00"); else if (test.equals("fn-current-dateTime-24")) dt = new DateTimeValue("2005-12-05T17:10:00.469-05:00"); else dt = new DateTimeValue("2005-12-05T17:10:00.203-05:00"); //if (dt != null) context.setCalendar(dt.calendar); } } catch (XPathException e) { } } @Override protected String getCollection() { return XQTS_URI.toString(); } }
// checkstyle: Checks Java source code for adherence to a set of rules. // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.puppycrawl.tools.checkstyle; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.storage.file.FileRepositoryBuilder; import org.junit.BeforeClass; import org.junit.Test; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; /** * Validate commit message has proper structure. * * Commits to check are resolved from different places according * to type of commit in current HEAD. If current HEAD commit is * non-merge commit , previous commits are resolved due to current * HEAD commit. Otherwise if it is a merge commit, it will invoke * resolving previous commits due to commits which was merged. * * After calculating commits to start with ts resolves previous * commits according to COMMITS_RESOLUTION_MODE variable. * At default(BY_LAST_COMMIT_AUTHOR) it checks first commit author * and return all consecutive commits with same author. Second * mode(BY_COUNTER) makes returning first PREVIOUS_COMMITS_TO_CHECK_COUNT * commits after starter commit. * * Resolved commits are filtered according to author. If commit author * belong to list USERS_EXCLUDED_FROM_VALIDATION then this commit will * not be validated. * * Filtered commit list is checked if their messages has proper structure. * * @author <a href="mailto:piotr.listkiewicz@gmail.com">liscju</a> */ public class CommitValidationTest { private static final List<String> USERS_EXCLUDED_FROM_VALIDATION = Collections.singletonList("Roman Ivanov"); private static final String ISSUE_COMMIT_MESSAGE_REGEX_PATTERN = "^Issue private static final String PR_COMMIT_MESSAGE_REGEX_PATTERN = "^Pull private static final String OTHER_COMMIT_MESSAGE_REGEX_PATTERN = "^(minor|config|infra|doc|spelling): .*$"; private static final String ACCEPTED_COMMIT_MESSAGE_REGEX_PATTERN = "(" + ISSUE_COMMIT_MESSAGE_REGEX_PATTERN + ")|" + "(" + PR_COMMIT_MESSAGE_REGEX_PATTERN + ")|" + "(" + OTHER_COMMIT_MESSAGE_REGEX_PATTERN + ")"; private static final Pattern ACCEPTED_COMMIT_MESSAGE_PATTERN = Pattern.compile(ACCEPTED_COMMIT_MESSAGE_REGEX_PATTERN, Pattern.DOTALL); private static final String NEWLINE_REGEX_PATTERN = "\r\n?|\n"; private static final Pattern NEWLINE_PATTERN = Pattern.compile(NEWLINE_REGEX_PATTERN); private static final int PREVIOUS_COMMITS_TO_CHECK_COUNT = 10; private enum CommitsResolutionMode { BY_COUNTER, BY_LAST_COMMIT_AUTHOR } private static final CommitsResolutionMode COMMITS_RESOLUTION_MODE = CommitsResolutionMode.BY_LAST_COMMIT_AUTHOR; private static List<RevCommit> lastCommits; @BeforeClass public static void setUp() throws Exception { lastCommits = getCommitsToCheck(); } @Test public void testCommitMessageHasProperStructure() throws Exception { for (RevCommit commit : filterValidCommits(lastCommits)) { String commitId = commit.getId().getName(); String commitMessage = commit.getFullMessage(); Matcher matcher = ACCEPTED_COMMIT_MESSAGE_PATTERN.matcher(commitMessage); assertTrue(getInvalidCommitMessageFormattingError(commitId, commitMessage), matcher.matches()); } } @Test public void testCommitMessageHasSingleLine() throws Exception { for (RevCommit commit : filterValidCommits(lastCommits)) { String commitId = commit.getId().getName(); String commitMessage = commit.getFullMessage(); Matcher matcher = NEWLINE_PATTERN.matcher(commitMessage); if (matcher.find()) { /** * Git by default put newline character at the end of commit message. To check * if commit message has a single line we have to make sure that the only * newline character found is in the end of commit message. */ boolean isFoundNewLineCharacterAtTheEndOfMessage = matcher.end() == commitMessage.length(); assertTrue(getInvalidCommitMessageFormattingError(commitId, commitMessage), isFoundNewLineCharacterAtTheEndOfMessage); } } } private static List<RevCommit> getCommitsToCheck() throws Exception { List<RevCommit> commits; try (Repository repo = new FileRepositoryBuilder().findGitDir().build()) { RevCommitsPair revCommitsPair = resolveRevCommitsPair(repo); if (COMMITS_RESOLUTION_MODE == CommitsResolutionMode.BY_COUNTER) { commits = getCommitsByCounter(revCommitsPair.getFirst()); commits.addAll(getCommitsByCounter(revCommitsPair.getSecond())); } else { commits = getCommitsByLastCommitAuthor(revCommitsPair.getFirst()); commits.addAll(getCommitsByLastCommitAuthor(revCommitsPair.getSecond())); } } return commits; } private static List<RevCommit> filterValidCommits(List<RevCommit> revCommits) { List<RevCommit> filteredCommits = new LinkedList<>(); for (RevCommit commit : revCommits) { String commitAuthor = commit.getAuthorIdent().getName(); if (!USERS_EXCLUDED_FROM_VALIDATION.contains(commitAuthor)) { filteredCommits.add(commit); } } return filteredCommits; } private static RevCommitsPair resolveRevCommitsPair(Repository repo) { RevCommitsPair revCommitIteratorPair; try (RevWalk revWalk = new RevWalk(repo)) { Iterator<RevCommit> first; Iterator<RevCommit> second; ObjectId headId = repo.resolve(Constants.HEAD); RevCommit headCommit = revWalk.parseCommit(headId); if (isMergeCommit(headCommit)) { RevCommit firstParent = headCommit.getParent(0); RevCommit secondParent = headCommit.getParent(1); try (Git git = new Git(repo)) { first = git.log().add(firstParent).call().iterator(); second = git.log().add(secondParent).call().iterator(); } } else { try (Git git = new Git(repo)) { first = git.log().call().iterator(); } second = Collections.emptyIterator(); } revCommitIteratorPair = new RevCommitsPair(new OmitMergeCommitsIterator(first), new OmitMergeCommitsIterator(second)); } catch (GitAPIException | IOException e) { revCommitIteratorPair = new RevCommitsPair(); } return revCommitIteratorPair; } private static boolean isMergeCommit(RevCommit currentCommit) { return currentCommit.getParentCount() > 1; } private static List<RevCommit> getCommitsByCounter(Iterator<RevCommit> previousCommitsIterator) { return Lists.newArrayList(Iterators.limit(previousCommitsIterator, PREVIOUS_COMMITS_TO_CHECK_COUNT)); } private static List<RevCommit> getCommitsByLastCommitAuthor(Iterator<RevCommit> previousCommitsIterator) { List<RevCommit> commits = new LinkedList<>(); if (previousCommitsIterator.hasNext()) { RevCommit lastCommit = previousCommitsIterator.next(); String lastCommitAuthor = lastCommit.getAuthorIdent().getName(); commits.add(lastCommit); boolean wasLastCheckedCommitAuthorSameAsLastCommit = true; while (previousCommitsIterator.hasNext() && wasLastCheckedCommitAuthorSameAsLastCommit) { RevCommit currentCommit = previousCommitsIterator.next(); String currentCommitAuthor = currentCommit.getAuthorIdent().getName(); if (currentCommitAuthor.equals(lastCommitAuthor)) { commits.add(currentCommit); } else { wasLastCheckedCommitAuthorSameAsLastCommit = false; } } } return commits; } private static String getRulesForCommitMessageFormatting() { return "Proper commit message should adhere to the following rules:\n" + " 1) Must match one of the following patterns:\n" + " " + ISSUE_COMMIT_MESSAGE_REGEX_PATTERN + "\n" + " " + PR_COMMIT_MESSAGE_REGEX_PATTERN + "\n" + " " + OTHER_COMMIT_MESSAGE_REGEX_PATTERN + "\n" + " 2) It contains only one line"; } private static String getInvalidCommitMessageFormattingError(String commitId, String commitMessage) { return "Commit " + commitId + " message: \"" + commitMessage + "\" is invalid\n" + getRulesForCommitMessageFormatting(); } private static class RevCommitsPair { private final Iterator<RevCommit> first; private final Iterator<RevCommit> second; RevCommitsPair() { first = Collections.emptyIterator(); second = Collections.emptyIterator(); } RevCommitsPair(Iterator<RevCommit> first, Iterator<RevCommit> second) { this.first = first; this.second = second; } public Iterator<RevCommit> getFirst() { return first; } public Iterator<RevCommit> getSecond() { return second; } } private static class OmitMergeCommitsIterator implements Iterator<RevCommit> { private final Iterator<RevCommit> revCommitIterator; OmitMergeCommitsIterator(Iterator<RevCommit> revCommitIterator) { this.revCommitIterator = revCommitIterator; } @Override public boolean hasNext() { return revCommitIterator.hasNext(); } @Override public RevCommit next() { RevCommit currentCommit = revCommitIterator.next(); while (isMergeCommit(currentCommit)) { currentCommit = revCommitIterator.next(); } return currentCommit; } @Override public void remove() { throw new UnsupportedOperationException("remove"); } } }
package uk.me.steev.java.heating.io.http; import java.io.IOException; import java.util.Map; import java.util.TreeMap; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONObject; import uk.me.steev.java.heating.controller.Heating; import uk.me.steev.java.heating.io.temperature.BluetoothTemperatureSensor; public class AllDetailsAfterProcessServlet extends HeatingServlet { private static final long serialVersionUID = -2479268631077208608L; static final Logger logger = LogManager.getLogger(CurrentTempServlet.class.getName()); public AllDetailsAfterProcessServlet(Heating heating) { super(heating); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); JSONObject json = new JSONObject(); String pathInfo = request.getPathInfo().replaceFirst("/", ""); if (null != pathInfo && !"no_wait".equals(pathInfo)) { synchronized(heating) { try { heating.wait(); } catch (InterruptedException ie) { logger.catching(ie); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } Map<String, BluetoothTemperatureSensor> sensors = heating.getSensors(); Map<String, Float> temps = new TreeMap<String, Float>(); for (String s : sensors.keySet()) { temps.put(sensors.get(s).getName(), sensors.get(s).getCurrentTemperature()); } json.put("temps", temps); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(json.toString(2)); } } }
package uk.me.steev.java.heating.io.http; import java.io.IOException; import java.util.Map; import java.util.TreeMap; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONObject; import uk.me.steev.java.heating.controller.Heating; import uk.me.steev.java.heating.io.temperature.BluetoothTemperatureSensor; public class AllDetailsAfterProcessServlet extends HeatingServlet { private static final long serialVersionUID = -2479268631077208608L; static final Logger logger = LogManager.getLogger(CurrentTempServlet.class.getName()); public AllDetailsAfterProcessServlet(Heating heating) { super(heating); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); JSONObject json = new JSONObject(); String pathInfo = null; if (null != request.getPathInfo()) pathInfo = request.getPathInfo().replaceFirst("/", ""); if (null != pathInfo && !"no_wait".equals(pathInfo)) { synchronized(heating) { try { heating.wait(); } catch (InterruptedException ie) { logger.catching(ie); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } Map<String, BluetoothTemperatureSensor> sensors = heating.getSensors(); Map<String, Float> temps = new TreeMap<String, Float>(); for (String s : sensors.keySet()) { temps.put(sensors.get(s).getName(), sensors.get(s).getCurrentTemperature()); } json.put("temps", temps); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(json.toString(2)); } } }
package org.endeavourhealth.hl7; import ca.uhn.hl7v2.DefaultHapiContext; import ca.uhn.hl7v2.HL7Exception; import ca.uhn.hl7v2.HapiContext; import ca.uhn.hl7v2.model.Message; import ca.uhn.hl7v2.model.v23.segment.MRG; import ca.uhn.hl7v2.parser.Parser; import ca.uhn.hl7v2.util.Terser; import ca.uhn.hl7v2.validation.impl.NoValidation; import com.google.common.base.Strings; import com.zaxxer.hikari.HikariDataSource; import org.apache.commons.lang3.StringUtils; import org.endeavourhealth.common.config.ConfigManager; import org.endeavourhealth.common.utility.SlackHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; public class Main { private static final Logger LOG = LoggerFactory.getLogger(Main.class); private static HikariDataSource connectionPool = null; private static HapiContext context; private static Parser parser; /** * utility to check the HL7 Receiver database and move any blocking messages to the Dead Letter Queue * * Parameters: * <db_connection_url> <driver_class> <db_username> <db_password> */ public static void main(String[] args) throws Exception { ConfigManager.Initialize("Hl7Checker"); if (args.length < 4) { LOG.error("Expecting four parameters:"); LOG.error("<db_connection_url> <driver_class> <db_username> <db_password>"); System.exit(0); return; } String url = args[0]; String driverClass = args[1]; String user = args[2]; String pass = args[3]; //optional fifth parameter puts it in read only mode boolean readOnly = false; if (args.length > 4) { readOnly = Boolean.parseBoolean(args[4]); } LOG.info("Starting HL7 Check on " + url); try { openConnectionPool(url, driverClass, user, pass); context = new DefaultHapiContext(); context.setValidationContext(new NoValidation()); parser = context.getGenericParser(); String sql = "SELECT message_id, channel_id, inbound_message_type, inbound_payload, error_message, pid2 FROM log.message WHERE error_message is not null;"; Connection connection = getConnection(); ResultSet resultSet = executeQuery(connection, sql); try { while (resultSet.next()) { int messageId = resultSet.getInt(1); int channelId = resultSet.getInt(2); String messageType = resultSet.getString(3); String inboundPayload = resultSet.getString(4); String errorMessage = resultSet.getString(5); String localPatientId = resultSet.getString(6); String ignoreReason = shouldIgnore(channelId, messageType, inboundPayload, errorMessage); if (!Strings.isNullOrEmpty(ignoreReason)) { if (readOnly) { LOG.info("Would have moved message " + messageId + " to the DLQ but in read only mode"); continue; } //if we have a non-null reason, move to the DLQ moveToDlq(messageId, ignoreReason); //and notify Slack that we've done so sendSlackMessage(channelId, messageId, ignoreReason, localPatientId); } } } finally { resultSet.close(); connection.close(); } } catch (Exception ex) { LOG.error("", ex); //although the error may be related to Homerton, just send to one channel for simplicity SlackHelper.sendSlackMessage(SlackHelper.Channel.Hl7ReceiverAlertsBarts, "Exception in HL7 Checker", ex); System.exit(0); } LOG.info("Completed HL7 Check on " + url); System.exit(0); } private static void sendSlackMessage(int channelId, int messageId, String ignoreReason, String localPatientId) throws Exception { SlackHelper.Channel channel = null; if (channelId == 1) { channel = SlackHelper.Channel.Hl7ReceiverAlertsHomerton; } else if (channelId == 2) { channel = SlackHelper.Channel.Hl7ReceiverAlertsBarts; } else { throw new Exception("Unknown channel " + channelId); } SlackHelper.sendSlackMessage(channel, "HL7 Checker moved message ID " + messageId + " (PatientId=" + localPatientId + "):\r\n" + ignoreReason); } /*private static String findMessageSource(int channelId) throws Exception { String sql = "SELECT channel_name FROM configuration.channel WHERE channel_id = " + channelId + ";"; Connection connection = getConnection(); ResultSet rs = executeQuery(connection, sql); if (!rs.next()) { throw new Exception("Failed to find name for channel " + channelId); } String ret = rs.getString(1); rs.close(); connection.close(); return ret; }*/ private static String shouldIgnore(int channelId, String messageType, String inboundPayload, String errorMessage) throws HL7Exception { LOG.info("Checking auto-DLQ rules"); LOG.info("channelId:" + channelId); LOG.info("messageType:" + messageType); LOG.info("errorMessage:" + errorMessage); LOG.info("inboundPayload:" + inboundPayload); // Rules for Homerton if (channelId == 1 && messageType.equals("ADT^A44") && errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[java.lang.NullPointerException] episodeIdentifierValue")) { Message hapiMsg = parser.parse(inboundPayload); Terser terser = new Terser(hapiMsg); String mergeEpisodeId = terser.get("/PATIENT/MRG-5"); LOG.info("mergeEpisodeId:" + mergeEpisodeId); // If merge episodeId is missing then move to DLQ if (Strings.isNullOrEmpty(mergeEpisodeId)) { return "Automatically moved A44 because of missing episode ID"; } String mergeEpisodeIdSource = terser.get("/PATIENT/MRG-5-4"); LOG.info("mergeEpisodeIdSource:" + mergeEpisodeIdSource); // If merge episodeId is from Newham then move to DLQ if (mergeEpisodeIdSource != null && mergeEpisodeIdSource.toUpperCase().startsWith("NEWHAM")) { return "Automatically moved A44 because of merging Newham episode"; } } if (channelId == 1 && messageType.equals("ADT^A44") && errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[java.lang.NullPointerException] patientIdentifierValue")) { Message hapiMsg = parser.parse(inboundPayload); Terser terser = new Terser(hapiMsg); String mergePatientId = terser.get("/PATIENT/MRG-1"); LOG.info("mergePatientId:" + mergePatientId); // If merge patientId is missing then move to DLQ if (Strings.isNullOrEmpty(mergePatientId)) { return "Automatically moved A44 because of missing MRG patientId ID"; } } // Added 2017-10-24 if (channelId == 1 && messageType.equals("ADT^A07") && errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[java.lang.IllegalArgumentException] episodeIdentifierValue")) { Message hapiMsg = parser.parse(inboundPayload); Terser terser = new Terser(hapiMsg); String episodeId = terser.get("/PV1-19"); LOG.info("episodeId:" + episodeId); // If episode id / encounter id is missing then move to DLQ if (Strings.isNullOrEmpty(episodeId)) { return "Automatically moved A07 because of missing PV1:19"; } } // Added 2017-11-08 if (channelId == 1 && messageType.equals("ADT^A34") && errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[org.endeavourhealth.hl7transform.common.TransformException] MRG segment exists less than 1 time(s)")) { Message hapiMsg = parser.parse(inboundPayload); MRG mrg = (MRG) hapiMsg.get("MRG"); // If MRG missing if (mrg == null) { return "Automatically moved A34 because of missing MRG"; } } // Rules for Barts if (channelId == 2 && messageType.equals("ADT^A31") && errorMessage.startsWith("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[org.endeavourhealth.hl7transform.common.TransformException] Could not create organisation ")) { Message hapiMsg = parser.parse(inboundPayload); Terser terser = new Terser(hapiMsg); String gpPracticeId = terser.get("/PD1-3-3"); LOG.info("Practice:" + gpPracticeId); // If practice id is missing or numeric then move to DLQ if (Strings.isNullOrEmpty(gpPracticeId) || StringUtils.isNumeric(gpPracticeId)) { return "Automatically moved A31 because of invalid practice code"; } } // Added 2017-10-25 if (channelId == 2 && messageType.equals("ADT^A03") && errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[java.lang.NullPointerException] episodeIdentifierValue")) { Message hapiMsg = parser.parse(inboundPayload); Terser terser = new Terser(hapiMsg); String episodeId = terser.get("/PV1-19"); LOG.info("episodeId:" + episodeId); // If episode id / encounter id is missing then move to DLQ if (Strings.isNullOrEmpty(episodeId)) { return "Automatically moved A03 because of missing PV1:19"; } } // Added 2017-11-07 if (channelId == 2 && messageType.equals("ADT^A08") && errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[java.lang.NullPointerException] episodeIdentifierValue")) { Message hapiMsg = parser.parse(inboundPayload); Terser terser = new Terser(hapiMsg); String episodeId = terser.get("/PV1-19"); LOG.info("episodeId:" + episodeId); // If episode id / encounter id is missing then move to DLQ if (Strings.isNullOrEmpty(episodeId)) { return "Automatically moved A08 because of missing PV1:19"; } } // Added 2017-11-08 if (channelId == 2 && messageType.equals("ADT^A34") && errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[org.endeavourhealth.hl7transform.common.TransformException] MRG segment exists less than 1 time(s)")) { LOG.info("Looking for MRG segment"); Message hapiMsg = parser.parse(inboundPayload); MRG mrg = (MRG) hapiMsg.get("MRG"); // If MRG missing if (mrg == null) { return "Automatically moved A34 because of missing MRG"; } else { LOG.info("MRG segment found"); } } // Added 2017-11-08 if (channelId == 2 && messageType.equals("ADT^A35") && errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[org.endeavourhealth.hl7transform.common.TransformException] MRG segment exists less than 1 time(s)")) { LOG.info("Looking for MRG segment"); Message hapiMsg = parser.parse(inboundPayload); MRG mrg = (MRG) hapiMsg.get("MRG"); // If MRG missing if (mrg == null) { return "Automatically moved A35 because of missing MRG"; } else { LOG.info("MRG segment found. isEmpty()=" + mrg.isEmpty()); } } //return null to indicate we don't ignore it return null; } private static void moveToDlq(int messageId, String reason) throws Exception { //although it looks like a select, it's just invoking a function which performs an update String sql = "SELECT helper.move_message_to_dead_letter(" + messageId + ", '" + reason + "');"; executeUpdate(sql); sql = "UPDATE log.message" + " SET next_attempt_date = now() - interval '1 hour'" + " WHERE message_id = " + messageId + ";"; executeUpdate(sql); } private static void openConnectionPool(String url, String driverClass, String username, String password) throws Exception { //force the driver to be loaded Class.forName(driverClass); HikariDataSource pool = new HikariDataSource(); pool.setJdbcUrl(url); pool.setUsername(username); pool.setPassword(password); pool.setMaximumPoolSize(4); pool.setMinimumIdle(1); pool.setIdleTimeout(60000); pool.setPoolName("Hl7CheckerPool" + url); pool.setAutoCommit(false); connectionPool = pool; //test getting a connection Connection conn = pool.getConnection(); conn.close(); } private static Connection getConnection() throws Exception { return connectionPool.getConnection(); } private static void executeUpdate(String sql) throws Exception { Connection connection = getConnection(); try { Statement statement = connection.createStatement(); statement.execute(sql); connection.commit(); } finally { connection.close(); } } private static ResultSet executeQuery(Connection connection, String sql) throws Exception { Statement statement = connection.createStatement(); return statement.executeQuery(sql); } }
package de.lancom.systems.stomp.core; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import de.lancom.systems.stomp.core.connection.StompConnection; import de.lancom.systems.stomp.core.connection.StompFrameAwaitJob; import de.lancom.systems.stomp.core.connection.StompFrameContext; import de.lancom.systems.stomp.core.connection.StompFrameTransmitJob; import de.lancom.systems.stomp.core.connection.StompSubscription; import de.lancom.systems.stomp.core.promise.DeferredFactory; import de.lancom.systems.stomp.core.promise.Promise; import de.lancom.systems.stomp.core.promise.callback.ExecutorCallback; import de.lancom.systems.stomp.core.util.NamedDaemonThreadFactory; import de.lancom.systems.stomp.core.wire.StompAction; import de.lancom.systems.stomp.core.wire.StompFrame; import de.lancom.systems.stomp.core.wire.StompHeader; import de.lancom.systems.stomp.core.wire.StompVersion; import de.lancom.systems.stomp.core.wire.frame.AckFrame; import de.lancom.systems.stomp.core.wire.frame.ConnectFrame; import de.lancom.systems.stomp.core.wire.frame.ConnectedFrame; import de.lancom.systems.stomp.core.wire.frame.DisconnectFrame; import de.lancom.systems.stomp.core.wire.frame.MessageFrame; import de.lancom.systems.stomp.core.wire.frame.NackFrame; import de.lancom.systems.stomp.core.wire.frame.ReceiptFrame; import de.lancom.systems.stomp.core.wire.frame.SendFrame; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; /** * Context for general information and settings used in stomp communication. */ @Slf4j public class StompContext { private static final long RECONNECT_TIMEOUT = 500; private static final long DEFAULT_TIMEOUT = 10000; private static final ExecutorService EXECUTOR_SERVICE = Executors.newCachedThreadPool( new NamedDaemonThreadFactory("Stomp") ); private final Map<String, Class<? extends StompFrame>> frameClasses = new HashMap<>(); private final List<StompConnection> connections = new CopyOnWriteArrayList<>(); private final AtomicBoolean running = new AtomicBoolean(); @Getter private final Selector selector; @Getter private final DeferredFactory deferred; @Getter @Setter private long timeout = DEFAULT_TIMEOUT; @Getter @Setter private boolean receiptsEnabled = true; @Getter @Setter private List<StompVersion> stompVersions = Arrays.asList( StompVersion.VERSION_1_0, StompVersion.VERSION_1_1, StompVersion.VERSION_1_2 ); /** * Create a new stomp context and run. * * @return context */ public static StompContext run() { final StompContext context = new StompContext(); context.start(); return context; } /** * Default constructor. */ public StompContext() { try { this.selector = Selector.open(); this.deferred = new DeferredFactory(EXECUTOR_SERVICE); // register client frames this.registerFrame(StompAction.CONNECT.value(), ConnectFrame.class); this.registerFrame(StompAction.DISCONNECT.value(), DisconnectFrame.class); this.registerFrame(StompAction.SEND.value(), SendFrame.class); this.registerFrame(StompAction.ACK.value(), AckFrame.class); this.registerFrame(StompAction.NACK.value(), NackFrame.class); // register server frames this.registerFrame(StompAction.CONNECTED.value(), ConnectedFrame.class); this.registerFrame(StompAction.RECEIPT.value(), ReceiptFrame.class); this.registerFrame(StompAction.MESSAGE.value(), MessageFrame.class); } catch (final Exception ex) { throw new RuntimeException("Failed to initialize stomp context", ex); } } /** * Register frame class for a given action. * * @param action action * @param frameClass frame class */ public void registerFrame(final String action, final Class<? extends StompFrame> frameClass) { this.frameClasses.put(action, frameClass); } /** * Create a new frame using the given action. * * @param action action * @return frame */ public StompFrame createFrame(final String action) { return createFrame(action, null); } /** * Create a new frame using the given action and headers. * * @param action action * @param headers headers * @return frame */ public StompFrame createFrame(final String action, final Map<String, String> headers) { final Class<? extends StompFrame> frameClass = frameClasses.get(action); final StompFrame frame; if (frameClass != null) { frame = createFrame(frameClass, headers); } else { frame = new StompFrame(action); } return frame; } /** * Create a new frame using the given frame class. * * @param frameClass frame class * @param <T> frame type * @return frame */ public <T extends StompFrame> T createFrame(final Class<T> frameClass) { return createFrame(frameClass, null); } /** * Create a new frame using the given frame class and headers. * * @param frameClass frame class * @param headers headers * @param <T> frame type * @return frame */ public <T extends StompFrame> T createFrame(final Class<T> frameClass, final Map<String, String> headers) { try { return frameClass.newInstance(); } catch (final Exception ex) { throw new RuntimeException("Could not defer frame parse class " + frameClass.getName(), ex); } } /** * Get connections. * * @return connections */ public List<StompConnection> getConnections() { return Collections.unmodifiableList(this.connections); } /** * Add a connection. * * @param connection connection */ public void addConnection(final StompConnection connection) { this.connections.add(connection); } /** * Remove a connection. * * @param connection connection */ public void removeConnection(final StompConnection connection) { this.connections.remove(connection); } /** * Start the client and listen for new frames. */ public void start() { if (running.compareAndSet(false, true)) { this.getDeferred().defer(new FrameTransmitter()); } } /** * Stop the client and close all connections. */ public void stop() { running.set(false); } /** * Frame receiver job. */ private final class FrameTransmitter implements ExecutorCallback { @Override public void execute() { while (running.get()) { try { selector.select(RECONNECT_TIMEOUT); for (final StompConnection connection : connections) { if (!connection.getTransmitJobs().isEmpty()) { if (connection.getState() == StompConnection.State.DISCONNECTED) { connection.connect(); } else { registerSubscriptions(connection); writeFrames(connection); } } } final Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); while (iterator.hasNext()) { final SelectionKey key = iterator.next(); try { readFrames((StompConnection) key.attachment()); } finally { iterator.remove(); } } } catch (final Exception ex) { if (log.isWarnEnabled()) { log.warn("Error processing stomp messages", ex); } } } final List<Promise<Void>> promises = new ArrayList<>(); for (final StompConnection connection : connections) { promises.add(connection.disconnect()); } final Iterator<Promise<Void>> iterator = promises.iterator(); while (iterator.hasNext()) { iterator.next().get(); iterator.remove(); } } /** * Register subscriptions of given connection if required. * * @param connection connection */ private void registerSubscriptions(final StompConnection connection) { for (final StompSubscription subscription : connection.getSubscriptionsForRegistration()) { subscription.subscribe(); } } /** * Write frames to connection. * * @param connection connection */ private void writeFrames(final StompConnection connection) { if (connection.getSerializer() != null) { final Iterator<StompFrameTransmitJob> transmitIterator = connection.getTransmitJobs().iterator(); while (transmitIterator.hasNext()) { final StompFrameTransmitJob job = transmitIterator.next(); final StompFrameContext context = job.getContext(); try { if (job.getCondition().getAsBoolean()) { connection.applyInterceptors(context); connection.getSerializer().writeFrame(context.getFrame()); transmitIterator.remove(); job.getDeferred().resolve(context); } } catch (final Exception ex) { connection.closeConnection(); if (log.isErrorEnabled()) { log.error(String.format( "Failed to write %s to %s, retrying", context.getFrame(), connection.toString() ), ex); } } } } } /** * Read frames from connection. * * @param connection connection */ private void readFrames(final StompConnection connection) { if (connection.getDeserializer() != null) { try { while (true) { StompFrame frame = connection.getDeserializer().readFrame(); if (frame != null) { if (log.isDebugEnabled()) { log.debug("Got " + frame); } final StompFrameContext context = new StompFrameContext(frame); connection.applyInterceptors(context); boolean handled = false; if (!handled) { final StompSubscription subscription; final String subscriptionId = frame.getHeader(StompHeader.SUBSCRIPTION); if (subscriptionId != null) { subscription = connection.getSubscription(subscriptionId); } else { subscription = null; } if (subscription != null) { deferred.defer(() -> { boolean success = false; try { success = subscription.getHandler().handle(context); } catch (final Exception ex) { success = false; } final String ack = context.getFrame().getHeader(StompHeader.ACK); if (ack != null) { if (success) { subscription.getConnection() .transmitFrame(new AckFrame(ack)) .fail(ex -> { if (log.isErrorEnabled()) { log.error("Could not send ack frame", ex); } }); } else { subscription.getConnection() .transmitFrame(new NackFrame(ack)) .fail(ex -> { if (log.isErrorEnabled()) { log.error("Could not send nack frame", ex); } }); } } }); handled = true; } } if (!handled) { final Iterator<StompFrameAwaitJob> awaitIterator = connection.getAwaitJobs().iterator(); while (!handled && awaitIterator.hasNext()) { final StompFrameAwaitJob job = awaitIterator.next(); if (job.getHandler().handle(context)) { awaitIterator.remove(); job.getDeferred().resolve(context); handled = true; } } } if (!handled && log.isWarnEnabled()) { log.warn("Frame {} has not been processed", frame); } } else { break; } } } catch (final Exception ex) { connection.closeConnection(); if (log.isErrorEnabled()) { log.error(String.format( "Failed to read frame from %s", connection.toString() ), ex); } } } } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.venky.swf.db.table; import com.venky.cache.Cache; import com.venky.core.collections.IgnoreCaseList; import com.venky.core.collections.LowerCaseStringCache; import com.venky.core.collections.SequenceMap; import com.venky.core.collections.SequenceSet; import com.venky.core.log.SWFLogger; import com.venky.core.log.TimerStatistics.Timer; import com.venky.core.string.StringUtil; import com.venky.core.util.MultiException; import com.venky.core.util.ObjectUtil; import com.venky.extension.Registry; import com.venky.swf.db.Database; import com.venky.swf.db.JdbcTypeHelper.TypeConverter; import com.venky.swf.db.JdbcTypeHelper.TypeRef; import com.venky.swf.db.annotations.column.COLUMN_DEF; import com.venky.swf.db.annotations.column.IS_VIRTUAL; import com.venky.swf.db.annotations.column.defaulting.StandardDefaulter; import com.venky.swf.db.annotations.column.pm.PARTICIPANT; import com.venky.swf.db.annotations.column.relationship.CONNECTED_VIA; import com.venky.swf.db.annotations.column.validations.processors.*; import com.venky.swf.db.annotations.model.CONFIGURATION; import com.venky.swf.db.annotations.model.validations.ModelValidator; import com.venky.swf.db.annotations.model.validations.UniqueKeyValidator; import com.venky.swf.db.model.Model; import com.venky.swf.db.model.User; import com.venky.swf.db.model.reflection.ModelReflector; import com.venky.swf.db.table.Table.ColumnDescriptor; import com.venky.swf.exceptions.AccessDeniedException; import com.venky.swf.routing.Config; import com.venky.swf.sql.*; import com.venky.swf.sql.parser.SQLExpressionParser; import java.lang.annotation.Annotation; import java.lang.reflect.*; import java.util.*; /** * * @author venky */ public class ModelInvocationHandler implements InvocationHandler { private Record record = null; private Class<? extends Model> modelClass = null; private List<String> virtualFields = new IgnoreCaseList(false); private String modelName = null; private transient Model proxy = null; private transient ModelReflector<? extends Model> reflector = null; @SuppressWarnings("unchecked") public <M extends Model> ModelReflector<M> getReflector() { if (reflector == null) { reflector = ModelReflector.instance(modelClass); } return (ModelReflector<M>) reflector; } public String getModelName(){ return modelName; } public String getPool(){ return getReflector().getPool(); } public Class<? extends Model> getModelClass(){ return modelClass; } /** * Used for serialization.: */ protected ModelInvocationHandler() { } public ModelInvocationHandler(Class<? extends Model> modelClass, Record record) { this.record = record; this.modelClass = modelClass; this.reflector = ModelReflector.instance(modelClass); this.modelName = Table.getSimpleModelClassName(reflector.getTableName()); this.virtualFields = reflector.getVirtualFields(); record.startTracking(false); } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { bootStrapProxy(getModelClass().cast(proxy)); String mName = method.getName(); Class<?> retType = method.getReturnType(); Class<?>[] parameters = method.getParameterTypes(); if (getReflector().getFieldGetterSignatures().contains(getReflector().getSignature(method))) { String fieldName = getReflector().getFieldName(method); if (!virtualFields.contains(fieldName)){ ColumnDescriptor cd = getReflector().getColumnDescriptor(fieldName); String columnName = cd.getName(); Object value = record.get(columnName); TypeRef<?> ref =Database.getJdbcTypeHelper(getPool()).getTypeRef(retType); TypeConverter<?> converter = ref.getTypeConverter(); if (value == null) { COLUMN_DEF colDef = getReflector().getAnnotation(method, COLUMN_DEF.class); if (colDef != null) { value = StandardDefaulter.getDefaultValue(colDef.value(), colDef.args()); } } if (value == null){ if (retType.isPrimitive()){ return converter.valueOf(value); }else { return value; } } else if (retType.isInstance(value) && !ref.isLOB()) { return value; } else { return converter.valueOf(value); } } } else if (getReflector().getFieldSetters().contains(method) ) { String fieldName = StringUtil.underscorize(mName.substring(3)); if (!virtualFields.contains(fieldName)){ String columnName = getReflector().getColumnDescriptor(fieldName).getName(); return record.put(columnName, args[0]); } } else if (getReflector().getReferredModelGetters().contains(method)) { if (!getReflector().isAnnotationPresent(method,IS_VIRTUAL.class)){ return getParent(method); } } else if (getReflector().getChildGetters().contains(method)) { if (!getReflector().isAnnotationPresent(method,IS_VIRTUAL.class)){ CONNECTED_VIA join = getReflector().getAnnotation(method,CONNECTED_VIA.class); if (join != null){ return getChildren(getReflector().getChildModelClass(method),join.value(),join.additional_join()); }else { return getChildren(getReflector().getChildModelClass(method)); } } } /* Optimization for (Object impl: modelImplObjects){ try { Method inModelImplClass = impl.getClass().getMethod(mName, parameters); if (retType.isAssignableFrom(inModelImplClass.getReturnType())){ Timer timer = startTimer(inModelImplClass.toString()); try { return inModelImplClass.invoke(impl, args); }catch(InvocationTargetException ex){ throw ex.getCause(); }finally{ timer.stop(); } } }catch(NoSuchMethodException ex){ // } } Method inCurrentClass = this.getClass().getMethod(mName, parameters); if (retType.isAssignableFrom(inCurrentClass.getReturnType())) { try { return inCurrentClass.invoke(this, args); }catch (InvocationTargetException ex){ throw ex.getCause(); } } else { throw new NoSuchMethodException("Donot know how to execute this method"); } */ Class<?> implClass = getMethodImplClass(method); Object implObject = null; if (implClass != null){ implObject = modelImplObjects.get(implClass); } if (implClass == null || implObject == null){ //implObject is null while constructing impls. implClass = this.getClass(); implObject = this; } Method inImplClass = implClass.getMethod(mName, parameters); if (retType.isAssignableFrom(inImplClass.getReturnType())) { Timer timer = cat().startTimer(inImplClass.toString()); try { return inImplClass.invoke(implObject, args); }catch (InvocationTargetException ex){ throw ex.getCause(); }finally{ timer.stop(); } }else { throw new NoSuchMethodException("Donot know how to execute " + getReflector().getSignature(method)); } } private SWFLogger cat() { return Config.instance().getLogger(getClass().getName()+"."+getModelName()); } @SuppressWarnings("unchecked") public <P extends Model> P getParent(Method parentGetter) { Class<P> parentClass = (Class<P>) parentGetter.getReturnType(); String parentIdFieldName = StringUtil.underscorize(parentGetter.getName().substring(3) +"Id"); Method parentIdGetter = this.getReflector().getFieldGetter(parentIdFieldName); Number parentId; try { parentId = (Number)parentIdGetter.invoke(proxy); } catch (Exception e) { throw new RuntimeException(parentIdFieldName,e); } P parent = null; if (parentId != null) { parent = Database.getTable(parentClass).get(parentId.longValue()); } return parent; } public <C extends Model> List<C> getChildren(Class<C> childClass){ Class<? extends Model> modelClass = getReflector().getModelClass(); ModelReflector<?> childReflector = ModelReflector.instance(childClass); Expression expression = new Expression(childReflector.getPool(),Conjunction.OR); for (String fieldName: childReflector.getFields()){ if (fieldName.endsWith("_ID")){ Method fieldGetter = childReflector.getFieldGetter(fieldName); Method referredModelGetter = childReflector.getReferredModelGetterFor(fieldGetter); if (referredModelGetter != null && ObjectUtil.equals(referredModelGetter.getReturnType().getSimpleName(),modelClass.getSimpleName())){ String columnName = childReflector.getColumnDescriptor(fieldName).getName(); expression.add(new Expression(childReflector.getPool(),columnName,Operator.EQ,proxy.getId())); } } } if (expression.isEmpty()){ throw new RuntimeException("Don;t know how to getChildren of kind " + childClass.getSimpleName() + " for " + modelClass.getSimpleName()); } return getChildren(childClass,expression); } public <C extends Model> List<C> getChildren(Class<C> childClass, String parentIdFieldName){ return getChildren(childClass,parentIdFieldName,null); } public <C extends Model> List<C> getChildren(Class<C> childClass, String parentIdFieldName, String addnl_condition){ long parentId = proxy.getId(); ModelReflector<C> childReflector = ModelReflector.instance(childClass); String parentIdColumnName = childReflector.getColumnDescriptor(parentIdFieldName).getName(); Expression where = new Expression(getPool(),Conjunction.AND); where.add(new Expression(getPool(),parentIdColumnName,Operator.EQ,new BindVariable(getPool(),parentId))); if (!ObjectUtil.isVoid(addnl_condition)){ Expression addnl = new SQLExpressionParser(childClass).parse(addnl_condition); where.add(addnl); } return getChildren(childClass, where); } public <C extends Model> List<C> getChildren(Class<C> childClass, Expression expression){ Select q = new Select(); q.from(childClass); q.where(expression); q.orderBy(ModelReflector.instance(childClass).getOrderBy()); return q.execute(childClass); } public <M extends Model> void setProxy(M proxy) { this.proxy = proxy; } @SuppressWarnings("unchecked") public <M extends Model> M getProxy() { return (M)proxy; } public boolean isAccessibleBy(User user){ return isAccessibleBy(user, getReflector().getModelClass()); } public Set<String> getParticipatingRoles(User user){ return getParticipatingRoles(user,getReflector().getModelClass()); } public Set<String> getParticipatingRoles(User user,Class<? extends Model> asModel){ if (!getReflector().reflects(asModel)){ throw new AccessDeniedException(); } return getParticipatingRoles(user, user.getParticipationOptions(asModel,getProxy())); } private Set<String> getParticipatingRoles(User user,Cache<String,Map<String,List<Long>>> pGroupOptions){ Timer timer = cat().startTimer(); try { ModelReflector<? extends Model> reflector = getReflector(); Set<String> participantingRoles = new HashSet<String>(); for (String participantRoleGroup : pGroupOptions.keySet()){ Map<String,List<Long>> pOptions = pGroupOptions.get(participantRoleGroup); for (String referencedModelIdFieldName :pOptions.keySet()){ Number referenceValue = reflector.get(getRawRecord(),referencedModelIdFieldName); PARTICIPANT participant = reflector.getAnnotation(reflector.getFieldGetter(referencedModelIdFieldName), PARTICIPANT.class); if (participant.redundant() || pOptions.get(referencedModelIdFieldName).contains(referenceValue)){ participantingRoles.add(reflector.getParticipatingRole(referencedModelIdFieldName)); } } if (!pOptions.isEmpty() && participantingRoles.isEmpty()){ throw new AccessDeniedException(); // User is not a participant on the model. } } return participantingRoles; }finally{ timer.stop(); } } public boolean isAccessibleBy(User user,Class<? extends Model> asModel){ Timer timer = cat().startTimer(null,Config.instance().isTimerAdditive()); try { if (!getReflector().reflects(asModel)){ return false; } Set<String> pRoles = getParticipatingRoles(user,asModel); return (pRoles != null);// It is always true. returning false depends on AccessDeniedException being thrown. }catch(AccessDeniedException ex){ return false; }finally{ timer.stop(); } } public Record getRawRecord(){ return record; } public static void dispose(){ modelImplClassesCache.clear(); methodImplClassCache.clear(); } public static <M extends Model> M getProxy(Class<M> modelClass, Record record) { ModelReflector<M> ref = ModelReflector.instance(modelClass); try { ModelInvocationHandler mImpl = new ModelInvocationHandler(modelClass, record); M m = modelClass.cast(Proxy.newProxyInstance(modelClass.getClassLoader(), ref.getClassHierarchies().toArray(new Class<?>[]{}), mImpl)); mImpl.bootStrapProxy(m); return m; } catch (Exception e) { throw new RuntimeException(e); } } private <M extends Model> void bootStrapProxy(M m) { if (proxy == null) { setProxy(m); if (modelImplObjects.isEmpty()){ List<Class<?>> modelImplClasses = getModelImplClasses(modelClass); for (Class<?> implClass: modelImplClasses){ addModelImplObject(constructImpl(implClass, m)); } }else { modelImplObjects.forEach((c,o) ->{ if (o instanceof ModelInvocationHandler) { ((ModelInvocationHandler) o).bootStrapProxy(m); } }); } } } @SuppressWarnings("unchecked") private static <M extends Model> Object constructImpl(Class<?> implClass, M m){ if (ModelImpl.class.isAssignableFrom(implClass)){ if (ModelImpl.class.equals(implClass)) { return new ModelImpl<M>(m); }else { ParameterizedType pt = (ParameterizedType)implClass.getGenericSuperclass(); Class<? extends Model> modelClass = (Class<? extends Model>) pt.getActualTypeArguments()[0]; try { return implClass.getConstructor(modelClass).newInstance(m); } catch (Exception e) { throw new RuntimeException(e); } } } throw new RuntimeException("Don't know how to instantiate " + implClass.getName()); } private SequenceMap<Class<?>,Object> modelImplObjects = new SequenceMap<Class<?>,Object>(); private void addModelImplObject(Object o){ modelImplObjects.put(o.getClass(),o); } private Class<?> getMethodImplClass(Method m){ return methodImplClassCache.get(getReflector().getModelClass()).get(m); } private static Cache<Class<? extends Model>,Cache<Method,Class<?>>> methodImplClassCache = new Cache<Class<? extends Model>, Cache<Method,Class<?>>>() { private static final long serialVersionUID = -8303755398345923039L; @Override protected Cache<Method, Class<?>> getValue(final Class<? extends Model> modelClass) { return new Cache<Method, Class<?>>() { private static final long serialVersionUID = 1322249489351360016L; @Override protected Class<?> getValue(Method method) { String mName = method.getName(); Class<?> retType = method.getReturnType(); Class<?>[] parameters = method.getParameterTypes(); for (Class<?> implClass: getModelImplClasses(modelClass)){ try { Method inModelImplClass = implClass.getMethod(mName, parameters); if (retType.isAssignableFrom(inModelImplClass.getReturnType())){ return implClass; } }catch (NoSuchMethodException ex){ } } return null; } }; } }; private static Cache<Class<? extends Model>,List<Class<?>>> modelImplClassesCache = new Cache<Class<? extends Model>, List<Class<?>>>() { private static final long serialVersionUID = 7544606584634901930L; @Override protected List<Class<?>> getValue(Class<? extends Model> modelClass) { SequenceSet<Class<? extends Model>> modelClasses = ModelReflector.instance(modelClass).getClassHierarchies(); List<Class<?>> modelImplClasses = new ArrayList<Class<?>>(); for (Class<?> c : modelClasses){ String modelImplClassName = c.getName()+"Impl"; try { Class<?> modelImplClass = Class.forName(modelImplClassName); if (ModelImpl.class.isAssignableFrom(modelImplClass)){ modelImplClasses.add(modelImplClass); }else { throw new ClassCastException(modelImplClassName + " does not extend " + ModelImpl.class.getName()); } }catch(ClassNotFoundException ex){ // Nothing } } return modelImplClasses; } }; private static <M extends Model> List<Class<?>> getModelImplClasses(Class<M> modelClass){ return modelImplClassesCache.get(modelClass); } public void save() { save(true); } public void save(boolean validate) { if (!isDirty()) { return; } if (validate){ validate(); } beforeSave(); if (record.isNewRecord()) { callExtensions("before.create"); create(); callExtensions("after.create"); } else { callExtensions("before.update"); update(); callExtensions("after.update"); } afterSave(); } public void init(){ } private static final Cache<String,List<FieldValidator<? extends Annotation>>> _fieldValidators = new Cache<String, List<FieldValidator<? extends Annotation>>>() { private static final long serialVersionUID = -8174150221673158116L; @Override protected List<FieldValidator<? extends Annotation>> getValue(String pool) { List<FieldValidator<? extends Annotation>> fieldValidators = new ArrayList<FieldValidator<? extends Annotation>>(); fieldValidators.add(new ExactLengthValidator(pool)); fieldValidators.add(new MaxLengthValidator(pool)); fieldValidators.add(new MinLengthValidator(pool)); fieldValidators.add(new NotNullValidator(pool)); fieldValidators.add(new RegExValidator(pool)); fieldValidators.add(new EnumerationValidator(pool)); fieldValidators.add(new DateFormatValidator(pool)); fieldValidators.add(new NumericRangeValidator(pool)); fieldValidators.add(new IntegerRangeValidator(pool)); return fieldValidators; } }; private static final List<ModelValidator> modelValidators = new ArrayList<ModelValidator>(); static{ modelValidators.add(new UniqueKeyValidator()); } protected boolean isModelValid(MultiException ex) { List<String> fields = getReflector().getEditableFields(); boolean ret = true; for (String field : fields) { MultiException fieldException = new MultiException(); if (!getReflector().isHouseKeepingField(field) && !isFieldValid(field,fieldException)) { ex.add(fieldException); ret = false; } } if (ret){ for (ModelValidator v : modelValidators){ ret = v.isValid(getProxy(),ex) && ret; } } return ret; } protected boolean isFieldValid(String field, MultiException fieldException) { boolean ret = true; Iterator<FieldValidator<? extends Annotation>> i = _fieldValidators.get(getPool()).iterator(); while (i.hasNext()) { FieldValidator<? extends Annotation> v = i.next(); ret = v.isValid(getProxy(), field, fieldException) && ret; } return ret; } protected void validate(){ beforeValidate(); MultiException me = new MultiException(); if (!isModelValid(me)) { throw me; } afterValidate(); } private <R extends Model> SequenceSet<String> getExtensionPoints(Class<R> modelClass, String extnPointNameSuffix){ SequenceSet<String> extnPoints = new SequenceSet<String>(); ModelReflector<R> ref = ModelReflector.instance(modelClass); for (Class<? extends Model> inHierarchy : ref.getClassHierarchies()){ String extnPoint = inHierarchy.getSimpleName() + "." + extnPointNameSuffix; extnPoints.add(extnPoint); } return extnPoints; } private <R extends Model> void callExtensions(String extnPointNameSuffix){ for (String extnPoint: getExtensionPoints(getReflector().getModelClass(), extnPointNameSuffix)){ Registry.instance().callExtensions(extnPoint, getProxy()); } } protected void beforeValidate(){ defaultFields(); callExtensions("before.validate"); } public void defaultFields(){ if (!record.isNewRecord()){ ColumnDescriptor updatedAt = getReflector().getColumnDescriptor("updated_at"); ColumnDescriptor updatorUser = getReflector().getColumnDescriptor("updater_user_id"); if (!updatedAt.isVirtual()){ proxy.setUpdatedAt(null); } if (!updatorUser.isVirtual()){ proxy.setUpdaterUserId(null); } } ModelReflector<? extends Model> reflector = getReflector(); for (String field:reflector.getRealFields()){ String columnName = reflector.getColumnDescriptor(field).getName(); if (record.get(columnName) == null){ Method fieldGetter = reflector.getFieldGetter(field); COLUMN_DEF cdef = reflector.getAnnotation(fieldGetter,COLUMN_DEF.class); if (cdef != null){ Object defaultValue = StandardDefaulter.getDefaultValue(cdef.value(),cdef.args(),reflector.getTimeZone()); record.put(columnName,defaultValue); } } } } protected void afterValidate(){ callExtensions("after.validate"); } protected void beforeSave() { callExtensions("before.save"); } protected void afterSave() { callExtensions("after.save"); } protected void beforeDestory(){ callExtensions("before.destroy"); } protected void afterDestroy(){ callExtensions("after.destroy"); } public boolean isBeingDestroyed(){ return beingDestroyed; } private boolean beingDestroyed = false; private void destroyCascade(){ ModelReflector<? extends Model> ref = getReflector(); for (Method childrenGetter : ref.getChildGetters()){ Class<? extends Model> childModelClass = ref.getChildModelClass(childrenGetter); ModelReflector<? extends Model> childReflector = ModelReflector.instance(childModelClass); List<String> referenceFields = childReflector.getReferenceFields(ref.getModelClass()); for (String referenceField: referenceFields){ try { if (childReflector.getRealModelClass() == null){ continue; } @SuppressWarnings("unchecked") List<Model> children = (List<Model>)childrenGetter.invoke(getProxy()); for (Model child : children){ if (childReflector.isFieldMandatory(referenceField)){ child.destroy(); }else { childReflector.set(child,referenceField,null); child.save(); } } } catch (Exception e) { throw new RuntimeException(e); } } } } public void destroy() { if (isBeingDestroyed()){ return; } try { beingDestroyed = true; beforeDestory(); destroyCascade(); Delete q = new Delete(getReflector()); Expression condition = new Expression(getPool(),Conjunction.AND); condition.add(new Expression(getPool(),getReflector().getColumnDescriptor("id").getName(),Operator.EQ,new BindVariable(getPool(),proxy.getId()))); condition.add(new Expression(getPool(),getReflector().getColumnDescriptor("lock_id").getName(),Operator.EQ,new BindVariable(getPool(),proxy.getLockId()))); q.where(condition); if (q.executeUpdate() <= 0){ throw new RecordNotFoundException(); } Database.getInstance().getCache(getReflector()).registerDestroy((Model)getProxy()); Database.getInstance().getCurrentTransaction().registerTableDataChanged(getReflector().getTableName()); afterDestroy(); }finally{ beingDestroyed = false; } } private void update() { int oldLockId = proxy.getLockId(); int newLockId = oldLockId + 1; Update q = new Update(getReflector()); Iterator<String> fI = record.getDirtyFields().iterator(); while (fI.hasNext()) { String columnName = fI.next(); String fieldName = getReflector().getFieldName(columnName); TypeRef<?> ref = Database.getJdbcTypeHelper(getPool()).getTypeRef(getReflector().getFieldGetter(fieldName).getReturnType()); q.set(columnName,new BindVariable(getPool(),record.get(columnName), ref)); } String idColumn = getReflector().getColumnDescriptor("id").getName(); Expression condition = new Expression(getPool(),Conjunction.AND); condition.add(new Expression(getPool(),idColumn,Operator.EQ,new BindVariable(getPool(),proxy.getId()))); ColumnDescriptor lockIdColumDescriptor = getReflector().getColumnDescriptor("lock_id"); if (!lockIdColumDescriptor.isVirtual()){ String lockidColumn = lockIdColumDescriptor.getName(); q.set(lockidColumn,new BindVariable(getPool(),newLockId)); condition.add(new Expression(getPool(),lockidColumn,Operator.EQ,new BindVariable(getPool(),oldLockId))); } q.where(condition); if (q.executeUpdate() <= 0){ throw new RecordNotFoundException(); } proxy.setLockId(newLockId); record.startTracking(); if (!getReflector().isAnnotationPresent(CONFIGURATION.class)){ record.setLocked(true); //Do only for transaction tables as config cache would need to be reset to false after commit. This is just to avoid that unwanted loop over config records cached. } Database.getInstance().getCache(getReflector()).registerUpdate((Model)getProxy()); Database.getInstance().getCurrentTransaction().registerTableDataChanged(getReflector().getTableName()); } private void create() { proxy.setLockId(0); //Table<? extends Model> table = Database.getTable(getReflector().getTableName()); Insert insertSQL = new Insert(getReflector()); Map<String,BindVariable> values = new HashMap<String, BindVariable>(); Iterator<String> columnIterator = record.getDirtyFields().iterator(); while (columnIterator.hasNext()) { String columnName = columnIterator.next(); String fieldName = getReflector().getFieldName(columnName); if (fieldName == null){ continue; } TypeRef<?> ref = Database.getJdbcTypeHelper(getPool()).getTypeRef(getReflector().getFieldGetter(fieldName).getReturnType()); values.put(columnName,new BindVariable(getPool(),record.get(columnName), ref)); } insertSQL.values(values); Record generatedValues = new Record(getPool()); Set<String> autoIncrementColumns = getReflector().getAutoIncrementColumns(); assert (autoIncrementColumns.size() <= 1); // atmost one auto increment id column List<String> generatedKeys = new ArrayList<String>(); for (String anAutoIncrementColumn:autoIncrementColumns){ if ( Database.getJdbcTypeHelper(getPool()).isColumnNameAutoLowerCasedInDB() ){ generatedKeys.add(LowerCaseStringCache.instance().get(anAutoIncrementColumn)); }else { generatedKeys.add(anAutoIncrementColumn); } } insertSQL.executeUpdate(generatedValues, generatedKeys.toArray(new String[]{})); if (generatedKeys.size() == 1){ if (generatedValues.getFieldNames().size() == 1){ String virtualFieldName = generatedValues.getFieldNames().iterator().next(); long id = ((Number)generatedValues.get(virtualFieldName)).longValue(); String fieldName = generatedKeys.get(0); record.put(fieldName, id); } } record.setNewRecord(false); record.startTracking(); if (!getReflector().isAnnotationPresent(CONFIGURATION.class)){ record.setLocked(true); } Database.getInstance().getCache(getReflector()).registerInsert((Model)getProxy()); Database.getInstance().getCurrentTransaction().registerTableDataChanged(getReflector().getTableName()); } @Override public boolean equals(Object o){ if (o == null){ return false; } if (!(o instanceof ModelInvocationHandler) && !getReflector().canReflect(o)){ return false; } if (o instanceof ModelInvocationHandler){ return equalImpl((ModelInvocationHandler)o); }else { return equalsProxy((Model)o); } } public int hashCode(){ return (getModelName() + ":" + getProxy().getId()).hashCode() ; } protected boolean equalImpl(ModelInvocationHandler anotherImpl){ return (getProxy().getId() == anotherImpl.getProxy().getId()) && getReflector().getTableName().equals(anotherImpl.getReflector().getTableName()); } protected boolean equalsProxy(Model anotherProxy){ boolean ret = false; if (anotherProxy != null){ ret = getProxy().getId() == anotherProxy.getId(); } return ret; } @SuppressWarnings("unchecked") public <M extends Model> M cloneProxy(){ return (M)getRawRecord().clone().getAsProxy(getReflector().getModelClass()); } private transient Map<String,Object> txnProperties = new HashMap<String, Object>(); public Object getTxnProperty(String name) { return txnProperties.get(name); } public void setTxnProperty(String name,Object value) { txnProperties.put(name, value); } public Object removeTxnProperty(String name) { return txnProperties.remove(name); } public boolean isDirty(){ return !getProxy().getRawRecord().getDirtyFields().isEmpty(); } }
package ca.corefacility.bioinformatics.irida.ria.integration.projects; import ca.corefacility.bioinformatics.irida.ria.integration.AbstractIridaUIITChromeDriver; import ca.corefacility.bioinformatics.irida.ria.integration.pages.LoginPage; import ca.corefacility.bioinformatics.irida.ria.integration.pages.ProjectsNewPage; import ca.corefacility.bioinformatics.irida.ria.integration.pages.projects.ProjectMetadataPage; import ca.corefacility.bioinformatics.irida.ria.integration.pages.projects.ProjectSamplesPage; import com.github.springtestdbunit.annotation.DatabaseSetup; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.Assert.*; import java.util.List; /** * <p> * Integration test to ensure that the ProjectsNew Page. * </p> * */ @DatabaseSetup("/ca/corefacility/bioinformatics/irida/ria/web/ProjectsPageIT.xml") public class ProjectsNewPageIT extends AbstractIridaUIITChromeDriver { private static final Logger logger = LoggerFactory.getLogger(ProjectsNewPageIT.class); private ProjectsNewPage page; @Before public void setUpTest() { LoginPage.loginAsManager(driver()); page = new ProjectsNewPage(driver()); } @Test public void testCreateNewProjectForm() { logger.debug("Testing: CreateNewProjectFrom"); page.goToPage(); assertEquals("Should have the correct page title", "IRIDA Platform - Create a New Project", driver().getTitle()); // Start with just submitting the empty form page.submitForm("", "", "", ""); assertTrue("Should show a required error.", page.isErrorNameRequiredDisplayed()); // Clear the error by adding a name page.setName("Random Name"); assertFalse("Error Field should be gone", page.formHasErrors()); // Let's try adding a bad url page.goToPage(); page.setRemoteURL("red dog"); assertTrue("Should have a bad url error", page.isErrorUrlDisplayed()); // Let add a good url page.setRemoteURL("http://google.com"); assertFalse("URL Error Field should be gone", page.formHasErrors()); // Create the project page.goToPage(); page.submitForm("test project name", "", "", ""); page.clickSubmit(); ProjectMetadataPage metadataPage = new ProjectMetadataPage(driver()); assertTrue("Should be on metadata page which has edit button", metadataPage.hasEditButton()); } @Test public void testCustomTaxa() { page.goToPage(); page.setOrganism("something new"); assertTrue("warning should be displayed", page.isNewOrganismWarningDisplayed()); page.setOrganism(ProjectsNewPage.EXISTING_TAXA); assertFalse("warning should not be displayed", page.isNewOrganismWarningDisplayed()); } @Test public void testProjectFromCart() { // get samples from original project and add to cart ProjectSamplesPage samplesPage = ProjectSamplesPage.gotToPage(driver(), 1); List<String> originalSamples = samplesPage.getSampleNamesOnPage(); samplesPage.selectAllSamples(); samplesPage.addSelectedSamplesToCart(); // create project page.goToPageWithCart(); page.setName("newProjectWithSamples"); page.clickSubmit(); ProjectMetadataPage metadataPage = new ProjectMetadataPage(driver()); assertTrue("Should be on metadata page which has edit buttong", metadataPage.hasEditButton()); Long projectId = metadataPage.getProjectId(); // check if samples match samplesPage = ProjectSamplesPage.gotToPage(driver(), projectId.intValue()); List<String> sampleNames = samplesPage.getSampleNamesOnPage(); assertFalse("Should have samples", sampleNames.isEmpty()); assertEquals("should have the same samples as the other project", originalSamples, sampleNames); } }
package club.zhcs.thunder.module.admin.settings; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.nutz.dao.Cnd; import org.nutz.ioc.impl.PropertiesProxy; import org.nutz.ioc.loader.annotation.Inject; import org.nutz.lang.ContinueLoop; import org.nutz.lang.Each; import org.nutz.lang.ExitLoop; import org.nutz.lang.Lang; import org.nutz.lang.LoopException; import org.nutz.mvc.Mvcs; import org.nutz.mvc.annotation.At; import org.nutz.mvc.annotation.GET; import org.nutz.mvc.annotation.Ok; import org.nutz.mvc.annotation.POST; import org.nutz.mvc.annotation.Param; import org.nutz.weixin.bean.WxMenu; import org.nutz.weixin.impl.WxApi2Impl; import org.nutz.weixin.spi.WXAccountApi.Type; import org.nutz.weixin.spi.WxResp; import club.zhcs.thunder.bean.config.WechatMenu; import club.zhcs.thunder.bean.config.WxConfig; import club.zhcs.thunder.biz.config.WechatMenuService; import club.zhcs.thunder.biz.config.WxConfigService; import club.zhcs.thunder.ext.shiro.anno.ThunderRequiresPermissions; import club.zhcs.thunder.vo.InstallPermission; import club.zhcs.titans.nutz.module.base.AbstractBaseModule; import club.zhcs.titans.utils.db.Result; @At("/setting/wechat") public class WechatSettingModule extends AbstractBaseModule { @Inject WxConfigService wxConfigService; @Inject PropertiesProxy config; @Inject WxApi2Impl wxApi; @Inject WechatMenuService wechatMenuService; @At("/menu/add") @ThunderRequiresPermissions(InstallPermission.CONFIG_WECHAT) @GET @Ok("beetl:pages/admin/setting/menu_add.html") public Result addMenu() { return Result.success().addData("types", WechatMenu.Type.values()).addData("menus", wechatMenuService.query(Cnd.where("parentId", "=", 0))); } @At("/menu/add") @ThunderRequiresPermissions(InstallPermission.CONFIG_WECHAT) @POST public Result addMenu(@Param("..") WechatMenu menu) { return wechatMenuService.save(menu) != null ? Result.success() : Result.fail("!"); } @At @ThunderRequiresPermissions(InstallPermission.CONFIG_WECHAT) public Result addOrUpdate(@Param("..") WxConfig config) { if (wxConfigService.queryAll().size() == 0) { config = wxConfigService.save(config); if (config != null) { modifyApi(config); } return config == null ? Result.fail("!<br>:") : Result.success(); } else { int r = wxConfigService.update(config, Cnd.where("1", "=", 1), "appid", "appsecret", "token", "encodingAesKey"); if (r == 1) { modifyApi(config); } return r == 1 ? Result.success() : Result.fail("!<br>:"); } } @At("/menu/asyn") @GET @ThunderRequiresPermissions(InstallPermission.CONFIG_WECHAT) @Ok("beetl:pages/admin/setting/menu_asyn.html") public Result asynMenu() { List<WechatMenu> menus = wechatMenuService.query(Cnd.where("parentId", "=", 0).orderBy("index", "ASC")); Lang.each(menus, new Each<WechatMenu>() { @Override public void invoke(int index, WechatMenu menu, int length) throws ExitLoop, ContinueLoop, LoopException { menu.setSubMenus( wechatMenuService.query(Cnd.where("parentId", "=", menu.getId()).orderBy("index", "ASC"))); } }); return Result.success().addData("menus", menus).addData("wxMenu", wechatMenuService.exchange(menus)); } @At("/menu/asyn") @POST @ThunderRequiresPermissions(InstallPermission.CONFIG_WECHAT) public Result asynMenuToWechat() { List<WxMenu> menus = wechatMenuService.getWxMenus(); WxResp resp = wxApi.menu_create(menus); if (resp.ok()) { return Result.success(); } return Result.fail(resp.errmsg()); } @At("/menu/delete") @ThunderRequiresPermissions(InstallPermission.CONFIG_WECHAT) public Result deleteMenu(@Param("id") int id) { return wechatMenuService.delete(id) == 1 ? Result.success() : Result.fail("!"); }
package br.com.caelum.vraptor.interceptor; import static java.lang.String.format; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import net.vidageek.mirror.list.dsl.MirrorList; import br.com.caelum.vraptor.AfterCall; import br.com.caelum.vraptor.AroundCall; import br.com.caelum.vraptor.BeforeCall; import br.com.caelum.vraptor.InterceptionException; @ApplicationScoped public class NoInterceptMethodsValidationRule implements ValidationRule { private StepInvoker stepInvoker; @Inject public NoInterceptMethodsValidationRule(StepInvoker stepInvoker) { this.stepInvoker = stepInvoker; } @Override public void validate(Class<?> originalType, MirrorList<Method> methods) { boolean hasAfterMethod = notNull(AfterCall.class, originalType, methods); boolean hasAroundMethod = notNull(AroundCall.class, originalType, methods); boolean hasBeforeMethod = notNull(BeforeCall.class, originalType, methods); if (!hasAfterMethod && !hasAroundMethod && !hasBeforeMethod) { throw new InterceptionException(format("Interceptor %s must " + "declare at least one method whith @AfterCall, @AroundCall " + "or @BeforeCall annotation", originalType.getCanonicalName())); } } private boolean notNull(Class<? extends Annotation> step, Class<?> originalType, MirrorList<Method> methods) { return stepInvoker.findMethod(methods, step, originalType) != null; } }
package org.ow2.chameleon.wisdom.maven.utils; import aQute.lib.osgi.*; import org.apache.commons.io.IOUtils; import org.apache.felix.ipojo.manipulator.Pojoization; import org.apache.maven.artifact.Artifact; import org.apache.maven.model.License; import org.apache.maven.model.Model; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.PropertyUtils; import org.ow2.chameleon.wisdom.maven.mojos.AbstractWisdomMojo; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.util.*; /** * Packages the bundle using BND. Have to be as close as possible from the Wisdom Test Probe Maker. */ public class BundlePackagerExecutor { public static final String INSTRUCTIONS_FILE = "src/main/osgi/osgi.bnd"; private static final String MAVEN_SYMBOLICNAME = "maven-symbolicname"; public static void execute(AbstractWisdomMojo mojo, File output) throws Exception { Properties properties = getDefaultProperties(mojo, mojo.project); boolean provided = readInstructionsFromBndFiles(properties, mojo.basedir); if (! provided) { // Using defaults if there are no bnd file. populatePropertiesWithDefaults(mojo.basedir, properties); } Builder builder = getOSGiBuilder(mojo, properties, computeClassPath(mojo)); buildOSGiBundle(builder); reportErrors("BND ~> ", builder.getWarnings(), builder.getErrors()); File bnd = File.createTempFile("bnd-", ".jar"); File ipojo = File.createTempFile("ipojo-", ".jar"); builder.getJar().write(bnd); Pojoization pojoization = new Pojoization(); pojoization.pojoization(bnd, ipojo, new File(mojo.basedir, "src/main/resources")); reportErrors("iPOJO ~> ", pojoization.getWarnings(), pojoization.getErrors()); ipojo.renameTo(output); } private static void populatePropertiesWithDefaults(File basedir, Properties properties) throws IOException { List<String> privates = new ArrayList<>(); List<String> exports = new ArrayList<>(); File classes = new File(basedir, "target/classes"); Set<String> packages = new LinkedHashSet<>(); if (classes.isDirectory()) { Jar jar = new Jar(".", classes); packages.addAll(jar.getPackages()); } for (String s : packages) { if (s.endsWith("service") || s.endsWith("services")) { exports.add(s); } else { if (! s.isEmpty()) { privates.add(s + ";-split-package:=merge-first"); } } } properties.put(Constants.PRIVATE_PACKAGE, toClause(privates)); if (!exports.isEmpty()) { properties.put(Constants.EXPORT_PACKAGE, toClause(privates)); } // Already set. // properties.put(Constants.IMPORT_PACKAGE, "*"); } private static String toClause(List<String> packages) { StringBuilder builder = new StringBuilder(); for (String p : packages) { if (builder.length() != 0) { builder.append(", "); } builder.append(p); } return builder.toString(); } private static Jar[] computeClassPath(AbstractWisdomMojo mojo) throws IOException { List<Jar> list = new ArrayList<>(); File classes = new File(mojo.basedir, "target/classes"); if (classes.isDirectory()) { list.add(new Jar(".", classes)); } for (Artifact artifact : mojo.project.getArtifacts()) { if (artifact.getArtifactHandler().isAddedToClasspath()) { if (!Artifact.SCOPE_TEST.equals(artifact.getScope())) { File file = artifact.getFile(); if (file == null) { mojo.getLog().warn( "File is not available for artifact " + artifact + " in project " + mojo.project.getArtifact()); continue; } Jar jar = new Jar(artifact.getArtifactId(), file); list.add(jar); } } } Jar[] cp = new Jar[list.size()]; list.toArray(cp); return cp; } protected static Builder getOSGiBuilder(AbstractWisdomMojo mojo, Properties properties, Jar[] classpath) throws Exception { Builder builder = new Builder(); synchronized (BundlePackagerExecutor.class) { builder.setBase(mojo.basedir); } builder.setProperties(sanitize(properties)); if (classpath != null) { builder.setClasspath(classpath); } return builder; } private static boolean readInstructionsFromBndFiles(Properties properties, File basedir) throws IOException { Properties props = new Properties(); File instructionFile = new File(basedir, INSTRUCTIONS_FILE); if (instructionFile.isFile()) { InputStream is = new FileInputStream(instructionFile); properties.load(is); IOUtils.closeQuietly(is); } else { return false; } // Insert in the given properties to the list of properties. @SuppressWarnings("unchecked") Enumeration<String> names = (Enumeration<String>) props.propertyNames(); while (names.hasMoreElements()) { String key = names.nextElement(); properties.put(key, props.getProperty(key)); } return true; } protected static Properties sanitize(Properties properties) { // convert any non-String keys/values to Strings Properties sanitizedEntries = new Properties(); for (Iterator itr = properties.entrySet().iterator(); itr.hasNext(); ) { Map.Entry entry = (Map.Entry) itr.next(); if (!(entry.getKey() instanceof String)) { String key = sanitize(entry.getKey()); if (!properties.containsKey(key)) { sanitizedEntries.setProperty(key, sanitize(entry.getValue())); } itr.remove(); } else if (!(entry.getValue() instanceof String)) { entry.setValue(sanitize(entry.getValue())); } } properties.putAll(sanitizedEntries); return properties; } protected static String sanitize(Object value) { if (value instanceof String) { return (String) value; } else if (value instanceof Iterable) { String delim = ""; StringBuilder buf = new StringBuilder(); for (Object i : (Iterable<?>) value) { buf.append(delim).append(i); delim = ", "; } return buf.toString(); } else if (value.getClass().isArray()) { String delim = ""; StringBuilder buf = new StringBuilder(); for (int i = 0, len = Array.getLength(value); i < len; i++) { buf.append(delim).append(Array.get(value, i)); delim = ", "; } return buf.toString(); } else { return String.valueOf(value); } } protected static Builder buildOSGiBundle(Builder builder) throws Exception { builder.build(); return builder; } protected static boolean reportErrors(String prefix, List<String> warnings, List<String> errors) { for (String msg : warnings) { System.err.println(prefix + " : " + msg); } boolean hasErrors = false; String fileNotFound = "Input file does not exist: "; for (String msg : errors) { if (msg.startsWith(fileNotFound) && msg.endsWith("~")) { // treat as warning; this error happens when you have duplicate entries in Include-Resource String duplicate = Processor.removeDuplicateMarker(msg.substring(fileNotFound.length())); System.err.println(prefix + " Duplicate path '" + duplicate + "' in Include-Resource"); } else { System.err.println(prefix + " : " + msg); hasErrors = true; } } return hasErrors; } private static void header(Properties properties, String key, Object value) { if (value == null) return; if (value instanceof Collection && ((Collection) value).isEmpty()) return; properties.put(key, value.toString().replaceAll("[\r\n]", "")); } private static Map getProperties(Model projectModel, String prefix) { Map properties = new LinkedHashMap(); Method methods[] = Model.class.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { String name = methods[i].getName(); if (name.startsWith("get")) { try { Object v = methods[i].invoke(projectModel, null); if (v != null) { name = prefix + Character.toLowerCase(name.charAt(3)) + name.substring(4); if (v.getClass().isArray()) properties.put(name, Arrays.asList((Object[]) v).toString()); else properties.put(name, v); } } catch (Exception e) { // too bad } } } return properties; } private static StringBuffer printLicenses(List licenses) { if (licenses == null || licenses.size() == 0) return null; StringBuffer sb = new StringBuffer(); String del = ""; for (Object license : licenses) { License l = (License) license; String url = l.getUrl(); if (url == null) continue; sb.append(del); sb.append(url); del = ", "; } if (sb.length() == 0) return null; return sb; } protected static Properties getDefaultProperties(AbstractWisdomMojo mojo, MavenProject currentProject) { Properties properties = new Properties(); DefaultMaven2OsgiConverter converter = new DefaultMaven2OsgiConverter(); String bsn; try { bsn = converter.getBundleSymbolicName(currentProject.getArtifact()); } catch (Exception e) { bsn = currentProject.getGroupId() + "." + currentProject.getArtifactId(); } // Setup defaults properties.put(MAVEN_SYMBOLICNAME, bsn); properties.put(Analyzer.BUNDLE_SYMBOLICNAME, bsn); properties.put(Analyzer.IMPORT_PACKAGE, "*"); properties.put(Analyzer.BUNDLE_VERSION, converter.getVersion(currentProject.getVersion())); // remove the extraneous Include-Resource and Private-Package entries from generated manifest properties.put(Constants.REMOVEHEADERS, Analyzer.INCLUDE_RESOURCE + ',' + Analyzer.PRIVATE_PACKAGE); header(properties, Analyzer.BUNDLE_DESCRIPTION, currentProject.getDescription()); StringBuffer licenseText = printLicenses(currentProject.getLicenses()); if (licenseText != null) { header(properties, Analyzer.BUNDLE_LICENSE, licenseText); } header(properties, Analyzer.BUNDLE_NAME, currentProject.getName()); if (currentProject.getOrganization() != null) { if (currentProject.getOrganization().getName() != null) { String organizationName = currentProject.getOrganization().getName(); header(properties, Analyzer.BUNDLE_VENDOR, organizationName); properties.put("project.organization.name", organizationName); properties.put("pom.organization.name", organizationName); } if (currentProject.getOrganization().getUrl() != null) { String organizationUrl = currentProject.getOrganization().getUrl(); header(properties, Analyzer.BUNDLE_DOCURL, organizationUrl); properties.put("project.organization.url", organizationUrl); properties.put("pom.organization.url", organizationUrl); } } properties.putAll(currentProject.getProperties()); properties.putAll(currentProject.getModel().getProperties()); for (String s : currentProject.getFilters()) { File filterFile = new File(s); if (filterFile.isFile()) { properties.putAll(PropertyUtils.loadProperties(filterFile)); } } if (mojo.session != null) { try { // don't pass upper-case session settings to bnd as they end up in the manifest Properties sessionProperties = mojo.session.getExecutionProperties(); for (Enumeration e = sessionProperties.propertyNames(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); if (key.length() > 0 && !Character.isUpperCase(key.charAt(0))) { properties.put(key, sessionProperties.getProperty(key)); } } } catch (Exception e) { mojo.getLog().warn("Problem with Maven session properties: " + e.getLocalizedMessage()); } } properties.putAll(getProperties(currentProject.getModel(), "project.build.")); properties.putAll(getProperties(currentProject.getModel(), "pom.")); properties.putAll(getProperties(currentProject.getModel(), "project.")); properties.put("project.baseDir", mojo.basedir); properties.put("project.build.directory", mojo.buildDirectory); properties.put("project.build.outputdirectory", new File(mojo.buildDirectory, "classes")); return properties; } }
package org.kuali.kfs.module.ar.service.impl; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.sql.Date; import java.sql.Timestamp; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.kuali.kfs.coa.businessobject.Account; import org.kuali.kfs.coa.businessobject.AccountingPeriod; import org.kuali.kfs.coa.businessobject.ObjectType; import org.kuali.kfs.coa.service.AccountService; import org.kuali.kfs.coa.service.AccountingPeriodService; import org.kuali.kfs.gl.businessobject.Balance; import org.kuali.kfs.integration.ar.AccountsReceivableCustomer; import org.kuali.kfs.integration.cg.ContractsAndGrantsBillingAgency; import org.kuali.kfs.integration.cg.ContractsAndGrantsBillingAward; import org.kuali.kfs.integration.cg.ContractsAndGrantsBillingAwardAccount; import org.kuali.kfs.integration.cg.ContractsAndGrantsModuleBillingService; import org.kuali.kfs.integration.cg.ContractsAndGrantsOrganization; import org.kuali.kfs.module.ar.ArConstants; import org.kuali.kfs.module.ar.ArKeyConstants; import org.kuali.kfs.module.ar.ArParameterKeyConstants; import org.kuali.kfs.module.ar.ArPropertyConstants; import org.kuali.kfs.module.ar.batch.service.VerifyBillingFrequencyService; import org.kuali.kfs.module.ar.businessobject.AccountsReceivableDocumentHeader; import org.kuali.kfs.module.ar.businessobject.AwardAccountObjectCodeTotalBilled; import org.kuali.kfs.module.ar.businessobject.Bill; import org.kuali.kfs.module.ar.businessobject.ContractsGrantsInvoiceDetail; import org.kuali.kfs.module.ar.businessobject.ContractsGrantsInvoiceDocumentErrorLog; import org.kuali.kfs.module.ar.businessobject.ContractsGrantsInvoiceDocumentErrorMessage; import org.kuali.kfs.module.ar.businessobject.CostCategory; import org.kuali.kfs.module.ar.businessobject.Customer; import org.kuali.kfs.module.ar.businessobject.CustomerAddress; import org.kuali.kfs.module.ar.businessobject.InvoiceAccountDetail; import org.kuali.kfs.module.ar.businessobject.InvoiceAddressDetail; import org.kuali.kfs.module.ar.businessobject.InvoiceBill; import org.kuali.kfs.module.ar.businessobject.InvoiceDetailAccountObjectCode; import org.kuali.kfs.module.ar.businessobject.InvoiceGeneralDetail; import org.kuali.kfs.module.ar.businessobject.InvoiceMilestone; import org.kuali.kfs.module.ar.businessobject.Milestone; import org.kuali.kfs.module.ar.dataaccess.AwardAccountObjectCodeTotalBilledDao; import org.kuali.kfs.module.ar.document.ContractsGrantsInvoiceDocument; import org.kuali.kfs.module.ar.document.service.AccountsReceivableDocumentHeaderService; import org.kuali.kfs.module.ar.document.service.ContractsGrantsBillingAwardVerificationService; import org.kuali.kfs.module.ar.document.service.ContractsGrantsInvoiceDocumentService; import org.kuali.kfs.module.ar.document.service.CustomerService; import org.kuali.kfs.module.ar.service.ContractsGrantsBillingUtilityService; import org.kuali.kfs.module.ar.service.ContractsGrantsInvoiceCreateDocumentService; import org.kuali.kfs.module.ar.service.CostCategoryService; import org.kuali.kfs.sys.KFSConstants; import org.kuali.kfs.sys.KFSPropertyConstants; import org.kuali.kfs.sys.businessobject.FinancialSystemDocumentHeader; import org.kuali.kfs.sys.businessobject.SystemOptions; import org.kuali.kfs.sys.document.service.FinancialSystemDocumentService; import org.kuali.kfs.sys.document.validation.event.DocumentSystemSaveEvent; import org.kuali.kfs.sys.service.OptionsService; import org.kuali.kfs.sys.service.UniversityDateService; import org.kuali.rice.core.api.config.property.ConfigurationService; import org.kuali.rice.core.api.datetime.DateTimeService; import org.kuali.rice.core.api.util.type.KualiDecimal; import org.kuali.rice.coreservice.framework.parameter.ParameterService; import org.kuali.rice.kew.api.document.DocumentStatus; import org.kuali.rice.kew.api.exception.WorkflowException; import org.kuali.rice.krad.service.BusinessObjectService; import org.kuali.rice.krad.service.DocumentService; import org.kuali.rice.krad.service.KualiModuleService; import org.kuali.rice.krad.util.ErrorMessage; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.util.ObjectUtils; import org.kuali.rice.krad.workflow.service.WorkflowDocumentService; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; /** * This is the default implementation of the ContractsGrantsInvoiceDocumentCreateService interface. * * @see org.kuali.kfs.module.ar.batch.service.ContractsGrantsInvoiceDocumentCreateService */ @Transactional public class ContractsGrantsInvoiceCreateDocumentServiceImpl implements ContractsGrantsInvoiceCreateDocumentService { private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(ContractsGrantsInvoiceCreateDocumentServiceImpl.class); protected AccountService accountService; protected AccountingPeriodService accountingPeriodService; protected AccountsReceivableDocumentHeaderService accountsReceivableDocumentHeaderService; protected AwardAccountObjectCodeTotalBilledDao awardAccountObjectCodeTotalBilledDao; protected BusinessObjectService businessObjectService; protected ConfigurationService configurationService; protected ContractsGrantsBillingAwardVerificationService contractsGrantsBillingAwardVerificationService; protected ContractsGrantsBillingUtilityService contractsGrantsBillingUtilityService; protected ContractsAndGrantsModuleBillingService contractsAndGrantsModuleBillingService; protected ContractsGrantsInvoiceDocumentService contractsGrantsInvoiceDocumentService; protected CostCategoryService costCategoryService; protected CustomerService customerService; protected DateTimeService dateTimeService; protected DocumentService documentService; protected FinancialSystemDocumentService financialSystemDocumentService; protected KualiModuleService kualiModuleService; protected ParameterService parameterService; protected VerifyBillingFrequencyService verifyBillingFrequencyService; protected WorkflowDocumentService workflowDocumentService; protected UniversityDateService universityDateService; protected OptionsService optionsService; public static final String REPORT_LINE_DIVIDER = " @Override public List<ErrorMessage> createCGInvoiceDocumentsByAwards(Collection<ContractsAndGrantsBillingAward> awards, ArConstants.ContractsAndGrantsInvoiceDocumentCreationProcessType creationProcessTypeCode) { List<ErrorMessage> errorMessages = createInvoices(awards); if (!CollectionUtils.isEmpty(errorMessages)) { storeCreationErrors(errorMessages, creationProcessTypeCode.getCode()); } return errorMessages; } /** * This method iterates through awards and create cgInvoice documents * @param awards used to create cgInvoice documents * @return List of error messages (if any) */ protected List<ErrorMessage> createInvoices(Collection<ContractsAndGrantsBillingAward> awards) { List<ErrorMessage> errorMessages = new ArrayList<ErrorMessage>(); if (ObjectUtils.isNotNull(awards) && awards.size() > 0) { for (ContractsAndGrantsBillingAward awd : awards) { String invOpt = awd.getInvoicingOptionCode(); final ContractsAndGrantsOrganization awardOrganization = awd.getPrimaryAwardOrganization(); if (ObjectUtils.isNull(awardOrganization)) { final ErrorMessage errorMessage = new ErrorMessage(ArKeyConstants.ContractsGrantsInvoiceCreateDocumentConstants.NO_ORGANIZATION_ON_AWARD, awd.getProposalNumber().toString()); errorMessages.add(errorMessage); } else { if (invOpt.equals(ArConstants.INV_ACCOUNT)) { // case 1: create Contracts Grants Invoice by accounts createInvoicesByAccounts(awd, errorMessages); } else if (invOpt.equals(ArConstants.INV_CONTRACT_CONTROL_ACCOUNT)) { // case 2: create Contracts Grants Invoices by contractControlAccounts createInvoicesByContractControlAccounts(awd, errorMessages); } // case 3: create Contracts Grants Invoice by award else if (invOpt.equals(ArConstants.INV_AWARD)) { createInvoicesByAward(awd, errorMessages); } } } } else { final ErrorMessage errorMessage = new ErrorMessage(ArKeyConstants.ContractsGrantsInvoiceCreateDocumentConstants.NO_AWARD); errorMessages.add(errorMessage); } return errorMessages; } /** * Generates and saves a single contracts and grants invoice document based on the given award * @param awd the award to generate a contracts and grants invoice document for * @param errLines a holder for error messages */ protected void createInvoicesByAward(ContractsAndGrantsBillingAward awd, List<ErrorMessage> errorMessages) { // Check if awardaccounts has the same control account int accountNum = awd.getActiveAwardAccounts().size(); Collection<Account> controlAccounts = getContractsGrantsInvoiceDocumentService().getContractControlAccounts(awd); if (controlAccounts == null || controlAccounts.size() < accountNum) { final ErrorMessage errorMessage = new ErrorMessage(ArKeyConstants.ContractsGrantsInvoiceCreateDocumentConstants.BILL_BY_CONTRACT_VALID_ACCOUNTS, awd.getProposalNumber().toString()); errorMessages.add(errorMessage); } else { // check if control accounts of awardaccounts are the same boolean isValid = true; if (accountNum != 1) { Set<Account> distinctAwardAccounts = new HashSet<>(); for (ContractsAndGrantsBillingAwardAccount awardAccount : awd.getActiveAwardAccounts()) { if (!ObjectUtils.isNull(awardAccount.getAccount().getContractControlAccount())) { distinctAwardAccounts.add(awardAccount.getAccount().getContractControlAccount()); } } if (distinctAwardAccounts.size() > 1) { final ErrorMessage errorMessage = new ErrorMessage(ArKeyConstants.ContractsGrantsInvoiceCreateDocumentConstants.DIFFERING_CONTROL_ACCOUNTS, awd.getProposalNumber().toString()); errorMessages.add(errorMessage); isValid = false; } } if (isValid) { String coaCode = null; String orgCode = null; for (ContractsAndGrantsBillingAwardAccount awardAccount : awd.getActiveAwardAccounts()) { Account account = awardAccount.getAccount(); coaCode = awd.getPrimaryAwardOrganization().getChartOfAccountsCode(); orgCode = awd.getPrimaryAwardOrganization().getOrganizationCode(); } // To get valid award accounts of amounts > zero$ and pass it to the create invoices method if (!getValidAwardAccounts(awd.getActiveAwardAccounts(), awd).containsAll(awd.getActiveAwardAccounts())) { final ErrorMessage errorMessage = new ErrorMessage(ArKeyConstants.ContractsGrantsInvoiceCreateDocumentConstants.NOT_ALL_BILLABLE_ACCOUNTS, awd.getProposalNumber().toString()); errorMessages.add(errorMessage); } generateAndSaveContractsAndGrantsInvoiceDocument(awd, getValidAwardAccounts(awd.getActiveAwardAccounts(), awd), coaCode, orgCode, errorMessages); } } } /** * Generates and saves contracts and grants invoice documents based on the given award's contract control accounts * @param awd the award with contract control accounts to build contracts and grants invoice documents from * @param errLines a holder for error messages */ protected void createInvoicesByContractControlAccounts(ContractsAndGrantsBillingAward awd, List<ErrorMessage> errorMessages) { List<ContractsAndGrantsBillingAwardAccount> tmpAcctList = new ArrayList<ContractsAndGrantsBillingAwardAccount>(); List<Account> controlAccounts = getContractsGrantsInvoiceDocumentService().getContractControlAccounts(awd); List<Account> controlAccountsTemp = getContractsGrantsInvoiceDocumentService().getContractControlAccounts(awd); if (controlAccounts == null || (controlAccounts.size() != awd.getActiveAwardAccounts().size())) {// to check if the number of contract control accounts is same as the number of accounts final ErrorMessage errorMessage = new ErrorMessage(ArKeyConstants.ContractsGrantsInvoiceCreateDocumentConstants.NO_CONTROL_ACCOUNT, awd.getProposalNumber().toString()); errorMessages.add(errorMessage); } else { Set<Account> controlAccountSet = new HashSet<Account>(); for (int i = 0; i < controlAccountsTemp.size(); i++) { if (ObjectUtils.isNotNull(controlAccountsTemp.get(i))) { for (int j = i + 1; j < controlAccounts.size(); j++) { if (controlAccountsTemp.get(i).equals(controlAccounts.get(j))) { controlAccounts.set(j, null); } } } else { break; } } for (Account ctrlAcct : controlAccounts) { if (ObjectUtils.isNotNull(ctrlAcct)) { controlAccountSet.add(ctrlAcct); } } // control accounts are set correctly for award accounts if (controlAccountSet.size() != 0) { for (Account controlAccount : controlAccountSet) { Account tmpCtrlAcct = null; for (ContractsAndGrantsBillingAwardAccount awardAccount : awd.getActiveAwardAccounts()) { if (!awardAccount.isFinalBilledIndicator()) { tmpCtrlAcct = awardAccount.getAccount().getContractControlAccount(); if (tmpCtrlAcct.getChartOfAccountsCode().equals(controlAccount.getChartOfAccountsCode()) && tmpCtrlAcct.getAccountNumber().equals(controlAccount.getAccountNumber())) { tmpAcctList.add(awardAccount); } } } // To get valid award accounts of amounts > zero$ and pass it to the create invoices method if (!getValidAwardAccounts(tmpAcctList, awd).containsAll(tmpAcctList)) { final ErrorMessage errorMessage = new ErrorMessage(ArKeyConstants.ContractsGrantsInvoiceCreateDocumentConstants.CONTROL_ACCOUNT_NON_BILLABLE, controlAccount.getAccountNumber(), awd.getProposalNumber().toString()); errorMessages.add(errorMessage); } generateAndSaveContractsAndGrantsInvoiceDocument(awd, getValidAwardAccounts(tmpAcctList, awd), awd.getPrimaryAwardOrganization().getChartOfAccountsCode(), awd.getPrimaryAwardOrganization().getOrganizationCode(), errorMessages); } } else { final ErrorMessage errorMessage = new ErrorMessage(ArKeyConstants.ContractsGrantsInvoiceCreateDocumentConstants.BILL_BY_CONTRACT_LACKS_CONTROL_ACCOUNT, awd.getProposalNumber().toString()); errorMessages.add(errorMessage); } } } /** * Generates and saves contracts and grants invoice documens based on the award accounts of the passed in award * @param awd the award to build contracts and grants invoice documents from the award accounts on * @param errLines a holder for error messages */ protected void createInvoicesByAccounts(ContractsAndGrantsBillingAward awd, List<ErrorMessage> errorMessages) { List<ContractsAndGrantsBillingAwardAccount> tmpAcctList = new ArrayList<ContractsAndGrantsBillingAwardAccount>(); for (ContractsAndGrantsBillingAwardAccount awardAccount : awd.getActiveAwardAccounts()) { if (!awardAccount.isFinalBilledIndicator()) { // only one account is added into the list to create cgin tmpAcctList.clear(); tmpAcctList.add(awardAccount); // To get valid award accounts of amounts > zero$ and pass it to the create invoices method if (!getValidAwardAccounts(tmpAcctList, awd).containsAll(tmpAcctList)) { final ErrorMessage errorMessage = new ErrorMessage(ArKeyConstants.ContractsGrantsInvoiceCreateDocumentConstants.NON_BILLABLE, awardAccount.getAccountNumber(), awd.getProposalNumber().toString()); errorMessages.add(errorMessage); } generateAndSaveContractsAndGrantsInvoiceDocument(awd, getValidAwardAccounts(tmpAcctList, awd), awd.getPrimaryAwardOrganization().getChartOfAccountsCode(), awd.getPrimaryAwardOrganization().getOrganizationCode(), errorMessages); } } } /** * Generates and then saves a contracts and grants invoice document * @param awd the award for the document * @param validAwardAccounts the award accounts which should appear on the document * @param coaCode the chart code for the document * @param orgCode the organization code for the document * @param errLines a List of error messages, to be appended to if there are errors in document generation */ protected void generateAndSaveContractsAndGrantsInvoiceDocument(ContractsAndGrantsBillingAward awd, List<ContractsAndGrantsBillingAwardAccount> validAwardAccounts, final String coaCode, final String orgCode, List<ErrorMessage> errorMessages) { ContractsGrantsInvoiceDocument cgInvoiceDocument = createCGInvoiceDocumentByAwardInfo(awd, validAwardAccounts, coaCode, orgCode, errorMessages); if (ObjectUtils.isNotNull(cgInvoiceDocument)) { // Saving the document try { documentService.saveDocument(cgInvoiceDocument, DocumentSystemSaveEvent.class); } catch (WorkflowException ex) { LOG.error("Error creating cgin documents: " + ex.getMessage(), ex); throw new RuntimeException("Error creating cgin documents: " + ex.getMessage(), ex); } } } /** * This method retrieves create a ContractsGrantsInvoiceDocument by Award * @param awd * * @return ContractsGrantsInvoiceDocument */ @Override public ContractsGrantsInvoiceDocument createCGInvoiceDocumentByAwardInfo(ContractsAndGrantsBillingAward awd, List<ContractsAndGrantsBillingAwardAccount> accounts, String chartOfAccountsCode, String organizationCode, List<ErrorMessage> errorMessages) { ContractsGrantsInvoiceDocument cgInvoiceDocument = null; if (ObjectUtils.isNotNull(accounts) && !accounts.isEmpty()) { if (chartOfAccountsCode != null && organizationCode != null) { try { cgInvoiceDocument = (ContractsGrantsInvoiceDocument) documentService.getNewDocument(ContractsGrantsInvoiceDocument.class); // Set description to the document created. cgInvoiceDocument.getDocumentHeader().setDocumentDescription(ArConstants.BatchFileSystem.CGINVOICE_DOCUMENT_DESCRIPTION_OF_BATCH_PROCESS); // setup several Default Values for CGInvoice document which extends from Customer Invoice Document // a) set billing org and chart code cgInvoiceDocument.setBillByChartOfAccountCode(chartOfAccountsCode); cgInvoiceDocument.setBilledByOrganizationCode(organizationCode); // b) set processing org and chart code List<String> procCodes = getContractsGrantsInvoiceDocumentService().getProcessingFromBillingCodes(chartOfAccountsCode, organizationCode); AccountsReceivableDocumentHeader accountsReceivableDocumentHeader = new AccountsReceivableDocumentHeader(); accountsReceivableDocumentHeader.setDocumentNumber(cgInvoiceDocument.getDocumentNumber()); // Set processing chart and org codes if (procCodes != null){ int procCodesSize = procCodes.size(); // Set processing chart if (procCodesSize > 0){ accountsReceivableDocumentHeader.setProcessingChartOfAccountCode(procCodes.get(0)); } // Set processing org code if (procCodesSize > 1){ accountsReceivableDocumentHeader.setProcessingOrganizationCode(procCodes.get(1)); } } cgInvoiceDocument.setAccountsReceivableDocumentHeader(accountsReceivableDocumentHeader); populateInvoiceFromAward(awd, accounts,cgInvoiceDocument); contractsGrantsInvoiceDocumentService.createSourceAccountingLines(cgInvoiceDocument); if (ObjectUtils.isNotNull(cgInvoiceDocument.getInvoiceGeneralDetail().getAward())) { contractsGrantsInvoiceDocumentService.updateSuspensionCategoriesOnDocument(cgInvoiceDocument); } LOG.info("Created Contracts and Grants invoice document " + cgInvoiceDocument.getDocumentNumber()); } catch (WorkflowException ex) { LOG.error("Error creating cgin documents: " + ex.getMessage(), ex); throw new RuntimeException("Error creating cgin documents: " + ex.getMessage(), ex); } } else { // if chart of account code or organization code is not available, output the error final ErrorMessage errorMessage = new ErrorMessage(ArKeyConstants.ContractsGrantsInvoiceCreateDocumentConstants.NO_CHART_OR_ORG, awd.getProposalNumber().toString()); errorMessages.add(errorMessage); } } return cgInvoiceDocument; } /** * This method takes all the applicable attributes from the associated award object and sets those attributes into their * corresponding invoice attributes. * * @param award The associated award that the invoice will be linked to. * @param awardAccounts * @param document */ protected void populateInvoiceFromAward(ContractsAndGrantsBillingAward award, List<ContractsAndGrantsBillingAwardAccount> awardAccounts, ContractsGrantsInvoiceDocument document) { if (ObjectUtils.isNotNull(award)) { // Invoice General Detail section InvoiceGeneralDetail invoiceGeneralDetail = new InvoiceGeneralDetail(); invoiceGeneralDetail.setDocumentNumber(document.getDocumentNumber()); invoiceGeneralDetail.setProposalNumber(award.getProposalNumber()); invoiceGeneralDetail.setAward(award); // Set the last Billed Date and Billing Period Timestamp ts = new Timestamp(new java.util.Date().getTime()); java.sql.Date today = new java.sql.Date(ts.getTime()); AccountingPeriod currPeriod = accountingPeriodService.getByDate(today); java.sql.Date[] pair = verifyBillingFrequencyService.getStartDateAndEndDateOfPreviousBillingPeriod(award, currPeriod); invoiceGeneralDetail.setBillingPeriod(pair[0] + " to " + pair[1]); invoiceGeneralDetail.setLastBilledDate(pair[1]); populateInvoiceDetailFromAward(invoiceGeneralDetail, award); document.setInvoiceGeneralDetail(invoiceGeneralDetail); // To set Bill by address identifier because it is a required field - set the value to 1 as it is never being used. document.setCustomerBillToAddressIdentifier(1); // Set Invoice due date to current date as it is required field and never used. document.setInvoiceDueDate(dateTimeService.getCurrentSqlDateMidnight()); // copy award's customer address to invoice address details document.getInvoiceAddressDetails().clear(); ContractsAndGrantsBillingAgency agency = award.getAgency(); if (ObjectUtils.isNotNull(agency)) { final List<InvoiceAddressDetail> invoiceAddressDetails = buildInvoiceAddressDetailsFromAgency(agency, document); document.getInvoiceAddressDetails().addAll(invoiceAddressDetails); } java.sql.Date invoiceDate = document.getInvoiceGeneralDetail().getLastBilledDate(); if (document.getInvoiceGeneralDetail().getBillingFrequencyCode().equalsIgnoreCase(ArConstants.MILESTONE_BILLING_SCHEDULE_CODE)) {// To check if award has milestones final List<Milestone> milestones = getContractsGrantsBillingUtilityService().getActiveMilestonesForProposalNumber(award.getProposalNumber()); if (!CollectionUtils.isEmpty(milestones)) { // copy award milestones to invoice milestones document.getInvoiceMilestones().clear(); final List<InvoiceMilestone> invoiceMilestones = buildInvoiceMilestones(milestones, invoiceDate); document.getInvoiceMilestones().addAll(invoiceMilestones); } } else if (document.getInvoiceGeneralDetail().getBillingFrequencyCode().equalsIgnoreCase(ArConstants.PREDETERMINED_BILLING_SCHEDULE_CODE)) {// To check if award has bills final List<Bill> bills = getContractsGrantsBillingUtilityService().getActiveBillsForProposalNumber(award.getProposalNumber()); if (!CollectionUtils.isEmpty(bills)) { // copy award milestones to invoice milestones document.getInvoiceBills().clear(); final List<InvoiceBill> invoiceBills = buildInvoiceBills(bills, invoiceDate); document.getInvoiceBills().addAll(invoiceBills); } } // copy award's accounts to invoice account details document.getAccountDetails().clear(); final List<InvoiceAccountDetail> invoiceAccountDetails = new ArrayList<>(); List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectsCodes = new ArrayList<>(); Map<String, KualiDecimal> budgetAmountsByCostCategory = new HashMap<>(); Integer currentYear = getUniversityDateService().getCurrentFiscalYear(); final boolean firstFiscalPeriod = isFirstFiscalPeriod(); final Integer fiscalYear = firstFiscalPeriod && useTimeBasedBillingFrequency(document.getInvoiceGeneralDetail().getBillingFrequencyCode()) ? currentYear - 1 : currentYear; final SystemOptions systemOptions = optionsService.getOptions(fiscalYear); List<String> balanceTypeCodeList = new ArrayList<String>(); balanceTypeCodeList.add(systemOptions.getBudgetCheckingBalanceTypeCd()); balanceTypeCodeList.add(systemOptions.getActualFinancialBalanceTypeCd()); for (ContractsAndGrantsBillingAwardAccount awardAccount : awardAccounts) { InvoiceAccountDetail invoiceAccountDetail = buildInvoiceAccountDetailForAwardAccount(award, awardAccount, document.getDocumentNumber(), document.getInvoiceGeneralDetail()); List<Balance> glBalances = retrieveBalances(fiscalYear, awardAccount.getChartOfAccountsCode(), awardAccount.getAccountNumber(), balanceTypeCodeList); KualiDecimal awardAccountBudgetAmount = KualiDecimal.ZERO; KualiDecimal balanceAmount = KualiDecimal.ZERO; KualiDecimal awardAccountCumulativeAmount = KualiDecimal.ZERO; for (Balance balance : glBalances) { if (!isBalanceCostShare(balance)) { if (balance.getBalanceTypeCode().equalsIgnoreCase(systemOptions.getBudgetCheckingBalanceTypeCd())) { awardAccountBudgetAmount = addBalanceToAwardAccountBudgetAmount(balance, awardAccountBudgetAmount, firstFiscalPeriod); updateCategoryBudgetAmountsByBalance(balance, budgetAmountsByCostCategory, firstFiscalPeriod); } else if (balance.getBalanceTypeCode().equalsIgnoreCase(systemOptions.getActualFinancialBalanceTypeCd())) { awardAccountCumulativeAmount = addBalanceToAwardAccountCumulativeAmount(document, balance, award, awardAccountCumulativeAmount, firstFiscalPeriod); updateCategoryActualAmountsByBalance(document, balance, award, invoiceDetailAccountObjectsCodes, firstFiscalPeriod); } } invoiceAccountDetail.setBudgetAmount(awardAccountBudgetAmount); invoiceAccountDetail.setCumulativeAmount(awardAccountCumulativeAmount); } invoiceAccountDetails.add(invoiceAccountDetail); if (awardAccount.isLetterOfCreditReviewIndicator() && StringUtils.equalsIgnoreCase(award.getBillingFrequencyCode(), ArConstants.LOC_BILLING_SCHEDULE_CODE)) { distributeAmountAmongAllAccountObjectCodes(document, awardAccount, invoiceDetailAccountObjectsCodes); } else { updateInvoiceDetailAccountObjectCodesByBilledAmount(awardAccount, invoiceDetailAccountObjectsCodes); } } document.getAccountDetails().addAll(invoiceAccountDetails); if (!document.getInvoiceGeneralDetail().getBillingFrequencyCode().equalsIgnoreCase(ArConstants.MILESTONE_BILLING_SCHEDULE_CODE) && !document.getInvoiceGeneralDetail().getBillingFrequencyCode().equalsIgnoreCase(ArConstants.PREDETERMINED_BILLING_SCHEDULE_CODE)) { document.getInvoiceDetailAccountObjectCodes().addAll(invoiceDetailAccountObjectsCodes); List<AwardAccountObjectCodeTotalBilled> awardAccountObjectCodeTotalBilleds = getAwardAccountObjectCodeTotalBilledDao().getAwardAccountObjectCodeTotalBuildByProposalNumberAndAccount(awardAccounts); List<ContractsGrantsInvoiceDetail> invoiceDetails = generateValuesForCategories(document.getDocumentNumber(), document.getInvoiceDetailAccountObjectCodes(), budgetAmountsByCostCategory, awardAccountObjectCodeTotalBilleds); document.getInvoiceDetails().addAll(invoiceDetails); } // Set some basic values to invoice Document populateContractsGrantsInvoiceDocument(award, document); } } /** * Updates the appropriate amounts for the InvoiceDetailAccountObjectCode matching the given balance * @param document the CINV document we're generating * @param balance the balance to update amounts by * @param award the award on the CINV document we're generating * @param invoiceDetailAccountObjectsCodes the List of invoiceDetailObjectCodes to update one of * @param firstFiscalPeriod whether we're generating the CINV document in the fiscal fiscal period or not */ protected void updateCategoryActualAmountsByBalance(ContractsGrantsInvoiceDocument document, Balance balance, ContractsAndGrantsBillingAward award, List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectCodes, boolean firstFiscalPeriod) { final CostCategory category = getCostCategoryService().getCostCategoryForObjectCode(balance.getUniversityFiscalYear(), balance.getChartOfAccountsCode(), balance.getObjectCode()); if (!ObjectUtils.isNull(category)) { final InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode = getInvoiceDetailAccountObjectCodeByBalanceAndCategory(invoiceDetailAccountObjectCodes, balance, document.getDocumentNumber(), document.getInvoiceGeneralDetail().getProposalNumber(), category); if (useTimeBasedBillingFrequency(document.getInvoiceGeneralDetail().getBillingFrequencyCode())) { if (firstFiscalPeriod) { invoiceDetailAccountObjectCode.setCumulativeExpenditures(cleanAmount(invoiceDetailAccountObjectCode.getCumulativeExpenditures()).add(cleanAmount(balance.getContractsGrantsBeginningBalanceAmount())).add(cleanAmount(balance.getAccountLineAnnualBalanceAmount()))); if (!includePeriod13InPeriod01Calculations()) { invoiceDetailAccountObjectCode.setCumulativeExpenditures(cleanAmount(invoiceDetailAccountObjectCode.getCumulativeExpenditures()).subtract(cleanAmount(balance.getMonth13Amount()))); } } else { invoiceDetailAccountObjectCode.setCumulativeExpenditures(cleanAmount(invoiceDetailAccountObjectCode.getCumulativeExpenditures()).add(calculateBalanceAmountWithoutLastBilledPeriod(document.getInvoiceGeneralDetail().getLastBilledDate(), balance))); } } else {// For other billing frequencies KualiDecimal balanceAmount = cleanAmount(balance.getContractsGrantsBeginningBalanceAmount()).add(cleanAmount(balance.getAccountLineAnnualBalanceAmount())); invoiceDetailAccountObjectCode.setCumulativeExpenditures(cleanAmount(invoiceDetailAccountObjectCode.getCumulativeExpenditures()).add(cleanAmount(balance.getContractsGrantsBeginningBalanceAmount()).add(cleanAmount(balance.getAccountLineAnnualBalanceAmount())))); } } } /** * Sums the balance to the given awardAccountCumulativeAmount and returns that summed amount * @param document the CINV document we're generating * @param balance the balance to update amounts by * @param award the award on the CINV document we're generating * @param awardAccountCumulativeAmount the beginning cumulative expense amount for the award account of the balance * @param firstFiscalPeriod whether we're generating the CINV document in the fiscal fiscal period or not * @return the updated cumulative amount on the award account */ protected KualiDecimal addBalanceToAwardAccountCumulativeAmount(ContractsGrantsInvoiceDocument document, Balance balance, ContractsAndGrantsBillingAward award, KualiDecimal awardAccountCumulativeAmount, boolean firstFiscalPeriod) { if (useTimeBasedBillingFrequency(document.getInvoiceGeneralDetail().getBillingFrequencyCode())) { if (firstFiscalPeriod) { KualiDecimal newAwardAccountCumulativeAmount = awardAccountCumulativeAmount.add(cleanAmount(balance.getContractsGrantsBeginningBalanceAmount())).add(cleanAmount(balance.getAccountLineAnnualBalanceAmount())); if (!includePeriod13InPeriod01Calculations()) { newAwardAccountCumulativeAmount = awardAccountCumulativeAmount.subtract(balance.getMonth13Amount()); } return newAwardAccountCumulativeAmount; } else { return awardAccountCumulativeAmount.add(calculateBalanceAmountWithoutLastBilledPeriod(award.getLastBilledDate(), balance)); } } else {// For other billing frequencies KualiDecimal balanceAmount = cleanAmount(balance.getContractsGrantsBeginningBalanceAmount()).add(cleanAmount(balance.getAccountLineAnnualBalanceAmount())); return awardAccountCumulativeAmount.add(balanceAmount); } } /** * Updates the cost category budget amount (in the given Map, budgetAmountsByCostCategory) by the total amount of the balance * @param balance the balance to update the budget amounts by * @param budgetAmountsByCostCategory the Map of budget amounts sorted by cost category * @param firstFiscalPeriod whether this CINV is being generated in the first fiscal period or not * @return the updated award account budget amount */ protected void updateCategoryBudgetAmountsByBalance(Balance balance, Map<String, KualiDecimal> budgetAmountsByCostCategory, boolean firstFiscalPeriod) { CostCategory category = getCostCategoryService().getCostCategoryForObjectCode(balance.getUniversityFiscalYear(), balance.getChartOfAccountsCode(), balance.getObjectCode()); if (!ObjectUtils.isNull(category)) { final KualiDecimal balanceAmount = getBudgetBalanceAmount(balance, firstFiscalPeriod); KualiDecimal categoryBudgetAmount = budgetAmountsByCostCategory.get(category.getCategoryCode()); if (categoryBudgetAmount == null) { categoryBudgetAmount = KualiDecimal.ZERO; } categoryBudgetAmount = categoryBudgetAmount.add(balanceAmount); budgetAmountsByCostCategory.put(category.getCategoryCode(), categoryBudgetAmount); } else { LOG.warn("Could not find cost category for balance: "+balance.getUniversityFiscalYear()+" "+balance.getChartOfAccountsCode()+" "+balance.getAccountNumber()+" "+balance.getSubAccountNumber()+" "+balance.getObjectCode()+" "+balance.getSubObjectCode()+" "+balance.getBalanceTypeCode()); } } /** * Adds the budget balance to the award account budget amount * @param balance the balance to update the budget amounts by * @param awardAccountBudgetAmount the beginning award account budget amount * @param firstFiscalPeriod whether this CINV is being generated in the first fiscal period or not * @return the updated award account budget amount */ protected KualiDecimal addBalanceToAwardAccountBudgetAmount(Balance balance, KualiDecimal awardAccountBudgetAmount, boolean firstFiscalPeriod) { final KualiDecimal balanceAmount = getBudgetBalanceAmount(balance, firstFiscalPeriod); return awardAccountBudgetAmount.add(balanceAmount); } /** * Determines the balance amount (cg + annual) from the given budget balance * @param balance balance to find amount from * @param firstFiscalPeriod whether the CINV is being created in the first fiscal period or not * @return the total amount from the balance */ protected KualiDecimal getBudgetBalanceAmount(Balance balance, boolean firstFiscalPeriod) { KualiDecimal balanceAmount = balance.getContractsGrantsBeginningBalanceAmount().add(balance.getAccountLineAnnualBalanceAmount()); if (firstFiscalPeriod && !includePeriod13InPeriod01Calculations()) { balanceAmount = balanceAmount.subtract(balance.getMonth13Amount()); // get rid of period 13 if we should not include in calculations } return balanceAmount; } /** * Builds a new invoice account detail for a given award account * @param award the award associated with the award account * @param awardAccount the award account to build the invoice account detail for * @param documentNumber the number of the document we're currently building * @param invoiceGeneralDetail the invoice general detail for the the document we're currently building * @return the built invoice account detail */ protected InvoiceAccountDetail buildInvoiceAccountDetailForAwardAccount(ContractsAndGrantsBillingAward award, ContractsAndGrantsBillingAwardAccount awardAccount, final String documentNumber, InvoiceGeneralDetail invoiceGeneralDetail) { InvoiceAccountDetail invoiceAccountDetail = new InvoiceAccountDetail(); invoiceAccountDetail.setDocumentNumber(documentNumber); invoiceAccountDetail.setAccountNumber(awardAccount.getAccountNumber()); if (ObjectUtils.isNotNull(awardAccount.getAccount()) && StringUtils.isNotEmpty(awardAccount.getAccount().getContractControlAccountNumber())) { invoiceAccountDetail.setContractControlAccountNumber(awardAccount.getAccount().getContractControlAccountNumber()); } invoiceAccountDetail.setChartOfAccountsCode(awardAccount.getChartOfAccountsCode()); invoiceAccountDetail.setProposalNumber(awardAccount.getProposalNumber()); return invoiceAccountDetail; } /** * Generates InvoiceBills for each of the given Bills * @param bills the bulls to associate with a contracts & grants billing invoice * @param invoiceDate the date of the invoice we're building * @return the List of generated InvoiceBill objects */ protected List<InvoiceBill> buildInvoiceBills(List<Bill> bills, java.sql.Date invoiceDate) { List<InvoiceBill> invoiceBills = new ArrayList<>(); for (Bill awdBill : bills) { // To check for null - Bill Completion date. // To consider the completed milestones only. if (awdBill.getBillDate() != null && !invoiceDate.before(awdBill.getBillDate()) && !awdBill.isBilled() && awdBill.getEstimatedAmount().isGreaterThan(KualiDecimal.ZERO)) { InvoiceBill invBill = new InvoiceBill(); invBill.setBillNumber(awdBill.getBillNumber()); invBill.setBillIdentifier(awdBill.getBillIdentifier()); invBill.setBillDescription(awdBill.getBillDescription()); invBill.setBillDate(awdBill.getBillDate()); invBill.setEstimatedAmount(awdBill.getEstimatedAmount()); invoiceBills.add(invBill); } } return invoiceBills; } /** * Generates InvoiceMilestones for each of the given milestones * @param milestones the milestones to associate with a contracts & grants billing invoice * @param invoiceDate the date of the invoice we're building * @return the List of InvoiceMilestones */ protected List<InvoiceMilestone> buildInvoiceMilestones(List<Milestone> milestones, java.sql.Date invoiceDate) { List<InvoiceMilestone> invoiceMilestones = new ArrayList<>(); for (Milestone awdMilestone : milestones) { // To consider the completed milestones only. // To check for null - Milestone Completion date. if (awdMilestone.getMilestoneActualCompletionDate() != null && !invoiceDate.before(awdMilestone.getMilestoneActualCompletionDate()) && !awdMilestone.isBilled() && awdMilestone.getMilestoneAmount().isGreaterThan(KualiDecimal.ZERO)) { InvoiceMilestone invMilestone = new InvoiceMilestone(); invMilestone.setMilestoneNumber(awdMilestone.getMilestoneNumber()); invMilestone.setMilestoneIdentifier(awdMilestone.getMilestoneIdentifier()); invMilestone.setMilestoneDescription(awdMilestone.getMilestoneDescription()); invMilestone.setMilestoneActualCompletionDate(awdMilestone.getMilestoneActualCompletionDate()); invMilestone.setMilestoneAmount(awdMilestone.getMilestoneAmount()); invoiceMilestones.add(invMilestone); } } return invoiceMilestones; } /** * Builds a list of InvoiceAddressDetails based on the customer associated with an Agency * @param agency the agency associated with the proposal we're building a CINV document for * @param documentNumber the document number of the CINV document we're creating * @return a List of the generated invoice address details */ protected List<InvoiceAddressDetail> buildInvoiceAddressDetailsFromAgency(ContractsAndGrantsBillingAgency agency, ContractsGrantsInvoiceDocument document) { Map<String, Object> mapKey = new HashMap<String, Object>(); mapKey.put(KFSPropertyConstants.CUSTOMER_NUMBER, agency.getCustomerNumber()); final List<CustomerAddress> customerAddresses = (List<CustomerAddress>) businessObjectService.findMatching(CustomerAddress.class, mapKey); String documentNumber = document.getDocumentNumber(); List<InvoiceAddressDetail> invoiceAddressDetails = new ArrayList<>(); for (CustomerAddress customerAddress : customerAddresses) { if (StringUtils.equalsIgnoreCase(ArKeyConstants.CustomerConstants.CUSTOMER_ADDRESS_TYPE_CODE_PRIMARY, customerAddress.getCustomerAddressTypeCode())) { document.setCustomerBillToAddressOnInvoice(customerAddress); } InvoiceAddressDetail invoiceAddressDetail = new InvoiceAddressDetail(); invoiceAddressDetail.setCustomerNumber(customerAddress.getCustomerNumber()); invoiceAddressDetail.setDocumentNumber(documentNumber); invoiceAddressDetail.setCustomerAddressIdentifier(customerAddress.getCustomerAddressIdentifier()); invoiceAddressDetail.setCustomerAddressTypeCode(customerAddress.getCustomerAddressTypeCode()); invoiceAddressDetail.setCustomerAddressName(customerAddress.getCustomerAddressName()); invoiceAddressDetail.setInvoiceTransmissionMethodCode(customerAddress.getInvoiceTransmissionMethodCode()); invoiceAddressDetail.setCustomerEmailAddress(customerAddress.getCustomerEmailAddress()); invoiceAddressDetail.setCustomerLine1StreetAddress(customerAddress.getCustomerLine1StreetAddress()); invoiceAddressDetail.setCustomerLine2StreetAddress(customerAddress.getCustomerLine2StreetAddress()); invoiceAddressDetail.setCustomerCityName(customerAddress.getCustomerCityName()); invoiceAddressDetail.setCustomerStateCode(customerAddress.getCustomerStateCode()); invoiceAddressDetail.setCustomerZipCode(customerAddress.getCustomerZipCode()); invoiceAddressDetail.setCustomerCountryCode(customerAddress.getCustomerCountryCode()); invoiceAddressDetail.setCustomerInternationalMailCode(customerAddress.getCustomerInternationalMailCode()); invoiceAddressDetail.setCustomerAddressInternationalProvinceName(customerAddress.getCustomerAddressInternationalProvinceName()); if (StringUtils.isNotBlank(customerAddress.getCustomerInvoiceTemplateCode())) { invoiceAddressDetail.setCustomerInvoiceTemplateCode(customerAddress.getCustomerInvoiceTemplateCode()); } else { AccountsReceivableCustomer customer = agency.getCustomer(); if (ObjectUtils.isNotNull(customer) && StringUtils.isNotBlank(customer.getCustomerInvoiceTemplateCode())) { invoiceAddressDetail.setCustomerInvoiceTemplateCode(customer.getCustomerInvoiceTemplateCode()); } } invoiceAddressDetails.add(invoiceAddressDetail); } return invoiceAddressDetails; } /** * 1. This method is responsible to populate categories column for the ContractsGrantsInvoice Document. 2. The categories are * retrieved from the Maintenance document as a collection and then a logic with conditions to handle ranges of Object Codes. 3. * Once the object codes are retrieved and categories are set the performAccountingCalculations method of InvoiceDetail BO will * do all the accounting calculations. * @param documentNumber the number of the document we want to add invoice details to * @param invoiceDetailAccountObjectCodes the List of InvoiceDetailAccountObjectCodes containing amounts to sum into our invoice details * @param budgetAmountsByCostCategory the budget amounts, sorted by cost category * @param awardAccountObjectCodeTotalBilleds the business objects containg what has been billed from the document's award accounts already */ public List<ContractsGrantsInvoiceDetail> generateValuesForCategories(String documentNumber, List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectCodes, Map<String, KualiDecimal> budgetAmountsByCostCategory, List<AwardAccountObjectCodeTotalBilled> awardAccountObjectCodeTotalBilleds) { Collection<CostCategory> costCategories = retrieveAllBillingCategories(); List<ContractsGrantsInvoiceDetail> invoiceDetails = new ArrayList<>(); Map<String, List<InvoiceDetailAccountObjectCode>> invoiceDetailAccountObjectCodesMap = mapInvoiceDetailAccountObjectCodesByCategoryCode(invoiceDetailAccountObjectCodes); Map<String, List<AwardAccountObjectCodeTotalBilled>> billedsMap = mapAwardAccountObjectCodeTotalBilledsByCategoryCode(awardAccountObjectCodeTotalBilleds); for (CostCategory category : costCategories) { ContractsGrantsInvoiceDetail invDetail = new ContractsGrantsInvoiceDetail(); invDetail.setDocumentNumber(documentNumber); invDetail.setCategoryCode(category.getCategoryCode()); invDetail.setCostCategory(category); invDetail.setIndirectCostIndicator(category.isIndirectCostIndicator()); // calculate total billed first invDetail.setCumulative(KualiDecimal.ZERO); invDetail.setExpenditures(KualiDecimal.ZERO); invDetail.setBilled(KualiDecimal.ZERO); List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectCodesForCategory = invoiceDetailAccountObjectCodesMap.get(category.getCategoryCode()); if (!CollectionUtils.isEmpty(invoiceDetailAccountObjectCodesForCategory)) { for (InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode : invoiceDetailAccountObjectCodesForCategory) { invDetail.setCumulative(invDetail.getCumulative().add(invoiceDetailAccountObjectCode.getCumulativeExpenditures())); invDetail.setExpenditures(invDetail.getExpenditures().add(invoiceDetailAccountObjectCode.getCurrentExpenditures())); } } List<AwardAccountObjectCodeTotalBilled> billedForCategory = billedsMap.get(category.getCategoryCode()); if (!CollectionUtils.isEmpty(billedForCategory)) { for (AwardAccountObjectCodeTotalBilled accountObjectCodeTotalBilled : billedForCategory) { invDetail.setBilled(invDetail.getBilled().add(accountObjectCodeTotalBilled.getTotalBilled())); // this adds up all the total billed based on object code into categories; sum for this category. } } // calculate the rest using billed to date if (!ObjectUtils.isNull(budgetAmountsByCostCategory.get(category.getCategoryCode()))) { invDetail.setBudget(budgetAmountsByCostCategory.get(category.getCategoryCode())); } else { invDetail.setBudget(KualiDecimal.ZERO); } invoiceDetails.add(invDetail); } return invoiceDetails; } /** * Converts a List of InvoiceDetailAccountObjectCodes into a map where the key is the category code * @param invoiceDetailAccountObjectCodes a List of InvoiceDetailAccountObjectCodes * @return that List converted to a Map, keyed by category code */ protected Map<String, List<InvoiceDetailAccountObjectCode>> mapInvoiceDetailAccountObjectCodesByCategoryCode(List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectCodes) { Map<String, List<InvoiceDetailAccountObjectCode>> invoiceDetailAccountObjectCodesMap = new HashMap<>(); for (InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode : invoiceDetailAccountObjectCodes) { List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectCodesForCategory = invoiceDetailAccountObjectCodesMap.get(invoiceDetailAccountObjectCode.getCategoryCode()); if (invoiceDetailAccountObjectCodesForCategory == null) { invoiceDetailAccountObjectCodesForCategory = new ArrayList<>(); } invoiceDetailAccountObjectCodesForCategory.add(invoiceDetailAccountObjectCode); invoiceDetailAccountObjectCodesMap.put(invoiceDetailAccountObjectCode.getCategoryCode(), invoiceDetailAccountObjectCodesForCategory); } return invoiceDetailAccountObjectCodesMap; } /** * Converts a List of AwardAccountObjectCodeTotalBilled into a Map, keyed by the Cost Category which most closely matches them * @param awardAccountObjectCodeTotalBilleds the List of AwardAccountObjectCodeTotalBilled business objects to Map * @return the Mapped AwardAccountObjectCodeTotalBilled records */ protected Map<String, List<AwardAccountObjectCodeTotalBilled>> mapAwardAccountObjectCodeTotalBilledsByCategoryCode( List<AwardAccountObjectCodeTotalBilled> awardAccountObjectCodeTotalBilleds) { Integer fiscalYear = getUniversityDateService().getCurrentFiscalYear(); Map<String, List<AwardAccountObjectCodeTotalBilled>> billedsMap = new HashMap<>(); for (AwardAccountObjectCodeTotalBilled billed : awardAccountObjectCodeTotalBilleds) { final CostCategory category = getCostCategoryService().getCostCategoryForObjectCode(fiscalYear, billed.getChartOfAccountsCode(), billed.getFinancialObjectCode()); if (!ObjectUtils.isNull(category)) { List<AwardAccountObjectCodeTotalBilled> billedForCategory = billedsMap.get(category.getCategoryCode()); if (billedForCategory == null) { billedForCategory = new ArrayList<>(); } billedForCategory.add(billed); billedsMap.put(category.getCategoryCode(), billedForCategory); } else { LOG.warn("Could not find cost category for AwardAccountObjectCodeTotalBilled, fiscal year = "+fiscalYear+" "+billed.getChartOfAccountsCode()+" "+billed.getFinancialObjectCode()); } } return billedsMap; } /** * This method takes all the applicable attributes from the associated award object and sets those attributes into their * corresponding invoice attributes. * @param invoiceGeneralDetail the invoice detail to populate * @param award The associated award that the invoice will be linked to. */ protected void populateInvoiceDetailFromAward(InvoiceGeneralDetail invoiceGeneralDetail, ContractsAndGrantsBillingAward award) { // copy General details from award to the invoice invoiceGeneralDetail.setAwardTotal(award.getAwardTotalAmount()); invoiceGeneralDetail.setAgencyNumber(award.getAgencyNumber()); if (ObjectUtils.isNotNull(award.getBillingFrequencyCode())) { invoiceGeneralDetail.setBillingFrequencyCode(award.getBillingFrequencyCode()); } if (ObjectUtils.isNotNull(award.getInstrumentTypeCode())) { invoiceGeneralDetail.setInstrumentTypeCode(award.getInstrumentTypeCode()); } // To set Award Date range - this would be (Award Start Date to Award Stop Date) String awdDtRange = award.getAwardBeginningDate() + " to " + award.getAwardEndingDate(); invoiceGeneralDetail.setAwardDateRange(awdDtRange); // set the billed to Date Field // To check if award has milestones if (StringUtils.equalsIgnoreCase(invoiceGeneralDetail.getBillingFrequencyCode(), ArConstants.MILESTONE_BILLING_SCHEDULE_CODE)) { invoiceGeneralDetail.setBilledToDateAmount(contractsGrantsInvoiceDocumentService.getMilestonesBilledToDateAmount(award.getProposalNumber())); } else if (StringUtils.equalsIgnoreCase(invoiceGeneralDetail.getBillingFrequencyCode(),ArConstants.PREDETERMINED_BILLING_SCHEDULE_CODE)) { invoiceGeneralDetail.setBilledToDateAmount(contractsGrantsInvoiceDocumentService.getPredeterminedBillingBilledToDateAmount(award.getProposalNumber())); } else { invoiceGeneralDetail.setBilledToDateAmount(contractsGrantsInvoiceDocumentService.getAwardBilledToDateAmountByProposalNumber(award.getProposalNumber())); } } /** * For letter of credit, this distributes the amount for matching LOC invoice detail account object codes (which is very probably all of invoice detail account object codes in the given list) evenly * @param document the CINV document we're creating * @param awdAcct the C&G Award Account * @param invoiceDetailAccountObjectsCodes the List of invoice detail account object codes we're attempting to generate */ protected void distributeAmountAmongAllAccountObjectCodes(ContractsGrantsInvoiceDocument document, ContractsAndGrantsBillingAwardAccount awdAcct, List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectsCodes) { KualiDecimal amountToDrawForObjectCodes = KualiDecimal.ZERO; List<InvoiceDetailAccountObjectCode> locRedistributionInvoiceDetailAccountObjectCodes = new ArrayList<InvoiceDetailAccountObjectCode>(); for (InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode : invoiceDetailAccountObjectsCodes) { if (invoiceDetailAccountObjectCode.getDocumentNumber().equals(document.getDocumentNumber()) && invoiceDetailAccountObjectCode.getProposalNumber().equals(document.getInvoiceGeneralDetail().getProposalNumber()) && invoiceDetailAccountObjectCode.getAccountNumber().equals(awdAcct.getAccountNumber()) && invoiceDetailAccountObjectCode.getChartOfAccountsCode().equals(awdAcct.getChartOfAccountsCode())) { locRedistributionInvoiceDetailAccountObjectCodes.add(invoiceDetailAccountObjectCode); } } amountToDrawForObjectCodes = awdAcct.getAmountToDraw().divide(new KualiDecimal(locRedistributionInvoiceDetailAccountObjectCodes.size())); // Now to set the divided value equally to all the object code rows. for (InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode : locRedistributionInvoiceDetailAccountObjectCodes) { invoiceDetailAccountObjectCode.setCurrentExpenditures(amountToDrawForObjectCodes); } } /** * Updates all of the given invoice detail object codes by the billed amount for the given award account (and updates the current expenditures accordingly) * @param awdAcct the award account to find billing information for * @param invoiceDetailAccountObjectsCodes the List of invoice detail account object code business objects to update */ protected void updateInvoiceDetailAccountObjectCodesByBilledAmount(ContractsAndGrantsBillingAwardAccount awdAcct, List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectsCodes) { List<AwardAccountObjectCodeTotalBilled> awardAccountObjectCodeTotalBilledList = retrieveBillingInformationForAwardAccount(awdAcct); for (InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode : invoiceDetailAccountObjectsCodes) { // since there may be multiple accounts represented in the Invoice Detail Account Object Codes, only process the ones that match if (StringUtils.equals(invoiceDetailAccountObjectCode.getChartOfAccountsCode(), awdAcct.getChartOfAccountsCode()) && StringUtils.equals(invoiceDetailAccountObjectCode.getAccountNumber(), awdAcct.getAccountNumber())) { if (!CollectionUtils.isEmpty(awardAccountObjectCodeTotalBilledList)) { for (AwardAccountObjectCodeTotalBilled awardAccountObjectCodeTotalBilled : awardAccountObjectCodeTotalBilledList) { if (invoiceDetailAccountObjectCode.getFinancialObjectCode().equalsIgnoreCase(awardAccountObjectCodeTotalBilled.getFinancialObjectCode())) { invoiceDetailAccountObjectCode.setTotalBilled(awardAccountObjectCodeTotalBilled.getTotalBilled()); } } } invoiceDetailAccountObjectCode.setCurrentExpenditures(invoiceDetailAccountObjectCode.getCumulativeExpenditures().subtract(invoiceDetailAccountObjectCode.getTotalBilled())); } } } /** * Retrieves all of the billing information performed against the given award account * @param awdAcct a C&G award account * @return the List of billing information */ protected List<AwardAccountObjectCodeTotalBilled> retrieveBillingInformationForAwardAccount(ContractsAndGrantsBillingAwardAccount awdAcct) { Map<String, Object> totalBilledKeys = new HashMap<String, Object>(); totalBilledKeys.put(KFSPropertyConstants.PROPOSAL_NUMBER, awdAcct.getProposalNumber()); totalBilledKeys.put(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE, awdAcct.getChartOfAccountsCode()); totalBilledKeys.put(KFSPropertyConstants.ACCOUNT_NUMBER, awdAcct.getAccountNumber()); List<AwardAccountObjectCodeTotalBilled> awardAccountObjectCodeTotalBilledList = (List<AwardAccountObjectCodeTotalBilled>) businessObjectService.findMatching(AwardAccountObjectCodeTotalBilled.class, totalBilledKeys); return awardAccountObjectCodeTotalBilledList; } /** * Determines if today, the document creation date, occurs within the first fiscal period * @return true if it is the first fiscal period, false otherwise */ protected boolean isFirstFiscalPeriod() { final AccountingPeriod currentPeriod = accountingPeriodService.getByDate(getDateTimeService().getCurrentSqlDate()); final boolean firstFiscalPeriod = StringUtils.equals(currentPeriod.getUniversityFiscalPeriodCode(), KFSConstants.MONTH1); return firstFiscalPeriod; } /** * @return a Collection of all active contracts and grants billing categories */ protected Collection<CostCategory> retrieveAllBillingCategories() { Map<String, Object> criteria = new HashMap<String, Object>(); criteria.put(KFSPropertyConstants.ACTIVE, true); Collection<CostCategory> costCategories = businessObjectService.findMatching(CostCategory.class, criteria); return costCategories; } /** * Looks up or constructs an InvoiceDetailAccountObjectCode based on a given balance and billing category * @param invoiceDetailAccountObjectCodes the list of invoice detail account object codes to find a matching Invoice Detail Account Object Code in * @param bal the balance to get the account object code from * @param documentNumber the document number of the CINV doc being created * @param proposalNumber the proposal number associated with the award on the CINV document we're currently building * @param costCategory the cost category associated with the balance * @return the retrieved or constructed (if nothing was found in the database) InvoiceDetailAccountObjectCode object */ protected InvoiceDetailAccountObjectCode getInvoiceDetailAccountObjectCodeByBalanceAndCategory(List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectCodes, Balance bal, String documentNumber, final Long proposalNumber, CostCategory category) { // Check if there is an existing invoice detail account object code existing (if there are more than one fiscal years) InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode = lookupInvoiceDetailAccountObjectCode(invoiceDetailAccountObjectCodes, bal, proposalNumber); if (ObjectUtils.isNull(invoiceDetailAccountObjectCode)) { if (!ObjectUtils.isNull(category)) { invoiceDetailAccountObjectCode = new InvoiceDetailAccountObjectCode(); invoiceDetailAccountObjectCode.setDocumentNumber(documentNumber); invoiceDetailAccountObjectCode.setProposalNumber(proposalNumber); invoiceDetailAccountObjectCode.setFinancialObjectCode(bal.getObjectCode()); invoiceDetailAccountObjectCode.setCategoryCode(category.getCategoryCode()); invoiceDetailAccountObjectCode.setAccountNumber(bal.getAccountNumber()); invoiceDetailAccountObjectCode.setChartOfAccountsCode(bal.getChartOfAccountsCode()); invoiceDetailAccountObjectCodes.add(invoiceDetailAccountObjectCode); } else { LOG.warn("Could not find cost category for balance: "+bal.getUniversityFiscalYear()+" "+bal.getChartOfAccountsCode()+" "+bal.getAccountNumber()+" "+bal.getSubAccountNumber()+" "+bal.getObjectCode()+" "+bal.getSubObjectCode()+" "+bal.getBalanceTypeCode()); } } return invoiceDetailAccountObjectCode; } /** * Looks for a matching invoice detail account object code in the given list that matches the given balance and proposal number * @param invoiceDetailAccountObjectsCodes a List of invoice detail account object codes to look up values from * @param bal the balance to match * @param proposalNumber the proposal number to match * @return the matching invoice detail account object code record, or null if no matching record can be found */ protected InvoiceDetailAccountObjectCode lookupInvoiceDetailAccountObjectCode(List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectsCodes, Balance bal, final Long proposalNumber) { for (InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode : invoiceDetailAccountObjectsCodes) { if (StringUtils.equals(bal.getChartOfAccountsCode(), invoiceDetailAccountObjectCode.getChartOfAccountsCode()) && StringUtils.equals(bal.getAccountNumber(), invoiceDetailAccountObjectCode.getAccountNumber()) && StringUtils.equals(bal.getObjectCode(), invoiceDetailAccountObjectCode.getFinancialObjectCode()) && org.apache.commons.lang.ObjectUtils.equals(proposalNumber, invoiceDetailAccountObjectCode.getProposalNumber())) { return invoiceDetailAccountObjectCode; } } return null; } /** * Determines if a balance represents a cost share or not * @param bal the balance to check * @return true if the balance is a cost share, false otherwise */ protected boolean isBalanceCostShare(Balance bal) { return !ObjectUtils.isNull(bal.getSubAccount()) && !ObjectUtils.isNull(bal.getSubAccount().getA21SubAccount()) && StringUtils.equalsIgnoreCase(bal.getSubAccount().getA21SubAccount().getSubAccountTypeCode(), KFSConstants.SubAccountType.COST_SHARE); } /** * Given the billing frequency code, determines if the billing is time-based: monthly, quarterly, bi-annual, or annual * @param billingFrequencyCode the billing frequency code * @return true if time-based billing is used, false if */ protected boolean useTimeBasedBillingFrequency(String billingFrequencyCode) { return billingFrequencyCode.equalsIgnoreCase(ArConstants.MONTHLY_BILLING_SCHEDULE_CODE) || billingFrequencyCode.equalsIgnoreCase(ArConstants.QUATERLY_BILLING_SCHEDULE_CODE) || billingFrequencyCode.equalsIgnoreCase(ArConstants.SEMI_ANNUALLY_BILLING_SCHEDULE_CODE) || billingFrequencyCode.equalsIgnoreCase(ArConstants.ANNUALLY_BILLING_SCHEDULE_CODE); } /** * Retrieves balances used to populate amounts for an invoice account detail * @param fiscalYear the fiscal year of the balances to find * @param chartOfAccountsCode the chart of accounts code of balances to find * @param accountNumber the account number of balances to find * @param balanceTypeCodeList the balance type codes of balances to find * @return a List of retrieved balances */ protected List<Balance> retrieveBalances(Integer fiscalYear, String chartOfAccountsCode, String accountNumber, List<String> balanceTypeCodeList) { final SystemOptions systemOptions = optionsService.getOptions(fiscalYear); Map<String, Object> balanceKeys = new HashMap<String, Object>(); balanceKeys.put(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode); balanceKeys.put(KFSPropertyConstants.ACCOUNT_NUMBER, accountNumber); balanceKeys.put(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR, fiscalYear); balanceKeys.put(KFSPropertyConstants.OBJECT_TYPE_CODE, retrieveExpenseObjectTypes()); balanceKeys.put(KFSPropertyConstants.BALANCE_TYPE_CODE,balanceTypeCodeList); return (List<Balance>)getBusinessObjectService().findMatching(Balance.class, balanceKeys); } /** * Determines if Period 13 should be included in Period 01 calculations for invoice details and invoice account details * @return true if period 13 should be included, false otherwise */ protected boolean includePeriod13InPeriod01Calculations() { return getParameterService().getParameterValueAsBoolean(ContractsGrantsInvoiceDocument.class, ArParameterKeyConstants.INCLUDE_PERIOD_13_IN_BUDGET_AND_CURRENT_IND_PARM_NM, Boolean.FALSE); } /** * This method helps in setting up basic values for Contracts Grants Invoice Document */ protected void populateContractsGrantsInvoiceDocument(ContractsAndGrantsBillingAward award, ContractsGrantsInvoiceDocument document) { if (ObjectUtils.isNotNull(award.getAgency())) { if (ObjectUtils.isNotNull(document.getAccountsReceivableDocumentHeader())) { document.getAccountsReceivableDocumentHeader().setCustomerNumber(award.getAgency().getCustomerNumber()); } Customer customer = getCustomerService().getByPrimaryKey(award.getAgency().getCustomerNumber()); if (ObjectUtils.isNotNull(customer)) { document.setCustomerName(customer.getCustomerName()); } } // To set open invoice indicator to true to help doing cash control for the invoice document.setOpenInvoiceIndicator(true); // To set LOC creation type and appropriate values from award. if (StringUtils.isNotEmpty(award.getLetterOfCreditCreationType())) { document.getInvoiceGeneralDetail().setLetterOfCreditCreationType(award.getLetterOfCreditCreationType()); } // To set up values for Letter of Credit Fund and Fund Group irrespective of the LOC Creation type. if (StringUtils.isNotEmpty(award.getLetterOfCreditFundCode())) { document.getInvoiceGeneralDetail().setLetterOfCreditFundCode(award.getLetterOfCreditFundCode()); } if (ObjectUtils.isNotNull(award.getLetterOfCreditFund())) { if (StringUtils.isNotEmpty(award.getLetterOfCreditFund().getLetterOfCreditFundGroupCode())) { document.getInvoiceGeneralDetail().setLetterOfCreditFundGroupCode(award.getLetterOfCreditFund().getLetterOfCreditFundGroupCode()); } } // set totalBilled by Account Number in Account Details Map<String, KualiDecimal> totalBilledByAccountNumberMap = new HashMap<String, KualiDecimal>(); for (InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode : document.getInvoiceDetailAccountObjectCodes()) { String key = invoiceDetailAccountObjectCode.getChartOfAccountsCode()+"-"+invoiceDetailAccountObjectCode.getAccountNumber(); KualiDecimal totalBilled = cleanAmount(totalBilledByAccountNumberMap.get(key)); totalBilled = totalBilled.add(invoiceDetailAccountObjectCode.getTotalBilled()); totalBilledByAccountNumberMap.put(key, totalBilled); } KualiDecimal totalExpendituredAmount = KualiDecimal.ZERO; for (InvoiceAccountDetail invAcctD : document.getAccountDetails()) { KualiDecimal currentExpenditureAmount = KualiDecimal.ZERO; if (!ObjectUtils.isNull(totalBilledByAccountNumberMap.get(invAcctD.getChartOfAccountsCode()+"-"+invAcctD.getAccountNumber()))) { invAcctD.setBilledAmount(totalBilledByAccountNumberMap.get(invAcctD.getChartOfAccountsCode()+"-"+invAcctD.getAccountNumber())); } else { invAcctD.setBilledAmount(KualiDecimal.ZERO); } currentExpenditureAmount = invAcctD.getCumulativeAmount().subtract(invAcctD.getBilledAmount()); invAcctD.setExpenditureAmount(currentExpenditureAmount); // overwriting account detail expenditure amount if locReview Indicator is true - and award belongs to LOC Billing for (ContractsAndGrantsBillingAwardAccount awardAccount : award.getActiveAwardAccounts()) { if (StringUtils.equals(awardAccount.getChartOfAccountsCode(), invAcctD.getChartOfAccountsCode()) && StringUtils.equals(awardAccount.getAccountNumber(), invAcctD.getAccountNumber()) && awardAccount.isLetterOfCreditReviewIndicator() && StringUtils.equalsIgnoreCase(award.getBillingFrequencyCode(), ArConstants.LOC_BILLING_SCHEDULE_CODE)) { currentExpenditureAmount = awardAccount.getAmountToDraw(); invAcctD.setExpenditureAmount(currentExpenditureAmount); } } totalExpendituredAmount = totalExpendituredAmount.add(currentExpenditureAmount); } totalExpendituredAmount = totalExpendituredAmount.add(document.getInvoiceGeneralDetail().getBilledToDateAmount()); KualiDecimal totalMilestoneAmount = KualiDecimal.ZERO; // To calculate the total milestone amount. if (document.getInvoiceMilestones().size() > 0) { for (InvoiceMilestone milestone : document.getInvoiceMilestones()) { if (milestone.getMilestoneAmount() != null) { totalMilestoneAmount = totalMilestoneAmount.add(milestone.getMilestoneAmount()); } } } totalMilestoneAmount = totalMilestoneAmount.add(document.getInvoiceGeneralDetail().getBilledToDateAmount()); KualiDecimal totalBillAmount = KualiDecimal.ZERO; // To calculate the total bill amount. if (document.getInvoiceBills().size() > 0) { for (InvoiceBill bill : document.getInvoiceBills()) { if (bill.getEstimatedAmount() != null) { totalBillAmount = totalBillAmount.add(bill.getEstimatedAmount()); } } } totalBillAmount = totalBillAmount.add(document.getInvoiceGeneralDetail().getBilledToDateAmount()); // To set the New Total Billed Amount. if (document.getInvoiceMilestones().size() > 0) { document.getInvoiceGeneralDetail().setNewTotalBilled(totalMilestoneAmount); } else if (document.getInvoiceBills().size() > 0) { document.getInvoiceGeneralDetail().setNewTotalBilled(totalBillAmount); } else { document.getInvoiceGeneralDetail().setNewTotalBilled(totalExpendituredAmount); } } /** * This method would make sure the amounts of the current period are not included. So it calculates the cumulative and * subtracts the current period values. This would be done for Billing Frequencies - Monthly, Quarterly, Semi-Annual and Annual. * * @param glBalance * @return balanceAmount */ protected KualiDecimal calculateBalanceAmountWithoutLastBilledPeriod(java.sql.Date lastBilledDate, Balance glBalance) { Timestamp ts = new Timestamp(new java.util.Date().getTime()); java.sql.Date today = new java.sql.Date(ts.getTime()); AccountingPeriod currPeriod = accountingPeriodService.getByDate(today); String currentPeriodCode = currPeriod.getUniversityFiscalPeriodCode(); KualiDecimal currentBalanceAmount = KualiDecimal.ZERO; switch (currentPeriodCode) { case KFSConstants.MONTH13: currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth12Amount())); // notice - no break!!!! we want to fall through to pick up all the prior months amounts case KFSConstants.MONTH12: currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth11Amount())); case KFSConstants.MONTH11: currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth10Amount())); case KFSConstants.MONTH10: currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth9Amount())); case KFSConstants.MONTH9: currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth8Amount())); case KFSConstants.MONTH8: currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth7Amount())); case KFSConstants.MONTH7: currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth6Amount())); case KFSConstants.MONTH6: currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth5Amount())); case KFSConstants.MONTH5: currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth4Amount())); case KFSConstants.MONTH4: currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth3Amount())); case KFSConstants.MONTH3: currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth2Amount())); case KFSConstants.MONTH2: currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth1Amount())); } return glBalance.getContractsGrantsBeginningBalanceAmount().add(currentBalanceAmount); } /** * Null protects the addition in retrieveAccurateBalanceAmount * @param amount the amount to return * @return zero if the amount was null, the given amount otherwise */ protected KualiDecimal cleanAmount(KualiDecimal amount) { return amount == null ? KualiDecimal.ZERO : amount; } /** * @see org.kuali.kfs.module.ar.service.ContractsGrantsInvoiceCreateDocumentService#retrieveNonLOCAwards() */ @Override public Collection<ContractsAndGrantsBillingAward> retrieveNonLOCAwards() { Map<String, Object> map = new HashMap<String, Object>(); map.put(KFSPropertyConstants.ACTIVE, true); // It would be nice not to have to manually remove LOC awards, maybe when we convert to KRAD // we could leverage the KRAD-DATA Criteria framework to avoid this Collection<ContractsAndGrantsBillingAward> awards = kualiModuleService.getResponsibleModuleService(ContractsAndGrantsBillingAward.class).getExternalizableBusinessObjectsList(ContractsAndGrantsBillingAward.class, map); Iterator<ContractsAndGrantsBillingAward> it = awards.iterator(); while (it.hasNext()) { ContractsAndGrantsBillingAward award = it.next(); if (StringUtils.equalsIgnoreCase(award.getBillingFrequencyCode(), ArConstants.LOC_BILLING_SCHEDULE_CODE)) { it.remove(); } } return awards; } /** * @see org.kuali.kfs.module.ar.batch.service.ContractsGrantsInvoiceCreateDocumentService#validateAwards(java.util.Collection, java.util.Collection) */ @Override public Collection<ContractsAndGrantsBillingAward> validateAwards(Collection<ContractsAndGrantsBillingAward> awards, Collection<ContractsGrantsInvoiceDocumentErrorLog> contractsGrantsInvoiceDocumentErrorLogs, String errOutputFile, String creationProcessTypeCode) { Map<ContractsAndGrantsBillingAward, List<String>> invalidGroup = new HashMap<ContractsAndGrantsBillingAward, List<String>>(); List<ContractsAndGrantsBillingAward> qualifiedAwards = new ArrayList<ContractsAndGrantsBillingAward>(); if (ObjectUtils.isNull(contractsGrantsInvoiceDocumentErrorLogs)) { contractsGrantsInvoiceDocumentErrorLogs = new ArrayList<ContractsGrantsInvoiceDocumentErrorLog>(); } performAwardValidation(awards, invalidGroup, qualifiedAwards); if (!CollectionUtils.isEmpty(invalidGroup)) { if (StringUtils.isNotBlank(errOutputFile)) { writeErrorToFile(invalidGroup, errOutputFile); } storeValidationErrors(invalidGroup, contractsGrantsInvoiceDocumentErrorLogs, creationProcessTypeCode); } return qualifiedAwards; } /** * Perform all validation checks on the awards passed in to determine if CGB Invoice documents can be * created for the given awards. * * @param awards to be validated * @param invalidGroup Map of errors per award that failed validation * @param qualifiedAwards List of awards that are valid to create CGB Invoice docs from */ protected void performAwardValidation(Collection<ContractsAndGrantsBillingAward> awards, Map<ContractsAndGrantsBillingAward, List<String>> invalidGroup, List<ContractsAndGrantsBillingAward> qualifiedAwards) { for (ContractsAndGrantsBillingAward award : awards) { List<String> errorList = new ArrayList<String>(); if (award.getAwardBeginningDate() != null) { if (award.getBillingFrequencyCode() != null && getContractsGrantsBillingAwardVerificationService().isValueOfBillingFrequencyValid(award)) { if (verifyBillingFrequencyService.validateBillingFrequency(award)) { validateAward(errorList, award); } else { errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_AWARD_INVALID_BILLING_PERIOD)); } } else { errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_BILLING_FREQUENCY_MISSING_ERROR)); } } else { errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_AWARD_START_DATE_MISSING_ERROR)); } if (errorList.size() > 0) { invalidGroup.put(award, errorList); } else { qualifiedAwards.add(award); } } } /** * Perform validation for an award to determine if a CGB Invoice document can be created for the award. * * @param errorList list of validation errors per award * @param award to perform validation upon */ protected void validateAward(List<String> errorList, ContractsAndGrantsBillingAward award) { // 1. Award is excluded from invoicing if (award.isExcludedFromInvoicing()) { errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_AWARD_EXCLUDED_FROM_INVOICING)); } // 2. Award is Inactive if (!award.isActive()) { errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_AWARD_INACTIVE_ERROR)); } // 4. Award invoicing option is missing if (StringUtils.isEmpty(award.getInvoicingOptionCode())) { errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_INVOICING_OPTION_MISSING_ERROR)); } // 5. Award billing frequency is not set correctly if (!getContractsGrantsBillingAwardVerificationService().isBillingFrequencySetCorrectly(award)) { errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_SINGLE_ACCOUNT_ERROR)); } // 6. Award has no accounts assigned if (CollectionUtils.isEmpty(award.getActiveAwardAccounts())) { errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_NO_ACTIVE_ACCOUNTS_ASSIGNED_ERROR)); } // 7. Award contains expired account or accounts Collection<Account> expAccounts = getContractsGrantsInvoiceDocumentService().getExpiredAccountsOfAward(award); if (ObjectUtils.isNotNull(expAccounts) && !expAccounts.isEmpty()) { StringBuilder line = new StringBuilder(); line.append(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_CONAINS_EXPIRED_ACCOUNTS_ERROR)); for (Account expAccount : expAccounts) { line.append(" (expired account: " + expAccount.getAccountNumber() + " expiration date " + expAccount.getAccountExpirationDate() + ") "); } errorList.add(line.toString()); } // 8. Award has final invoice Billed already if (getContractsGrantsBillingAwardVerificationService().isAwardFinalInvoiceAlreadyBuilt(award)) { errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_AWARD_FINAL_BILLED_ERROR)); } // 9. Award has no valid milestones to invoice if (!getContractsGrantsBillingAwardVerificationService().hasMilestonesToInvoice(award)) { errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_AWARD_NO_VALID_MILESTONES)); } // 10. All has no valid bills to invoice if (!getContractsGrantsBillingAwardVerificationService().hasBillsToInvoice(award)) { errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_AWARD_NO_VALID_BILLS)); } // 11. Agency has no matching Customer record if (!getContractsGrantsBillingAwardVerificationService().owningAgencyHasCustomerRecord(award)) { errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_AWARD_AGENCY_NO_CUSTOMER_RECORD)); } // 12. All accounts of an Award have zero$ to invoice if (!hasBillableAccounts(award)) { errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_AWARD_NO_VALID_ACCOUNTS)); } // 13. Award does not have appropriate Contract Control Accounts set based on Invoicing Options List<String> errorString = contractsGrantsInvoiceDocumentService.checkAwardContractControlAccounts(award); if (!CollectionUtils.isEmpty(errorString) && errorString.size() > 1) { errorList.add(configurationService.getPropertyValueAsString(errorString.get(0)).replace("{0}", errorString.get(1))); } // 14. System Information and ORganization Accounting Default not setup. if (!getContractsGrantsBillingAwardVerificationService().isChartAndOrgSetupForInvoicing(award)) { errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_SYS_INFO_OADF_NOT_SETUP)); } } protected void writeErrorToFile(Map<ContractsAndGrantsBillingAward, List<String>> invalidGroup, String errOutputFile) { PrintStream outputFileStream = null; File errOutPutfile = new File(errOutputFile); try { outputFileStream = new PrintStream(errOutPutfile); writeReportHeader(outputFileStream); for (ContractsAndGrantsBillingAward award : invalidGroup.keySet()) { writeErrorEntryByAward(award, invalidGroup.get(award), outputFileStream); } outputFileStream.printf("\r\n"); } catch (IOException ioe) { LOG.error("Could not write errors in contracts and grants invoice document creation process to file" + ioe.getMessage()); throw new RuntimeException("Could not write errors in contracts and grants invoice document creation process to file", ioe); } finally { if (outputFileStream != null) { outputFileStream.close(); } } } protected void storeValidationErrors(Map<ContractsAndGrantsBillingAward, List<String>> invalidGroup, Collection<ContractsGrantsInvoiceDocumentErrorLog> contractsGrantsInvoiceDocumentErrorLogs, String creationProcessTypeCode) { for (ContractsAndGrantsBillingAward award : invalidGroup.keySet()) { KualiDecimal cumulativeExpenses = KualiDecimal.ZERO; ContractsGrantsInvoiceDocumentErrorLog contractsGrantsInvoiceDocumentErrorLog = new ContractsGrantsInvoiceDocumentErrorLog(); if (ObjectUtils.isNotNull(award)){ String proposalNumber = award.getProposalNumber().toString(); Date beginningDate = award.getAwardBeginningDate(); Date endingDate = award.getAwardEndingDate(); KualiDecimal totalAmount = award.getAwardTotalAmount(); final SystemOptions systemOptions = optionsService.getCurrentYearOptions(); contractsGrantsInvoiceDocumentErrorLog.setProposalNumber(award.getProposalNumber()); contractsGrantsInvoiceDocumentErrorLog.setAwardBeginningDate(beginningDate); contractsGrantsInvoiceDocumentErrorLog.setAwardEndingDate(endingDate); contractsGrantsInvoiceDocumentErrorLog.setAwardTotalAmount(award.getAwardTotalAmount().bigDecimalValue()); if (ObjectUtils.isNotNull(award.getAwardPrimaryFundManager())) { contractsGrantsInvoiceDocumentErrorLog.setPrimaryFundManagerPrincipalId(award.getAwardPrimaryFundManager().getPrincipalId()); } if (!CollectionUtils.isEmpty(award.getActiveAwardAccounts())) { boolean firstLineFlag = true; for (ContractsAndGrantsBillingAwardAccount awardAccount : award.getActiveAwardAccounts()) { cumulativeExpenses = cumulativeExpenses.add(contractsGrantsInvoiceDocumentService.getBudgetAndActualsForAwardAccount(awardAccount, systemOptions.getActualFinancialBalanceTypeCd(), beginningDate)); if (firstLineFlag) { firstLineFlag = false; contractsGrantsInvoiceDocumentErrorLog.setAccounts(awardAccount.getAccountNumber()); } else { contractsGrantsInvoiceDocumentErrorLog.setAccounts(contractsGrantsInvoiceDocumentErrorLog.getAccounts() + ";" + awardAccount.getAccountNumber()); } } } contractsGrantsInvoiceDocumentErrorLog.setCumulativeExpensesAmount(cumulativeExpenses.bigDecimalValue()); } for (String vCat : invalidGroup.get(award)) { ContractsGrantsInvoiceDocumentErrorMessage contractsGrantsInvoiceDocumentErrorCategory = new ContractsGrantsInvoiceDocumentErrorMessage(); contractsGrantsInvoiceDocumentErrorCategory.setErrorMessageText(vCat); contractsGrantsInvoiceDocumentErrorLog.getErrorMessages().add(contractsGrantsInvoiceDocumentErrorCategory); } contractsGrantsInvoiceDocumentErrorLog.setErrorDate(dateTimeService.getCurrentTimestamp()); contractsGrantsInvoiceDocumentErrorLog.setCreationProcessTypeCode(creationProcessTypeCode); businessObjectService.save(contractsGrantsInvoiceDocumentErrorLog); contractsGrantsInvoiceDocumentErrorLogs.add(contractsGrantsInvoiceDocumentErrorLog); } } protected void storeCreationErrors(List<ErrorMessage> errorMessages, String creationProcessTypeCode) { for (ErrorMessage errorMessage : errorMessages) { ContractsGrantsInvoiceDocumentErrorLog contractsGrantsInvoiceDocumentErrorLog = new ContractsGrantsInvoiceDocumentErrorLog(); ContractsGrantsInvoiceDocumentErrorMessage contractsGrantsInvoiceDocumentErrorCategory = new ContractsGrantsInvoiceDocumentErrorMessage(); contractsGrantsInvoiceDocumentErrorCategory.setErrorMessageText(MessageFormat.format(configurationService.getPropertyValueAsString(errorMessage.getErrorKey()), (Object[])errorMessage.getMessageParameters())); contractsGrantsInvoiceDocumentErrorLog.getErrorMessages().add(contractsGrantsInvoiceDocumentErrorCategory); contractsGrantsInvoiceDocumentErrorLog.setErrorDate(dateTimeService.getCurrentTimestamp()); contractsGrantsInvoiceDocumentErrorLog.setCreationProcessTypeCode(creationProcessTypeCode); businessObjectService.save(contractsGrantsInvoiceDocumentErrorLog); } } /** * This method retrieves all the contracts grants invoice documents with a status of Saved and * routes them to the next step in the routing path. * * @return True if the routing was performed successfully. A runtime exception will be thrown if any errors occur while routing. * @see org.kuali.kfs.module.ar.batch.service.ContractsGrantsInvoiceDocumentCreateService#routeContractsGrantsInvoiceDocuments() */ @Override public void routeContractsGrantsInvoiceDocuments() { final String currentUserPrincipalId = GlobalVariables.getUserSession().getPerson().getPrincipalId(); List<String> documentIdList = retrieveContractsGrantsInvoiceDocumentsToRoute(DocumentStatus.SAVED, currentUserPrincipalId); if (LOG.isInfoEnabled()) { LOG.info("CGinvoice to Route: " + documentIdList); } for (String cgInvoiceDocId : documentIdList) { try { ContractsGrantsInvoiceDocument cgInvoicDoc = (ContractsGrantsInvoiceDocument) documentService.getByDocumentHeaderId(cgInvoiceDocId); // To route documents only if the user in the session is same as the initiator. if (LOG.isInfoEnabled()) { LOG.info("Routing Contracts Grants Invoice document # " + cgInvoiceDocId + "."); } documentService.prepareWorkflowDocument(cgInvoicDoc); // calling workflow service to bypass business rule checks workflowDocumentService.route(cgInvoicDoc.getDocumentHeader().getWorkflowDocument(), "", null); } catch (WorkflowException e) { LOG.error("Error routing document # " + cgInvoiceDocId + " " + e.getMessage()); throw new RuntimeException(e.getMessage(), e); } } } /** * Returns a list of all saved but not yet routed contracts grants invoice documents, using the KualiWorkflowInfo service. * * @return a list of contracts grants invoice documents to route */ protected List<String> retrieveContractsGrantsInvoiceDocumentsToRoute(DocumentStatus statusCode, String initiatorPrincipalId) { List<String> documentIds = new ArrayList<String>(); Map<String, Object> fieldValues = new HashMap<String, Object>(); fieldValues.put(KFSPropertyConstants.WORKFLOW_DOCUMENT_TYPE_NAME, ArConstants.ArDocumentTypeCodes.CONTRACTS_GRANTS_INVOICE); fieldValues.put(KFSPropertyConstants.WORKFLOW_DOCUMENT_STATUS_CODE, statusCode.getCode()); fieldValues.put(KFSPropertyConstants.INITIATOR_PRINCIPAL_ID, initiatorPrincipalId); Collection<FinancialSystemDocumentHeader> docHeaders = businessObjectService.findMatching(FinancialSystemDocumentHeader.class, fieldValues); for (FinancialSystemDocumentHeader docHeader : docHeaders) { documentIds.add(docHeader.getDocumentNumber()); } return documentIds; } protected void writeErrorEntryByAward(ContractsAndGrantsBillingAward award, List<String> validationCategory, PrintStream printStream) throws IOException { // %15s %18s %20s %19s %15s %18s %23s %18s if (ObjectUtils.isNotNull(award)){ KualiDecimal cumulativeExpenses = KualiDecimal.ZERO; String awardBeginningDate; String awardEndingDate; String awardTotalAmount; String proposalNumber = award.getProposalNumber().toString(); Date beginningDate = award.getAwardBeginningDate(); Date endingDate = award.getAwardEndingDate(); KualiDecimal totalAmount = award.getAwardTotalAmount(); if (ObjectUtils.isNotNull(beginningDate)) { awardBeginningDate = beginningDate.toString(); } else { awardBeginningDate = "null award beginning date"; } if (ObjectUtils.isNotNull(endingDate)) { awardEndingDate = endingDate.toString(); } else { awardEndingDate = "null award ending date"; } if (ObjectUtils.isNotNull(totalAmount) && ObjectUtils.isNotNull(totalAmount.bigDecimalValue())) { awardTotalAmount = totalAmount.toString(); } else { awardTotalAmount = "null award total amount"; } if (CollectionUtils.isEmpty(award.getActiveAwardAccounts())) { writeToReport(proposalNumber, "", awardBeginningDate, awardEndingDate, awardTotalAmount, cumulativeExpenses.toString(), printStream); } else { final SystemOptions systemOptions = optionsService.getCurrentYearOptions(); // calculate cumulativeExpenses for (ContractsAndGrantsBillingAwardAccount awardAccount : award.getActiveAwardAccounts()) { cumulativeExpenses = cumulativeExpenses.add(contractsGrantsInvoiceDocumentService.getBudgetAndActualsForAwardAccount(awardAccount, systemOptions.getActualFinancialBalanceTypeCd(), award.getAwardBeginningDate())); } boolean firstLineFlag = true; for (ContractsAndGrantsBillingAwardAccount awardAccount : award.getActiveAwardAccounts()) { if (firstLineFlag) { writeToReport(proposalNumber, awardAccount.getAccountNumber(), awardBeginningDate, awardEndingDate, awardTotalAmount, cumulativeExpenses.toString(), printStream); firstLineFlag = false; } else { writeToReport("", awardAccount.getAccountNumber(), "", "", "", "", printStream); } } } } // To print all the errors from the validation category. for (String vCat : validationCategory) { printStream.printf("%s", " " + vCat); printStream.printf("\r\n"); } printStream.printf(REPORT_LINE_DIVIDER); printStream.printf("\r\n"); } protected void writeToReport(String proposalNumber, String accountNumber, String awardBeginningDate, String awardEndingDate, String awardTotalAmount, String cumulativeExpenses, PrintStream printStream) throws IOException { printStream.printf("%15s", proposalNumber); printStream.printf("%18s", accountNumber); printStream.printf("%20s", awardBeginningDate); printStream.printf("%19s", awardEndingDate); printStream.printf("%15s", awardTotalAmount); printStream.printf("%23s", cumulativeExpenses); printStream.printf("\r\n"); } /** * @param printStream * @throws IOException */ protected void writeReportHeader(PrintStream printStream) throws IOException { printStream.printf("%15s%18s%20s%19s%15s%23s\r\n", "Proposal Number", "Account Number", "Award Start Date", "Award Stop Date", "Award Total", "Cumulative Expenses"); printStream.printf("%23s", "Validation Category"); printStream.printf("\r\n"); printStream.printf(REPORT_LINE_DIVIDER); printStream.printf("\r\n"); } protected boolean hasBillableAccounts(ContractsAndGrantsBillingAward award) { String billingFrequencyCode = award.getBillingFrequencyCode(); if (StringUtils.equalsIgnoreCase(billingFrequencyCode, ArConstants.MILESTONE_BILLING_SCHEDULE_CODE) || StringUtils.equalsIgnoreCase(billingFrequencyCode, ArConstants.PREDETERMINED_BILLING_SCHEDULE_CODE)) { return !getContractsGrantsBillingAwardVerificationService().isInvoiceInProgress(award); } else { return CollectionUtils.isEmpty(award.getActiveAwardAccounts()) || !CollectionUtils.isEmpty(getValidAwardAccounts(award.getActiveAwardAccounts(), award)); } } /** * This method returns the valid award accounts based on evaluation of billing frequency and invoice document status * * @param awardAccounts * @return valid awardAccounts */ protected List<ContractsAndGrantsBillingAwardAccount> getValidAwardAccounts(List<ContractsAndGrantsBillingAwardAccount> awardAccounts, ContractsAndGrantsBillingAward award) { if (!award.getBillingFrequencyCode().equalsIgnoreCase(ArConstants.MILESTONE_BILLING_SCHEDULE_CODE) && !award.getBillingFrequencyCode().equalsIgnoreCase(ArConstants.PREDETERMINED_BILLING_SCHEDULE_CODE)) { List<ContractsAndGrantsBillingAwardAccount> validAwardAccounts = new ArrayList<ContractsAndGrantsBillingAwardAccount>(); final Set<Account> invalidAccounts = harvestAccountsFromContractsGrantsInvoices(getInProgressInvoicesForAward(award)); for (ContractsAndGrantsBillingAwardAccount awardAccount : awardAccounts) { if (!invalidAccounts.contains(awardAccount.getAccount())) { validAwardAccounts.add(awardAccount); } } return validAwardAccounts; } else { return awardAccounts; } } /** * Pulls all the unique accounts from the source accounting lines on the given ContractsGrantsInvoiceDocument * @param contractsGrantsInvoices the invoices to pull unique accounts from * @return a Set of the unique accounts */ protected Set<Account> harvestAccountsFromContractsGrantsInvoices(Collection<ContractsGrantsInvoiceDocument> contractsGrantsInvoices) { Set<Account> accounts = new HashSet<Account>(); for (ContractsGrantsInvoiceDocument invoice : contractsGrantsInvoices) { for (InvoiceAccountDetail invoiceAccountDetail : invoice.getAccountDetails()) { final Account account = getAccountService().getByPrimaryId(invoiceAccountDetail.getChartOfAccountsCode(), invoiceAccountDetail.getAccountNumber()); if (!ObjectUtils.isNull(account)) { accounts.add(account); } } } return accounts; } /** * Looks up all the in progress contracts & grants invoices for the award * @param award the award to look up contracts & grants invoices for * @return a Collection matching in progress/pending Contracts & Grants Invoice documents */ protected Collection<ContractsGrantsInvoiceDocument> getInProgressInvoicesForAward(ContractsAndGrantsBillingAward award) { Map<String, Object> fieldValues = new HashMap<String, Object>(); fieldValues.put(ArPropertyConstants.ContractsGrantsInvoiceDocumentFields.PROPOSAL_NUMBER, award.getProposalNumber()); fieldValues.put(KFSPropertyConstants.DOCUMENT_HEADER+"."+KFSPropertyConstants.WORKFLOW_DOCUMENT_STATUS_CODE, financialSystemDocumentService.getPendingDocumentStatuses()); return businessObjectService.findMatching(ContractsGrantsInvoiceDocument.class, fieldValues); } /** * Retrieve expense object types by the basic accounting category for expenses * @see org.kuali.kfs.module.ar.service.ContractsGrantsInvoiceCreateDocumentService#retrieveExpenseObjectTypes() */ @Override public Collection<String> retrieveExpenseObjectTypes() { List<String> objectTypeCodes = new ArrayList<>(); Map<String, Object> fieldValues = new HashMap<>(); fieldValues.put(KFSPropertyConstants.BASIC_ACCOUNTING_CATEGORY_CODE, KFSConstants.BasicAccountingCategoryCodes.EXPENSES); final Collection<ObjectType> objectTypes = getBusinessObjectService().findMatching(ObjectType.class, fieldValues); for (ObjectType objectType : objectTypes) { objectTypeCodes.add(objectType.getCode()); } return objectTypeCodes; } public AccountService getAccountService() { return accountService; } public void setAccountService(AccountService accountService) { this.accountService = accountService; } /** * Sets the accountingPeriodService attribute value. * * @param accountingPeriodService The accountingPeriodService to set. */ public void setAccountingPeriodService(AccountingPeriodService accountingPeriodService) { this.accountingPeriodService = accountingPeriodService; } /** * Sets the verifyBillingFrequencyService attribute value. * * @param verifyBillingFrequencyService The verifyBillingFrequencyService to set. */ public void setVerifyBillingFrequencyService(VerifyBillingFrequencyService verifyBillingFrequencyService) { this.verifyBillingFrequencyService = verifyBillingFrequencyService; } public BusinessObjectService getBusinessObjectService() { return businessObjectService; } /** * Sets the businessObjectService attribute value. * * @param businessObjectService The businessObjectService to set. */ public void setBusinessObjectService(BusinessObjectService businessObjectService) { this.businessObjectService = businessObjectService; } /** * Sets the workflowDocumentService attribute value. * * @param workflowDocumentService The workflowDocumentService to set. */ public void setWorkflowDocumentService(WorkflowDocumentService workflowDocumentService) { this.workflowDocumentService = workflowDocumentService; } /** * Sets the documentService attribute value. * * @param documentService The documentService to set. */ public void setDocumentService(DocumentService documentService) { this.documentService = documentService; } /** * Sets the accountsReceivableDocumentHeaderService attribute value. * * @param accountsReceivableDocumentHeaderService The accountsReceivableDocumentHeaderService to set. */ public void setAccountsReceivableDocumentHeaderService(AccountsReceivableDocumentHeaderService accountsReceivableDocumentHeaderService) { this.accountsReceivableDocumentHeaderService = accountsReceivableDocumentHeaderService; } /** * Sets the contractsGrantsInvoiceDocumentService attribute value. * * @param contractsGrantsInvoiceDocumentService The contractsGrantsInvoiceDocumentService to set. */ public void setContractsGrantsInvoiceDocumentService(ContractsGrantsInvoiceDocumentService contractsGrantsInvoiceDocumentService) { this.contractsGrantsInvoiceDocumentService = contractsGrantsInvoiceDocumentService; } public ContractsGrantsInvoiceDocumentService getContractsGrantsInvoiceDocumentService() { return contractsGrantsInvoiceDocumentService; } public DateTimeService getDateTimeService() { return dateTimeService; } public void setDateTimeService(DateTimeService dateTimeService) { this.dateTimeService = dateTimeService; } /** * Sets the kualiModuleService attribute value. * * @param kualiModuleService The kualiModuleService to set. */ public void setKualiModuleService(KualiModuleService kualiModuleService) { this.kualiModuleService = kualiModuleService; } public ConfigurationService getConfigurationService() { return configurationService; } public void setConfigurationService(ConfigurationService configurationService) { this.configurationService = configurationService; } public ContractsGrantsBillingUtilityService getContractsGrantsBillingUtilityService() { return contractsGrantsBillingUtilityService; } public void setContractsGrantsBillingUtilityService(ContractsGrantsBillingUtilityService contractsGrantsBillingUtilityService) { this.contractsGrantsBillingUtilityService = contractsGrantsBillingUtilityService; } public ContractsAndGrantsModuleBillingService getContractsAndGrantsModuleBillingService() { return contractsAndGrantsModuleBillingService; } public void setContractsAndGrantsModuleBillingService(ContractsAndGrantsModuleBillingService contractsAndGrantsModuleBillingService) { this.contractsAndGrantsModuleBillingService = contractsAndGrantsModuleBillingService; } public FinancialSystemDocumentService getFinancialSystemDocumentService() { return financialSystemDocumentService; } public void setFinancialSystemDocumentService(FinancialSystemDocumentService financialSystemDocumentService) { this.financialSystemDocumentService = financialSystemDocumentService; } public UniversityDateService getUniversityDateService() { return universityDateService; } public void setUniversityDateService(UniversityDateService universityDateService) { this.universityDateService = universityDateService; } public AwardAccountObjectCodeTotalBilledDao getAwardAccountObjectCodeTotalBilledDao() { return awardAccountObjectCodeTotalBilledDao; } public void setAwardAccountObjectCodeTotalBilledDao(AwardAccountObjectCodeTotalBilledDao awardAccountObjectCodeTotalBilledDao) { this.awardAccountObjectCodeTotalBilledDao = awardAccountObjectCodeTotalBilledDao; } public CustomerService getCustomerService() { return customerService; } public void setCustomerService(CustomerService customerService) { this.customerService = customerService; } public ParameterService getParameterService() { return parameterService; } public void setParameterService(ParameterService parameterService) { this.parameterService = parameterService; } public ContractsGrantsBillingAwardVerificationService getContractsGrantsBillingAwardVerificationService() { return contractsGrantsBillingAwardVerificationService; } public void setContractsGrantsBillingAwardVerificationService(ContractsGrantsBillingAwardVerificationService contractsGrantsBillingAwardVerificationService) { this.contractsGrantsBillingAwardVerificationService = contractsGrantsBillingAwardVerificationService; } public CostCategoryService getCostCategoryService() { return costCategoryService; } public void setCostCategoryService(CostCategoryService costCategoryService) { this.costCategoryService = costCategoryService; } public OptionsService getOptionsService() { return optionsService; } public void setOptionsService(OptionsService optionsService) { this.optionsService = optionsService; } }
package info.bitrich.xchangestream.poloniex2; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import info.bitrich.xchangestream.poloniex2.dto.PoloniexWebSocketEvent; import info.bitrich.xchangestream.poloniex2.dto.PoloniexWebSocketEventsTransaction; import info.bitrich.xchangestream.poloniex2.dto.PoloniexWebSocketSubscriptionMessage; import info.bitrich.xchangestream.service.netty.JsonNettyStreamingService; import info.bitrich.xchangestream.service.netty.StreamingObjectMapperHelper; import io.reactivex.Completable; import io.reactivex.Observable; import org.knowm.xchange.currency.CurrencyPair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Optional; public class PoloniexStreamingService extends JsonNettyStreamingService { private static final Logger LOG = LoggerFactory.getLogger(PoloniexStreamingService.class); private static final String HEARTBEAT = "1010"; private final Map<String, String> subscribedChannels = new HashMap<>(); private final Map<String, Observable<JsonNode>> subscriptions = new HashMap<>(); public PoloniexStreamingService(String apiUrl) { super(apiUrl, Integer.MAX_VALUE); } @Override protected void handleMessage(JsonNode message) { if (message.isArray()) { if (message.size() < 3) { if (message.get(0).asText().equals(HEARTBEAT)) return; else if (message.get(0).asText().equals("1002")) return; } Integer channelId = new Integer(message.get(0).toString()); if (channelId > 0 && channelId < 1000) { JsonNode events = message.get(2); if (events.isArray()) { JsonNode event = events.get(0); if (event.get(0).toString().equals("\"i\"")) { if (event.get(1).has("orderBook")) { String currencyPair = event.get(1).get("currencyPair").asText(); LOG.info("Register {} as {}", String.valueOf(channelId), currencyPair); subscribedChannels.put(String.valueOf(channelId), currencyPair); } } } } } if (message.has("error")) { LOG.error("Error with message: " + message.get("error").asText()); return; } super.handleMessage(message); } @Override public boolean processArrayMassageSeparately() { return false; } @Override public Observable<JsonNode> subscribeChannel(String channelName, Object... args) { if (!channels.containsKey(channelName)) { Observable<JsonNode> subscription = super.subscribeChannel(channelName, args); subscriptions.put(channelName, subscription); } return subscriptions.get(channelName); } public Observable<PoloniexWebSocketEvent> subscribeCurrencyPairChannel(CurrencyPair currencyPair) { String channelName = currencyPair.counter.toString() + "_" + currencyPair.base.toString(); return subscribeChannel(channelName) .scan(Optional.<JsonNode>empty(), (jsonNodeOldOptional, jsonNodeNew) -> { jsonNodeOldOptional.ifPresent(jsonNode -> { if (jsonNode.get(1).longValue() + 1 != jsonNodeNew.get(1).longValue()) { throw new RuntimeException("Invalid sequencing"); } }); return Optional.of(jsonNodeNew); }) .filter(Optional::isPresent) .map(Optional::get) .flatMapIterable(s -> { PoloniexWebSocketEventsTransaction transaction = objectMapper.treeToValue(s, PoloniexWebSocketEventsTransaction.class); return Arrays.asList(transaction.getEvents()); }).share(); } @Override protected String getChannelNameFromMessage(JsonNode message) throws IOException { String strChannelId = message.get(0).asText(); Integer channelId = new Integer(strChannelId); if (channelId >= 1000) return strChannelId; else return subscribedChannels.get(message.get(0).asText()); } @Override public String getSubscribeMessage(String channelName, Object... args) throws IOException { PoloniexWebSocketSubscriptionMessage subscribeMessage = new PoloniexWebSocketSubscriptionMessage("subscribe", channelName); final ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper(); return objectMapper.writeValueAsString(subscribeMessage); } @Override public String getUnsubscribeMessage(String channelName) throws IOException { PoloniexWebSocketSubscriptionMessage subscribeMessage = new PoloniexWebSocketSubscriptionMessage("unsubscribe", channelName); final ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper(); return objectMapper.writeValueAsString(subscribeMessage); } @Override public Completable disconnect() { return super.disconnect(); } }
package org.opendaylight.yangtools.yang.model.api; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; import com.google.common.annotations.Beta; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Optional; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import org.opendaylight.yangtools.yang.common.QName; /** * Node which can contains other nodes. */ public interface DataNodeContainer { /** * Returns set of all newly defined types within this DataNodeContainer. * * @return typedef statements in lexicographical order */ @NonNull Collection<? extends @NonNull TypeDefinition<?>> getTypeDefinitions(); /** * Returns set of all child nodes defined within this DataNodeContainer. Although the return type is a collection, * each node is guaranteed to be present at most once. * * <p> * Note that the nodes returned are <strong>NOT</strong> {@code data nodes}, but rather {@link DataSchemaNode}s, * hence {@link ChoiceSchemaNode} and {@link CaseSchemaNode} are present instead of their children. This * is consistent with {@code schema tree}. * * @return child nodes in lexicographical order */ @NonNull Collection<? extends @NonNull DataSchemaNode> getChildNodes(); /** * Returns set of all groupings defined within this DataNodeContainer. * * @return grouping statements in lexicographical order */ @NonNull Collection<? extends @NonNull GroupingDefinition> getGroupings(); /** * Returns the child node corresponding to the specified name. * * <p> * Note that the nodes searched are <strong>NOT</strong> {@code data nodes}, but rather {@link DataSchemaNode}s, * hence {@link ChoiceSchemaNode} and {@link CaseSchemaNode} are returned instead of their matching children. This * is consistent with {@code schema tree}. * * @param name QName of child * @return child node of this DataNodeContainer if child with given name is present, null otherwise * @throws NullPointerException if {@code name} is null */ default @Nullable DataSchemaNode dataChildByName(final QName name) { return findDataChildByName(name).orElse(null); } /** * Returns the child node corresponding to the specified name. * * <p> * Note that the nodes searched are <strong>NOT</strong> {@code data nodes}, but rather {@link DataSchemaNode}s, * hence {@link ChoiceSchemaNode} and {@link CaseSchemaNode} are returned instead of their matching children. This * is consistent with {@code schema tree}. * * @param name QName of child * @return child node of this DataNodeContainer if child with given name is present, null otherwise * @deprecated Use {@link #dataChildByName(QName)} or {@link #findDataChildByName(QName)} instead. This method will * be repurposed to assert existence in the next major release. * @throws NullPointerException if {@code name} is null */ @Deprecated(forRemoval = true) default @Nullable DataSchemaNode getDataChildByName(final QName name) { return dataChildByName(name); } /** * Returns the child node corresponding to the specified name. * * <p> * Note that the nodes searched are <strong>NOT</strong> {@code data nodes}, but rather {@link DataSchemaNode}s, * hence {@link ChoiceSchemaNode} and {@link CaseSchemaNode} are returned instead of their matching children. * * @param name QName of child * @return child node of this DataNodeContainer if child with given name is present, empty otherwise * @throws NullPointerException if {@code name} is null */ Optional<DataSchemaNode> findDataChildByName(QName name); /** * Returns the child node corresponding to the specified name. * * <p> * Note that the nodes searched are <strong>NOT</strong> {@code data nodes}, but rather {@link DataSchemaNode}s, * hence {@link ChoiceSchemaNode} and {@link CaseSchemaNode} are returned instead of their matching children. * * @param first QName of first child * @param others QNames of subsequent children * @return child node of this DataNodeContainer if child with given name is present, empty otherwise * @throws NullPointerException if any argument is null */ default Optional<DataSchemaNode> findDataChildByName(final QName first, final QName... others) { Optional<DataSchemaNode> optCurrent = findDataChildByName(first); for (QName qname : others) { if (optCurrent.isPresent()) { final DataSchemaNode current = optCurrent.get(); if (current instanceof DataNodeContainer) { optCurrent = ((DataNodeContainer) current).findDataChildByName(qname); continue; } } return Optional.empty(); } return optCurrent; } /** * Returns grouping nodes used ny this container. * * @return Set of all uses nodes defined within this DataNodeContainer */ @NonNull Collection<? extends @NonNull UsesNode> getUses(); /** * Returns a {@code data node} identified by a QName. This method is distinct from * {@link #findDataChildByName(QName)} in that it skips over {@link ChoiceSchemaNode}s and {@link CaseSchemaNode}s, * hence mirroring layout of the {@code data tree}, not {@code schema tree}. * * @param name QName identifier of the data node * @return Direct or indirect child of this DataNodeContainer which is a {@code data node}, empty otherwise * @throws NullPointerException if {@code name} is null */ @Beta default Optional<DataSchemaNode> findDataTreeChild(final QName name) { // First we try to find a direct child and check if it is a data node (as per RFC7950) final Optional<DataSchemaNode> optDataChild = findDataChildByName(name); if (HelperMethods.isDataNode(optDataChild)) { return optDataChild; } // There either is no such node present, or there are Choice/CaseSchemaNodes with the same name involved, // hence we have to resort to a full search. for (DataSchemaNode child : getChildNodes()) { if (child instanceof ChoiceSchemaNode) { for (CaseSchemaNode choiceCase : ((ChoiceSchemaNode) child).getCases()) { final Optional<DataSchemaNode> caseChild = choiceCase.findDataTreeChild(name); if (caseChild.isPresent()) { return caseChild; } } } } return Optional.empty(); } @Beta default Optional<DataSchemaNode> findDataTreeChild(final QName... path) { return findDataTreeChild(Arrays.asList(path)); } @Beta default Optional<DataSchemaNode> findDataTreeChild(final Iterable<QName> path) { final Iterator<QName> it = path.iterator(); DataNodeContainer parent = this; do { final Optional<DataSchemaNode> optChild = parent.findDataTreeChild(requireNonNull(it.next())); if (optChild.isEmpty() || !it.hasNext()) { return optChild; } final DataSchemaNode child = optChild.get(); checkArgument(child instanceof DataNodeContainer, "Path %s extends beyond terminal child %s", path, child); parent = (DataNodeContainer) child; } while (true); } }
package io.yope.payment.blockchain.bitcoinj; import java.io.ByteArrayOutputStream; import java.math.BigDecimal; import javax.xml.bind.DatatypeConverter; import org.bitcoinj.core.AbstractWalletEventListener; import org.bitcoinj.core.Coin; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.PeerGroup; import org.bitcoinj.core.TransactionConfidence; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.crypto.DeterministicKey; import org.bitcoinj.script.Script; import io.yope.payment.domain.Transaction; import io.yope.payment.domain.Wallet; import io.yope.payment.domain.transferobjects.TransactionTO; import io.yope.payment.domain.transferobjects.WalletTO; import io.yope.payment.exceptions.IllegalTransactionStateException; import io.yope.payment.exceptions.InsufficientFundsException; import io.yope.payment.exceptions.ObjectNotFoundException; import io.yope.payment.services.TransactionService; import io.yope.payment.services.WalletService; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; @Slf4j @AllArgsConstructor public class WalletEventListener extends AbstractWalletEventListener { private final PeerGroup peerGroup; private final NetworkParameters params; private final TransactionService transactionService; private final BlockchainSettings settings; private final WalletService walletService; private final Wallet centralWallet; @Override public void onTransactionConfidenceChanged(final org.bitcoinj.core.Wallet wallet, final org.bitcoinj.core.Transaction tx) { receiveCoins(wallet,tx); final String transactionHash = tx.getHashAsString(); final Transaction loaded = transactionService.getByTransactionHash(transactionHash); if (loaded == null) { log.warn("transaction hash {} does not yet exist", transactionHash); return; } log.info(" final TransactionConfidence confidence = tx.getConfidence(); log.info("new block depth: {} ", confidence.getDepthInBlocks()); if (confidence.getDepthInBlocks() >= settings.getConfirmations()) { if (!Transaction.Status.ACCEPTED.equals(loaded.getStatus())) { log.error("transaction {} has status {}", loaded.getId(), loaded.getStatus()); return; } try { transactionService.transition(loaded.getId(), Transaction.Status.COMPLETED); } catch (final ObjectNotFoundException e) { log.error("transaction not found", e); } catch (final InsufficientFundsException e) { log.error("Insufficient money", e); } catch (final IllegalTransactionStateException e) { log.error("Illegal transaction state", e); } } } private void receiveCoins(final org.bitcoinj.core.Wallet wallet, final org.bitcoinj.core.Transaction tx) { // super.onCoinsReceived(wallet, tx, prevBalance, newBalance); final Coin valueSentToMe = tx.getValueSentToMe(wallet); final Coin valueSentFromMe = tx.getValueSentFromMe(wallet); final DeterministicKey freshKey = wallet.freshReceiveKey(); final String freshHash = freshKey.toAddress(params).toString(); log.info("******** fresh hash: {}", freshHash); BitcoinjBlockchainServiceImpl.HASH_STACK.push(freshHash); log.info("******** Coins on central wallet to me {} from me {}", valueSentToMe, valueSentFromMe); final String receiverHash = getReceiverHash(tx); final String senderHash = getSenderHash(tx); if (receiverHash == null) { return; } try { final Transaction pending = transactionService.getByReceiverHash(receiverHash); if (pending == null) { log.debug("******** receiver hash {} does not exist", receiverHash); return; } if (!Transaction.Status.PENDING.equals(pending.getStatus())) { log.debug("******** transaction {} with {} has status {}", pending.getId(), receiverHash, pending.getStatus()); return; } final BigDecimal balance = new BigDecimal(valueSentToMe.subtract(valueSentFromMe).longValue()).divide(new BigDecimal(Constants.MILLI_TO_SATOSHI)); BigDecimal fees = new BigDecimal(valueSentFromMe.getValue()); if (fees.floatValue() > 0) { fees = fees.divide(new BigDecimal(Constants.MILLI_TO_SATOSHI)); } final BigDecimal amount = balance.add(fees); log.info("transaction: amount {} = {} + {} (balance + fees)", pending.getAmount(), balance, fees); if (amount.compareTo(pending.getAmount()) > 0) { log.error("Transaction {}: paid amount {} greater than expected amont {}", receiverHash, amount, pending.getAmount()); } if (amount.compareTo(pending.getAmount()) < 0) { log.error("Transaction {}: paid amount {} less than expected amont {}", receiverHash, amount, pending.getAmount()); } final Transaction transaction = TransactionTO .from(pending) .transactionHash(tx.getHashAsString()) .balance(balance) .blockchainFees(fees) .senderHash(senderHash) .receiverHash(null) .QR(null) .status(Transaction.Status.ACCEPTED) .build(); transactionService.save(transaction.getId(), transaction); peerGroup.broadcastTransaction(tx); } catch (final ObjectNotFoundException e) { log.error("transaction not found", e); } catch (final IllegalTransactionStateException e) { log.error("illegal transaction state", e); } catch (final InsufficientFundsException e) { log.error("insufficient funds", e); } catch (final Exception e) { log.error("Unexpected error", e); } saveWallet(wallet); } private void saveWallet(final org.bitcoinj.core.Wallet wallet) { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { wallet.saveToFileStream(outputStream); walletService.save(WalletTO.from(centralWallet).content(DatatypeConverter.printBase64Binary(outputStream.toByteArray())).build()); } catch (final Exception e) { log.error("error adding wallet {}", e); } } private String getSenderHash(final org.bitcoinj.core.Transaction tx) { for (final TransactionOutput out : tx.getOutputs() ) { final String hash = new Script(out.getScriptBytes()).getToAddress(params).toString(); if (!BitcoinjBlockchainServiceImpl.HASH_LIST.contains(hash)) { return hash; } } return null; } private String getReceiverHash(final org.bitcoinj.core.Transaction tx) { for (final TransactionOutput out : tx.getOutputs() ) { final String hash = new Script(out.getScriptBytes()).getToAddress(params).toString(); if (BitcoinjBlockchainServiceImpl.HASH_LIST.contains(hash)) { return hash; } } return null; } }